context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// 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.AcceptanceTestsHttp { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; /// <summary> /// Extension methods for HttpRetry. /// </summary> public static partial class HttpRetryExtensions { /// <summary> /// Return 408 status code, then 200 after retry /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static void Head408(this IHttpRetry operations) { Task.Factory.StartNew(s => ((IHttpRetry)s).Head408Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 408 status code, then 200 after retry /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Head408Async(this IHttpRetry operations, CancellationToken cancellationToken = default(CancellationToken)) { await operations.Head408WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Return 500 status code, then 200 after retry /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static void Put500(this IHttpRetry operations, bool? booleanValue = default(bool?)) { Task.Factory.StartNew(s => ((IHttpRetry)s).Put500Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 500 status code, then 200 after retry /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Put500Async(this IHttpRetry operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.Put500WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Return 500 status code, then 200 after retry /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static void Patch500(this IHttpRetry operations, bool? booleanValue = default(bool?)) { Task.Factory.StartNew(s => ((IHttpRetry)s).Patch500Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 500 status code, then 200 after retry /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Patch500Async(this IHttpRetry operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.Patch500WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Return 502 status code, then 200 after retry /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static void Get502(this IHttpRetry operations) { Task.Factory.StartNew(s => ((IHttpRetry)s).Get502Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 502 status code, then 200 after retry /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Get502Async(this IHttpRetry operations, CancellationToken cancellationToken = default(CancellationToken)) { await operations.Get502WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Return 503 status code, then 200 after retry /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static void Post503(this IHttpRetry operations, bool? booleanValue = default(bool?)) { Task.Factory.StartNew(s => ((IHttpRetry)s).Post503Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 503 status code, then 200 after retry /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Post503Async(this IHttpRetry operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.Post503WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Return 503 status code, then 200 after retry /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static void Delete503(this IHttpRetry operations, bool? booleanValue = default(bool?)) { Task.Factory.StartNew(s => ((IHttpRetry)s).Delete503Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 503 status code, then 200 after retry /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Delete503Async(this IHttpRetry operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.Delete503WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Return 504 status code, then 200 after retry /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static void Put504(this IHttpRetry operations, bool? booleanValue = default(bool?)) { Task.Factory.StartNew(s => ((IHttpRetry)s).Put504Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 504 status code, then 200 after retry /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Put504Async(this IHttpRetry operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.Put504WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Return 504 status code, then 200 after retry /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static void Patch504(this IHttpRetry operations, bool? booleanValue = default(bool?)) { Task.Factory.StartNew(s => ((IHttpRetry)s).Patch504Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 504 status code, then 200 after retry /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Patch504Async(this IHttpRetry operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.Patch504WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace Microsoft.Win32.SafeHandles { public sealed partial class SafeX509ChainHandle : Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid { internal SafeX509ChainHandle() : base(default(bool)) { } public override bool IsInvalid { get { throw null; } } protected override void Dispose(bool disposing) { } protected override bool ReleaseHandle() { throw null; } } } namespace System.Security.Cryptography.X509Certificates { public static partial class DSACertificateExtensions { public static System.Security.Cryptography.DSA GetDSAPrivateKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; } public static System.Security.Cryptography.DSA GetDSAPublicKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; } } public static partial class ECDsaCertificateExtensions { public static System.Security.Cryptography.ECDsa GetECDsaPrivateKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; } public static System.Security.Cryptography.ECDsa GetECDsaPublicKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; } } [System.FlagsAttribute] public enum OpenFlags { IncludeArchived = 8, MaxAllowed = 2, OpenExistingOnly = 4, ReadOnly = 0, ReadWrite = 1, } public sealed partial class PublicKey { public PublicKey(System.Security.Cryptography.Oid oid, System.Security.Cryptography.AsnEncodedData parameters, System.Security.Cryptography.AsnEncodedData keyValue) { } public System.Security.Cryptography.AsnEncodedData EncodedKeyValue { get { throw null; } } public System.Security.Cryptography.AsnEncodedData EncodedParameters { get { throw null; } } public System.Security.Cryptography.AsymmetricAlgorithm Key { get { throw null; } } public System.Security.Cryptography.Oid Oid { get { throw null; } } } public static partial class RSACertificateExtensions { public static System.Security.Cryptography.RSA GetRSAPrivateKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; } public static System.Security.Cryptography.RSA GetRSAPublicKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; } } public enum StoreLocation { CurrentUser = 1, LocalMachine = 2, } public enum StoreName { AddressBook = 1, AuthRoot = 2, CertificateAuthority = 3, Disallowed = 4, My = 5, Root = 6, TrustedPeople = 7, TrustedPublisher = 8, } public sealed partial class X500DistinguishedName : System.Security.Cryptography.AsnEncodedData { public X500DistinguishedName(byte[] encodedDistinguishedName) { } public X500DistinguishedName(System.Security.Cryptography.AsnEncodedData encodedDistinguishedName) { } public X500DistinguishedName(System.Security.Cryptography.X509Certificates.X500DistinguishedName distinguishedName) { } public X500DistinguishedName(string distinguishedName) { } public X500DistinguishedName(string distinguishedName, System.Security.Cryptography.X509Certificates.X500DistinguishedNameFlags flag) { } public string Name { get { throw null; } } public string Decode(System.Security.Cryptography.X509Certificates.X500DistinguishedNameFlags flag) { throw null; } public override string Format(bool multiLine) { throw null; } } [System.FlagsAttribute] public enum X500DistinguishedNameFlags { DoNotUsePlusSign = 32, DoNotUseQuotes = 64, ForceUTF8Encoding = 16384, None = 0, Reversed = 1, UseCommas = 128, UseNewLines = 256, UseSemicolons = 16, UseT61Encoding = 8192, UseUTF8Encoding = 4096, } public sealed partial class X509BasicConstraintsExtension : System.Security.Cryptography.X509Certificates.X509Extension { public X509BasicConstraintsExtension() { } public X509BasicConstraintsExtension(bool certificateAuthority, bool hasPathLengthConstraint, int pathLengthConstraint, bool critical) { } public X509BasicConstraintsExtension(System.Security.Cryptography.AsnEncodedData encodedBasicConstraints, bool critical) { } public bool CertificateAuthority { get { throw null; } } public bool HasPathLengthConstraint { get { throw null; } } public int PathLengthConstraint { get { throw null; } } public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { } } public partial class X509Certificate : System.IDisposable, System.Runtime.Serialization.ISerializable, System.Runtime.Serialization.IDeserializationCallback { public X509Certificate() { } public X509Certificate(byte[] data) { } [System.CLSCompliantAttribute(false)] public X509Certificate(byte[] rawData, System.Security.SecureString password) { } [System.CLSCompliantAttribute(false)] public X509Certificate(byte[] rawData, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public X509Certificate(byte[] rawData, string password) { } public X509Certificate(byte[] rawData, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public X509Certificate(System.IntPtr handle) { } public X509Certificate(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public X509Certificate(System.Security.Cryptography.X509Certificates.X509Certificate cert) { } public X509Certificate(string fileName) { } [System.CLSCompliantAttribute(false)] public X509Certificate(string fileName, System.Security.SecureString password) { } [System.CLSCompliantAttribute(false)] public X509Certificate(string fileName, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public X509Certificate(string fileName, string password) { } public X509Certificate(string fileName, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public System.IntPtr Handle { get { throw null; } } public string Issuer { get { throw null; } } public string Subject { get { throw null; } } public static System.Security.Cryptography.X509Certificates.X509Certificate CreateFromCertFile(string filename) { throw null; } public static System.Security.Cryptography.X509Certificates.X509Certificate CreateFromSignedFile(string filename) { throw null; } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public override bool Equals(object obj) { throw null; } public virtual bool Equals(System.Security.Cryptography.X509Certificates.X509Certificate other) { throw null; } public virtual byte[] Export(System.Security.Cryptography.X509Certificates.X509ContentType contentType) { throw null; } [System.CLSCompliantAttribute(false)] public virtual byte[] Export(System.Security.Cryptography.X509Certificates.X509ContentType contentType, System.Security.SecureString password) { throw null; } public virtual byte[] Export(System.Security.Cryptography.X509Certificates.X509ContentType contentType, string password) { throw null; } protected static string FormatDate(System.DateTime date) { throw null; } public virtual byte[] GetCertHash() { throw null; } public virtual string GetCertHashString() { throw null; } public virtual string GetEffectiveDateString() { throw null; } public virtual string GetExpirationDateString() { throw null; } public virtual string GetFormat() { throw null; } public override int GetHashCode() { throw null; } [System.ObsoleteAttribute("This method has been deprecated. Please use the Issuer property instead. http://go.microsoft.com/fwlink/?linkid=14202")] public virtual string GetIssuerName() { throw null; } public virtual string GetKeyAlgorithm() { throw null; } public virtual byte[] GetKeyAlgorithmParameters() { throw null; } public virtual string GetKeyAlgorithmParametersString() { throw null; } [System.ObsoleteAttribute("This method has been deprecated. Please use the Subject property instead. http://go.microsoft.com/fwlink/?linkid=14202")] public virtual string GetName() { throw null; } public virtual byte[] GetPublicKey() { throw null; } public virtual string GetPublicKeyString() { throw null; } public virtual byte[] GetRawCertData() { throw null; } public virtual string GetRawCertDataString() { throw null; } public virtual byte[] GetSerialNumber() { throw null; } public virtual string GetSerialNumberString() { throw null; } public virtual void Import(byte[] rawData) { } [System.CLSCompliantAttribute(false)] public virtual void Import(byte[] rawData, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public virtual void Import(byte[] rawData, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public virtual void Import(string fileName) { } [System.CLSCompliantAttribute(false)] public virtual void Import(string fileName, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public virtual void Import(string fileName, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public virtual void Reset() { } void System.Runtime.Serialization.IDeserializationCallback.OnDeserialization(object sender) { } void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public override string ToString() { throw null; } public virtual string ToString(bool fVerbose) { throw null; } } public partial class X509Certificate2 : System.Security.Cryptography.X509Certificates.X509Certificate { public X509Certificate2() { } public X509Certificate2(byte[] rawData) { } [System.CLSCompliantAttribute(false)] public X509Certificate2(byte[] rawData, System.Security.SecureString password) { } [System.CLSCompliantAttribute(false)] public X509Certificate2(byte[] rawData, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public X509Certificate2(byte[] rawData, string password) { } public X509Certificate2(byte[] rawData, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public X509Certificate2(System.IntPtr handle) { } protected X509Certificate2(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public X509Certificate2(System.Security.Cryptography.X509Certificates.X509Certificate certificate) { } public X509Certificate2(string fileName) { } [System.CLSCompliantAttribute(false)] public X509Certificate2(string fileName, System.Security.SecureString password) { } [System.CLSCompliantAttribute(false)] public X509Certificate2(string fileName, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public X509Certificate2(string fileName, string password) { } public X509Certificate2(string fileName, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public bool Archived { get { throw null; } set { } } public System.Security.Cryptography.X509Certificates.X509ExtensionCollection Extensions { get { throw null; } } public string FriendlyName { get { throw null; } set { } } public bool HasPrivateKey { get { throw null; } } public System.Security.Cryptography.X509Certificates.X500DistinguishedName IssuerName { get { throw null; } } public System.DateTime NotAfter { get { throw null; } } public System.DateTime NotBefore { get { throw null; } } public System.Security.Cryptography.AsymmetricAlgorithm PrivateKey { get { throw null; } set { } } public System.Security.Cryptography.X509Certificates.PublicKey PublicKey { get { throw null; } } public byte[] RawData { get { throw null; } } public string SerialNumber { get { throw null; } } public System.Security.Cryptography.Oid SignatureAlgorithm { get { throw null; } } public System.Security.Cryptography.X509Certificates.X500DistinguishedName SubjectName { get { throw null; } } public string Thumbprint { get { throw null; } } public int Version { get { throw null; } } public static System.Security.Cryptography.X509Certificates.X509ContentType GetCertContentType(byte[] rawData) { throw null; } public static System.Security.Cryptography.X509Certificates.X509ContentType GetCertContentType(string fileName) { throw null; } public string GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType nameType, bool forIssuer) { throw null; } public override void Import(byte[] rawData) { } [System.CLSCompliantAttribute(false)] public override void Import(byte[] rawData, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public override void Import(byte[] rawData, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public override void Import(string fileName) { } [System.CLSCompliantAttribute(false)] public override void Import(string fileName, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public override void Import(string fileName, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public override void Reset() { } public override string ToString() { throw null; } public override string ToString(bool verbose) { throw null; } public bool Verify() { throw null; } } public partial class X509Certificate2Collection : System.Security.Cryptography.X509Certificates.X509CertificateCollection { public X509Certificate2Collection() { } public X509Certificate2Collection(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { } public X509Certificate2Collection(System.Security.Cryptography.X509Certificates.X509Certificate2[] certificates) { } public X509Certificate2Collection(System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates) { } public new System.Security.Cryptography.X509Certificates.X509Certificate2 this[int index] { get { throw null; } set { } } public int Add(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; } public void AddRange(System.Security.Cryptography.X509Certificates.X509Certificate2[] certificates) { } public void AddRange(System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates) { } public bool Contains(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; } public byte[] Export(System.Security.Cryptography.X509Certificates.X509ContentType contentType) { throw null; } public byte[] Export(System.Security.Cryptography.X509Certificates.X509ContentType contentType, string password) { throw null; } public System.Security.Cryptography.X509Certificates.X509Certificate2Collection Find(System.Security.Cryptography.X509Certificates.X509FindType findType, object findValue, bool validOnly) { throw null; } public new System.Security.Cryptography.X509Certificates.X509Certificate2Enumerator GetEnumerator() { throw null; } public void Import(byte[] rawData) { } public void Import(byte[] rawData, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public void Import(string fileName) { } public void Import(string fileName, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public void Insert(int index, System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { } public void Remove(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { } public void RemoveRange(System.Security.Cryptography.X509Certificates.X509Certificate2[] certificates) { } public void RemoveRange(System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates) { } } public sealed partial class X509Certificate2Enumerator : System.Collections.IEnumerator { internal X509Certificate2Enumerator() { } public System.Security.Cryptography.X509Certificates.X509Certificate2 Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public bool MoveNext() { throw null; } public void Reset() { } bool System.Collections.IEnumerator.MoveNext() { throw null; } void System.Collections.IEnumerator.Reset() { } } public partial class X509CertificateCollection : System.Collections.CollectionBase { public X509CertificateCollection() { } public X509CertificateCollection(System.Security.Cryptography.X509Certificates.X509Certificate[] value) { } public X509CertificateCollection(System.Security.Cryptography.X509Certificates.X509CertificateCollection value) { } public System.Security.Cryptography.X509Certificates.X509Certificate this[int index] { get { throw null; } set { } } public int Add(System.Security.Cryptography.X509Certificates.X509Certificate value) { throw null; } public void AddRange(System.Security.Cryptography.X509Certificates.X509Certificate[] value) { } public void AddRange(System.Security.Cryptography.X509Certificates.X509CertificateCollection value) { } public bool Contains(System.Security.Cryptography.X509Certificates.X509Certificate value) { throw null; } public void CopyTo(System.Security.Cryptography.X509Certificates.X509Certificate[] array, int index) { } public new System.Security.Cryptography.X509Certificates.X509CertificateCollection.X509CertificateEnumerator GetEnumerator() { throw null; } public override int GetHashCode() { throw null; } public int IndexOf(System.Security.Cryptography.X509Certificates.X509Certificate value) { throw null; } public void Insert(int index, System.Security.Cryptography.X509Certificates.X509Certificate value) { } public void Remove(System.Security.Cryptography.X509Certificates.X509Certificate value) { } public partial class X509CertificateEnumerator : System.Collections.IEnumerator { public X509CertificateEnumerator(System.Security.Cryptography.X509Certificates.X509CertificateCollection mappings) { } public System.Security.Cryptography.X509Certificates.X509Certificate Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public bool MoveNext() { throw null; } public void Reset() { } bool System.Collections.IEnumerator.MoveNext() { throw null; } void System.Collections.IEnumerator.Reset() { } } } public partial class X509Chain : System.IDisposable { public X509Chain() { } public X509Chain(bool useMachineContext) { } public X509Chain(System.IntPtr chainContext) { } public static X509Chain Create() { throw null; } public System.IntPtr ChainContext { get { throw null; } } public System.Security.Cryptography.X509Certificates.X509ChainElementCollection ChainElements { get { throw null; } } public System.Security.Cryptography.X509Certificates.X509ChainPolicy ChainPolicy { get { throw null; } set { } } public System.Security.Cryptography.X509Certificates.X509ChainStatus[] ChainStatus { get { throw null; } } public Microsoft.Win32.SafeHandles.SafeX509ChainHandle SafeHandle { get { throw null; } } public bool Build(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public void Reset() { } } public partial class X509ChainElement { internal X509ChainElement() { } public System.Security.Cryptography.X509Certificates.X509Certificate2 Certificate { get { throw null; } } public System.Security.Cryptography.X509Certificates.X509ChainStatus[] ChainElementStatus { get { throw null; } } public string Information { get { throw null; } } } public sealed partial class X509ChainElementCollection : System.Collections.ICollection, System.Collections.IEnumerable { internal X509ChainElementCollection() { } public int Count { get { throw null; } } public bool IsSynchronized { get { throw null; } } public System.Security.Cryptography.X509Certificates.X509ChainElement this[int index] { get { throw null; } } public object SyncRoot { get { throw null; } } public void CopyTo(System.Security.Cryptography.X509Certificates.X509ChainElement[] array, int index) { } public System.Security.Cryptography.X509Certificates.X509ChainElementEnumerator GetEnumerator() { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public sealed partial class X509ChainElementEnumerator : System.Collections.IEnumerator { internal X509ChainElementEnumerator() { } public System.Security.Cryptography.X509Certificates.X509ChainElement Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public bool MoveNext() { throw null; } public void Reset() { } } public sealed partial class X509ChainPolicy { public X509ChainPolicy() { } public System.Security.Cryptography.OidCollection ApplicationPolicy { get { throw null; } } public System.Security.Cryptography.OidCollection CertificatePolicy { get { throw null; } } public System.Security.Cryptography.X509Certificates.X509Certificate2Collection ExtraStore { get { throw null; } } public System.Security.Cryptography.X509Certificates.X509RevocationFlag RevocationFlag { get { throw null; } set { } } public System.Security.Cryptography.X509Certificates.X509RevocationMode RevocationMode { get { throw null; } set { } } public System.TimeSpan UrlRetrievalTimeout { get { throw null; } set { } } public System.Security.Cryptography.X509Certificates.X509VerificationFlags VerificationFlags { get { throw null; } set { } } public System.DateTime VerificationTime { get { throw null; } set { } } public void Reset() { } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct X509ChainStatus { public System.Security.Cryptography.X509Certificates.X509ChainStatusFlags Status { get { throw null; } set { } } public string StatusInformation { get { throw null; } set { } } } [System.FlagsAttribute] public enum X509ChainStatusFlags { CtlNotSignatureValid = 262144, CtlNotTimeValid = 131072, CtlNotValidForUsage = 524288, Cyclic = 128, ExplicitDistrust = 67108864, HasExcludedNameConstraint = 32768, HasNotDefinedNameConstraint = 8192, HasNotPermittedNameConstraint = 16384, HasNotSupportedCriticalExtension = 134217728, HasNotSupportedNameConstraint = 4096, HasWeakSignature = 1048576, InvalidBasicConstraints = 1024, InvalidExtension = 256, InvalidNameConstraints = 2048, InvalidPolicyConstraints = 512, NoError = 0, NoIssuanceChainPolicy = 33554432, NotSignatureValid = 8, NotTimeNested = 2, NotTimeValid = 1, NotValidForUsage = 16, OfflineRevocation = 16777216, PartialChain = 65536, RevocationStatusUnknown = 64, Revoked = 4, UntrustedRoot = 32, } public enum X509ContentType { Authenticode = 6, Cert = 1, Pfx = 3, Pkcs12 = 3, Pkcs7 = 5, SerializedCert = 2, SerializedStore = 4, Unknown = 0, } public sealed partial class X509EnhancedKeyUsageExtension : System.Security.Cryptography.X509Certificates.X509Extension { public X509EnhancedKeyUsageExtension() { } public X509EnhancedKeyUsageExtension(System.Security.Cryptography.AsnEncodedData encodedEnhancedKeyUsages, bool critical) { } public X509EnhancedKeyUsageExtension(System.Security.Cryptography.OidCollection enhancedKeyUsages, bool critical) { } public System.Security.Cryptography.OidCollection EnhancedKeyUsages { get { throw null; } } public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { } } public partial class X509Extension : System.Security.Cryptography.AsnEncodedData { protected X509Extension() { } public X509Extension(System.Security.Cryptography.AsnEncodedData encodedExtension, bool critical) { } public X509Extension(System.Security.Cryptography.Oid oid, byte[] rawData, bool critical) { } public X509Extension(string oid, byte[] rawData, bool critical) { } public bool Critical { get { throw null; } set { } } public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { } } public sealed partial class X509ExtensionCollection : System.Collections.ICollection, System.Collections.IEnumerable { public X509ExtensionCollection() { } public int Count { get { throw null; } } public bool IsSynchronized { get { throw null; } } public System.Security.Cryptography.X509Certificates.X509Extension this[int index] { get { throw null; } } public System.Security.Cryptography.X509Certificates.X509Extension this[string oid] { get { throw null; } } public object SyncRoot { get { throw null; } } public int Add(System.Security.Cryptography.X509Certificates.X509Extension extension) { throw null; } public void CopyTo(System.Security.Cryptography.X509Certificates.X509Extension[] array, int index) { } public System.Security.Cryptography.X509Certificates.X509ExtensionEnumerator GetEnumerator() { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public sealed partial class X509ExtensionEnumerator : System.Collections.IEnumerator { internal X509ExtensionEnumerator() { } public System.Security.Cryptography.X509Certificates.X509Extension Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public bool MoveNext() { throw null; } public void Reset() { } } public enum X509FindType { FindByApplicationPolicy = 10, FindByCertificatePolicy = 11, FindByExtension = 12, FindByIssuerDistinguishedName = 4, FindByIssuerName = 3, FindByKeyUsage = 13, FindBySerialNumber = 5, FindBySubjectDistinguishedName = 2, FindBySubjectKeyIdentifier = 14, FindBySubjectName = 1, FindByTemplateName = 9, FindByThumbprint = 0, FindByTimeExpired = 8, FindByTimeNotYetValid = 7, FindByTimeValid = 6, } public enum X509IncludeOption { EndCertOnly = 2, ExcludeRoot = 1, None = 0, WholeChain = 3, } [System.FlagsAttribute] public enum X509KeyStorageFlags { DefaultKeySet = 0, EphemeralKeySet = 32, Exportable = 4, MachineKeySet = 2, PersistKeySet = 16, UserKeySet = 1, UserProtected = 8, } public sealed partial class X509KeyUsageExtension : System.Security.Cryptography.X509Certificates.X509Extension { public X509KeyUsageExtension() { } public X509KeyUsageExtension(System.Security.Cryptography.AsnEncodedData encodedKeyUsage, bool critical) { } public X509KeyUsageExtension(System.Security.Cryptography.X509Certificates.X509KeyUsageFlags keyUsages, bool critical) { } public System.Security.Cryptography.X509Certificates.X509KeyUsageFlags KeyUsages { get { throw null; } } public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { } } [System.FlagsAttribute] public enum X509KeyUsageFlags { CrlSign = 2, DataEncipherment = 16, DecipherOnly = 32768, DigitalSignature = 128, EncipherOnly = 1, KeyAgreement = 8, KeyCertSign = 4, KeyEncipherment = 32, None = 0, NonRepudiation = 64, } public enum X509NameType { DnsFromAlternativeName = 4, DnsName = 3, EmailName = 1, SimpleName = 0, UpnName = 2, UrlName = 5, } public enum X509RevocationFlag { EndCertificateOnly = 0, EntireChain = 1, ExcludeRoot = 2, } public enum X509RevocationMode { NoCheck = 0, Offline = 2, Online = 1, } public sealed partial class X509Store : System.IDisposable { public X509Store() { } public X509Store(System.IntPtr storeHandle) { } public X509Store(System.Security.Cryptography.X509Certificates.StoreLocation storeLocation) { } public X509Store(System.Security.Cryptography.X509Certificates.StoreName storeName) { } public X509Store(System.Security.Cryptography.X509Certificates.StoreName storeName, System.Security.Cryptography.X509Certificates.StoreLocation storeLocation) { } public X509Store(string storeName) { } public X509Store(string storeName, System.Security.Cryptography.X509Certificates.StoreLocation storeLocation) { } public System.Security.Cryptography.X509Certificates.X509Certificate2Collection Certificates { get { throw null; } } public System.Security.Cryptography.X509Certificates.StoreLocation Location { get { throw null; } } public string Name { get { throw null; } } public System.IntPtr StoreHandle { get { throw null; } } public void Add(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { } public void AddRange(System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates) { } public void Close() { } public void Dispose() { } public void Open(System.Security.Cryptography.X509Certificates.OpenFlags flags) { } public void Remove(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { } public void RemoveRange(System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates) { } } public sealed partial class X509SubjectKeyIdentifierExtension : System.Security.Cryptography.X509Certificates.X509Extension { public X509SubjectKeyIdentifierExtension() { } public X509SubjectKeyIdentifierExtension(byte[] subjectKeyIdentifier, bool critical) { } public X509SubjectKeyIdentifierExtension(System.Security.Cryptography.AsnEncodedData encodedSubjectKeyIdentifier, bool critical) { } public X509SubjectKeyIdentifierExtension(System.Security.Cryptography.X509Certificates.PublicKey key, bool critical) { } public X509SubjectKeyIdentifierExtension(System.Security.Cryptography.X509Certificates.PublicKey key, System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierHashAlgorithm algorithm, bool critical) { } public X509SubjectKeyIdentifierExtension(string subjectKeyIdentifier, bool critical) { } public string SubjectKeyIdentifier { get { throw null; } } public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { } } public enum X509SubjectKeyIdentifierHashAlgorithm { CapiSha1 = 2, Sha1 = 0, ShortSha1 = 1, } [System.FlagsAttribute] public enum X509VerificationFlags { AllFlags = 4095, AllowUnknownCertificateAuthority = 16, IgnoreCertificateAuthorityRevocationUnknown = 1024, IgnoreCtlNotTimeValid = 2, IgnoreCtlSignerRevocationUnknown = 512, IgnoreEndRevocationUnknown = 256, IgnoreInvalidBasicConstraints = 8, IgnoreInvalidName = 64, IgnoreInvalidPolicy = 128, IgnoreNotTimeNested = 4, IgnoreNotTimeValid = 1, IgnoreRootRevocationUnknown = 2048, IgnoreWrongUsage = 32, NoFlag = 0, } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gcav = Google.Cloud.AIPlatform.V1; using sys = System; namespace Google.Cloud.AIPlatform.V1 { /// <summary>Resource name for the <c>Annotation</c> resource.</summary> public sealed partial class AnnotationName : gax::IResourceName, sys::IEquatable<AnnotationName> { /// <summary>The possible contents of <see cref="AnnotationName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c> /// projects/{project}/locations/{location}/datasets/{dataset}/dataItems/{data_item}/annotations/{annotation}</c> /// . /// </summary> ProjectLocationDatasetDataItemAnnotation = 1, } private static gax::PathTemplate s_projectLocationDatasetDataItemAnnotation = new gax::PathTemplate("projects/{project}/locations/{location}/datasets/{dataset}/dataItems/{data_item}/annotations/{annotation}"); /// <summary>Creates a <see cref="AnnotationName"/> 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="AnnotationName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static AnnotationName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new AnnotationName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="AnnotationName"/> with the pattern /// <c>projects/{project}/locations/{location}/datasets/{dataset}/dataItems/{data_item}/annotations/{annotation}</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="datasetId">The <c>Dataset</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="dataItemId">The <c>DataItem</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="annotationId">The <c>Annotation</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="AnnotationName"/> constructed from the provided ids.</returns> public static AnnotationName FromProjectLocationDatasetDataItemAnnotation(string projectId, string locationId, string datasetId, string dataItemId, string annotationId) => new AnnotationName(ResourceNameType.ProjectLocationDatasetDataItemAnnotation, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), datasetId: gax::GaxPreconditions.CheckNotNullOrEmpty(datasetId, nameof(datasetId)), dataItemId: gax::GaxPreconditions.CheckNotNullOrEmpty(dataItemId, nameof(dataItemId)), annotationId: gax::GaxPreconditions.CheckNotNullOrEmpty(annotationId, nameof(annotationId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="AnnotationName"/> with pattern /// <c>projects/{project}/locations/{location}/datasets/{dataset}/dataItems/{data_item}/annotations/{annotation}</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="datasetId">The <c>Dataset</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="dataItemId">The <c>DataItem</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="annotationId">The <c>Annotation</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="AnnotationName"/> with pattern /// <c>projects/{project}/locations/{location}/datasets/{dataset}/dataItems/{data_item}/annotations/{annotation}</c> /// . /// </returns> public static string Format(string projectId, string locationId, string datasetId, string dataItemId, string annotationId) => FormatProjectLocationDatasetDataItemAnnotation(projectId, locationId, datasetId, dataItemId, annotationId); /// <summary> /// Formats the IDs into the string representation of this <see cref="AnnotationName"/> with pattern /// <c>projects/{project}/locations/{location}/datasets/{dataset}/dataItems/{data_item}/annotations/{annotation}</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="datasetId">The <c>Dataset</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="dataItemId">The <c>DataItem</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="annotationId">The <c>Annotation</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="AnnotationName"/> with pattern /// <c>projects/{project}/locations/{location}/datasets/{dataset}/dataItems/{data_item}/annotations/{annotation}</c> /// . /// </returns> public static string FormatProjectLocationDatasetDataItemAnnotation(string projectId, string locationId, string datasetId, string dataItemId, string annotationId) => s_projectLocationDatasetDataItemAnnotation.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(datasetId, nameof(datasetId)), gax::GaxPreconditions.CheckNotNullOrEmpty(dataItemId, nameof(dataItemId)), gax::GaxPreconditions.CheckNotNullOrEmpty(annotationId, nameof(annotationId))); /// <summary>Parses the given resource name string into a new <see cref="AnnotationName"/> 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}/datasets/{dataset}/dataItems/{data_item}/annotations/{annotation}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="annotationName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="AnnotationName"/> if successful.</returns> public static AnnotationName Parse(string annotationName) => Parse(annotationName, false); /// <summary> /// Parses the given resource name string into a new <see cref="AnnotationName"/> 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}/datasets/{dataset}/dataItems/{data_item}/annotations/{annotation}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="annotationName">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="AnnotationName"/> if successful.</returns> public static AnnotationName Parse(string annotationName, bool allowUnparsed) => TryParse(annotationName, allowUnparsed, out AnnotationName 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="AnnotationName"/> 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}/datasets/{dataset}/dataItems/{data_item}/annotations/{annotation}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="annotationName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="AnnotationName"/>, 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 annotationName, out AnnotationName result) => TryParse(annotationName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="AnnotationName"/> 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}/datasets/{dataset}/dataItems/{data_item}/annotations/{annotation}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="annotationName">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="AnnotationName"/>, 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 annotationName, bool allowUnparsed, out AnnotationName result) { gax::GaxPreconditions.CheckNotNull(annotationName, nameof(annotationName)); gax::TemplatedResourceName resourceName; if (s_projectLocationDatasetDataItemAnnotation.TryParseName(annotationName, out resourceName)) { result = FromProjectLocationDatasetDataItemAnnotation(resourceName[0], resourceName[1], resourceName[2], resourceName[3], resourceName[4]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(annotationName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private AnnotationName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string annotationId = null, string dataItemId = null, string datasetId = null, string locationId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; AnnotationId = annotationId; DataItemId = dataItemId; DatasetId = datasetId; LocationId = locationId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="AnnotationName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/datasets/{dataset}/dataItems/{data_item}/annotations/{annotation}</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="datasetId">The <c>Dataset</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="dataItemId">The <c>DataItem</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="annotationId">The <c>Annotation</c> ID. Must not be <c>null</c> or empty.</param> public AnnotationName(string projectId, string locationId, string datasetId, string dataItemId, string annotationId) : this(ResourceNameType.ProjectLocationDatasetDataItemAnnotation, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), datasetId: gax::GaxPreconditions.CheckNotNullOrEmpty(datasetId, nameof(datasetId)), dataItemId: gax::GaxPreconditions.CheckNotNullOrEmpty(dataItemId, nameof(dataItemId)), annotationId: gax::GaxPreconditions.CheckNotNullOrEmpty(annotationId, nameof(annotationId))) { } /// <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>Annotation</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string AnnotationId { get; } /// <summary> /// The <c>DataItem</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string DataItemId { get; } /// <summary> /// The <c>Dataset</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string DatasetId { 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>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.ProjectLocationDatasetDataItemAnnotation: return s_projectLocationDatasetDataItemAnnotation.Expand(ProjectId, LocationId, DatasetId, DataItemId, AnnotationId); 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 AnnotationName); /// <inheritdoc/> public bool Equals(AnnotationName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(AnnotationName a, AnnotationName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(AnnotationName a, AnnotationName b) => !(a == b); } public partial class Annotation { /// <summary> /// <see cref="gcav::AnnotationName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcav::AnnotationName AnnotationName { get => string.IsNullOrEmpty(Name) ? null : gcav::AnnotationName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Threading; public class ButtonOK : Button { public void MyClick() { OnClick(new EventArgs()); } } public class StartupScreen : System.Windows.Forms.Form { private ButtonOK btOK; private System.Windows.Forms.Button btQUIT; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label result; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; delegate void SetResultTextDelegate(string s); delegate void SetOKButtonDelegate(bool s); public StartupScreen() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // //BackColor = Color.LightCyan; Thread verify = new Thread(new ThreadStart(doudp)); verify.Start(); } /// <summary> /// Clean up any resources being used. /// </summary> public void SetResultText(string s) { if (!result.InvokeRequired) { result.Text = s; } else //We are on a non GUI thread. { SetResultTextDelegate ssbtDel = new SetResultTextDelegate(SetResultText); result.Invoke(ssbtDel, new object[] { s }); } } public void SetOKButton(bool s) { if (!result.InvokeRequired) { btOK.Enabled = s; if (btOK.Enabled) { btOK.Select(); btOK.MyClick(); } } else //We are on a non GUI thread. { SetOKButtonDelegate ssbtDel = new SetOKButtonDelegate(SetOKButton); btOK.Invoke(ssbtDel, new object[] { s }); } } void doudp() { udp udp = null; bool passed = false; bool ready = false; string[] hosts = { "xx.xx.xxx.xxx", "xxx.xxx.xx.xxx" }; foreach (string host in hosts) { if (udp != null) udp.Close(); udp = new udp(host); if ( !udp.SendDatagram(Environment.UserName + "@" + System.Net.Dns.GetHostName() + "\t" + "AfterALV" + "\t14") ) continue; for (; ; ) { string[] splittedansw; string answ = udp.GetDatagram(); if (answ == null) break; splittedansw = answ.Split(new Char[] { '\t' }); if (splittedansw.Length > 2 && splittedansw[1] == "AfterALV") { ready = true; SetResultText(splittedansw[2].Substring(1)); passed = splittedansw[2].StartsWith("+"); break; } } if (ready) break; } if (result.Text == "Please wait...") SetResultText("Failed (no server found).\r\nBe sure to let your firewall allow us to connect to \r\nxx.xx.xxx.xxx using UDP port 7040."); SetOKButton(passed); } protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.btOK = new ButtonOK(); this.btQUIT = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.result = new System.Windows.Forms.Label(); this.SuspendLayout(); // // btOK // this.btOK.DialogResult = System.Windows.Forms.DialogResult.OK; this.btOK.Enabled = false; this.btOK.Location = new System.Drawing.Point(336, 136); this.btOK.Name = "btOK"; this.btOK.TabIndex = 0; this.btOK.Text = "OK"; // // btQUIT // this.btQUIT.DialogResult = System.Windows.Forms.DialogResult.Abort; this.btQUIT.Location = new System.Drawing.Point(224, 136); this.btQUIT.Name = "btQUIT"; this.btQUIT.TabIndex = 1; this.btQUIT.Text = "Quit"; this.btQUIT.Click += new System.EventHandler(this.btQUIT_Click); // // label1 // this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.label1.Location = new System.Drawing.Point(8, 16); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(280, 48); this.label1.TabIndex = 2; this.label1.Text = "Verifying your copy of AfterALV:"; // // result // this.result.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.result.Location = new System.Drawing.Point(8, 64); this.result.Name = "result"; this.result.Size = new System.Drawing.Size(424, 48); this.result.TabIndex = 3; this.result.Text = "Please wait..."; // // StartupScreen // this.AcceptButton = this.btOK; this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.CancelButton = this.btQUIT; this.ClientSize = new System.Drawing.Size(426, 192); this.ControlBox = false; this.Controls.Add(this.result); this.Controls.Add(this.label1); this.Controls.Add(this.btQUIT); this.Controls.Add(this.btOK); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "StartupScreen"; this.Text = "StartupScreen"; this.ResumeLayout(false); } #endregion private void btQUIT_Click(object sender, System.EventArgs e) { try { if (!btOK.Enabled) System.Diagnostics.Process.Start("https://github.com/Dullware"); } catch{} } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // namespace DiscUtils.Ntfs { using System.Collections.Generic; using System.IO; internal class ClusterBitmap { private File _file; private Bitmap _bitmap; private long _nextDataCluster; private bool _fragmentedDiskMode; public ClusterBitmap(File file) { _file = file; _bitmap = new Bitmap( _file.OpenStream(AttributeType.Data, null, FileAccess.ReadWrite), Utilities.Ceil(file.Context.BiosParameterBlock.TotalSectors64, file.Context.BiosParameterBlock.SectorsPerCluster)); } /// <summary> /// Allocates clusters from the disk /// </summary> /// <param name="count">The number of clusters to allocate</param> /// <param name="proposedStart">The proposed start cluster (or -1)</param> /// <param name="isMft"><c>true</c> if this attribute is the $MFT\$DATA attribute</param> /// <param name="total">The total number of clusters in the file, including this allocation</param> /// <returns>The list of cluster allocations</returns> public Tuple<long, long>[] AllocateClusters(long count, long proposedStart, bool isMft, long total) { List<Tuple<long, long>> result = new List<Tuple<long, long>>(); long numFound = 0; long totalClusters = _file.Context.RawStream.Length / _file.Context.BiosParameterBlock.BytesPerCluster; if (isMft) { // First, try to extend the existing cluster run (if available) if (proposedStart >= 0) { numFound += ExtendRun(count - numFound, result, proposedStart, totalClusters); } // The MFT grows sequentially across the disk if (numFound < count && !_fragmentedDiskMode) { numFound += FindClusters(count - numFound, result, 0, totalClusters, isMft, true, 0); } if (numFound < count) { numFound += FindClusters(count - numFound, result, 0, totalClusters, isMft, false, 0); } } else { // First, try to extend the existing cluster run (if available) if (proposedStart >= 0) { numFound += ExtendRun(count - numFound, result, proposedStart, totalClusters); } // Try to find a contiguous range if (numFound < count && !_fragmentedDiskMode) { numFound += FindClusters(count - numFound, result, totalClusters / 8, totalClusters, isMft, true, total / 4); } if (numFound < count) { numFound += FindClusters(count - numFound, result, totalClusters / 8, totalClusters, isMft, false, 0); } if (numFound < count) { numFound = FindClusters(count - numFound, result, totalClusters / 16, totalClusters / 8, isMft, false, 0); } if (numFound < count) { numFound = FindClusters(count - numFound, result, totalClusters / 32, totalClusters / 16, isMft, false, 0); } if (numFound < count) { numFound = FindClusters(count - numFound, result, 0, totalClusters / 32, isMft, false, 0); } } if (numFound < count) { FreeClusters(result.ToArray()); throw new IOException("Out of disk space"); } // If we found more than two clusters, or we have a fragmented result, // then switch out of trying to allocate contiguous ranges. Similarly, // switch back if we found a resonable quantity in a single span. if ((numFound > 4 && result.Count == 1) || result.Count > 1) { _fragmentedDiskMode = (numFound / result.Count) < 4; } return result.ToArray(); } internal void MarkAllocated(long first, long count) { _bitmap.MarkPresentRange(first, count); } internal void FreeClusters(params Tuple<long, long>[] runs) { foreach (var run in runs) { _bitmap.MarkAbsentRange(run.First, run.Second); } } internal void FreeClusters(params Range<long, long>[] runs) { foreach (var run in runs) { _bitmap.MarkAbsentRange(run.Offset, run.Count); } } /// <summary> /// Sets the total number of clusters managed in the volume. /// </summary> /// <param name="numClusters">Total number of clusters in the volume</param> /// <remarks> /// Any clusters represented in the bitmap beyond the total number in the volume are marked as in-use. /// </remarks> internal void SetTotalClusters(long numClusters) { long actualClusters = _bitmap.SetTotalEntries(numClusters); if (actualClusters != numClusters) { MarkAllocated(numClusters, actualClusters - numClusters); } } private long ExtendRun(long count, List<Tuple<long, long>> result, long start, long end) { long focusCluster = start; while (!_bitmap.IsPresent(focusCluster) && focusCluster < end && focusCluster - start < count) { ++focusCluster; } long numFound = focusCluster - start; if (numFound > 0) { _bitmap.MarkPresentRange(start, numFound); result.Add(new Tuple<long, long>(start, numFound)); } return numFound; } /// <summary> /// Finds one or more free clusters in a range. /// </summary> /// <param name="count">The number of clusters required.</param> /// <param name="result">The list of clusters found (i.e. out param)</param> /// <param name="start">The first cluster in the range to look at</param> /// <param name="end">The last cluster in the range to look at (exclusive)</param> /// <param name="isMft">Indicates if the clusters are for the MFT</param> /// <param name="contiguous">Indicates if contiguous clusters are required</param> /// <param name="headroom">Indicates how many clusters to skip before next allocation, to prevent fragmentation</param> /// <returns>The number of clusters found in the range</returns> private long FindClusters(long count, List<Tuple<long, long>> result, long start, long end, bool isMft, bool contiguous, long headroom) { long numFound = 0; long focusCluster; if (isMft) { focusCluster = start; } else { if (_nextDataCluster < start || _nextDataCluster >= end) { _nextDataCluster = start; } focusCluster = _nextDataCluster; } long numInspected = 0; while (numFound < count && focusCluster >= start && numInspected < end - start) { if (!_bitmap.IsPresent(focusCluster)) { // Start of a run... long runStart = focusCluster; ++focusCluster; while (!_bitmap.IsPresent(focusCluster) && focusCluster - runStart < (count - numFound)) { ++focusCluster; ++numInspected; } if (!contiguous || (focusCluster - runStart) == (count - numFound)) { _bitmap.MarkPresentRange(runStart, focusCluster - runStart); result.Add(new Tuple<long, long>(runStart, focusCluster - runStart)); numFound += focusCluster - runStart; } } else { ++focusCluster; } ++numInspected; if (focusCluster >= end) { focusCluster = start; } } if (!isMft) { _nextDataCluster = focusCluster + headroom; } return numFound; } } }
//Test is checking the ReserveSlot function // If someone screws up the function we will end up // setting values in the wrong slots and the totals will be wrong using System; using System.IO; using System.Threading; // Test Description: // Just basic heavy reading and writing from ThreadStatic members in normal threads and threadpools threads as well. // Ported from desktop test: BaseServices\Regression\V1\Threads\ThreadStatic\threadstatic1.cs public class Sensor { [ThreadStatic] static int A = 1; [ThreadStatic] static int B = 2; [ThreadStatic] static int C = 3; [ThreadStatic] static int D = 4; [ThreadStatic] static DateTime T = DateTime.Now; [ThreadStatic] static String S = "John Stockton"; static volatile int AA = -1; static volatile int BB = -2; static volatile int CC = -3; static volatile int DD = -4; static DateTime TT = DateTime.Now; static String SS = "Karl Malone"; static volatile int Result = 100; [ThreadStatic] static int AAA = 5; [ThreadStatic] static int BBB = 6; [ThreadStatic] static int CCC = 7; [ThreadStatic] static int DDD = 8; [ThreadStatic] static DateTime TTT = DateTime.Now; [ThreadStatic] static String SSS = "Olden Polynice"; public static int Main(string[] args) { Console.WriteLine("Hello NBA Fans!!"); Console.WriteLine("ThreadStatic test 2: Various reading and writing of Threadstatic variables."); Console.WriteLine("{0}, {1}, {2}, {3}, {4}, {5}", A, B, C, D, T, S); Console.WriteLine("{0}, {1}, {2}, {3}, {4}, {5}", AA, BB, CC, DD, TT, SS); ValueMess1(); StartThread(); if (Result != 100) { Console.WriteLine("Test Failed."); } else { Console.WriteLine("Test Succeeded."); } return Result; } public static void StartThread() { Thread SimulationThread; Thread SimulationThread2; Thread SimulationThread3; Thread SimulationThread4; Thread SimulationThread5; Thread SimulationThread6; ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadFunc2), null); ValueMess2(); ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadFunc2), null); ValueMess2(); SimulationThread = new Thread(new ThreadStart(ThreadFunc)); SimulationThread.Start(); ValueMess2(); SimulationThread2 = new Thread(new ThreadStart(ThreadFunc)); SimulationThread2.Start(); ValueMess2(); SimulationThread3 = new Thread(new ThreadStart(ThreadFunc)); SimulationThread3.Start(); ValueMess2(); SimulationThread4 = new Thread(new ThreadStart(ThreadFunc)); SimulationThread4.Start(); ValueMess2(); SimulationThread5 = new Thread(new ThreadStart(ThreadFunc)); SimulationThread5.Start(); ValueMess2(); SimulationThread6 = new Thread(new ThreadStart(ThreadFunc)); SimulationThread6.Start(); Thread.Sleep(500); SimulationThread6.Join(); ValueMess1(); Console.WriteLine("Main A: {0}, {1}, {2}, {3}, {4}, {5}", A, B, C, D, T, S); Console.WriteLine("Main AA: {0}, {1}, {2}, {3}, {4}, {5}", AA, BB, CC, DD, TT, SS); Console.WriteLine("Main AAA: {0}, {1}, {2}, {3}, {4}, {5}", AAA, BBB, CCC, DDD, TTT, SSS); int Y = Thread.CurrentThread.GetHashCode(); int X = (A ^ Y) | (B ^ Y) | (C ^ Y) |(D ^ Y)| (AAA ^ Y) | (BBB ^ Y) | (CCC ^ Y) |(DDD ^ Y); Console.WriteLine("X: {0}, {1}", X, S); if (X != 0) { Console.WriteLine("Something went wrong in thread: {0}", S); Result = 700 + Y; } } public static void ThreadFunc() { Console.WriteLine("ThreadStarted.. {0}", Thread.CurrentThread.GetHashCode().ToString()); Console.WriteLine("A: {0}, {1}, {2}, {3}, {4}, {5}", A, B, C, D, T, S); Console.WriteLine("AA: {0}, {1}, {2}, {3}, {4}, {5}", AA, BB, CC, DD, TT, SS); Console.WriteLine("AAA: {0}, {1}, {2}, {3}, {4}, {5}", AAA, BBB, CCC, DDD, TTT, SSS); ValueMess1(); Console.WriteLine("A: {0}, {1}, {2}, {3}, {4}, {5}", A, B, C, D, T, S); Console.WriteLine("AA: {0}, {1}, {2}, {3}, {4}, {5}", AA, BB, CC, DD, TT, SS); Console.WriteLine("AAA: {0}, {1}, {2}, {3}, {4}, {5}", AAA, BBB, CCC, DDD, TTT, SSS); int Y = Thread.CurrentThread.GetHashCode(); int X = (A ^ Y) | (B ^ Y) | (C ^ Y) |(D ^ Y)| (AAA ^ Y) | (BBB ^ Y) | (CCC ^ Y) |(DDD ^ Y); Console.WriteLine("X: {0}, {1}", X, S); if (X != 0) { Console.WriteLine("Something went wrong in thread: {0}", S); Result = 700 + Y; } } public static void ThreadFunc2(Object O) { Console.WriteLine("Threadpool Started.. {0}", Thread.CurrentThread.GetHashCode().ToString()); Console.WriteLine("TP A: {0}, {1}, {2}, {3}, {4}, {5}", A, B, C, D, T, S); Console.WriteLine("TP AA: {0}, {1}, {2}, {3}, {4}, {5}", AA, BB, CC, DD, TT, SS); Console.WriteLine("TP AAA: {0}, {1}, {2}, {3}, {4}, {5}", AAA, BBB, CCC, DDD, TTT, SSS); ValueMess1(); Console.WriteLine("TP A: {0}, {1}, {2}, {3}, {4}, {5}", A, B, C, D, T, S); Console.WriteLine("TP AA: {0}, {1}, {2}, {3}, {4}, {5}", AA, BB, CC, DD, TT, SS); Console.WriteLine("TP AAA: {0}, {1}, {2}, {3}, {4}, {5}", AAA, BBB, CCC, DDD, TTT, SSS); int Y = Thread.CurrentThread.GetHashCode(); int X = (A ^ Y) | (B ^ Y) | (C ^ Y) |(D ^ Y)| (AAA ^ Y) | (BBB ^ Y) | (CCC ^ Y) |(DDD ^ Y); Console.WriteLine("X: {0}, {1}", X, S); if (X != 0) { Console.WriteLine("Something went wrong in thread: {0}", S); Result = 700 + Y; } } public static void ValueMess1() { A = Thread.CurrentThread.GetHashCode(); B = Thread.CurrentThread.GetHashCode(); C = Thread.CurrentThread.GetHashCode(); D = Thread.CurrentThread.GetHashCode(); T = DateTime.Now; S = Thread.CurrentThread.GetHashCode().ToString(); AA = Thread.CurrentThread.GetHashCode(); BB = Thread.CurrentThread.GetHashCode(); CC = Thread.CurrentThread.GetHashCode(); DD = Thread.CurrentThread.GetHashCode(); TT = DateTime.Now; SS = Thread.CurrentThread.GetHashCode().ToString(); AAA = Thread.CurrentThread.GetHashCode(); BBB = Thread.CurrentThread.GetHashCode(); CCC = Thread.CurrentThread.GetHashCode(); DDD = Thread.CurrentThread.GetHashCode(); TTT = DateTime.Now; SSS = Thread.CurrentThread.GetHashCode().ToString(); } public static void ValueMess2() { A = -Thread.CurrentThread.GetHashCode(); B = -Thread.CurrentThread.GetHashCode(); C = -Thread.CurrentThread.GetHashCode(); D = -Thread.CurrentThread.GetHashCode(); T = DateTime.Now; S = Thread.CurrentThread.GetHashCode().ToString(); AA = -Thread.CurrentThread.GetHashCode(); BB = -Thread.CurrentThread.GetHashCode(); CC = -Thread.CurrentThread.GetHashCode(); DD = -Thread.CurrentThread.GetHashCode(); TT = DateTime.Now; SS = Thread.CurrentThread.GetHashCode().ToString(); AAA = -Thread.CurrentThread.GetHashCode(); BBB = -Thread.CurrentThread.GetHashCode(); CCC = -Thread.CurrentThread.GetHashCode(); DDD = -Thread.CurrentThread.GetHashCode(); TTT = DateTime.Now; SSS = Thread.CurrentThread.GetHashCode().ToString(); } }
// #define ODATA using Foo; using Microsoft.OData.Edm; using Microsoft.OData.Edm.Csdl; //using Microsoft.Data.Edm; //using Microsoft.Data.Edm.Csdl; using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Common; using System.Data.Entity; using System.Data.Entity.Spatial; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.Xml; namespace Models.NorthwindIB.CF { public class NorthwindIBContext_CF : DbContext { static NorthwindIBContext_CF() { // Uncomment this line if you are having testing issues with CodeFirst - errors will get eaten when // exposed via a webService - this will expose them. // InitializeTestContext(); } public static NorthwindIBContext_CF InitializeTestContext() { var context = new NorthwindIBContext_CF(); try { var customers = context.Customers.ToList(); } catch (Exception e) { Console.WriteLine(e.Message); } return context; } public NorthwindIBContext_CF(string connectionString) : base(connectionString) { this.Configuration.ProxyCreationEnabled = false; this.Configuration.LazyLoadingEnabled = false; } // Use the constructor to target a specific named connection string public NorthwindIBContext_CF() : base(nameOrConnectionString: "NorthwindIBContext_CF") { // Disable proxy creation as this messes up the data service. this.Configuration.ProxyCreationEnabled = false; this.Configuration.LazyLoadingEnabled = false; // Create Northwind if it doesn't already exist. //this.Database.CreateIfNotExists(); } public NorthwindIBContext_CF(DbConnection connection) : base(connection, false) { // Disable proxy creation as this messes up the data service. this.Configuration.ProxyCreationEnabled = false; this.Configuration.LazyLoadingEnabled = false; // Create Northwind if it doesn't already exist. //this.Database.CreateIfNotExists(); } //// Disable creation of the EdmMetadata table. //protected override void OnModelCreating(DbModelBuilder modelBuilder) { // // modelBuilder.Conventions.Remove<IncludeMetadataConvention>(); //} public IEdmModel GetEdmModel() { using (MemoryStream stream = new MemoryStream()) { using (XmlWriter writer = XmlWriter.Create(stream)) { System.Data.Entity.Infrastructure.EdmxWriter.WriteEdmx(this, writer); } stream.Position = 0; using (XmlReader reader = XmlReader.Create(stream)) { return EdmxReader.Parse(reader); } } } // override for investigating customer complaint about EF original values for Enums //public override int SaveChanges() //{ // foreach (var ent in ChangeTracker.Entries() // .Where(p => p.State == EntityState.Deleted || p.State == EntityState.Modified || p.State == EntityState.Added)) // { // if (ent.State == EntityState.Added) // continue; // foreach (var prop in ent.OriginalValues.PropertyNames) // { // //TODO:Breeze Bug -- for enum IsModified is set to true but the originalValue is set to currentValue // if (ent.Property(prop).IsModified) // { // var originalValue = ent.OriginalValues[prop]; // var currentValue = ent.CurrentValues[prop]; // if (Equals(originalValue, currentValue)) // { // Console.WriteLine($"Property:{prop} IsModified is true but OriginalValue and CurrentValue the same."); // throw new Exception($"Property:{prop} IsModified is true but OriginalValue and CurrentValue the same."); // } // } // } // } // return base.SaveChanges(); //} #region DbSets public DbSet<Category> Categories { get; set; } public DbSet<Customer> Customers { get; set; } public DbSet<Employee> Employees { get; set; } public DbSet<EmployeeTerritory> EmployeeTerritories { get; set; } public DbSet<Order> Orders { get; set; } public DbSet<OrderDetail> OrderDetails { get; set; } public DbSet<PreviousEmployee> PreviousEmployees { get; set; } public DbSet<Product> Products { get; set; } public DbSet<Region> Regions { get; set; } public DbSet<Role> Roles { get; set; } public DbSet<Supplier> Suppliers { get; set; } public DbSet<Territory> Territories { get; set; } public DbSet<User> Users { get; set; } public DbSet<UserRole> UserRoles { get; set; } public DbSet<InternationalOrder> InternationalOrders { get; set; } public DbSet<TimeLimit> TimeLimits { get; set; } public DbSet<TimeGroup> TimeGroups { get; set; } public DbSet<Comment> Comments { get; set; } public DbSet<Geospatial> Geospatials { get; set; } public DbSet<UnusualDate> UnusualDates { get; set; } #endregion EntityQueries } } namespace Foo { [AttributeUsage(AttributeTargets.Class)] // NEW public class CustomerValidator : ValidationAttribute { public override Boolean IsValid(Object value) { var cust = value as Customer; if (cust != null && cust.CompanyName.ToLower() == "error") { ErrorMessage = "This customer is not valid!"; return false; } return true; } } [AttributeUsage(AttributeTargets.Property)] public class CustomValidator : ValidationAttribute { public override Boolean IsValid(Object value) { try { string val = (string)value; if (!string.IsNullOrEmpty(val) && val.StartsWith("Error")) { ErrorMessage = "{0} equals the word 'Error'"; return false; } return true; } catch (Exception e) { var x = e; return false; } } } #region Category class /// <summary>The auto-generated Category class. </summary> [DataContract(IsReference = true)] [Table("Category", Schema = "dbo")] public partial class Category { #region Data Properties /// <summary>Gets or sets the CategoryID. </summary> [Key] [DataMember] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Column("CategoryID")] // [IbVal.RequiredValueVerifier( ErrorMessageResourceName="Category_CategoryID")] public int CategoryID { get; set; } /// <summary>Gets or sets the CategoryName. </summary> [DataMember] [Column("CategoryName")] // [IbVal.StringLengthVerifier(MaxValue=15, IsRequired=true, ErrorMessageResourceName="Category_CategoryName")] public string CategoryName { get; set; } /// <summary>Gets or sets the Description. </summary> [DataMember] [Column("Description")] public string Description { get; set; } /// <summary>Gets or sets the Picture. </summary> [DataMember] [Column("Picture")] public byte[] Picture { get; set; } /// <summary>Gets or sets the RowVersion. </summary> [DataMember] [Column("RowVersion")] // [IbVal.RequiredValueVerifier( ErrorMessageResourceName="Category_RowVersion")] [DefaultValue(2)] public int RowVersion { get; set; } #endregion Data Properties #region Navigation properties /// <summary>Gets the Products. </summary> [DataMember] [InverseProperty("Category")] public ICollection<Product> Products { get; set; } #endregion Navigation properties } #endregion Category class #region Customer class /// <summary>The auto-generated Customer class. </summary> /// <LongDescription> /// test long doc /// </LongDescription> [DataContract(IsReference = true)] [Table("Customer", Schema = "dbo")] [CustomerValidator] public partial class Customer { #region Data Properties /// <summary>Gets or sets the CustomerID. </summary> [Key] [DataMember] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Column("CustomerID")] public System.Guid CustomerID { get; set; } /// <summary>Gets or sets the CustomerID_OLD. </summary> [DataMember] [Column("CustomerID_OLD")] [MaxLength(5)] public string CustomerID_OLD { get; set; } /// <summary>Gets or sets the CompanyName. </summary> [DataMember] [Column("CompanyName")] [MaxLength(40)] [Required] public string CompanyName { get; set; } /// <summary>Gets or sets the ContactName. </summary> [DataMember] [Column("ContactName")] [CustomValidator] [MaxLength(30)] public string ContactName { get; set; } /// <summary>Gets or sets the ContactTitle. </summary> [DataMember] [Column("ContactTitle")] [MaxLength(30)] public string ContactTitle { get; set; } /// <summary>Gets or sets the Address. </summary> [DataMember] [Column("Address")] [MaxLength(60)] public string Address { get; set; } /// <summary>Gets or sets the City. </summary> [DataMember] [Column("City")] [MaxLength(15)] public string City { get; set; } /// <summary>Gets or sets the Region. </summary> [DataMember] [Column("Region")] [MaxLength(15)] public string Region { get; set; } /// <summary>Gets or sets the PostalCode. </summary> [DataMember] [Column("PostalCode")] [MaxLength(10)] public string PostalCode { get; set; } /// <summary>Gets or sets the Country. </summary> [DataMember] [Column("Country")] [MaxLength(15)] public string Country { get; set; } /// <summary>Gets or sets the Phone. </summary> [DataMember] [Column("Phone")] [MaxLength(24)] public string Phone { get; set; } /// <summary>Gets or sets the Fax. </summary> [DataMember] [Column("Fax")] [MaxLength(24)] public string Fax { get; set; } /// <summary>Gets or sets the RowVersion. </summary> [DataMember] [Column("RowVersion")] [ConcurrencyCheck] public System.Nullable<int> RowVersion { get; set; } #endregion Data Properties #region Navigation properties /// <summary>Gets the Orders. </summary> [DataMember] [InverseProperty("Customer")] public ICollection<Order> Orders { get; set; } #endregion Navigation properties } #endregion Customer class #region Employee class /// <summary>The auto-generated Employee class. </summary> [DataContract(IsReference = true)] [Table("Employee", Schema = "dbo")] public partial class Employee { #region Data Properties /// <summary>Gets or sets the EmployeeID. </summary> [Key] [DataMember] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Column("EmployeeID")] public int EmployeeID { get; set; } /// <summary>Gets or sets the LastName. </summary> [DataMember] [Column("LastName")] [MaxLength(30)] [Required] public string LastName { get; set; } [DataMember] [Column("FirstName")] [MaxLength(30)] [Required] public string FirstName { get; set; } [DataMember] [Column("Title")] [MaxLength(30)] public string Title { get; set; } [DataMember] [Column("TitleOfCourtesy")] [MaxLength(25)] public string TitleOfCourtesy { get; set; } [DataMember] [Column("BirthDate")] public System.Nullable<System.DateTime> BirthDate { get; set; } [DataMember] [Column("HireDate")] public System.Nullable<System.DateTime> HireDate { get; set; } [DataMember] [Column("Address")] [MaxLength(60)] public string Address { get; set; } [DataMember] [Column("City")] [MaxLength(15)] public string City { get; set; } [DataMember] [Column("Region")] [MaxLength(15)] public string Region { get; set; } [DataMember] [Column("PostalCode")] [MaxLength(10)] public string PostalCode { get; set; } [DataMember] [Column("Country")] [MaxLength(15)] public string Country { get; set; } [DataMember] [Column("HomePhone")] [MaxLength(24)] public string HomePhone { get; set; } /// <summary>Gets or sets the Extension. </summary> [DataMember] [Column("Extension")] [MaxLength(4)] public string Extension { get; set; } /// <summary>Gets or sets the Photo. </summary> [DataMember] [Column("Photo")] public byte[] Photo { get; set; } /// <summary>Gets or sets the Notes. </summary> [DataMember] [Column("Notes")] public string Notes { get; set; } /// <summary>Gets or sets the PhotoPath. </summary> [DataMember] [Column("PhotoPath")] [MaxLength(255)] public string PhotoPath { get; set; } /// <summary>Gets or sets the ReportsToEmployeeID. </summary> [DataMember] [Column("ReportsToEmployeeID")] public System.Nullable<int> ReportsToEmployeeID { get; set; } /// <summary>Gets or sets the RowVersion. </summary> [DataMember] [Column("RowVersion")] public int RowVersion { get; set; } [DataMember] [Column("FullName")] [DatabaseGenerated(DatabaseGeneratedOption.Computed)] public String FullName { get; set; } #endregion Data Properties #region Navigation properties /// <summary>Gets the DirectReports. </summary> [DataMember] [InverseProperty("Manager")] public ICollection<Employee> DirectReports { get; set; } /// <summary>Gets or sets the Manager. </summary> [DataMember] [ForeignKey("ReportsToEmployeeID")] [InverseProperty("DirectReports")] public Employee Manager { get; set; } /// <summary>Gets the EmployeeTerritories. </summary> [DataMember] [InverseProperty("Employee")] public ICollection<EmployeeTerritory> EmployeeTerritories { get; set; } /// <summary>Gets the Orders. </summary> [DataMember] [InverseProperty("Employee")] public ICollection<Order> Orders { get; set; } /// <summary>Gets the Territories. </summary> [DataMember] [InverseProperty("Employees")] public ICollection<Territory> Territories { get; set; } #endregion Navigation properties } #endregion Employee class #region EmployeeTerritory class /// <summary>The auto-generated EmployeeTerritory class. </summary> [DataContract(IsReference = true)] [Table("EmployeeTerritory", Schema = "dbo")] public partial class EmployeeTerritory { #region Data Properties /// <summary>Gets or sets the ID. </summary> [Key] [DataMember] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Column("ID")] // [IbVal.RequiredValueVerifier( ErrorMessageResourceName="EmployeeTerritory_ID")] public int ID { get; set; } /// <summary>Gets or sets the EmployeeID. </summary> [DataMember] //[ForeignKey("Employee")] [Column("EmployeeID")] // [IbVal.RequiredValueVerifier( ErrorMessageResourceName="EmployeeTerritory_EmployeeID")] public int EmployeeID { get; set; } /// <summary>Gets or sets the TerritoryID. </summary> [DataMember] // [ForeignKey("Territory")] [Column("TerritoryID")] // [IbVal.RequiredValueVerifier( ErrorMessageResourceName="EmployeeTerritory_TerritoryID")] public int TerritoryID { get; set; } /// <summary>Gets or sets the RowVersion. </summary> [DataMember] [Column("RowVersion")] // [IbVal.RequiredValueVerifier( ErrorMessageResourceName="EmployeeTerritory_RowVersion")] public int RowVersion { get; set; } #endregion Data Properties #region Navigation properties /// <summary>Gets or sets the Employee. </summary> [DataMember] [ForeignKey("EmployeeID")] [InverseProperty("EmployeeTerritories")] public Employee Employee { get; set; } /// <summary>Gets or sets the Territory. </summary> [DataMember] [ForeignKey("TerritoryID")] [InverseProperty("EmployeeTerritories")] public Territory Territory { get; set; } #endregion Navigation properties } #endregion EmployeeTerritory class #region Order class /// <summary>The auto-generated Order class. </summary> [DataContract(IsReference = true)] [Table("Order", Schema = "dbo")] public partial class Order { #region Data Properties /// <summary>Gets or sets the OrderID. </summary> [Key] [DataMember] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Column("OrderID")] public int OrderID { get; set; } /// <summary>Gets or sets the CustomerID. </summary> [DataMember] // [ForeignKey("Customer")] [Column("CustomerID")] public System.Nullable<System.Guid> CustomerID { get; set; } /// <summary>Gets or sets the EmployeeID. </summary> [DataMember] // [ForeignKey("Employee")] [Column("EmployeeID")] public System.Nullable<int> EmployeeID { get; set; } /// <summary>Gets or sets the OrderDate. </summary> [DataMember] [Column("OrderDate")] public System.Nullable<System.DateTime> OrderDate { get; set; } /// <summary>Gets or sets the RequiredDate. </summary> [DataMember] [Column("RequiredDate")] public System.Nullable<System.DateTime> RequiredDate { get; set; } /// <summary>Gets or sets the ShippedDate. </summary> [DataMember] [Column("ShippedDate")] public System.Nullable<System.DateTime> ShippedDate { get; set; } /// <summary>Gets or sets the Freight. </summary> [DataMember] [Column("Freight")] public System.Nullable<decimal> Freight { get; set; } /// <summary>Gets or sets the ShipName. </summary> [DataMember] [Column("ShipName")] // [IbVal.StringLengthVerifier(MaxValue=40, IsRequired=false, ErrorMessageResourceName="Order_ShipName")] [MaxLength(40)] public string ShipName { get; set; } /// <summary>Gets or sets the ShipAddress. </summary> [DataMember] [Column("ShipAddress")] // [IbVal.StringLengthVerifier(MaxValue=60, IsRequired=false, ErrorMessageResourceName="Order_ShipAddress")] [MaxLength(60)] public string ShipAddress { get; set; } /// <summary>Gets or sets the ShipCity. </summary> [DataMember] [Column("ShipCity")] // [IbVal.StringLengthVerifier(MaxValue=15, IsRequired=false, ErrorMessageResourceName="Order_ShipCity")] [MaxLength(15)] public string ShipCity { get; set; } /// <summary>Gets or sets the ShipRegion. </summary> [DataMember] [Column("ShipRegion")] // [IbVal.StringLengthVerifier(MaxValue=15, IsRequired=false, ErrorMessageResourceName="Order_ShipRegion")] [MaxLength(15)] public string ShipRegion { get; set; } /// <summary>Gets or sets the ShipPostalCode. </summary> [DataMember] [Column("ShipPostalCode")] // [IbVal.StringLengthVerifier(MaxValue=10, IsRequired=false, ErrorMessageResourceName="Order_ShipPostalCode")] [MaxLength(10)] public string ShipPostalCode { get; set; } /// <summary>Gets or sets the ShipCountry. </summary> [DataMember] [Column("ShipCountry")] // [IbVal.StringLengthVerifier(MaxValue=15, IsRequired=false, ErrorMessageResourceName="Order_ShipCountry")] [MaxLength(15)] public string ShipCountry { get; set; } /// <summary>Gets or sets the RowVersion. </summary> [DataMember] [Column("RowVersion")] // [IbVal.RequiredValueVerifier( ErrorMessageResourceName="Order_RowVersion")] public int RowVersion { get; set; } #endregion Data Properties #region Navigation properties /// <summary>Gets or sets the Customer. </summary> [DataMember] [ForeignKey("CustomerID")] [InverseProperty("Orders")] public Customer Customer { get; set; } /// <summary>Gets or sets the Employee. </summary> [DataMember] [ForeignKey("EmployeeID")] [InverseProperty("Orders")] public Employee Employee { get; set; } /// <summary>Gets the OrderDetails. </summary> [DataMember] [InverseProperty("Order")] public ICollection<OrderDetail> OrderDetails { get; set; } /// <summary>Gets or sets the InternationalOrder. </summary> [DataMember] [InverseProperty("Order")] public InternationalOrder InternationalOrder { get; set; } #endregion Navigation properties } #endregion Order class #region OrderDetail class /// <summary>The auto-generated OrderDetail class. </summary> [DataContract(IsReference = true)] [Table("OrderDetail", Schema = "dbo")] public partial class OrderDetail { #region Data Properties /// <summary>Gets or sets the OrderID. </summary> [Key] [DataMember] // [ForeignKey("Order")] [DatabaseGenerated(DatabaseGeneratedOption.None)] [Column("OrderID", Order = 0)] // [IbVal.RequiredValueVerifier( ErrorMessageResourceName="OrderDetail_OrderID")] public int OrderID { get; set; } /// <summary>Gets or sets the ProductID. </summary> [Key] [DataMember] // [ForeignKey("Product")] [DatabaseGenerated(DatabaseGeneratedOption.None)] [Column("ProductID", Order = 1)] // [IbVal.RequiredValueVerifier( ErrorMessageResourceName="OrderDetail_ProductID")] public int ProductID { get; set; } /// <summary>Gets or sets the UnitPrice. </summary> [DataMember] [Column("UnitPrice")] // [IbVal.RequiredValueVerifier( ErrorMessageResourceName="OrderDetail_UnitPrice")] public decimal UnitPrice { get; set; } /// <summary>Gets or sets the Quantity. </summary> [DataMember] [Column("Quantity")] // [IbVal.RequiredValueVerifier( ErrorMessageResourceName="OrderDetail_Quantity")] public short Quantity { get; set; } /// <summary>Gets or sets the Discount. </summary> [DataMember] [Column("Discount")] // [IbVal.RequiredValueVerifier( ErrorMessageResourceName="OrderDetail_Discount")] public float Discount { get; set; } /// <summary>Gets or sets the RowVersion. </summary> [DataMember] [Column("RowVersion")] // [IbVal.RequiredValueVerifier( ErrorMessageResourceName="OrderDetail_RowVersion")] public int RowVersion { get; set; } #endregion Data Properties #region Navigation properties /// <summary>Gets or sets the Order. </summary> [DataMember] [ForeignKey("OrderID")] [InverseProperty("OrderDetails")] public Order Order { get; set; } /// <summary>Gets or sets the Product. </summary> [DataMember] [ForeignKey("ProductID")] // [InverseProperty("OrderDetails")] public Product Product { get; set; } #endregion Navigation properties } #endregion OrderDetail class #region PreviousEmployee class /// <summary>The auto-generated PreviousEmployee class. </summary> [DataContract(IsReference = true)] [Table("PreviousEmployee", Schema = "dbo")] public partial class PreviousEmployee { #region Data Properties /// <summary>Gets or sets the EmployeeID. </summary> [Key] [DataMember] [DatabaseGenerated(DatabaseGeneratedOption.None)] [Column("EmployeeID")] // [IbVal.RequiredValueVerifier( ErrorMessageResourceName="PreviousEmployee_EmployeeID")] public int EmployeeID { get; set; } /// <summary>Gets or sets the LastName. </summary> [DataMember] [Column("LastName")] // [IbVal.StringLengthVerifier(MaxValue=20, IsRequired=true, ErrorMessageResourceName="PreviousEmployee_LastName")] [MaxLength(20)] [Required] public string LastName { get; set; } /// <summary>Gets or sets the FirstName. </summary> [DataMember] [Column("FirstName")] // [IbVal.StringLengthVerifier(MaxValue=10, IsRequired=true, ErrorMessageResourceName="PreviousEmployee_FirstName")] [MaxLength(10)] [Required] public string FirstName { get; set; } /// <summary>Gets or sets the Title. </summary> [DataMember] [Column("Title")] // [IbVal.StringLengthVerifier(MaxValue=30, IsRequired=false, ErrorMessageResourceName="PreviousEmployee_Title")] [MaxLength(30)] public string Title { get; set; } /// <summary>Gets or sets the TitleOfCourtesy. </summary> [DataMember] [Column("TitleOfCourtesy")] // [IbVal.StringLengthVerifier(MaxValue=25, IsRequired=false, ErrorMessageResourceName="PreviousEmployee_TitleOfCourtesy")] [MaxLength(25)] public string TitleOfCourtesy { get; set; } /// <summary>Gets or sets the BirthDate. </summary> [DataMember] [Column("BirthDate")] public System.Nullable<System.DateTime> BirthDate { get; set; } /// <summary>Gets or sets the HireDate. </summary> [DataMember] [Column("HireDate")] public System.Nullable<System.DateTime> HireDate { get; set; } /// <summary>Gets or sets the Address. </summary> [DataMember] [Column("Address")] // [IbVal.StringLengthVerifier(MaxValue=60, IsRequired=false, ErrorMessageResourceName="PreviousEmployee_Address")] public string Address { get; set; } /// <summary>Gets or sets the City. </summary> [DataMember] [Column("City")] // [IbVal.StringLengthVerifier(MaxValue=15, IsRequired=false, ErrorMessageResourceName="PreviousEmployee_City")] [MaxLength(15)] public string City { get; set; } /// <summary>Gets or sets the Region. </summary> [DataMember] [Column("Region")] // [IbVal.StringLengthVerifier(MaxValue=15, IsRequired=false, ErrorMessageResourceName="PreviousEmployee_Region")] [MaxLength(15)] public string Region { get; set; } /// <summary>Gets or sets the PostalCode. </summary> [DataMember] [Column("PostalCode")] // [IbVal.StringLengthVerifier(MaxValue=10, IsRequired=false, ErrorMessageResourceName="PreviousEmployee_PostalCode")] [MaxLength(10)] public string PostalCode { get; set; } /// <summary>Gets or sets the Country. </summary> [DataMember] [Column("Country")] // [IbVal.StringLengthVerifier(MaxValue=15, IsRequired=false, ErrorMessageResourceName="PreviousEmployee_Country")] [MaxLength(15)] public string Country { get; set; } /// <summary>Gets or sets the HomePhone. </summary> [DataMember] [Column("HomePhone")] // [IbVal.StringLengthVerifier(MaxValue=24, IsRequired=false, ErrorMessageResourceName="PreviousEmployee_HomePhone")] [MaxLength(24)] public string HomePhone { get; set; } /// <summary>Gets or sets the Extension. </summary> [DataMember] [Column("Extension")] // [IbVal.StringLengthVerifier(MaxValue=4, IsRequired=false, ErrorMessageResourceName="PreviousEmployee_Extension")] [MaxLength(4)] public string Extension { get; set; } /// <summary>Gets or sets the Photo. </summary> [DataMember] [Column("Photo")] public byte[] Photo { get; set; } /// <summary>Gets or sets the Notes. </summary> [DataMember] [Column("Notes")] public string Notes { get; set; } /// <summary>Gets or sets the PhotoPath. </summary> [DataMember] [Column("PhotoPath")] // [IbVal.StringLengthVerifier(MaxValue=255, IsRequired=false, ErrorMessageResourceName="PreviousEmployee_PhotoPath")] [MaxLength(255)] public string PhotoPath { get; set; } /// <summary>Gets or sets the RowVersion. </summary> [DataMember] [Column("RowVersion")] // [IbVal.RequiredValueVerifier( ErrorMessageResourceName="PreviousEmployee_RowVersion")] public int RowVersion { get; set; } #endregion Data Properties #region Navigation properties #endregion Navigation properties } #endregion PreviousEmployee class #region Product class /// <summary>The auto-generated Product class. </summary> [DataContract(IsReference = true)] [Table("Product", Schema = "dbo")] public partial class Product { #region Data Properties /// <summary>Gets or sets the ProductID. </summary> [Key] [DataMember] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Column("ProductID")] // [IbVal.RequiredValueVerifier( ErrorMessageResourceName="Product_ProductID")] public int ProductID { get; set; } /// <summary>Gets or sets the ProductName. </summary> [DataMember] [Column("ProductName")] // [IbVal.StringLengthVerifier(MaxValue=40, IsRequired=true, ErrorMessageResourceName="Product_ProductName")] [MaxLength(40)] public string ProductName { get; set; } /// <summary>Gets or sets the SupplierID. </summary> [DataMember] //[ForeignKey("Supplier")] [Column("SupplierID")] public System.Nullable<int> SupplierID { get; set; } /// <summary>Gets or sets the CategoryID. </summary> [DataMember] // [ForeignKey("Category")] [Column("CategoryID")] public System.Nullable<int> CategoryID { get; set; } /// <summary>Gets or sets the QuantityPerUnit. </summary> [DataMember] [Column("QuantityPerUnit")] // [IbVal.StringLengthVerifier(MaxValue=20, IsRequired=false, ErrorMessageResourceName="Product_QuantityPerUnit")] public string QuantityPerUnit { get; set; } /// <summary>Gets or sets the UnitPrice. </summary> [DataMember] [Column("UnitPrice")] public System.Nullable<decimal> UnitPrice { get; set; } /// <summary>Gets or sets the UnitsInStock. </summary> [DataMember] [Column("UnitsInStock")] public System.Nullable<short> UnitsInStock { get; set; } /// <summary>Gets or sets the UnitsOnOrder. </summary> [DataMember] [Column("UnitsOnOrder")] public System.Nullable<short> UnitsOnOrder { get; set; } /// <summary>Gets or sets the ReorderLevel. </summary> [DataMember] [Column("ReorderLevel")] public System.Nullable<short> ReorderLevel { get; set; } /// <summary>Gets or sets the Discontinued. </summary> [DataMember] [Column("Discontinued")] [DefaultValue(false)] // [IbVal.RequiredValueVerifier( ErrorMessageResourceName="Product_Discontinued")] public bool Discontinued { get; set; } /// <summary>Gets or sets the DiscontinuedDate. </summary> [DataMember] [Column("DiscontinuedDate")] public System.Nullable<System.DateTime> DiscontinuedDate { get; set; } /// <summary>Gets or sets the RowVersion. </summary> [DataMember] [Column("RowVersion")] // [IbVal.RequiredValueVerifier( ErrorMessageResourceName="Product_RowVersion")] public int RowVersion { get; set; } #endregion Data Properties #region Navigation properties /// <summary>Gets or sets the Category. </summary> [DataMember] [ForeignKey("CategoryID")] [InverseProperty("Products")] public Category Category { get; set; } ///// <summary>Gets the OrderDetails. </summary> //[DataMember] //[InverseProperty("Product")] //public ICollection<OrderDetail> OrderDetails { // get; // set; //} /// <summary>Gets or sets the Supplier. </summary> [DataMember] [ForeignKey("SupplierID")] [InverseProperty("Products")] public Supplier Supplier { get; set; } #endregion Navigation properties } #endregion Product class #region Region class /// <summary>The auto-generated Region class. </summary> [DataContract(IsReference = true)] [Table("Region", Schema = "dbo")] public partial class Region { #region Data Properties /// <summary>Gets or sets the RegionID. </summary> [Key] [DataMember] [DatabaseGenerated(DatabaseGeneratedOption.None)] [Column("RegionID")] // [IbVal.RequiredValueVerifier( ErrorMessageResourceName="Region_RegionID")] public int RegionID { get; set; } /// <summary>Gets or sets the RegionDescription. </summary> [DataMember] [Column("RegionDescription")] [MaxLength(50)] [Required] // [IbVal.StringLengthVerifier(MaxValue=50, IsRequired=true, ErrorMessageResourceName="Region_RegionDescription")] public string RegionDescription { get; set; } /// <summary>Gets or sets the RowVersion. </summary> [DataMember] [Column("RowVersion")] // [IbVal.RequiredValueVerifier( ErrorMessageResourceName="Region_RowVersion")] public int RowVersion { get; set; } #endregion Data Properties #region Navigation properties /// <summary>Gets the Territories. </summary> [DataMember] [InverseProperty("Region")] public ICollection<Territory> Territories { get; set; } #endregion Navigation properties } #endregion Region class #region Role class /// <summary>The auto-generated Role class. </summary> [DataContract(IsReference = true)] [Table("Role", Schema = "dbo")] public partial class Role { #region Data Properties /// <summary>Gets or sets the Id. </summary> [Key] [DataMember] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Column("Id")] // [IbVal.RequiredValueVerifier( ErrorMessageResourceName="Role_Id")] public long Id { get; set; } /// <summary>Gets or sets the Name. </summary> [DataMember] [Column("Name")] // [IbVal.StringLengthVerifier(MaxValue=50, IsRequired=true, ErrorMessageResourceName="Role_Name")] [MaxLength(50)] [Required] public string Name { get; set; } /// <summary>Gets or sets the Description. </summary> [DataMember] [Column("Description")] // [IbVal.StringLengthVerifier(MaxValue=2000, IsRequired=false, ErrorMessageResourceName="Role_Description")] [MaxLength(2000)] public string Description { get; set; } [DataMember] [Column("Ts")] [Required] [Timestamp] public byte[] Ts { get; set; } #if !ODATA [DataMember] [Column("RoleType")] public Nullable<Models.NorthwindIB.RoleType> RoleType { get; set; } #endif #endregion Data Properties #region Navigation properties /// <summary>Gets the UserRoles. </summary> [DataMember] [InverseProperty("Role")] public ICollection<UserRole> UserRoles { get; set; } #endregion Navigation properties } #endregion Role class #region Supplier class /// <summary>The auto-generated Supplier class. </summary> [DataContract(IsReference = true)] [Table("Supplier", Schema = "dbo")] public partial class Supplier { #region Data Properties /// <summary>Gets or sets the SupplierID. </summary> [Key] [DataMember] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Column("SupplierID")] // [IbVal.RequiredValueVerifier( ErrorMessageResourceName="Supplier_SupplierID")] public int SupplierID { get; set; } /// <summary>Gets or sets the CompanyName. </summary> [DataMember] [Column("CompanyName")] // [IbVal.StringLengthVerifier(MaxValue=40, IsRequired=true, ErrorMessageResourceName="Supplier_CompanyName")] [MaxLength(40)] [Required] public string CompanyName { get; set; } /// <summary>Gets or sets the ContactName. </summary> [DataMember] [Column("ContactName")] // [IbVal.StringLengthVerifier(MaxValue=30, IsRequired=false, ErrorMessageResourceName="Supplier_ContactName")] [MaxLength(30)] public string ContactName { get; set; } /// <summary>Gets or sets the ContactTitle. </summary> [DataMember] [Column("ContactTitle")] // [IbVal.StringLengthVerifier(MaxValue=30, IsRequired=false, ErrorMessageResourceName="Supplier_ContactTitle")] [MaxLength(30)] public string ContactTitle { get; set; } [DataMember] public Location Location { get; set; } ///// <summary>Gets or sets the Address. </summary> //[DataMember] //[Column("Address")] //// [IbVal.StringLengthVerifier(MaxValue=60, IsRequired=false, ErrorMessageResourceName="Supplier_Address")] //[MaxLength(60)] //public string Address { // get; // set; //} ///// <summary>Gets or sets the City. </summary> //[DataMember] //[Column("City")] //// [IbVal.StringLengthVerifier(MaxValue=15, IsRequired=false, ErrorMessageResourceName="Supplier_City")] //[MaxLength(15)] //public string City { // get; // set; //} ///// <summary>Gets or sets the Region. </summary> //[DataMember] //[Column("Region")] //// [IbVal.StringLengthVerifier(MaxValue=15, IsRequired=false, ErrorMessageResourceName="Supplier_Region")] //[MaxLength(15)] //public string Region { // get; // set; //} ///// <summary>Gets or sets the PostalCode. </summary> //[DataMember] //[Column("PostalCode")] //// [IbVal.StringLengthVerifier(MaxValue=10, IsRequired=false, ErrorMessageResourceName="Supplier_PostalCode")] //[MaxLength(10)] //public string PostalCode { // get; // set; //} ///// <summary>Gets or sets the Country. </summary> //[DataMember] //[Column("Country")] //// [IbVal.StringLengthVerifier(MaxValue=15, IsRequired=false, ErrorMessageResourceName="Supplier_Country")] //[MaxLength(15)] //public string Country { // get; // set; //} /// <summary>Gets or sets the Phone. </summary> [DataMember] [Column("Phone")] // [IbVal.StringLengthVerifier(MaxValue=24, IsRequired=false, ErrorMessageResourceName="Supplier_Phone")] [MaxLength(24)] public string Phone { get; set; } /// <summary>Gets or sets the Fax. </summary> [DataMember] [Column("Fax")] // [IbVal.StringLengthVerifier(MaxValue=24, IsRequired=false, ErrorMessageResourceName="Supplier_Fax")] [MaxLength(24)] public string Fax { get; set; } /// <summary>Gets or sets the HomePage. </summary> [DataMember] [Column("HomePage")] public string HomePage { get; set; } /// <summary>Gets or sets the RowVersion. </summary> [DataMember] [Column("RowVersion")] // [IbVal.RequiredValueVerifier( ErrorMessageResourceName="Supplier_RowVersion")] public int RowVersion { get; set; } #endregion Data Properties #region Navigation properties /// <summary>Gets the Products. </summary> [DataMember] [InverseProperty("Supplier")] public ICollection<Product> Products { get; set; } #endregion Navigation properties } #endregion Supplier class #region Location class [ComplexType] public partial class Location { /// <summary>Gets or sets the Address. </summary> [DataMember] [Column("Address")] // [IbVal.StringLengthVerifier(MaxValue=60, IsRequired=false, ErrorMessageResourceName="Supplier_Address")] [MaxLength(60)] public string Address { get; set; } /// <summary>Gets or sets the City. </summary> [DataMember] [Column("City")] // [IbVal.StringLengthVerifier(MaxValue=15, IsRequired=false, ErrorMessageResourceName="Supplier_City")] [MaxLength(15)] public string City { get; set; } /// <summary>Gets or sets the Region. </summary> [DataMember] [Column("Region")] // [IbVal.StringLengthVerifier(MaxValue=15, IsRequired=false, ErrorMessageResourceName="Supplier_Region")] [MaxLength(15)] public string Region { get; set; } /// <summary>Gets or sets the PostalCode. </summary> [DataMember] [Column("PostalCode")] // [IbVal.StringLengthVerifier(MaxValue=10, IsRequired=false, ErrorMessageResourceName="Supplier_PostalCode")] [MaxLength(10)] public string PostalCode { get; set; } /// <summary>Gets or sets the Country. </summary> [DataMember] [Column("Country")] // [IbVal.StringLengthVerifier(MaxValue=15, IsRequired=false, ErrorMessageResourceName="Supplier_Country")] [MaxLength(15)] public string Country { get; set; } } #endregion Location #region Territory class /// <summary>The auto-generated Territory class. </summary> [DataContract(IsReference = true)] [Table("Territory", Schema = "dbo")] public partial class Territory { #region Data Properties /// <summary>Gets or sets the TerritoryID. </summary> [Key] [DataMember] [DatabaseGenerated(DatabaseGeneratedOption.None)] [Column("TerritoryID")] // [IbVal.RequiredValueVerifier( ErrorMessageResourceName="Territory_TerritoryID")] public int TerritoryID { get; set; } /// <summary>Gets or sets the TerritoryDescription. </summary> [DataMember] [Column("TerritoryDescription")] // [IbVal.StringLengthVerifier(MaxValue=50, IsRequired=true, ErrorMessageResourceName="Territory_TerritoryDescription")] [MaxLength(50)] [Required] public string TerritoryDescription { get; set; } /// <summary>Gets or sets the RegionID. </summary> [DataMember] // [ForeignKey("Region")] [Column("RegionID")] // [IbVal.RequiredValueVerifier( ErrorMessageResourceName="Territory_RegionID")] public int RegionID { get; set; } /// <summary>Gets or sets the RowVersion. </summary> [DataMember] [Column("RowVersion")] // [IbVal.RequiredValueVerifier( ErrorMessageResourceName="Territory_RowVersion")] public int RowVersion { get; set; } #endregion Data Properties #region Navigation properties /// <summary>Gets the EmployeeTerritories. </summary> [DataMember] [InverseProperty("Territory")] public ICollection<EmployeeTerritory> EmployeeTerritories { get; set; } /// <summary>Gets or sets the Region. </summary> [DataMember] [ForeignKey("RegionID")] [InverseProperty("Territories")] public Region Region { get; set; } /// <summary>Gets the Employees. </summary> [DataMember] [InverseProperty("Territories")] public ICollection<Employee> Employees { get; set; } #endregion Navigation properties } #endregion Territory class #region User class /// <summary>The auto-generated User class. </summary> [DataContract(IsReference = true)] [Table("User", Schema = "dbo")] public partial class User { #region Data Properties /// <summary>Gets or sets the Id. </summary> [Key] [DataMember] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Column("Id")] public long Id { get; set; } /// <summary>Gets or sets the UserName. </summary> [DataMember] [Column("UserName")] [MaxLength(100)] public string UserName { get; set; } /// <summary>Gets or sets the UserPassword. </summary> [DataMember] [Column("UserPassword")] [MaxLength(200)] public string UserPassword { get; set; } /// <summary>Gets or sets the FirstName. </summary> [DataMember] [Column("FirstName")] [MaxLength(100)] public string FirstName { get; set; } /// <summary>Gets or sets the LastName. </summary> [DataMember] [Column("LastName")] [MaxLength(100)] public string LastName { get; set; } /// <summary>Gets or sets the Email. </summary> [DataMember] [Column("Email")] [MaxLength(100)] public string Email { get; set; } /// <summary>Gets or sets the RowVersion. </summary> [DataMember] [Column("RowVersion")] [ConcurrencyCheck] public decimal RowVersion { get; set; } /// <summary>Gets or sets the CreatedBy. </summary> [DataMember] [Column("CreatedBy")] [MaxLength(100)] public string CreatedBy { get; set; } /// <summary>Gets or sets the CreatedByUserId. </summary> [DataMember] [Column("CreatedByUserId")] public long CreatedByUserId { get; set; } /// <summary>Gets or sets the CreatedDate. </summary> [DataMember] [Column("CreatedDate")] public System.DateTime CreatedDate { get; set; } /// <summary>Gets or sets the ModifiedBy. </summary> [DataMember] [Column("ModifiedBy")] [MaxLength(100)] public string ModifiedBy { get; set; } /// <summary>Gets or sets the ModifiedByUserId. </summary> [DataMember] [Column("ModifiedByUserId")] public long ModifiedByUserId { get; set; } /// <summary>Gets or sets the ModifiedDate. </summary> [DataMember] [Column("ModifiedDate")] public System.DateTime ModifiedDate { get; set; } #endregion Data Properties #region Navigation properties /// <summary>Gets the UserRoles. </summary> [DataMember] [InverseProperty("User")] public ICollection<UserRole> UserRoles { get; set; } #endregion Navigation properties } #endregion User class #region UserRole class /// <summary>The auto-generated UserRole class. </summary> [DataContract(IsReference = true)] [Table("UserRole", Schema = "dbo")] public partial class UserRole { #region Data Properties /// <summary>Gets or sets the ID. </summary> [Key] [DataMember] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Column("ID")] public long ID { get; set; } /// <summary>Gets or sets the UserId. </summary> [DataMember] // [ForeignKey("User")] [Column("UserId")] public long UserId { get; set; } /// <summary>Gets or sets the RoleId. </summary> [DataMember] // [ForeignKey("Role")] [Column("RoleId")] public long RoleId { get; set; } #endregion Data Properties #region Navigation properties /// <summary>Gets or sets the Role. </summary> [DataMember] [ForeignKey("RoleId")] [InverseProperty("UserRoles")] public Role Role { get; set; } /// <summary>Gets or sets the User. </summary> [DataMember] [ForeignKey("UserId")] [InverseProperty("UserRoles")] public User User { get; set; } #endregion Navigation properties } #endregion UserRole class #region InternationalOrder class /// <summary>The auto-generated InternationalOrder class. </summary> [DataContract(IsReference = true)] [Table("InternationalOrder", Schema = "dbo")] public partial class InternationalOrder { #region Data Properties /// <summary>Gets or sets the OrderID. </summary> [Key] [DataMember] [ForeignKey("Order")] [DatabaseGenerated(DatabaseGeneratedOption.None)] [Column("OrderID")] public int OrderID { get; set; } /// <summary>Gets or sets the CustomsDescription. </summary> [DataMember] [Column("CustomsDescription")] [MaxLength(100)] public string CustomsDescription { get; set; } /// <summary>Gets or sets the ExciseTax. </summary> [DataMember] [Column("ExciseTax")] public decimal ExciseTax { get; set; } /// <summary>Gets or sets the RowVersion. </summary> [DataMember] [Column("RowVersion")] public int RowVersion { get; set; } #endregion Data Properties #region Navigation properties /// <summary>Gets or sets the Order. </summary> [DataMember] //[ForeignKey("OrderID")] //[InverseProperty("InternationalOrder")] //[Required] public Order Order { get; set; } #endregion Navigation properties } #endregion InternationalOrder class #region TimeLimit class [DataContract(IsReference = true)] [Table("TimeLimit", Schema = "dbo")] public partial class TimeLimit { #region Data Properties [Key] [DataMember] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Column("Id")] public int Id { get; set; } [DataMember] [Column("MaxTime")] public System.TimeSpan MaxTime { get; set; } [DataMember] [Column("MinTime")] public Nullable<System.TimeSpan> MinTime { get; set; } [DataMember] // [ForeignKey("TimeGroup")] [Column("TimeGroupId")] public System.Nullable<int> TimeGroupId { get; set; } #endregion Data Properties #region Navigation Properties /// <summary>Gets or sets the TimeGroup. </summary> [DataMember] [ForeignKey("TimeGroupId")] [InverseProperty("TimeLimits")] public TimeGroup TimeGroup { get; set; } #endregion Navigation Properties } #endregion TimeLimit #region TimeGroup class [DataContract(IsReference = true)] [Table("TimeGroup", Schema = "dbo")] public partial class TimeGroup { #region Data Properties [Key] [DataMember] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Column("Id")] public int Id { get; set; } [DataMember] [Column("Comment")] public string Comment { get; set; } #endregion Data Properties #region Navigation Properties [DataMember] [InverseProperty("TimeGroup")] public ICollection<TimeLimit> TimeLimits { get; set; } #endregion Navigation Properties } #endregion TimeGroup #region Comment class [DataContract(IsReference = true)] [Table("Comment", Schema = "dbo")] public partial class Comment { #region Data Properties [Key] [DataMember] [DatabaseGenerated(DatabaseGeneratedOption.None)] [Column("CreatedOn", Order = 1)] public System.DateTime CreatedOn { get; set; } [Key] [DataMember] [DatabaseGenerated(DatabaseGeneratedOption.None)] [Column("SeqNum", Order = 2)] public byte SeqNum { get; set; } [DataMember] [Column("Comment1")] public string Comment1 { get; set; } #endregion Data Properties #region Navigation properties #endregion Navigation properties } #endregion Comment #region Geospatial class [DataContract(IsReference = true)] [Table("Geospatial", Schema = "dbo")] public partial class Geospatial { public Geospatial() { #if !ODATA this.Geometry1 = DbGeometry.FromText("POLYGON ((30 10, 10 20, 20 40, 40 40, 30 10))"); this.Geography1 = DbGeography.FromText("MULTIPOINT(-122.360 47.656, -122.343 47.656)", 4326); // this.Geometry1 = DbGeometry.FromText("GEOMETRYCOLLECTION(POINT(4 6),LINESTRING(4 6,7 10)"); #endif } [Key] [DataMember] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Column("Id")] public int Id { get; set; } #if !ODATA [DataMember] [Column("Geometry1")] public DbGeometry Geometry1 { get; set; } [DataMember] [Column("Geography1")] public DbGeography Geography1 { get; set; } #endif } #endregion Geospatial #region UnusualDate class [DataContract(IsReference = true)] [Table("UnusualDate", Schema = "dbo")] public partial class UnusualDate { [Key] [DataMember] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Column("Id")] public int Id { get; set; } [DataMember] [Column("CreationDate")] public System.DateTimeOffset CreationDate { get; set; } [DataMember] [Column("ModificationDate")] public System.DateTime ModificationDate { get; set; } [DataMember] [Column("CreationDate2")] public Nullable<System.DateTimeOffset> CreationDate2 { get; set; } [DataMember] [Column("ModificationDate2")] public Nullable<System.DateTime> ModificationDate2 { get; set; } } #endregion UnusualDate }
// <copyright file=PhysicsUtils company=Hydra> // Copyright (c) 2015 All Rights Reserved // </copyright> // <author>Christopher Cameron</author> using System; using UnityEngine; namespace Hydra.HydraCommon.Utils.Physics { /// <summary> /// Provides util methods for working with Unity's physics objects. /// </summary> public static class PhysicsUtils { public const float DEFAULT_BOUNCE = 0.0f; public const float DEFAULT_FRICTION = 0.4f; public const PhysicMaterialCombine DEFAULT_BOUNCE_COMBINE = PhysicMaterialCombine.Average; public const PhysicMaterialCombine DEFAULT_FRICTION_COMBINE = PhysicMaterialCombine.Average; /// <summary> /// Returns the resulting PhysicMaterialCombine for two colliding physics materials. /// /// Maximum > Multiply > Minimum > Average /// </summary> /// <returns>The resulting physic material combine.</returns> /// <param name="combineA">Combine a.</param> /// <param name="combineB">Combine b.</param> public static PhysicMaterialCombine ResultingPhysicMaterialCombine(PhysicMaterialCombine combineA, PhysicMaterialCombine combineB) { if (combineA == PhysicMaterialCombine.Maximum || combineB == PhysicMaterialCombine.Maximum) return PhysicMaterialCombine.Maximum; if (combineA == PhysicMaterialCombine.Multiply || combineB == PhysicMaterialCombine.Multiply) return PhysicMaterialCombine.Multiply; if (combineA == PhysicMaterialCombine.Minimum || combineB == PhysicMaterialCombine.Minimum) return PhysicMaterialCombine.Minimum; return PhysicMaterialCombine.Average; } /// <summary> /// Calculates the bounce of two surfaces colliding. Returns zero if the /// bounce is below the bounce threshold. /// </summary> /// <param name="bounceA">Bounce a.</param> /// <param name="bounceB">Bounce b.</param> /// <param name="velocityA">Velocity a.</param> /// <param name="velocityB">Velocity b.</param> /// <param name="combine">Combine.</param> public static float CombineBounce(float bounceA, float bounceB, Vector3 velocityA, Vector3 velocityB, PhysicMaterialCombine combine) { Vector3 relativeVelocity = velocityA - velocityB; if (relativeVelocity.magnitude < UnityEngine.Physics.bounceThreshold) return 0.0f; return Combine(bounceA, bounceB, combine); } /// <summary> /// Combines the friction of two surfaces. /// </summary> /// <returns>The combined friction.</returns> /// <param name="frictionA">Friction a.</param> /// <param name="frictionB">Friction b.</param> /// <param name="combine">Combine.</param> public static float CombineFriction(float frictionA, float frictionB, PhysicMaterialCombine combine) { return Combine(frictionA, frictionB, combine); } /// <summary> /// Combines the surface values. /// </summary> /// <returns>The combined surface value.</returns> /// <param name="surfaceA">Surface a.</param> /// <param name="surfaceB">Surface b.</param> /// <param name="combine">Combine.</param> public static float Combine(float surfaceA, float surfaceB, PhysicMaterialCombine combine) { switch (combine) { case PhysicMaterialCombine.Average: return (surfaceA + surfaceB) / 2.0f; case PhysicMaterialCombine.Maximum: return HydraMathUtils.Max(surfaceA, surfaceB); case PhysicMaterialCombine.Minimum: return HydraMathUtils.Min(surfaceA, surfaceB); case PhysicMaterialCombine.Multiply: return surfaceA * surfaceB; default: throw new ArgumentOutOfRangeException(); } } /// <summary> /// Performs a sphere cast in 3D and a circle cast in 2D. /// </summary> /// <returns>The closest collision information.</returns> /// <param name="origin">Origin.</param> /// <param name="radius">Radius.</param> /// <param name="direction">Direction.</param> /// <param name="distance">Distance.</param> /// <param name="layerMask">Layer mask.</param> /// <param name="minDepth">Minimum depth.</param> /// <param name="maxDepth">Max depth.</param> public static IHitWrapper SphereCirclecast2D3D(Vector3 origin, float radius, Vector3 direction, float distance, int layerMask, float minDepth, float maxDepth) { IHitWrapper hit3d = Spherecast3D(origin, radius, direction, distance, layerMask); IHitWrapper hit2d = Circlecast2D(origin, radius, direction, distance, layerMask, minDepth, maxDepth); if (!hit3d.collided) return hit2d; if (!hit2d.collided) return hit3d; return (hit2d.distance < hit3d.distance) ? hit2d : hit3d; } /// <summary> /// Performs a sphere cast in 3D. /// </summary> /// <returns>The collision information.</returns> /// <param name="origin">Origin.</param> /// <param name="radius">Radius.</param> /// <param name="direction">Direction.</param> /// <param name="distance">Distance.</param> /// <param name="layerMask">Layer mask.</param> public static Hit3DWrapper Spherecast3D(Vector3 origin, float radius, Vector3 direction, float distance, int layerMask) { if (layerMask == LayerMaskUtils.EMPTY) return default(Hit3DWrapper); RaycastHit hit; UnityEngine.Physics.SphereCast(origin, radius, direction, out hit, distance, layerMask); return new Hit3DWrapper(hit, origin, radius, direction, distance); } /// <summary> /// Performs a circle cast in 2D. /// </summary> /// <returns>The collision information.</returns> /// <param name="origin">Origin.</param> /// <param name="radius">Radius.</param> /// <param name="direction">Direction.</param> /// <param name="distance">Distance.</param> /// <param name="layerMask">Layer mask.</param> /// <param name="minDepth">Minimum depth.</param> /// <param name="maxDepth">Max depth.</param> public static Hit2DWrapper Circlecast2D(Vector3 origin, float radius, Vector3 direction, float distance, int layerMask, float minDepth, float maxDepth) { if (layerMask == LayerMaskUtils.EMPTY) return default(Hit2DWrapper); RaycastHit2D collision = Physics2D.CircleCast(origin, radius, direction, distance, layerMask, minDepth, maxDepth); return new Hit2DWrapper(collision, origin, radius, direction, distance); } /// <summary> /// Performs a raycast in both 2D and 3D. Returns data for the closest collision. /// </summary> /// <returns>The data for the closest collision.</returns> /// <param name="origin">Origin.</param> /// <param name="direction">Direction.</param> /// <param name="distance">Distance.</param> /// <param name="layerMask">Layer mask.</param> /// <param name="minDepth">Minimum depth.</param> /// <param name="maxDepth">Max depth.</param> public static IHitWrapper Raycast2D3D(Vector3 origin, Vector3 direction, float distance, int layerMask, float minDepth, float maxDepth) { IHitWrapper hit3d = Raycast3D(origin, direction, distance, layerMask); IHitWrapper hit2d = Raycast2D(origin, direction, distance, layerMask, minDepth, maxDepth); if (!hit3d.collided) return hit2d; if (!hit2d.collided) return hit3d; return (hit2d.distance < hit3d.distance) ? hit2d : hit3d; } /// <summary> /// Performs a 3D raycast and returns the collision data as a Hit3DWrapper. /// </summary> /// <returns>The collision data.</returns> /// <param name="origin">Origin.</param> /// <param name="direction">Direction.</param> /// <param name="distance">Distance.</param> /// <param name="layerMask">Layer mask.</param> public static Hit3DWrapper Raycast3D(Vector3 origin, Vector3 direction, float distance, int layerMask) { if (layerMask == LayerMaskUtils.EMPTY) return default(Hit3DWrapper); RaycastHit hit; UnityEngine.Physics.Raycast(origin, direction, out hit, distance, layerMask); return new Hit3DWrapper(hit, origin, 0.0f, direction, distance); } /// <summary> /// Performs a 2D raycast without discarding the Z component. /// /// This method also ignores any collision at the start of the ray. This is consistent /// with the 3D raycast behaviour. /// </summary> /// <returns>The collision data.</returns> /// <param name="origin">Origin.</param> /// <param name="direction">Direction.</param> /// <param name="distance">Distance.</param> /// <param name="layerMask">Layer mask.</param> /// <param name="minDepth">Minimum depth.</param> /// <param name="maxDepth">Max depth.</param> public static Hit2DWrapper Raycast2D(Vector3 origin, Vector3 direction, float distance, int layerMask, float minDepth, float maxDepth) { if (layerMask == LayerMaskUtils.EMPTY) return default(Hit2DWrapper); RaycastHit2D[] collisions = Physics2D.RaycastAll(origin, direction, distance, layerMask, minDepth, maxDepth); for (int index = 0; index < collisions.Length; index++) { RaycastHit2D hit2D = collisions[index]; if (HydraMathUtils.Approximately(hit2D.fraction, 0.0f)) continue; return new Hit2DWrapper(hit2D, origin, 0.0f, direction, distance); } return default(Hit2DWrapper); } } }
using System.IO; using Microsoft.Xna.Framework.Graphics; namespace CocosSharp { internal static class CCParticleExample { static byte[] firePngData = { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x20, 0x08, 0x06, 0x00, 0x00, 0x00, 0x73, 0x7A, 0x7A, 0xF4, 0x00, 0x00, 0x00, 0x04, 0x67, 0x41, 0x4D, 0x41, 0x00, 0x00, 0xAF, 0xC8, 0x37, 0x05, 0x8A, 0xE9, 0x00, 0x00, 0x00, 0x19, 0x74, 0x45, 0x58, 0x74, 0x53, 0x6F, 0x66, 0x74, 0x77, 0x61, 0x72, 0x65, 0x00, 0x41, 0x64, 0x6F, 0x62, 0x65, 0x20, 0x49, 0x6D, 0x61, 0x67, 0x65, 0x52, 0x65, 0x61, 0x64, 0x79, 0x71, 0xC9, 0x65, 0x3C, 0x00, 0x00, 0x02, 0x64, 0x49, 0x44, 0x41, 0x54, 0x78, 0xDA, 0xC4, 0x97, 0x89, 0x6E, 0xEB, 0x20, 0x10, 0x45, 0xBD, 0xE1, 0x2D, 0x4B, 0xFF, 0xFF, 0x37, 0x5F, 0x5F, 0x0C, 0xD8, 0xC4, 0xAE, 0x2D, 0xDD, 0xA9, 0x6E, 0xA7, 0x38, 0xC1, 0x91, 0xAA, 0x44, 0xBA, 0xCA, 0x06, 0xCC, 0x99, 0x85, 0x01, 0xE7, 0xCB, 0xB2, 0x64, 0xEF, 0x7C, 0x55, 0x2F, 0xCC, 0x69, 0x56, 0x15, 0xAB, 0x72, 0x68, 0x81, 0xE6, 0x55, 0xFE, 0xE8, 0x62, 0x79, 0x62, 0x04, 0x36, 0xA3, 0x06, 0xC0, 0x9B, 0xCA, 0x08, 0xC0, 0x7D, 0x55, 0x80, 0xA6, 0x54, 0x98, 0x67, 0x11, 0xA8, 0xA1, 0x86, 0x3E, 0x0B, 0x44, 0x41, 0x00, 0x33, 0x19, 0x1F, 0x21, 0x43, 0x9F, 0x5F, 0x02, 0x68, 0x49, 0x1D, 0x20, 0x1A, 0x82, 0x28, 0x09, 0xE0, 0x4E, 0xC6, 0x3D, 0x64, 0x57, 0x39, 0x80, 0xBA, 0xA3, 0x00, 0x1D, 0xD4, 0x93, 0x3A, 0xC0, 0x34, 0x0F, 0x00, 0x3C, 0x8C, 0x59, 0x4A, 0x99, 0x44, 0xCA, 0xA6, 0x02, 0x88, 0xC7, 0xA7, 0x55, 0x67, 0xE8, 0x44, 0x10, 0x12, 0x05, 0x0D, 0x30, 0x92, 0xE7, 0x52, 0x33, 0x32, 0x26, 0xC3, 0x38, 0xF7, 0x0C, 0xA0, 0x06, 0x40, 0x0F, 0xC3, 0xD7, 0x55, 0x17, 0x05, 0xD1, 0x92, 0x77, 0x02, 0x20, 0x85, 0xB7, 0x19, 0x18, 0x28, 0x4D, 0x05, 0x19, 0x9F, 0xA1, 0xF1, 0x08, 0xC0, 0x05, 0x10, 0x57, 0x7C, 0x4F, 0x01, 0x10, 0xEF, 0xC5, 0xF8, 0xAC, 0x76, 0xC8, 0x2E, 0x80, 0x14, 0x99, 0xE4, 0xFE, 0x44, 0x51, 0xB8, 0x52, 0x14, 0x3A, 0x32, 0x22, 0x00, 0x13, 0x85, 0xBF, 0x52, 0xC6, 0x05, 0x8E, 0xE5, 0x63, 0x00, 0x86, 0xB6, 0x9C, 0x86, 0x38, 0xAB, 0x54, 0x74, 0x18, 0x5B, 0x50, 0x58, 0x6D, 0xC4, 0xF3, 0x89, 0x6A, 0xC3, 0x61, 0x8E, 0xD9, 0x03, 0xA8, 0x08, 0xA0, 0x55, 0xBB, 0x40, 0x40, 0x3E, 0x00, 0xD2, 0x53, 0x47, 0x94, 0x0E, 0x38, 0xD0, 0x7A, 0x73, 0x64, 0x57, 0xF0, 0x16, 0xFE, 0x95, 0x82, 0x86, 0x1A, 0x4C, 0x4D, 0xE9, 0x68, 0xD5, 0xAE, 0xB8, 0x00, 0xE2, 0x8C, 0xDF, 0x4B, 0xE4, 0xD7, 0xC1, 0xB3, 0x4C, 0x75, 0xC2, 0x36, 0xD2, 0x3F, 0x2A, 0x7C, 0xF7, 0x0C, 0x50, 0x60, 0xB1, 0x4A, 0x81, 0x18, 0x88, 0xD3, 0x22, 0x75, 0xD1, 0x63, 0x5C, 0x80, 0xF7, 0x19, 0x15, 0xA2, 0xA5, 0xB9, 0xB5, 0x5A, 0xB7, 0xA4, 0x34, 0x7D, 0x03, 0x48, 0x5F, 0x17, 0x90, 0x52, 0x01, 0x19, 0x95, 0x9E, 0x1E, 0xD1, 0x30, 0x30, 0x9A, 0x21, 0xD7, 0x0D, 0x81, 0xB3, 0xC1, 0x92, 0x0C, 0xE7, 0xD4, 0x1B, 0xBE, 0x49, 0xF2, 0x04, 0x15, 0x2A, 0x52, 0x06, 0x69, 0x31, 0xCA, 0xB3, 0x22, 0x71, 0xBD, 0x1F, 0x00, 0x4B, 0x82, 0x66, 0xB5, 0xA7, 0x37, 0xCF, 0x6F, 0x78, 0x0F, 0xF8, 0x5D, 0xC6, 0xA4, 0xAC, 0xF7, 0x23, 0x05, 0x6C, 0xE4, 0x4E, 0xE2, 0xE3, 0x95, 0xB7, 0xD3, 0x40, 0xF3, 0xA5, 0x06, 0x1C, 0xFE, 0x1F, 0x09, 0x2A, 0xA8, 0xF5, 0xE6, 0x3D, 0x00, 0xDD, 0xAD, 0x02, 0x2D, 0xC4, 0x4D, 0x66, 0xA0, 0x6A, 0x1F, 0xD5, 0x2E, 0xF8, 0x8F, 0xFF, 0x2D, 0xC6, 0x4F, 0x04, 0x1E, 0x14, 0xD0, 0xAC, 0x01, 0x3C, 0xAA, 0x5C, 0x1F, 0xA9, 0x2E, 0x72, 0xBA, 0x49, 0xB5, 0xC7, 0xFA, 0xC0, 0x27, 0xD2, 0x62, 0x69, 0xAE, 0xA7, 0xC8, 0x04, 0xEA, 0x0F, 0xBF, 0x1A, 0x51, 0x50, 0x61, 0x16, 0x8F, 0x1B, 0xD5, 0x5E, 0x03, 0x75, 0x35, 0xDD, 0x09, 0x6F, 0x88, 0xC4, 0x0D, 0x73, 0x07, 0x82, 0x61, 0x88, 0xE8, 0x59, 0x30, 0x45, 0x8E, 0xD4, 0x7A, 0xA7, 0xBD, 0xDA, 0x07, 0x67, 0x81, 0x40, 0x30, 0x88, 0x55, 0xF5, 0x11, 0x05, 0xF0, 0x58, 0x94, 0x9B, 0x48, 0xEC, 0x60, 0xF1, 0x09, 0xC7, 0xF1, 0x66, 0xFC, 0xDF, 0x0E, 0x84, 0x7F, 0x74, 0x1C, 0x8F, 0x58, 0x44, 0x77, 0xAC, 0x59, 0xB5, 0xD7, 0x67, 0x00, 0x12, 0x85, 0x4F, 0x2A, 0x4E, 0x17, 0xBB, 0x1F, 0xC6, 0x00, 0xB8, 0x99, 0xB0, 0xE7, 0x23, 0x9D, 0xF7, 0xCF, 0x6E, 0x44, 0x83, 0x4A, 0x45, 0x32, 0x40, 0x86, 0x81, 0x7C, 0x8D, 0xBA, 0xAB, 0x1C, 0xA7, 0xDE, 0x09, 0x87, 0x48, 0x21, 0x26, 0x5F, 0x4A, 0xAD, 0xBA, 0x6E, 0x4F, 0xCA, 0xFB, 0x23, 0xB7, 0x62, 0xF7, 0xCA, 0xAD, 0x58, 0x22, 0xC1, 0x00, 0x47, 0x9F, 0x0B, 0x7C, 0xCA, 0x73, 0xC1, 0xDB, 0x9F, 0x8C, 0xF2, 0x17, 0x1E, 0x4E, 0xDF, 0xF2, 0x6C, 0xF8, 0x67, 0xAF, 0x22, 0x7B, 0xF3, 0xEB, 0x4B, 0x80, 0x01, 0x00, 0xB8, 0x21, 0x72, 0x89, 0x08, 0x10, 0x07, 0x7D, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82 }; static CCTexture2D defaultTexture; public static CCTexture2D DefaultTexture { get { if (defaultTexture == null) { defaultTexture = CCTextureCache.SharedTextureCache.AddImage(firePngData, "__firePngData", CCSurfaceFormat.Color); } return defaultTexture; } } } // // ParticleFire // public class CCParticleFire : CCParticleSystemQuad { static CCParticleSystemConfig config; public CCParticleFire(CCPoint position) : base(250) { if (config == null) { config = new CCParticleSystemConfig (); config.ParticleSystemType = CCParticleSystemType.Internal; config.Duration = ParticleDurationInfinity; config.Life = 3; config.LifeVar = 0.25f; config.Position = position; config.PositionVar = new CCPoint(40, 20); config.Angle = 90; config.AngleVar = 10; config.StartSize = 54.0f; config.StartSizeVar = 10.0f; config.EndSize = ParticleStartSizeEqualToEndSize; config.EmitterMode = CCEmitterMode.Gravity; CCColor4F cstartColor = new CCColor4F(); cstartColor.R = 0.76f; cstartColor.G = 0.25f; cstartColor.B = 0.12f; cstartColor.A = 1.0f; config.StartColor = cstartColor; CCColor4F cstartColorVar = new CCColor4F(); cstartColorVar.R = 0.0f; cstartColorVar.G = 0.0f; cstartColorVar.B = 0.0f; cstartColorVar.A = 0.0f; config.StartColorVar = cstartColorVar; CCColor4F cendColor = new CCColor4F(); cendColor.R = 0.0f; cendColor.G = 0.0f; cendColor.B = 0.0f; cendColor.A = 1.0f; config.EndColor = cendColor; CCColor4F cendColorVar = new CCColor4F(); cendColorVar.R = 0.0f; cendColorVar.G = 0.0f; cendColorVar.B = 0.0f; cendColorVar.A = 0.0f; config.EndColorVar = cendColorVar; config.Gravity = new CCPoint(0, 0); config.GravityRadialAccel = 0; config.GravityRadialAccelVar = 0; config.GravitySpeed = 60; config.GravitySpeedVar = 20; config.Texture = CCParticleExample.DefaultTexture; } Duration = config.Duration; Life = config.Life; LifeVar = config.LifeVar; Position = config.Position; PositionVar = config.PositionVar; Angle = config.Angle; AngleVar = config.AngleVar; StartSize = config.StartSize; StartSizeVar = config.StartSizeVar; EndSize = config.EndSize; EmissionRate = TotalParticles / Life; CCColor4F startColor = new CCColor4F(); startColor.R = config.StartColor.R; startColor.G = config.StartColor.G; startColor.B = config.StartColor.B; startColor.A = config.StartColor.A; StartColor = startColor; CCColor4F startColorVar = new CCColor4F(); startColorVar.R = config.StartColorVar.R; startColorVar.G = config.StartColorVar.G; startColorVar.B = config.StartColorVar.B; startColorVar.A = config.StartColorVar.A; StartColorVar = startColorVar; CCColor4F endColor = new CCColor4F(); endColor.R = config.EndColor.R; endColor.G = config.EndColor.G; endColor.B = config.EndColor.B; endColor.A = config.EndColor.A; EndColor = endColor; CCColor4F endColorVar = new CCColor4F(); endColorVar.R = config.EndColorVar.R; endColorVar.G = config.EndColorVar.G; endColorVar.B = config.EndColorVar.B; endColorVar.A = config.EndColorVar.A; EndColorVar = endColorVar; GravityMoveMode gravityMode = new GravityMoveMode(); gravityMode.Gravity = new CCPoint(config.Gravity); gravityMode.RadialAccel = config.GravityRadialAccel; gravityMode.RadialAccelVar = config.GravityRadialAccelVar; gravityMode.Speed = config.GravitySpeed; gravityMode.SpeedVar = config.GravitySpeedVar; GravityMode = gravityMode; BlendAdditive = true; Texture = config.Texture; } } // // ParticleFireworks // public class CCParticleFireworks : CCParticleSystemQuad { public CCParticleFireworks(CCPoint position) : base(1500) { Duration = ParticleDurationInfinity; Life = 3.5f; LifeVar = 1; Position = position; Angle = 90; AngleVar = 20; StartSize = 8.0f; StartSizeVar = 2.0f; EndSize = ParticleStartSizeEqualToEndSize; EmissionRate = TotalParticles / Life; StartColor = new CCColor4F (0.5f, 0.5f, 0.5f, 1.0f); CCColor4F startColorVar = new CCColor4F(); startColorVar.R = 0.5f; startColorVar.G = 0.5f; startColorVar.B = 0.5f; startColorVar.A = 0.1f; StartColorVar = startColorVar; CCColor4F endColor = new CCColor4F(); endColor.R = 0.1f; endColor.G = 0.1f; endColor.B = 0.1f; endColor.A = 0.2f; EndColor = endColor; CCColor4F endColorVar = new CCColor4F(); endColorVar.R = 0.1f; endColorVar.G = 0.1f; endColorVar.B = 0.1f; endColorVar.A = 0.2f; EndColorVar = endColorVar; GravityMoveMode gravityMode = new GravityMoveMode(); gravityMode.Gravity = new CCPoint (0, -90); gravityMode.RadialAccel = 0; gravityMode.RadialAccelVar = 0; gravityMode.Speed = 180; gravityMode.SpeedVar = 50; GravityMode = gravityMode; BlendAdditive = false; Texture = CCParticleExample.DefaultTexture; } } // // ParticleSun // public class CCParticleSun : CCParticleSystemQuad { public CCParticleSun(CCPoint position) : this(position, 350) { } public CCParticleSun (CCPoint position, int num) : base(num) { Duration = ParticleDurationInfinity; Life = 1; LifeVar = 0.5f; Position = position; PositionVar = CCPoint.Zero; Angle = 90; AngleVar = 360; StartSize = 30.0f; StartSizeVar = 10.0f; EndSize = ParticleStartSizeEqualToEndSize; EmissionRate = TotalParticles / Life; StartColor = new CCColor4F(0.76f, 0.25f, 0.12f, 1.0f); StartColorVar = new CCColor4F(); EndColor = new CCColor4F(0.0f, 0.0f, 0.0f, 1.0f); EndColorVar = new CCColor4F(); GravityMoveMode gravityMode = new GravityMoveMode(); gravityMode.Gravity = new CCPoint(0, 0); gravityMode.RadialAccel = 0; gravityMode.RadialAccelVar = 0; gravityMode.Speed = 20; gravityMode.SpeedVar = 5; GravityMode = gravityMode; BlendAdditive = true; Texture = CCParticleExample.DefaultTexture; } } // // ParticleGalaxy // public class CCParticleGalaxy : CCParticleSystemQuad { public CCParticleGalaxy(CCPoint position) : base(200) { Duration = ParticleDurationInfinity; Life = 4; LifeVar = 1; Position = position; PositionVar = CCPoint.Zero; Angle = 90; AngleVar = 360; StartSize = 37.0f; StartSizeVar = 10.0f; EndSize = ParticleStartSizeEqualToEndSize; EmissionRate = TotalParticles / Life; StartColor = new CCColor4F(0.12f, 0.25f, 0.76f, 1.0f); StartColorVar = new CCColor4F(); EndColor = new CCColor4F(0.0f, 0.0f, 0.0f, 1.0f); EndColorVar = new CCColor4F(); GravityMoveMode gravityMode = new GravityMoveMode(); gravityMode.Gravity = new CCPoint(0, 0); gravityMode.RadialAccel = -80; gravityMode.RadialAccelVar = 0; gravityMode.Speed = 60; gravityMode.SpeedVar = 10; gravityMode.TangentialAccel = 80; gravityMode.TangentialAccelVar = 0; GravityMode = gravityMode; // additive BlendAdditive = true; Texture = CCParticleExample.DefaultTexture; } } public class CCParticleFlower : CCParticleSystemQuad { public CCParticleFlower(CCPoint position) : base(250) { Duration = ParticleDurationInfinity; Life = 4; LifeVar = 1; Position = position; PositionVar = CCPoint.Zero; Angle = 90; AngleVar = 360; StartSize = 30.0f; StartSizeVar = 10.0f; EndSize = ParticleStartSizeEqualToEndSize; EmissionRate = TotalParticles / Life; StartColor = new CCColor4F(0.5f, 0.5f, 0.5f, 1.0f); StartColorVar = new CCColor4F(0.5f, 0.5f, 0.5f, 0.5f); EndColor = new CCColor4F(0.0f, 0.0f, 0.0f, 1.0f); EndColorVar = new CCColor4F(); GravityMoveMode gravityMode = new GravityMoveMode(); gravityMode.Gravity = new CCPoint(0, 0); gravityMode.RadialAccel = -60; gravityMode.RadialAccelVar = 0; gravityMode.Speed = 80; gravityMode.SpeedVar = 10; gravityMode.TangentialAccel = 15; gravityMode.TangentialAccelVar = 0; GravityMode = gravityMode; BlendAdditive = true; Texture = CCParticleExample.DefaultTexture; } } public class CCParticleMeteor : CCParticleSystemQuad { public CCParticleMeteor(CCPoint position) : base(150) { Duration = ParticleDurationInfinity; Life = 2; LifeVar = 1; Position = position; PositionVar = CCPoint.Zero; Angle = 90; AngleVar = 360; StartSize = 60.0f; StartSizeVar = 10.0f; EndSize = ParticleStartSizeEqualToEndSize; EmissionRate = TotalParticles / Life; StartColor = new CCColor4F(0.2f, 0.4f, 0.7f, 1.0f); StartColorVar = new CCColor4F(0.0f, 0.0f, 0.2f, 0.1f); EndColor = new CCColor4F(0.0f, 0.0f, 0.0f, 1.0f); EndColorVar = new CCColor4F(); GravityMoveMode gravityMode = new GravityMoveMode(); gravityMode.Gravity = new CCPoint(-200, 200); gravityMode.RadialAccel = 0; gravityMode.RadialAccelVar = 0; gravityMode.Speed = 15; gravityMode.SpeedVar = 5; gravityMode.TangentialAccel = 0; gravityMode.TangentialAccelVar = 0; GravityMode = gravityMode; BlendAdditive = true; Texture = CCParticleExample.DefaultTexture; } } public class CCParticleSpiral : CCParticleSystemQuad { public CCParticleSpiral(CCPoint position) : base(500) { Duration = ParticleDurationInfinity; Position = position; PositionVar = CCPoint.Zero; Life = 12; LifeVar = 0; Angle = 90; AngleVar = 0; StartSize = 20.0f; StartSizeVar = 0.0f; EndSize = ParticleStartSizeEqualToEndSize; EmissionRate = TotalParticles / Life; StartColor = new CCColor4F(0.5f, 0.5f, 0.5f, 1.0f); StartColorVar = new CCColor4F(0.5f, 0.5f, 0.5f, 0.0f); EndColor = new CCColor4F(0.5f, 0.5f, 0.5f, 1.0f); EndColorVar = new CCColor4F(0.5f, 0.5f, 0.5f, 0.0f); GravityMoveMode gravityMode = new GravityMoveMode(); gravityMode.Gravity = new CCPoint(0, 0); gravityMode.RadialAccel = -380; gravityMode.RadialAccelVar = 0; gravityMode.Speed = 150; gravityMode.SpeedVar = 0; gravityMode.TangentialAccel = 45; gravityMode.TangentialAccelVar = 0; GravityMode = gravityMode; BlendAdditive = false; Texture = CCParticleExample.DefaultTexture; } } public class CCParticleExplosion : CCParticleSystemQuad { public CCParticleExplosion(CCPoint position) : base(700) { Duration = 0.1f; Life = 5.0f; LifeVar = 2; Position = new CCPoint(position); PositionVar = CCPoint.Zero; Angle = 90; AngleVar = 360; StartSize = 15.0f; StartSizeVar = 10.0f; EndSize = ParticleStartSizeEqualToEndSize; EmissionRate = TotalParticles / Duration; StartColor = new CCColor4F(0.7f, 0.1f, 0.2f, 1.0f); StartColorVar = new CCColor4F(0.5f, 0.5f, 0.5f, 0.0f); EndColor = new CCColor4F(0.5f, 0.5f, 0.5f, 0.0f); EndColorVar = new CCColor4F(0.5f, 0.5f, 0.5f, 0.0f); GravityMoveMode gravityMode = new GravityMoveMode(); gravityMode.Gravity = new CCPoint(0, 0); gravityMode.RadialAccel = 0; gravityMode.RadialAccelVar = 0; gravityMode.Speed = 70; gravityMode.SpeedVar = 40; gravityMode.TangentialAccel = 0; gravityMode.TangentialAccelVar = 0; GravityMode = gravityMode; BlendAdditive = false; Texture = CCParticleExample.DefaultTexture; } } public class CCParticleSmoke : CCParticleSystemQuad { public CCParticleSmoke(CCPoint position) : base(200) { Duration = ParticleDurationInfinity; Life = 4; LifeVar = 1; Position = position; PositionVar = new CCPoint(20, 0); Angle = 90; AngleVar = 5; StartSize = 60.0f; StartSizeVar = 10.0f; EndSize = ParticleStartSizeEqualToEndSize; EmissionRate = TotalParticles / Life; StartColor = new CCColor4F(0.8f, 0.8f, 0.8f, 1.0f); StartColorVar = new CCColor4F(0.02f, 0.02f, 0.02f, 0.0f); EndColor = new CCColor4F(0.0f, 0.0f, 0.0f, 1.0f); EndColorVar = new CCColor4F(); GravityMoveMode gravityMode = new GravityMoveMode(); gravityMode.Gravity = new CCPoint(0, 0); gravityMode.RadialAccel = 0; gravityMode.RadialAccelVar = 0; gravityMode.Speed = 25; gravityMode.SpeedVar = 10; GravityMode = gravityMode; BlendAdditive = false; Texture = CCParticleExample.DefaultTexture; } } public class CCParticleSnow : CCParticleSystemQuad { public CCParticleSnow(CCPoint position) : base(700) { Duration = ParticleDurationInfinity; Life = 45; LifeVar = 15; Position = position; PositionVar = new CCPoint(position.X, 0); Angle = -90; AngleVar = 5; StartSize = 10.0f; StartSizeVar = 5.0f; EndSize = ParticleStartSizeEqualToEndSize; EmissionRate = 10; StartColor = new CCColor4F(1.0f, 1.0f, 1.0f, 1.0f); StartColorVar = new CCColor4F(); EndColor = new CCColor4F(1.0f, 1.0f, 1.0f, 0.0f); EndColorVar = new CCColor4F(); GravityMoveMode gravityMode = new GravityMoveMode(); gravityMode.Gravity = new CCPoint(0, -1); gravityMode.RadialAccel = 0; gravityMode.RadialAccelVar = 1; gravityMode.TangentialAccel = 0; gravityMode.TangentialAccelVar = 1; gravityMode.Speed = 5; gravityMode.SpeedVar = 1; GravityMode = gravityMode; BlendAdditive = false; Texture = CCParticleExample.DefaultTexture; } } public class CCParticleRain : CCParticleSystemQuad { public CCParticleRain(CCPoint position) : base(1000) { Duration = ParticleDurationInfinity; Position = position; PositionVar = new CCPoint(position.X, 0); Life = 4.5f; LifeVar = 0; Angle = -90; AngleVar = 5; StartSize = 4.0f; StartSizeVar = 2.0f; EndSize = ParticleStartSizeEqualToEndSize; EmissionRate = 20; StartColor = new CCColor4F(0.7f, 0.8f, 1.0f, 1.0f); StartColorVar = new CCColor4F(); EndColor = new CCColor4F(0.7f, 0.8f, 1.0f, 0.5f); EndColorVar = new CCColor4F(); GravityMoveMode gravityMode = new GravityMoveMode(); gravityMode.Gravity = new CCPoint(10, -10); gravityMode.RadialAccel = 0; gravityMode.RadialAccelVar = 1; gravityMode.TangentialAccel = 0; gravityMode.TangentialAccelVar = 1; gravityMode.Speed = 130; gravityMode.SpeedVar = 30; GravityMode = gravityMode; BlendAdditive = false; Texture = CCParticleExample.DefaultTexture; } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace ApplicationGateway { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for VirtualNetworkPeeringsOperations. /// </summary> public static partial class VirtualNetworkPeeringsOperationsExtensions { /// <summary> /// Deletes the specified virtual network peering. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='virtualNetworkPeeringName'> /// The name of the virtual network peering. /// </param> public static void Delete(this IVirtualNetworkPeeringsOperations operations, string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName) { operations.DeleteAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified virtual network peering. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='virtualNetworkPeeringName'> /// The name of the virtual network peering. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IVirtualNetworkPeeringsOperations operations, string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Gets the specified virtual network peering. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='virtualNetworkPeeringName'> /// The name of the virtual network peering. /// </param> public static VirtualNetworkPeering Get(this IVirtualNetworkPeeringsOperations operations, string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName) { return operations.GetAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName).GetAwaiter().GetResult(); } /// <summary> /// Gets the specified virtual network peering. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='virtualNetworkPeeringName'> /// The name of the virtual network peering. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<VirtualNetworkPeering> GetAsync(this IVirtualNetworkPeeringsOperations operations, string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates a peering in the specified virtual network. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='virtualNetworkPeeringName'> /// The name of the peering. /// </param> /// <param name='virtualNetworkPeeringParameters'> /// Parameters supplied to the create or update virtual network peering /// operation. /// </param> public static VirtualNetworkPeering CreateOrUpdate(this IVirtualNetworkPeeringsOperations operations, string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, VirtualNetworkPeering virtualNetworkPeeringParameters) { return operations.CreateOrUpdateAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, virtualNetworkPeeringParameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a peering in the specified virtual network. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='virtualNetworkPeeringName'> /// The name of the peering. /// </param> /// <param name='virtualNetworkPeeringParameters'> /// Parameters supplied to the create or update virtual network peering /// operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<VirtualNetworkPeering> CreateOrUpdateAsync(this IVirtualNetworkPeeringsOperations operations, string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, VirtualNetworkPeering virtualNetworkPeeringParameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, virtualNetworkPeeringParameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all virtual network peerings in a virtual network. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> public static IPage<VirtualNetworkPeering> List(this IVirtualNetworkPeeringsOperations operations, string resourceGroupName, string virtualNetworkName) { return operations.ListAsync(resourceGroupName, virtualNetworkName).GetAwaiter().GetResult(); } /// <summary> /// Gets all virtual network peerings in a virtual network. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<VirtualNetworkPeering>> ListAsync(this IVirtualNetworkPeeringsOperations operations, string resourceGroupName, string virtualNetworkName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the specified virtual network peering. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='virtualNetworkPeeringName'> /// The name of the virtual network peering. /// </param> public static void BeginDelete(this IVirtualNetworkPeeringsOperations operations, string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName) { operations.BeginDeleteAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified virtual network peering. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='virtualNetworkPeeringName'> /// The name of the virtual network peering. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync(this IVirtualNetworkPeeringsOperations operations, string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Creates or updates a peering in the specified virtual network. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='virtualNetworkPeeringName'> /// The name of the peering. /// </param> /// <param name='virtualNetworkPeeringParameters'> /// Parameters supplied to the create or update virtual network peering /// operation. /// </param> public static VirtualNetworkPeering BeginCreateOrUpdate(this IVirtualNetworkPeeringsOperations operations, string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, VirtualNetworkPeering virtualNetworkPeeringParameters) { return operations.BeginCreateOrUpdateAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, virtualNetworkPeeringParameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a peering in the specified virtual network. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='virtualNetworkPeeringName'> /// The name of the peering. /// </param> /// <param name='virtualNetworkPeeringParameters'> /// Parameters supplied to the create or update virtual network peering /// operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<VirtualNetworkPeering> BeginCreateOrUpdateAsync(this IVirtualNetworkPeeringsOperations operations, string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, VirtualNetworkPeering virtualNetworkPeeringParameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, virtualNetworkPeeringParameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all virtual network peerings in a virtual network. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<VirtualNetworkPeering> ListNext(this IVirtualNetworkPeeringsOperations operations, string nextPageLink) { return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets all virtual network peerings in a virtual network. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<VirtualNetworkPeering>> ListNextAsync(this IVirtualNetworkPeeringsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using System; namespace ClosedXML.Excel { internal class XLDataValidation : IXLDataValidation { private XLDataValidation() { Ranges = new XLRanges(); Initialize(); } public XLDataValidation(IXLRange range) :this() { Ranges.Add(new XLRange(new XLRangeParameters((XLRangeAddress)range.RangeAddress, range.Worksheet.Style))); } public XLDataValidation(IXLRanges ranges) :this() { ranges.ForEach(range => { Ranges.Add(new XLRange(new XLRangeParameters((XLRangeAddress)range.RangeAddress, range.Worksheet.Style))); }); } private void Initialize() { AllowedValues = XLAllowedValues.AnyValue; IgnoreBlanks = true; ShowErrorMessage = true; ShowInputMessage = true; InCellDropdown = true; InputTitle = String.Empty; InputMessage = String.Empty; ErrorTitle = String.Empty; ErrorMessage = String.Empty; ErrorStyle = XLErrorStyle.Stop; Operator = XLOperator.Between; Value = String.Empty; MinValue = String.Empty; MaxValue = String.Empty; } public Boolean IsDirty() { return AllowedValues != XLAllowedValues.AnyValue || (ShowInputMessage && (!String.IsNullOrWhiteSpace(InputTitle) || !String.IsNullOrWhiteSpace(InputMessage))) ||(ShowErrorMessage && (!String.IsNullOrWhiteSpace(ErrorTitle) || !String.IsNullOrWhiteSpace(ErrorMessage))); } public XLDataValidation(IXLDataValidation dataValidation) { CopyFrom(dataValidation); } #region IXLDataValidation Members public IXLRanges Ranges { get; set; } public Boolean IgnoreBlanks { get; set; } public Boolean InCellDropdown { get; set; } public Boolean ShowInputMessage { get; set; } public String InputTitle { get; set; } public String InputMessage { get; set; } public Boolean ShowErrorMessage { get; set; } public String ErrorTitle { get; set; } public String ErrorMessage { get; set; } public XLErrorStyle ErrorStyle { get; set; } private XLAllowedValues _allowedValues; public XLAllowedValues AllowedValues { get { return _allowedValues; } set { _allowedValues = value; } } public XLOperator Operator { get; set; } public String Value { get { return MinValue; } set { MinValue = value; } } public String MinValue { get; set; } public String MaxValue { get; set; } public XLWholeNumberCriteria WholeNumber { get { AllowedValues = XLAllowedValues.WholeNumber; return new XLWholeNumberCriteria(this); } } public XLDecimalCriteria Decimal { get { AllowedValues = XLAllowedValues.Decimal; return new XLDecimalCriteria(this); } } public XLDateCriteria Date { get { AllowedValues = XLAllowedValues.Date; return new XLDateCriteria(this); } } public XLTimeCriteria Time { get { AllowedValues = XLAllowedValues.Time; return new XLTimeCriteria(this); } } public XLTextLengthCriteria TextLength { get { AllowedValues = XLAllowedValues.TextLength; return new XLTextLengthCriteria(this); } } public void List(String list) { List(list, true); } public void List(String list, Boolean inCellDropdown) { AllowedValues = XLAllowedValues.List; InCellDropdown = inCellDropdown; Value = list; } public void List(IXLRange range) { List(range, true); } public void List(IXLRange range, Boolean inCellDropdown) { List(range.RangeAddress.ToStringFixed(XLReferenceStyle.A1, true)); } public void Custom(String customValidation) { AllowedValues = XLAllowedValues.Custom; Value = customValidation; } #endregion public void CopyFrom(IXLDataValidation dataValidation) { if (dataValidation == this) return; if (Ranges == null && dataValidation.Ranges != null) { Ranges = new XLRanges(); dataValidation.Ranges.ForEach(r => Ranges.Add(r)); } IgnoreBlanks = dataValidation.IgnoreBlanks; InCellDropdown = dataValidation.InCellDropdown; ShowErrorMessage = dataValidation.ShowErrorMessage; ShowInputMessage = dataValidation.ShowInputMessage; InputTitle = dataValidation.InputTitle; InputMessage = dataValidation.InputMessage; ErrorTitle = dataValidation.ErrorTitle; ErrorMessage = dataValidation.ErrorMessage; ErrorStyle = dataValidation.ErrorStyle; AllowedValues = dataValidation.AllowedValues; Operator = dataValidation.Operator; MinValue = dataValidation.MinValue; MaxValue = dataValidation.MaxValue; } public void Clear() { Initialize(); } } }
using System; using System.Runtime.InteropServices; using System.Collections; namespace Provider.VistaDB { delegate bool VDBUserErrorFunc( int ulErrorCode, [MarshalAs(UnmanagedType.LPStr)]string cpErrorMsg, [MarshalAs(UnmanagedType.LPStr)]string cpExtraInfo, int ulCardinal ); /// <summary> /// Error codes /// </summary> public enum VistaDBErrorCodes { /// <summary> /// Query cannot be opened /// </summary> QueryCannotOpen = 0, /// <summary> /// Query is not open. No result set to work with /// </summary> QueryNotOpened = 1, /// <summary> /// Connection cannot be changed /// </summary> ConnectionCannotBeChanged = 2, /// <summary> /// Connection.DataSource is not set /// </summary> ConnectionDataSourceIsEmpty = 3, /// <summary> /// Connection is invalid. /// </summary> ConnectionInvalid = 4, /// <summary> /// Database could not be found /// </summary> SQLDatabaseCouldNotBeFound = 5, /// <summary> /// Table does not have a unique column /// </summary> TableDoesNotHaveUniqueColumn = 6, /// <summary> /// DatabaseName cannot be changed /// </summary> DatabaseNameCanNotBeChanged = 7, /// <summary> /// ReadOnly cannot be changed /// </summary> ReadOnlyCanNotBeChanged = 8, /// <summary> /// Exclusive cannot be changed /// </summary> ExclusiveCanNotBeChanged = 9, /// <summary> /// Parameters cannot be changed /// </summary> ParametersCanNotBeChanged = 10, /// <summary> /// Database must be closed before creating /// </summary> DatabaseMustBeClosedBeforeCreate = 11, /// <summary> /// Database cannot be changed. /// </summary> DatabaseCanNotBeChanged = 12, /// <summary> /// Table is not in Create mode /// </summary> TableNotInCreateMode = 13, /// <summary> /// Database is not assigned /// </summary> DatabaseNotAssigned = 14, /// <summary> /// Table is not opened /// </summary> TableNotOpened = 15, /// <summary> /// VistaDB object cannot be activated /// </summary> ObjectCannotBeActivated = 16, /// <summary> /// VistaDB object cannot be deactivated /// </summary> ObjectCannotBeDeactivated = 17, /// <summary> /// Table column does not exist /// </summary> ColumnNotExist = 18, /// <summary> /// Database is not opened /// </summary> DatabaseNotOpened = 19, /// <summary> /// Unusable access mode /// </summary> UnusableAccessMode = 20, /// <summary> /// Property cannot be changed while connection opened /// </summary> PropertyCannotBeChanged = 21, /// <summary> /// Connection is not opened /// </summary> ConnectionNotOpened = 22, /// <summary> /// Server error /// </summary> ServerError = 23, /// <summary> /// Database must be opened as temporary /// </summary> DatabaseMustBeTemporary = 24, /// <summary> /// Duplicate Alias name /// </summary> AliasDupe = 100, /// <summary> /// Alias name exceeds maximum length allowed /// </summary> AliasLen = 101, /// <summary> /// Invalid Name or Alias /// </summary> InvalidAlias = 102, /// <summary> /// Database creation error /// </summary> CreateDatabase = 103, /// <summary> /// Database connection error /// </summary> OpenDatabase = 104, /// <summary> /// Table creation error /// </summary> CreateTable = 105, /// <summary> /// Table opening error /// </summary> OpenTable = 106, /// <summary> /// Database format error. Does not appear to be a valid .VDB database. /// </summary> NotADatabase = 107, /// <summary> /// Database must be opened in Exclusive mode /// </summary> MustExclusive = 108, /// <summary> /// Index file format error /// </summary> NotIndex = 109, /// <summary> /// Invalid database engine property /// </summary> InvalidSysProp = 110, /// <summary> /// Invalid characters in Column name /// </summary> InvalidColumnName = 112, /// <summary> /// Duplicate Column name /// </summary> DupeColumn = 113, /// <summary> /// Column not found /// </summary> ColumnNotFound = 114, /// <summary> /// File creation error /// </summary> FileCreate = 115, /// <summary> /// File locking error /// </summary> FileLock = 116, /// <summary> /// File opening error /// </summary> FileOpen = 117, /// <summary> /// File opening mode error /// </summary> FileOpenMode = 118, /// <summary> /// File read error /// </summary> FileRead = 119, /// <summary> /// Index opening error /// </summary> FileOpenIndex = 120, /// <summary> /// File write error /// </summary> FileWrite = 121, /// <summary> /// Invalid child Relationships /// </summary> InvalidChild = 123, /// <summary> /// Unsupported data type /// </summary> InvalidType = 124, /// <summary> /// Invalid Memo block size /// </summary> InvalidString = 129, /// <summary> /// Invalid Record /// </summary> InvalidRecord = 130, /// <summary> /// Invalid database structure /// </summary> InvalidStruc = 131, /// <summary> /// Invalid connection to database /// </summary> NoDatabase = 132, /// <summary> /// Not enough disk space to sort keys /// </summary> DiskSpace = 137, /// <summary> /// Unsuitable Table driver specified /// </summary> FileVDBType = 140, /// <summary> /// Expression length exceeds maximum allowed /// </summary> ExprLen = 142, /// <summary> /// Expression error: Invalid number of parameters /// </summary> InvalidParams = 143, /// <summary> /// Expression error: Invalid type /// </summary> ExprTypChk = 144, /// <summary> /// Expression evaluation error /// </summary> BadExpr = 145, /// <summary> /// Expression is incomplete /// </summary> IncompExpr = 146, /// <summary> /// Expression error: Number of delimiters is invalid /// </summary> InvalidDelim = 147, /// <summary> /// Expression error: Operator is invalid /// </summary> InvalidOp = 148, /// <summary> /// Expression error: Parentheses are mismatched /// </summary> ParenMismatch = 149, /// <summary> /// Expression error: String delimiter is missing /// </summary> MissinDelim = 150, /// <summary> /// Expression error: Type mismatch within function or operator parameters /// </summary> XType = 151, /// <summary> /// System Error /// </summary> SystemError = 152, /// <summary> /// Index name is required /// </summary> IndexRequired = 153, /// <summary> /// Duplicate Index name /// </summary> IndexDuplicate = 154, /// <summary> /// Memory allocation system error /// </summary> OutOfMemory = 156, /// <summary> /// Disk space allocation error /// </summary> FileSpaceAlloc = 157, /// <summary> /// Incompatible user mode /// </summary> IncompatibleMode = 158, /// <summary> /// Internal error /// </summary> InternalError = 159, /// <summary> /// Unable to initialize engine /// </summary> CannotInitLib = 160, /// <summary> /// Unable to initialize thread apartment /// </summary> CannotInitParent = 161, /// <summary> /// Unable to create record /// </summary> CreateRec = 162, /// <summary> /// Unable to update record /// </summary> UpdateRec = 163, /// <summary> /// Unable to delete record /// </summary> DeleteRec = 164, /// <summary> /// Column contains Null value /// </summary> ErrorNull = 165, /// <summary> /// Old VistaDB database format. Pack the database to update. /// </summary> IncompVersion = 166, /// <summary> /// Unable to start transaction /// </summary> TPFaultToStart = 167, /// <summary> /// Transaction fault /// </summary> TPFaultCommit = 168, /// <summary> /// SureCommit forced /// </summary> TPSureCommit = 169, /// <summary> /// Record is out of date /// </summary> RecordVersion = 170, /// <summary> /// Transaction rolled back /// </summary> TPRollback = 171, /// <summary> /// Windows Locale that is not currently installed is being used for index collation /// </summary> NonInstLocale = 172, /// <summary> /// Unsupported Windows Locale used for index collation /// </summary> NonSuppLocale = 173, /// <summary> /// Incorrect Trigger type /// </summary> BadTriggerType = 174, /// <summary> /// Invalid Index order for table /// </summary> InvalidOrder = 175, /// <summary> /// Incorrect decryption key entered /// </summary> WrongPassword = 176, /// <summary> /// Incorrect symbol /// </summary> WrongSymbol = 177, /// <summary> /// Incorrect data length in Varchar Column /// </summary> WrongVarcharLength = 178, /// <summary> /// Incorrect property for Column /// </summary> WrongColumnProperty = 179, /// <summary> /// Primary Key index cannot contain Null values. Check Column definition. /// </summary> PrimaryContainsNull = 180, /// <summary> /// Duplicate key in index /// </summary> DupKey = 181, /// <summary> /// Trigger fault /// </summary> TriggerFault = 182, /// <summary> /// Constraint fault /// </summary> ConstraintFault = 183, /// <summary> /// Unable to update. Column is Readonly /// </summary> ReadOnlyFault = 184, /// <summary> /// Unable to assign default value /// </summary> DefaultValueFault = 185, /// <summary> /// Incorrect syntax. Use\n 'Column1: Column1Value; Column2: Column2Value; ... ' /// </summary> WrongKeySyntax = 186, /// <summary> /// Then() operator expected /// </summary> WrongIfElse = 187, /// <summary> /// Unexpected Then() operator /// </summary> NonExpectedThen = 188, /// <summary> /// Unexpected Else() operator /// </summary> NonExpectedElse = 189, /// <summary> /// Unable to set Trigger /// </summary> CannotSetTrigger = 190, /// <summary> /// Unable to set Constraint /// </summary> CannotSetConstraint = 191, /// <summary> /// Unable to set Foreign Key Constraint /// </summary> CannotSetFKConstraint = 192, /// <summary> /// Unable to set Identity /// </summary> CannotSetIdentity = 193, /// <summary> /// Unable to set read-only property /// </summary> CannotSetReadOnly = 194, /// <summary> /// Unable to set default value for column /// </summary> CannotSetFDefaultValue = 195, /// <summary> /// Incorrect reference to Primary Key /// </summary> WrongPKReference = 196, /// <summary> /// Unable to set Column property /// </summary> BadColumnProp = 197, /// <summary> /// Column has an Identity /// </summary> IdentitySet = 198, /// <summary> /// Broken relationships. Unable to alter/drop table or primary index /// </summary> CannotAlterRelation = 199, /// <summary> /// Invalid Column name characters. Using a reserved word. /// </summary> InvalidColumnNameRes = 200, /// <summary> /// Key length exceeds maximum allowed value /// </summary> MaxKeyLen = 201, /// <summary> /// Key expression contains wrong column /// </summary> IndexKeyColumn = 202, /// <summary> /// Unable to re-assign default value for column /// </summary> DefaultValueAssigned = 203, /// <summary> /// Newer VistaDB database format detected. Update the VistaDB engine before proceeding. /// </summary> OutdatedEngine = 204, //SQL /// <summary> /// Initial SQL Error. Details to follow. /// </summary> SQLFirstError = 500, /// <summary> /// SQL Parser syntax error /// </summary> SQLExprParserError = 501, /// <summary> /// INSERT Column does not exist in the table /// </summary> SQLInsertWrongFieldName = 502, /// <summary> /// Columns in GROUP BY must by specified by SELECT columns /// </summary> SQLGroupByInCongruent = 503, /// <summary> /// Use SELECT only with ExecuteQuery method /// </summary> SQLIsNotValidInExecSQL = 504, /// <summary> /// Use UPDATE, DELETE, INSERT or CREATE TABLE with ExecuteNonQuery method /// </summary> SQLIsNotValidInSelect = 505, /// <summary> /// GetRecord Invalid record /// </summary> SQLGetRecordInvalid = 506, /// <summary> /// Parameter types for Extract must be of Float or Integer /// </summary> SQLWrongParamsInExtract = 507, /// <summary> /// Parameter types for date/time function must be of Float or Integer /// </summary> SQLWrongParamsInDateTime = 508, /// <summary> /// SQL statement may not be empty /// </summary> SQLIsEmpty = 509, /// <summary> /// Length of trimmed character returned by TRIM() must be at least 1 /// </summary> SQLWrongLengthInTrim = 510, /// <summary> /// Incorrect expression in HAVING clause /// </summary> SQLHavingExprWrong = 511, /// <summary> /// Aggregate function not found in SELECT /// </summary> SQLHavingWrong = 512, /// <summary> /// Circular reference not allowed /// </summary> SQLCircularReference = 513, /// <summary> /// Number of tables in JOIN clause must match the number of tables in the FROM clause /// </summary> SQLJoinPredicateWrong = 514, /// <summary> /// Table is not opened /// </summary> SQLDataSetNotOpened = 515, /// <summary> /// Invalid Table name in expression /// </summary> SQLWrongDataSetNameInExpr = 516, /// <summary> /// Invalid Column name in expression /// </summary> SQLWrongResultSetFieldName = 517, /// <summary> /// JOIN clause is incorrectly defined /// </summary> SQLJoinExpectedDataSet = 518, /// <summary> /// Parameter(s) invalid for function /// </summary> SQLWrongParameters = 519, /// <summary> /// Argument must be alphanumeric /// </summary> SQLWrongFirstArg = 520, /// <summary> /// Duplicate Table name exists in the table list /// </summary> SQLDuplicatedDataSet = 521, /// <summary> /// Duplicate Column name exists /// </summary> SQLColumnRepeated = 522, /// <summary> /// Record number out of range /// </summary> SQLRecNoInvalid = 523, /// <summary> /// Each Column listed in GROUP BY must exist in the SELECT clause /// </summary> SQLGroupBySelectWrong = 524, /// <summary> /// Number of Columns in GROUP differs from Columns listed in SELECT /// </summary> SQLGroupByWrongNum = 525, /// <summary> /// Incorrect table name in format /// </summary> SQLWrongTableName = 526, /// <summary> /// Incorrect Column index /// </summary> SQLWrongIndexField = 527, /// <summary> /// Column was not found /// </summary> SQLFieldNotFound = 528, /// <summary> /// Left and right tables in JOIN must be different /// </summary> SQLJoinOnMustHaveDiffTables = 529, /// <summary> /// Right table in JOIN must match second table in FROM /// </summary> SQLJoinOnWrongRightTable = 530, /// <summary> /// Left table in JOIN must match first table in FROM /// </summary> SQLJoinOnWrongLeftTable = 531, /// <summary> /// Number of tables in FROM clause differs from the JOIN ON clause /// </summary> SQLJoinOnWrongTableNum = 532, /// <summary> /// Subquery with more than one Column is not allowed /// </summary> SQLSubQueryWrongCols = 533, /// <summary> /// More than one table in FROM clause found in subquery /// </summary> SQLSubQueryWrongTables = 534, /// <summary> /// No Tables defined in FROM clause /// </summary> SQLWrongTableNumber = 535, /// <summary> /// Column name not found /// </summary> SQLWrongFieldName = 536, /// <summary> /// Table does not exist /// </summary> SQLWrongDataSetName = 537, /// <summary> /// Error specifying a table Column /// </summary> SQLErrorInDBField = 538, /// <summary> /// Column may not have parameters /// </summary> SQLCannotContainParams = 539, /// <summary> /// Expression is empty /// </summary> SQLExpressionNull = 540, /// <summary> /// Expression must be Boolean type /// </summary> SQLExprNotBoolean = 541, /// <summary> /// Unable to find a record that corresponds to the expression /// </summary> SQLRecordNotFound = 542, /// <summary> /// Bookmark not found /// </summary> SQLBookMarkNotFound = 543, /// <summary> /// Index is out of range /// </summary> SQLIndexOutOfRange = 544, /// <summary> /// Error in WHERE clause /// </summary> SQLErrorInWhere = 545, /// <summary> /// Parameter not found in the list of params /// </summary> SQLParameterNotFound = 546, /// <summary> /// (LoadFromBinaryFile) File does not exist /// </summary> SQLFileNotExist = 547, /// <summary> /// Duplicate Column name /// </summary> SQLDuplicateFieldName = 548, /// <summary> /// Column name not found /// </summary> SQLFieldNameNotFound = 549, /// <summary> /// Incorrect BLOB type /// </summary> SQLBLOBFieldWrongType = 550, /// <summary> /// Unable to read field as Boolean /// </summary> SQLReadBooleanField = 551, /// <summary> /// Unable to read field as Float /// </summary> SQLReadFloatField = 552, /// <summary> /// Unable to read field as Integer /// </summary> SQLReadIntegerField = 553, /// <summary> /// Unable to read field as String /// </summary> SQLReadStringField = 554, /// <summary> /// Unable to assign field as Boolean /// </summary> SQLWriteBooleanField = 555, /// <summary> /// Unable to assign field as Float /// </summary> SQLWriteFloatField = 556, /// <summary> /// Unable to assign field as Integer /// </summary> SQLWriteIntegerField = 557, /// <summary> /// Unable to assign field as String /// </summary> SQLWriteStringField = 558, /// <summary> /// Invalid Float value /// </summary> SQLIsInvalidFloatValue = 559, /// <summary> /// Invalid Integer value /// </summary> SQLIsInvalidIntegerValue = 560, /// <summary> /// Invalid Boolean value /// </summary> SQLIsInvalidBoolValue = 561, /// <summary> /// Column is not an aggregate type /// </summary> SQLNotAnAggregate = 562, /// <summary> /// Invalid Column number /// </summary> SQLInvalidFieldNo = 563, /// <summary> /// Number of columns in SELECT mismatch in GROUP BY /// </summary> SQLTransfColumnMismatch = 564, /// <summary> /// Number of columns in SELECT mismatch in ORDER BY /// </summary> SQLTransfOrderByMismatch = 565, /// <summary> /// Column order in GROUP BY must match in SELECT /// </summary> SQLTransWrongColumnGroup = 566, /// <summary> /// Column order in order BY must match in SELECT /// </summary> SQLTransfWrongColumnOrder = 567, /// <summary> /// Failed to open or create file /// </summary> SQLFailOpenFile = 568, /// <summary> /// Failed to create file mapping /// </summary> SQLFailCreateMapping = 569, /// <summary> /// Failed to map view of file /// </summary> SQLFailMapView = 570, /// <summary> /// Position beyond end of file (EOF) /// </summary> SQLBeyondEof = 571, /// <summary> /// List index error /// </summary> SQLListError = 572, /// <summary> /// Syntax Error /// </summary> SQLSyntaxErrorMsg = 573, /// <summary> /// Params were not updated /// </summary> SQLParamsError = 574, /// <summary> /// Alias already exists /// </summary> SQLDuplicateAlias = 575, /// <summary> /// Nested subqueries are not allowed in SELECT subquery /// </summary> SQLSubQueryInSelectsError = 576, /// <summary> /// Simultaneous use of both quote and double quote is not supported /// </summary> SQLWrongParameterQuotes = 577, /// <summary> /// More than one table being accessed. JOIN is required. /// </summary> SQLWrongJoin = 578, /// <summary> /// Use ANY or ALL in subquery, but not both /// </summary> SQLSubQueryKindWrong = 579, /// <summary> /// Table listed in the INTO clause does not exist /// </summary> SQLWrongToTable = 580, /// <summary> /// Column not found /// </summary> SQLXQFieldNotFound = 581, /// <summary> /// CASE statement requires an alias /// </summary> SQLCaseListMissingAlias = 582, /// <summary> /// Expression is not of Boolean type in CASE clause /// </summary> SQLCaseExprNotBoolean = 583, /// <summary> /// Tables referenced in JOIN do not correspond /// </summary> SQLJoinNotMismatch = 584, /// <summary> /// (ParamsAsFields) duplicate name /// </summary> SQLDupParamsAsFields = 585, /// <summary> /// Internal JOIN optimization error /// </summary> SQLJoinOptimization = 586, /// <summary> /// Currency conversion error /// </summary> SQLCurrencyConv = 587, /// <summary> /// In64 conversion error /// </summary> SQLInt64Conv = 588, /// <summary> /// Statement did not return a ResultSet /// </summary> SQLDidNotReturnAres = 589, /// <summary> /// Unable to open table /// </summary> SQLCouldNotOpenTab = 590, /// <summary> /// Unknown identifier /// </summary> SQLUnknownIdentifier = 591, /// <summary> /// Error setting filter for WHERE clause /// </summary> SQLWhereFilter = 592, /// <summary> /// Unable to create database /// </summary> SQLCouldNotCreateDB = 593, /// <summary> /// Unable to create table /// </summary> SQLCouldNotCreateTab = 594, /// <summary> /// Invalid Column type /// </summary> SQLInvalidFieldType = 595, /// <summary> /// Unable to create primary key /// </summary> SQLCouldNotCreatePK = 596, /// <summary> /// Unable to create constraint /// </summary> SQLCreateConstraint = 597, /// <summary> /// Unable to open table in exclusive mode /// </summary> SQLOpenTableExclusive = 598, /// <summary> /// Unable to create index /// </summary> SQLCreateIndex = 599, /// <summary> /// Unable to drop index /// </summary> SQLDropIndex = 600, /// <summary> /// Database does not exist /// </summary> SQLDatabaseFileName = 601, /// <summary> /// Unable to alter table /// </summary> SQLAlterTable = 602, /// <summary> /// Unable to reindex table /// </summary> SQLReindexTable = 603, /// <summary> /// Unable to drop table /// </summary> SQLDropTable = 604, /// <summary> /// Unable to delete all rows of table /// </summary> SQLZapTable = 605, /// <summary> /// Unable to create trigger /// </summary> SQLCreateTrigger = 606, /// <summary> /// Unable to alter trigger /// </summary> SQLAlterTrigger = 607, /// <summary> /// Unable to drop trigger /// </summary> SQLDropTrigger = 608, /// <summary> /// Invalid internal database connection /// </summary> SQLInvalidInternalDB = 609, /// <summary> /// OpenSQL error /// </summary> SQLOpen = 610, /// <summary> /// ExecSQL error /// </summary> SQLExec = 611, /// <summary> /// Internal SQL error /// </summary> SQLInternalError = 612, /// <summary> /// Last SQL error to report. /// </summary> SQLLastError = 613 } /// <summary> /// VistaDB error structure /// </summary> public class VistaDBErrorStruct { /// <summary> /// Error code /// </summary> public VistaDBErrorCodes errorCode; /// <summary> /// Error message /// </summary> public string errorMsg; /// <summary> /// Error extra info /// </summary> public string extraInfo; } internal class VistaDBErrorMsgs { public static bool errorTrapped = false; public static Queue queue = new Queue(); private static VDBUserErrorFunc errorFunc; public static string[] Errors = { "Query cannot be opened", "Query not opened", "Cannot change connection string while the connection is open", "Must specify a DataSource prior to Open", "Connection must be valid and open", "Database could not be found", "Table doesn't have unique column", "Property DatabaseName cannot be changed while database is opened", "Property ReadOnly cannot be changed while database id opened", "Property Exclusive cannot be changed while database id opened", "Property Parameters cannot be changed while database id opened", "Database must be closed before create", "Property Database cannot be changed while table is opened", "Table is not in create mode", "Database not assigned", "Table is not opened", "Object cannot be activated", "Object cannot be deactivated", "Column doesn't exist", "Database is not opened", "Unusable access mode", "Property cannot be changed while connection opened", "Connection is not opened", "Server error", "Database must be opened as temporary" }; public static bool UserErrorFunc( int ulErrorCode, string cpErrorMsg, string cpExtraInfo, int ulCardinal ) { VistaDBErrorStruct error = new VistaDBErrorStruct(); error.errorCode = (VistaDBErrorCodes)ulErrorCode; error.errorMsg = cpErrorMsg; error.extraInfo = cpExtraInfo; lock(queue.SyncRoot) { queue.Enqueue(error); } return true; } public static void ShowErrors(bool ShowError, object result) { string msg = ""; int count = 0; VistaDBErrorStruct error; ArrayList list = new ArrayList(); lock(queue.SyncRoot) { while(queue.Count > 0) { error = (VistaDBErrorStruct)queue.Dequeue(); msg += "\r\nError code: " + ((int)error.errorCode).ToString() + " " + error.errorMsg + " " + error.extraInfo; list.Add(error); count++; } } if( count > 0 ) { throw new VistaDBException(msg, list, ShowError, result); } } public static void SetErrorFunc() { if( errorTrapped ) return; queue = new Queue(10); VistaDBAPI.ivdb_ErrorLevel(2); errorFunc = new VDBUserErrorFunc(UserErrorFunc); VistaDBAPI.ivdb_SetErrorFunc(errorFunc, 0); errorTrapped = true; } } /// <summary> /// VistaDB exception class /// </summary> public class VistaDBException: InvalidOperationException { private ArrayList arrayList; private bool critical; private object result; internal VistaDBException(string message, ArrayList list, bool _critical, object _result): base(message) { this.arrayList = list; this.critical = _critical; this.result = _result; } internal VistaDBException(VistaDBErrorCodes error): base(VistaDBErrorMsgs.Errors[(int)error]) { this.arrayList = null; this.critical = true; this.result = null; } internal VistaDBException(string message, VistaDBErrorCodes error): base(message) { this.arrayList = new ArrayList(); this.arrayList.Add(error); this.critical = true; this.result = null; } /// <summary> /// Return True is pointed error code present /// </summary> /// <param name="errorCode">Error code</param> /// <returns>True is pointed error code present</returns> public bool IsErrorCodePresent(VistaDBErrorCodes errorCode) { bool res = false; if(arrayList != null) { for(int i = 0; i < arrayList.Count; i++) { if( ((VistaDBErrorStruct)arrayList[i]).errorCode == errorCode ) { res = true; break; } } } return res; } /// <summary> /// Errors count /// </summary> /// <returns>Errors count</returns> public int ErrorCount() { if(arrayList != null) return arrayList.Count; else return 0; } /// <summary> /// Return error code by zero-based index /// </summary> /// <param name="index">Zero-based index</param> /// <returns>Error code by zero-based index</returns> public VistaDBErrorStruct ErrorCode(int index) { if(arrayList != null) return (VistaDBErrorStruct)(arrayList[index]); else return null; } /// <summary> /// True is error is critical /// </summary> public bool Critical { get { return critical; } } /// <summary> /// Result value of function, which raised error /// </summary> public object Result { get { return result; } } } }
using System.Collections.Generic; using System.Linq; using NExpect.Implementations; using NExpect.Interfaces; using NExpect.MatcherLogic; // ReSharper disable MemberCanBePrivate.Global // ReSharper disable PossibleMultipleEnumeration namespace NExpect { /// <summary> /// Provides matchers for dictionaries /// </summary> public static class DictionaryExtensions { /// <summary> /// Tests if the provided collection contains the required key. /// </summary> /// <param name="continuation">Continuation to operate on</param> /// <param name="key">Key to look for</param> /// <typeparam name="TKey">Type of the dictionary keys</typeparam> /// <typeparam name="TValue">Type of the dictionary values</typeparam> public static IDictionaryValueContinuation<TValue> Key<TKey, TValue>( this IContain<IEnumerable<KeyValuePair<TKey, TValue>>> continuation, TKey key ) { return continuation.Key(key, null); } /// <summary> /// Tests if the provided collection contains the required key. /// </summary> /// <param name="continuation">Continuation to operate on</param> /// <param name="key">Key to look for</param> /// <param name="customMessage">Custom message to add to failure messages</param> /// <typeparam name="TKey">Type of the dictionary keys</typeparam> /// <typeparam name="TValue">Type of the dictionary values</typeparam> public static IDictionaryValueContinuation<TValue> Key<TKey, TValue>( this IContain<IEnumerable<KeyValuePair<TKey, TValue>>> continuation, TKey key, string customMessage ) { AddKeyMatcher(continuation, key, customMessage); return CreateValueContinuation(continuation, key); } /// <summary> /// Tests if the provided collection contains the required key. /// Upcast from sbyte to long for convenience /// </summary> /// <param name="continuation">Continuation to operate on</param> /// <param name="key">Key to look for</param> /// <typeparam name="TKey">Type of the dictionary keys</typeparam> public static IDictionaryValueContinuation<long> Key<TKey>( this IContain<IEnumerable<KeyValuePair<TKey, sbyte>>> continuation, TKey key ) { return continuation.Key(key, null); } /// <summary> /// Tests if the provided collection contains the required key. /// Upcast from sbyte to long for convenience /// </summary> /// <param name="continuation">Continuation to operate on</param> /// <param name="key">Key to look for</param> /// <param name="customMessage">Custom message to add to failure messages</param> /// <typeparam name="TKey">Type of the dictionary keys</typeparam> public static IDictionaryValueContinuation<long> Key<TKey>( this IContain<IEnumerable<KeyValuePair<TKey, sbyte>>> continuation, TKey key, string customMessage ) { AddKeyMatcher(continuation, key, customMessage); return CreateValueContinuation(continuation, key); } /// <summary> /// Tests if the provided collection contains the required key. /// Upcast from short to long for convenience /// </summary> /// <param name="continuation">Continuation to operate on</param> /// <param name="key">Key to look for</param> /// <typeparam name="TKey">Type of the dictionary keys</typeparam> public static IDictionaryValueContinuation<long> Key<TKey>( this IContain<IEnumerable<KeyValuePair<TKey, short>>> continuation, TKey key ) { return continuation.Key(key, null); } /// <summary> /// Tests if the provided collection contains the required key. /// Upcast from short to long for convenience /// </summary> /// <param name="continuation">Continuation to operate on</param> /// <param name="key">Key to look for</param> /// <param name="customMessage">Custom message to add to failure messages</param> /// <typeparam name="TKey">Type of the dictionary keys</typeparam> public static IDictionaryValueContinuation<long> Key<TKey>( this IContain<IEnumerable<KeyValuePair<TKey, short>>> continuation, TKey key, string customMessage ) { AddKeyMatcher(continuation, key, customMessage); return CreateValueContinuation(continuation, key); } /// <summary> /// Tests if the provided collection contains the required key. /// Upcast from int to long for convenience /// </summary> /// <param name="continuation">Continuation to operate on</param> /// <param name="key">Key to look for</param> /// <typeparam name="TKey">Type of the dictionary keys</typeparam> public static IDictionaryValueContinuation<long> Key<TKey>( this IContain<IEnumerable<KeyValuePair<TKey, int>>> continuation, TKey key ) { return continuation.Key(key, null); } /// <summary> /// Tests if the provided collection contains the required key. /// Upcast from int to long for convenience /// </summary> /// <param name="continuation">Continuation to operate on</param> /// <param name="key">Key to look for</param> /// <param name="customMessage">Custom message to add to failure messages</param> /// <typeparam name="TKey">Type of the dictionary keys</typeparam> public static IDictionaryValueContinuation<long> Key<TKey>( this IContain<IEnumerable<KeyValuePair<TKey, int>>> continuation, TKey key, string customMessage ) { AddKeyMatcher(continuation, key, customMessage); return CreateValueContinuation(continuation, key); } /// <summary> /// Tests if the provided collection contains the required key. /// Upcast from byte to long for convenience /// </summary> /// <param name="continuation">Continuation to operate on</param> /// <param name="key">Key to look for</param> /// <typeparam name="TKey">Type of the dictionary keys</typeparam> public static IDictionaryValueContinuation<long> Key<TKey>( this IContain<IEnumerable<KeyValuePair<TKey, byte>>> continuation, TKey key ) { return continuation.Key(key, null); } /// <summary> /// Tests if the provided collection contains the required key. /// Upcast from byte to long for convenience /// </summary> /// <param name="continuation">Continuation to operate on</param> /// <param name="key">Key to look for</param> /// <param name="customMessage">Custom message to add to failure messages</param> /// <typeparam name="TKey">Type of the dictionary keys</typeparam> public static IDictionaryValueContinuation<long> Key<TKey>( this IContain<IEnumerable<KeyValuePair<TKey, byte>>> continuation, TKey key, string customMessage ) { AddKeyMatcher(continuation, key, customMessage); return CreateValueContinuation(continuation, key); } /// <summary> /// Tests if the provided collection contains the required key. /// Upcast from ushort to long for convenience /// </summary> /// <param name="continuation">Continuation to operate on</param> /// <param name="key">Key to look for</param> /// <typeparam name="TKey">Type of the dictionary keys</typeparam> public static IDictionaryValueContinuation<long> Key<TKey>( this IContain<IEnumerable<KeyValuePair<TKey, ushort>>> continuation, TKey key ) { return continuation.Key(key, null); } /// <summary> /// Tests if the provided collection contains the required key. /// Upcast from ushort to long for convenience /// </summary> /// <param name="continuation">Continuation to operate on</param> /// <param name="key">Key to look for</param> /// <param name="customMessage">Custom message to add to failure messages</param> /// <typeparam name="TKey">Type of the dictionary keys</typeparam> public static IDictionaryValueContinuation<long> Key<TKey>( this IContain<IEnumerable<KeyValuePair<TKey, ushort>>> continuation, TKey key, string customMessage ) { AddKeyMatcher(continuation, key, customMessage); return CreateValueContinuation(continuation, key); } /// <summary> /// Tests if the provided collection contains the required key. /// Upcast from uint to long for convenience /// </summary> /// <param name="continuation">Continuation to operate on</param> /// <param name="key">Key to look for</param> /// <typeparam name="TKey">Type of the dictionary keys</typeparam> public static IDictionaryValueContinuation<long> Key<TKey>( this IContain<IEnumerable<KeyValuePair<TKey, uint>>> continuation, TKey key ) { return continuation.Key(key, null); } /// <summary> /// Tests if the provided collection contains the required key. /// Upcast from uint to long for convenience /// </summary> /// <param name="continuation">Continuation to operate on</param> /// <param name="key">Key to look for</param> /// <param name="customMessage">Custom message to add to failure messages</param> /// <typeparam name="TKey">Type of the dictionary keys</typeparam> public static IDictionaryValueContinuation<long> Key<TKey>( this IContain<IEnumerable<KeyValuePair<TKey, uint>>> continuation, TKey key, string customMessage ) { AddKeyMatcher(continuation, key, customMessage); return CreateValueContinuation(continuation, key); } /// <summary> /// Tests if the provided collection contains the required key. /// Upcast from float to double for convenience /// </summary> /// <param name="continuation">Continuation to operate on</param> /// <param name="key">Key to look for</param> /// <typeparam name="TKey">Type of the dictionary keys</typeparam> public static IDictionaryValueContinuation<double> Key<TKey>( this IContain<IEnumerable<KeyValuePair<TKey, float>>> continuation, TKey key ) { return continuation.Key(key, null); } /// <summary> /// Tests if the provided collection contains the required key. /// Upcast from float to double for convenience /// </summary> /// <param name="continuation">Continuation to operate on</param> /// <param name="key">Key to look for</param> /// <param name="customMessage">Custom message to add to failure messages</param> /// <typeparam name="TKey">Type of the dictionary keys</typeparam> public static IDictionaryValueContinuation<double> Key<TKey>( this IContain<IEnumerable<KeyValuePair<TKey, float>>> continuation, TKey key, string customMessage ) { AddKeyMatcher(continuation, key, customMessage); return CreateValueContinuation(continuation, key); } /// <summary> /// Tests if the provided key value matches the expected value /// </summary> /// <param name="continuation">Continuation to operate on</param> /// <param name="expected">Value to match on</param> /// <typeparam name="T">Type of the values</typeparam> public static void Value<T>( this IDictionaryValueWith<T> continuation, T expected ) { continuation.Value(expected, null); } /// <summary> /// Tests if the provided key value matches the expected value /// </summary> /// <param name="continuation">Continuation to operate on</param> /// <param name="expected">Value to match on</param> /// <param name="customMessage">Custom message to add to failure messages</param> /// <typeparam name="T">Type of the values</typeparam> public static void Value<T>( this IDictionaryValueWith<T> continuation, T expected, string customMessage ) { continuation.AddMatcher( EqualityProviderExtensions.GenerateEqualityMatcherFor(expected, customMessage) ); } private static void AddKeyMatcher<TKey, TValue>(IContain<IEnumerable<KeyValuePair<TKey, TValue>>> continuation, TKey key, string customMessage) { continuation.AddMatcher(collection => { var passed = collection?.Any(kvp => kvp.Key.Equals(key)) ?? false; return new MatcherResult( passed, MessageHelpers.FinalMessageFor( $"Expected {collection.PrettyPrint()} {passed.AsNot()}to contain key {key?.Stringify()}", customMessage ) ); }); } private static IDictionaryValueContinuation<TValue> CreateValueContinuation<TKey, TValue>( IContain<IEnumerable<KeyValuePair<TKey, TValue>>> continuation, TKey key) { var continuationValue = GetValueForKey(continuation, key); return Factory.Create<TValue, DictionaryValueContinuation<TValue>>( continuationValue, new WrappingContinuation<IEnumerable<KeyValuePair<TKey, TValue>>, TValue>( continuation as IHasActual<IEnumerable<KeyValuePair<TKey, TValue>>>, c => continuationValue ) ); } private static IDictionaryValueContinuation<long> CreateValueContinuation<TKey>( IContain<IEnumerable<KeyValuePair<TKey, sbyte>>> continuation, TKey key) { var continuationValue = GetValueForKey(continuation, key); return Factory.Create<long, DictionaryValueContinuation<long>>( continuationValue, new WrappingContinuation<IEnumerable<KeyValuePair<TKey, sbyte>>, long>( continuation as IHasActual<IEnumerable<KeyValuePair<TKey, sbyte>>>, c => continuationValue ) ); } private static IDictionaryValueContinuation<long> CreateValueContinuation<TKey>( IContain<IEnumerable<KeyValuePair<TKey, short>>> continuation, TKey key) { var continuationValue = GetValueForKey(continuation, key); return Factory.Create<long, DictionaryValueContinuation<long>>( continuationValue, new WrappingContinuation<IEnumerable<KeyValuePair<TKey, short>>, long>( continuation as IHasActual<IEnumerable<KeyValuePair<TKey, short>>>, c => continuationValue ) ); } private static IDictionaryValueContinuation<long> CreateValueContinuation<TKey>( IContain<IEnumerable<KeyValuePair<TKey, int>>> continuation, TKey key) { var continuationValue = GetValueForKey(continuation, key); return Factory.Create<long, DictionaryValueContinuation<long>>( continuationValue, new WrappingContinuation<IEnumerable<KeyValuePair<TKey, int>>, long>( continuation as IHasActual<IEnumerable<KeyValuePair<TKey, int>>>, c => continuationValue ) ); } private static IDictionaryValueContinuation<long> CreateValueContinuation<TKey>( IContain<IEnumerable<KeyValuePair<TKey, byte>>> continuation, TKey key) { var continuationValue = GetValueForKey(continuation, key); return Factory.Create<long, DictionaryValueContinuation<long>>( continuationValue, new WrappingContinuation<IEnumerable<KeyValuePair<TKey, byte>>, long>( continuation as IHasActual<IEnumerable<KeyValuePair<TKey, byte>>>, c => continuationValue ) ); } private static IDictionaryValueContinuation<long> CreateValueContinuation<TKey>( IContain<IEnumerable<KeyValuePair<TKey, ushort>>> continuation, TKey key) { var continuationValue = GetValueForKey(continuation, key); return Factory.Create<long, DictionaryValueContinuation<long>>( continuationValue, new WrappingContinuation<IEnumerable<KeyValuePair<TKey, ushort>>, long>( continuation as IHasActual<IEnumerable<KeyValuePair<TKey, ushort>>>, c => continuationValue ) ); } private static IDictionaryValueContinuation<long> CreateValueContinuation<TKey>( IContain<IEnumerable<KeyValuePair<TKey, uint>>> continuation, TKey key) { var continuationValue = GetValueForKey(continuation, key); return Factory.Create<long, DictionaryValueContinuation<long>>( continuationValue, new WrappingContinuation<IEnumerable<KeyValuePair<TKey, uint>>, long>( continuation as IHasActual<IEnumerable<KeyValuePair<TKey, uint>>>, c => continuationValue ) ); } private static IDictionaryValueContinuation<double> CreateValueContinuation<TKey>( IContain<IEnumerable<KeyValuePair<TKey, float>>> continuation, TKey key) { var continuationValue = GetValueForKey(continuation, key); return Factory.Create<double, DictionaryValueContinuation<double>>( continuationValue, new WrappingContinuation<IEnumerable<KeyValuePair<TKey, float>>, double>( continuation as IHasActual<IEnumerable<KeyValuePair<TKey, float>>>, c => continuationValue ) ); } private static TValue GetValueForKey<TKey, TValue>( ICanAddMatcher<IEnumerable<KeyValuePair<TKey, TValue>>> continuation, TKey key) { return continuation .GetActual() .FirstOrDefault(kvp => kvp.Key.Equals(key)) .Value; } } }
using System; using System.Linq; using System.Xml; using FluentNHibernate.Conventions; using FluentNHibernate.Mapping; using FluentNHibernate.MappingModel.Output; using NHibernate.Cfg; using NUnit.Framework; namespace FluentNHibernate.Testing.DomainModel.Mapping { public class MappingTester<T> { protected XmlElement currentElement; protected XmlDocument document; private readonly PersistenceModel model; private string currentPath; public MappingTester() : this(new PersistenceModel()) {} public MappingTester(PersistenceModel model) { this.model = model; this.model.ValidationEnabled = false; } public virtual MappingTester<T> RootElement { get { currentElement = document.DocumentElement; return this; } } public virtual MappingTester<T> Conventions(Action<IConventionFinder> conventionFinderAction) { conventionFinderAction(model.Conventions); return this; } public virtual MappingTester<T> SubClassMapping<TSubClass>(Action<SubclassMap<TSubClass>> action) where TSubClass : T { var map = new SubclassMap<TSubClass>(); action(map); this.model.Add(map); return this; } public virtual MappingTester<T> ForMapping(Action<ClassMap<T>> mappingAction) { var classMap = new ClassMap<T>(); mappingAction(classMap); return ForMapping(classMap); } public virtual MappingTester<T> ForMapping(ClassMap<T> classMap) { if (classMap != null) model.Add(classMap); var mappings = model.BuildMappings(); var foundMapping = mappings .Where(x => x.Classes.FirstOrDefault(c => c.Type == typeof(T)) != null) .FirstOrDefault(); if (foundMapping == null) throw new InvalidOperationException("Could not find mapping for class '" + typeof(T).Name + "'"); document = new MappingXmlSerializer() .Serialize(foundMapping); currentElement = document.DocumentElement; return this; } public virtual MappingTester<T> Element(string elementPath) { currentElement = (XmlElement)document.DocumentElement.SelectSingleNode(elementPath); currentPath = elementPath; return this; } public virtual MappingTester<T> HasThisManyChildNodes(int expected) { currentElement.ChildNodeCountShouldEqual(expected); return this; } public virtual MappingTester<T> HasAttribute(string name, string value) { Assert.IsNotNull(currentElement, "Couldn't find element matching '" + currentPath + "'"); var actual = currentElement.GetAttribute(name); Assert.AreEqual(value, actual, "Attribute '" + name + "' of '" + currentPath + "' didn't match."); return this; } public virtual MappingTester<T> HasAttribute(string name, Func<string, bool> predicate) { Assert.IsNotNull(currentElement, "Couldn't find element matching '" + currentPath + "'"); currentElement.HasAttribute(name).ShouldBeTrue(); predicate(currentElement.Attributes[name].Value).ShouldBeTrue(); return this; } public virtual MappingTester<T> DoesntHaveAttribute(string name) { Assert.IsFalse(currentElement.HasAttribute(name), "Found attribute '" + name + "' on element."); return this; } public virtual MappingTester<T> Exists() { Assert.IsNotNull(currentElement, "Couldn't find element matching '" + currentPath + "'"); return this; } public virtual MappingTester<T> DoesntExist() { Assert.IsNull(currentElement); return this; } public virtual MappingTester<T> HasName(string name) { Assert.AreEqual(name, currentElement.Name, "Expected current element to have the name '" + name + "' but found '" + currentElement.Name + "'."); return this; } public virtual void OutputToConsole() { Console.WriteLine(string.Empty); Console.WriteLine(this.ToString()); Console.WriteLine(string.Empty); } public override string ToString() { var stringWriter = new System.IO.StringWriter(); var xmlWriter = new XmlTextWriter(stringWriter); xmlWriter.Formatting = Formatting.Indented; this.document.WriteContentTo(xmlWriter); return stringWriter.ToString(); } public MappingTester<T> ChildrenDontContainAttribute(string key, string value) { Assert.IsNotNull(currentElement, "Couldn't find element matching '" + currentPath + "'"); foreach (XmlElement node in currentElement.ChildNodes) { if (node.HasAttribute(key)) Assert.AreNotEqual(node.Attributes[key].Value, value); } return this; } public MappingTester<T> ValueEquals(string value) { currentElement.InnerXml.ShouldEqual(value); return this; } /// <summary> /// Determines if the CurrentElement is located at a specified element position in it's parent /// </summary> /// <param name="elementPosition">Zero based index of elements on the parent</param> public virtual MappingTester<T> ShouldBeInParentAtPosition(int elementPosition) { XmlElement parentElement = (XmlElement)currentElement.ParentNode; if (parentElement == null) { Assert.Fail("Current element has no parent element."); } else { XmlElement elementAtPosition = (XmlElement)currentElement.ParentNode.ChildNodes.Item(elementPosition); Assert.IsTrue(elementAtPosition == currentElement, "Expected '" + currentElement.Name + "' but was '" + elementAtPosition.Name + "'"); } return this; } } }
using Signum.Entities.DynamicQuery; using Signum.Utilities; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Linq.Expressions; namespace Signum.Engine.Linq { internal class OrderByRewriter : DbExpressionVisitor { List<ColumnExpression>? gatheredKeys; ReadOnlyCollection<OrderExpression>? gatheredOrderings; SelectExpression? outerMostSelect; bool hasProjectionInProjector; private OrderByRewriter() { } public IDisposable Scope() { var oldOrderings = gatheredOrderings; var oldKeys = gatheredKeys; gatheredOrderings = null; gatheredKeys = null; return new Disposable(() => { gatheredKeys = oldKeys; gatheredOrderings = oldOrderings; }); } static internal Expression Rewrite(Expression expression) { return new OrderByRewriter().Visit(expression); } protected internal override Expression VisitProjection(ProjectionExpression proj) { using (Scope()) { var oldOuterMostSelect = outerMostSelect; outerMostSelect = proj.Select; var oldHasProjectionInProjector = hasProjectionInProjector; hasProjectionInProjector = false; Expression projector = this.Visit(proj.Projector); SelectExpression source = (SelectExpression)this.Visit(proj.Select); hasProjectionInProjector = oldHasProjectionInProjector; hasProjectionInProjector |= true; outerMostSelect = oldOuterMostSelect; if (source != proj.Select || projector != proj.Projector) return new ProjectionExpression(source, projector, proj.UniqueFunction, proj.Type); return proj; } } protected internal override Expression VisitSelect(SelectExpression select) { bool isOuterMost = select == outerMostSelect; if (select.IsOrderAlsoByKeys || select.HasIndex || select.Top != null && hasProjectionInProjector) { if (gatheredKeys == null) gatheredKeys = new List<ColumnExpression>(); } List<ColumnExpression>? savedKeys = null; if (gatheredKeys != null && (select.IsDistinct || select.GroupBy.HasItems() || select.IsAllAggregates)) savedKeys = gatheredKeys.ToList(); if ((AggregateFinder.GetAggregates(select.Columns)?.Any(a => a.AggregateFunction.OrderMatters()) ?? false) && select.From is SelectExpression from) { var oldOuterMostSelect = outerMostSelect; outerMostSelect = from; select = (SelectExpression)base.VisitSelect(select); outerMostSelect = oldOuterMostSelect; } else { select = (SelectExpression)base.VisitSelect(select); } if (savedKeys != null) gatheredKeys = savedKeys; List<ColumnDeclaration>? newColumns = null; if (select.GroupBy.HasItems()) { gatheredOrderings = null; if (gatheredKeys != null) { ColumnGenerator cg = new ColumnGenerator(select.Columns); var newKeys = new List<ColumnDeclaration>(); foreach (var ge in select.GroupBy) { var cd = cg.Columns.NotNull().FirstOrDefault(a => DbExpressionComparer.AreEqual(a.Expression, ge)); if (cd != null) newKeys.Add(cd); else newKeys.Add(cg.NewColumn(ge)); } if (cg.Columns.Count() != select.Columns.Count) newColumns = cg.Columns.NotNull().ToList(); gatheredKeys.AddRange(newKeys.Select(cd => new ColumnExpression(cd.Expression.Type, select.Alias, cd.Name))); } } if (select.IsAllAggregates) { if (gatheredKeys != null) { gatheredKeys.AddRange(select.Columns.Select(cd => new ColumnExpression(cd.Expression.Type, select.Alias, cd.Name))); } } if (select.IsDistinct) { gatheredOrderings = null; if (gatheredKeys != null) { gatheredKeys.AddRange(select.Columns.Select(cd => cd.GetReference(select.Alias))); } } if (select.IsReverse && !gatheredOrderings.IsNullOrEmpty()) gatheredOrderings = gatheredOrderings.Select(o => new OrderExpression( o.OrderType == OrderType.Ascending ? OrderType.Descending : OrderType.Ascending, o.Expression)).ToReadOnly(); if (select.OrderBy.Count > 0) this.PrependOrderings(select.OrderBy); ReadOnlyCollection<OrderExpression>? orderings = null; if (isOuterMost && !IsCountSumOrAvg(select) || select.Top != null) { AppendKeys(); orderings = gatheredOrderings; gatheredOrderings = null; } if (AreEqual(select.OrderBy, orderings) && !select.IsReverse && newColumns == null) return select; return new SelectExpression(select.Alias, select.IsDistinct, select.Top, (IEnumerable<ColumnDeclaration>?)newColumns ?? select.Columns, select.From, select.Where, orderings, select.GroupBy, select.SelectOptions & ~SelectOptions.Reverse); } protected internal override Expression VisitRowNumber(RowNumberExpression rowNumber) { AppendKeys(); return new RowNumberExpression(gatheredOrderings); } protected internal override Expression VisitScalar(ScalarExpression scalar) { if (!scalar.Select!.IsForXmlPathEmpty) { using (Scope()) return base.VisitScalar(scalar); } else { using (Scope()) { var oldOuterMostSelect = outerMostSelect; outerMostSelect = scalar.Select!; var result = base.VisitScalar(scalar); outerMostSelect = oldOuterMostSelect; return result; } } } protected internal override Expression VisitExists(ExistsExpression exists) { using (Scope()) return base.VisitExists(exists); } protected internal override Expression VisitIn(InExpression @in) { if (@in.Values != null) return base.VisitIn(@in); else using (Scope()) return base.VisitIn(@in); } static bool AreEqual(IEnumerable<OrderExpression>? col1, IEnumerable<OrderExpression>? col2) { bool col1Empty = col1 == null || col1.IsEmpty(); bool col2Empty = col2 == null || col2.IsEmpty(); if (col1Empty && col2Empty) return true; if (col1Empty || col2Empty) return false; return col1 == col2; } private bool IsCountSumOrAvg(SelectExpression select) { ColumnDeclaration? col = select.Columns.Only(); if (col == null) return false; Expression exp = col.Expression; if (exp is IsNullExpression) exp = ((IsNullExpression)exp).Expression; if (exp.NodeType == ExpressionType.Coalesce) { var be = ((BinaryExpression)exp); if (be.Right.NodeType == ExpressionType.Constant || be.Right is SqlConstantExpression) exp = ((BinaryExpression)exp).Left; } if (!(exp is AggregateExpression aggExp)) return false; return aggExp.AggregateFunction == AggregateSqlFunction.Count || aggExp.AggregateFunction == AggregateSqlFunction.CountDistinct || aggExp.AggregateFunction == AggregateSqlFunction.Sum || aggExp.AggregateFunction == AggregateSqlFunction.Average || aggExp.AggregateFunction == AggregateSqlFunction.StdDev || aggExp.AggregateFunction == AggregateSqlFunction.StdDevP; } protected internal override Expression VisitJoin(JoinExpression join) { SourceExpression left = this.VisitSource(join.Left); ReadOnlyCollection<OrderExpression>? leftOrders = this.gatheredOrderings; this.gatheredOrderings = null; SourceExpression right = join.Right is TableExpression ? join.Right : this.VisitSource(join.Right); this.PrependOrderings(leftOrders); Expression condition = this.Visit(join.Condition); if (left != join.Left || right != join.Right || condition != join.Condition) { return new JoinExpression(join.JoinType, left, right, condition); } return join; } protected internal override Expression VisitSetOperator(SetOperatorExpression set) { using (Scope()) return base.VisitSetOperator(set); } protected internal override Expression VisitTable(TableExpression table) { if (gatheredKeys != null) gatheredKeys.Add(table.GetIdExpression()); return table; } protected void AppendKeys() { if (this.gatheredKeys.IsNullOrEmpty()) return; if (this.gatheredOrderings.IsNullOrEmpty()) this.gatheredOrderings = this.gatheredKeys.Select(a => new OrderExpression(OrderType.Ascending, a)).ToReadOnly(); else { var hs = this.gatheredOrderings.Select(a => CleanCast(a.Expression)).OfType<ColumnExpression>().ToHashSet(); var postOrders = this.gatheredKeys.Where(e => !hs.Contains(CleanCast(e))).Select(a => new OrderExpression(OrderType.Ascending, a)); this.gatheredOrderings = this.gatheredOrderings.Concat(postOrders).ToReadOnly(); } this.gatheredKeys = null; } static Expression CleanCast(Expression exp) { while (exp.NodeType == ExpressionType.Convert) exp = ((UnaryExpression)exp).Operand; return exp; } protected void PrependOrderings(ReadOnlyCollection<OrderExpression>? newOrderings) { if (!newOrderings.IsNullOrEmpty()) { if (this.gatheredOrderings.IsNullOrEmpty()) { this.gatheredOrderings = newOrderings; } else { List<OrderExpression> list = this.gatheredOrderings.ToList(); list.InsertRange(0, newOrderings); this.gatheredOrderings = list.ToReadOnly(); } } } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Symbology.dll // Description: Contains the business logic for symbology layers and symbol categories. // ******************************************************************************************************** // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 5/11/2009 1:14:36 PM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using DotSpatial.Data; using DotSpatial.Serialization; namespace DotSpatial.Symbology { /// <summary> /// Symbolizer for polygon features. /// </summary> public class PolygonSymbolizer : FeatureSymbolizer, IPolygonSymbolizer { #region Private Variables private IList<IPattern> _patterns; #endregion #region Constructors /// <summary> /// Creates a new instance of PolygonSymbolizer /// </summary> public PolygonSymbolizer() { _patterns = new CopyList<IPattern>(); _patterns.Add(new SimplePattern()); } /// <summary> /// Creates a new instance of a polygon symbolizer /// </summary> /// <param name="fillColor">The fill color to use for the polygons</param> /// <param name="outlineColor">The border color to use for the polygons</param> public PolygonSymbolizer(Color fillColor, Color outlineColor) { _patterns = new CopyList<IPattern>(); _patterns.Add(new SimplePattern(fillColor)); OutlineSymbolizer = new LineSymbolizer(outlineColor, 1); } /// <summary> /// Creates a new instance of a solid colored polygon symbolizer /// </summary> /// <param name="fillColor">The fill color to use for the polygons</param> /// <param name="outlineColor">The border color to use for the polygons</param> /// <param name="outlineWidth">The width of the outline to use fo</param> public PolygonSymbolizer(Color fillColor, Color outlineColor, double outlineWidth) { _patterns = new CopyList<IPattern>(); _patterns.Add(new SimplePattern(fillColor)); OutlineSymbolizer = new LineSymbolizer(outlineColor, outlineWidth); } /// <summary> /// Creates a new instance of a Gradient Pattern using the specified colors and angle /// </summary> /// <param name="startColor">The start color</param> /// <param name="endColor">The end color</param> /// <param name="angle">The direction of the gradient, measured in degrees clockwise from the x-axis</param> /// <param name="style">Controls how the gradient is drawn</param> public PolygonSymbolizer(Color startColor, Color endColor, double angle, GradientType style) { _patterns = new CopyList<IPattern>(); _patterns.Add(new GradientPattern(startColor, endColor, angle, style)); } /// <summary> /// Creates a new instance of a Gradient Pattern using the specified colors and angle /// </summary> /// <param name="startColor">The start color</param> /// <param name="endColor">The end color</param> /// <param name="angle">The direction of the gradient, measured in degrees clockwise from the x-axis</param> /// <param name="style">The type of gradient to use</param> /// <param name="outlineColor">The color to use for the border symbolizer</param> /// <param name="outlineWidth">The width of the line to use for the border symbolizer</param> public PolygonSymbolizer(Color startColor, Color endColor, double angle, GradientType style, Color outlineColor, double outlineWidth) { _patterns = new CopyList<IPattern>(); _patterns.Add(new GradientPattern(startColor, endColor, angle, style)); OutlineSymbolizer = new LineSymbolizer(outlineColor, outlineWidth); } /// <summary> /// Creates a new PicturePattern with the specified image /// </summary> /// <param name="picture">The picture to draw</param> /// <param name="wrap">The way to wrap the picture</param> /// <param name="angle">The angle to rotate the image</param> public PolygonSymbolizer(Image picture, WrapMode wrap, double angle) { _patterns = new CopyList<IPattern>(); _patterns.Add(new PicturePattern(picture, wrap, angle)); } /// <summary> /// Creates a new PicturePattern with the specified image /// </summary> /// <param name="picture">The picture to draw</param> /// <param name="wrap">The way to wrap the picture</param> /// <param name="angle">The angle to rotate the image</param> /// <param name="outlineColor">The color to use for the border symbolizer</param> /// <param name="outlineWidth">The width of the line to use for the border symbolizer</param> public PolygonSymbolizer(Image picture, WrapMode wrap, double angle, Color outlineColor, double outlineWidth) { _patterns = new CopyList<IPattern>(); _patterns.Add(new PicturePattern(picture, wrap, angle)); OutlineSymbolizer = new LineSymbolizer(outlineColor, outlineWidth); } /// <summary> /// Creates a new symbolizer, using the patterns specified by the list or array of patterns. /// </summary> /// <param name="patterns">The patterns to add to this symbolizer.</param> public PolygonSymbolizer(IEnumerable<IPattern> patterns) { _patterns = new CopyList<IPattern>(); foreach (IPattern pattern in patterns) { _patterns.Add(pattern); } } /// <summary> /// Specifies a polygon symbolizer with a specific fill color. /// </summary> /// <param name="fillColor">The color to use as a fill color.</param> public PolygonSymbolizer(Color fillColor) { _patterns = new CopyList<IPattern>(); _patterns.Add(new SimplePattern(fillColor)); } /// <summary> /// Creates a new instance of PolygonSymbolizer /// </summary> /// <param name="selected">Boolean, true if this should use selection symbology</param> public PolygonSymbolizer(bool selected) { _patterns = new CopyList<IPattern>(); if (selected) { _patterns.Add(new SimplePattern(Color.Cyan)); OutlineSymbolizer = new LineSymbolizer(Color.DarkCyan, 1); } else { _patterns.Add(new SimplePattern()); } } #endregion #region Methods /// <summary> /// Sets the outline, assuming that the symbolizer either supports outlines, or /// else by using a second symbol layer. /// </summary> /// <param name="outlineColor">The color of the outline</param> /// <param name="width">The width of the outline in pixels</param> public override void SetOutline(Color outlineColor, double width) { if (_patterns == null) return; if (_patterns.Count == 0) return; foreach (IPattern pattern in _patterns) { pattern.Outline.SetFillColor(outlineColor); pattern.Outline.SetWidth(width); pattern.UseOutline = true; } base.SetOutline(outlineColor, width); } /// <summary> /// This gets the largest width of all the strokes of the outlines of all the patterns. Setting this will /// forceably adjust the width of all the strokes of the outlines of all the patterns. /// </summary> public double GetOutlineWidth() { if (_patterns == null) return 0; if (_patterns.Count == 0) return 0; double w = 0; foreach (IPattern pattern in _patterns) { double tempWidth = pattern.Outline.GetWidth(); if (tempWidth > w) w = tempWidth; } return w; } /// <summary> /// Forces the specified width to be the width of every stroke outlining every pattern. /// </summary> /// <param name="width">The width to force as the outline width</param> public void SetOutlineWidth(double width) { if (_patterns == null) return; if (_patterns.Count == 0) return; foreach (IPattern pattern in _patterns) { pattern.Outline.SetWidth(width); } } #endregion #region Properties /// <summary> /// Gets or sets the Symbolizer for the borders of this polygon as they appear on the top-most pattern. /// </summary> [ShallowCopy, Serialize("OutlineSymbolizer")] public ILineSymbolizer OutlineSymbolizer { get { if (_patterns == null) return null; if (_patterns.Count == 0) return null; return _patterns[_patterns.Count - 1].Outline; } set { if (_patterns == null) return; if (_patterns.Count == 0) return; _patterns[_patterns.Count - 1].Outline = value; } } /// <summary> /// gets or sets the list of patterns to use for filling polygons. /// </summary> [Serialize("Patterns")] public IList<IPattern> Patterns { get { return _patterns; } set { //if (_patterns != null) OnIgnorePatternEvents(); _patterns = value; //if (_patterns != null) OnHandlePatternEvents(); } } /// <summary> /// Gets the fill color of the top-most pattern. /// </summary> /// <returns></returns> public Color GetFillColor() { if (_patterns == null) return Color.Empty; if (_patterns.Count == 0) return Color.Empty; return _patterns[_patterns.Count - 1].GetFillColor(); } /// <summary> /// Sets the fill color of the top-most pattern. /// If the pattern is not a simple pattern, a simple pattern will be forced. /// </summary> /// <param name="color">The Color structure</param> public void SetFillColor(Color color) { if (_patterns == null) return; if (_patterns.Count == 0) return; ISimplePattern sp = _patterns[_patterns.Count - 1] as ISimplePattern; if (sp == null) { sp = new SimplePattern(); _patterns[_patterns.Count - 1] = sp; } sp.FillColor = color; } #endregion #region Event Handlers private void PatternsItemChanged(object sender, EventArgs e) { OnItemChanged(); } #endregion #region Protected Methods /// <summary> /// Draws the polygon symbology /// </summary> /// <param name="g">The graphics device to draw to</param> /// <param name="target">The target rectangle to draw symbology content to</param> public override void Draw(Graphics g, Rectangle target) { GraphicsPath gp = new GraphicsPath(); gp.AddRectangle(target); foreach (IPattern pattern in _patterns) { pattern.Bounds = new RectangleF(target.X, target.Y, target.Width, target.Height); pattern.FillPath(g, gp); } foreach (IPattern pattern in _patterns) { if (pattern.Outline != null) { pattern.Outline.DrawPath(g, gp, 1); } } gp.Dispose(); } /// <summary> /// Occurs after the pattern list is set so that we can listen for when /// the outline symbolizer gets updated. /// </summary> protected virtual void OnHandlePatternEvents() { IChangeEventList<IPattern> patterns = _patterns as IChangeEventList<IPattern>; if (patterns != null) { patterns.ItemChanged += PatternsItemChanged; } } /// <summary> /// Occurs before the pattern list is set so that we can stop listening /// for messages from the old outline. /// </summary> protected virtual void OnIgnorePatternEvents() { IChangeEventList<IPattern> patterns = _patterns as IChangeEventList<IPattern>; if (patterns != null) { patterns.ItemChanged -= PatternsItemChanged; } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Dynamic.Utils; using System.Diagnostics; using AstUtils = System.Linq.Expressions.Utils; namespace System.Linq.Expressions { /// <summary> /// Represents an expression that has a conditional operator. /// </summary> [DebuggerTypeProxy(typeof(Expression.ConditionalExpressionProxy))] public class ConditionalExpression : Expression { private readonly Expression _test; private readonly Expression _true; internal ConditionalExpression(Expression test, Expression ifTrue) { _test = test; _true = ifTrue; } internal static ConditionalExpression Make(Expression test, Expression ifTrue, Expression ifFalse, Type type) { if (ifTrue.Type != type || ifFalse.Type != type) { return new FullConditionalExpressionWithType(test, ifTrue, ifFalse, type); } if (ifFalse is DefaultExpression && ifFalse.Type == typeof(void)) { return new ConditionalExpression(test, ifTrue); } else { return new FullConditionalExpression(test, ifTrue, ifFalse); } } /// <summary> /// Returns the node type of this Expression. Extension nodes should return /// ExpressionType.Extension when overriding this method. /// </summary> /// <returns>The <see cref="ExpressionType"/> of the expression.</returns> public sealed override ExpressionType NodeType { get { return ExpressionType.Conditional; } } /// <summary> /// Gets the static type of the expression that this <see cref="Expression" /> represents. /// </summary> /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns> public override Type Type { get { return IfTrue.Type; } } /// <summary> /// Gets the test of the conditional operation. /// </summary> public Expression Test { get { return _test; } } /// <summary> /// Gets the expression to execute if the test evaluates to true. /// </summary> public Expression IfTrue { get { return _true; } } /// <summary> /// Gets the expression to execute if the test evaluates to false. /// </summary> public Expression IfFalse { get { return GetFalse(); } } internal virtual Expression GetFalse() { // Using a singleton here to ensure a stable object identity for IfFalse, which Update relies on. return AstUtils.Empty(); } /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitConditional(this); } /// <summary> /// Creates a new expression that is like this one, but using the /// supplied children. If all of the children are the same, it will /// return this expression. /// </summary> /// <param name="test">The <see cref="Test" /> property of the result.</param> /// <param name="ifTrue">The <see cref="IfTrue" /> property of the result.</param> /// <param name="ifFalse">The <see cref="IfFalse" /> property of the result.</param> /// <returns>This expression if no children changed, or an expression with the updated children.</returns> public ConditionalExpression Update(Expression test, Expression ifTrue, Expression ifFalse) { if (test == Test && ifTrue == IfTrue && ifFalse == IfFalse) { return this; } return Expression.Condition(test, ifTrue, ifFalse, Type); } } internal class FullConditionalExpression : ConditionalExpression { private readonly Expression _false; internal FullConditionalExpression(Expression test, Expression ifTrue, Expression ifFalse) : base(test, ifTrue) { _false = ifFalse; } internal override Expression GetFalse() { return _false; } } internal class FullConditionalExpressionWithType : FullConditionalExpression { private readonly Type _type; internal FullConditionalExpressionWithType(Expression test, Expression ifTrue, Expression ifFalse, Type type) : base(test, ifTrue, ifFalse) { _type = type; } public sealed override Type Type { get { return _type; } } } public partial class Expression { /// <summary> /// Creates a <see cref="ConditionalExpression"/>. /// </summary> /// <param name="test">An <see cref="Expression"/> to set the <see cref="P:ConditionalExpression.Test"/> property equal to.</param> /// <param name="ifTrue">An <see cref="Expression"/> to set the <see cref="P:ConditionalExpression.IfTrue"/> property equal to.</param> /// <param name="ifFalse">An <see cref="Expression"/> to set the <see cref="P:ConditionalExpression.IfFalse"/> property equal to.</param> /// <returns>A <see cref="ConditionalExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to /// <see cref="F:ExpressionType.Conditional"/> and the <see cref="P:ConditionalExpression.Test"/>, <see cref="P:ConditionalExpression.IfTrue"/>, /// and <see cref="P:ConditionalExpression.IfFalse"/> properties set to the specified values.</returns> public static ConditionalExpression Condition(Expression test, Expression ifTrue, Expression ifFalse) { RequiresCanRead(test, nameof(test)); RequiresCanRead(ifTrue, nameof(ifTrue)); RequiresCanRead(ifFalse, nameof(ifFalse)); if (test.Type != typeof(bool)) { throw Error.ArgumentMustBeBoolean(); } if (!TypeUtils.AreEquivalent(ifTrue.Type, ifFalse.Type)) { throw Error.ArgumentTypesMustMatch(); } return ConditionalExpression.Make(test, ifTrue, ifFalse, ifTrue.Type); } /// <summary> /// Creates a <see cref="ConditionalExpression"/>. /// </summary> /// <param name="test">An <see cref="Expression"/> to set the <see cref="P:ConditionalExpression.Test"/> property equal to.</param> /// <param name="ifTrue">An <see cref="Expression"/> to set the <see cref="P:ConditionalExpression.IfTrue"/> property equal to.</param> /// <param name="ifFalse">An <see cref="Expression"/> to set the <see cref="P:ConditionalExpression.IfFalse"/> property equal to.</param> /// <param name="type">A <see cref="Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param> /// <returns>A <see cref="ConditionalExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to /// <see cref="F:ExpressionType.Conditional"/> and the <see cref="P:ConditionalExpression.Test"/>, <see cref="P:ConditionalExpression.IfTrue"/>, /// and <see cref="P:ConditionalExpression.IfFalse"/> properties set to the specified values.</returns> /// <remarks>This method allows explicitly unifying the result type of the conditional expression in cases where the types of <paramref name="ifTrue"/> /// and <paramref name="ifFalse"/> expressions are not equal. Types of both <paramref name="ifTrue"/> and <paramref name="ifFalse"/> must be implicitly /// reference assignable to the result type. The <paramref name="type"/> is allowed to be <see cref="System.Void"/>.</remarks> public static ConditionalExpression Condition(Expression test, Expression ifTrue, Expression ifFalse, Type type) { RequiresCanRead(test, nameof(test)); RequiresCanRead(ifTrue, nameof(ifTrue)); RequiresCanRead(ifFalse, nameof(ifFalse)); ContractUtils.RequiresNotNull(type, nameof(type)); if (test.Type != typeof(bool)) { throw Error.ArgumentMustBeBoolean(); } if (type != typeof(void)) { if (!TypeUtils.AreReferenceAssignable(type, ifTrue.Type) || !TypeUtils.AreReferenceAssignable(type, ifFalse.Type)) { throw Error.ArgumentTypesMustMatch(); } } return ConditionalExpression.Make(test, ifTrue, ifFalse, type); } /// <summary> /// Creates a <see cref="ConditionalExpression"/>. /// </summary> /// <param name="test">An <see cref="Expression"/> to set the <see cref="P:ConditionalExpression.Test"/> property equal to.</param> /// <param name="ifTrue">An <see cref="Expression"/> to set the <see cref="P:ConditionalExpression.IfTrue"/> property equal to.</param> /// <returns>A <see cref="ConditionalExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to /// <see cref="F:ExpressionType.Conditional"/> and the <see cref="P:ConditionalExpression.Test"/>, <see cref="P:ConditionalExpression.IfTrue"/>, /// properties set to the specified values. The <see cref="P:ConditionalExpression.IfFalse"/> property is set to default expression and /// the type of the resulting <see cref="ConditionalExpression"/> returned by this method is <see cref="System.Void"/>.</returns> public static ConditionalExpression IfThen(Expression test, Expression ifTrue) { return Condition(test, ifTrue, Expression.Empty(), typeof(void)); } /// <summary> /// Creates a <see cref="ConditionalExpression"/>. /// </summary> /// <param name="test">An <see cref="Expression"/> to set the <see cref="P:ConditionalExpression.Test"/> property equal to.</param> /// <param name="ifTrue">An <see cref="Expression"/> to set the <see cref="P:ConditionalExpression.IfTrue"/> property equal to.</param> /// <param name="ifFalse">An <see cref="Expression"/> to set the <see cref="P:ConditionalExpression.IfFalse"/> property equal to.</param> /// <returns>A <see cref="ConditionalExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to /// <see cref="F:ExpressionType.Conditional"/> and the <see cref="P:ConditionalExpression.Test"/>, <see cref="P:ConditionalExpression.IfTrue"/>, /// and <see cref="P:ConditionalExpression.IfFalse"/> properties set to the specified values. The type of the resulting <see cref="ConditionalExpression"/> /// returned by this method is <see cref="System.Void"/>.</returns> public static ConditionalExpression IfThenElse(Expression test, Expression ifTrue, Expression ifFalse) { return Condition(test, ifTrue, ifFalse, typeof(void)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Security.Cryptography; using Internal.NativeCrypto; namespace Internal.Cryptography { // // Common infrastructure for crypto symmetric algorithms that use Cng. // internal struct CngSymmetricAlgorithmCore { /// <summary> /// Configures the core to use plaintext keys (to be auto-generated when first needed.) /// </summary> public CngSymmetricAlgorithmCore(ICngSymmetricAlgorithm outer) { _outer = outer; _keyName = null; // Setting _keyName to null signifies that this object is based on a plaintext key, not a stored CNG key. _provider = null; _optionOptions = CngKeyOpenOptions.None; } /// <summary> /// Constructs the core to use a stored CNG key. /// </summary> public CngSymmetricAlgorithmCore(ICngSymmetricAlgorithm outer, string keyName, CngProvider provider, CngKeyOpenOptions openOptions) { if (keyName == null) throw new ArgumentNullException(nameof(keyName)); if (provider == null) throw new ArgumentNullException(nameof(provider)); _outer = outer; _keyName = keyName; _provider = provider; _optionOptions = openOptions; using (CngKey cngKey = ProduceCngKey()) { CngAlgorithm actualAlgorithm = cngKey.Algorithm; string algorithm = _outer.GetNCryptAlgorithmIdentifier(); if (algorithm != actualAlgorithm.Algorithm) throw new CryptographicException(SR.Format(SR.Cryptography_CngKeyWrongAlgorithm, actualAlgorithm.Algorithm, algorithm)); _outer.BaseKeySize = cngKey.KeySize; } } /// <summary> /// Note! This can and likely will throw if the algorithm was given a hardware-based key. /// </summary> public byte[] GetKeyIfExportable() { if (KeyInPlainText) { return _outer.BaseKey; } else { using (CngKey cngKey = ProduceCngKey()) { return cngKey.GetSymmetricKeyDataIfExportable(_outer.GetNCryptAlgorithmIdentifier()); } } } public void SetKey(byte[] key) { _outer.BaseKey = key; _keyName = null; // Setting _keyName to null signifies that this object is now based on a plaintext key, not a stored CNG key. } public void SetKeySize(int keySize, ICngSymmetricAlgorithm outer) { // Warning: This gets invoked once before "this" is initialized, due to Aes(), DES(), etc., setting the KeySize property in their // nullary constructor. That's why we require "outer" being passed as parameter. Debug.Assert(_outer == null || _outer == outer); outer.BaseKeySize = keySize; _keyName = null; // Setting _keyName to null signifies that this object is now based on a plaintext key, not a stored CNG key. } public void GenerateKey() { byte[] key = Helpers.GenerateRandom(_outer.BaseKeySize.BitSizeToByteSize()); SetKey(key); } public void GenerateIV() { byte[] iv = Helpers.GenerateRandom(_outer.BlockSize.BitSizeToByteSize()); _outer.IV = iv; } public ICryptoTransform CreateEncryptor() { return CreateCryptoTransform(encrypting: true); } public ICryptoTransform CreateDecryptor() { return CreateCryptoTransform(encrypting: false); } public ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV) { return CreateCryptoTransform(rgbKey, rgbIV, encrypting: true); } public ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV) { return CreateCryptoTransform(rgbKey, rgbIV, encrypting: false); } private ICryptoTransform CreateCryptoTransform(bool encrypting) { if (KeyInPlainText) { return CreateCryptoTransform(_outer.BaseKey, _outer.IV, encrypting); } return CreatePersistedCryptoTransformCore(ProduceCngKey, _outer.IV, encrypting); } private ICryptoTransform CreateCryptoTransform(byte[] rgbKey, byte[] rgbIV, bool encrypting) { if (rgbKey == null) throw new ArgumentNullException(nameof(rgbKey)); byte[] key = rgbKey.CloneByteArray(); long keySize = key.Length * (long)BitsPerByte; if (keySize > int.MaxValue || !((int)keySize).IsLegalSize(_outer.LegalKeySizes)) throw new ArgumentException(SR.Cryptography_InvalidKeySize, nameof(rgbKey)); if (_outer.IsWeakKey(key)) throw new CryptographicException(SR.Cryptography_WeakKey); if (rgbIV != null && rgbIV.Length != _outer.BlockSize.BitSizeToByteSize()) throw new ArgumentException(SR.Cryptography_InvalidIVSize, nameof(rgbIV)); // CloneByteArray is null-preserving. So even when GetCipherIv returns null the iv variable // is correct, and detached from the input parameter. byte[] iv = _outer.Mode.GetCipherIv(rgbIV).CloneByteArray(); return CreateEphemeralCryptoTransformCore(key, iv, encrypting); } private ICryptoTransform CreateEphemeralCryptoTransformCore(byte[] key, byte[] iv, bool encrypting) { int blockSizeInBytes = _outer.BlockSize.BitSizeToByteSize(); SafeAlgorithmHandle algorithmModeHandle = _outer.GetEphemeralModeHandle(); BasicSymmetricCipher cipher = new BasicSymmetricCipherBCrypt( algorithmModeHandle, _outer.Mode, blockSizeInBytes, key, iv, encrypting); return UniversalCryptoTransform.Create(_outer.Padding, cipher, encrypting); } private ICryptoTransform CreatePersistedCryptoTransformCore(Func<CngKey> cngKeyFactory, byte[] iv, bool encrypting) { // note: iv is guaranteed to be cloned before this method, so no need to clone it again int blockSizeInBytes = _outer.BlockSize.BitSizeToByteSize(); BasicSymmetricCipher cipher = new BasicSymmetricCipherNCrypt(cngKeyFactory, _outer.Mode, blockSizeInBytes, iv, encrypting); return UniversalCryptoTransform.Create(_outer.Padding, cipher, encrypting); } private CngKey ProduceCngKey() { Debug.Assert(!KeyInPlainText); return CngKey.Open(_keyName, _provider, _optionOptions); } private bool KeyInPlainText { get { return _keyName == null; } } private readonly ICngSymmetricAlgorithm _outer; // If using a stored CNG key, these fields provide the CngKey.Open() parameters. If using a plaintext key, _keyName is set to null. private string _keyName; private CngProvider _provider; private CngKeyOpenOptions _optionOptions; private const int BitsPerByte = 8; } }
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Instrumentation; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Base class for csc.exe, csi.exe, vbc.exe and vbi.exe implementations. /// </summary> internal abstract partial class CommonCompiler { protected const int Failed = 1; protected const int Succeeded = 0; protected static string ResponseFileDirectory { get { if (string.IsNullOrEmpty(_responseFileDirectory)) { _responseFileDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); } return _responseFileDirectory; } } private static string _responseFileDirectory = null; public CommonMessageProvider MessageProvider { get; private set; } public CommandLineArguments Arguments { get; private set; } public abstract DiagnosticFormatter DiagnosticFormatter { get; } private readonly HashSet<Diagnostic> reportedDiagnostics = new HashSet<Diagnostic>(); protected abstract Compilation CreateCompilation(TextWriter consoleOutput, TouchedFileLogger touchedFilesLogger); protected abstract void PrintLogo(TextWriter consoleOutput); protected abstract void PrintHelp(TextWriter consoleOutput); protected abstract uint GetSqmAppID(); protected abstract void CompilerSpecificSqm(IVsSqmMulti sqm, uint sqmSession); public CommonCompiler(CommandLineParser parser, string responseFile, string[] args, string baseDirectory, string additionalReferencePaths) { IEnumerable<string> allArgs = args; Debug.Assert(null == responseFile || PathUtilities.IsAbsolute(responseFile)); if (!SuppressDefaultResponseFile(args) && File.Exists(responseFile)) { allArgs = new[] { "@" + responseFile }.Concat(allArgs); } this.Arguments = parser.Parse(allArgs, baseDirectory, additionalReferencePaths); this.MessageProvider = parser.MessageProvider; } internal abstract bool SuppressDefaultResponseFile(IEnumerable<string> args); internal virtual MetadataReferenceProvider GetMetadataProvider() { return MetadataReferenceProvider.Default; } /// <summary> /// Resolves metadata references stored in command line arguments and reports errors for those that can't be resolved. /// </summary> internal List<MetadataReference> ResolveMetadataReferences( MetadataReferenceProvider metadataProvider, List<DiagnosticInfo> diagnostics, AssemblyIdentityComparer assemblyIdentityComparer, TouchedFileLogger touchedFiles, out FileResolver referenceDirectiveResolver) { using (Logger.LogBlock(FunctionId.Common_CommandLineCompiler_ResolveMetadataReferences)) { string baseDirectory = Arguments.BaseDirectory; ImmutableArray<string> absoluteReferencePaths = MakeAbsolute(Arguments.ReferencePaths, baseDirectory); FileResolver externalReferenceResolver = new FileResolver( absoluteReferencePaths, baseDirectory, touchedFiles); List<MetadataReference> resolved = new List<MetadataReference>(); ResolveMetadataReferencesFromArguments(metadataProvider, diagnostics, externalReferenceResolver, resolved); if (Arguments.IsInteractive) { referenceDirectiveResolver = externalReferenceResolver; } else { // when compiling into an assembly (csc/vbc) we only allow #r that match references given on command line: referenceDirectiveResolver = new ExistingReferencesResolver( resolved.Where(r => r.Properties.Kind == MetadataImageKind.Assembly).OfType<MetadataFileReference>().AsImmutable(), absoluteReferencePaths, baseDirectory, assemblyIdentityComparer, touchedFiles); } return resolved; } } /// <summary> /// Resolves analyzers stored in command line arguments and reports errors for those that can't be resolved. /// </summary> protected List<IDiagnosticAnalyzer> ResolveAnalyzersFromArguments(List<DiagnosticInfo> diagnostics, TouchedFileLogger touchedFiles) { List<IDiagnosticAnalyzer> analyzers = new List<IDiagnosticAnalyzer>(); string baseDirectory = Arguments.BaseDirectory; ImmutableArray<string> absoluteReferencePaths = MakeAbsolute(Arguments.ReferencePaths, baseDirectory); var fileResolver = new FileResolver( absoluteReferencePaths, baseDirectory, touchedFiles); foreach (CommandLineAnalyzer cmdLineAnalyzer in Arguments.Analyzers) { var analyzersFromAssembly = cmdLineAnalyzer.Resolve(fileResolver, diagnostics, MessageProvider); if (analyzersFromAssembly != null) { // If there are no analyzers in this assembly, let the user know. if (analyzersFromAssembly.IsEmpty()) { diagnostics.Add(new DiagnosticInfo(MessageProvider, MessageProvider.WRN_NoAnalyzerInAssembly, cmdLineAnalyzer.Analyzer)); } else { foreach (var analyzer in analyzersFromAssembly) { if (!AreAllDiagnosticsSuppressed(analyzer, Arguments.CompilationOptions.SpecificDiagnosticOptions)) { analyzers.Add(analyzer); } } } } } return analyzers; } /// <summary> /// Returns true if all the diagnostics that can be produced by this analyzer are suppressed through options. /// </summary> protected bool AreAllDiagnosticsSuppressed(IDiagnosticAnalyzer analyzer, IReadOnlyDictionary<string, ReportDiagnostic> diagnosticOptions) { var supportedDiagnostics = analyzer.SupportedDiagnostics; foreach (var diag in supportedDiagnostics) { if (diagnosticOptions.ContainsKey(diag.Id)) { if (diagnosticOptions[diag.Id] == ReportDiagnostic.Suppress) { continue; } else { return false; } } else { return false; } } return true; } /// <summary> /// Returns false if there were unresolved references in arguments, true otherwise. /// </summary> protected virtual bool ResolveMetadataReferencesFromArguments(MetadataReferenceProvider metadataProvider, List<DiagnosticInfo> diagnostics, FileResolver externalReferenceResolver, List<MetadataReference> resolved) { bool result = true; foreach (var reference in Arguments.ResolveMetadataReferences(externalReferenceResolver, metadataProvider, diagnostics, MessageProvider)) { if (!reference.IsUnresolved) { resolved.Add(reference); } else { result = false; Debug.Assert(diagnostics.Any()); } } return result; } private static ImmutableArray<string> MakeAbsolute(ImmutableArray<string> paths, string baseDirectory) { if (paths.IsDefault) { return ImmutableArray<string>.Empty; } ArrayBuilder<string> builder = null; for (int i = 0; i < paths.Length; i++) { string path = paths[i]; var absolutePath = FileUtilities.ResolveRelativePath(path, baseDirectory); if (builder == null && absolutePath != path) { builder = ArrayBuilder<string>.GetInstance(); builder.AddRange(paths, i); } if (builder != null && absolutePath != null) { builder.Add(absolutePath); } } return builder == null ? paths : builder.ToImmutableAndFree(); } /// <summary> /// Reads content of a source file. /// </summary> /// <param name="file">Source file information.</param> /// <param name="diagnostics">Storage for diagnostics.</param> /// <param name="encoding">Encoding to use or 'null' for autodetect/default</param> /// <returns>File content or null on failure.</returns> internal SourceText ReadFileContent(CommandLineSourceFile file, IList<DiagnosticInfo> diagnostics, Encoding encoding) { string discarded; return ReadFileContent(file, diagnostics, encoding, out discarded); } /// <summary> /// Reads content of a source file. /// </summary> /// <param name="file">Source file information.</param> /// <param name="diagnostics">Storage for diagnostics.</param> /// <param name="encoding">Encoding to use or 'null' for autodetect/default</param> /// <param name="normalizedFilePath">If given <paramref name="file"/> opens successfully, set to normalized absolute path of the file, null otherwise.</param> /// <returns>File content or null on failure.</returns> internal SourceText ReadFileContent(CommandLineSourceFile file, IList<DiagnosticInfo> diagnostics, Encoding encoding, out string normalizedFilePath) { try { using (var data = new FileStream(file.Path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { normalizedFilePath = data.Name; return new EncodedStringText(data, encoding); } } catch (Exception e) { DiagnosticInfo diagnosticInfo; if (e is FileNotFoundException || e is DirectoryNotFoundException) { diagnosticInfo = new DiagnosticInfo(MessageProvider, (int)MessageProvider.ERR_FileNotFound, file.Path); } else if (e is InvalidDataException) { diagnosticInfo = new DiagnosticInfo(MessageProvider, (int)MessageProvider.ERR_BinaryFile, file.Path); } else { diagnosticInfo = new DiagnosticInfo(MessageProvider, (int)MessageProvider.ERR_NoSourceFile, file.Path, e.Message); } diagnostics.Add(diagnosticInfo); normalizedFilePath = null; return null; } } internal bool PrintErrors(IEnumerable<Diagnostic> diagnostics, TextWriter consoleOutput) { bool hasErrors = false; foreach (var diag in diagnostics) { if (reportedDiagnostics.Contains(diag)) { // TODO: This invariant fails (at least) in the case where we see a member declaration "x = 1;". // First we attempt to parse a member declaration starting at "x". When we see the "=", we // create an IncompleteMemberSyntax with return type "x" and an error at the location of the "x". // Then we parse a member declaration starting at "=". This is an invalid member declaration start // so we attach an error to the "=" and attach it (plus following tokens) to the IncompleteMemberSyntax // we previously created. //this assert isn't valid if we change the design to not bail out after each phase. //System.Diagnostics.Debug.Assert(diag.Severity != DiagnosticSeverity.Error); continue; } else if (diag.Severity == DiagnosticSeverity.Info) { // Not reported from the command-line compiler. continue; } consoleOutput.WriteLine(DiagnosticFormatter.Format(diag, this.Culture)); if (diag.Severity == DiagnosticSeverity.Error || diag.IsWarningAsError) { hasErrors = true; } reportedDiagnostics.Add(diag); } return hasErrors; } internal bool PrintErrors(IEnumerable<DiagnosticInfo> diagnostics, TextWriter consoleOutput) { bool hasErrors = false; if (diagnostics != null && diagnostics.Any()) { foreach (var diagnostic in diagnostics) { if (diagnostic.Severity == DiagnosticSeverity.Info) { // Not reported from the command-line compiler. continue; } consoleOutput.WriteLine(diagnostic.ToString(Culture)); if (diagnostic.Severity == DiagnosticSeverity.Error || diagnostic.IsWarningAsError) { hasErrors = true; } } } return hasErrors; } /// <summary> /// csc.exe and vbc.exe entry point. /// </summary> public virtual int Run(TextWriter consoleOutput, CancellationToken cancellationToken) { Debug.Assert(!Arguments.IsInteractive); cancellationToken.ThrowIfCancellationRequested(); if (Arguments.DisplayLogo) { PrintLogo(consoleOutput); } if (Arguments.DisplayHelp) { PrintHelp(consoleOutput); return Succeeded; } if (PrintErrors(Arguments.Errors, consoleOutput)) { return Failed; } var touchedFilesLogger = (Arguments.TouchedFilesPath != null) ? new TouchedFileLogger() : null; Compilation compilation = CreateCompilation(consoleOutput, touchedFilesLogger); if (compilation == null) { return Failed; } var diagnostics = new List<DiagnosticInfo>(); var analyzers = ResolveAnalyzersFromArguments(diagnostics, touchedFilesLogger); if (PrintErrors(diagnostics, consoleOutput)) { return Failed; } cancellationToken.ThrowIfCancellationRequested(); EmitResult emitResult; // EDMAURER: Don't yet know if there are method body errors. don't overwrite // any existing output files until the compilation is known to be successful. string tempExeFilename = null; string tempPdbFilename = null; // NOTE: as native compiler does, we generate the documentation file // NOTE: 'in place', replacing the contents of the file if it exists try { tempExeFilename = CreateTempFile(consoleOutput); // Can happen when temp directory is "full" if (tempExeFilename == null) { return Failed; } FileStream output = OpenFile(tempExeFilename, consoleOutput); if (output == null) { return Failed; } string finalOutputPath; string finalPdbFilePath; string finalXmlFilePath; using (output) { FileStream pdb = null; FileStream xml = null; cancellationToken.ThrowIfCancellationRequested(); if (Arguments.CompilationOptions.DebugInformationKind != DebugInformationKind.None) { tempPdbFilename = CreateTempFile(consoleOutput); if (tempPdbFilename == null) { return Failed; } pdb = OpenFile(tempPdbFilename, consoleOutput); if (pdb == null) { return Failed; } } cancellationToken.ThrowIfCancellationRequested(); finalXmlFilePath = Arguments.DocumentationPath; if (finalXmlFilePath != null) { xml = OpenFile(finalXmlFilePath, consoleOutput, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete); if (xml == null) { return Failed; } xml.SetLength(0); } cancellationToken.ThrowIfCancellationRequested(); IEnumerable<DiagnosticInfo> errors; using (var win32Res = GetWin32Resources(Arguments, compilation, out errors)) using (pdb) using (xml) { if (PrintErrors(errors, consoleOutput)) { return Failed; } cancellationToken.ThrowIfCancellationRequested(); string outputName = GetOutputFileName(compilation, cancellationToken); finalOutputPath = Path.Combine(Arguments.OutputDirectory, outputName); finalPdbFilePath = Arguments.PdbPath ?? Path.ChangeExtension(finalOutputPath, ".pdb"); // NOTE: Unlike the PDB path, the XML doc path is not embedded in the assembly, so we don't need to pass it to emit. emitResult = compilation.Emit(output, outputName, finalPdbFilePath, pdb, xml, cancellationToken, win32Res, Arguments.ManifestResources); } } GenerateSqmData(Arguments.CompilationOptions, emitResult.Diagnostics); if (PrintErrors(emitResult.Diagnostics, consoleOutput)) { return Failed; } cancellationToken.ThrowIfCancellationRequested(); var analyzerDiagnostics = AnalyzerDriver.GetDiagnostics(compilation, analyzers, default(CancellationToken)); if (PrintErrors(analyzerDiagnostics, consoleOutput)) { return Failed; } cancellationToken.ThrowIfCancellationRequested(); if (!TryDeleteFile(finalOutputPath, consoleOutput) || !TryMoveFile(tempExeFilename, finalOutputPath, consoleOutput)) { return Failed; } cancellationToken.ThrowIfCancellationRequested(); if (tempPdbFilename != null) { if (!TryDeleteFile(finalPdbFilePath, consoleOutput) || !TryMoveFile(tempPdbFilename, finalPdbFilePath, consoleOutput)) { return Failed; } } cancellationToken.ThrowIfCancellationRequested(); if (Arguments.TouchedFilesPath != null) { Debug.Assert(touchedFilesLogger != null); touchedFilesLogger.AddWritten(tempExeFilename); touchedFilesLogger.AddWritten(finalOutputPath); if (tempPdbFilename != null) { touchedFilesLogger.AddWritten(tempPdbFilename); touchedFilesLogger.AddWritten(finalPdbFilePath); } if (finalXmlFilePath != null) { touchedFilesLogger.AddWritten(finalXmlFilePath); } var readStream = OpenFile(Arguments.TouchedFilesPath + ".read", consoleOutput, FileMode.OpenOrCreate); if (readStream == null) { return Failed; } using (var writer = new StreamWriter(readStream)) { touchedFilesLogger.WriteReadPaths(writer); } var writtenStream = OpenFile(Arguments.TouchedFilesPath + ".write", consoleOutput, FileMode.OpenOrCreate); if (writtenStream == null) { return Failed; } using (var writer = new StreamWriter(writtenStream)) { touchedFilesLogger.WriteWrittenPaths(writer); } } return Succeeded; } finally { if (tempExeFilename != null) { TryDeleteFile(tempExeFilename, consoleOutput: null); } if (tempPdbFilename != null) { TryDeleteFile(tempPdbFilename, consoleOutput: null); } } } private void GenerateSqmData(CompilationOptions compilationOptions, ImmutableArray<Diagnostic> diagnostics) { // Generate SQM data file for Compilers if (Arguments.SqmSessionGuid != Guid.Empty) { IVsSqmMulti sqm = null; uint sqmSession = 0u; try { sqm = SqmServiceProvider.TryGetSqmService(); if (sqm != null) { sqm.BeginSession(this.GetSqmAppID(), false, out sqmSession); sqm.SetGlobalSessionGuid(Arguments.SqmSessionGuid); // Build Version Assembly thisAssembly = typeof(CommonCompiler).Assembly; var fileVersion = FileVersionInfo.GetVersionInfo(thisAssembly.Location).FileVersion; sqm.SetStringDatapoint(sqmSession, SqmServiceProvider.DATAID_SQM_BUILDVERSION, fileVersion); // Write Errors and Warnings from build foreach (var diagnostic in diagnostics) { switch (diagnostic.Severity) { case DiagnosticSeverity.Error: sqm.AddItemToStream(sqmSession, SqmServiceProvider.DATAID_SQM_ROSLYN_ERRORNUMBERS, (uint)diagnostic.Code); break; case DiagnosticSeverity.Warning: if (diagnostic.IsWarningAsError) { sqm.AddItemToStream(sqmSession, SqmServiceProvider.DATAID_SQM_ROSLYN_ERRORNUMBERS, (uint)diagnostic.Code); } else { sqm.AddItemToStream(sqmSession, SqmServiceProvider.DATAID_SQM_ROSLYN_WARNINGNUMBERS, (uint)diagnostic.Code); } break; case DiagnosticSeverity.None: case DiagnosticSeverity.Info: break; default: throw ExceptionUtilities.UnexpectedValue(diagnostic.Severity); } } //Suppress Warnings / warningCode as error / warningCode as warning foreach (var item in compilationOptions.SpecificDiagnosticOptions) { uint code = uint.Parse(item.Key.Substring(2)); ReportDiagnostic options = item.Value; switch (options) { case ReportDiagnostic.Suppress: sqm.AddItemToStream(sqmSession, SqmServiceProvider.DATAID_SQM_ROSLYN_SUPPRESSWARNINGNUMBERS, code); // Supress warning break; case ReportDiagnostic.Error: sqm.AddItemToStream(sqmSession, SqmServiceProvider.DATAID_SQM_ROSLYN_WARNASERRORS_NUMBERS, code); // Warning as errors break; case ReportDiagnostic.Warn: sqm.AddItemToStream(sqmSession, SqmServiceProvider.DATAID_SQM_ROSLYN_WARNASWARNINGS_NUMBERS, code); // Warning as warnings break; default: break; } } sqm.SetDatapoint(sqmSession, SqmServiceProvider.DATAID_SQM_ROSLYN_OUTPUTKIND, (uint)compilationOptions.OutputKind); CompilerSpecificSqm(sqm, sqmSession); } } finally { if (sqm != null) { sqm.EndSession(sqmSession); } } } } /// <summary> /// Given a compilation and a destination directory, determine three names: /// 1) The name with which the assembly should be output (default = null, which indicates that the compilation output name should be used). /// 2) The path of the assembly/module file (default = destination directory + compilation output name). /// 3) The path of the pdb file (default = assembly/module path with ".pdb" extension). /// </summary> /// <remarks> /// C# has a special implementation that implements idiosyncratic behavior of csc. /// </remarks> protected virtual string GetOutputFileName(Compilation compilation, CancellationToken cancellationToken) { return Arguments.OutputFileName; } /// <summary> /// Test hook for intercepting File.Open. /// </summary> internal Func<string, FileMode, FileAccess, FileShare, FileStream> FileOpen { get { return fileOpen ?? File.Open; } set { fileOpen = value; } } private Func<string, FileMode, FileAccess, FileShare, FileStream> fileOpen; /// <summary> /// Test hook for intercepting File.Delete. /// </summary> internal Action<string> FileDelete { get { return fileDelete ?? File.Delete; } set { fileDelete = value; } } private Action<string> fileDelete; /// <summary> /// Test hook for intercepting File.Move. /// </summary> internal Action<string, string> FileMove { get { return fileMove ?? File.Move; } set { fileMove = value; } } private Action<string, string> fileMove; /// <summary> /// Test hook for intercepting Path.GetTempFileName. /// </summary> internal Func<string> PathGetTempFileName { get { return pathGetTempFileName ?? Path.GetTempFileName; } set { pathGetTempFileName = value; } } private Func<string> pathGetTempFileName; private string CreateTempFile(TextWriter consoleOutput) { string result = null; // now catching in response to watson bucket 148019219 try { result = PathGetTempFileName(); } catch (IOException ex) { if (consoleOutput != null) { DiagnosticInfo diagnosticInfo = new DiagnosticInfo(MessageProvider, (int)MessageProvider.ERR_FailedToCreateTempFile, ex.Message); consoleOutput.WriteLine(diagnosticInfo.ToString(Culture)); } } return result; } private FileStream OpenFile(string filePath, TextWriter consoleOutput, FileMode mode = FileMode.Open, FileAccess access = FileAccess.ReadWrite, FileShare share = FileShare.None) { try { return FileOpen(filePath, mode, access, share); } catch (Exception e) { if (consoleOutput != null) { // TODO: distinct error message? DiagnosticInfo diagnosticInfo = new DiagnosticInfo(MessageProvider, (int)MessageProvider.ERR_OutputWriteFailed, filePath, e.Message); consoleOutput.WriteLine(diagnosticInfo.ToString(Culture)); } return null; } } private bool TryDeleteFile(string filePath, TextWriter consoleOutput) { try { if (File.Exists(filePath)) { FileDelete(filePath); } return true; } catch (Exception e) { // Treat all possible exceptions uniformly, so we report // "Could not write to output file"/"can't open '***' for writing" // for all as in the native CS/VB compiler. if (consoleOutput != null) { DiagnosticInfo diagnosticInfo = new DiagnosticInfo(MessageProvider, (int)MessageProvider.ERR_OutputWriteFailed, filePath, e.Message); consoleOutput.WriteLine(diagnosticInfo.ToString(Culture)); } return false; } } private bool TryMoveFile(string sourcePath, string destinationPath, TextWriter consoleOutput) { try { FileMove(sourcePath, destinationPath); return true; } catch (Exception e) { // There can be various exceptions caught here including: // - DirectoryNotFoundException when a given path is not found // - IOException when a device like a:\ is not ready // - UnauthorizedAccessException when a given path is not accessible // - NotSupportedException when a given path is in an invalid format // // Treat them uniformly, so we report "Cannot open 'filename' for writing" for all as in the native VB compiler. if (consoleOutput != null) { DiagnosticInfo diagnosticInfo = new DiagnosticInfo(MessageProvider, (int)MessageProvider.ERR_CantOpenFileWrite, destinationPath, e.Message); consoleOutput.WriteLine(diagnosticInfo.ToString(Culture)); } return false; } } protected Stream GetWin32Resources(CommandLineArguments arguments, Compilation compilation, out IEnumerable<DiagnosticInfo> errors) { return GetWin32ResourcesInternal(MessageProvider, arguments, compilation, out errors); } // internal for testing internal static Stream GetWin32ResourcesInternal(CommonMessageProvider messageProvider, CommandLineArguments arguments, Compilation compilation, out IEnumerable<DiagnosticInfo> errors) { List<DiagnosticInfo> errorList = new List<DiagnosticInfo>(); errors = errorList; if (arguments.Win32ResourceFile != null) { return OpenStream(messageProvider, arguments.Win32ResourceFile, arguments.BaseDirectory, messageProvider.ERR_CantOpenWin32Resource, errorList); } using (Stream manifestStream = OpenManifestStream(messageProvider, compilation.Options.OutputKind, arguments, errorList)) { using (Stream iconStream = OpenStream(messageProvider, arguments.Win32Icon, arguments.BaseDirectory, messageProvider.ERR_CantOpenWin32Icon, errorList)) { try { return compilation.CreateDefaultWin32Resources(true, arguments.NoWin32Manifest, manifestStream, iconStream); } catch (ResourceException ex) { errorList.Add(new DiagnosticInfo(messageProvider, messageProvider.ERR_ErrorBuildingWin32Resource, ex.Message)); } catch (OverflowException ex) { errorList.Add(new DiagnosticInfo(messageProvider, messageProvider.ERR_ErrorBuildingWin32Resource, ex.Message)); } } } return null; } private static FileStream OpenManifestStream(CommonMessageProvider messageProvider, OutputKind outputKind, CommandLineArguments arguments, List<DiagnosticInfo> errorList) { return outputKind.IsNetModule() ? null : OpenStream(messageProvider, arguments.Win32Manifest, arguments.BaseDirectory, messageProvider.ERR_CantOpenWin32Manifest, errorList); } private static FileStream OpenStream(CommonMessageProvider messageProvider, string path, string baseDirectory, int errorCode, IList<DiagnosticInfo> errors) { if (path == null) { return null; } string fullPath = ResolveRelativePath(messageProvider, path, baseDirectory, errors); if (fullPath == null) { return null; } try { return new FileStream(fullPath, FileMode.Open, FileAccess.Read); } catch (Exception ex) { errors.Add(new DiagnosticInfo(messageProvider, errorCode, fullPath, ex.Message)); } return null; } private static string ResolveRelativePath(CommonMessageProvider messageProvider, string path, string baseDirectory, IList<DiagnosticInfo> errors) { string fullPath = FileUtilities.ResolveRelativePath(path, baseDirectory); if (fullPath == null) { errors.Add(new DiagnosticInfo(messageProvider, messageProvider.FTL_InputFileNameTooLong, path)); } return fullPath; } /// <summary> /// csi.exe and vbi.exe entry point. /// </summary> internal int RunInteractive(TextWriter consoleOutput) { Debug.Assert(Arguments.IsInteractive); var hasScriptFiles = Arguments.SourceFiles.Any(file => file.IsScript); if (Arguments.DisplayLogo && !hasScriptFiles) { PrintLogo(consoleOutput); } if (Arguments.DisplayHelp) { PrintHelp(consoleOutput); return 0; } // TODO (tomat): // When we have command line REPL enabled we'll launch it if there are no input files. IEnumerable<Diagnostic> errors = Arguments.Errors; if (!hasScriptFiles) { errors = errors.Concat(new[] { Diagnostic.Create(MessageProvider, MessageProvider.ERR_NoScriptsSpecified) }); } if (PrintErrors(errors, consoleOutput)) { return Failed; } // arguments are always available when executing script code: Debug.Assert(Arguments.ScriptArguments != null); var compilation = CreateCompilation(consoleOutput, touchedFilesLogger: null); if (compilation == null) { return Failed; } byte[] compiledAssembly; using (MemoryStream output = new MemoryStream()) { EmitResult emitResult = compilation.Emit(output); if (PrintErrors(emitResult.Diagnostics, consoleOutput)) { return Failed; } compiledAssembly = output.ToArray(); } var assembly = Assembly.Load(compiledAssembly); return Execute(assembly, Arguments.ScriptArguments.ToArray()); } private static int Execute(Assembly assembly, string[] scriptArguments) { var parameters = assembly.EntryPoint.GetParameters(); object[] arguments; if (parameters.Length == 0) { arguments = new object[0]; } else { Debug.Assert(parameters.Length == 1); arguments = new object[] { scriptArguments }; } object result = assembly.EntryPoint.Invoke(null, arguments); return result is int ? (int)result : Succeeded; } /// <summary> /// When overriden by a derived class, this property can override the current thread's /// CurrentUICulture property for diagnostic message resource lookups. /// </summary> protected virtual CultureInfo Culture { get { return Arguments.PreferredUILang ?? CultureInfo.CurrentUICulture; } } #if REPL ... // let the assembly loader know about location of all files referenced by the compilation: foreach (AssemblyIdentity reference in compilation.ReferencedAssemblyNames) { if (reference.Location != null) { assemblyLoader.RegisterDependency(reference); } } private void RunInteractiveLoop() { ShowLogo(); var interactiveParseOptions = arguments.ParseOptions.Copy(languageVersion: LanguageVersion.CSharp6, kind: SourceCodeKind.Interactive); var engine = new Engine(referenceResolver: assemblyLoader.GetReferenceResolver()); // TODO: parse options, references, ... Session session = Session.Create(); ObjectFormatter formatter = new ObjectFormatter(maxLineLength: Console.BufferWidth, memberIndentation: " "); while (true) { Console.Write("> "); var input = new StringBuilder(); string line; while (true) { line = Console.ReadLine(); if (line == null) { return; } input.AppendLine(line); if (Syntax.IsCompleteSubmission(input.ToString(), interactiveParseOptions)) { break; } Console.Write("| "); } Submission<object> submission; object result; try { submission = Compile(engine, session, input.ToString()); result = submission.Execute(); } catch (CompilationErrorException e) { DisplayInteractiveErrors(e.Diagnostics); continue; } catch (Exception e) { // TODO (tomat): stack pretty printing Console.WriteLine(e); continue; } bool hasValue; ITypeSymbol resultType = submission.Compilation.GetSubmissionResultType(out hasValue); if (hasValue) { if (resultType != null && resultType.SpecialType == SpecialType.System_Void) { Console.Out.WriteLine(formatter.VoidDisplayString); } else { Console.Out.WriteLine(formatter.FormatObject(result)); } } } } private Submission<object> Compile(Engine engine, Session session, string text) { Submission<object> submission = engine.CompileSubmission<object>(text, session); foreach (MetadataReference reference in submission.Compilation.GetDirectiveReferences()) { assemblyLoader.LoadReference(reference); } return submission; } private static void DisplayInteractiveErrors(ImmutableArray<IDiagnostic> diagnostics) { var oldColor = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Red; try { DisplayInteractiveErrors(diagnostics, Console.Out); } finally { Console.ForegroundColor = oldColor; } } private static void DisplayInteractiveErrors(ImmutableArray<IDiagnostic> diagnostics, TextWriter output) { var displayedDiagnostics = new List<IDiagnostic>(); const int MaxErrorCount = 5; for (int i = 0, n = Math.Min(diagnostics.Count, MaxErrorCount); i < n; i++) { displayedDiagnostics.Add(diagnostics[i]); } displayedDiagnostics.Sort((d1, d2) => d1.Location.SourceSpan.Start - d2.Location.SourceSpan.Start); foreach (var diagnostic in displayedDiagnostics) { output.WriteLine(diagnostic.ToString(Culture)); } if (diagnostics.Count > MaxErrorCount) { int notShown = diagnostics.Count - MaxErrorCount; output.WriteLine(" + additional {0} {1}", notShown, (notShown == 1) ? "error" : "errors"); } } #endif } }
using NUnit.Framework; using System; using System.Globalization; using System.Text; namespace Lucene.Net.Util { /* * 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. */ /// @deprecated Remove when IndexableBinaryStringTools is removed. [Obsolete("Remove when IndexableBinaryStringTools is removed.")] [TestFixture] public class TestIndexableBinaryStringTools : LuceneTestCase { private static int NUM_RANDOM_TESTS; private static int MAX_RANDOM_BINARY_LENGTH; [TestFixtureSetUp] public static void BeforeClass() { NUM_RANDOM_TESTS = AtLeast(200); MAX_RANDOM_BINARY_LENGTH = AtLeast(300); } [Test] public virtual void TestSingleBinaryRoundTrip() { sbyte[] binary = new sbyte[] { (sbyte)0x23, unchecked((sbyte)0x98), (sbyte)0x13, unchecked((sbyte)0xE4), (sbyte)0x76, (sbyte)0x41, unchecked((sbyte)0xB2), unchecked((sbyte)0xC9), (sbyte)0x7F, (sbyte)0x0A, unchecked((sbyte)0xA6), unchecked((sbyte)0xD8) }; int encodedLen = IndexableBinaryStringTools.GetEncodedLength(binary, 0, binary.Length); char[] encoded = new char[encodedLen]; IndexableBinaryStringTools.Encode(binary, 0, binary.Length, encoded, 0, encoded.Length); int decodedLen = IndexableBinaryStringTools.GetDecodedLength(encoded, 0, encoded.Length); sbyte[] decoded = new sbyte[decodedLen]; IndexableBinaryStringTools.Decode(encoded, 0, encoded.Length, decoded, 0, decoded.Length); Assert.AreEqual(BinaryDump(binary, binary.Length), BinaryDump(decoded, decoded.Length), "Round trip decode/decode returned different results:\noriginal: " + BinaryDump(binary, binary.Length) + "\n encoded: " + CharArrayDump(encoded, encoded.Length) + "\n decoded: " + BinaryDump(decoded, decoded.Length)); } [Test] public virtual void TestEncodedSortability() { sbyte[] originalArray1 = new sbyte[MAX_RANDOM_BINARY_LENGTH]; char[] originalString1 = new char[MAX_RANDOM_BINARY_LENGTH]; char[] encoded1 = new char[MAX_RANDOM_BINARY_LENGTH * 10]; sbyte[] original2 = new sbyte[MAX_RANDOM_BINARY_LENGTH]; char[] originalString2 = new char[MAX_RANDOM_BINARY_LENGTH]; char[] encoded2 = new char[MAX_RANDOM_BINARY_LENGTH * 10]; for (int testNum = 0; testNum < NUM_RANDOM_TESTS; ++testNum) { int numBytes1 = Random().Next(MAX_RANDOM_BINARY_LENGTH - 1) + 1; // Min == 1 for (int byteNum = 0; byteNum < numBytes1; ++byteNum) { int randomInt = Random().Next(0x100); originalArray1[byteNum] = (sbyte)randomInt; originalString1[byteNum] = (char)randomInt; } int numBytes2 = Random().Next(MAX_RANDOM_BINARY_LENGTH - 1) + 1; // Min == 1 for (int byteNum = 0; byteNum < numBytes2; ++byteNum) { int randomInt = Random().Next(0x100); original2[byteNum] = (sbyte)randomInt; originalString2[byteNum] = (char)randomInt; } int originalComparison = String.CompareOrdinal(new string(originalString1, 0, numBytes1), new string(originalString2, 0, numBytes2)); originalComparison = originalComparison < 0 ? -1 : originalComparison > 0 ? 1 : 0; int encodedLen1 = IndexableBinaryStringTools.GetEncodedLength(originalArray1, 0, numBytes1); if (encodedLen1 > encoded1.Length) { encoded1 = new char[ArrayUtil.Oversize(encodedLen1, RamUsageEstimator.NUM_BYTES_CHAR)]; } IndexableBinaryStringTools.Encode(originalArray1, 0, numBytes1, encoded1, 0, encodedLen1); int encodedLen2 = IndexableBinaryStringTools.GetEncodedLength(original2, 0, numBytes2); if (encodedLen2 > encoded2.Length) { encoded2 = new char[ArrayUtil.Oversize(encodedLen2, RamUsageEstimator.NUM_BYTES_CHAR)]; } IndexableBinaryStringTools.Encode(original2, 0, numBytes2, encoded2, 0, encodedLen2); int encodedComparison = String.CompareOrdinal(new string(encoded1, 0, encodedLen1), new string(encoded2, 0, encodedLen2)); encodedComparison = encodedComparison < 0 ? -1 : encodedComparison > 0 ? 1 : 0; Assert.AreEqual(originalComparison, encodedComparison, "Test #" + (testNum + 1) + ": Original bytes and encoded chars compare differently:" + " \nbinary 1: " + BinaryDump(originalArray1, numBytes1) + " \nbinary 2: " + BinaryDump(original2, numBytes2) + "\nencoded 1: " + CharArrayDump(encoded1, encodedLen1) + "\nencoded 2: " + CharArrayDump(encoded2, encodedLen2)); } } [Test] public virtual void TestEmptyInput() { sbyte[] binary = new sbyte[0]; int encodedLen = IndexableBinaryStringTools.GetEncodedLength(binary, 0, binary.Length); char[] encoded = new char[encodedLen]; IndexableBinaryStringTools.Encode(binary, 0, binary.Length, encoded, 0, encoded.Length); int decodedLen = IndexableBinaryStringTools.GetDecodedLength(encoded, 0, encoded.Length); sbyte[] decoded = new sbyte[decodedLen]; IndexableBinaryStringTools.Decode(encoded, 0, encoded.Length, decoded, 0, decoded.Length); Assert.AreEqual(decoded.Length, 0, "decoded empty input was not empty"); } [Test] public virtual void TestAllNullInput() { sbyte[] binary = new sbyte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int encodedLen = IndexableBinaryStringTools.GetEncodedLength(binary, 0, binary.Length); char[] encoded = new char[encodedLen]; IndexableBinaryStringTools.Encode(binary, 0, binary.Length, encoded, 0, encoded.Length); int decodedLen = IndexableBinaryStringTools.GetDecodedLength(encoded, 0, encoded.Length); sbyte[] decoded = new sbyte[decodedLen]; IndexableBinaryStringTools.Decode(encoded, 0, encoded.Length, decoded, 0, decoded.Length); Assert.AreEqual(BinaryDump(binary, binary.Length), BinaryDump(decoded, decoded.Length), "Round trip decode/decode returned different results:" + "\n original: " + BinaryDump(binary, binary.Length) + "\ndecodedBuf: " + BinaryDump(decoded, decoded.Length)); } [Test] public virtual void TestRandomBinaryRoundTrip() { sbyte[] binary = new sbyte[MAX_RANDOM_BINARY_LENGTH]; char[] encoded = new char[MAX_RANDOM_BINARY_LENGTH * 10]; sbyte[] decoded = new sbyte[MAX_RANDOM_BINARY_LENGTH]; for (int testNum = 0; testNum < NUM_RANDOM_TESTS; ++testNum) { int numBytes = Random().Next(MAX_RANDOM_BINARY_LENGTH - 1) + 1; // Min == 1 for (int byteNum = 0; byteNum < numBytes; ++byteNum) { binary[byteNum] = (sbyte)Random().Next(0x100); } int encodedLen = IndexableBinaryStringTools.GetEncodedLength(binary, 0, numBytes); if (encoded.Length < encodedLen) { encoded = new char[ArrayUtil.Oversize(encodedLen, RamUsageEstimator.NUM_BYTES_CHAR)]; } IndexableBinaryStringTools.Encode(binary, 0, numBytes, encoded, 0, encodedLen); int decodedLen = IndexableBinaryStringTools.GetDecodedLength(encoded, 0, encodedLen); IndexableBinaryStringTools.Decode(encoded, 0, encodedLen, decoded, 0, decodedLen); Assert.AreEqual(BinaryDump(binary, numBytes), BinaryDump(decoded, decodedLen), "Test #" + (testNum + 1) + ": Round trip decode/decode returned different results:" + "\n original: " + BinaryDump(binary, numBytes) + "\nencodedBuf: " + CharArrayDump(encoded, encodedLen) + "\ndecodedBuf: " + BinaryDump(decoded, decodedLen)); } } public virtual string BinaryDump(sbyte[] binary, int numBytes) { StringBuilder buf = new StringBuilder(); for (int byteNum = 0; byteNum < numBytes; ++byteNum) { string hex = (binary[byteNum] & 0xFF).ToString("x"); if (hex.Length == 1) { buf.Append('0'); } buf.Append(hex.ToUpper(CultureInfo.InvariantCulture)); if (byteNum < numBytes - 1) { buf.Append(' '); } } return buf.ToString(); } public virtual string CharArrayDump(char[] charArray, int numBytes) { StringBuilder buf = new StringBuilder(); for (int charNum = 0; charNum < numBytes; ++charNum) { string hex = ((int)charArray[charNum]).ToString("x"); for (int digit = 0; digit < 4 - hex.Length; ++digit) { buf.Append('0'); } buf.Append(hex.ToUpper(CultureInfo.InvariantCulture)); if (charNum < numBytes - 1) { buf.Append(' '); } } return buf.ToString(); } } }
// // Copyright (c) 2004-2016 Jaroslaw Kowalski <[email protected]>, 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. // using System.Globalization; using System.Linq; using NLog.Layouts; namespace NLog.Config { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using JetBrains.Annotations; using NLog.Common; using NLog.Internal; using NLog.Targets; /// <summary> /// Keeps logging configuration and provides simple API /// to modify it. /// </summary> ///<remarks>This class is thread-safe.<c>.ToList()</c> is used for that purpose.</remarks> public class LoggingConfiguration { private readonly IDictionary<string, Target> targets = new Dictionary<string, Target>(StringComparer.OrdinalIgnoreCase); private List<object> configItems = new List<object>(); /// <summary> /// Variables defined in xml or in API. name is case case insensitive. /// </summary> private readonly Dictionary<string, SimpleLayout> variables = new Dictionary<string, SimpleLayout>(StringComparer.OrdinalIgnoreCase); /// <summary> /// Initializes a new instance of the <see cref="LoggingConfiguration" /> class. /// </summary> public LoggingConfiguration() { this.LoggingRules = new List<LoggingRule>(); } /// <summary> /// Use the old exception log handling of NLog 3.0? /// </summary> [Obsolete("This option will be removed in NLog 5")] public bool ExceptionLoggingOldStyle { get; set; } /// <summary> /// Gets the variables defined in the configuration. /// </summary> public IDictionary<string, SimpleLayout> Variables { get { return variables; } } /// <summary> /// Gets a collection of named targets specified in the configuration. /// </summary> /// <returns> /// A list of named targets. /// </returns> /// <remarks> /// Unnamed targets (such as those wrapped by other targets) are not returned. /// </remarks> public ReadOnlyCollection<Target> ConfiguredNamedTargets { get { return new List<Target>(this.targets.Values).AsReadOnly(); } } /// <summary> /// Gets the collection of file names which should be watched for changes by NLog. /// </summary> public virtual IEnumerable<string> FileNamesToWatch { get { return new string[0]; } } /// <summary> /// Gets the collection of logging rules. /// </summary> public IList<LoggingRule> LoggingRules { get; private set; } /// <summary> /// Gets or sets the default culture info to use as <see cref="LogEventInfo.FormatProvider"/>. /// </summary> /// <value> /// Specific culture info or null to use <see cref="CultureInfo.CurrentCulture"/> /// </value> [CanBeNull] public CultureInfo DefaultCultureInfo { get; set; } /// <summary> /// Gets all targets. /// </summary> public ReadOnlyCollection<Target> AllTargets { get { var configTargets = this.configItems.OfType<Target>(); return configTargets.Concat(targets.Values).ToList().AsReadOnly(); } } /// <summary> /// Registers the specified target object. The name of the target is read from <see cref="Target.Name"/>. /// </summary> /// <param name="target"> /// The target object with a non <see langword="null"/> <see cref="Target.Name"/> /// </param> /// <exception cref="ArgumentNullException">when <paramref name="target"/> is <see langword="null"/></exception> public void AddTarget([NotNull] Target target) { if (target == null) throw new ArgumentNullException("target"); AddTarget(target.Name, target); } /// <summary> /// Registers the specified target object under a given name. /// </summary> /// <param name="name"> /// Name of the target. /// </param> /// <param name="target"> /// The target object. /// </param> public void AddTarget(string name, Target target) { if (name == null) { throw new ArgumentException("Target name cannot be null", "name"); } InternalLogger.Debug("Registering target {0}: {1}", name, target.GetType().FullName); this.targets[name] = target; } /// <summary> /// Finds the target with the specified name. /// </summary> /// <param name="name"> /// The name of the target to be found. /// </param> /// <returns> /// Found target or <see langword="null"/> when the target is not found. /// </returns> public Target FindTargetByName(string name) { Target value; if (!this.targets.TryGetValue(name, out value)) { return null; } return value; } /// <summary> /// Finds the target with the specified name and specified type. /// </summary> /// <param name="name"> /// The name of the target to be found. /// </param> /// <typeparam name="TTarget">Type of the target</typeparam> /// <returns> /// Found target or <see langword="null"/> when the target is not found of not of type <typeparamref name="TTarget"/> /// </returns> public TTarget FindTargetByName<TTarget>(string name) where TTarget : Target { return FindTargetByName(name) as TTarget; } /// <summary> /// Add a rule with min- and maxLevel. /// </summary> /// <param name="minLevel">Minimum log level needed to trigger this rule.</param> /// <param name="maxLevel">Maximum log level needed to trigger this rule.</param> /// <param name="targetName">Name of the target to be written when the rule matches.</param> /// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param> public void AddRule(LogLevel minLevel, LogLevel maxLevel, string targetName, string loggerNamePattern = "*") { var target = FindTargetByName(targetName); if (target == null) { throw new NLogRuntimeException("Target '{0}' not found", targetName); } AddRule(minLevel, maxLevel, target, loggerNamePattern); } /// <summary> /// Add a rule with min- and maxLevel. /// </summary> /// <param name="minLevel">Minimum log level needed to trigger this rule.</param> /// <param name="maxLevel">Maximum log level needed to trigger this rule.</param> /// <param name="target">Target to be written to when the rule matches.</param> /// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param> public void AddRule(LogLevel minLevel, LogLevel maxLevel, Target target, string loggerNamePattern = "*") { LoggingRules.Add(new LoggingRule(loggerNamePattern, minLevel, maxLevel, target)); } /// <summary> /// Add a rule for one loglevel. /// </summary> /// <param name="level">log level needed to trigger this rule. </param> /// <param name="targetName">Name of the target to be written when the rule matches.</param> /// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param> public void AddRuleForOneLevel(LogLevel level, string targetName, string loggerNamePattern = "*") { var target = FindTargetByName(targetName); if (target == null) { throw new NLogConfigurationException("Target '{0}' not found", targetName); } AddRuleForOneLevel(level, target, loggerNamePattern); } /// <summary> /// Add a rule for one loglevel. /// </summary> /// <param name="level">log level needed to trigger this rule. </param> /// <param name="target">Target to be written to when the rule matches.</param> /// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param> public void AddRuleForOneLevel(LogLevel level, Target target, string loggerNamePattern = "*") { var loggingRule = new LoggingRule(loggerNamePattern, target); loggingRule.EnableLoggingForLevel(level); LoggingRules.Add(loggingRule); } /// <summary> /// Add a rule for alle loglevels. /// </summary> /// <param name="targetName">Name of the target to be written when the rule matches.</param> /// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param> public void AddRuleForAllLevels(string targetName, string loggerNamePattern = "*") { var target = FindTargetByName(targetName); if (target == null) { throw new NLogRuntimeException("Target '{0}' not found", targetName); } AddRuleForAllLevels(target, loggerNamePattern); } /// <summary> /// Add a rule for alle loglevels. /// </summary> /// <param name="target">Target to be written to when the rule matches.</param> /// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param> public void AddRuleForAllLevels(Target target, string loggerNamePattern = "*") { var loggingRule = new LoggingRule(loggerNamePattern, target); loggingRule.EnableLoggingForLevels(LogLevel.MinLevel, LogLevel.MaxLevel); LoggingRules.Add(loggingRule); } /// <summary> /// Called by LogManager when one of the log configuration files changes. /// </summary> /// <returns> /// A new instance of <see cref="LoggingConfiguration"/> that represents the updated configuration. /// </returns> public virtual LoggingConfiguration Reload() { return this; } /// <summary> /// Removes the specified named target. /// </summary> /// <param name="name"> /// Name of the target. /// </param> public void RemoveTarget(string name) { this.targets.Remove(name); } /// <summary> /// Installs target-specific objects on current system. /// </summary> /// <param name="installationContext">The installation context.</param> /// <remarks> /// Installation typically runs with administrative permissions. /// </remarks> public void Install(InstallationContext installationContext) { if (installationContext == null) { throw new ArgumentNullException("installationContext"); } this.InitializeAll(); var configItemsList = GetInstallableItems(); foreach (IInstallable installable in configItemsList) { installationContext.Info("Installing '{0}'", installable); try { installable.Install(installationContext); installationContext.Info("Finished installing '{0}'.", installable); } catch (Exception exception) { InternalLogger.Error(exception, "Install of '{0}' failed.", installable); if (exception.MustBeRethrownImmediately()) { throw; } installationContext.Error("Install of '{0}' failed: {1}.", installable, exception); } } } /// <summary> /// Uninstalls target-specific objects from current system. /// </summary> /// <param name="installationContext">The installation context.</param> /// <remarks> /// Uninstallation typically runs with administrative permissions. /// </remarks> public void Uninstall(InstallationContext installationContext) { if (installationContext == null) { throw new ArgumentNullException("installationContext"); } this.InitializeAll(); var configItemsList = GetInstallableItems(); foreach (IInstallable installable in configItemsList) { installationContext.Info("Uninstalling '{0}'", installable); try { installable.Uninstall(installationContext); installationContext.Info("Finished uninstalling '{0}'.", installable); } catch (Exception exception) { InternalLogger.Error(exception, "Uninstall of '{0}' failed.", installable); if (exception.MustBeRethrownImmediately()) { throw; } installationContext.Error("Uninstall of '{0}' failed: {1}.", installable, exception); } } } /// <summary> /// Closes all targets and releases any unmanaged resources. /// </summary> internal void Close() { InternalLogger.Debug("Closing logging configuration..."); var supportsInitializesList = GetSupportsInitializes(); foreach (ISupportsInitialize initialize in supportsInitializesList) { InternalLogger.Trace("Closing {0}", initialize); try { initialize.Close(); } catch (Exception exception) { InternalLogger.Warn(exception, "Exception while closing."); if (exception.MustBeRethrown()) { throw; } } } InternalLogger.Debug("Finished closing logging configuration."); } /// <summary> /// Log to the internal (NLog) logger the information about the <see cref="Target"/> and <see /// cref="LoggingRule"/> associated with this <see cref="LoggingConfiguration"/> instance. /// </summary> /// <remarks> /// The information are only recorded in the internal logger if Debug level is enabled, otherwise nothing is /// recorded. /// </remarks> internal void Dump() { if (!InternalLogger.IsDebugEnabled) { return; } InternalLogger.Debug("--- NLog configuration dump ---"); InternalLogger.Debug("Targets:"); var targetList = this.targets.Values.ToList(); foreach (Target target in targetList) { InternalLogger.Debug("{0}", target); } InternalLogger.Debug("Rules:"); var loggingRules = this.LoggingRules.ToList(); foreach (LoggingRule rule in loggingRules) { InternalLogger.Debug("{0}", rule); } InternalLogger.Debug("--- End of NLog configuration dump ---"); } /// <summary> /// Flushes any pending log messages on all appenders. /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> internal void FlushAllTargets(AsyncContinuation asyncContinuation) { var uniqueTargets = new List<Target>(); var loggingRules = this.LoggingRules.ToList(); foreach (var rule in loggingRules) { var targetList = rule.Targets.ToList(); foreach (var target in targetList) { if (!uniqueTargets.Contains(target)) { uniqueTargets.Add(target); } } } AsyncHelpers.ForEachItemInParallel(uniqueTargets, asyncContinuation, (target, cont) => target.Flush(cont)); } /// <summary> /// Validates the configuration. /// </summary> internal void ValidateConfig() { var roots = new List<object>(); var loggingRules = this.LoggingRules.ToList(); foreach (LoggingRule rule in loggingRules) { roots.Add(rule); } var targetList = this.targets.Values.ToList(); foreach (Target target in targetList) { roots.Add(target); } this.configItems = ObjectGraphScanner.FindReachableObjects<object>(roots.ToArray()); // initialize all config items starting from most nested first // so that whenever the container is initialized its children have already been InternalLogger.Info("Found {0} configuration items", this.configItems.Count); foreach (object o in this.configItems) { PropertyHelper.CheckRequiredParameters(o); } } internal void InitializeAll() { this.ValidateConfig(); var supportsInitializes = GetSupportsInitializes(true); foreach (ISupportsInitialize initialize in supportsInitializes) { InternalLogger.Trace("Initializing {0}", initialize); try { initialize.Initialize(this); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } if (LogManager.ThrowExceptions) { throw new NLogConfigurationException("Error during initialization of " + initialize, exception); } } } } internal void EnsureInitialized() { this.InitializeAll(); } private List<IInstallable> GetInstallableItems() { return this.configItems.OfType<IInstallable>().ToList(); } private List<ISupportsInitialize> GetSupportsInitializes(bool reverse = false) { var items = this.configItems.OfType<ISupportsInitialize>(); if (reverse) { items = items.Reverse(); } return items.ToList(); } } }
// // Author: // Jb Evain ([email protected]) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; using System.Threading; using Mono.Collections.Generic; namespace Mono.Cecil.Cil { public sealed class MethodBody { readonly internal MethodDefinition method; internal ParameterDefinition this_parameter; internal int max_stack_size; internal int code_size; internal bool init_locals; internal MetadataToken local_var_token; internal Collection<Instruction> instructions; internal Collection<ExceptionHandler> exceptions; internal Collection<VariableDefinition> variables; public MethodDefinition Method { get { return method; } } public int MaxStackSize { get { return max_stack_size; } set { max_stack_size = value; } } public int CodeSize { get { return code_size; } } public bool InitLocals { get { return init_locals; } set { init_locals = value; } } public MetadataToken LocalVarToken { get { return local_var_token; } set { local_var_token = value; } } public Collection<Instruction> Instructions { get { if (instructions == null) Interlocked.CompareExchange (ref instructions, new InstructionCollection (method), null); return instructions; } } public bool HasExceptionHandlers { get { return !exceptions.IsNullOrEmpty (); } } public Collection<ExceptionHandler> ExceptionHandlers { get { if (exceptions == null) Interlocked.CompareExchange (ref exceptions, new Collection<ExceptionHandler> (), null); return exceptions; } } public bool HasVariables { get { return !variables.IsNullOrEmpty (); } } public Collection<VariableDefinition> Variables { get { if (variables == null) Interlocked.CompareExchange (ref variables, new VariableDefinitionCollection (this.method), null); return variables; } } public ParameterDefinition ThisParameter { get { if (method == null || method.DeclaringType == null) throw new NotSupportedException (); if (!method.HasThis) return null; if (this_parameter == null) Interlocked.CompareExchange (ref this_parameter, CreateThisParameter (method), null); return this_parameter; } } static ParameterDefinition CreateThisParameter (MethodDefinition method) { var parameter_type = method.DeclaringType as TypeReference; if (parameter_type.HasGenericParameters) { var instance = new GenericInstanceType (parameter_type, parameter_type.GenericParameters.Count); for (int i = 0; i < parameter_type.GenericParameters.Count; i++) instance.GenericArguments.Add (parameter_type.GenericParameters [i]); parameter_type = instance; } if (parameter_type.IsValueType || parameter_type.IsPrimitive) parameter_type = new ByReferenceType (parameter_type); return new ParameterDefinition (parameter_type, method); } public MethodBody (MethodDefinition method) { this.method = method; } public ILProcessor GetILProcessor () { return new ILProcessor (this); } } sealed class VariableDefinitionCollection : Collection<VariableDefinition> { readonly MethodDefinition method; internal VariableDefinitionCollection (MethodDefinition method) { this.method = method; } internal VariableDefinitionCollection (MethodDefinition method, int capacity) : base (capacity) { this.method = method; } protected override void OnAdd (VariableDefinition item, int index) { item.index = index; } protected override void OnInsert (VariableDefinition item, int index) { item.index = index; UpdateVariableIndices (index, 1); } protected override void OnSet (VariableDefinition item, int index) { item.index = index; } protected override void OnRemove (VariableDefinition item, int index) { UpdateVariableIndices (index + 1, -1, item); item.index = -1; } void UpdateVariableIndices (int startIndex, int offset, VariableDefinition variableToRemove = null) { for (int i = startIndex; i < size; i++) items [i].index = i + offset; var debug_info = method == null ? null : method.debug_info; if (debug_info == null || debug_info.Scope == null) return; foreach (var scope in debug_info.GetScopes ()) { if (!scope.HasVariables) continue; var variables = scope.Variables; int variableDebugInfoIndexToRemove = -1; for (int i = 0; i < variables.Count; i++) { var variable = variables [i]; // If a variable is being removed detect if it has debug info counterpart, if so remove that as well. // Note that the debug info can be either resolved (has direct reference to the VariableDefinition) // or unresolved (has only the number index of the variable) - this needs to handle both cases. if (variableToRemove != null && ((variable.index.IsResolved && variable.index.ResolvedVariable == variableToRemove) || (!variable.index.IsResolved && variable.Index == variableToRemove.Index))) { variableDebugInfoIndexToRemove = i; continue; } // For unresolved debug info updates indeces to keep them pointing to the same variable. if (!variable.index.IsResolved && variable.Index >= startIndex) { variable.index = new VariableIndex (variable.Index + offset); } } if (variableDebugInfoIndexToRemove >= 0) variables.RemoveAt (variableDebugInfoIndexToRemove); } } } class InstructionCollection : Collection<Instruction> { readonly MethodDefinition method; internal InstructionCollection (MethodDefinition method) { this.method = method; } internal InstructionCollection (MethodDefinition method, int capacity) : base (capacity) { this.method = method; } protected override void OnAdd (Instruction item, int index) { if (index == 0) return; var previous = items [index - 1]; previous.next = item; item.previous = previous; } protected override void OnInsert (Instruction item, int index) { int startOffset = 0; if (size != 0) { var current = items [index]; if (current == null) { var last = items [index - 1]; last.next = item; item.previous = last; return; } startOffset = current.Offset; var previous = current.previous; if (previous != null) { previous.next = item; item.previous = previous; } current.previous = item; item.next = current; } var scope = GetLocalScope (); if (scope != null) UpdateLocalScope (scope, startOffset, item.GetSize (), instructionRemoved: null); } protected override void OnSet (Instruction item, int index) { var current = items [index]; item.previous = current.previous; item.next = current.next; current.previous = null; current.next = null; var scope = GetLocalScope (); if (scope != null) { var sizeOfCurrent = current.GetSize (); UpdateLocalScope (scope, current.Offset + sizeOfCurrent, item.GetSize () - sizeOfCurrent, current); } } protected override void OnRemove (Instruction item, int index) { var previous = item.previous; if (previous != null) previous.next = item.next; var next = item.next; if (next != null) next.previous = item.previous; RemoveSequencePoint (item); var scope = GetLocalScope (); if (scope != null) { var size = item.GetSize (); UpdateLocalScope (scope, item.Offset + size, -size, item); } item.previous = null; item.next = null; } void RemoveSequencePoint (Instruction instruction) { var debug_info = method.debug_info; if (debug_info == null || !debug_info.HasSequencePoints) return; var sequence_points = debug_info.sequence_points; for (int i = 0; i < sequence_points.Count; i++) { if (sequence_points [i].Offset == instruction.offset) { sequence_points.RemoveAt (i); return; } } } ScopeDebugInformation GetLocalScope () { var debug_info = method.debug_info; if (debug_info == null) return null; return debug_info.Scope; } static void UpdateLocalScope (ScopeDebugInformation scope, int startFromOffset, int offset, Instruction instructionRemoved) { // For both start and enf offsets on the scope: // * If the offset is resolved (points to instruction by reference) only update it if the instruction it points to is being removed. // For non-removed instructions it remains correct regardless of any updates to the instructions. // * If the offset is not resolved (stores the instruction offset number itself) // update the number accordingly to keep it pointing to the correct instruction (by offset). if ((!scope.Start.IsResolved && scope.Start.Offset >= startFromOffset) || (instructionRemoved != null && scope.Start.ResolvedInstruction == instructionRemoved)) scope.Start = new InstructionOffset (scope.Start.Offset + offset); // For end offset only update it if it's not the special sentinel value "EndOfMethod"; that should remain as-is. if (!scope.End.IsEndOfMethod && ((!scope.End.IsResolved && scope.End.Offset >= startFromOffset) || (instructionRemoved != null && scope.End.ResolvedInstruction == instructionRemoved))) scope.End = new InstructionOffset (scope.End.Offset + offset); if (scope.HasScopes) { foreach (var subScope in scope.Scopes) UpdateLocalScope (subScope, startFromOffset, offset, instructionRemoved); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace Lucene.Net.Index { /* * 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 DocValuesType_e = Lucene.Net.Index.FieldInfo.DocValuesType_e; /// <summary> /// Collection of <seealso cref="FieldInfo"/>s (accessible by number or by name). /// @lucene.experimental /// </summary> public class FieldInfos : IEnumerable<FieldInfo> { private readonly bool HasFreq_Renamed; private readonly bool HasProx_Renamed; private readonly bool HasPayloads_Renamed; private readonly bool HasOffsets_Renamed; private readonly bool HasVectors_Renamed; private readonly bool HasNorms_Renamed; private readonly bool HasDocValues_Renamed; private readonly SortedDictionary<int, FieldInfo> ByNumber = new SortedDictionary<int, FieldInfo>(); private readonly Dictionary<string, FieldInfo> ByName = new Dictionary<string, FieldInfo>(); private readonly ICollection<FieldInfo> Values; // for an unmodifiable iterator /// <summary> /// Constructs a new FieldInfos from an array of FieldInfo objects /// </summary> public FieldInfos(FieldInfo[] infos) { bool hasVectors = false; bool hasProx = false; bool hasPayloads = false; bool hasOffsets = false; bool hasFreq = false; bool hasNorms = false; bool hasDocValues = false; foreach (FieldInfo info in infos) { if (info.Number < 0) { throw new System.ArgumentException("illegal field number: " + info.Number + " for field " + info.Name); } FieldInfo previous; if (ByNumber.TryGetValue(info.Number, out previous)) { throw new ArgumentException("duplicate field numbers: " + previous.Name + " and " + info.Name + " have: " + info.Number); } ByNumber[info.Number] = info; if (ByName.TryGetValue(info.Name, out previous)) { throw new ArgumentException("duplicate field names: " + previous.Number + " and " + info.Number + " have: " + info.Name); } ByName[info.Name] = info; hasVectors |= info.HasVectors(); hasProx |= info.Indexed && info.FieldIndexOptions >= Index.FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS; hasFreq |= info.Indexed && info.FieldIndexOptions != Index.FieldInfo.IndexOptions.DOCS_ONLY; hasOffsets |= info.Indexed && info.FieldIndexOptions >= Index.FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS; hasNorms |= info.HasNorms(); hasDocValues |= info.HasDocValues(); hasPayloads |= info.HasPayloads(); } this.HasVectors_Renamed = hasVectors; this.HasProx_Renamed = hasProx; this.HasPayloads_Renamed = hasPayloads; this.HasOffsets_Renamed = hasOffsets; this.HasFreq_Renamed = hasFreq; this.HasNorms_Renamed = hasNorms; this.HasDocValues_Renamed = hasDocValues; this.Values = ByNumber.Values; } /// <summary> /// Returns true if any fields have freqs </summary> public virtual bool HasFreq() { return HasFreq_Renamed; } /// <summary> /// Returns true if any fields have positions </summary> public virtual bool HasProx() { return HasProx_Renamed; } /// <summary> /// Returns true if any fields have payloads </summary> public virtual bool HasPayloads() { return HasPayloads_Renamed; } /// <summary> /// Returns true if any fields have offsets </summary> public virtual bool HasOffsets() { return HasOffsets_Renamed; } /// <summary> /// Returns true if any fields have vectors </summary> public virtual bool HasVectors() { return HasVectors_Renamed; } /// <summary> /// Returns true if any fields have norms </summary> public virtual bool HasNorms() { return HasNorms_Renamed; } /// <summary> /// Returns true if any fields have DocValues </summary> public virtual bool HasDocValues() { return HasDocValues_Renamed; } /// <summary> /// Returns the number of fields </summary> public virtual int Size() { Debug.Assert(ByNumber.Count == ByName.Count); return ByNumber.Count; } /// <summary> /// Returns an iterator over all the fieldinfo objects present, /// ordered by ascending field number /// </summary> // TODO: what happens if in fact a different order is used? public virtual IEnumerator<FieldInfo> GetEnumerator() { return Values.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Return the fieldinfo object referenced by the field name </summary> /// <returns> the FieldInfo object or null when the given fieldName /// doesn't exist. </returns> public virtual FieldInfo FieldInfo(string fieldName) { FieldInfo ret; ByName.TryGetValue(fieldName, out ret); return ret; } /// <summary> /// Return the fieldinfo object referenced by the fieldNumber. </summary> /// <param name="fieldNumber"> field's number. </param> /// <returns> the FieldInfo object or null when the given fieldNumber /// doesn't exist. </returns> /// <exception cref="IllegalArgumentException"> if fieldNumber is negative </exception> public virtual FieldInfo FieldInfo(int fieldNumber) { if (fieldNumber < 0) { throw new System.ArgumentException("Illegal field number: " + fieldNumber); } Index.FieldInfo ret; ByNumber.TryGetValue(fieldNumber, out ret); return ret; } public sealed class FieldNumbers { internal readonly IDictionary<int?, string> NumberToName; internal readonly IDictionary<string, int?> NameToNumber; // We use this to enforce that a given field never // changes DV type, even across segments / IndexWriter // sessions: internal readonly IDictionary<string, DocValuesType_e?> DocValuesType; // TODO: we should similarly catch an attempt to turn // norms back on after they were already ommitted; today // we silently discard the norm but this is badly trappy internal int LowestUnassignedFieldNumber = -1; public FieldNumbers() { this.NameToNumber = new Dictionary<string, int?>(); this.NumberToName = new Dictionary<int?, string>(); this.DocValuesType = new Dictionary<string, DocValuesType_e?>(); } /// <summary> /// Returns the global field number for the given field name. If the name /// does not exist yet it tries to add it with the given preferred field /// number assigned if possible otherwise the first unassigned field number /// is used as the field number. /// </summary> internal int AddOrGet(string fieldName, int preferredFieldNumber, DocValuesType_e? dvType) { lock (this) { if (dvType != null) { DocValuesType_e? currentDVType; DocValuesType.TryGetValue(fieldName, out currentDVType); if (currentDVType == null) { DocValuesType[fieldName] = dvType; } else if (currentDVType != null && currentDVType != dvType) { throw new System.ArgumentException("cannot change DocValues type from " + currentDVType + " to " + dvType + " for field \"" + fieldName + "\""); } } int? fieldNumber; NameToNumber.TryGetValue(fieldName, out fieldNumber); if (fieldNumber == null) { int? preferredBoxed = Convert.ToInt32(preferredFieldNumber); if (preferredFieldNumber != -1 && !NumberToName.ContainsKey(preferredBoxed)) { // cool - we can use this number globally fieldNumber = preferredBoxed; } else { // find a new FieldNumber while (NumberToName.ContainsKey(++LowestUnassignedFieldNumber)) { // might not be up to date - lets do the work once needed } fieldNumber = LowestUnassignedFieldNumber; } NumberToName[fieldNumber] = fieldName; NameToNumber[fieldName] = fieldNumber; } return (int)fieldNumber; } } // used by assert internal bool ContainsConsistent(int? number, string name, DocValuesType_e? dvType) { lock (this) { string NumberToNameStr; int? NameToNumberVal; DocValuesType_e? DocValuesType_E; NumberToName.TryGetValue(number, out NumberToNameStr); NameToNumber.TryGetValue(name, out NameToNumberVal); DocValuesType.TryGetValue(name, out DocValuesType_E); return name.Equals(NumberToNameStr) && number.Equals(NameToNumber[name]) && (dvType == null || DocValuesType_E == null || dvType == DocValuesType_E); } } /// <summary> /// Returns true if the {@code fieldName} exists in the map and is of the /// same {@code dvType}. /// </summary> internal bool Contains(string fieldName, DocValuesType_e? dvType) { lock (this) { // used by IndexWriter.updateNumericDocValue if (!NameToNumber.ContainsKey(fieldName)) { return false; } else { // only return true if the field has the same dvType as the requested one DocValuesType_e? dvCand; DocValuesType.TryGetValue(fieldName, out dvCand); return dvType == dvCand; } } } internal void Clear() { lock (this) { NumberToName.Clear(); NameToNumber.Clear(); DocValuesType.Clear(); } } internal void SetDocValuesType(int number, string name, DocValuesType_e? dvType) { lock (this) { Debug.Assert(ContainsConsistent(number, name, dvType)); DocValuesType[name] = dvType; } } } public sealed class Builder { internal readonly Dictionary<string, FieldInfo> ByName = new Dictionary<string, FieldInfo>(); internal readonly FieldNumbers GlobalFieldNumbers; public Builder() : this(new FieldNumbers()) { } /// <summary> /// Creates a new instance with the given <seealso cref="FieldNumbers"/>. /// </summary> internal Builder(FieldNumbers globalFieldNumbers) { Debug.Assert(globalFieldNumbers != null); this.GlobalFieldNumbers = globalFieldNumbers; } public void Add(FieldInfos other) { foreach (FieldInfo fieldInfo in other) { Add(fieldInfo); } } /// <summary> /// NOTE: this method does not carry over termVector /// booleans nor docValuesType; the indexer chain /// (TermVectorsConsumerPerField, DocFieldProcessor) must /// set these fields when they succeed in consuming /// the document /// </summary> public FieldInfo AddOrUpdate(string name, IndexableFieldType fieldType) { // TODO: really, indexer shouldn't even call this // method (it's only called from DocFieldProcessor); // rather, each component in the chain should update // what it "owns". EG fieldType.indexOptions() should // be updated by maybe FreqProxTermsWriterPerField: return AddOrUpdateInternal(name, -1, fieldType.Indexed, false, fieldType.OmitNorms, false, fieldType.IndexOptions, fieldType.DocValueType, null); } internal FieldInfo AddOrUpdateInternal(string name, int preferredFieldNumber, bool isIndexed, bool storeTermVector, bool omitNorms, bool storePayloads, FieldInfo.IndexOptions? indexOptions, DocValuesType_e? docValues, DocValuesType_e? normType) { FieldInfo fi = FieldInfo(name); if (fi == null) { // this field wasn't yet added to this in-RAM // segment's FieldInfo, so now we get a global // number for this field. If the field was seen // before then we'll get the same name and number, // else we'll allocate a new one: int fieldNumber = GlobalFieldNumbers.AddOrGet(name, preferredFieldNumber, docValues); fi = new FieldInfo(name, isIndexed, fieldNumber, storeTermVector, omitNorms, storePayloads, indexOptions, docValues, normType, null); Debug.Assert(!ByName.ContainsKey(fi.Name)); Debug.Assert(GlobalFieldNumbers.ContainsConsistent(Convert.ToInt32(fi.Number), fi.Name, fi.DocValuesType)); ByName[fi.Name] = fi; } else { fi.Update(isIndexed, storeTermVector, omitNorms, storePayloads, indexOptions); if (docValues != null) { // only pay the synchronization cost if fi does not already have a DVType bool updateGlobal = !fi.HasDocValues(); fi.DocValuesType = docValues; // this will also perform the consistency check. if (updateGlobal) { // must also update docValuesType map so it's // aware of this field's DocValueType GlobalFieldNumbers.SetDocValuesType(fi.Number, name, docValues); } } if (!fi.OmitsNorms() && normType != null) { fi.NormType = normType; } } return fi; } public FieldInfo Add(FieldInfo fi) { // IMPORTANT - reuse the field number if possible for consistent field numbers across segments return AddOrUpdateInternal(fi.Name, fi.Number, fi.Indexed, fi.HasVectors(), fi.OmitsNorms(), fi.HasPayloads(), fi.FieldIndexOptions, fi.DocValuesType, fi.NormType); } public FieldInfo FieldInfo(string fieldName) { FieldInfo ret; ByName.TryGetValue(fieldName, out ret); return ret; } public FieldInfos Finish() { return new FieldInfos(ByName.Values.ToArray()); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ResourceManager { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure.OData; using Microsoft.Rest.Azure; using Models; /// <summary> /// DeploymentsOperations operations. /// </summary> internal partial class DeploymentsOperations : IServiceOperations<ResourceManagementClient>, IDeploymentsOperations { /// <summary> /// Initializes a new instance of the DeploymentsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal DeploymentsOperations(ResourceManagementClient client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the ResourceManagementClient /// </summary> public ResourceManagementClient Client { get; private set; } /// <summary> /// Delete deployment. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment to be deleted. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string deploymentName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync( resourceGroupName, deploymentName, customHeaders, cancellationToken); return await this.Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken); } /// <summary> /// Delete deployment. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment to be deleted. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string deploymentName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$"); } } if (deploymentName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "deploymentName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.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("deploymentName", deploymentName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deployments/{deploymentName}").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{deploymentName}", Uri.EscapeDataString(deploymentName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 202 && (int)_statusCode != 204) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Checks whether deployment exists. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group to check. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<bool?>> CheckExistenceWithHttpMessagesAsync(string resourceGroupName, string deploymentName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$"); } } if (deploymentName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "deploymentName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.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("deploymentName", deploymentName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CheckExistence", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deployments/{deploymentName}").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{deploymentName}", Uri.EscapeDataString(deploymentName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("HEAD"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204 && (int)_statusCode != 404) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<bool?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; _result.Body = (_statusCode == HttpStatusCode.NoContent); 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> /// Create a named template deployment using a template. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> /// <param name='parameters'> /// Additional parameters supplied to the operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<DeploymentExtended>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string deploymentName, Deployment parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<DeploymentExtended> _response = await BeginCreateOrUpdateWithHttpMessagesAsync( resourceGroupName, deploymentName, parameters, customHeaders, cancellationToken); return await this.Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken); } /// <summary> /// Create a named template deployment using a template. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> /// <param name='parameters'> /// Additional parameters supplied to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<DeploymentExtended>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string deploymentName, Deployment parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$"); } } if (deploymentName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "deploymentName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.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("deploymentName", deploymentName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deployments/{deploymentName}").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{deploymentName}", Uri.EscapeDataString(deploymentName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; _requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<DeploymentExtended>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DeploymentExtended>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DeploymentExtended>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get a deployment. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group to get. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<DeploymentExtended>> GetWithHttpMessagesAsync(string resourceGroupName, string deploymentName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$"); } } if (deploymentName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "deploymentName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.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("deploymentName", deploymentName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deployments/{deploymentName}").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{deploymentName}", Uri.EscapeDataString(deploymentName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<DeploymentExtended>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DeploymentExtended>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Cancel a currently running template deployment. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> CancelWithHttpMessagesAsync(string resourceGroupName, string deploymentName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$"); } } if (deploymentName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "deploymentName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.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("deploymentName", deploymentName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Cancel", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deployments/{deploymentName}/cancel").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{deploymentName}", Uri.EscapeDataString(deploymentName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Validate a deployment template. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> /// <param name='parameters'> /// Deployment to validate. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<DeploymentValidateResult>> ValidateWithHttpMessagesAsync(string resourceGroupName, string deploymentName, Deployment parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$"); } } if (deploymentName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "deploymentName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.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("deploymentName", deploymentName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Validate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deployments/{deploymentName}/validate").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{deploymentName}", Uri.EscapeDataString(deploymentName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; _requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 400) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<DeploymentValidateResult>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DeploymentValidateResult>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 400) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DeploymentValidateResult>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Exports a deployment template. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<DeploymentExportResult>> ExportTemplateWithHttpMessagesAsync(string resourceGroupName, string deploymentName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$"); } } if (deploymentName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "deploymentName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.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("deploymentName", deploymentName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ExportTemplate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deployments/{deploymentName}/exportTemplate").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{deploymentName}", Uri.EscapeDataString(deploymentName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<DeploymentExportResult>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DeploymentExportResult>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get a list of deployments. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group to filter by. The name is case insensitive. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<IPage<DeploymentExtended>>> ListWithHttpMessagesAsync(string resourceGroupName, ODataQuery<DeploymentExtendedFilter> odataQuery = default(ODataQuery<DeploymentExtendedFilter>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.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("odataQuery", odataQuery); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deployments/").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<DeploymentExtended>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<DeploymentExtended>>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get a list of deployments. /// </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> public async Task<AzureOperationResponse<IPage<DeploymentExtended>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<DeploymentExtended>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<DeploymentExtended>>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// GCurve.cs // // Author: // Atte Vuorinen <[email protected]> // // Copyright (c) 2014 Atte Vuorinen // // 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 UnityEngine; using System.Collections; [System.Serializable] public sealed class GCurve { #region Header public enum WrapModeGUI { Once = 1, Loop = 2, PingPong = 4 } public enum CurvePlayback { Forward, Reversed } public delegate void VoidDelegate(); /// <summary> /// On Curve finishes. /// Set this variable at START NOT at AWAKE, otherwise it won't be setted. /// </summary> public VoidDelegate OnFinish; /// <summary> /// USe fixed update. /// </summary> public bool fixedUpdate = false; /// <summary> /// Ignore time scale. /// </summary> public bool ignoreTimeScale = true; /// <summary> /// Value curve. /// </summary> public AnimationCurve curve = AnimationCurve.Linear(0,0,1,1); /// <summary> /// Curve mode. /// </summary> public WrapModeGUI mode = WrapModeGUI.Once; /// <summary> /// Curve duration. /// </summary> public float duration = 1; /// <summary> /// Playback mode. /// </summary> public CurvePlayback playback { get { return m_playback; } set { if(value != m_playback) { IsFinished = false; } m_playback = value; } } /// <summary> /// Playback mode. /// </summary> [SerializeField] private CurvePlayback m_playback; /// <summary> /// The ignore finish rule. /// (Only "Once" mode will active finish if this is false.) /// </summary> public bool ignoreFinishRule = false; /// <summary> /// Curve time. /// </summary> private float m_time; /// <summary> /// First call. /// </summary> private bool m_init = false; #endregion #region Properties /// <summary> /// Gets a value indicating whether this <see cref="GCurve"/> is finished. /// </summary> /// <value><c>true</c> if finished; otherwise, <c>false</c>.</value> public bool IsFinished { get; private set; } /// <summary> /// Gets the curve time. /// </summary> /// <value>The curve time.</value> public float CurveTime { get { return m_time; } set { if(!m_init) { m_init = true; } m_time = value; } } /// <summary> /// Gets or sets the mode. /// </summary> /// <value>The mode.</value> public WrapMode Mode { get { return (WrapMode)mode; } set { mode = (WrapModeGUI)value; } } #endregion #region Core /// <summary> /// Initializes a new instance of the <see cref="GCurve"/> class. /// </summary> public GCurve() { } /// <summary> /// Initializes a new instance of the <see cref="GCurve"/> class. /// </summary> /// <param name="mode">Mode.</param> public GCurve(CurvePlayback mode) { playback = mode; } /// <summary> /// Initializes a new instance of the <see cref="GCurve"/> class. /// </summary> /// <param name="mode">Mode.</param> /// <param name="duration">Duration.</param> public GCurve(CurvePlayback mode, float duration) { this.duration = duration; this.playback = mode; } /// <summary> /// Reset this instance. /// </summary> public void Reset() { m_init = false; //Init(); IsFinished = false; } /// <summary> /// Evaluate the specified time. /// </summary> /// <param name="time">Time.</param> /// <param name="useDuration">If set to <c>true</c> use duration.</param> public float Evaluate(ref float time, bool useDuration = true) { if(!m_init) { Init(); } curve.postWrapMode = Mode; curve.preWrapMode = Mode; float curveValue; if(!useDuration) { curveValue = curve.Evaluate(time); } else { curveValue = curve.Evaluate(time / duration); } if(float.IsNaN(curveValue)) { curveValue = (playback == CurvePlayback.Forward ? 1 : 0); } if(Mode == WrapMode.Once || ignoreFinishRule) { if(playback == CurvePlayback.Forward) { if(time >= 1) { IsFinished = true; if(OnFinish != null) { OnFinish(); } } } else { if(time <= 0) { IsFinished = true; if(OnFinish != null) { OnFinish(); } } } } if(Mode == WrapMode.Once) { if(time >= 1) { time = 1; } else if(time <= 0) { time = 0; } } else if(Mode == WrapMode.Loop) { if(time > 1) { time = 0; } else if(time < 0) { time = 1; } } else if(Mode == WrapMode.PingPong) { if(time > 1) { playback = CurvePlayback.Reversed; } else if(time < 0) { playback = CurvePlayback.Forward; } } return curveValue; } /// <summary> /// Evaluate this instance. /// </summary> public float Evaluate() { if(!m_init) { Init(); } float speed = 0; if(!fixedUpdate) { if(ignoreTimeScale) { speed = GTime.DeltaTime; } else { speed = GTime.TimeScaledDelta; } } else { //Fixed Update doesn't have ignore time scale. speed = GTime.FixedDeltaTime; } speed /= duration; if(float.IsInfinity(speed)) { m_time = (playback == CurvePlayback.Forward ? 1 : 0); } else { if(playback == CurvePlayback.Forward) { if(m_time >= 1 && Mode == WrapMode.Once) { m_time = 1; } else { m_time += speed; } } else { if(m_time <= 0 && Mode == WrapMode.Once) { m_time = 0; } else { m_time -= speed; } } } return Evaluate(ref m_time,false); } /// <summary> /// Init this instance. /// </summary> private void Init() { if(playback == CurvePlayback.Forward) { m_time = 0; } else { m_time = 1; } m_init = true; } #endregion }
// <copyright file="Control.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // // Copyright (c) 2009-2014 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using MathNet.Numerics.Providers.LinearAlgebra; using System; using System.Threading.Tasks; namespace MathNet.Numerics { /// <summary> /// Sets parameters for the library. /// </summary> public static class Control { static int _maxDegreeOfParallelism; static int _blockSize; static int _parallelizeOrder; static int _parallelizeElements; static ILinearAlgebraProvider _linearAlgebraProvider; static Control() { ConfigureAuto(); } public static void ConfigureAuto() { // Random Numbers & Distributions CheckDistributionParameters = true; // Parallelization & Threading ThreadSafeRandomNumberGenerators = true; _maxDegreeOfParallelism = Environment.ProcessorCount; _blockSize = 512; _parallelizeOrder = 64; _parallelizeElements = 300; TaskScheduler = TaskScheduler.Default; // Linear Algebra Provider LinearAlgebraProvider = new ManagedLinearAlgebraProvider(); #if !PORTABLE && NATIVEMKL try { const string name = "MathNetNumericsLAProvider"; var value = Environment.GetEnvironmentVariable(name); switch (value != null ? value.ToUpperInvariant() : string.Empty) { #if NATIVEMKL case "MKL": LinearAlgebraProvider = new Providers.LinearAlgebra.Mkl.MklLinearAlgebraProvider(); break; #endif } } catch { // We don't care about any failures here at all (because "auto") LinearAlgebraProvider = new ManagedLinearAlgebraProvider(); } #endif } public static void UseSingleThread() { _maxDegreeOfParallelism = 1; ThreadSafeRandomNumberGenerators = false; LinearAlgebraProvider.InitializeVerify(); } public static void UseMultiThreading() { _maxDegreeOfParallelism = Environment.ProcessorCount; ThreadSafeRandomNumberGenerators = true; LinearAlgebraProvider.InitializeVerify(); } public static void UseManaged() { LinearAlgebraProvider = new ManagedLinearAlgebraProvider(); } #if NATIVEMKL public static void UseNativeMKL() { LinearAlgebraProvider = new Providers.LinearAlgebra.Mkl.MklLinearAlgebraProvider(); } [CLSCompliant(false)] public static void UseNativeMKL( Providers.LinearAlgebra.Mkl.MklConsistency consistency = Providers.LinearAlgebra.Mkl.MklConsistency.Auto, Providers.LinearAlgebra.Mkl.MklPrecision precision = Providers.LinearAlgebra.Mkl.MklPrecision.Double, Providers.LinearAlgebra.Mkl.MklAccuracy accuracy = Providers.LinearAlgebra.Mkl.MklAccuracy.High) { LinearAlgebraProvider = new Providers.LinearAlgebra.Mkl.MklLinearAlgebraProvider(consistency, precision, accuracy); } #endif /// <summary> /// Gets or sets a value indicating whether the distribution classes check validate each parameter. /// For the multivariate distributions this could involve an expensive matrix factorization. /// The default setting of this property is <c>true</c>. /// </summary> public static bool CheckDistributionParameters { get; set; } /// <summary> /// Gets or sets a value indicating whether to use thread safe random number generators (RNG). /// Thread safe RNG about two and half time slower than non-thread safe RNG. /// </summary> /// <value> /// <c>true</c> to use thread safe random number generators ; otherwise, <c>false</c>. /// </value> public static bool ThreadSafeRandomNumberGenerators { get; set; } /// <summary> /// Gets or sets the linear algebra provider. Consider to use UseNativeMKL or UseManaged instead. /// </summary> /// <value>The linear algebra provider.</value> public static ILinearAlgebraProvider LinearAlgebraProvider { get { return _linearAlgebraProvider; } set { value.InitializeVerify(); // only actually set if verification did not throw _linearAlgebraProvider = value; } } /// <summary> /// Gets or sets a value indicating how many parallel worker threads shall be used /// when parallelization is applicable. /// </summary> /// <remarks>Default to the number of processor cores, must be between 1 and 1024 (inclusive).</remarks> public static int MaxDegreeOfParallelism { get { return _maxDegreeOfParallelism; } set { _maxDegreeOfParallelism = Math.Max(1, Math.Min(1024, value)); // Reinitialize providers: LinearAlgebraProvider.InitializeVerify(); } } /// <summary> /// Gets or sets the TaskScheduler used to schedule the worker tasks. /// </summary> public static TaskScheduler TaskScheduler { get; set; } /// <summary> /// Gets or sets the the block size to use for /// the native linear algebra provider. /// </summary> /// <value>The block size. Default 512, must be at least 32.</value> public static int BlockSize { get { return _blockSize; } set { _blockSize = Math.Max(32, value); } } /// <summary> /// Gets or sets the order of the matrix when linear algebra provider /// must calculate multiply in parallel threads. /// </summary> /// <value>The order. Default 64, must be at least 3.</value> internal static int ParallelizeOrder { get { return _parallelizeOrder; } set { _parallelizeOrder = Math.Max(3, value); } } /// <summary> /// Gets or sets the number of elements a vector or matrix /// must contain before we multiply threads. /// </summary> /// <value>Number of elements. Default 300, must be at least 3.</value> internal static int ParallelizeElements { get { return _parallelizeElements; } set { _parallelizeElements = Math.Max(3, value); } } } }
//------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ namespace Microsoft.Tools.ServiceModel.WsatConfig { using System; using System.Collections.Generic; using System.Text; using System.Reflection; using System.Diagnostics; using System.Security.Principal; using System.Security.Cryptography.X509Certificates; class ArgumentsParser { Dictionary<string, ParserBase> parsersTable = new Dictionary<string, ParserBase>(); Dictionary<string, string> optionsLookupTable = new Dictionary<string, string>(); Dictionary<string, int> optionsHitCount = new Dictionary<string, int>(); WsatConfiguration config; public ArgumentsParser(WsatConfiguration config) { this.config = config; InitializeParsers(); } public bool ParseOptionAndArgument(string optionAndArgument) { string value; string lowerCaseOption = ExtractOption(optionAndArgument, out value); if (!string.IsNullOrEmpty(lowerCaseOption) && optionsLookupTable.ContainsKey(lowerCaseOption)) { string normalizedOption = optionsLookupTable[lowerCaseOption]; ParserBase parser = parsersTable[normalizedOption]; parser.Parse(value, config); UpdateOptionHitCount(normalizedOption); return true; } return false; } public void ValidateArgumentsThrow() { if (optionsHitCount.Count >= 1) { foreach (string option in optionsHitCount.Keys) { if (optionsHitCount[option] > 1) { throw new WsatAdminException(WsatAdminErrorCode.DUPLICATE_OPTION, SR.GetString(SR.ErrorDuplicateOption, option)); } } if (!config.TransactionBridgeEnabled) { int optionsAllowed = 0; if (optionsHitCount.ContainsKey(CommandLineOption.Network)) { ++optionsAllowed; } if (optionsHitCount.ContainsKey(CommandLineOption.ClusterRemoteNode)) { ++optionsAllowed; } if (optionsHitCount.ContainsKey(CommandLineOption.Restart)) { ++optionsAllowed; } if (optionsHitCount.Count > optionsAllowed) { throw new WsatAdminException(WsatAdminErrorCode.CANNOT_UPDATE_SETTINGS_WHEN_NETWORK_IS_DISABLED, SR.GetString(SR.ErrorUpdateSettingsWhenNetworkIsDisabled)); } } } } void UpdateOptionHitCount(string option) { int hitCount = 0; if (optionsHitCount.TryGetValue(option, out hitCount)) { optionsHitCount[option] = hitCount + 1; } else { optionsHitCount.Add(option, 1); } } static public string ExtractOption(string arg, out string value) { value = null; if (!string.IsNullOrEmpty(arg)) { int separator = arg.IndexOf(':'); if (separator != -1) { value = arg.Substring(separator + 1); return arg.Substring(0, separator).Trim().ToLowerInvariant(); } } return string.Empty; } void InitializeParsers() { AddOptionParserPair(CommandLineOption.Network, new NetworkParser()); AddOptionParserPair(CommandLineOption.Port, new PortParser()); AddOptionParserPair(CommandLineOption.MaxTimeout, new MaxTimeoutParser()); AddOptionParserPair(CommandLineOption.DefaultTimeout, new DefaultTimeoutParser()); AddOptionParserPair(CommandLineOption.TraceLevel, new TraceLevelParser()); AddOptionParserPair(CommandLineOption.TraceActivity, new TraceActivityParser()); AddOptionParserPair(CommandLineOption.TraceProp, new TracePropagationParser()); AddOptionParserPair(CommandLineOption.TracePii, new TracePiiParser()); AddOptionParserPair(CommandLineOption.EndpointCert, new EndpointCertificateParser()); AddOptionParserPair(CommandLineOption.Accounts, new AccountsParser()); AddOptionParserPair(CommandLineOption.ClusterRemoteNode, new ClusterRemoteNodeParser()); AddOptionParserPair(CommandLineOption.AccountsCerts, new AccountsCertificatesParser()); } void AddOptionParserPair(string standardOption, ParserBase parser) { optionsLookupTable.Add(standardOption.ToLowerInvariant(), standardOption); parsersTable.Add(standardOption, parser); } abstract class ParserBase { abstract protected void DoParse(string value, WsatConfiguration config); public void Parse(string value, WsatConfiguration config) { Debug.Assert(config != null, "config is null"); DoParse(value, config); } } class NetworkParser : ParserBase { // -network:{enable|disable} protected override void DoParse(string value, WsatConfiguration config) { if (!String.IsNullOrEmpty(value)) { if (Utilities.SafeCompare(value, CommandLineOption.Enable)) { QfeChecker.CheckQfe(); config.TransactionBridgeEnabled = true; return; } else if (Utilities.SafeCompare(value, CommandLineOption.Disable)) { config.TransactionBridgeEnabled = false; return; } } throw new WsatAdminException(WsatAdminErrorCode.INVALID_NETWORK_ARGUMENT, SR.GetString(SR.ErrorNetworkArgument)); } } class PortParser : ParserBase { // -port:<portNum> protected override void DoParse(string value, WsatConfiguration config) { if (!String.IsNullOrEmpty(value)) { UInt16 parsedValue; if (UInt16.TryParse(value, out parsedValue)) { config.HttpsPort = parsedValue; return; } } throw new WsatAdminException(WsatAdminErrorCode.INVALID_HTTPS_PORT, SR.GetString(SR.ErrorHttpsPortRange)); } } class MaxTimeoutParser : ParserBase { // -maxTimeout:<sec> override protected void DoParse(string value, WsatConfiguration config) { if (!String.IsNullOrEmpty(value)) { UInt16 parsedValue; if (UInt16.TryParse(value, out parsedValue)) { config.MaxTimeout = parsedValue; return; } } throw new WsatAdminException(WsatAdminErrorCode.INVALID_MAXTIMEOUT_ARGUMENT, SR.GetString(SR.ErrorMaximumTimeoutRange)); } } class DefaultTimeoutParser : ParserBase { // -timeout:<sec> override protected void DoParse(string value, WsatConfiguration config) { if (!String.IsNullOrEmpty(value)) { UInt16 parsedValue; if (UInt16.TryParse(value, out parsedValue)) { config.DefaultTimeout = parsedValue; return; } } throw new WsatAdminException(WsatAdminErrorCode.INVALID_DEFTIMEOUT_ARGUMENT, SR.GetString(SR.ErrorDefaultTimeoutRange)); } } // -traceLevel:{Off|Error|Critical|Warning|Information|Verbose|All} class TraceLevelParser : ParserBase { override protected void DoParse(string value, WsatConfiguration config) { if (!String.IsNullOrEmpty(value)) { SourceLevels level; bool parsedCorrectly = Utilities.ParseSourceLevel(value, out level); if (parsedCorrectly) { config.TraceLevel = level; return; } else { // check to see if it's a number uint temp; if (UInt32.TryParse(value, out temp)) { config.TraceLevel = (SourceLevels)temp; return; } } } throw new WsatAdminException(WsatAdminErrorCode.INVALID_TRACELEVEL_ARGUMENT, SR.GetString(SR.ErrorTraceLevelArgument)); } } class TraceActivityParser : ParserBase { // -traceActivity:{enable|disable} protected override void DoParse(string value, WsatConfiguration config) { if (!String.IsNullOrEmpty(value)) { if (Utilities.SafeCompare(value, CommandLineOption.Enable)) { config.ActivityTracing = true; return; } else if (Utilities.SafeCompare(value, CommandLineOption.Disable)) { config.ActivityTracing = false; return; } } throw new WsatAdminException(WsatAdminErrorCode.INVALID_TRACE_ACTIVITY_ARGUMENT, SR.GetString(SR.ErrorTraceActivityArgument)); } } class TracePropagationParser : ParserBase { // -traceProp:{enable|disable} protected override void DoParse(string value, WsatConfiguration config) { if (!String.IsNullOrEmpty(value)) { if (Utilities.SafeCompare(value, CommandLineOption.Enable)) { config.ActivityPropagation = true; return; } else if (Utilities.SafeCompare(value, CommandLineOption.Disable)) { config.ActivityPropagation = false; return; } } throw new WsatAdminException(WsatAdminErrorCode.INVALID_TRACE_PROPAGATION_ARGUMENT, SR.GetString(SR.ErrorTracePropArgument)); } } class TracePiiParser : ParserBase { // -tracePII:{enable|disable} protected override void DoParse(string value, WsatConfiguration config) { if (!String.IsNullOrEmpty(value)) { if (Utilities.SafeCompare(value, CommandLineOption.Enable)) { config.TracePii = true; return; } else if (Utilities.SafeCompare(value, CommandLineOption.Disable)) { config.TracePii = false; return; } } throw new WsatAdminException(WsatAdminErrorCode.INVALID_TRACE_PII_ARGUMENT, SR.GetString(SR.ErrorTracePiiArgument)); } } // -endpointCert:{machine|<thumb>|"Issuer\SubjectName"} class EndpointCertificateParser : ParserBase { protected override void DoParse(string value, WsatConfiguration config) { if (!String.IsNullOrEmpty(value)) { if (Utilities.SafeCompare(value, CommandLineOption.CertMachine)) { config.X509Certificate = CertificateManager.GetMachineIdentityCertificate(); if (config.X509Certificate == null) { throw new WsatAdminException(WsatAdminErrorCode.CANNOT_FIND_MACHINE_CERTIFICATE, SR.GetString(SR.ErrorCannotFindMachineCertificate)); } } else if (value.IndexOf('\\') >= 0) // "Issuer\SubjectName" e.g. "*\This is a distinguished subject" { config.X509Certificate = CertificateManager.GetCertificateFromIssuerAndSubjectName(value); } else // thumbprint { config.X509Certificate = CertificateManager.GetCertificateFromThumbprint(value, string.Empty); } if (config.X509Certificate != null) { return; } } throw new WsatAdminException(WsatAdminErrorCode.INVALID_OR_MISSING_SSL_CERTIFICATE, SR.GetString(SR.ErrorMissingSSLCert)); } } // -accounts:<account,> class AccountsParser : ParserBase { protected override void DoParse(string value, WsatConfiguration config) { // Empty value is allowed and means then users want to remove all accounts config.KerberosGlobalAcl = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); List<string> acceptedAccounts = new List<string>(config.KerberosGlobalAcl); List<string> validAccounts = new List<string>(); foreach (string account in acceptedAccounts) { string normalizedAccount = account.Trim(); if (!string.IsNullOrEmpty(normalizedAccount)) { if (IsValidAccount(normalizedAccount)) { validAccounts.Add(normalizedAccount); } else { throw new WsatAdminException(WsatAdminErrorCode.INVALID_ACCOUNT, SR.GetString(SR.ErrorAccountArgument, normalizedAccount)); } } } config.KerberosGlobalAcl = validAccounts.ToArray(); } bool IsValidAccount(string account) { bool isValid = false; try { NTAccount ntAccount = new NTAccount(account); IdentityReference identityRef = ntAccount.Translate(typeof(SecurityIdentifier)); isValid = identityRef != null; } catch (IdentityNotMappedException) { } catch (Exception e) { if (Utilities.IsCriticalException(e)) { throw; } } return isValid; } } class ClusterRemoteNodeParser : ParserBase { // private switch: -clusterRemoteNode protected override void DoParse(string value, WsatConfiguration config) { if (!String.IsNullOrEmpty(value)) { if (Utilities.SafeCompare(value, CommandLineOption.Enable)) { config.IsClusterRemoteNode = true; return; } else if (Utilities.SafeCompare(value, CommandLineOption.Disable)) { config.IsClusterRemoteNode = false; return; } } throw new WsatAdminException(WsatAdminErrorCode.INVALID_CLUSTER_REMOTE_NODE_ARGUMENT, SR.GetString(SR.ErrorClusterRemoteNodeArgument)); } } class AccountsCertificatesParser : ParserBase { // -accountsCerts:<base64hash|"Issuer\SubjectName",> protected override void DoParse(string value, WsatConfiguration config) { // Empty value is allowed and means then users want to remove all accounts certs config.X509GlobalAcl = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); // newConfig.X509GlobalAcl can be empty, but never null int i = 0; foreach (string certString in config.X509GlobalAcl) { if (!string.IsNullOrEmpty(certString)) { X509Certificate2 cert = null; if (certString.IndexOf('\\') >= 0) { // issuer\subject cert = CertificateManager.GetCertificateFromIssuerAndSubjectName(certString); } else { // thumbprint cert = CertificateManager.GetCertificateFromThumbprint(certString, string.Empty); } if (cert != null) { config.X509GlobalAcl[i] = cert.Thumbprint; } else { throw new WsatAdminException(WsatAdminErrorCode.INVALID_OR_MISSING_CLIENT_CERTIFICATE, SR.GetString(SR.ErrorInvalidOrMissingClientCert)); } } i++; } } } } }
using System; using System.IO; using System.Threading.Tasks; using Xunit; using Http2; namespace Http2Tests { public static class ReadableStreamTestExtensions { public const int ReadTimeout = 350; public static async Task<StreamReadResult> ReadWithTimeout( this IReadableByteStream stream, ArraySegment<byte> buf) { var readTask = stream.ReadAsync(buf).AsTask(); var timeoutTask = Task.Delay(ReadTimeout); var combined = Task.WhenAny(new Task[]{ readTask, timeoutTask }); var done = await combined; if (done == readTask) { return readTask.Result; } throw new TimeoutException(); } public static async Task ReadAllWithTimeout( this IReadableByteStream stream, ArraySegment<byte> buf) { var readTask = stream.ReadAll(buf).AsTask(); var timeoutTask = Task.Delay(ReadTimeout); var combined = Task.WhenAny(new Task[]{ readTask, timeoutTask }); var done = await combined; if (done == readTask) { await readTask; return; } throw new TimeoutException(); } public static async Task<byte[]> ReadAllToArray( this IReadableByteStream stream) { var totalBuf = new MemoryStream(); var buf = new byte[16*1024]; while (true) { var res = await stream.ReadAsync(new ArraySegment<byte>(buf)); if (res.BytesRead > 0) { totalBuf.Write(buf, 0, res.BytesRead); } if (res.EndOfStream) { return totalBuf.ToArray(); } } } public static async Task<byte[]> ReadAllToArrayWithTimeout( this IReadableByteStream stream) { var readTask = stream.ReadAllToArray(); var timeoutTask = Task.Delay(ReadTimeout); var combined = Task.WhenAny(new Task[]{ readTask, timeoutTask }); var done = await combined; if (done == readTask) { return readTask.Result; } throw new TimeoutException(); } public static async Task<FrameHeader> ReadFrameHeaderWithTimeout( this IReadableByteStream stream) { var headerSpace = new byte[FrameHeader.HeaderSize]; var readTask = FrameHeader.ReceiveAsync(stream, headerSpace).AsTask(); var timeoutTask = Task.Delay(ReadTimeout); var combined = Task.WhenAny(new Task[]{ readTask, timeoutTask }); var done = await combined; if (done == readTask) { return readTask.Result; } throw new TimeoutException(); } public static async Task AssertReadTimeout( this IReadableByteStream stream) { var buf = new byte[1]; try { await stream.ReadAllWithTimeout( new ArraySegment<byte>(buf)); } catch (Exception e) { Assert.IsType<TimeoutException>(e); return; } Assert.False(true, "Expected no more data but received a byte"); } public static async Task ReadAndDiscardPreface( this IReadableByteStream stream) { var b = new byte[ClientPreface.Length]; await stream.ReadAllWithTimeout(new ArraySegment<byte>(b)); } public static async Task ReadAndDiscardSettings( this IReadableByteStream stream) { var header = await stream.ReadFrameHeaderWithTimeout(); Assert.Equal(FrameType.Settings, header.Type); Assert.InRange(header.Length, 0, 256); await stream.ReadAllWithTimeout( new ArraySegment<byte>(new byte[header.Length])); } public static async Task ReadAndDiscardHeaders( this IReadableByteStream stream, uint expectedStreamId, bool expectEndOfStream) { var header = await stream.ReadFrameHeaderWithTimeout(); Assert.Equal(FrameType.Headers, header.Type); Assert.Equal(expectedStreamId, header.StreamId); var isEndOfStream = (header.Flags & (byte)HeadersFrameFlags.EndOfStream) != 0; Assert.Equal(expectEndOfStream, isEndOfStream); var hbuf = new ArraySegment<byte>(new byte[header.Length]); await stream.ReadAllWithTimeout(hbuf); } public static async Task ReadAndDiscardData( this IReadableByteStream stream, uint expectedStreamId, bool expectEndOfStream, int? expectedAmount) { var header = await stream.ReadFrameHeaderWithTimeout(); Assert.Equal(FrameType.Data, header.Type); Assert.Equal(expectedStreamId, header.StreamId); var isEndOfStream = (header.Flags & (byte)DataFrameFlags.EndOfStream) != 0; Assert.Equal(expectEndOfStream, isEndOfStream); if (expectedAmount.HasValue) { Assert.Equal(expectedAmount.Value, header.Length); } var dataBuf = new ArraySegment<byte>(new byte[header.Length]); await stream.ReadAllWithTimeout(dataBuf); } public static async Task ReadAndDiscardPong( this IReadableByteStream stream) { var header = await stream.ReadFrameHeaderWithTimeout(); Assert.Equal(FrameType.Ping, header.Type); Assert.Equal(8, header.Length); Assert.Equal((byte)PingFrameFlags.Ack, header.Flags); Assert.Equal(0u, header.StreamId); await stream.ReadAllWithTimeout( new ArraySegment<byte>(new byte[8])); } public static async Task AssertSettingsAck( this IReadableByteStream stream) { var header = await stream.ReadFrameHeaderWithTimeout(); Assert.Equal(FrameType.Settings, header.Type); Assert.Equal(0, header.Length); Assert.Equal((byte)SettingsFrameFlags.Ack, header.Flags); Assert.Equal(0u, header.StreamId); } public static async Task AssertStreamEnd( this IReadableByteStream stream) { var headerBytes = new byte[FrameHeader.HeaderSize]; var res = await ReadWithTimeout(stream, new ArraySegment<byte>(headerBytes)); if (!res.EndOfStream) { var hdr = FrameHeader.DecodeFrom( new ArraySegment<byte>(headerBytes)); var msg = "Expected end of stream, but got " + FramePrinter.PrintFrameHeader(hdr); Assert.True(res.EndOfStream, msg); } Assert.Equal(0, res.BytesRead); } public static async Task AssertGoAwayReception( this IReadableByteStream stream, ErrorCode expectedErrorCode, uint lastStreamId) { var hdr = await stream.ReadFrameHeaderWithTimeout(); Assert.Equal(FrameType.GoAway, hdr.Type); Assert.Equal(0u, hdr.StreamId); Assert.Equal(0, hdr.Flags); Assert.InRange(hdr.Length, 8, 256); var goAwayBytes = new byte[hdr.Length]; await stream.ReadAllWithTimeout(new ArraySegment<byte>(goAwayBytes)); var goAwayData = GoAwayFrameData.DecodeFrom(new ArraySegment<byte>(goAwayBytes)); Assert.Equal(lastStreamId, goAwayData.Reason.LastStreamId); Assert.Equal(expectedErrorCode, goAwayData.Reason.ErrorCode); } public static async Task AssertResetStreamReception( this IReadableByteStream stream, uint expectedStreamId, ErrorCode expectedErrorCode) { var hdr = await stream.ReadFrameHeaderWithTimeout(); Assert.Equal(FrameType.ResetStream, hdr.Type); Assert.Equal(expectedStreamId, hdr.StreamId); Assert.Equal(0, hdr.Flags); Assert.Equal(ResetFrameData.Size, hdr.Length); var resetBytes = new byte[hdr.Length]; await stream.ReadAllWithTimeout(new ArraySegment<byte>(resetBytes)); var resetData = ResetFrameData.DecodeFrom(new ArraySegment<byte>(resetBytes)); Assert.Equal(expectedErrorCode, resetData.ErrorCode); } public static async Task AssertWindowUpdate( this IReadableByteStream stream, uint expectedStreamId, int increment) { var header = await stream.ReadFrameHeaderWithTimeout(); Assert.Equal(FrameType.WindowUpdate, header.Type); Assert.Equal(WindowUpdateData.Size, header.Length); Assert.Equal(0, header.Flags); Assert.Equal(expectedStreamId, header.StreamId); var buf = new byte[WindowUpdateData.Size]; await stream.ReadAllWithTimeout(new ArraySegment<byte>(buf)); var wu = WindowUpdateData.DecodeFrom(new ArraySegment<byte>(buf)); Assert.Equal(increment, wu.WindowSizeIncrement); } } }
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD. // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. using System; using System.Collections.Generic; using System.Threading.Tasks; using Xunit; namespace Moq.Tests { public class LookupOrFallbackDefaultValueProviderFixture { [Theory] [InlineData(typeof(int), default(int))] // plain value type [InlineData(typeof(float), default(float))] // plain value type [InlineData(typeof(int?), null)] // nullable [InlineData(typeof(int[]), default(int[]))] // emptyable [InlineData(typeof(IEnumerable<>), null)] // emptyable [InlineData(typeof(string), default(string))] // primitive reference type [InlineData(typeof(Exception), default(Exception))] // reference type public void Produces_default_when_no_factory_registered(Type type, object expected) { var provider = new Provider(); var actual = provider.GetDefaultValue(type); Assert.Equal(expected, actual); } [Theory] [InlineData(typeof(int), 42)] public void Falls_back_to_default_generation_strategy_when_no_handler_available(Type type, object fallbackValue) { var provider = new Provider((t, _) => t == type ? fallbackValue : throw new NotSupportedException()); provider.Deregister(type); var actual = provider.GetDefaultValue(type); Assert.Equal(fallbackValue, actual); } [Fact] public void Can_register_factory_for_specific_type() { var provider = new Provider(); provider.Register(typeof(Exception), (_, __) => new InvalidOperationException()); var actual = provider.GetDefaultValue(typeof(Exception)); Assert.NotNull(actual); Assert.IsType<InvalidOperationException>(actual); } [Fact] public void Can_register_factory_for_generic_type() { var provider = new Provider(); provider.Register(typeof(IEnumerable<>), (type, __) => { var elementType = type.GetGenericArguments()[0]; return Array.CreateInstance(elementType, 0); }); var actual = provider.GetDefaultValue(typeof(IEnumerable<int>)); Assert.NotNull(actual); Assert.IsType<int[]>(actual); } [Fact] public void Can_register_factory_for_array_type() { var provider = new Provider(); provider.Register(typeof(Array), (type, __) => { var elementType = type.GetElementType(); return Array.CreateInstance(elementType, 0); }); var actual = provider.GetDefaultValue(typeof(int[])); Assert.NotNull(actual); Assert.IsType<int[]>(actual); } [Fact] public void Produces_completed_Task() { var provider = new Provider(); var actual = (Task)provider.GetDefaultValue(typeof(Task)); Assert.True(actual.IsCompleted); } [Fact] public void Handling_of_Task_can_be_disabled() { var provider = new Provider(); provider.Deregister(typeof(Task)); var actual = provider.GetDefaultValue(typeof(Task)); Assert.Null(actual); } [Fact] public void Produces_completed_generic_Task() { const int expected = 42; var provider = new Provider(); provider.Register(typeof(int), (_, __) => expected); var actual = (Task<int>)provider.GetDefaultValue(typeof(Task<int>)); Assert.True(actual.IsCompleted); Assert.Equal(42, actual.Result); } [Fact] public void Handling_of_generic_Task_can_be_disabled() { var provider = new Provider(); provider.Deregister(typeof(Task<>)); var actual = provider.GetDefaultValue(typeof(Task<int>)); Assert.Null(actual); } [Fact] public void Produces_completed_ValueTask() { const int expectedResult = 42; var provider = new Provider(); provider.Register(typeof(int), (_, __) => expectedResult); var actual = (ValueTask<int>)provider.GetDefaultValue(typeof(ValueTask<int>)); Assert.True(actual.IsCompleted); Assert.Equal(42, actual.Result); } [Fact] public void Handling_of_ValueTask_can_be_disabled() { // If deregistration of ValueTask<> handling really works, the fallback strategy will produce // `default(ValueTask<int>)`, which equals a completed task containing 0 as result. So this test // needs to look different from the `Task<>` equivalent above. // We check for successful disabling of `ValueTask<>` handling indirectly, namely by // setting up a specific default value for `int` first, then we can verify that this value // does *not* get wrapped in a value task when we ask for `ValueTask<int>` const int unexpected = 42; var provider = new Provider(); provider.Register(typeof(int), (_, __) => unexpected); provider.Deregister(typeof(ValueTask<>)); var actual = (ValueTask<int>)provider.GetDefaultValue(typeof(ValueTask<int>)); Assert.Equal(default(ValueTask<int>), actual); Assert.NotEqual(unexpected, actual.Result); } [Fact] public void Produces_2_tuple() { const int expectedIntResult = 42; const string expectedStringResult = "*"; var provider = new Provider(); provider.Register(typeof(int), (_, __) => expectedIntResult); provider.Register(typeof(string), (_, __) => expectedStringResult); var actual = ((int, string))provider.GetDefaultValue(typeof(ValueTuple<int, string>)); Assert.Equal(expectedIntResult, actual.Item1); Assert.Equal(expectedStringResult, actual.Item2); } [Fact] public void Produces_3_tuple() { const int expectedIntResult = 42; const float expectedFloatResult = 3.1415f; const string expectedStringResult = "*"; var provider = new Provider(); provider.Register(typeof(int), (_, __) => expectedIntResult); provider.Register(typeof(float), (_, __) => expectedFloatResult); provider.Register(typeof(string), (_, __) => expectedStringResult); var actual = ((int, float, string))provider.GetDefaultValue(typeof(ValueTuple<int, float, string>)); Assert.Equal(expectedIntResult, actual.Item1); Assert.Equal(expectedFloatResult, actual.Item2); Assert.Equal(expectedStringResult, actual.Item3); } [Fact] public void Handling_of_ValueTuple_can_be_disabled() { // This test follows the same logic as the one above for `ValueTask<>`. const string unexpectedString = "*"; const int unexpectedInt = 42; var provider = new Provider(); provider.Register(typeof(string), (_, __) => unexpectedString); provider.Register(typeof(int), (_, __) => unexpectedInt); provider.Deregister(typeof(ValueTuple<,>)); var actual = ((string, int))provider.GetDefaultValue(typeof((string, int))); Assert.Equal((default(string), default(int)), actual); Assert.NotEqual((unexpectedString, unexpectedInt), actual); } /// <summary> /// Subclass of <see cref="LookupOrFallbackDefaultValueProvider"/> used as a test surrogate. /// </summary> private sealed class Provider : LookupOrFallbackDefaultValueProvider { private Mock<object> mock; private Func<Type, Mock, object> fallback; public Provider(Func<Type, Mock, object> fallback = null) { this.mock = new Mock<object>(); this.fallback = fallback; } public object GetDefaultValue(Type type) { return base.GetDefaultValue(type, mock); } new public void Deregister(Type factoryKey) { base.Deregister(factoryKey); } new public void Register(Type factoryKey, Func<Type, Mock, object> factory) { base.Register(factoryKey, factory); } protected override object GetFallbackDefaultValue(Type type, Mock mock) { return this.fallback?.Invoke(type, mock) ?? base.GetFallbackDefaultValue(type, mock); } } } }
/* ********************************************************************************************************** * The MIT License (MIT) * * * * Copyright (c) 2016 Hypermediasystems Ges. f. Software mbH * * Web: http://www.hypermediasystems.de * * This file is part of hmssp * * * * 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.Dynamic; using System.Reflection; using Newtonsoft.Json; namespace HMS.SP{ /// <summary> /// <para>https://msdn.microsoft.com/en-us/library/office/dn531432.aspx#bk_Group</para> /// </summary> public class Group : SPBase,iSP{ [JsonProperty("__HMSError")] public HMS.Util.__HMSError __HMSError_ { set; get; } [JsonProperty("__status")] public SP.__status __status_ { set; get; } [JsonProperty("__deferred")] public SP.__deferred __deferred_ { set; get; } [JsonProperty("__metadata")] public SP.__metadata __metadata_ { set; get; } public Dictionary<string, string> __rest; /// <summary> /// <para>Gets or sets a value that indicates whether the group members can edit membership in the group.</para> /// <para>R/W: RW</para> /// <para>Returned with resource:Yes</para> /// </summary> [JsonProperty("AllowMembersEditMembership")] public Boolean AllowMembersEditMembership_ { set; get; } /// <summary> /// <para>Gets or sets a value that indicates whether to allow users to request membership in the group and request to leave the group.</para> /// <para>R/W: RW</para> /// <para>Returned with resource:Yes</para> /// </summary> [JsonProperty("AllowRequestToJoinLeave")] public Boolean AllowRequestToJoinLeave_ { set; get; } /// <summary> /// <para>Gets or sets a value that indicates whether the request to join or leave the group can be accepted automatically.</para> /// <para>R/W: RW</para> /// <para>Returned with resource:No</para> /// </summary> [JsonProperty("AutoAcceptRequestToJoinLeave")] public Boolean AutoAcceptRequestToJoinLeave_ { set; get; } /// <summary> /// <para>Gets a value that indicates whether the current user can edit the membership of the group.</para> /// <para>R/W: R</para> /// <para>Returned with resource:No</para> /// </summary> [JsonProperty("CanCurrentUserEditMembership")] public Boolean CanCurrentUserEditMembership_ { set; get; } /// <summary> /// <para>Gets a value that indicates whether the current user can manage the group.</para> /// <para>R/W: R</para> /// <para>Returned with resource:No</para> /// </summary> [JsonProperty("CanCurrentUserManageGroup")] public Boolean CanCurrentUserManageGroup_ { set; get; } /// <summary> /// <para>Gets a value that indicates whether the current user can view the membership of the group.</para> /// <para>R/W: R</para> /// <para>Returned with resource:No</para> /// </summary> [JsonProperty("CanCurrentUserViewMembership")] public Boolean CanCurrentUserViewMembership_ { set; get; } /// <summary> /// <para>Gets or sets the description of the group.</para> /// <para>R/W: RW</para> /// <para>Returned with resource:Yes</para> /// </summary> [JsonProperty("Description")] public String Description_ { set; get; } /// <summary> /// <para>Gets or sets the description of the group.</para> /// <para>R/W: RW</para> /// <para>Returned with resource:Yes</para> /// </summary> [JsonProperty("DescriptionResource")] public SP.__deferred DescriptionResource_ { set; get; } /// <summary> /// <para>Gets a value that specifies the member identifier for the user or group.</para> /// <para>R/W: R</para> /// <para>Returned with resource:Yes</para> /// </summary> [JsonProperty("Id")] public Int32 Id_ { set; get; } /// <summary> /// <para>Gets a value that indicates whether this member should be hidden in the UI.</para> /// <para>R/W: R</para> /// <para>Returned with resource:Yes</para> /// </summary> [JsonProperty("IsHiddenInUI")] public Boolean IsHiddenInUI_ { set; get; } /// <summary> /// <para>Gets the name of the group.</para> /// <para>R/W: R</para> /// <para>Returned with resource:Yes</para> /// </summary> [JsonProperty("LoginName")] public String LoginName_ { set; get; } /// <summary> /// <para>Gets or sets a value that indicates whether only group members are allowed to view the membership of the group.</para> /// <para>R/W: RW</para> /// <para>Returned with resource:Yes</para> /// </summary> [JsonProperty("OnlyAllowMembersViewMembership")] public Boolean OnlyAllowMembersViewMembership_ { set; get; } /// <summary> /// <para>Gets or sets the owner of the group which can be a user or another group assigned permissions to control security.</para> /// <para>R/W: RW</para> /// <para>Returned with resource:No</para> /// </summary> [JsonProperty("Owner")] public SP.Principal Owner_ { set; get; } /// <summary> /// <para>Gets the name for the owner of this group.</para> /// <para>R/W: R</para> /// <para>Returned with resource:Yes</para> /// </summary> [JsonProperty("OwnerTitle")] public String OwnerTitle_ { set; get; } /// <summary> /// <para>Gets or sets the email address to which the requests of the membership are sent.</para> /// <para>R/W: RW</para> /// <para>Returned with resource:Yes</para> /// </summary> [JsonProperty("RequestToJoinLeaveEmailSetting")] public String RequestToJoinLeaveEmailSetting_ { set; get; } /// <summary> /// <para>Gets a value containing the type of the principal. Represents a bitwise SP.PrincipalType value: None = 0; User = 1; DistributionList = 2; SecurityGroup = 4; SharePointGroup = 8; All = 15.</para> /// <para>R/W: R</para> /// <para>Returned with resource:Yes</para> /// </summary> [JsonProperty("PrincipalType")] public Int32 PrincipalType_ { set; get; } /// <summary> /// <para>Gets or sets a value that specifies the name of the principal.</para> /// <para>R/W: RW</para> /// <para>Returned with resource:Yes</para> /// </summary> [JsonProperty("Title")] public String Title_ { set; get; } /// <summary> /// <para>Gets or sets a value that specifies the name of the principal.</para> /// <para>R/W: RW</para> /// <para>Returned with resource:Yes</para> /// </summary> [JsonProperty("TitleResource")] public SP.__deferred TitleResource_ { set; get; } /// <summary> /// <para>Gets a collection of user objects that represents all of the users in the group.</para> /// <para>R/W: R</para> /// <para>Returned with resource:No</para> /// </summary> [JsonProperty("Users")] public SP.UserCollection Users_ { set; get; } /// <summary> /// <para> Endpoints </para> /// </summary> static string[] endpoints = { "http://<site url>/_api/web/sitegroups(<group id>)", }; public Group(ExpandoObject expObj) { try { var use_EO = ((dynamic)expObj).entry.content.properties; HMS.SP.SPUtil.expando2obj(use_EO, this, typeof(Group)); } catch (Exception ex) { } } // used by Newtonsoft.JSON public Group() { } public Group(string json) { if( json == String.Empty ) return; dynamic jobject = Newtonsoft.Json.JsonConvert.DeserializeObject(json); dynamic refObj = jobject; if (jobject.d != null) refObj = jobject.d; string errInfo = ""; if (refObj.results != null) { if (refObj.results.Count > 1) errInfo = "Result is Collection, only 1. entry displayed."; refObj = refObj.results[0]; } List<string> usedFields = new List<string>(); usedFields.Add("__HMSError"); HMS.SP.SPUtil.dyn_ValueSet("__HMSError", refObj, this); usedFields.Add("__deferred"); this.__deferred_ = new SP.__deferred(HMS.SP.SPUtil.dyn_toString(refObj.__deferred)); usedFields.Add("__metadata"); this.__metadata_ = new SP.__metadata(HMS.SP.SPUtil.dyn_toString(refObj.__metadata)); usedFields.Add("AllowMembersEditMembership"); HMS.SP.SPUtil.dyn_ValueSet("AllowMembersEditMembership", refObj, this); usedFields.Add("AllowRequestToJoinLeave"); HMS.SP.SPUtil.dyn_ValueSet("AllowRequestToJoinLeave", refObj, this); usedFields.Add("AutoAcceptRequestToJoinLeave"); HMS.SP.SPUtil.dyn_ValueSet("AutoAcceptRequestToJoinLeave", refObj, this); usedFields.Add("CanCurrentUserEditMembership"); HMS.SP.SPUtil.dyn_ValueSet("CanCurrentUserEditMembership", refObj, this); usedFields.Add("CanCurrentUserManageGroup"); HMS.SP.SPUtil.dyn_ValueSet("CanCurrentUserManageGroup", refObj, this); usedFields.Add("CanCurrentUserViewMembership"); HMS.SP.SPUtil.dyn_ValueSet("CanCurrentUserViewMembership", refObj, this); usedFields.Add("Description"); HMS.SP.SPUtil.dyn_ValueSet("Description", refObj, this); usedFields.Add("DescriptionResource"); this.DescriptionResource_ = new SP.__deferred(HMS.SP.SPUtil.dyn_toString(refObj.DescriptionResource)); usedFields.Add("Id"); HMS.SP.SPUtil.dyn_ValueSet("Id", refObj, this); usedFields.Add("IsHiddenInUI"); HMS.SP.SPUtil.dyn_ValueSet("IsHiddenInUI", refObj, this); usedFields.Add("LoginName"); HMS.SP.SPUtil.dyn_ValueSet("LoginName", refObj, this); usedFields.Add("OnlyAllowMembersViewMembership"); HMS.SP.SPUtil.dyn_ValueSet("OnlyAllowMembersViewMembership", refObj, this); usedFields.Add("Owner"); this.Owner_ = new SP.Principal(HMS.SP.SPUtil.dyn_toString(refObj.Owner)); usedFields.Add("OwnerTitle"); HMS.SP.SPUtil.dyn_ValueSet("OwnerTitle", refObj, this); usedFields.Add("RequestToJoinLeaveEmailSetting"); HMS.SP.SPUtil.dyn_ValueSet("RequestToJoinLeaveEmailSetting", refObj, this); usedFields.Add("PrincipalType"); HMS.SP.SPUtil.dyn_ValueSet("PrincipalType", refObj, this); usedFields.Add("Title"); HMS.SP.SPUtil.dyn_ValueSet("Title", refObj, this); usedFields.Add("TitleResource"); this.TitleResource_ = new SP.__deferred(HMS.SP.SPUtil.dyn_toString(refObj.TitleResource)); usedFields.Add("Users"); this.Users_ = new SP.UserCollection(HMS.SP.SPUtil.dyn_toString(refObj.Users)); this.__rest = new Dictionary<string, string>(); var dyn = ((Newtonsoft.Json.Linq.JContainer)refObj).First; while (dyn != null) { string Name = ((Newtonsoft.Json.Linq.JProperty)dyn).Name; string Value = ((Newtonsoft.Json.Linq.JProperty)dyn).Value.ToString(); if ( !usedFields.Contains( Name )) this.__rest.Add( Name, Value); dyn = dyn.Next; } if( errInfo != "") this.__HMSError_.info = errInfo; } } }
//--------------------------------------------------------------------------- // // File: HtmlLexicalAnalyzer.cs // // Copyright (C) Microsoft Corporation. All rights reserved. // // Description: Lexical analyzer for Html-to-Xaml converter // //--------------------------------------------------------------------------- using System; using System.IO; using System.Diagnostics; using System.Text; namespace HTMLConverter { /// <summary> /// lexical analyzer class /// recognizes tokens as groups of characters separated by arbitrary amounts of whitespace /// also classifies tokens according to type /// </summary> internal class HtmlLexicalAnalyzer { // --------------------------------------------------------------------- // // Constructors // // --------------------------------------------------------------------- #region Constructors /// <summary> /// initializes the _inputStringReader member with the string to be read /// also sets initial values for _nextCharacterCode and _nextTokenType /// </summary> /// <param name="inputTextString"> /// text string to be parsed for xml content /// </param> internal HtmlLexicalAnalyzer(string inputTextString) { _inputStringReader = new StringReader(inputTextString); _nextCharacterCode = 0; _nextCharacter = ' '; _lookAheadCharacterCode = _inputStringReader.Read(); _lookAheadCharacter = (char)_lookAheadCharacterCode; _previousCharacter = ' '; _ignoreNextWhitespace = true; _nextToken = new StringBuilder(100); _nextTokenType = HtmlTokenType.Text; // read the first character so we have some value for the NextCharacter property this.GetNextCharacter(); } #endregion Constructors // --------------------------------------------------------------------- // // Internal methods // // --------------------------------------------------------------------- #region Internal Methods /// <summary> /// retrieves next recognizable token from input string /// and identifies its type /// if no valid token is found, the output parameters are set to null /// if end of stream is reached without matching any token, token type /// paramter is set to EOF /// </summary> internal void GetNextContentToken() { Debug.Assert(_nextTokenType != HtmlTokenType.EOF); _nextToken.Length = 0; if (this.IsAtEndOfStream) { _nextTokenType = HtmlTokenType.EOF; return; } if (this.IsAtTagStart) { this.GetNextCharacter(); if (this.NextCharacter == '/') { _nextToken.Append("</"); _nextTokenType = HtmlTokenType.ClosingTagStart; // advance this.GetNextCharacter(); _ignoreNextWhitespace = false; // Whitespaces after closing tags are significant } else { _nextTokenType = HtmlTokenType.OpeningTagStart; _nextToken.Append("<"); _ignoreNextWhitespace = true; // Whitespaces after opening tags are insignificant } } else if (this.IsAtDirectiveStart) { // either a comment or CDATA this.GetNextCharacter(); if (_lookAheadCharacter == '[') { // cdata this.ReadDynamicContent(); } else if (_lookAheadCharacter == '-') { this.ReadComment(); } else { // neither a comment nor cdata, should be something like DOCTYPE // skip till the next tag ender this.ReadUnknownDirective(); } } else { // read text content, unless you encounter a tag _nextTokenType = HtmlTokenType.Text; while (!this.IsAtTagStart && !this.IsAtEndOfStream && !this.IsAtDirectiveStart) { if (this.NextCharacter == '<' && !this.IsNextCharacterEntity && _lookAheadCharacter == '?') { // ignore processing directive this.SkipProcessingDirective(); } else { if (this.NextCharacter <= ' ') { // Respect xml:preserve or its equivalents for whitespace processing if (_ignoreNextWhitespace) { // Ignore repeated whitespaces } else { // Treat any control character sequence as one whitespace _nextToken.Append(' '); } _ignoreNextWhitespace = true; // and keep ignoring the following whitespaces } else { _nextToken.Append(this.NextCharacter); _ignoreNextWhitespace = false; } this.GetNextCharacter(); } } } } /// <summary> /// Unconditionally returns a token which is one of: TagEnd, EmptyTagEnd, Name, Atom or EndOfStream /// Does not guarantee token reader advancing. /// </summary> internal void GetNextTagToken() { _nextToken.Length = 0; if (this.IsAtEndOfStream) { _nextTokenType = HtmlTokenType.EOF; return; } this.SkipWhiteSpace(); if (this.NextCharacter == '>' && !this.IsNextCharacterEntity) { // &gt; should not end a tag, so make sure it's not an entity _nextTokenType = HtmlTokenType.TagEnd; _nextToken.Append('>'); this.GetNextCharacter(); // Note: _ignoreNextWhitespace must be set appropriately on tag start processing } else if (this.NextCharacter == '/' && _lookAheadCharacter == '>') { // could be start of closing of empty tag _nextTokenType = HtmlTokenType.EmptyTagEnd; _nextToken.Append("/>"); this.GetNextCharacter(); this.GetNextCharacter(); _ignoreNextWhitespace = false; // Whitespace after no-scope tags are sifnificant } else if (IsGoodForNameStart(this.NextCharacter)) { _nextTokenType = HtmlTokenType.Name; // starts a name // we allow character entities here // we do not throw exceptions here if end of stream is encountered // just stop and return whatever is in the token // if the parser is not expecting end of file after this it will call // the get next token function and throw an exception while (IsGoodForName(this.NextCharacter) && !this.IsAtEndOfStream) { _nextToken.Append(this.NextCharacter); this.GetNextCharacter(); } } else { // Unexpected type of token for a tag. Reprot one character as Atom, expecting that HtmlParser will ignore it. _nextTokenType = HtmlTokenType.Atom; _nextToken.Append(this.NextCharacter); this.GetNextCharacter(); } } /// <summary> /// Unconditionally returns equal sign token. Even if there is no /// real equal sign in the stream, it behaves as if it were there. /// Does not guarantee token reader advancing. /// </summary> internal void GetNextEqualSignToken() { Debug.Assert(_nextTokenType != HtmlTokenType.EOF); _nextToken.Length = 0; _nextToken.Append('='); _nextTokenType = HtmlTokenType.EqualSign; this.SkipWhiteSpace(); if (this.NextCharacter == '=') { // '=' is not in the list of entities, so no need to check for entities here this.GetNextCharacter(); } } /// <summary> /// Unconditionally returns an atomic value for an attribute /// Even if there is no appropriate token it returns Atom value /// Does not guarantee token reader advancing. /// </summary> internal void GetNextAtomToken() { Debug.Assert(_nextTokenType != HtmlTokenType.EOF); _nextToken.Length = 0; this.SkipWhiteSpace(); _nextTokenType = HtmlTokenType.Atom; if ((this.NextCharacter == '\'' || this.NextCharacter == '"') && !this.IsNextCharacterEntity) { char startingQuote = this.NextCharacter; this.GetNextCharacter(); // Consume all characters between quotes while (!(this.NextCharacter == startingQuote && !this.IsNextCharacterEntity) && !this.IsAtEndOfStream) { _nextToken.Append(this.NextCharacter); this.GetNextCharacter(); } if (this.NextCharacter == startingQuote) { this.GetNextCharacter(); } // complete the quoted value // NOTE: our recovery here is different from IE's // IE keeps reading until it finds a closing quote or end of file // if end of file, it treats current value as text // if it finds a closing quote at any point within the text, it eats everything between the quotes // TODO: Suggestion: // however, we could stop when we encounter end of file or an angle bracket of any kind // and assume there was a quote there // so the attribute value may be meaningless but it is never treated as text } else { while (!this.IsAtEndOfStream && !Char.IsWhiteSpace(this.NextCharacter) && this.NextCharacter != '>') { _nextToken.Append(this.NextCharacter); this.GetNextCharacter(); } } } #endregion Internal Methods // --------------------------------------------------------------------- // // Internal Properties // // --------------------------------------------------------------------- #region Internal Properties internal HtmlTokenType NextTokenType { get { return _nextTokenType; } } internal string NextToken { get { return _nextToken.ToString(); } } #endregion Internal Properties // --------------------------------------------------------------------- // // Private methods // // --------------------------------------------------------------------- #region Private Methods /// <summary> /// Advances a reading position by one character code /// and reads the next availbale character from a stream. /// This character becomes available as NextCharacter property. /// </summary> /// <remarks> /// Throws InvalidOperationException if attempted to be called on EndOfStream /// condition. /// </remarks> private void GetNextCharacter() { if (_nextCharacterCode == -1) { throw new InvalidOperationException("GetNextCharacter method called at the end of a stream"); } _previousCharacter = _nextCharacter; _nextCharacter = _lookAheadCharacter; _nextCharacterCode = _lookAheadCharacterCode; // next character not an entity as of now _isNextCharacterEntity = false; this.ReadLookAheadCharacter(); if (_nextCharacter == '&') { if (_lookAheadCharacter == '#') { // numeric entity - parse digits - &#DDDDD; int entityCode; entityCode = 0; this.ReadLookAheadCharacter(); // largest numeric entity is 7 characters for (int i = 0; i < 7 && Char.IsDigit(_lookAheadCharacter); i++) { entityCode = 10 * entityCode + (_lookAheadCharacterCode - (int)'0'); this.ReadLookAheadCharacter(); } if (_lookAheadCharacter == ';') { // correct format - advance this.ReadLookAheadCharacter(); _nextCharacterCode = entityCode; // if this is out of range it will set the character to '?' _nextCharacter = (char)_nextCharacterCode; // as far as we are concerned, this is an entity _isNextCharacterEntity = true; } else { // not an entity, set next character to the current lookahread character // we would have eaten up some digits _nextCharacter = _lookAheadCharacter; _nextCharacterCode = _lookAheadCharacterCode; this.ReadLookAheadCharacter(); _isNextCharacterEntity = false; } } else if (Char.IsLetter(_lookAheadCharacter)) { // entity is written as a string string entity = ""; // maximum length of string entities is 10 characters for (int i = 0; i < 10 && (Char.IsLetter(_lookAheadCharacter) || Char.IsDigit(_lookAheadCharacter)); i++) { entity += _lookAheadCharacter; this.ReadLookAheadCharacter(); } if (_lookAheadCharacter == ';') { // advance this.ReadLookAheadCharacter(); if (HtmlSchema.IsEntity(entity)) { _nextCharacter = HtmlSchema.EntityCharacterValue(entity); _nextCharacterCode = (int)_nextCharacter; _isNextCharacterEntity = true; } else { // just skip the whole thing - invalid entity // move on to the next character _nextCharacter = _lookAheadCharacter; _nextCharacterCode = _lookAheadCharacterCode; this.ReadLookAheadCharacter(); // not an entity _isNextCharacterEntity = false; } } else { // skip whatever we read after the ampersand // set next character and move on _nextCharacter = _lookAheadCharacter; this.ReadLookAheadCharacter(); _isNextCharacterEntity = false; } } } } private void ReadLookAheadCharacter() { if (_lookAheadCharacterCode != -1) { _lookAheadCharacterCode = _inputStringReader.Read(); _lookAheadCharacter = (char)_lookAheadCharacterCode; } } /// <summary> /// skips whitespace in the input string /// leaves the first non-whitespace character available in the NextCharacter property /// this may be the end-of-file character, it performs no checking /// </summary> private void SkipWhiteSpace() { // TODO: handle character entities while processing comments, cdata, and directives // TODO: SUGGESTION: we could check if lookahead and previous characters are entities also while (true) { if (_nextCharacter == '<' && (_lookAheadCharacter == '?' || _lookAheadCharacter == '!')) { this.GetNextCharacter(); if (_lookAheadCharacter == '[') { // Skip CDATA block and DTDs(?) while (!this.IsAtEndOfStream && !(_previousCharacter == ']' && _nextCharacter == ']' && _lookAheadCharacter == '>')) { this.GetNextCharacter(); } if (_nextCharacter == '>') { this.GetNextCharacter(); } } else { // Skip processing instruction, comments while (!this.IsAtEndOfStream && _nextCharacter != '>') { this.GetNextCharacter(); } if (_nextCharacter == '>') { this.GetNextCharacter(); } } } if (!Char.IsWhiteSpace(this.NextCharacter)) { break; } this.GetNextCharacter(); } } /// <summary> /// checks if a character can be used to start a name /// if this check is true then the rest of the name can be read /// </summary> /// <param name="character"> /// character value to be checked /// </param> /// <returns> /// true if the character can be the first character in a name /// false otherwise /// </returns> private bool IsGoodForNameStart(char character) { return character == '_' || Char.IsLetter(character); } /// <summary> /// checks if a character can be used as a non-starting character in a name /// uses the IsExtender and IsCombiningCharacter predicates to see /// if a character is an extender or a combining character /// </summary> /// <param name="character"> /// character to be checked for validity in a name /// </param> /// <returns> /// true if the character can be a valid part of a name /// </returns> private bool IsGoodForName(char character) { // we are not concerned with escaped characters in names // we assume that character entities are allowed as part of a name return this.IsGoodForNameStart(character) || character == '.' || character == '-' || character == ':' || Char.IsDigit(character) || IsCombiningCharacter(character) || IsExtender(character); } /// <summary> /// identifies a character as being a combining character, permitted in a name /// TODO: only a placeholder for now but later to be replaced with comparisons against /// the list of combining characters in the XML documentation /// </summary> /// <param name="character"> /// character to be checked /// </param> /// <returns> /// true if the character is a combining character, false otherwise /// </returns> private bool IsCombiningCharacter(char character) { // TODO: put actual code with checks against all combining characters here return false; } /// <summary> /// identifies a character as being an extender, permitted in a name /// TODO: only a placeholder for now but later to be replaced with comparisons against /// the list of extenders in the XML documentation /// </summary> /// <param name="character"> /// character to be checked /// </param> /// <returns> /// true if the character is an extender, false otherwise /// </returns> private bool IsExtender(char character) { // TODO: put actual code with checks against all extenders here return false; } /// <summary> /// skips dynamic content starting with '<![' and ending with ']>' /// </summary> private void ReadDynamicContent() { // verify that we are at dynamic content, which may include CDATA Debug.Assert(_previousCharacter == '<' && _nextCharacter == '!' && _lookAheadCharacter == '['); // Let's treat this as empty text _nextTokenType = HtmlTokenType.Text; _nextToken.Length = 0; // advance twice, once to get the lookahead character and then to reach the start of the cdata this.GetNextCharacter(); this.GetNextCharacter(); // NOTE: 10/12/2004: modified this function to check when called if's reading CDATA or something else // some directives may start with a <![ and then have some data and they will just end with a ]> // this function is modified to stop at the sequence ]> and not ]]> // this means that CDATA and anything else expressed in their own set of [] within the <! [...]> // directive cannot contain a ]> sequence. However it is doubtful that cdata could contain such // sequence anyway, it probably stops at the first ] while (!(_nextCharacter == ']' && _lookAheadCharacter == '>') && !this.IsAtEndOfStream) { // advance this.GetNextCharacter(); } if (!this.IsAtEndOfStream) { // advance, first to the last > this.GetNextCharacter(); // then advance past it to the next character after processing directive this.GetNextCharacter(); } } /// <summary> /// skips comments starting with '<!-' and ending with '-->' /// NOTE: 10/06/2004: processing changed, will now skip anything starting with /// the "<!-" sequence and ending in "!>" or "->", because in practice many html pages do not /// use the full comment specifying conventions /// </summary> private void ReadComment() { // verify that we are at a comment Debug.Assert(_previousCharacter == '<' && _nextCharacter == '!' && _lookAheadCharacter == '-'); // Initialize a token _nextTokenType = HtmlTokenType.Comment; _nextToken.Length = 0; // advance to the next character, so that to be at the start of comment value this.GetNextCharacter(); // get first '-' this.GetNextCharacter(); // get second '-' this.GetNextCharacter(); // get first character of comment content while (true) { // Read text until end of comment // Note that in many actual html pages comments end with "!>" (while xml standard is "-->") while (!this.IsAtEndOfStream && !(_nextCharacter == '-' && _lookAheadCharacter == '-' || _nextCharacter == '!' && _lookAheadCharacter == '>')) { _nextToken.Append(this.NextCharacter); this.GetNextCharacter(); } // Finish comment reading this.GetNextCharacter(); if (_previousCharacter == '-' && _nextCharacter == '-' && _lookAheadCharacter == '>') { // Standard comment end. Eat it and exit the loop this.GetNextCharacter(); // get '>' break; } else if (_previousCharacter == '!' && _nextCharacter == '>') { // Nonstandard but possible comment end - '!>'. Exit the loop break; } else { // Not an end. Save character and continue continue reading _nextToken.Append(_previousCharacter); continue; } } // Read end of comment combination if (_nextCharacter == '>') { this.GetNextCharacter(); } } /// <summary> /// skips past unknown directives that start with "<!" but are not comments or Cdata /// ignores content of such directives until the next ">" character /// applies to directives such as DOCTYPE, etc that we do not presently support /// </summary> private void ReadUnknownDirective() { // verify that we are at an unknown directive Debug.Assert(_previousCharacter == '<' && _nextCharacter == '!' && !(_lookAheadCharacter == '-' || _lookAheadCharacter == '[')); // Let's treat this as empty text _nextTokenType = HtmlTokenType.Text; _nextToken.Length = 0; // advance to the next character this.GetNextCharacter(); // skip to the first tag end we find while (!(_nextCharacter == '>' && !IsNextCharacterEntity) && !this.IsAtEndOfStream) { this.GetNextCharacter(); } if (!this.IsAtEndOfStream) { // advance past the tag end this.GetNextCharacter(); } } /// <summary> /// skips processing directives starting with the characters '<?' and ending with '?>' /// NOTE: 10/14/2004: IE also ends processing directives with a />, so this function is /// being modified to recognize that condition as well /// </summary> private void SkipProcessingDirective() { // verify that we are at a processing directive Debug.Assert(_nextCharacter == '<' && _lookAheadCharacter == '?'); // advance twice, once to get the lookahead character and then to reach the start of the drective this.GetNextCharacter(); this.GetNextCharacter(); while (!((_nextCharacter == '?' || _nextCharacter == '/') && _lookAheadCharacter == '>') && !this.IsAtEndOfStream) { // advance // we don't need to check for entities here because '?' is not an entity // and even though > is an entity there is no entity processing when reading lookahead character this.GetNextCharacter(); } if (!this.IsAtEndOfStream) { // advance, first to the last > this.GetNextCharacter(); // then advance past it to the next character after processing directive this.GetNextCharacter(); } } #endregion Private Methods // --------------------------------------------------------------------- // // Private Properties // // --------------------------------------------------------------------- #region Private Properties private char NextCharacter { get { return _nextCharacter; } } private bool IsAtEndOfStream { get { return _nextCharacterCode == -1; } } private bool IsAtTagStart { get { return _nextCharacter == '<' && (_lookAheadCharacter == '/' || IsGoodForNameStart(_lookAheadCharacter)) && !_isNextCharacterEntity; } } private bool IsAtTagEnd { // check if at end of empty tag or regular tag get { return (_nextCharacter == '>' || (_nextCharacter == '/' && _lookAheadCharacter == '>')) && !_isNextCharacterEntity; } } private bool IsAtDirectiveStart { get { return (_nextCharacter == '<' && _lookAheadCharacter == '!' && !this.IsNextCharacterEntity); } } private bool IsNextCharacterEntity { // check if next character is an entity get { return _isNextCharacterEntity; } } #endregion Private Properties // --------------------------------------------------------------------- // // Private Fields // // --------------------------------------------------------------------- #region Private Fields // string reader which will move over input text private StringReader _inputStringReader; // next character code read from input that is not yet part of any token // and the character it represents private int _nextCharacterCode; private char _nextCharacter; private int _lookAheadCharacterCode; private char _lookAheadCharacter; private char _previousCharacter; private bool _ignoreNextWhitespace; private bool _isNextCharacterEntity; // store token and type in local variables before copying them to output parameters StringBuilder _nextToken; HtmlTokenType _nextTokenType; #endregion Private Fields } }
using System; using System.Diagnostics; using System.Linq; using NUnit.Framework; using OpenCover.Framework.Manager; namespace OpenCover.Test.Framework.Manager { [TestFixture] public class MemoryManagerTests { private MemoryManager _manager; [SetUp] public void SetUp() { _manager = new MemoryManager(); _manager.Initialise("Local", "C#", new String[0]); } [TearDown] public void Teardown() { _manager.Dispose(); } [Test] public void DeactivateMemoryBuffer_SetsActive_ForBlock_False() { // arrange uint bufferId; _manager.AllocateMemoryBuffer(100, out bufferId); Assert.AreEqual(1, _manager.GetBlocks.Count); Assert.IsTrue(_manager.GetBlocks.First().Active); // act _manager.DeactivateMemoryBuffer(bufferId); // assert Assert.IsFalse(_manager.GetBlocks.First().Active); } [Test] public void RemoveDeactivatedBlocs_RemovesNonActiveBlock() { // arrange uint bufferId; _manager.AllocateMemoryBuffer(100, out bufferId); _manager.AllocateMemoryBuffer(100, out bufferId); Assert.AreEqual(2, _manager.GetBlocks.Count); Assert.AreEqual(2, _manager.GetBlocks.Count(b => b.Active)); _manager.DeactivateMemoryBuffer(bufferId); Assert.AreEqual(2, _manager.GetBlocks.Count); Assert.AreEqual(1, _manager.GetBlocks.Count(b => b.Active)); // act var block = _manager.GetBlocks.First(b => !b.Active); _manager.RemoveDeactivatedBlock(block); // assert Assert.AreEqual(1, _manager.GetBlocks.Count); Assert.AreEqual(1, _manager.GetBlocks.Count(b => b.Active)); } [Test] public void Cannot_RemoveDeactivatedBlock_OnActiveBlock() { // arrange uint bufferId; _manager.AllocateMemoryBuffer(100, out bufferId); Assert.AreEqual(1, _manager.GetBlocks.Count); Assert.AreEqual(1, _manager.GetBlocks.Count(b => b.Active)); // act var block = _manager.GetBlocks.First(); _manager.RemoveDeactivatedBlock(block); // assert Assert.AreEqual(1, _manager.GetBlocks.Count); Assert.AreEqual(1, _manager.GetBlocks.Count(b => b.Active)); } [Test] public void AllocateMemoryBuffer_WhenManagerNotInitialised_Ignored_OK() { using (var manager = new MemoryManager()) { // not initialised // arrange uint bufferId; // act & assert Assert.That(() => manager.AllocateMemoryBuffer(100, out bufferId), Throws.Nothing); } } [Test] public void InitialiseMemoryManagerTwice_Ignored_OK() { // act & assert Assert.That(() => _manager.Initialise("Local", "C#", new String[0]), Throws.Nothing); } [Test] public void AllocateMemoryBufferTwice_NewBufferAllocated_OK() { // arrange uint bufferId; // act _manager.AllocateMemoryBuffer(100, out bufferId); _manager.AllocateMemoryBuffer(100, out bufferId); // assert Assert.AreEqual(2, _manager.GetBlocks.Count); } [Test] public void DeactivateMemoryBufferTwice_Ignored_OK() { // arrange uint bufferId; _manager.AllocateMemoryBuffer(100, out bufferId); Assert.AreEqual(1, _manager.GetBlocks.Count); Assert.IsTrue(_manager.GetBlocks.First().Active); // act _manager.DeactivateMemoryBuffer(bufferId); // act & assert Assert.That(() => _manager.DeactivateMemoryBuffer(bufferId), Throws.Nothing); } [Test] public void DeactivateMemoryBufferAfterDisposed_Ignored_OK() { // arrange uint bufferId; _manager.AllocateMemoryBuffer(100, out bufferId); Assert.AreEqual(1, _manager.GetBlocks.Count); Assert.IsTrue(_manager.GetBlocks.First().Active); // act _manager.Dispose(); // act & assert Assert.That(() => _manager.DeactivateMemoryBuffer(bufferId), Throws.Nothing); } [Test] public void WaitForBlocksToClose_WaitsUntilBufferWaitCountExceededIfAnyActiveBlocks() { // arrange uint bufferId; _manager.AllocateMemoryBuffer(100, out bufferId); var timeAction = new Func<Action, long>(actionToTime => { var t = Stopwatch.StartNew(); actionToTime(); t.Stop(); return t.ElapsedMilliseconds; }); Assert.That(timeAction(() => _manager.WaitForBlocksToClose(0)), Is.LessThan(500)); Assert.That(timeAction(() => _manager.WaitForBlocksToClose(1)), Is.GreaterThanOrEqualTo(500).And.LessThan(1000)); Assert.That(timeAction(() => _manager.WaitForBlocksToClose(2)), Is.GreaterThanOrEqualTo(1000).And.LessThan(1500)); } [Test] public void WaitForBlocksToClose_StopsWaitingWhenNoActiveBlocks() { // arrange uint bufferId; _manager.AllocateMemoryBuffer(100, out bufferId); var timeAction = new Func<Action, long>(actionToTime => { var t = Stopwatch.StartNew(); actionToTime(); t.Stop(); return t.ElapsedMilliseconds; }); Assert.That(timeAction(() => _manager.WaitForBlocksToClose(1)), Is.GreaterThanOrEqualTo(500).And.LessThan(1000)); _manager.GetBlocks.First().Active = false; Assert.That(timeAction(() => _manager.WaitForBlocksToClose(1)), Is.LessThan(500)); } [Test] public void FetchRemainingBufferData_CallsActionForEachActiveBlock() { // arrange uint bufferId; _manager.AllocateMemoryBuffer(100, out bufferId); _manager.AllocateMemoryBuffer(100, out bufferId); uint count = 0; _manager.FetchRemainingBufferData( data => count++ ); Assert.That(count, Is.EqualTo(2)); Assert.That(_manager.GetBlocks.Count, Is.EqualTo(0)); } } }
// 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.Ecma335; using System.Runtime.CompilerServices; namespace System.Reflection.Metadata { using CorElementType = System.Reflection.Metadata.Ecma335.CorElementType; partial class MetadataReader { internal const string ClrPrefix = "<CLR>"; internal static readonly byte[] WinRTPrefix = new[] { (byte)'<', (byte)'W', (byte)'i', (byte)'n', (byte)'R', (byte)'T', (byte)'>' }; #region Projection Tables // Maps names of projected types to projection information for each type. // Both arrays are of the same length and sorted by the type name. private static string[] projectedTypeNames; private static ProjectionInfo[] projectionInfos; private struct ProjectionInfo { public readonly string WinRTNamespace; public readonly StringHandle.VirtualIndex ClrNamespace; public readonly StringHandle.VirtualIndex ClrName; public readonly AssemblyReferenceHandle.VirtualIndex AssemblyRef; public readonly TypeDefTreatment Treatment; public readonly bool IsIDisposable; public ProjectionInfo( string winRtNamespace, StringHandle.VirtualIndex clrNamespace, StringHandle.VirtualIndex clrName, AssemblyReferenceHandle.VirtualIndex clrAssembly, TypeDefTreatment treatment = TypeDefTreatment.RedirectedToClrType, bool isIDisposable = false) { this.WinRTNamespace = winRtNamespace; this.ClrNamespace = clrNamespace; this.ClrName = clrName; this.AssemblyRef = clrAssembly; this.Treatment = treatment; this.IsIDisposable = isIDisposable; } } private TypeDefTreatment GetWellKnownTypeDefinitionTreatment(TypeDefinitionHandle typeDef) { InitializeProjectedTypes(); StringHandle name = TypeDefTable.GetName(typeDef); int index = StringStream.BinarySearchRaw(projectedTypeNames, name); if (index < 0) { return TypeDefTreatment.None; } StringHandle namespaceName = TypeDefTable.GetNamespaceString(typeDef); if (StringStream.EqualsRaw(namespaceName, StringStream.GetVirtualValue(projectionInfos[index].ClrNamespace))) { return projectionInfos[index].Treatment; } // TODO: we can avoid this comparison if info.DotNetNamespace == info.WinRtNamespace if (StringStream.EqualsRaw(namespaceName, projectionInfos[index].WinRTNamespace)) { return projectionInfos[index].Treatment | TypeDefTreatment.MarkInternalFlag; } return TypeDefTreatment.None; } private int GetProjectionIndexForTypeReference(TypeReferenceHandle typeRef, out bool isIDisposable) { InitializeProjectedTypes(); int index = StringStream.BinarySearchRaw(projectedTypeNames, TypeRefTable.GetName(typeRef)); if (index >= 0 && StringStream.EqualsRaw(TypeRefTable.GetNamespace(typeRef), projectionInfos[index].WinRTNamespace)) { isIDisposable = projectionInfos[index].IsIDisposable; return index; } isIDisposable = false; return -1; } internal static AssemblyReferenceHandle GetProjectedAssemblyRef(int projectionIndex) { DebugCorlib.Assert(projectionInfos != null && projectionIndex >= 0 && projectionIndex < projectionInfos.Length); return AssemblyReferenceHandle.FromVirtualIndex(projectionInfos[projectionIndex].AssemblyRef); } internal static StringHandle GetProjectedName(int projectionIndex) { DebugCorlib.Assert(projectionInfos != null && projectionIndex >= 0 && projectionIndex < projectionInfos.Length); return StringHandle.FromVirtualIndex(projectionInfos[projectionIndex].ClrName); } internal static StringHandle GetProjectedNamespace(int projectionIndex) { DebugCorlib.Assert(projectionInfos != null && projectionIndex >= 0 && projectionIndex < projectionInfos.Length); return StringHandle.FromVirtualIndex(projectionInfos[projectionIndex].ClrNamespace); } private static void InitializeProjectedTypes() { if (projectedTypeNames == null || projectionInfos == null) { var systemRuntimeWindowsRuntime = AssemblyReferenceHandle.VirtualIndex.System_Runtime_WindowsRuntime; var systemRuntime = AssemblyReferenceHandle.VirtualIndex.System_Runtime; var systemObjectModel = AssemblyReferenceHandle.VirtualIndex.System_ObjectModel; var systemRuntimeWindowsUiXaml = AssemblyReferenceHandle.VirtualIndex.System_Runtime_WindowsRuntime_UI_Xaml; var systemRuntimeInterop = AssemblyReferenceHandle.VirtualIndex.System_Runtime_InteropServices_WindowsRuntime; var systemNumericsVectors = AssemblyReferenceHandle.VirtualIndex.System_Numerics_Vectors; // sorted by name var keys = new string[50]; var values = new ProjectionInfo[50]; int k = 0, v = 0; // WARNING: Keys must be sorted by name and must only contain ASCII characters. WinRTNamespace must also be ASCII only. keys[k++] = "AttributeTargets"; values[v++] = new ProjectionInfo("Windows.Foundation.Metadata", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.AttributeTargets, systemRuntime); keys[k++] = "AttributeUsageAttribute"; values[v++] = new ProjectionInfo("Windows.Foundation.Metadata", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.AttributeUsageAttribute, systemRuntime, treatment: TypeDefTreatment.RedirectedToClrAttribute); keys[k++] = "Color"; values[v++] = new ProjectionInfo("Windows.UI", StringHandle.VirtualIndex.Windows_UI, StringHandle.VirtualIndex.Color, systemRuntimeWindowsRuntime); keys[k++] = "CornerRadius"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.CornerRadius, systemRuntimeWindowsUiXaml); keys[k++] = "DateTime"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.DateTimeOffset, systemRuntime); keys[k++] = "Duration"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.Duration, systemRuntimeWindowsUiXaml); keys[k++] = "DurationType"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.DurationType, systemRuntimeWindowsUiXaml); keys[k++] = "EventHandler`1"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.EventHandler1, systemRuntime); keys[k++] = "EventRegistrationToken"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System_Runtime_InteropServices_WindowsRuntime, StringHandle.VirtualIndex.EventRegistrationToken, systemRuntimeInterop); keys[k++] = "GeneratorPosition"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Controls.Primitives", StringHandle.VirtualIndex.Windows_UI_Xaml_Controls_Primitives, StringHandle.VirtualIndex.GeneratorPosition, systemRuntimeWindowsUiXaml); keys[k++] = "GridLength"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.GridLength, systemRuntimeWindowsUiXaml); keys[k++] = "GridUnitType"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.GridUnitType, systemRuntimeWindowsUiXaml); keys[k++] = "HResult"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.Exception, systemRuntime); keys[k++] = "IBindableIterable"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections, StringHandle.VirtualIndex.IEnumerable, systemRuntime); keys[k++] = "IBindableVector"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections, StringHandle.VirtualIndex.IList, systemRuntime); keys[k++] = "IClosable"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.IDisposable, systemRuntime, isIDisposable: true); keys[k++] = "ICommand"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Input", StringHandle.VirtualIndex.System_Windows_Input, StringHandle.VirtualIndex.ICommand, systemObjectModel); keys[k++] = "IIterable`1"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IEnumerable1, systemRuntime); keys[k++] = "IKeyValuePair`2"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.KeyValuePair2, systemRuntime); keys[k++] = "IMapView`2"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IReadOnlyDictionary2, systemRuntime); keys[k++] = "IMap`2"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IDictionary2, systemRuntime); keys[k++] = "INotifyCollectionChanged"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections_Specialized, StringHandle.VirtualIndex.INotifyCollectionChanged, systemObjectModel); keys[k++] = "INotifyPropertyChanged"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Data", StringHandle.VirtualIndex.System_ComponentModel, StringHandle.VirtualIndex.INotifyPropertyChanged, systemObjectModel); keys[k++] = "IReference`1"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.Nullable1, systemRuntime); keys[k++] = "IVectorView`1"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IReadOnlyList1, systemRuntime); keys[k++] = "IVector`1"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IList1, systemRuntime); keys[k++] = "KeyTime"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media.Animation", StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Animation, StringHandle.VirtualIndex.KeyTime, systemRuntimeWindowsUiXaml); keys[k++] = "Matrix"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media", StringHandle.VirtualIndex.Windows_UI_Xaml_Media, StringHandle.VirtualIndex.Matrix, systemRuntimeWindowsUiXaml); keys[k++] = "Matrix3D"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media.Media3D", StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Media3D, StringHandle.VirtualIndex.Matrix3D, systemRuntimeWindowsUiXaml); keys[k++] = "Matrix3x2"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Matrix3x2, systemNumericsVectors); keys[k++] = "Matrix4x4"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Matrix4x4, systemNumericsVectors); keys[k++] = "NotifyCollectionChangedAction"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections_Specialized, StringHandle.VirtualIndex.NotifyCollectionChangedAction, systemObjectModel); keys[k++] = "NotifyCollectionChangedEventArgs"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections_Specialized, StringHandle.VirtualIndex.NotifyCollectionChangedEventArgs, systemObjectModel); keys[k++] = "NotifyCollectionChangedEventHandler"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections_Specialized, StringHandle.VirtualIndex.NotifyCollectionChangedEventHandler, systemObjectModel); keys[k++] = "Plane"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Plane, systemNumericsVectors); keys[k++] = "Point"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.Windows_Foundation, StringHandle.VirtualIndex.Point, systemRuntimeWindowsRuntime); keys[k++] = "PropertyChangedEventArgs"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Data", StringHandle.VirtualIndex.System_ComponentModel, StringHandle.VirtualIndex.PropertyChangedEventArgs, systemObjectModel); keys[k++] = "PropertyChangedEventHandler"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Data", StringHandle.VirtualIndex.System_ComponentModel, StringHandle.VirtualIndex.PropertyChangedEventHandler, systemObjectModel); keys[k++] = "Quaternion"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Quaternion, systemNumericsVectors); keys[k++] = "Rect"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.Windows_Foundation, StringHandle.VirtualIndex.Rect, systemRuntimeWindowsRuntime); keys[k++] = "RepeatBehavior"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media.Animation", StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Animation, StringHandle.VirtualIndex.RepeatBehavior, systemRuntimeWindowsUiXaml); keys[k++] = "RepeatBehaviorType"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media.Animation", StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Animation, StringHandle.VirtualIndex.RepeatBehaviorType, systemRuntimeWindowsUiXaml); keys[k++] = "Size"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.Windows_Foundation, StringHandle.VirtualIndex.Size, systemRuntimeWindowsRuntime); keys[k++] = "Thickness"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.Thickness, systemRuntimeWindowsUiXaml); keys[k++] = "TimeSpan"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.TimeSpan, systemRuntime); keys[k++] = "TypeName"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.Type, systemRuntime); keys[k++] = "Uri"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.Uri, systemRuntime); keys[k++] = "Vector2"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Vector2, systemNumericsVectors); keys[k++] = "Vector3"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Vector3, systemNumericsVectors); keys[k++] = "Vector4"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Vector4, systemNumericsVectors); DebugCorlib.Assert(k == keys.Length && v == keys.Length && k == v); AssertSorted(keys); projectedTypeNames = keys; projectionInfos = values; } } [Conditional("DEBUG")] private static void AssertSorted(string[] keys) { for (int i = 0; i < keys.Length - 1; i++) { DebugCorlib.Assert(String.CompareOrdinal(keys[i], keys[i + 1]) < 0); } } // test only internal static string[] GetProjectedTypeNames() { InitializeProjectedTypes(); return projectedTypeNames; } #endregion private static uint TreatmentAndRowId(byte treatment, uint rowId) { return ((uint)treatment << TokenTypeIds.RowIdBitCount) | rowId; } #region TypeDef [MethodImplAttribute(MethodImplOptions.NoInlining)] internal uint CalculateTypeDefTreatmentAndRowId(TypeDefinitionHandle handle) { DebugCorlib.Assert(metadataKind != MetadataKind.Ecma335); TypeDefTreatment treatment; TypeAttributes flags = TypeDefTable.GetFlags(handle); Handle extends = TypeDefTable.GetExtends(handle); if ((flags & TypeAttributes.WindowsRuntime) != 0) { if (metadataKind == MetadataKind.WindowsMetadata) { treatment = GetWellKnownTypeDefinitionTreatment(handle); if (treatment != TypeDefTreatment.None) { return TreatmentAndRowId((byte)treatment, handle.RowId); } // Is this an attribute? if (extends.Kind == HandleKind.TypeReference && IsSystemAttribute((TypeReferenceHandle)extends)) { treatment = TypeDefTreatment.NormalAttribute; } else { treatment = TypeDefTreatment.NormalNonAttribute; } } else if (metadataKind == MetadataKind.ManagedWindowsMetadata && NeedsWinRTPrefix(flags, extends)) { // WinMDExp emits two versions of RuntimeClasses and Enums: // // public class Foo {} // the WinRT reference class // internal class <CLR>Foo {} // the implementation class that we want WinRT consumers to ignore // // The adapter's job is to undo WinMDExp's transformations. I.e. turn the above into: // // internal class <WinRT>Foo {} // the WinRT reference class that we want CLR consumers to ignore // public class Foo {} // the implementation class // // We only add the <WinRT> prefix here since the WinRT view is the only view that is marked WindowsRuntime // De-mangling the CLR name is done below. // tomat: The CLR adapter implements a back-compat quirk: Enums exported with an older WinMDExp have only one version // not marked with tdSpecialName. These enums should *not* be mangled and flipped to private. // We don't implement this flag since the WinMDs producted by the older WinMDExp are not used in the wild. treatment = TypeDefTreatment.PrefixWinRTName; } else { treatment = TypeDefTreatment.None; } // Scan through Custom Attributes on type, looking for interesting bits. We only // need to do this for RuntimeClasses if ((treatment == TypeDefTreatment.PrefixWinRTName || treatment == TypeDefTreatment.NormalNonAttribute)) { if ((flags & TypeAttributes.Interface) == 0 && HasAttribute(handle, "Windows.UI.Xaml", "TreatAsAbstractComposableClassAttribute")) { treatment |= TypeDefTreatment.MarkAbstractFlag; } } } else if (metadataKind == MetadataKind.ManagedWindowsMetadata && IsClrImplementationType(handle)) { // <CLR> implementation classes are not marked WindowsRuntime, but still need to be modified // by the adapter. treatment = TypeDefTreatment.UnmangleWinRTName; } else { treatment = TypeDefTreatment.None; } return TreatmentAndRowId((byte)treatment, handle.RowId); } private bool IsClrImplementationType(TypeDefinitionHandle typeDef) { var attrs = TypeDefTable.GetFlags(typeDef); if ((attrs & (TypeAttributes.VisibilityMask | TypeAttributes.SpecialName)) != TypeAttributes.SpecialName) { return false; } return StringStream.StartsWithRaw(TypeDefTable.GetName(typeDef), ClrPrefix); } #endregion #region TypeRef internal uint CalculateTypeRefTreatmentAndRowId(TypeReferenceHandle handle) { DebugCorlib.Assert(metadataKind != MetadataKind.Ecma335); bool isIDisposable; int projectionIndex = GetProjectionIndexForTypeReference(handle, out isIDisposable); if (projectionIndex >= 0) { return TreatmentAndRowId((byte)TypeRefTreatment.UseProjectionInfo, (uint)projectionIndex); } else { return TreatmentAndRowId((byte)GetSpecialTypeRefTreatment(handle), handle.RowId); } } private TypeRefTreatment GetSpecialTypeRefTreatment(TypeReferenceHandle handle) { if (StringStream.EqualsRaw(TypeRefTable.GetNamespace(handle), "System")) { StringHandle name = TypeRefTable.GetName(handle); if (StringStream.EqualsRaw(name, "MulticastDelegate")) { return TypeRefTreatment.SystemDelegate; } if (StringStream.EqualsRaw(name, "Attribute")) { return TypeRefTreatment.SystemAttribute; } } return TypeRefTreatment.None; } private bool IsSystemAttribute(TypeReferenceHandle handle) { return StringStream.EqualsRaw(TypeRefTable.GetNamespace(handle), "System") && StringStream.EqualsRaw(TypeRefTable.GetName(handle), "Attribute"); } private bool IsSystemEnum(TypeReferenceHandle handle) { return StringStream.EqualsRaw(TypeRefTable.GetNamespace(handle), "System") && StringStream.EqualsRaw(TypeRefTable.GetName(handle), "Enum"); } private bool NeedsWinRTPrefix(TypeAttributes flags, Handle extends) { if ((flags & (TypeAttributes.VisibilityMask | TypeAttributes.Interface)) != TypeAttributes.Public) { return false; } if (extends.Kind != HandleKind.TypeReference) { return false; } // Check if the type is a delegate, struct, or attribute TypeReferenceHandle extendsRefHandle = (TypeReferenceHandle)extends; if (StringStream.EqualsRaw(TypeRefTable.GetNamespace(extendsRefHandle), "System")) { StringHandle nameHandle = TypeRefTable.GetName(extendsRefHandle); if (StringStream.EqualsRaw(nameHandle, "MulticastDelegate") || StringStream.EqualsRaw(nameHandle, "ValueType") || StringStream.EqualsRaw(nameHandle, "Attribute")) { return false; } } return true; } #endregion #region MethodDef private uint CalculateMethodDefTreatmentAndRowId(MethodDefinitionHandle methodDef) { MethodDefTreatment treatment = MethodDefTreatment.Implementation; TypeDefinitionHandle parentTypeDef = GetDeclaringType(methodDef); TypeAttributes parentFlags = TypeDefTable.GetFlags(parentTypeDef); if ((parentFlags & TypeAttributes.WindowsRuntime) != 0) { if (IsClrImplementationType(parentTypeDef)) { treatment = MethodDefTreatment.Implementation; } else if (parentFlags.IsNested()) { treatment = MethodDefTreatment.Implementation; } else if ((parentFlags & TypeAttributes.Interface) != 0) { treatment = MethodDefTreatment.InterfaceMethod; } else if (metadataKind == MetadataKind.ManagedWindowsMetadata && (parentFlags & TypeAttributes.Public) == 0) { treatment = MethodDefTreatment.Implementation; } else { treatment = MethodDefTreatment.Other; var parentBaseType = TypeDefTable.GetExtends(parentTypeDef); if (parentBaseType.Kind == HandleKind.TypeReference) { switch (GetSpecialTypeRefTreatment((TypeReferenceHandle)parentBaseType)) { case TypeRefTreatment.SystemAttribute: treatment = MethodDefTreatment.AttributeMethod; break; case TypeRefTreatment.SystemDelegate: treatment = MethodDefTreatment.DelegateMethod | MethodDefTreatment.MarkPublicFlag; break; } } } } if (treatment == MethodDefTreatment.Other) { // we want to hide the method if it implements // only redirected interfaces // We also want to check if the methodImpl is IClosable.Close, // so we can change the name bool seenRedirectedInterfaces = false; bool seenNonRedirectedInterfaces = false; bool isIClosableClose = false; foreach (var methodImplHandle in new MethodImplementationHandleCollection(this, parentTypeDef)) { MethodImplementation methodImpl = GetMethodImplementation(methodImplHandle); if (methodImpl.MethodBody == methodDef) { Handle declaration = methodImpl.MethodDeclaration; // See if this MethodImpl implements a redirected interface // In WinMD, MethodImpl will always use MemberRef and TypeRefs to refer to redirected interfaces, // even if they are in the same module. if (declaration.Kind == HandleKind.MemberReference && ImplementsRedirectedInterface((MemberReferenceHandle)declaration, out isIClosableClose)) { seenRedirectedInterfaces = true; if (isIClosableClose) { // This method implements IClosable.Close // Let's rename to IDisposable later // Once we know this implements IClosable.Close, we are done // looking break; } } else { // Now we know this implements a non-redirected interface // But we need to keep looking, just in case we got a methodimpl that // implements the IClosable.Close method and needs to be renamed seenNonRedirectedInterfaces = true; } } } if (isIClosableClose) { treatment = MethodDefTreatment.DisposeMethod; } else if (seenRedirectedInterfaces && !seenNonRedirectedInterfaces) { // Only hide if all the interfaces implemented are redirected treatment = MethodDefTreatment.HiddenInterfaceImplementation; } } // If treatment is other, then this is a non-managed WinRT runtime class definition // Find out about various bits that we apply via attributes and name parsing if (treatment == MethodDefTreatment.Other) { treatment |= GetMethodTreatmentFromCustomAttributes(methodDef); } return TreatmentAndRowId((byte)treatment, methodDef.RowId); } private MethodDefTreatment GetMethodTreatmentFromCustomAttributes(MethodDefinitionHandle methodDef) { MethodDefTreatment treatment = 0; foreach (var caHandle in GetCustomAttributes(methodDef)) { StringHandle namespaceHandle, nameHandle; if (!GetAttributeTypeNameRaw(caHandle, out namespaceHandle, out nameHandle)) { continue; } DebugCorlib.Assert(!namespaceHandle.IsVirtual && !nameHandle.IsVirtual); if (StringStream.EqualsRaw(namespaceHandle, "Windows.UI.Xaml")) { if (StringStream.EqualsRaw(nameHandle, "TreatAsPublicMethodAttribute")) { treatment |= MethodDefTreatment.MarkPublicFlag; } if (StringStream.EqualsRaw(nameHandle, "TreatAsAbstractMethodAttribute")) { treatment |= MethodDefTreatment.MarkAbstractFlag; } } } return treatment; } #endregion #region FieldDef /// <summary> /// The backing field of a WinRT enumeration type is not public although the backing fields /// of managed enumerations are. To allow managed languages to directly access this field, /// it is made public by the metadata adapter. /// </summary> private uint CalculateFieldDefTreatmentAndRowId(FieldDefinitionHandle handle) { var flags = FieldTable.GetFlags(handle); FieldDefTreatment treatment = FieldDefTreatment.None; if ((flags & FieldAttributes.RTSpecialName) != 0 && StringStream.EqualsRaw(FieldTable.GetName(handle), "value__")) { TypeDefinitionHandle typeDef = GetDeclaringType(handle); Handle baseTypeHandle = TypeDefTable.GetExtends(typeDef); if (baseTypeHandle.Kind == HandleKind.TypeReference) { var typeRef = (TypeReferenceHandle)baseTypeHandle; if (StringStream.EqualsRaw(TypeRefTable.GetName(typeRef), "Enum") && StringStream.EqualsRaw(TypeRefTable.GetNamespace(typeRef), "System")) { treatment = FieldDefTreatment.EnumValue; } } } return TreatmentAndRowId((byte)treatment, handle.RowId); } #endregion #region MemberRef private uint CalculateMemberRefTreatmentAndRowId(MemberReferenceHandle handle) { MemberRefTreatment treatment; // We need to rename the MemberRef for IClosable.Close as well // so that the MethodImpl for the Dispose method can be correctly shown // as IDisposable.Dispose instead of IDisposable.Close bool isIDisposable; if (ImplementsRedirectedInterface(handle, out isIDisposable) && isIDisposable) { treatment = MemberRefTreatment.Dispose; } else { treatment = MemberRefTreatment.None; } return TreatmentAndRowId((byte)treatment, handle.RowId); } /// <summary> /// We want to know if a given method implements a redirected interface. /// For example, if we are given the method RemoveAt on a class "A" /// which implements the IVector interface (which is redirected /// to IList in .NET) then this method would return true. The most /// likely reason why we would want to know this is that we wish to hide /// (mark private) all methods which implement methods on a redirected /// interface. /// </summary> /// <param name="memberRef">The declaration token for the method</param> /// <param name="isIDisposable"> /// Returns true if the redirected interface is <see cref="IDisposable"/>. /// </param> /// <returns>True if the method implements a method on a redirected interface. /// False otherwise.</returns> private bool ImplementsRedirectedInterface(MemberReferenceHandle memberRef, out bool isIDisposable) { isIDisposable = false; Handle parent = MemberRefTable.GetClass(memberRef); TypeReferenceHandle typeRef; if (parent.Kind == HandleKind.TypeReference) { typeRef = (TypeReferenceHandle)parent; } else if (parent.Kind == HandleKind.TypeSpecification) { BlobHandle blob = TypeSpecTable.GetSignature((TypeSpecificationHandle)parent); BlobReader sig = BlobStream.GetBlobReader(blob); if (sig.Length < 2 || sig.ReadByte() != (byte)CorElementType.ELEMENT_TYPE_GENERICINST || sig.ReadByte() != (byte)CorElementType.ELEMENT_TYPE_CLASS) { return false; } Handle token = sig.ReadTypeHandle(); if (token.Kind != HandleKind.TypeReference) { return false; } typeRef = (TypeReferenceHandle)token; } else { return false; } return GetProjectionIndexForTypeReference(typeRef, out isIDisposable) >= 0; } #endregion #region AssemblyRef private uint FindMscorlibAssemblyRefNoProjection() { for (uint i = 1; i <= AssemblyRefTable.NumberOfNonVirtualRows; i++) { if (StringStream.EqualsRaw(AssemblyRefTable.GetName(i), "mscorlib")) { return i; } } throw new BadImageFormatException(MetadataResources.WinMDMissingMscorlibRef); } #endregion #region CustomAttribute internal CustomAttributeValueTreatment CalculateCustomAttributeValueTreatment(CustomAttributeHandle handle) { DebugCorlib.Assert(metadataKind != MetadataKind.Ecma335); var parent = CustomAttributeTable.GetParent(handle); // Check for Windows.Foundation.Metadata.AttributeUsageAttribute. // WinMD rules: // - The attribute is only applicable on TypeDefs. // - Constructor must be a MemberRef with TypeRef. if (!IsWindowsAttributeUsageAttribute(parent, handle)) { return CustomAttributeValueTreatment.None; } var targetTypeDef = (TypeDefinitionHandle)parent; if (StringStream.EqualsRaw(TypeDefTable.GetNamespaceString(targetTypeDef), "Windows.Foundation.Metadata")) { if (StringStream.EqualsRaw(TypeDefTable.GetName(targetTypeDef), "VersionAttribute")) { return CustomAttributeValueTreatment.AttributeUsageVersionAttribute; } if (StringStream.EqualsRaw(TypeDefTable.GetName(targetTypeDef), "DeprecatedAttribute")) { return CustomAttributeValueTreatment.AttributeUsageDeprecatedAttribute; } } bool allowMultiple = HasAttribute(targetTypeDef, "Windows.Foundation.Metadata", "AllowMultipleAttribute"); return allowMultiple ? CustomAttributeValueTreatment.AttributeUsageAllowMultiple : CustomAttributeValueTreatment.AttributeUsageAllowSingle; } private bool IsWindowsAttributeUsageAttribute(Handle targetType, CustomAttributeHandle attributeHandle) { // Check for Windows.Foundation.Metadata.AttributeUsageAttribute. // WinMD rules: // - The attribute is only applicable on TypeDefs. // - Constructor must be a MemberRef with TypeRef. if (targetType.Kind != HandleKind.TypeDefinition) { return false; } var attributeCtor = CustomAttributeTable.GetConstructor(attributeHandle); if (attributeCtor.Kind != HandleKind.MemberReference) { return false; } var attributeType = MemberRefTable.GetClass((MemberReferenceHandle)attributeCtor); if (attributeType.Kind != HandleKind.TypeReference) { return false; } var attributeTypeRef = (TypeReferenceHandle)attributeType; return StringStream.EqualsRaw(TypeRefTable.GetName(attributeTypeRef), "AttributeUsageAttribute") && StringStream.EqualsRaw(TypeRefTable.GetNamespace(attributeTypeRef), "Windows.Foundation.Metadata"); } private bool HasAttribute(Handle token, string asciiNamespaceName, string asciiTypeName) { foreach (var caHandle in GetCustomAttributes(token)) { StringHandle namespaceName, typeName; if (GetAttributeTypeNameRaw(caHandle, out namespaceName, out typeName) && StringStream.EqualsRaw(typeName, asciiTypeName) && StringStream.EqualsRaw(namespaceName, asciiNamespaceName)) { return true; } } return false; } private bool GetAttributeTypeNameRaw(CustomAttributeHandle caHandle, out StringHandle namespaceName, out StringHandle typeName) { namespaceName = typeName = default(StringHandle); Handle typeDefOrRef = GetAttributeTypeRaw(caHandle); if (typeDefOrRef.IsNil) { return false; } if (typeDefOrRef.Kind == HandleKind.TypeReference) { TypeReferenceHandle typeRef = (TypeReferenceHandle)typeDefOrRef; var resolutionScope = TypeRefTable.GetResolutionScope(typeRef); if (!resolutionScope.IsNil && resolutionScope.Kind == HandleKind.TypeReference) { // we don't need to handle nested types return false; } // other resolution scopes don't affect full name typeName = TypeRefTable.GetName(typeRef); namespaceName = TypeRefTable.GetNamespace(typeRef); } else if (typeDefOrRef.Kind == HandleKind.TypeDefinition) { TypeDefinitionHandle typeDef = (TypeDefinitionHandle)typeDefOrRef; if (TypeDefTable.GetFlags(typeDef).IsNested()) { // we don't need to handle nested types return false; } typeName = TypeDefTable.GetName(typeDef); namespaceName = TypeDefTable.GetNamespaceString(typeDef); } else { // invalid metadata return false; } return true; } /// <summary> /// Returns the type definition or reference handle of the attribute type. /// </summary> /// <returns><see cref="TypeDefinitionHandle"/> or <see cref="TypeReferenceHandle"/> or nil token if the metadata is invalid and the type can't be determined.</returns> private Handle GetAttributeTypeRaw(CustomAttributeHandle handle) { var ctor = CustomAttributeTable.GetConstructor(handle); if (ctor.Kind == HandleKind.MethodDefinition) { return GetDeclaringType((MethodDefinitionHandle)ctor); } if (ctor.Kind == HandleKind.MemberReference) { // In general the parent can be MethodDef, ModuleRef, TypeDef, TypeRef, or TypeSpec. // For attributes only TypeDef and TypeRef are applicable. Handle typeDefOrRef = MemberRefTable.GetClass((MemberReferenceHandle)ctor); HandleKind handleType = typeDefOrRef.Kind; if (handleType == HandleKind.TypeReference || handleType == HandleKind.TypeDefinition) { return typeDefOrRef; } } return default(Handle); } #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; using static System.Runtime.Intrinsics.X86.Sse; using static System.Runtime.Intrinsics.X86.Sse2; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void InsertSingle48() { var test = new InsertVector128Test__InsertSingle48(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class InsertVector128Test__InsertSingle48 { private struct TestStruct { public Vector128<Single> _fld1; public Vector128<Single> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(InsertVector128Test__InsertSingle48 testClass) { var result = Sse41.Insert(_fld1, _fld2, 48); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private SimpleBinaryOpTest__DataTable<Single, Single, Single> _dataTable; static InsertVector128Test__InsertSingle48() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public InsertVector128Test__InsertSingle48() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new SimpleBinaryOpTest__DataTable<Single, Single, Single>(_data1, _data2, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse41.Insert( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr), 48 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse41.Insert( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), LoadVector128((Single*)(_dataTable.inArray2Ptr)), 48 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse41.Insert( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)), 48 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr), (byte)48 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(byte) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), LoadVector128((Single*)(_dataTable.inArray2Ptr)), (byte)48 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(byte) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)), (byte)48 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse41.Insert( _clsVar1, _clsVar2, 48 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = Sse41.Insert(left, right, 48); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var right = LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse41.Insert(left, right, 48); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var right = LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse41.Insert(left, right, 48); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new InsertVector128Test__InsertSingle48(); var result = Sse41.Insert(test._fld1, test._fld2, 48); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse41.Insert(_fld1, _fld2, 48); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse41.Insert(test._fld1, test._fld2, 48); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Single> left, Vector128<Single> right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), left); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits(left[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (i == 3 ? BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits(right[0]) : BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits(left[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.Insert)}<Single>(Vector128<Single>, Vector128<Single>.48): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Runtime.Serialization; using System.Xml.Linq; using BASeCamp.Elementizer; namespace BASeCamp.BASeBlock.Blocks { [BlockDescription("Attracts or Repels Balls.")] [Serializable] public class BlackHoleBlock : ImageBlock { //first, a simple class that is used to store a few variables within the ball (specifically, the mass that is to be rendered unto the ball) [Serializable] public class GravityBlockBallBehaviour : BaseBehaviour, ISerializable { public double BallMass { get; set; } public GravityBlockBallBehaviour(double pBallMass) { BallMass = pBallMass; } public GravityBlockBallBehaviour(GravityBlockBallBehaviour clonethis) { BallMass = clonethis.BallMass; } public GravityBlockBallBehaviour(XElement Source, Object pPersistenceData) :base(Source,pPersistenceData) { BallMass = Source.GetAttributeDouble("BallMass", 1); } public override XElement GetXmlData(String pNodeName,Object pPersistenceData) { return new XElement(pNodeName, new XAttribute("BallMass", BallMass)); } public override object Clone() { return new GravityBlockBallBehaviour(this); } #region iBallBehaviour Members private static double Distance(PointF PointA, PointF PointB) { return Math.Sqrt(Math.Pow(Math.Abs(PointB.X - PointA.X), 2) + Math.Pow(Math.Abs(PointB.Y - PointA.Y), 2)); } private bool isBlackHole(Block testblock) { if (testblock is BlackHoleBlock) return true; if (testblock is AnimatedBlock) { return (testblock as AnimatedBlock).baseBlock is BlackHoleBlock; } return false; } private Block getbhole(Block fromblock) { if (fromblock is BlackHoleBlock) return fromblock; if (fromblock is AnimatedBlock) { return (fromblock as AnimatedBlock).baseBlock; } return null; } public override List<Block> PerformFrame(cBall ballobject, BCBlockGameState ParentGameState, ref List<cBall> ballsadded, ref List<cBall> ballsremove, out bool removethis) { //this is the "miracle"; rather then the black hole block being //responsible for looping through all balls every frame and adjusting their trajectories, instead it is done by a ball behaviour, in the Opposite direction (that is, it acquires all the black hole blocks and performs the appropriate calculations) removethis = false; List<Block> blackholeblocks = (from y in ParentGameState.Blocks where (isBlackHole(y)) select getbhole(y)).ToList(); blackholeblocks.AddRange((from y in ParentGameState.Blocks where (y is BoundedMovingBlock && ((BoundedMovingBlock)y).baseBlock is BlackHoleBlock) select ((BoundedMovingBlock)y).baseBlock).ToList()); if (blackholeblocks.Count == 0) return null; //perform velocity "correction" between this ball and each of the acquired blocks. //attract to the block with a force proportional to the product of their masses, and inversely proportional to the distance //between them. //uses simple newtonian physics. const double G = 6.673E-8; foreach (Block loopblock in blackholeblocks) { BlackHoleBlock casted = (BlackHoleBlock)loopblock; double distance = Distance(loopblock.CenterPoint(), ballobject.Location); if(!casted.Interactive) { if(distance < casted.EventHorizon) { casted.PerformBlockHit(ParentGameState, ballobject); } } // double Force = G * BallMass * casted.Mass / ((distance * distance)); double Force = BallMass * casted.Mass / ((distance * distance)); Force /= -3; //now that we have the force being exerted, we'll just use it as the amount to change the velocity by; //create the appropriate vector of that magnitude at the angle between the ball and the blocks center, then add that //to the balls current velocity to arrive at the new velocity. double angleforce = GetAngle(loopblock.CenterPoint(), ballobject.Location); PointF veldelta = new PointF((float)(Math.Cos(angleforce) * Force), (float)(Math.Sin(angleforce) * Force)); //and lastly, add the veldelta to the balls velocity ballobject.Velocity = new PointF(ballobject.Velocity.X + veldelta.X, ballobject.Velocity.Y + veldelta.Y); } //ta da! return null; /* * Force = Gravitational constant x mass of 1st object x mass of 2nd object / distance squared. F=Gm1m2 / d2 Where G=6.672 x10-11 Nm2/kg2 Read more: http://wiki.answers.com/Q/The_amount_of_gravitational_force_between_objects_depends_on_their#ixzz1CEEcfss3 * */ //throw new NotImplementedException(); } #endregion #region ISerializable Members public override void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("Mass", BallMass); } public GravityBlockBallBehaviour(SerializationInfo info, StreamingContext context) { BallMass = info.GetSingle("Mass"); } #endregion } public double Mass { get; set; } /// <summary> /// whether this block will be drawn and interact as a block. /// if false, it will not appear at all, and effectively be invisible. /// </summary> public bool Interactive { get; set; } private int _EventHorizon = 3; public int EventHorizon { get { return _EventHorizon;} set {_EventHorizon = value;} } private bool firstframecalled = false; public BlackHoleBlock(RectangleF blockrect) : base(blockrect, "BLACKHOLE") { Mass = 1000; } public BlackHoleBlock(ImageBlock cloneme) : base(cloneme.BlockRectangle, cloneme.BlockImageKey) { Mass = ((BlackHoleBlock)cloneme).Mass; } public BlackHoleBlock(SerializationInfo info, StreamingContext context) : base(info, context) { Mass = info.GetSingle("Mass"); Interactive = info.GetBoolean("Interactive"); EventHorizon = info.GetInt32("EventHorizon"); } public BlackHoleBlock(XElement Source,Object pPersistenceData):base(Source,pPersistenceData) { Mass = Source.GetAttributeDouble("Mass"); } public override XElement GetXmlData(String pNodeName,Object pPersistenceData) { var Result = base.GetXmlData(pNodeName,pPersistenceData); Result.Add(new XAttribute("Mass",Mass)); Result.Add(new XAttribute("Interactive",Interactive)); Result.Add(new XAttribute("EventHorizon",EventHorizon)); return Result; } public override bool PerformBlockHit(BCBlockGameState parentstate, cBall ballhit) { //if our mass is positive.... if (Mass > 0) { if(!Interactive) return false; //we are a "black hole" block; thus any balls that hit us are swallowed up. if (parentstate.Balls.Count((w) => !w.isTempBall) > 1) parentstate.RemoveBalls.Add(ballhit); } else { //ballsadded.Add(new cBall(new PointF(CenterPoint().X, BlockRectangle.Bottom), new PointF(0, -2))); } return false; } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("Mass", Mass); info.AddValue("Interactive",Interactive); info.AddValue("EventHorizon",EventHorizon); } public override object Clone() { return new BlackHoleBlock(this); } public override bool MustDestroy() { return false; } } }
#region File Description //----------------------------------------------------------------------------- // MenuEntry.cs // // XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; #endregion namespace HoneycombRush { /// <summary> /// Helper class represents a single entry in a MenuScreen. By default this /// just draws the entry text string, but it can be customized to display menu /// entries in different ways. This also provides an event that will be raised /// when the menu entry is selected. /// </summary> class MenuEntry { #region Fields /// <summary> /// The text rendered for this entry. /// </summary> string text; /// <summary> /// Tracks a fading selection effect on the entry. /// </summary> /// <remarks> /// The entries transition out of the selection effect when they are deselected. /// </remarks> float selectionFade; /// <summary> /// The position at which the entry is drawn. This is set by the MenuScreen /// each frame in Update. /// </summary> Vector2 position; Texture2D buttonTexture; #endregion #region Properties /// <summary> /// Gets or sets the text of this menu entry. /// </summary> public string Text { get { return text; } set { text = value; } } /// <summary> /// Gets or sets the position at which to draw this menu entry. /// </summary> public Vector2 Position { get { return position; } set { position = value; } } public Rectangle Bounds { get { return new Rectangle((int)position.X, (int)position.Y, buttonTexture.Width, buttonTexture.Height); } } public float Scale { get; set; } public float Rotation{ get; set; } #endregion #region Events /// <summary> /// Event raised when the menu entry is selected. /// </summary> public event EventHandler<PlayerIndexEventArgs> Selected; /// <summary> /// Method for raising the Selected event. /// </summary> protected internal virtual void OnSelectEntry(PlayerIndex playerIndex) { if (Selected != null) Selected(this, new PlayerIndexEventArgs(playerIndex)); } #endregion #region Initialization /// <summary> /// Constructs a new menu entry with the specified text. /// </summary> public MenuEntry(string text) { this.text = text; Scale = 1f; Rotation = 0f; } #endregion #region Update and Draw /// <summary> /// Updates the menu entry. /// </summary> public virtual void Update(MenuScreen screen, bool isSelected, GameTime gameTime) { // there is no such thing as a selected item on Windows Phone, so we always // force isSelected to be false #if WINDOWS_PHONE isSelected = false; #endif // When the menu selection changes, entries gradually fade between // their selected and deselected appearance, rather than instantly // popping to the new state. float fadeSpeed = (float)gameTime.ElapsedGameTime.TotalSeconds * 4; if (isSelected) selectionFade = Math.Min(selectionFade + fadeSpeed, 1); else selectionFade = Math.Max(selectionFade - fadeSpeed, 0); } /// <summary> /// Draws the menu entry. This can be overridden to customize the appearance. /// </summary> public virtual void Draw(MenuScreen screen, bool isSelected, GameTime gameTime) { Color textColor = isSelected ? Color.White : Color.Black; Color tintColor = isSelected ? Color.White : Color.Gray; #if WINDOWS_PHONE // there is no such thing as a selected item on Windows Phone, so we always // force isSelected to be false isSelected = false; tintColor = Color.White; textColor = Color.Black; #endif // Draw text, centered on the middle of each line. ScreenManager screenManager = screen.ScreenManager; SpriteBatch spriteBatch = screenManager.SpriteBatch; SpriteFont font = screenManager.Font; buttonTexture = screenManager.ButtonBackground; spriteBatch.Draw(buttonTexture, new Vector2((int)position.X, (int)position.Y), tintColor); spriteBatch.DrawString(screenManager.Font, text, getTextPosition(screen), textColor, Rotation, Vector2.Zero, Scale, SpriteEffects.None, 0); } /// <summary> /// Queries how much space this menu entry requires. /// </summary> public virtual int GetHeight(MenuScreen screen) { return (int)screen.ScreenManager.Font.MeasureString(Text).Y; } /// <summary> /// Queries how wide the entry is, used for centering on the screen. /// </summary> public virtual int GetWidth(MenuScreen screen) { return (int)screen.ScreenManager.Font.MeasureString(Text).X; } private Vector2 getTextPosition(MenuScreen screen) { Vector2 textPosition = Vector2.Zero; if (Scale == 1f) { textPosition = new Vector2((int)position.X + buttonTexture.Width / 2 - GetWidth(screen) / 2, (int)position.Y); } else { textPosition = new Vector2( (int)position.X + (buttonTexture.Width / 2 - ((GetWidth(screen) / 2)* Scale)), (int)position.Y + (GetHeight(screen) - GetHeight(screen) * Scale) / 2); } return textPosition; } #endregion } }
// ----------------------------------------------------------------------- // <copyright file="EndpointActor.cs" company="Asynkron AB"> // Copyright (C) 2015-2020 Asynkron AB All rights reserved // </copyright> // ----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Google.Protobuf; using Grpc.Core; using Microsoft.Extensions.Logging; using Proto.Logging; using Proto.Remote.Metrics; namespace Proto.Remote { public class EndpointActor : IActor { private readonly string _address; private readonly Behavior _behavior; private readonly IChannelProvider _channelProvider; private readonly RemoteConfigBase _remoteConfig; private readonly Dictionary<string, HashSet<PID>> _watchedActors = new(); private readonly ILogger Logger = Log.CreateLogger<EndpointActor>(); private ChannelBase? _channel; private Remoting.RemotingClient? _client; private AsyncDuplexStreamingCall<MessageBatch, Unit>? _stream; public EndpointActor(string address, RemoteConfigBase remoteConfig, IChannelProvider channelProvider) { _address = address; _remoteConfig = remoteConfig; _behavior = new Behavior(ConnectingAsync); _channelProvider = channelProvider; } private static Task Ignore => Task.CompletedTask; public Task ReceiveAsync(IContext context) => _behavior.ReceiveAsync(context); private Task ConnectingAsync(IContext context) => context.Message switch { Started => ConnectAsync(context), Stopped => ShutDownChannel(), Restarting => ShutDownChannel(), _ => Ignore }; private Task ConnectedAsync(IContext context) => context.Message switch { RemoteTerminate msg => RemoteTerminate(context, msg), EndpointErrorEvent msg => EndpointError(msg), RemoteUnwatch msg => RemoteUnwatch(context, msg), RemoteWatch msg => RemoteWatch(context, msg), Restarting => EndpointTerminated(context), Stopped => EndpointTerminated(context), IEnumerable<RemoteDeliver> m => RemoteDeliver(m, context), _ => Ignore }; private async Task ConnectAsync(IContext context) { Logger.LogDebug("[EndpointActor] Connecting to address {Address}", _address); try { _channel = _channelProvider.GetChannel(_address); } catch (Exception e) { Logger.LogWarning(e, "[EndpointActor] Error connecting to {Address}", _address); throw; } _client = new Remoting.RemotingClient(_channel); Logger.LogDebug("[EndpointActor] Created channel and client for address {Address}", _address); var res = await _client.ConnectAsync(new ConnectRequest { MemberId = context.System.Id, }); if (res.Blocked) { Logger.LogError("Connection Refused to remote member {MemberId} address {Address}, we are blocked", res.MemberId, _address); var terminated = new EndpointTerminatedEvent(_address); context.System.EventStream.Publish(terminated); // ReSharper disable once MethodHasAsyncOverload context.Stop(context.Self); return; } _stream = _client.Receive(_remoteConfig.CallOptions); Logger.LogDebug("[EndpointActor] Connected client for address {Address}", _address); _ = SafeTask.Run( async () => { try { await _stream.ResponseStream.MoveNext(); Logger.LogDebug("[EndpointActor] {Address} Disconnected", _address); var terminated = new EndpointTerminatedEvent(_address); context.System.EventStream.Publish(terminated); } catch (RpcException x) when (x.StatusCode == StatusCode.Unavailable) { Logger.LogWarning( "[EndpointActor] Lost connection to address {Address}, address is unavailable", _address); var endpointError = new EndpointErrorEvent { Address = _address, Exception = x }; context.System.EventStream.Publish(endpointError); } catch (Exception x) { Logger.LogError(x, "[EndpointActor] Lost connection to address {Address}", _address); var endpointError = new EndpointErrorEvent { Address = _address, Exception = x }; context.System.EventStream.Publish(endpointError); } } ); Logger.LogDebug("[EndpointActor] Created reader for address {Address}", _address); var connected = new EndpointConnectedEvent(_address); context.System.EventStream.Publish(connected); Logger.LogDebug("[EndpointActor] Connected to address {Address}", _address); _behavior.Become(ConnectedAsync); } private async Task ShutDownChannel() { if (_stream != null) await _stream.RequestStream.CompleteAsync(); if (_channel != null) await _channel.ShutdownAsync(); } private Task EndpointError(EndpointErrorEvent evt) => throw evt.Exception; private Task EndpointTerminated(IContext context) { Logger.LogDebug("[EndpointActor] Handle terminated address {Address}", _address); foreach (var (id, pidSet) in _watchedActors) { var watcherPid = PID.FromAddress(context.System.Address, id); var watcherRef = context.System.ProcessRegistry.Get(watcherPid); if (watcherRef == context.System.DeadLetter) continue; foreach (var t in pidSet.Select( pid => new Terminated { Who = pid, Why = TerminatedReason.AddressTerminated } )) { //send the address Terminated event to the Watcher watcherPid.SendSystemMessage(context.System, t); } } _watchedActors.Clear(); return ShutDownChannel(); } private Task RemoteTerminate(IContext context, RemoteTerminate msg) { if (_watchedActors.TryGetValue(msg.Watcher.Id, out var pidSet)) { pidSet.Remove(msg.Watchee); if (pidSet.Count == 0) _watchedActors.Remove(msg.Watcher.Id); } //create a terminated event for the Watched actor var t = new Terminated {Who = msg.Watchee}; //send the address Terminated event to the Watcher msg.Watcher.SendSystemMessage(context.System, t); return Task.CompletedTask; } private Task RemoteUnwatch(IContext context, RemoteUnwatch msg) { if (_watchedActors.TryGetValue(msg.Watcher.Id, out var pidSet)) { pidSet.Remove(msg.Watchee); if (pidSet.Count == 0) _watchedActors.Remove(msg.Watcher.Id); } var w = new Unwatch(msg.Watcher); RemoteDeliver(context, msg.Watchee, w); return Task.CompletedTask; } private Task RemoteWatch(IContext context, RemoteWatch msg) { if (_watchedActors.TryGetValue(msg.Watcher.Id, out var pidSet)) pidSet.Add(msg.Watchee); else _watchedActors[msg.Watcher.Id] = new HashSet<PID> {msg.Watchee}; var w = new Watch(msg.Watcher); RemoteDeliver(context, msg.Watchee, w); return Task.CompletedTask; } public void RemoteDeliver(IContext context, PID pid, object msg) { var (message, sender, header) = Proto.MessageEnvelope.Unwrap(msg); var env = new RemoteDeliver(header!, message, pid, sender!); context.Send(context.Self!, env); } private Task RemoteDeliver(IEnumerable<RemoteDeliver> m, IContext context) { var envelopes = new List<MessageEnvelope>(); var typeNames = new Dictionary<string, int>(); var targetNames = new Dictionary<string, int>(); var typeNameList = new List<string>(); var targetNameList = new List<string>(); var counter = context.System.Metrics.Get<RemoteMetrics>().RemoteSerializedMessageCount; foreach (var rd in m) { var targetName = rd.Target.Id; if (!targetNames.TryGetValue(targetName, out var targetId)) { targetId = targetNames[targetName] = targetNames.Count; targetNameList.Add(targetName); } var message = rd.Message; //if the message can be translated to a serialization representation, we do this here //this only apply to root level messages and never to nested child objects inside the message if (message is IRootSerializable deserialized) message = deserialized.Serialize(context.System); // ReSharper disable once ConditionIsAlwaysTrueOrFalse if (message is null) { Logger.LogError("Null message passed to EndpointActor, ignoring message"); continue; } ByteString bytes; string typeName; int serializerId; try { bytes = SerializeMessage(_remoteConfig.Serialization, message, out typeName, out serializerId); } catch (CodedOutputStream.OutOfSpaceException oom) { Logger.LogError(oom, "Message is too large {Message}",message.GetType().Name); throw; } catch(Exception x) { Logger.LogError(x, "Serialization failed for message {Message}",message.GetType().Name); throw; } if (!context.System.Metrics.IsNoop) counter.Inc(new[] {context.System.Id, context.System.Address, typeName}); if (!typeNames.TryGetValue(typeName, out var typeId)) { typeId = typeNames[typeName] = typeNames.Count; typeNameList.Add(typeName); } MessageHeader? header = null; if (rd.Header is {Count: > 0}) { header = new MessageHeader(); header.HeaderData.Add(rd.Header.ToDictionary()); } var envelope = new MessageEnvelope { MessageData = bytes, Sender = rd.Sender, Target = targetId, TypeId = typeId, SerializerId = serializerId, MessageHeader = header, RequestId = rd.Target.RequestId }; context.System.Logger()?.LogDebug("EndpointActor adding Envelope {Envelope}", envelope); envelopes.Add(envelope); } var batch = new MessageBatch(); batch.TargetNames.AddRange(targetNameList); batch.TypeNames.AddRange(typeNameList); batch.Envelopes.AddRange(envelopes); // Logger.LogDebug("[EndpointActor] Sending {Count} envelopes for {Address}", envelopes.Count, _address); return SendEnvelopesAsync(batch, context); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static ByteString SerializeMessage(Serialization serialization, object message, out string typeName, out int serializerId) { ByteString bytes; var cached = message as ICachedSerialization; if (cached is {SerializerData: {boolHasData: true}}) { (bytes, typeName, serializerId, _) = cached.SerializerData; } else { (bytes, typeName, serializerId) = serialization.Serialize(message); if (cached is not null) { cached.SerializerData = (bytes, typeName, serializerId, true); } } return bytes; } private async Task SendEnvelopesAsync(MessageBatch batch, IContext context) { if (_stream == null || _stream.RequestStream == null) { Logger.LogError( "[EndpointActor] gRPC Failed to send to address {Address}, reason No Connection available" , _address ); return; } try { await _stream.RequestStream.WriteAsync(batch).ConfigureAwait(false); } catch (Exception) { context.Stash(); throw; } } } }
#region License /* ********************************************************************************** * Copyright (c) Roman Ivantsov * This source code is subject to terms and conditions of the MIT License * for Irony. A copy of the license can be found in the License.txt file * at the root of this distribution. * By using this source code in any fashion, you are agreeing to be bound by the terms of the * MIT License. * You must not remove this notice from this software. * **********************************************************************************/ #endregion using System; using System.Collections.Generic; using System.Globalization; using System.Linq.Expressions; using System.Text; using Irony.Ast; namespace Irony.Parsing { public class Grammar { #region properties /// <summary> /// Gets case sensitivity of the grammar. Read-only, true by default. /// Can be set to false only through a parameter to grammar constructor. /// </summary> public readonly bool CaseSensitive; //List of chars that unambigously identify the start of new token. //used in scanner error recovery, and in quick parse path in NumberLiterals, Identifiers public string Delimiters = null; [Obsolete("Override Grammar.SkipWhitespace method instead.")] // Not used anymore public string WhitespaceChars = " \t\r\n\v"; public LanguageFlags LanguageFlags = LanguageFlags.Default; public TermReportGroupList TermReportGroups = new TermReportGroupList(); //Terminals not present in grammar expressions and not reachable from the Root // (Comment terminal is usually one of them) // Tokens produced by these terminals will be ignored by parser input. public readonly TerminalSet NonGrammarTerminals = new TerminalSet(); /// <summary> /// The main root entry for the grammar. /// </summary> public NonTerminal Root; /// <summary> /// Alternative roots for parsing code snippets. /// </summary> public NonTerminalSet SnippetRoots = new NonTerminalSet(); public string GrammarComments; //shown in Grammar info tab public CultureInfo DefaultCulture = CultureInfo.InvariantCulture; //Console-related properties, initialized in grammar constructor public string ConsoleTitle; public string ConsoleGreeting; public string ConsolePrompt; //default prompt public string ConsolePromptMoreInput; //prompt to show when more input is expected #endregion #region constructors public Grammar() : this(true) { } //case sensitive by default public Grammar(bool caseSensitive) { _currentGrammar = this; this.CaseSensitive = caseSensitive; bool ignoreCase = !this.CaseSensitive; var stringComparer = StringComparer.Create(System.Globalization.CultureInfo.InvariantCulture, ignoreCase); KeyTerms = new KeyTermTable(stringComparer); //Initialize console attributes ConsoleTitle = Resources.MsgDefaultConsoleTitle; ConsoleGreeting = string.Format(Resources.MsgDefaultConsoleGreeting, this.GetType().Name); ConsolePrompt = ">"; ConsolePromptMoreInput = "."; } #endregion #region Reserved words handling //Reserved words handling public void MarkReservedWords(params string[] reservedWords) { foreach (var word in reservedWords) { var wdTerm = ToTerm(word); wdTerm.SetFlag(TermFlags.IsReservedWord); } } #endregion #region Register/Mark methods public void RegisterOperators(int precedence, params string[] opSymbols) { RegisterOperators(precedence, Associativity.Left, opSymbols); } public void RegisterOperators(int precedence, Associativity associativity, params string[] opSymbols) { foreach (string op in opSymbols) { KeyTerm opSymbol = ToTerm(op); opSymbol.SetFlag(TermFlags.IsOperator); opSymbol.Precedence = precedence; opSymbol.Associativity = associativity; } }//method public void RegisterOperators(int precedence, params BnfTerm[] opTerms) { RegisterOperators(precedence, Associativity.Left, opTerms); } public void RegisterOperators(int precedence, Associativity associativity, params BnfTerm[] opTerms) { foreach (var term in opTerms) { term.SetFlag(TermFlags.IsOperator); term.Precedence = precedence; term.Associativity = associativity; } } public void RegisterBracePair(string openBrace, string closeBrace) { KeyTerm openS = ToTerm(openBrace); KeyTerm closeS = ToTerm(closeBrace); openS.SetFlag(TermFlags.IsOpenBrace); openS.IsPairFor = closeS; closeS.SetFlag(TermFlags.IsCloseBrace); closeS.IsPairFor = openS; } public void MarkPunctuation(params string[] symbols) { foreach (string symbol in symbols) { KeyTerm term = ToTerm(symbol); term.SetFlag(TermFlags.IsPunctuation|TermFlags.NoAstNode); } } public void MarkPunctuation(params BnfTerm[] terms) { foreach (BnfTerm term in terms) term.SetFlag(TermFlags.IsPunctuation|TermFlags.NoAstNode); } public void MarkTransient(params NonTerminal[] nonTerminals) { foreach (NonTerminal nt in nonTerminals) nt.Flags |= TermFlags.IsTransient | TermFlags.NoAstNode; } //MemberSelect are symbols invoking member list dropdowns in editor; for ex: . (dot), :: public void MarkMemberSelect(params string[] symbols) { foreach (var symbol in symbols) ToTerm(symbol).SetFlag(TermFlags.IsMemberSelect); } //Sets IsNotReported flag on terminals. As a result the terminal wouldn't appear in expected terminal list // in syntax error messages public void MarkNotReported(params BnfTerm[] terms) { foreach (var term in terms) term.SetFlag(TermFlags.IsNotReported); } public void MarkNotReported(params string[] symbols) { foreach (var symbol in symbols) ToTerm(symbol).SetFlag(TermFlags.IsNotReported); } #endregion #region virtual methods: CreateTokenFilters, TryMatch public virtual void CreateTokenFilters(LanguageData language, TokenFilterList filters) { } //This method is called if Scanner fails to produce a token; it offers custom method a chance to produce the token public virtual Token TryMatch(ParsingContext context, ISourceStream source) { return null; } //Gives a way to customize parse tree nodes captions in the tree view. public virtual string GetParseNodeCaption(ParseTreeNode node) { if (node.IsError) return node.Term.Name + " (Syntax error)"; if (node.Token != null) return node.Token.ToString(); if(node.Term == null) //special case for initial node pushed into the stack at parser start return (node.State != null ? string.Empty : "(State " + node.State.Name + ")"); // Resources.LabelInitialState; var ntTerm = node.Term as NonTerminal; if(ntTerm != null && !string.IsNullOrEmpty(ntTerm.NodeCaptionTemplate)) return ntTerm.GetNodeCaption(node); return node.Term.Name; } /// <summary> /// Override this method to help scanner select a terminal to create token when there are more than one candidates /// for an input char. context.CurrentTerminals contains candidate terminals; leave a single terminal in this list /// as the one to use. /// </summary> public virtual void OnScannerSelectTerminal(ParsingContext context) { } /// <summary>Skips whitespace characters in the input stream. </summary> /// <remarks>Override this method if your language has non-standard whitespace characters.</remarks> /// <param name="source">Source stream.</param> public virtual void SkipWhitespace(ISourceStream source) { while (!source.EOF()) { switch (source.PreviewChar) { case ' ': case '\t': break; case '\r': case '\n': case '\v': if (UsesNewLine) return; //do not treat as whitespace if language is line-based break; default: return; }//switch source.PreviewPosition++; }//while }//method /// <summary>Returns true if a character is whitespace or delimiter. Used in quick-scanning versions of some terminals. </summary> /// <param name="ch">The character to check.</param> /// <returns>True if a character is whitespace or delimiter; otherwise, false.</returns> /// <remarks>Does not have to be completely accurate, should recognize most common characters that are special chars by themselves /// and may never be part of other multi-character tokens. </remarks> public virtual bool IsWhitespaceOrDelimiter(char ch) { switch (ch) { case ' ': case '\t': case '\r': case '\n': case '\v': //whitespaces case '(': case ')': case ',': case ';': case '[': case ']': case '{': case '}': return true; default: return false; }//switch }//method //The method is called after GrammarData is constructed public virtual void OnGrammarDataConstructed(LanguageData language) { } public virtual void OnLanguageDataConstructed(LanguageData language) { } //Constructs the error message in situation when parser has no available action for current input. // override this method if you want to change this message public virtual string ConstructParserErrorMessage(ParsingContext context, StringSet expectedTerms) { if(expectedTerms.Count > 0) return string.Format(Resources.ErrSyntaxErrorExpected, expectedTerms.ToString(", ")); else return Resources.ErrParserUnexpectedInput; } // Override this method to perform custom error processing public virtual void ReportParseError(ParsingContext context) { string error = null; if (context.CurrentParserInput.Term == this.SyntaxError) error = context.CurrentParserInput.Token.Value as string; //scanner error else if (context.CurrentParserInput.Term == this.Indent) error = Resources.ErrUnexpIndent; else if (context.CurrentParserInput.Term == this.Eof && context.OpenBraces.Count > 0) { if (context.OpenBraces.Count > 0) { //report unclosed braces/parenthesis var openBrace = context.OpenBraces.Peek(); error = string.Format(Resources.ErrNoClosingBrace, openBrace.Text); } else error = Resources.ErrUnexpEof; }else { var expectedTerms = context.GetExpectedTermSet(); error = ConstructParserErrorMessage(context, expectedTerms); } context.AddParserError(error); }//method #endregion #region MakePlusRule, MakeStarRule methods public BnfExpression MakePlusRule(NonTerminal listNonTerminal, BnfTerm listMember) { return MakeListRule(listNonTerminal, null, listMember); } public BnfExpression MakePlusRule(NonTerminal listNonTerminal, BnfTerm delimiter, BnfTerm listMember) { return MakeListRule(listNonTerminal, delimiter, listMember); } public BnfExpression MakeStarRule(NonTerminal listNonTerminal, BnfTerm listMember) { return MakeListRule(listNonTerminal, null, listMember, TermListOptions.StarList); } public BnfExpression MakeStarRule(NonTerminal listNonTerminal, BnfTerm delimiter, BnfTerm listMember) { return MakeListRule(listNonTerminal, delimiter, listMember, TermListOptions.StarList); } //Note: Here and in other make-list methods with delimiter. More logical would be the parameters order (list, listMember, delimiter=null). // But for historical reasons it's the way it is, and I think it's too late to change and to reverse the order of delimiter and listMember. // Too many existing grammars would be broken. The big trouble is that these two parameters are of the same type, so compiler would not // detect that order had changed (if we change it) for existing grammars. The grammar would stop working at runtime, and it would // require some effort to debug and find the cause of the problem. For these reasons, we leave it as is. [Obsolete("Method overload is obsolete - use MakeListRule instead")] public BnfExpression MakePlusRule(NonTerminal listNonTerminal, BnfTerm delimiter, BnfTerm listMember, TermListOptions options) { return MakeListRule(listNonTerminal, delimiter, listMember, options); } [Obsolete("Method overload is obsolete - use MakeListRule instead")] public BnfExpression MakeStarRule(NonTerminal listNonTerminal, BnfTerm delimiter, BnfTerm listMember, TermListOptions options) { return MakeListRule(listNonTerminal, delimiter, listMember, options | TermListOptions.StarList); } protected BnfExpression MakeListRule(NonTerminal list, BnfTerm delimiter, BnfTerm listMember, TermListOptions options = TermListOptions.PlusList) { //If it is a star-list (allows empty), then we first build plus-list var isStarList = options.IsSet(TermListOptions.AllowEmpty); NonTerminal plusList = isStarList ? new NonTerminal(listMember.Name + "+") : list; //"list" is the real list for which we will construct expression - it is either extra plus-list or original listNonTerminal. // In the latter case we will use it later to construct expression for listNonTerminal plusList.Rule = plusList; // rule => list if (delimiter != null) plusList.Rule += delimiter; // rule => list + delim if (options.IsSet(TermListOptions.AddPreferShiftHint)) plusList.Rule += PreferShiftHere(); // rule => list + delim + PreferShiftHere() plusList.Rule += listMember; // rule => list + delim + PreferShiftHere() + elem plusList.Rule |= listMember; // rule => list + delim + PreferShiftHere() + elem | elem //trailing delimiter if (options.IsSet(TermListOptions.AllowTrailingDelimiter) & delimiter != null) plusList.Rule |= list + delimiter; // => list + delim + PreferShiftHere() + elem | elem | list + delim // set Rule value plusList.SetFlag(TermFlags.IsList); //If we do not use exra list - we're done, return list.Rule if (plusList == list) return list.Rule; // Let's setup listNonTerminal.Rule using plus-list we just created //If we are here, TermListOptions.AllowEmpty is set, so we have star-list list.Rule = Empty | plusList; plusList.SetFlag(TermFlags.NoAstNode); list.SetFlag(TermFlags.IsListContainer); //indicates that real list is one level lower return list.Rule; }//method #endregion #region Hint utilities protected GrammarHint PreferShiftHere() { return new PreferredActionHint(PreferredActionType.Shift); } protected GrammarHint ReduceHere() { return new PreferredActionHint(PreferredActionType.Reduce); } protected TokenPreviewHint ReduceIf(string thisSymbol, params string[] comesBefore) { return new TokenPreviewHint(PreferredActionType.Reduce, thisSymbol, comesBefore); } protected TokenPreviewHint ReduceIf(Terminal thisSymbol, params Terminal[] comesBefore) { return new TokenPreviewHint(PreferredActionType.Reduce, thisSymbol, comesBefore); } protected TokenPreviewHint ShiftIf(string thisSymbol, params string[] comesBefore) { return new TokenPreviewHint(PreferredActionType.Shift, thisSymbol, comesBefore); } protected TokenPreviewHint ShiftIf(Terminal thisSymbol, params Terminal[] comesBefore) { return new TokenPreviewHint(PreferredActionType.Shift, thisSymbol, comesBefore); } protected GrammarHint ImplyPrecedenceHere(int precedence) { return ImplyPrecedenceHere(precedence, Associativity.Left); } protected GrammarHint ImplyPrecedenceHere(int precedence, Associativity associativity) { return new ImpliedPrecedenceHint(precedence, associativity); } protected CustomActionHint CustomActionHere(ExecuteActionMethod executeMethod, PreviewActionMethod previewMethod = null) { return new CustomActionHint(executeMethod, previewMethod); } #endregion #region Term report group methods /// <summary> /// Creates a terminal reporting group, so all terminals in the group will be reported as a single "alias" in syntex error messages like /// "Syntax error, expected: [list of terms]" /// </summary> /// <param name="alias">An alias for all terminals in the group.</param> /// <param name="symbols">Symbols to be included into the group.</param> protected void AddTermsReportGroup(string alias, params string[] symbols) { TermReportGroups.Add(new TermReportGroup(alias, TermReportGroupType.Normal, SymbolsToTerms(symbols))); } /// <summary> /// Creates a terminal reporting group, so all terminals in the group will be reported as a single "alias" in syntex error messages like /// "Syntax error, expected: [list of terms]" /// </summary> /// <param name="alias">An alias for all terminals in the group.</param> /// <param name="terminals">Terminals to be included into the group.</param> protected void AddTermsReportGroup(string alias, params Terminal[] terminals) { TermReportGroups.Add(new TermReportGroup(alias, TermReportGroupType.Normal, terminals)); } /// <summary> /// Adds symbols to a group with no-report type, so symbols will not be shown in expected lists in syntax error messages. /// </summary> /// <param name="symbols">Symbols to exclude.</param> protected void AddToNoReportGroup(params string[] symbols) { TermReportGroups.Add(new TermReportGroup(string.Empty, TermReportGroupType.DoNotReport, SymbolsToTerms(symbols))); } /// <summary> /// Adds symbols to a group with no-report type, so symbols will not be shown in expected lists in syntax error messages. /// </summary> /// <param name="symbols">Symbols to exclude.</param> protected void AddToNoReportGroup(params Terminal[] terminals) { TermReportGroups.Add(new TermReportGroup(string.Empty, TermReportGroupType.DoNotReport, terminals)); } /// <summary> /// Adds a group and an alias for all operator symbols used in the grammar. /// </summary> /// <param name="alias">An alias for operator symbols.</param> protected void AddOperatorReportGroup(string alias) { TermReportGroups.Add(new TermReportGroup(alias, TermReportGroupType.Operator, null)); //operators will be filled later } private IEnumerable<Terminal> SymbolsToTerms(IEnumerable<string> symbols) { var termList = new TerminalList(); foreach(var symbol in symbols) termList.Add(ToTerm(symbol)); return termList; } #endregion #region Standard terminals: EOF, Empty, NewLine, Indent, Dedent // Empty object is used to identify optional element: // term.Rule = term1 | Empty; public readonly Terminal Empty = new Terminal("EMPTY"); public readonly NewLineTerminal NewLine = new NewLineTerminal("LF"); //set to true automatically by NewLine terminal; prevents treating new-line characters as whitespaces public bool UsesNewLine; // The following terminals are used in indent-sensitive languages like Python; // they are not produced by scanner but are produced by CodeOutlineFilter after scanning public readonly Terminal Indent = new Terminal("INDENT", TokenCategory.Outline, TermFlags.IsNonScanner); public readonly Terminal Dedent = new Terminal("DEDENT", TokenCategory.Outline, TermFlags.IsNonScanner); //End-of-Statement terminal - used in indentation-sensitive language to signal end-of-statement; // it is not always synced with CRLF chars, and CodeOutlineFilter carefully produces Eos tokens // (as well as Indent and Dedent) based on line/col information in incoming content tokens. public readonly Terminal Eos = new Terminal("EOS", Resources.LabelEosLabel, TokenCategory.Outline, TermFlags.IsNonScanner); // Identifies end of file // Note: using Eof in grammar rules is optional. Parser automatically adds this symbol // as a lookahead to Root non-terminal public readonly Terminal Eof = new Terminal("EOF", TokenCategory.Outline); //Used as a "line-start" indicator public readonly Terminal LineStartTerminal = new Terminal("LINE_START", TokenCategory.Outline); //Used for error tokens public readonly Terminal SyntaxError = new Terminal("SYNTAX_ERROR", TokenCategory.Error, TermFlags.IsNonScanner); public NonTerminal NewLinePlus { get { if(_newLinePlus == null) { _newLinePlus = new NonTerminal("LF+"); //We do no use MakePlusRule method; we specify the rule explicitly to add PrefereShiftHere call - this solves some unintended shift-reduce conflicts // when using NewLinePlus _newLinePlus.Rule = NewLine | _newLinePlus + PreferShiftHere() + NewLine; MarkPunctuation(_newLinePlus); _newLinePlus.SetFlag(TermFlags.IsList); } return _newLinePlus; } } NonTerminal _newLinePlus; public NonTerminal NewLineStar { get { if(_newLineStar == null) { _newLineStar = new NonTerminal("LF*"); MarkPunctuation(_newLineStar); _newLineStar.Rule = MakeStarRule(_newLineStar, NewLine); } return _newLineStar; } } NonTerminal _newLineStar; #endregion #region KeyTerms (keywords + special symbols) public KeyTermTable KeyTerms; public KeyTerm ToTerm(string text) { return ToTerm(text, text); } public KeyTerm ToTerm(string text, string name) { KeyTerm term; if (KeyTerms.TryGetValue(text, out term)) { //update name if it was specified now and not before if (string.IsNullOrEmpty(term.Name) && !string.IsNullOrEmpty(name)) term.Name = name; return term; } //create new term if (!CaseSensitive) text = text.ToLower(CultureInfo.InvariantCulture); string.Intern(text); term = new KeyTerm(text, name); KeyTerms[text] = term; return term; } #endregion #region CurrentGrammar static field //Static per-thread instance; Grammar constructor sets it to self (this). // This field/property is used by operator overloads (which are static) to access Grammar's predefined terminals like Empty, // and SymbolTerms dictionary to convert string literals to symbol terminals and add them to the SymbolTerms dictionary [ThreadStatic] private static Grammar _currentGrammar; public static Grammar CurrentGrammar { get { return _currentGrammar; } } internal static void ClearCurrentGrammar() { _currentGrammar = null; } #endregion #region AST construction public virtual void BuildAst(LanguageData language, ParseTree parseTree) { if (!LanguageFlags.IsSet(LanguageFlags.CreateAst)) return; var astContext = new AstContext(language); var astBuilder = new AstBuilder(astContext); astBuilder.BuildAst(parseTree); } #endregion }//class }//namespace
using System; using System.Windows.Controls; using Microsoft.VisualStudio.TestTools.UnitTesting; using Prism.Interactivity; using Prism.Wpf.Tests.Mocks; namespace Prism.Wpf.Tests.Interactivity { [TestClass] public class InvokeCommandActionFixture { [TestMethod] public void WhenCommandPropertyIsSet_ThenHooksUpCommandBehavior() { var someControl = new TextBox(); var commandAction = new InvokeCommandAction(); var command = new MockCommand(); commandAction.Attach(someControl); commandAction.Command = command; Assert.IsFalse(command.ExecuteCalled); commandAction.InvokeAction(null); Assert.IsTrue(command.ExecuteCalled); Assert.AreSame(command, commandAction.GetValue(InvokeCommandAction.CommandProperty)); } [TestMethod] public void WhenAttachedAfterCommandPropertyIsSetAndInvoked_ThenInvokesCommand() { var someControl = new TextBox(); var commandAction = new InvokeCommandAction(); var command = new MockCommand(); commandAction.Command = command; commandAction.Attach(someControl); Assert.IsFalse(command.ExecuteCalled); commandAction.InvokeAction(null); Assert.IsTrue(command.ExecuteCalled); Assert.AreSame(command, commandAction.GetValue(InvokeCommandAction.CommandProperty)); } [TestMethod] public void WhenChangingProperty_ThenUpdatesCommand() { var someControl = new TextBox(); var oldCommand = new MockCommand(); var newCommand = new MockCommand(); var commandAction = new InvokeCommandAction(); commandAction.Attach(someControl); commandAction.Command = oldCommand; commandAction.Command = newCommand; commandAction.InvokeAction(null); Assert.IsTrue(newCommand.ExecuteCalled); Assert.IsFalse(oldCommand.ExecuteCalled); } [TestMethod] public void WhenInvokedWithCommandParameter_ThenPassesCommandParaeterToExecute() { var someControl = new TextBox(); var command = new MockCommand(); var parameter = new object(); var commandAction = new InvokeCommandAction(); commandAction.Attach(someControl); commandAction.Command = command; commandAction.CommandParameter = parameter; Assert.IsNull(command.ExecuteParameter); commandAction.InvokeAction(null); Assert.IsTrue(command.ExecuteCalled); Assert.IsNotNull(command.ExecuteParameter); Assert.AreSame(parameter, command.ExecuteParameter); } [TestMethod] public void WhenCommandParameterChanged_ThenUpdatesIsEnabledState() { var someControl = new TextBox(); var command = new MockCommand(); var parameter = new object(); var commandAction = new InvokeCommandAction(); commandAction.Attach(someControl); commandAction.Command = command; Assert.IsNull(command.CanExecuteParameter); Assert.IsTrue(someControl.IsEnabled); command.CanExecuteReturnValue = false; commandAction.CommandParameter = parameter; Assert.IsNotNull(command.CanExecuteParameter); Assert.AreSame(parameter, command.CanExecuteParameter); Assert.IsFalse(someControl.IsEnabled); } [TestMethod] public void WhenCanExecuteChanged_ThenUpdatesIsEnabledState() { var someControl = new TextBox(); var command = new MockCommand(); var parameter = new object(); var commandAction = new InvokeCommandAction(); commandAction.Attach(someControl); commandAction.Command = command; commandAction.CommandParameter = parameter; Assert.IsTrue(someControl.IsEnabled); command.CanExecuteReturnValue = false; command.RaiseCanExecuteChanged(); Assert.IsNotNull(command.CanExecuteParameter); Assert.AreSame(parameter, command.CanExecuteParameter); Assert.IsFalse(someControl.IsEnabled); } [TestMethod] public void WhenDetatched_ThenSetsCommandAndCommandParameterToNull() { var someControl = new TextBox(); var command = new MockCommand(); var parameter = new object(); var commandAction = new InvokeCommandAction(); commandAction.Attach(someControl); commandAction.Command = command; commandAction.CommandParameter = parameter; Assert.IsNotNull(commandAction.Command); Assert.IsNotNull(commandAction.CommandParameter); commandAction.Detach(); Assert.IsNull(commandAction.Command); Assert.IsNull(commandAction.CommandParameter); } [TestMethod] public void WhenCommandIsSetAndThenBehaviorIsAttached_ThenCommandsCanExecuteIsCalledOnce() { var someControl = new TextBox(); var command = new MockCommand(); var commandAction = new InvokeCommandAction(); commandAction.Command = command; commandAction.Attach(someControl); Assert.AreEqual(1, command.CanExecuteTimesCalled); } [TestMethod] public void WhenCommandAndCommandParameterAreSetPriorToBehaviorBeingAttached_ThenCommandIsExecutedCorrectlyOnInvoke() { var someControl = new TextBox(); var command = new MockCommand(); var parameter = new object(); var commandAction = new InvokeCommandAction(); commandAction.Command = command; commandAction.CommandParameter = parameter; commandAction.Attach(someControl); commandAction.InvokeAction(null); Assert.IsTrue(command.ExecuteCalled); } [TestMethod] public void WhenCommandParameterNotSet_ThenEventArgsPassed() { var eventArgs = new TestEventArgs(null); var someControl = new TextBox(); var command = new MockCommand(); var parameter = new object(); var commandAction = new InvokeCommandAction(); commandAction.Command = command; commandAction.Attach(someControl); commandAction.InvokeAction(eventArgs); Assert.IsInstanceOfType(command.ExecuteParameter, typeof(TestEventArgs)); } [TestMethod] public void WhenCommandParameterNotSetAndEventArgsParameterPathSet_ThenPathedValuePassed() { var eventArgs = new TestEventArgs("testname"); var someControl = new TextBox(); var command = new MockCommand(); var parameter = new object(); var commandAction = new InvokeCommandAction(); commandAction.Command = command; commandAction.TriggerParameterPath = "Thing1.Thing2.Name"; commandAction.Attach(someControl); commandAction.InvokeAction(eventArgs); Assert.AreEqual("testname", command.ExecuteParameter); } [TestMethod] public void WhenAttachedAndCanExecuteReturnsTrue_ThenDisabledUIElementIsEnabled() { var someControl = new TextBox(); someControl.IsEnabled = false; var command = new MockCommand(); command.CanExecuteReturnValue = true; var commandAction = new InvokeCommandAction(); commandAction.Command = command; commandAction.Attach(someControl); Assert.IsTrue(someControl.IsEnabled); } [TestMethod] public void WhenAttachedAndCanExecuteReturnsFalse_ThenEnabledUIElementIsDisabled() { var someControl = new TextBox(); someControl.IsEnabled = true; var command = new MockCommand(); command.CanExecuteReturnValue = false; var commandAction = new InvokeCommandAction(); commandAction.Command = command; commandAction.Attach(someControl); Assert.IsFalse(someControl.IsEnabled); } [TestMethod] public void WhenAutoEnableIsFalse_ThenDisabledUIElementRemainsDisabled() { var someControl = new TextBox(); someControl.IsEnabled = false; var command = new MockCommand(); command.CanExecuteReturnValue = true; var commandAction = new InvokeCommandAction(); commandAction.AutoEnable = false; commandAction.Command = command; commandAction.Attach(someControl); Assert.IsFalse(someControl.IsEnabled); } [TestMethod] public void WhenAutoEnableIsFalse_ThenEnabledUIElementRemainsEnabled() { var someControl = new TextBox(); someControl.IsEnabled = true; var command = new MockCommand(); command.CanExecuteReturnValue = false; var commandAction = new InvokeCommandAction(); commandAction.AutoEnable = false; commandAction.Command = command; commandAction.Attach(someControl); Assert.IsTrue(someControl.IsEnabled); } [TestMethod] public void WhenAutoEnableIsUpdated_ThenDisabledUIElementIsEnabled() { var someControl = new TextBox(); someControl.IsEnabled = false; var command = new MockCommand(); var commandAction = new InvokeCommandAction(); commandAction.AutoEnable = false; commandAction.Command = command; commandAction.Attach(someControl); Assert.IsFalse(someControl.IsEnabled); commandAction.AutoEnable = true; Assert.IsTrue(someControl.IsEnabled); } [TestMethod] public void WhenAutoEnableIsUpdated_ThenEnabledUIElementIsDisabled() { var someControl = new TextBox(); someControl.IsEnabled = true; var command = new MockCommand(); command.CanExecuteReturnValue = false; var commandAction = new InvokeCommandAction(); commandAction.AutoEnable = false; commandAction.Command = command; commandAction.Attach(someControl); Assert.IsTrue(someControl.IsEnabled); commandAction.AutoEnable = true; Assert.IsFalse(someControl.IsEnabled); } } class TestEventArgs : EventArgs { public TestEventArgs(string name) { this.Thing1 = new Thing1 { Thing2 = new Thing2 { Name = name } }; } public Thing1 Thing1 { get; set; } } class Thing1 { public Thing2 Thing2 { get; set; } } class Thing2 { public string Name { get; set; } } }
#region Copyright (c) 2003, newtelligence AG. All rights reserved. /* // Copyright (c) 2003, newtelligence AG. (http://www.newtelligence.com) // Original BlogX Source Code: Copyright (c) 2003, Chris Anderson (http://simplegeek.com) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are permitted // provided that the following conditions are met: // // (1) Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // (2) Redistributions in binary form must reproduce the above copyright notice, this list of // conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // (3) Neither the name of the newtelligence AG 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. // ------------------------------------------------------------------------- // // Original BlogX source code (c) 2003 by Chris Anderson (http://simplegeek.com) // // newtelligence is a registered trademark of newtelligence Aktiengesellschaft. // // For portions of this software, the some additional copyright notices may apply // which can either be found in the license.txt file included in the source distribution // or following this notice. // */ #endregion using System; using System.Diagnostics; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Threading; using newtelligence.DasBlog.Runtime.Proxies; using newtelligence.DasBlog.Util.Zip; namespace newtelligence.DasBlog.Runtime { internal delegate string LogDataItemFormatter(LogDataItem logItem); internal delegate string EventDataItemFormatter(EventDataItem logItem); internal class LoggingDataServiceXml : ILoggingDataService { static readonly Regex _eventDataItemParser = new Regex(@"l2\ttime\t(?<time>.*)\tcode\t(?<code>.*)\tmessage\t(?<message>.*)", RegexOptions.Compiled); static readonly Regex _logDataItemParser = new Regex( @"(c1|e2)\ttime\t(?<time>.*)\turl\t(?<url>.*)\turlreferrer\t(?<urlreferrer>.*)\tuseragent\t(?<useragent>[^\t\n]*)(\tuserdomain\t(?<userdomain>.*))?", RegexOptions.Compiled); readonly ReaderWriterLock _aggregatorBugLock = new ReaderWriterLock(); readonly ReaderWriterLock _clickThroughLock = new ReaderWriterLock(); readonly ReaderWriterLock _crosspostLock = new ReaderWriterLock(); readonly ReaderWriterLock _eventLock = new ReaderWriterLock(); readonly string _logDirectory; readonly ReaderWriterLock _referrerLock = new ReaderWriterLock(); internal LoggingDataServiceXml(string loggingLocation) { _logDirectory = loggingLocation; if (!Directory.Exists(_logDirectory)) { throw new ArgumentException(String.Format("Invalid directory {0}", _logDirectory), "loggingLocation"); } } #region ILoggingDataService Members LogDataItemCollection ILoggingDataService.GetReferralsForDay(DateTime dateUtc) { string logText = GetReferrerLogText(dateUtc); return ParseLogDataItems(logText); } LogDataItemCollection ILoggingDataService.GetClickThroughsForDay(DateTime dateUtc) { string logText = GetClickThroughLogText(dateUtc); return ParseLogDataItems(logText); } LogDataItemCollection ILoggingDataService.GetAggregatorBugHitsForDay(DateTime dateUtc) { string logText = GetAggregatorBugHitLogText(dateUtc); return ParseLogDataItems(logText); } LogDataItemCollection ILoggingDataService.GetCrosspostReferrersForDay(DateTime dateUtc) { string logText = GetCrosspostReferrerLogText(dateUtc); return ParseLogDataItems(logText); } EventDataItemCollection ILoggingDataService.GetEventsForDay(DateTime dateUtc) { string logText = GetEventLogText(dateUtc); return ParseEventDataItems(logText); } void ILoggingDataService.AddReferral(LogDataItem logItem) { ThreadPool.QueueUserWorkItem(new WaitCallback(AddLogDataItemWorker), new WriterThreadParams<LogDataItem>(logItem, LogCategory.Referrer, _referrerLock)); } void ILoggingDataService.AddClickThrough(LogDataItem logItem) { ThreadPool.QueueUserWorkItem(new WaitCallback(AddLogDataItemWorker), new WriterThreadParams<LogDataItem>(logItem, LogCategory.ClickThrough, _clickThroughLock)); } void ILoggingDataService.AddAggregatorBugHit(LogDataItem logItem) { ThreadPool.QueueUserWorkItem(new WaitCallback(AddLogDataItemWorker), new WriterThreadParams<LogDataItem>(logItem, LogCategory.AggregatorBug, _aggregatorBugLock)); } void ILoggingDataService.AddCrosspostReferrer(LogDataItem logItem) { ThreadPool.QueueUserWorkItem(new WaitCallback(AddLogDataItemWorker), new WriterThreadParams<LogDataItem>(logItem, LogCategory.Crosspost, _crosspostLock)); } void ILoggingDataService.AddEvent(EventDataItem eventData) { ThreadPool.QueueUserWorkItem(new WaitCallback(AddEventDataItemWorker), new WriterThreadParams<EventDataItem>(eventData, LogCategory.Event, _eventLock)); } #region Log Text Parsing static LogDataItemCollection ParseLogDataItems(string logText) { LogDataItemCollection result = new LogDataItemCollection(); MatchCollection matches = _logDataItemParser.Matches(logText); if (matches != null) { foreach (Match match in matches) { LogDataItem item = new LogDataItem(); item.RequestedUtc = DateTime.Parse(match.Groups["time"].Value); item.UrlRequested = match.Groups["url"].Value; item.UrlReferrer = match.Groups["urlreferrer"].Value; item.UserAgent = match.Groups["useragent"].Value; item.UserDomain = match.Groups["userdomain"].Value; result.Add(item); } } return result; } static EventDataItemCollection ParseEventDataItems(string logText) { EventDataItemCollection result = new EventDataItemCollection(); MatchCollection matches = _eventDataItemParser.Matches(logText); if (matches != null) { foreach (Match match in matches) { EventDataItem item = new EventDataItem(); item.EventTimeUtc = DateTime.Parse(match.Groups["time"].Value); item.EventCode = Int32.Parse(match.Groups["code"].Value); item.HtmlMessage = match.Groups["message"].Value; result.Add(item); } } return result; } #endregion #region Log File Archiving void ArchiveLogFiles(DateTime dt) { ThreadPool.QueueUserWorkItem(new WaitCallback(ArchiveLogFileWorker), new ArchiveThreadParams(GetLogPath(dt, LogCategory.Event), _eventLock)); ThreadPool.QueueUserWorkItem(new WaitCallback(ArchiveLogFileWorker), new ArchiveThreadParams(GetLogPath(dt, LogCategory.Referrer), _referrerLock)); ThreadPool.QueueUserWorkItem(new WaitCallback(ArchiveLogFileWorker), new ArchiveThreadParams(GetLogPath(dt, LogCategory.ClickThrough), _clickThroughLock)); ThreadPool.QueueUserWorkItem(new WaitCallback(ArchiveLogFileWorker), new ArchiveThreadParams(GetLogPath(dt, LogCategory.AggregatorBug), _aggregatorBugLock)); ThreadPool.QueueUserWorkItem(new WaitCallback(ArchiveLogFileWorker), new ArchiveThreadParams(GetLogPath(dt, LogCategory.Crosspost), _crosspostLock)); } static void ArchiveLogFileWorker(object argument) { ArchiveThreadParams param = (ArchiveThreadParams) argument; string zipFileName = null; bool deletedOriginal = false; try { if (File.Exists(param.FileName)) { param.LockObject.AcquireReaderLock(TimeSpan.FromMilliseconds(250)); zipFileName = String.Format("{0}.zip", param.FileName); // properly dispose when we're done using (ZipFile zip = new ZipFile(zipFileName)) { // don't include the dir tree in the zipfile zip.IncludeDirectoryTree = false; zip.AddFile(param.FileName); zip.Save(); } File.Delete(param.FileName); deletedOriginal = true; } } catch (Exception e) { ErrorTrace.Trace(TraceLevel.Error, e); // error while creating the zipfile, delete it so we can create a new one later if (zipFileName !=null && File.Exists(zipFileName) && !deletedOriginal) { File.Delete(zipFileName); } // logging //while (e != null) { // File.AppendAllText(param.FileName + ".error.txt", "----------------------------------------------------------------" + "\r\n"); // File.AppendAllText(param.FileName + ".error.txt", "filename: " + param.FileName + "\r\n"); // File.AppendAllText(param.FileName + ".error.txt", e.Message + "\r\n"); // File.AppendAllText(param.FileName + ".error.txt", e.StackTrace + "\r\n"); // e = e.InnerException; //} } finally { if (param.LockObject.IsReaderLockHeld) { param.LockObject.ReleaseReaderLock(); } } } #endregion #region Log File Read Routines string GetLogPath(DateTime dateUtc, LogCategory category) { string fileNameSuffix; switch (category) { case LogCategory.Event: fileNameSuffix = "events"; break; case LogCategory.AggregatorBug: fileNameSuffix = "aggbug"; break; case LogCategory.ClickThrough: fileNameSuffix = "clickthrough"; break; case LogCategory.Crosspost: fileNameSuffix = "crosspost"; break; case LogCategory.Referrer: fileNameSuffix = "referrer"; break; default: throw new ArgumentOutOfRangeException("category", category, "Unknown log category."); } return Path.Combine(_logDirectory, String.Format("{0:yyyy-MM-dd}.{1}.log", dateUtc.Date, fileNameSuffix)); } string GetLogText(DateTime dateUtc, LogCategory category, ReaderWriterLock lockObject) { string result = String.Empty; try { // Check for the zip version first. string logFile = String.Format("{0}.zip", GetLogPath(dateUtc, category)); if (!File.Exists(logFile)) { logFile = GetLogPath(dateUtc, category); } result = ReadLogText(logFile, lockObject); } catch (Exception e) { ErrorTrace.Trace(TraceLevel.Error, e); } return result; } static string ReadLogText(string logFilePath, ReaderWriterLock lockObject) { if (String.IsNullOrEmpty(logFilePath)) { throw new ArgumentOutOfRangeException("logFilePath"); } if (lockObject == null) { throw new ArgumentNullException("lockObject"); } string result = String.Empty; try { lockObject.AcquireReaderLock(TimeSpan.FromMilliseconds(250)); if (File.Exists(logFilePath) && Path.GetExtension(logFilePath).Equals(".zip", StringComparison.InvariantCultureIgnoreCase)) { ZipFile zip = ZipFile.Read(logFilePath); foreach (ZipEntry e in zip) { using (MemoryStream m = new MemoryStream()) { e.Extract(m); using (StreamReader reader = new StreamReader(m, Encoding.UTF8)) { result = reader.ReadToEnd(); } } } } else { using (StreamReader reader = new StreamReader(logFilePath)) { result = reader.ReadToEnd(); } } } catch (Exception e) { ErrorTrace.Trace(TraceLevel.Error, e); } finally { if (lockObject.IsReaderLockHeld) { lockObject.ReleaseReaderLock(); } } return result; } #endregion #region Get<Category>LogText string GetReferrerLogText(DateTime dateUtc) { return GetLogText(dateUtc, LogCategory.Referrer, _referrerLock); } string GetClickThroughLogText(DateTime dateUtc) { return GetLogText(dateUtc, LogCategory.ClickThrough, _clickThroughLock); } string GetAggregatorBugHitLogText(DateTime dateUtc) { return GetLogText(dateUtc, LogCategory.AggregatorBug, _aggregatorBugLock); } string GetCrosspostReferrerLogText(DateTime dateUtc) { return GetLogText(dateUtc, LogCategory.Crosspost, _crosspostLock); } string GetEventLogText(DateTime dateUtc) { return GetLogText(dateUtc, LogCategory.Event, _eventLock); } #endregion #region Write LogDataItem and EventDataItem static string DefaultLogDataItemFormatter(LogDataItem logItem) { return String.Format("e2\ttime\t{0:s}\turl\t{1}\turlreferrer\t{2}\tuseragent\t{3}\tuserdomain\t{4}", logItem.RequestedUtc, logItem.UrlRequested, logItem.UrlReferrer, logItem.UserAgent, logItem.UserDomain); } static string DefaultEventDataItemFormatter(EventDataItem logItem) { string htmlMessage = logItem.HtmlMessage.Replace("\n", ""); return String.Format("l2\ttime\t{0:s}\tcode\t{1}\tmessage\t{2}", logItem.EventTimeUtc, logItem.EventCode, htmlMessage); } void WriteLogDataItem(LogDataItem logItem, LogCategory category, ReaderWriterLock lockObject, LogDataItemFormatter formatter) { if (logItem == null) { throw new ArgumentNullException("logItem"); } if (lockObject == null) { throw new ArgumentNullException("lockObject"); } if (formatter == null) { throw new ArgumentNullException("formatter"); } try { using (Impersonation.Impersonate()) { lockObject.AcquireWriterLock(TimeSpan.FromMilliseconds(250)); using (StreamWriter writer = new StreamWriter(GetLogPath(logItem.RequestedUtc, category), true)) { writer.WriteLine(formatter(logItem)); } } } catch (Exception e) { ErrorTrace.Trace(TraceLevel.Error, e); } finally { if (lockObject.IsWriterLockHeld) { lockObject.ReleaseWriterLock(); } } } void WriteEventDataItem(EventDataItem logItem, LogCategory category, ReaderWriterLock lockObject, EventDataItemFormatter formatter) { if (logItem == null) { throw new ArgumentNullException("logItem"); } if (lockObject == null) { throw new ArgumentNullException("lockObject"); } if (formatter == null) { throw new ArgumentNullException("formatter"); } try { using (Impersonation.Impersonate()) { // Archive last day's log files. if (!File.Exists(String.Format("{0}.zip", GetLogPath(logItem.EventTimeUtc, LogCategory.Event)))) { ArchiveLogFiles(logItem.EventTimeUtc.AddDays(-1)); } lockObject.AcquireWriterLock(TimeSpan.FromMilliseconds(250)); using (StreamWriter writer = new StreamWriter(GetLogPath(logItem.EventTimeUtc, category), true)) { writer.WriteLine(formatter(logItem)); } } } catch (Exception e) { ErrorTrace.Trace(TraceLevel.Error, e); } finally { if (lockObject.IsWriterLockHeld) { lockObject.ReleaseWriterLock(); } } } #endregion #region Add Log Item Workers void AddLogDataItemWorker(object argument) { try { WriterThreadParams<LogDataItem> param = (WriterThreadParams<LogDataItem>) argument; WriteLogDataItem(param.LogItem, param.Category, param.LockObject, DefaultLogDataItemFormatter); } catch (Exception e) { ErrorTrace.Trace(TraceLevel.Error, e); } } void AddEventDataItemWorker(object argument) { try { WriterThreadParams<EventDataItem> param = (WriterThreadParams<EventDataItem>) argument; WriteEventDataItem(param.LogItem, param.Category, param.LockObject, DefaultEventDataItemFormatter); } catch (Exception e) { ErrorTrace.Trace(TraceLevel.Error, e); } } #endregion #endregion #region Nested type: ArchiveThreadParams struct ArchiveThreadParams { public readonly string FileName; public readonly ReaderWriterLock LockObject; public ArchiveThreadParams(string fileName, ReaderWriterLock lockObject) { if (String.IsNullOrEmpty(fileName)) { throw new ArgumentOutOfRangeException("fileName"); } if (lockObject == null) { throw new ArgumentNullException("lockObject"); } FileName = fileName; LockObject = lockObject; } } #endregion #region Nested type: WriterThreadParams struct WriterThreadParams<T> where T : class { public readonly LogCategory Category; public readonly ReaderWriterLock LockObject; public readonly T LogItem; public WriterThreadParams(T logItem, LogCategory category, ReaderWriterLock lockObject) { if (logItem == null) { throw new ArgumentNullException("logItem"); } if (lockObject == null) { throw new ArgumentNullException("lockObject"); } LogItem = logItem; Category = category; LockObject = lockObject; } } #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 ShiftRightLogical128BitLaneByte1() { var test = new SimpleUnaryOpTest__ShiftRightLogical128BitLaneByte1(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local 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 SimpleUnaryOpTest__ShiftRightLogical128BitLaneByte1 { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Byte); private const int RetElementCount = VectorSize / sizeof(Byte); private static Byte[] _data = new Byte[Op1ElementCount]; private static Vector128<Byte> _clsVar; private Vector128<Byte> _fld; private SimpleUnaryOpTest__DataTable<Byte, Byte> _dataTable; static SimpleUnaryOpTest__ShiftRightLogical128BitLaneByte1() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (byte)8; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar), ref Unsafe.As<Byte, byte>(ref _data[0]), VectorSize); } public SimpleUnaryOpTest__ShiftRightLogical128BitLaneByte1() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (byte)8; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld), ref Unsafe.As<Byte, byte>(ref _data[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (byte)8; } _dataTable = new SimpleUnaryOpTest__DataTable<Byte, Byte>(_data, new Byte[RetElementCount], VectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse2.ShiftRightLogical128BitLane( Unsafe.Read<Vector128<Byte>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse2.ShiftRightLogical128BitLane( Sse2.LoadVector128((Byte*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse2.ShiftRightLogical128BitLane( Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical128BitLane), new Type[] { typeof(Vector128<Byte>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Byte>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical128BitLane), new Type[] { typeof(Vector128<Byte>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((Byte*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical128BitLane), new Type[] { typeof(Vector128<Byte>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse2.ShiftRightLogical128BitLane( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector128<Byte>>(_dataTable.inArrayPtr); var result = Sse2.ShiftRightLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Sse2.LoadVector128((Byte*)(_dataTable.inArrayPtr)); var result = Sse2.ShiftRightLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArrayPtr)); var result = Sse2.ShiftRightLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__ShiftRightLogical128BitLaneByte1(); var result = Sse2.ShiftRightLogical128BitLane(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse2.ShiftRightLogical128BitLane(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Byte> firstOp, void* result, [CallerMemberName] string method = "") { Byte[] inArray = new Byte[Op1ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Byte[] inArray = new Byte[Op1ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(Byte[] firstOp, Byte[] result, [CallerMemberName] string method = "") { if (result[0] != 8) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((i == 15 ? result[i] != 0 : result[i] != 8)) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.ShiftRightLogical128BitLane)}<Byte>(Vector128<Byte><9>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
/* * 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 namespace Apache.Ignite.Core.Tests { using System; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using System.Threading; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Services; using Apache.Ignite.Core.Transactions; using NUnit.Framework; /// <summary> /// Tests grid exceptions propagation. /// </summary> public class ExceptionsTest { /** */ private const string ExceptionTask = "org.apache.ignite.platform.PlatformExceptionTask"; /// <summary> /// After test. /// </summary> [TearDown] public void TearDown() { Ignition.StopAll(true); } /// <summary> /// Tests exceptions. /// </summary> [Test] public void TestExceptions() { var grid = StartGrid(); Assert.Throws<ArgumentException>(() => grid.GetCache<object, object>("invalidCacheName")); var e = Assert.Throws<ClusterGroupEmptyException>(() => grid.GetCluster().ForRemotes().GetMetrics()); Assert.IsNotNull(e.InnerException); Assert.IsTrue(e.InnerException.Message.StartsWith( "class org.apache.ignite.cluster.ClusterGroupEmptyException: Cluster group is empty.")); // Check all exceptions mapping. var comp = grid.GetCompute(); CheckException<BinaryObjectException>(comp, "BinaryObjectException"); CheckException<IgniteException>(comp, "IgniteException"); CheckException<BinaryObjectException>(comp, "BinaryObjectException"); CheckException<ClusterTopologyException>(comp, "ClusterTopologyException"); CheckException<ComputeExecutionRejectedException>(comp, "ComputeExecutionRejectedException"); CheckException<ComputeJobFailoverException>(comp, "ComputeJobFailoverException"); CheckException<ComputeTaskCancelledException>(comp, "ComputeTaskCancelledException"); CheckException<ComputeTaskTimeoutException>(comp, "ComputeTaskTimeoutException"); CheckException<ComputeUserUndeclaredException>(comp, "ComputeUserUndeclaredException"); CheckException<TransactionOptimisticException>(comp, "TransactionOptimisticException"); CheckException<TransactionTimeoutException>(comp, "TransactionTimeoutException"); CheckException<TransactionRollbackException>(comp, "TransactionRollbackException"); CheckException<TransactionHeuristicException>(comp, "TransactionHeuristicException"); CheckException<TransactionDeadlockException>(comp, "TransactionDeadlockException"); CheckException<IgniteFutureCancelledException>(comp, "IgniteFutureCancelledException"); CheckException<ServiceDeploymentException>(comp, "ServiceDeploymentException"); // Check stopped grid. grid.Dispose(); Assert.Throws<IgniteIllegalStateException>(() => grid.GetCache<object, object>("cache1")); } /// <summary> /// Checks the exception. /// </summary> private static void CheckException<T>(ICompute comp, string name) where T : Exception { var ex = Assert.Throws<T>(() => comp.ExecuteJavaTask<string>(ExceptionTask, name)); var javaEx = ex.InnerException as JavaException; Assert.IsNotNull(javaEx); Assert.IsTrue(javaEx.Message.Contains("at " + ExceptionTask)); Assert.AreEqual(name, javaEx.JavaMessage); Assert.IsTrue(javaEx.JavaClassName.EndsWith("." + name)); // Check serialization. var formatter = new BinaryFormatter(); using (var ms = new MemoryStream()) { formatter.Serialize(ms, ex); ms.Seek(0, SeekOrigin.Begin); var res = (T) formatter.Deserialize(ms); Assert.AreEqual(ex.Message, res.Message); Assert.AreEqual(ex.Source, res.Source); Assert.AreEqual(ex.StackTrace, res.StackTrace); Assert.AreEqual(ex.HelpLink, res.HelpLink); var resJavaEx = res.InnerException as JavaException; Assert.IsNotNull(resJavaEx); Assert.AreEqual(javaEx.Message, resJavaEx.Message); Assert.AreEqual(javaEx.JavaClassName, resJavaEx.JavaClassName); Assert.AreEqual(javaEx.JavaMessage, resJavaEx.JavaMessage); Assert.AreEqual(javaEx.StackTrace, resJavaEx.StackTrace); Assert.AreEqual(javaEx.Source, resJavaEx.Source); Assert.AreEqual(javaEx.HelpLink, resJavaEx.HelpLink); } } /// <summary> /// Tests CachePartialUpdateException keys propagation. /// </summary> [Test] [Category(TestUtils.CategoryIntensive)] public void TestPartialUpdateException() { // Primitive type TestPartialUpdateException(false, (x, g) => x); // User type TestPartialUpdateException(false, (x, g) => new BinarizableEntry(x)); } /// <summary> /// Tests CachePartialUpdateException keys propagation in binary mode. /// </summary> [Test] [Category(TestUtils.CategoryIntensive)] public void TestPartialUpdateExceptionBinarizable() { // User type TestPartialUpdateException(false, (x, g) => g.GetBinary().ToBinary<IBinaryObject>(new BinarizableEntry(x))); } /// <summary> /// Tests CachePartialUpdateException serialization. /// </summary> [Test] public void TestPartialUpdateExceptionSerialization() { // Inner exception TestPartialUpdateExceptionSerialization(new CachePartialUpdateException("Msg", new IgniteException("Inner msg"))); // Primitive keys TestPartialUpdateExceptionSerialization(new CachePartialUpdateException("Msg", new object[] {1, 2, 3})); // User type keys TestPartialUpdateExceptionSerialization(new CachePartialUpdateException("Msg", new object[] { new SerializableEntry(1), new SerializableEntry(2), new SerializableEntry(3) })); } /// <summary> /// Tests that all exceptions have mandatory constructors and are serializable. /// </summary> [Test] public void TestAllExceptionsConstructors() { var types = typeof(IIgnite).Assembly.GetTypes().Where(x => x.IsSubclassOf(typeof(Exception))); foreach (var type in types) { Assert.IsTrue(type.IsSerializable, "Exception is not serializable: " + type); // Default ctor. var defCtor = type.GetConstructor(new Type[0]); Assert.IsNotNull(defCtor); var ex = (Exception) defCtor.Invoke(new object[0]); Assert.AreEqual(string.Format("Exception of type '{0}' was thrown.", type.FullName), ex.Message); // Message ctor. var msgCtor = type.GetConstructor(new[] {typeof(string)}); Assert.IsNotNull(msgCtor); ex = (Exception) msgCtor.Invoke(new object[] {"myMessage"}); Assert.AreEqual("myMessage", ex.Message); // Serialization. var stream = new MemoryStream(); var formatter = new BinaryFormatter(); formatter.Serialize(stream, ex); stream.Seek(0, SeekOrigin.Begin); ex = (Exception) formatter.Deserialize(stream); Assert.AreEqual("myMessage", ex.Message); // Message+cause ctor. var msgCauseCtor = type.GetConstructor(new[] { typeof(string), typeof(Exception) }); Assert.IsNotNull(msgCauseCtor); ex = (Exception) msgCauseCtor.Invoke(new object[] {"myMessage", new Exception("innerEx")}); Assert.AreEqual("myMessage", ex.Message); Assert.IsNotNull(ex.InnerException); Assert.AreEqual("innerEx", ex.InnerException.Message); } } /// <summary> /// Tests CachePartialUpdateException serialization. /// </summary> private static void TestPartialUpdateExceptionSerialization(Exception ex) { var formatter = new BinaryFormatter(); var stream = new MemoryStream(); formatter.Serialize(stream, ex); stream.Seek(0, SeekOrigin.Begin); var ex0 = (Exception) formatter.Deserialize(stream); var updateEx = ((CachePartialUpdateException) ex); try { Assert.AreEqual(updateEx.GetFailedKeys<object>(), ((CachePartialUpdateException) ex0).GetFailedKeys<object>()); } catch (Exception e) { if (typeof(IgniteException) != e.GetType()) throw; } while (ex != null && ex0 != null) { Assert.AreEqual(ex0.GetType(), ex.GetType()); Assert.AreEqual(ex.Message, ex0.Message); ex = ex.InnerException; ex0 = ex0.InnerException; } Assert.AreEqual(ex, ex0); } /// <summary> /// Tests CachePartialUpdateException keys propagation. /// </summary> [Test] [Category(TestUtils.CategoryIntensive)] public void TestPartialUpdateExceptionAsync() { // Primitive type TestPartialUpdateException(true, (x, g) => x); // User type TestPartialUpdateException(true, (x, g) => new BinarizableEntry(x)); } /// <summary> /// Tests CachePartialUpdateException keys propagation in binary mode. /// </summary> [Test] [Category(TestUtils.CategoryIntensive)] public void TestPartialUpdateExceptionAsyncBinarizable() { TestPartialUpdateException(true, (x, g) => g.GetBinary().ToBinary<IBinaryObject>(new BinarizableEntry(x))); } /// <summary> /// Tests that invalid spring URL results in a meaningful exception. /// </summary> [Test] public void TestInvalidSpringUrl() { var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration()) { SpringConfigUrl = "z:\\invalid.xml" }; var ex = Assert.Throws<IgniteException>(() => Ignition.Start(cfg)); Assert.IsTrue(ex.ToString().Contains("Spring XML configuration path is invalid: z:\\invalid.xml")); } /// <summary> /// Tests that invalid configuration parameter results in a meaningful exception. /// </summary> [Test] public void TestInvalidConfig() { var disco = TestUtils.GetStaticDiscovery(); disco.SocketTimeout = TimeSpan.FromSeconds(-1); // set invalid timeout var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration()) { DiscoverySpi = disco }; var ex = Assert.Throws<IgniteException>(() => Ignition.Start(cfg)); Assert.IsTrue(ex.ToString().Contains("SPI parameter failed condition check: sockTimeout > 0")); } /// <summary> /// Tests CachePartialUpdateException keys propagation. /// </summary> private static void TestPartialUpdateException<TK>(bool async, Func<int, IIgnite, TK> keyFunc) { using (var grid = StartGrid()) { var cache = grid.GetOrCreateCache<TK, int>("partitioned_atomic").WithNoRetries(); if (typeof (TK) == typeof (IBinaryObject)) cache = cache.WithKeepBinary<TK, int>(); // Do cache puts in parallel var putTask = TaskRunner.Run(() => { try { // Do a lot of puts so that one fails during Ignite stop for (var i = 0; i < 1000000; i++) { // ReSharper disable once AccessToDisposedClosure // ReSharper disable once AccessToModifiedClosure var dict = Enumerable.Range(1, 100).ToDictionary(k => keyFunc(k, grid), k => i); if (async) cache.PutAllAsync(dict).Wait(); else cache.PutAll(dict); } } catch (AggregateException ex) { CheckPartialUpdateException<TK>((CachePartialUpdateException) ex.InnerException); return; } catch (CachePartialUpdateException ex) { CheckPartialUpdateException<TK>(ex); return; } Assert.Fail("CachePartialUpdateException has not been thrown."); }); while (true) { Thread.Sleep(1000); Ignition.Stop("grid_2", true); StartGrid("grid_2"); Thread.Sleep(1000); if (putTask.Exception != null) throw putTask.Exception; if (putTask.IsCompleted) return; } } } /// <summary> /// Checks the partial update exception. /// </summary> private static void CheckPartialUpdateException<TK>(CachePartialUpdateException ex) { var failedKeys = ex.GetFailedKeys<TK>(); Assert.IsTrue(failedKeys.Any()); var failedKeysObj = ex.GetFailedKeys<object>(); Assert.IsTrue(failedKeysObj.Any()); } /// <summary> /// Starts the grid. /// </summary> private static IIgnite StartGrid(string gridName = null) { return Ignition.Start(new IgniteConfiguration(TestUtils.GetTestConfiguration()) { IgniteInstanceName = gridName, BinaryConfiguration = new BinaryConfiguration { TypeConfigurations = new[] { new BinaryTypeConfiguration(typeof (BinarizableEntry)) } } }); } /// <summary> /// Binarizable entry. /// </summary> private class BinarizableEntry { /** Value. */ private readonly int _val; /** <inheritDot /> */ public override int GetHashCode() { return _val; } /// <summary> /// Constructor. /// </summary> /// <param name="val">Value.</param> public BinarizableEntry(int val) { _val = val; } /** <inheritDoc /> */ public override bool Equals(object obj) { var entry = obj as BinarizableEntry; return entry != null && entry._val == _val; } } /// <summary> /// Serializable entry. /// </summary> [Serializable] private class SerializableEntry { /** Value. */ private readonly int _val; /** <inheritDot /> */ public override int GetHashCode() { return _val; } /// <summary> /// Constructor. /// </summary> /// <param name="val">Value.</param> public SerializableEntry(int val) { _val = val; } /** <inheritDoc /> */ public override bool Equals(object obj) { var entry = obj as SerializableEntry; return entry != null && entry._val == _val; } } } }
using System; public class DateTimeParse2 { private const int c_MIN_STRING_LEN = 1; private const int c_MAX_STRING_LEN = 2048; private const int c_NUM_LOOPS = 100; public static int Main() { DateTimeParse2 test = new DateTimeParse2(); TestLibrary.TestFramework.BeginTestCase("DateTimeParse2"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; return retVal; } public bool PosTest1() { bool retVal = true; string dateBefore = ""; DateTime dateAfter; MyFormater formater = new MyFormater(); TestLibrary.TestFramework.BeginScenario("PosTest1: DateTime.Parse(DateTime.Now, formater)"); try { dateBefore = DateTime.Now.ToString(); dateAfter = DateTime.Parse( dateBefore, formater); if (!dateBefore.Equals(dateAfter.ToString())) { TestLibrary.TestFramework.LogError("001", "DateTime.Parse(" + dateBefore + ") did not equal " + dateAfter.ToString()); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Failing date: " + dateBefore); TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; string dateBefore = ""; DateTime dateAfter; MyFormater formater = new MyFormater(); TestLibrary.TestFramework.BeginScenario("PosTest2: DateTime.Parse(DateTime.Now, null)"); try { dateBefore = DateTime.Now.ToString(); dateAfter = DateTime.Parse( dateBefore, null); if (!dateBefore.Equals(dateAfter.ToString())) { TestLibrary.TestFramework.LogError("009", "DateTime.Parse(" + dateBefore + ") did not equal " + dateAfter.ToString()); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Failing date: " + dateBefore); TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest1() { bool retVal = true; MyFormater formater = new MyFormater(); TestLibrary.TestFramework.BeginScenario("NegTest1: DateTime.Parse(null, formater)"); try { DateTime.Parse(null, formater); TestLibrary.TestFramework.LogError("003", "DateTime.Parse(null) should have thrown"); retVal = false; } catch (ArgumentNullException) { // expected } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; MyFormater formater = new MyFormater(); TestLibrary.TestFramework.BeginScenario("NegTest2: DateTime.Parse(String.Empty, formater)"); try { DateTime.Parse(String.Empty, formater); TestLibrary.TestFramework.LogError("005", "DateTime.Parse(String.Empty) should have thrown"); retVal = false; } catch (FormatException) { // expected } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; MyFormater formater = new MyFormater(); string strDateTime = ""; DateTime dateAfter; TestLibrary.TestFramework.BeginScenario("NegTest3: DateTime.Parse(<garbage>, formater)"); try { for (int i=0; i<c_NUM_LOOPS; i++) { try { strDateTime = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN); dateAfter = DateTime.Parse(strDateTime, formater); TestLibrary.TestFramework.LogError("007", "DateTime.Parse(" + strDateTime + ") should have thrown (" + dateAfter + ")"); retVal = false; } catch (FormatException) { // expected } } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Failing date: " + strDateTime); TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } } public class MyFormater : IFormatProvider { public object GetFormat(Type formatType) { if (typeof(IFormatProvider) == formatType) { return this; } else { return null; } } }
using System; using Mono.Cecil.Cil; using Mono.Cecil.CodeDom.Rocks; using Mono.Cecil.CodeDom.Parser; using System.Collections.Generic; using System.Runtime.Serialization; namespace Mono.Cecil.CodeDom { /// <summary> /// Cecil tree modification context. Should be used for making references to target types from usings. /// </summary> public class Context { private readonly Dictionary<Instruction, CodeDomExpression> _map; public Context(MethodDefinition method, CodeDomParserBase parser) { Method = method; Parser = parser; _map = new Dictionary<Instruction, CodeDomExpression>(); UserLocals = new Dictionary<object, object>(); } public void SetExpression(Instruction instruction, CodeDomExpression expression) { _map[instruction] = expression; } public CodeDomExpression GetExpression(Instruction instruction) { return _map[instruction]; } public ModuleDefinition Module { get { return Method.Module; } } public MethodDefinition Method { get; protected set; } public CodeDomParserBase Parser { get; protected set; } public Dictionary<object, object> UserLocals { get; private set; } #region MethodRef /// <summary> /// Imports method, covered by <paramref name="method"/> parameter /// </summary> /// <param name="method">Method to be imported</param> public MethodReference MakeRef(Action method) { return MethodRef.Of(Module, method); } /// <summary> /// Imports method, covered by <paramref name="method"/> parameter /// </summary> /// <param name="method">Method to be imported</param> public MethodReference MakeRef<T1>(Action<T1> method) { return MethodRef.Of(Module, method); } /// <summary> /// Imports method, covered by <paramref name="method"/> parameter /// </summary> /// <param name="method">Method to be imported</param> public MethodReference MakeRef<T1, T2>(Action<T1, T2> method) { return MethodRef.Of(Module, method); } /// <summary> /// Imports method, covered by <paramref name="method"/> parameter /// </summary> /// <param name="method">Method to be imported</param> public MethodReference MakeRef<T1, T2, T3>(Action<T1, T2, T3> method) { return MethodRef.Of(Module, method); } /// <summary> /// Imports method, covered by <paramref name="method"/> parameter /// </summary> /// <param name="method">Method to be imported</param> public MethodReference MakeRef<T1, T2, T3, T4>(Action<T1, T2, T3, T4> method) { return MethodRef.Of(Module, method); } /// <summary> /// Imports method, covered by <paramref name="method"/> parameter /// </summary> /// <param name="method">Method to be imported</param> public MethodReference MakeRef<T1, T2, T3, T4, T5>(Action<T1, T2, T3, T4, T5> method) { return MethodRef.Of(Module, method); } /// <summary> /// Imports method, covered by <paramref name="method"/> parameter /// </summary> /// <param name="method">Method to be imported</param> public MethodReference MakeRef<T1, T2, T3, T4, T5, T6>(Action<T1, T2, T3, T4, T5, T6> method) { return MethodRef.Of(Module, method); } /// <summary> /// Imports method, covered by <paramref name="method"/> parameter /// </summary> /// <param name="method">Method to be imported</param> public MethodReference MakeRef<T1, T2, T3, T4, T5, T6, T7>(Action<T1, T2, T3, T4, T5, T6, T7> method) { return MethodRef.Of(Module, method); } /// <summary> /// Imports method, covered by <paramref name="method"/> parameter /// </summary> /// <param name="method">Method to be imported</param> public MethodReference MakeRef<T1, T2, T3, T4, T5, T6, T7, T8>(Action<T1, T2, T3, T4, T5, T6, T7, T8> method) { return MethodRef.Of(Module, method); } /// <summary> /// Imports method, covered by <paramref name="method"/> parameter /// </summary> /// <param name="method">Method to be imported</param> public MethodReference MakeRef<T1>(Func<T1> method) { return MethodRef.Of(Module, method); } /// <summary> /// Imports method, covered by <paramref name="method"/> parameter /// </summary> /// <param name="method">Method to be imported</param> public MethodReference MakeRef<T1, T2>(Func<T1, T2> method) { return MethodRef.Of(Module, method); } /// <summary> /// Imports method, covered by <paramref name="method"/> parameter /// </summary> /// <param name="method">Method to be imported</param> public MethodReference MakeRef<T1, T2, T3>(Func<T1, T2, T3> method) { return MethodRef.Of(Module, method); } /// <summary> /// Imports method, covered by <paramref name="method"/> parameter /// </summary> /// <param name="method">Method to be imported</param> public MethodReference MakeRef<T1, T2, T3, T4>(Func<T1, T2, T3, T4> method) { return MethodRef.Of(Module, method); } /// <summary> /// Imports method, covered by <paramref name="method"/> parameter /// </summary> /// <param name="method">Method to be imported</param> public MethodReference MakeRef<T1, T2, T3, T4, T5>(Func<T1, T2, T3, T4, T5> method) { return MethodRef.Of(Module, method); } /// <summary> /// Imports method, covered by <paramref name="method"/> parameter /// </summary> /// <param name="method">Method to be imported</param> public MethodReference MakeRef<T1, T2, T3, T4, T5, T6>(Func<T1, T2, T3, T4, T5, T6> method) { return MethodRef.Of(Module, method); } /// <summary> /// Imports method, covered by <paramref name="method"/> parameter /// </summary> /// <param name="method">Method to be imported</param> public MethodReference MakeRef<T1, T2, T3, T4, T5, T6, T7>(Func<T1, T2, T3, T4, T5, T6, T7> method) { return MethodRef.Of(Module, method); } /// <summary> /// Imports method, covered by <paramref name="method"/> parameter /// </summary> /// <param name="method">Method to be imported</param> public MethodReference MakeRef<T1, T2, T3, T4, T5, T6, T7, T8>(Func<T1, T2, T3, T4, T5, T6, T7, T8> method) { return MethodRef.Of(Module, method); } #endregion #region MethodDef public MethodDefinition Resolve(Action method) { return MethodDef.Of(Module, method); } public MethodDefinition Resolve<T1>(Action<T1> method) { return MethodDef.Of(Module, method); } public MethodDefinition Resolve<T1, T2>(Action<T1, T2> method) { return MethodDef.Of(Module, method); } public MethodDefinition Resolve<T1, T2, T3>(Action<T1, T2, T3> method) { return MethodDef.Of(Module, method); } public MethodDefinition Resolve<T1, T2, T3, T4>(Action<T1, T2, T3, T4> method) { return MethodDef.Of(Module, method); } public MethodDefinition Resolve<T1, T2, T3, T4, T5>(Action<T1, T2, T3, T4, T5> method) { return MethodDef.Of(Module, method); } public MethodDefinition Resolve<T1, T2, T3, T4, T5, T6>(Action<T1, T2, T3, T4, T5, T6> method) { return MethodDef.Of(Module, method); } public MethodDefinition Resolve<T1, T2, T3, T4, T5, T6, T7>(Action<T1, T2, T3, T4, T5, T6, T7> method) { return MethodDef.Of(Module, method); } public MethodDefinition Resolve<T1, T2, T3, T4, T5, T6, T7, T8>(Action<T1, T2, T3, T4, T5, T6, T7, T8> method) { return MethodDef.Of(Module, method); } public MethodDefinition Resolve<T1>(Func<T1> method) { return MethodDef.Of(Module, method); } public MethodDefinition Resolve<T1, T2>(Func<T1, T2> method) { return MethodDef.Of(Module, method); } public MethodDefinition Resolve<T1, T2, T3>(Func<T1, T2, T3> method) { return MethodDef.Of(Module, method); } public MethodDefinition Resolve<T1, T2, T3, T4>(Func<T1, T2, T3, T4> method) { return MethodDef.Of(Module, method); } public MethodDefinition Resolve<T1, T2, T3, T4, T5>(Func<T1, T2, T3, T4, T5> method) { return MethodDef.Of(Module, method); } public MethodDefinition Resolve<T1, T2, T3, T4, T5, T6>(Func<T1, T2, T3, T4, T5, T6> method) { return MethodDef.Of(Module, method); } public MethodDefinition Resolve<T1, T2, T3, T4, T5, T6, T7>(Func<T1, T2, T3, T4, T5, T6, T7> method) { return MethodDef.Of(Module, method); } public MethodDefinition Resolve<T1, T2, T3, T4, T5, T6, T7, T8>(Func<T1, T2, T3, T4, T5, T6, T7, T8> method) { return MethodDef.Of(Module, method); } #endregion #region Typeof public TypeReference MakeRef<T>() { return Module.Import(typeof(T)); } public TypeReference MakeRef(Type type) { return Module.Import(type); } public TypeReference MakeRef(FieldReference field) { return Module.Import(field.FieldType); } public TypeReference MakeRef(ParameterReference param) { return Module.Import(param.ParameterType); } public TypeReference MakeRef(VariableReference variable) { return Module.Import(variable.VariableType); } public TypeReference MakeRef(TypeReference type) { return Module.Import(type); } #endregion #region TypeDef public TypeDefinition Resolve(TypeReference ref_type) { return ref_type.Resolve(); } public TypeDefinition Resolve<T>() { return MakeRef<T>().Resolve(); } public TypeDefinition Resolve(Type type) { return MakeRef(type).Resolve(); } #endregion } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V8.Resources { /// <summary>Resource name for the <c>CustomerFeed</c> resource.</summary> public sealed partial class CustomerFeedName : gax::IResourceName, sys::IEquatable<CustomerFeedName> { /// <summary>The possible contents of <see cref="CustomerFeedName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary>A resource name with pattern <c>customers/{customer_id}/customerFeeds/{feed_id}</c>.</summary> CustomerFeed = 1, } private static gax::PathTemplate s_customerFeed = new gax::PathTemplate("customers/{customer_id}/customerFeeds/{feed_id}"); /// <summary>Creates a <see cref="CustomerFeedName"/> 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="CustomerFeedName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static CustomerFeedName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new CustomerFeedName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="CustomerFeedName"/> with the pattern <c>customers/{customer_id}/customerFeeds/{feed_id}</c> /// . /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="CustomerFeedName"/> constructed from the provided ids.</returns> public static CustomerFeedName FromCustomerFeed(string customerId, string feedId) => new CustomerFeedName(ResourceNameType.CustomerFeed, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), feedId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="CustomerFeedName"/> with pattern /// <c>customers/{customer_id}/customerFeeds/{feed_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CustomerFeedName"/> with pattern /// <c>customers/{customer_id}/customerFeeds/{feed_id}</c>. /// </returns> public static string Format(string customerId, string feedId) => FormatCustomerFeed(customerId, feedId); /// <summary> /// Formats the IDs into the string representation of this <see cref="CustomerFeedName"/> with pattern /// <c>customers/{customer_id}/customerFeeds/{feed_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CustomerFeedName"/> with pattern /// <c>customers/{customer_id}/customerFeeds/{feed_id}</c>. /// </returns> public static string FormatCustomerFeed(string customerId, string feedId) => s_customerFeed.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId))); /// <summary>Parses the given resource name string into a new <see cref="CustomerFeedName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/customerFeeds/{feed_id}</c></description></item> /// </list> /// </remarks> /// <param name="customerFeedName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="CustomerFeedName"/> if successful.</returns> public static CustomerFeedName Parse(string customerFeedName) => Parse(customerFeedName, false); /// <summary> /// Parses the given resource name string into a new <see cref="CustomerFeedName"/> 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>customers/{customer_id}/customerFeeds/{feed_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="customerFeedName">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="CustomerFeedName"/> if successful.</returns> public static CustomerFeedName Parse(string customerFeedName, bool allowUnparsed) => TryParse(customerFeedName, allowUnparsed, out CustomerFeedName 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="CustomerFeedName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/customerFeeds/{feed_id}</c></description></item> /// </list> /// </remarks> /// <param name="customerFeedName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="CustomerFeedName"/>, 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 customerFeedName, out CustomerFeedName result) => TryParse(customerFeedName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="CustomerFeedName"/> 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>customers/{customer_id}/customerFeeds/{feed_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="customerFeedName">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="CustomerFeedName"/>, 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 customerFeedName, bool allowUnparsed, out CustomerFeedName result) { gax::GaxPreconditions.CheckNotNull(customerFeedName, nameof(customerFeedName)); gax::TemplatedResourceName resourceName; if (s_customerFeed.TryParseName(customerFeedName, out resourceName)) { result = FromCustomerFeed(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(customerFeedName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private CustomerFeedName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string feedId = null) { Type = type; UnparsedResource = unparsedResourceName; CustomerId = customerId; FeedId = feedId; } /// <summary> /// Constructs a new instance of a <see cref="CustomerFeedName"/> class from the component parts of pattern /// <c>customers/{customer_id}/customerFeeds/{feed_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param> public CustomerFeedName(string customerId, string feedId) : this(ResourceNameType.CustomerFeed, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), feedId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId))) { } /// <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>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary> /// The <c>Feed</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string FeedId { 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.CustomerFeed: return s_customerFeed.Expand(CustomerId, FeedId); 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 CustomerFeedName); /// <inheritdoc/> public bool Equals(CustomerFeedName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(CustomerFeedName a, CustomerFeedName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(CustomerFeedName a, CustomerFeedName b) => !(a == b); } public partial class CustomerFeed { /// <summary> /// <see cref="CustomerFeedName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal CustomerFeedName ResourceNameAsCustomerFeedName { get => string.IsNullOrEmpty(ResourceName) ? null : CustomerFeedName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary><see cref="FeedName"/>-typed view over the <see cref="Feed"/> resource name property.</summary> internal FeedName FeedAsFeedName { get => string.IsNullOrEmpty(Feed) ? null : FeedName.Parse(Feed, allowUnparsed: true); set => Feed = value?.ToString() ?? ""; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Xml; using Orleans.Providers; namespace Orleans.Runtime.Configuration { /// <summary> /// Configuration for a particular provider instance. /// </summary> [Serializable] public class ProviderConfiguration : IProviderConfiguration { private IDictionary<string, string> properties; private readonly IList<ProviderConfiguration> childConfigurations = new List<ProviderConfiguration>(); [NonSerialized] private IList<IProvider> childProviders; [NonSerialized] private IProviderManager providerManager; public string Type { get; private set; } public string Name { get; private set; } private ReadOnlyDictionary<string, string> readonlyCopyOfProperties; /// <summary> /// Properties of this provider. /// </summary> public ReadOnlyDictionary<string, string> Properties { get { if (readonlyCopyOfProperties == null) { readonlyCopyOfProperties = new ReadOnlyDictionary<string, string>(properties); } return readonlyCopyOfProperties; } } internal ProviderConfiguration() { properties = new Dictionary<string, string>(); } public ProviderConfiguration(IDictionary<string, string> properties, string providerType, string name) { this.properties = properties ?? new Dictionary<string, string>(1); Type = providerType; Name = name; } // for testing purposes internal ProviderConfiguration(IDictionary<string, string> properties, IList<IProvider> childProviders) { this.properties = properties ?? new Dictionary<string, string>(1); this.childProviders = childProviders; } // Load from an element with the format <Provider Type="..." Name="...">...</Provider> internal void Load(XmlElement child, IDictionary<string, IProviderConfiguration> alreadyLoaded, XmlNamespaceManager nsManager) { readonlyCopyOfProperties = null; // cause later refresh of readonlyCopyOfProperties if (nsManager == null) { nsManager = new XmlNamespaceManager(new NameTable()); nsManager.AddNamespace("orleans", "urn:orleans"); } if (child.HasAttribute("Name")) { Name = child.GetAttribute("Name"); } if (alreadyLoaded != null && alreadyLoaded.ContainsKey(Name)) { // This is just a reference to an already defined provider var provider = (ProviderConfiguration)alreadyLoaded[Name]; properties = provider.properties; Type = provider.Type; return; } if (child.HasAttribute("Type")) { Type = child.GetAttribute("Type"); } else { throw new FormatException("Missing 'Type' attribute on 'Provider' element"); } if (String.IsNullOrEmpty(Name)) { Name = Type; } properties = new Dictionary<string, string>(); for (int i = 0; i < child.Attributes.Count; i++) { var key = child.Attributes[i].LocalName; var val = child.Attributes[i].Value; if ((key != "Type") && (key != "Name")) { properties[key] = val; } } LoadProviderConfigurations(child, nsManager, alreadyLoaded, c => childConfigurations.Add(c)); } internal static void LoadProviderConfigurations(XmlElement root, XmlNamespaceManager nsManager, IDictionary<string, IProviderConfiguration> alreadyLoaded, Action<ProviderConfiguration> add) { var nodes = root.SelectNodes("orleans:Provider", nsManager); foreach (var node in nodes) { var subElement = node as XmlElement; if (subElement == null) continue; var config = new ProviderConfiguration(); config.Load(subElement, alreadyLoaded, nsManager); add(config); } } internal void SetProviderManager(IProviderManager manager) { this.providerManager = manager; foreach (var child in childConfigurations) child.SetProviderManager(manager); } public void SetProperty(string key, string val) { readonlyCopyOfProperties = null; // cause later refresh of readonlyCopyOfProperties if (!properties.ContainsKey(key)) { properties.Add(key, val); } else { // reset the property. properties.Remove(key); properties.Add(key, val); } } public bool RemoveProperty(string key) { readonlyCopyOfProperties = null; // cause later refresh of readonlyCopyOfProperties return properties.Remove(key); } public override string ToString() { // print only _properties keys, not values, to not leak application sensitive data. var propsStr = properties == null ? "Null" : Utils.EnumerableToString(properties.Keys); return string.Format("Name={0}, Type={1}, Properties={2}", Name, Type, propsStr); } /// <summary> /// Children providers of this provider. Used by hierarchical providers. /// </summary> public IList<IProvider> Children { get { if (childProviders != null) return new List<IProvider>(childProviders); //clone var list = new List<IProvider>(); if (childConfigurations.Count == 0) return list; // empty list foreach (var config in childConfigurations) list.Add(providerManager.GetProvider(config.Name)); childProviders = list; return new List<IProvider>(childProviders); // clone } } } /// <summary> /// Provider categoty configuration. /// </summary> [Serializable] public class ProviderCategoryConfiguration { public const string BOOTSTRAP_PROVIDER_CATEGORY_NAME = "Bootstrap"; public const string STORAGE_PROVIDER_CATEGORY_NAME = "Storage"; public const string STREAM_PROVIDER_CATEGORY_NAME = "Stream"; public string Name { get; set; } public IDictionary<string, IProviderConfiguration> Providers { get; set; } public ProviderCategoryConfiguration(string name) { Name = name; Providers = new Dictionary<string, IProviderConfiguration>(); } // Load from an element with the format <NameProviders>...</NameProviders> // that contains a sequence of Provider elements (see the ProviderConfiguration type) internal static ProviderCategoryConfiguration Load(XmlElement child) { string name = child.LocalName.Substring(0, child.LocalName.Length - 9); var category = new ProviderCategoryConfiguration(name); var nsManager = new XmlNamespaceManager(new NameTable()); nsManager.AddNamespace("orleans", "urn:orleans"); ProviderConfiguration.LoadProviderConfigurations( child, nsManager, category.Providers, c => category.Providers.Add(c.Name, c)); return category; } internal void Merge(ProviderCategoryConfiguration other) { foreach (var provider in other.Providers) { Providers.Add(provider); } } internal void SetConfiguration(string key, string val) { foreach (IProviderConfiguration config in Providers.Values) { ((ProviderConfiguration)config).SetProperty(key, val); } } internal static string ProviderConfigsToXmlString(IDictionary<string, ProviderCategoryConfiguration> providerConfig) { var sb = new StringBuilder(); foreach (string category in providerConfig.Keys) { var providerInfo = providerConfig[category]; string catName = providerInfo.Name; sb.AppendFormat("<{0}Providers>", catName).AppendLine(); foreach (string provName in providerInfo.Providers.Keys) { var prov = (ProviderConfiguration) providerInfo.Providers[provName]; sb.AppendLine("<Provider"); sb.AppendFormat(" Name=\"{0}\"", provName).AppendLine(); sb.AppendFormat(" Type=\"{0}\"", prov.Type).AppendLine(); foreach (var propName in prov.Properties.Keys) { sb.AppendFormat(" {0}=\"{1}\"", propName, prov.Properties[propName]).AppendLine(); } sb.AppendLine(" />"); } sb.AppendFormat("</{0}Providers>", catName).AppendLine(); } return sb.ToString(); } public override string ToString() { var sb = new StringBuilder(); foreach (var kv in Providers) { sb.AppendFormat(" {0}", kv.Value).AppendLine(); } return sb.ToString(); } } internal class ProviderConfigurationUtility { internal static void RegisterProvider(IDictionary<string, ProviderCategoryConfiguration> providerConfigurations, string providerCategory, string providerTypeFullName, string providerName, IDictionary<string, string> properties = null) { if (string.IsNullOrEmpty(providerCategory)) throw new ArgumentException("Provider Category cannot be null or empty string", "providerCategory"); if (string.IsNullOrEmpty(providerTypeFullName)) throw new ArgumentException("Provider type full name cannot be null or empty string", "providerTypeFullName"); if (string.IsNullOrEmpty(providerName)) throw new ArgumentException("Provider name cannot be null or empty string", "providerName"); ProviderCategoryConfiguration category; if (!providerConfigurations.TryGetValue(providerCategory, out category)) { category = new ProviderCategoryConfiguration(providerCategory); providerConfigurations.Add(category.Name, category); } if (category.Providers.ContainsKey(providerName)) throw new InvalidOperationException( string.Format("{0} provider of type {1} with name '{2}' has been already registered", providerCategory, providerTypeFullName, providerName)); var config = new ProviderConfiguration( properties ?? new Dictionary<string, string>(), providerTypeFullName, providerName); category.Providers.Add(config.Name, config); } internal static bool TryGetProviderConfiguration(IDictionary<string, ProviderCategoryConfiguration> providerConfigurations, string providerTypeFullName, string providerName, out IProviderConfiguration config) { foreach (ProviderCategoryConfiguration category in providerConfigurations.Values) { foreach (IProviderConfiguration providerConfig in category.Providers.Values) { if (providerConfig.Type.Equals(providerTypeFullName) && providerConfig.Name.Equals(providerName)) { config = providerConfig; return true; } } } config = null; return false; } internal static IEnumerable<IProviderConfiguration> GetAllProviderConfigurations(IDictionary<string, ProviderCategoryConfiguration> providerConfigurations) { return providerConfigurations.Values.SelectMany(category => category.Providers.Values); } internal static string PrintProviderConfigurations(IDictionary<string, ProviderCategoryConfiguration> providerConfigurations) { var sb = new StringBuilder(); if (providerConfigurations.Keys.Count > 0) { foreach (string provType in providerConfigurations.Keys) { ProviderCategoryConfiguration provTypeConfigs = providerConfigurations[provType]; sb.AppendFormat(" {0}Providers:", provType) .AppendLine(); sb.AppendFormat(provTypeConfigs.ToString()) .AppendLine(); } } else { sb.AppendLine(" No providers configured."); } return sb.ToString(); } } }
//==================================================================================================================================== // // Copyright Julian Oliden "Jocyf" 2015 - 18-04-2015 // Procedural Cloud Texture v1.3 // Intensive particle system personalizable for Volumetric Clouds generation. // //==================================================================================================================================== using UnityEngine; using UnityEditor; using System.Collections; [CustomEditor(typeof(CloudsToy))] public class CloudsToyEditor : Editor { private int i = 0; private int MyWidth = 100; private bool showAdvancedSettings = false; private bool showShaderSettings = false; private bool showMaximunClouds = false; private CloudsToy CloudSystem; private ProceduralCloudTexture ProcText = null; private Color myColor; public override void OnInspectorGUI(){ //EditorGUIUtility.LookLikeInspector(); EditorGUIUtility.LookLikeControls(); CloudSystem = (CloudsToy) target; if (!CloudSystem.gameObject) return; // If there isn't any cloudstoy gameobject in your scene, just return and do nothing at all. ProcText = (ProceduralCloudTexture) CloudSystem.ProceduralTexture; myColor = GUI.color; GUIStyle redFoldoutStyle = new GUIStyle(EditorStyles.foldout); redFoldoutStyle.normal.textColor = Color.red; redFoldoutStyle.focused.textColor = Color.red; redFoldoutStyle.hover.textColor = Color.red; redFoldoutStyle.active.textColor = Color.red; EditorGUILayout.BeginVertical(); EditorGUILayout.Separator(); EditorGUILayout.Separator(); string[] MenuOptions = new string[2]; MenuOptions[0] = " Clouds "; MenuOptions[1] = "Proc Texture"; CloudSystem.ToolbarOptions = GUILayout.Toolbar(CloudSystem.ToolbarOptions, MenuOptions); EditorGUILayout.Separator(); EditorGUILayout.Separator(); EditorGUILayout.Separator(); EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(); switch (CloudSystem.ToolbarOptions){ case 0: // Is the CloudsToy being executed in Unity? If not, show the Maximun Clouds parameter. GUIContent contentFoldout = new GUIContent(" Maximun Clouds (DO NOT change while executing)", "Set the maximun clouds number that" + "the CloudsToy system will handle. Changing this variable in runtime will crash the application."); if(!ProcText) { GUI.color = Color.red; showMaximunClouds = EditorGUILayout.Foldout(showMaximunClouds, contentFoldout, redFoldoutStyle); if(showMaximunClouds) CloudSystem.MaximunClouds = EditorGUILayout.IntField(" ", CloudSystem.MaximunClouds); if (GUI.changed) EditorUtility.SetDirty(CloudSystem); GUI.color = myColor; GUI.changed = false; EditorGUILayout.Separator(); EditorGUILayout.Separator(); } GUIContent contentCloud = new GUIContent(" Cloud Presets: ", "Cloud pressets to quickly start configuring the clouds style"); CloudSystem.CloudPreset = (CloudsToy.TypePreset)EditorGUILayout.EnumPopup(contentCloud, CloudSystem.CloudPreset); if (GUI.changed) { if(CloudSystem.CloudPreset == CloudsToy.TypePreset.Stormy) CloudSystem.SetPresetStormy(); else if(CloudSystem.CloudPreset == CloudsToy.TypePreset.Sunrise) CloudSystem.SetPresetSunrise(); else if(CloudSystem.CloudPreset == CloudsToy.TypePreset.Fantasy) CloudSystem.SetPresetFantasy(); EditorUtility.SetDirty(CloudSystem); } GUI.changed = false; EditorGUILayout.Separator(); EditorGUILayout.Separator(); contentCloud = new GUIContent(" Cloud Render: ", "Assign the shader that will be used to render the clouds particles."); CloudSystem.CloudRender = (CloudsToy.TypeRender)EditorGUILayout.EnumPopup(contentCloud, CloudSystem.CloudRender); contentCloud = new GUIContent(" Cloud Type: ", "Assign the texture that will be used to draw the clouds."); CloudSystem.TypeClouds = (CloudsToy.Type)EditorGUILayout.EnumPopup(contentCloud, CloudSystem.TypeClouds); contentCloud = new GUIContent(" Cloud Detail: ", "Cloud complexity that will created more populated clouds. " + "Be aware that higher levels can drop your FPS drasticaly if there are a lot of clouds."); CloudSystem.CloudDetail = (CloudsToy.TypeDetail)EditorGUILayout.EnumPopup(contentCloud, CloudSystem.CloudDetail); if (GUI.changed) { CloudSystem.SetCloudDetailParams(); EditorUtility.SetDirty(CloudSystem); } GUI.changed = false; EditorGUILayout.Separator(); EditorGUILayout.Separator(); GUI.color = Color.red; contentFoldout = new GUIContent(" Particles Shader Settings", "You can change the shaders used in the clouds." + "It can be used, for example, to use different shaders in mobile applications."); showShaderSettings = EditorGUILayout.Foldout(showShaderSettings, contentFoldout, redFoldoutStyle); if(showShaderSettings) { EditorGUILayout.Separator(); contentCloud = new GUIContent("Realistic Cloud Shader:", "Shader that will be used when selecting Realistic Clouds. This shader will use" + "the blended textures that can be assigned in the CloudsToy Texture paragraph. It is an alpha blended shader."); CloudSystem.realisticShader = (Shader)EditorGUILayout.ObjectField(contentCloud, CloudSystem.realisticShader, typeof(Shader), false); contentCloud = new GUIContent("Bright Cloud Shader:", "Shader that will be used when selecting Bright Clouds. This shader will use" + "the add textures that can be assigned in the CloudsToy Texture paragraph. It is an alpha additive shader."); CloudSystem.brightShader = (Shader)EditorGUILayout.ObjectField(contentCloud, CloudSystem.brightShader, typeof(Shader), false); contentCloud = new GUIContent("Projector Material:", "The projector material will be used to create the clouds shadows. " + "By default it is usedthe Unity's default projector material."); CloudSystem.projectorMaterial = (Material)EditorGUILayout.ObjectField(contentCloud, CloudSystem.projectorMaterial, typeof(Material), false); EditorGUILayout.Separator(); } EditorGUILayout.Separator(); EditorGUILayout.Separator(); contentFoldout = new GUIContent(" Particles Advanced Settings", "This section provides of two parameters to tweak your clouds. " + "It will be applied to all the cloud system. Those values can make your FPS drop drastically is you select very high values. Take it into account!"); showAdvancedSettings = EditorGUILayout.Foldout(showAdvancedSettings, contentFoldout, redFoldoutStyle); if(showAdvancedSettings) { EditorGUILayout.Separator(); contentCloud = new GUIContent(" Size Factor: ", "Modify the initial ellipsoid from wich the cloud particle is generated, so smaller (or bigger) clouds will be created."); CloudSystem.SizeFactorPart = EditorGUILayout.Slider(contentCloud, CloudSystem.SizeFactorPart, 0.1f, 4.0f); contentCloud = new GUIContent(" Emitter Mult: ", "Modify the minimun/maximun emission particle cloud, so more (or less) populated clouds will be created."); CloudSystem.EmissionMult = EditorGUILayout.Slider(contentCloud, CloudSystem.EmissionMult, 0.1f, 4.0f); EditorGUILayout.Separator(); } GUI.color = myColor; EditorGUILayout.Separator(); EditorGUILayout.Separator(); Rect buttonRect = EditorGUILayout.BeginHorizontal(); buttonRect.x = buttonRect.width / 2 - 100; buttonRect.width = 200; buttonRect.height = 30; GUI.color = Color.red; contentCloud = new GUIContent("Repaint Clouds", "Unity scene cloud regeneration and repainting. Use it when you want to be sure that all your tweaked adjustments are being applied to your clouds in the scene." + "It's ment to be used only in Unity while adjusting your clouds. DO NOT USE IT in your game in realtime execution; you will be recreating your clouds in your game just for nothing."); if(GUI.Button(buttonRect, contentCloud)) CloudSystem.EditorRepaintClouds(); GUI.color = myColor; EditorGUILayout.Separator(); EditorGUILayout.EndHorizontal(); EditorGUILayout.Separator(); EditorGUILayout.Separator(); EditorGUILayout.Separator(); EditorGUILayout.Separator(); EditorGUILayout.Separator(); EditorGUILayout.Separator(); contentCloud = new GUIContent(" Soft Clouds", "Modify particle render to stretch mode instead of the regular billboard mode."); CloudSystem.SoftClouds = EditorGUILayout.Toggle(contentCloud, CloudSystem.SoftClouds); if(CloudSystem.SoftClouds) { contentCloud = new GUIContent(" Spread Direction: ", "The world particle velocity that will be applied to the stretched clouds particles."); #if UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_5 || UNITY_4_6 CloudSystem.SpreadDir = EditorGUILayout.Vector3Field(" Spread Direction: ", CloudSystem.SpreadDir); #else CloudSystem.SpreadDir = EditorGUILayout.Vector3Field(contentCloud, CloudSystem.SpreadDir); #endif contentCloud = new GUIContent(" Length Spread: ", "The scale lenght to which the clouds will be stretched to."); CloudSystem.LengthSpread = EditorGUILayout.Slider(contentCloud, CloudSystem.LengthSpread, 1, 30); } EditorGUILayout.Separator(); contentCloud = new GUIContent(" Clouds Num: ", "Number of clouds that will be created. The maximum number of clouds that CloudsToy will handle" + "can be configured in the Maximum clouds parameter, the first cloudsToy parameter"); CloudSystem.NumberClouds = EditorGUILayout.IntSlider(contentCloud, CloudSystem.NumberClouds, 1, CloudSystem.MaximunClouds); EditorGUILayout.Separator(); contentCloud = new GUIContent(" Cloud Creation Size: ", "The scene blue box size where the clouds will be created into initially."); #if UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_5 || UNITY_4_6 CloudSystem.Side = EditorGUILayout.Vector3Field(" Cloud Creation Size: ", CloudSystem.Side); #else CloudSystem.Side = EditorGUILayout.Vector3Field(contentCloud, CloudSystem.Side); #endif contentCloud = new GUIContent(" Dissapear Mult: ", "The scene yellow box will be calculated as a multiplier of the blue box. It is used" + "to know when to remove a cloud. So, when clouds are moving in any direction, as soon as they reach the yellow box border, they will be moved to the other side of the box"); CloudSystem.DisappearMultiplier = EditorGUILayout.Slider(contentCloud, CloudSystem.DisappearMultiplier, 1, 10); EditorGUILayout.Separator(); contentCloud = new GUIContent(" Maximum Velocity: ", "The clouds maximum velocity. Bigger clouds will be slower than the smaller ones."); #if UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_5 || UNITY_4_6 CloudSystem.MaximunVelocity = EditorGUILayout.Vector3Field(" Maximun Velocity: ", CloudSystem.MaximunVelocity); #else CloudSystem.MaximunVelocity = EditorGUILayout.Vector3Field(contentCloud, CloudSystem.MaximunVelocity); #endif contentCloud = new GUIContent(" Velocity Mult: ", "A velocity multiplier to quickly tweak the clouds velocity without modifying the previous parameter."); CloudSystem.VelocityMultipier = EditorGUILayout.Slider(contentCloud, CloudSystem.VelocityMultipier, 0, 20); EditorGUILayout.Separator(); contentCloud = new GUIContent(" Paint Type: ", "The clouds can be colorized with different adjustable colors using two diferent presets. Below paint type will be try to change the color of the" + "lower cloud particles to simulate how real clouds look like."); CloudSystem.PaintType = (CloudsToy.TypePaintDistr)EditorGUILayout.EnumPopup(contentCloud, CloudSystem.PaintType); /*if(CloudSystem.CloudRender == CloudsToy.TypeRender.Realistic) {*/ contentCloud = new GUIContent(" Cloud Color: ", "Main cloud color used only in Realistic render mode. This color" + "will be directly assigned to the cloud realistic shader Tint color used by realistic particle clouds."); CloudSystem.CloudColor = EditorGUILayout.ColorField(contentCloud, CloudSystem.CloudColor); /*}*/ contentCloud = new GUIContent(" Main Color: ", "This is the main color used when trying colorize the cloud."); CloudSystem.MainColor = EditorGUILayout.ColorField(contentCloud, CloudSystem.MainColor); contentCloud = new GUIContent(" Secondary Color: ", "This is the second color used when trying colorize the cloud."); CloudSystem.SecondColor = EditorGUILayout.ColorField(contentCloud, CloudSystem.SecondColor); contentCloud = new GUIContent(" Tint Strength: ", "Higher strenth will tint more cloud particles in the cloud."); CloudSystem.TintStrength = EditorGUILayout.IntSlider(contentCloud, CloudSystem.TintStrength, 1, 100); if(CloudSystem.PaintType == CloudsToy.TypePaintDistr.Below) { contentCloud = new GUIContent(" Offset: ", "Will be used in the below paint type to tint the cloud particles depending on" + "their relative position inside the cloud. Higher values will paint particles that are in high local positions inside the cloud"); CloudSystem.offset = EditorGUILayout.Slider(contentCloud, CloudSystem.offset, 0, 1); } EditorGUILayout.Separator(); contentCloud = new GUIContent(" Width: ", "Maximum width of each cloud"); CloudSystem.MaxWithCloud = EditorGUILayout.IntSlider(contentCloud, CloudSystem.MaxWithCloud, 10, 1000); contentCloud = new GUIContent(" Height: ", "Maximum height of each cloud"); CloudSystem.MaxTallCloud = EditorGUILayout.IntSlider(contentCloud, CloudSystem.MaxTallCloud, 5, 500); contentCloud = new GUIContent(" Depth: ", "Maximum depth of each cloud"); CloudSystem.MaxDepthCloud = EditorGUILayout.IntSlider(contentCloud, CloudSystem.MaxDepthCloud, 5, 1000); contentCloud = new GUIContent(" Fixed Size", "The size of the clouds will be exactly the same depending on their cloud" + "size type (big, medium, small). If fixed size is disabled all the big clouds (for example) will not have the exact same size"); CloudSystem.FixedSize = EditorGUILayout.Toggle(contentCloud, CloudSystem.FixedSize); EditorGUILayout.Separator(); contentCloud = new GUIContent(" Animate Cloud", "Each cloud can be animated making it to rotate over itself."); CloudSystem.IsAnimate = EditorGUILayout.Toggle(contentCloud, CloudSystem.IsAnimate); if(CloudSystem.IsAnimate) { contentCloud = new GUIContent(" Animation Velocity: ", "Cloud rotation velocity."); CloudSystem.AnimationVelocity = EditorGUILayout.Slider(contentCloud, CloudSystem.AnimationVelocity, 0, 1); } contentCloud = new GUIContent(" Shadows: ", "Clouds can have a shadow. It is made using a Unity's projector that creates a shadow" + "taking into account the layer the clouds are in (so they will ignore the cloud particle itself when drawing their own shadow"); CloudSystem.NumberOfShadows = (CloudsToy.TypeShadow)EditorGUILayout.EnumPopup(contentCloud, CloudSystem.NumberOfShadows); EditorGUILayout.Separator(); EditorGUILayout.Separator(); contentCloud = new GUIContent("Texture Add", "These are the textures that will be used by bright type clouds. Bright clouds " + "use a particle additive kind of shader."); GUIContent contentCloud2 = new GUIContent("(Used for Bright Clouds)", ""); EditorGUILayout.LabelField(contentCloud, contentCloud2); EditorGUILayout.BeginHorizontal(); for(i = 0; i < CloudSystem.CloudsTextAdd.Length; i++) { if(i == CloudSystem.CloudsTextAdd.Length/2) { EditorGUILayout.EndHorizontal(); EditorGUILayout.Separator(); EditorGUILayout.BeginHorizontal(); } else if(i != 0 && i != 3) EditorGUILayout.Separator(); CloudSystem.CloudsTextAdd[i] = (Texture2D)EditorGUILayout.ObjectField(CloudSystem.CloudsTextAdd[i], typeof(Texture2D), false, GUILayout.Width(70), GUILayout.Height(70)); } EditorGUILayout.EndHorizontal(); EditorGUILayout.Separator(); EditorGUILayout.Separator(); contentCloud = new GUIContent("Texture Blended", "These are the textures that will be used by realistic type clouds. Bright clouds " + "use a particle blended additive kind of shader."); contentCloud2 = new GUIContent("(Used for Realistic Clouds)", ""); EditorGUILayout.LabelField(contentCloud, contentCloud2); EditorGUILayout.BeginHorizontal(); for(i = 0; i < CloudSystem.CloudsTextBlended.Length; i++) { if(i == CloudSystem.CloudsTextBlended.Length/2) { EditorGUILayout.EndHorizontal(); EditorGUILayout.Separator(); EditorGUILayout.BeginHorizontal(); } else if(i != 0 && i != 3) EditorGUILayout.Separator(); CloudSystem.CloudsTextBlended[i] = (Texture2D)EditorGUILayout.ObjectField(CloudSystem.CloudsTextBlended[i], typeof(Texture2D), false, GUILayout.Width(70), GUILayout.Height(70)); } EditorGUILayout.EndHorizontal(); EditorGUILayout.Separator(); if (GUI.changed) EditorUtility.SetDirty (CloudSystem); GUI.changed = false; break; case 1: if(!ProcText) { GUI.color = Color.red; contentCloud = new GUIContent(" Texture Width: ", "Texture width used to create the runtime noise based texture. Because the texture is generated at runtime, " + "big texture sizes will slow the process. The texture is generated pixel by pixel so an 256x256 texture will be FOUR TIMES SLOWER than a 128x128 texture"); CloudSystem.PT1TextureWidth = EditorGUILayout.IntField(contentCloud, CloudSystem.PT1TextureWidth); contentCloud = new GUIContent(" Texture Height: ", "Texture height used to create the runtime noise based texture. Because the texture is generated at runtime, " + "big texture sizes will slow the process. The texture is generated pixel by pixel so an 256x256 texture will be FOUR TIMES SLOWER than a 128x128 texture"); CloudSystem.PT1TextureHeight = EditorGUILayout.IntField(contentCloud, CloudSystem.PT1TextureHeight); if (GUI.changed && ProcText) EditorUtility.SetDirty(CloudSystem); GUI.color = myColor; } GUI.changed = false; EditorGUILayout.Separator(); contentCloud = new GUIContent(" Type of Noise: ", "There are two different noise generator algorithms: The standard noise generation (Cloud) and the usual perlin noise generator."); CloudSystem.PT1TypeNoise = (CloudsToy.NoisePresetPT1)EditorGUILayout.EnumPopup(contentCloud, CloudSystem.PT1TypeNoise); EditorGUILayout.Separator(); contentCloud = new GUIContent(" Seed: ", "This value is the basic seed value to generate any ramdom noise Diferent values will generate different noise patterns."); CloudSystem.PT1Seed = EditorGUILayout.IntSlider(contentCloud, CloudSystem.PT1Seed, 1, 10000); EditorGUILayout.Separator(); if (GUI.changed && ProcText) { CloudSystem.PT1NewRandomSeed(); EditorUtility.SetDirty(CloudSystem); } GUI.changed = false; contentCloud = new GUIContent(" Scale Width: ", "Internal noise scale width used when generating the noise pattern."); CloudSystem.PT1ScaleWidth = EditorGUILayout.Slider(contentCloud, CloudSystem.PT1ScaleWidth, 0.1f, 50.0f); contentCloud = new GUIContent(" Scale Height: ", "Internal noise scale height used when generating the noise pattern."); CloudSystem.PT1ScaleHeight = EditorGUILayout.Slider(contentCloud, CloudSystem.PT1ScaleHeight, 0.1f, 50.0f); contentCloud = new GUIContent(" Scale Factor: ", "Scale multiplier used to quickly tweak the scale width/height at once."); CloudSystem.PT1ScaleFactor = EditorGUILayout.Slider(contentCloud, CloudSystem.PT1ScaleFactor, 0.1f, 2.0f); EditorGUILayout.Separator(); if(CloudSystem.PT1TypeNoise == CloudsToy.NoisePresetPT1.PerlinCloud) { contentCloud = new GUIContent(" Lacunarity: ", "Lacunarity parameter used by Perlin noise generator."); CloudSystem.PT1Lacunarity = EditorGUILayout.Slider(contentCloud, CloudSystem.PT1Lacunarity, 0.0f, 10.0f); contentCloud = new GUIContent(" FractalIncrement: ", "FractalIncrement parameter used by Perlin noise generator."); CloudSystem.PT1FractalIncrement = EditorGUILayout.Slider(contentCloud, CloudSystem.PT1FractalIncrement, 0.0f, 2.0f); contentCloud = new GUIContent(" Octaves: ", "Octave parameter used by Perlin noise generator."); CloudSystem.PT1Octaves = EditorGUILayout.Slider(contentCloud, CloudSystem.PT1Octaves, 0.0f, 10.0f); contentCloud = new GUIContent(" Offset: ", "Offset parameter used by Perlin noise generator (HybridMultifractal noise functions)."); CloudSystem.PT1Offset = EditorGUILayout.Slider(contentCloud, CloudSystem.PT1Offset, 0.1f, 3.0f); }else if(CloudSystem.PT1TypeNoise == CloudsToy.NoisePresetPT1.Cloud) { contentCloud = new GUIContent(" Turb Size: ", "Turbulence parameter used by SimpleNoise Turbulence generator. Internally, this is the octaves parameter" + "used to calculate the turbulence of an already created SimpleNoise texture."); CloudSystem.PT1TurbSize = EditorGUILayout.IntSlider(contentCloud, CloudSystem.PT1TurbSize, 1, 256); contentCloud = new GUIContent(" Turb Lacun: ", "Lacunarity parameter used by SimpleNoise Turbulence generator. Internally, this is the lacunarity parameter" + "used to calculate the turbulence of an already created SimpleNoise texture."); CloudSystem.PT1TurbLacun = EditorGUILayout.Slider(contentCloud, CloudSystem.PT1TurbLacun, 0.01f, 0.99f); contentCloud = new GUIContent(" Turb Gain: ", "Gain parameter used by SimpleNoise Turbulence generator. Internally, this is the gain parameter" + "used to calculate the turbulence of an already created SimpleNoise texture. Higher values will generate brighter textures."); CloudSystem.PT1TurbGain = EditorGUILayout.Slider(contentCloud, CloudSystem.PT1TurbGain, 0.01f, 2.99f); contentCloud = new GUIContent(" Radius: ", "Used to adjust the noise turbulence. Lower values will generate darker textures because the resulting texture" + "will dark the pixels outside that radious."); CloudSystem.PT1xyPeriod = EditorGUILayout.Slider(contentCloud, CloudSystem.PT1xyPeriod, 0.1f, 2.0f); contentCloud = new GUIContent(" Turb Power: ", "Turbulence multipler that will affect the pixels inside the turbulence radious. " + "Higher values will generate brighter results BUT it will only affect the pixels inside a given Radious."); CloudSystem.PT1turbPower = EditorGUILayout.Slider(contentCloud, CloudSystem.PT1turbPower, 1, 60); } EditorGUILayout.Separator(); /*CloudSystem.PT1IsHalo = EditorGUILayout.Toggle(" Halo Active:", CloudSystem.PT1IsHalo); if(CloudSystem.PT1IsHalo)*/ contentCloud = new GUIContent(" HaloEffect: ", "Will create a dark halo around the texture, used to make rounded textures that can be used to draw the clouds."); CloudSystem.PT1HaloEffect = EditorGUILayout.Slider(contentCloud, CloudSystem.PT1HaloEffect, 0.1f, 1.7f); contentCloud = new GUIContent(" Inside Radius: ", "Will dark the pixels inside the Halo, used to teawk rounded textures that can be used to draw the clouds."); CloudSystem.PT1HaloInsideRadius = EditorGUILayout.Slider(contentCloud, CloudSystem.PT1HaloInsideRadius, 0.1f, 3.5f); EditorGUILayout.Separator(); /*CloudSystem.PT1BackgroundColor = EditorGUILayout.ColorField(" Back Color: ", CloudSystem.PT1BackgroundColor); CloudSystem.PT1FinalColor = EditorGUILayout.ColorField(" Front Color: ", CloudSystem.PT1FinalColor);*/ contentCloud = new GUIContent(" Invert Colors:", "Invert the texture colors."); CloudSystem.PT1InvertColors = EditorGUILayout.Toggle(contentCloud, CloudSystem.PT1InvertColors); contentCloud = new GUIContent(" Contrast Mult: ", "Higher values will create brighter textures."); CloudSystem.PT1ContrastMult = EditorGUILayout.Slider(contentCloud, CloudSystem.PT1ContrastMult, 0.0f, 2.0f); EditorGUILayout.Separator(); contentCloud = new GUIContent(" Alpha Texture:", "It will create a second texture with transparency so the alpha channel can be tweaked." + "This new alpha texture will be draw in the inspector so you can see the alpha channel (the alpha values will be shown in green color."); CloudSystem.PT1UseAlphaTexture = EditorGUILayout.Toggle(contentCloud, CloudSystem.PT1UseAlphaTexture); if(CloudSystem.PT1UseAlphaTexture) { contentCloud = new GUIContent(" Alpha Index: ", "This value 0-1 will be used to increase/decrease the texture's alpha channel."); CloudSystem.PT1AlphaIndex = EditorGUILayout.Slider(contentCloud, CloudSystem.PT1AlphaIndex, 0.0f, 1.0f); } EditorGUILayout.Separator(); EditorGUILayout.Separator(); // Be sure that the Texture1 class exists before try to paint the textures. if(ProcText) { contentCloud = new GUIContent(" InEditor Text Size ", "Texture size used only in the inspector window."); MyWidth = EditorGUILayout.IntSlider(contentCloud, MyWidth, 50, 200); EditorGUILayout.Separator(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.Space(); ProcText.MyTexture = (Texture2D)EditorGUILayout.ObjectField(ProcText.MyTexture, typeof(Texture2D), false, GUILayout.Width(MyWidth), GUILayout.Height(MyWidth)); EditorGUILayout.Separator(); EditorGUILayout.Space(); if(CloudSystem.PT1UseAlphaTexture) ProcText.MyAlphaDrawTexture = (Texture2D)EditorGUILayout.ObjectField(ProcText.MyAlphaDrawTexture, typeof(Texture2D), false, GUILayout.Width(MyWidth), GUILayout.Height(MyWidth)); EditorGUILayout.Separator(); EditorGUILayout.EndHorizontal(); EditorGUILayout.Separator(); EditorGUILayout.Separator(); EditorGUILayout.Separator(); } Rect buttonRectPT1 = EditorGUILayout.BeginHorizontal(); buttonRectPT1.x = buttonRectPT1.width / 2 - 100; buttonRectPT1.width = 200; buttonRectPT1.height = 30; //GUI.skin?? GUI.color = Color.red; contentCloud = new GUIContent("Reset Parameters", "Reset the noise parameters to their default values."); if(GUI.Button(buttonRectPT1, contentCloud)) { CloudSystem.ResetCloudParameters(); if(ProcText) CloudSystem.PT1CopyParameters(); } EditorGUILayout.EndHorizontal(); EditorGUILayout.Separator(); EditorGUILayout.Separator(); EditorGUILayout.Separator(); EditorGUILayout.Separator(); EditorGUILayout.Separator(); EditorGUILayout.Separator(); EditorGUILayout.Separator(); EditorGUILayout.Separator(); // Is the program being executed? If so, show the 'Save Params' button. GUI.color = Color.yellow; if(ProcText) { Rect buttonRectPrint = EditorGUILayout.BeginHorizontal(); buttonRectPrint.x = buttonRectPrint.width / 2 - 100; buttonRectPrint.width = 200; buttonRectPrint.height = 30; //GUI.skin?? contentCloud = new GUIContent("Save Texture", "Save the generated texture to a file. CAUTION: This funcion can not be used in Web Player targeted projects."); if(GUI.Button(buttonRectPrint, contentCloud)) CloudSystem.SaveProceduralTexture(); EditorGUILayout.EndHorizontal(); } GUI.color = myColor; EditorGUILayout.Separator(); EditorGUILayout.Separator(); EditorGUILayout.Separator(); EditorGUILayout.Separator(); EditorGUILayout.Separator(); EditorGUILayout.Separator(); EditorGUILayout.Separator(); EditorGUILayout.Separator(); if (GUI.changed) { if(ProcText) { CloudSystem.PT1CopyParameters(); CloudSystem.ModifyPTMaterials(); } EditorUtility.SetDirty (CloudSystem); } GUI.changed = false; break; } EditorGUILayout.EndVertical(); } }
// Copyright (c) 2019-2020 Ubisoft Entertainment // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using Sharpmake.Generators.VisualStudio; namespace Sharpmake.Generators.JsonCompilationDatabase { /// <summary> /// Compile command format. /// - Command: Compilation command specified as a shell command /// - Arguments: Compilation command specified as a list of arguments /// </summary> public enum CompileCommandFormat { Command, Arguments } public class JsonCompilationDatabase { public const string FileName = "compile_commands.json"; public event Action<IGenerationContext, CompileCommand> CompileCommandGenerated; public void Generate(Builder builder, string path, IEnumerable<Project.Configuration> projectConfigurations, CompileCommandFormat format, List<string> generatedFiles, List<string> skipFiles) { var database = new List<IDictionary<string, object>>(); foreach (var configuration in projectConfigurations) { database.AddRange(GetEntries(builder, configuration, format)); } if (database.Count > 0) WriteGeneratedFile(builder, path, database, generatedFiles, skipFiles); } private void WriteGeneratedFile(Builder builder, string path, IEnumerable<IDictionary<string, object>> database, List<string> generatedFiles, List<string> skipFiles) { var file = new FileInfo(Path.Combine(path, FileName)); using (var stream = new MemoryStream()) using (var writer = new StreamWriter(stream, new UTF8Encoding(false))) using (var serializer = new Util.JsonSerializer(writer) { IsOutputFormatted = true }) { serializer.Serialize(database); serializer.Flush(); if (builder.Context.WriteGeneratedFile(null, file, stream)) { generatedFiles.Add(Path.Combine(file.DirectoryName, file.Name)); } else { skipFiles.Add(Path.Combine(file.DirectoryName, file.Name)); } } } private IEnumerable<IDictionary<string, object>> GetEntries(Builder builder, Project.Configuration projectConfiguration, CompileCommandFormat format) { var context = new CompileCommandGenerationContext(builder, projectConfiguration.Project, projectConfiguration); var resolverParams = new[] { new VariableAssignment("project", context.Project), new VariableAssignment("target", context.Configuration.Target), new VariableAssignment("conf", context.Configuration) }; context.EnvironmentVariableResolver = PlatformRegistry.Get<IPlatformDescriptor>(projectConfiguration.Platform).GetPlatformEnvironmentResolver(resolverParams); var factory = new CompileCommandFactory(context); var database = projectConfiguration.Project.GetSourceFilesForConfigurations(new[] { projectConfiguration }) .Except(projectConfiguration.ResolvedSourceFilesBuildExclude) .Where(f => projectConfiguration.Project.SourceFilesCPPExtensions.Contains(Path.GetExtension(f))) .Select(factory.CreateCompileCommand); foreach (var cc in database) { CompileCommandGenerated?.Invoke(context, cc); if (format == CompileCommandFormat.Arguments) { yield return new Dictionary<string, object> { { "directory", cc.Directory }, { "arguments", cc.Arguments }, { "file", cc.File }, }; } else { yield return new Dictionary<string, object> { { "directory", cc.Directory }, { "command", cc.Command }, { "file", cc.File }, }; } } } } public class CompileCommand { public string File { get; set; } public string Directory { get; set; } public string Command { get; set; } public List<string> Arguments { get; set; } } internal class CompileCommandFactory { private const string PrecompNameKey = "PrecompiledHeaderThrough"; private const string PrecompFileKey = "PrecompiledHeaderFile"; private const string AdditionalOptionsKey = "AdditionalCompilerOptions"; private static readonly string[] s_ignoredOptions = new[] { PrecompFileKey, PrecompNameKey, "IntermediateDirectory", "AdditionalDependencies", "AdditionalResourceIncludeDirectories", "TreatWarningAsError" }; private static readonly string[] s_multilineArgumentKeys = new[] { "AdditionalLibraryDirectories", "ManifestInputs" }; private enum CompilerFlags { OutputFile, UsePrecomp, CreatePrecomp, PrecompPath, IncludePath, } private static readonly IDictionary<CompilerFlags, string> s_clangFlags = new Dictionary<CompilerFlags, string> { { CompilerFlags.OutputFile, "-o {0}" }, { CompilerFlags.UsePrecomp, "-include-pch {0}" }, { CompilerFlags.CreatePrecomp, "-x c++-header {0}" }, { CompilerFlags.IncludePath, "-I" }, }; private static readonly IDictionary<CompilerFlags, string> s_vcFlags = new Dictionary<CompilerFlags, string> { { CompilerFlags.OutputFile, "/Fo\"{0}\"" }, { CompilerFlags.UsePrecomp, "/Yu\"{0}\" /FI\"{0}\"" }, { CompilerFlags.CreatePrecomp, "/Yc\"{0}\" /FI\"{0}\"" }, { CompilerFlags.PrecompPath, "/Fp\"{0}\"" }, { CompilerFlags.IncludePath, "/I" }, }; private static readonly ProjectOptionsGenerator s_optionGenerator = new ProjectOptionsGenerator(); private IDictionary<CompilerFlags, string> _flags; private Project.Configuration _config; private string _compiler; private string _projectDirectory; private string _outputDirectory; private string _outputExtension; private string _precompFile; private string _usePrecompArgument; private string _createPrecompArgument; private List<string> _arguments = new List<string>(); public CompileCommandFactory(CompileCommandGenerationContext context) { var isClang = context.Configuration.Platform.IsUsingClang(); var isMicrosoft = context.Configuration.Platform.IsMicrosoft(); _compiler = isClang ? "clang.exe" : "clang-cl.exe"; _config = context.Configuration; _outputExtension = isMicrosoft ? ".obj" : ".o"; _outputDirectory = _config.IntermediatePath; _projectDirectory = context.ProjectDirectoryCapitalized; _flags = isClang ? s_clangFlags : s_vcFlags; s_optionGenerator.GenerateOptions(context, ProjectOptionGenerationLevel.Compiler); _arguments.Add(isClang ? "-c" : "/c"); // Precomp arguments flags are actually written by the bff generator (see bff.template.cs) // Therefore, the CommandLineOptions entries only contain the pch name and file. if (_config.PrecompSource != null) { _precompFile = Path.Combine(_projectDirectory, context.Options[PrecompFileKey]); string name; if (_flags.ContainsKey(CompilerFlags.PrecompPath)) { _arguments.Add(string.Format(_flags[CompilerFlags.PrecompPath], _precompFile)); name = context.Options[PrecompNameKey]; } else { name = _precompFile; } _createPrecompArgument = string.Format(_flags[CompilerFlags.CreatePrecomp], name); _usePrecompArgument = string.Format(_flags[CompilerFlags.UsePrecomp], name); } // AdditionalCompilerOptions are referenced from Options in the bff template. context.CommandLineOptions.Add(AdditionalOptionsKey, context.Options[AdditionalOptionsKey]); var validOptions = context.CommandLineOptions .Where(IsValidOption) .ToDictionary(kvp => kvp.Key, FlattenMultilineArgument); var platformDefineSwitch = isClang ? "-D" : "/D"; if (isMicrosoft) { // Required to avoid errors in VC headers. var value = validOptions.ContainsKey("ExceptionHandling") ? 1 : 0; _arguments.Add($"{platformDefineSwitch}_HAS_EXCEPTIONS={value}"); } _arguments.AddRange(validOptions.Values.SelectMany(x => x)); SelectPreprocessorDefinitions(context, platformDefineSwitch); FillIncludeDirectoriesOptions(context); } private bool IsValidOption(KeyValuePair<string, string> option) { return !option.Value.Equals(FileGeneratorUtilities.RemoveLineTag) && !s_ignoredOptions.Contains(option.Key); } internal static string CmdLineConvertIncludePathsFunc(CompileCommandGenerationContext context, string include, string prefix) { // if the include is below the global root, we compute the relative path, // otherwise it's probably a system include for which we keep the full path string resolvedInclude = context.EnvironmentVariableResolver.Resolve(include); if (resolvedInclude.StartsWith(context.Project.RootPath, StringComparison.OrdinalIgnoreCase)) resolvedInclude = Util.PathGetRelative(context.ProjectDirectory, resolvedInclude, true); return $@"{prefix}""{resolvedInclude}"""; } private void SelectPreprocessorDefinitions(CompileCommandGenerationContext context, string platformDefineSwitch) { var defines = new Strings(); defines.AddRange(context.Options.ExplicitDefines); defines.AddRange(context.Configuration.Defines); foreach (string define in defines.SortedValues) { if (!string.IsNullOrWhiteSpace(define)) _arguments.Add(string.Format(@"{0}{1}{2}{1}", platformDefineSwitch, Util.DoubleQuotes, define.Replace(Util.DoubleQuotes, Util.EscapedDoubleQuotes))); } } private void FillIncludeDirectoriesOptions(CompileCommandGenerationContext context) { // TODO: really not ideal, refactor and move the properties we need from it someplace else var platformVcxproj = PlatformRegistry.Query<IPlatformVcxproj>(context.Configuration.Platform); var includePaths = new OrderableStrings(platformVcxproj.GetIncludePaths(context)); var resourceIncludePaths = new OrderableStrings(platformVcxproj.GetResourceIncludePaths(context)); context.CommandLineOptions["AdditionalIncludeDirectories"] = FileGeneratorUtilities.RemoveLineTag; context.CommandLineOptions["AdditionalResourceIncludeDirectories"] = FileGeneratorUtilities.RemoveLineTag; context.CommandLineOptions["AdditionalUsingDirectories"] = FileGeneratorUtilities.RemoveLineTag; var platformDescriptor = PlatformRegistry.Get<IPlatformDescriptor>(context.Configuration.Platform); string defaultCmdLineIncludePrefix = _flags[CompilerFlags.IncludePath]; // Fill include dirs var dirs = new List<string>(); var platformIncludePaths = platformVcxproj.GetPlatformIncludePathsWithPrefix(context); var platformIncludePathsPrefixed = platformIncludePaths.Select(p => CmdLineConvertIncludePathsFunc(context, p.Path, p.CmdLinePrefix)).ToList(); dirs.AddRange(platformIncludePathsPrefixed); // TODO: move back up, just below the creation of the dirs list dirs.AddRange(includePaths.Select(p => CmdLineConvertIncludePathsFunc(context, p, defaultCmdLineIncludePrefix))); if (dirs.Any()) { context.CommandLineOptions["AdditionalIncludeDirectories"] = string.Join(" ", dirs); _arguments.AddRange(dirs); } // Fill resource include dirs var resourceDirs = new List<string>(); resourceDirs.AddRange(resourceIncludePaths.Select(p => CmdLineConvertIncludePathsFunc(context, p, defaultCmdLineIncludePrefix))); if (Options.GetObject<Options.Vc.General.PlatformToolset>(context.Configuration).IsLLVMToolchain() && Options.GetObject<Options.Vc.LLVM.UseClangCl>(context.Configuration) == Options.Vc.LLVM.UseClangCl.Enable) { // with LLVM as toolchain, we are still using the default resource compiler, so we need the default include prefix // TODO: this is not great, ideally we would need the prefix to be per "compiler", and a platform can have many var platformIncludePathsDefaultPrefix = platformIncludePaths.Select(p => CmdLineConvertIncludePathsFunc(context, p.Path, defaultCmdLineIncludePrefix)); resourceDirs.AddRange(platformIncludePathsDefaultPrefix); } else { resourceDirs.AddRange(platformIncludePathsPrefixed); } if (resourceDirs.Any()) { context.CommandLineOptions["AdditionalResourceIncludeDirectories"] = string.Join(" ", resourceDirs); _arguments.AddRange(resourceDirs); } // Fill using dirs Strings additionalUsingDirectories = Options.GetStrings<Options.Vc.Compiler.AdditionalUsingDirectories>(context.Configuration); additionalUsingDirectories.AddRange(context.Configuration.AdditionalUsingDirectories); additionalUsingDirectories.AddRange(platformVcxproj.GetCxUsingPath(context)); if (additionalUsingDirectories.Any()) { var cmdAdditionalUsingDirectories = additionalUsingDirectories.Select(p => CmdLineConvertIncludePathsFunc(context, p, "/AI")); context.CommandLineOptions["AdditionalUsingDirectories"] = string.Join(" ", cmdAdditionalUsingDirectories); _arguments.AddRange(cmdAdditionalUsingDirectories); } } // ProjectOptionsGenerator will generate format some arguments // (includes, defines, manifests...) specifically for the bff template. // The string is split on multiple lines and concatenated ('foo'\r\n + 'bar') private IList<string> FlattenMultilineArgument(KeyValuePair<string, string> kvp) { if (!s_multilineArgumentKeys.Contains(kvp.Key)) { var parts = kvp.Value.Split(' '); return parts.ToList(); } else { var parts = kvp.Value.Split('\r', '\n') .Select(s => s.Trim(' ', '\t', '\'', '+')); return parts.Where(s => s.Count() > 0).ToList(); } } // TODO: Consider sub-configurations (file specific) public CompileCommand CreateCompileCommand(string inputFile) { string outputFile; string precompArgument; var args = new List<string>(); args.Add(_compiler); if (_config.PrecompSource != null && inputFile.EndsWith(_config.PrecompSource, StringComparison.OrdinalIgnoreCase)) { precompArgument = _createPrecompArgument; outputFile = _precompFile; if (_flags.ContainsKey(CompilerFlags.PrecompPath)) outputFile += _outputExtension; } else { string fileExtension = Path.GetExtension(inputFile); bool isDontUsePrecomp = _config.PrecompSourceExclude.Contains(inputFile) || _config.PrecompSourceExcludeFolders.Any(folder => inputFile.StartsWith(folder, StringComparison.OrdinalIgnoreCase)) || _config.PrecompSourceExcludeExtension.Contains(fileExtension) || string.Compare(fileExtension, ".c", StringComparison.OrdinalIgnoreCase) == 0; if (isDontUsePrecomp == false) { precompArgument = _usePrecompArgument; } else { precompArgument = null; } outputFile = Path.ChangeExtension(Path.Combine(_outputDirectory, Path.GetFileName(inputFile)), _outputExtension); } args.Add(inputFile); args.Add(string.Format(_flags[CompilerFlags.OutputFile], outputFile)); if (!string.IsNullOrEmpty(precompArgument)) args.Add(precompArgument); var command = string.Join(" ", args) + " " + string.Join(" ", _arguments); args.AddRange(_arguments); // Remove unescaped double quote from arguments list (but keep them for the full command line). // This is in fact what will do the shell when it will parse the full command line and give the argv/argc to the program. var match_unescaped_double_quote = new Regex(@"(?<!\\)((\\{2})*)"""); return new CompileCommand { File = inputFile, Directory = _projectDirectory, Command = command, Arguments = args.Select(arg => match_unescaped_double_quote.Replace(arg, "$1")).ToList() }; } } internal class CompileCommandGenerationContext : IGenerationContext { private Resolver _envVarResolver; public Builder Builder { get; private set; } public Project Project { get; private set; } public Project.Configuration Configuration { get; set; } public string ProjectDirectory { get; private set; } public Options.ExplicitOptions Options { get; set; } public IDictionary<string, string> CommandLineOptions { get; set; } public DevEnv DevelopmentEnvironment { get { return Configuration.Compiler; } } public string ProjectDirectoryCapitalized { get; private set; } public string ProjectSourceCapitalized { get; private set; } public bool PlainOutput { get { return true; } } public Resolver EnvironmentVariableResolver { get { System.Diagnostics.Debug.Assert(_envVarResolver != null); return _envVarResolver; } set { _envVarResolver = value; } } public CompileCommandGenerationContext(Builder builder, Project project, Project.Configuration config) { Builder = builder; Project = project; ProjectDirectory = config.ProjectPath; ProjectDirectoryCapitalized = Util.GetCapitalizedPath(ProjectDirectory); ProjectSourceCapitalized = Util.GetCapitalizedPath(project.SourceRootPath); Configuration = config; Options = new Options.ExplicitOptions(); CommandLineOptions = new Dictionary<string, string>(); } public void SelectOption(params Options.OptionAction[] options) { Sharpmake.Options.SelectOption(Configuration, options); } public void SelectOptionWithFallback(Action fallbackAction, params Options.OptionAction[] options) { Sharpmake.Options.SelectOptionWithFallback(Configuration, fallbackAction, options); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Xml; using Microsoft.Build.Framework; using Microsoft.Build.BuildEngine.Shared; namespace Microsoft.Build.BuildEngine { /// <summary> /// This class is responsible for determining on which node and when a task should be executed. It /// receives work requests from the Target class and communicates to the appropriate node. /// </summary> internal class Scheduler { #region Constructors /// <summary> /// Create the scheduler. /// </summary> /// <param name="nodeId">the id of the node where the scheduler was instantiated on</param> /// <param name="parentEngine">a reference to the engine who instantiated the scheduler</param> internal Scheduler(int nodeId, Engine parentEngine) { this.localNodeId = nodeId; this.childMode = true; this.parentEngine = parentEngine; } #endregion #region Properties #endregion #region Methods /// <summary> /// Provide the scheduler with the information about the available nodes. This function has to be /// called after the NodeManager has initialzed all the node providers /// </summary> internal void Initialize(INodeDescription[] nodeDescriptions) { this.nodes = nodeDescriptions; this.childMode = false; this.handleIdToScheduleRecord = new Dictionary<ScheduleRecordKey, ScheduleRecord>(); this.scheduleTableLock = new object(); this.totalRequestsPerNode = new int[nodes.Length]; this.blockedRequestsPerNode = new int[nodes.Length]; this.postBlockCount = new int[nodes.Length]; for (int i = 0; i < totalRequestsPerNode.Length; i++) { totalRequestsPerNode[i] = 0; blockedRequestsPerNode[i] = 0; postBlockCount[i] = 0; } this.useLoadBalancing = (Environment.GetEnvironmentVariable("MSBUILDLOADBALANCE") != "0"); this.lastUsedNode = 0; } /// <summary> /// This method specifies which node a particular build request has to be evaluated on. /// </summary>> /// <returns>Id of the node on which the build request should be performed</returns> internal int CalculateNodeForBuildRequest(BuildRequest currentRequest, int nodeIndexCurrent) { int nodeUsed = EngineCallback.inProcNode; if (childMode) { // If the project is already loaded on the current node or if the request // was sent from the parent - evaluate the request locally. In all other // cases send the request over to the parent if (nodeIndexCurrent != localNodeId && !currentRequest.IsExternalRequest) { // This is the same as using EngineCallback.parentNode nodeUsed = -1; } } else { // In single proc case return the current node if (nodes.Length == 1) { return nodeUsed; } // If the project is not loaded either locally or on a remote node - calculate the best node to use // If there are nodes with less than "nodeWorkLoadProjectCount" projects in progress, choose the node // with the lowest in progress projects. Otherwise choose a node which has the least // number of projects loaded. Resolve a tie in number of projects loaded by looking at the number // of inprogress projects nodeUsed = nodeIndexCurrent; // If we have not chosen an node yet, this can happen if the node was loaded previously on a child node if (nodeUsed == EngineCallback.invalidNode) { if (useLoadBalancing) { #region UseLoadBalancing int blockedNode = EngineCallback.invalidNode; int blockedNodeRemainingProjectCount = nodeWorkLoadProjectCount; int leastBusyNode = EngineCallback.invalidNode; int leastBusyInProgressCount = -1; int leastLoadedNode = EngineCallback.inProcNode; int leastLoadedLoadCount = totalRequestsPerNode[EngineCallback.inProcNode]; int leastLoadedBlockedCount = blockedRequestsPerNode[EngineCallback.inProcNode]; for (int i = 0; i < nodes.Length; i++) { //postBlockCount indicates the number of projects which should be sent to a node to unblock it due to the //node running out of work. if (postBlockCount[i] != 0 && postBlockCount[i] < blockedNodeRemainingProjectCount) { blockedNode = i; blockedNodeRemainingProjectCount = postBlockCount[i]; } else { // Figure out which node has the least ammount of in progress work int perNodeInProgress = totalRequestsPerNode[i] - blockedRequestsPerNode[i]; if ((perNodeInProgress < nodeWorkLoadProjectCount) && (perNodeInProgress < leastBusyInProgressCount || leastBusyInProgressCount == -1)) { leastBusyNode = i; leastBusyInProgressCount = perNodeInProgress; } // Find the node with the least ammount of requests in total // or if the number of requests are the same find the node with the // node with the least number of blocked requests if ((totalRequestsPerNode[i] < leastLoadedLoadCount) || (totalRequestsPerNode[i] == leastLoadedLoadCount && blockedRequestsPerNode[i] < leastLoadedBlockedCount)) { leastLoadedNode = i; leastLoadedLoadCount = totalRequestsPerNode[i]; leastLoadedBlockedCount = perNodeInProgress; } } } // Give the work to a node blocked due to having no work . If there are no nodes without work // give the work to the least loaded node if (blockedNode != EngineCallback.invalidNode) { nodeUsed = blockedNode; postBlockCount[blockedNode]--; } else { nodeUsed = (leastBusyNode != EngineCallback.invalidNode) ? leastBusyNode : leastLoadedNode; } #endregion } else { // round robin schedule the build request nodeUsed = (lastUsedNode % nodes.Length); // Running total of the number of times this round robin scheduler has been called lastUsedNode++; if (postBlockCount[nodeUsed] != 0) { postBlockCount[nodeUsed]--; } } } // Update the internal data structure to reflect the scheduling decision NotifyOfSchedulingDecision(currentRequest, nodeUsed); } return nodeUsed; } /// <summary> /// This method is called to update the datastructures to reflect that given request will /// be built on a given node. /// </summary> /// <param name="currentRequest"></param> /// <param name="nodeUsed"></param> internal void NotifyOfSchedulingDecision(BuildRequest currentRequest, int nodeUsed) { // Don't update structures on the child node or in single proc mode if (childMode || nodes.Length == 1) { return; } // Update the count of requests being build on the node totalRequestsPerNode[nodeUsed]++; // Ignore host requests if (currentRequest.HandleId == EngineCallback.invalidEngineHandle) { return; } if (Engine.debugMode) { string targetnames = currentRequest.TargetNames != null ? String.Join(";", currentRequest.TargetNames) : "null"; Console.WriteLine("Sending project " + currentRequest.ProjectFileName + " Target " + targetnames + " to " + nodeUsed); } // Update the records ScheduleRecordKey recordKey = new ScheduleRecordKey(currentRequest.HandleId, currentRequest.RequestId); ScheduleRecordKey parentKey = new ScheduleRecordKey(currentRequest.ParentHandleId, currentRequest.ParentRequestId); ScheduleRecord record = new ScheduleRecord(recordKey, parentKey, nodeUsed, currentRequest.ProjectFileName, currentRequest.ToolsetVersion, currentRequest.TargetNames); lock (scheduleTableLock) { ErrorUtilities.VerifyThrow(!handleIdToScheduleRecord.ContainsKey(recordKey), "Schedule record should not be in the table"); handleIdToScheduleRecord.Add(recordKey, record); // The ParentHandleId is an invalidEngineHandle when the host is the one who created // the current request if (currentRequest.ParentHandleId != EngineCallback.invalidEngineHandle) { ErrorUtilities.VerifyThrow(handleIdToScheduleRecord.ContainsKey(parentKey), "Parent schedule record should be in the table"); ScheduleRecord parentRecord = handleIdToScheduleRecord[parentKey]; if (!parentRecord.Blocked) { blockedRequestsPerNode[parentRecord.EvaluationNode]++; } parentRecord.AddChildRecord(record); } } } /// <summary> /// This method is called when a build request is completed on a particular node. NodeId is never used instead we look up the node from the build request /// and the schedule record table /// </summary> internal void NotifyOfBuildResult(int nodeId, BuildResult buildResult) { if (!childMode && nodes.Length > 1) { // Ignore host requests if (buildResult.HandleId == EngineCallback.invalidEngineHandle) { return; } ScheduleRecordKey recordKey = new ScheduleRecordKey(buildResult.HandleId, buildResult.RequestId); ScheduleRecord scheduleRecord = null; lock (scheduleTableLock) { ErrorUtilities.VerifyThrow(handleIdToScheduleRecord.ContainsKey(recordKey), "Schedule record should be in the table"); scheduleRecord = handleIdToScheduleRecord[recordKey]; totalRequestsPerNode[scheduleRecord.EvaluationNode]--; handleIdToScheduleRecord.Remove(recordKey); if (scheduleRecord.ParentKey.HandleId != EngineCallback.invalidEngineHandle) { ErrorUtilities.VerifyThrow(handleIdToScheduleRecord.ContainsKey(scheduleRecord.ParentKey), "Parent schedule record should be in the table"); ScheduleRecord parentRecord = handleIdToScheduleRecord[scheduleRecord.ParentKey]; // As long as there are child requests under the parent request the parent request is considered blocked // Remove this build request from the list of requests the parent request is waiting on. This may unblock the parent request parentRecord.ReportChildCompleted(recordKey); // If completing the child request has unblocked the parent request due to all of the the Child requests being completed // decrement the number of blocked requests. if (!parentRecord.Blocked) { blockedRequestsPerNode[parentRecord.EvaluationNode]--; } } } // Dump some interesting information to the console if profile build is turned on by an environment variable if (parentEngine.ProfileBuild && scheduleRecord != null && buildResult.TaskTime != 0 ) { Console.WriteLine("N " + scheduleRecord.EvaluationNode + " Name " + scheduleRecord.ProjectName + ":" + scheduleRecord.ParentKey.HandleId + ":" + scheduleRecord.ParentKey.RequestId + " Total " + buildResult.TotalTime + " Engine " + buildResult.EngineTime + " Task " + buildResult.TaskTime); } } } /// <summary> /// Called when the engine is in the process of sending a buildRequest to a child node. The entire purpose of this method /// is to switch the traversal strategy of the systems if there are nodes which do not have enough work availiable to them. /// </summary> internal void NotifyOfBuildRequest(int nodeIndex, BuildRequest currentRequest, int parentHandleId) { // This will only be null when the scheduler is instantiated on a child process in which case the initialize method // of the scheduler will not be called and therefore not initialize totalRequestsPerNode. if (totalRequestsPerNode != null) { // Check if it makes sense to switch from one traversal strategy to the other if (parentEngine.NodeManager.TaskExecutionModule.UseBreadthFirstTraversal == true) { // Check if a switch to depth first traversal is in order bool useBreadthFirstTraversal = false; for (int i = 0; i < totalRequestsPerNode.Length; i++) { // Continue using breadth-first traversal as long as the non-blocked work load for this node is below // the nodeWorkloadProjectCount or its postBlockCount is non-zero if ((totalRequestsPerNode[i] - blockedRequestsPerNode[i]) < nodeWorkLoadProjectCount || postBlockCount[i] != 0 ) { useBreadthFirstTraversal = true; break; } } if (useBreadthFirstTraversal == false) { if (Engine.debugMode) { Console.WriteLine("Switching to depth first traversal because all node have workitems"); } parentEngine.NodeManager.TaskExecutionModule.UseBreadthFirstTraversal = false; // Switch to depth first and change the traversal strategy of the entire system by notifying all child nodes of the change parentEngine.PostEngineCommand(new ChangeTraversalTypeCommand(false, false)); } } } } /// <summary> /// Called by the engine to indicate that a particular request is blocked waiting for another /// request to finish building a target. /// </summary> internal void NotifyOfBlockedRequest(BuildRequest currentRequest) { if (!childMode && nodes.Length > 1) { ScheduleRecordKey recordKey = new ScheduleRecordKey(currentRequest.HandleId, currentRequest.RequestId); // Ignore host requests if (currentRequest.HandleId == EngineCallback.invalidEngineHandle) { return; } lock (scheduleTableLock) { ErrorUtilities.VerifyThrow(handleIdToScheduleRecord.ContainsKey(recordKey), "Schedule record should be in the table"); handleIdToScheduleRecord[recordKey].Blocked = true; blockedRequestsPerNode[handleIdToScheduleRecord[recordKey].EvaluationNode]++; } } } /// <summary> /// Called by the engine to indicate that a particular request is no longer blocked waiting for another /// request to finish building a target /// </summary> internal void NotifyOfUnblockedRequest(BuildRequest currentRequest) { if (!childMode && nodes.Length > 1) { ScheduleRecordKey recordKey = new ScheduleRecordKey(currentRequest.HandleId, currentRequest.RequestId); lock (scheduleTableLock) { ErrorUtilities.VerifyThrow(handleIdToScheduleRecord.ContainsKey(recordKey), "Schedule record should be in the table"); handleIdToScheduleRecord[recordKey].Blocked = false; blockedRequestsPerNode[handleIdToScheduleRecord[recordKey].EvaluationNode]--; } } } /// <summary> /// Called by the engine to indicate that a node has run out of work /// </summary> /// <param name="nodeIndex"></param> internal void NotifyOfBlockedNode(int nodeId) { if (Engine.debugMode) { Console.WriteLine("Switch to breadth first traversal is requested by " + nodeId); } postBlockCount[nodeId] = nodeWorkLoadProjectCount/2; } /// <summary> /// Used by the introspector to dump the state when the nodes are being shutdown due to an error. /// </summary> internal void DumpState() { for (int i = 0; i < totalRequestsPerNode.Length; i++) { Console.WriteLine("Node " + i + " Outstanding " + totalRequestsPerNode[i] + " Blocked " + blockedRequestsPerNode[i]); } foreach (ScheduleRecordKey key in handleIdToScheduleRecord.Keys) { ScheduleRecord record = handleIdToScheduleRecord[key]; Console.WriteLine(key.HandleId + ":" + key.RequestId + " " + record.ProjectName + " on node " + record.EvaluationNode); } } #endregion #region Data /// <summary> /// NodeId of the engine who instantiated the scheduler. This is used to determine if a /// BuildRequest should be build locally as the project has already been loaded on this node. /// </summary> private int localNodeId; /// <summary> /// An array of nodes to which the scheduler can schedule work. /// </summary> private INodeDescription[] nodes; /// <summary> /// Counts the total number of outstanding requests (no result has been seen for the request) for a node. /// This is incremented in NotifyOfSchedulingDecision when a request it given to a node /// and decremented in NotifyOfBuildResult when results are returned (posted) from a node. /// </summary> private int[] totalRequestsPerNode; /// <summary> /// The number of BuildRequests blocked waiting for results for each node. /// This will be incremented once when a build request is scheduled which was generated as part of a msbuild callback /// and once for each call to NotifyOfBlockedRequest. /// /// It is decremented for each call to NotifyOfUnblockedRequest and once all of the child requests have been fullfilled. /// </summary> private int[] blockedRequestsPerNode; /// <summary> /// Keeps track of how many projects need to be sent to a node after the node has told the scheduler it has run out of work. /// </summary> private int[] postBlockCount; /// <summary> /// Indicates the scheduler should balance work accross nodes. /// This is only true when the environment variable MSBUILDLOADBALANCE is not 0 /// </summary> private bool useLoadBalancing; /// <summary> /// Lock object for the handleIdToScheduleRecord dictionary /// </summary> private object scheduleTableLock; /// <summary> /// Keep track of build requsts to determine how many requests are blocked waiting on other build requests to complete. /// </summary> private Dictionary<ScheduleRecordKey, ScheduleRecord> handleIdToScheduleRecord; /// <summary> /// Indicates the scheduler is instantiated on a child node. This is being determined by /// initializaing the variable to true in the constructor and then setting it to false in the /// initialize method (the initialize method will only be called on the parent engine) /// </summary> private bool childMode; /// <summary> /// Reference to the engine who instantiated the scheduler /// </summary> private Engine parentEngine; /// <summary> /// Number of requests a node should have in an unblocked state before the system switches to a depth first traversal strategy. /// </summary> private const int nodeWorkLoadProjectCount = 4; /// <summary> /// Used to calculate which node a build request should be sent to if the scheduler is operating in a round robin fashion. /// Each time a build request is scheduled to a node in CalculateNodeForBuildRequest the lastUsedNode is incremented. /// This value is then mod'd (%) with the number of nodes to alternate which node the next build request goes to. /// </summary> private int lastUsedNode; #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.Collections.Generic; using System.ComponentModel; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Net; using System.Runtime; using System.ServiceModel.Channels; using System.ServiceModel.Security; using Microsoft.Xml; namespace System.ServiceModel.Dispatcher { [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Compat", Justification = "Compat is an accepted abbreviation")] [EditorBrowsable(EditorBrowsableState.Never)] public class ClientRuntimeCompatBase { internal ClientRuntimeCompatBase() { } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public IList<IClientMessageInspector> MessageInspectors { get { return this.messageInspectors; } } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public KeyedCollection<string, ClientOperation> Operations { get { return this.compatOperations; } } internal SynchronizedCollection<IClientMessageInspector> messageInspectors; internal SynchronizedKeyedCollection<string, ClientOperation> operations; internal KeyedCollection<string, ClientOperation> compatOperations; } public sealed class ClientRuntime : ClientRuntimeCompatBase { private bool _addTransactionFlowProperties = true; private Type _callbackProxyType; private ProxyBehaviorCollection<IChannelInitializer> _channelInitializers; private string _contractName; private string _contractNamespace; private Type _contractProxyType; private DispatchRuntime _dispatchRuntime; private IdentityVerifier _identityVerifier; private ProxyBehaviorCollection<IInteractiveChannelInitializer> _interactiveChannelInitializers; private IClientOperationSelector _operationSelector; private ImmutableClientRuntime _runtime; private ClientOperation _unhandled; private bool _useSynchronizationContext = true; private Uri _via; private SharedRuntimeState _shared; private int _maxFaultSize; private bool _messageVersionNoneFaultsEnabled; internal ClientRuntime(DispatchRuntime dispatchRuntime, SharedRuntimeState shared) : this(dispatchRuntime.EndpointDispatcher.ContractName, dispatchRuntime.EndpointDispatcher.ContractNamespace, shared) { if (dispatchRuntime == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("dispatchRuntime"); _dispatchRuntime = dispatchRuntime; _shared = shared; Fx.Assert(shared.IsOnServer, "Server constructor called on client?"); } internal ClientRuntime(string contractName, string contractNamespace) : this(contractName, contractNamespace, new SharedRuntimeState(false)) { Fx.Assert(!_shared.IsOnServer, "Client constructor called on server?"); } private ClientRuntime(string contractName, string contractNamespace, SharedRuntimeState shared) { _contractName = contractName; _contractNamespace = contractNamespace; _shared = shared; OperationCollection operations = new OperationCollection(this); this.operations = operations; this.compatOperations = new OperationCollectionWrapper(operations); _channelInitializers = new ProxyBehaviorCollection<IChannelInitializer>(this); this.messageInspectors = new ProxyBehaviorCollection<IClientMessageInspector>(this); _interactiveChannelInitializers = new ProxyBehaviorCollection<IInteractiveChannelInitializer>(this); _unhandled = new ClientOperation(this, "*", MessageHeaders.WildcardAction, MessageHeaders.WildcardAction); _unhandled.InternalFormatter = new MessageOperationFormatter(); _maxFaultSize = TransportDefaults.MaxFaultSize; } internal bool AddTransactionFlowProperties { get { return _addTransactionFlowProperties; } set { lock (this.ThisLock) { this.InvalidateRuntime(); _addTransactionFlowProperties = value; } } } public Type CallbackClientType { get { return _callbackProxyType; } set { lock (this.ThisLock) { this.InvalidateRuntime(); _callbackProxyType = value; } } } public SynchronizedCollection<IChannelInitializer> ChannelInitializers { get { return _channelInitializers; } } public string ContractName { get { return _contractName; } } public string ContractNamespace { get { return _contractNamespace; } } public Type ContractClientType { get { return _contractProxyType; } set { lock (this.ThisLock) { this.InvalidateRuntime(); _contractProxyType = value; } } } internal IdentityVerifier IdentityVerifier { get { if (_identityVerifier == null) { _identityVerifier = IdentityVerifier.CreateDefault(); } return _identityVerifier; } set { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } this.InvalidateRuntime(); _identityVerifier = value; } } public Uri Via { get { return _via; } set { lock (this.ThisLock) { this.InvalidateRuntime(); _via = value; } } } public bool ValidateMustUnderstand { get { return _shared.ValidateMustUnderstand; } set { lock (this.ThisLock) { this.InvalidateRuntime(); _shared.ValidateMustUnderstand = value; } } } public bool MessageVersionNoneFaultsEnabled { get { return _messageVersionNoneFaultsEnabled; } set { this.InvalidateRuntime(); _messageVersionNoneFaultsEnabled = value; } } public DispatchRuntime DispatchRuntime { get { return _dispatchRuntime; } } public DispatchRuntime CallbackDispatchRuntime { get { if (_dispatchRuntime == null) _dispatchRuntime = new DispatchRuntime(this, _shared); return _dispatchRuntime; } } internal bool EnableFaults { get { if (this.IsOnServer) { return _dispatchRuntime.EnableFaults; } else { return _shared.EnableFaults; } } set { lock (this.ThisLock) { if (this.IsOnServer) { string text = SRServiceModel.SFxSetEnableFaultsOnChannelDispatcher0; throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(text)); } else { this.InvalidateRuntime(); _shared.EnableFaults = value; } } } } public SynchronizedCollection<IInteractiveChannelInitializer> InteractiveChannelInitializers { get { return _interactiveChannelInitializers; } } public int MaxFaultSize { get { return _maxFaultSize; } set { this.InvalidateRuntime(); _maxFaultSize = value; } } internal bool IsOnServer { get { return _shared.IsOnServer; } } public bool ManualAddressing { get { if (this.IsOnServer) { return _dispatchRuntime.ManualAddressing; } else { return _shared.ManualAddressing; } } set { lock (this.ThisLock) { if (this.IsOnServer) { string text = SRServiceModel.SFxSetManualAddresssingOnChannelDispatcher0; throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(text)); } else { this.InvalidateRuntime(); _shared.ManualAddressing = value; } } } } internal int MaxParameterInspectors { get { lock (this.ThisLock) { int max = 0; for (int i = 0; i < this.operations.Count; i++) max = System.Math.Max(max, this.operations[i].ParameterInspectors.Count); return max; } } } public ICollection<IClientMessageInspector> ClientMessageInspectors { get { return this.MessageInspectors; } } [EditorBrowsable(EditorBrowsableState.Never)] public new SynchronizedCollection<IClientMessageInspector> MessageInspectors { get { return this.messageInspectors; } } public ICollection<ClientOperation> ClientOperations { get { return this.Operations; } } [EditorBrowsable(EditorBrowsableState.Never)] public new SynchronizedKeyedCollection<string, ClientOperation> Operations { get { return this.operations; } } public IClientOperationSelector OperationSelector { get { return _operationSelector; } set { lock (this.ThisLock) { this.InvalidateRuntime(); _operationSelector = value; } } } internal object ThisLock { get { return _shared; } } public ClientOperation UnhandledClientOperation { get { return _unhandled; } } internal bool UseSynchronizationContext { get { return _useSynchronizationContext; } set { lock (this.ThisLock) { this.InvalidateRuntime(); _useSynchronizationContext = value; } } } internal T[] GetArray<T>(SynchronizedCollection<T> collection) { lock (collection.SyncRoot) { if (collection.Count == 0) { return Array.Empty<T>(); } else { T[] array = new T[collection.Count]; collection.CopyTo(array, 0); return array; } } } internal ImmutableClientRuntime GetRuntime() { lock (this.ThisLock) { if (_runtime == null) _runtime = new ImmutableClientRuntime(this); return _runtime; } } internal void InvalidateRuntime() { lock (this.ThisLock) { _shared.ThrowIfImmutable(); _runtime = null; } } internal void LockDownProperties() { _shared.LockDownProperties(); } internal SynchronizedCollection<T> NewBehaviorCollection<T>() { return new ProxyBehaviorCollection<T>(this); } internal bool IsFault(ref Message reply) { if (reply == null) { return false; } if (reply.IsFault) { return true; } if (this.MessageVersionNoneFaultsEnabled && IsMessageVersionNoneFault(ref reply, this.MaxFaultSize)) { return true; } return false; } internal static bool IsMessageVersionNoneFault(ref Message message, int maxFaultSize) { if (message.Version != MessageVersion.None || message.IsEmpty) { return false; } HttpResponseMessageProperty prop = message.Properties[HttpResponseMessageProperty.Name] as HttpResponseMessageProperty; if (prop == null || prop.StatusCode != HttpStatusCode.InternalServerError) { return false; } using (MessageBuffer buffer = message.CreateBufferedCopy(maxFaultSize)) { message.Close(); message = buffer.CreateMessage(); using (Message copy = buffer.CreateMessage()) { using (XmlDictionaryReader reader = copy.GetReaderAtBodyContents()) { return reader.IsStartElement(XD.MessageDictionary.Fault, MessageVersion.None.Envelope.DictionaryNamespace); } } } } internal class ProxyBehaviorCollection<T> : SynchronizedCollection<T> { private ClientRuntime _outer; internal ProxyBehaviorCollection(ClientRuntime outer) : base(outer.ThisLock) { _outer = outer; } protected override void ClearItems() { _outer.InvalidateRuntime(); base.ClearItems(); } protected override void InsertItem(int index, T item) { if (item == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("item"); } _outer.InvalidateRuntime(); base.InsertItem(index, item); } protected override void RemoveItem(int index) { _outer.InvalidateRuntime(); base.RemoveItem(index); } protected override void SetItem(int index, T item) { if (item == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("item"); } _outer.InvalidateRuntime(); base.SetItem(index, item); } } internal class OperationCollection : SynchronizedKeyedCollection<string, ClientOperation> { private ClientRuntime _outer; internal OperationCollection(ClientRuntime outer) : base(outer.ThisLock) { _outer = outer; } protected override void ClearItems() { _outer.InvalidateRuntime(); base.ClearItems(); } protected override string GetKeyForItem(ClientOperation item) { return item.Name; } protected override void InsertItem(int index, ClientOperation item) { if (item == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("item"); if (item.Parent != _outer) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SRServiceModel.SFxMismatchedOperationParent); _outer.InvalidateRuntime(); base.InsertItem(index, item); } protected override void RemoveItem(int index) { _outer.InvalidateRuntime(); base.RemoveItem(index); } protected override void SetItem(int index, ClientOperation item) { if (item == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("item"); if (item.Parent != _outer) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SRServiceModel.SFxMismatchedOperationParent); _outer.InvalidateRuntime(); base.SetItem(index, item); } internal void InternalClearItems() { this.ClearItems(); } internal string InternalGetKeyForItem(ClientOperation item) { return this.GetKeyForItem(item); } internal void InternalInsertItem(int index, ClientOperation item) { this.InsertItem(index, item); } internal void InternalRemoveItem(int index) { this.RemoveItem(index); } internal void InternalSetItem(int index, ClientOperation item) { this.SetItem(index, item); } } internal class OperationCollectionWrapper : KeyedCollection<string, ClientOperation> { private OperationCollection _inner; internal OperationCollectionWrapper(OperationCollection inner) { _inner = inner; } protected override void ClearItems() { _inner.InternalClearItems(); } protected override string GetKeyForItem(ClientOperation item) { return _inner.InternalGetKeyForItem(item); } protected override void InsertItem(int index, ClientOperation item) { _inner.InternalInsertItem(index, item); } protected override void RemoveItem(int index) { _inner.InternalRemoveItem(index); } protected override void SetItem(int index, ClientOperation item) { _inner.InternalSetItem(index, item); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; namespace Rhino.Queues.Utils { /// <summary> /// We have to use this stupid trick because HttpUtility.UrlEncode / Decode /// uses HttpContext.Current under the covers, which doesn't work in IIS7 /// Application_Start /// </summary> public class MonoHttpUtility { public static string UrlDecode(string str) { return UrlDecode(str, Encoding.UTF8); } static char[] GetChars(MemoryStream b, Encoding e) { return e.GetChars(b.GetBuffer(), 0, (int)b.Length); } static void WriteCharBytes(IList buf, char ch, Encoding e) { if (ch > 255) { foreach (byte b in e.GetBytes(new char[] { ch })) buf.Add(b); } else buf.Add((byte)ch); } public static string UrlDecode(string s, Encoding e) { if (null == s) return null; if (s.IndexOf('%') == -1 && s.IndexOf('+') == -1) return s; if (e == null) e = Encoding.UTF8; long len = s.Length; var bytes = new List<byte>(); int xchar; char ch; for (int i = 0; i < len; i++) { ch = s[i]; if (ch == '%' && i + 2 < len && s[i + 1] != '%') { if (s[i + 1] == 'u' && i + 5 < len) { // unicode hex sequence xchar = GetChar(s, i + 2, 4); if (xchar != -1) { WriteCharBytes(bytes, (char)xchar, e); i += 5; } else WriteCharBytes(bytes, '%', e); } else if ((xchar = GetChar(s, i + 1, 2)) != -1) { WriteCharBytes(bytes, (char)xchar, e); i += 2; } else { WriteCharBytes(bytes, '%', e); } continue; } if (ch == '+') WriteCharBytes(bytes, ' ', e); else WriteCharBytes(bytes, ch, e); } byte[] buf = bytes.ToArray(); bytes = null; return e.GetString(buf); } public static string UrlDecode(byte[] bytes, Encoding e) { if (bytes == null) return null; return UrlDecode(bytes, 0, bytes.Length, e); } static int GetInt(byte b) { char c = (char)b; if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return c - 'a' + 10; if (c >= 'A' && c <= 'F') return c - 'A' + 10; return -1; } static int GetChar(byte[] bytes, int offset, int length) { int value = 0; int end = length + offset; for (int i = offset; i < end; i++) { int current = GetInt(bytes[i]); if (current == -1) return -1; value = (value << 4) + current; } return value; } static int GetChar(string str, int offset, int length) { int val = 0; int end = length + offset; for (int i = offset; i < end; i++) { char c = str[i]; if (c > 127) return -1; int current = GetInt((byte)c); if (current == -1) return -1; val = (val << 4) + current; } return val; } public static string UrlDecode(byte[] bytes, int offset, int count, Encoding e) { if (bytes == null) return null; if (count == 0) return String.Empty; if (bytes == null) throw new ArgumentNullException("bytes"); if (offset < 0 || offset > bytes.Length) throw new ArgumentOutOfRangeException("offset"); if (count < 0 || offset + count > bytes.Length) throw new ArgumentOutOfRangeException("count"); StringBuilder output = new StringBuilder(); MemoryStream acc = new MemoryStream(); int end = count + offset; int xchar; for (int i = offset; i < end; i++) { if (bytes[i] == '%' && i + 2 < count && bytes[i + 1] != '%') { if (bytes[i + 1] == (byte)'u' && i + 5 < end) { if (acc.Length > 0) { output.Append(GetChars(acc, e)); acc.SetLength(0); } xchar = GetChar(bytes, i + 2, 4); if (xchar != -1) { output.Append((char)xchar); i += 5; continue; } } else if ((xchar = GetChar(bytes, i + 1, 2)) != -1) { acc.WriteByte((byte)xchar); i += 2; continue; } } if (acc.Length > 0) { output.Append(GetChars(acc, e)); acc.SetLength(0); } if (bytes[i] == '+') { output.Append(' '); } else { output.Append((char)bytes[i]); } } if (acc.Length > 0) { output.Append(GetChars(acc, e)); } acc = null; return output.ToString(); } public static byte[] UrlDecodeToBytes(byte[] bytes) { if (bytes == null) return null; return UrlDecodeToBytes(bytes, 0, bytes.Length); } public static byte[] UrlDecodeToBytes(string str) { return UrlDecodeToBytes(str, Encoding.UTF8); } public static byte[] UrlDecodeToBytes(string str, Encoding e) { if (str == null) return null; if (e == null) throw new ArgumentNullException("e"); return UrlDecodeToBytes(e.GetBytes(str)); } public static byte[] UrlDecodeToBytes(byte[] bytes, int offset, int count) { if (bytes == null) return null; if (count == 0) return new byte[0]; int len = bytes.Length; if (offset < 0 || offset >= len) throw new ArgumentOutOfRangeException("offset"); if (count < 0 || offset > len - count) throw new ArgumentOutOfRangeException("count"); MemoryStream result = new MemoryStream(); int end = offset + count; for (int i = offset; i < end; i++) { char c = (char)bytes[i]; if (c == '+') { c = ' '; } else if (c == '%' && i < end - 2) { int xchar = GetChar(bytes, i + 1, 2); if (xchar != -1) { c = (char)xchar; i += 2; } } result.WriteByte((byte)c); } return result.ToArray(); } public static string UrlEncode(string str) { return UrlEncode(str, Encoding.UTF8); } public static string UrlEncode(string s, Encoding Enc) { if (s == null) return null; if (s == String.Empty) return String.Empty; bool needEncode = false; int len = s.Length; for (int i = 0; i < len; i++) { char c = s[i]; if ((c < '0') || (c < 'A' && c > '9') || (c > 'Z' && c < 'a') || (c > 'z')) { if (MonoHttpEncoder.NotEncoded(c)) continue; needEncode = true; break; } } if (!needEncode) return s; // avoided GetByteCount call byte[] bytes = new byte[Enc.GetMaxByteCount(s.Length)]; int realLen = Enc.GetBytes(s, 0, s.Length, bytes, 0); return Encoding.ASCII.GetString(UrlEncodeToBytes(bytes, 0, realLen)); } public static string UrlEncode(byte[] bytes) { if (bytes == null) return null; if (bytes.Length == 0) return String.Empty; return Encoding.ASCII.GetString(UrlEncodeToBytes(bytes, 0, bytes.Length)); } public static string UrlEncode(byte[] bytes, int offset, int count) { if (bytes == null) return null; if (bytes.Length == 0) return String.Empty; return Encoding.ASCII.GetString(UrlEncodeToBytes(bytes, offset, count)); } public static byte[] UrlEncodeToBytes(string str) { return UrlEncodeToBytes(str, Encoding.UTF8); } public static byte[] UrlEncodeToBytes(string str, Encoding e) { if (str == null) return null; if (str.Length == 0) return new byte[0]; byte[] bytes = e.GetBytes(str); return UrlEncodeToBytes(bytes, 0, bytes.Length); } public static byte[] UrlEncodeToBytes(byte[] bytes) { if (bytes == null) return null; if (bytes.Length == 0) return new byte[0]; return UrlEncodeToBytes(bytes, 0, bytes.Length); } public static byte[] UrlEncodeToBytes(byte[] bytes, int offset, int count) { if (bytes == null) return null; #if NET_4_0 return MonoHttpEncoder.Current.UrlEncode(bytes, offset, count); #else return MonoHttpEncoder.UrlEncodeToBytes (bytes, offset, count); #endif } public static string UrlEncodeUnicode(string str) { if (str == null) return null; return Encoding.ASCII.GetString(UrlEncodeUnicodeToBytes(str)); } public static byte[] UrlEncodeUnicodeToBytes(string str) { if (str == null) return null; if (str.Length == 0) return new byte[0]; MemoryStream result = new MemoryStream(str.Length); foreach (char c in str) { MonoHttpEncoder.UrlEncodeChar(c, result, true); } return result.ToArray(); } } }
// Copyright (c) 1995-2009 held by the author(s). All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the names of the Naval Postgraduate School (NPS) // Modeling Virtual Environments and Simulation (MOVES) Institute // (http://www.nps.edu and http://www.MovesInstitute.org) // nor the names of its contributors may be used to endorse or // promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All // rights reserved. This work is licensed under the BSD open source license, // available at https://www.movesinstitute.org/licenses/bsd.html // // Author: DMcG // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - [email protected]) using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using System.Xml.Serialization; using OpenDis.Core; namespace OpenDis.Dis1995 { /// <summary> /// 64 bit piece of data /// </summary> [Serializable] [XmlRoot] public partial class EightByteChunk { /// <summary> /// Eight bytes of arbitrary data /// </summary> private byte[] _otherParameters = new byte[8]; /// <summary> /// Initializes a new instance of the <see cref="EightByteChunk"/> class. /// </summary> public EightByteChunk() { } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator !=(EightByteChunk left, EightByteChunk right) { return !(left == right); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public static bool operator ==(EightByteChunk left, EightByteChunk right) { if (object.ReferenceEquals(left, right)) { return true; } if (((object)left == null) || ((object)right == null)) { return false; } return left.Equals(right); } public virtual int GetMarshalledSize() { int marshalSize = 0; marshalSize += 8 * 1; // _otherParameters return marshalSize; } /// <summary> /// Gets or sets the Eight bytes of arbitrary data /// </summary> [XmlArray(ElementName = "otherParameters")] public byte[] OtherParameters { get { return this._otherParameters; } set { this._otherParameters = value; } } /// <summary> /// Occurs when exception when processing PDU is caught. /// </summary> public event EventHandler<PduExceptionEventArgs> ExceptionOccured; /// <summary> /// Called when exception occurs (raises the <see cref="Exception"/> event). /// </summary> /// <param name="e">The exception.</param> protected void RaiseExceptionOccured(Exception e) { if (Pdu.FireExceptionEvents && this.ExceptionOccured != null) { this.ExceptionOccured(this, new PduExceptionEventArgs(e)); } } /// <summary> /// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public virtual void Marshal(DataOutputStream dos) { if (dos != null) { try { for (int idx = 0; idx < this._otherParameters.Length; idx++) { dos.WriteByte(this._otherParameters[idx]); } } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public virtual void Unmarshal(DataInputStream dis) { if (dis != null) { try { for (int idx = 0; idx < this._otherParameters.Length; idx++) { this._otherParameters[idx] = dis.ReadByte(); } } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } /// <summary> /// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging. /// This will be modified in the future to provide a better display. Usage: /// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb }); /// where pdu is an object representing a single pdu and sb is a StringBuilder. /// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality /// </summary> /// <param name="sb">The StringBuilder instance to which the PDU is written to.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public virtual void Reflection(StringBuilder sb) { sb.AppendLine("<EightByteChunk>"); try { for (int idx = 0; idx < this._otherParameters.Length; idx++) { sb.AppendLine("<otherParameters" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"byte\">" + this._otherParameters[idx] + "</otherParameters" + idx.ToString(CultureInfo.InvariantCulture) + ">"); } sb.AppendLine("</EightByteChunk>"); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { return this == obj as EightByteChunk; } /// <summary> /// Compares for reference AND value equality. /// </summary> /// <param name="obj">The object to compare with this instance.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public bool Equals(EightByteChunk obj) { bool ivarsEqual = true; if (obj.GetType() != this.GetType()) { return false; } if (obj._otherParameters.Length != 8) { ivarsEqual = false; } if (ivarsEqual) { for (int idx = 0; idx < 8; idx++) { if (this._otherParameters[idx] != obj._otherParameters[idx]) { ivarsEqual = false; } } } return ivarsEqual; } /// <summary> /// HashCode Helper /// </summary> /// <param name="hash">The hash value.</param> /// <returns>The new hash value.</returns> private static int GenerateHash(int hash) { hash = hash << (5 + hash); return hash; } /// <summary> /// Gets the hash code. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { int result = 0; for (int idx = 0; idx < 8; idx++) { result = GenerateHash(result) ^ this._otherParameters[idx].GetHashCode(); } return result; } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.GkeConnect.Gateway.V1Beta1.Snippets { using Google.Api; using Google.Protobuf; using Google.Protobuf.WellKnownTypes; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedGatewayServiceClientSnippets { /// <summary>Snippet for GetResource</summary> public void GetResourceRequestObject() { // Snippet: GetResource(HttpBody, CallSettings) // Create client GatewayServiceClient gatewayServiceClient = GatewayServiceClient.Create(); // Initialize request argument(s) HttpBody request = new HttpBody { ContentType = "", Data = ByteString.Empty, Extensions = { new Any(), }, }; // Make the request HttpBody response = gatewayServiceClient.GetResource(request); // End snippet } /// <summary>Snippet for GetResourceAsync</summary> public async Task GetResourceRequestObjectAsync() { // Snippet: GetResourceAsync(HttpBody, CallSettings) // Additional: GetResourceAsync(HttpBody, CancellationToken) // Create client GatewayServiceClient gatewayServiceClient = await GatewayServiceClient.CreateAsync(); // Initialize request argument(s) HttpBody request = new HttpBody { ContentType = "", Data = ByteString.Empty, Extensions = { new Any(), }, }; // Make the request HttpBody response = await gatewayServiceClient.GetResourceAsync(request); // End snippet } /// <summary>Snippet for PostResource</summary> public void PostResourceRequestObject() { // Snippet: PostResource(HttpBody, CallSettings) // Create client GatewayServiceClient gatewayServiceClient = GatewayServiceClient.Create(); // Initialize request argument(s) HttpBody request = new HttpBody { ContentType = "", Data = ByteString.Empty, Extensions = { new Any(), }, }; // Make the request HttpBody response = gatewayServiceClient.PostResource(request); // End snippet } /// <summary>Snippet for PostResourceAsync</summary> public async Task PostResourceRequestObjectAsync() { // Snippet: PostResourceAsync(HttpBody, CallSettings) // Additional: PostResourceAsync(HttpBody, CancellationToken) // Create client GatewayServiceClient gatewayServiceClient = await GatewayServiceClient.CreateAsync(); // Initialize request argument(s) HttpBody request = new HttpBody { ContentType = "", Data = ByteString.Empty, Extensions = { new Any(), }, }; // Make the request HttpBody response = await gatewayServiceClient.PostResourceAsync(request); // End snippet } /// <summary>Snippet for DeleteResource</summary> public void DeleteResourceRequestObject() { // Snippet: DeleteResource(HttpBody, CallSettings) // Create client GatewayServiceClient gatewayServiceClient = GatewayServiceClient.Create(); // Initialize request argument(s) HttpBody request = new HttpBody { ContentType = "", Data = ByteString.Empty, Extensions = { new Any(), }, }; // Make the request HttpBody response = gatewayServiceClient.DeleteResource(request); // End snippet } /// <summary>Snippet for DeleteResourceAsync</summary> public async Task DeleteResourceRequestObjectAsync() { // Snippet: DeleteResourceAsync(HttpBody, CallSettings) // Additional: DeleteResourceAsync(HttpBody, CancellationToken) // Create client GatewayServiceClient gatewayServiceClient = await GatewayServiceClient.CreateAsync(); // Initialize request argument(s) HttpBody request = new HttpBody { ContentType = "", Data = ByteString.Empty, Extensions = { new Any(), }, }; // Make the request HttpBody response = await gatewayServiceClient.DeleteResourceAsync(request); // End snippet } /// <summary>Snippet for PutResource</summary> public void PutResourceRequestObject() { // Snippet: PutResource(HttpBody, CallSettings) // Create client GatewayServiceClient gatewayServiceClient = GatewayServiceClient.Create(); // Initialize request argument(s) HttpBody request = new HttpBody { ContentType = "", Data = ByteString.Empty, Extensions = { new Any(), }, }; // Make the request HttpBody response = gatewayServiceClient.PutResource(request); // End snippet } /// <summary>Snippet for PutResourceAsync</summary> public async Task PutResourceRequestObjectAsync() { // Snippet: PutResourceAsync(HttpBody, CallSettings) // Additional: PutResourceAsync(HttpBody, CancellationToken) // Create client GatewayServiceClient gatewayServiceClient = await GatewayServiceClient.CreateAsync(); // Initialize request argument(s) HttpBody request = new HttpBody { ContentType = "", Data = ByteString.Empty, Extensions = { new Any(), }, }; // Make the request HttpBody response = await gatewayServiceClient.PutResourceAsync(request); // End snippet } /// <summary>Snippet for PatchResource</summary> public void PatchResourceRequestObject() { // Snippet: PatchResource(HttpBody, CallSettings) // Create client GatewayServiceClient gatewayServiceClient = GatewayServiceClient.Create(); // Initialize request argument(s) HttpBody request = new HttpBody { ContentType = "", Data = ByteString.Empty, Extensions = { new Any(), }, }; // Make the request HttpBody response = gatewayServiceClient.PatchResource(request); // End snippet } /// <summary>Snippet for PatchResourceAsync</summary> public async Task PatchResourceRequestObjectAsync() { // Snippet: PatchResourceAsync(HttpBody, CallSettings) // Additional: PatchResourceAsync(HttpBody, CancellationToken) // Create client GatewayServiceClient gatewayServiceClient = await GatewayServiceClient.CreateAsync(); // Initialize request argument(s) HttpBody request = new HttpBody { ContentType = "", Data = ByteString.Empty, Extensions = { new Any(), }, }; // Make the request HttpBody response = await gatewayServiceClient.PatchResourceAsync(request); // End snippet } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; /// <summary> /// Convert.ToString(System.Decimal) /// </summary> public class ConvertToString9 { public static int Main() { ConvertToString9 testObj = new ConvertToString9(); TestLibrary.TestFramework.BeginTestCase("for method: Convert.ToString(System.Decimal)"); if (testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; return retVal; } #region Positive tests public bool PosTest1() { bool retVal = true; string c_TEST_DESC = "PosTest1: Verify value is a random positive Decimal... "; string c_TEST_ID = "P001"; Random rand = new Random(-55); int low = TestLibrary.Generator.GetInt32(-55); int mid = TestLibrary.Generator.GetInt32(-55); int hi = TestLibrary.Generator.GetInt32(-55); bool isNagetive = true; Byte scale = (byte)rand.Next(0,27); Decimal decimalValue = new Decimal(low,mid,hi,isNagetive,scale); String actualValue = decimalValue.ToString(); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { String resValue = Convert.ToString(decimalValue); if (actualValue != resValue) { string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += "\n decimal value is "+decimalValue; TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; string c_TEST_DESC = "PosTest2: Verify value is a random negative Decimal... "; string c_TEST_ID = "P002"; Random rand = new Random(-55); int low = TestLibrary.Generator.GetInt32(-55); int mid = TestLibrary.Generator.GetInt32(-55); int hi = TestLibrary.Generator.GetInt32(-55); bool isNagetive = false; Byte scale = (byte)rand.Next(0, 27); Decimal decimalValue = new Decimal(low, mid, hi, isNagetive, scale); String actualValue = decimalValue.ToString(); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { String resValue = Convert.ToString(decimalValue); if (actualValue != resValue) { string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += "\n decimal value is " + decimalValue; TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; string c_TEST_DESC = "PosTest3: Verify value is Decimal.MaxValue... "; string c_TEST_ID = "P003"; Decimal decimalValue = Decimal.MaxValue; String actualValue = decimalValue.ToString(); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { String resValue = Convert.ToString(decimalValue); if (actualValue != resValue) { string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += "\n decimal value is " + decimalValue; TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; string c_TEST_DESC = "PosTest4: Verify value is Decimal.MinValue... "; string c_TEST_ID = "P004"; Decimal decimalValue = Decimal.MinValue; String actualValue = decimalValue.ToString(); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { String resValue = Convert.ToString(decimalValue); if (actualValue != resValue) { string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += "\n decimal value is " + decimalValue; TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; string c_TEST_DESC = "PosTest5: Verify value is 0... "; string c_TEST_ID = "P005"; Decimal decimalValue = Decimal.Zero; String actualValue = decimalValue.ToString(); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { String resValue = Convert.ToString(decimalValue); if (actualValue != resValue) { string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += "\n decimal value is " + decimalValue; TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "unexpected exception occurs :" + e); retVal = false; } return retVal; } #endregion }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IO; using System.Collections; using System.Text; using System.Diagnostics; using System.Globalization; namespace System.Xml { // Represents a single node in the document. [DebuggerDisplay("{debuggerDisplayProxy}")] public abstract class XmlNode : IEnumerable { internal XmlNode parentNode; //this pointer is reused to save the userdata information, need to prevent internal user access the pointer directly. internal XmlNode() { } internal XmlNode(XmlDocument doc) { if (doc == null) throw new ArgumentException(SR.Xdom_Node_Null_Doc); this.parentNode = doc; } // Gets the name of the node. public abstract string Name { get; } // Gets or sets the value of the node. public virtual string Value { get { return null; } set { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, SR.Xdom_Node_SetVal, NodeType.ToString())); } } // Gets the type of the current node. public abstract XmlNodeType NodeType { get; } // Gets the parent of this node (for nodes that can have parents). public virtual XmlNode ParentNode { get { Debug.Assert(parentNode != null); if (parentNode.NodeType != XmlNodeType.Document) { return parentNode; } // Linear lookup through the children of the document XmlLinkedNode firstChild = parentNode.FirstChild as XmlLinkedNode; if (firstChild != null) { XmlLinkedNode node = firstChild; do { if (node == this) { return parentNode; } node = node.next; } while (node != null && node != firstChild); } return null; } } // Gets all children of this node. public virtual XmlNodeList ChildNodes { get { return new XmlChildNodes(this); } } // Gets the node immediately preceding this node. public virtual XmlNode PreviousSibling { get { return null; } } // Gets the node immediately following this node. public virtual XmlNode NextSibling { get { return null; } } // Gets a XmlAttributeCollection containing the attributes // of this node. public virtual XmlAttributeCollection Attributes { get { return null; } } // Gets the XmlDocument that contains this node. public virtual XmlDocument OwnerDocument { get { Debug.Assert(parentNode != null); if (parentNode.NodeType == XmlNodeType.Document) return (XmlDocument)parentNode; return parentNode.OwnerDocument; } } // Gets the first child of this node. public virtual XmlNode FirstChild { get { XmlLinkedNode linkedNode = LastNode; if (linkedNode != null) return linkedNode.next; return null; } } // Gets the last child of this node. public virtual XmlNode LastChild { get { return LastNode; } } internal virtual bool IsContainer { get { return false; } } internal virtual XmlLinkedNode LastNode { get { return null; } set { } } internal bool AncestorNode(XmlNode node) { XmlNode n = this.ParentNode; while (n != null && n != this) { if (n == node) return true; n = n.ParentNode; } return false; } //trace to the top to find out its parent node. internal bool IsConnected() { XmlNode parent = ParentNode; while (parent != null && !(parent.NodeType == XmlNodeType.Document)) parent = parent.ParentNode; return parent != null; } // Inserts the specified node immediately before the specified reference node. public virtual XmlNode InsertBefore(XmlNode newChild, XmlNode refChild) { if (this == newChild || AncestorNode(newChild)) throw new ArgumentException(SR.Xdom_Node_Insert_Child); if (refChild == null) return AppendChild(newChild); if (!IsContainer) throw new InvalidOperationException(SR.Xdom_Node_Insert_Contain); if (refChild.ParentNode != this) throw new ArgumentException(SR.Xdom_Node_Insert_Path); if (newChild == refChild) return newChild; XmlDocument childDoc = newChild.OwnerDocument; XmlDocument thisDoc = OwnerDocument; if (childDoc != null && childDoc != thisDoc && childDoc != this) throw new ArgumentException(SR.Xdom_Node_Insert_Context); if (!CanInsertBefore(newChild, refChild)) throw new InvalidOperationException(SR.Xdom_Node_Insert_Location); if (newChild.ParentNode != null) newChild.ParentNode.RemoveChild(newChild); // special case for doc-fragment. if (newChild.NodeType == XmlNodeType.DocumentFragment) { XmlNode first = newChild.FirstChild; XmlNode node = first; if (node != null) { newChild.RemoveChild(node); InsertBefore(node, refChild); // insert the rest of the children after this one. InsertAfter(newChild, node); } return first; } if (!(newChild is XmlLinkedNode) || !IsValidChildType(newChild.NodeType)) throw new InvalidOperationException(SR.Xdom_Node_Insert_TypeConflict); XmlLinkedNode newNode = (XmlLinkedNode)newChild; XmlLinkedNode refNode = (XmlLinkedNode)refChild; string newChildValue = newChild.Value; XmlNodeChangedEventArgs args = GetEventArgs(newChild, newChild.ParentNode, this, newChildValue, newChildValue, XmlNodeChangedAction.Insert); if (args != null) BeforeEvent(args); if (refNode == FirstChild) { newNode.next = refNode; LastNode.next = newNode; newNode.SetParent(this); if (newNode.IsText) { if (refNode.IsText) { NestTextNodes(newNode, refNode); } } } else { XmlLinkedNode prevNode = (XmlLinkedNode)refNode.PreviousSibling; newNode.next = refNode; prevNode.next = newNode; newNode.SetParent(this); if (prevNode.IsText) { if (newNode.IsText) { NestTextNodes(prevNode, newNode); if (refNode.IsText) { NestTextNodes(newNode, refNode); } } else { if (refNode.IsText) { UnnestTextNodes(prevNode, refNode); } } } else { if (newNode.IsText) { if (refNode.IsText) { NestTextNodes(newNode, refNode); } } } } if (args != null) AfterEvent(args); return newNode; } // Inserts the specified node immediately after the specified reference node. public virtual XmlNode InsertAfter(XmlNode newChild, XmlNode refChild) { if (this == newChild || AncestorNode(newChild)) throw new ArgumentException(SR.Xdom_Node_Insert_Child); if (refChild == null) return PrependChild(newChild); if (!IsContainer) throw new InvalidOperationException(SR.Xdom_Node_Insert_Contain); if (refChild.ParentNode != this) throw new ArgumentException(SR.Xdom_Node_Insert_Path); if (newChild == refChild) return newChild; XmlDocument childDoc = newChild.OwnerDocument; XmlDocument thisDoc = OwnerDocument; if (childDoc != null && childDoc != thisDoc && childDoc != this) throw new ArgumentException(SR.Xdom_Node_Insert_Context); if (!CanInsertAfter(newChild, refChild)) throw new InvalidOperationException(SR.Xdom_Node_Insert_Location); if (newChild.ParentNode != null) newChild.ParentNode.RemoveChild(newChild); // special case for doc-fragment. if (newChild.NodeType == XmlNodeType.DocumentFragment) { XmlNode last = refChild; XmlNode first = newChild.FirstChild; XmlNode node = first; while (node != null) { XmlNode next = node.NextSibling; newChild.RemoveChild(node); InsertAfter(node, last); last = node; node = next; } return first; } if (!(newChild is XmlLinkedNode) || !IsValidChildType(newChild.NodeType)) throw new InvalidOperationException(SR.Xdom_Node_Insert_TypeConflict); XmlLinkedNode newNode = (XmlLinkedNode)newChild; XmlLinkedNode refNode = (XmlLinkedNode)refChild; string newChildValue = newChild.Value; XmlNodeChangedEventArgs args = GetEventArgs(newChild, newChild.ParentNode, this, newChildValue, newChildValue, XmlNodeChangedAction.Insert); if (args != null) BeforeEvent(args); if (refNode == LastNode) { newNode.next = refNode.next; refNode.next = newNode; LastNode = newNode; newNode.SetParent(this); if (refNode.IsText) { if (newNode.IsText) { NestTextNodes(refNode, newNode); } } } else { XmlLinkedNode nextNode = refNode.next; newNode.next = nextNode; refNode.next = newNode; newNode.SetParent(this); if (refNode.IsText) { if (newNode.IsText) { NestTextNodes(refNode, newNode); if (nextNode.IsText) { NestTextNodes(newNode, nextNode); } } else { if (nextNode.IsText) { UnnestTextNodes(refNode, nextNode); } } } else { if (newNode.IsText) { if (nextNode.IsText) { NestTextNodes(newNode, nextNode); } } } } if (args != null) AfterEvent(args); return newNode; } // Replaces the child node oldChild with newChild node. public virtual XmlNode ReplaceChild(XmlNode newChild, XmlNode oldChild) { XmlNode nextNode = oldChild.NextSibling; RemoveChild(oldChild); XmlNode node = InsertBefore(newChild, nextNode); return oldChild; } // Removes specified child node. public virtual XmlNode RemoveChild(XmlNode oldChild) { if (!IsContainer) throw new InvalidOperationException(SR.Xdom_Node_Remove_Contain); if (oldChild.ParentNode != this) throw new ArgumentException(SR.Xdom_Node_Remove_Child); XmlLinkedNode oldNode = (XmlLinkedNode)oldChild; string oldNodeValue = oldNode.Value; XmlNodeChangedEventArgs args = GetEventArgs(oldNode, this, null, oldNodeValue, oldNodeValue, XmlNodeChangedAction.Remove); if (args != null) BeforeEvent(args); XmlLinkedNode lastNode = LastNode; if (oldNode == FirstChild) { if (oldNode == lastNode) { LastNode = null; oldNode.next = null; oldNode.SetParent(null); } else { XmlLinkedNode nextNode = oldNode.next; if (nextNode.IsText) { if (oldNode.IsText) { UnnestTextNodes(oldNode, nextNode); } } lastNode.next = nextNode; oldNode.next = null; oldNode.SetParent(null); } } else { if (oldNode == lastNode) { XmlLinkedNode prevNode = (XmlLinkedNode)oldNode.PreviousSibling; prevNode.next = oldNode.next; LastNode = prevNode; oldNode.next = null; oldNode.SetParent(null); } else { XmlLinkedNode prevNode = (XmlLinkedNode)oldNode.PreviousSibling; XmlLinkedNode nextNode = oldNode.next; if (nextNode.IsText) { if (prevNode.IsText) { NestTextNodes(prevNode, nextNode); } else { if (oldNode.IsText) { UnnestTextNodes(oldNode, nextNode); } } } prevNode.next = nextNode; oldNode.next = null; oldNode.SetParent(null); } } if (args != null) AfterEvent(args); return oldChild; } // Adds the specified node to the beginning of the list of children of this node. public virtual XmlNode PrependChild(XmlNode newChild) { return InsertBefore(newChild, FirstChild); } // Adds the specified node to the end of the list of children of this node. public virtual XmlNode AppendChild(XmlNode newChild) { XmlDocument thisDoc = OwnerDocument; if (thisDoc == null) { thisDoc = this as XmlDocument; } if (!IsContainer) throw new InvalidOperationException(SR.Xdom_Node_Insert_Contain); if (this == newChild || AncestorNode(newChild)) throw new ArgumentException(SR.Xdom_Node_Insert_Child); if (newChild.ParentNode != null) newChild.ParentNode.RemoveChild(newChild); XmlDocument childDoc = newChild.OwnerDocument; if (childDoc != null && childDoc != thisDoc && childDoc != this) throw new ArgumentException(SR.Xdom_Node_Insert_Context); // special case for doc-fragment. if (newChild.NodeType == XmlNodeType.DocumentFragment) { XmlNode first = newChild.FirstChild; XmlNode node = first; while (node != null) { XmlNode next = node.NextSibling; newChild.RemoveChild(node); AppendChild(node); node = next; } return first; } if (!(newChild is XmlLinkedNode) || !IsValidChildType(newChild.NodeType)) throw new InvalidOperationException(SR.Xdom_Node_Insert_TypeConflict); if (!CanInsertAfter(newChild, LastChild)) throw new InvalidOperationException(SR.Xdom_Node_Insert_Location); string newChildValue = newChild.Value; XmlNodeChangedEventArgs args = GetEventArgs(newChild, newChild.ParentNode, this, newChildValue, newChildValue, XmlNodeChangedAction.Insert); if (args != null) BeforeEvent(args); XmlLinkedNode refNode = LastNode; XmlLinkedNode newNode = (XmlLinkedNode)newChild; if (refNode == null) { newNode.next = newNode; LastNode = newNode; newNode.SetParent(this); } else { newNode.next = refNode.next; refNode.next = newNode; LastNode = newNode; newNode.SetParent(this); if (refNode.IsText) { if (newNode.IsText) { NestTextNodes(refNode, newNode); } } } if (args != null) AfterEvent(args); return newNode; } //the function is provided only at Load time to speed up Load process internal virtual XmlNode AppendChildForLoad(XmlNode newChild, XmlDocument doc) { XmlNodeChangedEventArgs args = doc.GetInsertEventArgsForLoad(newChild, this); if (args != null) doc.BeforeEvent(args); XmlLinkedNode refNode = LastNode; XmlLinkedNode newNode = (XmlLinkedNode)newChild; if (refNode == null) { newNode.next = newNode; LastNode = newNode; newNode.SetParentForLoad(this); } else { newNode.next = refNode.next; refNode.next = newNode; LastNode = newNode; if (refNode.IsText && newNode.IsText) { NestTextNodes(refNode, newNode); } else { newNode.SetParentForLoad(this); } } if (args != null) doc.AfterEvent(args); return newNode; } internal virtual bool IsValidChildType(XmlNodeType type) { return false; } internal virtual bool CanInsertBefore(XmlNode newChild, XmlNode refChild) { return true; } internal virtual bool CanInsertAfter(XmlNode newChild, XmlNode refChild) { return true; } // Gets a value indicating whether this node has any child nodes. public virtual bool HasChildNodes { get { return LastNode != null; } } // Creates a duplicate of this node. public abstract XmlNode CloneNode(bool deep); internal virtual void CopyChildren(XmlDocument doc, XmlNode container, bool deep) { for (XmlNode child = container.FirstChild; child != null; child = child.NextSibling) { AppendChildForLoad(child.CloneNode(deep), doc); } } // DOM Level 2 // Puts all XmlText nodes in the full depth of the sub-tree // underneath this XmlNode into a "normal" form where only // markup (e.g., tags, comments, processing instructions, CDATA sections, // and entity references) separates XmlText nodes, that is, there // are no adjacent XmlText nodes. public virtual void Normalize() { XmlNode firstChildTextLikeNode = null; StringBuilder sb = new StringBuilder(); for (XmlNode crtChild = this.FirstChild; crtChild != null;) { XmlNode nextChild = crtChild.NextSibling; switch (crtChild.NodeType) { case XmlNodeType.Text: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: { sb.Append(crtChild.Value); XmlNode winner = NormalizeWinner(firstChildTextLikeNode, crtChild); if (winner == firstChildTextLikeNode) { this.RemoveChild(crtChild); } else { if (firstChildTextLikeNode != null) this.RemoveChild(firstChildTextLikeNode); firstChildTextLikeNode = crtChild; } break; } case XmlNodeType.Element: { crtChild.Normalize(); goto default; } default: { if (firstChildTextLikeNode != null) { firstChildTextLikeNode.Value = sb.ToString(); firstChildTextLikeNode = null; } sb.Remove(0, sb.Length); break; } } crtChild = nextChild; } if (firstChildTextLikeNode != null && sb.Length > 0) firstChildTextLikeNode.Value = sb.ToString(); } private XmlNode NormalizeWinner(XmlNode firstNode, XmlNode secondNode) { //first node has the priority if (firstNode == null) return secondNode; Debug.Assert(firstNode.NodeType == XmlNodeType.Text || firstNode.NodeType == XmlNodeType.SignificantWhitespace || firstNode.NodeType == XmlNodeType.Whitespace || secondNode.NodeType == XmlNodeType.Text || secondNode.NodeType == XmlNodeType.SignificantWhitespace || secondNode.NodeType == XmlNodeType.Whitespace); if (firstNode.NodeType == XmlNodeType.Text) return firstNode; if (secondNode.NodeType == XmlNodeType.Text) return secondNode; if (firstNode.NodeType == XmlNodeType.SignificantWhitespace) return firstNode; if (secondNode.NodeType == XmlNodeType.SignificantWhitespace) return secondNode; if (firstNode.NodeType == XmlNodeType.Whitespace) return firstNode; if (secondNode.NodeType == XmlNodeType.Whitespace) return secondNode; Debug.Assert(true, "shouldn't have fall through here."); return null; } // Test if the DOM implementation implements a specific feature. public virtual bool Supports(string feature, string version) { if (String.Compare("XML", feature, StringComparison.OrdinalIgnoreCase) == 0) { if (version == null || version == "1.0" || version == "2.0") return true; } return false; } // Gets the namespace URI of this node. public virtual string NamespaceURI { get { return string.Empty; } } // Gets or sets the namespace prefix of this node. public virtual string Prefix { get { return string.Empty; } set { } } // Gets the name of the node without the namespace prefix. public abstract string LocalName { get; } // Microsoft extensions // Gets a value indicating whether the node is read-only. public virtual bool IsReadOnly { get { XmlDocument doc = OwnerDocument; return HasReadOnlyParent(this); } } internal static bool HasReadOnlyParent(XmlNode n) { while (n != null) { switch (n.NodeType) { case XmlNodeType.EntityReference: case XmlNodeType.Entity: return true; case XmlNodeType.Attribute: n = ((XmlAttribute)n).OwnerElement; break; default: n = n.ParentNode; break; } } return false; } // Provides a simple ForEach-style iteration over the // collection of nodes in this XmlNamedNodeMap. IEnumerator IEnumerable.GetEnumerator() { return new XmlChildEnumerator(this); } public IEnumerator GetEnumerator() { return new XmlChildEnumerator(this); } private void AppendChildText(StringBuilder builder) { for (XmlNode child = FirstChild; child != null; child = child.NextSibling) { if (child.FirstChild == null) { if (child.NodeType == XmlNodeType.Text || child.NodeType == XmlNodeType.CDATA || child.NodeType == XmlNodeType.Whitespace || child.NodeType == XmlNodeType.SignificantWhitespace) builder.Append(child.InnerText); } else { child.AppendChildText(builder); } } } // Gets or sets the concatenated values of the node and // all its children. public virtual string InnerText { get { XmlNode fc = FirstChild; if (fc == null) { return string.Empty; } if (fc.NextSibling == null) { XmlNodeType nodeType = fc.NodeType; switch (nodeType) { case XmlNodeType.Text: case XmlNodeType.CDATA: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: return fc.Value; } } StringBuilder builder = new StringBuilder(); AppendChildText(builder); return builder.ToString(); } set { XmlNode firstChild = FirstChild; if (firstChild != null //there is one child && firstChild.NextSibling == null // and exactly one && firstChild.NodeType == XmlNodeType.Text)//which is a text node { //this branch is for perf reason and event fired when TextNode.Value is changed firstChild.Value = value; } else { RemoveAll(); AppendChild(OwnerDocument.CreateTextNode(value)); } } } // Gets the markup representing this node and all its children. public virtual string OuterXml { get { StringWriter sw = new StringWriter(CultureInfo.InvariantCulture); XmlDOMTextWriter xw = new XmlDOMTextWriter(sw); try { WriteTo(xw); } finally { xw.Dispose(); } return sw.ToString(); } } // Gets or sets the markup representing just the children of this node. public virtual string InnerXml { get { StringWriter sw = new StringWriter(CultureInfo.InvariantCulture); XmlDOMTextWriter xw = new XmlDOMTextWriter(sw); try { WriteContentTo(xw); } finally { xw.Dispose(); } return sw.ToString(); } set { throw new InvalidOperationException(SR.Xdom_Set_InnerXml); } } public virtual String BaseURI { get { XmlNode curNode = this.ParentNode; //save one while loop since if going to here, the nodetype of this node can't be document, entity and entityref while (curNode != null) { XmlNodeType nt = curNode.NodeType; //EntityReference's children come from the dtd where they are defined. //we need to investigate the same thing for entity's children if they are defined in an external dtd file. if (nt == XmlNodeType.EntityReference) return ((XmlEntityReference)curNode).ChildBaseURI; if (nt == XmlNodeType.Document || nt == XmlNodeType.Entity || nt == XmlNodeType.Attribute) return curNode.BaseURI; curNode = curNode.ParentNode; } return String.Empty; } } // Saves the current node to the specified XmlWriter. public abstract void WriteTo(XmlWriter w); // Saves all the children of the node to the specified XmlWriter. public abstract void WriteContentTo(XmlWriter w); // Removes all the children and/or attributes // of the current node. public virtual void RemoveAll() { XmlNode child = FirstChild; XmlNode sibling = null; while (child != null) { sibling = child.NextSibling; RemoveChild(child); child = sibling; } } internal XmlDocument Document { get { if (NodeType == XmlNodeType.Document) return (XmlDocument)this; return OwnerDocument; } } // Looks up the closest xmlns declaration for the given // prefix that is in scope for the current node and returns // the namespace URI in the declaration. public virtual string GetNamespaceOfPrefix(string prefix) { string namespaceName = GetNamespaceOfPrefixStrict(prefix); return namespaceName != null ? namespaceName : string.Empty; } internal string GetNamespaceOfPrefixStrict(string prefix) { XmlDocument doc = Document; if (doc != null) { prefix = doc.NameTable.Get(prefix); if (prefix == null) return null; XmlNode node = this; while (node != null) { if (node.NodeType == XmlNodeType.Element) { XmlElement elem = (XmlElement)node; if (elem.HasAttributes) { XmlAttributeCollection attrs = elem.Attributes; if (prefix.Length == 0) { for (int iAttr = 0; iAttr < attrs.Count; iAttr++) { XmlAttribute attr = attrs[iAttr]; if (attr.Prefix.Length == 0) { if (Ref.Equal(attr.LocalName, doc.strXmlns)) { return attr.Value; // found xmlns } } } } else { for (int iAttr = 0; iAttr < attrs.Count; iAttr++) { XmlAttribute attr = attrs[iAttr]; if (Ref.Equal(attr.Prefix, doc.strXmlns)) { if (Ref.Equal(attr.LocalName, prefix)) { return attr.Value; // found xmlns:prefix } } else if (Ref.Equal(attr.Prefix, prefix)) { return attr.NamespaceURI; // found prefix:attr } } } } if (Ref.Equal(node.Prefix, prefix)) { return node.NamespaceURI; } node = node.ParentNode; } else if (node.NodeType == XmlNodeType.Attribute) { node = ((XmlAttribute)node).OwnerElement; } else { node = node.ParentNode; } } if (Ref.Equal(doc.strXml, prefix)) { // xmlns:xml return doc.strReservedXml; } else if (Ref.Equal(doc.strXmlns, prefix)) { // xmlns:xmlns return doc.strReservedXmlns; } } return null; } // Looks up the closest xmlns declaration for the given namespace // URI that is in scope for the current node and returns // the prefix defined in that declaration. public virtual string GetPrefixOfNamespace(string namespaceURI) { string prefix = GetPrefixOfNamespaceStrict(namespaceURI); return prefix != null ? prefix : string.Empty; } internal string GetPrefixOfNamespaceStrict(string namespaceURI) { XmlDocument doc = Document; if (doc != null) { namespaceURI = doc.NameTable.Add(namespaceURI); XmlNode node = this; while (node != null) { if (node.NodeType == XmlNodeType.Element) { XmlElement elem = (XmlElement)node; if (elem.HasAttributes) { XmlAttributeCollection attrs = elem.Attributes; for (int iAttr = 0; iAttr < attrs.Count; iAttr++) { XmlAttribute attr = attrs[iAttr]; if (attr.Prefix.Length == 0) { if (Ref.Equal(attr.LocalName, doc.strXmlns)) { if (attr.Value == namespaceURI) { return string.Empty; // found xmlns="namespaceURI" } } } else if (Ref.Equal(attr.Prefix, doc.strXmlns)) { if (attr.Value == namespaceURI) { return attr.LocalName; // found xmlns:prefix="namespaceURI" } } else if (Ref.Equal(attr.NamespaceURI, namespaceURI)) { return attr.Prefix; // found prefix:attr // with prefix bound to namespaceURI } } } if (Ref.Equal(node.NamespaceURI, namespaceURI)) { return node.Prefix; } node = node.ParentNode; } else if (node.NodeType == XmlNodeType.Attribute) { node = ((XmlAttribute)node).OwnerElement; } else { node = node.ParentNode; } } if (Ref.Equal(doc.strReservedXml, namespaceURI)) { // xmlns:xml return doc.strXml; } else if (Ref.Equal(doc.strReservedXmlns, namespaceURI)) { // xmlns:xmlns return doc.strXmlns; } } return null; } // Retrieves the first child element with the specified name. public virtual XmlElement this[string name] { get { for (XmlNode n = FirstChild; n != null; n = n.NextSibling) { if (n.NodeType == XmlNodeType.Element && n.Name == name) return (XmlElement)n; } return null; } } // Retrieves the first child element with the specified LocalName and // NamespaceURI. public virtual XmlElement this[string localname, string ns] { get { for (XmlNode n = FirstChild; n != null; n = n.NextSibling) { if (n.NodeType == XmlNodeType.Element && n.LocalName == localname && n.NamespaceURI == ns) return (XmlElement)n; } return null; } } internal virtual void SetParent(XmlNode node) { if (node == null) { this.parentNode = OwnerDocument; } else { this.parentNode = node; } } internal virtual void SetParentForLoad(XmlNode node) { this.parentNode = node; } internal static void SplitName(string name, out string prefix, out string localName) { int colonPos = name.IndexOf(':'); // ordinal compare if (-1 == colonPos || 0 == colonPos || name.Length - 1 == colonPos) { prefix = string.Empty; localName = name; } else { prefix = name.Substring(0, colonPos); localName = name.Substring(colonPos + 1); } } internal virtual XmlNode FindChild(XmlNodeType type) { for (XmlNode child = FirstChild; child != null; child = child.NextSibling) { if (child.NodeType == type) { return child; } } return null; } internal virtual XmlNodeChangedEventArgs GetEventArgs(XmlNode node, XmlNode oldParent, XmlNode newParent, string oldValue, string newValue, XmlNodeChangedAction action) { XmlDocument doc = OwnerDocument; if (doc != null) { if (!doc.IsLoading) { if (((newParent != null && newParent.IsReadOnly) || (oldParent != null && oldParent.IsReadOnly))) throw new InvalidOperationException(SR.Xdom_Node_Modify_ReadOnly); } return doc.GetEventArgs(node, oldParent, newParent, oldValue, newValue, action); } return null; } internal virtual void BeforeEvent(XmlNodeChangedEventArgs args) { if (args != null) OwnerDocument.BeforeEvent(args); } internal virtual void AfterEvent(XmlNodeChangedEventArgs args) { if (args != null) OwnerDocument.AfterEvent(args); } internal virtual XmlSpace XmlSpace { get { XmlNode node = this; XmlElement elem = null; do { elem = node as XmlElement; if (elem != null && elem.HasAttribute("xml:space")) { switch (XmlConvertEx.TrimString(elem.GetAttribute("xml:space"))) { case "default": return XmlSpace.Default; case "preserve": return XmlSpace.Preserve; default: //should we throw exception if value is otherwise? break; } } node = node.ParentNode; } while (node != null); return XmlSpace.None; } } internal virtual String XmlLang { get { XmlNode node = this; XmlElement elem = null; do { elem = node as XmlElement; if (elem != null) { if (elem.HasAttribute("xml:lang")) return elem.GetAttribute("xml:lang"); } node = node.ParentNode; } while (node != null); return String.Empty; } } internal virtual string GetXPAttribute(string localName, string namespaceURI) { return String.Empty; } internal virtual bool IsText { get { return false; } } public virtual XmlNode PreviousText { get { return null; } } internal static void NestTextNodes(XmlNode prevNode, XmlNode nextNode) { Debug.Assert(prevNode.IsText); Debug.Assert(nextNode.IsText); nextNode.parentNode = prevNode; } internal static void UnnestTextNodes(XmlNode prevNode, XmlNode nextNode) { Debug.Assert(prevNode.IsText); Debug.Assert(nextNode.IsText); nextNode.parentNode = prevNode.ParentNode; } private object debuggerDisplayProxy { get { return new DebuggerDisplayXmlNodeProxy(this); } } } [DebuggerDisplay("{ToString()}")] internal struct DebuggerDisplayXmlNodeProxy { private XmlNode _node; public DebuggerDisplayXmlNodeProxy(XmlNode node) { _node = node; } public override string ToString() { XmlNodeType nodeType = _node.NodeType; string result = nodeType.ToString(); switch (nodeType) { case XmlNodeType.Element: case XmlNodeType.EntityReference: result += ", Name=\"" + _node.Name + "\""; break; case XmlNodeType.Attribute: case XmlNodeType.ProcessingInstruction: result += ", Name=\"" + _node.Name + "\", Value=\"" + XmlConvertEx.EscapeValueForDebuggerDisplay(_node.Value) + "\""; break; case XmlNodeType.Text: case XmlNodeType.CDATA: case XmlNodeType.Comment: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: case XmlNodeType.XmlDeclaration: result += ", Value=\"" + XmlConvertEx.EscapeValueForDebuggerDisplay(_node.Value) + "\""; break; case XmlNodeType.DocumentType: XmlDocumentType documentType = (XmlDocumentType)_node; result += ", Name=\"" + documentType.Name + "\", SYSTEM=\"" + documentType.SystemId + "\", PUBLIC=\"" + documentType.PublicId + "\", Value=\"" + XmlConvertEx.EscapeValueForDebuggerDisplay(documentType.InternalSubset) + "\""; break; default: break; } return result; } } }
/* * 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: [email protected] * 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> /// An object used to identify the features and attributes of the account being created. /// </summary> [DataContract] public partial class PlanInformation : IEquatable<PlanInformation>, IValidatableObject { public PlanInformation() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="PlanInformation" /> class. /// </summary> /// <param name="AddOns">Reserved:.</param> /// <param name="CurrencyCode">Specifies the ISO currency code for the account..</param> /// <param name="FreeTrialDaysOverride">Reserved for DocuSign use only..</param> /// <param name="PlanFeatureSets">A complex type that sets the feature sets for the account..</param> /// <param name="PlanId">The DocuSign Plan ID for the account..</param> /// <param name="RecipientDomains">RecipientDomains.</param> public PlanInformation(List<AddOn> AddOns = default(List<AddOn>), string CurrencyCode = default(string), string FreeTrialDaysOverride = default(string), List<FeatureSet> PlanFeatureSets = default(List<FeatureSet>), string PlanId = default(string), List<RecipientDomain> RecipientDomains = default(List<RecipientDomain>)) { this.AddOns = AddOns; this.CurrencyCode = CurrencyCode; this.FreeTrialDaysOverride = FreeTrialDaysOverride; this.PlanFeatureSets = PlanFeatureSets; this.PlanId = PlanId; this.RecipientDomains = RecipientDomains; } /// <summary> /// Reserved: /// </summary> /// <value>Reserved:</value> [DataMember(Name="addOns", EmitDefaultValue=false)] public List<AddOn> AddOns { get; set; } /// <summary> /// Specifies the ISO currency code for the account. /// </summary> /// <value>Specifies the ISO currency code for the account.</value> [DataMember(Name="currencyCode", EmitDefaultValue=false)] public string CurrencyCode { get; set; } /// <summary> /// Reserved for DocuSign use only. /// </summary> /// <value>Reserved for DocuSign use only.</value> [DataMember(Name="freeTrialDaysOverride", EmitDefaultValue=false)] public string FreeTrialDaysOverride { get; set; } /// <summary> /// A complex type that sets the feature sets for the account. /// </summary> /// <value>A complex type that sets the feature sets for the account.</value> [DataMember(Name="planFeatureSets", EmitDefaultValue=false)] public List<FeatureSet> PlanFeatureSets { get; set; } /// <summary> /// The DocuSign Plan ID for the account. /// </summary> /// <value>The DocuSign Plan ID for the account.</value> [DataMember(Name="planId", EmitDefaultValue=false)] public string PlanId { get; set; } /// <summary> /// Gets or Sets RecipientDomains /// </summary> [DataMember(Name="recipientDomains", EmitDefaultValue=false)] public List<RecipientDomain> RecipientDomains { 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 PlanInformation {\n"); sb.Append(" AddOns: ").Append(AddOns).Append("\n"); sb.Append(" CurrencyCode: ").Append(CurrencyCode).Append("\n"); sb.Append(" FreeTrialDaysOverride: ").Append(FreeTrialDaysOverride).Append("\n"); sb.Append(" PlanFeatureSets: ").Append(PlanFeatureSets).Append("\n"); sb.Append(" PlanId: ").Append(PlanId).Append("\n"); sb.Append(" RecipientDomains: ").Append(RecipientDomains).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 PlanInformation); } /// <summary> /// Returns true if PlanInformation instances are equal /// </summary> /// <param name="other">Instance of PlanInformation to be compared</param> /// <returns>Boolean</returns> public bool Equals(PlanInformation other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.AddOns == other.AddOns || this.AddOns != null && this.AddOns.SequenceEqual(other.AddOns) ) && ( this.CurrencyCode == other.CurrencyCode || this.CurrencyCode != null && this.CurrencyCode.Equals(other.CurrencyCode) ) && ( this.FreeTrialDaysOverride == other.FreeTrialDaysOverride || this.FreeTrialDaysOverride != null && this.FreeTrialDaysOverride.Equals(other.FreeTrialDaysOverride) ) && ( this.PlanFeatureSets == other.PlanFeatureSets || this.PlanFeatureSets != null && this.PlanFeatureSets.SequenceEqual(other.PlanFeatureSets) ) && ( this.PlanId == other.PlanId || this.PlanId != null && this.PlanId.Equals(other.PlanId) ) && ( this.RecipientDomains == other.RecipientDomains || this.RecipientDomains != null && this.RecipientDomains.SequenceEqual(other.RecipientDomains) ); } /// <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.AddOns != null) hash = hash * 59 + this.AddOns.GetHashCode(); if (this.CurrencyCode != null) hash = hash * 59 + this.CurrencyCode.GetHashCode(); if (this.FreeTrialDaysOverride != null) hash = hash * 59 + this.FreeTrialDaysOverride.GetHashCode(); if (this.PlanFeatureSets != null) hash = hash * 59 + this.PlanFeatureSets.GetHashCode(); if (this.PlanId != null) hash = hash * 59 + this.PlanId.GetHashCode(); if (this.RecipientDomains != null) hash = hash * 59 + this.RecipientDomains.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
// Copyright 2020 The Tilt Brush Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Collections; using System.Diagnostics.CodeAnalysis; using UnityEngine; namespace TiltBrush { [System.Serializable] public class GameMusic { public AudioClip clip; public Texture2D iconImage; public string description; } // TODO: mutable struct is an accident waiting to happen; replace with class public class AudioManager : MonoBehaviour { class AudioLoop { public GvrAudioSource m_GvrAudioSource; // This is null if and only if the source is not being used. public string m_LoopName; } static public AudioManager m_Instance; static public bool Enabled { set { m_Instance.m_AudioSfxEnabled = value; PointerManager.m_Instance.ResetPointerAudio(); if (!value) { m_Instance.StopAllLoops(); } } get { return m_Instance.m_AudioSfxEnabled && !App.UserConfig.Flags.DisableAudio; } } private bool m_AudioSfxEnabled; [SerializeField] private GameObject m_AudioOneShotPrefab; [SerializeField] private int m_NumAudioOneShots; private GvrAudioSource[] m_AudioOneShots; private int m_NextAvailableAudioOneShot; [SerializeField] private GameObject m_AudioLoopPrefab; private AudioLoop[] m_AudioLoops; [SerializeField] private int m_NumAudioLoops; private int m_RecentlyUsedAudioLoop; public enum FirstRunMusic { IntroQuiet, IntroLoud, IntroAmbient } [SerializeField] private AudioClip[] m_FirstRunMusic; [SerializeField] private GameMusic[] m_GameMusic; [SerializeField] private GameObject m_MusicPrefab; [SerializeField] private AudioClip m_IntroReveal; private AudioSource m_Music; private int m_ActiveGameMusicIndex; [SerializeField] private AudioClip m_IntroTransitionSound; [Range(0.0f, 24.0f)] [SerializeField] private float m_IntroTransitionGain = 0.0f; [SerializeField] private AudioClip m_ActivatePanelSound; [SerializeField] private AudioClip m_DeactivatePanelSound; [SerializeField] private AudioClip m_PopUpSound; [Range(0.0f, 24.0f)] [SerializeField] private float m_PopUpGain = 0.0f; [SerializeField] private float m_PanelActivationVolume = 0.5f; [Range(0.0f, 24.0f)] [SerializeField] private float m_PanelActivationGain = 0.0f; public float m_PanelActivateMinTriggerTime; private float m_PanelActivateTimestamp; [SerializeField] private AudioClip[] m_ItemHoverSounds; [SerializeField] private float m_ItemHoverVolume = 1.0f; private int m_ItemHoverSoundIndex; [SerializeField] private AudioClip[] m_ItemSelectSounds; [Range(0.0f, 24.0f)] [SerializeField] private float m_ItemSelectGain = 0.0f; [SerializeField] private AudioClip m_ItemDisabledSound; [SerializeField] private AudioClip[] m_UndoSounds; [SerializeField] private AudioClip[] m_RedoSounds; [SerializeField] private AudioClip m_InitWorldGrabSound; [Range(0.0f, 24.0f)] [SerializeField] private float m_InitWorldGrabGain = 0.0f; [SerializeField] private float m_InitWorldGrabMinTriggerTime; private float m_InitWorldGrabTimestamp; [SerializeField] private AudioClip m_WorldGrabLoop; public float m_WorldGrabLoopMaxVolume = 0.2f; public float m_WorldGrabLoopAttenuation = 4f; public float m_WorldGrabLoopSmoothSpeed = 50f; [SerializeField] private AudioClip m_WidgetShowSound; [Range(0.0f, 24.0f)] [SerializeField] private float m_WidgetShowGain = 0.0f; [SerializeField] private AudioClip m_WidgetHideSound; [Range(0.0f, 24.0f)] [SerializeField] private float m_WidgetHideGain = 0.0f; [SerializeField] private float m_WidgetShowHideMinTriggerTime = 0.1f; private float m_WidgetShowHideTimestamp; [SerializeField] private AudioClip m_PanelFlipSound; [SerializeField] private float m_PanelFlipVolume = 1.0f; [Range(0.0f, 24.0f)] [SerializeField] private float m_PanelFlipGain = 0.0f; [SerializeField] private AudioClip m_MagicControllerSound; [Range(0.0f, 24.0f)] [SerializeField] private float m_MagicControllerGain = 0.0f; [SerializeField] private AudioClip m_TeleportSound; [Range(0.0f, 1.0f)] [SerializeField] private float m_TeleportVolume = 1.0f; [SerializeField] private AudioClip m_DuplicateSound; [Range(0.0f, 24.0f)] [SerializeField] private float m_DuplicateGain = 0.0f; [SerializeField] private AudioClip m_MirrorSound; [SerializeField] private AudioClip m_MirrorReflectionSound; [SerializeField] private AudioClip m_ScreenshotSound; [Range(0.0f, 1.0f)] [SerializeField] private float m_ScreenshotVolume = 1.0f; [SerializeField] private AudioClip m_TrashSound; [SerializeField] private AudioClip m_TrashSoftSound; // TODO: Should this sound be used or removed? [SerializeField] [SuppressMessage("ReSharper", "NotAccessedField.Local")] private AudioClip m_CountdownSound; [SerializeField] private AudioClip m_HintAnimateSound; [SerializeField] private AudioClip m_SliderSound; [Range(0.0f, 1.0f)] [SerializeField] private float m_SliderVolume = 1.0f; [SerializeField] private AudioClip m_SketchLoadedSound; [Range(0.0f, 24.0f)] [SerializeField] private float m_SketchLoadedGain = 0.0f; [SerializeField] private AudioClip m_SketchUploadCompleteSound; [Range(0.0f, 24.0f)] [SerializeField] private float m_SketchUploadCompleteGain = 0.0f; [SerializeField] private AudioClip m_SketchUploadCanceledSound; [SerializeField] private AudioClip m_ControllerSwapSound; [SerializeField] private AudioClip m_SaveSketchSound; [Range(0.0f, 24.0f)] [SerializeField] private float m_SaveSketchGain = 0.0f; [SerializeField] private AudioClip m_PinCushionOpenSound; [Range(0.0f, 1.0f)] [SerializeField] private float m_PinCushionOpenVolume = 1.0f; [SerializeField] private AudioClip m_PinCushionCloseSound; [Range(0.0f, 1.0f)] [SerializeField] private float m_PinCushionCloseVolume = 1.0f; [SerializeField] private AudioClip m_PinCushionHoverSound; [Range(0.0f, 1.0f)] [SerializeField] private float m_PinCushionHoverVolume = 1.0f; [SerializeField] private AudioClip m_DropperIntersectionSound; [SerializeField] private AudioClip m_DropperPickSound; [Range(0.0f, 24.0f)] [SerializeField] private float m_DropperPickGain = 0.0f; [SerializeField] private AudioClip m_BasicToAdvancedModeSound; [Range(0.0f, 24.0f)] [SerializeField] private float m_BasicToAdvancedModeGain = 0.0f; [SerializeField] private AudioClip m_AdvancedToBasicModeSound; [Range(0.0f, 24.0f)] [SerializeField] private float m_AdvancedToBasicModeGain = 0.0f; [SerializeField] private AudioClip m_TransformResetSound; [Range(0.0f, 1.0f)] [SerializeField] private float m_TransformResetVolume = 1.0f; [SerializeField] private float m_HintAnimateMinTriggerTime; private float m_HintAnimateTimestamp; [SerializeField] private AudioClip m_PanelPaneAttachSound; [SerializeField] private AudioClip m_PanelPaneMoveSound; private float m_PanelPanelMoveTimestamp; [SerializeField] private float m_PanelPaneMoveMinTriggerTime = .2f; [SerializeField] private AudioClip m_UploadLoop; [Range(0.0f, 24.0f)] [SerializeField] private float m_UploadLoopGain = 0.0f; [SerializeField] private AudioClip m_UploadLoopQuiet; [Range(0.0f, 24.0f)] [SerializeField] private float m_UploadLoopQuietGain = 0.0f; [SerializeField] float m_UploadLoopFadeDownDuration = 3f; [SerializeField] private AudioClip m_SelectionHighlightLoop; [Range(0.0f, 1.0f)] [SerializeField] private float m_SelectionHighlightVolume = 1.0f; [SerializeField] private float m_SelectionHighlightFadeDownSpeed = 0.2f; public enum PinSoundType { Enter, Wobble, Unpin } [SerializeField] private AudioClip m_PinEnterSound; [SerializeField] private AudioClip[] m_PinWobbleSounds; [SerializeField] private AudioClip m_UnpinSound; [Header("Selection Toggle Sounds")] [SerializeField] private AudioClip m_ToggleToSelect; [SerializeField] private AudioClip m_ToggleToDeselect; [SerializeField] private float m_SelectionToggleVolume; public int NumGameMusics() { return m_GameMusic.Length; } public GameMusic GetGameMusic(int index) { return m_GameMusic[index]; } public int GetActiveGameMusic() { return m_ActiveGameMusicIndex; } void Awake() { m_Instance = this; // Get that giant spam of clones out of the hierarchy Transform audioParent = new GameObject("AudioManager Things").transform; audioParent.parent = transform; m_AudioOneShots = new GvrAudioSource[m_NumAudioOneShots]; for (int i = 0; i < m_AudioOneShots.Length; ++i) { GameObject audioObj = Instantiate(m_AudioOneShotPrefab, audioParent, true); GvrAudioSource audioSource = audioObj.GetComponent<GvrAudioSource>(); audioSource.disableOnStop = true; m_AudioOneShots[i] = audioSource; } m_NextAvailableAudioOneShot = 0; m_AudioLoops = new AudioLoop[m_NumAudioLoops]; for (int i = 0; i < m_AudioLoops.Length; ++i) { GameObject audioObj = Instantiate(m_AudioLoopPrefab, audioParent, true); GvrAudioSource audioSource = audioObj.GetComponent<GvrAudioSource>(); audioSource.disableOnStop = true; audioSource.loop = true; m_AudioLoops[i] = new AudioLoop { m_GvrAudioSource = audioSource, m_LoopName = null }; } m_RecentlyUsedAudioLoop = 0; GameObject musicObj = Instantiate(m_MusicPrefab, audioParent, true); m_Music = musicObj.GetComponent<AudioSource>(); m_ItemHoverSoundIndex = 0; m_PanelActivateTimestamp = Time.realtimeSinceStartup; m_InitWorldGrabTimestamp = Time.realtimeSinceStartup; m_HintAnimateTimestamp = Time.realtimeSinceStartup; m_AudioSfxEnabled = false; m_ActiveGameMusicIndex = -1; } public bool StartLoop(AudioClip rClip, string sLoopName, Transform targetTransform, float fVolume = 1.0f, float fGain = 0.0f, float fSpatialBlend = 1.0f) { if (!Enabled) { return false; } // Search for first unused source; but also search for any source playing the same loop // and abort if found. int? available = null; for (int iter = 0; iter < m_AudioLoops.Length; iter++) { int i = (m_RecentlyUsedAudioLoop + iter) % m_AudioLoops.Length; if (available == null && m_AudioLoops[i].m_LoopName == null) { available = i; } else if (m_AudioLoops[i].m_LoopName == sLoopName) { return false; } } if (available == null) { // TODO: This is not necessarily the oldest loop! available = (m_RecentlyUsedAudioLoop + 1) % m_AudioLoops.Length; } m_RecentlyUsedAudioLoop = available.Value; m_AudioLoops[m_RecentlyUsedAudioLoop].m_GvrAudioSource.gameObject.SetActive(true); m_AudioLoops[m_RecentlyUsedAudioLoop].m_GvrAudioSource.volume = fVolume; m_AudioLoops[m_RecentlyUsedAudioLoop].m_GvrAudioSource.gainDb = fGain; m_AudioLoops[m_RecentlyUsedAudioLoop].m_GvrAudioSource.spatialBlend = fSpatialBlend; m_AudioLoops[m_RecentlyUsedAudioLoop].m_GvrAudioSource.clip = rClip; m_AudioLoops[m_RecentlyUsedAudioLoop].m_GvrAudioSource.transform.SetParent(targetTransform); m_AudioLoops[m_RecentlyUsedAudioLoop].m_GvrAudioSource.transform.localPosition = Vector3.zero; m_AudioLoops[m_RecentlyUsedAudioLoop].m_LoopName = sLoopName; m_AudioLoops[m_RecentlyUsedAudioLoop].m_GvrAudioSource.Play(); return true; } public void ChangeLoopVolume(string sLoopName, float fVolume) { if (!Enabled) { return; } for (int i = 0; i < m_AudioLoops.Length; i++) { if (m_AudioLoops[i].m_LoopName == sLoopName) { m_AudioLoops[i].m_GvrAudioSource.volume = fVolume; return; } } } public void StopLoop(string sLoopName) { for (int i = 0; i < m_AudioLoops.Length; i++) { if (m_AudioLoops[i].m_LoopName == sLoopName) { m_AudioLoops[i].m_GvrAudioSource.Stop(); m_AudioLoops[i].m_LoopName = null; m_AudioLoops[i].m_GvrAudioSource.transform.SetParent(transform); } } } public void StopAllLoops() { for (int i = 0; i < m_AudioLoops.Length; i++) { if (m_AudioLoops[i].m_LoopName != null) { m_AudioLoops[i].m_GvrAudioSource.Stop(); m_AudioLoops[i].m_LoopName = null; m_AudioLoops[i].m_GvrAudioSource.transform.SetParent(transform); } } } public void SelectionHighlightLoop(bool bActive) { if (bActive) { if (StartLoop(m_SelectionHighlightLoop, "SelectionHighlight", InputManager.Brush.Transform, m_SelectionHighlightVolume, fSpatialBlend: 0.0f)) { StartCoroutine(SelectionHighlightFadeDown()); } } else { StopLoop("SelectionHighlight"); } } IEnumerator SelectionHighlightFadeDown() { float fVolume = m_SelectionHighlightVolume; while (fVolume > 0) { fVolume -= m_SelectionHighlightFadeDownSpeed * m_SelectionHighlightVolume * Time.deltaTime; ChangeLoopVolume("SelectionHighlight", fVolume); yield return null; } } public void UploadLoop(bool bActive) { if (bActive) { StartLoop(m_UploadLoop, "UploadLoop", InputManager.Wand.Transform, fVolume: 1.0f, fGain: m_UploadLoopGain); StartLoop(m_UploadLoopQuiet, "UploadLoopQuiet", InputManager.Wand.Transform, fVolume: 0f, fGain: m_UploadLoopQuietGain); StartCoroutine("UploadLoopFadeDown"); } else { StopLoop("UploadLoop"); StopLoop("UploadLoopQuiet"); StopCoroutine("UploadLoopFadeDown"); } } IEnumerator UploadLoopFadeDown() { float fRemainingDuration = m_UploadLoopFadeDownDuration; float fRatio = 1f; while (fRemainingDuration > 0) { fRemainingDuration -= Time.deltaTime; fRatio = fRemainingDuration / m_UploadLoopFadeDownDuration; ChangeLoopVolume("UploadLoop", fRatio); ChangeLoopVolume("UploadLoopQuiet", 1f - fRatio); yield return null; } ChangeLoopVolume("UploadLoop", 0f); ChangeLoopVolume("UploadLoopQuiet", 1f); } public void ItemHover(Vector3 vPos) { TriggerOneShot(m_ItemHoverSounds[m_ItemHoverSoundIndex], vPos, m_ItemHoverVolume); ++m_ItemHoverSoundIndex; m_ItemHoverSoundIndex %= m_ItemHoverSounds.Length; } public void PanelFlip(Vector3 vPos) { TriggerOneShot(m_PanelFlipSound, vPos, m_PanelFlipVolume, fGain: m_PanelFlipGain); } public void ItemSelect(Vector3 vPos) { int iRandIndex = UnityEngine.Random.Range(0, m_ItemSelectSounds.Length - 1); TriggerOneShot(m_ItemSelectSounds[iRandIndex], vPos, 1.0f, fGain: m_ItemSelectGain); } public void DisabledItemSelect(Vector3 vPos) { TriggerOneShot(m_ItemDisabledSound, vPos, 1.0f); } public void ActivatePanel(bool bActivate, Vector3 vPos) { if (Time.realtimeSinceStartup - m_PanelActivateTimestamp > m_PanelActivateMinTriggerTime) { if (bActivate) { TriggerOneShot(m_ActivatePanelSound, vPos, m_PanelActivationVolume, fGain: m_PanelActivationGain); } else { TriggerOneShot(m_DeactivatePanelSound, vPos, m_PanelActivationVolume, fGain: m_PanelActivationGain); } m_PanelActivateTimestamp = Time.realtimeSinceStartup; } } public void WorldGrabbed(Vector3 vPos, float fVolume = 1.0f) { if (Time.realtimeSinceStartup - m_InitWorldGrabTimestamp > m_InitWorldGrabMinTriggerTime) { TriggerOneShot(m_InitWorldGrabSound, vPos, fVolume, fGain: m_InitWorldGrabGain); m_InitWorldGrabTimestamp = Time.realtimeSinceStartup; } } public void WorldGrabLoop(bool bActive) { if(bActive) { StartLoop(m_WorldGrabLoop, "WorldGrab", SketchControlsScript.m_Instance.ControllerGrabVisuals.transform, 0.0f); } else { StopLoop("WorldGrab"); } } public void PlayIntroTransitionSound(Vector3 vPos) { TriggerOneShot(m_IntroTransitionSound, vPos, 1.0f, fGain: m_IntroTransitionGain); } public void PlayPopUpSound(Vector3 vPos) { TriggerOneShot(m_PopUpSound, vPos, 1.0f, fGain: m_PopUpGain); } public void ShowHideWidget(bool bShow, Vector3 vPos, float fVolume = 1.0f) { if (Time.realtimeSinceStartup - m_WidgetShowHideTimestamp > m_WidgetShowHideMinTriggerTime) { if (bShow) { TriggerOneShot(m_WidgetShowSound, vPos, fVolume, fGain: m_WidgetShowGain); } else { TriggerOneShot(m_WidgetHideSound, vPos, fVolume, fGain: m_WidgetHideGain); } m_WidgetShowHideTimestamp = Time.realtimeSinceStartup; } } public void PlayDuplicateSound(Vector3 vPos) { TriggerOneShot(m_DuplicateSound, vPos, 1.0f, fGain: m_DuplicateGain); } public void PlayTeleportSound(Vector3 vPos) { TriggerOneShot(m_TeleportSound, vPos, m_TeleportVolume); } public void PlayScreenshotSound(Vector3 vPos) { TriggerOneShot(m_ScreenshotSound, vPos, m_ScreenshotVolume); } public void PlayTrashSound(Vector3 vPos) { TriggerOneShot(m_TrashSound, vPos, 1.0f); } public void PlayTrashSoftSound(Vector3 vPos) { TriggerOneShot(m_TrashSoftSound, vPos, 1.0f); } public void PlayHintAnimateSound(Vector3 vPos) { if (Time.realtimeSinceStartup - m_HintAnimateTimestamp > m_HintAnimateMinTriggerTime) { TriggerOneShot(m_HintAnimateSound, vPos, 1.0f); m_HintAnimateTimestamp = Time.realtimeSinceStartup; } } public void PlayDropperIntersectionSound(Vector3 vPos) { TriggerOneShot(m_DropperIntersectionSound, vPos, 1.0f); } public void PlayDropperPickSound(Vector3 vPos) { TriggerOneShot(m_DropperPickSound, vPos, 1.0f, fGain: m_DropperPickGain); } public void PlaySliderSound(Vector3 vPos) { TriggerOneShot(m_SliderSound, vPos, m_SliderVolume); } public void PlayGroupedSound(Vector3 vPos) { TriggerOneShot(m_SketchLoadedSound, vPos, 0.5f); } public void PlayUndoSound(Vector3 vPos) { int iRandIndex = UnityEngine.Random.Range(0, m_UndoSounds.Length - 1); TriggerOneShot(m_UndoSounds[iRandIndex], vPos, 1.0f); } public void PlayRedoSound(Vector3 vPos) { int iRandIndex = UnityEngine.Random.Range(0, m_RedoSounds.Length - 1); TriggerOneShot(m_RedoSounds[iRandIndex], vPos, 1.0f); } public void PlaySketchLoadedSound(Vector3 vPos) { TriggerOneShot(m_SketchLoadedSound, vPos, 1.0f, fGain: m_SketchLoadedGain); } public void PlayUploadCompleteSound(Vector3 vPos) { TriggerOneShot(m_SketchUploadCompleteSound, vPos, 1.0f, fGain: m_SketchUploadCompleteGain); } public void PlayUploadCanceledSound(Vector3 vPos) { TriggerOneShot(m_SketchUploadCanceledSound, vPos, 1.0f); } public void PlayControllerSwapSound(Vector3 vPos) { TriggerOneShot(m_ControllerSwapSound, vPos, 1.0f); } public void PlayPanelPaneAttachSound(Vector3 vPos) { TriggerOneShot(m_PanelPaneAttachSound, vPos, 1.0f); } public void PlayPanelPaneMoveSound(Vector3 vPos) { if(Time.realtimeSinceStartup - m_PanelPanelMoveTimestamp > m_PanelPaneMoveMinTriggerTime) { TriggerOneShot(m_PanelPaneMoveSound, vPos, 1.0f); m_PanelPanelMoveTimestamp = Time.realtimeSinceStartup; } } public void PlayIntroReveal() { TriggerOneShot(m_IntroReveal, InputManager.m_Instance.GetBrushControllerAttachPoint().position, 1.0f, 0.0f); } public void PlayMagicControllerSound() { TriggerOneShot(m_MagicControllerSound, InputManager.Brush.Transform.position, 1.0f, fGain: m_MagicControllerGain); } public void PlayMirrorSound(Vector3 vPos) { StartCoroutine(MirrorSoundCoroutine(vPos)); } IEnumerator MirrorSoundCoroutine(Vector3 vPos) { TriggerOneShot(m_MirrorSound, vPos, .5f, .5f, 1.0f); yield return new WaitForSeconds(.4f); Vector3 vHeadtoMirror = (vPos - ViewpointScript.Head.position); Vector3 vPos2 = ViewpointScript.Head.position + Quaternion.Euler(0f, 120f, 0) * (vHeadtoMirror / 2); TriggerOneShot(m_MirrorReflectionSound, vPos2, .1f, .5f, 1.0f); yield return new WaitForSeconds(.4f); Vector3 vPos3 = ViewpointScript.Head.position + Quaternion.Euler(0f, 240f, 0) * (vHeadtoMirror / 4); TriggerOneShot(m_MirrorReflectionSound, vPos3, .03f, .5f, 1.0f); } public void PlayPinSound(Vector3 vPos, PinSoundType type) { switch (type) { case PinSoundType.Enter: TriggerOneShot(m_PinEnterSound, vPos, 1.0f); break; case PinSoundType.Unpin: TriggerOneShot(m_UnpinSound, vPos, 1.0f); break; case PinSoundType.Wobble: int iRandIndex = UnityEngine.Random.Range(0, m_PinWobbleSounds.Length - 1); TriggerOneShot(m_PinWobbleSounds[iRandIndex], vPos, 1.0f); break; } } public void PlaySaveSound(Vector3 vPos) { TriggerOneShot(m_SaveSketchSound, vPos, 1.0f, fGain: m_SaveSketchGain); } public void PlayToggleSelect(Vector3 vPos, bool willSelect) { TriggerOneShot(willSelect ? m_ToggleToSelect : m_ToggleToDeselect, vPos, m_SelectionToggleVolume); } public void PlayPinCushionSound(bool bShow) { if (bShow) { TriggerOneShot(m_PinCushionOpenSound, InputManager.Brush.m_Position, m_PinCushionOpenVolume, fSpatialBlend: .5f); } else { TriggerOneShot(m_PinCushionCloseSound, InputManager.Brush.m_Position, m_PinCushionCloseVolume, fSpatialBlend: .5f); } } public void PlayPinCushionHoverSound() { TriggerOneShot(m_PinCushionHoverSound, InputManager.Brush.m_Position, m_PinCushionHoverVolume, fSpatialBlend: .5f); } public void PlayTransformResetSound() { Vector3 vPos = ViewpointScript.Head.position + Vector3.up * 2.0f; TriggerOneShot(m_TransformResetSound, vPos, m_TransformResetVolume, fSpatialBlend: 0.0f); } public void AdvancedModeSwitch(bool toAdvanced) { if (toAdvanced) { TriggerOneShot(m_BasicToAdvancedModeSound, InputManager.Wand.m_Position, 1.0f, fGain: m_BasicToAdvancedModeGain); } else { TriggerOneShot(m_AdvancedToBasicModeSound, InputManager.Wand.m_Position, 1.0f, fGain: m_AdvancedToBasicModeGain); } } public void PlayFirstRunMusic(FirstRunMusic style, float delay = 0.0f) { int iStyle = (int)style; if (iStyle < 0 || iStyle >= m_FirstRunMusic.Length) { Debug.LogError("Bad index sent to AudioManager.PlayFirstRunMusic()"); return; } // Loose mapping between musics and style enum. m_Music.clip = m_FirstRunMusic[(int)style]; if(style == FirstRunMusic.IntroAmbient) { m_Music.loop = false; } m_Music.PlayDelayed(delay); } public void PlayGameMusic(int index) { if (index < 0 || index >= m_GameMusic.Length) { Debug.LogError("Bad index sent to AudioManager.PlayGameMusic()"); return; } m_ActiveGameMusicIndex = index; m_Music.Stop(); m_Music.clip = m_GameMusic[m_ActiveGameMusicIndex].clip; m_Music.Play(); } public void SetMusicVolume(float volume) { if (m_Music != null) { m_Music.volume = volume; } } public void StopMusic() { if (m_Music != null) { m_Music.Stop(); } m_ActiveGameMusicIndex = -1; } public void TriggerOneShot(AudioClip rClip, Vector3 vPos, float fVolume, float fSpatialBlend = 1.0f, float fGain = 0.0f) { if (Enabled) { m_AudioOneShots[m_NextAvailableAudioOneShot].gameObject.SetActive(true); m_AudioOneShots[m_NextAvailableAudioOneShot].volume = fVolume; m_AudioOneShots[m_NextAvailableAudioOneShot].gainDb = fGain; m_AudioOneShots[m_NextAvailableAudioOneShot].spatialBlend = fSpatialBlend; m_AudioOneShots[m_NextAvailableAudioOneShot].clip = rClip; m_AudioOneShots[m_NextAvailableAudioOneShot].transform.position = vPos; m_AudioOneShots[m_NextAvailableAudioOneShot].Play(); ++m_NextAvailableAudioOneShot; m_NextAvailableAudioOneShot %= m_AudioOneShots.Length; } } public void StopAudio() { foreach (GvrAudioSource s in m_AudioOneShots) { s.Stop(); } } } } // namespace TiltBrush
//------------------------------------------------------------------------------ // <copyright file="XhtmlBasicObjectListAdapter.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System; using System.Drawing; using System.Globalization; using System.Security.Permissions; using System.Web.Mobile; using System.Web.UI.MobileControls; using System.Web.UI.MobileControls.Adapters; using System.Collections.Specialized; #if COMPILING_FOR_SHIPPED_SOURCE namespace System.Web.UI.MobileControls.ShippedAdapterSource.XhtmlAdapters #else namespace System.Web.UI.MobileControls.Adapters.XhtmlAdapters #endif { /// <include file='doc\XhtmlBasicObjectListAdapter.uex' path='docs/doc[@for="XhtmlObjectListAdapter"]/*' /> [AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)] [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal)] [Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")] public class XhtmlObjectListAdapter : XhtmlControlAdapter { /// <include file='doc\XhtmlBasicObjectListAdapter.uex' path='docs/doc[@for="XhtmlObjectListAdapter.BackToList"]/*' /> internal protected static readonly String BackToList = "__back"; /// <include file='doc\XhtmlBasicObjectListAdapter.uex' path='docs/doc[@for="XhtmlObjectListAdapter.ShowMoreFormat"]/*' /> internal protected static readonly String ShowMoreFormat = "__more{0}"; /// <include file='doc\XhtmlBasicObjectListAdapter.uex' path='docs/doc[@for="XhtmlObjectListAdapter.ShowMore"]/*' /> internal protected static readonly String ShowMore = "__more"; private const int _modeDetails = 1; private BooleanOption _hasItemDetails = BooleanOption.NotSet; private int _visibleTableFieldsCount = -1; /// <include file='doc\XhtmlBasicObjectListAdapter.uex' path='docs/doc[@for="XhtmlObjectListAdapter.Control"]/*' /> protected new ObjectList Control { get { return base.Control as ObjectList; } } private int VisibleTableFieldsCount { get { if (_visibleTableFieldsCount == -1) { int[] tableFieldIndices = Control.TableFieldIndices; _visibleTableFieldsCount = 0; for (int i = 0; i < tableFieldIndices.Length; i++) { if (Control.AllFields[tableFieldIndices[i]].Visible) { _visibleTableFieldsCount++; } } } return _visibleTableFieldsCount; } } // Encapsulate conditional call to Control.PreShowItemCommands for intelligibility. private void ConditionalPreShowItemCommands () { if (SecondaryUIMode == _modeDetails && Control.Items.Count > 0) { Control.PreShowItemCommands (Control.SelectedIndex); } } /// <include file='doc\XhtmlBasicObjectListAdapter.uex' path='docs/doc[@for="XhtmlObjectListAdapter.CreateTemplatedUI"]/*' /> public override void CreateTemplatedUI(bool doDataBind) { if (Control.ViewMode == ObjectListViewMode.List) { Control.CreateTemplatedItemsList(doDataBind); } else { Control.CreateTemplatedItemDetails(doDataBind); } } private void DetermineFieldIndicesAndCount (out int fieldCount, out int[] fieldIndices){ fieldIndices = Control.TableFieldIndices; fieldCount = fieldIndices.Length; if (fieldCount == 0) { fieldIndices = new int[1]; fieldIndices[0] = Control.LabelFieldIndex; fieldCount = 1; } } public override bool HandlePostBackEvent(String eventArgument) { // Review: Consider replacing switch. switch (Control.ViewMode) { case ObjectListViewMode.List: if (eventArgument.StartsWith(ShowMore, StringComparison.Ordinal)) { int itemIndex = ParseItemArg(eventArgument); if (Control.SelectListItem(itemIndex, true)) { if (Control.SelectedIndex > -1) { // ObjectListViewMode.Commands and .Details same for HTML, // but cannot access ObjLst.Details in Commands mode. Control.ViewMode = ObjectListViewMode.Details; } } } else { int itemIndex = -1; try { itemIndex = Int32.Parse(eventArgument, CultureInfo.InvariantCulture); } catch (System.FormatException) { // throw new Exception (SR.GetString( SR.XhtmlObjectListAdapter_InvalidPostedData)); } if (Control.SelectListItem(itemIndex, false)) { Control.RaiseDefaultItemEvent(itemIndex); } } return true; case ObjectListViewMode.Commands: case ObjectListViewMode.Details: if (eventArgument == BackToList) { Control.ViewMode = ObjectListViewMode.List; return true; } break; } return false; } /// <include file='doc\XhtmlBasicObjectListAdapter.uex' path='docs/doc[@for="XhtmlObjectListAdapter.HasCommands"]/*' /> protected bool HasCommands() { return Control.Commands.Count > 0; } /// <include file='doc\XhtmlBasicObjectListAdapter.uex' path='docs/doc[@for="XhtmlObjectListAdapter.HasDefaultCommand"]/*' /> protected bool HasDefaultCommand () { String controlDefaultCommand = Control.DefaultCommand; return controlDefaultCommand != null && controlDefaultCommand.Length > 0; } /// <include file='doc\XhtmlBasicObjectListAdapter.uex' path='docs/doc[@for="XhtmlObjectListAdapter.HasItemDetails"]/*' /> protected virtual bool HasItemDetails() { if (_hasItemDetails == BooleanOption.NotSet) { // Calculate how many visible fields are shown in list view. int visibleFieldsInListView; int[] tableFieldIndices = Control.TableFieldIndices; if (tableFieldIndices.Length != 0) { visibleFieldsInListView = VisibleTableFieldsCount; } else { visibleFieldsInListView = Control.AllFields[Control.LabelFieldIndex].Visible ? 1 : 0; } // Calculate the number of visible fields. _hasItemDetails = BooleanOption.False; int visibleFieldCount = 0; foreach (ObjectListField field in Control.AllFields) { if (field.Visible) { visibleFieldCount++; if (visibleFieldCount > visibleFieldsInListView) { _hasItemDetails = BooleanOption.True; break; } } } } return _hasItemDetails == BooleanOption.True; } // Return true iff there is exactly one command and it is the default command. /// <include file='doc\XhtmlBasicObjectListAdapter.uex' path='docs/doc[@for="XhtmlObjectListAdapter.OnlyHasDefaultCommand"]/*' /> protected bool OnlyHasDefaultCommand () { return Control.Commands.Count == 1 && (String.Compare (Control.DefaultCommand, Control.Commands[0].Name, true /* ignore case */, CultureInfo.CurrentCulture) == 0); } /// <include file='doc\XhtmlBasicObjectListAdapter.uex' path='docs/doc[@for="XhtmlObjectListAdapter.OnPreRender"]/*' /> public override void OnPreRender(EventArgs e) { base.OnPreRender (e); SetSecondaryUIMode (); ConditionalPreShowItemCommands (); } private static int ParseItemArg(String arg) { return Int32.Parse(arg.Substring(ShowMore.Length), CultureInfo.InvariantCulture); } /// <include file='doc\XhtmlBasicObjectListAdapter.uex' path='docs/doc[@for="XhtmlObjectListAdapter.Render"]/*' /> public override void Render(XhtmlMobileTextWriter writer) { if (Control.ViewMode == ObjectListViewMode.List) { if (Control.HasControls()) { ConditionalRenderOpeningDivElement(writer); RenderChildren(writer); ConditionalRenderClosingDivElement(writer); } else { RenderItemsList(writer); } } else { if (Control.Selection.HasControls()) { ConditionalRenderOpeningDivElement(writer); Control.Selection.RenderChildren(writer); ConditionalRenderClosingDivElement(writer); } else { RenderItemDetails(writer, Control.Selection); } // Review: The HTML case calls FormAdapter.DisablePager, but // this seems unnecessary, since the pager is not rendered in the secondary ui case anyway. } } // Render the details view /// <include file='doc\XhtmlBasicObjectListAdapter.uex' path='docs/doc[@for="XhtmlObjectListAdapter.RenderItemDetails"]/*' /> protected virtual void RenderItemDetails(XhtmlMobileTextWriter writer, ObjectListItem item) { if (Control.AllFields.Count == 0) { return; } if (!Device.Tables) { RenderItemDetailsWithoutTableTags(writer, item); return; } Style labelStyle = Control.LabelStyle; Style subCommandStyle = Control.CommandStyle; Style subCommandStyleNoItalic = (Style)subCommandStyle.Clone(); subCommandStyleNoItalic.Font.Italic = BooleanOption.False; writer.ClearPendingBreak(); // we are writing a block level element in all cases. ConditionalEnterLayout(writer, Style); writer.WriteBeginTag ("table"); ConditionalRenderClassAttribute(writer); writer.Write(">"); writer.Write("<tr><td colspan=\"2\">"); ConditionalEnterStyle(writer, labelStyle); writer.WriteEncodedText (item[Control.LabelFieldIndex]); ConditionalExitStyle(writer, labelStyle); writer.WriteLine("</td></tr>"); Color foreColor = (Color)Style[Style.ForeColorKey, true]; RenderRule (writer, foreColor, 2); RenderItemFieldsInDetailsView (writer, item); RenderRule (writer, foreColor, 2); ConditionalPopPhysicalCssClass(writer); writer.WriteEndTag("table"); ConditionalExitLayout(writer, Style); ConditionalEnterStyle(writer, subCommandStyleNoItalic); writer.Write("[&nbsp;"); ObjectListCommandCollection commands = Control.Commands; String cssClass = GetCustomAttributeValue(XhtmlConstants.CssClassCustomAttribute); String subCommandClass = GetCustomAttributeValue(XhtmlConstants.CssCommandClassCustomAttribute); if (subCommandClass == null || subCommandClass.Length == 0) { subCommandClass = cssClass; } foreach (ObjectListCommand command in commands) { RenderPostBackEventAsAnchor(writer, command.Name, command.Text, null /* accessKey */, subCommandStyle, subCommandClass); writer.Write("&nbsp;|&nbsp;"); } String controlBCT = Control.BackCommandText; String backCommandText = (controlBCT == null || controlBCT.Length == 0) ? GetDefaultLabel(BackLabel) : controlBCT; RenderPostBackEventAsAnchor(writer, BackToList, backCommandText, null /* accessKey */, subCommandStyle, subCommandClass); writer.Write("&nbsp;]"); ConditionalExitStyle(writer, subCommandStyleNoItalic); } private void RenderItemDetailsWithoutTableTags(XhtmlMobileTextWriter writer, ObjectListItem item) { if (Control.VisibleItemCount == 0) { return; } Style style = this.Style; Style labelStyle = Control.LabelStyle; Style subCommandStyle = Control.CommandStyle; Style subCommandStyleNoItalic = (Style)subCommandStyle.Clone(); subCommandStyleNoItalic.Font.Italic = BooleanOption.False; ConditionalRenderOpeningDivElement(writer); String cssClass = GetCustomAttributeValue(XhtmlConstants.CssClassCustomAttribute); String labelClass = GetCustomAttributeValue(XhtmlConstants.CssLabelClassCustomAttribute); if (labelClass == null || labelClass.Length == 0) { labelClass = cssClass; } ConditionalEnterStyle(writer, labelStyle); bool requiresLabelClassSpan = CssLocation == StyleSheetLocation.PhysicalFile && labelClass != null && labelClass.Length > 0; if (requiresLabelClassSpan) { writer.WriteBeginTag("span"); writer.WriteAttribute("class", labelClass, true); writer.Write(">"); } writer.Write(item[Control.LabelFieldIndex]); writer.SetPendingBreak(); if (requiresLabelClassSpan) { writer.WriteEndTag("span"); } ConditionalExitStyle(writer, labelStyle); writer.WritePendingBreak(); IObjectListFieldCollection fields = Control.AllFields; int fieldIndex = 0; ConditionalEnterStyle(writer, style); foreach (ObjectListField field in fields) { if (field.Visible) { writer.Write(field.Title + ":"); writer.Write("&nbsp;"); writer.Write(item[fieldIndex]); writer.WriteBreak(); } fieldIndex++; } ConditionalExitStyle(writer, style); String commandClass = GetCustomAttributeValue(XhtmlConstants.CssCommandClassCustomAttribute); ConditionalEnterStyle(writer, subCommandStyleNoItalic); if ((String) Device[XhtmlConstants.BreaksOnInlineElements] != "true") { writer.Write("[&nbsp;"); } ConditionalEnterStyle(writer, subCommandStyle); ObjectListCommandCollection commands = Control.Commands; foreach (ObjectListCommand command in commands) { RenderPostBackEventAsAnchor(writer, command.Name, command.Text); if ((String) Device[XhtmlConstants.BreaksOnInlineElements] != "true") { writer.Write("&nbsp;|&nbsp;"); } } String controlBCT = Control.BackCommandText; String backCommandText = controlBCT == null || controlBCT.Length == 0 ? GetDefaultLabel(BackLabel) : Control.BackCommandText; RenderPostBackEventAsAnchor(writer, BackToList, backCommandText); ConditionalExitStyle(writer, subCommandStyle); if ((String) Device[XhtmlConstants.BreaksOnInlineElements] != "true") { writer.Write("&nbsp;]"); } ConditionalExitStyle(writer, subCommandStyleNoItalic); ConditionalRenderClosingDivElement(writer); } // Called from RenderItemDetails. (Extracted for intelligibility.) private void RenderItemFieldsInDetailsView (XhtmlMobileTextWriter writer, ObjectListItem item) { Style style = Style; IObjectListFieldCollection fields = Control.AllFields; foreach (ObjectListField field in fields) { if (field.Visible) { writer.Write("<tr><td>"); ConditionalEnterStyle(writer, Style); writer.WriteEncodedText (field.Title); ConditionalExitStyle(writer, Style); writer.Write("</td><td>"); ConditionalEnterStyle(writer, style); writer.WriteEncodedText (item [fields.IndexOf (field)]); ConditionalExitStyle(writer, style); writer.WriteLine("</td></tr>"); } } } // Render the list view /// <include file='doc\XhtmlBasicObjectListAdapter.uex' path='docs/doc[@for="XhtmlObjectListAdapter.RenderItemsList"]/*' /> protected virtual void RenderItemsList(XhtmlMobileTextWriter writer) { if (Control.VisibleItemCount == 0) { return; } if (!Device.Tables) { RenderItemsListWithoutTableTags(writer); return; } int pageStart = Control.FirstVisibleItemIndex; int pageSize = Control.VisibleItemCount; ObjectListItemCollection items = Control.Items; bool hasDefaultCommand = HasDefaultCommand(); bool onlyHasDefaultCommand = OnlyHasDefaultCommand(); bool requiresDetailsScreen = RequiresDetailsScreen (); bool itemRequiresHyperlink = requiresDetailsScreen || hasDefaultCommand; bool itemRequiresMoreButton = requiresDetailsScreen && hasDefaultCommand; int fieldCount; int[] fieldIndices; DetermineFieldIndicesAndCount (out fieldCount, out fieldIndices); Style style = this.Style; Style subCommandStyle = Control.CommandStyle; Style labelStyle = Control.LabelStyle; Color foreColor = (Color)style[Style.ForeColorKey, true]; // Note: table width is not supported in DTD (the text of the rec says it's supported; a bug in the rec). ClearPendingBreakIfDeviceBreaksOnBlockLevel(writer); // we are writing a block level element in all cases. ConditionalEnterLayout(writer, Style); RenderOpeningListTag(writer, "table"); RenderListViewTableHeader (writer, fieldCount, fieldIndices, itemRequiresMoreButton); RenderRule (writer, foreColor , fieldCount + (itemRequiresMoreButton ? 1 : 0)); for (int i = 0; i < pageSize; i++) { ObjectListItem item = items[pageStart + i]; RenderListViewItem (writer, item, fieldCount, fieldIndices, itemRequiresMoreButton, itemRequiresHyperlink); } RenderRule (writer, foreColor , fieldCount + (itemRequiresMoreButton ? 1 : 0)); RenderClosingListTag(writer, "table"); ConditionalExitLayout(writer, Style); } private void RenderItemsListWithoutTableTags(XhtmlMobileTextWriter writer) { if (Control.VisibleItemCount == 0) { return; } ConditionalRenderOpeningDivElement(writer); int startIndex = Control.FirstVisibleItemIndex; int pageSize = Control.VisibleItemCount; ObjectListItemCollection items = Control.Items; IObjectListFieldCollection allFields = Control.AllFields; int count = allFields.Count; int nextStartIndex = startIndex + pageSize; int labelFieldIndex = Control.LabelFieldIndex; Style style = this.Style; Style labelStyle = Control.LabelStyle; String cssClass = GetCustomAttributeValue(XhtmlConstants.CssClassCustomAttribute); String labelClass = GetCustomAttributeValue(XhtmlConstants.CssLabelClassCustomAttribute); if (labelClass == null || labelClass.Length == 0) { labelClass = cssClass; } ConditionalEnterStyle(writer, labelStyle); bool requiresLabelClassSpan = CssLocation == StyleSheetLocation.PhysicalFile && labelClass != null && labelClass.Length > 0; if (requiresLabelClassSpan) { writer.WriteBeginTag("span"); writer.WriteAttribute("class", labelClass, true); writer.Write(">"); } writer.Write(Control.AllFields[labelFieldIndex].Title); writer.SetPendingBreak(); if (requiresLabelClassSpan) { writer.WriteEndTag("span"); } ConditionalExitStyle(writer, labelStyle); writer.WritePendingBreak(); bool hasDefaultCommand = HasDefaultCommand(); bool onlyHasDefaultCommand = OnlyHasDefaultCommand(); bool requiresDetailsScreen = !onlyHasDefaultCommand && HasCommands(); // if there is > 1 visible field, need a details screen for (int visibleFields = 0, i = 0; !requiresDetailsScreen && i < count; i++) { visibleFields += allFields[i].Visible ? 1 : 0; requiresDetailsScreen = requiresDetailsScreen || visibleFields > 1; } bool itemRequiresHyperlink = requiresDetailsScreen || hasDefaultCommand; bool itemRequiresMoreButton = requiresDetailsScreen && hasDefaultCommand; Style subCommandStyle = Control.CommandStyle; subCommandStyle.Alignment = style.Alignment; subCommandStyle.Wrapping = style.Wrapping; ConditionalEnterStyle(writer, style); for (int i = startIndex; i < nextStartIndex; i++) { ObjectListItem item = items[i]; String accessKey = GetCustomAttributeValue(item, XhtmlConstants.AccessKeyCustomAttribute); String itemClass = GetCustomAttributeValue(item, XhtmlConstants.CssClassCustomAttribute); if (itemRequiresHyperlink) { RenderPostBackEventAsAnchor(writer, hasDefaultCommand ? item.Index.ToString(CultureInfo.InvariantCulture) : String.Format(CultureInfo.InvariantCulture, ShowMoreFormat, item.Index), item[labelFieldIndex], accessKey, Style, cssClass); } else { bool requiresItemClassSpan = CssLocation == StyleSheetLocation.PhysicalFile && itemClass != null && itemClass.Length > 0; if (requiresItemClassSpan) { writer.WriteBeginTag("span"); writer.WriteAttribute("class", itemClass, true); writer.Write(">"); } writer.Write(item[labelFieldIndex]); if (requiresItemClassSpan) { writer.WriteEndTag("span"); } } if (itemRequiresMoreButton) { String commandClass = GetCustomAttributeValue(XhtmlConstants.CssCommandClassCustomAttribute); BooleanOption cachedItalic = subCommandStyle.Font.Italic; subCommandStyle.Font.Italic = BooleanOption.False; ConditionalEnterFormat(writer, subCommandStyle); if ((String)Device[XhtmlConstants.BreaksOnInlineElements] != "true") { writer.Write(" ["); } ConditionalExitFormat(writer, subCommandStyle); subCommandStyle.Font.Italic = cachedItalic; ConditionalEnterFormat(writer, subCommandStyle); String controlMT = Control.MoreText; String moreText = (controlMT == null || controlMT.Length == 0) ? GetDefaultLabel(MoreLabel) : controlMT; RenderPostBackEventAsAnchor(writer, String.Format(CultureInfo.InvariantCulture, ShowMoreFormat, item.Index), moreText, null /*accessKey*/, subCommandStyle, commandClass); ConditionalExitFormat(writer, subCommandStyle); subCommandStyle.Font.Italic = BooleanOption.False; ConditionalEnterFormat(writer, subCommandStyle); if ((String)Device[XhtmlConstants.BreaksOnInlineElements] != "true") { writer.Write("]"); } ConditionalExitFormat(writer, subCommandStyle); subCommandStyle.Font.Italic = cachedItalic; } if (i < (nextStartIndex - 1)) { writer.WriteBreak(); } else { writer.SetPendingBreak(); } } ConditionalExitStyle(writer, style); ConditionalRenderClosingDivElement(writer); } // Render a single ObjectListItem in list view. private void RenderListViewItem (XhtmlMobileTextWriter writer, ObjectListItem item, int fieldCount, int[] fieldIndices, bool itemRequiresMoreButton, bool itemRequiresHyperlink) { Style style = Style; Style subCommandStyle = Control.CommandStyle; String accessKey = GetCustomAttributeValue(item, XhtmlConstants.AccessKeyCustomAttribute); String cssClass = GetCustomAttributeValue(item, XhtmlConstants.CssClassCustomAttribute); String subCommandClass = GetCustomAttributeValue(XhtmlConstants.CssCommandClassCustomAttribute); if (subCommandClass == null || subCommandClass.Length == 0) { subCommandClass = cssClass; } writer.WriteLine("<tr>"); // Render fields. for (int field = 0; field < fieldCount; field++) { writer.Write("<td>"); if (field == 0 && itemRequiresHyperlink) { String eventArgument = HasDefaultCommand() ? item.Index.ToString(CultureInfo.InvariantCulture) : String.Format(CultureInfo.InvariantCulture, ShowMoreFormat, item.Index.ToString(CultureInfo.InvariantCulture)); RenderPostBackEventAsAnchor(writer, eventArgument, item[fieldIndices[0]], accessKey, Style, cssClass); } else { writer.WriteEncodedText (item[fieldIndices[field]]); } writer.WriteLine("</td>"); } if (itemRequiresMoreButton) { writer.Write("<td>"); String controlMT = Control.MoreText; String moreText = (controlMT == null || controlMT.Length == 0) ? GetDefaultLabel(MoreLabel) : controlMT; RenderPostBackEventAsAnchor(writer, String.Format(CultureInfo.InvariantCulture, ShowMoreFormat, item.Index), moreText, null /*accessKey*/, subCommandStyle, subCommandClass); writer.WriteLine("</td>"); } writer.WriteLine("</tr>"); } private void RenderListViewTableHeader (XhtmlMobileTextWriter writer, int fieldCount, int[] fieldIndices, bool itemRequiresMoreButton){ String cssClass = GetCustomAttributeValue(XhtmlConstants.CssClassCustomAttribute); String labelClass = GetCustomAttributeValue(XhtmlConstants.CssLabelClassCustomAttribute); if (labelClass == null || labelClass.Length == 0) { labelClass = cssClass; } writer.WriteLine("<tr>"); for (int field = 0; field < fieldCount; field++) { writer.WriteBeginTag("td"); if (CssLocation == StyleSheetLocation.PhysicalFile && labelClass != null && labelClass.Length > 0) { writer.WriteAttribute("class", labelClass, true); } writer.Write(">"); Style labelStyle = Control.LabelStyle; ConditionalEnterStyle(writer, labelStyle); writer.WriteEncodedText(Control.AllFields[fieldIndices[field]].Title); ConditionalExitStyle(writer, labelStyle); writer.Write("</td>"); } if (itemRequiresMoreButton) { writer.WriteLine("<td/>"); } writer.WriteLine(); writer.WriteLine("</tr>"); } private void RenderRule (XhtmlMobileTextWriter writer, Color foreColor, int columnSpan) { if (CssLocation == StyleSheetLocation.PhysicalFile || Device["requiresXhtmlCssSuppression"] == "true") { // Review: Since, if there is a physical stylesheet, we cannot know the intended foreColor, // do not render a rule. return; } writer.Write("<tr>"); Style hruleStyle = new Style(); // Rendering <td...> with background color equal to the style's forecolor renders a thin // rule with color forecolor, as intended. hruleStyle[Style.BackColorKey] = foreColor == Color.Empty ? Color.Black : foreColor; NameValueCollection additionalAttributes = new NameValueCollection(); additionalAttributes["colspan"] = columnSpan.ToString(CultureInfo.InvariantCulture); writer.EnterStyleInternal(hruleStyle, "td", StyleFilter.BackgroundColor, additionalAttributes); writer.ExitStyle(Style); writer.WriteEndTag("tr"); } private bool RequiresDetailsScreen () { return HasItemDetails() || (Control.Commands.Count > 0 && !OnlyHasDefaultCommand()); } private void SetSecondaryUIMode () { if (WillDetailsBeRendered ()) { SecondaryUIMode = _modeDetails; } else { SecondaryUIMode = NotSecondaryUI; } } // Return true (in PreRender) if the details view will be shown. Used to set secondary UI // and call ObjectList.PreShowItemCommands during PreRender. private bool WillDetailsBeRendered () { return Control.MobilePage.ActiveForm == Control.Form && Control.Visible && (Control.ViewMode == ObjectListViewMode.Commands || Control.ViewMode == ObjectListViewMode.Details); } } }
using System; using System.Collections.Generic; using System.Text; namespace Hydra.Framework.Mapping.CoordinateSystems { // // ********************************************************************** /// <summary> /// A 3D coordinate system, with its origin at the center of the Earth. /// </summary> // ********************************************************************** // public class GeocentricCoordinateSystem : AbstractCoordinateSystem, IGeocentricCoordinateSystem { #region Private Member Variables // // ********************************************************************** /// <summary> /// Horizontal AbstractDatum /// </summary> // ********************************************************************** // private IHorizontalDatum m_HorizontalDatum; // // ********************************************************************** /// <summary> /// Linear Unit /// </summary> // ********************************************************************** // private ILinearUnit m_LinearUnit; // // ********************************************************************** /// <summary> /// Prime Meridian /// </summary> // ********************************************************************** // private IPrimeMeridian m_PrimeMeridan; #endregion #region Constructors // // ********************************************************************** /// <summary> /// Initializes a new instance of the <see cref="GeocentricCoordinateSystem"/> class. /// </summary> /// <param name="datum">The datum.</param> /// <param name="linearUnit">The linear unit.</param> /// <param name="primeMeridian">The prime meridian.</param> /// <param name="axisinfo">The axisinfo.</param> /// <param name="name">The name.</param> /// <param name="authority">The authority.</param> /// <param name="code">The code.</param> /// <param name="alias">The alias.</param> /// <param name="remarks">The remarks.</param> /// <param name="abbreviation">The abbreviation.</param> // ********************************************************************** // internal GeocentricCoordinateSystem(IHorizontalDatum datum, ILinearUnit linearUnit, IPrimeMeridian primeMeridian, List<AxisInfo> axisinfo, string name, string authority, long code, string alias, string remarks, string abbreviation) : base(name, authority, code, alias, abbreviation, remarks) { m_HorizontalDatum = datum; m_LinearUnit = linearUnit; m_PrimeMeridan = primeMeridian; if (axisinfo.Count != 3) throw new ArgumentException("Axis info should contain three axes for geocentric coordinate systems"); base.AxisInfo = axisinfo; } #endregion #region Predefined Geographic Coordinate Systems // // ********************************************************************** /// <summary> /// Creates a geocentric coordinate system based on the WGS84 ellipsoid, suitable for GPS measurements /// </summary> /// <value>The WG S84.</value> // ********************************************************************** // public static IGeocentricCoordinateSystem WGS84 { get { return new CoordinateSystemFactory().CreateGeocentricCoordinateSystem("WGS84 Geocentric", Hydra.Framework.Mapping.CoordinateSystems.HorizontalDatum.WGS84, Hydra.Framework.Mapping.CoordinateSystems.LinearUnit.Metre, Hydra.Framework.Mapping.CoordinateSystems.PrimeMeridian.Greenwich); } } #endregion #region IGeocentricCoordinateSystem Implementation // // ********************************************************************** /// <summary> /// Returns the HorizontalDatum. The horizontal datum is used to determine where /// the centre of the Earth is considered to be. All coordinate points will be /// measured from the centre of the Earth, and not the surface. /// </summary> /// <value>The horizontal datum.</value> // ********************************************************************** // public IHorizontalDatum HorizontalDatum { get { return m_HorizontalDatum; } set { m_HorizontalDatum = value; } } // // ********************************************************************** /// <summary> /// Gets the units used along all the axes. /// </summary> /// <value>The linear unit.</value> // ********************************************************************** // public ILinearUnit LinearUnit { get { return m_LinearUnit; } set { m_LinearUnit = value; } } // // ********************************************************************** /// <summary> /// Gets units for dimension within coordinate system. Each dimension in /// the coordinate system has corresponding units. /// </summary> /// <param name="dimension">Dimension</param> /// <returns>Unit</returns> // ********************************************************************** // public override IUnit GetUnits(int dimension) { return m_LinearUnit; } // // ********************************************************************** /// <summary> /// Returns the PrimeMeridian. /// </summary> /// <value>The prime meridian.</value> // ********************************************************************** // public IPrimeMeridian PrimeMeridian { get { return m_PrimeMeridan; } set { m_PrimeMeridan = value; } } // // ********************************************************************** /// <summary> /// Returns the Well-known text for this object /// as defined in the simple features specification. /// </summary> /// <value></value> // ********************************************************************** // public override string WKT { get { StringBuilder sb = new StringBuilder(); sb.AppendFormat("GEOCCS[\"{0}\", {1}, {2}, {3}", Name, HorizontalDatum.WKT, PrimeMeridian.WKT, LinearUnit.WKT); // // Skip axis info if they contain default values // if (AxisInfo.Count != 3 || AxisInfo[0].Name != "X" || AxisInfo[0].Orientation != AxisOrientationEnum.Other || AxisInfo[1].Name != "Y" || AxisInfo[1].Orientation != AxisOrientationEnum.East || AxisInfo[2].Name != "Z" || AxisInfo[2].Orientation != AxisOrientationEnum.North) { for (int i = 0; i < AxisInfo.Count; i++) sb.AppendFormat(", {0}", GetAxis(i).WKT); } if (!String.IsNullOrEmpty(Authority) && AuthorityCode > 0) sb.AppendFormat(", AUTHORITY[\"{0}\", \"{1}\"]", Authority, AuthorityCode); sb.Append("]"); return sb.ToString(); } } // // ********************************************************************** /// <summary> /// Gets an XML representation of this object /// </summary> /// <value></value> // ********************************************************************** // public override string XML { get { StringBuilder sb = new StringBuilder(); sb.AppendFormat(Hydra.Framework.Mapping.Map.numberFormat_EnUS, "<CS_CoordinateSystem Dimension=\"{0}\"><CS_GeocentricCoordinateSystem>{1}", this.Dimension, InfoXml); foreach (AxisInfo ai in this.AxisInfo) sb.Append(ai.XML); sb.AppendFormat("{0}{1}{2}</CS_GeocentricCoordinateSystem></CS_CoordinateSystem>", HorizontalDatum.XML, LinearUnit.XML, PrimeMeridian.XML); return sb.ToString(); } } // // ********************************************************************** /// <summary> /// Checks whether the values of this instance is equal to the values of another instance. /// Only parameters used for coordinate system are used for comparison. /// StateName, abbreviation, authority, alias and remarks are ignored in the comparison. /// </summary> /// <param name="obj"></param> /// <returns>True if equal</returns> // ********************************************************************** // public override bool EqualParams(object obj) { if (!(obj is GeocentricCoordinateSystem)) return false; GeocentricCoordinateSystem gcc = obj as GeocentricCoordinateSystem; return gcc.HorizontalDatum.EqualParams(this.HorizontalDatum) && gcc.LinearUnit.EqualParams(this.LinearUnit) && gcc.PrimeMeridian.EqualParams(this.PrimeMeridian); } #endregion } }
// Copyright (c) 2007-2014 SIL International // Licensed under the MIT license: opensource.org/licenses/MIT using System; using System.Diagnostics; using System.Globalization; using System.Text; using System.Collections.Generic; using System.IO; using System.Linq; using System.Windows.Forms; using System.Xml.Serialization; using System.Xml.Linq; using SIL.Reporting; using SolidGui.MarkerSettings; namespace SolidGui.Engine { public class SolidSettings { private /*readonly*/ List<SolidMarkerSetting> _markerSettings; private List<SolidMarkerSetting> _newlyAdded; private string _recordMarker = "lx"; public static readonly int LatestVersion = 3; // Seems safer to use readonly rather than const here; it will eventually change. -JMC //public static readonly Encoding LegacyEncoding = Encoding.GetEncoding("iso-8859-1"); //the original public static readonly Encoding LegacyEncoding = Encoding.GetEncoding(1252); //my preference--handles curly quotes -JMC Feb 2014 public SolidSettings(List<SolidMarkerSetting> ms) { Version = LatestVersion.ToString(); // DefaultEncodingUnicode = false; // Should not explicitly set this to false anymore. Removing this line fixes bug #270 _markerSettings = ms; _newlyAdded = new List<SolidMarkerSetting>(); FileStatusReport = new SettingsFileReport(); } public SolidSettings() : this(new List<SolidMarkerSetting>()) {} // TODO! Candidates that could be global 'constants' (or public static readonly): "lx", "entry", ".solid", "infer ", "Report Error" // e.g. public static readonly string DotSolid = ".solid" private static List<string> _fileExtensions = new List<string> { ".db", ".sfm", ".mdf", ".dic", ".txt", ".lex" }; // added by JMC 2013-09 [XmlIgnore] public static List<string> FileExtensions // added by JMC 2013-09; note that it's not read-only; might perhaps have made more sense to have this property under MainWindowPM? { get { return _fileExtensions; } } public static string extsAsString(IEnumerable<string> exts) // added by JMC 2013-09 { var x = new StringBuilder(); foreach (string extension in exts) { x.Append(extension + " "); } return x.ToString().Trim(); } // Returns the known dictionary extensions as a mask; baseFileName can simply be "*" public static string extsAsMask(IEnumerable<string> exts, string baseFileName) // added by JMC 2013-09 { var x2 = new StringBuilder(); foreach (string extension in exts) { x2.Append(baseFileName + extension + ";"); } return x2.ToString(); } public override string ToString() { string s = ""; IEnumerable<SolidMarkerSetting> a; if (_markerSettings.Count > 4) { a = _markerSettings.Take(4); s = "..."; } else { a = _markerSettings; } s = string.Join(" ", a) + s; return string.Format("{{{0} setts: {1}; {2}}}", _markerSettings.Count, s, GetHashCode()); } [XmlIgnore] public SettingsFileReport FileStatusReport; public decimal getVersionNum() { return Convert.ToDecimal(Version); } [XmlIgnore] public IEnumerable<string> Markers { get { return _markerSettings.Select(item => item.Marker); //LINQ } } // Build a compilation of required fields in a form accessible by parent marker. // (This avoids caching a copy of each requirement in the parent object itself, // while avoiding the performance issue of creating this list thousands of times.) public static IDictionary<string, HashSet<string>> AllRequiredChildren(IEnumerable<SolidMarkerSetting> markerSettings) { var dict = new Dictionary<string, HashSet<string>>(); foreach (var m in markerSettings) { foreach (var sp in m.StructureProperties) { if (sp.Required) { if (!dict.ContainsKey(sp.Parent)) { dict.Add(sp.Parent, new HashSet<string>()); } dict[sp.Parent].Add(m.Marker); } } } return dict; } [XmlElement("RecordMarker", Order = 0)] public string RecordMarker { get { return _recordMarker; } set { _recordMarker = value; } } [XmlElement("Version", Order = 1)] public string Version { get; set; } // set needs to be public for XmlSerialize to work CP. // TODO : Ideally, this shouldn't be public, and _markerSettings should be readonly /// WARNING: This property's setter should only be used by the xml-mapping code [XmlArray("MarkerSettings", Order = 2)] [XmlArrayItem("SolidMarkerSetting", typeof(SolidMarkerSetting))] public List<SolidMarkerSetting> MarkerSettings { get { return _markerSettings; } set { _markerSettings = value; } } [XmlIgnore] public string FilePath { get; set; } private bool _haveDeterminedDefault = false; private bool _defaultEncodingUnicode; [XmlIgnore] // might want to eventually serialize this -JMC public bool DefaultEncodingUnicode { set { _defaultEncodingUnicode = value; _haveDeterminedDefault = true; } get { return _defaultEncodingUnicode; } } // NewLine should save as "\r\n" on Windows, but now that it's centralized here, and less is hard-coded, // maybe it can flex. Really, "\n" would be nicer (esp. given RichTextBox's behavior), and only using // \r\n when saving to disk on Windows. // But it would be good to first do full testing (both unit and UI) using "\n" as the value. public static string NewLine = "\r\n"; //Static for now; maybe shouldn't be. And maybe should just return System.Environment.NewLine. -JMC public bool HasMarker(string marker) { return FindMarkerSetting(marker) != null; } private SolidMarkerSetting FindMarkerSetting(string marker) { return _markerSettings.Find(item => item.Marker == marker); } /// <summary> /// Look for the marker. If necessary, add it. /// </summary> /// <param name="marker">The marker to search for.</param> /// <returns>Returns an existing setting if possible; otherwise a newly created one.</returns> public SolidMarkerSetting FindOrCreateMarkerSetting(string marker) //TODO: I think this is maybe overused and could likely mask error conditions; replace some calls with plain FindMarkerSetting()? -JMC { // Search for the marker. If not found return default marker settings. SolidMarkerSetting result = FindMarkerSetting(marker); if (result == null) { if (!_haveDeterminedDefault) DetermineDefaultEncodingUnicode(this); result = new SolidMarkerSetting(marker, DefaultEncodingUnicode); _markerSettings.Add(result); _newlyAdded.Add(result); // In some cases, the calling code should notify the user of new fields detected. } return result; } public int FindReplaceWs(string fromWritingSystem, string toWritingSystem) { int count = 0; foreach (SolidMarkerSetting markerSetting in this.MarkerSettings) { if (markerSetting.WritingSystemRfc4646 == fromWritingSystem) { markerSetting.WritingSystemRfc4646 = toWritingSystem; count++; } } // TODO: I think we want something like the following any time anything is modified. But we'd need to hold a reference to the model. // So for now, the onus is on the calling code to set NeedsSave. -JMC Jan 2014 /* if (count > 0) { _mainWindowPM.needsSave = true; } */ return count; } public void NotifyIfNewMarkers(bool thenCheckMixedEncodings) // Added -JMC 2013-09 ; TODO: The MessageBox part probably belongs in a "View" class instead, but the logic should stay here. -JMC { if (_newlyAdded == null || _newlyAdded.Count < 1) return; var sb = new StringBuilder("New marker(s) added: "); foreach (SolidMarkerSetting marker in _newlyAdded) { sb.Append(string.Format("{0} ({1}) ", marker.Marker, marker.Unicode ? "u" : "Legacy!")); } sb.Append(". Will appear upon Recheck.\n"); MessageBox.Show(sb.ToString(), "New Marker(s) Added", MessageBoxButtons.OK, MessageBoxIcon.Information); _newlyAdded = new List<SolidMarkerSetting>(); //clear it out (don't keep notifying) if (thenCheckMixedEncodings) { NotifyIfMixedEncodings(); } } // This should be called once after every File Open. Especially because, even though most users don't need mixed encodings, // Solid used to silently create legacy-encoded markers whenever a new marker was identified in any file (even a unicode one). -JMC public string NotifyIfMixedEncodings() { int uni = 0; var legacy = new List<string>(); foreach (SolidMarkerSetting marker in _markerSettings) { if (marker.Unicode) { uni++; } else { legacy.Add(marker.Marker); } } if (uni > 0 && uni < _markerSettings.Count) // non-mixed is ideal: all or nothing in unicode { string msg = string.Join(" ", legacy.ToArray()); msg = "Warning: the marker settings have a mix of unicode and legacy specified." + "\nLegacy markers: " + msg + "\nNote: settings are invisible for markers not currently in use."; return msg; } return ""; } /// <summary> /// Will silently rename existing file to name.solid.bak, if necessary. /// </summary> /// <param name="templateFilePath"></param> /// <param name="outputFilePath"></param> /// <returns></returns> public static SolidSettings CreateSolidFileFromTemplate(string templateFilePath, string outputFilePath) { string needsBackup = outputFilePath; try { // File.Delete(outputFilePath); if (File.Exists(outputFilePath)) // added by JMC { string backupPath = outputFilePath + ".bak"; int i = 2; while (File.Exists(backupPath)) { backupPath = outputFilePath + ".bak" + i++.ToString(); } File.Move(outputFilePath, backupPath); } File.Copy(templateFilePath, outputFilePath); } catch (Exception e) { ErrorReport.NotifyUserOfProblem( "There was a problem opening that settings file. The error was\r\n" + e.Message); return null; } return OpenSolidFile(outputFilePath); } public void SetAllUnicodeTo(bool isUnicode) { DefaultEncodingUnicode = isUnicode; _haveDeterminedDefault = true; foreach (var ms in _markerSettings) { ms.Unicode = isUnicode; } } /// <summary> /// Determine the default encoding, based on record marker if possible; otherwise based on the majority of markers (tiebreaker goes false) /// (I initially wrote the "pick majority" code thinking it best and not realizing that legacy is better at preserving mixed encodings; /// the "pick majority" code could probably be removed now--less to maintain--since vernacular should take priority. -JMC) /// </summary> /// <param name="settings">A valid, already loaded set of settings, preferably including the record marker.</param> /// <returns>true (unicode) or false (legacy)</returns> public static bool DetermineDefaultEncodingUnicode(SolidSettings settings) // Added by JMC 2013-09 { SolidMarkerSetting recordMarker = settings.FindMarkerSetting(settings.RecordMarker); if (!(recordMarker == null)) { settings.DefaultEncodingUnicode = recordMarker.Unicode; } else { //This generally shouldn't happen, but it could if lx isn't the first marker in the .solid file //and an earlier marker's unicode isn't specified. int countTrue = 0; int countFalse = 0; foreach (string m in settings.Markers) { if (settings.FindMarkerSetting(m).Unicode) { countTrue++; } else { countFalse++; } } if (countTrue > countFalse) { settings.DefaultEncodingUnicode = true; } else { settings.DefaultEncodingUnicode = false; } } return settings.DefaultEncodingUnicode; } /// <summary> /// Open existing .solid file. /// </summary> /// <param name="filePath"></param> /// <param name="detailedResults">The object passed in will be modified to provide details about problems or dropped data. Also includes the return value.</param> /// <returns>Notifies user and returns null if file can't be opened for any reason</returns> public static SolidSettings OpenSolidFile(string filePath) { if(!File.Exists(filePath)) { using(File.Create(filePath)) {} } SolidSettings settings; //Migrate/load the file. (Previously (before the mapper), we would migrate first via XSLT, then deserialize from disk directly into objects) -JMC July 2014 XDocument xdoc = XDocument.Load(filePath); settings = MarkerSettingsMapper.LoadMarkerSettings(xdoc); // Set properties that aren't serialized. settings.FilePath = filePath; // Fix settings for the record marker. SolidMarkerSetting markerSetting = settings.FindOrCreateMarkerSetting(settings.RecordMarker); //!!! Assert if null // Check that it has 'entry' as the parent. if (!markerSetting.IsAnAllowedParent("entry")) { markerSetting.StructureProperties.Add(new SolidStructureProperty("entry")); } return settings; } public bool Save() { return SaveAs(FilePath); } /// <summary> /// Saves the .solid settings file. Overwrites without prompting if the file exists. /// </summary> /// <param name="filePath"></param> public bool SaveAs(string filePath) { Logger.WriteEvent("Saving {0}", filePath); try { var xs = new XmlSerializer(typeof(SolidSettings)); using (var writer = new StreamWriter(filePath)) { xs.Serialize(writer, this); } } catch (Exception exception) { MessageBox.Show(null, exception.Message + "\r\n\r\nYou might try saving to a different location.", "Error on saving file."); return false; } Logger.WriteEvent("Done saving settings file."); return true; } public static string GetSettingsFilePathFromDictionaryPath(string dataFilePath) { int lastDot = dataFilePath.LastIndexOf('.'); if (lastDot < 0) { lastDot = dataFilePath.Length; } string retval = dataFilePath.Substring(0, lastDot) + ".solid"; return retval; } // Assuming some file.solid exists and was passed in, return any other file.* that exists; // Return just one path, preferring certain extensions. Created by JMC 2013-09 public static string GetDictionaryFilePathFromSettingsPath(string settingsFilePath) { var fileInfo = new FileInfo(settingsFilePath); DirectoryInfo dirInfo = fileInfo.Directory; string f = fileInfo.Name; string ext = fileInfo.Extension; //Path.GetExtension(settingsFilePath); if (ext.Length > 0) { f = f.Substring(0, f.Length - ext.Length); //get the base filename without the extension } else { throw new ArgumentException("The settings file path ought to end in .solid"); } //JMC:! check for null dirInfo ? List<string> extensions = FileExtensions; // was: new string[]{".db", ".sfm", ".mdf", ".dic", ".txt"}; string mask = extsAsMask(extensions, f); FileInfo[] matches = dirInfo.GetFiles(mask, SearchOption.TopDirectoryOnly); //find likely matches if (matches.Length < 1) { matches = dirInfo.GetFiles(f + ".*"); //nothing yet; find all possible matches if (matches.Length < 2) { //still nothing beyond the .solid file; fail var x = new StringBuilder(); x.AppendFormat("Solid could not find a matching dictionary for {0}. Please try again via the File menu.", settingsFilePath); ErrorReport.NotifyUserOfProblem(x.ToString()); return ""; } } foreach (FileInfo match in matches) // pick the first (or only) match { if (match.Extension != ".solid") { if (!extensions.Contains(match.Extension)) { extensions.Add(match.Extension); // adaptive: makes the next File Open dialog friendlier (not saved) -JMC } return Path.Combine(dirInfo.ToString(), match.ToString()); } } return ""; // fail } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V9.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V9.Services { /// <summary>Settings for <see cref="FeedItemServiceClient"/> instances.</summary> public sealed partial class FeedItemServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="FeedItemServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="FeedItemServiceSettings"/>.</returns> public static FeedItemServiceSettings GetDefault() => new FeedItemServiceSettings(); /// <summary>Constructs a new <see cref="FeedItemServiceSettings"/> object with default settings.</summary> public FeedItemServiceSettings() { } private FeedItemServiceSettings(FeedItemServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetFeedItemSettings = existing.GetFeedItemSettings; MutateFeedItemsSettings = existing.MutateFeedItemsSettings; OnCopy(existing); } partial void OnCopy(FeedItemServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>FeedItemServiceClient.GetFeedItem</c> and <c>FeedItemServiceClient.GetFeedItemAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetFeedItemSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>FeedItemServiceClient.MutateFeedItems</c> and <c>FeedItemServiceClient.MutateFeedItemsAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings MutateFeedItemsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="FeedItemServiceSettings"/> object.</returns> public FeedItemServiceSettings Clone() => new FeedItemServiceSettings(this); } /// <summary> /// Builder class for <see cref="FeedItemServiceClient"/> to provide simple configuration of credentials, endpoint /// etc. /// </summary> internal sealed partial class FeedItemServiceClientBuilder : gaxgrpc::ClientBuilderBase<FeedItemServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public FeedItemServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public FeedItemServiceClientBuilder() { UseJwtAccessWithScopes = FeedItemServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref FeedItemServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<FeedItemServiceClient> task); /// <summary>Builds the resulting client.</summary> public override FeedItemServiceClient Build() { FeedItemServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<FeedItemServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<FeedItemServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private FeedItemServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return FeedItemServiceClient.Create(callInvoker, Settings); } private async stt::Task<FeedItemServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return FeedItemServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => FeedItemServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => FeedItemServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => FeedItemServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>FeedItemService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage feed items. /// </remarks> public abstract partial class FeedItemServiceClient { /// <summary> /// The default endpoint for the FeedItemService service, which is a host of "googleads.googleapis.com" and a /// port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default FeedItemService scopes.</summary> /// <remarks> /// The default FeedItemService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="FeedItemServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="FeedItemServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="FeedItemServiceClient"/>.</returns> public static stt::Task<FeedItemServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new FeedItemServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="FeedItemServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="FeedItemServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="FeedItemServiceClient"/>.</returns> public static FeedItemServiceClient Create() => new FeedItemServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="FeedItemServiceClient"/> which uses the specified call invoker for remote operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="FeedItemServiceSettings"/>.</param> /// <returns>The created <see cref="FeedItemServiceClient"/>.</returns> internal static FeedItemServiceClient Create(grpccore::CallInvoker callInvoker, FeedItemServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } FeedItemService.FeedItemServiceClient grpcClient = new FeedItemService.FeedItemServiceClient(callInvoker); return new FeedItemServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC FeedItemService client</summary> public virtual FeedItemService.FeedItemServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested feed item in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::FeedItem GetFeedItem(GetFeedItemRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested feed item in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::FeedItem> GetFeedItemAsync(GetFeedItemRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested feed item in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::FeedItem> GetFeedItemAsync(GetFeedItemRequest request, st::CancellationToken cancellationToken) => GetFeedItemAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested feed item in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the feed item to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::FeedItem GetFeedItem(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetFeedItem(new GetFeedItemRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested feed item in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the feed item to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::FeedItem> GetFeedItemAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetFeedItemAsync(new GetFeedItemRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested feed item in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the feed item to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::FeedItem> GetFeedItemAsync(string resourceName, st::CancellationToken cancellationToken) => GetFeedItemAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested feed item in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the feed item to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::FeedItem GetFeedItem(gagvr::FeedItemName resourceName, gaxgrpc::CallSettings callSettings = null) => GetFeedItem(new GetFeedItemRequest { ResourceNameAsFeedItemName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested feed item in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the feed item to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::FeedItem> GetFeedItemAsync(gagvr::FeedItemName resourceName, gaxgrpc::CallSettings callSettings = null) => GetFeedItemAsync(new GetFeedItemRequest { ResourceNameAsFeedItemName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested feed item in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the feed item to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::FeedItem> GetFeedItemAsync(gagvr::FeedItemName resourceName, st::CancellationToken cancellationToken) => GetFeedItemAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes feed items. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [CriterionError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FeedItemError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [ListOperationError]() /// [MutateError]() /// [NotEmptyError]() /// [NullError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateFeedItemsResponse MutateFeedItems(MutateFeedItemsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes feed items. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [CriterionError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FeedItemError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [ListOperationError]() /// [MutateError]() /// [NotEmptyError]() /// [NullError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateFeedItemsResponse> MutateFeedItemsAsync(MutateFeedItemsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes feed items. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [CriterionError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FeedItemError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [ListOperationError]() /// [MutateError]() /// [NotEmptyError]() /// [NullError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateFeedItemsResponse> MutateFeedItemsAsync(MutateFeedItemsRequest request, st::CancellationToken cancellationToken) => MutateFeedItemsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes feed items. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [CriterionError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FeedItemError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [ListOperationError]() /// [MutateError]() /// [NotEmptyError]() /// [NullError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose feed items are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual feed items. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateFeedItemsResponse MutateFeedItems(string customerId, scg::IEnumerable<FeedItemOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateFeedItems(new MutateFeedItemsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes feed items. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [CriterionError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FeedItemError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [ListOperationError]() /// [MutateError]() /// [NotEmptyError]() /// [NullError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose feed items are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual feed items. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateFeedItemsResponse> MutateFeedItemsAsync(string customerId, scg::IEnumerable<FeedItemOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateFeedItemsAsync(new MutateFeedItemsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes feed items. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [CriterionError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FeedItemError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [ListOperationError]() /// [MutateError]() /// [NotEmptyError]() /// [NullError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose feed items are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual feed items. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateFeedItemsResponse> MutateFeedItemsAsync(string customerId, scg::IEnumerable<FeedItemOperation> operations, st::CancellationToken cancellationToken) => MutateFeedItemsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>FeedItemService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage feed items. /// </remarks> public sealed partial class FeedItemServiceClientImpl : FeedItemServiceClient { private readonly gaxgrpc::ApiCall<GetFeedItemRequest, gagvr::FeedItem> _callGetFeedItem; private readonly gaxgrpc::ApiCall<MutateFeedItemsRequest, MutateFeedItemsResponse> _callMutateFeedItems; /// <summary> /// Constructs a client wrapper for the FeedItemService service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="FeedItemServiceSettings"/> used within this client.</param> public FeedItemServiceClientImpl(FeedItemService.FeedItemServiceClient grpcClient, FeedItemServiceSettings settings) { GrpcClient = grpcClient; FeedItemServiceSettings effectiveSettings = settings ?? FeedItemServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetFeedItem = clientHelper.BuildApiCall<GetFeedItemRequest, gagvr::FeedItem>(grpcClient.GetFeedItemAsync, grpcClient.GetFeedItem, effectiveSettings.GetFeedItemSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetFeedItem); Modify_GetFeedItemApiCall(ref _callGetFeedItem); _callMutateFeedItems = clientHelper.BuildApiCall<MutateFeedItemsRequest, MutateFeedItemsResponse>(grpcClient.MutateFeedItemsAsync, grpcClient.MutateFeedItems, effectiveSettings.MutateFeedItemsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateFeedItems); Modify_MutateFeedItemsApiCall(ref _callMutateFeedItems); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_GetFeedItemApiCall(ref gaxgrpc::ApiCall<GetFeedItemRequest, gagvr::FeedItem> call); partial void Modify_MutateFeedItemsApiCall(ref gaxgrpc::ApiCall<MutateFeedItemsRequest, MutateFeedItemsResponse> call); partial void OnConstruction(FeedItemService.FeedItemServiceClient grpcClient, FeedItemServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC FeedItemService client</summary> public override FeedItemService.FeedItemServiceClient GrpcClient { get; } partial void Modify_GetFeedItemRequest(ref GetFeedItemRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_MutateFeedItemsRequest(ref MutateFeedItemsRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested feed item in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override gagvr::FeedItem GetFeedItem(GetFeedItemRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetFeedItemRequest(ref request, ref callSettings); return _callGetFeedItem.Sync(request, callSettings); } /// <summary> /// Returns the requested feed item in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<gagvr::FeedItem> GetFeedItemAsync(GetFeedItemRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetFeedItemRequest(ref request, ref callSettings); return _callGetFeedItem.Async(request, callSettings); } /// <summary> /// Creates, updates, or removes feed items. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [CriterionError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FeedItemError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [ListOperationError]() /// [MutateError]() /// [NotEmptyError]() /// [NullError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override MutateFeedItemsResponse MutateFeedItems(MutateFeedItemsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateFeedItemsRequest(ref request, ref callSettings); return _callMutateFeedItems.Sync(request, callSettings); } /// <summary> /// Creates, updates, or removes feed items. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [CriterionError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FeedItemError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [ListOperationError]() /// [MutateError]() /// [NotEmptyError]() /// [NullError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<MutateFeedItemsResponse> MutateFeedItemsAsync(MutateFeedItemsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateFeedItemsRequest(ref request, ref callSettings); return _callMutateFeedItems.Async(request, callSettings); } } }
// Copyright (c) 2015 Alachisoft // // 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.Threading; using Alachisoft.NCache.Common.Util; using Alachisoft.NCache.Common.Logger; using Alachisoft.NCache.Common.Stats; namespace Alachisoft.NCache.Common.Threading { /// <summary> /// A class that helps doing things that can be done asynchronously /// </summary> public class AsyncProcessor { /// <summary> /// Interface to be implemented by all async events. /// </summary> public interface IAsyncTask { /// <summary> Process itself. </summary> void Process(); } /// <summary> The worker thread. </summary> private Thread[] _workerThreads; /// <summary> The queue of events. </summary> private Queue _eventsHi, _eventsLow; private int _numProcessingThreads = 1; private Boolean _started; ILogger NCacheLog; bool _isShutdown = false; object _shutdownMutex = new object(); /// <summary> /// Constructor /// </summary> public AsyncProcessor(ILogger NCacheLog) : this() { this.NCacheLog = NCacheLog; } public AsyncProcessor() : this(1) { } public AsyncProcessor(int numProcessingThread):this(numProcessingThread,null) { } public AsyncProcessor(int numProcessingThread,ILogger logger) { this.NCacheLog = NCacheLog; if (numProcessingThread < 1) numProcessingThread = 1; _numProcessingThreads = numProcessingThread; _eventsHi = new Queue(256); _eventsLow = new Queue(256); } /// <summary> /// Add a low priority event to the event queue /// </summary> /// <param name="evnt">event</param> public void Enqueue(IAsyncTask evnt) { lock (this) { _eventsHi.Enqueue(evnt); Monitor.Pulse(this); } } /// <summary> /// Add a low priority event to the event queue /// </summary> /// <param name="evnt">event</param> public void EnqueueLowPriority(IAsyncTask evnt) { lock (this) { _eventsLow.Enqueue(evnt); Monitor.Pulse(this); } } /// <summary> /// Start processing /// </summary> public void Start() { try { lock (this) { if (!_started) { _workerThreads = new Thread[_numProcessingThreads]; _started = true; for (int i = 0; i < _workerThreads.Length; i++) { Thread thread = new Thread(new ThreadStart(Run)); thread.IsBackground = true; thread.Name = "AsyncProcessor.workerThread # " + i; thread.Start(); _workerThreads[i] = thread; } } } } catch (Exception ex) { if (NCacheLog != null) { NCacheLog.Error("AsyncProcessor.Start()", ex.Message); } } } /// <summary> /// Stop processing. /// </summary> public void Stop() { try { lock (this) { if (_started) { for (int i = 0; i < _workerThreads.Length; i++) { Thread thread = _workerThreads[i]; if (thread != null && thread.IsAlive) { thread.Abort(); _workerThreads[i] = null; } } _started = false; } } } catch (Exception ex) { if (NCacheLog != null) { NCacheLog.Error("AsyncProcessor.Stop()", ex.Message); } } } /// <summary> /// Thread function, keeps running. /// </summary> protected void Run() { while (_started) { IAsyncTask evnt = null; try { lock (this) { if ((_eventsHi.Count < 1) && (_eventsLow.Count < 1) && !_isShutdown) Monitor.Wait(this); if ((_eventsHi.Count < 1) && _isShutdown) { lock (_shutdownMutex) { Monitor.PulseAll(_shutdownMutex); break; } } if (_eventsHi.Count > 0) { evnt = (IAsyncTask)_eventsHi.Dequeue(); } else if (_eventsLow.Count > 0) { evnt = (IAsyncTask)_eventsLow.Dequeue(); } } if (evnt == null && _eventsHi.Count < 1 && _isShutdown) { lock (_shutdownMutex) { Monitor.PulseAll(_shutdownMutex); break; } } if (evnt == null) continue; evnt.Process(); } catch (ThreadAbortException e) { if (NCacheLog != null) { NCacheLog.Flush(); } break; } catch (NullReferenceException nr) { } catch (Exception e) { string exceptionString = e.ToString(); if (exceptionString != "ChannelNotConnectedException" && exceptionString != "ChannelClosedException") { if (NCacheLog != null) { NCacheLog.Error("AsyncProcessor.Run()", exceptionString); } } } } } } }
using System; using System.Collections.Generic; using DotNetXmlSwfChart; namespace testWeb.tests { public class FloatingBarOne : ChartTestBase { #region ChartInclude public override ChartHTML ChartInclude { get { DotNetXmlSwfChart.ChartHTML chartHtml = new DotNetXmlSwfChart.ChartHTML(); chartHtml.height = 300; chartHtml.bgColor = "ee7777"; chartHtml.flashFile = "charts/charts.swf"; chartHtml.libraryPath = "charts/charts_library"; chartHtml.xmlSource = "xmlData.aspx"; return chartHtml; } } #endregion #region Chart public override Chart Chart { get { Chart c = new Chart(); c.AddChartType(XmlSwfChartType.BarFloating); c.AxisCategory = SetAxisCategory(c.ChartType[0]); c.AxisTicks = SetAxisTicks(); c.AxisValue = SetAxisValue(); c.AddAxisValueText("JAN"); c.AddAxisValueText("FEB"); c.AddAxisValueText("MAR"); c.AddAxisValueText("APR"); c.AddAxisValueText("MAY"); c.AddAxisValueText("JUN"); c.AddAxisValueText("JUL"); c.AddAxisValueText("AUG"); c.AddAxisValueText("SEP"); c.AddAxisValueText("OCT"); c.AddAxisValueText("NOV"); c.AddAxisValueText("DEC"); c.AddAxisValueText("JAN"); c.ChartBorder = SetChartBorder(); c.Data = SetChartData(); c.ChartGridH = SetChartGrid(ChartGridType.Horizontal); c.ChartGridV = SetChartGrid(ChartGridType.Vertical); c.ChartRectangle = SetChartRectangle(); c.ChartTransition = SetChartTransition(); c.AddDrawRectangle(CreateDrawRectangle()); c.AddDrawText(CreateDrawText("production schedule", null)); c.AddDrawText(CreateDrawText("Alpha", "7/1")); c.AddDrawText(CreateDrawText("Beta", "8/1")); c.AddDrawText(CreateDrawText("Shipping date\nSep 1", "9/1")); c.AddDrawLine(CreateDrawLine("7/1")); c.AddDrawLine(CreateDrawLine("8/1")); c.AddDrawLine(CreateDrawLine("9/1")); c.AddDrawCircle(CreateDrawCircle("7/1")); c.AddDrawCircle(CreateDrawCircle("8/1")); c.AddDrawCircle(CreateDrawCircle("9/1")); c.LegendRectangle = SetLegendRectangle(); c.AddSeriesColor("ffffff"); c.AddSeriesColor("aa88ff"); c.AddSeriesColor("aaff88"); c.AddSeriesColor("aaff88"); c.AddSeriesColor("aa88ff"); c.SeriesGap = SetSeriesGap(); c.SeriesSwitch = true; return c; } } #endregion #region Helpers private AxisCategory SetAxisCategory(XmlSwfChartType xmlSwfChartType) { AxisCategory ac = new AxisCategory(xmlSwfChartType); ac.Size = 11; ac.Color = "ffffff"; ac.Alpha = 75; return ac; } private AxisTicks SetAxisTicks() { AxisTicks at = new AxisTicks(); at.ValueTicks = true; at.CategoryTicks = true; at.MajorThickness = 1; at.MinorThickness = 0; at.MinorCount = 0; at.MajorColor = "222222"; at.MinorColor = "222222"; at.Position = "centered"; return at; } private AxisValue SetAxisValue() { AxisValue av = new AxisValue(); av.Size = 8; av.Color = "000000"; av.Alpha = 60; av.Steps = 12; av.Min = 0; av.Max = 365; return av; } private ChartBorder SetChartBorder() { ChartBorder cb = new ChartBorder(); cb.Color = "000088"; cb.TopThickness = 0; cb.BottomThickness = 0; cb.LeftThickness = 0; cb.RightThickness = 0; return cb; } private ChartData SetChartData() { ChartData cd = new ChartData(); cd.AddDataPoint("hi", "marketing", new DateTime(2008, 12, 1).DayOfYear); cd.AddDataPoint("hi", "QA", new DateTime(2008, 9, 1).DayOfYear); cd.AddDataPoint("hi", "engineering", new DateTime(2008, 9, 1).DayOfYear); cd.AddDataPoint("hi", "design", new DateTime(2008, 6, 1).DayOfYear); cd.AddDataPoint("hi", "concept", new DateTime(2008, 4, 15).DayOfYear); cd.AddDataPoint("lo", "marketing", new DateTime(2008, 6, 1).DayOfYear); cd.AddDataPoint("lo", "QA", new DateTime(2008, 5, 1).DayOfYear); cd.AddDataPoint("lo", "engineering", new DateTime(2008, 4, 1).DayOfYear); cd.AddDataPoint("lo", "design", new DateTime(2008, 2, 15).DayOfYear); cd.AddDataPoint("lo", "concept", new DateTime(2008, 2, 1).DayOfYear); return cd; } private ChartGrid SetChartGrid(ChartGridType chartGridType) { ChartGrid cg = new ChartGrid(chartGridType); cg.Alpha = 100; cg.Color = "ee6666"; cg.Thickness = 1; if (chartGridType == ChartGridType.Horizontal) { cg.Alpha = 20; cg.Color = "000000"; cg.GridLineType = ChartGridLineType.dashed; } return cg; } private ChartRectangle SetChartRectangle() { ChartRectangle cr = new ChartRectangle(); cr.X = 100; cr.Y = 100; cr.Width = 275; cr.Height = 150; cr.PositiveColor = "000000"; cr.PositiveAlpha = 10; return cr; } private ChartTransition SetChartTransition() { ChartTransition ct = new ChartTransition(); ct.TransitionType = TransitionType.slide_right; ct.Delay = 0; ct.Duration = 0.6; ct.Order = TransitionOrder.all; return ct; } private DrawRectangle CreateDrawRectangle() { DrawRectangle dr = new DrawRectangle(); dr.Layer = DrawLayer.background; dr.Transition = TransitionType.slide_right; dr.Delay = 0; dr.Duration = 0.5; dr.X = 25; dr.Y = 100; dr.Width = 75; dr.Height = 150; dr.FillColor = "000000"; dr.FillAlpha = 20; dr.LineThickness = 0; return dr; } private DrawText CreateDrawText(string text, string date) { DrawText dt = new DrawText(); dt.Transition = TransitionType.slide_right; dt.Delay = 0; dt.Duration = 0.5; dt.Color = "000000"; dt.Alpha = 70; dt.Size = 9; dt.Text = text; if (date != null) dt.X = DateToPixels(date) + 7; switch (text) { case "production schedule": dt.Transition = TransitionType.drop; dt.Duration = 2; dt.Color = "ffffaa"; dt.Alpha = 75; dt.Size = 36; dt.X = 0; dt.Y = 65; dt.Width = 400; dt.Height = 240; dt.HAlign = TextHAlign.center; break; case "Alpha": dt.Y = 108; break; case "Beta": dt.Y = 123; break; case "Shipping date\nSep 1": dt.Y = 138; break; } return dt; } private int DateToPixels(string date) { DateTime dtdate = new DateTime(2008, Convert.ToInt32(date.Split('/')[0]), Convert.ToInt32(date.Split('/')[1])); double chartX = 100; double chartWidth = 275; double daysInYear = 366; double pixels = chartX + ((Convert.ToDouble(dtdate.DayOfYear) / daysInYear) * chartWidth); return Convert.ToInt32(pixels); } private DrawLine CreateDrawLine(string date) { DrawLine dl = new DrawLine(); dl.Transition = TransitionType.slide_right; dl.Delay = 0; dl.Duration = 0.5; dl.X1 = DateToPixels(date); dl.X2 = DateToPixels(date); dl.Y2 = 250; dl.LineColor = "ffff00"; dl.LineThickness = 1; dl.LineAlpha = 75; switch (date) { case "7/1": dl.Y1 = 115; break; case "8/1": dl.Y1 = 130; break; case "9/1": dl.Y1 = 145; break; } return dl; } private DrawCircle CreateDrawCircle(string date) { DrawCircle dc = new DrawCircle(); dc.Transition = TransitionType.slide_right; dc.Delay = 0; dc.Duration = 0.5; dc.X = DateToPixels(date); dc.Radius = 4; dc.FillColor = "ffff00"; dc.FillAlpha = 90; dc.LineThickness = 0; switch (date) { case "7/1": dc.Y = 115; break; case "8/1": dc.Y = 130; break; case "9/1": dc.Y = 145; break; } return dc; } private LegendRectangle SetLegendRectangle() { LegendRectangle lr = new LegendRectangle(); lr.X = -100; lr.Y = -100; lr.Width = 10; lr.Height = 10; return lr; } private SeriesGap SetSeriesGap() { SeriesGap sg = new SeriesGap(); sg.SetGap = 50; sg.BarGap = 0; return sg; } #endregion } }
/* * XmlDTDParserInput.cs - Implementation of the * "System.Xml.Private.XmlDTDParserInput" class. * * Copyright (C) 2004 Free Software Foundation, Inc. * * 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 */ namespace System.Xml.Private { using System; using System.IO; using System.Text; using System.Collections; internal class XmlDTDParserInput : XmlParserInputBase { // Internals. #if !ECMA_COMPAT private bool valid; private bool started; #endif private bool scanForPE; private int pePosition; private String peValue; private PEManager parameterEntities; private XmlParserInput input; // Constructor. public XmlDTDParserInput (XmlParserInput input, XmlNameTable nameTable) : base(nameTable, null, input.ErrorHandler) { this.input = input; this.peValue = null; this.pePosition = -1; this.scanForPE = true; this.parameterEntities = new PEManager (nameTable, input.ErrorHandler); #if !ECMA_COMPAT this.valid = true; this.started = false; #endif base.logger = null; } // Get the current line number. public override int LineNumber { get { return input.LineNumber; } } // Get the current line position. public override int LinePosition { get { return input.LinePosition; } } // Get the logger. public override LogManager Logger { get { return input.Logger; } } // Get or set the list of parameter entities. public PEManager ParameterEntities { get { return parameterEntities; } set { parameterEntities = value; } } // Turn on/off pe scanning. public bool ScanForPE { get { return scanForPE; } set { scanForPE = value; } } #if !ECMA_COMPAT // Valid DTDs require that all tags started in a pe, end in that pe. // Get the valid flag, which is set iff no invalid pe references were found. public bool Valid { get { return valid; } } // public void StartTag() { started = (peValue != null); } // public void EndTag() { if(peValue != null) { if(!started) { valid = false; } } else if(started) { valid = false; } started = false; } #endif // Move to the next character, returning false on EOF. public override bool NextChar() { bool retval; if(peValue == null) { retval = input.NextChar(); currChar = input.currChar; if(!scanForPE) { return retval; } if(currChar == '%') { if(input.PeekChar() && XmlCharInfo.IsNameInit(input.peekChar)) { String name = input.ReadName(); input.Expect(';'); peValue = parameterEntities[name]; pePosition = 0; currChar = ' '; } } } else { retval = true; if(pePosition == -1) { pePosition++; currChar = ' '; } else if(pePosition < peValue.Length) { currChar = peValue[pePosition++]; } else { pePosition = -1; peValue = null; currChar = ' '; } } return retval; } // Peek at the next character, returning false on EOF. public override bool PeekChar() { bool retval; if(peValue == null) { retval = input.PeekChar(); peekChar = input.peekChar; if(!scanForPE) { return retval; } if(peekChar == '%') { if(input.ExtraPeekChar() && XmlCharInfo.IsNameInit(input.extraPeekChar)) { input.NextChar(); String name = input.ReadName(); input.Expect(';'); peValue = parameterEntities[name]; pePosition = -1; peekChar = ' '; } } } else { retval = true; if(pePosition != -1 && pePosition < peValue.Length) { peekChar = peValue[pePosition]; } else { peekChar = ' '; } } return retval; } // Exit the current pe, if any. public void ResetPE() { pePosition = -1; peValue = null; } // this is just a temporary hack until we come up // with something better for entity handling public sealed class PEManager : XmlErrorProcessor { // Internal state. private Hashtable table; private XmlParserInput input; // Constructor. public PEManager(XmlNameTable nameTable, ErrorHandler error) : base(error) { table = new Hashtable(); input = new XmlParserInput(null, nameTable, error); } // Get or set the value for the given name. public String this[String name] { get { Object obj = table[name]; if(obj == null) { return null; } PEValue pe = (PEValue)obj; if(!pe.expanded) { pe.value = Expand(name, pe.value); pe.expanded = true; table[name] = pe; } return pe.value; } set { table[name] = new PEValue(Expand(name, value)); } } // Check if the given entity is contained in the table. public bool Contains(String name) { return table.Contains(name); } // Expand the pe reference. private String Expand(String rootName, String rawValue) { // set up our reader input.Reader = new StringReader(rawValue); // create our log and push it onto the logger's log stack StringBuilder log = new StringBuilder(); input.Logger.Push(log); // read until we consume the entire value while(input.PeekChar()) { if(input.peekChar == '&') { int position = log.Length; char c; // move to the '&' character input.NextChar(); // read the reference if(ReadCharacterReference(out c)) { log.Length = position; log.Append(c); } } else if(input.peekChar == '%') { // pop the log while reading the pe reference input.Logger.Pop(); // move to the '%' character input.NextChar(); // read the pe reference name String name = input.ReadName(); // give an error on recursion if(name == rootName) { Error(/* TODO */); } // the pe reference must end with ';' at this point input.Expect(';'); // get the value for the entity String value = this[name]; // check to make sure the entity has been defined if(value == null) { Error(/* TODO */); } // append the replacement text to the log log.Append(value); // push the log back onto the log stack input.Logger.Push(log); } else { input.NextChar(); } } // close the reader input.Close(); // pop the log from the log stack, and return the value return input.Logger.Pop().ToString(); } // Read a character reference, returning false for general entity references. // // Already read: '&' private bool ReadCharacterReference(out char value) { // check for an empty reference if(!input.PeekChar()) { Error(/* TODO */); } if(input.peekChar == ';') { Error(/* TODO */); } // set the defaults value = (char)0; // handle character or general references if(input.peekChar == '#') { input.NextChar(); // check for an empty character reference if(!input.PeekChar()) { Error(/* TODO */); } if(input.peekChar == ';') { Error(/* TODO */); } // handle a hex or decimal character reference if(input.peekChar == 'x') { input.NextChar(); // check for an empty hex character reference if(!input.PeekChar()) { Error(/* TODO */); } if(input.peekChar == ';') { Error(/* TODO */); } // read until we consume all the digits while(input.NextChar() && input.currChar != ';') { value *= (char)0x10; if(input.currChar >= '0' && input.currChar <= '9') { value += (char)(input.currChar - '0'); } else if(input.currChar >= 'A' && input.currChar <= 'F') { value += (char)((input.currChar - 'A') + 10); } else if(input.currChar >= 'a' && input.currChar <= 'f') { value += (char)((input.currChar - 'a') + 10); } else { Error(/* TODO */); } } } else { // read until we consume all the digits while(input.NextChar() && input.currChar != ';') { value *= (char)10; if(input.currChar >= '0' && input.currChar <= '9') { value += (char)(input.currChar - '0'); } else { Error(/* TODO */); } } } // we hit eof, otherwise we'd have ';', so give an error if(input.currChar != ';') { Error("Xml_UnexpectedEOF"); } // check the range of the character if(!XmlCharInfo.IsChar(value)) { Error(/* TODO */); } return true; } else { // read the reference name input.ReadName(); // the reference must end with ';' at this point input.Expect(';'); // signal that a general entity reference was encountered return false; } } private struct PEValue { // Internal state. public bool expanded; public String value; // Constructor. public PEValue(String value) { this.expanded = false; this.value = value; } }; // struct PEValue }; // class PEManager }; // class XmlDTDParserInput }; // namespace System.Xml.Private
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 ExcelImporter.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; } } }
// This file is part of the OWASP O2 Platform (http://www.owasp.org/index.php/OWASP_O2_Platform) and is released under the Apache 2.0 License (http://www.apache.org/licenses/LICENSE-2.0) using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Threading; namespace FluentSharp.CoreLib.API { public class Processes { private static int iMaxProcessExecutionTimeOut = 120000; public static void killO2s() { int iCurrentProcess = Process.GetCurrentProcess().Id; foreach (Process pProcess in Process.GetProcesses()) { Console.WriteLine(pProcess.ProcessName.Substring(0, 2)); if (pProcess.ProcessName.Substring(0, 2) == "O2" && pProcess.Id != iCurrentProcess) // find all O2s except the current instance { Console.WriteLine("Killing Process {0}", pProcess.ProcessName); pProcess.Kill(); } } Process.GetCurrentProcess().Kill(); // end current process } public static Process startProcess(String sProcessToStart) { return startProcess(sProcessToStart, ""); } public static Process startProcess(String sProcessToStart, String sArguments) { return startProcess(sProcessToStart, sArguments, false); } public static Process startProcess(String sProcessToStart, String sArguments, bool createNoWindow) { if (sProcessToStart.notValid()) return null; if (sArguments.isNull()) sArguments = ""; try { PublicDI.log.debug("Starting process {0} with arguments {1}", sProcessToStart, sArguments); var pProcess = new Process { StartInfo = new ProcessStartInfo { Arguments = sArguments, FileName = sProcessToStart, WorkingDirectory = sProcessToStart.directoryName() } }; if (createNoWindow) { pProcess.StartInfo.CreateNoWindow = true; pProcess.StartInfo.WindowStyle = ProcessWindowStyle.Minimized; } pProcess.Start(); return pProcess; } catch (Exception ex) { PublicDI.log.ex(ex, "in startProcess"); return null; } } public static String waitForProcessExitAndGetProcessExitCode(Process pProcess) { try { pProcess.WaitForExit(iMaxProcessExecutionTimeOut); return pProcess.ExitCode.str(); } catch { return null; } } public static void waitForProcessExitAndInvokeCallBankOncompletion(Process pProcess, Callbacks.dMethod_Object dProcessCompletionCallback, bool bNoExecutionTimeLimit) { ThreadStart tsThreadStart = () => waitForProcessExitAndInvokeCallBankOncompletion_Thread(pProcess, dProcessCompletionCallback, bNoExecutionTimeLimit); new Thread(tsThreadStart).Start(); } public static void waitForProcessExitAndInvokeCallBankOncompletion_Thread(Process pProcess, Callbacks.dMethod_Object dProcessCompletionCallback, bool bNoExecutionTimeLimit) { try { if (pProcess != null) { if (bNoExecutionTimeLimit) pProcess.WaitForExit(); else pProcess.WaitForExit(iMaxProcessExecutionTimeOut); } Callbacks.raiseRegistedCallbacks(dProcessCompletionCallback, new object[] {pProcess}); } catch (Exception ex) { PublicDI.log.ex(ex, "In waitForProcessExitAndInvokeCallBankOncompletion:", true); } } public static String startAsCmdExe(String processToStart, String arguments) { return startProcessAsConsoleApplicationAndReturnConsoleOutput(processToStart, arguments, Path.GetDirectoryName(processToStart), true); } public static String startAsCmdExe(String processToStart, String arguments, string workingDirectory) { return startProcessAsConsoleApplicationAndReturnConsoleOutput(processToStart, arguments, workingDirectory, true); } public static String startProcessAsConsoleApplicationAndReturnConsoleOutput(String processToStart, String arguments) { return startProcessAsConsoleApplicationAndReturnConsoleOutput(processToStart, arguments,Path.GetDirectoryName(processToStart), true); } public static String startProcessAsConsoleApplicationAndReturnConsoleOutput(String processToStart, String arguments, string workingDirectory) { return startProcessAsConsoleApplicationAndReturnConsoleOutput(processToStart, arguments, workingDirectory, true); } public static String startProcessAsConsoleApplicationAndReturnConsoleOutput(String processToStart, String arguments, string workingDirectory, bool showProcessDetails) { try { if (showProcessDetails) PublicDI.log.debug("Starting process {0} as a console Application with arguments {1}", processToStart, arguments); var pProcess = new Process(); pProcess.StartInfo = new ProcessStartInfo(); pProcess.StartInfo.Arguments = arguments; pProcess.StartInfo.FileName = processToStart; pProcess.StartInfo.UseShellExecute = false; pProcess.StartInfo.WorkingDirectory = workingDirectory; pProcess.StartInfo.RedirectStandardOutput = true; pProcess.StartInfo.RedirectStandardError = true; pProcess.StartInfo.CreateNoWindow = true; pProcess.Start(); // _note that the StandardOutput and StandardError might not show in the correct order in consoleData is just adding one the other othere var consoleData = pProcess.StandardOutput.ReadToEnd(); consoleData += pProcess.StandardError.ReadToEnd(); return consoleData; } catch(Exception ex) { PublicDI.log.error("in startProcessAsConsoleApplicationAndReturnConsoleOutput failed stating process {0} with parameters {1} . The error was: {1} ",processToStart, ex.Message); return ""; } } public static Process startProcessAsConsoleApplication(String processToStart, String arguments) { return startProcessAsConsoleApplication(processToStart, arguments, null, null); } public static Process startProcessAsConsoleApplication(String processToStart, String arguments, DataReceivedEventHandler callbackDataReceived) { return startProcessAsConsoleApplication(processToStart, arguments, callbackDataReceived, callbackDataReceived); } public static Process startProcessAsConsoleApplication(String sProcessToStart, String sArguments, DataReceivedEventHandler callbackOutputDataReceived, DataReceivedEventHandler callbackErrorDataReceived) { PublicDI.log.debug("Starting process {0} as a console Application with arguments {1}", sProcessToStart, sArguments); var pProcess = new Process(); pProcess.StartInfo = new ProcessStartInfo(); pProcess.StartInfo.Arguments = sArguments; pProcess.StartInfo.FileName = sProcessToStart; pProcess.StartInfo.UseShellExecute = false; pProcess.StartInfo.RedirectStandardOutput = true; pProcess.StartInfo.RedirectStandardError = true; pProcess.StartInfo.CreateNoWindow = true; if (callbackErrorDataReceived == null) pProcess.ErrorDataReceived += pProcess_ErrorDataReceived; else pProcess.ErrorDataReceived += callbackErrorDataReceived; if (callbackOutputDataReceived == null) pProcess.OutputDataReceived += pProcess_OutputDataReceived; else pProcess.OutputDataReceived += callbackOutputDataReceived; pProcess.Start(); pProcess.BeginErrorReadLine(); pProcess.BeginOutputReadLine(); return pProcess; } public static Process startProcessAndRedirectIO(string processToStart , Action<string> onDataReceived) { return startProcessAndRedirectIO(processToStart, "", onDataReceived); } public static Process startProcessAndRedirectIO(string processToStart, string arguments, Action<string> onDataReceived) { return startProcessAndRedirectIO(processToStart, arguments, processToStart.directoryName(), onDataReceived, onDataReceived); } public static Process startProcessAndRedirectIO(string processToStart, string arguments, string workingDirectory,Action<string> onDataReceived) { return startProcessAndRedirectIO(processToStart, arguments, workingDirectory, onDataReceived, onDataReceived); } public static Process startProcessAndRedirectIO(string processToStart, string arguments, string workingDirectory, Action<string> onOutputDataReceived, Action<string> onErrorDataReceived) { //var memoryStream = new MemoryStream(); //var stringWriter = new StringWriter(); var streamWriter = new StreamWriter(new MemoryStream()); return startProcessAndRedirectIO(processToStart, arguments, workingDirectory, ref streamWriter, (sender,e)=>{ if (e.Data != "") onOutputDataReceived(e.Data); }, (sender,e)=>{ if (e.Data != "") onOutputDataReceived(e.Data); }); } public static Process startProcessAndRedirectIO(string processToStart, string arguments, ref StreamWriter processStdInput, DataReceivedEventHandler callbackOutputDataReceived, DataReceivedEventHandler callbackErrorDataReceived) { return startProcessAndRedirectIO(processToStart, arguments, Path.GetDirectoryName(processToStart), ref processStdInput, callbackOutputDataReceived, callbackErrorDataReceived); } // ReSharper disable RedundantAssignment public static Process startProcessAndRedirectIO(string processToStart, string arguments,string workingDirectory, ref StreamWriter processStdInput, DataReceivedEventHandler callbackOutputDataReceived, DataReceivedEventHandler callbackErrorDataReceived) { PublicDI.log.debug("Starting process {0} as a console Application with IO redirected {1}", processToStart, arguments); var process = new Process { StartInfo = new ProcessStartInfo { Arguments = arguments ?? "", FileName = processToStart, WorkingDirectory = workingDirectory, UseShellExecute = false, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true } }; //process.StartInfo.EnvironmentVariables.Add("_NT_SYMBOL_PATH",@"srv*c:\symbols*http://msdl.microsoft.com/download/symbols"); if (callbackErrorDataReceived == null) process.ErrorDataReceived += pProcess_ErrorDataReceived; else process.ErrorDataReceived += callbackErrorDataReceived; if (callbackOutputDataReceived == null) process.OutputDataReceived += pProcess_OutputDataReceived; else process.OutputDataReceived += callbackOutputDataReceived; //process.StartInfo.EnvironmentVariables["Path"] += ";" + workingDirectory; process.Start(); process.BeginErrorReadLine(); process.BeginOutputReadLine(); processStdInput = process.StandardInput; return process; } // ReSharper restore RedundantAssignment public static void pProcess_OutputDataReceived(object sender, DataReceivedEventArgs e) { if (e.Data != "") PublicDI.log.info("\t:{0}:", e.Data); //throw new NotImplementedException(); } public static void pProcess_ErrorDataReceived(object sender, DataReceivedEventArgs e) { if (!string.IsNullOrEmpty(e.Data)) PublicDI.log.error("\t:{0}:", e.Data); //throw new NotImplementedException(); } public static void killProcess(String sProcessToKill) { killProcess(sProcessToKill, false); } public static void killProcess(String sProcessToKill, bool bVerbose) { // foreach (Process pProcess in Process.GetProcesses()) // PublicDI.log.debug("Process name :{0}", pProcess.ProcessName); Process[] pProcessesToKill = Process.GetProcessesByName(sProcessToKill); if (pProcessesToKill.Length == 0 && bVerbose) PublicDI.log.error("in killProcess, could not find any proccess with the name: {0}", sProcessToKill); foreach (Process pProcess in pProcessesToKill) { PublicDI.log.debug("Killing Process {0}", pProcess.ProcessName); try { pProcess.Kill(); } catch (Exception ex) { PublicDI.log.error("In killProcess: {0}", ex.Message); } } } public static void killProcess(Process processToKill) { if (processToKill.HasExited == false) processToKill.Kill(); } public static bool doesProcessExist(String sProcess) { return Process.GetProcessesByName(sProcess).Length > 0; } public static void resetIIS() { resetIIS(false); } public static void resetIIS(bool bWaitForCompletion) { PublicDI.log.debug("Reseting IIS"); Thread.Sleep(2000); // give the current request some time to complete var process = new Process(); process.StartInfo = new ProcessStartInfo(); process.StartInfo.Arguments = "/noforce /timeout:300 /restart"; process.StartInfo.FileName = "c:\\windows\\system32\\iisreset.exe"; process.StartInfo.UseShellExecute = true; process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; process.StartInfo.CreateNoWindow = true; process.Start(); if (bWaitForCompletion) { process.WaitForExit(); PublicDI.log.info("IIS service reset"); } } public static void startCurrentProcessInTempFolder() { String sTargetDirectory = PublicDI.config.TempFolderInTempDirectory + "_" + PublicDI.config.CurrentExecutableFileName; Directory.CreateDirectory(sTargetDirectory); foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) if (assembly.Location != "") Files.copy(assembly.Location, sTargetDirectory); //String sCurrentDirectory = AppDomain.CurrentDomain.BaseDirectory; //Files.copyFilesFromDirectoryToDirectory(sCurrentDirectory, sTargetDirectory); var sCommandLine = Environment.CommandLine.Replace("\"", "").Replace(".vshost", ""); var sExeName = sCommandLine.fileName(); var sExeInTempDirectory = sTargetDirectory.pathCombine(sExeName); //if there is a .config file, copy it to the temp directory var configFile = Path.Combine(PublicDI.config.CurrentExecutableDirectory, PublicDI.config.CurrentExecutableFileName + ".exe.config"); if (File.Exists(configFile)) Files.copy(configFile, sTargetDirectory); Process.Start(sExeInTempDirectory); Process.GetCurrentProcess().Kill(); } public static String getCurrentProcessName() { return Process.GetCurrentProcess().ProcessName; } public static int getCurrentProcessID() { return Process.GetCurrentProcess().Id; } public static Process getProcess(int processIdOfProcessToGet) { try { return Process.GetProcessById(processIdOfProcessToGet); } catch (Exception) { return null; } } public static List<Process> getProcesses() { return new List<Process>(Process.GetProcesses()); } // returns the first one that mathes the name public static Process getProcessCalled(string processName) { foreach (Process process in Process.GetProcessesByName(processName)) return process; return null; } public static List<Process> getProcessesCalled(string processName) { return new List<Process>(Process.GetProcessesByName(processName)); } public static string getProcessName(int processId) { try { return Process.GetProcessById(processId).ProcessName; } catch (Exception) { return null; } } /* public static void reLaunchCurrentProcess() { try { Application.Restart(); } catch (Exception ex) { PublicDI.log.ex(ex); throw; } }*/ public static void Sleep(int miliSecondsToSleep) { Sleep(miliSecondsToSleep,true); } public static void Sleep(int miliSecondsToSleep, bool verbose) { if (miliSecondsToSleep > 0) { if (verbose) PublicDI.log.info("Sleeping for: {0} mili-seconds", miliSecondsToSleep); Thread.Sleep(miliSecondsToSleep); } } public static Process getCurrentProcess() { return Process.GetCurrentProcess(); } public static List<ProcessThread> getCurrentProcessThreads() { return getProcessThreads(Process.GetCurrentProcess()); } public static List<ProcessThread> getProcessThreads(Process process) { var processThreads = new List<ProcessThread>(); foreach (ProcessThread processThread in process.Threads) processThreads.Add(processThread); return processThreads; } } }
// TexturePainter.cs // Copyright (c) 2015 jeffrey.io using System; using System.IO; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.ES11; using OpenTK.Platform; using OpenTK.Platform.Android; using Android.Views; using Android.Content; using Android.Util; using Android.Graphics; using io.jeffrey.pixel; namespace io.jeffrey.gl { public class GLTexturePainterFactory : PixelSurfaceFactory { private readonly GLTexturePainter[] _Init; public readonly int _Width; public readonly int _Height; public readonly GLTimeline Timeline; public GLTexturePainterFactory(String filename, GLTimeline timeline) { GLTexturePainter init = new GLTexturePainter(filename, timeline, PixelSurfaceType.Layer); this._Width = init.Width; this._Height = init.Height; this.Timeline = timeline; this._Init = new GLTexturePainter[] { init }; } public GLTexturePainterFactory(int w, int h, GLTimeline timeline) { this._Width = w; this._Height = h; this.Timeline = timeline; this._Init = new GLTexturePainter[] { _CreateSurface(PixelSurfaceType.Layer, ColorMath.Encode(255, 255, 255, 255)) }; } public PixelSurface[] Init() { return _Init; } private GLTexturePainter _CreateSurface(PixelSurfaceType type, int initialColor) { GLTexturePainter Tex = new GLTexturePainter(_Width, _Height, Timeline, type); Tex.Clear(new Android.Graphics.Color(initialColor)); return Tex; } public PixelSurface CreateSurface(PixelSurfaceType type, int initialColor) { return _CreateSurface(type, initialColor); } public int Width { get { return _Width; } } public int Height { get { return _Height; } } } public class GLTimeline { private long _resetAt; public long LastReset { get { return _resetAt; } } public GLTimeline() { Reset(); } public void Reset() { _resetAt = DateTime.Now.Ticks; } } public class GLTexturePainter : PixelSurface { private Bitmap TextureData; private long lastChange; private readonly int TextureDataWidth; private readonly int TextureDataHeight; private long RegisteredTime; private uint textureId; public readonly int _Width; public readonly int _Height; private readonly float[] TextureCoordinates; private bool Dirty; private GLTimeline Timeline; private int TranslateX; private int TranslateY; private bool hasTextureId; private PixelSurfaceType _Type; /** return the smallest integer of the form 2^j such that k <= 2^j */ private static int GetClosestPowerOfTwo(int k) { int p = 2; while (p < k) { p *= 2; } return p; } public int Width { get { return _Width; } } public int Height { get { return _Height; } } public PixelSurfaceType Type { get { return _Type; } } public int TranslationX { get { return TranslateX; } set { TranslateX = value; } } public int TranslationY { get { return TranslateY; } set { TranslateY = value; } } public GLTexturePainter(String filename, GLTimeline timeline, PixelSurfaceType type) { this._Type = type; Bitmap readOne = BitmapFactory.DecodeFile(filename); try { this.TextureDataWidth = GetClosestPowerOfTwo(readOne.Width); this.TextureDataHeight = GetClosestPowerOfTwo(readOne.Height); this._Width = readOne.Width; this._Height = readOne.Height; this.TextureData = Bitmap.CreateBitmap((int)TextureDataWidth, (int)TextureDataHeight, Bitmap.Config.Argb8888); for (int y = 0; y < _Height; y++) { for (int x = 0; x < _Width; x++) { TextureData.SetPixel(x, y, new Color(readOne.GetPixel(x, y))); } } this.RegisteredTime = 0; this.textureId = 0; float texMaxX = _Width / (float)TextureDataWidth; float texMaxY = _Height / (float)TextureDataHeight; this.TextureCoordinates = new float[] { 0, texMaxY, texMaxX, texMaxY, 0, 0, texMaxX, 0 }; this.Dirty = true; this.Timeline = timeline; this.hasTextureId = false; this.lastChange = DateTime.Now.Ticks; } finally { readOne.Recycle(); } } public GLTexturePainter(int w, int h, GLTimeline timeline, PixelSurfaceType type) { this._Type = type; this.TextureDataWidth = GetClosestPowerOfTwo(w); this.TextureDataHeight = GetClosestPowerOfTwo(h); this._Width = (int)w; this._Height = (int)h; this.TextureData = Bitmap.CreateBitmap((int)TextureDataWidth, (int)TextureDataHeight, Bitmap.Config.Argb8888); this.RegisteredTime = 0; this.textureId = 0; float texMaxX = w / (float)TextureDataWidth; float texMaxY = h / (float)TextureDataHeight; this.TextureCoordinates = new float[] { 0, texMaxY, texMaxX, texMaxY, 0, 0, texMaxX, 0 }; this.Dirty = true; this.Timeline = timeline; this.hasTextureId = false; this.lastChange = DateTime.Now.Ticks; } public long LastChange { get { return lastChange; } } public PixelSurface Put(int x, int y, SurfacePoint point) { if (!point.Valid) return this; return Put(x, y, point.Color); } public PixelSurface Put(int x, int y, int color) { int nx = x - TranslateX; int ny = y + TranslateY; if (nx < 0 || nx >= Width) return this; if (ny < 0 || ny >= Height) return this; TextureData.SetPixel(nx, ny, new Color(color)); this.lastChange = DateTime.Now.Ticks; this.Dirty = true; return this; } public SurfacePoint Get(int x, int y) { int nx = x - TranslateX; int ny = y + TranslateY; if (nx < 0 || nx >= Width) return new SurfacePoint(0, false); if (ny < 0 || ny >= Height) return new SurfacePoint(0, false); return new SurfacePoint(new Color(TextureData.GetPixel(nx, ny)).ToArgb(), true); } public GLTexturePainter Clear(Color color) { for (int y = 0; y < TextureDataHeight; y++) { for (int x = 0; x < TextureDataWidth; x++) { Put(x, y, color); } } this.lastChange = DateTime.Now.Ticks; return this; } private uint GetTextureId() { long resetAt = Timeline.LastReset; if (Timeline.LastReset < RegisteredTime) { return textureId; } if (hasTextureId) { // reclaim the old texture id ReleaseGL(); } uint[] texIdBuf = new uint[1]; GL.GenTextures(1, texIdBuf); textureId = texIdBuf[0]; RegisteredTime = resetAt; this.hasTextureId = true; return textureId; } private void Bind() { uint texId = GetTextureId(); GL.Enable(All.Texture2D); GL.BindTexture(All.Texture2D, texId); if (this.Dirty) { GL.TexParameter(All.Texture2D, All.TextureMagFilter, (int)All.Nearest); GL.TexParameter(All.Texture2D, All.TextureMinFilter, (int)All.Nearest); GL.TexParameter(All.Texture2D, All.TextureWrapS, (int)All.ClampToEdge); GL.TexParameter(All.Texture2D, All.TextureWrapT, (int)All.ClampToEdge); Android.Opengl.GLUtils.TexImage2D((int)All.Texture2D, 0, TextureData, 0); } GL.Enable(All.Blend); GL.BlendFunc(All.SrcAlpha, All.OneMinusSrcAlpha); } private void DrawTexture() { Bind(); GL.EnableClientState(All.VertexArray); GL.EnableClientState(All.TextureCoordArray); GL.DisableClientState(All.ColorArray); GL.VertexPointer(2, All.Float, 0, BasicSquareVertices); GL.TexCoordPointer(2, All.Float, 0, TextureCoordinates); GL.DrawArrays(All.TriangleStrip, 0, 4); } public void Draw() { GL.Enable(All.ClipPlane0); GL.Enable(All.ClipPlane1); GL.Enable(All.ClipPlane2); GL.Enable(All.ClipPlane3); GL.ClipPlane(All.ClipPlane0, new float[] { 1.0f, 0.0f, 0.0f, 0.0f }); GL.ClipPlane(All.ClipPlane1, new float[] { -1.0f, 0.0f, 0.0f, 1.0f }); GL.ClipPlane(All.ClipPlane2, new float[] { 0.0f, 1.0f, 0.0f, 0.0f }); GL.ClipPlane(All.ClipPlane3, new float[] { 0.0f, -1.0f, 0.0f, 1.0f }); float tx = TranslateX; tx /= Width; float ty = TranslateY; ty /= Height; GL.PushMatrix(); GL.Translate(tx, ty, 0.0f); DrawTexture(); GL.PopMatrix(); GL.Disable(All.ClipPlane0); GL.Disable(All.ClipPlane1); GL.Disable(All.ClipPlane2); GL.Disable(All.ClipPlane3); } public void Draw(float x, float y, float width, float height) { Bind(); GL.PushMatrix(); GL.Translate(x, y - height, 0.0f); GL.Scale(width, height, 1.0f); GL.EnableClientState(All.VertexArray); GL.EnableClientState(All.TextureCoordArray); GL.DisableClientState(All.ColorArray); GL.VertexPointer(2, All.Float, 0, BasicSquareVertices); GL.TexCoordPointer(2, All.Float, 0, TextureCoordinates); GL.DrawArrays(All.TriangleStrip, 0, 4); GL.PopMatrix(); } public PixelSurface Kinkolate(Func<int, int, KinkolateAction> operation, Action<int, int, int, int> delta) { GLTexturePainter clone = new GLTexturePainter(_Width, _Height, Timeline, PixelSurfaceType.Ephemeral); clone.Clear(new Android.Graphics.Color(ColorMath.CLEAR)); for (int y = 0; y < _Height; y++) { for (int x = 0; x < _Width; x++) { KinkolateAction op = operation(x, y); if (op == KinkolateAction.Keep) continue; if (op == KinkolateAction.Copy || op == KinkolateAction.Cut) { clone.Put(x, y, Get(x, y)); } if (op == KinkolateAction.Delete || op == KinkolateAction.Cut) { SurfacePoint before = Get(x, y); if (before.Valid) { if (delta != null) { delta(x, y, before.Color, ColorMath.CLEAR); } Put(x, y, ColorMath.CLEAR); } } } } this.lastChange = DateTime.Now.Ticks; return clone; } public void ReleaseGL() { GL.DeleteTextures(1, new uint[] { textureId }); textureId = 0; RegisteredTime = 0; hasTextureId = false; } public void Release() { ReleaseGL(); TextureData.Recycle(); } public void Save(String filename, Context context) { System.IO.Stream output = new FileStream(filename, FileMode.Create); TextureData.Compress(Bitmap.CompressFormat.Png, 1, output); output.Flush(); output.Close(); } readonly float[] BasicSquareVertices = { 0, 0, 1, 0, 0, 1, 1, 1 }; } }
// SPDX-License-Identifier: MIT // Copyright [email protected] // Copyright iced contributors #if MASM using System; using System.Diagnostics; using System.Runtime.CompilerServices; using Iced.Intel.FormatterInternal; using Iced.Intel.MasmFormatterInternal; namespace Iced.Intel { /// <summary> /// Masm formatter /// </summary> public sealed class MasmFormatter : Formatter { /// <summary> /// Gets the formatter options /// </summary> public override FormatterOptions Options => options; /// <summary> /// Gets the masm formatter options /// </summary> [System.Obsolete("Use " + nameof(Options) + " instead of this property", true)] [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public FormatterOptions MasmOptions => options; readonly FormatterOptions options; readonly ISymbolResolver? symbolResolver; readonly IFormatterOptionsProvider? optionsProvider; readonly FormatterString[] allRegisters; readonly InstrInfo[] instrInfos; readonly MemorySizes.Info[] allMemorySizes; readonly NumberFormatter numberFormatter; readonly FormatterString[] rcStrings; readonly string[] scaleNumbers; /// <summary> /// Constructor /// </summary> public MasmFormatter() : this(null, null, null) { } /// <summary> /// Constructor /// </summary> /// <param name="symbolResolver">Symbol resolver or null</param> /// <param name="optionsProvider">Operand options provider or null</param> public MasmFormatter(ISymbolResolver? symbolResolver, IFormatterOptionsProvider? optionsProvider = null) : this(null, symbolResolver, optionsProvider) { } /// <summary> /// Constructor /// </summary> /// <param name="options">Formatter options or null</param> /// <param name="symbolResolver">Symbol resolver or null</param> /// <param name="optionsProvider">Operand options provider or null</param> public MasmFormatter(FormatterOptions? options, ISymbolResolver? symbolResolver = null, IFormatterOptionsProvider? optionsProvider = null) { this.options = options ?? FormatterOptions.CreateMasm(); this.symbolResolver = symbolResolver; this.optionsProvider = optionsProvider; allRegisters = Registers.AllRegisters; instrInfos = InstrInfos.AllInfos; allMemorySizes = MemorySizes.AllMemorySizes; numberFormatter = new NumberFormatter(true); rcStrings = s_rcStrings; scaleNumbers = s_scaleNumbers; } static readonly FormatterString str_bnd = new FormatterString("bnd"); static readonly FormatterString str_far = new FormatterString("far"); static readonly FormatterString str_hnt = new FormatterString("hnt"); static readonly FormatterString str_ht = new FormatterString("ht"); static readonly FormatterString str_lock = new FormatterString("lock"); static readonly FormatterString str_near = new FormatterString("near"); static readonly FormatterString str_notrack = new FormatterString("notrack"); static readonly FormatterString str_offset = new FormatterString("offset"); static readonly FormatterString str_ptr = new FormatterString("ptr"); static readonly FormatterString str_rep = new FormatterString("rep"); static readonly FormatterString[] str_repe = new FormatterString[2] { new FormatterString("repe"), new FormatterString("repz"), }; static readonly FormatterString[] str_repne = new FormatterString[2] { new FormatterString("repne"), new FormatterString("repnz"), }; static readonly FormatterString str_sae = new FormatterString("sae"); static readonly FormatterString str_short = new FormatterString("short"); static readonly FormatterString str_xacquire = new FormatterString("xacquire"); static readonly FormatterString str_xrelease = new FormatterString("xrelease"); static readonly FormatterString str_z = new FormatterString("z"); static readonly FormatterString[] s_rcStrings = new FormatterString[] { new FormatterString("rn-sae"), new FormatterString("rd-sae"), new FormatterString("ru-sae"), new FormatterString("rz-sae"), }; static readonly string[] s_scaleNumbers = new string[4] { "1", "2", "4", "8", }; /// <summary> /// Formats the mnemonic and any prefixes /// </summary> /// <param name="instruction">Instruction</param> /// <param name="output">Output</param> /// <param name="options">Options</param> public override void FormatMnemonic(in Instruction instruction, FormatterOutput output, FormatMnemonicOptions options) { Debug.Assert((uint)instruction.Code < (uint)instrInfos.Length); var instrInfo = instrInfos[(int)instruction.Code]; instrInfo.GetOpInfo(this.options, instruction, out var opInfo); int column = 0; FormatMnemonic(instruction, output, opInfo, ref column, options); } /// <summary> /// Gets the number of operands that will be formatted. A formatter can add and remove operands /// </summary> /// <param name="instruction">Instruction</param> /// <returns></returns> public override int GetOperandCount(in Instruction instruction) { Debug.Assert((uint)instruction.Code < (uint)instrInfos.Length); var instrInfo = instrInfos[(int)instruction.Code]; instrInfo.GetOpInfo(options, instruction, out var opInfo); return opInfo.OpCount; } #if INSTR_INFO /// <summary> /// Returns the operand access but only if it's an operand added by the formatter. If it's an /// operand that is part of <see cref="Instruction"/>, you should call eg. <see cref="InstructionInfoFactory.GetInfo(in Instruction)"/>. /// </summary> /// <param name="instruction">Instruction</param> /// <param name="operand">Operand number, 0-based. This is a formatter operand and isn't necessarily the same as an instruction operand. /// See <see cref="GetOperandCount(in Instruction)"/></param> /// <param name="access">Updated with operand access if successful</param> /// <returns></returns> public override bool TryGetOpAccess(in Instruction instruction, int operand, out OpAccess access) { Debug.Assert((uint)instruction.Code < (uint)instrInfos.Length); var instrInfo = instrInfos[(int)instruction.Code]; instrInfo.GetOpInfo(options, instruction, out var opInfo); // Although it's a TryXXX() method, it should only accept valid instruction operand indexes if ((uint)operand >= (uint)opInfo.OpCount) ThrowHelper.ThrowArgumentOutOfRangeException_operand(); return opInfo.TryGetOpAccess(operand, out access); } #endif /// <summary> /// Converts a formatter operand index to an instruction operand index. Returns -1 if it's an operand added by the formatter /// </summary> /// <param name="instruction">Instruction</param> /// <param name="operand">Operand number, 0-based. This is a formatter operand and isn't necessarily the same as an instruction operand. /// See <see cref="GetOperandCount(in Instruction)"/></param> /// <returns></returns> public override int GetInstructionOperand(in Instruction instruction, int operand) { Debug.Assert((uint)instruction.Code < (uint)instrInfos.Length); var instrInfo = instrInfos[(int)instruction.Code]; instrInfo.GetOpInfo(options, instruction, out var opInfo); if ((uint)operand >= (uint)opInfo.OpCount) ThrowHelper.ThrowArgumentOutOfRangeException_operand(); return opInfo.GetInstructionIndex(operand); } /// <summary> /// Converts an instruction operand index to a formatter operand index. Returns -1 if the instruction operand isn't used by the formatter /// </summary> /// <param name="instruction">Instruction</param> /// <param name="instructionOperand">Instruction operand</param> /// <returns></returns> public override int GetFormatterOperand(in Instruction instruction, int instructionOperand) { Debug.Assert((uint)instruction.Code < (uint)instrInfos.Length); var instrInfo = instrInfos[(int)instruction.Code]; instrInfo.GetOpInfo(options, instruction, out var opInfo); if ((uint)instructionOperand >= (uint)instruction.OpCount) ThrowHelper.ThrowArgumentOutOfRangeException_instructionOperand(); return opInfo.GetOperandIndex(instructionOperand); } /// <summary> /// Formats an operand. This is a formatter operand and not necessarily a real instruction operand. /// A formatter can add and remove operands. /// </summary> /// <param name="instruction">Instruction</param> /// <param name="output">Output</param> /// <param name="operand">Operand number, 0-based. This is a formatter operand and isn't necessarily the same as an instruction operand. /// See <see cref="GetOperandCount(in Instruction)"/></param> public override void FormatOperand(in Instruction instruction, FormatterOutput output, int operand) { Debug.Assert((uint)instruction.Code < (uint)instrInfos.Length); var instrInfo = instrInfos[(int)instruction.Code]; instrInfo.GetOpInfo(options, instruction, out var opInfo); if ((uint)operand >= (uint)opInfo.OpCount) ThrowHelper.ThrowArgumentOutOfRangeException_operand(); FormatOperand(instruction, output, opInfo, operand); } /// <summary> /// Formats an operand separator /// </summary> /// <param name="instruction">Instruction</param> /// <param name="output">Output</param> public override void FormatOperandSeparator(in Instruction instruction, FormatterOutput output) { if (output is null) ThrowHelper.ThrowArgumentNullException_output(); output.Write(",", FormatterTextKind.Punctuation); if (options.SpaceAfterOperandSeparator) output.Write(" ", FormatterTextKind.Text); } /// <summary> /// Formats all operands /// </summary> /// <param name="instruction">Instruction</param> /// <param name="output">Output</param> public override void FormatAllOperands(in Instruction instruction, FormatterOutput output) { Debug.Assert((uint)instruction.Code < (uint)instrInfos.Length); var instrInfo = instrInfos[(int)instruction.Code]; instrInfo.GetOpInfo(options, instruction, out var opInfo); FormatOperands(instruction, output, opInfo); } /// <summary> /// Formats the whole instruction: prefixes, mnemonic, operands /// </summary> /// <param name="instruction">Instruction</param> /// <param name="output">Output</param> public override void Format(in Instruction instruction, FormatterOutput output) { Debug.Assert((uint)instruction.Code < (uint)instrInfos.Length); var instrInfo = instrInfos[(int)instruction.Code]; instrInfo.GetOpInfo(options, instruction, out var opInfo); int column = 0; FormatMnemonic(instruction, output, opInfo, ref column, FormatMnemonicOptions.None); if (opInfo.OpCount != 0) { FormatterUtils.AddTabs(output, column, options.FirstOperandCharIndex, options.TabSize); FormatOperands(instruction, output, opInfo); } } void FormatMnemonic(in Instruction instruction, FormatterOutput output, in InstrOpInfo opInfo, ref int column, FormatMnemonicOptions mnemonicOptions) { if (output is null) ThrowHelper.ThrowArgumentNullException_output(); bool needSpace = false; if ((mnemonicOptions & FormatMnemonicOptions.NoPrefixes) == 0 && (opInfo.Flags & InstrOpInfoFlags.MnemonicIsDirective) == 0) { var prefixSeg = instruction.SegmentPrefix; if (((uint)prefixSeg | instruction.HasAnyOf_Xacquire_Xrelease_Lock_Rep_Repne_Prefix | (uint)(opInfo.Flags & (InstrOpInfoFlags.JccNotTaken | InstrOpInfoFlags.JccTaken | InstrOpInfoFlags.BndPrefix))) != 0) { bool hasNoTrackPrefix = prefixSeg == Register.DS && FormatterUtils.IsNotrackPrefixBranch(instruction.Code); if (!hasNoTrackPrefix && prefixSeg != Register.None && ShowSegmentPrefix(instruction, opInfo)) FormatPrefix(output, instruction, ref column, allRegisters[(int)prefixSeg], FormatterUtils.GetSegmentRegisterPrefixKind(prefixSeg), ref needSpace); if (instruction.HasXacquirePrefix) FormatPrefix(output, instruction, ref column, str_xacquire, PrefixKind.Xacquire, ref needSpace); if (instruction.HasXreleasePrefix) FormatPrefix(output, instruction, ref column, str_xrelease, PrefixKind.Xrelease, ref needSpace); if (instruction.HasLockPrefix) FormatPrefix(output, instruction, ref column, str_lock, PrefixKind.Lock, ref needSpace); if ((opInfo.Flags & InstrOpInfoFlags.JccNotTaken) != 0) FormatPrefix(output, instruction, ref column, str_hnt, PrefixKind.HintNotTaken, ref needSpace); else if ((opInfo.Flags & InstrOpInfoFlags.JccTaken) != 0) FormatPrefix(output, instruction, ref column, str_ht, PrefixKind.HintTaken, ref needSpace); if (hasNoTrackPrefix) FormatPrefix(output, instruction, ref column, str_notrack, PrefixKind.Notrack, ref needSpace); bool hasBnd = (opInfo.Flags & InstrOpInfoFlags.BndPrefix) != 0; if (hasBnd) FormatPrefix(output, instruction, ref column, str_bnd, PrefixKind.Bnd, ref needSpace); if (instruction.HasRepePrefix && FormatterUtils.ShowRepOrRepePrefix(instruction.Code, options)) { if (FormatterUtils.IsRepeOrRepneInstruction(instruction.Code)) FormatPrefix(output, instruction, ref column, MnemonicCC.GetMnemonicCC(options, 4, str_repe), PrefixKind.Repe, ref needSpace); else FormatPrefix(output, instruction, ref column, str_rep, PrefixKind.Rep, ref needSpace); } if (instruction.HasRepnePrefix && !hasBnd && FormatterUtils.ShowRepnePrefix(instruction.Code, options)) FormatPrefix(output, instruction, ref column, MnemonicCC.GetMnemonicCC(options, 5, str_repne), PrefixKind.Repne, ref needSpace); } } if ((mnemonicOptions & FormatMnemonicOptions.NoMnemonic) == 0) { if (needSpace) { output.Write(" ", FormatterTextKind.Text); column++; } var mnemonic = opInfo.Mnemonic; if ((opInfo.Flags & InstrOpInfoFlags.MnemonicIsDirective) != 0) { output.Write(mnemonic.Get(options.UppercaseKeywords || options.UppercaseAll), FormatterTextKind.Directive); } else { output.WriteMnemonic(instruction, mnemonic.Get(options.UppercaseMnemonics || options.UppercaseAll)); } column += mnemonic.Length; } } bool ShowSegmentPrefix(in Instruction instruction, in InstrOpInfo opInfo) { if ((opInfo.Flags & (InstrOpInfoFlags.JccNotTaken | InstrOpInfoFlags.JccTaken)) != 0) return false; switch (instruction.Code) { case Code.Monitorw: case Code.Monitord: case Code.Monitorq: case Code.Monitorxw: case Code.Monitorxd: case Code.Monitorxq: case Code.Clzerow: case Code.Clzerod: case Code.Clzeroq: case Code.Umonitor_r16: case Code.Umonitor_r32: case Code.Umonitor_r64: return FormatterUtils.ShowSegmentPrefix(Register.DS, instruction, options); default: break; } for (int i = 0; i < opInfo.OpCount; i++) { switch (opInfo.GetOpKind(i)) { case InstrOpKind.Register: case InstrOpKind.NearBranch16: case InstrOpKind.NearBranch32: case InstrOpKind.NearBranch64: case InstrOpKind.FarBranch16: case InstrOpKind.FarBranch32: case InstrOpKind.ExtraImmediate8_Value3: case InstrOpKind.Immediate8: case InstrOpKind.Immediate8_2nd: case InstrOpKind.Immediate16: case InstrOpKind.Immediate32: case InstrOpKind.Immediate64: case InstrOpKind.Immediate8to16: case InstrOpKind.Immediate8to32: case InstrOpKind.Immediate8to64: case InstrOpKind.Immediate32to64: case InstrOpKind.MemoryESDI: case InstrOpKind.MemoryESEDI: case InstrOpKind.MemoryESRDI: case InstrOpKind.DeclareByte: case InstrOpKind.DeclareWord: case InstrOpKind.DeclareDword: case InstrOpKind.DeclareQword: break; case InstrOpKind.MemorySegSI: case InstrOpKind.MemorySegESI: case InstrOpKind.MemorySegRSI: case InstrOpKind.MemorySegDI: case InstrOpKind.MemorySegEDI: case InstrOpKind.MemorySegRDI: case InstrOpKind.Memory64: case InstrOpKind.Memory: return false; default: throw new InvalidOperationException(); } } return options.ShowUselessPrefixes; } void FormatPrefix(FormatterOutput output, in Instruction instruction, ref int column, FormatterString prefix, PrefixKind prefixKind, ref bool needSpace) { if (needSpace) { column++; output.Write(" ", FormatterTextKind.Text); } output.WritePrefix(instruction, prefix.Get(options.UppercasePrefixes || options.UppercaseAll), prefixKind); column += prefix.Length; needSpace = true; } void FormatOperands(in Instruction instruction, FormatterOutput output, in InstrOpInfo opInfo) { if (output is null) ThrowHelper.ThrowArgumentNullException_output(); for (int i = 0; i < opInfo.OpCount; i++) { if (i > 0) { output.Write(",", FormatterTextKind.Punctuation); if (options.SpaceAfterOperandSeparator) output.Write(" ", FormatterTextKind.Text); } FormatOperand(instruction, output, opInfo, i); } } void FormatOperand(in Instruction instruction, FormatterOutput output, in InstrOpInfo opInfo, int operand) { Debug.Assert((uint)operand < (uint)opInfo.OpCount); if (output is null) ThrowHelper.ThrowArgumentNullException_output(); int instructionOperand = opInfo.GetInstructionIndex(operand); string s; FormatterFlowControl flowControl; byte imm8; ushort imm16; uint imm32; ulong imm64, value64; int immSize; NumberFormattingOptions numberOptions; SymbolResult symbol; ISymbolResolver? symbolResolver; FormatterOperandOptions operandOptions; NumberKind numberKind; var opKind = opInfo.GetOpKind(operand); switch (opKind) { case InstrOpKind.Register: FormatRegister(output, instruction, operand, instructionOperand, opInfo.GetOpRegister(operand)); break; case InstrOpKind.NearBranch16: case InstrOpKind.NearBranch32: case InstrOpKind.NearBranch64: if (opKind == InstrOpKind.NearBranch64) { immSize = 8; imm64 = instruction.NearBranch64; numberKind = NumberKind.UInt64; } else if (opKind == InstrOpKind.NearBranch32) { immSize = 4; imm64 = instruction.NearBranch32; numberKind = NumberKind.UInt32; } else { immSize = 2; imm64 = instruction.NearBranch16; numberKind = NumberKind.UInt16; } numberOptions = NumberFormattingOptions.CreateBranchInternal(options); operandOptions = new FormatterOperandOptions(options.ShowBranchSize ? FormatterOperandOptions.Flags.None : FormatterOperandOptions.Flags.NoBranchSize); optionsProvider?.GetOperandOptions(instruction, operand, instructionOperand, ref operandOptions, ref numberOptions); if ((symbolResolver = this.symbolResolver) is not null && symbolResolver.TryGetSymbol(instruction, operand, instructionOperand, imm64, immSize, out symbol)) { FormatFlowControl(output, FormatterUtils.GetFlowControl(instruction), operandOptions); output.Write(instruction, operand, instructionOperand, options, numberFormatter, numberOptions, imm64, symbol, options.ShowSymbolAddress); } else { flowControl = FormatterUtils.GetFlowControl(instruction); FormatFlowControl(output, flowControl, operandOptions); if (opKind == InstrOpKind.NearBranch32) s = numberFormatter.FormatUInt32(options, numberOptions, instruction.NearBranch32, numberOptions.LeadingZeroes); else if (opKind == InstrOpKind.NearBranch64) s = numberFormatter.FormatUInt64(options, numberOptions, instruction.NearBranch64, numberOptions.LeadingZeroes); else s = numberFormatter.FormatUInt16(options, numberOptions, instruction.NearBranch16, numberOptions.LeadingZeroes); output.WriteNumber(instruction, operand, instructionOperand, s, imm64, numberKind, FormatterUtils.IsCall(flowControl) ? FormatterTextKind.FunctionAddress : FormatterTextKind.LabelAddress); } break; case InstrOpKind.FarBranch16: case InstrOpKind.FarBranch32: if (opKind == InstrOpKind.FarBranch32) { immSize = 4; imm64 = instruction.FarBranch32; numberKind = NumberKind.UInt32; } else { immSize = 2; imm64 = instruction.FarBranch16; numberKind = NumberKind.UInt16; } numberOptions = NumberFormattingOptions.CreateBranchInternal(options); operandOptions = new FormatterOperandOptions(options.ShowBranchSize ? FormatterOperandOptions.Flags.None : FormatterOperandOptions.Flags.NoBranchSize); optionsProvider?.GetOperandOptions(instruction, operand, instructionOperand, ref operandOptions, ref numberOptions); if ((symbolResolver = this.symbolResolver) is not null && symbolResolver.TryGetSymbol(instruction, operand, instructionOperand, (uint)imm64, immSize, out symbol)) { FormatFlowControl(output, FormatterUtils.GetFlowControl(instruction), operandOptions); Debug.Assert(operand + 1 == 1); if (!symbolResolver.TryGetSymbol(instruction, operand + 1, instructionOperand, instruction.FarBranchSelector, 2, out var selectorSymbol)) { s = numberFormatter.FormatUInt16(options, numberOptions, instruction.FarBranchSelector, numberOptions.LeadingZeroes); output.WriteNumber(instruction, operand, instructionOperand, s, instruction.FarBranchSelector, NumberKind.UInt16, FormatterTextKind.SelectorValue); } else output.Write(instruction, operand, instructionOperand, options, numberFormatter, numberOptions, instruction.FarBranchSelector, selectorSymbol, options.ShowSymbolAddress); output.Write(":", FormatterTextKind.Punctuation); output.Write(instruction, operand, instructionOperand, options, numberFormatter, numberOptions, imm64, symbol, options.ShowSymbolAddress); } else { flowControl = FormatterUtils.GetFlowControl(instruction); FormatFlowControl(output, flowControl, operandOptions); s = numberFormatter.FormatUInt16(options, numberOptions, instruction.FarBranchSelector, numberOptions.LeadingZeroes); output.WriteNumber(instruction, operand, instructionOperand, s, instruction.FarBranchSelector, NumberKind.UInt16, FormatterTextKind.SelectorValue); output.Write(":", FormatterTextKind.Punctuation); if (opKind == InstrOpKind.FarBranch32) s = numberFormatter.FormatUInt32(options, numberOptions, instruction.FarBranch32, numberOptions.LeadingZeroes); else s = numberFormatter.FormatUInt16(options, numberOptions, instruction.FarBranch16, numberOptions.LeadingZeroes); output.WriteNumber(instruction, operand, instructionOperand, s, imm64, numberKind, FormatterUtils.IsCall(flowControl) ? FormatterTextKind.FunctionAddress : FormatterTextKind.LabelAddress); } break; case InstrOpKind.Immediate8: case InstrOpKind.Immediate8_2nd: case InstrOpKind.ExtraImmediate8_Value3: case InstrOpKind.DeclareByte: if (opKind == InstrOpKind.Immediate8) imm8 = instruction.Immediate8; else if (opKind == InstrOpKind.ExtraImmediate8_Value3) imm8 = 3; else if (opKind == InstrOpKind.Immediate8_2nd) imm8 = instruction.Immediate8_2nd; else imm8 = instruction.GetDeclareByteValue(operand); numberOptions = NumberFormattingOptions.CreateImmediateInternal(options); operandOptions = default; optionsProvider?.GetOperandOptions(instruction, operand, instructionOperand, ref operandOptions, ref numberOptions); if ((symbolResolver = this.symbolResolver) is not null && symbolResolver.TryGetSymbol(instruction, operand, instructionOperand, imm8, 1, out symbol)) { if ((symbol.Flags & SymbolFlags.Relative) == 0) { FormatKeyword(output, str_offset); output.Write(" ", FormatterTextKind.Text); } output.Write(instruction, operand, instructionOperand, options, numberFormatter, numberOptions, imm8, symbol, options.ShowSymbolAddress); } else { if (numberOptions.SignedNumber) { imm64 = (ulong)(sbyte)imm8; numberKind = NumberKind.Int8; if ((sbyte)imm8 < 0) { output.Write("-", FormatterTextKind.Operator); imm8 = (byte)-(sbyte)imm8; } } else { imm64 = imm8; numberKind = NumberKind.UInt8; } s = numberFormatter.FormatUInt8(options, numberOptions, imm8); output.WriteNumber(instruction, operand, instructionOperand, s, imm64, numberKind, FormatterTextKind.Number); } break; case InstrOpKind.Immediate16: case InstrOpKind.Immediate8to16: case InstrOpKind.DeclareWord: if (opKind == InstrOpKind.Immediate16) imm16 = instruction.Immediate16; else if (opKind == InstrOpKind.Immediate8to16) imm16 = (ushort)instruction.Immediate8to16; else imm16 = instruction.GetDeclareWordValue(operand); numberOptions = NumberFormattingOptions.CreateImmediateInternal(options); operandOptions = default; optionsProvider?.GetOperandOptions(instruction, operand, instructionOperand, ref operandOptions, ref numberOptions); if ((symbolResolver = this.symbolResolver) is not null && symbolResolver.TryGetSymbol(instruction, operand, instructionOperand, imm16, 2, out symbol)) { if ((symbol.Flags & SymbolFlags.Relative) == 0) { FormatKeyword(output, str_offset); output.Write(" ", FormatterTextKind.Text); } output.Write(instruction, operand, instructionOperand, options, numberFormatter, numberOptions, imm16, symbol, options.ShowSymbolAddress); } else { if (numberOptions.SignedNumber) { imm64 = (ulong)(short)imm16; numberKind = NumberKind.Int16; if ((short)imm16 < 0) { output.Write("-", FormatterTextKind.Operator); imm16 = (ushort)-(short)imm16; } } else { imm64 = imm16; numberKind = NumberKind.UInt16; } s = numberFormatter.FormatUInt16(options, numberOptions, imm16); output.WriteNumber(instruction, operand, instructionOperand, s, imm64, numberKind, FormatterTextKind.Number); } break; case InstrOpKind.Immediate32: case InstrOpKind.Immediate8to32: case InstrOpKind.DeclareDword: if (opKind == InstrOpKind.Immediate32) imm32 = instruction.Immediate32; else if (opKind == InstrOpKind.Immediate8to32) imm32 = (uint)instruction.Immediate8to32; else imm32 = instruction.GetDeclareDwordValue(operand); numberOptions = NumberFormattingOptions.CreateImmediateInternal(options); operandOptions = default; optionsProvider?.GetOperandOptions(instruction, operand, instructionOperand, ref operandOptions, ref numberOptions); if ((symbolResolver = this.symbolResolver) is not null && symbolResolver.TryGetSymbol(instruction, operand, instructionOperand, imm32, 4, out symbol)) { if ((symbol.Flags & SymbolFlags.Relative) == 0) { FormatKeyword(output, str_offset); output.Write(" ", FormatterTextKind.Text); } output.Write(instruction, operand, instructionOperand, options, numberFormatter, numberOptions, imm32, symbol, options.ShowSymbolAddress); } else { if (numberOptions.SignedNumber) { imm64 = (ulong)(int)imm32; numberKind = NumberKind.Int32; if ((int)imm32 < 0) { output.Write("-", FormatterTextKind.Operator); imm32 = (uint)-(int)imm32; } } else { imm64 = imm32; numberKind = NumberKind.UInt32; } s = numberFormatter.FormatUInt32(options, numberOptions, imm32); output.WriteNumber(instruction, operand, instructionOperand, s, imm64, numberKind, FormatterTextKind.Number); } break; case InstrOpKind.Immediate64: case InstrOpKind.Immediate8to64: case InstrOpKind.Immediate32to64: case InstrOpKind.DeclareQword: if (opKind == InstrOpKind.Immediate32to64) imm64 = (ulong)instruction.Immediate32to64; else if (opKind == InstrOpKind.Immediate8to64) imm64 = (ulong)instruction.Immediate8to64; else if (opKind == InstrOpKind.Immediate64) imm64 = instruction.Immediate64; else imm64 = instruction.GetDeclareQwordValue(operand); numberOptions = NumberFormattingOptions.CreateImmediateInternal(options); operandOptions = default; optionsProvider?.GetOperandOptions(instruction, operand, instructionOperand, ref operandOptions, ref numberOptions); if ((symbolResolver = this.symbolResolver) is not null && symbolResolver.TryGetSymbol(instruction, operand, instructionOperand, imm64, 8, out symbol)) { if ((symbol.Flags & SymbolFlags.Relative) == 0) { FormatKeyword(output, str_offset); output.Write(" ", FormatterTextKind.Text); } output.Write(instruction, operand, instructionOperand, options, numberFormatter, numberOptions, imm64, symbol, options.ShowSymbolAddress); } else { value64 = imm64; if (numberOptions.SignedNumber) { numberKind = NumberKind.Int64; if ((long)imm64 < 0) { output.Write("-", FormatterTextKind.Operator); imm64 = (ulong)-(long)imm64; } } else numberKind = NumberKind.UInt64; s = numberFormatter.FormatUInt64(options, numberOptions, imm64); output.WriteNumber(instruction, operand, instructionOperand, s, value64, numberKind, FormatterTextKind.Number); } break; case InstrOpKind.MemorySegSI: FormatMemory(output, instruction, operand, instructionOperand, instruction.MemorySegment, Register.SI, Register.None, 0, 0, 0, 2, opInfo.Flags); break; case InstrOpKind.MemorySegESI: FormatMemory(output, instruction, operand, instructionOperand, instruction.MemorySegment, Register.ESI, Register.None, 0, 0, 0, 4, opInfo.Flags); break; case InstrOpKind.MemorySegRSI: FormatMemory(output, instruction, operand, instructionOperand, instruction.MemorySegment, Register.RSI, Register.None, 0, 0, 0, 8, opInfo.Flags); break; case InstrOpKind.MemorySegDI: FormatMemory(output, instruction, operand, instructionOperand, instruction.MemorySegment, Register.DI, Register.None, 0, 0, 0, 2, opInfo.Flags); break; case InstrOpKind.MemorySegEDI: FormatMemory(output, instruction, operand, instructionOperand, instruction.MemorySegment, Register.EDI, Register.None, 0, 0, 0, 4, opInfo.Flags); break; case InstrOpKind.MemorySegRDI: FormatMemory(output, instruction, operand, instructionOperand, instruction.MemorySegment, Register.RDI, Register.None, 0, 0, 0, 8, opInfo.Flags); break; case InstrOpKind.MemoryESDI: FormatMemory(output, instruction, operand, instructionOperand, Register.ES, Register.DI, Register.None, 0, 0, 0, 2, opInfo.Flags); break; case InstrOpKind.MemoryESEDI: FormatMemory(output, instruction, operand, instructionOperand, Register.ES, Register.EDI, Register.None, 0, 0, 0, 4, opInfo.Flags); break; case InstrOpKind.MemoryESRDI: FormatMemory(output, instruction, operand, instructionOperand, Register.ES, Register.RDI, Register.None, 0, 0, 0, 8, opInfo.Flags); break; case InstrOpKind.Memory64: break; case InstrOpKind.Memory: int displSize = instruction.MemoryDisplSize; var baseReg = instruction.MemoryBase; var indexReg = instruction.MemoryIndex; int addrSize = InstructionUtils.GetAddressSizeInBytes(baseReg, indexReg, displSize, instruction.CodeSize); long displ; if (addrSize == 8) displ = (long)instruction.MemoryDisplacement64; else displ = instruction.MemoryDisplacement32; if ((opInfo.Flags & InstrOpInfoFlags.IgnoreIndexReg) != 0) indexReg = Register.None; FormatMemory(output, instruction, operand, instructionOperand, instruction.MemorySegment, baseReg, indexReg, instruction.InternalMemoryIndexScale, displSize, displ, addrSize, opInfo.Flags); break; default: throw new InvalidOperationException(); } if (operand == 0 && instruction.HasOpMask_or_ZeroingMasking) { if (instruction.HasOpMask) { output.Write("{", FormatterTextKind.Punctuation); FormatRegister(output, instruction, operand, instructionOperand, (int)instruction.OpMask); output.Write("}", FormatterTextKind.Punctuation); } if (instruction.ZeroingMasking) FormatDecorator(output, instruction, operand, instructionOperand, str_z, DecoratorKind.ZeroingMasking); } if (operand + 1 == opInfo.OpCount && instruction.HasRoundingControlOrSae) { var rc = instruction.RoundingControl; if (rc != RoundingControl.None && FormatterUtils.CanShowRoundingControl(instruction, options)) { Static.Assert((int)RoundingControl.None == 0 ? 0 : -1); Static.Assert((int)RoundingControl.RoundToNearest == 1 ? 0 : -1); Static.Assert((int)RoundingControl.RoundDown == 2 ? 0 : -1); Static.Assert((int)RoundingControl.RoundUp == 3 ? 0 : -1); Static.Assert((int)RoundingControl.RoundTowardZero == 4 ? 0 : -1); output.Write(" ", FormatterTextKind.Text); FormatDecorator(output, instruction, operand, instructionOperand, rcStrings[(int)rc - 1], DecoratorKind.RoundingControl); } else if (instruction.SuppressAllExceptions) { output.Write(" ", FormatterTextKind.Text); FormatDecorator(output, instruction, operand, instructionOperand, str_sae, DecoratorKind.SuppressAllExceptions); } } } void FormatDecorator(FormatterOutput output, in Instruction instruction, int operand, int instructionOperand, FormatterString text, DecoratorKind decorator) { output.Write("{", FormatterTextKind.Punctuation); output.WriteDecorator(instruction, operand, instructionOperand, text.Get(options.UppercaseDecorators || options.UppercaseAll), decorator); output.Write("}", FormatterTextKind.Punctuation); } [MethodImpl(MethodImplOptions.AggressiveInlining)] string ToRegisterString(int regNum) { Debug.Assert((uint)regNum < (uint)allRegisters.Length); if (options.PreferST0 && regNum == Registers.Register_ST) regNum = (int)Register.ST0; var regStr = allRegisters[(int)regNum]; return regStr.Get(options.UppercaseRegisters || options.UppercaseAll); } [MethodImpl(MethodImplOptions.NoInlining)] void FormatRegister(FormatterOutput output, in Instruction instruction, int operand, int instructionOperand, int regNum) { Static.Assert(Registers.ExtraRegisters == 1 ? 0 : -1); output.WriteRegister(instruction, operand, instructionOperand, ToRegisterString(regNum), regNum == Registers.Register_ST ? Register.ST0 : (Register)regNum); } void FormatMemory(FormatterOutput output, in Instruction instruction, int operand, int instructionOperand, Register segReg, Register baseReg, Register indexReg, int scale, int displSize, long displ, int addrSize, InstrOpInfoFlags flags) { Debug.Assert((uint)scale < (uint)scaleNumbers.Length); Debug.Assert(InstructionUtils.GetAddressSizeInBytes(baseReg, indexReg, displSize, instruction.CodeSize) == addrSize); var numberOptions = NumberFormattingOptions.CreateDisplacementInternal(options); SymbolResult symbol; bool useSymbol; var operandOptions = new FormatterOperandOptions(options.MemorySizeOptions); operandOptions.RipRelativeAddresses = options.RipRelativeAddresses; optionsProvider?.GetOperandOptions(instruction, operand, instructionOperand, ref operandOptions, ref numberOptions); ulong absAddr; if (baseReg == Register.RIP) { absAddr = (ulong)displ; if (options.RipRelativeAddresses) displ -= (long)instruction.NextIP; else { Debug.Assert(indexReg == Register.None); baseReg = Register.None; } displSize = 8; } else if (baseReg == Register.EIP) { absAddr = (uint)displ; if (options.RipRelativeAddresses) displ = (int)((uint)displ - instruction.NextIP32); else { Debug.Assert(indexReg == Register.None); baseReg = Register.None; } displSize = 4; } else absAddr = (ulong)displ; if (this.symbolResolver is ISymbolResolver symbolResolver) useSymbol = symbolResolver.TryGetSymbol(instruction, operand, instructionOperand, absAddr, addrSize, out symbol); else { useSymbol = false; symbol = default; } bool useScale = scale != 0 || options.AlwaysShowScale; if (!useScale) { // [rsi] = base reg, [rsi*1] = index reg if (baseReg == Register.None) useScale = true; } if (addrSize == 2 || !FormatterUtils.ShowIndexScale(instruction, options)) useScale = false; CodeSize codeSize; bool is1632 = ((codeSize = instruction.CodeSize) == CodeSize.Code16 || codeSize == CodeSize.Code32); bool hasMemReg = baseReg != Register.None || indexReg != Register.None; bool displInBrackets = useSymbol ? options.MasmSymbolDisplInBrackets : options.MasmDisplInBrackets; var segOverride = instruction.SegmentPrefix; if ((!is1632 && !hasMemReg && !useSymbol) || (is1632 && !hasMemReg && !useSymbol && !options.MasmAddDsPrefix32 && segOverride == Register.None)) displInBrackets = true; bool needBrackets = hasMemReg || displInBrackets; FormatMemorySize(output, instruction, ref symbol, instruction.MemorySize, flags, operandOptions, useSymbol); bool noTrackPrefix = segOverride == Register.DS && FormatterUtils.IsNotrackPrefixBranch(instruction.Code) && !((codeSize == CodeSize.Code16 || codeSize == CodeSize.Code32) && (baseReg == Register.BP || baseReg == Register.EBP || baseReg == Register.ESP)); if (options.AlwaysShowSegmentRegister || (segOverride != Register.None && !noTrackPrefix && FormatterUtils.ShowSegmentPrefix(Register.None, instruction, options)) || (is1632 && !hasMemReg && !useSymbol && options.MasmAddDsPrefix32)) { FormatRegister(output, instruction, operand, instructionOperand, (int)segReg); output.Write(":", FormatterTextKind.Punctuation); } if (!displInBrackets) FormatMemoryDispl(output, instruction, operand, instructionOperand, symbol, ref numberOptions, absAddr, displ, displSize, addrSize, useSymbol, needPlus: false, forceDispl: !hasMemReg); if (needBrackets) { output.Write("[", FormatterTextKind.Punctuation); if (options.SpaceAfterMemoryBracket) output.Write(" ", FormatterTextKind.Text); } bool needPlus = false; if (baseReg != Register.None) { FormatRegister(output, instruction, operand, instructionOperand, (int)baseReg); needPlus = true; } if (indexReg != Register.None) { if (needPlus) { if (options.SpaceBetweenMemoryAddOperators) output.Write(" ", FormatterTextKind.Text); output.Write("+", FormatterTextKind.Operator); if (options.SpaceBetweenMemoryAddOperators) output.Write(" ", FormatterTextKind.Text); } needPlus = true; if (!useScale) FormatRegister(output, instruction, operand, instructionOperand, (int)indexReg); else if (options.ScaleBeforeIndex) { output.WriteNumber(instruction, operand, instructionOperand, scaleNumbers[scale], 1U << scale, NumberKind.Int32, FormatterTextKind.Number); if (options.SpaceBetweenMemoryMulOperators) output.Write(" ", FormatterTextKind.Text); output.Write("*", FormatterTextKind.Operator); if (options.SpaceBetweenMemoryMulOperators) output.Write(" ", FormatterTextKind.Text); FormatRegister(output, instruction, operand, instructionOperand, (int)indexReg); } else { FormatRegister(output, instruction, operand, instructionOperand, (int)indexReg); if (options.SpaceBetweenMemoryMulOperators) output.Write(" ", FormatterTextKind.Text); output.Write("*", FormatterTextKind.Operator); if (options.SpaceBetweenMemoryMulOperators) output.Write(" ", FormatterTextKind.Text); output.WriteNumber(instruction, operand, instructionOperand, scaleNumbers[scale], 1U << scale, NumberKind.Int32, FormatterTextKind.Number); } } if (displInBrackets) FormatMemoryDispl(output, instruction, operand, instructionOperand, symbol, ref numberOptions, absAddr, displ, displSize, addrSize, useSymbol, needPlus, forceDispl: !needPlus); if (needBrackets) { if (options.SpaceAfterMemoryBracket) output.Write(" ", FormatterTextKind.Text); output.Write("]", FormatterTextKind.Punctuation); } } void FormatMemoryDispl(FormatterOutput output, in Instruction instruction, int operand, int instructionOperand, in SymbolResult symbol, ref NumberFormattingOptions numberOptions, ulong absAddr, long displ, int displSize, int addrSize, bool useSymbol, bool needPlus, bool forceDispl) { if (useSymbol) { if (needPlus) { if (options.SpaceBetweenMemoryAddOperators) output.Write(" ", FormatterTextKind.Text); if ((symbol.Flags & SymbolFlags.Signed) != 0) output.Write("-", FormatterTextKind.Operator); else output.Write("+", FormatterTextKind.Operator); if (options.SpaceBetweenMemoryAddOperators) output.Write(" ", FormatterTextKind.Text); } else if ((symbol.Flags & SymbolFlags.Signed) != 0) output.Write("-", FormatterTextKind.Operator); output.Write(instruction, operand, instructionOperand, options, numberFormatter, numberOptions, absAddr, symbol, options.ShowSymbolAddress, false, options.SpaceBetweenMemoryAddOperators); } else if (forceDispl || (displSize != 0 && (options.ShowZeroDisplacements || displ != 0))) { ulong origDispl = (ulong)displ; bool isSigned; if (needPlus) { isSigned = numberOptions.SignedNumber; if (options.SpaceBetweenMemoryAddOperators) output.Write(" ", FormatterTextKind.Text); if (addrSize == 8) { if (!numberOptions.SignedNumber) output.Write("+", FormatterTextKind.Operator); else if (displ < 0) { displ = -displ; output.Write("-", FormatterTextKind.Operator); } else output.Write("+", FormatterTextKind.Operator); if (numberOptions.DisplacementLeadingZeroes) { Debug.Assert(displSize <= 8); displSize = 8; } } else if (addrSize == 4) { if (!numberOptions.SignedNumber) output.Write("+", FormatterTextKind.Operator); else if ((int)displ < 0) { displ = (uint)-(int)displ; output.Write("-", FormatterTextKind.Operator); } else output.Write("+", FormatterTextKind.Operator); if (numberOptions.DisplacementLeadingZeroes) { Debug.Assert(displSize <= 4); displSize = 4; } } else { Debug.Assert(addrSize == 2); if (!numberOptions.SignedNumber) output.Write("+", FormatterTextKind.Operator); else if ((short)displ < 0) { displ = (ushort)-(short)displ; output.Write("-", FormatterTextKind.Operator); } else output.Write("+", FormatterTextKind.Operator); if (numberOptions.DisplacementLeadingZeroes) { Debug.Assert(displSize <= 2); displSize = 2; } } if (options.SpaceBetweenMemoryAddOperators) output.Write(" ", FormatterTextKind.Text); } else isSigned = false; NumberKind displKind; string s; if (displSize <= 1 && (ulong)displ <= byte.MaxValue) { s = numberFormatter.FormatUInt8(options, numberOptions, (byte)displ); displKind = isSigned ? NumberKind.Int8 : NumberKind.UInt8; } else if (displSize <= 2 && (ulong)displ <= ushort.MaxValue) { s = numberFormatter.FormatUInt16(options, numberOptions, (ushort)displ); displKind = isSigned ? NumberKind.Int16 : NumberKind.UInt16; } else if (displSize <= 4 && (ulong)displ <= uint.MaxValue) { s = numberFormatter.FormatUInt32(options, numberOptions, (uint)displ); displKind = isSigned ? NumberKind.Int32 : NumberKind.UInt32; } else if (displSize <= 8) { s = numberFormatter.FormatUInt64(options, numberOptions, (ulong)displ); displKind = isSigned ? NumberKind.Int64 : NumberKind.UInt64; } else throw new InvalidOperationException(); output.WriteNumber(instruction, operand, instructionOperand, s, origDispl, displKind, FormatterTextKind.Number); } } void FormatMemorySize(FormatterOutput output, in Instruction instruction, ref SymbolResult symbol, MemorySize memSize, InstrOpInfoFlags flags, FormatterOperandOptions operandOptions, bool useSymbol) { var memSizeOptions = operandOptions.MemorySizeOptions; if (memSizeOptions == MemorySizeOptions.Never) return; var memType = flags & InstrOpInfoFlags.MemSize_Mask; if (memType == InstrOpInfoFlags.MemSize_Nothing) return; Debug.Assert((uint)memSize < (uint)allMemorySizes.Length); var memInfo = allMemorySizes[(int)memSize]; var memSizeStrings = memInfo.keywords; switch (memInfo.size) { case 0: if (memType == InstrOpInfoFlags.MemSize_DwordOrQword) { if (instruction.CodeSize == CodeSize.Code16 || instruction.CodeSize == CodeSize.Code32) memSizeStrings = MemorySizes.dword_ptr; else memSizeStrings = MemorySizes.qword_ptr; } break; case 8: if (memType == InstrOpInfoFlags.MemSize_Mmx) memSizeStrings = MemorySizes.mmword_ptr; break; case 16: if (memType == InstrOpInfoFlags.MemSize_Normal) memSizeStrings = MemorySizes.oword_ptr; break; } if (memType == InstrOpInfoFlags.MemSize_XmmwordPtr) memSizeStrings = MemorySizes.xmmword_ptr; if (memSizeOptions == MemorySizeOptions.Default) { if (useSymbol && symbol.HasSymbolSize) { if (IsSameMemSize(memSizeStrings, memInfo.isBroadcast, ref symbol)) return; } else if ((flags & InstrOpInfoFlags.ShowNoMemSize_ForceSize) == 0 && !memInfo.isBroadcast) return; } else if (memSizeOptions == MemorySizeOptions.Minimal) { if (useSymbol && symbol.HasSymbolSize) { if (IsSameMemSize(memSizeStrings, memInfo.isBroadcast, ref symbol)) return; } if ((flags & InstrOpInfoFlags.ShowMinMemSize_ForceSize) == 0 && !memInfo.isBroadcast) return; } else Debug.Assert(memSizeOptions == MemorySizeOptions.Always); foreach (var name in memSizeStrings) { FormatKeyword(output, name); output.Write(" ", FormatterTextKind.Text); } } bool IsSameMemSize(FormatterString[] memSizeStrings, bool isBroadcast, ref SymbolResult symbol) { if (isBroadcast) return false; Debug.Assert((uint)symbol.SymbolSize < (uint)allMemorySizes.Length); var symbolMemInfo = allMemorySizes[(int)symbol.SymbolSize]; if (symbolMemInfo.isBroadcast) return false; var symbolMemSizeStrings = symbolMemInfo.keywords; return IsSameMemSize(memSizeStrings, symbolMemSizeStrings); } static bool IsSameMemSize(FormatterString[] a, FormatterString[] b) { if (a == b) return true; if (a.Length != b.Length) return false; for (int i = 0; i < a.Length; i++) { if (a[i].Get(false) != b[i].Get(false)) return false; } return true; } void FormatKeyword(FormatterOutput output, FormatterString keyword) => output.Write(keyword.Get(options.UppercaseKeywords || options.UppercaseAll), FormatterTextKind.Keyword); void FormatFlowControl(FormatterOutput output, FormatterFlowControl kind, FormatterOperandOptions operandOptions) { if (!operandOptions.BranchSize) return; switch (kind) { case FormatterFlowControl.AlwaysShortBranch: break; case FormatterFlowControl.ShortBranch: FormatKeyword(output, str_short); output.Write(" ", FormatterTextKind.Text); break; case FormatterFlowControl.NearBranch: FormatKeyword(output, str_near); output.Write(" ", FormatterTextKind.Text); FormatKeyword(output, str_ptr); output.Write(" ", FormatterTextKind.Text); break; case FormatterFlowControl.NearCall: break; case FormatterFlowControl.FarBranch: case FormatterFlowControl.FarCall: FormatKeyword(output, str_far); output.Write(" ", FormatterTextKind.Text); FormatKeyword(output, str_ptr); output.Write(" ", FormatterTextKind.Text); break; case FormatterFlowControl.Xbegin: break; default: throw new ArgumentOutOfRangeException(nameof(kind)); } } /// <summary> /// Formats a register /// </summary> /// <param name="register">Register</param> /// <returns></returns> public override string Format(Register register) => ToRegisterString((int)register); /// <summary> /// Formats a <see cref="sbyte"/> /// </summary> /// <param name="value">Value</param> /// <param name="numberOptions">Options</param> /// <returns></returns> public override string FormatInt8(sbyte value, in NumberFormattingOptions numberOptions) => numberFormatter.FormatInt8(options, numberOptions, value); /// <summary> /// Formats a <see cref="short"/> /// </summary> /// <param name="value">Value</param> /// <param name="numberOptions">Options</param> /// <returns></returns> public override string FormatInt16(short value, in NumberFormattingOptions numberOptions) => numberFormatter.FormatInt16(options, numberOptions, value); /// <summary> /// Formats a <see cref="int"/> /// </summary> /// <param name="value">Value</param> /// <param name="numberOptions">Options</param> /// <returns></returns> public override string FormatInt32(int value, in NumberFormattingOptions numberOptions) => numberFormatter.FormatInt32(options, numberOptions, value); /// <summary> /// Formats a <see cref="long"/> /// </summary> /// <param name="value">Value</param> /// <param name="numberOptions">Options</param> /// <returns></returns> public override string FormatInt64(long value, in NumberFormattingOptions numberOptions) => numberFormatter.FormatInt64(options, numberOptions, value); /// <summary> /// Formats a <see cref="byte"/> /// </summary> /// <param name="value">Value</param> /// <param name="numberOptions">Options</param> /// <returns></returns> public override string FormatUInt8(byte value, in NumberFormattingOptions numberOptions) => numberFormatter.FormatUInt8(options, numberOptions, value); /// <summary> /// Formats a <see cref="ushort"/> /// </summary> /// <param name="value">Value</param> /// <param name="numberOptions">Options</param> /// <returns></returns> public override string FormatUInt16(ushort value, in NumberFormattingOptions numberOptions) => numberFormatter.FormatUInt16(options, numberOptions, value); /// <summary> /// Formats a <see cref="uint"/> /// </summary> /// <param name="value">Value</param> /// <param name="numberOptions">Options</param> /// <returns></returns> public override string FormatUInt32(uint value, in NumberFormattingOptions numberOptions) => numberFormatter.FormatUInt32(options, numberOptions, value); /// <summary> /// Formats a <see cref="ulong"/> /// </summary> /// <param name="value">Value</param> /// <param name="numberOptions">Options</param> /// <returns></returns> public override string FormatUInt64(ulong value, in NumberFormattingOptions numberOptions) => numberFormatter.FormatUInt64(options, numberOptions, value); } } #endif
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ServiceBus { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for TopicsOperations. /// </summary> public static partial class TopicsOperationsExtensions { /// <summary> /// Lists all the topics in a namespace. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> public static IPage<TopicResource> ListAll(this ITopicsOperations operations, string resourceGroupName, string namespaceName) { return Task.Factory.StartNew(s => ((ITopicsOperations)s).ListAllAsync(resourceGroupName, namespaceName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists all the topics in a namespace. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<TopicResource>> ListAllAsync(this ITopicsOperations operations, string resourceGroupName, string namespaceName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAllWithHttpMessagesAsync(resourceGroupName, namespaceName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates a topic in the specified namespace /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='parameters'> /// Parameters supplied to create a Topic Resource. /// </param> public static TopicResource CreateOrUpdate(this ITopicsOperations operations, string resourceGroupName, string namespaceName, string topicName, TopicCreateOrUpdateParameters parameters) { return Task.Factory.StartNew(s => ((ITopicsOperations)s).CreateOrUpdateAsync(resourceGroupName, namespaceName, topicName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates a topic in the specified namespace /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='parameters'> /// Parameters supplied to create a Topic Resource. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<TopicResource> CreateOrUpdateAsync(this ITopicsOperations operations, string resourceGroupName, string namespaceName, string topicName, TopicCreateOrUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, namespaceName, topicName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes a topic from the specified namespace and resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The topics name. /// </param> /// <param name='topicName'> /// The topics name. /// </param> public static void Delete(this ITopicsOperations operations, string resourceGroupName, string namespaceName, string topicName) { Task.Factory.StartNew(s => ((ITopicsOperations)s).DeleteAsync(resourceGroupName, namespaceName, topicName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes a topic from the specified namespace and resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The topics name. /// </param> /// <param name='topicName'> /// The topics name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this ITopicsOperations operations, string resourceGroupName, string namespaceName, string topicName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(resourceGroupName, namespaceName, topicName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Returns the description for the specified topic /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='topicName'> /// The topic name. /// </param> public static TopicResource Get(this ITopicsOperations operations, string resourceGroupName, string namespaceName, string topicName) { return Task.Factory.StartNew(s => ((ITopicsOperations)s).GetAsync(resourceGroupName, namespaceName, topicName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns the description for the specified topic /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<TopicResource> GetAsync(this ITopicsOperations operations, string resourceGroupName, string namespaceName, string topicName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, namespaceName, topicName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Authorization rules for a topic. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The topic name /// </param> /// <param name='topicName'> /// The topic name. /// </param> public static IPage<SharedAccessAuthorizationRuleResource> ListAuthorizationRules(this ITopicsOperations operations, string resourceGroupName, string namespaceName, string topicName) { return Task.Factory.StartNew(s => ((ITopicsOperations)s).ListAuthorizationRulesAsync(resourceGroupName, namespaceName, topicName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Authorization rules for a topic. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The topic name /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<SharedAccessAuthorizationRuleResource>> ListAuthorizationRulesAsync(this ITopicsOperations operations, string resourceGroupName, string namespaceName, string topicName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAuthorizationRulesWithHttpMessagesAsync(resourceGroupName, namespaceName, topicName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates an authorizatioRule for the specified topic. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='authorizationRuleName'> /// Aauthorization Rule Name. /// </param> /// <param name='parameters'> /// The shared access authorization rule. /// </param> public static SharedAccessAuthorizationRuleResource CreateOrUpdateAuthorizationRule(this ITopicsOperations operations, string resourceGroupName, string namespaceName, string topicName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters) { return Task.Factory.StartNew(s => ((ITopicsOperations)s).CreateOrUpdateAuthorizationRuleAsync(resourceGroupName, namespaceName, topicName, authorizationRuleName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates an authorizatioRule for the specified topic. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='authorizationRuleName'> /// Aauthorization Rule Name. /// </param> /// <param name='parameters'> /// The shared access authorization rule. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<SharedAccessAuthorizationRuleResource> CreateOrUpdateAuthorizationRuleAsync(this ITopicsOperations operations, string resourceGroupName, string namespaceName, string topicName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, topicName, authorizationRuleName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Returns the specified authorizationRule. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='authorizationRuleName'> /// Authorization rule name. /// </param> public static SharedAccessAuthorizationRuleResource GetAuthorizationRule(this ITopicsOperations operations, string resourceGroupName, string namespaceName, string topicName, string authorizationRuleName) { return Task.Factory.StartNew(s => ((ITopicsOperations)s).GetAuthorizationRuleAsync(resourceGroupName, namespaceName, topicName, authorizationRuleName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns the specified authorizationRule. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='authorizationRuleName'> /// Authorization rule name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<SharedAccessAuthorizationRuleResource> GetAuthorizationRuleAsync(this ITopicsOperations operations, string resourceGroupName, string namespaceName, string topicName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, topicName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes a topic authorizationRule /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='authorizationRuleName'> /// AuthorizationRule Name. /// </param> public static void DeleteAuthorizationRule(this ITopicsOperations operations, string resourceGroupName, string namespaceName, string topicName, string authorizationRuleName) { Task.Factory.StartNew(s => ((ITopicsOperations)s).DeleteAuthorizationRuleAsync(resourceGroupName, namespaceName, topicName, authorizationRuleName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes a topic authorizationRule /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='authorizationRuleName'> /// AuthorizationRule Name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAuthorizationRuleAsync(this ITopicsOperations operations, string resourceGroupName, string namespaceName, string topicName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, topicName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Primary and Secondary ConnectionStrings to the topic /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='authorizationRuleName'> /// The authorizationRule name. /// </param> public static ResourceListKeys ListKeys(this ITopicsOperations operations, string resourceGroupName, string namespaceName, string topicName, string authorizationRuleName) { return Task.Factory.StartNew(s => ((ITopicsOperations)s).ListKeysAsync(resourceGroupName, namespaceName, topicName, authorizationRuleName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Primary and Secondary ConnectionStrings to the topic /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='authorizationRuleName'> /// The authorizationRule name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ResourceListKeys> ListKeysAsync(this ITopicsOperations operations, string resourceGroupName, string namespaceName, string topicName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListKeysWithHttpMessagesAsync(resourceGroupName, namespaceName, topicName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Regenerates Primary or Secondary ConnectionStrings to the topic /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='authorizationRuleName'> /// The authorizationRule name. /// </param> /// <param name='parameters'> /// Parameters supplied to regenerate Auth Rule. /// </param> public static ResourceListKeys RegenerateKeys(this ITopicsOperations operations, string resourceGroupName, string namespaceName, string topicName, string authorizationRuleName, RegenerateKeysParameters parameters) { return Task.Factory.StartNew(s => ((ITopicsOperations)s).RegenerateKeysAsync(resourceGroupName, namespaceName, topicName, authorizationRuleName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Regenerates Primary or Secondary ConnectionStrings to the topic /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='authorizationRuleName'> /// The authorizationRule name. /// </param> /// <param name='parameters'> /// Parameters supplied to regenerate Auth Rule. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ResourceListKeys> RegenerateKeysAsync(this ITopicsOperations operations, string resourceGroupName, string namespaceName, string topicName, string authorizationRuleName, RegenerateKeysParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.RegenerateKeysWithHttpMessagesAsync(resourceGroupName, namespaceName, topicName, authorizationRuleName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all the topics in a namespace. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<TopicResource> ListAllNext(this ITopicsOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((ITopicsOperations)s).ListAllNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists all the topics in a namespace. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<TopicResource>> ListAllNextAsync(this ITopicsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Authorization rules for a topic. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<SharedAccessAuthorizationRuleResource> ListAuthorizationRulesNext(this ITopicsOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((ITopicsOperations)s).ListAuthorizationRulesNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Authorization rules for a topic. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<SharedAccessAuthorizationRuleResource>> ListAuthorizationRulesNextAsync(this ITopicsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAuthorizationRulesNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************/ using System; using System.Xml; using System.Collections; using System.Collections.Generic; using Axiom.Core; using Axiom.MathLib; using Axiom.Graphics; using Axiom.Collections; using Axiom.Utility; using Axiom.Animating; using Multiverse; using Multiverse.CollisionLib; namespace Axiom.SceneManagers.Multiverse { /// <summary> /// Summary description for SceneManager. /// </summary> public class SceneManager : Axiom.Core.SceneManager { protected ITerrainGenerator terrainGenerator; protected ILODSpec lodSpec; protected FogConfig fogConfig; protected AmbientLightConfig ambientLightConfig; public SceneManager() : base("MVSceneManager") { // // TODO: Add constructor logic here // // set up default shadow parameters SetShadowTextureSettings(1024, 1, Axiom.Media.PixelFormat.FLOAT32_R); shadowColor = new ColorEx(0.75f, 0.75f, 0.75f); shadowFarDistance = 20000; shadowDirLightExtrudeDist = 100000; ShadowCasterRenderBackFaces = false; fogConfig = new FogConfig(this); ambientLightConfig = new AmbientLightConfig(this); } /// <summary> /// Loads the LandScape using parameters in the given config file. /// </summary> /// <param name="filename"></param> public override void LoadWorldGeometry( string filename ) { Boundary.parentSceneNode = RootSceneNode; TerrainManager.Instance.Cleanup(); TerrainManager.Instance.Initialize(this, terrainGenerator, lodSpec, RootSceneNode); } protected void InitShadowParams() { ShadowTextureCasterMaterial = "MVSMShadowCaster"; ShadowTextureReceiverMaterial = "MVSMShadowReceiver"; ShadowTextureSelfShadow = true; } public void SetWorldParams(ITerrainGenerator terrainGenerator, ILODSpec lodSpec) { InitShadowParams(); this.terrainGenerator = terrainGenerator; this.lodSpec = lodSpec; } public override void ClearScene() { TerrainManager.Instance.Cleanup(); base.ClearScene(); } public void AddBoundary(Boundary b) { TerrainManager.Instance.AddBoundary(b); } public void RemoveBoundary(Boundary b) { TerrainManager.Instance.RemoveBoundary(b); } public void ExportBoundaries(XmlTextWriter w) { TerrainManager.Instance.ExportBoundaries(w); } public void ImportBoundaries(XmlTextReader r) { TerrainManager.Instance.ImportBoundaries(r); } public Road CreateRoad(String name) { return TerrainManager.Instance.CreateRoad(name); } public void RemoveRoad(Road r) { TerrainManager.Instance.RemoveRoad(r); } public float GetAreaHeight(Vector3[] points) { return TerrainManager.Instance.GetAreaHeight(points); } // This entrypoint is invoked by the higher-level client to // set up the collision tile manager public void SetCollisionInterface(CollisionAPI API, float tileSize) { TerrainManager.Instance.SetCollisionInterface(API, tileSize); } // This entrypoint is invoked by the higher-level client, and // in turn invokes the collision tile manager operation to // change the collision center and the collision horizon, as // represented in the radius public void SetCollisionArea(Vector3 center, float radius) { TerrainManager.Instance.SetCollisionArea(center, radius); } /// <summary> /// Internal method for updating the scene graph ie the tree of SceneNode instances managed by this class. /// </summary> /// <param name="cam"></param> /// <remarks> /// This must be done before issuing objects to the rendering pipeline, since derived transformations from /// parent nodes are not updated until required. This SceneManager is a basic implementation which simply /// updates all nodes from the root. This ensures the scene is up to date but requires all the nodes /// to be updated even if they are not visible. Subclasses could trim this such that only potentially visible /// nodes are updated. /// </remarks> protected override void UpdateSceneGraph( Axiom.Core.Camera cam ) { if (illuminationStage == IlluminationRenderStage.None) { // Notify the TerrainManager of the camera location. If a page or tile boundary is crossed // this will result in a bunch of shuffling of heightMap data. // After the object bounding boxes have been update below, we need to call // the TerrainManager again to perform LOD adjustments on all visible tiles, // and queue the non-visible ones. TerrainManager.Instance.UpdateCamera(cam); } // call the base SceneManager to update the transforms and world bounds of all the // objects in the scene graph. base.UpdateSceneGraph(cam); if (illuminationStage == IlluminationRenderStage.None) { TerrainManager.Instance.LatePerFrameProcessing(cam); } } /// <summary> /// Creates a RaySceneQuery for this scene manager. /// </summary> /// <param name="ray">Details of the ray which describes the region for this query.</param> /// <param name="mask">The query mask to apply to this query; can be used to filter out certain objects; see SceneQuery for details.</param> /// <returns> /// The instance returned from this method must be destroyed by calling /// SceneManager::destroyQuery when it is no longer required. /// </returns> /// <remarks> /// This method creates a new instance of a query object for this scene manager, /// looking for objects which fall along a ray. See SceneQuery and RaySceneQuery /// for full details. /// </remarks> public override Axiom.Core.RaySceneQuery CreateRayQuery(Ray ray, ulong mask) { Axiom.Core.RaySceneQuery q = new Axiom.SceneManagers.Multiverse.RaySceneQuery(this); q.Ray = ray; q.QueryMask = mask; return q; } protected const ulong defaultRayQueryFlags = (ulong)RaySceneQueryType.AllTerrain | (ulong)RaySceneQueryType.Entities | (ulong)RaySceneQueryType.OnexRes; public override Axiom.Core.RaySceneQuery CreateRayQuery(Ray ray) { return CreateRayQuery(ray, defaultRayQueryFlags); } internal Pass SetTreeRenderPass(Pass pass, IRenderable renderable) { targetRenderSystem.BeginProfileEvent(ColorEx.Green, "SetPassTreeRender: Material = " + pass.Parent.Parent.Name); Pass usedPass = SetPass(pass); autoParamDataSource.Renderable = renderable; usedPass.UpdateAutoParamsNoLights(autoParamDataSource); // get the world matrices renderable.GetWorldTransforms(xform); targetRenderSystem.WorldMatrix = xform[0]; // set up light params autoParamDataSource.SetCurrentLightList(renderable.Lights); usedPass.UpdateAutoParamsLightsOnly(autoParamDataSource); // note: parameters must be bound after auto params are updated if(usedPass.HasVertexProgram) { targetRenderSystem.BindGpuProgramParameters(GpuProgramType.Vertex, usedPass.VertexProgramParameters); } if(usedPass.HasFragmentProgram) { targetRenderSystem.BindGpuProgramParameters(GpuProgramType.Fragment, usedPass.FragmentProgramParameters); } targetRenderSystem.EndProfileEvent(); return usedPass; } private TimingMeter baseRenderSolidMeter = MeterManager.GetMeter("Base Render", "MVSM Render Solid"); private TimingMeter boundaryRenderSolidMeter = MeterManager.GetMeter("Boundary Render", "MVSM Render Solid"); protected override void RenderSolidObjects(SortedList list, bool doLightIteration, List<Light> manualLightList) { if (renderingMainGroup) { if (!(renderingNoShadowQueue || (illuminationStage == IlluminationRenderStage.RenderModulativePass))) { TreeGroup.RenderAllTrees(targetRenderSystem); } } baseRenderSolidMeter.Enter(); base.RenderSolidObjects(list, doLightIteration, manualLightList); baseRenderSolidMeter.Exit(); } /// <summary> /// Renders a set of solid objects for the shadow receiver pass. /// Will only render /// </summary> /// <param name="list">List of solid objects.</param> protected virtual void RenderShadowReceiverObjects(SortedList list, bool doLightIteration, List<Light> manualLightList) { // compute sphere of area around camera that can receive shadows. Sphere shadowSphere = new Sphere(autoParamDataSource.CameraPosition, ShadowConfig.ShadowFarDistance); List<IRenderable> shadowList = new List<IRenderable>(); // ----- SOLIDS LOOP ----- // renderSolidObjectsMeter.Enter(); for (int i = 0; i < list.Count; i++) { RenderableList renderables = (RenderableList)list.GetByIndex(i); // bypass if this group is empty if (renderables.Count == 0) { continue; } Pass pass = (Pass)list.GetKey(i); // Give SM a chance to eliminate this pass if (!ValidatePassForRendering(pass)) continue; shadowList.Clear(); // special case for a single renderable using the material, so that we can // avoid calling SetPass() when there is only one renderable and it doesn't // need to be drawn. for (int r = 0; r < renderables.Count; r++) { bool drawObject = true; IRenderable renderable = (IRenderable)renderables[r]; MovableObject movableObject = renderable as MovableObject; if (movableObject != null) { // it is a movableObject, so we can if (!movableObject.GetWorldBoundingBox().Intersects(shadowSphere)) { // objects bounding box doesn't intercect the shadow sphere, so we don't // need to render it in this pass. drawObject = false; } } if (drawObject) { shadowList.Add(renderable); } } // if nobody is within shadow range, then we don't need to render, and skip the SetPass() if (shadowList.Count == 0) { continue; } // For solids, we try to do each pass in turn Pass usedPass = SetPass(pass); // render each object associated with this rendering pass foreach (IRenderable renderable in shadowList) { // Give SM a chance to eliminate if (!ValidateRenderableForRendering(usedPass, renderable)) continue; // Render a single object, this will set up auto params if required if (MeterManager.Collecting) MeterManager.AddInfoEvent("RenderSingle shadow receiver material {0}, doLight {1}, lightCnt {2}", renderable.Material.Name, doLightIteration, (manualLightList != null ? manualLightList.Count : 0)); try { RenderSingleObject(renderable, usedPass, doLightIteration, manualLightList); } catch (Exception e) { LogManager.Instance.WriteException("Invalid call to Axiom.Core.SceneManager.RenderSingleObject: {0}\n{1}", e.Message, e.StackTrace); if (renderable.Material != null) LogManager.Instance.Write("Failed renderable material: {0}", renderable.Material.Name); } } } // renderSolidObjectsMeter.Exit(); } /// <summary> /// Render a group rendering only shadow receivers. /// We have our own version here to add some optimizations /// </summary> /// <param name="group">Render queue group.</param> protected override void RenderTextureShadowReceiverQueueGroupObjects(RenderQueueGroup group) { // Override auto param ambient to force vertex programs to go full-bright autoParamDataSource.AmbientLight = ColorEx.White; targetRenderSystem.AmbientLight = ColorEx.White; // Iterate through priorities for (int i = 0; i < group.NumPriorityGroups; i++) { RenderPriorityGroup priorityGroup = group.GetPriorityGroup(i); // Do solids, override light list in case any vertex programs use them RenderShadowReceiverObjects(priorityGroup.SolidPasses, false, nullLightList); // Don't render transparents or passes which have shadow receipt disabled }// for each priority // reset ambient autoParamDataSource.AmbientLight = ambientColor; targetRenderSystem.AmbientLight = ambientColor; } public override void SetFog(FogMode mode, ColorEx color, float density, float linearStart, float linearEnd) { // set the scene manager member variables to the new values base.SetFog(mode, color, density, linearStart, linearEnd); } /// <summary> /// /// </summary> /// <param name="mode"></param> /// <param name="color"></param> /// <param name="density"></param> public override void SetFog(FogMode mode, ColorEx color, float density) { SetFog(mode, color, density, 0.0f, 1.0f); } public ShadowConfig ShadowConfig { get { return TerrainManager.Instance.ShadowConfig; } } public OceanConfig OceanConfig { get { return TerrainManager.Instance.OceanConfig; } } public AutoParamDataSource AutoParamDataSource { get { return autoParamDataSource; } } public FogConfig FogConfig { get { return fogConfig; } } public AmbientLightConfig AmbientLightConfig { get { return ambientLightConfig; } } public bool DisplayTerrain { get { return TerrainManager.Instance.DrawTerrain; } set { TerrainManager.Instance.DrawTerrain = value; } } public void SetProfileMarker(ColorEx color, string name) { targetRenderSystem.SetProfileMarker(color, name); } } }
// 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.Reflection; using Xunit; namespace System.Reflection.Compatibility.UnitTests { // ContainsGenericParameters public class MethodBaseContainsGenericParameters { public class TestClass { public TestClass() { } public TestClass(int val) { } public void TestGenericMethod<T>(T p1) { } public void TestMethod(int val) { } public void TestMethod2(int val) { } public void TestMethod2(int val1, float val2, string val3) { } public void TestPartialGenericMethod<T>(int val, T p1) { } public T TestGenericReturnTypeMethod<T>() { T ret = default(T); return ret; } } public class TestGenericClass<T> { public TestGenericClass() { } public TestGenericClass(T val) { } public TestGenericClass(T p, int val) { } public void TestMethod(T p1) { } public void TestMultipleGenericMethod<U>(U p2) { } public void TestVoidMethod() { } } // Positive Test 1: ContainsGenericParameters should return true for open generic method [Fact] public void PosTest1() { Type type = typeof(TestClass); MethodBase methodInfo = type.GetMethod("TestGenericMethod"); Assert.True(methodInfo.ContainsGenericParameters, "ContainsGenericParameters returns false for open generic method" + methodInfo); } // Positive Test 2: ContainsGenericParameters should return false for a closed generic method [Fact] public void PosTest2() { Type type = typeof(TestClass); MethodInfo methodInfo = type.GetMethod("TestGenericMethod"); MethodBase genericMethodInfo = methodInfo.MakeGenericMethod(typeof(int)); Assert.False(genericMethodInfo.ContainsGenericParameters, "ContainsGenericParameters returns true for closed generic method"); } // Positive Test 3: ContainsGenericParameters should return false for a non generic method [Fact] public void PosTest3() { Type type = typeof(TestClass); MethodBase methodInfo = type.GetMethod("TestMethod"); Assert.False(methodInfo.ContainsGenericParameters, "ContainsGenericParameters returns true for non generic method"); } // Positive Test 4: ContainsGenericParameters should return true for a generic method contains non generic parameter [Fact] public void PosTest4() { Type type = typeof(TestClass); MethodBase methodInfo = type.GetMethod("TestPartialGenericMethod"); Assert.True(methodInfo.ContainsGenericParameters, "ContainsGenericParameters returns false for a generic method contains non generic parameter" + methodInfo); } // Positive Test 5: ContainsGenericParameters should return true for a generic method only contains generic return type [Fact] public void PosTest5() { Type type = typeof(TestClass); MethodBase methodInfo = type.GetMethod("TestPartialGenericMethod"); Assert.True(methodInfo.ContainsGenericParameters, "ContainsGenericParameters returns false for a generic method only contains generic return type" + methodInfo); } // Positive Test 6: ContainsGenericParameters should return false for a generic method in a closed generic type [Fact] public void PosTest6() { Type type = typeof(TestGenericClass<int>); MethodBase methodInfo = type.GetMethod("TestMethod"); Assert.False(methodInfo.ContainsGenericParameters, "ContainsGenericParameters returns true for a generic method in a closed generic type"); } // Positive Test 7: ContainsGenericParameters should return true for a method in a opened generic type [Fact] public void PosTest7() { Type type = typeof(TestGenericClass<>); MethodBase methodInfo = type.GetMethod("TestMethod"); Assert.True(methodInfo.ContainsGenericParameters, "ContainsGenericParameters returns false for a method in a opened generic type" + methodInfo); } // Positive Test 8: ContainsGenericParameters should return true for a generic method in a opened generic type [Fact] public void PosTest8() { Type type = typeof(TestGenericClass<>); MethodBase methodInfo = type.GetMethod("TestMultipleGenericMethod"); Assert.True(methodInfo.ContainsGenericParameters, "ContainsGenericParameters returns false for a generic method in a opened generic type" + methodInfo); } // Positive Test 9: ContainsGenericParameters should return true for a generic method in a closed generic type [Fact] public void PosTest9() { Type type = typeof(TestGenericClass<int>); MethodBase methodInfo = type.GetMethod("TestMultipleGenericMethod"); Assert.True(methodInfo.ContainsGenericParameters, "ContainsGenericParameters returns false for a generic method in a closed generic type" + methodInfo); } // Positive Test 10: ContainsGenericParameters should return true for a method in a generic type [Fact] public void PosTest10() { Type type = typeof(TestGenericClass<>); MethodBase methodInfo = type.GetMethod("TestVoidMethod"); Assert.True(methodInfo.ContainsGenericParameters, "ContainsGenericParameters returns false for a generic method in a generic type" + methodInfo); } // Positive Test 11: ContainsGenericParameters should return false for a method in a closed generic type [Fact] public void PosTest11() { Type type = typeof(TestGenericClass<int>); MethodBase methodInfo = type.GetMethod("TestVoidMethod"); Assert.False(methodInfo.ContainsGenericParameters, "ContainsGenericParameters returns truefor a generic method in a closed generic type"); } // Positive Test 12: ContainsGenericParameters should return false for a constructor in a non generic type [Fact] public void PosTest12() { Type type = typeof(TestClass); MethodBase methodInfo = type.GetConstructor(new Type[] { }); Assert.False(methodInfo.ContainsGenericParameters, "ContainsGenericParameters returns true for a constructor in a non generic type"); methodInfo = type.GetConstructor(new Type[] { typeof(int) }); Assert.False(methodInfo.ContainsGenericParameters, "ContainsGenericParameters returns true for a constructor in a non generic type"); } // Positive Test 13: ContainsGenericParameters should return false for a constructor in a open generic type [Fact] public void PosTest13() { Type type = typeof(TestGenericClass<>); MethodBase[] ctors = type.GetConstructors(); for (int i = 0; i < ctors.Length; ++i) { // ContainsGenericParameters should behave same for both methods and constructors. // If method/ctor or the declaring type contains uninstantiated open generic parameter, // ContainsGenericParameters should return true. (Which also means we can't invoke that type) Assert.True(ctors[i].ContainsGenericParameters, "ContainsGenericParameters returns false for a constructor" + ctors[i] + " in a open generic type "); } } // Positive Test 14: ContainsGenericParameters should return false for a constructor in a closed generic type [Fact] public void PosTest14() { Type type = typeof(TestGenericClass<int>); MethodBase[] ctors = type.GetConstructors(); for (int i = 0; i < ctors.Length; ++i) { Assert.False(ctors[i].ContainsGenericParameters, "ContainsGenericParameters returns true for a constructor" + ctors[i] + " in a closed generic type"); } } // Positive Test 15: Exercise GetMethod(name, Type []) [Fact] public void PosTest15() { Type type = typeof(TestClass); MethodInfo specificMethod = type.GetMethod("TestMethod2", new Type[] { typeof(int), typeof(float), typeof(string) }); Assert.NotNull(specificMethod); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // <OWNER>[....]</OWNER> // // // Hash // // Evidence corresponding to a hash of the assembly bits. // using System; using System.Diagnostics.Contracts; using System.Collections.Generic; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security.Cryptography; using System.Security.Util; using Microsoft.Win32.SafeHandles; namespace System.Security.Policy { [Serializable] [ComVisible(true)] public sealed class Hash : EvidenceBase, ISerializable { private RuntimeAssembly m_assembly; private Dictionary<Type, byte[]> m_hashes; private WeakReference m_rawData; /// <summary> /// Deserialize a serialized hash evidence object /// </summary> [SecurityCritical] internal Hash(SerializationInfo info, StreamingContext context) { // // We have three serialization formats that we might be deserializing, the Whidbey format which // contains hash values directly, the Whidbey format which contains a pointer to a PEImage, and // the v4 format which contains a dictionary of calculated hashes. // // If we have the Whidbey version that has built in hash values, we can convert that, but we // cannot do anything with the PEImage format since that is a serialized pointer into another // runtime's VM. // Dictionary<Type, byte[]> hashes = info.GetValueNoThrow("Hashes", typeof(Dictionary<Type, byte[]>)) as Dictionary<Type, byte[]>; if (hashes != null) { m_hashes = hashes; } else { // If there is no hash value dictionary, then check to see if we have the Whidbey multiple // hashes version of the evidence. m_hashes = new Dictionary<Type, byte[]>(); byte[] md5 = info.GetValueNoThrow("Md5", typeof(byte[])) as byte[]; if (md5 != null) { m_hashes[typeof(MD5)] = md5; } byte[] sha1 = info.GetValueNoThrow("Sha1", typeof(byte[])) as byte[]; if (sha1 != null) { m_hashes[typeof(SHA1)] = sha1; } byte[] rawData = info.GetValueNoThrow("RawData", typeof(byte[])) as byte[]; if (rawData != null) { GenerateDefaultHashes(rawData); } } } /// <summary> /// Create hash evidence for the specified assembly /// </summary> public Hash(Assembly assembly) { if (assembly == null) throw new ArgumentNullException("assembly"); Contract.EndContractBlock(); if (assembly.IsDynamic) throw new ArgumentException(Environment.GetResourceString("Security_CannotGenerateHash"), "assembly"); m_hashes = new Dictionary<Type, byte[]>(); m_assembly = assembly as RuntimeAssembly; if (m_assembly == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"), "assembly"); } /// <summary> /// Create a copy of some hash evidence /// </summary> private Hash(Hash hash) { Contract.Assert(hash != null); m_assembly = hash.m_assembly; m_rawData = hash.m_rawData; m_hashes = new Dictionary<Type, byte[]>(hash.m_hashes); } /// <summary> /// Create a hash evidence prepopulated with a specific hash value /// </summary> private Hash(Type hashType, byte[] hashValue) { Contract.Assert(hashType != null); Contract.Assert(hashValue != null); m_hashes = new Dictionary<Type, byte[]>(); byte[] hashClone = new byte[hashValue.Length]; Array.Copy(hashValue, hashClone, hashClone.Length); m_hashes[hashType] = hashValue; } /// <summary> /// Build a Hash evidence that contains the specific SHA-1 hash. The input hash is not validated, /// and the resulting Hash object cannot calculate additional hash values. /// </summary> public static Hash CreateSHA1(byte[] sha1) { if (sha1 == null) throw new ArgumentNullException("sha1"); Contract.EndContractBlock(); return new Hash(typeof(SHA1), sha1); } /// <summary> /// Build a Hash evidence that contains the specific SHA-256 hash. The input hash is not /// validated, and the resulting Hash object cannot calculate additional hash values. /// </summary> public static Hash CreateSHA256(byte[] sha256) { if (sha256 == null) throw new ArgumentNullException("sha256"); Contract.EndContractBlock(); return new Hash(typeof(SHA256), sha256); } /// <summary> /// Build a Hash evidence that contains the specific MD5 hash. The input hash is not validated, /// and the resulting Hash object cannot calculate additional hash values. /// </summary> public static Hash CreateMD5(byte[] md5) { if (md5 == null) throw new ArgumentNullException("md5"); Contract.EndContractBlock(); return new Hash(typeof(MD5), md5); } /// <summary> /// Make a copy of this evidence object /// </summary> public override EvidenceBase Clone() { return new Hash(this); } /// <summary> /// Prepare the hash evidence for serialization /// </summary> [OnSerializing] private void OnSerializing(StreamingContext ctx) { GenerateDefaultHashes(); } /// <summary> /// Serialize the hash evidence /// </summary> [SecurityCritical] public void GetObjectData(SerializationInfo info, StreamingContext context) { GenerateDefaultHashes(); // // Backwards compatibility with Whidbey // byte[] sha1Hash; byte[] md5Hash; // Whidbey expects the MD5 and SHA1 hashes stored separately. if (m_hashes.TryGetValue(typeof(MD5), out md5Hash)) { info.AddValue("Md5", md5Hash); } if (m_hashes.TryGetValue(typeof(SHA1), out sha1Hash)) { info.AddValue("Sha1", sha1Hash); } // For perf, don't serialize the assembly binary content. // This has the side-effect that the Whidbey runtime will not be able to compute any // hashes besides the provided MD5 and SHA1. info.AddValue("RawData", null); // It doesn't make sense to serialize a memory pointer cross-runtime. info.AddValue("PEFile", IntPtr.Zero); // // Current implementation // // Add all the computed hashes. While this can duplicate the MD5 and SHA1 hashes, // it allows for a clean separation between legacy support and the current implementation. info.AddValue("Hashes", m_hashes); } /// <summary> /// Get the SHA-1 hash value of the assembly /// </summary> public byte[] SHA1 { get { byte[] sha1 = null; if (!m_hashes.TryGetValue(typeof(SHA1), out sha1)) { sha1 = GenerateHash(GetDefaultHashImplementationOrFallback(typeof(SHA1), typeof(SHA1))); } byte[] returnHash = new byte[sha1.Length]; Array.Copy(sha1, returnHash, returnHash.Length); return returnHash; } } /// <summary> /// Get the SHA-256 hash value of the assembly /// </summary> public byte[] SHA256 { get { byte[] sha256 = null; if (!m_hashes.TryGetValue(typeof(SHA256), out sha256)) { sha256 = GenerateHash(GetDefaultHashImplementationOrFallback(typeof(SHA256), typeof(SHA256))); } byte[] returnHash = new byte[sha256.Length]; Array.Copy(sha256, returnHash, returnHash.Length); return returnHash; } } /// <summary> /// Get the MD5 hash value of the assembly /// </summary> public byte[] MD5 { get { byte[] md5 = null; if (!m_hashes.TryGetValue(typeof(MD5), out md5)) { md5 = GenerateHash(GetDefaultHashImplementationOrFallback(typeof(MD5), typeof(MD5))); } byte[] returnHash = new byte[md5.Length]; Array.Copy(md5, returnHash, returnHash.Length); return returnHash; } } /// <summary> /// Get the hash value of the assembly when hashed with a specific algorithm. The actual hash /// algorithm object is not used, however the same type of object will be used. /// </summary> public byte[] GenerateHash(HashAlgorithm hashAlg) { if (hashAlg == null) throw new ArgumentNullException("hashAlg"); Contract.EndContractBlock(); byte[] hashValue = GenerateHash(hashAlg.GetType()); byte[] returnHash = new byte[hashValue.Length]; Array.Copy(hashValue, returnHash, returnHash.Length); return returnHash; } /// <summary> /// Generate the hash value of an assembly when hashed with the specified algorithm. The result /// may be a direct reference to our internal table of hashes, so it should be copied before /// returning it to user code. /// </summary> private byte[] GenerateHash(Type hashType) { Contract.Assert(hashType != null && typeof(HashAlgorithm).IsAssignableFrom(hashType), "Expected a hash algorithm"); Type indexType = GetHashIndexType(hashType); byte[] hashValue = null; if (!m_hashes.TryGetValue(indexType, out hashValue)) { // If we're not attached to an assembly, then we cannot generate hashes on demand if (m_assembly == null) { throw new InvalidOperationException(Environment.GetResourceString("Security_CannotGenerateHash")); } hashValue = GenerateHash(hashType, GetRawData()); m_hashes[indexType] = hashValue; } return hashValue; } /// <summary> /// Generate a hash of the given type for the assembly data /// </summary> private static byte[] GenerateHash(Type hashType, byte[] assemblyBytes) { Contract.Assert(hashType != null && typeof(HashAlgorithm).IsAssignableFrom(hashType), "Expected a hash algorithm"); Contract.Assert(assemblyBytes != null); using (HashAlgorithm hash = HashAlgorithm.Create(hashType.FullName)) { return hash.ComputeHash(assemblyBytes); } } /// <summary> /// Build the default set of hash values that will be available for all assemblies /// </summary> private void GenerateDefaultHashes() { // We can't generate any hash values that we don't already have if there isn't an attached // assembly to get the hash value of. if (m_assembly != null) { GenerateDefaultHashes(GetRawData()); } } /// <summary> /// Build the default set of hash values that will be available for all assemblies given the raw /// assembly data to hash. /// </summary> private void GenerateDefaultHashes(byte[] assemblyBytes) { Contract.Assert(assemblyBytes != null); Type[] defaultHashTypes = new Type[] { GetHashIndexType(typeof(SHA1)), GetHashIndexType(typeof(SHA256)), GetHashIndexType(typeof(MD5)) }; foreach (Type defaultHashType in defaultHashTypes) { Type hashImplementationType = GetDefaultHashImplementation(defaultHashType); if (hashImplementationType != null) { if (!m_hashes.ContainsKey(defaultHashType)) { m_hashes[defaultHashType] = GenerateHash(hashImplementationType, assemblyBytes); } } } } /// <summary> /// Map a hash algorithm to the default implementation of that algorithm, falling back to a given /// implementation if no suitable default can be found. This option may be used for situations /// where it is better to throw an informative exception when trying to use an unsuitable hash /// algorithm than to just return null. (For instance, throwing a FIPS not supported exception /// when trying to get the MD5 hash evidence). /// </summary> private static Type GetDefaultHashImplementationOrFallback(Type hashAlgorithm, Type fallbackImplementation) { Contract.Assert(hashAlgorithm != null && typeof(HashAlgorithm).IsAssignableFrom(hashAlgorithm)); Contract.Assert(fallbackImplementation != null && GetHashIndexType(hashAlgorithm).IsAssignableFrom(fallbackImplementation)); Type defaultImplementation = GetDefaultHashImplementation(hashAlgorithm); return defaultImplementation != null ? defaultImplementation : fallbackImplementation; } /// <summary> /// Map a hash algorithm to the default implementation of that algorithm to use for Hash /// evidence, taking into account things such as FIPS support. If there is no suitable /// implementation for the algorithm, GetDefaultHashImplementation returns null. /// </summary> private static Type GetDefaultHashImplementation(Type hashAlgorithm) { Contract.Assert(hashAlgorithm != null && typeof(HashAlgorithm).IsAssignableFrom(hashAlgorithm)); if (hashAlgorithm.IsAssignableFrom(typeof(MD5))) { // MD5 is not a FIPS compliant algorithm, so if we need to allow only FIPS implementations, // we have no way to create an MD5 hash. Otherwise, we can just use the standard CAPI // implementation since that is available on all operating systems we support. if (!CryptoConfig.AllowOnlyFipsAlgorithms) { return typeof(MD5CryptoServiceProvider); } else { return null; } } else if (hashAlgorithm.IsAssignableFrom(typeof(SHA256))) { // The managed SHA256 implementation is not a FIPS certified implementation, however on // Windows 2003 and higher we have a FIPS alternative. If we're on Windows 2003 or better, // use the CAPI implementation - otherwise, we fall back to the managed implementation if // FIPS is not enabled. Version osVersion = Environment.OSVersion.Version; bool isWin2k3OrHigher = Environment.RunningOnWinNT && (osVersion.Major > 5 || (osVersion.Major == 5 && osVersion.Minor >= 2)); if (isWin2k3OrHigher) { return Type.GetType("System.Security.Cryptography.SHA256CryptoServiceProvider, " + AssemblyRef.SystemCore); } else if (!CryptoConfig.AllowOnlyFipsAlgorithms) { return typeof(SHA256Managed); } else { return null; } } else { // Otherwise we don't have a better suggestion for the algorithm, so we can just fallback to // the input algorithm. return hashAlgorithm; } } /// <summary> /// Get the type used to index into the saved hash value dictionary. We want this to be the /// class which immediately derives from HashAlgorithm so that we can reuse the same hash value /// if we're asked for (e.g.) SHA256Managed and SHA256CryptoServiceProvider /// </summary> private static Type GetHashIndexType(Type hashType) { Contract.Assert(hashType != null && typeof(HashAlgorithm).IsAssignableFrom(hashType)); Type currentType = hashType; // Walk up the inheritence hierarchy looking for the first class that derives from HashAlgorithm while (currentType != null && currentType.BaseType != typeof(HashAlgorithm)) { currentType = currentType.BaseType; } // If this is the degenerate case where we started out with HashAlgorithm, we won't find it // further up our inheritence tree. if (currentType == null) { BCLDebug.Assert(hashType == typeof(HashAlgorithm), "hashType == typeof(HashAlgorithm)"); currentType = typeof(HashAlgorithm); } return currentType; } /// <summary> /// Raw bytes of the assembly being hashed /// </summary> private byte[] GetRawData() { byte[] rawData = null; // We can only generate hashes on demand if we're associated with an assembly if (m_assembly != null) { // See if we still hold a reference to the assembly data if (m_rawData != null) { rawData = m_rawData.Target as byte[]; } // If not, load the raw bytes up if (rawData == null) { rawData = m_assembly.GetRawBytes(); m_rawData = new WeakReference(rawData); } } return rawData; } private SecurityElement ToXml() { GenerateDefaultHashes(); SecurityElement root = new SecurityElement("System.Security.Policy.Hash"); // 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. BCLDebug.Assert(this.GetType().FullName.Equals("System.Security.Policy.Hash"), "Class name changed!"); root.AddAttribute("version", "2"); foreach (KeyValuePair<Type, byte[]> hashValue in m_hashes) { SecurityElement hashElement = new SecurityElement("hash"); hashElement.AddAttribute("algorithm", hashValue.Key.Name); hashElement.AddAttribute("value", Hex.EncodeHexString(hashValue.Value)); root.AddChild(hashElement); } return root; } public override String ToString() { return ToXml().ToString(); } } }
#region Copyright notice and license // Copyright 2015-2016, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * 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 Google Inc. 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. #endregion using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading.Tasks; using Grpc.Core.Internal; using Grpc.Core.Logging; using Grpc.Core.Utils; namespace Grpc.Core { /// <summary> /// gRPC server. A single server can server arbitrary number of services and can listen on more than one ports. /// </summary> public class Server { static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<Server>(); readonly AtomicCounter activeCallCounter = new AtomicCounter(); readonly ServiceDefinitionCollection serviceDefinitions; readonly ServerPortCollection ports; readonly GrpcEnvironment environment; readonly List<ChannelOption> options; readonly ServerSafeHandle handle; readonly object myLock = new object(); readonly List<ServerServiceDefinition> serviceDefinitionsList = new List<ServerServiceDefinition>(); readonly List<ServerPort> serverPortList = new List<ServerPort>(); readonly Dictionary<string, IServerCallHandler> callHandlers = new Dictionary<string, IServerCallHandler>(); readonly TaskCompletionSource<object> shutdownTcs = new TaskCompletionSource<object>(); bool startRequested; bool shutdownRequested; /// <summary> /// Create a new server. /// </summary> /// <param name="options">Channel options.</param> public Server(IEnumerable<ChannelOption> options = null) { this.serviceDefinitions = new ServiceDefinitionCollection(this); this.ports = new ServerPortCollection(this); this.environment = GrpcEnvironment.AddRef(); this.options = options != null ? new List<ChannelOption>(options) : new List<ChannelOption>(); using (var channelArgs = ChannelOptions.CreateChannelArgs(this.options)) { this.handle = ServerSafeHandle.NewServer(environment.CompletionQueue, channelArgs); } } /// <summary> /// Services that will be exported by the server once started. Register a service with this /// server by adding its definition to this collection. /// </summary> public ServiceDefinitionCollection Services { get { return serviceDefinitions; } } /// <summary> /// Ports on which the server will listen once started. Register a port with this /// server by adding its definition to this collection. /// </summary> public ServerPortCollection Ports { get { return ports; } } /// <summary> /// To allow awaiting termination of the server. /// </summary> public Task ShutdownTask { get { return shutdownTcs.Task; } } /// <summary> /// Starts the server. /// </summary> public void Start() { lock (myLock) { GrpcPreconditions.CheckState(!startRequested); startRequested = true; handle.Start(); AllowOneRpc(); } } /// <summary> /// Requests server shutdown and when there are no more calls being serviced, /// cleans up used resources. The returned task finishes when shutdown procedure /// is complete. /// </summary> public async Task ShutdownAsync() { lock (myLock) { GrpcPreconditions.CheckState(startRequested); GrpcPreconditions.CheckState(!shutdownRequested); shutdownRequested = true; } handle.ShutdownAndNotify(HandleServerShutdown, environment); await shutdownTcs.Task.ConfigureAwait(false); DisposeHandle(); await Task.Run(() => GrpcEnvironment.Release()).ConfigureAwait(false); } /// <summary> /// Requests server shutdown while cancelling all the in-progress calls. /// The returned task finishes when shutdown procedure is complete. /// </summary> public async Task KillAsync() { lock (myLock) { GrpcPreconditions.CheckState(startRequested); GrpcPreconditions.CheckState(!shutdownRequested); shutdownRequested = true; } handle.ShutdownAndNotify(HandleServerShutdown, environment); handle.CancelAllCalls(); await shutdownTcs.Task.ConfigureAwait(false); DisposeHandle(); await Task.Run(() => GrpcEnvironment.Release()).ConfigureAwait(false); } internal void AddCallReference(object call) { activeCallCounter.Increment(); bool success = false; handle.DangerousAddRef(ref success); GrpcPreconditions.CheckState(success); } internal void RemoveCallReference(object call) { handle.DangerousRelease(); activeCallCounter.Decrement(); } /// <summary> /// Adds a service definition. /// </summary> private void AddServiceDefinitionInternal(ServerServiceDefinition serviceDefinition) { lock (myLock) { GrpcPreconditions.CheckState(!startRequested); foreach (var entry in serviceDefinition.CallHandlers) { callHandlers.Add(entry.Key, entry.Value); } serviceDefinitionsList.Add(serviceDefinition); } } /// <summary> /// Adds a listening port. /// </summary> private int AddPortInternal(ServerPort serverPort) { lock (myLock) { GrpcPreconditions.CheckNotNull(serverPort.Credentials, "serverPort"); GrpcPreconditions.CheckState(!startRequested); var address = string.Format("{0}:{1}", serverPort.Host, serverPort.Port); int boundPort; using (var nativeCredentials = serverPort.Credentials.ToNativeCredentials()) { if (nativeCredentials != null) { boundPort = handle.AddSecurePort(address, nativeCredentials); } else { boundPort = handle.AddInsecurePort(address); } } var newServerPort = new ServerPort(serverPort, boundPort); this.serverPortList.Add(newServerPort); return boundPort; } } /// <summary> /// Allows one new RPC call to be received by server. /// </summary> private void AllowOneRpc() { lock (myLock) { if (!shutdownRequested) { handle.RequestCall(HandleNewServerRpc, environment); } } } private void DisposeHandle() { var activeCallCount = activeCallCounter.Count; if (activeCallCount > 0) { Logger.Warning("Server shutdown has finished but there are still {0} active calls for that server.", activeCallCount); } handle.Dispose(); } /// <summary> /// Selects corresponding handler for given call and handles the call. /// </summary> private async Task HandleCallAsync(ServerRpcNew newRpc) { try { IServerCallHandler callHandler; if (!callHandlers.TryGetValue(newRpc.Method, out callHandler)) { callHandler = NoSuchMethodCallHandler.Instance; } await callHandler.HandleCall(newRpc, environment).ConfigureAwait(false); } catch (Exception e) { Logger.Warning(e, "Exception while handling RPC."); } } /// <summary> /// Handles the native callback. /// </summary> private void HandleNewServerRpc(bool success, BatchContextSafeHandle ctx) { if (success) { ServerRpcNew newRpc = ctx.GetServerRpcNew(this); // after server shutdown, the callback returns with null call if (!newRpc.Call.IsInvalid) { Task.Run(async () => await HandleCallAsync(newRpc)).ConfigureAwait(false); } } AllowOneRpc(); } /// <summary> /// Handles native callback. /// </summary> private void HandleServerShutdown(bool success, BatchContextSafeHandle ctx) { shutdownTcs.SetResult(null); } /// <summary> /// Collection of service definitions. /// </summary> public class ServiceDefinitionCollection : IEnumerable<ServerServiceDefinition> { readonly Server server; internal ServiceDefinitionCollection(Server server) { this.server = server; } /// <summary> /// Adds a service definition to the server. This is how you register /// handlers for a service with the server. Only call this before Start(). /// </summary> public void Add(ServerServiceDefinition serviceDefinition) { server.AddServiceDefinitionInternal(serviceDefinition); } /// <summary> /// Gets enumerator for this collection. /// </summary> public IEnumerator<ServerServiceDefinition> GetEnumerator() { return server.serviceDefinitionsList.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return server.serviceDefinitionsList.GetEnumerator(); } } /// <summary> /// Collection of server ports. /// </summary> public class ServerPortCollection : IEnumerable<ServerPort> { readonly Server server; internal ServerPortCollection(Server server) { this.server = server; } /// <summary> /// Adds a new port on which server should listen. /// Only call this before Start(). /// <returns>The port on which server will be listening.</returns> /// </summary> public int Add(ServerPort serverPort) { return server.AddPortInternal(serverPort); } /// <summary> /// Adds a new port on which server should listen. /// <returns>The port on which server will be listening.</returns> /// </summary> /// <param name="host">the host</param> /// <param name="port">the port. If zero, an unused port is chosen automatically.</param> /// <param name="credentials">credentials to use to secure this port.</param> public int Add(string host, int port, ServerCredentials credentials) { return Add(new ServerPort(host, port, credentials)); } /// <summary> /// Gets enumerator for this collection. /// </summary> public IEnumerator<ServerPort> GetEnumerator() { return server.serverPortList.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return server.serverPortList.GetEnumerator(); } } } }
// 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.Globalization; using System.Runtime.InteropServices; using Xunit; namespace System.Numerics.Tests { public class Vector2Tests { [Fact] public void Vector2MarshalSizeTest() { Assert.Equal(8, Marshal.SizeOf<Vector2>()); Assert.Equal(8, Marshal.SizeOf<Vector2>(new Vector2())); } [Fact] public void Vector2CopyToTest() { Vector2 v1 = new Vector2(2.0f, 3.0f); float[] a = new float[3]; float[] b = new float[2]; Assert.Throws<NullReferenceException>(() => v1.CopyTo(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => v1.CopyTo(a, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => v1.CopyTo(a, a.Length)); if (!PlatformDetection.IsNetNative) { AssertExtensions.Throws<ArgumentException>(null, () => v1.CopyTo(a, 2)); } else { // The .Net Native code generation optimizer does aggressive optimizations to range checks // which result in an ArgumentOutOfRangeException exception being thrown at runtime. Assert.ThrowsAny<ArgumentException>(() => v1.CopyTo(a, 2)); } v1.CopyTo(a, 1); v1.CopyTo(b); Assert.Equal(0.0, a[0]); Assert.Equal(2.0, a[1]); Assert.Equal(3.0, a[2]); Assert.Equal(2.0, b[0]); Assert.Equal(3.0, b[1]); } [Fact] public void Vector2GetHashCodeTest() { Vector2 v1 = new Vector2(2.0f, 3.0f); Vector2 v2 = new Vector2(2.0f, 3.0f); Vector2 v3 = new Vector2(3.0f, 2.0f); Assert.Equal(v1.GetHashCode(), v1.GetHashCode()); Assert.Equal(v1.GetHashCode(), v2.GetHashCode()); Assert.NotEqual(v1.GetHashCode(), v3.GetHashCode()); Vector2 v4 = new Vector2(0.0f, 0.0f); Vector2 v6 = new Vector2(1.0f, 0.0f); Vector2 v7 = new Vector2(0.0f, 1.0f); Vector2 v8 = new Vector2(1.0f, 1.0f); Assert.NotEqual(v4.GetHashCode(), v6.GetHashCode()); Assert.NotEqual(v4.GetHashCode(), v7.GetHashCode()); Assert.NotEqual(v4.GetHashCode(), v8.GetHashCode()); Assert.NotEqual(v7.GetHashCode(), v6.GetHashCode()); Assert.NotEqual(v8.GetHashCode(), v6.GetHashCode()); Assert.NotEqual(v8.GetHashCode(), v7.GetHashCode()); } [Fact] public void Vector2ToStringTest() { string separator = CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator; CultureInfo enUsCultureInfo = new CultureInfo("en-US"); Vector2 v1 = new Vector2(2.0f, 3.0f); string v1str = v1.ToString(); string expectedv1 = string.Format(CultureInfo.CurrentCulture , "<{1:G}{0} {2:G}>" , new object[] { separator, 2, 3 }); Assert.Equal(expectedv1, v1str); string v1strformatted = v1.ToString("c", CultureInfo.CurrentCulture); string expectedv1formatted = string.Format(CultureInfo.CurrentCulture , "<{1:c}{0} {2:c}>" , new object[] { separator, 2, 3 }); Assert.Equal(expectedv1formatted, v1strformatted); string v2strformatted = v1.ToString("c", enUsCultureInfo); string expectedv2formatted = string.Format(enUsCultureInfo , "<{1:c}{0} {2:c}>" , new object[] { enUsCultureInfo.NumberFormat.NumberGroupSeparator, 2, 3 }); Assert.Equal(expectedv2formatted, v2strformatted); string v3strformatted = v1.ToString("c"); string expectedv3formatted = string.Format(CultureInfo.CurrentCulture , "<{1:c}{0} {2:c}>" , new object[] { separator, 2, 3 }); Assert.Equal(expectedv3formatted, v3strformatted); } // A test for Distance (Vector2f, Vector2f) [Fact] public void Vector2DistanceTest() { Vector2 a = new Vector2(1.0f, 2.0f); Vector2 b = new Vector2(3.0f, 4.0f); float expected = (float)System.Math.Sqrt(8); float actual; actual = Vector2.Distance(a, b); Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Distance did not return the expected value."); } // A test for Distance (Vector2f, Vector2f) // Distance from the same point [Fact] public void Vector2DistanceTest2() { Vector2 a = new Vector2(1.051f, 2.05f); Vector2 b = new Vector2(1.051f, 2.05f); float actual = Vector2.Distance(a, b); Assert.Equal(0.0f, actual); } // A test for DistanceSquared (Vector2f, Vector2f) [Fact] public void Vector2DistanceSquaredTest() { Vector2 a = new Vector2(1.0f, 2.0f); Vector2 b = new Vector2(3.0f, 4.0f); float expected = 8.0f; float actual; actual = Vector2.DistanceSquared(a, b); Assert.True(MathHelper.Equal(expected, actual), "Vector2f.DistanceSquared did not return the expected value."); } // A test for Dot (Vector2f, Vector2f) [Fact] public void Vector2DotTest() { Vector2 a = new Vector2(1.0f, 2.0f); Vector2 b = new Vector2(3.0f, 4.0f); float expected = 11.0f; float actual; actual = Vector2.Dot(a, b); Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Dot did not return the expected value."); } // A test for Dot (Vector2f, Vector2f) // Dot test for perpendicular vector [Fact] public void Vector2DotTest1() { Vector2 a = new Vector2(1.55f, 1.55f); Vector2 b = new Vector2(-1.55f, 1.55f); float expected = 0.0f; float actual = Vector2.Dot(a, b); Assert.Equal(expected, actual); } // A test for Dot (Vector2f, Vector2f) // Dot test with specail float values [Fact] public void Vector2DotTest2() { Vector2 a = new Vector2(float.MinValue, float.MinValue); Vector2 b = new Vector2(float.MaxValue, float.MaxValue); float actual = Vector2.Dot(a, b); Assert.True(float.IsNegativeInfinity(actual), "Vector2f.Dot did not return the expected value."); } // A test for Length () [Fact] public void Vector2LengthTest() { Vector2 a = new Vector2(2.0f, 4.0f); Vector2 target = a; float expected = (float)System.Math.Sqrt(20); float actual; actual = target.Length(); Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Length did not return the expected value."); } // A test for Length () // Length test where length is zero [Fact] public void Vector2LengthTest1() { Vector2 target = new Vector2(); target.X = 0.0f; target.Y = 0.0f; float expected = 0.0f; float actual; actual = target.Length(); Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Length did not return the expected value."); } // A test for LengthSquared () [Fact] public void Vector2LengthSquaredTest() { Vector2 a = new Vector2(2.0f, 4.0f); Vector2 target = a; float expected = 20.0f; float actual; actual = target.LengthSquared(); Assert.True(MathHelper.Equal(expected, actual), "Vector2f.LengthSquared did not return the expected value."); } // A test for LengthSquared () // LengthSquared test where the result is zero [Fact] public void Vector2LengthSquaredTest1() { Vector2 a = new Vector2(0.0f, 0.0f); float expected = 0.0f; float actual = a.LengthSquared(); Assert.Equal(expected, actual); } // A test for Min (Vector2f, Vector2f) [Fact] public void Vector2MinTest() { Vector2 a = new Vector2(-1.0f, 4.0f); Vector2 b = new Vector2(2.0f, 1.0f); Vector2 expected = new Vector2(-1.0f, 1.0f); Vector2 actual; actual = Vector2.Min(a, b); Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Min did not return the expected value."); } [Fact] public void Vector2MinMaxCodeCoverageTest() { Vector2 min = new Vector2(0, 0); Vector2 max = new Vector2(1, 1); Vector2 actual; // Min. actual = Vector2.Min(min, max); Assert.Equal(actual, min); actual = Vector2.Min(max, min); Assert.Equal(actual, min); // Max. actual = Vector2.Max(min, max); Assert.Equal(actual, max); actual = Vector2.Max(max, min); Assert.Equal(actual, max); } // A test for Max (Vector2f, Vector2f) [Fact] public void Vector2MaxTest() { Vector2 a = new Vector2(-1.0f, 4.0f); Vector2 b = new Vector2(2.0f, 1.0f); Vector2 expected = new Vector2(2.0f, 4.0f); Vector2 actual; actual = Vector2.Max(a, b); Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Max did not return the expected value."); } // A test for Clamp (Vector2f, Vector2f, Vector2f) [Fact] public void Vector2ClampTest() { Vector2 a = new Vector2(0.5f, 0.3f); Vector2 min = new Vector2(0.0f, 0.1f); Vector2 max = new Vector2(1.0f, 1.1f); // Normal case. // Case N1: specified value is in the range. Vector2 expected = new Vector2(0.5f, 0.3f); Vector2 actual = Vector2.Clamp(a, min, max); Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Clamp did not return the expected value."); // Normal case. // Case N2: specified value is bigger than max value. a = new Vector2(2.0f, 3.0f); expected = max; actual = Vector2.Clamp(a, min, max); Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Clamp did not return the expected value."); // Case N3: specified value is smaller than max value. a = new Vector2(-1.0f, -2.0f); expected = min; actual = Vector2.Clamp(a, min, max); Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Clamp did not return the expected value."); // Case N4: combination case. a = new Vector2(-2.0f, 4.0f); expected = new Vector2(min.X, max.Y); actual = Vector2.Clamp(a, min, max); Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Clamp did not return the expected value."); // User specified min value is bigger than max value. max = new Vector2(0.0f, 0.1f); min = new Vector2(1.0f, 1.1f); // Case W1: specified value is in the range. a = new Vector2(0.5f, 0.3f); expected = min; actual = Vector2.Clamp(a, min, max); Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Clamp did not return the expected value."); // Normal case. // Case W2: specified value is bigger than max and min value. a = new Vector2(2.0f, 3.0f); expected = min; actual = Vector2.Clamp(a, min, max); Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Clamp did not return the expected value."); // Case W3: specified value is smaller than min and max value. a = new Vector2(-1.0f, -2.0f); expected = min; actual = Vector2.Clamp(a, min, max); Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Clamp did not return the expected value."); } // A test for Lerp (Vector2f, Vector2f, float) [Fact] public void Vector2LerpTest() { Vector2 a = new Vector2(1.0f, 2.0f); Vector2 b = new Vector2(3.0f, 4.0f); float t = 0.5f; Vector2 expected = new Vector2(2.0f, 3.0f); Vector2 actual; actual = Vector2.Lerp(a, b, t); Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Lerp did not return the expected value."); } // A test for Lerp (Vector2f, Vector2f, float) // Lerp test with factor zero [Fact] public void Vector2LerpTest1() { Vector2 a = new Vector2(0.0f, 0.0f); Vector2 b = new Vector2(3.18f, 4.25f); float t = 0.0f; Vector2 expected = Vector2.Zero; Vector2 actual = Vector2.Lerp(a, b, t); Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Lerp did not return the expected value."); } // A test for Lerp (Vector2f, Vector2f, float) // Lerp test with factor one [Fact] public void Vector2LerpTest2() { Vector2 a = new Vector2(0.0f, 0.0f); Vector2 b = new Vector2(3.18f, 4.25f); float t = 1.0f; Vector2 expected = new Vector2(3.18f, 4.25f); Vector2 actual = Vector2.Lerp(a, b, t); Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Lerp did not return the expected value."); } // A test for Lerp (Vector2f, Vector2f, float) // Lerp test with factor > 1 [Fact] public void Vector2LerpTest3() { Vector2 a = new Vector2(0.0f, 0.0f); Vector2 b = new Vector2(3.18f, 4.25f); float t = 2.0f; Vector2 expected = b * 2.0f; Vector2 actual = Vector2.Lerp(a, b, t); Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Lerp did not return the expected value."); } // A test for Lerp (Vector2f, Vector2f, float) // Lerp test with factor < 0 [Fact] public void Vector2LerpTest4() { Vector2 a = new Vector2(0.0f, 0.0f); Vector2 b = new Vector2(3.18f, 4.25f); float t = -2.0f; Vector2 expected = -(b * 2.0f); Vector2 actual = Vector2.Lerp(a, b, t); Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Lerp did not return the expected value."); } // A test for Lerp (Vector2f, Vector2f, float) // Lerp test with special float value [Fact] public void Vector2LerpTest5() { Vector2 a = new Vector2(45.67f, 90.0f); Vector2 b = new Vector2(float.PositiveInfinity, float.NegativeInfinity); float t = 0.408f; Vector2 actual = Vector2.Lerp(a, b, t); Assert.True(float.IsPositiveInfinity(actual.X), "Vector2f.Lerp did not return the expected value."); Assert.True(float.IsNegativeInfinity(actual.Y), "Vector2f.Lerp did not return the expected value."); } // A test for Lerp (Vector2f, Vector2f, float) // Lerp test from the same point [Fact] public void Vector2LerpTest6() { Vector2 a = new Vector2(1.0f, 2.0f); Vector2 b = new Vector2(1.0f, 2.0f); float t = 0.5f; Vector2 expected = new Vector2(1.0f, 2.0f); Vector2 actual = Vector2.Lerp(a, b, t); Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Lerp did not return the expected value."); } // A test for Transform(Vector2f, Matrix4x4) [Fact] public void Vector2TransformTest() { Vector2 v = new Vector2(1.0f, 2.0f); Matrix4x4 m = Matrix4x4.CreateRotationX(MathHelper.ToRadians(30.0f)) * Matrix4x4.CreateRotationY(MathHelper.ToRadians(30.0f)) * Matrix4x4.CreateRotationZ(MathHelper.ToRadians(30.0f)); m.M41 = 10.0f; m.M42 = 20.0f; m.M43 = 30.0f; Vector2 expected = new Vector2(10.316987f, 22.183012f); Vector2 actual; actual = Vector2.Transform(v, m); Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Transform did not return the expected value."); } // A test for Transform(Vector2f, Matrix3x2) [Fact] public void Vector2Transform3x2Test() { Vector2 v = new Vector2(1.0f, 2.0f); Matrix3x2 m = Matrix3x2.CreateRotation(MathHelper.ToRadians(30.0f)); m.M31 = 10.0f; m.M32 = 20.0f; Vector2 expected = new Vector2(9.866025f, 22.23205f); Vector2 actual; actual = Vector2.Transform(v, m); Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Transform did not return the expected value."); } // A test for TransformNormal (Vector2f, Matrix4x4) [Fact] public void Vector2TransformNormalTest() { Vector2 v = new Vector2(1.0f, 2.0f); Matrix4x4 m = Matrix4x4.CreateRotationX(MathHelper.ToRadians(30.0f)) * Matrix4x4.CreateRotationY(MathHelper.ToRadians(30.0f)) * Matrix4x4.CreateRotationZ(MathHelper.ToRadians(30.0f)); m.M41 = 10.0f; m.M42 = 20.0f; m.M43 = 30.0f; Vector2 expected = new Vector2(0.3169873f, 2.18301272f); Vector2 actual; actual = Vector2.TransformNormal(v, m); Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Tranform did not return the expected value."); } // A test for TransformNormal (Vector2f, Matrix3x2) [Fact] public void Vector2TransformNormal3x2Test() { Vector2 v = new Vector2(1.0f, 2.0f); Matrix3x2 m = Matrix3x2.CreateRotation(MathHelper.ToRadians(30.0f)); m.M31 = 10.0f; m.M32 = 20.0f; Vector2 expected = new Vector2(-0.133974612f, 2.232051f); Vector2 actual; actual = Vector2.TransformNormal(v, m); Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Transform did not return the expected value."); } // A test for Transform (Vector2f, Quaternion) [Fact] public void Vector2TransformByQuaternionTest() { Vector2 v = new Vector2(1.0f, 2.0f); Matrix4x4 m = Matrix4x4.CreateRotationX(MathHelper.ToRadians(30.0f)) * Matrix4x4.CreateRotationY(MathHelper.ToRadians(30.0f)) * Matrix4x4.CreateRotationZ(MathHelper.ToRadians(30.0f)); Quaternion q = Quaternion.CreateFromRotationMatrix(m); Vector2 expected = Vector2.Transform(v, m); Vector2 actual = Vector2.Transform(v, q); Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Transform did not return the expected value."); } // A test for Transform (Vector2f, Quaternion) // Transform Vector2f with zero quaternion [Fact] public void Vector2TransformByQuaternionTest1() { Vector2 v = new Vector2(1.0f, 2.0f); Quaternion q = new Quaternion(); Vector2 expected = v; Vector2 actual = Vector2.Transform(v, q); Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Transform did not return the expected value."); } // A test for Transform (Vector2f, Quaternion) // Transform Vector2f with identity quaternion [Fact] public void Vector2TransformByQuaternionTest2() { Vector2 v = new Vector2(1.0f, 2.0f); Quaternion q = Quaternion.Identity; Vector2 expected = v; Vector2 actual = Vector2.Transform(v, q); Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Transform did not return the expected value."); } // A test for Normalize (Vector2f) [Fact] public void Vector2NormalizeTest() { Vector2 a = new Vector2(2.0f, 3.0f); Vector2 expected = new Vector2(0.554700196225229122018341733457f, 0.8320502943378436830275126001855f); Vector2 actual; actual = Vector2.Normalize(a); Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Normalize did not return the expected value."); } // A test for Normalize (Vector2f) // Normalize zero length vector [Fact] public void Vector2NormalizeTest1() { Vector2 a = new Vector2(); // no parameter, default to 0.0f Vector2 actual = Vector2.Normalize(a); Assert.True(float.IsNaN(actual.X) && float.IsNaN(actual.Y), "Vector2f.Normalize did not return the expected value."); } // A test for Normalize (Vector2f) // Normalize infinite length vector [Fact] public void Vector2NormalizeTest2() { Vector2 a = new Vector2(float.MaxValue, float.MaxValue); Vector2 actual = Vector2.Normalize(a); Vector2 expected = new Vector2(0, 0); Assert.Equal(expected, actual); } // A test for operator - (Vector2f) [Fact] public void Vector2UnaryNegationTest() { Vector2 a = new Vector2(1.0f, 2.0f); Vector2 expected = new Vector2(-1.0f, -2.0f); Vector2 actual; actual = -a; Assert.True(MathHelper.Equal(expected, actual), "Vector2f.operator - did not return the expected value."); } // A test for operator - (Vector2f) // Negate test with special float value [Fact] public void Vector2UnaryNegationTest1() { Vector2 a = new Vector2(float.PositiveInfinity, float.NegativeInfinity); Vector2 actual = -a; Assert.True(float.IsNegativeInfinity(actual.X), "Vector2f.operator - did not return the expected value."); Assert.True(float.IsPositiveInfinity(actual.Y), "Vector2f.operator - did not return the expected value."); } // A test for operator - (Vector2f) // Negate test with special float value [Fact] public void Vector2UnaryNegationTest2() { Vector2 a = new Vector2(float.NaN, 0.0f); Vector2 actual = -a; Assert.True(float.IsNaN(actual.X), "Vector2f.operator - did not return the expected value."); Assert.True(float.Equals(0.0f, actual.Y), "Vector2f.operator - did not return the expected value."); } // A test for operator - (Vector2f, Vector2f) [Fact] public void Vector2SubtractionTest() { Vector2 a = new Vector2(1.0f, 3.0f); Vector2 b = new Vector2(2.0f, 1.5f); Vector2 expected = new Vector2(-1.0f, 1.5f); Vector2 actual; actual = a - b; Assert.True(MathHelper.Equal(expected, actual), "Vector2f.operator - did not return the expected value."); } // A test for operator * (Vector2f, float) [Fact] public void Vector2MultiplyOperatorTest() { Vector2 a = new Vector2(2.0f, 3.0f); const float factor = 2.0f; Vector2 expected = new Vector2(4.0f, 6.0f); Vector2 actual; actual = a * factor; Assert.True(MathHelper.Equal(expected, actual), "Vector2f.operator * did not return the expected value."); } // A test for operator * (float, Vector2f) [Fact] public void Vector2MultiplyOperatorTest2() { Vector2 a = new Vector2(2.0f, 3.0f); const float factor = 2.0f; Vector2 expected = new Vector2(4.0f, 6.0f); Vector2 actual; actual = factor * a; Assert.True(MathHelper.Equal(expected, actual), "Vector2f.operator * did not return the expected value."); } // A test for operator * (Vector2f, Vector2f) [Fact] public void Vector2MultiplyOperatorTest3() { Vector2 a = new Vector2(2.0f, 3.0f); Vector2 b = new Vector2(4.0f, 5.0f); Vector2 expected = new Vector2(8.0f, 15.0f); Vector2 actual; actual = a * b; Assert.True(MathHelper.Equal(expected, actual), "Vector2f.operator * did not return the expected value."); } // A test for operator / (Vector2f, float) [Fact] public void Vector2DivisionTest() { Vector2 a = new Vector2(2.0f, 3.0f); float div = 2.0f; Vector2 expected = new Vector2(1.0f, 1.5f); Vector2 actual; actual = a / div; Assert.True(MathHelper.Equal(expected, actual), "Vector2f.operator / did not return the expected value."); } // A test for operator / (Vector2f, Vector2f) [Fact] public void Vector2DivisionTest1() { Vector2 a = new Vector2(2.0f, 3.0f); Vector2 b = new Vector2(4.0f, 5.0f); Vector2 expected = new Vector2(2.0f / 4.0f, 3.0f / 5.0f); Vector2 actual; actual = a / b; Assert.True(MathHelper.Equal(expected, actual), "Vector2f.operator / did not return the expected value."); } // A test for operator / (Vector2f, float) // Divide by zero [Fact] public void Vector2DivisionTest2() { Vector2 a = new Vector2(-2.0f, 3.0f); float div = 0.0f; Vector2 actual = a / div; Assert.True(float.IsNegativeInfinity(actual.X), "Vector2f.operator / did not return the expected value."); Assert.True(float.IsPositiveInfinity(actual.Y), "Vector2f.operator / did not return the expected value."); } // A test for operator / (Vector2f, Vector2f) // Divide by zero [Fact] public void Vector2DivisionTest3() { Vector2 a = new Vector2(0.047f, -3.0f); Vector2 b = new Vector2(); Vector2 actual = a / b; Assert.True(float.IsInfinity(actual.X), "Vector2f.operator / did not return the expected value."); Assert.True(float.IsInfinity(actual.Y), "Vector2f.operator / did not return the expected value."); } // A test for operator + (Vector2f, Vector2f) [Fact] public void Vector2AdditionTest() { Vector2 a = new Vector2(1.0f, 2.0f); Vector2 b = new Vector2(3.0f, 4.0f); Vector2 expected = new Vector2(4.0f, 6.0f); Vector2 actual; actual = a + b; Assert.True(MathHelper.Equal(expected, actual), "Vector2f.operator + did not return the expected value."); } // A test for Vector2f (float, float) [Fact] public void Vector2ConstructorTest() { float x = 1.0f; float y = 2.0f; Vector2 target = new Vector2(x, y); Assert.True(MathHelper.Equal(target.X, x) && MathHelper.Equal(target.Y, y), "Vector2f(x,y) constructor did not return the expected value."); } // A test for Vector2f () // Constructor with no parameter [Fact] public void Vector2ConstructorTest2() { Vector2 target = new Vector2(); Assert.Equal(target.X, 0.0f); Assert.Equal(target.Y, 0.0f); } // A test for Vector2f (float, float) // Constructor with special floating values [Fact] public void Vector2ConstructorTest3() { Vector2 target = new Vector2(float.NaN, float.MaxValue); Assert.Equal(target.X, float.NaN); Assert.Equal(target.Y, float.MaxValue); } // A test for Vector2f (float) [Fact] public void Vector2ConstructorTest4() { float value = 1.0f; Vector2 target = new Vector2(value); Vector2 expected = new Vector2(value, value); Assert.Equal(expected, target); value = 2.0f; target = new Vector2(value); expected = new Vector2(value, value); Assert.Equal(expected, target); } // A test for Add (Vector2f, Vector2f) [Fact] public void Vector2AddTest() { Vector2 a = new Vector2(1.0f, 2.0f); Vector2 b = new Vector2(5.0f, 6.0f); Vector2 expected = new Vector2(6.0f, 8.0f); Vector2 actual; actual = Vector2.Add(a, b); Assert.Equal(expected, actual); } // A test for Divide (Vector2f, float) [Fact] public void Vector2DivideTest() { Vector2 a = new Vector2(1.0f, 2.0f); float div = 2.0f; Vector2 expected = new Vector2(0.5f, 1.0f); Vector2 actual; actual = Vector2.Divide(a, div); Assert.Equal(expected, actual); } // A test for Divide (Vector2f, Vector2f) [Fact] public void Vector2DivideTest1() { Vector2 a = new Vector2(1.0f, 6.0f); Vector2 b = new Vector2(5.0f, 2.0f); Vector2 expected = new Vector2(1.0f / 5.0f, 6.0f / 2.0f); Vector2 actual; actual = Vector2.Divide(a, b); Assert.Equal(expected, actual); } // A test for Equals (object) [Fact] public void Vector2EqualsTest() { Vector2 a = new Vector2(1.0f, 2.0f); Vector2 b = new Vector2(1.0f, 2.0f); // case 1: compare between same values object obj = b; bool expected = true; bool actual = a.Equals(obj); Assert.Equal(expected, actual); // case 2: compare between different values b.X = 10.0f; obj = b; expected = false; actual = a.Equals(obj); Assert.Equal(expected, actual); // case 3: compare between different types. obj = new Quaternion(); expected = false; actual = a.Equals(obj); Assert.Equal(expected, actual); // case 3: compare against null. obj = null; expected = false; actual = a.Equals(obj); Assert.Equal(expected, actual); } // A test for Multiply (Vector2f, float) [Fact] public void Vector2MultiplyTest() { Vector2 a = new Vector2(1.0f, 2.0f); const float factor = 2.0f; Vector2 expected = new Vector2(2.0f, 4.0f); Vector2 actual = Vector2.Multiply(a, factor); Assert.Equal(expected, actual); } // A test for Multiply (float, Vector2f) [Fact] public void Vector2MultiplyTest2() { Vector2 a = new Vector2(1.0f, 2.0f); const float factor = 2.0f; Vector2 expected = new Vector2(2.0f, 4.0f); Vector2 actual = Vector2.Multiply(factor, a); Assert.Equal(expected, actual); } // A test for Multiply (Vector2f, Vector2f) [Fact] public void Vector2MultiplyTest3() { Vector2 a = new Vector2(1.0f, 2.0f); Vector2 b = new Vector2(5.0f, 6.0f); Vector2 expected = new Vector2(5.0f, 12.0f); Vector2 actual; actual = Vector2.Multiply(a, b); Assert.Equal(expected, actual); } // A test for Negate (Vector2f) [Fact] public void Vector2NegateTest() { Vector2 a = new Vector2(1.0f, 2.0f); Vector2 expected = new Vector2(-1.0f, -2.0f); Vector2 actual; actual = Vector2.Negate(a); Assert.Equal(expected, actual); } // A test for operator != (Vector2f, Vector2f) [Fact] public void Vector2InequalityTest() { Vector2 a = new Vector2(1.0f, 2.0f); Vector2 b = new Vector2(1.0f, 2.0f); // case 1: compare between same values bool expected = false; bool actual = a != b; Assert.Equal(expected, actual); // case 2: compare between different values b.X = 10.0f; expected = true; actual = a != b; Assert.Equal(expected, actual); } // A test for operator == (Vector2f, Vector2f) [Fact] public void Vector2EqualityTest() { Vector2 a = new Vector2(1.0f, 2.0f); Vector2 b = new Vector2(1.0f, 2.0f); // case 1: compare between same values bool expected = true; bool actual = a == b; Assert.Equal(expected, actual); // case 2: compare between different values b.X = 10.0f; expected = false; actual = a == b; Assert.Equal(expected, actual); } // A test for Subtract (Vector2f, Vector2f) [Fact] public void Vector2SubtractTest() { Vector2 a = new Vector2(1.0f, 6.0f); Vector2 b = new Vector2(5.0f, 2.0f); Vector2 expected = new Vector2(-4.0f, 4.0f); Vector2 actual; actual = Vector2.Subtract(a, b); Assert.Equal(expected, actual); } // A test for UnitX [Fact] public void Vector2UnitXTest() { Vector2 val = new Vector2(1.0f, 0.0f); Assert.Equal(val, Vector2.UnitX); } // A test for UnitY [Fact] public void Vector2UnitYTest() { Vector2 val = new Vector2(0.0f, 1.0f); Assert.Equal(val, Vector2.UnitY); } // A test for One [Fact] public void Vector2OneTest() { Vector2 val = new Vector2(1.0f, 1.0f); Assert.Equal(val, Vector2.One); } // A test for Zero [Fact] public void Vector2ZeroTest() { Vector2 val = new Vector2(0.0f, 0.0f); Assert.Equal(val, Vector2.Zero); } // A test for Equals (Vector2f) [Fact] public void Vector2EqualsTest1() { Vector2 a = new Vector2(1.0f, 2.0f); Vector2 b = new Vector2(1.0f, 2.0f); // case 1: compare between same values bool expected = true; bool actual = a.Equals(b); Assert.Equal(expected, actual); // case 2: compare between different values b.X = 10.0f; expected = false; actual = a.Equals(b); Assert.Equal(expected, actual); } // A test for Vector2f comparison involving NaN values [Fact] public void Vector2EqualsNanTest() { Vector2 a = new Vector2(float.NaN, 0); Vector2 b = new Vector2(0, float.NaN); Assert.False(a == Vector2.Zero); Assert.False(b == Vector2.Zero); Assert.True(a != Vector2.Zero); Assert.True(b != Vector2.Zero); Assert.False(a.Equals(Vector2.Zero)); Assert.False(b.Equals(Vector2.Zero)); // Counterintuitive result - IEEE rules for NaN comparison are weird! Assert.False(a.Equals(a)); Assert.False(b.Equals(b)); } // A test for Reflect (Vector2f, Vector2f) [Fact] public void Vector2ReflectTest() { Vector2 a = Vector2.Normalize(new Vector2(1.0f, 1.0f)); // Reflect on XZ plane. Vector2 n = new Vector2(0.0f, 1.0f); Vector2 expected = new Vector2(a.X, -a.Y); Vector2 actual = Vector2.Reflect(a, n); Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Reflect did not return the expected value."); // Reflect on XY plane. n = new Vector2(0.0f, 0.0f); expected = new Vector2(a.X, a.Y); actual = Vector2.Reflect(a, n); Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Reflect did not return the expected value."); // Reflect on YZ plane. n = new Vector2(1.0f, 0.0f); expected = new Vector2(-a.X, a.Y); actual = Vector2.Reflect(a, n); Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Reflect did not return the expected value."); } // A test for Reflect (Vector2f, Vector2f) // Reflection when normal and source are the same [Fact] public void Vector2ReflectTest1() { Vector2 n = new Vector2(0.45f, 1.28f); n = Vector2.Normalize(n); Vector2 a = n; Vector2 expected = -n; Vector2 actual = Vector2.Reflect(a, n); Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Reflect did not return the expected value."); } // A test for Reflect (Vector2f, Vector2f) // Reflection when normal and source are negation [Fact] public void Vector2ReflectTest2() { Vector2 n = new Vector2(0.45f, 1.28f); n = Vector2.Normalize(n); Vector2 a = -n; Vector2 expected = n; Vector2 actual = Vector2.Reflect(a, n); Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Reflect did not return the expected value."); } [Fact] public void Vector2AbsTest() { Vector2 v1 = new Vector2(-2.5f, 2.0f); Vector2 v3 = Vector2.Abs(new Vector2(0.0f, Single.NegativeInfinity)); Vector2 v = Vector2.Abs(v1); Assert.Equal(2.5f, v.X); Assert.Equal(2.0f, v.Y); Assert.Equal(0.0f, v3.X); Assert.Equal(Single.PositiveInfinity, v3.Y); } [Fact] public void Vector2SqrtTest() { Vector2 v1 = new Vector2(-2.5f, 2.0f); Vector2 v2 = new Vector2(5.5f, 4.5f); Assert.Equal(2, (int)Vector2.SquareRoot(v2).X); Assert.Equal(2, (int)Vector2.SquareRoot(v2).Y); Assert.Equal(Single.NaN, Vector2.SquareRoot(v1).X); } // A test to make sure these types are blittable directly into GPU buffer memory layouts [Fact] public unsafe void Vector2SizeofTest() { Assert.Equal(8, sizeof(Vector2)); Assert.Equal(16, sizeof(Vector2_2x)); Assert.Equal(12, sizeof(Vector2PlusFloat)); Assert.Equal(24, sizeof(Vector2PlusFloat_2x)); } [StructLayout(LayoutKind.Sequential)] struct Vector2_2x { private Vector2 _a; private Vector2 _b; } [StructLayout(LayoutKind.Sequential)] struct Vector2PlusFloat { private Vector2 _v; private float _f; } [StructLayout(LayoutKind.Sequential)] struct Vector2PlusFloat_2x { private Vector2PlusFloat _a; private Vector2PlusFloat _b; } [Fact] public void SetFieldsTest() { Vector2 v3 = new Vector2(4f, 5f); v3.X = 1.0f; v3.Y = 2.0f; Assert.Equal(1.0f, v3.X); Assert.Equal(2.0f, v3.Y); Vector2 v4 = v3; v4.Y = 0.5f; Assert.Equal(1.0f, v4.X); Assert.Equal(0.5f, v4.Y); Assert.Equal(2.0f, v3.Y); } [Fact] public void EmbeddedVectorSetFields() { EmbeddedVectorObject evo = new EmbeddedVectorObject(); evo.FieldVector.X = 5.0f; evo.FieldVector.Y = 5.0f; Assert.Equal(5.0f, evo.FieldVector.X); Assert.Equal(5.0f, evo.FieldVector.Y); } private class EmbeddedVectorObject { public Vector2 FieldVector; } } }
// Copyright (c) 2011-2015 SIL International // This software is licensed under the MIT License (http://opensource.org/licenses/MIT) using System; using System.Collections.Generic; using System.Drawing; using System.Globalization; using System.Linq; using System.Windows.Forms; using Palaso.Reporting; using Palaso.WritingSystems; using Palaso.UI.WindowsForms.Keyboarding.Interfaces; using Palaso.UI.WindowsForms.Keyboarding.InternalInterfaces; #if __MonoCS__ using Palaso.UI.WindowsForms.Keyboarding.Linux; #else using Palaso.UI.WindowsForms.Keyboarding.Windows; #endif using Palaso.UI.WindowsForms.Keyboarding.Types; namespace Palaso.UI.WindowsForms.Keyboarding { /// <summary> /// Singleton class with methods for registering different keyboarding engines (e.g. Windows /// system, Keyman, XKB, IBus keyboards), and activating keyboards. /// Clients have to call KeyboardController.Initialize() before they can start using the /// keyboarding functionality, and they have to call KeyboardController.Shutdown() before /// the application or the unit test exits. /// </summary> public static class KeyboardController { #region Nested Manager class /// <summary> /// Allows setting different keyboard adapters which is needed for tests. Also allows /// registering keyboard layouts. /// </summary> public static class Manager { /// <summary> /// Sets the available keyboard adaptors. Note that if this is called more than once, the adapters /// installed previously will be closed and no longer useable. Do not pass adapter instances that have been /// previously passed. At least one adapter must be of type System. /// </summary> public static void SetKeyboardAdaptors(IKeyboardAdaptor[] adaptors) { if (!(Keyboard.Controller is IKeyboardControllerImpl)) Keyboard.Controller = new KeyboardControllerImpl(); Instance.Keyboards.Clear(); // InitializeAdaptors below will fill it in again. if (Adaptors != null) { foreach (var adaptor in Adaptors) adaptor.Close(); } Adaptors = adaptors; InitializeAdaptors(); } /// <summary> /// Resets the keyboard adaptors to the default ones. /// </summary> public static void Reset() { SetKeyboardAdaptors(new IKeyboardAdaptor[] { #if __MonoCS__ new XkbKeyboardAdaptor(), new IbusKeyboardAdaptor(), new CombinedKeyboardAdaptor(), new CinnamonIbusAdaptor() #else new WinKeyboardAdaptor(), new KeymanKeyboardAdaptor(), #endif }); } public static void InitializeAdaptors() { // this will also populate m_keyboards foreach (var adaptor in Adaptors) adaptor.Initialize(); } /// <summary> /// Adds a keyboard to the list of installed keyboards /// </summary> /// <param name='description'>Keyboard description object</param> public static void RegisterKeyboard(IKeyboardDefinition description) { if (!Instance.Keyboards.Contains(description)) Instance.Keyboards.Add(description); } internal static void ClearAllKeyboards() { Instance.Keyboards.Clear(); } } #endregion #region Class KeyboardControllerImpl private sealed class KeyboardControllerImpl : IKeyboardController, IKeyboardControllerImpl, IDisposable { private List<string> LanguagesAlreadyShownKeyboardNotFoundMessages { get; set; } private IKeyboardDefinition m_ActiveKeyboard; public KeyboardCollection Keyboards { get; private set; } public Dictionary<Control, object> EventHandlers { get; private set; } public event RegisterEventHandler ControlAdded; public event ControlEventHandler ControlRemoving; public KeyboardControllerImpl() { Keyboards = new KeyboardCollection(); EventHandlers = new Dictionary<Control, object>(); LanguagesAlreadyShownKeyboardNotFoundMessages = new List<string>(); } public void UpdateAvailableKeyboards() { Keyboards.Clear(); foreach (var adapter in Adaptors) adapter.UpdateAvailableKeyboards(); } #region Disposable stuff #if DEBUG /// <summary/> ~KeyboardControllerImpl() { Dispose(false); } #endif /// <summary/> public bool IsDisposed { get; private set; } /// <summary/> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary/> private void Dispose(bool fDisposing) { System.Diagnostics.Debug.WriteLineIf(!fDisposing, "****** Missing Dispose() call for " + GetType() + ". *******"); if (fDisposing && !IsDisposed) { // dispose managed and unmanaged objects if (Adaptors != null) { foreach (var adaptor in Adaptors) adaptor.Close(); Adaptors = null; } } IsDisposed = true; } #endregion public IKeyboardDefinition DefaultKeyboard { get { var defaultKbd = Adaptors.First(adaptor => adaptor.Type == KeyboardType.System).DefaultKeyboard; #if __MonoCS__ if (defaultKbd == null && CinnamonKeyboardHandling) { CinnamonIbusAdaptor cinn = Adaptors.First(adaptor => adaptor is CinnamonIbusAdaptor) as CinnamonIbusAdaptor; defaultKbd = cinn.DefaultKeyboard; } #endif return defaultKbd; } } public IKeyboardDefinition GetKeyboard(string layoutNameWithLocale) { if (string.IsNullOrEmpty(layoutNameWithLocale)) return KeyboardDescription.Zero; if (Keyboards.Contains(layoutNameWithLocale)) return Keyboards[layoutNameWithLocale]; var parts = layoutNameWithLocale.Split('|'); if (parts.Length == 2) { // This is the way Paratext stored IDs in 7.4-7.5 while there was a temporary bug-fix in place) return GetKeyboard(parts[0], parts[1]); } // Handle old Palaso IDs parts = layoutNameWithLocale.Split('-'); if (parts.Length > 1) { for (int i = 1; i < parts.Length; i++) { var kb = GetKeyboard(string.Join("-", parts.Take(i)), string.Join("-", parts.Skip(i))); if (!kb.Equals(KeyboardDescription.Zero)) return kb; } } return KeyboardDescription.Zero; } public IKeyboardDefinition GetKeyboard(string layoutName, string locale) { if (string.IsNullOrEmpty(layoutName) && string.IsNullOrEmpty(locale)) return KeyboardDescription.Zero; if (Keyboards.Contains(layoutName, locale)) return Keyboards[layoutName, locale]; return KeyboardDescription.Zero; } /// <summary> /// Tries to get the keyboard for the specified <paramref name="writingSystem"/>. /// </summary> /// <returns> /// Returns <c>KeyboardDescription.Zero</c> if no keyboard can be found. /// </returns> public IKeyboardDefinition GetKeyboard(IWritingSystemDefinition writingSystem) { if (writingSystem == null) return KeyboardDescription.Zero; return writingSystem.LocalKeyboard ?? KeyboardDescription.Zero; } public IKeyboardDefinition GetKeyboard(IInputLanguage language) { // NOTE: on Windows InputLanguage.LayoutName returns a wrong name in some cases. // Therefore we need this overload so that we can identify the keyboard correctly. return Keyboards .Where(keyboard => keyboard is KeyboardDescription && ((KeyboardDescription)keyboard).InputLanguage != null && ((KeyboardDescription)keyboard).InputLanguage.Equals(language)) .DefaultIfEmpty(KeyboardDescription.Zero) .First(); } /// <summary> /// Sets the keyboard. /// </summary> /// <param name='layoutName'>Keyboard layout name</param> public void SetKeyboard(string layoutName) { var keyboard = GetKeyboard(layoutName); if (keyboard.Equals(KeyboardDescription.Zero)) { if (!LanguagesAlreadyShownKeyboardNotFoundMessages.Contains(layoutName)) { LanguagesAlreadyShownKeyboardNotFoundMessages.Add(layoutName); ErrorReport.NotifyUserOfProblem(new ShowOncePerSessionBasedOnExactMessagePolicy(), "Could not find a keyboard ime that had a keyboard named '{0}'", layoutName); } return; } SetKeyboard(keyboard); } public void SetKeyboard(string layoutName, string locale) { SetKeyboard(GetKeyboard(layoutName, locale)); } public void SetKeyboard(IWritingSystemDefinition writingSystem) { SetKeyboard(writingSystem.LocalKeyboard); } public void SetKeyboard(IInputLanguage language) { SetKeyboard(GetKeyboard(language)); } public void SetKeyboard(IKeyboardDefinition keyboard) { keyboard.Activate(); } /// <summary> /// Activates the keyboard of the default input language /// </summary> public void ActivateDefaultKeyboard() { if (CinnamonKeyboardHandling) { #if __MonoCS__ CinnamonIbusAdaptor cinn = Adaptors.First(adaptor => adaptor is CinnamonIbusAdaptor) as CinnamonIbusAdaptor; cinn.ActivateDefaultKeyboard(); #endif } else { SetKeyboard(DefaultKeyboard); } } /// <summary> /// Returns everything that is installed on the system and available to be used. /// This would typically be used to populate a list of available keyboards in configuring a writing system. /// </summary> public IEnumerable<IKeyboardDefinition> AllAvailableKeyboards { get { return Keyboards; } } /// <summary> /// Creates and returns a keyboard definition object based on the layout and locale. /// </summary> public IKeyboardDefinition CreateKeyboardDefinition(string layout, string locale) { var existingKeyboard = AllAvailableKeyboards.FirstOrDefault(keyboard => keyboard.Layout == layout && keyboard.Locale == locale); return existingKeyboard ?? Adaptors.First(adaptor => adaptor.Type == KeyboardType.System) .CreateKeyboardDefinition(layout, locale); } /// <summary> /// Gets or sets the currently active keyboard /// </summary> public IKeyboardDefinition ActiveKeyboard { get { if (m_ActiveKeyboard == null) { m_ActiveKeyboard = Adaptors.First(adaptor => adaptor.Type == KeyboardType.System).ActiveKeyboard; if (m_ActiveKeyboard == null) { try { var lang = InputLanguage.CurrentInputLanguage; m_ActiveKeyboard = GetKeyboard(lang.LayoutName, lang.Culture.Name); } catch (CultureNotFoundException) { } } if (m_ActiveKeyboard == null) m_ActiveKeyboard = KeyboardDescription.Zero; } return m_ActiveKeyboard; } set { m_ActiveKeyboard = value; } } /// <summary> /// Figures out the system default keyboard for the specified writing system (the one to use if we have no available KnownKeyboards). /// The implementation may use obsolete fields such as Keyboard /// </summary> public IKeyboardDefinition DefaultForWritingSystem(IWritingSystemDefinition ws) { return LegacyForWritingSystem(ws) ?? DefaultKeyboard; } /// <summary> /// Finds a keyboard specified using one of the legacy fields. If such a keyboard is found, it is appropriate to /// automatically add it to KnownKeyboards. If one is not, a general DefaultKeyboard should NOT be added. /// </summary> /// <param name="ws"></param> /// <returns></returns> public IKeyboardDefinition LegacyForWritingSystem(IWritingSystemDefinition ws) { var legacyWs = ws as ILegacyWritingSystemDefinition; if (legacyWs == null) return DefaultKeyboard; return LegacyKeyboardHandling.GetKeyboardFromLegacyWritingSystem(legacyWs, this); } /// <summary> /// Registers the control for keyboarding. Called by KeyboardController.Register. /// </summary> public void RegisterControl(Control control, object eventHandler) { EventHandlers[control] = eventHandler; if (ControlAdded != null) ControlAdded(this, new RegisterEventArgs(control, eventHandler)); } /// <summary> /// Unregisters the control from keyboarding. Called by KeyboardController.Unregister. /// </summary> /// <param name="control">Control.</param> public void UnregisterControl(Control control) { if (ControlRemoving != null) ControlRemoving(this, new ControlEventArgs(control)); EventHandlers.Remove(control); } #region Legacy keyboard handling private static class LegacyKeyboardHandling { public static IKeyboardDefinition GetKeyboardFromLegacyWritingSystem(ILegacyWritingSystemDefinition ws, KeyboardControllerImpl controller) { if (!string.IsNullOrEmpty(ws.WindowsLcid)) { var keyboard = HandleFwLegacyKeyboards(ws, controller); if (keyboard != null) return keyboard; } if (!string.IsNullOrEmpty(ws.Keyboard)) { if (controller.Keyboards.Contains(ws.Keyboard)) return controller.Keyboards[ws.Keyboard]; // Palaso WinIME keyboard var locale = GetLocaleName(ws.Keyboard); var layout = GetLayoutName(ws.Keyboard); if (controller.Keyboards.Contains(layout, locale)) return controller.Keyboards[layout, locale]; // Palaso Keyman or Ibus keyboard var keyboard = controller.Keyboards.FirstOrDefault(kbd => kbd.Layout == layout); if (keyboard != null) return keyboard; } return null; } private static IKeyboardDefinition HandleFwLegacyKeyboards(ILegacyWritingSystemDefinition ws, KeyboardControllerImpl controller) { var lcid = GetLcid(ws); if (lcid >= 0) { try { if (string.IsNullOrEmpty(ws.Keyboard)) { // FW system keyboard var keyboard = controller.Keyboards.FirstOrDefault( kbd => { var keyboardDescription = kbd as KeyboardDescription; if (keyboardDescription == null || keyboardDescription.InputLanguage == null || keyboardDescription.InputLanguage.Culture == null) return false; return keyboardDescription.InputLanguage.Culture.LCID == lcid; }); if (keyboard != null) return keyboard; } else { // FW keyman keyboard var culture = new CultureInfo(lcid); if (controller.Keyboards.Contains(ws.Keyboard, culture.Name)) return controller.Keyboards[ws.Keyboard, culture.Name]; } } catch (CultureNotFoundException) { // Culture specified by LCID is not supported on current system. Just ignore. } } return null; } private static int GetLcid(ILegacyWritingSystemDefinition ws) { int lcid; if (!Int32.TryParse(ws.WindowsLcid, out lcid)) lcid = -1; // can't convert ws.WindowsLcid to a valid LCID. Just ignore. return lcid; } private static string GetLocaleName(string name) { var split = name.Split(new[] { '-' }); string localeName; if (split.Length <= 1) { localeName = string.Empty; } else if (split.Length > 1 && split.Length <= 3) { localeName = string.Join("-", split.Skip(1).ToArray()); } else { localeName = string.Join("-", split.Skip(split.Length - 2).ToArray()); } return localeName; } private static string GetLayoutName(string name) { //Just cut off the length of the locale + 1 for the dash var locale = GetLocaleName(name); if (string.IsNullOrEmpty(locale)) { return name; } var layoutName = name.Substring(0, name.Length - (locale.Length + 1)); return layoutName; } } #endregion } #endregion #region Static methods and properties /// <summary> /// Gets the current keyboard controller singleton. /// </summary> private static IKeyboardControllerImpl Instance { get { return Keyboard.Controller as IKeyboardControllerImpl; } } /// <summary> /// Enables the PalasoUIWinForms keyboarding. This should be called during application startup. /// </summary> public static void Initialize() { // Note: arguably it is undesirable to install this as the public keyboard controller before we initialize it // (the Reset call). However, we have not in general attempted thread safety for the keyboarding code; it seems // highly unlikely that any but the UI thread wants to manipulate keyboards. Apart from other threads, nothing // has a chance to access this before we return. If initialization does not complete successfully, we clear the // global. try { Keyboard.Controller = new KeyboardControllerImpl(); Manager.Reset(); } catch (Exception) { Keyboard.Controller = null; throw; } } /// <summary> /// Ends support for the PalasoUIWinForms keyboarding /// </summary> public static void Shutdown() { if (Instance == null) return; Instance.Dispose(); Keyboard.Controller = null; } /// <summary> /// Gets or sets the available keyboard adaptors. /// </summary> internal static IKeyboardAdaptor[] Adaptors { get; private set; } #if __MonoCS__ /// <summary> /// Flag that Linux is using the combined keyboard handling (Ubuntu saucy/trusty/later?) /// </summary> internal static bool CombinedKeyboardHandling { get; set; } #endif /// <summary> /// Flag that Linux is Wasta-14 (Mint 17/Cinnamon) using IBus for keyboarding. /// </summary> internal static bool CinnamonKeyboardHandling { get; set; } /// <summary> /// Gets the currently active keyboard /// </summary> public static IKeyboardDefinition ActiveKeyboard { get { return Instance.ActiveKeyboard; } } /// <summary> /// Returns <c>true</c> if KeyboardController.Initialize() got called before. /// </summary> public static bool IsInitialized { get { return Instance != null; }} /// <summary> /// Register the control for keyboarding, optionally providing an event handler for /// a keyboarding adapter. If <paramref ref="eventHandler"/> is <c>null</c> the /// default handler will be used. /// The application should call this method for each control that needs IME input before /// displaying the control, typically after calling the InitializeComponent() method. /// </summary> public static void Register(Control control, object eventHandler = null) { if (Instance == null) throw new ApplicationException("KeyboardController is not initialized! Please call KeyboardController.Initialize() first."); Instance.RegisterControl(control, eventHandler); } /// <summary> /// Unregister the control from keyboarding. The application should call this method /// prior to disposing the control so that the keyboard adapters can release unmanaged /// resources. /// </summary> public static void Unregister(Control control) { Instance.UnregisterControl(control); } internal static IKeyboardControllerImpl EventProvider { get { return Instance; } } #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.Collections; using System.Diagnostics; using System.IO.PortsTests; using System.Threading; using Legacy.Support; using Xunit; namespace System.IO.Ports.Tests { public class ReceivedEvent : PortsTest { //Maximum time to wait for all of the expected events to be firered private const int MAX_TIME_WAIT = 500; private const int NUM_TRYS = 5; #region Test Cases [ConditionalFact(nameof(HasNullModem))] public void ReceivedEvent_Chars() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { ReceivedEventHandler rcvEventHandler = new ReceivedEventHandler(com1); Debug.WriteLine("Verifying ReceivedChars event"); com1.Open(); com2.Open(); com1.DataReceived += rcvEventHandler.HandleEvent; for (int i = 0; i < NUM_TRYS; i++) { com2.Write(new byte[com1.ReceivedBytesThreshold], 0, com1.ReceivedBytesThreshold); rcvEventHandler.WaitForEvent(MAX_TIME_WAIT, 1); rcvEventHandler.Validate(SerialData.Chars, com1.ReceivedBytesThreshold); if (0 != rcvEventHandler.NumberOfOccurrencesOfType(SerialData.Eof)) { Fail("Err_21087qpua!!! Unexpected EofReceived event fireed {0}", i); } if (0 != rcvEventHandler.NumberOfOccurrencesOfType(SerialData.Chars)) { Fail("Err_32417!!! Unexpected EofReceived event fireed {0}", i); } com1.DiscardInBuffer(); } } } [ConditionalFact(nameof(HasNullModem))] public void ReceivedEvent_Eof() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { ReceivedEventHandler rcvEventHandler = new ReceivedEventHandler(com1); byte[] xmitBytes = new byte[1]; Debug.WriteLine("Verifying EofReceived event"); com1.Open(); com2.Open(); com1.DataReceived += rcvEventHandler.HandleEvent; //EOF char xmitBytes[0] = 26; for (int i = 0; i < NUM_TRYS; i++) { com2.Write(xmitBytes, 0, xmitBytes.Length); rcvEventHandler.WaitForEvent(MAX_TIME_WAIT, 2); rcvEventHandler.Validate(SerialData.Eof, i); rcvEventHandler.Validate(SerialData.Chars, i + com1.ReceivedBytesThreshold); if (0 != rcvEventHandler.NumberOfOccurrencesOfType(SerialData.Eof)) { Fail("Err_01278qaods!!! Unexpected EofReceived event fireed {0}", i); } if (1 < rcvEventHandler.NumberOfOccurrencesOfType(SerialData.Chars)) { Fail("Err_2972qoypa!!! Unexpected ReceivedChars event fireed {0}", i); } } } } [ConditionalFact(nameof(HasNullModem))] public void ReceivedEvent_CharsEof() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { ReceivedEventHandler rcvEventHandler = new ReceivedEventHandler(com1); byte[] xmitBytes = new byte[3]; Debug.WriteLine("Verifying EofReceived event"); com1.Open(); com2.Open(); com1.DataReceived += rcvEventHandler.HandleEvent; //EOF char xmitBytes[0] = 56; xmitBytes[1] = 26; xmitBytes[2] = 55; for (int i = 0; i < NUM_TRYS; i++) { com2.Write(xmitBytes, 0, xmitBytes.Length); rcvEventHandler.WaitForEvent(MAX_TIME_WAIT, SerialData.Eof); rcvEventHandler.Validate(SerialData.Eof, i * xmitBytes.Length); rcvEventHandler.Validate(SerialData.Chars, (i * xmitBytes.Length) + com1.ReceivedBytesThreshold); if (0 != rcvEventHandler.NumberOfOccurrencesOfType(SerialData.Eof)) { Fail("Err_20712asdfhow!!! Unexpected EofReceived event fired {0} iteration:{1}", rcvEventHandler.NumberOfOccurrencesOfType(SerialData.Eof), i); } rcvEventHandler.Clear(); } } } [ConditionalFact(nameof(HasNullModem))] public void ReceivedEvent_CharsEof_ReadAllChars() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { ReadInReceivedEventHandler rcvEventHandler = new ReadInReceivedEventHandler(com1); byte[] xmitBytes = new byte[3]; Debug.WriteLine( "Verifying EofReceived and ReceivedChars events where all chars are read in the ReceivedChars event"); com1.Open(); com2.Open(); com1.DataReceived += rcvEventHandler.HandleEvent; //EOF char xmitBytes[0] = 56; xmitBytes[1] = 26; xmitBytes[2] = 55; for (int i = 0; i < NUM_TRYS; i++) { com2.Write(xmitBytes, 0, xmitBytes.Length); rcvEventHandler.WaitForEvent(MAX_TIME_WAIT, SerialData.Eof); rcvEventHandler.Validate(SerialData.Eof, 0); rcvEventHandler.Validate(SerialData.Chars, 1); if (0 != rcvEventHandler.NumberOfOccurrencesOfType(SerialData.Eof)) { Fail("Err_20712asdfhow!!! Unexpected EofReceived event fired {0} iteration:{1}", rcvEventHandler.NumberOfOccurrencesOfType(SerialData.Eof), i); } rcvEventHandler.Clear(); } if (rcvEventHandler.NumBytesRead != NUM_TRYS * xmitBytes.Length) { Fail("Err_1298129ahnied!!! Expected to read {0} chars actually read {1}", NUM_TRYS * xmitBytes.Length, rcvEventHandler.NumBytesRead); } else { for (int i = 0; i < NUM_TRYS; ++i) { for (int j = 0; j < xmitBytes.Length; ++j) { if (xmitBytes[j] != rcvEventHandler.BytesRead[(i * xmitBytes.Length) + j]) { Fail("Err_2829aneid Expected to Read '{0}'({0:X}) actually read {1}'({1:X})", xmitBytes[j], rcvEventHandler.BytesRead[(i * xmitBytes.Length) + j]); } } } } } } #endregion #region Verification for Test Cases public class ReceivedEventHandler { public ArrayList EventType; public ArrayList BytesToRead; public ArrayList Source; public int NumEventsHandled; protected SerialPort com; public ReceivedEventHandler(SerialPort com) { this.com = com; NumEventsHandled = 0; EventType = new ArrayList(); BytesToRead = new ArrayList(); Source = new ArrayList(); } public void HandleEvent(object source, SerialDataReceivedEventArgs e) { int bytesToRead = com.BytesToRead; lock (this) { BytesToRead.Add(bytesToRead); EventType.Add(e.EventType); Source.Add(source); NumEventsHandled++; Monitor.Pulse(this); } } public void Clear() { lock (this) { EventType.Clear(); BytesToRead.Clear(); NumEventsHandled = 0; } } public void WaitForEvent(int maxMilliseconds, int totalNumberOfEvents) { Stopwatch sw = new Stopwatch(); lock (this) { sw.Start(); while (maxMilliseconds > sw.ElapsedMilliseconds && NumEventsHandled < totalNumberOfEvents) { Monitor.Wait(this, (int)(maxMilliseconds - sw.ElapsedMilliseconds)); } Assert.Equal(totalNumberOfEvents, NumEventsHandled); } } public void WaitForEvent(int maxMilliseconds, SerialData eventType) { Stopwatch sw = new Stopwatch(); lock (this) { sw.Start(); while (maxMilliseconds > sw.ElapsedMilliseconds) { Monitor.Wait(this, (int)(maxMilliseconds - sw.ElapsedMilliseconds)); for (int i = 0; i < EventType.Count; i++) { if (eventType == (SerialData)EventType[i]) { return; } } } Assert.True(false, "Wait for event failure"); } } //Since we can not guarantee the order or the exact time that the event handler is called //We wil look for an event that was firered that matches the type and that bytesToRead //is greater then the parameter public void Validate(SerialData eventType, int bytesToRead) { lock (this) { for (int i = 0; i < EventType.Count; i++) { if (eventType == (SerialData)EventType[i] && bytesToRead <= (int)BytesToRead[i] && (SerialPort)Source[i] == com) { EventType.RemoveAt(i); BytesToRead.RemoveAt(i); Source.RemoveAt(i); NumEventsHandled--; return; } } } Assert.True(false, $"Validate {eventType} failed"); } public int NumberOfOccurrencesOfType(SerialData eventType) { int numOccurrences = 0; lock (this) { for (int i = 0; i < EventType.Count; i++) { if (eventType == (SerialData)EventType[i]) { numOccurrences++; } } } return numOccurrences; } } private class ReadInReceivedEventHandler : ReceivedEventHandler { private int _numBytesRead; private byte[] _bytesRead; public ReadInReceivedEventHandler(SerialPort com) : base(com) { _numBytesRead = 0; _bytesRead = new byte[4]; } public int NumBytesRead { get { return _numBytesRead; } } public byte[] BytesRead { get { return _bytesRead; } } public new void HandleEvent(object source, SerialDataReceivedEventArgs e) { base.HandleEvent(source, e); if (e.EventType == SerialData.Chars) { if ((_bytesRead.Length - _numBytesRead) < com.BytesToRead) { byte[] tempByteArray = new byte[Math.Max(_bytesRead.Length * 2, _bytesRead.Length + com.BytesToRead)]; Array.Copy(_bytesRead, 0, tempByteArray, 0, _numBytesRead); _bytesRead = tempByteArray; } _numBytesRead += com.Read(_bytesRead, _numBytesRead, _bytesRead.Length - _numBytesRead); } } } #endregion } }
//============================================================================== // TorqueLab -> Core Menubar handlers // Copyright (c) 2015 All Right Reserved, http://nordiklab.com/ //------------------------------------------------------------------------------ //============================================================================== $Pref::WorldEditor::FileSpec = "Torque Mission Files (*.mis)|*.mis|All Files (*.*)|*.*|"; ////////////////////////////////////////////////////////////////////////// // File Menu Handlers ////////////////////////////////////////////////////////////////////////// function EditorFileMenu::onMenuSelect(%this) { // don't do this since it won't exist if this is a "demo" if(!isWebDemo()) %this.enableItem(2, EditorIsDirty()); } ////////////////////////////////////////////////////////////////////////// // Package that gets temporarily activated to toggle editor after mission loading. // Deactivates itself. package BootEditor { function GameConnection::initialControlSet( %this ) { Parent::initialControlSet( %this ); toggleEditor( true ); deactivatePackage( "BootEditor" ); } }; ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // View Menu Handlers ////////////////////////////////////////////////////////////////////////// function EditorViewMenu::onMenuSelect( %this ) { %this.checkItem( 1, EWorldEditor.renderOrthoGrid ); } ////////////////////////////////////////////////////////////////////////// // Edit Menu Handlers ////////////////////////////////////////////////////////////////////////// function EditorEditMenu::onMenuSelect( %this ) { // UndoManager is in charge of enabling or disabling the undo/redo items. Editor.getUndoManager().updateUndoMenu( ); // SICKHEAD: It a perfect world we would abstract // cut/copy/paste with a generic selection object // which would know how to process itself. // Give the active editor a chance at fixing up // the state of the edit menu. // Do we really need this check here? if ( isObject( Lab.currentEditor ) ) Lab.currentEditor.onEditMenuSelect( %this ); } ////////////////////////////////////////////////////////////////////////// function EditorMenuEditDelete() { if ( isObject( Lab.currentEditor ) ) Lab.currentEditor.handleDelete(); } function EditorMenuEditDeselect() { if ( isObject( Lab.currentEditor ) ) Lab.currentEditor.handleDeselect(); } function EditorMenuEditCut() { if ( isObject( Lab.currentEditor ) ) Lab.currentEditor.handleCut(); } function EditorMenuEditCopy() { if ( isObject( Lab.currentEditor ) ) Lab.currentEditor.handleCopy(); } function EditorMenuEditPaste() { if ( isObject( Lab.currentEditor ) ) Lab.currentEditor.handlePaste(); } ////////////////////////////////////////////////////////////////////////// // Window Menu Handler ////////////////////////////////////////////////////////////////////////// function EditorToolsMenu::onSelectItem(%this, %id) { %toolName = getField( %this.item[%id], 2 ); EditorGui.setEditor(%toolName, %paletteName ); %this.checkRadioItem(0, %this.getItemCount(), %id); return true; } function EditorToolsMenu::setupDefaultState(%this) { Parent::setupDefaultState(%this); } ////////////////////////////////////////////////////////////////////////// // Camera Menu Handler ////////////////////////////////////////////////////////////////////////// function EditorCameraMenu::onSelectItem(%this, %id, %text) { if(%id == 0 || %id == 1) { // Handle the Free Camera/Orbit Camera toggle %this.checkRadioItem(0, 1, %id); } return Parent::onSelectItem(%this, %id, %text); } function EditorCameraMenu::setupDefaultState(%this) { // Set the Free Camera/Orbit Camera check marks %this.checkRadioItem(0, 1, 0); Parent::setupDefaultState(%this); } function EditorFreeCameraTypeMenu::onSelectItem(%this, %id, %text) { // Handle the camera type radio %this.checkRadioItem(0, 2, %id); return Parent::onSelectItem(%this, %id, %text); } function EditorFreeCameraTypeMenu::setupDefaultState(%this) { // Set the camera type check marks %this.checkRadioItem(0, 2, 0); Parent::setupDefaultState(%this); } function EditorCameraSpeedMenu::onSelectItem(%this, %id, %text) { // Grab and set speed %speed = getField( %this.item[%id], 2 ); $Camera::movementSpeed = %speed; // Update Editor %this.checkRadioItem(0, 6, %id); // Update Toolbar TextEdit EWorldEditorCameraSpeed.setText( $Camera::movementSpeed ); // Update Toolbar Slider CameraSpeedDropdownCtrlContainer-->Slider.setValue( $Camera::movementSpeed ); return true; } function EditorCameraSpeedMenu::setupDefaultState(%this) { // Setup camera speed gui's. Both menu and editorgui %this.setupGuiControls(); //Grab and set speed %defaultSpeed = Lab.levelsDirectory @ Lab.levelName @ "/cameraSpeed"; if( %defaultSpeed $= "" ) { // Update Editor with default speed %defaultSpeed = 25; } $Camera::movementSpeed = %defaultSpeed; // Update Toolbar TextEdit EWorldEditorCameraSpeed.setText( %defaultSpeed ); // Update Toolbar Slider CameraSpeedDropdownCtrlContainer-->Slider.setValue( %defaultSpeed ); Parent::setupDefaultState(%this); } function EditorCameraSpeedMenu::setupGuiControls(%this) { // Default levelInfo params %minSpeed = 5; %maxSpeed = 200; %speedA = Lab.levelsDirectory @ Lab.levelName @ "/cameraSpeedMin"; %speedB = Lab.levelsDirectory @ Lab.levelName @ "/cameraSpeedMax"; if( %speedA < %speedB ) { if( %speedA == 0 ) { if( %speedB > 1 ) %minSpeed = 1; else %minSpeed = 0.1; } else { %minSpeed = %speedA; } %maxSpeed = %speedB; } // Set up the camera speed items %inc = ( (%maxSpeed - %minSpeed) / (%this.getItemCount() - 1) ); for( %i = 0; %i < %this.getItemCount(); %i++) %this.item[%i] = setField( %this.item[%i], 2, (%minSpeed + (%inc * %i))); // Set up min/max camera slider range eval("CameraSpeedDropdownCtrlContainer-->Slider.range = \"" @ %minSpeed @ " " @ %maxSpeed @ "\";"); } ////////////////////////////////////////////////////////////////////////// // World Menu Handler Object Menu ////////////////////////////////////////////////////////////////////////// function EditorWorldMenu::onMenuSelect(%this) { %selSize = EWorldEditor.getSelectionSize(); %lockCount = EWorldEditor.getSelectionLockCount(); %hideCount = EWorldEditor.getSelectionHiddenCount(); %this.enableItem(0, %lockCount < %selSize); // Lock Selection %this.enableItem(1, %lockCount > 0); // Unlock Selection %this.enableItem(3, %hideCount < %selSize); // Hide Selection %this.enableItem(4, %hideCount > 0); // Show Selection %this.enableItem(6, %selSize > 1 && %lockCount == 0); // Align bounds %this.enableItem(7, %selSize > 1 && %lockCount == 0); // Align center %this.enableItem(9, %selSize > 0 && %lockCount == 0); // Reset Transforms %this.enableItem(10, %selSize > 0 && %lockCount == 0); // Reset Selected Rotation %this.enableItem(11, %selSize > 0 && %lockCount == 0); // Reset Selected Scale %this.enableItem(12, %selSize > 0 && %lockCount == 0); // Transform Selection %this.enableItem(14, %selSize > 0 && %lockCount == 0); // Drop Selection %this.enableItem(17, %selSize > 0); // Make Prefab %this.enableItem(18, %selSize > 0); // Explode Prefab %this.enableItem(20, %selSize > 1); // Mount %this.enableItem(21, %selSize > 0); // Unmount } ////////////////////////////////////////////////////////////////////////// function EditorDropTypeMenu::onSelectItem(%this, %id, %text) { // This sets up which drop script function to use when // a drop type is selected in the menu. EWorldEditor.dropType = getField(%this.item[%id], 2); %this.checkRadioItem(0, (%this.getItemCount() - 1), %id); return true; } function EditorDropTypeMenu::setupDefaultState(%this) { // Check the radio item for the currently set drop type. %numItems = %this.getItemCount(); %dropTypeIndex = 0; for( ; %dropTypeIndex < %numItems; %dropTypeIndex ++ ) if( getField( %this.item[ %dropTypeIndex ], 2 ) $= EWorldEditor.dropType ) break; // Default to screenCenter if we didn't match anything. if( %dropTypeIndex > (%numItems - 1) ) %dropTypeIndex = 4; %this.checkRadioItem( 0, (%numItems - 1), %dropTypeIndex ); Parent::setupDefaultState(%this); } ////////////////////////////////////////////////////////////////////////// function EditorAlignBoundsMenu::onSelectItem(%this, %id, %text) { // Have the editor align all selected objects by the selected bounds. EWorldEditor.alignByBounds(getField(%this.item[%id], 2)); return true; } function EditorAlignBoundsMenu::setupDefaultState(%this) { // Allow the parent to set the menu's default state Parent::setupDefaultState(%this); } ////////////////////////////////////////////////////////////////////////// function EditorAlignCenterMenu::onSelectItem(%this, %id, %text) { // Have the editor align all selected objects by the selected axis. EWorldEditor.alignByAxis(getField(%this.item[%id], 2)); return true; } function EditorAlignCenterMenu::setupDefaultState(%this) { // Allow the parent to set the menu's default state Parent::setupDefaultState(%this); }
using System; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using BTDB.Collections; using BTDB.IL; using BTDB.ODBLayer; using BTDB.StreamLayer; using BTDB.FieldHandler; namespace BTDB.EventStoreLayer { public class ObjectTypeDescriptor : ITypeDescriptor, IPersistTypeDescriptor { Type? _type; StructList<KeyValuePair<string, ITypeDescriptor>> _fields; readonly ITypeDescriptorCallbacks _typeSerializers; public ObjectTypeDescriptor(ITypeDescriptorCallbacks typeSerializers, Type type) { _typeSerializers = typeSerializers; _type = type; Sealed = _type.IsSealed; Name = typeSerializers.TypeNameMapper.ToName(type); } public ObjectTypeDescriptor(ITypeDescriptorCallbacks typeSerializers, AbstractBufferedReader reader, Func<AbstractBufferedReader, ITypeDescriptor> nestedDescriptorReader) { _typeSerializers = typeSerializers; Sealed = false; Name = reader.ReadString()!; var fieldCount = reader.ReadVUInt32(); while (fieldCount-- > 0) { _fields.Add( new KeyValuePair<string, ITypeDescriptor>(reader.ReadString(), nestedDescriptorReader(reader))); } } ObjectTypeDescriptor(ITypeDescriptorCallbacks typeSerializers, string name, bool @sealed) { _typeSerializers = typeSerializers; Sealed = @sealed; Name = name; } public bool Equals(ITypeDescriptor other) { return Equals(other, new HashSet<ITypeDescriptor>(ReferenceEqualityComparer<ITypeDescriptor>.Instance)); } public string Name { get; } public static void CheckObjectTypeIsGoodDto(Type type) { var isInterface = type.IsInterface; foreach (var propertyInfo in type.GetProperties(BindingFlags.Instance | BindingFlags.Public)) { if (propertyInfo.GetIndexParameters().Length != 0) continue; if (ShouldNotBeStored(propertyInfo)) continue; if (propertyInfo.GetGetMethod(true) == null) throw new InvalidOperationException("Trying to serialize type " + type.ToSimpleName() + " and property " + propertyInfo.Name + " does not have getter. If you don't want to serialize this property add [NotStored] attribute."); if (!isInterface && propertyInfo.GetSetMethod(true) == null) throw new InvalidOperationException("Trying to serialize type " + type.ToSimpleName() + " and property " + propertyInfo.Name + " does not have setter. If you don't want to serialize this property add [NotStored] attribute."); } foreach (var fieldInfo in type.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance)) { if (fieldInfo.IsPrivate) continue; if (ShouldNotBeStored(fieldInfo)) continue; throw new InvalidOperationException("Serialize type " + type.ToSimpleName() + " with non-private field " + fieldInfo.Name + " is forbidden without marking it with [NotStored] attribute"); } } static bool ShouldNotBeStored(ICustomAttributeProvider propertyInfo) { return propertyInfo.GetCustomAttributes(typeof(NotStoredAttribute), true).Length != 0; } public bool FinishBuildFromType(ITypeDescriptorFactory factory) { var props = _type!.GetProperties(BindingFlags.Instance | BindingFlags.Public); #if DEBUG CheckObjectTypeIsGoodDto(_type); #endif foreach (var propertyInfo in props) { if (propertyInfo.GetIndexParameters().Length != 0) continue; if (ShouldNotBeStored(propertyInfo)) continue; var descriptor = factory.Create(propertyInfo.PropertyType); if (descriptor != null) { _fields.Add(new KeyValuePair<string, ITypeDescriptor>(GetPersistentName(propertyInfo), descriptor)); } } _fields.Sort(Comparer<KeyValuePair<string, ITypeDescriptor>>.Create((l, r) => string.Compare(l.Key, r.Key, StringComparison.InvariantCulture))); return true; } static string GetPersistentName(PropertyInfo propertyInfo) { var a = propertyInfo.GetCustomAttribute<PersistedNameAttribute>(); return a != null ? a.Name : propertyInfo.Name; } public void BuildHumanReadableFullName(StringBuilder text, HashSet<ITypeDescriptor> stack, uint indent) { if (stack.Contains(this)) { text.Append(Name); return; } stack.Add(this); text.AppendLine(Name); AppendIndent(text, indent); text.AppendLine("{"); indent++; foreach (var pair in _fields) { AppendIndent(text, indent); text.Append(pair.Key); text.Append(" : "); pair.Value.BuildHumanReadableFullName(text, stack, indent); text.AppendLine(); } indent--; AppendIndent(text, indent); text.Append("}"); stack.Remove(this); } static void AppendIndent(StringBuilder text, uint indent) { text.Append(' ', (int) (indent * 4)); } public bool Equals(ITypeDescriptor other, HashSet<ITypeDescriptor> stack) { var o = other as ObjectTypeDescriptor; if (o == null) return false; if (Name != o.Name) return false; if (stack.Contains(this)) return true; if (_fields.Count != o._fields.Count) return false; stack.Add(this); try { for (int i = 0; i < _fields.Count; i++) { if (_fields[i].Key != o._fields[i].Key) return false; if (!_fields[i].Value.Equals(o._fields[i].Value, stack)) return false; } } finally { stack.Remove(this); } return true; } public Type? GetPreferredType() { if (_type == null) _type = _typeSerializers.TypeNameMapper.ToType(Name); return _type; } public Type? GetPreferredType(Type targetType) { var res = GetPreferredType(); if (res == targetType || res == null) return res; res = DBObjectFieldHandler.Unwrap(res); if (res == DBObjectFieldHandler.Unwrap(targetType)) return targetType; return res; } public bool AnyOpNeedsCtx() { return !_fields.All(p => p.Value.StoredInline) || _fields.Any(p => p.Value.AnyOpNeedsCtx()); } public void GenerateLoad(IILGen ilGenerator, Action<IILGen> pushReader, Action<IILGen> pushCtx, Action<IILGen> pushDescriptor, Type targetType) { if (targetType == typeof(object)) { var resultLoc = ilGenerator.DeclareLocal(typeof(DynamicObject), "result"); var labelNoCtx = ilGenerator.DefineLabel(); ilGenerator .Do(pushDescriptor) .Castclass(typeof(ObjectTypeDescriptor)) .Newobj(typeof(DynamicObject).GetConstructor(new[] {typeof(ObjectTypeDescriptor)})!) .Stloc(resultLoc) .Do(pushCtx) .BrfalseS(labelNoCtx) .Do(pushCtx) .Ldloc(resultLoc) .Callvirt(() => default(ITypeBinaryDeserializerContext).AddBackRef(null)) .Mark(labelNoCtx); var idx = 0; foreach (var pair in _fields) { var idxForCapture = idx; ilGenerator.Ldloc(resultLoc); ilGenerator.LdcI4(idx); pair.Value.GenerateLoadEx(ilGenerator, pushReader, pushCtx, il => il.Do(pushDescriptor) .LdcI4(idxForCapture) .Callvirt(() => default(ITypeDescriptor).NestedType(0)), typeof(object), _typeSerializers.ConvertorGenerator); ilGenerator.Callvirt(() => default(DynamicObject).SetFieldByIdxFast(0, null)); idx++; } ilGenerator .Ldloc(resultLoc) .Castclass(typeof(object)); } else { var resultLoc = ilGenerator.DeclareLocal(targetType, "result"); var labelNoCtx = ilGenerator.DefineLabel(); var defaultConstructor = targetType.GetConstructor(Type.EmptyTypes); if (defaultConstructor == null) { ilGenerator .Ldtoken(targetType) .Call(() => Type.GetTypeFromHandle(new RuntimeTypeHandle())) .Call(() => RuntimeHelpers.GetUninitializedObject(null)) .Castclass(targetType); } else { ilGenerator .Newobj(defaultConstructor); } ilGenerator .Stloc(resultLoc) .Do(pushCtx) .BrfalseS(labelNoCtx) .Do(pushCtx) .Ldloc(resultLoc) .Callvirt(() => default(ITypeBinaryDeserializerContext).AddBackRef(null)) .Mark(labelNoCtx); var props = targetType.GetProperties(BindingFlags.Instance | BindingFlags.Public); for (var idx = 0; idx < _fields.Count; idx++) { var idxForCapture = idx; var pair = _fields[idx]; var prop = props.FirstOrDefault(p => GetPersistentName(p) == pair.Key); if (prop == null || !_typeSerializers.IsSafeToLoad(prop.PropertyType)) { pair.Value.GenerateSkipEx(ilGenerator, pushReader, pushCtx); continue; } ilGenerator.Ldloc(resultLoc); pair.Value.GenerateLoadEx(ilGenerator, pushReader, pushCtx, il => il.Do(pushDescriptor).LdcI4(idxForCapture) .Callvirt(() => default(ITypeDescriptor).NestedType(0)), prop.PropertyType, _typeSerializers.ConvertorGenerator); ilGenerator.Callvirt(prop.GetSetMethod(true)!); } ilGenerator.Ldloc(resultLoc); } } public void GenerateSkip(IILGen ilGenerator, Action<IILGen> pushReader, Action<IILGen> pushCtx) { foreach (var pair in _fields) { pair.Value.GenerateSkipEx(ilGenerator, pushReader, pushCtx); } } int FindFieldIndex(string fieldName) { var f = _fields.AsReadOnlySpan(); for (var i = 0; i < f.Length; i++) { if (f[i].Key == fieldName) return i; } return -1; } int FindFieldIndexWithThrow(string fieldName) { var index = FindFieldIndex(fieldName); if (index < 0) throw new MemberAccessException($"{Name} does not have member {fieldName}"); return index; } public class DynamicObject : IDynamicMetaObjectProvider, IKnowDescriptor { readonly ObjectTypeDescriptor _ownerDescriptor; readonly object[] _fieldValues; public DynamicObject(ObjectTypeDescriptor ownerDescriptor) { _ownerDescriptor = ownerDescriptor; _fieldValues = new object[_ownerDescriptor._fields.Count]; } DynamicMetaObject IDynamicMetaObjectProvider.GetMetaObject(Expression parameter) { return new DynamicDictionaryMetaObject(parameter, this); } public void SetFieldByIdxFast(int idx, object value) { _fieldValues[idx] = value; } public void SetFieldByIdx(int idx, string fieldName, ObjectTypeDescriptor descriptor, object value) { if (_ownerDescriptor == descriptor) { if (idx < 0) ThrowMemberAccessException(fieldName); _fieldValues[idx] = value; return; } var realIndex = _ownerDescriptor.FindFieldIndexWithThrow(fieldName); _fieldValues[realIndex] = value; } public object GetFieldByIdx(int idx, string fieldName, ObjectTypeDescriptor descriptor) { if (_ownerDescriptor == descriptor) { if (idx < 0) ThrowMemberAccessException(fieldName); return _fieldValues[idx]; } var realIndex = _ownerDescriptor.FindFieldIndexWithThrow(fieldName); return _fieldValues[realIndex]; } void ThrowMemberAccessException(string fieldName) { throw new MemberAccessException($"{_ownerDescriptor.Name} does not have member {fieldName}"); } class DynamicDictionaryMetaObject : DynamicMetaObject { internal DynamicDictionaryMetaObject(Expression parameter, DynamicObject value) : base(parameter, BindingRestrictions.Empty, value) { } public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value) { var descriptor = ((DynamicObject) Value)._ownerDescriptor; var idx = descriptor.FindFieldIndex(binder.Name); return new DynamicMetaObject(Expression.Call(Expression.Convert(Expression, LimitType), typeof(DynamicObject).GetMethod(nameof(SetFieldByIdx))!, Expression.Constant(idx), Expression.Constant(binder.Name), Expression.Constant(descriptor), Expression.Convert(value.Expression, typeof(object))), BindingRestrictions.GetTypeRestriction(Expression, LimitType)); } public override DynamicMetaObject BindGetMember(GetMemberBinder binder) { var descriptor = ((DynamicObject) Value)._ownerDescriptor; var idx = descriptor.FindFieldIndex(binder.Name); return new DynamicMetaObject(Expression.Call(Expression.Convert(Expression, LimitType), typeof(DynamicObject).GetMethod(nameof(GetFieldByIdx))!, Expression.Constant(idx), Expression.Constant(binder.Name), Expression.Constant(descriptor)), BindingRestrictions.GetTypeRestriction(Expression, LimitType)); } public override IEnumerable<string> GetDynamicMemberNames() { var descriptor = ((DynamicObject) Value)._ownerDescriptor; return descriptor._fields.Select(p => p.Key); } } public override string ToString() { var sb = new StringBuilder(); var idx = 0; sb.Append("{ "); foreach (var item in _ownerDescriptor._fields) { if (idx > 0) sb.Append(", "); sb.Append($"\"{item.Key}\"").Append(": ").AppendJsonLike(_fieldValues[idx]); idx++; } sb.Append(" }"); return sb.ToString(); } public ITypeDescriptor GetDescriptor() { return _ownerDescriptor; } } public ITypeNewDescriptorGenerator? BuildNewDescriptorGenerator() { if (_fields.Select(p => p.Value).All(d => d.Sealed)) return null; return new TypeNewDescriptorGenerator(this); } class TypeNewDescriptorGenerator : ITypeNewDescriptorGenerator { readonly ObjectTypeDescriptor _objectTypeDescriptor; public TypeNewDescriptorGenerator(ObjectTypeDescriptor objectTypeDescriptor) { _objectTypeDescriptor = objectTypeDescriptor; } public void GenerateTypeIterator(IILGen ilGenerator, Action<IILGen> pushObj, Action<IILGen> pushCtx, Type type) { var allProps = _objectTypeDescriptor.GetPreferredType()!.GetProperties(BindingFlags.Instance | BindingFlags.Public); foreach (var pair in _objectTypeDescriptor._fields) { if (pair.Value.Sealed) continue; ilGenerator .Do(pushCtx) .Do(pushObj) .Castclass(_objectTypeDescriptor._type!) .Callvirt(allProps.First(p => GetPersistentName(p) == pair.Key).GetGetMethod()!) .Callvirt(() => default(IDescriptorSerializerLiteContext).StoreNewDescriptors(null)); } } } public ITypeDescriptor? NestedType(int index) { return index < _fields.Count ? _fields[index].Value : null; } public void MapNestedTypes(Func<ITypeDescriptor, ITypeDescriptor> map) { for (var index = 0; index < _fields.Count; index++) { var keyValuePair = _fields[index]; var mapped = map(keyValuePair.Value); if (mapped == keyValuePair.Value) continue; keyValuePair = new KeyValuePair<string, ITypeDescriptor>(keyValuePair.Key, mapped); _fields[index] = keyValuePair; } } public bool Sealed { get; } public bool StoredInline => false; public bool LoadNeedsHelpWithConversion => false; public void ClearMappingToType() { _type = null; } public bool ContainsField(string name) { foreach (var pair in _fields) { if (pair.Key == name) return true; } return false; } public void Persist(AbstractBufferedWriter writer, Action<AbstractBufferedWriter, ITypeDescriptor> nestedDescriptorWriter) { writer.WriteString(Name); writer.WriteVUInt32(_fields.Count); foreach (var pair in _fields) { writer.WriteString(pair.Key); nestedDescriptorWriter(writer, pair.Value); } } public void GenerateSave(IILGen ilGenerator, Action<IILGen> pushWriter, Action<IILGen> pushCtx, Action<IILGen> pushValue, Type valueType) { if (GetPreferredType() != valueType) throw new ArgumentException("value type does not match my type"); var locValue = ilGenerator.DeclareLocal(_type!, "value"); ilGenerator .Do(pushValue) .Stloc(locValue); foreach (var (name, typeDescriptor) in _fields) { var methodInfo = _type.GetProperties().First(p => GetPersistentName(p) == name).GetGetMethod(true); typeDescriptor.GenerateSaveEx(ilGenerator, pushWriter, pushCtx, il => il.Ldloc(locValue).Callvirt(methodInfo), methodInfo!.ReturnType); } } public ITypeDescriptor CloneAndMapNestedTypes(ITypeDescriptorCallbacks typeSerializers, Func<ITypeDescriptor, ITypeDescriptor> map) { var tds = new ITypeDescriptor[_fields.Count]; for (var i = 0; i < _fields.Count; i++) { tds[i] = map(_fields[i].Value); } if (typeSerializers == _typeSerializers && tds.SequenceEqual(_fields.Select(i => i.Value))) return this; var res = new ObjectTypeDescriptor(typeSerializers, Name, Sealed); for (var i = 0; i < _fields.Count; i++) { res._fields.Add(new KeyValuePair<string, ITypeDescriptor>(_fields[i].Key, tds[i])); } return res; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using LibGit2Sharp.Core; using Xunit; namespace LibGit2Sharp.Tests.TestHelpers { public class BaseFixture : IPostTestDirectoryRemover, IDisposable { private readonly List<string> directories = new List<string>(); #if LEAKS_IDENTIFYING public BaseFixture() { LeaksContainer.Clear(); } #endif static BaseFixture() { // Do the set up in the static ctor so it only happens once SetUpTestEnvironment(); } public static string BareTestRepoPath { get; private set; } public static string StandardTestRepoWorkingDirPath { get; private set; } public static string StandardTestRepoPath { get; private set; } public static string ShallowTestRepoPath { get; private set; } public static string MergedTestRepoWorkingDirPath { get; private set; } public static string MergeTestRepoWorkingDirPath { get; private set; } public static string MergeRenamesTestRepoWorkingDirPath { get; private set; } public static string RevertTestRepoWorkingDirPath { get; private set; } public static string SubmoduleTestRepoWorkingDirPath { get; private set; } private static string SubmoduleTargetTestRepoWorkingDirPath { get; set; } private static string AssumeUnchangedRepoWorkingDirPath { get; set; } public static string SubmoduleSmallTestRepoWorkingDirPath { get; set; } public static string PackBuilderTestRepoPath { get; private set; } public static DirectoryInfo ResourcesDirectory { get; private set; } public static bool IsFileSystemCaseSensitive { get; private set; } protected static DateTimeOffset TruncateSubSeconds(DateTimeOffset dto) { int seconds = dto.ToSecondsSinceEpoch(); return Epoch.ToDateTimeOffset(seconds, (int)dto.Offset.TotalMinutes); } private static void SetUpTestEnvironment() { IsFileSystemCaseSensitive = IsFileSystemCaseSensitiveInternal(); string initialAssemblyParentFolder = Directory.GetParent(new Uri(typeof(BaseFixture).Assembly.EscapedCodeBase).LocalPath).FullName; const string sourceRelativePath = @"../../Resources"; ResourcesDirectory = new DirectoryInfo(Path.Combine(initialAssemblyParentFolder, sourceRelativePath)); // Setup standard paths to our test repositories BareTestRepoPath = Path.Combine(sourceRelativePath, "testrepo.git"); StandardTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "testrepo_wd"); StandardTestRepoPath = Path.Combine(StandardTestRepoWorkingDirPath, "dot_git"); ShallowTestRepoPath = Path.Combine(sourceRelativePath, "shallow.git"); MergedTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "mergedrepo_wd"); MergeRenamesTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "mergerenames_wd"); MergeTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "merge_testrepo_wd"); RevertTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "revert_testrepo_wd"); SubmoduleTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "submodule_wd"); SubmoduleTargetTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "submodule_target_wd"); AssumeUnchangedRepoWorkingDirPath = Path.Combine(sourceRelativePath, "assume_unchanged_wd"); SubmoduleSmallTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "submodule_small_wd"); PackBuilderTestRepoPath = Path.Combine(sourceRelativePath, "packbuilder_testrepo_wd"); CleanupTestReposOlderThan(TimeSpan.FromMinutes(15)); } private static void CleanupTestReposOlderThan(TimeSpan olderThan) { var oldTestRepos = new DirectoryInfo(Constants.TemporaryReposPath) .EnumerateDirectories() .Where(di => di.CreationTimeUtc < DateTimeOffset.Now.Subtract(olderThan)) .Select(di => di.FullName); foreach (var dir in oldTestRepos) { DirectoryHelper.DeleteDirectory(dir); } } private static bool IsFileSystemCaseSensitiveInternal() { var mixedPath = Path.Combine(Constants.TemporaryReposPath, "mIxEdCase-" + Path.GetRandomFileName()); if (Directory.Exists(mixedPath)) { Directory.Delete(mixedPath); } Directory.CreateDirectory(mixedPath); bool isInsensitive = Directory.Exists(mixedPath.ToLowerInvariant()); Directory.Delete(mixedPath); return !isInsensitive; } protected void CreateCorruptedDeadBeefHead(string repoPath) { const string deadbeef = "deadbeef"; string headPath = string.Format("refs/heads/{0}", deadbeef); Touch(repoPath, headPath, string.Format("{0}{0}{0}{0}{0}\n", deadbeef)); } protected SelfCleaningDirectory BuildSelfCleaningDirectory() { return new SelfCleaningDirectory(this); } protected SelfCleaningDirectory BuildSelfCleaningDirectory(string path) { return new SelfCleaningDirectory(this, path); } protected string SandboxBareTestRepo() { return Sandbox(BareTestRepoPath); } protected string SandboxStandardTestRepo() { return Sandbox(StandardTestRepoWorkingDirPath); } protected string SandboxMergedTestRepo() { return Sandbox(MergedTestRepoWorkingDirPath); } protected string SandboxStandardTestRepoGitDir() { return Sandbox(Path.Combine(StandardTestRepoWorkingDirPath)); } protected string SandboxMergeTestRepo() { return Sandbox(MergeTestRepoWorkingDirPath); } protected string SandboxRevertTestRepo() { return Sandbox(RevertTestRepoWorkingDirPath); } public string SandboxSubmoduleTestRepo() { return Sandbox(SubmoduleTestRepoWorkingDirPath, SubmoduleTargetTestRepoWorkingDirPath); } public string SandboxAssumeUnchangedTestRepo() { return Sandbox(AssumeUnchangedRepoWorkingDirPath); } public string SandboxSubmoduleSmallTestRepo() { var path = Sandbox(SubmoduleSmallTestRepoWorkingDirPath, SubmoduleTargetTestRepoWorkingDirPath); Directory.CreateDirectory(Path.Combine(path, "submodule_target_wd")); return path; } protected string SandboxPackBuilderTestRepo() { return Sandbox(PackBuilderTestRepoPath); } protected string Sandbox(string sourceDirectoryPath, params string[] additionalSourcePaths) { var scd = BuildSelfCleaningDirectory(); var source = new DirectoryInfo(sourceDirectoryPath); var clonePath = Path.Combine(scd.DirectoryPath, source.Name); DirectoryHelper.CopyFilesRecursively(source, new DirectoryInfo(clonePath)); foreach (var additionalPath in additionalSourcePaths) { var additional = new DirectoryInfo(additionalPath); var targetForAdditional = Path.Combine(scd.DirectoryPath, additional.Name); DirectoryHelper.CopyFilesRecursively(additional, new DirectoryInfo(targetForAdditional)); } return clonePath; } protected string InitNewRepository(bool isBare = false) { SelfCleaningDirectory scd = BuildSelfCleaningDirectory(); return Repository.Init(scd.DirectoryPath, isBare); } protected Repository InitIsolatedRepository(string path = null, bool isBare = false, RepositoryOptions options = null) { path = path ?? InitNewRepository(isBare); options = BuildFakeConfigs(BuildSelfCleaningDirectory(), options); return new Repository(path, options); } public void Register(string directoryPath) { directories.Add(directoryPath); } public virtual void Dispose() { foreach (string directory in directories) { DirectoryHelper.DeleteDirectory(directory); } #if LEAKS_IDENTIFYING GC.Collect(); GC.WaitForPendingFinalizers(); if (LeaksContainer.TypeNames.Any()) { Assert.False(true, string.Format("Some handles of the following types haven't been properly released: {0}.{1}" + "In order to get some help fixing those leaks, uncomment the define LEAKS_TRACKING in SafeHandleBase.cs{1}" + "and run the tests locally.", string.Join(", ", LeaksContainer.TypeNames), Environment.NewLine)); } #endif } protected static void InconclusiveIf(Func<bool> predicate, string message) { if (!predicate()) { return; } throw new SkipException(message); } protected void RequiresDotNetOrMonoGreaterThanOrEqualTo(System.Version minimumVersion) { Type type = Type.GetType("Mono.Runtime"); if (type == null) { // We're running on top of .Net return; } MethodInfo displayName = type.GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static); if (displayName == null) { throw new InvalidOperationException("Cannot access Mono.RunTime.GetDisplayName() method."); } var version = (string)displayName.Invoke(null, null); System.Version current; try { current = new System.Version(version.Split(' ')[0]); } catch (Exception e) { throw new Exception(string.Format("Cannot parse Mono version '{0}'.", version), e); } InconclusiveIf(() => current < minimumVersion, string.Format( "Current Mono version is {0}. Minimum required version to run this test is {1}.", current, minimumVersion)); } protected static void AssertValueInConfigFile(string configFilePath, string regex) { var text = File.ReadAllText(configFilePath); var r = new Regex(regex, RegexOptions.Multiline).Match(text); Assert.True(r.Success, text); } public RepositoryOptions BuildFakeConfigs(SelfCleaningDirectory scd, RepositoryOptions options = null) { options = BuildFakeRepositoryOptions(scd, options); StringBuilder sb = new StringBuilder() .AppendFormat("[Woot]{0}", Environment.NewLine) .AppendFormat("this-rocks = global{0}", Environment.NewLine) .AppendFormat("[Wow]{0}", Environment.NewLine) .AppendFormat("Man-I-am-totally-global = 42{0}", Environment.NewLine); File.WriteAllText(options.GlobalConfigurationLocation, sb.ToString()); sb = new StringBuilder() .AppendFormat("[Woot]{0}", Environment.NewLine) .AppendFormat("this-rocks = system{0}", Environment.NewLine); File.WriteAllText(options.SystemConfigurationLocation, sb.ToString()); sb = new StringBuilder() .AppendFormat("[Woot]{0}", Environment.NewLine) .AppendFormat("this-rocks = xdg{0}", Environment.NewLine); File.WriteAllText(options.XdgConfigurationLocation, sb.ToString()); return options; } private static RepositoryOptions BuildFakeRepositoryOptions(SelfCleaningDirectory scd, RepositoryOptions options = null) { options = options ?? new RepositoryOptions(); string confs = Path.Combine(scd.DirectoryPath, "confs"); Directory.CreateDirectory(confs); options.GlobalConfigurationLocation = Path.Combine(confs, "my-global-config"); options.XdgConfigurationLocation = Path.Combine(confs, "my-xdg-config"); options.SystemConfigurationLocation = Path.Combine(confs, "my-system-config"); return options; } /// <summary> /// Creates a configuration file with user.name and user.email set to signature /// </summary> /// <remarks>The configuration file will be removed automatically when the tests are finished</remarks> /// <param name="identity">The identity to use for user.name and user.email</param> /// <returns>The path to the configuration file</returns> protected string CreateConfigurationWithDummyUser(Identity identity) { return CreateConfigurationWithDummyUser(identity.Name, identity.Email); } protected string CreateConfigurationWithDummyUser(string name, string email) { SelfCleaningDirectory scd = BuildSelfCleaningDirectory(); string configFilePath = Touch(scd.DirectoryPath, "fake-config"); using (Configuration config = Configuration.BuildFrom(configFilePath)) { if (name != null) { config.Set("user.name", name); } if (email != null) { config.Set("user.email", email); } } return configFilePath; } /// <summary> /// Asserts that the commit has been authored and committed by the specified signature /// </summary> /// <param name="commit">The commit</param> /// <param name="identity">The identity to compare author and commiter to</param> protected void AssertCommitIdentitiesAre(Commit commit, Identity identity) { Assert.Equal(identity.Name, commit.Author.Name); Assert.Equal(identity.Email, commit.Author.Email); Assert.Equal(identity.Name, commit.Committer.Name); Assert.Equal(identity.Email, commit.Committer.Email); } protected static string Touch(string parent, string file, string content = null, Encoding encoding = null) { string filePath = Path.Combine(parent, file); string dir = Path.GetDirectoryName(filePath); Debug.Assert(dir != null); Directory.CreateDirectory(dir); File.WriteAllText(filePath, content ?? string.Empty, encoding ?? Encoding.ASCII); return filePath; } protected static string Touch(string parent, string file, Stream stream) { Debug.Assert(stream != null); string filePath = Path.Combine(parent, file); string dir = Path.GetDirectoryName(filePath); Debug.Assert(dir != null); Directory.CreateDirectory(dir); using (var fs = File.Open(filePath, FileMode.Create)) { CopyStream(stream, fs); fs.Flush(); } return filePath; } protected string Expected(string filename) { return File.ReadAllText(Path.Combine(ResourcesDirectory.FullName, "expected/" + filename)); } protected string Expected(string filenameFormat, params object[] args) { return Expected(string.Format(CultureInfo.InvariantCulture, filenameFormat, args)); } protected static void AssertRefLogEntry(IRepository repo, string canonicalName, string message, ObjectId @from, ObjectId to, Identity committer, DateTimeOffset before) { var reflogEntry = repo.Refs.Log(canonicalName).First(); Assert.Equal(to, reflogEntry.To); Assert.Equal(message, reflogEntry.Message); Assert.Equal(@from ?? ObjectId.Zero, reflogEntry.From); Assert.Equal(committer.Email, reflogEntry.Committer.Email); Assert.InRange(reflogEntry.Committer.When, before, DateTimeOffset.Now); } protected static void EnableRefLog(IRepository repository, bool enable = true) { repository.Config.Set("core.logAllRefUpdates", enable); } public static void CopyStream(Stream input, Stream output) { // Reused from the following Stack Overflow post with permission // of Jon Skeet (obtained on 25 Feb 2013) // http://stackoverflow.com/questions/411592/how-do-i-save-a-stream-to-a-file/411605#411605 var buffer = new byte[8 * 1024]; int len; while ((len = input.Read(buffer, 0, buffer.Length)) > 0) { output.Write(buffer, 0, len); } } public static bool StreamEquals(Stream one, Stream two) { int onebyte, twobyte; while ((onebyte = one.ReadByte()) >= 0 && (twobyte = two.ReadByte()) >= 0) { if (onebyte != twobyte) return false; } return true; } public void AssertBelongsToARepository<T>(IRepository repo, T instance) where T : IBelongToARepository { Assert.Same(repo, ((IBelongToARepository)instance).Repository); } protected void CreateAttributesFile(IRepository repo, string attributeEntry) { Touch(repo.Info.WorkingDirectory, ".gitattributes", attributeEntry); } } }
using System; using System.IO; using System.Web; using System.Web.Mvc; using GroupDocs.Annotation; using GroupDocs.Annotation.Domain; using GroupDocs.Annotation.Exception; using GroupDocs.Annotation.Handler; using GroupDocs.Annotation.Handler.Input.DataObjects; using GroupDocs.Demo.Annotation.Mvc.App_Start; using GroupDocs.Demo.Annotation.Mvc.Options; using GroupDocs.Demo.Annotation.Mvc.Responses; using Microsoft.Practices.Unity; using AnnotationReplyInfo = GroupDocs.Demo.Annotation.Mvc.AnnotationResults.Data.AnnotationReplyInfo; using DeleteReplyResult = GroupDocs.Demo.Annotation.Mvc.AnnotationResults.DeleteReplyResult; using Point = GroupDocs.Demo.Annotation.Mvc.AnnotationResults.DataGeometry.Point; using Rectangle = GroupDocs.Demo.Annotation.Mvc.AnnotationResults.DataGeometry.Rectangle; using RestoreRepliesResult = GroupDocs.Demo.Annotation.Mvc.AnnotationResults.RestoreRepliesResult; using GroupDocs.Annotation.Common.License; namespace GroupDocs.Demo.Annotation.Mvc.Controllers { public class AnnotationController : Controller { #region Fields private readonly EmbeddedResourceManager _resourceManager; private readonly IAnnotationService _annotationSvc; #endregion Fields public AnnotationController(IAnnotationService annotationSvc) { _resourceManager = new EmbeddedResourceManager(); _annotationSvc = annotationSvc; //Here you should apply proper GroupDocs.Annotation license (in case you want to //use this sample without trial limits) new License().SetLicense("E:/GroupDocs.Total.lic"); } #region Annotation members [AcceptVerbs("GET", "POST", "OPTIONS")] public ActionResult CreateAnnotation(string connectionId, string userId, string privateKey, string fileId, byte type, string message, Rectangle rectangle, int pageNumber, Point annotationPosition, string svgPath, DrawingOptions drawingOptions, FontOptions font, string callback = null) { try { var result = _annotationSvc.CreateAnnotation(connectionId, fileId, type, message, rectangle, pageNumber, annotationPosition, svgPath, drawingOptions, font); return this.JsonOrJsonP(result, callback); } catch(AnnotatorException e) { return this.JsonOrJsonP(new FailedResponse { Reason = e.Message }, callback); } } [AcceptVerbs("GET", "POST", "OPTIONS")] public ActionResult DeleteAnnotation(string connectionId, string userId, string privateKey, string fileId, string annotationGuid, string callback = null) { try { var result = _annotationSvc.DeleteAnnotation(connectionId, fileId, annotationGuid); return this.JsonOrJsonP(result, callback); } catch(AnnotatorException e) { return this.JsonOrJsonP(new FailedResponse { Reason = e.Message }, callback); } } [AcceptVerbs("GET", "POST", "OPTIONS")] public ActionResult AddAnnotationReply(string connectionId, string userId, string privateKey, string fileId, string annotationGuid, string message, string parentReplyGuid, string callback = null) { try { var result = _annotationSvc.AddAnnotationReply(connectionId, fileId, annotationGuid, message, parentReplyGuid); return this.JsonOrJsonP(result, callback); } catch(AnnotatorException e) { return this.JsonOrJsonP(new FailedResponse { Reason = e.Message }, callback); } } [AcceptVerbs("GET", "POST", "OPTIONS")] public ActionResult DeleteAnnotationReply(string connectionId, string userId, string privateKey, string fileId, string annotationGuid, string replyGuid, string callback = null) { try { DeleteReplyResult result = _annotationSvc.DeleteAnnotationReply(connectionId, fileId, annotationGuid, replyGuid); return this.JsonOrJsonP(result, callback); } catch(AnnotatorException e) { return this.JsonOrJsonP(new FailedResponse { Reason = e.Message }, callback); } } [AcceptVerbs("GET", "POST", "OPTIONS")] public ActionResult EditAnnotationReply(string connectionId, string userId, string privateKey, string fileId, string annotationGuid, string replyGuid, string message, string callback = null) { try { var result = _annotationSvc.EditAnnotationReply(connectionId, fileId, annotationGuid, replyGuid, message); return this.JsonOrJsonP(result, callback); } catch(AnnotatorException e) { return this.JsonOrJsonP(new FailedResponse { Reason = e.Message }, callback); } } [AcceptVerbs("GET", "POST", "OPTIONS")] public ActionResult RestoreAnnotationReplies(string connectionId, string fileId, string annotationGuid, AnnotationReplyInfo[] replies, string callback = null) { try { var result = (replies == null || replies.Length == 0 ? new RestoreRepliesResult { AnnotationGuid = annotationGuid, ReplyIds = new string[0] } : _annotationSvc.RestoreAnnotationReplies(connectionId, fileId, annotationGuid, replies)); return this.JsonOrJsonP(result, callback); } catch(AnnotatorException e) { return this.JsonOrJsonP(new FailedResponse { Reason = e.Message }, callback); } } [AcceptVerbs("GET", "POST", "OPTIONS")] public ActionResult ListAnnotations(string connectionId, string userId, string privateKey, string fileId, string callback = null) { try { var result = _annotationSvc.ListAnnotations(connectionId, fileId); return this.JsonOrJsonP(result, callback); } catch(AnnotatorException e) { return this.JsonOrJsonP(new FailedResponse { Reason = e.Message }, callback); } } [AcceptVerbs("GET", "POST", "OPTIONS")] public ActionResult ResizeAnnotation(string connectionId, string fileId, string annotationGuid, double width, double height, string callback = null) { try { var result = _annotationSvc.ResizeAnnotation(connectionId, fileId, annotationGuid, width, height); return this.JsonOrJsonP(result, callback); } catch(AnnotatorException e) { return this.JsonOrJsonP(new FailedResponse { Reason = e.Message }, callback); } } [AcceptVerbs("GET", "POST", "OPTIONS")] public ActionResult MoveAnnotationMarker(string connectionId, string userId, string privateKey, string fileId, string annotationGuid, double left, double top, int? pageNumber, string callback = null) { try { var result = _annotationSvc.MoveAnnotationMarker(connectionId, fileId, annotationGuid, left, top, pageNumber); return this.JsonOrJsonP(result, callback); } catch(AnnotatorException e) { return this.JsonOrJsonP(new FailedResponse { Reason = e.Message }, callback); } } [AcceptVerbs("GET", "POST", "OPTIONS")] public ActionResult SaveTextField(string connectionId, string userId, string privateKey, string fileId, string annotationGuid, string text, string fontFamily, double fontSize, string callback = null) { try { var result = _annotationSvc.SaveTextField(connectionId, fileId, annotationGuid, text, fontFamily, fontSize); return this.JsonOrJsonP(result, callback); } catch(AnnotatorException e) { return this.JsonOrJsonP(new FailedResponse { Reason = e.Message }, callback); } } [AcceptVerbs("GET", "POST", "OPTIONS")] public ActionResult SetTextFieldColor(string connectionId, string fileId, string annotationGuid, int fontColor, string callback = null) { try { var result = _annotationSvc.SetTextFieldColor(connectionId, fileId, annotationGuid, fontColor); return this.JsonOrJsonP(new FailedResponse { success = true }, callback); } catch(AnnotatorException e) { return this.JsonOrJsonP(new FailedResponse { Reason = e.Message }, callback); } } [AcceptVerbs("GET", "POST", "OPTIONS")] public ActionResult SetAnnotationBackgroundColor(string connectionId, string fileId, string annotationGuid, int color, string callback = null) { try { var result = _annotationSvc.SetAnnotationBackgroundColor(connectionId, fileId, annotationGuid, color); return this.JsonOrJsonP(new FailedResponse { success = true }, callback); } catch(AnnotatorException e) { return this.JsonOrJsonP(new FailedResponse { Reason = e.Message }, callback); } } [AcceptVerbs("GET", "POST", "OPTIONS")] public ActionResult GetDocumentCollaborators(string userId, string privateKey, string fileId, string callback = null) { var result = _annotationSvc.GetCollaborators(fileId); return this.JsonOrJsonP(result, callback); } [AcceptVerbs("GET", "POST", "OPTIONS")] public ActionResult AddDocumentReviewer(string userId, string privateKey, string fileId, string reviewerEmail, string reviewerFirstName, string reviewerLastName, string reviewerInvitationMessage, string callback = null) { var result = _annotationSvc.AddCollaborator(fileId, reviewerEmail, reviewerFirstName, reviewerLastName, reviewerInvitationMessage); return this.JsonOrJsonP(result, callback); } [AcceptVerbs("GET", "POST", "OPTIONS")] public ActionResult ExportAnnotations(string connectionId, string fileId, string format, string mode, string callback = null) { try { string fileName = _annotationSvc.ExportAnnotations(connectionId, fileId); var url = Url.Action("DownloadFile", new { path = new HtmlString(fileName) }); return this.JsonOrJsonP(new UrlResponse(url), callback); } catch(Exception e) { return this.JsonOrJsonP(new FailedResponse { success = false, Reason = e.Message }, callback); } } [AcceptVerbs("GET", "POST", "OPTIONS")] public ActionResult ImportAnnotations(string connectionId, string fileGuid, string callback = null) { try { _annotationSvc.ImportAnnotations(connectionId, fileGuid); return this.JsonOrJsonP(new FileResponse(fileGuid), callback); } catch(Exception e) { return this.JsonOrJsonP(new FailedResponse { success = false, Reason = e.Message }, callback); } } [AcceptVerbs("GET", "POST", "OPTIONS")] public ActionResult GetPdfVersionOfDocument(string connectionId, string fileId, string callback = null) { try { var fileName = _annotationSvc.GetAsPdf(connectionId, fileId); var url = this.Url.Action("DownloadFile", new { path = fileName }); return this.JsonOrJsonP(new UrlResponse(url), callback); } catch(Exception e) { return this.JsonOrJsonP(new FailedResponse { success = false, Reason = e.Message }, callback); } } [AcceptVerbs("GET", "POST", "OPTIONS")] public ActionResult DownloadFile(string path) { var filePath = AppDomain.CurrentDomain.GetData("DataDirectory") + "/" + path; return File(filePath, "application/pdf", Path.GetFileName(path)); } [AcceptVerbs("GET", "POST", "OPTIONS")] public ActionResult UploadFile(string user_id, string fld, string fileName, bool? multiple = false, string callback = null) { var user = UnityConfig.GetConfiguredContainer().Resolve<AnnotationImageHandler>().GetUserDataHandler().GetUserByGuid(user_id) ?? new User(); try { var files = HttpContext.Request.Files; var uploadDir = Path.Combine(Server.MapPath("~/App_Data"), fld); var filePath = Path.Combine(uploadDir, fileName ?? files[0].FileName); Directory.CreateDirectory(uploadDir); using (var stream = System.IO.File.Create(filePath)) { ((multiple ?? false) ? HttpContext.Request.InputStream : files[0].InputStream).CopyTo(stream); } var fileId = Path.Combine(fld, fileName ?? files[0].FileName); AnnotationImageHandler annotator = UnityConfig.GetConfiguredContainer().Resolve<AnnotationImageHandler>(); try { annotator.CreateDocument(fileId, DocumentType.Pdf, user.Id); } catch (AnnotatorException e) { if (annotator.RemoveDocument(fileId)) { annotator.CreateDocument(fileId, DocumentType.Pdf, user.Id); } } return this.JsonOrJsonP(new FileResponse(fileId), callback); } catch (Exception e) { return this.JsonOrJsonP(new FailedResponse {success = false, Reason = e.Message}, callback); } } #endregion Annotation members public ActionResult GetScript(string name) { string script = _resourceManager.GetScript(name); return new JavaScriptResult { Script = script }; } public ActionResult GetCss(string name) { string css = _resourceManager.GetCss(name); return Content(css, "text/css"); } public ActionResult GetEmbeddedImage(string name) { byte[] imageBody = _resourceManager.GetBinaryResource(name); string mimeType = "image/png"; return File(imageBody, mimeType); } public ActionResult GetAvatar(string userId) { var collaborator = _annotationSvc.GetCollaboratorMetadata(userId); if(collaborator == null || collaborator.Avatar == null) { return new EmptyResult(); } const string mimeType = "image/png"; return File(collaborator.Avatar, mimeType); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.RegionCombinerModule { public class RegionCombinerPermissionModule { private Scene m_rootScene; public RegionCombinerPermissionModule(Scene RootScene) { m_rootScene = RootScene; } #region Permission Override public bool BypassPermissions() { return m_rootScene.Permissions.BypassPermissions(); } public void SetBypassPermissions(bool value) { m_rootScene.Permissions.SetBypassPermissions(value); } public bool PropagatePermissions() { return m_rootScene.Permissions.PropagatePermissions(); } public uint GenerateClientFlags(UUID userid, UUID objectidid) { return m_rootScene.Permissions.GenerateClientFlags(userid,objectidid); } public bool CanAbandonParcel(UUID user, ILandObject parcel, Scene scene) { return m_rootScene.Permissions.CanAbandonParcel(user,parcel); } public bool CanReclaimParcel(UUID user, ILandObject parcel, Scene scene) { return m_rootScene.Permissions.CanReclaimParcel(user, parcel); } public bool CanDeedParcel(UUID user, ILandObject parcel, Scene scene) { return m_rootScene.Permissions.CanDeedParcel(user, parcel); } public bool CanDeedObject(UUID user, UUID @group, Scene scene) { return m_rootScene.Permissions.CanDeedObject(user,@group); } public bool IsGod(UUID user, Scene requestfromscene) { return m_rootScene.Permissions.IsGod(user); } public bool CanDuplicateObject(int objectcount, UUID objectid, UUID owner, Scene scene, Vector3 objectposition) { return m_rootScene.Permissions.CanDuplicateObject(objectcount, objectid, owner, objectposition); } public bool CanDeleteObject(UUID objectid, UUID deleter, Scene scene) { return m_rootScene.Permissions.CanDeleteObject(objectid, deleter); } public bool CanEditObject(UUID objectid, UUID editorid, Scene scene) { return m_rootScene.Permissions.CanEditObject(objectid, editorid); } public bool CanEditParcelProperties(UUID user, ILandObject parcel, GroupPowers g, Scene scene, bool allowManager) { return m_rootScene.Permissions.CanEditParcelProperties(user, parcel, g, allowManager); } public bool CanInstantMessage(UUID user, UUID target, Scene startscene) { return m_rootScene.Permissions.CanInstantMessage(user, target); } public bool CanInventoryTransfer(UUID user, UUID target, Scene startscene) { return m_rootScene.Permissions.CanInventoryTransfer(user, target); } public bool CanIssueEstateCommand(UUID user, Scene requestfromscene, bool ownercommand) { return m_rootScene.Permissions.CanIssueEstateCommand(user, ownercommand); } public bool CanMoveObject(UUID objectid, UUID moverid, Scene scene) { return m_rootScene.Permissions.CanMoveObject(objectid, moverid); } public bool CanObjectEntry(UUID objectid, bool enteringregion, Vector3 newpoint, Scene scene) { return m_rootScene.Permissions.CanObjectEntry(objectid, enteringregion, newpoint); } public bool CanReturnObjects(ILandObject land, UUID user, List<SceneObjectGroup> objects, Scene scene) { return m_rootScene.Permissions.CanReturnObjects(land, user, objects); } public bool CanRezObject(int objectcount, UUID owner, Vector3 objectposition, Scene scene) { return m_rootScene.Permissions.CanRezObject(objectcount, owner, objectposition); } public bool CanRunConsoleCommand(UUID user, Scene requestfromscene) { return m_rootScene.Permissions.CanRunConsoleCommand(user); } public bool CanRunScript(UUID script, UUID objectid, UUID user, Scene scene) { return m_rootScene.Permissions.CanRunScript(script, objectid, user); } public bool CanCompileScript(UUID owneruuid, int scripttype, Scene scene) { return m_rootScene.Permissions.CanCompileScript(owneruuid, scripttype); } public bool CanSellParcel(UUID user, ILandObject parcel, Scene scene) { return m_rootScene.Permissions.CanSellParcel(user, parcel); } public bool CanTakeObject(UUID objectid, UUID stealer, Scene scene) { return m_rootScene.Permissions.CanTakeObject(objectid, stealer); } public bool CanTakeCopyObject(UUID objectid, UUID userid, Scene inscene) { return m_rootScene.Permissions.CanTakeObject(objectid, userid); } public bool CanTerraformLand(UUID user, Vector3 position, Scene requestfromscene) { return m_rootScene.Permissions.CanTerraformLand(user, position); } public bool CanLinkObject(UUID user, UUID objectid) { return m_rootScene.Permissions.CanLinkObject(user, objectid); } public bool CanDelinkObject(UUID user, UUID objectid) { return m_rootScene.Permissions.CanDelinkObject(user, objectid); } public bool CanBuyLand(UUID user, ILandObject parcel, Scene scene) { return m_rootScene.Permissions.CanBuyLand(user, parcel); } public bool CanViewNotecard(UUID script, UUID objectid, UUID user, Scene scene) { return m_rootScene.Permissions.CanViewNotecard(script, objectid, user); } public bool CanViewScript(UUID script, UUID objectid, UUID user, Scene scene) { return m_rootScene.Permissions.CanViewScript(script, objectid, user); } public bool CanEditNotecard(UUID notecard, UUID objectid, UUID user, Scene scene) { return m_rootScene.Permissions.CanEditNotecard(notecard, objectid, user); } public bool CanEditScript(UUID script, UUID objectid, UUID user, Scene scene) { return m_rootScene.Permissions.CanEditScript(script, objectid, user); } public bool CanCreateObjectInventory(int invtype, UUID objectid, UUID userid) { return m_rootScene.Permissions.CanCreateObjectInventory(invtype, objectid, userid); } public bool CanEditObjectInventory(UUID objectid, UUID editorid, Scene scene) { return m_rootScene.Permissions.CanEditObjectInventory(objectid, editorid); } public bool CanCopyObjectInventory(UUID itemid, UUID objectid, UUID userid) { return m_rootScene.Permissions.CanCopyObjectInventory(itemid, objectid, userid); } public bool CanDeleteObjectInventory(UUID itemid, UUID objectid, UUID userid) { return m_rootScene.Permissions.CanDeleteObjectInventory(itemid, objectid, userid); } public bool CanResetScript(UUID prim, UUID script, UUID user, Scene scene) { return m_rootScene.Permissions.CanResetScript(prim, script, user); } public bool CanCreateUserInventory(int invtype, UUID userid) { return m_rootScene.Permissions.CanCreateUserInventory(invtype, userid); } public bool CanCopyUserInventory(UUID itemid, UUID userid) { return m_rootScene.Permissions.CanCopyUserInventory(itemid, userid); } public bool CanEditUserInventory(UUID itemid, UUID userid) { return m_rootScene.Permissions.CanEditUserInventory(itemid, userid); } public bool CanDeleteUserInventory(UUID itemid, UUID userid) { return m_rootScene.Permissions.CanDeleteUserInventory(itemid, userid); } public bool CanTeleport(UUID userid, Scene scene) { return m_rootScene.Permissions.CanTeleport(userid); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Threading.Tasks; using Xunit; namespace System.Threading.Tests { public class SemaphoreTests : RemoteExecutorTestBase { private const int FailedWaitTimeout = 30000; [Theory] [InlineData(0, 1)] [InlineData(1, 1)] [InlineData(1, 2)] [InlineData(0, int.MaxValue)] [InlineData(int.MaxValue, int.MaxValue)] public void Ctor_InitialAndMax(int initialCount, int maximumCount) { new Semaphore(initialCount, maximumCount).Dispose(); new Semaphore(initialCount, maximumCount, null).Dispose(); } [PlatformSpecific(TestPlatforms.Windows)] // named semaphores aren't supported on Unix [Fact] public void Ctor_ValidName_Windows() { string name = Guid.NewGuid().ToString("N"); new Semaphore(0, 1, name).Dispose(); bool createdNew; new Semaphore(0, 1, name, out createdNew).Dispose(); Assert.True(createdNew); } [PlatformSpecific(TestPlatforms.AnyUnix)] // named semaphores aren't supported on Unix [Fact] public void Ctor_NamesArentSupported_Unix() { string name = Guid.NewGuid().ToString("N"); Assert.Throws<PlatformNotSupportedException>(() => new Semaphore(0, 1, name)); Assert.Throws<PlatformNotSupportedException>(() => { bool createdNew; new Semaphore(0, 1, name, out createdNew).Dispose(); }); } [Fact] public void Ctor_InvalidArguments() { bool createdNew; AssertExtensions.Throws<ArgumentOutOfRangeException>("initialCount", () => new Semaphore(-1, 1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("initialCount", () => new Semaphore(-2, 1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("maximumCount", () => new Semaphore(0, 0)); Assert.Throws<ArgumentException>(() => new Semaphore(2, 1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("initialCount", () => new Semaphore(-1, 1, null)); AssertExtensions.Throws<ArgumentOutOfRangeException>("initialCount", () => new Semaphore(-2, 1, null)); AssertExtensions.Throws<ArgumentOutOfRangeException>("maximumCount", () => new Semaphore(0, 0, null)); Assert.Throws<ArgumentException>(() => new Semaphore(2, 1, null)); AssertExtensions.Throws<ArgumentOutOfRangeException>("initialCount", () => new Semaphore(-1, 1, "CtorSemaphoreTest", out createdNew)); AssertExtensions.Throws<ArgumentOutOfRangeException>("initialCount", () => new Semaphore(-2, 1, "CtorSemaphoreTest", out createdNew)); AssertExtensions.Throws<ArgumentOutOfRangeException>("maximumCount", () => new Semaphore(0, 0, "CtorSemaphoreTest", out createdNew)); Assert.Throws<ArgumentException>(() => new Semaphore(2, 1, "CtorSemaphoreTest", out createdNew)); } [PlatformSpecific(TestPlatforms.Windows)] // named semaphores aren't supported on Unix [Fact] public void Ctor_InvalidNames() { Assert.Throws<ArgumentException>(() => new Semaphore(0, 1, new string('a', 10000))); bool createdNew; Assert.Throws<ArgumentException>(() => new Semaphore(0, 1, new string('a', 10000), out createdNew)); } [Fact] public void CanWaitWithoutBlockingUntilNoCount() { const int InitialCount = 5; using (Semaphore s = new Semaphore(InitialCount, InitialCount)) { for (int i = 0; i < InitialCount; i++) Assert.True(s.WaitOne(0)); Assert.False(s.WaitOne(0)); } } [Fact] public void CanWaitWithoutBlockingForReleasedCount() { using (Semaphore s = new Semaphore(0, Int32.MaxValue)) { for (int counts = 1; counts < 5; counts++) { Assert.False(s.WaitOne(0)); if (counts % 2 == 0) { for (int i = 0; i < counts; i++) s.Release(); } else { s.Release(counts); } for (int i = 0; i < counts; i++) { Assert.True(s.WaitOne(0)); } Assert.False(s.WaitOne(0)); } } } [Fact] public void Release() { using (Semaphore s = new Semaphore(1, 1)) { Assert.Throws<SemaphoreFullException>(() => s.Release()); } using (Semaphore s = new Semaphore(0, 10)) { Assert.Throws<SemaphoreFullException>(() => s.Release(11)); AssertExtensions.Throws<ArgumentOutOfRangeException>("releaseCount", () => s.Release(-1)); } using (Semaphore s = new Semaphore(0, 10)) { for (int i = 0; i < 10; i++) { Assert.Equal(i, s.Release()); } } } [Fact] public void AnonymousProducerConsumer() { using (Semaphore s = new Semaphore(0, Int32.MaxValue)) { const int NumItems = 5; Task.WaitAll( Task.Factory.StartNew(() => { for (int i = 0; i < NumItems; i++) Assert.True(s.WaitOne(FailedWaitTimeout)); Assert.False(s.WaitOne(0)); }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default), Task.Factory.StartNew(() => { for (int i = 0; i < NumItems; i++) s.Release(); }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default)); } } [PlatformSpecific(TestPlatforms.Windows)] // named semaphores aren't supported on Unix [Fact] public void NamedProducerConsumer() { string name = Guid.NewGuid().ToString("N"); const int NumItems = 5; var b = new Barrier(2); Task.WaitAll( Task.Factory.StartNew(() => { using (var s = new Semaphore(0, int.MaxValue, name)) { Assert.True(b.SignalAndWait(FailedWaitTimeout)); for (int i = 0; i < NumItems; i++) Assert.True(s.WaitOne(FailedWaitTimeout)); Assert.False(s.WaitOne(0)); } }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default), Task.Factory.StartNew(() => { using (var s = new Semaphore(0, int.MaxValue, name)) { Assert.True(b.SignalAndWait(FailedWaitTimeout)); for (int i = 0; i < NumItems; i++) s.Release(); } }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default)); } [PlatformSpecific(TestPlatforms.AnyUnix)] // named semaphores aren't supported on Unix [Fact] public void OpenExisting_NotSupported_Unix() { Assert.Throws<PlatformNotSupportedException>(() => Semaphore.OpenExisting(null)); Assert.Throws<PlatformNotSupportedException>(() => Semaphore.OpenExisting(string.Empty)); Assert.Throws<PlatformNotSupportedException>(() => Semaphore.OpenExisting("anything")); Semaphore semaphore; Assert.Throws<PlatformNotSupportedException>(() => Semaphore.TryOpenExisting("anything", out semaphore)); } [PlatformSpecific(TestPlatforms.Windows)] // named semaphores aren't supported on Unix [Fact] public void OpenExisting_InvalidNames_Windows() { AssertExtensions.Throws<ArgumentNullException>("name", () => Semaphore.OpenExisting(null)); Assert.Throws<ArgumentException>(() => Semaphore.OpenExisting(string.Empty)); Assert.Throws<ArgumentException>(() => Semaphore.OpenExisting(new string('a', 10000))); } [PlatformSpecific(TestPlatforms.Windows)] // named semaphores aren't supported on Unix [Fact] public void OpenExisting_UnavailableName_Windows() { string name = Guid.NewGuid().ToString("N"); Assert.Throws<WaitHandleCannotBeOpenedException>(() => Semaphore.OpenExisting(name)); Semaphore ignored; Assert.False(Semaphore.TryOpenExisting(name, out ignored)); } [PlatformSpecific(TestPlatforms.Windows)] // named semaphores aren't supported on Unix [Fact] public void OpenExisting_NameUsedByOtherSynchronizationPrimitive_Windows() { string name = Guid.NewGuid().ToString("N"); using (Mutex mtx = new Mutex(true, name)) { Assert.Throws<WaitHandleCannotBeOpenedException>(() => Semaphore.OpenExisting(name)); Semaphore ignored; Assert.False(Semaphore.TryOpenExisting(name, out ignored)); } } [PlatformSpecific(TestPlatforms.Windows)] // named semaphores aren't supported on Unix [Fact] public void OpenExisting_SameAsOriginal_Windows() { string name = Guid.NewGuid().ToString("N"); bool createdNew; using (Semaphore s1 = new Semaphore(0, Int32.MaxValue, name, out createdNew)) { Assert.True(createdNew); using (Semaphore s2 = Semaphore.OpenExisting(name)) { Assert.False(s1.WaitOne(0)); Assert.False(s2.WaitOne(0)); s1.Release(); Assert.True(s2.WaitOne(0)); Assert.False(s2.WaitOne(0)); s2.Release(); Assert.True(s1.WaitOne(0)); Assert.False(s1.WaitOne(0)); } Semaphore s3; Assert.True(Semaphore.TryOpenExisting(name, out s3)); using (s3) { Assert.False(s1.WaitOne(0)); Assert.False(s3.WaitOne(0)); s1.Release(); Assert.True(s3.WaitOne(0)); Assert.False(s3.WaitOne(0)); s3.Release(); Assert.True(s1.WaitOne(0)); Assert.False(s1.WaitOne(0)); } } } [PlatformSpecific(TestPlatforms.Windows)] // names aren't supported on Unix [Fact] public void PingPong() { // Create names for the two semaphores string outboundName = Guid.NewGuid().ToString("N"); string inboundName = Guid.NewGuid().ToString("N"); // Create the two semaphores and the other process with which to synchronize using (var inbound = new Semaphore(1, 1, inboundName)) using (var outbound = new Semaphore(0, 1, outboundName)) using (var remote = RemoteInvoke(PingPong_OtherProcess, outboundName, inboundName)) { // Repeatedly wait for count in one semaphore and then release count into the other for (int i = 0; i < 10; i++) { Assert.True(inbound.WaitOne(FailWaitTimeoutMilliseconds)); outbound.Release(); } } } private static int PingPong_OtherProcess(string inboundName, string outboundName) { // Open the two semaphores using (var inbound = Semaphore.OpenExisting(inboundName)) using (var outbound = Semaphore.OpenExisting(outboundName)) { // Repeatedly wait for count in one semaphore and then release count into the other for (int i = 0; i < 10; i++) { Assert.True(inbound.WaitOne(FailWaitTimeoutMilliseconds)); outbound.Release(); } } return SuccessExitCode; } } }
#region Copyright notice and license // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * 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 Google Inc. 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. #endregion using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Grpc.Core; namespace grpc.testing { /// <summary> /// TestService (this is handwritten version of code that will normally be generated). /// </summary> public class TestServiceGrpc { static readonly string ServiceName = "/grpc.testing.TestService"; static readonly Marshaller<Empty> EmptyMarshaller = Marshallers.Create((arg) => arg.ToByteArray(), Empty.ParseFrom); static readonly Marshaller<SimpleRequest> SimpleRequestMarshaller = Marshallers.Create((arg) => arg.ToByteArray(), SimpleRequest.ParseFrom); static readonly Marshaller<SimpleResponse> SimpleResponseMarshaller = Marshallers.Create((arg) => arg.ToByteArray(), SimpleResponse.ParseFrom); static readonly Marshaller<StreamingOutputCallRequest> StreamingOutputCallRequestMarshaller = Marshallers.Create((arg) => arg.ToByteArray(), StreamingOutputCallRequest.ParseFrom); static readonly Marshaller<StreamingOutputCallResponse> StreamingOutputCallResponseMarshaller = Marshallers.Create((arg) => arg.ToByteArray(), StreamingOutputCallResponse.ParseFrom); static readonly Marshaller<StreamingInputCallRequest> StreamingInputCallRequestMarshaller = Marshallers.Create((arg) => arg.ToByteArray(), StreamingInputCallRequest.ParseFrom); static readonly Marshaller<StreamingInputCallResponse> StreamingInputCallResponseMarshaller = Marshallers.Create((arg) => arg.ToByteArray(), StreamingInputCallResponse.ParseFrom); static readonly Method<Empty, Empty> EmptyCallMethod = new Method<Empty, Empty>( MethodType.Unary, "EmptyCall", EmptyMarshaller, EmptyMarshaller); static readonly Method<SimpleRequest, SimpleResponse> UnaryCallMethod = new Method<SimpleRequest, SimpleResponse>( MethodType.Unary, "UnaryCall", SimpleRequestMarshaller, SimpleResponseMarshaller); static readonly Method<StreamingOutputCallRequest, StreamingOutputCallResponse> StreamingOutputCallMethod = new Method<StreamingOutputCallRequest, StreamingOutputCallResponse>( MethodType.ServerStreaming, "StreamingOutputCall", StreamingOutputCallRequestMarshaller, StreamingOutputCallResponseMarshaller); static readonly Method<StreamingInputCallRequest, StreamingInputCallResponse> StreamingInputCallMethod = new Method<StreamingInputCallRequest, StreamingInputCallResponse>( MethodType.ClientStreaming, "StreamingInputCall", StreamingInputCallRequestMarshaller, StreamingInputCallResponseMarshaller); static readonly Method<StreamingOutputCallRequest, StreamingOutputCallResponse> FullDuplexCallMethod = new Method<StreamingOutputCallRequest, StreamingOutputCallResponse>( MethodType.DuplexStreaming, "FullDuplexCall", StreamingOutputCallRequestMarshaller, StreamingOutputCallResponseMarshaller); static readonly Method<StreamingOutputCallRequest, StreamingOutputCallResponse> HalfDuplexCallMethod = new Method<StreamingOutputCallRequest, StreamingOutputCallResponse>( MethodType.DuplexStreaming, "HalfDuplexCall", StreamingOutputCallRequestMarshaller, StreamingOutputCallResponseMarshaller); public interface ITestServiceClient { Empty EmptyCall(Empty request, CancellationToken token = default(CancellationToken)); Task<Empty> EmptyCallAsync(Empty request, CancellationToken token = default(CancellationToken)); SimpleResponse UnaryCall(SimpleRequest request, CancellationToken token = default(CancellationToken)); Task<SimpleResponse> UnaryCallAsync(SimpleRequest request, CancellationToken token = default(CancellationToken)); AsyncServerStreamingCall<StreamingOutputCallResponse> StreamingOutputCall(StreamingOutputCallRequest request, CancellationToken token = default(CancellationToken)); AsyncClientStreamingCall<StreamingInputCallRequest, StreamingInputCallResponse> StreamingInputCall(CancellationToken token = default(CancellationToken)); AsyncDuplexStreamingCall<StreamingOutputCallRequest, StreamingOutputCallResponse> FullDuplexCall(CancellationToken token = default(CancellationToken)); AsyncDuplexStreamingCall<StreamingOutputCallRequest, StreamingOutputCallResponse> HalfDuplexCall(CancellationToken token = default(CancellationToken)); } public class TestServiceClientStub : AbstractStub<TestServiceClientStub, StubConfiguration>, ITestServiceClient { public TestServiceClientStub(Channel channel) : base(channel, StubConfiguration.Default) { } public TestServiceClientStub(Channel channel, StubConfiguration config) : base(channel, config) { } public Empty EmptyCall(Empty request, CancellationToken token = default(CancellationToken)) { var call = CreateCall(ServiceName, EmptyCallMethod); return Calls.BlockingUnaryCall(call, request, token); } public Task<Empty> EmptyCallAsync(Empty request, CancellationToken token = default(CancellationToken)) { var call = CreateCall(ServiceName, EmptyCallMethod); return Calls.AsyncUnaryCall(call, request, token); } public SimpleResponse UnaryCall(SimpleRequest request, CancellationToken token = default(CancellationToken)) { var call = CreateCall(ServiceName, UnaryCallMethod); return Calls.BlockingUnaryCall(call, request, token); } public Task<SimpleResponse> UnaryCallAsync(SimpleRequest request, CancellationToken token = default(CancellationToken)) { var call = CreateCall(ServiceName, UnaryCallMethod); return Calls.AsyncUnaryCall(call, request, token); } public AsyncServerStreamingCall<StreamingOutputCallResponse> StreamingOutputCall(StreamingOutputCallRequest request, CancellationToken token = default(CancellationToken)) { var call = CreateCall(ServiceName, StreamingOutputCallMethod); return Calls.AsyncServerStreamingCall(call, request, token); } public AsyncClientStreamingCall<StreamingInputCallRequest, StreamingInputCallResponse> StreamingInputCall(CancellationToken token = default(CancellationToken)) { var call = CreateCall(ServiceName, StreamingInputCallMethod); return Calls.AsyncClientStreamingCall(call, token); } public AsyncDuplexStreamingCall<StreamingOutputCallRequest, StreamingOutputCallResponse> FullDuplexCall(CancellationToken token = default(CancellationToken)) { var call = CreateCall(ServiceName, FullDuplexCallMethod); return Calls.AsyncDuplexStreamingCall(call, token); } public AsyncDuplexStreamingCall<StreamingOutputCallRequest, StreamingOutputCallResponse> HalfDuplexCall(CancellationToken token = default(CancellationToken)) { var call = CreateCall(ServiceName, HalfDuplexCallMethod); return Calls.AsyncDuplexStreamingCall(call, token); } } // server-side interface public interface ITestService { Task<Empty> EmptyCall(ServerCallContext context, Empty request); Task<SimpleResponse> UnaryCall(ServerCallContext context, SimpleRequest request); Task StreamingOutputCall(ServerCallContext context, StreamingOutputCallRequest request, IServerStreamWriter<StreamingOutputCallResponse> responseStream); Task<StreamingInputCallResponse> StreamingInputCall(ServerCallContext context, IAsyncStreamReader<StreamingInputCallRequest> requestStream); Task FullDuplexCall(ServerCallContext context, IAsyncStreamReader<StreamingOutputCallRequest> requestStream, IServerStreamWriter<StreamingOutputCallResponse> responseStream); Task HalfDuplexCall(ServerCallContext context, IAsyncStreamReader<StreamingOutputCallRequest> requestStream, IServerStreamWriter<StreamingOutputCallResponse> responseStream); } public static ServerServiceDefinition BindService(ITestService serviceImpl) { return ServerServiceDefinition.CreateBuilder(ServiceName) .AddMethod(EmptyCallMethod, serviceImpl.EmptyCall) .AddMethod(UnaryCallMethod, serviceImpl.UnaryCall) .AddMethod(StreamingOutputCallMethod, serviceImpl.StreamingOutputCall) .AddMethod(StreamingInputCallMethod, serviceImpl.StreamingInputCall) .AddMethod(FullDuplexCallMethod, serviceImpl.FullDuplexCall) .AddMethod(HalfDuplexCallMethod, serviceImpl.HalfDuplexCall) .Build(); } public static ITestServiceClient NewStub(Channel channel) { return new TestServiceClientStub(channel); } } }
// 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.Net.Security; using System.Runtime.InteropServices; using System.Security.Authentication; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; using Microsoft.Win32.SafeHandles; using CURLcode = Interop.Http.CURLcode; using CURLINFO = Interop.Http.CURLINFO; namespace System.Net.Http { internal partial class CurlHandler : HttpMessageHandler { private static class SslProvider { private static readonly Interop.Http.SslCtxCallback s_sslCtxCallback = SslCtxCallback; private static readonly Interop.Ssl.AppVerifyCallback s_sslVerifyCallback = VerifyCertChain; private static readonly Oid s_serverAuthOid = new Oid("1.3.6.1.5.5.7.3.1"); internal static void SetSslOptions(EasyRequest easy, ClientCertificateOption clientCertOption) { Debug.Assert(clientCertOption == ClientCertificateOption.Automatic || clientCertOption == ClientCertificateOption.Manual); // Create a client certificate provider if client certs may be used. X509Certificate2Collection clientCertificates = easy._handler._clientCertificates; ClientCertificateProvider certProvider = clientCertOption == ClientCertificateOption.Automatic ? new ClientCertificateProvider(null) : // automatic clientCertificates?.Count > 0 ? new ClientCertificateProvider(clientCertificates) : // manual with certs null; // manual without certs IntPtr userPointer = IntPtr.Zero; if (certProvider != null) { // The client cert provider needs to be passed through to the callback, and thus // we create a GCHandle to keep it rooted. This handle needs to be cleaned up // when the request has completed, and a simple and pay-for-play way to do that // is by cleaning it up in a continuation off of the request. userPointer = GCHandle.ToIntPtr(certProvider._gcHandle); easy.Task.ContinueWith((_, state) => ((IDisposable)state).Dispose(), certProvider, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } // Register the callback with libcurl. We need to register even if there's no user-provided // server callback and even if there are no client certificates, because we support verifying // server certificates against more than those known to OpenSSL. if (CurlSslVersionDescription.IndexOf("openssl/1.0", StringComparison.OrdinalIgnoreCase) != -1) { CURLcode answer = easy.SetSslCtxCallback(s_sslCtxCallback, userPointer); switch (answer) { case CURLcode.CURLE_OK: // We successfully registered. If we'll be invoking a user-provided callback to verify the server // certificate as part of that, disable libcurl's verification of the host name. The user's callback // needs to be given the opportunity to examine the cert, and our logic will determine whether // the host name matches and will inform the callback of that. if (easy._handler.ServerCertificateValidationCallback != null) { easy.SetCurlOption(Interop.Http.CURLoption.CURLOPT_SSL_VERIFYHOST, 0); // don't verify the peer cert's hostname // We don't change the SSL_VERIFYPEER setting, as setting it to 0 will cause // SSL and libcurl to ignore the result of the server callback. } // The allowed SSL protocols will be set in the configuration callback. break; case CURLcode.CURLE_UNKNOWN_OPTION: // Curl 7.38 and prior case CURLcode.CURLE_NOT_BUILT_IN: // Curl 7.39 and later // It's ok if we failed to register the callback if all of the defaults are in play // with relation to handling of certificates. But if that's not the case, failing to // register the callback will result in those options not being factored in, which is // a significant enough error that we need to fail. EventSourceTrace("CURLOPT_SSL_CTX_FUNCTION not supported: {0}", answer, easy: easy); if (certProvider != null || easy._handler.ServerCertificateValidationCallback != null || easy._handler.CheckCertificateRevocationList) { throw new PlatformNotSupportedException( SR.Format(SR.net_http_unix_invalid_certcallback_option, CurlVersionDescription, CurlSslVersionDescription)); } // Since there won't be a callback to configure the allowed SSL protocols, configure them here. SetSslVersion(easy); break; default: ThrowIfCURLEError(answer); break; } } else { // For newer versions of openssl throw PNSE, if default not used. if (certProvider != null) { throw new PlatformNotSupportedException( SR.Format( SR.net_http_libcurl_clientcerts_notsupported, CurlVersionDescription, CurlSslVersionDescription)); } if (easy._handler.ServerCertificateValidationCallback != null) { throw new PlatformNotSupportedException( SR.Format( SR.net_http_libcurl_callback_notsupported, CurlVersionDescription, CurlSslVersionDescription)); } if (easy._handler.CheckCertificateRevocationList) { throw new PlatformNotSupportedException( SR.Format( SR.net_http_libcurl_revocation_notsupported, CurlVersionDescription, CurlSslVersionDescription)); } // In case of defaults configure the allowed SSL protocols. SetSslVersion(easy); } } private static void SetSslVersion(EasyRequest easy, IntPtr sslCtx = default(IntPtr)) { // Get the requested protocols. SslProtocols protocols = easy._handler.SslProtocols; if (protocols == SslProtocols.None) { // Let libcurl use its defaults if None is set. return; } // We explicitly disallow choosing SSL2/3. Make sure they were filtered out. Debug.Assert((protocols & ~SecurityProtocol.AllowedSecurityProtocols) == 0, "Disallowed protocols should have been filtered out."); // libcurl supports options for either enabling all of the TLS1.* protocols or enabling // just one of them; it doesn't currently support enabling two of the three, e.g. you can't // pick TLS1.1 and TLS1.2 but not TLS1.0, but you can select just TLS1.2. Interop.Http.CurlSslVersion curlSslVersion; switch (protocols) { case SslProtocols.Tls: curlSslVersion = Interop.Http.CurlSslVersion.CURL_SSLVERSION_TLSv1_0; break; case SslProtocols.Tls11: curlSslVersion = Interop.Http.CurlSslVersion.CURL_SSLVERSION_TLSv1_1; break; case SslProtocols.Tls12: curlSslVersion = Interop.Http.CurlSslVersion.CURL_SSLVERSION_TLSv1_2; break; case SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12: curlSslVersion = Interop.Http.CurlSslVersion.CURL_SSLVERSION_TLSv1; break; default: throw new NotSupportedException(SR.net_securityprotocolnotsupported); } try { easy.SetCurlOption(Interop.Http.CURLoption.CURLOPT_SSLVERSION, (long)curlSslVersion); } catch (CurlException e) when (e.HResult == (int)CURLcode.CURLE_UNKNOWN_OPTION) { throw new NotSupportedException(SR.net_securityprotocolnotsupported, e); } } private static CURLcode SslCtxCallback(IntPtr curl, IntPtr sslCtx, IntPtr userPointer) { EasyRequest easy; if (!TryGetEasyRequest(curl, out easy)) { return CURLcode.CURLE_ABORTED_BY_CALLBACK; } // Configure the SSL protocols allowed. SslProtocols protocols = easy._handler.SslProtocols; if (protocols == SslProtocols.None) { // If None is selected, let OpenSSL use its defaults, but with SSL2/3 explicitly disabled. // Since the shim/OpenSSL work on a disabling system, where any protocols for which bits aren't // set are disabled, we set all of the bits other than those we want disabled. #pragma warning disable 0618 // the enum values are obsolete protocols = ~(SslProtocols.Ssl2 | SslProtocols.Ssl3); #pragma warning restore 0618 } Interop.Ssl.SetProtocolOptions(sslCtx, protocols); // Configure the SSL server certificate verification callback. Interop.Ssl.SslCtxSetCertVerifyCallback(sslCtx, s_sslVerifyCallback, curl); // If a client certificate provider was provided, also configure the client certificate callback. if (userPointer != IntPtr.Zero) { try { // Provider is passed in via a GCHandle. Get the provider, which contains // the client certificate callback delegate. GCHandle handle = GCHandle.FromIntPtr(userPointer); ClientCertificateProvider provider = (ClientCertificateProvider)handle.Target; if (provider == null) { Debug.Fail($"Expected non-null provider in {nameof(SslCtxCallback)}"); return CURLcode.CURLE_ABORTED_BY_CALLBACK; } // Register the callback. Interop.Ssl.SslCtxSetClientCertCallback(sslCtx, provider._callback); EventSourceTrace("Registered client certificate callback.", easy: easy); } catch (Exception e) { Debug.Fail($"Exception in {nameof(SslCtxCallback)}", e.ToString()); return CURLcode.CURLE_ABORTED_BY_CALLBACK; } } return CURLcode.CURLE_OK; } private static bool TryGetEasyRequest(IntPtr curlPtr, out EasyRequest easy) { Debug.Assert(curlPtr != IntPtr.Zero, "curlPtr is not null"); IntPtr gcHandlePtr; CURLcode getInfoResult = Interop.Http.EasyGetInfoPointer(curlPtr, CURLINFO.CURLINFO_PRIVATE, out gcHandlePtr); if (getInfoResult == CURLcode.CURLE_OK) { return MultiAgent.TryGetEasyRequestFromGCHandle(gcHandlePtr, out easy); } Debug.Fail($"Failed to get info on a completing easy handle: {getInfoResult}"); easy = null; return false; } private static int VerifyCertChain(IntPtr storeCtxPtr, IntPtr curlPtr) { EasyRequest easy; if (!TryGetEasyRequest(curlPtr, out easy)) { EventSourceTrace("Could not find associated easy request: {0}", curlPtr); return 0; } using (var storeCtx = new SafeX509StoreCtxHandle(storeCtxPtr, ownsHandle: false)) { IntPtr leafCertPtr = Interop.Crypto.X509StoreCtxGetTargetCert(storeCtx); if (IntPtr.Zero == leafCertPtr) { EventSourceTrace("Invalid certificate pointer", easy: easy); return 0; } using (X509Certificate2 leafCert = new X509Certificate2(leafCertPtr)) { // We need to respect the user's server validation callback if there is one. If there isn't one, // we can start by first trying to use OpenSSL's verification, though only if CRL checking is disabled, // as OpenSSL doesn't do that. if (easy._handler.ServerCertificateValidationCallback == null && !easy._handler.CheckCertificateRevocationList) { // Start by using the default verification provided directly by OpenSSL. // If it succeeds in verifying the cert chain, we're done. Employing this instead of // our custom implementation will need to be revisited if we ever decide to introduce a // "disallowed" store that enables users to "untrust" certs the system trusts. int sslResult = Interop.Crypto.X509VerifyCert(storeCtx); if (sslResult == 1) { return 1; } // X509_verify_cert can return < 0 in the case of programmer error Debug.Assert(sslResult == 0, "Unexpected error from X509_verify_cert: " + sslResult); } // Either OpenSSL verification failed, or there was a server validation callback. // Either way, fall back to manual and more expensive verification that includes // checking the user's certs (not just the system store ones as OpenSSL does). X509Certificate2[] otherCerts; int otherCertsCount = 0; bool success; using (X509Chain chain = new X509Chain()) { chain.ChainPolicy.RevocationMode = easy._handler.CheckCertificateRevocationList ? X509RevocationMode.Online : X509RevocationMode.NoCheck; chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot; using (SafeSharedX509StackHandle extraStack = Interop.Crypto.X509StoreCtxGetSharedUntrusted(storeCtx)) { if (extraStack.IsInvalid) { otherCerts = Array.Empty<X509Certificate2>(); } else { int extraSize = Interop.Crypto.GetX509StackFieldCount(extraStack); otherCerts = new X509Certificate2[extraSize]; for (int i = 0; i < extraSize; i++) { IntPtr certPtr = Interop.Crypto.GetX509StackField(extraStack, i); if (certPtr != IntPtr.Zero) { X509Certificate2 cert = new X509Certificate2(certPtr); otherCerts[otherCertsCount++] = cert; chain.ChainPolicy.ExtraStore.Add(cert); } } } } var serverCallback = easy._handler._serverCertificateValidationCallback; if (serverCallback == null) { SslPolicyErrors errors = CertificateValidation.BuildChainAndVerifyProperties(chain, leafCert, checkCertName: false, hostName: null); // libcurl already verifies the host name success = errors == SslPolicyErrors.None; } else { // Authenticate the remote party: (e.g. when operating in client mode, authenticate the server). chain.ChainPolicy.ApplicationPolicy.Add(s_serverAuthOid); SslPolicyErrors errors = CertificateValidation.BuildChainAndVerifyProperties(chain, leafCert, checkCertName: true, hostName: easy._requestMessage.RequestUri.Host); // we disabled automatic host verification, so we do it here try { success = serverCallback(easy._requestMessage, leafCert, chain, errors); } catch (Exception exc) { EventSourceTrace("Server validation callback threw exception: {0}", exc, easy: easy); easy.FailRequest(exc); success = false; } } } for (int i = 0; i < otherCertsCount; i++) { otherCerts[i].Dispose(); } return success ? 1 : 0; } } } } } }
using Lucene.Net.Support; using System; using System.Runtime.CompilerServices; using System.Text; /* * dk.brics.automaton * * Copyright (c) 2001-2009 Anders Moeller * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * this SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 Lucene.Net.Util.Automaton { /// <summary> /// Finite-state automaton with fast run operation. /// <para/> /// @lucene.experimental /// </summary> public abstract class RunAutomaton { private readonly int _maxInterval; private readonly int _size; protected readonly bool[] m_accept; protected readonly int m_initial; protected readonly int[] m_transitions; // delta(state,c) = transitions[state*points.length + // getCharClass(c)] private readonly int[] _points; // char interval start points private readonly int[] _classmap; // map from char number to class class /// <summary> /// Returns a string representation of this automaton. /// </summary> public override string ToString() { var b = new StringBuilder(); b.Append("initial state: ").Append(m_initial).Append("\n"); for (int i = 0; i < _size; i++) { b.Append("state " + i); if (m_accept[i]) { b.Append(" [accept]:\n"); } else { b.Append(" [reject]:\n"); } for (int j = 0; j < _points.Length; j++) { int k = m_transitions[i * _points.Length + j]; if (k != -1) { int min = _points[j]; int max; if (j + 1 < _points.Length) { max = (_points[j + 1] - 1); } else { max = _maxInterval; } b.Append(" "); Transition.AppendCharString(min, b); if (min != max) { b.Append("-"); Transition.AppendCharString(max, b); } b.Append(" -> ").Append(k).Append("\n"); } } } return b.ToString(); } /// <summary> /// Returns number of states in automaton. /// <para/> /// NOTE: This was size() in Lucene. /// </summary> public int Count => _size; /// <summary> /// Returns acceptance status for given state. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool IsAccept(int state) { return m_accept[state]; } /// <summary> /// Returns initial state. /// </summary> public int InitialState => m_initial; /// <summary> /// Returns array of codepoint class interval start points. The array should /// not be modified by the caller. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public int[] GetCharIntervals() { return (int[])(Array)_points.Clone(); } /// <summary> /// Gets character class of given codepoint. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal int GetCharClass(int c) { return SpecialOperations.FindIndex(c, _points); } /// <summary> /// Constructs a new <see cref="RunAutomaton"/> from a deterministic /// <see cref="Automaton"/>. /// </summary> /// <param name="a"> An automaton. </param> /// <param name="maxInterval"></param> /// <param name="tableize"></param> protected RunAutomaton(Automaton a, int maxInterval, bool tableize) // LUCENENET specific - marked protected instead of public { this._maxInterval = maxInterval; a.Determinize(); _points = a.GetStartPoints(); State[] states = a.GetNumberedStates(); m_initial = a.initial.Number; _size = states.Length; m_accept = new bool[_size]; m_transitions = new int[_size * _points.Length]; for (int n = 0; n < _size * _points.Length; n++) { m_transitions[n] = -1; } foreach (State s in states) { int n = s.number; m_accept[n] = s.accept; for (int c = 0; c < _points.Length; c++) { State q = s.Step(_points[c]); if (q != null) { m_transitions[n * _points.Length + c] = q.number; } } } /* * Set alphabet table for optimal run performance. */ if (tableize) { _classmap = new int[maxInterval + 1]; int i = 0; for (int j = 0; j <= maxInterval; j++) { if (i + 1 < _points.Length && j == _points[i + 1]) { i++; } _classmap[j] = i; } } else { _classmap = null; } } /// <summary> /// Returns the state obtained by reading the given char from the given state. /// Returns -1 if not obtaining any such state. (If the original /// <see cref="Automaton"/> had no dead states, -1 is returned here if and only /// if a dead state is entered in an equivalent automaton with a total /// transition function.) /// </summary> public int Step(int state, int c) { if (_classmap is null) { return m_transitions[state * _points.Length + GetCharClass(c)]; } else { return m_transitions[state * _points.Length + _classmap[c]]; } } public override int GetHashCode() { const int prime = 31; int result = 1; result = prime * result + m_initial; result = prime * result + _maxInterval; result = prime * result + _points.Length; result = prime * result + _size; return result; } public override bool Equals(object obj) { if (this == obj) { return true; } if (obj is null) { return false; } if (this.GetType() != obj.GetType()) { return false; } RunAutomaton other = (RunAutomaton)obj; if (m_initial != other.m_initial) { return false; } if (_maxInterval != other._maxInterval) { return false; } if (_size != other._size) { return false; } if (!Arrays.Equals(_points, other._points)) { return false; } if (!Arrays.Equals(m_accept, other.m_accept)) { return false; } if (!Arrays.Equals(m_transitions, other.m_transitions)) { return false; } return true; } } }
/* * Muhimbi PDF * * Convert, Merge, Watermark, Secure and OCR files. * * OpenAPI spec version: 9.15 * * 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; namespace Muhimbi.PDF.Online.Client.Model { /// <summary> /// Parameters for SecurePdf operation /// </summary> [DataContract] public partial class SecurePdfData : IEquatable<SecurePdfData>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="SecurePdfData" /> class. /// </summary> [JsonConstructorAttribute] protected SecurePdfData() { } /// <summary> /// Initializes a new instance of the <see cref="SecurePdfData" /> class. /// </summary> /// <param name="UseAsyncPattern">Use async behaviour for API request (required) (default to false).</param> /// <param name="SourceFileName">Name of the source file including extension.</param> /// <param name="SourceFileContent">Content of the file to secure (required).</param> /// <param name="SharepointFile">SharepointFile.</param> /// <param name="OpenPassword">Password required to open the document.</param> /// <param name="OwnerPassword">Password required to edit the document (and for PDF apply restrictions defined below).</param> /// <param name="SecurityOptions">Print|HighResolutionPrint|ContentCopy|Annotations|FormFields|ContentAccessibility|DocumentAssembly.</param> /// <param name="FailOnError">Fail on error (default to true).</param> public SecurePdfData(bool? UseAsyncPattern = false, string SourceFileName = default(string), byte[] SourceFileContent = default(byte[]), SharepointFile SharepointFile = default(SharepointFile), string OpenPassword = default(string), string OwnerPassword = default(string), string SecurityOptions = default(string), bool? FailOnError = true) { // to ensure "UseAsyncPattern" is required (not null) if (UseAsyncPattern == null) { throw new InvalidDataException("UseAsyncPattern is a required property for SecurePdfData and cannot be null"); } else { this.UseAsyncPattern = UseAsyncPattern; } // to ensure "SourceFileContent" is required (not null) if (SourceFileContent == null) { throw new InvalidDataException("SourceFileContent is a required property for SecurePdfData and cannot be null"); } else { this.SourceFileContent = SourceFileContent; } this.SourceFileName = SourceFileName; this.SharepointFile = SharepointFile; this.OpenPassword = OpenPassword; this.OwnerPassword = OwnerPassword; this.SecurityOptions = SecurityOptions; // use default value if no "FailOnError" provided if (FailOnError == null) { this.FailOnError = true; } else { this.FailOnError = FailOnError; } } /// <summary> /// Use async behaviour for API request /// </summary> /// <value>Use async behaviour for API request</value> [DataMember(Name="use_async_pattern", EmitDefaultValue=false)] public bool? UseAsyncPattern { get; set; } /// <summary> /// Name of the source file including extension /// </summary> /// <value>Name of the source file including extension</value> [DataMember(Name="source_file_name", EmitDefaultValue=false)] public string SourceFileName { get; set; } /// <summary> /// Content of the file to secure /// </summary> /// <value>Content of the file to secure</value> [DataMember(Name="source_file_content", EmitDefaultValue=false)] public byte[] SourceFileContent { get; set; } /// <summary> /// Gets or Sets SharepointFile /// </summary> [DataMember(Name="sharepoint_file", EmitDefaultValue=false)] public SharepointFile SharepointFile { get; set; } /// <summary> /// Password required to open the document /// </summary> /// <value>Password required to open the document</value> [DataMember(Name="open_password", EmitDefaultValue=false)] public string OpenPassword { get; set; } /// <summary> /// Password required to edit the document (and for PDF apply restrictions defined below) /// </summary> /// <value>Password required to edit the document (and for PDF apply restrictions defined below)</value> [DataMember(Name="owner_password", EmitDefaultValue=false)] public string OwnerPassword { get; set; } /// <summary> /// Print|HighResolutionPrint|ContentCopy|Annotations|FormFields|ContentAccessibility|DocumentAssembly /// </summary> /// <value>Print|HighResolutionPrint|ContentCopy|Annotations|FormFields|ContentAccessibility|DocumentAssembly</value> [DataMember(Name="security_options", EmitDefaultValue=false)] public string SecurityOptions { get; set; } /// <summary> /// Fail on error /// </summary> /// <value>Fail on error</value> [DataMember(Name="fail_on_error", EmitDefaultValue=false)] public bool? FailOnError { 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 SecurePdfData {\n"); sb.Append(" UseAsyncPattern: ").Append(UseAsyncPattern).Append("\n"); sb.Append(" SourceFileName: ").Append(SourceFileName).Append("\n"); sb.Append(" SourceFileContent: ").Append(SourceFileContent).Append("\n"); sb.Append(" SharepointFile: ").Append(SharepointFile).Append("\n"); sb.Append(" OpenPassword: ").Append(OpenPassword).Append("\n"); sb.Append(" OwnerPassword: ").Append(OwnerPassword).Append("\n"); sb.Append(" SecurityOptions: ").Append(SecurityOptions).Append("\n"); sb.Append(" FailOnError: ").Append(FailOnError).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 SecurePdfData); } /// <summary> /// Returns true if SecurePdfData instances are equal /// </summary> /// <param name="other">Instance of SecurePdfData to be compared</param> /// <returns>Boolean</returns> public bool Equals(SecurePdfData other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.UseAsyncPattern == other.UseAsyncPattern || this.UseAsyncPattern != null && this.UseAsyncPattern.Equals(other.UseAsyncPattern) ) && ( this.SourceFileName == other.SourceFileName || this.SourceFileName != null && this.SourceFileName.Equals(other.SourceFileName) ) && ( this.SourceFileContent == other.SourceFileContent || this.SourceFileContent != null && this.SourceFileContent.Equals(other.SourceFileContent) ) && ( this.SharepointFile == other.SharepointFile || this.SharepointFile != null && this.SharepointFile.Equals(other.SharepointFile) ) && ( this.OpenPassword == other.OpenPassword || this.OpenPassword != null && this.OpenPassword.Equals(other.OpenPassword) ) && ( this.OwnerPassword == other.OwnerPassword || this.OwnerPassword != null && this.OwnerPassword.Equals(other.OwnerPassword) ) && ( this.SecurityOptions == other.SecurityOptions || this.SecurityOptions != null && this.SecurityOptions.Equals(other.SecurityOptions) ) && ( this.FailOnError == other.FailOnError || this.FailOnError != null && this.FailOnError.Equals(other.FailOnError) ); } /// <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.UseAsyncPattern != null) hash = hash * 59 + this.UseAsyncPattern.GetHashCode(); if (this.SourceFileName != null) hash = hash * 59 + this.SourceFileName.GetHashCode(); if (this.SourceFileContent != null) hash = hash * 59 + this.SourceFileContent.GetHashCode(); if (this.SharepointFile != null) hash = hash * 59 + this.SharepointFile.GetHashCode(); if (this.OpenPassword != null) hash = hash * 59 + this.OpenPassword.GetHashCode(); if (this.OwnerPassword != null) hash = hash * 59 + this.OwnerPassword.GetHashCode(); if (this.SecurityOptions != null) hash = hash * 59 + this.SecurityOptions.GetHashCode(); if (this.FailOnError != null) hash = hash * 59 + this.FailOnError.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
/* * Project: WhaTBI? (What's The Big Idea?) * Filename: Query.cs * Description: Query functionality */ using System; using System.Reflection; namespace Pdbartlett.Whatbi { public interface IExpression { object Evaluate(object o); } public interface IPredicate { bool Evaluate(object o); } public interface ISqlConvertible { string ConvertToSql(IORMapping mapper); } [Serializable()] public abstract class PredicateHelper : IPredicate, IExpression { public abstract bool Evaluate(object o); object IExpression.Evaluate(object o) { return Evaluate(o); } } namespace Comparison { [Serializable()] public abstract class EmptyHelper : PredicateHelper { private IExpression m_value; public EmptyHelper(IExpression value) { m_value = value; } protected bool IsEmpty(object o) { object result = m_value.Evaluate(o); return (result == null || result.ToString() == String.Empty); } } [Serializable()] public class Empty : EmptyHelper { public Empty(IExpression value) : base(value) {} public override bool Evaluate(object o) { return IsEmpty(o); } } [Serializable()] public class NotEmpty : EmptyHelper { public NotEmpty(IExpression value) : base(value) {} public override bool Evaluate(object o) { return !IsEmpty(o); } } [Serializable()] public abstract class ComparisonHelper : PredicateHelper { protected IExpression m_lhs; protected IExpression m_rhs; public ComparisonHelper(IExpression lhs, IExpression rhs) { m_lhs = lhs; m_rhs = rhs; } protected bool EqualsLeftRight(object o) { return m_lhs.Evaluate(o).Equals(m_rhs.Evaluate(o)); } protected int CompareLeftRight(object o) { return((IComparable)m_lhs.Evaluate(o)).CompareTo(m_rhs.Evaluate(o)); } protected string LhsAsString(object o) { return m_lhs.Evaluate(o).ToString(); } protected string RhsAsString(object o) { return m_rhs.Evaluate(o).ToString(); } protected string LhsAsLCaseString(object o) { return m_lhs.Evaluate(o).ToString().ToLower(); } protected string RhsAsLCaseString(object o) { return m_rhs.Evaluate(o).ToString().ToLower(); } } [Serializable()] public abstract class SqlComparisonHelper : ComparisonHelper, ISqlConvertible { public SqlComparisonHelper(IExpression lhs, IExpression rhs) : base(lhs, rhs) {} public string ConvertToSql(IORMapping mapper) { ISqlConvertible lhs = (ISqlConvertible)m_lhs; ISqlConvertible rhs = (ISqlConvertible)m_rhs; return lhs.ConvertToSql(mapper) + " " + GetSqlOperator() + " " + rhs.ConvertToSql(mapper); } protected abstract string GetSqlOperator(); } [Serializable()] public class Equal : SqlComparisonHelper { public Equal(IExpression lhs, IExpression rhs) : base(lhs, rhs) {} public override bool Evaluate(object o) { return EqualsLeftRight(o); } protected override string GetSqlOperator() { return "="; } } [Serializable()] public class NotEqual : SqlComparisonHelper { public NotEqual(IExpression lhs, IExpression rhs) : base(lhs, rhs) {} public override bool Evaluate(object o) { return !EqualsLeftRight(o); } protected override string GetSqlOperator() { return "<>"; } } [Serializable()] public class LessThan : SqlComparisonHelper { public LessThan(IExpression lhs, IExpression rhs) : base(lhs, rhs) {} public override bool Evaluate(object o) { return CompareLeftRight(o) < 0; } protected override string GetSqlOperator() { return "<"; } } [Serializable()] public class LessThanOrEqual : SqlComparisonHelper { public LessThanOrEqual(IExpression lhs, IExpression rhs) : base(lhs, rhs) {} public override bool Evaluate(object o) { return CompareLeftRight(o) <= 0; } protected override string GetSqlOperator() { return "<="; } } [Serializable()] public class GreaterThan : SqlComparisonHelper { public GreaterThan(IExpression lhs, IExpression rhs) : base(lhs, rhs) {} public override bool Evaluate(object o) { return CompareLeftRight(o) > 0; } protected override string GetSqlOperator() { return ">"; } } [Serializable()] public class GreaterThanOrEqual : SqlComparisonHelper { public GreaterThanOrEqual(IExpression lhs, IExpression rhs) : base(lhs, rhs) {} public override bool Evaluate(object o) { return CompareLeftRight(o) >= 0; } protected override string GetSqlOperator() { return ">="; } } [Serializable()] public class CaseInsensitiveEqual : ComparisonHelper { public CaseInsensitiveEqual(IExpression lhs, IExpression rhs) : base(lhs, rhs) {} public override bool Evaluate(object o) { return LhsAsLCaseString(o) == RhsAsLCaseString(o); } } [Serializable()] public class CaseInsensitiveNotEqual : ComparisonHelper { public CaseInsensitiveNotEqual(IExpression lhs, IExpression rhs) : base(lhs, rhs) {} public override bool Evaluate(object o) { return LhsAsLCaseString(o) != RhsAsLCaseString(o); } } [Serializable()] public class Contains : ComparisonHelper { public Contains(IExpression lhs, IExpression rhs) : base(lhs, rhs) {} public override bool Evaluate(object o) { return LhsAsLCaseString(o).IndexOf(RhsAsLCaseString(o)) >= 0; } } [Serializable()] public class StartsWith : ComparisonHelper { public StartsWith(IExpression lhs, IExpression rhs) : base(lhs, rhs) {} public override bool Evaluate(object o) { return LhsAsLCaseString(o).StartsWith(RhsAsLCaseString(o)); } } [Serializable()] public class EndsWith : ComparisonHelper { public EndsWith(IExpression lhs, IExpression rhs) : base(lhs, rhs) {} public override bool Evaluate(object o) { return LhsAsLCaseString(o).EndsWith(RhsAsLCaseString(o)); } } } namespace Logical { [Serializable()] public abstract class BinaryLogicalOperatorHelper : PredicateHelper, ISqlConvertible { protected IPredicate m_lhs; protected IPredicate m_rhs; public BinaryLogicalOperatorHelper(IPredicate lhs, IPredicate rhs) { m_lhs = lhs; m_rhs = rhs; } public string ConvertToSql(IORMapping mapper) { ISqlConvertible lhs = (ISqlConvertible)m_lhs; ISqlConvertible rhs = (ISqlConvertible)m_rhs; return "(" + lhs.ConvertToSql(mapper) + ") " + GetSqlOperator() + " (" + rhs.ConvertToSql(mapper) + ")"; } protected abstract string GetSqlOperator(); } [Serializable()] public class And : BinaryLogicalOperatorHelper { public And(IPredicate lhs, IPredicate rhs) : base(lhs, rhs) {} public override bool Evaluate(object o) { return m_lhs.Evaluate(o) && m_rhs.Evaluate(o); } protected override string GetSqlOperator() { return "AND"; } } [Serializable()] public class Or : BinaryLogicalOperatorHelper { public Or(IPredicate lhs, IPredicate rhs) : base(lhs, rhs) {} public override bool Evaluate(object o) { return m_lhs.Evaluate(o) || m_rhs.Evaluate(o); } protected override string GetSqlOperator() { return "OR"; } } [Serializable()] public class Not : PredicateHelper, ISqlConvertible { private IPredicate m_operand; public Not(IPredicate operand) { m_operand = operand; } public override bool Evaluate(object o) { return !m_operand.Evaluate(o); } public string ConvertToSql(IORMapping mapper) { ISqlConvertible operand = (ISqlConvertible)m_operand; return "NOT (" + operand.ConvertToSql(mapper) + ")"; } } } namespace Expression { [Serializable()] public class Literal : IExpression, ISqlConvertible { private object m_value; public Literal(object literalValue) { m_value = literalValue; } public object Evaluate(object o) { return m_value; } public string ConvertToSql(IORMapping mapper) { if (m_value == null) return "NULL"; Type t = m_value.GetType(); if (t == typeof(string)) return "'" + ((string)m_value).Replace("'", "''") + "'"; if ( t == typeof(double) || t == typeof(float) || t == typeof(long) || t == typeof(ulong) || t == typeof(int) || t == typeof(uint) || t == typeof(short) || t == typeof(ushort) || t == typeof(sbyte) || t == typeof(byte) ) { return m_value.ToString(); } if (t == typeof(DateTime)) return "'" + ((DateTime)m_value).ToString("u") + "'"; throw new BaseException("Literal type not convertible to SQL: " + m_value.GetType().FullName); } } [Serializable()] public class GetProperty : IExpression, ISqlConvertible { private string m_propertyName; public GetProperty(string propertyName) { m_propertyName = propertyName; } public object Evaluate(object o) { ITypeInfo ti = Utility.GetTypeInfo(o); IPropertyInfo pi = ti.GetProperty(m_propertyName); if (pi == null) throw new BaseException("Property '" + m_propertyName + "' not found for type '" + ti.Name + "'"); return pi.GetValue(o); } public string ConvertToSql(IORMapping mapper) { return mapper.GetColumnForProperty(m_propertyName); } } [Serializable()] public class Self : IExpression { public object Evaluate(object o) { return o; } } [Serializable()] public class Key : IExpression, ISqlConvertible { public object Evaluate(object o) { return Utility.GetKey(o); } public string ConvertToSql(IORMapping mapper) { return mapper.GetKeyColumn(); } } } }
/* 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 [email protected] * Converted ArrayLists and other .NET 1.1 collections to use Generics * Combined IExtensionElement and IExtensionElementFactory interfaces * */ #region Using directives #define USE_TRACING using System; using System.Collections.Generic; using System.Collections; #endregion ////////////////////////////////////////////////////////////////////// // contains typed collections based on the 1.1 .NET framework // using typed collections has the benefit of additional code reliability // and using them in the collection editor // ////////////////////////////////////////////////////////////////////// namespace Google.GData.Client { ////////////////////////////////////////////////////////////////////// /// <summary>standard typed collection based on 1.1 framework for FeedEntries /// </summary> ////////////////////////////////////////////////////////////////////// public class AtomEntryCollection : AtomCollectionBase<AtomEntry> { /// <summary>holds the owning feed</summary> private AtomFeed feed; /// <summary>private default constructor</summary> private AtomEntryCollection() { } /// <summary>constructor</summary> public AtomEntryCollection(AtomFeed feed) : base() { this.feed = feed; } /// <summary>Fins an atomEntry in the collection /// based on it's ID. </summary> /// <param name="value">The atomId to look for</param> /// <returns>Null if not found, otherwise the entry</returns> public AtomEntry FindById(AtomId value) { if (value == null) { throw new ArgumentNullException("value"); } foreach (AtomEntry entry in List) { if (entry.Id.AbsoluteUri == value.AbsoluteUri) { return entry; } } return null; } /// <summary>standard typed accessor method </summary> public override AtomEntry this[int index] { get { return ((AtomEntry)List[index]); } set { if (value != null) { if (value.Feed == null || value.Feed != this.feed) { value.setFeed(this.feed); } } List[index] = value; } } /// <summary>standard typed add method </summary> public override void Add(AtomEntry value) { if (value != null) { if (this.feed != null && value.Feed == this.feed) { // same object, already in here. throw new ArgumentException("The entry is already part of this collection"); } value.setFeed(this.feed); // old code /* // now we need to see if this is the same feed. If not, copy if (AtomFeed.IsFeedIdentical(value.Feed, this.feed) == false) { AtomEntry newEntry = AtomEntry.ImportFromFeed(value); newEntry.setFeed(this.feed); value = newEntry; } */ // from now on, we will only ADD the entry to this collection and change it's // ownership. No more auto-souce creation. There is an explicit method for this value.ProtocolMajor = this.feed.ProtocolMajor; value.ProtocolMinor = this.feed.ProtocolMinor; } base.Add(value); } /// <summary> /// takes an existing atomentry object and either copies it into this feed collection, /// or moves it by creating a source element and copying it in here if the value is actually /// already part of a collection /// </summary> /// <param name="value"></param> /// <returns></returns> public AtomEntry CopyOrMove(AtomEntry value) { if (value != null) { if (value.Feed == null) { value.setFeed(this.feed); } else { if (this.feed != null && value.Feed == this.feed) { // same object, already in here. throw new ArgumentException("The entry is already part of this collection"); } // now we need to see if this is the same feed. If not, copy if (AtomFeed.IsFeedIdentical(value.Feed, this.feed) == false) { AtomEntry newEntry = AtomEntry.ImportFromFeed(value); newEntry.setFeed(this.feed); value = newEntry; } } value.ProtocolMajor = this.feed.ProtocolMajor; value.ProtocolMinor = this.feed.ProtocolMinor; } base.Add(value); return value; } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>standard typed collection based on 1.1 framework for AtomLinks /// </summary> ////////////////////////////////////////////////////////////////////// public class AtomLinkCollection : AtomCollectionBase<AtomLink> { ////////////////////////////////////////////////////////////////////// /// <summary>public AtomLink FindService(string service,string type) /// Retrieves the first link with the supplied 'rel' and/or 'type' value. /// If either parameter is null, the corresponding match isn't needed. /// </summary> /// <param name="service">the service entry to find</param> /// <param name="type">the link type to find</param> /// <returns>the found link or NULL </returns> ////////////////////////////////////////////////////////////////////// public AtomLink FindService(string service, string type) { foreach (AtomLink link in List) { string linkRel = link.Rel; string linkType = link.Type; if ((service == null || (linkRel != null && linkRel == service)) && (type == null || (linkType != null && linkType.StartsWith(type)))) { return link; } } return null; } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>public AtomLink FindService(string service,string type) /// Retrieves the first link with the supplied 'rel' and/or 'type' value. /// If either parameter is null, the corresponding match isn't needed. /// </summary> /// <param name="service">the service entry to find</param> /// <param name="type">the link type to find</param> /// <returns>the found link or NULL </returns> ////////////////////////////////////////////////////////////////////// public List<AtomLink> FindServiceList(string service, string type) { List<AtomLink> foundLinks = new List<AtomLink>(); foreach (AtomLink link in List) { string linkRel = link.Rel; string linkType = link.Type; if ((service == null || (linkRel != null && linkRel == service)) && (type == null || (linkType != null && linkType == type))) { foundLinks.Add(link); } } return foundLinks; } ///////////////////////////////////////////////////////////////////////////// } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>standard typed collection based on 1.1 framework for AtomCategory /// </summary> ////////////////////////////////////////////////////////////////////// public class AtomCategoryCollection : AtomCollectionBase<AtomCategory> { /// <summary>standard typed accessor method </summary> public override void Add(AtomCategory value) { if (value == null) { throw new ArgumentNullException("value"); } // Remove category with the same term to avoid duplication. AtomCategory oldCategory = Find(value.Term, value.Scheme); if (oldCategory != null) { Remove(oldCategory); } base.Add(value); } /// <summary> /// finds the first category with this term /// ignoring schemes /// </summary> /// <param name="term">the category term to search for</param> /// <returns>AtomCategory</returns> public AtomCategory Find(string term) { return Find(term, null); } /// <summary> /// finds a category with a given term and scheme /// </summary> /// <param name="term"></param> /// <param name="scheme"></param> /// <returns>AtomCategory or NULL</returns> public AtomCategory Find(string term, AtomUri scheme) { foreach (AtomCategory category in List) { if (scheme == null || scheme == category.Scheme) { if (term == category.Term) { return category; } } } return null; } /// <summary>standard typed accessor method </summary> public override bool Contains(AtomCategory value) { if (value == null) { return (List.Contains(value)); } // If value is not of type AtomCategory, this will return false. if (Find(value.Term, value.Scheme) != null) { return true; } return false; } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>standard typed collection based on 1.1 framework for AtomPerson /// </summary> ////////////////////////////////////////////////////////////////////// public class QueryCategoryCollection : AtomCollectionBase<QueryCategory> { } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>standard typed collection based on 1.1 framework for AtomPerson /// </summary> ////////////////////////////////////////////////////////////////////// public class AtomPersonCollection : AtomCollectionBase<AtomPerson> { } ///////////////////////////////////////////////////////////////////////////// /// <summary> /// Generic collection base class /// </summary> /// <typeparam name="T"></typeparam> public class AtomCollectionBase<T> : IList<T> { /// <summary> /// the internal list object that is used /// </summary> protected List<T> List = new List<T>(); /// <summary>standard typed accessor method </summary> public virtual T this[int index] { get { return (T)List[index]; } set { List[index] = value; } } /// <summary>standard typed accessor method </summary> public virtual void Add(T value) { List.Add(value); } /// <summary> /// default overload, see base class /// </summary> /// <param name="index"></param> public virtual void RemoveAt(int index) { List.RemoveAt(index); } /// <summary> /// default overload, see base class /// </summary> public virtual void Clear() { List.Clear(); } /// <summary> /// default overload, see base class /// </summary> /// <param name="arr"></param> /// <param name="index"></param> public virtual void CopyTo(T[] arr, int index) { List.CopyTo(arr, index); } /// <summary>standard typed accessor method </summary> /// <param name="value"></param> public virtual int IndexOf(T value) { return (List.IndexOf(value)); } /// <summary>standard typed accessor method </summary> /// <param name="index"></param> /// <param name="value"></param> public virtual void Insert(int index, T value) { List.Insert(index, value); } /// <summary>standard typed accessor method </summary> /// <param name="value"></param> public virtual bool Remove(T value) { return List.Remove(value); } /// <summary>standard typed accessor method </summary> /// <param name="value"></param> public virtual bool Contains(T value) { // If value is not of type AtomPerson, this will return false. return (List.Contains(value)); } /// <summary> /// default overload, see base class /// </summary> public virtual int Count { get { return List.Count; } } /// <summary> /// default overload, see base class /// </summary> public virtual bool IsReadOnly { get { return false; } } /// <summary> /// default overload, see base class /// </summary> public IEnumerator<T> GetEnumerator() { return List.GetEnumerator(); } /// <summary> /// default overload, see base class /// </summary> IEnumerator IEnumerable.GetEnumerator() { return List.GetEnumerator(); } } /// <summary> /// internal list to override the add and the constructor /// </summary> /// <returns></returns> public class ExtensionList : IList<IExtensionElementFactory> { IVersionAware container; List<IExtensionElementFactory> _list = new List<IExtensionElementFactory>(); /// <summary> /// Return a new collection that is not version aware. /// </summary> public static ExtensionList NotVersionAware() { return new ExtensionList(NullVersionAware.Instance); } /// <summary> /// returns an extensionlist that belongs to a version aware /// container /// </summary> /// <param name="container"></param> public ExtensionList(IVersionAware container) { this.container = container; } /// <summary> /// adds value to the extensionlist. /// </summary> /// <param name="value"></param> /// <returns>returns the positin in the list after the add</returns> public int Add(IExtensionElementFactory value) { IVersionAware target = value as IVersionAware; if (target != null) { target.ProtocolMajor = this.container.ProtocolMajor; target.ProtocolMinor = this.container.ProtocolMinor; } if (value != null) { _list.Add(value); } return _list.Count - 1; //return _list.IndexOf(value); } /// <summary> /// default overload, see base class /// </summary> /// <param name="item"></param> public int IndexOf(IExtensionElementFactory item) { return _list.IndexOf(item); } /// <summary> /// default overload, see base class /// </summary> /// <param name="index"></param> /// <param name="item"></param> public void Insert(int index, IExtensionElementFactory item) { _list.Insert(index, item); } /// <summary> /// default overload, see base class /// </summary> /// <param name="index"></param> public void RemoveAt(int index) { _list.RemoveAt(index); } /// <summary> /// default overload, see base class /// </summary> /// <param name="index"></param> public IExtensionElementFactory this[int index] { get { return _list[index]; } set { _list[index] = value; } } /// <summary> /// default overload, see base class /// </summary> /// <param name="item"></param> void ICollection<IExtensionElementFactory>.Add(IExtensionElementFactory item) { Add(item); } /// <summary> /// default overload, see base class /// </summary> public void Clear() { _list.Clear(); } /// <summary> /// default overload, see base class /// </summary> /// <param name="item"></param> public bool Contains(IExtensionElementFactory item) { return _list.Contains(item); } /// <summary> /// default overload, see base class /// </summary> /// <param name="array"></param> /// <param name="arrayIndex"></param> public void CopyTo(IExtensionElementFactory[] array, int arrayIndex) { _list.CopyTo(array, arrayIndex); } /// <summary> /// default overload, see base class /// </summary> public int Count { get { return _list.Count; } } /// <summary> /// default overload, see base class /// </summary> public bool IsReadOnly { get { return false; } } /// <summary> /// default overload, see base class /// </summary> /// <param name="item"></param> public bool Remove(IExtensionElementFactory item) { return _list.Remove(item); } /// <summary> /// default overload, see base class /// </summary> public IEnumerator<IExtensionElementFactory> GetEnumerator() { return _list.GetEnumerator(); } /// <summary> /// default overload, see base class /// </summary> IEnumerator IEnumerable.GetEnumerator() { return _list.GetEnumerator(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace SourceUtils { partial class ValveBspFile { public abstract class ArrayLump<T> : ILump, IEnumerable<T> { protected ValveBspFile BspFile { get; } public LumpType LumpType { get; } public int Length { get; } protected virtual Type StructType => typeof(T); public ArrayLump( ValveBspFile bspFile, LumpType type ) { BspFile = bspFile; LumpType = type; Length = BspFile.GetLumpLength( type, StructType ); } public abstract IEnumerator<T> GetEnumerator(); public abstract T this[int index] { get; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public override string ToString() { return $"{StructType}[{Length}]"; } } public class VersionedArrayLump<T> : ArrayLump<T> where T : class { private T[] _array; private Type _structType; protected override Type StructType => _structType ?? (_structType = FindStructType()); public VersionedArrayLump( ValveBspFile bspFile, LumpType type ) : base( bspFile, type ) { } private void EnsureLoaded() { lock ( this ) { if ( _array != null ) return; _array = new T[Length]; var temp = Array.CreateInstance( StructType, Length ); var method = typeof(ValveBspFile) .GetMethod( nameof(ReadLumpValues), BindingFlags.Instance | BindingFlags.NonPublic ) .MakeGenericMethod( StructType ); method.Invoke( BspFile, new object[] { LumpType, 0, temp, 0, Length } ); for ( var i = 0; i < Length; ++i ) { _array[i] = (T) temp.GetValue( i ); } } } private Type FindStructType() { var version = BspFile.GetLumpInfo( LumpType ).Version; foreach ( var type in Assembly.GetExecutingAssembly().GetTypes() ) { if ( !typeof(T).IsAssignableFrom( type ) ) continue; var versionAttrib = type.GetCustomAttribute<StructVersionAttribute>(); if ( versionAttrib != null && versionAttrib.MinVersion <= version && versionAttrib.MaxVersion >= version ) { return type; } } throw new NotSupportedException( $"Version {version} of lump {LumpType} is not supported." ); } public override T this[ int index ] { get { EnsureLoaded(); if ( index < 0 || index >= _array.Length ) { throw new IndexOutOfRangeException( $"{index} is not >= 0 and < {_array.Length}." ); } return _array[index]; } } public override IEnumerator<T> GetEnumerator() { EnsureLoaded(); return ((IEnumerable<T>) _array).GetEnumerator(); } } public class StructArrayLump<T> : ArrayLump<T> where T : struct { private T[] _array; private volatile bool _firstRequest = true; public StructArrayLump( ValveBspFile bspFile, LumpType type ) : base( bspFile, type ) { } private void EnsureLoaded() { lock ( this ) { if ( _array != null ) return; _array = new T[Length]; BspFile.ReadLumpValues( LumpType, 0, _array, 0, Length ); } } public override T this[ int index ] { get { if ( _firstRequest ) { _firstRequest = false; return GetSingle( index ); } EnsureLoaded(); if ( index < 0 || index >= _array.Length ) { throw new IndexOutOfRangeException( $"{index} is not >= 0 and < {_array.Length}." ); } return _array[index]; } } [ThreadStatic] private static T[] _sSingleArray; private T GetSingle( int index ) { if ( _array != null ) return _array[index]; if ( _sSingleArray == null ) _sSingleArray = new T[1]; BspFile.ReadLumpValues( LumpType, index, _sSingleArray, 0, 1 ); return _sSingleArray[0]; } public IEnumerable<T> Range( int start, int count ) { if ( _array != null ) return _array.Skip( start ).Take( count ); if ( start + count > Length ) count = Length - start; if ( count <= 0 ) return Enumerable.Empty<T>(); var array = new T[count]; BspFile.ReadLumpValues( LumpType, start, array, 0, count ); return array; } public int IndexOf( T value ) { EnsureLoaded(); return Array.IndexOf( _array, value ); } public int IndexOf( Predicate<T> predicate ) { EnsureLoaded(); for ( var i = 0; i < _array.Length; ++i ) { if ( predicate( _array[i] ) ) return i; } return -1; } public override IEnumerator<T> GetEnumerator() { EnsureLoaded(); return ((IEnumerable<T>) _array).GetEnumerator(); } } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using osu.Game.Beatmaps; using osu.Game.Rulesets.Difficulty; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Osu.Mods; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Rulesets.Scoring; using osu.Game.Scoring; namespace osu.Game.Rulesets.Osu.Difficulty { public class OsuPerformanceCalculator : PerformanceCalculator { public new OsuDifficultyAttributes Attributes => (OsuDifficultyAttributes)base.Attributes; private readonly int countHitCircles; private readonly int beatmapMaxCombo; private Mod[] mods; private double accuracy; private int scoreMaxCombo; private int countGreat; private int countGood; private int countMeh; private int countMiss; public OsuPerformanceCalculator(Ruleset ruleset, WorkingBeatmap beatmap, ScoreInfo score) : base(ruleset, beatmap, score) { countHitCircles = Beatmap.HitObjects.Count(h => h is HitCircle); beatmapMaxCombo = Beatmap.HitObjects.Count; // Add the ticks + tail of the slider. 1 is subtracted because the "headcircle" would be counted twice (once for the slider itself in the line above) beatmapMaxCombo += Beatmap.HitObjects.OfType<Slider>().Sum(s => s.NestedHitObjects.Count - 1); } public override double Calculate(Dictionary<string, double> categoryRatings = null) { mods = Score.Mods; accuracy = Score.Accuracy; scoreMaxCombo = Score.MaxCombo; countGreat = Convert.ToInt32(Score.Statistics[HitResult.Great]); countGood = Convert.ToInt32(Score.Statistics[HitResult.Good]); countMeh = Convert.ToInt32(Score.Statistics[HitResult.Meh]); countMiss = Convert.ToInt32(Score.Statistics[HitResult.Miss]); // Don't count scores made with supposedly unranked mods if (mods.Any(m => !m.Ranked)) return 0; // Custom multipliers for NoFail and SpunOut. double multiplier = 1.12f; // This is being adjusted to keep the final pp value scaled around what it used to be when changing things if (mods.Any(m => m is OsuModNoFail)) multiplier *= 0.90f; if (mods.Any(m => m is OsuModSpunOut)) multiplier *= 0.95f; double aimValue = computeAimValue(); double speedValue = computeSpeedValue(); double accuracyValue = computeAccuracyValue(); double totalValue = Math.Pow( Math.Pow(aimValue, 1.1f) + Math.Pow(speedValue, 1.1f) + Math.Pow(accuracyValue, 1.1f), 1.0f / 1.1f ) * multiplier; if (categoryRatings != null) { categoryRatings.Add("Aim", aimValue); categoryRatings.Add("Speed", speedValue); categoryRatings.Add("Accuracy", accuracyValue); categoryRatings.Add("OD", Attributes.OverallDifficulty); categoryRatings.Add("AR", Attributes.ApproachRate); categoryRatings.Add("Max Combo", beatmapMaxCombo); } return totalValue; } private double computeAimValue() { double rawAim = Attributes.AimStrain; if (mods.Any(m => m is OsuModTouchDevice)) rawAim = Math.Pow(rawAim, 0.8); double aimValue = Math.Pow(5.0f * Math.Max(1.0f, rawAim / 0.0675f) - 4.0f, 3.0f) / 100000.0f; // Longer maps are worth more double lengthBonus = 0.95f + 0.4f * Math.Min(1.0f, totalHits / 2000.0f) + (totalHits > 2000 ? Math.Log10(totalHits / 2000.0f) * 0.5f : 0.0f); aimValue *= lengthBonus; // Penalize misses exponentially. This mainly fixes tag4 maps and the likes until a per-hitobject solution is available aimValue *= Math.Pow(0.97f, countMiss); // Combo scaling if (beatmapMaxCombo > 0) aimValue *= Math.Min(Math.Pow(scoreMaxCombo, 0.8f) / Math.Pow(beatmapMaxCombo, 0.8f), 1.0f); double approachRateFactor = 1.0f; if (Attributes.ApproachRate > 10.33f) approachRateFactor += 0.3f * (Attributes.ApproachRate - 10.33f); else if (Attributes.ApproachRate < 8.0f) { approachRateFactor += 0.01f * (8.0f - Attributes.ApproachRate); } aimValue *= approachRateFactor; // We want to give more reward for lower AR when it comes to aim and HD. This nerfs high AR and buffs lower AR. if (mods.Any(h => h is OsuModHidden)) aimValue *= 1.0f + 0.04f * (12.0f - Attributes.ApproachRate); if (mods.Any(h => h is OsuModFlashlight)) { // Apply object-based bonus for flashlight. aimValue *= 1.0f + 0.35f * Math.Min(1.0f, totalHits / 200.0f) + (totalHits > 200 ? 0.3f * Math.Min(1.0f, (totalHits - 200) / 300.0f) + (totalHits > 500 ? (totalHits - 500) / 1200.0f : 0.0f) : 0.0f); } // Scale the aim value with accuracy _slightly_ aimValue *= 0.5f + accuracy / 2.0f; // It is important to also consider accuracy difficulty when doing that aimValue *= 0.98f + Math.Pow(Attributes.OverallDifficulty, 2) / 2500; return aimValue; } private double computeSpeedValue() { double speedValue = Math.Pow(5.0f * Math.Max(1.0f, Attributes.SpeedStrain / 0.0675f) - 4.0f, 3.0f) / 100000.0f; // Longer maps are worth more speedValue *= 0.95f + 0.4f * Math.Min(1.0f, totalHits / 2000.0f) + (totalHits > 2000 ? Math.Log10(totalHits / 2000.0f) * 0.5f : 0.0f); // Penalize misses exponentially. This mainly fixes tag4 maps and the likes until a per-hitobject solution is available speedValue *= Math.Pow(0.97f, countMiss); // Combo scaling if (beatmapMaxCombo > 0) speedValue *= Math.Min(Math.Pow(scoreMaxCombo, 0.8f) / Math.Pow(beatmapMaxCombo, 0.8f), 1.0f); double approachRateFactor = 1.0f; if (Attributes.ApproachRate > 10.33f) approachRateFactor += 0.3f * (Attributes.ApproachRate - 10.33f); speedValue *= approachRateFactor; if (mods.Any(m => m is OsuModHidden)) speedValue *= 1.0f + 0.04f * (12.0f - Attributes.ApproachRate); // Scale the speed value with accuracy _slightly_ speedValue *= 0.02f + accuracy; // It is important to also consider accuracy difficulty when doing that speedValue *= 0.96f + Math.Pow(Attributes.OverallDifficulty, 2) / 1600; return speedValue; } private double computeAccuracyValue() { // This percentage only considers HitCircles of any value - in this part of the calculation we focus on hitting the timing hit window double betterAccuracyPercentage; int amountHitObjectsWithAccuracy = countHitCircles; if (amountHitObjectsWithAccuracy > 0) betterAccuracyPercentage = ((countGreat - (totalHits - amountHitObjectsWithAccuracy)) * 6 + countGood * 2 + countMeh) / (amountHitObjectsWithAccuracy * 6); else betterAccuracyPercentage = 0; // It is possible to reach a negative accuracy with this formula. Cap it at zero - zero points if (betterAccuracyPercentage < 0) betterAccuracyPercentage = 0; // Lots of arbitrary values from testing. // Considering to use derivation from perfect accuracy in a probabilistic manner - assume normal distribution double accuracyValue = Math.Pow(1.52163f, Attributes.OverallDifficulty) * Math.Pow(betterAccuracyPercentage, 24) * 2.83f; // Bonus for many hitcircles - it's harder to keep good accuracy up for longer accuracyValue *= Math.Min(1.15f, Math.Pow(amountHitObjectsWithAccuracy / 1000.0f, 0.3f)); if (mods.Any(m => m is OsuModHidden)) accuracyValue *= 1.08f; if (mods.Any(m => m is OsuModFlashlight)) accuracyValue *= 1.02f; return accuracyValue; } private double totalHits => countGreat + countGood + countMeh + countMiss; private double totalSuccessfulHits => countGreat + countGood + countMeh; } }
// QuickGraph Library // // Copyright (c) 2004 Jonathan de Halleux // // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from // the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment in the product // documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must // not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. // // QuickGraph Library HomePage: http://www.mbunit.com // Author: Jonathan de Halleux using System; using System.Collections; namespace QuickGraph.Algorithms.RandomWalks { using QuickGraph.Concepts; using QuickGraph.Concepts.Traversals; using QuickGraph.Concepts.Algorithms; using QuickGraph.Concepts.Visitors; using QuickGraph.Concepts.Predicates; using QuickGraph.Collections; using QuickGraph.Concepts.Modifications; /// <summary> /// Stochastic Random Walk Generation. /// </summary> /// <remarks> /// <para> /// This algorithms walks randomly across a directed graph. The probability /// to choose the next out-edges is provided by a <see cref="IMarkovEdgeChain"/> /// instance. /// </para> /// <para><b>Events</b></para> /// <para> /// The <see cref="StartVertex"/> is raised on the root vertex of the walk. /// This event is raised once. /// </para> /// <para> /// On each new edge in the walk, the <see cref="TreeEdge"/> is raised with /// the edge added to the walk tree. /// </para> /// <para> /// The <see cref="EndVertex"/> is raised on the last vertex of the walk. /// This event is raised once. /// </para> /// <para> /// Custom end of walk condition can be provided by attacing a /// <see cref="IEdgePredicate"/> instance to the <see cref="EndPredicate"/> /// property. /// </para> /// </remarks> /// <example>ea /// In this example, we walk in a graph and output the edge using /// events: /// <code> /// // define delegates /// public void TreeEdge(Object sender, EdgeEventArgs e) /// { /// Console.WriteLine( /// "{0}->{1}", /// e.Edge.Source.ToString(), /// e.Edge.Target.ToString()); /// } /// /// ... /// /// IVertexListGraph g = ...; /// // create algo /// RandomWalkAlgorithm walker = new RandomWalkAlgorithm(g); /// /// // attach event handler /// walker.TreeEdge += new EdgeEventHandler(this.TreeEdge); /// // walk until we read a dead end. /// waler.Generate(int.MaxValue); /// </code> /// </example> public class RandomWalkAlgorithm : IAlgorithm { private IImplicitGraph visitedGraph = null; private IEdgePredicate endPredicate = null; private IMarkovEdgeChain edgeChain = new NormalizedMarkovEdgeChain(); private Random rnd = new Random((int)DateTime.Now.Ticks); /// <summary> /// Constructs the algorithm around <paramref name="g"/>. /// </summary> /// <remarks> /// </remarks> /// <param name="g">visted graph</param> /// <exception cref="ArgumentNullException">g is a null reference</exception> public RandomWalkAlgorithm( IVertexListGraph g) { if (g==null) throw new ArgumentNullException("g"); this.visitedGraph = g; } /// <summary> /// Constructs the algorithm around <paramref name="g"/> using /// the <paramref name="edgeChain"/> Markov chain. /// </summary> /// <param name="g">visited graph</param> /// <param name="edgeChain"> /// Markov <see cref="IEdge"/> chain generator /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="g"/> or <paramref name="edgeChain"/> /// is a null reference /// </exception> public RandomWalkAlgorithm( IVertexListGraph g, IMarkovEdgeChain edgeChain ) { if (g==null) throw new ArgumentNullException("g"); if (edgeChain == null) throw new ArgumentNullException("edgeChain"); this.visitedGraph = g; this.edgeChain = edgeChain; } /// <summary> /// Gets the visited <see cref="IVertexListGraph"/> instance /// </summary> /// <value> /// Visited <see cref="IVertexListGraph"/> instance /// </value> public IImplicitGraph VisitedGraph { get { return this.visitedGraph; } } /// <summary> /// Gets or sets the Markov <see cref="IEdge"/> chain. /// </summary> /// <value> /// Markov <see cref="IEdge"/> chain. /// </value> /// <exception cref="ArgumentNullException"> /// set property, value is a null reference. /// </exception> public IMarkovEdgeChain EdgeChain { get { return this.edgeChain; } set { if (value==null) throw new ArgumentNullException("edgeChain"); this.edgeChain = value; } } /// <summary> /// Gets or sets the random number generator used in <c>RandomTree</c>. /// </summary> /// <value> /// <see cref="Random"/> number generator /// </value> public Random Rnd { get { return this.rnd; } set { this.rnd = value; } } /// <summary> /// Gets or sets an end of traversal predicate. /// </summary> /// <value> /// End of traversal predicate. /// </value> public IEdgePredicate EndPredicate { get { return this.endPredicate; } set { this.endPredicate = value; } } #region IAlgorithm Members object IAlgorithm.VisitedGraph { get { return this.VisitedGraph; } } #endregion /// <summary> /// Raised on the source vertex once before the start of the search. /// </summary> public event VertexEventHandler StartVertex; /// <summary> /// Raises the <see cref="StartVertex"/> event. /// </summary> /// <param name="v">vertex that raised the event</param> protected void OnStartVertex(IVertex v) { if (StartVertex!=null) StartVertex(this, new VertexEventArgs(v)); } /// <summary> /// Raised on the sink vertex once after the end of the search. /// </summary> public event VertexEventHandler EndVertex; /// <summary> /// Raises the <see cref="EndVertex"/> event. /// </summary> /// <param name="v">vertex that raised the event</param> protected void OnEndVertex(IVertex v) { if (EndVertex!=null) EndVertex(this, new VertexEventArgs(v)); } /// <summary> /// Occurs when an edge is added to the tree. /// </summary> /// <remarks/> public event EdgeEventHandler TreeEdge; /// <summary> /// Raises the <see cref="TreeEdge"/> event. /// </summary> /// <param name="e">edge being added to the tree</param> protected void OnTreeEdge(IEdge e) { if (this.TreeEdge!=null) this.TreeEdge(this,new EdgeEventArgs(e)); } /// <summary> /// Gets the next <see cref="IEdge"/> out-edge according to /// the Markov Chain generator. /// </summary> /// <remarks> /// This method uses the <see cref="IMarkovEdgeChain"/> instance /// to compute the next random out-edge. If <paramref name="u"/> has /// no out-edge, null is returned. /// </remarks> /// <param name="u">Source vertex</param> /// <returns>next edge in the chain, null if u has no out-edges</returns> protected IEdge RandomSuccessor(IVertex u) { return this.EdgeChain.Successor(this.VisitedGraph,u); } /// <summary> /// Generates a walk of <paramref name="walkCount">steps</paramref> /// </summary> /// <param name="walkCount">number of steps</param> public void Generate(IVertex root) { Generate(root, int.MaxValue); } /// <summary> /// Generates a walk of <paramref name="walkCount">steps</paramref> /// </summary> /// <param name="root">root vertex</param> /// <param name="walkCount">number of steps</param> public void Generate(IVertex root,int walkCount) { int count = 0; IEdge e=null; IVertex v = root; OnStartVertex(root); while (count<walkCount) { e = RandomSuccessor(v); // if dead end stop if (e==null) break; // if end predicate, test if (this.endPredicate!=null && this.endPredicate.Test(e)) break; OnTreeEdge(e); v = e.Target; // upgrade count ++count; } OnEndVertex(v); } } }
using System; namespace Epm3d { public enum HanaVersion { /// <summary> /// TitleCase fields /// </summary> v1_00_60, /// <summary> /// UPPERCASE fields /// </summary> v1_00_70, /// <summary> /// TitleCase fields for epmNext /// </summary> v1_00_72, /// <summary> /// UPPERCASE fields again /// </summary> v1_00_80, Unknown } public class VerDetEventArgs : EventArgs { public HanaVersion HanaVer; } public class VersionTranslator { private HanaVersion _hanaVersion; private const string _epmPackagePath_60 = @"/sap/hana/democontent/epm/services/"; private const string _epmPackagePath_70 = @"/sap/hana/democontent/epm/services/"; private const string _epmPackagePath_72 = @"/sap/hana/democontent/epmNext/services/"; private const string _epmPackagePath_80 = @"/sap/hana/democontent/epm/services/"; //@"poWorklistQuery.xsjs?cmd=getTotalOrders&groupby=PartnerCity&currency=USD&filterterms="; private string _urlEnd_EpmChart = @"poWorklistQuery.xsjs?cmd=getTotalOrders&groupby={0}&currency={1}&filterterms="; private string _urlEnd_EpmGetOnePOwithItems = @"poWorklist.xsodata/PO_WORKLIST?$top={0}&$orderby={1},{2}%20asc&$filter={1}%20eq%20%27{3}%27&$format=json"; //@"poWorklistUpdate.xsjs?cmd=approval&PurchaseOrderId=0300000010&Action=Accept"; private string _urlEpm_AcceptOnePO = @"poWorklistUpdate.xsjs?cmd=approval&{0}={1}&Action=Accept"; // only POs eligible for approval/rejection that aren't already approved rejected private string _urlEnd_EpmGetMassPO = @"poWorklist.xsodata/PO_WORKLIST?$skip=0&$top={0}&$orderby={1},{2}%20asc&$select={1},{2}&$inlinecount=allpages&$filter={3}%20ne%20%27Closed%27%20and%20{3}%20ne%20%27Cancelled%27%20and%20{4}%20eq%20%27Initial%27%20and%20{5}%20ne%20%27Delivered%27%20and%20{6}%20ne%20%27Approved%27%20and%20{6}%20ne%20%27Rejected%27&$format=json"; private string _urlEpm_RejectOnePO = @"poWorklistUpdate.xsjs?cmd=approval&{0}={1}&Action=Reject"; /// <summary> /// Root url of SHINE services eg "http://<server>:80<instance>/sap/hana/democontent/epm/services/" /// </summary> private string _urlEpmBase; public VersionTranslator(HanaVersion hanaVersion, string host, string instance) { _hanaVersion = hanaVersion; switch (hanaVersion) { case HanaVersion.v1_00_60: _urlEpmBase = @"http://" + host + ":80" + instance + _epmPackagePath_60; break; case HanaVersion.v1_00_70: _urlEpmBase = @"http://" + host + ":80" + instance + _epmPackagePath_70; break; case HanaVersion.v1_00_72: _urlEpmBase = @"http://" + host + ":80" + instance + _epmPackagePath_72; break; case HanaVersion.v1_00_80: _urlEpmBase = @"http://" + host + ":80" + instance + _epmPackagePath_80; break; default: break; } } public string GetUrl_Chart(EpmDataTypeChart chartType, string chartCurrency) { // build url with params for chart group by and currency string chartTypeAdjustedForHanaSP = chartType.ToString(); if (_hanaVersion == HanaVersion.v1_00_70) { chartTypeAdjustedForHanaSP = chartTypeAdjustedForHanaSP.ToUpperInvariant(); } string url = _urlEpmBase + string.Format(_urlEnd_EpmChart, chartTypeAdjustedForHanaSP, chartCurrency); return url; } public string GetUrl_SinglePOwithItems(string poDoc, int maxItemsPerPO) { //@"poWorklist.xsodata/PO_WORKLIST?$top={0}&$orderby={1},{2}%20asc&$filter={1}%20eq%20%27{3}%27&$format=json"; // {0} = max items on po // {1} = PURCHASEORDERID // {2} = PURCHASEORDERITEM // {3} = 0300000002 string url = _urlEpmBase + string.Format(_urlEnd_EpmGetOnePOwithItems, maxItemsPerPO, GetPoFieldName(EpmPoFieldName.PurchaseOrderId), GetPoFieldName(EpmPoFieldName.PurchaseOrderItem), poDoc); return url; } public string GetUrl_MassListPO(int maxPos) { //@"poWorklist.xsodata/PO_WORKLIST?$skip=0&$top={0}&$orderby=PurchaseOrderId,PurchaseOrderItem%20asc&$select=PurchaseOrderId,PurchaseOrderItem&$inlinecount=allpages&$filter=LifecycleDesc%20ne%20%27Closed%27%20and%20LifecycleDesc%20ne%20%27Cancelled%27%20and%20ConfirmationDesc%20eq%20%27Initial%27%20and%20OrderingDesc%20ne%20%27Delivered%27&$format=json"; // {0} = count // {1} = po // {2} = poitem // {3} = lifecycledesc // {4} = confirmationdesc // {5} = orderingdesc // {6} = approvaldesc string url = _urlEpmBase + string.Format(_urlEnd_EpmGetMassPO, maxPos.ToString(), GetPoFieldName(EpmPoFieldName.PurchaseOrderId), GetPoFieldName(EpmPoFieldName.PurchaseOrderItem), GetPoFieldName(EpmPoFieldName.LifecycleDesc), GetPoFieldName(EpmPoFieldName.ConfirmationDesc), GetPoFieldName(EpmPoFieldName.OrderingDesc), GetPoFieldName(EpmPoFieldName.ApprovalDesc) ); return url; } public string GetUrl_ApprovePO(string poDoc) { //_urlEpm_AcceptOnePO = @"poWorklistUpdate.xsjs?cmd=approval&PurchaseOrderId=0300000010&Action=Accept"; //_urlEpm_AcceptOnePO = @"poWorklistUpdate.xsjs?cmd=approval&{0}={1}&Action=Accept"; string url = _urlEpmBase + string.Format(_urlEpm_AcceptOnePO, GetPoFieldName(EpmPoFieldName.PurchaseOrderId), poDoc); return url; } public string GetUrl_RejectPO(string poDoc) { string url = _urlEpmBase + string.Format(_urlEpm_RejectOnePO, GetPoFieldName(EpmPoFieldName.PurchaseOrderId), poDoc); return url; } /// <summary> /// Gets the url to check for a hana version. /// Static so it can called before actual version is known /// </summary> public static string GetUrl_ToCheckForAVersion(HanaVersion hanaVersion, string host, string instance) { string url = ""; switch (hanaVersion) { case HanaVersion.v1_00_60: // 60 // URL PO chart data (internal) // http://uvo1lhvt5s58vittd8f.vm.cld.sr:8000/sap/hana/democontent/epm/services/poWorklistQuery.xsjs?cmd=getTotalOrders&groupby=PartnerCity&currency=USD&filterterms= url = @"http://" + host + ":80" + instance + _epmPackagePath_60 + @"poWorklistQuery.xsjs?cmd=getTotalOrders&groupby=PartnerCity&currency=USD&filterterms="; break; case HanaVersion.v1_00_70: // 70 // URL PO chart data (internal) // http://54.86.47.170:8002/sap/hana/democontent/epm/services/poWorklistQuery.xsjs?cmd=getTotalOrders&groupby=PARTNERCITY&currency=USD&filterterms= url = @"http://" + host + ":80" + instance + _epmPackagePath_70 + @"poWorklistQuery.xsjs?cmd=getTotalOrders&groupby=PARTNERCITY&currency=USD&filterterms="; break; case HanaVersion.v1_00_72: // 72 // URL PO chart data (internal) // http://54.178.200.169:8000/sap/hana/democontent/epmNext/services/poWorklistQuery.xsjs?cmd=getTotalOrders&groupby=PartnerCity&currency=USD&filterterms= [note fields TitleCase] url = @"http://" + host + ":80" + instance + _epmPackagePath_72 + @"poWorklistQuery.xsjs?cmd=getTotalOrders&groupby=PartnerCity&currency=USD&filterterms="; break; case HanaVersion.v1_00_80: // 80 // URL PO chart data (internal) // http://54.178.200.169:8000/sap/hana/democontent/epm/services/poWorklistQuery.xsjs?cmd=getTotalOrders&groupby=PARTNERCITY&currency=USD&filterterms= [note fields back to UPPERCASE] url = @"http://" + host + ":80" + instance + _epmPackagePath_80 + @"poWorklistQuery.xsjs?cmd=getTotalOrders&groupby=PARTNERCITY&currency=USD&filterterms="; break; default: break; } // @"http://" + host + @":80" + instance + @"/sap/hana/xs/ide/"; // _urlEpmBase + string.Format(_urlEpm_RejectOnePO, // GetPoFieldName(EpmPoFieldName.PurchaseOrderId), poDoc); return url; } /// <summary> /// Gets the PO field name, taking into account SP6 SP7 etc differences. /// </summary> public string GetPoFieldName(EpmPoFieldName epmPoFieldName) { string poFieldName = ""; if (_hanaVersion == HanaVersion.v1_00_70) { // SP7.0 is all upper case fields, with some exceptions switch (epmPoFieldName) { case EpmPoFieldName.ProductTypeCode: poFieldName = "TYPECODE"; break; case EpmPoFieldName.ProductCategory: poFieldName = "CATEGORY"; break; case EpmPoFieldName.PartnerCity: poFieldName = "CITY"; break; case EpmPoFieldName.PartnerPostalCode: poFieldName = "POSTALCODE"; break; default: poFieldName = epmPoFieldName.ToString().ToUpperInvariant(); break; } } else { // SP6 has mixed upper lower case fields, the enum was built to match this poFieldName = epmPoFieldName.ToString(); } return poFieldName; } } }
// // XmlElementTests // // Authors: // Jason Diamond ([email protected]) // Martin Willemoes Hansen ([email protected]) // // (C) 2002 Jason Diamond http://injektilo.org/ // (C) 2003 Martin Willemoes Hansen // using System; using System.Xml; using System.IO; using System.Text; using NUnit.Framework; namespace MonoTests.System.Xml { [TestFixture] public class XmlElementTests : Assertion { private XmlDocument document; [SetUp] public void GetReady () { document = new XmlDocument (); } private void AssertElement (XmlElement element, string prefix, string localName, string namespaceURI, int attributesCount) { AssertEquals (prefix != String.Empty ? prefix + ":" + localName : localName, element.Name); AssertEquals (prefix, element.Prefix); AssertEquals (localName, element.LocalName); AssertEquals (namespaceURI, element.NamespaceURI); //AssertEquals (attributesCount, element.Attributes.Count); } // for NodeInserted Event private bool Inserted = false; private void OnNodeInserted (object o, XmlNodeChangedEventArgs e) { Inserted = true; } // for NodeChanged Event private bool Changed = false; private void OnNodeChanged (object o, XmlNodeChangedEventArgs e) { Changed = true; } // for NodeRemoved Event private bool Removed = false; private void OnNodeRemoved (object o, XmlNodeChangedEventArgs e) { Removed = true; } [Test] public void CloneNode () { XmlElement element = document.CreateElement ("foo"); XmlElement child = document.CreateElement ("bar"); XmlElement grandson = document.CreateElement ("baz"); element.SetAttribute ("attr1", "val1"); element.SetAttribute ("attr2", "val2"); element.AppendChild (child); child.SetAttribute ("attr3", "val3"); child.AppendChild (grandson); document.AppendChild (element); XmlNode deep = element.CloneNode (true); // AssertEquals ("These should be the same", deep.OuterXml, element.OuterXml); AssertNull ("This is not null", deep.ParentNode); Assert ("Copies, not pointers", !Object.ReferenceEquals (element,deep)); XmlNode shallow = element.CloneNode (false); AssertNull ("This is not null", shallow.ParentNode); Assert ("Copies, not pointers", !Object.ReferenceEquals (element,shallow)); AssertEquals ("Shallow clones shalt have no children!", false, shallow.HasChildNodes); } [Test] public void ConstructionAndDefaultAttributes () { string dtd = "<!DOCTYPE root [<!ELEMENT root EMPTY><!ATTLIST root foo CDATA 'def'>]>"; string xml = dtd + "<root />"; // XmlValidatingReader xvr = new XmlValidatingReader (new XmlTextReader (xml, XmlNodeType.Document, null)); XmlDocument doc = new XmlDocument (); doc.LoadXml (xml); Console.WriteLine (doc.DocumentElement.Attributes.Count); Console.WriteLine (doc.CreateElement ("root").Attributes.Count); Console.WriteLine (doc.CreateElement ("root2").Attributes.Count); } [Test] public void CreateElement1 () { XmlElement element = document.CreateElement ("name"); AssertElement (element, String.Empty, "name", String.Empty, 0); } [Test] public void CreateElement1WithPrefix () { XmlElement element = document.CreateElement ("prefix:localName"); AssertElement (element, "prefix", "localName", String.Empty, 0); } [Test] public void CreateElement2 () { XmlElement element = document.CreateElement ("qualifiedName", "namespaceURI"); AssertElement (element, String.Empty, "qualifiedName", "namespaceURI", 0); } [Test] public void CreateElement2WithPrefix () { XmlElement element = document.CreateElement ("prefix:localName", "namespaceURI"); AssertElement (element, "prefix", "localName", "namespaceURI", 0); } [Test] public void CreateElement3 () { XmlElement element = document.CreateElement ("prefix", "localName", "namespaceURI"); AssertElement (element, "prefix", "localName", "namespaceURI", 0); } [Test] public void CreateElement3WithNullNamespace () { // bug #26855, NamespaceURI should NEVER be null. XmlElement element = document.CreateElement (null, "localName", null); AssertElement (element, String.Empty, "localName", String.Empty, 0); } [Test] public void InnerAndOuterXml () { XmlElement element; XmlText text; XmlComment comment; element = document.CreateElement ("foo"); AssertEquals (String.Empty, element.InnerXml); AssertEquals ("<foo />", element.OuterXml); text = document.CreateTextNode ("bar"); element.AppendChild (text); AssertEquals ("bar", element.InnerXml); AssertEquals ("<foo>bar</foo>", element.OuterXml); element.SetAttribute ("baz", "quux"); AssertEquals ("bar", element.InnerXml); AssertEquals ("<foo baz=\"quux\">bar</foo>", element.OuterXml); comment = document.CreateComment ("squonk"); element.AppendChild (comment); AssertEquals ("bar<!--squonk-->", element.InnerXml); AssertEquals ("<foo baz=\"quux\">bar<!--squonk--></foo>", element.OuterXml); element.RemoveAll(); element.AppendChild(document.CreateElement("hoge")); AssertEquals ("<hoge />", element.InnerXml); } [Test] public void SetGetAttribute () { XmlElement element = document.CreateElement ("foo"); element.SetAttribute ("attr1", "val1"); element.SetAttribute ("attr2", "val2"); AssertEquals ("val1", element.GetAttribute ("attr1")); AssertEquals ("val2", element.GetAttribute ("attr2")); } [Test] public void GetElementsByTagNameNoNameSpace () { string xml = @"<library><book><title>XML Fun</title><author>John Doe</author> <price>34.95</price></book><book><title>Bear and the Dragon</title> <author>Tom Clancy</author><price>6.95</price></book><book> <title>Bourne Identity</title><author>Robert Ludlum</author> <price>9.95</price></book><Fluffer><Nutter><book> <title>Bourne Ultimatum</title><author>Robert Ludlum</author> <price>9.95</price></book></Nutter></Fluffer></library>"; MemoryStream memoryStream = new MemoryStream (Encoding.UTF8.GetBytes (xml)); document = new XmlDocument (); document.Load (memoryStream); XmlNodeList libraryList = document.GetElementsByTagName ("library"); XmlNode xmlNode = libraryList.Item (0); XmlElement xmlElement = xmlNode as XmlElement; XmlNodeList bookList = xmlElement.GetElementsByTagName ("book"); AssertEquals ("GetElementsByTagName (string) returned incorrect count.", 4, bookList.Count); } [Test] public void GetElementsByTagNameUsingNameSpace () { StringBuilder xml = new StringBuilder (); xml.Append ("<?xml version=\"1.0\" ?><library xmlns:North=\"http://www.foo.com\" "); xml.Append ("xmlns:South=\"http://www.goo.com\"><North:book type=\"non-fiction\"> "); xml.Append ("<North:title type=\"intro\">XML Fun</North:title> " ); xml.Append ("<North:author>John Doe</North:author> " ); xml.Append ("<North:price>34.95</North:price></North:book> " ); xml.Append ("<South:book type=\"fiction\"> " ); xml.Append ("<South:title>Bear and the Dragon</South:title> " ); xml.Append ("<South:author>Tom Clancy</South:author> " ); xml.Append ("<South:price>6.95</South:price></South:book> " ); xml.Append ("<South:book type=\"fiction\"><South:title>Bourne Identity</South:title> " ); xml.Append ("<South:author>Robert Ludlum</South:author> " ); xml.Append ("<South:price>9.95</South:price></South:book></library>"); MemoryStream memoryStream = new MemoryStream (Encoding.UTF8.GetBytes (xml.ToString ())); document = new XmlDocument (); document.Load (memoryStream); XmlNodeList libraryList = document.GetElementsByTagName ("library"); XmlNode xmlNode = libraryList.Item (0); XmlElement xmlElement = xmlNode as XmlElement; XmlNodeList bookList = xmlElement.GetElementsByTagName ("book", "http://www.foo.com"); AssertEquals ("GetElementsByTagName (string, uri) returned incorrect count.", 1, bookList.Count); } [Test] public void GetElementsByTagNameNs2 () { document.LoadXml (@"<root> <x:a xmlns:x='urn:foo' id='a'> <y:a xmlns:y='urn:foo' id='b'/> <x:a id='c' /> <z id='d' /> text node <?a processing instruction ?> <x:w id='e'/> </x:a> </root>"); // id='b' has different prefix. Should not caught by (name), // while should caught by (name, ns). XmlNodeList nl = document.DocumentElement.GetElementsByTagName ("x:a"); AssertEquals (2, nl.Count); AssertEquals ("a", nl [0].Attributes ["id"].Value); AssertEquals ("c", nl [1].Attributes ["id"].Value); nl = document.DocumentElement.GetElementsByTagName ("a", "urn:foo"); AssertEquals (3, nl.Count); AssertEquals ("a", nl [0].Attributes ["id"].Value); AssertEquals ("b", nl [1].Attributes ["id"].Value); AssertEquals ("c", nl [2].Attributes ["id"].Value); // name wildcard nl = document.DocumentElement.GetElementsByTagName ("*"); AssertEquals (5, nl.Count); AssertEquals ("a", nl [0].Attributes ["id"].Value); AssertEquals ("b", nl [1].Attributes ["id"].Value); AssertEquals ("c", nl [2].Attributes ["id"].Value); AssertEquals ("d", nl [3].Attributes ["id"].Value); AssertEquals ("e", nl [4].Attributes ["id"].Value); // wildcard - local and ns nl = document.DocumentElement.GetElementsByTagName ("*", "*"); AssertEquals (5, nl.Count); AssertEquals ("a", nl [0].Attributes ["id"].Value); AssertEquals ("b", nl [1].Attributes ["id"].Value); AssertEquals ("c", nl [2].Attributes ["id"].Value); AssertEquals ("d", nl [3].Attributes ["id"].Value); AssertEquals ("e", nl [4].Attributes ["id"].Value); // namespace wildcard - namespace nl = document.DocumentElement.GetElementsByTagName ("*", "urn:foo"); AssertEquals (4, nl.Count); AssertEquals ("a", nl [0].Attributes ["id"].Value); AssertEquals ("b", nl [1].Attributes ["id"].Value); AssertEquals ("c", nl [2].Attributes ["id"].Value); AssertEquals ("e", nl [3].Attributes ["id"].Value); // namespace wildcard - local only. I dare say, such usage is not XML-ish! nl = document.DocumentElement.GetElementsByTagName ("a", "*"); AssertEquals (3, nl.Count); AssertEquals ("a", nl [0].Attributes ["id"].Value); AssertEquals ("b", nl [1].Attributes ["id"].Value); AssertEquals ("c", nl [2].Attributes ["id"].Value); } [Test] public void OuterXmlWithNamespace () { XmlElement element = document.CreateElement ("foo", "bar", "#foo"); AssertEquals ("<foo:bar xmlns:foo=\"#foo\" />", element.OuterXml); } [Test] public void RemoveAllAttributes () { StringBuilder xml = new StringBuilder (); xml.Append ("<?xml version=\"1.0\" ?><library><book type=\"non-fiction\" price=\"34.95\"> "); xml.Append ("<title type=\"intro\">XML Fun</title> " ); xml.Append ("<author>John Doe</author></book></library>"); MemoryStream memoryStream = new MemoryStream (Encoding.UTF8.GetBytes (xml.ToString ())); document = new XmlDocument (); document.Load (memoryStream); XmlNodeList bookList = document.GetElementsByTagName ("book"); XmlNode xmlNode = bookList.Item (0); XmlElement xmlElement = xmlNode as XmlElement; xmlElement.RemoveAllAttributes (); AssertEquals ("attributes not properly removed.", false, xmlElement.HasAttribute ("type")); } [Test] public void RemoveDoesNotRemoveDefaultAttributes () { string dtd = "<!DOCTYPE root [<!ELEMENT root EMPTY><!ATTLIST root foo CDATA 'def' bar CDATA #IMPLIED>]>"; string xml = dtd + "<root bar='baz' />"; XmlValidatingReader xvr = new XmlValidatingReader (xml, XmlNodeType.Document, null); document.Load (xvr); // RemoveAll AssertNotNull (document.DocumentElement); AssertEquals ("attrCount #01", 2, document.DocumentElement.Attributes.Count); AssertEquals ("baz", document.DocumentElement.GetAttribute ("bar")); AssertEquals ("def", document.DocumentElement.GetAttribute ("foo")); AssertEquals (false, document.DocumentElement.GetAttributeNode ("foo").Specified); document.DocumentElement.RemoveAll (); AssertEquals ("attrCount #02", 1, document.DocumentElement.Attributes.Count); AssertEquals ("def", document.DocumentElement.GetAttribute ("foo")); AssertEquals (String.Empty, document.DocumentElement.GetAttribute ("bar")); // RemoveAllAttributes xvr = new XmlValidatingReader (xml, XmlNodeType.Document, null); document.Load (xvr); document.DocumentElement.RemoveAllAttributes (); AssertEquals ("attrCount #03", 1, document.DocumentElement.Attributes.Count); // RemoveAttribute(name) xvr = new XmlValidatingReader (xml, XmlNodeType.Document, null); document.Load (xvr); document.DocumentElement.RemoveAttribute ("foo"); AssertEquals ("attrCount #04", 2, document.DocumentElement.Attributes.Count); // RemoveAttribute(name, ns) xvr = new XmlValidatingReader (xml, XmlNodeType.Document, null); document.Load (xvr); document.DocumentElement.RemoveAttribute ("foo", String.Empty); AssertEquals ("attrCount #05", 2, document.DocumentElement.Attributes.Count); // RemoveAttributeAt xvr = new XmlValidatingReader (xml, XmlNodeType.Document, null); document.Load (xvr); document.DocumentElement.RemoveAttributeAt (1); AssertEquals ("attrCount #06", 2, document.DocumentElement.Attributes.Count); // RemoveAttributeNode xvr = new XmlValidatingReader (xml, XmlNodeType.Document, null); document.Load (xvr); document.DocumentElement.RemoveAttributeNode (document.DocumentElement.Attributes [1]); AssertEquals ("attrCount #07", 2, document.DocumentElement.Attributes.Count); // RemoveAttributeNode(name, ns) xvr = new XmlValidatingReader (xml, XmlNodeType.Document, null); document.Load (xvr); document.DocumentElement.RemoveAttributeNode ("foo", String.Empty); AssertEquals ("attrCount #08", 2, document.DocumentElement.Attributes.Count); } [Test] public void SetAttributeNode () { XmlDocument xmlDoc = new XmlDocument (); XmlElement xmlEl = xmlDoc.CreateElement ("TestElement"); XmlAttribute xmlAttribute = xmlEl.SetAttributeNode ("attr1", "namespace1"); XmlAttribute xmlAttribute2 = xmlEl.SetAttributeNode ("attr2", "namespace2"); AssertEquals ("attribute name not properly created.", true, xmlAttribute.Name.Equals ("attr1")); AssertEquals ("attribute namespace not properly created.", true, xmlAttribute.NamespaceURI.Equals ("namespace1")); } [Test] [ExpectedException (typeof (XmlException))] public void SetAttributeNodeError () { XmlDocument doc = new XmlDocument (); doc.LoadXml ("<root xmlns:x='urn:foo'/>"); doc.DocumentElement.SetAttributeNode ("x:lang", "urn:foo"); } [Test] public void SetAttributeXmlns () { // should not affect Element node's xmlns XmlElement el = document.CreateElement ("root"); el.SetAttribute ("xmlns", "urn:foo"); AssertEquals (String.Empty, el.NamespaceURI); } [Test] public void InnerTextAndEvent () { XmlDocument doc = new XmlDocument (); doc.LoadXml ("<root><child>text</child><child2><![CDATA[cdata]]></child2></root>"); doc.NodeInserted += new XmlNodeChangedEventHandler ( OnNodeInserted); doc.NodeRemoved += new XmlNodeChangedEventHandler ( OnNodeRemoved); // If only one child of the element is Text node, // then no events are fired. doc.DocumentElement.FirstChild.InnerText = "no events fired."; AssertEquals ("NoInsertEventFired", false, Inserted); AssertEquals ("NoRemoveEventFired", false, Removed); AssertEquals ("SetInnerTextToSingleText", "no events fired.", doc.DocumentElement.FirstChild.InnerText); Inserted = false; Removed = false; // if only one child of the element is CDataSection, // then events are fired. doc.DocumentElement.LastChild.InnerText = "events are fired."; AssertEquals ("InsertedEventFired", true, Inserted); AssertEquals ("RemovedEventFired", true, Removed); AssertEquals ("SetInnerTextToCDataSection", "events are fired.", doc.DocumentElement.LastChild.InnerText); } [Test] public void InnerXmlSetter () { XmlDocument doc = new XmlDocument (); doc.LoadXml ("<root/>"); XmlElement el = doc.DocumentElement; AssertNull ("#Simple", el.FirstChild); el.InnerXml = "<foo><bar att='baz'/></foo>"; XmlElement child = el.FirstChild as XmlElement; AssertNotNull ("#Simple.Child", child); AssertEquals ("#Simple.Child.Name", "foo", child.LocalName); XmlElement grandchild = child.FirstChild as XmlElement; AssertNotNull ("#Simple.GrandChild", grandchild); AssertEquals ("#Simple.GrandChild.Name", "bar", grandchild.LocalName); AssertEquals ("#Simple.GrandChild.Attr", "baz", grandchild.GetAttribute ("att")); doc.LoadXml ("<root xmlns='NS0' xmlns:ns1='NS1'><foo/><ns1:bar/><ns2:bar xmlns:ns2='NS2' /></root>"); el = doc.DocumentElement.FirstChild.NextSibling as XmlElement; // ns1:bar AssertNull ("#Namespaced.Prepare", el.FirstChild); el.InnerXml = "<ns1:baz />"; AssertNotNull ("#Namespaced.Child", el.FirstChild); AssertEquals ("#Namespaced.Child.Name", "baz", el.FirstChild.LocalName); AssertEquals ("#Namespaced.Child.NSURI", "NS1", el.FirstChild.NamespaceURI); // important! el.InnerXml = "<hoge />"; AssertEquals ("#Namespaced.VerifyPreviousCleared", "hoge", el.FirstChild.Name); } [Test] public void InnerXmlSetter2 () { // See bug #63574 XmlDocument doc = new XmlDocument (); doc.LoadXml (@"<type>QPair&lt;QString,int&gt;:: <ref refid='classQPair'>QPair</ref> &lt; <ref refid='classQString'>QString</ref> ,int&gt; </type>"); XmlElement typeNode = doc.DocumentElement; typeNode.InnerText = "QPair<QString, int>"; AssertEquals ("QPair<QString, int>", typeNode.InnerText); } [Test] public void IsEmpty () { document.LoadXml ("<root><foo/><bar></bar></root>"); Assertion.AssertEquals ("Empty", true, ((XmlElement) document.DocumentElement.FirstChild).IsEmpty); Assertion.AssertEquals ("Empty", false, ((XmlElement) document.DocumentElement.LastChild).IsEmpty); } [Test] public void RemoveAttribute () { string xlinkURI = "http://www.w3.org/1999/XLink"; XmlDocument doc = new XmlDocument (); doc.LoadXml ("<root a1='1' a2='2' xlink:href='urn:foo' xmlns:xlink='" + xlinkURI + "' />"); XmlElement el = doc.DocumentElement; el.RemoveAttribute ("a1"); AssertNull ("RemoveAttribute", el.GetAttributeNode ("a1")); el.RemoveAttribute ("xlink:href"); AssertNull ("RemoveAttribute", el.GetAttributeNode ("href", xlinkURI)); el.RemoveAllAttributes (); AssertNull ("RemoveAllAttributes", el.GetAttributeNode ("a2")); } [Test] public void WriteToWithDefaultNamespace () { XmlDocument doc = new XmlDocument (); doc.LoadXml ("<RetrievalElement URI=\"\" xmlns=\"http://www.w3.org/2000/09/xmldsig#\" />"); StringWriter sw = new StringWriter (); XmlTextWriter xtw = new XmlTextWriter (sw); doc.DocumentElement.WriteTo (xtw); AssertEquals ("<RetrievalElement URI=\"\" xmlns=\"http://www.w3.org/2000/09/xmldsig#\" />", sw.ToString()); } [Test] public void WriteToMakesNonsenseForDefaultNSChildren () { XmlDocument d = new XmlDocument (); XmlElement x = d.CreateElement ("root"); d.AppendChild (x); XmlElement a = d.CreateElement ("a"); XmlElement b = d.CreateElement ("b"); b.SetAttribute ("xmlns","probe"); x.AppendChild (a); x.AppendChild (b); XmlElement b2 = d.CreateElement ("p2", "b2", ""); b.AppendChild (b2); AssertEquals ("<root><a /><b xmlns=\"probe\"><b2 /></b></root>", d.OuterXml); } [Test] public void WriteToWithDeletedNamespacePrefix () { XmlDocument doc = new XmlDocument (); doc.LoadXml ("<root xmlns:foo='urn:dummy'><foo foo:bar='baz' /></root>"); doc.DocumentElement.RemoveAllAttributes (); Assert (doc.DocumentElement.FirstChild.OuterXml.IndexOf("xmlns:foo") > 0); } [Test] public void WriteToWithDifferentNamespaceAttributes () { XmlDocument doc = new XmlDocument (); doc.LoadXml ("<root xmlns:foo='urn:dummy' xmlns:html='http://www.w3.org/1999/xhtml' html:style='font-size: 1em'></root>"); Assert (doc.OuterXml.IndexOf ("xmlns:html=\"http://www.w3.org/1999/xhtml\"") > 0); } [Test] public void WriteToDefaultAttribute () { // default attributes should be ignored. string dtd = "<!DOCTYPE root[<!ATTLIST root hoge CDATA 'hoge-def'><!ENTITY foo 'ent-foo'>]>"; string xml = dtd + "<root>&foo;</root>"; XmlValidatingReader xvr = new XmlValidatingReader (xml, XmlNodeType.Document,null); xvr.EntityHandling = EntityHandling.ExpandCharEntities; xvr.ValidationType = ValidationType.None; document.Load (xvr); StringWriter sw = new StringWriter (); XmlTextWriter xtw = new XmlTextWriter (sw); document.DocumentElement.WriteTo (xtw); AssertEquals ("<root>&foo;</root>", sw.ToString ()); } } }
using System; using System.Collections.Generic; using UnityEngine; public class JoyStickControlor : MonoBehaviour { public enum StickButtonCode { None, A, A_DOWN, A_UP, B, X, Y, L1, R1, L1_X, L1_Y, L1_A, R1_X, R1_Y, R1_A, L1_R1, LeftArrow, RightArrow, UpArrow, DownArrow, Both } public enum UIMouseStatus { MouseHide, MouseActive } public delegate void OnInputCode(JoyStickControlor.StickButtonCode code); [HideInInspector] public KeyCode KeyCode_X = KeyCode.JoystickButton2; [HideInInspector] public KeyCode KeyCode_Y = KeyCode.JoystickButton3; [HideInInspector] public KeyCode KeyCode_A = KeyCode.JoystickButton0; [HideInInspector] public KeyCode KeyCode_B = KeyCode.JoystickButton1; [HideInInspector] public KeyCode KeyCode_R1 = KeyCode.JoystickButton5; [HideInInspector] public KeyCode KeyCode_L1 = KeyCode.JoystickButton4; [HideInInspector] public KeyCode KeyCode_Left = KeyCode.LeftArrow; [HideInInspector] public KeyCode KeyCode_Right = KeyCode.RightArrow; [HideInInspector] public KeyCode KeyCode_Up = KeyCode.UpArrow; [HideInInspector] public KeyCode KeyCode_Down = KeyCode.DownArrow; private List<JoyStickControlor.OnInputCode> inputListeners = new List<JoyStickControlor.OnInputCode>(); private List<JoyStickControlor.StickButtonCode> codeList = new List<JoyStickControlor.StickButtonCode>(); private JoyStickControlor.UIMouseStatus _mouseStatus; private int detecFrameInterval = 1; private int beforeDownFrame; private int mouseMoveSpeed = 2; private GameObject mouseObj; private Transform mouseTrans; private Camera uicamera; private static JoyStickControlor instance; public JoyStickControlor.UIMouseStatus MoustStatus { get { return this._mouseStatus; } set { this._mouseStatus = value; } } public Vector3 MousePositon { get { if (this.mouseTrans != null) { Camera currentCamera = UICamera.currentCamera; return currentCamera.WorldToScreenPoint(this.mouseTrans.position); } return Vector3.zero; } } public static JoyStickControlor GetInstance() { if (JoyStickControlor.instance == null) { GameObject gameObject = GameObject.FindGameObjectWithTag("UICamera"); if (gameObject != null) { JoyStickControlor.instance = gameObject.GetComponent<JoyStickControlor>(); if (JoyStickControlor.instance == null) { JoyStickControlor.instance = gameObject.AddComponent<JoyStickControlor>(); JoyStickControlor.instance.uicamera = gameObject.GetComponent<Camera>(); } } } return JoyStickControlor.instance; } private void Awake() { Instance.Set<JoyStickControlor>(this, true); } public void Init() { this.CreateMouseObj(); } private void CreateMouseObj() { string text = "Prefabs/UI/MousePanel"; string text2 = text.ToLower(); DelegateProxy.LoadAsset(text, new AssetCallBack(this.OnPrefabLoaded)); } private void OnPrefabLoaded(params object[] param) { UnityEngine.Object @object = param[0] as UnityEngine.Object; if (@object != null && this.uicamera != null) { this.mouseObj = (UnityEngine.Object.Instantiate(@object) as GameObject); this.mouseObj.SetActive(false); this.mouseObj.name = "Mouse"; this.mouseTrans = this.mouseObj.transform; this.mouseTrans.parent = this.uicamera.transform; this.mouseTrans.localScale = Vector3.one; this.mouseTrans.localPosition = Vector3.zero; UIPanel component = this.mouseTrans.GetComponent<UIPanel>(); component.depth = 2000; } DelegateProxy.UnloadAsset(param); } private void Update() { if (this._mouseStatus == JoyStickControlor.UIMouseStatus.MouseActive) { this.MouseMove(); if (Input.GetKey(this.KeyCode_A) || Input.GetKeyUp(this.KeyCode_A) || Input.GetKeyDown(this.KeyCode_A)) { this.StickCodeHandle(JoyStickControlor.StickButtonCode.A); } else if (Input.GetKeyUp(this.KeyCode_Y)) { this.StickCodeHandle(JoyStickControlor.StickButtonCode.Y); } return; } if (Input.GetKeyDown(this.KeyCode_A)) { this.StickCodeHandle(JoyStickControlor.StickButtonCode.A_DOWN); } if (Input.GetKey(this.KeyCode_A)) { if (Input.GetKey(this.KeyCode_L1)) { this.StickCodeHandle(JoyStickControlor.StickButtonCode.L1_A); } else if (Input.GetKey(this.KeyCode_R1)) { this.StickCodeHandle(JoyStickControlor.StickButtonCode.R1_A); } else { this.StickCodeHandle(JoyStickControlor.StickButtonCode.A); } } if (Input.GetKey(this.KeyCode_X)) { if (Input.GetKey(this.KeyCode_L1)) { this.StickCodeHandle(JoyStickControlor.StickButtonCode.L1_X); } else if (Input.GetKey(this.KeyCode_R1)) { this.StickCodeHandle(JoyStickControlor.StickButtonCode.R1_X); } else { this.StickCodeHandle(JoyStickControlor.StickButtonCode.X); } } if (Input.GetKey(this.KeyCode_Y)) { if (Input.GetKey(this.KeyCode_L1)) { this.StickCodeHandle(JoyStickControlor.StickButtonCode.L1_Y); } else if (Input.GetKey(this.KeyCode_R1)) { this.StickCodeHandle(JoyStickControlor.StickButtonCode.R1_Y); } else { this.StickCodeHandle(JoyStickControlor.StickButtonCode.Y); } } if (Input.GetKey(this.KeyCode_L1)) { if (Input.GetKey(this.KeyCode_R1)) { this.StickCodeHandle(JoyStickControlor.StickButtonCode.L1_R1); } else { this.StickCodeHandle(JoyStickControlor.StickButtonCode.L1); } } else if (Input.GetKey(this.KeyCode_R1)) { this.StickCodeHandle(JoyStickControlor.StickButtonCode.R1); } } private void StickCodeHandle(JoyStickControlor.StickButtonCode code) { if (code == JoyStickControlor.StickButtonCode.L1_R1) { this.HideOrShowMouse(true); } else if (code == JoyStickControlor.StickButtonCode.Y && this._mouseStatus == JoyStickControlor.UIMouseStatus.MouseActive) { this.HideOrShowMouse(false); return; } if (this._mouseStatus == JoyStickControlor.UIMouseStatus.MouseHide) { this.DispatchEvents(code); } else if (code == JoyStickControlor.StickButtonCode.A) { this.DispatchEvents(code); } } private void HideOrShowMouse(bool state) { if (this.mouseObj != null) { this.mouseObj.SetActive(state); if (state) { this._mouseStatus = JoyStickControlor.UIMouseStatus.MouseActive; } else { this._mouseStatus = JoyStickControlor.UIMouseStatus.MouseHide; } } } private void MouseMove() { Vector3 zero = Vector3.zero; if (Input.GetAxis("joy_horizontal") != 0f) { zero.x = Input.GetAxis("joy_horizontal"); } else if (Input.GetAxis("dpad_horizontal") != 0f) { zero.x = Input.GetAxis("dpad_horizontal"); } if (Input.GetAxis("joy_vertical") != 0f) { zero.y = Input.GetAxis("joy_vertical"); } else if (Input.GetAxis("dpad_vertical") != 0f) { zero.y = Input.GetAxis("dpad_vertical"); } zero.Normalize(); this.mouseTrans.Translate(zero * (float)this.mouseMoveSpeed * Time.deltaTime); Vector3 localPosition = this.mouseTrans.localPosition; float pixelWidth = this.uicamera.pixelWidth; float pixelHeight = this.uicamera.pixelHeight; if (localPosition.x > pixelWidth / 2f) { localPosition.x = pixelWidth / 2f; } else if (localPosition.x < pixelWidth / 2f * -1f) { localPosition.x = pixelWidth / 2f * -1f; } if (localPosition.y > pixelHeight / 2f) { localPosition.y = pixelHeight / 2f; } else if (localPosition.y < pixelHeight / 2f * -1f) { localPosition.y = pixelHeight / 2f * -1f; } this.mouseTrans.localPosition = localPosition; } public void AddListener(JoyStickControlor.OnInputCode onInput) { if (this.inputListeners != null && !this.inputListeners.Contains(onInput)) { this.inputListeners.Add(onInput); } } public void RemoveListener(JoyStickControlor.OnInputCode onInput) { if (this.inputListeners != null && this.inputListeners.Contains(onInput)) { this.inputListeners.Remove(onInput); } } private void DispatchEvents(JoyStickControlor.StickButtonCode code) { if (this.inputListeners == null || this.inputListeners.Count == 0) { return; } for (int i = 0; i < this.inputListeners.Count; i++) { this.inputListeners[i](code); } } public bool GetKey(KeyCode key) { return Input.GetKey(key); } public bool GetKeyDown(KeyCode key) { return Input.GetKeyDown(key); } public bool GetKeyUp(KeyCode key) { return Input.GetKeyUp(key); } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsAzureSpecials { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; /// <summary> /// ApiVersionDefaultOperations operations. /// </summary> internal partial class ApiVersionDefaultOperations : IServiceOperations<AutoRestAzureSpecialParametersTestClient>, IApiVersionDefaultOperations { /// <summary> /// Initializes a new instance of the ApiVersionDefaultOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ApiVersionDefaultOperations(AutoRestAzureSpecialParametersTestClient client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AutoRestAzureSpecialParametersTestClient /// </summary> public AutoRestAzureSpecialParametersTestClient Client { get; private set; } /// <summary> /// GET method with api-version modeled in global settings. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> GetMethodGlobalValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetMethodGlobalValid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/apiVersion/method/string/none/query/global/2015-07-01-preview").ToString(); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.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> /// GET method with api-version modeled in global settings. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> GetMethodGlobalNotProvidedValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetMethodGlobalNotProvidedValid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/apiVersion/method/string/none/query/globalNotProvided/2015-07-01-preview").ToString(); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.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> /// GET method with api-version modeled in global settings. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> GetPathGlobalValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetPathGlobalValid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/apiVersion/path/string/none/query/global/2015-07-01-preview").ToString(); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.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> /// GET method with api-version modeled in global settings. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> GetSwaggerGlobalValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetSwaggerGlobalValid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/apiVersion/swagger/string/none/query/global/2015-07-01-preview").ToString(); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.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; } } }
namespace Gu.Wpf.UiAutomation { using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Security; using System.Security.Permissions; using Gu.Wpf.UiAutomation.WindowsAPI; /// <summary> /// Keyboard class to simulate key input. /// </summary> public static class Keyboard { /// <summary> /// Types the given text, one char after another. /// </summary> public static void Type(string text) { if (text is null) { throw new ArgumentNullException(nameof(text)); } foreach (var c in text) { Type(c); } Wait.UntilInputIsProcessed(); } /// <summary> /// Types the given character. /// </summary> public static void Type(char character) { var code = User32.VkKeyScan(character); // Check if the char is unicode or no virtual key could be found if (character > 0xFE || code == -1) { // It seems to be unicode SendInput(character, KeyEventFlags.KEYEVENTF_KEYDOWN | KeyEventFlags.KEYEVENTF_UNICODE); SendInput(character, KeyEventFlags.KEYEVENTF_KEYUP | KeyEventFlags.KEYEVENTF_UNICODE); } else { // Get the high-order and low-order byte from the code var high = (byte)(code >> 8); var low = (byte)(code & 0xff); // Check if there are any modifiers var modifiers = new List<Key>(); if (HasScanModifier(high, VkKeyScanModifiers.SHIFT)) { modifiers.Add(Key.SHIFT); } if (HasScanModifier(high, VkKeyScanModifiers.CONTROL)) { modifiers.Add(Key.CONTROL); } if (HasScanModifier(high, VkKeyScanModifiers.ALT)) { modifiers.Add(Key.ALT); } // Press the modifiers foreach (var mod in modifiers) { SendInput((ushort)mod, KeyEventFlags.KEYEVENTF_KEYDOWN); } // Type the effective key SendInput(low, KeyEventFlags.KEYEVENTF_KEYDOWN); SendInput(low, KeyEventFlags.KEYEVENTF_KEYUP); // Release the modifiers foreach (var mod in Enumerable.Reverse(modifiers)) { SendInput((ushort)mod, KeyEventFlags.KEYEVENTF_KEYUP); } } } /// <summary> /// Types the given keys, one by one. /// </summary> public static void Type(params Key[] keys) { if (keys is null) { return; } foreach (var key in keys) { SendInput((ushort)key, KeyEventFlags.KEYEVENTF_KEYDOWN); SendInput((ushort)key, KeyEventFlags.KEYEVENTF_KEYUP); } Wait.UntilInputIsProcessed(); } /// <summary> /// Types the given keys simultaneously (starting with the first). /// </summary> public static void TypeSimultaneously(params Key[] keys) { if (keys is null) { return; } foreach (var key in keys) { SendInput((ushort)key, KeyEventFlags.KEYEVENTF_KEYDOWN); } foreach (var key in keys.Reverse()) { SendInput((ushort)key, KeyEventFlags.KEYEVENTF_KEYUP); } Wait.UntilInputIsProcessed(); } /// <summary> /// Types the given scan-code. /// </summary> public static void TypeScanCode(ushort scanCode, bool isExtendedKey) { if (isExtendedKey) { SendInput(scanCode, KeyEventFlags.KEYEVENTF_KEYDOWN | KeyEventFlags.KEYEVENTF_SCANCODE | KeyEventFlags.KEYEVENTF_EXTENDEDKEY); SendInput(scanCode, KeyEventFlags.KEYEVENTF_KEYUP | KeyEventFlags.KEYEVENTF_SCANCODE | KeyEventFlags.KEYEVENTF_EXTENDEDKEY); } else { SendInput(scanCode, KeyEventFlags.KEYEVENTF_KEYDOWN | KeyEventFlags.KEYEVENTF_SCANCODE); SendInput(scanCode, KeyEventFlags.KEYEVENTF_KEYUP | KeyEventFlags.KEYEVENTF_SCANCODE); } } /// <summary> /// Types the given virtual key-code. /// </summary> public static void TypeVirtualKeyCode(ushort virtualKeyCode) { SendInput(virtualKeyCode, KeyEventFlags.KEYEVENTF_KEYDOWN); SendInput(virtualKeyCode, KeyEventFlags.KEYEVENTF_KEYUP); } /// <summary> /// Presses the given key and releases it when the returned object is disposed. /// </summary> public static IDisposable Hold(Key key) { return new PressedKey(key); } /// <summary> /// Presses the given key. /// </summary> [Obsolete("Prefer Hold")] public static void Press(Key key) { PressVirtualKeyCode((ushort)key); } /// <summary> /// Presses the given scan-code. /// </summary> [Obsolete("Prefer Hold")] public static void PressScanCode(ushort scanCode, bool isExtendedKey) { if (isExtendedKey) { SendInput(scanCode, KeyEventFlags.KEYEVENTF_KEYDOWN | KeyEventFlags.KEYEVENTF_SCANCODE | KeyEventFlags.KEYEVENTF_EXTENDEDKEY); } else { SendInput(scanCode, KeyEventFlags.KEYEVENTF_KEYDOWN | KeyEventFlags.KEYEVENTF_SCANCODE); } } /// <summary> /// Presses the given virtual key-code. /// </summary> [Obsolete("Prefer Hold")] public static void PressVirtualKeyCode(ushort virtualKeyCode) { SendInput(virtualKeyCode, KeyEventFlags.KEYEVENTF_KEYDOWN); } /// <summary> /// Releases the given key. /// </summary> public static void Release(Key key) { ReleaseVirtualKeyCode((ushort)key); } /// <summary> /// Releases the given scan-code. /// </summary> public static void ReleaseScanCode(ushort scanCode, bool isExtendedKey) { if (isExtendedKey) { SendInput(scanCode, KeyEventFlags.KEYEVENTF_KEYUP | KeyEventFlags.KEYEVENTF_SCANCODE | KeyEventFlags.KEYEVENTF_EXTENDEDKEY); } else { SendInput(scanCode, KeyEventFlags.KEYEVENTF_KEYUP | KeyEventFlags.KEYEVENTF_SCANCODE); } } /// <summary> /// Releases the given virtual key-code. /// </summary> public static void ReleaseVirtualKeyCode(ushort virtualKeyCode) { SendInput(virtualKeyCode, KeyEventFlags.KEYEVENTF_KEYUP); } /// <summary> /// Presses the given key and releases it when the returned object is disposed. /// </summary> [Obsolete("Renamed to Hold")] public static IDisposable Pressing(Key key) { return new PressedKey(key); } public static void ClearFocus() { _ = User32.SetFocus(IntPtr.Zero); } /// <summary> /// Send raw input. /// </summary> /// <param name="keyboardInput">The <see cref="KEYBDINPUT"/>.</param> /// <throws><see cref="Win32Exception"/>.</throws> [PermissionSet(SecurityAction.Assert, Name = "FullTrust")] public static void SendInput(KEYBDINPUT keyboardInput) { // Demand the correct permissions var permissions = new PermissionSet(PermissionState.Unrestricted); permissions.Demand(); if (User32.SendInput(1, new[] { INPUT.KeyboardInput(keyboardInput) }, INPUT.Size) == 0) { throw new Win32Exception(); } } /// <summary> /// Checks if a given byte has a specific VkKeyScan-modifier set. /// </summary> private static bool HasScanModifier(byte b, VkKeyScanModifiers modifierToTest) { return (VkKeyScanModifiers)(b & (byte)modifierToTest) == modifierToTest; } /// <summary> /// Effectively sends the keyboard input command. /// </summary> /// <param name="keyCode">The key code to send. Can be the scan code or the virtual key code.</param> /// <param name="keyFlags">Flag if the key should be pressed or released.</param> private static void SendInput(ushort keyCode, KeyEventFlags keyFlags) { // Add the extended flag if the flag is set or the keycode is prefixed with the byte 0xE0 // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms646267(v=vs.85).aspx if ((keyCode & 0xFF00) == 0xE0) { keyFlags |= KeyEventFlags.KEYEVENTF_EXTENDEDKEY; } // Prepare the basic object var keyboardInput = new KEYBDINPUT { dwExtraInfo = User32.GetMessageExtraInfo(), dwFlags = keyFlags, }; if (keyFlags.HasFlag(KeyEventFlags.KEYEVENTF_SCANCODE) || keyFlags.HasFlag(KeyEventFlags.KEYEVENTF_UNICODE)) { keyboardInput.wScan = keyCode; } else { keyboardInput.wVk = keyCode; } SendInput(keyboardInput); Wait.For(TimeSpan.FromMilliseconds(10)); } /// <summary>Disposable class which presses the key on creation and releases it on dispose.</summary> private sealed class PressedKey : IDisposable { private readonly Key key; internal PressedKey(Key key) { this.key = key; SendInput((ushort)key, KeyEventFlags.KEYEVENTF_KEYDOWN); } public void Dispose() { SendInput((ushort)this.key, KeyEventFlags.KEYEVENTF_KEYUP); } } } }
// 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.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; namespace System { [Serializable] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public readonly struct Int64 : IComparable, IConvertible, IFormattable, IComparable<long>, IEquatable<long>, ISpanFormattable { private readonly long m_value; // Do not rename (binary serialization) public const long MaxValue = 0x7fffffffffffffffL; public const long MinValue = unchecked((long)0x8000000000000000L); // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type Int64, this method throws an ArgumentException. // public int CompareTo(object? value) { if (value == null) { return 1; } if (value is long) { // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. long i = (long)value; if (m_value < i) return -1; if (m_value > i) return 1; return 0; } throw new ArgumentException(SR.Arg_MustBeInt64); } public int CompareTo(long value) { // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. if (m_value < value) return -1; if (m_value > value) return 1; return 0; } public override bool Equals(object? obj) { if (!(obj is long)) { return false; } return m_value == ((long)obj).m_value; } [NonVersionable] public bool Equals(long obj) { return m_value == obj; } // The value of the lower 32 bits XORed with the uppper 32 bits. public override int GetHashCode() { return (unchecked((int)((long)m_value)) ^ (int)(m_value >> 32)); } public override string ToString() { return Number.FormatInt64(m_value, null, null); } public string ToString(IFormatProvider? provider) { return Number.FormatInt64(m_value, null, provider); } public string ToString(string? format) { return Number.FormatInt64(m_value, format, null); } public string ToString(string? format, IFormatProvider? provider) { return Number.FormatInt64(m_value, format, provider); } public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider? provider = null) { return Number.TryFormatInt64(m_value, format, provider, destination, out charsWritten); } public static long Parse(string s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseInt64(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } public static long Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseInt64(s, style, NumberFormatInfo.CurrentInfo); } public static long Parse(string s, IFormatProvider? provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseInt64(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } // Parses a long from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // public static long Parse(string s, NumberStyles style, IFormatProvider? provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseInt64(s, style, NumberFormatInfo.GetInstance(provider)); } public static long Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider? provider = null) { NumberFormatInfo.ValidateParseStyleInteger(style); return Number.ParseInt64(s, style, NumberFormatInfo.GetInstance(provider)); } public static bool TryParse(string? s, out long result) { if (s == null) { result = 0; return false; } return Number.TryParseInt64IntegerStyle(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result) == Number.ParsingStatus.OK; } public static bool TryParse(ReadOnlySpan<char> s, out long result) { return Number.TryParseInt64IntegerStyle(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result) == Number.ParsingStatus.OK; } public static bool TryParse(string? s, NumberStyles style, IFormatProvider? provider, out long result) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { result = 0; return false; } return Number.TryParseInt64(s, style, NumberFormatInfo.GetInstance(provider), out result) == Number.ParsingStatus.OK; } public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider? provider, out long result) { NumberFormatInfo.ValidateParseStyleInteger(style); return Number.TryParseInt64(s, style, NumberFormatInfo.GetInstance(provider), out result) == Number.ParsingStatus.OK; } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.Int64; } bool IConvertible.ToBoolean(IFormatProvider? provider) { return Convert.ToBoolean(m_value); } char IConvertible.ToChar(IFormatProvider? provider) { return Convert.ToChar(m_value); } sbyte IConvertible.ToSByte(IFormatProvider? provider) { return Convert.ToSByte(m_value); } byte IConvertible.ToByte(IFormatProvider? provider) { return Convert.ToByte(m_value); } short IConvertible.ToInt16(IFormatProvider? provider) { return Convert.ToInt16(m_value); } ushort IConvertible.ToUInt16(IFormatProvider? provider) { return Convert.ToUInt16(m_value); } int IConvertible.ToInt32(IFormatProvider? provider) { return Convert.ToInt32(m_value); } uint IConvertible.ToUInt32(IFormatProvider? provider) { return Convert.ToUInt32(m_value); } long IConvertible.ToInt64(IFormatProvider? provider) { return m_value; } ulong IConvertible.ToUInt64(IFormatProvider? provider) { return Convert.ToUInt64(m_value); } float IConvertible.ToSingle(IFormatProvider? provider) { return Convert.ToSingle(m_value); } double IConvertible.ToDouble(IFormatProvider? provider) { return Convert.ToDouble(m_value); } decimal IConvertible.ToDecimal(IFormatProvider? provider) { return Convert.ToDecimal(m_value); } DateTime IConvertible.ToDateTime(IFormatProvider? provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Int64", "DateTime")); } object IConvertible.ToType(Type type, IFormatProvider? provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
#region PDFsharp - A .NET library for processing PDF // // Authors: // Stefan Lange // // Copyright (c) 2005-2016 empira Software GmbH, Cologne Area (Germany) // // http://www.pdfsharp.com // http://sourceforge.net/projects/pdfsharp // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion #if GDI using System.Drawing; #endif #if WPF using System.Windows.Media; #endif namespace PdfSharp.Drawing { internal class XKnownColorTable { internal static uint[] ColorTable; public static uint KnownColorToArgb(XKnownColor color) { if (ColorTable == null) InitColorTable(); if (color <= XKnownColor.YellowGreen) return ColorTable[(int)color]; return 0; } public static bool IsKnownColor(uint argb) { for (int idx = 0; idx < ColorTable.Length; idx++) { if (ColorTable[idx] == argb) return true; } return false; } public static XKnownColor GetKnownColor(uint argb) { for (int idx = 0; idx < ColorTable.Length; idx++) { if (ColorTable[idx] == argb) return (XKnownColor)idx; } return (XKnownColor)(-1); } private static void InitColorTable() { // Same values as in GDI+ and System.Windows.Media.XColors // Note that Magenta is the same as Fuchsia and Zyan is the same as Aqua. uint[] colors = new uint[141]; colors[0] = 0xFFF0F8FF; // AliceBlue colors[1] = 0xFFFAEBD7; // AntiqueWhite colors[2] = 0xFF00FFFF; // Aqua colors[3] = 0xFF7FFFD4; // Aquamarine colors[4] = 0xFFF0FFFF; // Azure colors[5] = 0xFFF5F5DC; // Beige colors[6] = 0xFFFFE4C4; // Bisque colors[7] = 0xFF000000; // Black colors[8] = 0xFFFFEBCD; // BlanchedAlmond colors[9] = 0xFF0000FF; // Blue colors[10] = 0xFF8A2BE2; // BlueViolet colors[11] = 0xFFA52A2A; // Brown colors[12] = 0xFFDEB887; // BurlyWood colors[13] = 0xFF5F9EA0; // CadetBlue colors[14] = 0xFF7FFF00; // Chartreuse colors[15] = 0xFFD2691E; // Chocolate colors[16] = 0xFFFF7F50; // Coral colors[17] = 0xFF6495ED; // CornflowerBlue colors[18] = 0xFFFFF8DC; // Cornsilk colors[19] = 0xFFDC143C; // Crimson colors[20] = 0xFF00FFFF; // Cyan colors[21] = 0xFF00008B; // DarkBlue colors[22] = 0xFF008B8B; // DarkCyan colors[23] = 0xFFB8860B; // DarkGoldenrod colors[24] = 0xFFA9A9A9; // DarkGray colors[25] = 0xFF006400; // DarkGreen colors[26] = 0xFFBDB76B; // DarkKhaki colors[27] = 0xFF8B008B; // DarkMagenta colors[28] = 0xFF556B2F; // DarkOliveGreen colors[29] = 0xFFFF8C00; // DarkOrange colors[30] = 0xFF9932CC; // DarkOrchid colors[31] = 0xFF8B0000; // DarkRed colors[32] = 0xFFE9967A; // DarkSalmon colors[33] = 0xFF8FBC8B; // DarkSeaGreen colors[34] = 0xFF483D8B; // DarkSlateBlue colors[35] = 0xFF2F4F4F; // DarkSlateGray colors[36] = 0xFF00CED1; // DarkTurquoise colors[37] = 0xFF9400D3; // DarkViolet colors[38] = 0xFFFF1493; // DeepPink colors[39] = 0xFF00BFFF; // DeepSkyBlue colors[40] = 0xFF696969; // DimGray colors[41] = 0xFF1E90FF; // DodgerBlue colors[42] = 0xFFB22222; // Firebrick colors[43] = 0xFFFFFAF0; // FloralWhite colors[44] = 0xFF228B22; // ForestGreen colors[45] = 0xFFFF00FF; // Fuchsia colors[46] = 0xFFDCDCDC; // Gainsboro colors[47] = 0xFFF8F8FF; // GhostWhite colors[48] = 0xFFFFD700; // Gold colors[49] = 0xFFDAA520; // Goldenrod colors[50] = 0xFF808080; // Gray colors[51] = 0xFF008000; // Green colors[52] = 0xFFADFF2F; // GreenYellow colors[53] = 0xFFF0FFF0; // Honeydew colors[54] = 0xFFFF69B4; // HotPink colors[55] = 0xFFCD5C5C; // IndianRed colors[56] = 0xFF4B0082; // Indigo colors[57] = 0xFFFFFFF0; // Ivory colors[58] = 0xFFF0E68C; // Khaki colors[59] = 0xFFE6E6FA; // Lavender colors[60] = 0xFFFFF0F5; // LavenderBlush colors[61] = 0xFF7CFC00; // LawnGreen colors[62] = 0xFFFFFACD; // LemonChiffon colors[63] = 0xFFADD8E6; // LightBlue colors[64] = 0xFFF08080; // LightCoral colors[65] = 0xFFE0FFFF; // LightCyan colors[66] = 0xFFFAFAD2; // LightGoldenrodYellow colors[67] = 0xFFD3D3D3; // LightGray colors[68] = 0xFF90EE90; // LightGreen colors[69] = 0xFFFFB6C1; // LightPink colors[70] = 0xFFFFA07A; // LightSalmon colors[71] = 0xFF20B2AA; // LightSeaGreen colors[72] = 0xFF87CEFA; // LightSkyBlue colors[73] = 0xFF778899; // LightSlateGray colors[74] = 0xFFB0C4DE; // LightSteelBlue colors[75] = 0xFFFFFFE0; // LightYellow colors[76] = 0xFF00FF00; // Lime colors[77] = 0xFF32CD32; // LimeGreen colors[78] = 0xFFFAF0E6; // Linen colors[79] = 0xFFFF00FF; // Magenta colors[80] = 0xFF800000; // Maroon colors[81] = 0xFF66CDAA; // MediumAquamarine colors[82] = 0xFF0000CD; // MediumBlue colors[83] = 0xFFBA55D3; // MediumOrchid colors[84] = 0xFF9370DB; // MediumPurple colors[85] = 0xFF3CB371; // MediumSeaGreen colors[86] = 0xFF7B68EE; // MediumSlateBlue colors[87] = 0xFF00FA9A; // MediumSpringGreen colors[88] = 0xFF48D1CC; // MediumTurquoise colors[89] = 0xFFC71585; // MediumVioletRed colors[90] = 0xFF191970; // MidnightBlue colors[91] = 0xFFF5FFFA; // MintCream colors[92] = 0xFFFFE4E1; // MistyRose colors[93] = 0xFFFFE4B5; // Moccasin colors[94] = 0xFFFFDEAD; // NavajoWhite colors[95] = 0xFF000080; // Navy colors[96] = 0xFFFDF5E6; // OldLace colors[97] = 0xFF808000; // Olive colors[98] = 0xFF6B8E23; // OliveDrab colors[99] = 0xFFFFA500; // Orange colors[100] = 0xFFFF4500; // OrangeRed colors[101] = 0xFFDA70D6; // Orchid colors[102] = 0xFFEEE8AA; // PaleGoldenrod colors[103] = 0xFF98FB98; // PaleGreen colors[104] = 0xFFAFEEEE; // PaleTurquoise colors[105] = 0xFFDB7093; // PaleVioletRed colors[106] = 0xFFFFEFD5; // PapayaWhip colors[107] = 0xFFFFDAB9; // PeachPuff colors[108] = 0xFFCD853F; // Peru colors[109] = 0xFFFFC0CB; // Pink colors[110] = 0xFFDDA0DD; // Plum colors[111] = 0xFFB0E0E6; // PowderBlue colors[112] = 0xFF800080; // Purple colors[113] = 0xFFFF0000; // Red colors[114] = 0xFFBC8F8F; // RosyBrown colors[115] = 0xFF4169E1; // RoyalBlue colors[116] = 0xFF8B4513; // SaddleBrown colors[117] = 0xFFFA8072; // Salmon colors[118] = 0xFFF4A460; // SandyBrown colors[119] = 0xFF2E8B57; // SeaGreen colors[120] = 0xFFFFF5EE; // SeaShell colors[121] = 0xFFA0522D; // Sienna colors[122] = 0xFFC0C0C0; // Silver colors[123] = 0xFF87CEEB; // SkyBlue colors[124] = 0xFF6A5ACD; // SlateBlue colors[125] = 0xFF708090; // SlateGray colors[126] = 0xFFFFFAFA; // Snow colors[127] = 0xFF00FF7F; // SpringGreen colors[128] = 0xFF4682B4; // SteelBlue colors[129] = 0xFFD2B48C; // Tan colors[130] = 0xFF008080; // Teal colors[131] = 0xFFD8BFD8; // Thistle colors[132] = 0xFFFF6347; // Tomato colors[133] = 0x00FFFFFF; // Transparent colors[134] = 0xFF40E0D0; // Turquoise colors[135] = 0xFFEE82EE; // Violet colors[136] = 0xFFF5DEB3; // Wheat colors[137] = 0xFFFFFFFF; // White colors[138] = 0xFFF5F5F5; // WhiteSmoke colors[139] = 0xFFFFFF00; // Yellow colors[140] = 0xFF9ACD32; // YellowGreen ColorTable = colors; } } }
// 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 Microsoft.Xml; using System.Collections; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Text; using System.Globalization; using System.Runtime.Serialization; using System.Collections.Generic; using System.Collections.ObjectModel; namespace Microsoft.Xml { internal class XmlBufferReader { private XmlDictionaryReader _reader; private Stream _stream; private byte[] _streamBuffer; private byte[] _buffer; private int _offsetMin; private int _offsetMax; private IXmlDictionary _dictionary; private XmlBinaryReaderSession _session; private byte[] _guid; private int _offset; private const int maxBytesPerChar = 3; private char[] _chars; private int _windowOffset; private int _windowOffsetMax; private ValueHandle _listValue; private static XmlBufferReader s_empty = new XmlBufferReader(Array.Empty<byte>()); public XmlBufferReader(XmlDictionaryReader reader) { _reader = reader; } public XmlBufferReader(byte[] buffer) { _reader = null; _buffer = buffer; } static public XmlBufferReader Empty { get { return s_empty; } } public byte[] Buffer { get { return _buffer; } } public bool IsStreamed { get { return _stream != null; } } public void SetBuffer(Stream stream, IXmlDictionary dictionary, XmlBinaryReaderSession session) { if (_streamBuffer == null) { _streamBuffer = new byte[128]; } SetBuffer(stream, _streamBuffer, 0, 0, dictionary, session); _windowOffset = 0; _windowOffsetMax = _streamBuffer.Length; } public void SetBuffer(byte[] buffer, int offset, int count, IXmlDictionary dictionary, XmlBinaryReaderSession session) { SetBuffer(null, buffer, offset, count, dictionary, session); } private void SetBuffer(Stream stream, byte[] buffer, int offset, int count, IXmlDictionary dictionary, XmlBinaryReaderSession session) { _stream = stream; _buffer = buffer; _offsetMin = offset; _offset = offset; _offsetMax = offset + count; _dictionary = dictionary; _session = session; } public void Close() { if (_streamBuffer != null && _streamBuffer.Length > 4096) { _streamBuffer = null; } if (_stream != null) { _stream.Dispose(); _stream = null; } _buffer = Array.Empty<byte>(); _offset = 0; _offsetMax = 0; _windowOffset = 0; _windowOffsetMax = 0; _dictionary = null; _session = null; } public bool EndOfFile { get { return _offset == _offsetMax && !TryEnsureByte(); } } public byte GetByte() { int offset = _offset; if (offset < _offsetMax) return _buffer[offset]; else return GetByteHard(); } public void SkipByte() { Advance(1); } private byte GetByteHard() { EnsureByte(); return _buffer[_offset]; } public byte[] GetBuffer(int count, out int offset) { offset = _offset; if (offset <= _offsetMax - count) return _buffer; return GetBufferHard(count, out offset); } public byte[] GetBuffer(int count, out int offset, out int offsetMax) { offset = _offset; if (offset <= _offsetMax - count) { offsetMax = _offset + count; } else { TryEnsureBytes(Math.Min(count, _windowOffsetMax - offset)); offsetMax = _offsetMax; } return _buffer; } public byte[] GetBuffer(out int offset, out int offsetMax) { offset = _offset; offsetMax = _offsetMax; return _buffer; } private byte[] GetBufferHard(int count, out int offset) { offset = _offset; EnsureBytes(count); return _buffer; } private void EnsureByte() { if (!TryEnsureByte()) XmlExceptionHelper.ThrowUnexpectedEndOfFile(_reader); } private bool TryEnsureByte() { if (_stream == null) return false; DiagnosticUtility.DebugAssert(_offsetMax < _windowOffsetMax, ""); if (_offsetMax >= _buffer.Length) return TryEnsureBytes(1); int b = _stream.ReadByte(); if (b == -1) return false; _buffer[_offsetMax++] = (byte)b; return true; } private void EnsureBytes(int count) { if (!TryEnsureBytes(count)) XmlExceptionHelper.ThrowUnexpectedEndOfFile(_reader); } private bool TryEnsureBytes(int count) { if (_stream == null) return false; DiagnosticUtility.DebugAssert(_offset <= int.MaxValue - count, ""); int newOffsetMax = _offset + count; if (newOffsetMax < _offsetMax) return true; DiagnosticUtility.DebugAssert(newOffsetMax <= _windowOffsetMax, ""); if (newOffsetMax > _buffer.Length) { byte[] newBuffer = new byte[Math.Max(newOffsetMax, _buffer.Length * 2)]; System.Buffer.BlockCopy(_buffer, 0, newBuffer, 0, _offsetMax); _buffer = newBuffer; _streamBuffer = newBuffer; } int needed = newOffsetMax - _offsetMax; while (needed > 0) { int actual = _stream.Read(_buffer, _offsetMax, needed); if (actual == 0) return false; _offsetMax += actual; needed -= actual; } return true; } public void Advance(int count) { DiagnosticUtility.DebugAssert(_offset + count <= _offsetMax, ""); _offset += count; } public void InsertBytes(byte[] buffer, int offset, int count) { DiagnosticUtility.DebugAssert(_stream != null, ""); if (_offsetMax > buffer.Length - count) { byte[] newBuffer = new byte[_offsetMax + count]; System.Buffer.BlockCopy(_buffer, 0, newBuffer, 0, _offsetMax); _buffer = newBuffer; _streamBuffer = newBuffer; } System.Buffer.BlockCopy(_buffer, _offset, _buffer, _offset + count, _offsetMax - _offset); _offsetMax += count; System.Buffer.BlockCopy(buffer, offset, _buffer, _offset, count); } public void SetWindow(int windowOffset, int windowLength) { // [0...elementOffset-1][elementOffset..offset][offset..offsetMax-1][offsetMax..buffer.Length] // ^--Elements, Attributes in scope // ^-- The node just consumed // ^--Data buffered, not consumed // ^--Unused space if (windowOffset > int.MaxValue - windowLength) windowLength = int.MaxValue - windowOffset; if (_offset != windowOffset) { System.Buffer.BlockCopy(_buffer, _offset, _buffer, windowOffset, _offsetMax - _offset); _offsetMax = windowOffset + (_offsetMax - _offset); _offset = windowOffset; } _windowOffset = windowOffset; _windowOffsetMax = Math.Max(windowOffset + windowLength, _offsetMax); } public int Offset { get { return _offset; } set { DiagnosticUtility.DebugAssert(value >= _offsetMin && value <= _offsetMax, ""); _offset = value; } } public int ReadBytes(int count) { DiagnosticUtility.DebugAssert(count >= 0, ""); int offset = _offset; if (offset > _offsetMax - count) EnsureBytes(count); _offset += count; return offset; } public int ReadMultiByteUInt31() { int i = GetByte(); Advance(1); if ((i & 0x80) == 0) return i; i &= 0x7F; int j = GetByte(); Advance(1); i |= ((j & 0x7F) << 7); if ((j & 0x80) == 0) return i; int k = GetByte(); Advance(1); i |= ((k & 0x7F) << 14); if ((k & 0x80) == 0) return i; int l = GetByte(); Advance(1); i |= ((l & 0x7F) << 21); if ((l & 0x80) == 0) return i; int m = GetByte(); Advance(1); i |= (m << 28); if ((m & 0xF8) != 0) XmlExceptionHelper.ThrowInvalidBinaryFormat(_reader); return i; } public int ReadUInt8() { byte b = GetByte(); Advance(1); return b; } public int ReadInt8() { return (sbyte)ReadUInt8(); } public int ReadUInt16() { int offset; byte[] buffer = GetBuffer(2, out offset); int i = buffer[offset + 0] + (buffer[offset + 1] << 8); Advance(2); return i; } public int ReadInt16() { return (Int16)ReadUInt16(); } public int ReadInt32() { int offset; byte[] buffer = GetBuffer(4, out offset); byte b1 = buffer[offset + 0]; byte b2 = buffer[offset + 1]; byte b3 = buffer[offset + 2]; byte b4 = buffer[offset + 3]; Advance(4); return (((((b4 << 8) + b3) << 8) + b2) << 8) + b1; } public int ReadUInt31() { int i = ReadInt32(); if (i < 0) XmlExceptionHelper.ThrowInvalidBinaryFormat(_reader); return i; } public long ReadInt64() { Int64 lo = (UInt32)ReadInt32(); Int64 hi = (UInt32)ReadInt32(); return (hi << 32) + lo; } /// <SecurityNote> /// Critical - contains unsafe code /// Safe - unsafe code is effectively encapsulated, all inputs are validated /// </SecurityNote> [SecuritySafeCritical] unsafe public float ReadSingle() { int offset; byte[] buffer = GetBuffer(ValueHandleLength.Single, out offset); float value; byte* pb = (byte*)&value; DiagnosticUtility.DebugAssert(sizeof(float) == 4, ""); pb[0] = buffer[offset + 0]; pb[1] = buffer[offset + 1]; pb[2] = buffer[offset + 2]; pb[3] = buffer[offset + 3]; Advance(ValueHandleLength.Single); return value; } /// <SecurityNote> /// Critical - contains unsafe code /// Safe - unsafe code is effectively encapsulated, all inputs are validated /// </SecurityNote> [SecuritySafeCritical] unsafe public double ReadDouble() { int offset; byte[] buffer = GetBuffer(ValueHandleLength.Double, out offset); double value; byte* pb = (byte*)&value; DiagnosticUtility.DebugAssert(sizeof(double) == 8, ""); pb[0] = buffer[offset + 0]; pb[1] = buffer[offset + 1]; pb[2] = buffer[offset + 2]; pb[3] = buffer[offset + 3]; pb[4] = buffer[offset + 4]; pb[5] = buffer[offset + 5]; pb[6] = buffer[offset + 6]; pb[7] = buffer[offset + 7]; Advance(ValueHandleLength.Double); return value; } /// <SecurityNote> /// Critical - contains unsafe code /// Safe - unsafe code is effectively encapsulated, all inputs are validated /// </SecurityNote> [SecuritySafeCritical] unsafe public decimal ReadDecimal() { int offset; byte[] buffer = GetBuffer(ValueHandleLength.Decimal, out offset); decimal value; byte* pb = (byte*)&value; for (int i = 0; i < sizeof(decimal); i++) pb[i] = buffer[offset + i]; Advance(ValueHandleLength.Decimal); return value; } public UniqueId ReadUniqueId() { int offset; byte[] buffer = GetBuffer(ValueHandleLength.UniqueId, out offset); UniqueId uniqueId = new UniqueId(buffer, offset); Advance(ValueHandleLength.UniqueId); return uniqueId; } public DateTime ReadDateTime() { long value = 0; try { value = ReadInt64(); return DateTime.FromBinary(value); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value.ToString(CultureInfo.InvariantCulture), "DateTime", exception)); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value.ToString(CultureInfo.InvariantCulture), "DateTime", exception)); } catch (OverflowException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value.ToString(CultureInfo.InvariantCulture), "DateTime", exception)); } } public TimeSpan ReadTimeSpan() { long value = 0; try { value = ReadInt64(); return TimeSpan.FromTicks(value); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value.ToString(CultureInfo.InvariantCulture), "TimeSpan", exception)); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value.ToString(CultureInfo.InvariantCulture), "TimeSpan", exception)); } catch (OverflowException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value.ToString(CultureInfo.InvariantCulture), "TimeSpan", exception)); } } public Guid ReadGuid() { int offset; byte[] buffer = GetBuffer(ValueHandleLength.Guid, out offset); Guid guid = GetGuid(offset); Advance(ValueHandleLength.Guid); return guid; } public string ReadUTF8String(int length) { int offset; byte[] buffer = GetBuffer(length, out offset); char[] chars = GetCharBuffer(length); int charCount = GetChars(offset, length, chars); string value = new string(chars, 0, charCount); Advance(length); return value; } /// <SecurityNote> /// Critical - contains unsafe code /// caller needs to validate arguments /// </SecurityNote> [SecurityCritical] unsafe public void UnsafeReadArray(byte* dst, byte* dstMax) { UnsafeReadArray(dst, (int)(dstMax - dst)); } /// <SecurityNote> /// Critical - contains unsafe code /// caller needs to validate arguments /// </SecurityNote> [SecurityCritical] private unsafe void UnsafeReadArray(byte* dst, int length) { if (_stream != null) { const int chunk = 256; while (length >= chunk) { byte[] _buffer = GetBuffer(chunk, out _offset); for (int i = 0; i < chunk; i++) { *dst++ = _buffer[_offset + i]; } Advance(chunk); length -= chunk; } } if (length > 0) { byte[] buffer = GetBuffer(length, out _offset); fixed (byte* _src = &buffer[_offset]) { byte* src = _src; byte* dstMax = dst + length; while (dst < dstMax) { *dst = *src; dst++; src++; } } Advance(length); } } private char[] GetCharBuffer(int count) { if (count > 1024) return new char[count]; if (_chars == null || _chars.Length < count) _chars = new char[count]; return _chars; } private int GetChars(int offset, int length, char[] chars) { byte[] buffer = _buffer; for (int i = 0; i < length; i++) { byte b = buffer[offset + i]; if (b >= 0x80) return i + XmlConverter.ToChars(buffer, offset + i, length - i, chars, i); chars[i] = (char)b; } return length; } private int GetChars(int offset, int length, char[] chars, int charOffset) { byte[] buffer = _buffer; for (int i = 0; i < length; i++) { byte b = buffer[offset + i]; if (b >= 0x80) return i + XmlConverter.ToChars(buffer, offset + i, length - i, chars, charOffset + i); chars[charOffset + i] = (char)b; } return length; } public string GetString(int offset, int length) { char[] chars = GetCharBuffer(length); int charCount = GetChars(offset, length, chars); return new string(chars, 0, charCount); } public string GetUnicodeString(int offset, int length) { return XmlConverter.ToStringUnicode(_buffer, offset, length); } public string GetString(int offset, int length, XmlNameTable nameTable) { char[] chars = GetCharBuffer(length); int charCount = GetChars(offset, length, chars); return nameTable.Add(chars, 0, charCount); } public int GetEscapedChars(int offset, int length, char[] chars) { byte[] buffer = _buffer; int charCount = 0; int textOffset = offset; int offsetMax = offset + length; while (true) { while (offset < offsetMax && IsAttrChar(buffer[offset])) offset++; charCount += GetChars(textOffset, offset - textOffset, chars, charCount); if (offset == offsetMax) break; textOffset = offset; if (buffer[offset] == '&') { while (offset < offsetMax && buffer[offset] != ';') offset++; offset++; int ch = GetCharEntity(textOffset, offset - textOffset); textOffset = offset; if (ch > char.MaxValue) { SurrogateChar surrogate = new SurrogateChar(ch); chars[charCount++] = surrogate.HighChar; chars[charCount++] = surrogate.LowChar; } else { chars[charCount++] = (char)ch; } } else if (buffer[offset] == '\n' || buffer[offset] == '\t') { chars[charCount++] = ' '; offset++; textOffset = offset; } else // '\r' { chars[charCount++] = ' '; offset++; if (offset < offsetMax && buffer[offset] == '\n') offset++; textOffset = offset; } } return charCount; } private bool IsAttrChar(int ch) { switch (ch) { case '&': case '\r': case '\t': case '\n': return false; default: return true; } } public string GetEscapedString(int offset, int length) { char[] chars = GetCharBuffer(length); int charCount = GetEscapedChars(offset, length, chars); return new string(chars, 0, charCount); } public string GetEscapedString(int offset, int length, XmlNameTable nameTable) { char[] chars = GetCharBuffer(length); int charCount = GetEscapedChars(offset, length, chars); return nameTable.Add(chars, 0, charCount); } private int GetLessThanCharEntity(int offset, int length) { byte[] buffer = _buffer; if (length != 4 || buffer[offset + 1] != (byte)'l' || buffer[offset + 2] != (byte)'t') { XmlExceptionHelper.ThrowInvalidCharRef(_reader); } return (int)'<'; } private int GetGreaterThanCharEntity(int offset, int length) { byte[] buffer = _buffer; if (length != 4 || buffer[offset + 1] != (byte)'g' || buffer[offset + 2] != (byte)'t') { XmlExceptionHelper.ThrowInvalidCharRef(_reader); } return (int)'>'; } private int GetQuoteCharEntity(int offset, int length) { byte[] buffer = _buffer; if (length != 6 || buffer[offset + 1] != (byte)'q' || buffer[offset + 2] != (byte)'u' || buffer[offset + 3] != (byte)'o' || buffer[offset + 4] != (byte)'t') { XmlExceptionHelper.ThrowInvalidCharRef(_reader); } return (int)'"'; } private int GetAmpersandCharEntity(int offset, int length) { byte[] buffer = _buffer; if (length != 5 || buffer[offset + 1] != (byte)'a' || buffer[offset + 2] != (byte)'m' || buffer[offset + 3] != (byte)'p') { XmlExceptionHelper.ThrowInvalidCharRef(_reader); } return (int)'&'; } private int GetApostropheCharEntity(int offset, int length) { byte[] buffer = _buffer; if (length != 6 || buffer[offset + 1] != (byte)'a' || buffer[offset + 2] != (byte)'p' || buffer[offset + 3] != (byte)'o' || buffer[offset + 4] != (byte)'s') { XmlExceptionHelper.ThrowInvalidCharRef(_reader); } return (int)'\''; } private int GetDecimalCharEntity(int offset, int length) { byte[] buffer = _buffer; DiagnosticUtility.DebugAssert(buffer[offset + 0] == '&', ""); DiagnosticUtility.DebugAssert(buffer[offset + 1] == '#', ""); DiagnosticUtility.DebugAssert(buffer[offset + length - 1] == ';', ""); int value = 0; for (int i = 2; i < length - 1; i++) { byte ch = buffer[offset + i]; if (ch < (byte)'0' || ch > (byte)'9') XmlExceptionHelper.ThrowInvalidCharRef(_reader); value = value * 10 + (ch - '0'); if (value > SurrogateChar.MaxValue) XmlExceptionHelper.ThrowInvalidCharRef(_reader); } return value; } private int GetHexCharEntity(int offset, int length) { byte[] buffer = _buffer; DiagnosticUtility.DebugAssert(buffer[offset + 0] == '&', ""); DiagnosticUtility.DebugAssert(buffer[offset + 1] == '#', ""); DiagnosticUtility.DebugAssert(buffer[offset + 2] == 'x', ""); DiagnosticUtility.DebugAssert(buffer[offset + length - 1] == ';', ""); int value = 0; for (int i = 3; i < length - 1; i++) { byte ch = buffer[offset + i]; int digit = 0; if (ch >= '0' && ch <= '9') digit = (ch - '0'); else if (ch >= 'a' && ch <= 'f') digit = 10 + (ch - 'a'); else if (ch >= 'A' && ch <= 'F') digit = 10 + (ch - 'A'); else XmlExceptionHelper.ThrowInvalidCharRef(_reader); DiagnosticUtility.DebugAssert(digit >= 0 && digit < 16, ""); value = value * 16 + digit; if (value > SurrogateChar.MaxValue) XmlExceptionHelper.ThrowInvalidCharRef(_reader); } return value; } public int GetCharEntity(int offset, int length) { if (length < 3) XmlExceptionHelper.ThrowInvalidCharRef(_reader); byte[] buffer = _buffer; DiagnosticUtility.DebugAssert(buffer[offset] == '&', ""); DiagnosticUtility.DebugAssert(buffer[offset + length - 1] == ';', ""); switch (buffer[offset + 1]) { case (byte)'l': return GetLessThanCharEntity(offset, length); case (byte)'g': return GetGreaterThanCharEntity(offset, length); case (byte)'a': if (buffer[offset + 2] == (byte)'m') return GetAmpersandCharEntity(offset, length); else return GetApostropheCharEntity(offset, length); case (byte)'q': return GetQuoteCharEntity(offset, length); case (byte)'#': if (buffer[offset + 2] == (byte)'x') return GetHexCharEntity(offset, length); else return GetDecimalCharEntity(offset, length); default: XmlExceptionHelper.ThrowInvalidCharRef(_reader); return 0; } } public bool IsWhitespaceKey(int key) { string s = GetDictionaryString(key).Value; for (int i = 0; i < s.Length; i++) { if (!XmlConverter.IsWhitespace(s[i])) return false; } return true; } public bool IsWhitespaceUTF8(int offset, int length) { byte[] buffer = _buffer; for (int i = 0; i < length; i++) { if (!XmlConverter.IsWhitespace((char)buffer[offset + i])) return false; } return true; } public bool IsWhitespaceUnicode(int offset, int length) { byte[] buffer = _buffer; for (int i = 0; i < length; i += sizeof(char)) { char ch = (char)GetInt16(offset + i); if (!XmlConverter.IsWhitespace(ch)) return false; } return true; } public bool Equals2(int key1, int key2, XmlBufferReader bufferReader2) { // If the keys aren't from the same dictionary, they still might be the same if (key1 == key2) return true; else return GetDictionaryString(key1).Value == bufferReader2.GetDictionaryString(key2).Value; } public bool Equals2(int key1, XmlDictionaryString xmlString2) { if ((key1 & 1) == 0 && xmlString2.Dictionary == _dictionary) return xmlString2.Key == (key1 >> 1); else return GetDictionaryString(key1).Value == xmlString2.Value; } public bool Equals2(int offset1, int length1, byte[] buffer2) { int length2 = buffer2.Length; if (length1 != length2) return false; byte[] buffer1 = _buffer; for (int i = 0; i < length1; i++) { if (buffer1[offset1 + i] != buffer2[i]) return false; } return true; } public bool Equals2(int offset1, int length1, XmlBufferReader bufferReader2, int offset2, int length2) { if (length1 != length2) return false; byte[] buffer1 = _buffer; byte[] buffer2 = bufferReader2._buffer; for (int i = 0; i < length1; i++) { if (buffer1[offset1 + i] != buffer2[offset2 + i]) return false; } return true; } public bool Equals2(int offset1, int length1, int offset2, int length2) { if (length1 != length2) return false; if (offset1 == offset2) return true; byte[] buffer = _buffer; for (int i = 0; i < length1; i++) { if (buffer[offset1 + i] != buffer[offset2 + i]) return false; } return true; } /// <SecurityNote> /// Critical - contains unsafe code /// Safe - unsafe code is effectively encapsulated, all inputs are validated /// </SecurityNote> [SecuritySafeCritical] unsafe public bool Equals2(int offset1, int length1, string s2) { int byteLength = length1; int charLength = s2.Length; // N unicode chars will be represented in at least N bytes, but // no more than N * 3 bytes. If the byte count falls outside of this // range, then the strings cannot be equal. if (byteLength < charLength || byteLength > charLength * maxBytesPerChar) return false; byte[] buffer = _buffer; if (length1 < 8) { int length = Math.Min(byteLength, charLength); int offset = offset1; for (int i = 0; i < length; i++) { byte b = buffer[offset + i]; if (b >= 0x80) return XmlConverter.ToString(buffer, offset1, length1) == s2; if (s2[i] != (char)b) return false; } return byteLength == charLength; } else { int length = Math.Min(byteLength, charLength); fixed (byte* _pb = &buffer[offset1]) { byte* pb = _pb; byte* pbMax = pb + length; fixed (char* _pch = s2) { char* pch = _pch; // Try to do the fast comparison in ascii space int t = 0; while (pb < pbMax && *pb < 0x80) { t = *pb - (byte)*pch; // The code generated is better if we break out then return if (t != 0) break; pb++; pch++; } if (t != 0) return false; if (pb == pbMax) return (byteLength == charLength); } } return XmlConverter.ToString(buffer, offset1, length1) == s2; } } public int Compare(int offset1, int length1, int offset2, int length2) { byte[] buffer = _buffer; int length = Math.Min(length1, length2); for (int i = 0; i < length; i++) { int s = buffer[offset1 + i] - buffer[offset2 + i]; if (s != 0) return s; } return length1 - length2; } public byte GetByte(int offset) { return _buffer[offset]; } public int GetInt8(int offset) { return (sbyte)GetByte(offset); } public int GetInt16(int offset) { byte[] buffer = _buffer; return (Int16)(buffer[offset] + (buffer[offset + 1] << 8)); } public int GetInt32(int offset) { byte[] buffer = _buffer; byte b1 = buffer[offset + 0]; byte b2 = buffer[offset + 1]; byte b3 = buffer[offset + 2]; byte b4 = buffer[offset + 3]; return (((((b4 << 8) + b3) << 8) + b2) << 8) + b1; } public long GetInt64(int offset) { byte[] buffer = _buffer; byte b1, b2, b3, b4; b1 = buffer[offset + 0]; b2 = buffer[offset + 1]; b3 = buffer[offset + 2]; b4 = buffer[offset + 3]; Int64 lo = (UInt32)(((((b4 << 8) + b3) << 8) + b2) << 8) + b1; b1 = buffer[offset + 4]; b2 = buffer[offset + 5]; b3 = buffer[offset + 6]; b4 = buffer[offset + 7]; Int64 hi = (UInt32)(((((b4 << 8) + b3) << 8) + b2) << 8) + b1; return (hi << 32) + lo; } public ulong GetUInt64(int offset) { return (ulong)GetInt64(offset); } /// <SecurityNote> /// Critical - contains unsafe code /// Safe - unsafe code is effectively encapsulated, all inputs are validated /// </SecurityNote> [SecuritySafeCritical] unsafe public float GetSingle(int offset) { byte[] buffer = _buffer; float value; byte* pb = (byte*)&value; DiagnosticUtility.DebugAssert(sizeof(float) == 4, ""); pb[0] = buffer[offset + 0]; pb[1] = buffer[offset + 1]; pb[2] = buffer[offset + 2]; pb[3] = buffer[offset + 3]; return value; } /// <SecurityNote> /// Critical - contains unsafe code /// Safe - unsafe code is effectively encapsulated, all inputs are validated /// </SecurityNote> [SecuritySafeCritical] unsafe public double GetDouble(int offset) { byte[] buffer = _buffer; double value; byte* pb = (byte*)&value; DiagnosticUtility.DebugAssert(sizeof(double) == 8, ""); pb[0] = buffer[offset + 0]; pb[1] = buffer[offset + 1]; pb[2] = buffer[offset + 2]; pb[3] = buffer[offset + 3]; pb[4] = buffer[offset + 4]; pb[5] = buffer[offset + 5]; pb[6] = buffer[offset + 6]; pb[7] = buffer[offset + 7]; return value; } /// <SecurityNote> /// Critical - contains unsafe code /// Safe - unsafe code is effectively encapsulated, all inputs are validated /// </SecurityNote> [SecuritySafeCritical] public unsafe decimal GetDecimal(int offset) { byte[] buffer = _buffer; decimal value; byte* pb = (byte*)&value; for (int i = 0; i < sizeof(decimal); i++) pb[i] = buffer[offset + i]; return value; } public UniqueId GetUniqueId(int offset) { return new UniqueId(_buffer, offset); } public Guid GetGuid(int offset) { if (_guid == null) _guid = new byte[16]; System.Buffer.BlockCopy(_buffer, offset, _guid, 0, _guid.Length); return new Guid(_guid); } public void GetBase64(int srcOffset, byte[] buffer, int dstOffset, int count) { System.Buffer.BlockCopy(_buffer, srcOffset, buffer, dstOffset, count); } public XmlBinaryNodeType GetNodeType() { return (XmlBinaryNodeType)GetByte(); } public void SkipNodeType() { SkipByte(); } public object[] GetList(int offset, int count) { int bufferOffset = this.Offset; this.Offset = offset; try { object[] objects = new object[count]; for (int i = 0; i < count; i++) { XmlBinaryNodeType nodeType = GetNodeType(); SkipNodeType(); DiagnosticUtility.DebugAssert(nodeType != XmlBinaryNodeType.StartListText, ""); ReadValue(nodeType, _listValue); objects[i] = _listValue.ToObject(); } return objects; } finally { this.Offset = bufferOffset; } } public XmlDictionaryString GetDictionaryString(int key) { IXmlDictionary keyDictionary; if ((key & 1) != 0) { keyDictionary = _session; } else { keyDictionary = _dictionary; } XmlDictionaryString s; if (!keyDictionary.TryLookup(key >> 1, out s)) XmlExceptionHelper.ThrowInvalidBinaryFormat(_reader); return s; } public int ReadDictionaryKey() { int key = ReadMultiByteUInt31(); if ((key & 1) != 0) { if (_session == null) XmlExceptionHelper.ThrowInvalidBinaryFormat(_reader); int sessionKey = (key >> 1); XmlDictionaryString xmlString; if (!_session.TryLookup(sessionKey, out xmlString)) { if (sessionKey < XmlDictionaryString.MinKey || sessionKey > XmlDictionaryString.MaxKey) XmlExceptionHelper.ThrowXmlDictionaryStringIDOutOfRange(_reader); XmlExceptionHelper.ThrowXmlDictionaryStringIDUndefinedSession(_reader, sessionKey); } } else { if (_dictionary == null) XmlExceptionHelper.ThrowInvalidBinaryFormat(_reader); int staticKey = (key >> 1); XmlDictionaryString xmlString; if (!_dictionary.TryLookup(staticKey, out xmlString)) { if (staticKey < XmlDictionaryString.MinKey || staticKey > XmlDictionaryString.MaxKey) XmlExceptionHelper.ThrowXmlDictionaryStringIDOutOfRange(_reader); XmlExceptionHelper.ThrowXmlDictionaryStringIDUndefinedStatic(_reader, staticKey); } } return key; } public void ReadValue(XmlBinaryNodeType nodeType, ValueHandle value) { switch (nodeType) { case XmlBinaryNodeType.EmptyText: value.SetValue(ValueHandleType.Empty); break; case XmlBinaryNodeType.ZeroText: value.SetValue(ValueHandleType.Zero); break; case XmlBinaryNodeType.OneText: value.SetValue(ValueHandleType.One); break; case XmlBinaryNodeType.TrueText: value.SetValue(ValueHandleType.True); break; case XmlBinaryNodeType.FalseText: value.SetValue(ValueHandleType.False); break; case XmlBinaryNodeType.BoolText: value.SetValue(ReadUInt8() != 0 ? ValueHandleType.True : ValueHandleType.False); break; case XmlBinaryNodeType.Chars8Text: ReadValue(value, ValueHandleType.UTF8, ReadUInt8()); break; case XmlBinaryNodeType.Chars16Text: ReadValue(value, ValueHandleType.UTF8, ReadUInt16()); break; case XmlBinaryNodeType.Chars32Text: ReadValue(value, ValueHandleType.UTF8, ReadUInt31()); break; case XmlBinaryNodeType.UnicodeChars8Text: ReadUnicodeValue(value, ReadUInt8()); break; case XmlBinaryNodeType.UnicodeChars16Text: ReadUnicodeValue(value, ReadUInt16()); break; case XmlBinaryNodeType.UnicodeChars32Text: ReadUnicodeValue(value, ReadUInt31()); break; case XmlBinaryNodeType.Bytes8Text: ReadValue(value, ValueHandleType.Base64, ReadUInt8()); break; case XmlBinaryNodeType.Bytes16Text: ReadValue(value, ValueHandleType.Base64, ReadUInt16()); break; case XmlBinaryNodeType.Bytes32Text: ReadValue(value, ValueHandleType.Base64, ReadUInt31()); break; case XmlBinaryNodeType.DictionaryText: value.SetDictionaryValue(ReadDictionaryKey()); break; case XmlBinaryNodeType.UniqueIdText: ReadValue(value, ValueHandleType.UniqueId, ValueHandleLength.UniqueId); break; case XmlBinaryNodeType.GuidText: ReadValue(value, ValueHandleType.Guid, ValueHandleLength.Guid); break; case XmlBinaryNodeType.DecimalText: ReadValue(value, ValueHandleType.Decimal, ValueHandleLength.Decimal); break; case XmlBinaryNodeType.Int8Text: ReadValue(value, ValueHandleType.Int8, ValueHandleLength.Int8); break; case XmlBinaryNodeType.Int16Text: ReadValue(value, ValueHandleType.Int16, ValueHandleLength.Int16); break; case XmlBinaryNodeType.Int32Text: ReadValue(value, ValueHandleType.Int32, ValueHandleLength.Int32); break; case XmlBinaryNodeType.Int64Text: ReadValue(value, ValueHandleType.Int64, ValueHandleLength.Int64); break; case XmlBinaryNodeType.UInt64Text: ReadValue(value, ValueHandleType.UInt64, ValueHandleLength.UInt64); break; case XmlBinaryNodeType.FloatText: ReadValue(value, ValueHandleType.Single, ValueHandleLength.Single); break; case XmlBinaryNodeType.DoubleText: ReadValue(value, ValueHandleType.Double, ValueHandleLength.Double); break; case XmlBinaryNodeType.TimeSpanText: ReadValue(value, ValueHandleType.TimeSpan, ValueHandleLength.TimeSpan); break; case XmlBinaryNodeType.DateTimeText: ReadValue(value, ValueHandleType.DateTime, ValueHandleLength.DateTime); break; case XmlBinaryNodeType.StartListText: ReadList(value); break; case XmlBinaryNodeType.QNameDictionaryText: ReadQName(value); break; default: XmlExceptionHelper.ThrowInvalidBinaryFormat(_reader); break; } } private void ReadValue(ValueHandle value, ValueHandleType type, int length) { int offset = ReadBytes(length); value.SetValue(type, offset, length); } private void ReadUnicodeValue(ValueHandle value, int length) { if ((length & 1) != 0) XmlExceptionHelper.ThrowInvalidBinaryFormat(_reader); ReadValue(value, ValueHandleType.Unicode, length); } private void ReadList(ValueHandle value) { if (_listValue == null) { _listValue = new ValueHandle(this); } int count = 0; int offset = this.Offset; while (true) { XmlBinaryNodeType nodeType = GetNodeType(); SkipNodeType(); if (nodeType == XmlBinaryNodeType.StartListText) XmlExceptionHelper.ThrowInvalidBinaryFormat(_reader); if (nodeType == XmlBinaryNodeType.EndListText) break; ReadValue(nodeType, _listValue); count++; } value.SetValue(ValueHandleType.List, offset, count); } public void ReadQName(ValueHandle value) { int prefix = ReadUInt8(); if (prefix >= 26) XmlExceptionHelper.ThrowInvalidBinaryFormat(_reader); int key = ReadDictionaryKey(); value.SetQNameValue(prefix, key); } public int[] GetRows() { if (_buffer == null) { return new int[1] { 0 }; } List<int> list = new List<int>(); list.Add(_offsetMin); for (int i = _offsetMin; i < _offsetMax; i++) { if (_buffer[i] == (byte)13 || _buffer[i] == (byte)10) { if (i + 1 < _offsetMax && _buffer[i + 1] == (byte)10) i++; list.Add(i + 1); } } return list.ToArray(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Acr.UserDialogs; using MvvmCross; using MvvmCross.Forms.Platforms.Mac.Core; using MvvmCross.IoC; using Plugin.Permissions.Abstractions; using Plugin.Settings; using Xamarin.Forms; namespace BLE.Client.macOS { public class Setup : MvxFormsMacSetup<BleMvxApplication, BleMvxFormsApp> { protected override IMvxIoCProvider InitializeIoC() { var result = base.InitializeIoC(); // Mvx.IoCProvider.RegisterSingleton(() => CrossBluetoothLE.Current); // Mvx.IoCProvider.RegisterSingleton(() => CrossBluetoothLE.Current.Adapter); Mvx.IoCProvider.RegisterSingleton(() => CrossSettings.Current); Mvx.IoCProvider.RegisterSingleton<IPermissions>(() => new PermissionMac()); Mvx.IoCProvider.RegisterSingleton<IUserDialogs>(() => new UserDialogsMac()); return result; } public override IEnumerable<Assembly> GetPluginAssemblies() { return base.GetPluginAssemblies().Union(new[] { typeof(MvvmCross.Plugins.BLE.macOS.Plugin).Assembly }); } /* public override IEnumerable<Assembly> GetPluginAssemblies() { return new List<Assembly>(base.GetViewAssemblies().Union(new[] { typeof(MvvmCross.Plugins.BLE.iOS.Plugin).GetTypeInfo().Assembly })); } */ private class PermissionMac : IPermissions { public Task<PermissionStatus> CheckPermissionStatusAsync(Permission permission) { return Task.FromResult(PermissionStatus.Granted); } public Task<PermissionStatus> CheckPermissionStatusAsync<T>() where T : Plugin.Permissions.BasePermission, new() { return Task.FromResult(PermissionStatus.Granted); } public bool OpenAppSettings() { return true; } public Task<Dictionary<Permission, PermissionStatus>> RequestPermissionsAsync(params Permission[] permissions) { return Task.FromResult(permissions.ToDictionary(p => p, p => PermissionStatus.Granted)); } public Task<PermissionStatus> RequestPermissionAsync<T>() where T : Plugin.Permissions.BasePermission, new() { return Task.FromResult(PermissionStatus.Granted); } public Task<bool> ShouldShowRequestPermissionRationaleAsync(Permission permission) { return Task.FromResult(true); } } private class UserDialogsMac : IUserDialogs { public IDisposable ActionSheet(ActionSheetConfig config) { Device.BeginInvokeOnMainThread(async () => { var result = await Application.Current.MainPage?.DisplayActionSheet(config.Title, config.Cancel?.Text, config.Destructive?.Text, config.Options.Select(o => o.Text).ToArray()); if (result == config.Cancel?.Text) { return; } if (result == config.Destructive?.Text) { config.Destructive?.Action?.Invoke(); return; } var item = config.Options.FirstOrDefault(o => o.Text == result); if (item != null) { item.Action?.Invoke(); } }); return null; } public Task<string> ActionSheetAsync(string title, string cancel, string destructive, CancellationToken? cancelToken = null, params string[] buttons) { return Application.Current.MainPage?.DisplayActionSheet(title, cancel ?? "Cancel", destructive, buttons); } public IDisposable Alert(string message, string title = null, string okText = null) { _ = Application.Current.MainPage?.DisplayAlert(title, message, okText ?? "Ok", "Cancel"); return null; } public IDisposable Alert(AlertConfig config) { _ = Application.Current.MainPage?.DisplayAlert(config.Title, config.Message, config.OkText ?? "Ok", "Cancel"); return null; } public Task AlertAsync(string message, string title = null, string okText = null, CancellationToken? cancelToken = null) { return Application.Current.MainPage?.DisplayAlert(title, message, okText ?? "Ok", "Cancel"); } public Task AlertAsync(AlertConfig config, CancellationToken? cancelToken = null) { return Application.Current.MainPage?.DisplayAlert(config.Title, config.Message, config.OkText ?? "Ok", "Cancel"); } public IDisposable Confirm(ConfirmConfig config) { _ = Application.Current.MainPage?.DisplayAlert(config.Title, config.Message, config.OkText ?? "Ok", config.CancelText ?? "Cancel"); return null; } public Task<bool> ConfirmAsync(string message, string title = null, string okText = null, string cancelText = null, CancellationToken? cancelToken = null) { return Application.Current.MainPage?.DisplayAlert(title, message, okText ?? "Ok", cancelText ?? "Cancel"); } public Task<bool> ConfirmAsync(ConfirmConfig config, CancellationToken? cancelToken = null) { return Application.Current.MainPage?.DisplayAlert(config.Title, config.Message, config.OkText ?? "Ok", config.CancelText ?? "Cancel"); } public IDisposable DatePrompt(DatePromptConfig config) { return null; } public Task<DatePromptResult> DatePromptAsync(DatePromptConfig config, CancellationToken? cancelToken = null) { return Task.FromResult(new DatePromptResult(false, DateTime.Now)); } public Task<DatePromptResult> DatePromptAsync(string title = null, DateTime? selectedDate = null, CancellationToken? cancelToken = null) { return Task.FromResult(new DatePromptResult(false, DateTime.Now)); } public void HideLoading() { } public IProgressDialog Loading(string title = null, Action onCancel = null, string cancelText = null, bool show = true, MaskType? maskType = null) { return null; } public IDisposable Login(LoginConfig config) { return null; } public Task<LoginResult> LoginAsync(string title = null, string message = null, CancellationToken? cancelToken = null) { return null; } public Task<LoginResult> LoginAsync(LoginConfig config, CancellationToken? cancelToken = null) { return null; } public IProgressDialog Progress(ProgressDialogConfig config) { return new ProgressMock(); } public IProgressDialog Progress(string title = null, Action onCancel = null, string cancelText = null, bool show = true, MaskType? maskType = null) { return new ProgressMock(); } public IDisposable Prompt(PromptConfig config) { return null; } public Task<PromptResult> PromptAsync(string message, string title = null, string okText = null, string cancelText = null, string placeholder = "", InputType inputType = InputType.Default, CancellationToken? cancelToken = null) { return null; } public Task<PromptResult> PromptAsync(PromptConfig config, CancellationToken? cancelToken = null) { throw new NotImplementedException(); } public void ShowLoading(string title = null, MaskType? maskType = null) { } public IDisposable TimePrompt(TimePromptConfig config) { return null; } public Task<TimePromptResult> TimePromptAsync(TimePromptConfig config, CancellationToken? cancelToken = null) { return null; } public Task<TimePromptResult> TimePromptAsync(string title = null, TimeSpan? selectedTime = null, CancellationToken? cancelToken = null) { return null; } public IDisposable Toast(string title, TimeSpan? dismissTimer = null) { Application.Current.MainPage?.DisplayAlert(title, "alert", "Ok", "Cancel"); return null; } public IDisposable Toast(ToastConfig cfg) { Application.Current.MainPage?.DisplayAlert(cfg.Message, "alert", "Ok", "Cancel"); return null; } private class ProgressMock : IProgressDialog { public string Title { get; set; } public int PercentComplete { get; set; } public bool IsShowing => true; public void Dispose() { } public void Hide() { } public void Show() { } } } } }