context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics.CodeAnalysis; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Collections.Generic; namespace System.Net.Http { public class HttpRequestMessage : IDisposable { private const int MessageNotYetSent = 0; private const int MessageAlreadySent = 1; // Track whether the message has been sent. // The message shouldn't be sent again if this field is equal to MessageAlreadySent. private int _sendStatus = MessageNotYetSent; private HttpMethod _method; private Uri _requestUri; private HttpRequestHeaders _headers; private Version _version; private HttpContent _content; private bool _disposed; private IDictionary<String, Object> _properties; public Version Version { get { return _version; } set { if (value == null) { throw new ArgumentNullException("value"); } CheckDisposed(); _version = value; } } public HttpContent Content { get { return _content; } set { CheckDisposed(); if (Logging.On) { if (value == null) { Logging.PrintInfo(Logging.Http, this, SR.net_http_log_content_null); } else { Logging.Associate(Logging.Http, this, value); } } // It's OK to set a 'null' content, even if the method is POST/PUT. _content = value; } } public HttpMethod Method { get { return _method; } set { if (value == null) { throw new ArgumentNullException("value"); } CheckDisposed(); _method = value; } } public Uri RequestUri { get { return _requestUri; } set { if ((value != null) && (value.IsAbsoluteUri) && (!HttpUtilities.IsHttpUri(value))) { throw new ArgumentException(SR.net_http_client_http_baseaddress_required, "value"); } CheckDisposed(); // It's OK to set 'null'. HttpClient will add the 'BaseAddress'. If there is no 'BaseAddress' // sending this message will throw. _requestUri = value; } } public HttpRequestHeaders Headers { get { if (_headers == null) { _headers = new HttpRequestHeaders(); } return _headers; } } public IDictionary<String, Object> Properties { get { if (_properties == null) { _properties = new Dictionary<String, Object>(); } return _properties; } } public HttpRequestMessage() : this(HttpMethod.Get, (Uri)null) { } public HttpRequestMessage(HttpMethod method, Uri requestUri) { if (Logging.On) Logging.Enter(Logging.Http, this, ".ctor", "Method: " + method + ", Uri: '" + requestUri + "'"); InitializeValues(method, requestUri); if (Logging.On) Logging.Exit(Logging.Http, this, ".ctor", null); } [SuppressMessage("Microsoft.Design", "CA1057:StringUriOverloadsCallSystemUriOverloads", Justification = "It is OK to provide 'null' values. A Uri instance is created from 'requestUri' if it is != null.")] public HttpRequestMessage(HttpMethod method, string requestUri) { if (Logging.On) Logging.Enter(Logging.Http, this, ".ctor", "Method: " + method + ", Uri: '" + requestUri + "'"); // It's OK to have a 'null' request Uri. If HttpClient is used, the 'BaseAddress' will be added. // If there is no 'BaseAddress', sending this request message will throw. // Note that we also allow the string to be empty: null and empty are considered equivalent. if (string.IsNullOrEmpty(requestUri)) { InitializeValues(method, null); } else { InitializeValues(method, new Uri(requestUri, UriKind.RelativeOrAbsolute)); } if (Logging.On) Logging.Exit(Logging.Http, this, ".ctor", null); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("Method: "); sb.Append(_method); sb.Append(", RequestUri: '"); sb.Append(_requestUri == null ? "<null>" : _requestUri.ToString()); sb.Append("', Version: "); sb.Append(_version); sb.Append(", Content: "); sb.Append(_content == null ? "<null>" : _content.GetType().ToString()); sb.Append(", Headers:\r\n"); sb.Append(HeaderUtilities.DumpHeaders(_headers, _content == null ? null : _content.Headers)); return sb.ToString(); } private void InitializeValues(HttpMethod method, Uri requestUri) { if (method == null) { throw new ArgumentNullException("method"); } if ((requestUri != null) && (requestUri.IsAbsoluteUri) && (!HttpUtilities.IsHttpUri(requestUri))) { throw new ArgumentException(SR.net_http_client_http_baseaddress_required, "requestUri"); } _method = method; _requestUri = requestUri; _version = HttpUtilities.DefaultRequestVersion; } internal bool MarkAsSent() { return Interlocked.Exchange(ref _sendStatus, MessageAlreadySent) == MessageNotYetSent; } #region IDisposable Members protected virtual void Dispose(bool disposing) { // The reason for this type to implement IDisposable is that it contains instances of types that implement // IDisposable (content). if (disposing && !_disposed) { _disposed = true; if (_content != null) { _content.Dispose(); } } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(this.GetType().ToString()); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ApiManagement { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for TenantConfigurationOperations. /// </summary> public static partial class TenantConfigurationOperationsExtensions { /// <summary> /// This operation applies changes from the specified Git branch to the /// configuration database. This is a long running operation and could take /// several minutes to complete. /// <see href="https://azure.microsoft.com/en-us/documentation/articles/api-management-configuration-repository-git/#to-deploy-any-service-configuration-changes-to-the-api-management-service-instance" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='parameters'> /// Deploy Configuration parameters. /// </param> public static OperationResultContract Deploy(this ITenantConfigurationOperations operations, string resourceGroupName, string serviceName, DeployConfigurationParameters parameters) { return operations.DeployAsync(resourceGroupName, serviceName, parameters).GetAwaiter().GetResult(); } /// <summary> /// This operation applies changes from the specified Git branch to the /// configuration database. This is a long running operation and could take /// several minutes to complete. /// <see href="https://azure.microsoft.com/en-us/documentation/articles/api-management-configuration-repository-git/#to-deploy-any-service-configuration-changes-to-the-api-management-service-instance" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='parameters'> /// Deploy Configuration parameters. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<OperationResultContract> DeployAsync(this ITenantConfigurationOperations operations, string resourceGroupName, string serviceName, DeployConfigurationParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.DeployWithHttpMessagesAsync(resourceGroupName, serviceName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// This operation creates a commit with the current configuration snapshot to /// the specified branch in the repository. This is a long running operation /// and could take several minutes to complete. /// <see href="https://azure.microsoft.com/en-us/documentation/articles/api-management-configuration-repository-git/#to-save-the-service-configuration-to-the-git-repository" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='parameters'> /// Save Configuration parameters. /// </param> public static OperationResultContract Save(this ITenantConfigurationOperations operations, string resourceGroupName, string serviceName, SaveConfigurationParameter parameters) { return operations.SaveAsync(resourceGroupName, serviceName, parameters).GetAwaiter().GetResult(); } /// <summary> /// This operation creates a commit with the current configuration snapshot to /// the specified branch in the repository. This is a long running operation /// and could take several minutes to complete. /// <see href="https://azure.microsoft.com/en-us/documentation/articles/api-management-configuration-repository-git/#to-save-the-service-configuration-to-the-git-repository" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='parameters'> /// Save Configuration parameters. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<OperationResultContract> SaveAsync(this ITenantConfigurationOperations operations, string resourceGroupName, string serviceName, SaveConfigurationParameter parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.SaveWithHttpMessagesAsync(resourceGroupName, serviceName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// This operation validates the changes in the specified Git branch. This is a /// long running operation and could take several minutes to complete. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='parameters'> /// Validate Configuration parameters. /// </param> public static OperationResultContract Validate(this ITenantConfigurationOperations operations, string resourceGroupName, string serviceName, DeployConfigurationParameters parameters) { return operations.ValidateAsync(resourceGroupName, serviceName, parameters).GetAwaiter().GetResult(); } /// <summary> /// This operation validates the changes in the specified Git branch. This is a /// long running operation and could take several minutes to complete. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='parameters'> /// Validate Configuration parameters. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<OperationResultContract> ValidateAsync(this ITenantConfigurationOperations operations, string resourceGroupName, string serviceName, DeployConfigurationParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ValidateWithHttpMessagesAsync(resourceGroupName, serviceName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the status of the most recent synchronization between the /// configuration database and the Git repository. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> public static TenantConfigurationSyncStateContract GetSyncState(this ITenantConfigurationOperations operations, string resourceGroupName, string serviceName) { return operations.GetSyncStateAsync(resourceGroupName, serviceName).GetAwaiter().GetResult(); } /// <summary> /// Gets the status of the most recent synchronization between the /// configuration database and the Git repository. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<TenantConfigurationSyncStateContract> GetSyncStateAsync(this ITenantConfigurationOperations operations, string resourceGroupName, string serviceName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetSyncStateWithHttpMessagesAsync(resourceGroupName, serviceName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// This operation applies changes from the specified Git branch to the /// configuration database. This is a long running operation and could take /// several minutes to complete. /// <see href="https://azure.microsoft.com/en-us/documentation/articles/api-management-configuration-repository-git/#to-deploy-any-service-configuration-changes-to-the-api-management-service-instance" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='parameters'> /// Deploy Configuration parameters. /// </param> public static OperationResultContract BeginDeploy(this ITenantConfigurationOperations operations, string resourceGroupName, string serviceName, DeployConfigurationParameters parameters) { return operations.BeginDeployAsync(resourceGroupName, serviceName, parameters).GetAwaiter().GetResult(); } /// <summary> /// This operation applies changes from the specified Git branch to the /// configuration database. This is a long running operation and could take /// several minutes to complete. /// <see href="https://azure.microsoft.com/en-us/documentation/articles/api-management-configuration-repository-git/#to-deploy-any-service-configuration-changes-to-the-api-management-service-instance" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='parameters'> /// Deploy Configuration parameters. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<OperationResultContract> BeginDeployAsync(this ITenantConfigurationOperations operations, string resourceGroupName, string serviceName, DeployConfigurationParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginDeployWithHttpMessagesAsync(resourceGroupName, serviceName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// This operation creates a commit with the current configuration snapshot to /// the specified branch in the repository. This is a long running operation /// and could take several minutes to complete. /// <see href="https://azure.microsoft.com/en-us/documentation/articles/api-management-configuration-repository-git/#to-save-the-service-configuration-to-the-git-repository" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='parameters'> /// Save Configuration parameters. /// </param> public static OperationResultContract BeginSave(this ITenantConfigurationOperations operations, string resourceGroupName, string serviceName, SaveConfigurationParameter parameters) { return operations.BeginSaveAsync(resourceGroupName, serviceName, parameters).GetAwaiter().GetResult(); } /// <summary> /// This operation creates a commit with the current configuration snapshot to /// the specified branch in the repository. This is a long running operation /// and could take several minutes to complete. /// <see href="https://azure.microsoft.com/en-us/documentation/articles/api-management-configuration-repository-git/#to-save-the-service-configuration-to-the-git-repository" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='parameters'> /// Save Configuration parameters. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<OperationResultContract> BeginSaveAsync(this ITenantConfigurationOperations operations, string resourceGroupName, string serviceName, SaveConfigurationParameter parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginSaveWithHttpMessagesAsync(resourceGroupName, serviceName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// This operation validates the changes in the specified Git branch. This is a /// long running operation and could take several minutes to complete. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='parameters'> /// Validate Configuration parameters. /// </param> public static OperationResultContract BeginValidate(this ITenantConfigurationOperations operations, string resourceGroupName, string serviceName, DeployConfigurationParameters parameters) { return operations.BeginValidateAsync(resourceGroupName, serviceName, parameters).GetAwaiter().GetResult(); } /// <summary> /// This operation validates the changes in the specified Git branch. This is a /// long running operation and could take several minutes to complete. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='parameters'> /// Validate Configuration parameters. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<OperationResultContract> BeginValidateAsync(this ITenantConfigurationOperations operations, string resourceGroupName, string serviceName, DeployConfigurationParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginValidateWithHttpMessagesAsync(resourceGroupName, serviceName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Security.Cryptography { public abstract partial class Aes : System.Security.Cryptography.SymmetricAlgorithm { protected Aes() { } public override System.Security.Cryptography.KeySizes[] LegalBlockSizes { get { return default(System.Security.Cryptography.KeySizes[]); } } public override System.Security.Cryptography.KeySizes[] LegalKeySizes { get { return default(System.Security.Cryptography.KeySizes[]); } } public static System.Security.Cryptography.Aes Create() { return default(System.Security.Cryptography.Aes); } } public abstract partial class DeriveBytes : System.IDisposable { protected DeriveBytes() { } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public abstract byte[] GetBytes(int cb); public abstract void Reset(); } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct ECCurve { public byte[] A; public byte[] B; public byte[] Cofactor; public System.Security.Cryptography.ECCurve.ECCurveType CurveType; public System.Security.Cryptography.ECPoint G; public System.Nullable<System.Security.Cryptography.HashAlgorithmName> Hash; public byte[] Order; public byte[] Polynomial; public byte[] Prime; public byte[] Seed; public bool IsCharacteristic2 { get { return default(bool); } } public bool IsExplicit { get { return default(bool); } } public bool IsNamed { get { return default(bool); } } public bool IsPrime { get { return default(bool); } } public System.Security.Cryptography.Oid Oid { get { return default(System.Security.Cryptography.Oid); } } public static System.Security.Cryptography.ECCurve CreateFromFriendlyName(string oidFriendlyName) { return default(System.Security.Cryptography.ECCurve); } public static System.Security.Cryptography.ECCurve CreateFromOid(System.Security.Cryptography.Oid curveOid) { return default(System.Security.Cryptography.ECCurve); } public static System.Security.Cryptography.ECCurve CreateFromValue(string oidValue) { return default(System.Security.Cryptography.ECCurve); } public void Validate() { } public enum ECCurveType { Characteristic2 = 4, Implicit = 0, Named = 5, PrimeMontgomery = 3, PrimeShortWeierstrass = 1, PrimeTwistedEdwards = 2, } public static partial class NamedCurves { public static System.Security.Cryptography.ECCurve brainpoolP160r1 { get { return default(System.Security.Cryptography.ECCurve); } } public static System.Security.Cryptography.ECCurve brainpoolP160t1 { get { return default(System.Security.Cryptography.ECCurve); } } public static System.Security.Cryptography.ECCurve brainpoolP192r1 { get { return default(System.Security.Cryptography.ECCurve); } } public static System.Security.Cryptography.ECCurve brainpoolP192t1 { get { return default(System.Security.Cryptography.ECCurve); } } public static System.Security.Cryptography.ECCurve brainpoolP224r1 { get { return default(System.Security.Cryptography.ECCurve); } } public static System.Security.Cryptography.ECCurve brainpoolP224t1 { get { return default(System.Security.Cryptography.ECCurve); } } public static System.Security.Cryptography.ECCurve brainpoolP256r1 { get { return default(System.Security.Cryptography.ECCurve); } } public static System.Security.Cryptography.ECCurve brainpoolP256t1 { get { return default(System.Security.Cryptography.ECCurve); } } public static System.Security.Cryptography.ECCurve brainpoolP320r1 { get { return default(System.Security.Cryptography.ECCurve); } } public static System.Security.Cryptography.ECCurve brainpoolP320t1 { get { return default(System.Security.Cryptography.ECCurve); } } public static System.Security.Cryptography.ECCurve brainpoolP384r1 { get { return default(System.Security.Cryptography.ECCurve); } } public static System.Security.Cryptography.ECCurve brainpoolP384t1 { get { return default(System.Security.Cryptography.ECCurve); } } public static System.Security.Cryptography.ECCurve brainpoolP512r1 { get { return default(System.Security.Cryptography.ECCurve); } } public static System.Security.Cryptography.ECCurve brainpoolP512t1 { get { return default(System.Security.Cryptography.ECCurve); } } public static System.Security.Cryptography.ECCurve nistP256 { get { return default(System.Security.Cryptography.ECCurve); } } public static System.Security.Cryptography.ECCurve nistP384 { get { return default(System.Security.Cryptography.ECCurve); } } public static System.Security.Cryptography.ECCurve nistP521 { get { return default(System.Security.Cryptography.ECCurve); } } } } public abstract partial class ECDsa : System.Security.Cryptography.AsymmetricAlgorithm { protected ECDsa() { } public static System.Security.Cryptography.ECDsa Create() { return default(System.Security.Cryptography.ECDsa); } public static System.Security.Cryptography.ECDsa Create(System.Security.Cryptography.ECCurve curve) { return default(System.Security.Cryptography.ECDsa); } public static System.Security.Cryptography.ECDsa Create(System.Security.Cryptography.ECParameters parameters) { return default(System.Security.Cryptography.ECDsa); } public virtual System.Security.Cryptography.ECParameters ExportExplicitParameters(bool includePrivateParameters) { return default(System.Security.Cryptography.ECParameters); } public virtual System.Security.Cryptography.ECParameters ExportParameters(bool includePrivateParameters) { return default(System.Security.Cryptography.ECParameters); } public virtual void GenerateKey(System.Security.Cryptography.ECCurve curve) { } protected abstract byte[] HashData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm); protected abstract byte[] HashData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm); public virtual void ImportParameters(System.Security.Cryptography.ECParameters parameters) { } public virtual byte[] SignData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(byte[]); } public virtual byte[] SignData(byte[] data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(byte[]); } public virtual byte[] SignData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(byte[]); } public abstract byte[] SignHash(byte[] hash); public bool VerifyData(byte[] data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(bool); } public virtual bool VerifyData(byte[] data, int offset, int count, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(bool); } public bool VerifyData(System.IO.Stream data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(bool); } public abstract bool VerifyHash(byte[] hash, byte[] signature); } public struct ECParameters { public System.Security.Cryptography.ECCurve Curve; public byte[] D; public System.Security.Cryptography.ECPoint Q; public void Validate() { } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct ECPoint { public byte[] X; public byte[] Y; } public partial class HMACMD5 : System.Security.Cryptography.HMAC { public HMACMD5() { } public HMACMD5(byte[] key) { } public override int HashSize { get { return default(int); } } public override byte[] Key { get { return default(byte[]); } set { } } protected override void Dispose(bool disposing) { } protected override void HashCore(byte[] rgb, int ib, int cb) { } protected override byte[] HashFinal() { return default(byte[]); } public override void Initialize() { } } public partial class HMACSHA1 : System.Security.Cryptography.HMAC { public HMACSHA1() { } public HMACSHA1(byte[] key) { } public override int HashSize { get { return default(int); } } public override byte[] Key { get { return default(byte[]); } set { } } protected override void Dispose(bool disposing) { } protected override void HashCore(byte[] rgb, int ib, int cb) { } protected override byte[] HashFinal() { return default(byte[]); } public override void Initialize() { } } public partial class HMACSHA256 : System.Security.Cryptography.HMAC { public HMACSHA256() { } public HMACSHA256(byte[] key) { } public override int HashSize { get { return default(int); } } public override byte[] Key { get { return default(byte[]); } set { } } protected override void Dispose(bool disposing) { } protected override void HashCore(byte[] rgb, int ib, int cb) { } protected override byte[] HashFinal() { return default(byte[]); } public override void Initialize() { } } public partial class HMACSHA384 : System.Security.Cryptography.HMAC { public HMACSHA384() { } public HMACSHA384(byte[] key) { } public override int HashSize { get { return default(int); } } public override byte[] Key { get { return default(byte[]); } set { } } protected override void Dispose(bool disposing) { } protected override void HashCore(byte[] rgb, int ib, int cb) { } protected override byte[] HashFinal() { return default(byte[]); } public override void Initialize() { } } public partial class HMACSHA512 : System.Security.Cryptography.HMAC { public HMACSHA512() { } public HMACSHA512(byte[] key) { } public override int HashSize { get { return default(int); } } public override byte[] Key { get { return default(byte[]); } set { } } protected override void Dispose(bool disposing) { } protected override void HashCore(byte[] rgb, int ib, int cb) { } protected override byte[] HashFinal() { return default(byte[]); } public override void Initialize() { } } public sealed partial class IncrementalHash : System.IDisposable { internal IncrementalHash() { } public System.Security.Cryptography.HashAlgorithmName AlgorithmName { get { return default(System.Security.Cryptography.HashAlgorithmName); } } public void AppendData(byte[] data) { } public void AppendData(byte[] data, int offset, int count) { } public static System.Security.Cryptography.IncrementalHash CreateHash(System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(System.Security.Cryptography.IncrementalHash); } public static System.Security.Cryptography.IncrementalHash CreateHMAC(System.Security.Cryptography.HashAlgorithmName hashAlgorithm, byte[] key) { return default(System.Security.Cryptography.IncrementalHash); } public void Dispose() { } public byte[] GetHashAndReset() { return default(byte[]); } } public abstract partial class MD5 : System.Security.Cryptography.HashAlgorithm { protected MD5() { } public static System.Security.Cryptography.MD5 Create() { return default(System.Security.Cryptography.MD5); } } public abstract partial class RandomNumberGenerator : System.IDisposable { protected RandomNumberGenerator() { } public static System.Security.Cryptography.RandomNumberGenerator Create() { return default(System.Security.Cryptography.RandomNumberGenerator); } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public abstract void GetBytes(byte[] data); } public partial class Rfc2898DeriveBytes : System.Security.Cryptography.DeriveBytes { public Rfc2898DeriveBytes(byte[] password, byte[] salt, int iterations) { } public Rfc2898DeriveBytes(string password, byte[] salt) { } public Rfc2898DeriveBytes(string password, byte[] salt, int iterations) { } public Rfc2898DeriveBytes(string password, int saltSize) { } public Rfc2898DeriveBytes(string password, int saltSize, int iterations) { } public int IterationCount { get { return default(int); } set { } } public byte[] Salt { get { return default(byte[]); } set { } } protected override void Dispose(bool disposing) { } public override byte[] GetBytes(int cb) { return default(byte[]); } public override void Reset() { } } public abstract partial class RSA : System.Security.Cryptography.AsymmetricAlgorithm { protected RSA() { } public static RSA Create() { return default(RSA); } public abstract byte[] Decrypt(byte[] data, System.Security.Cryptography.RSAEncryptionPadding padding); public abstract byte[] Encrypt(byte[] data, System.Security.Cryptography.RSAEncryptionPadding padding); public abstract System.Security.Cryptography.RSAParameters ExportParameters(bool includePrivateParameters); protected abstract byte[] HashData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm); protected abstract byte[] HashData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm); public abstract void ImportParameters(System.Security.Cryptography.RSAParameters parameters); public virtual byte[] SignData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { return default(byte[]); } public byte[] SignData(byte[] data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { return default(byte[]); } public virtual byte[] SignData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { return default(byte[]); } public abstract byte[] SignHash(byte[] hash, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding); public bool VerifyData(byte[] data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { return default(bool); } public virtual bool VerifyData(byte[] data, int offset, int count, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { return default(bool); } public bool VerifyData(System.IO.Stream data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { return default(bool); } public abstract bool VerifyHash(byte[] hash, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding); } public sealed partial class RSAEncryptionPadding : System.IEquatable<System.Security.Cryptography.RSAEncryptionPadding> { internal RSAEncryptionPadding() { } public System.Security.Cryptography.RSAEncryptionPaddingMode Mode { get { return default(System.Security.Cryptography.RSAEncryptionPaddingMode); } } public System.Security.Cryptography.HashAlgorithmName OaepHashAlgorithm { get { return default(System.Security.Cryptography.HashAlgorithmName); } } public static System.Security.Cryptography.RSAEncryptionPadding OaepSHA1 { get { return default(System.Security.Cryptography.RSAEncryptionPadding); } } public static System.Security.Cryptography.RSAEncryptionPadding OaepSHA256 { get { return default(System.Security.Cryptography.RSAEncryptionPadding); } } public static System.Security.Cryptography.RSAEncryptionPadding OaepSHA384 { get { return default(System.Security.Cryptography.RSAEncryptionPadding); } } public static System.Security.Cryptography.RSAEncryptionPadding OaepSHA512 { get { return default(System.Security.Cryptography.RSAEncryptionPadding); } } public static System.Security.Cryptography.RSAEncryptionPadding Pkcs1 { get { return default(System.Security.Cryptography.RSAEncryptionPadding); } } public static System.Security.Cryptography.RSAEncryptionPadding CreateOaep(System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(System.Security.Cryptography.RSAEncryptionPadding); } public override bool Equals(object obj) { return default(bool); } public bool Equals(System.Security.Cryptography.RSAEncryptionPadding other) { return default(bool); } public override int GetHashCode() { return default(int); } public static bool operator ==(System.Security.Cryptography.RSAEncryptionPadding left, System.Security.Cryptography.RSAEncryptionPadding right) { return default(bool); } public static bool operator !=(System.Security.Cryptography.RSAEncryptionPadding left, System.Security.Cryptography.RSAEncryptionPadding right) { return default(bool); } public override string ToString() { return default(string); } } public enum RSAEncryptionPaddingMode { Oaep = 1, Pkcs1 = 0, } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct RSAParameters { public byte[] D; public byte[] DP; public byte[] DQ; public byte[] Exponent; public byte[] InverseQ; public byte[] Modulus; public byte[] P; public byte[] Q; } public sealed partial class RSASignaturePadding : System.IEquatable<System.Security.Cryptography.RSASignaturePadding> { internal RSASignaturePadding() { } public System.Security.Cryptography.RSASignaturePaddingMode Mode { get { return default(System.Security.Cryptography.RSASignaturePaddingMode); } } public static System.Security.Cryptography.RSASignaturePadding Pkcs1 { get { return default(System.Security.Cryptography.RSASignaturePadding); } } public static System.Security.Cryptography.RSASignaturePadding Pss { get { return default(System.Security.Cryptography.RSASignaturePadding); } } public override bool Equals(object obj) { return default(bool); } public bool Equals(System.Security.Cryptography.RSASignaturePadding other) { return default(bool); } public override int GetHashCode() { return default(int); } public static bool operator ==(System.Security.Cryptography.RSASignaturePadding left, System.Security.Cryptography.RSASignaturePadding right) { return default(bool); } public static bool operator !=(System.Security.Cryptography.RSASignaturePadding left, System.Security.Cryptography.RSASignaturePadding right) { return default(bool); } public override string ToString() { return default(string); } } public enum RSASignaturePaddingMode { Pkcs1 = 0, Pss = 1, } public abstract partial class SHA1 : System.Security.Cryptography.HashAlgorithm { protected SHA1() { } public static System.Security.Cryptography.SHA1 Create() { return default(System.Security.Cryptography.SHA1); } } public abstract partial class SHA256 : System.Security.Cryptography.HashAlgorithm { protected SHA256() { } public static System.Security.Cryptography.SHA256 Create() { return default(System.Security.Cryptography.SHA256); } } public abstract partial class SHA384 : System.Security.Cryptography.HashAlgorithm { protected SHA384() { } public static System.Security.Cryptography.SHA384 Create() { return default(System.Security.Cryptography.SHA384); } } public abstract partial class SHA512 : System.Security.Cryptography.HashAlgorithm { protected SHA512() { } public static System.Security.Cryptography.SHA512 Create() { return default(System.Security.Cryptography.SHA512); } } public abstract partial class TripleDES : System.Security.Cryptography.SymmetricAlgorithm { protected TripleDES() { } public override byte[] Key { get { return default(byte[]); } set { } } public override System.Security.Cryptography.KeySizes[] LegalBlockSizes { get { return default(System.Security.Cryptography.KeySizes[]); } } public override System.Security.Cryptography.KeySizes[] LegalKeySizes { get { return default(System.Security.Cryptography.KeySizes[]); } } public static System.Security.Cryptography.TripleDES Create() { return default(System.Security.Cryptography.TripleDES); } public static bool IsWeakKey(byte[] rgbKey) { return default(bool); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using Microsoft.Azure.Management.WebSites.Models; using Microsoft.WindowsAzure.Common.Internals; namespace Microsoft.Azure.Management.WebSites.Models { /// <summary> /// The Get Web Site Configuration operation response. /// </summary> public partial class WebSiteGetConfigurationResponse { private IDictionary<string, string> _appSettings; /// <summary> /// Optional. A set of name/value pairs that contain application /// settings for a site. /// </summary> public IDictionary<string, string> AppSettings { get { return this._appSettings; } set { this._appSettings = value; } } private string _autoSwapSlotName; /// <summary> /// Optional. Gets the slot name to swap with after successful /// deployment. /// </summary> public string AutoSwapSlotName { get { return this._autoSwapSlotName; } set { this._autoSwapSlotName = value; } } private IList<ConnectionStringInfo> _connectionStrings; /// <summary> /// Optional. Contains connection strings for database and other /// external resources. /// </summary> public IList<ConnectionStringInfo> ConnectionStrings { get { return this._connectionStrings; } set { this._connectionStrings = value; } } private IList<string> _defaultDocuments; /// <summary> /// Optional. Contains one or more string elements that list, in order /// of preference, the name of the file that a web site returns when /// the web site's domain name is requested by itself. For example, if /// the default document for http://contoso.com is default.htm, the /// page http://www.contoso.com/default.htm is returned when the /// browser is pointed to http://www.contoso.com. /// </summary> public IList<string> DefaultDocuments { get { return this._defaultDocuments; } set { this._defaultDocuments = value; } } private bool? _detailedErrorLoggingEnabled; /// <summary> /// Optional. True if detailed error logging is enabled; otherwise, /// false. /// </summary> public bool? DetailedErrorLoggingEnabled { get { return this._detailedErrorLoggingEnabled; } set { this._detailedErrorLoggingEnabled = value; } } private string _documentRoot; /// <summary> /// Optional. The document root. /// </summary> public string DocumentRoot { get { return this._documentRoot; } set { this._documentRoot = value; } } private IList<WebSiteGetConfigurationResponse.HandlerMapping> _handlerMappings; /// <summary> /// Optional. Specifies custom executable programs for handling /// requests for specific file name extensions. /// </summary> public IList<WebSiteGetConfigurationResponse.HandlerMapping> HandlerMappings { get { return this._handlerMappings; } set { this._handlerMappings = value; } } private bool? _httpLoggingEnabled; /// <summary> /// Optional. True if HTTP error logging is enabled; otherwise, false. /// </summary> public bool? HttpLoggingEnabled { get { return this._httpLoggingEnabled; } set { this._httpLoggingEnabled = value; } } private int? _logsDirectorySizeLimit; /// <summary> /// Optional. The limit of the logs directory. /// </summary> public int? LogsDirectorySizeLimit { get { return this._logsDirectorySizeLimit; } set { this._logsDirectorySizeLimit = value; } } private Microsoft.Azure.Management.WebSites.Models.ManagedPipelineMode? _managedPipelineMode; /// <summary> /// Optional. Managed pipeline modes. /// </summary> public Microsoft.Azure.Management.WebSites.Models.ManagedPipelineMode? ManagedPipelineMode { get { return this._managedPipelineMode; } set { this._managedPipelineMode = value; } } private IDictionary<string, string> _metadata; /// <summary> /// Optional. Contains name/value pairs for source control or other /// information. /// </summary> public IDictionary<string, string> Metadata { get { return this._metadata; } set { this._metadata = value; } } private string _netFrameworkVersion; /// <summary> /// Optional. The .NET Framework version. Supported values are v2.0 and /// v4.0. /// </summary> public string NetFrameworkVersion { get { return this._netFrameworkVersion; } set { this._netFrameworkVersion = value; } } private int? _numberOfWorkers; /// <summary> /// Optional. The number of web workers allotted to the web site. If /// the site mode is Free, this value is 1. If the site mode is /// Shared, this value can range from 1 through 6. If the site mode is /// Standard, this value can range from 1 through 10. /// </summary> public int? NumberOfWorkers { get { return this._numberOfWorkers; } set { this._numberOfWorkers = value; } } private string _phpVersion; /// <summary> /// Optional. Supported values are an empty string (an empty string /// disables PHP), 5.3, and 5.4. /// </summary> public string PhpVersion { get { return this._phpVersion; } set { this._phpVersion = value; } } private string _publishingPassword; /// <summary> /// Optional. Hash value of the password used for publishing the web /// site. /// </summary> public string PublishingPassword { get { return this._publishingPassword; } set { this._publishingPassword = value; } } private string _publishingUserName; /// <summary> /// Optional. The username used for publishing the web site. This is /// normally a dollar sign prepended to the web site name (for /// example, "$contoso"). /// </summary> public string PublishingUserName { get { return this._publishingUserName; } set { this._publishingUserName = value; } } private bool? _remoteDebuggingEnabled; /// <summary> /// Optional. True remote debugging is enabled; otherwise, false. /// </summary> public bool? RemoteDebuggingEnabled { get { return this._remoteDebuggingEnabled; } set { this._remoteDebuggingEnabled = value; } } private RemoteDebuggingVersion _remoteDebuggingVersion; /// <summary> /// Optional. True remote debugging version. /// </summary> public RemoteDebuggingVersion RemoteDebuggingVersion { get { return this._remoteDebuggingVersion; } set { this._remoteDebuggingVersion = value; } } private bool? _requestTracingEnabled; /// <summary> /// Optional. True if request tracing is enabled; otherwise, false. /// </summary> public bool? RequestTracingEnabled { get { return this._requestTracingEnabled; } set { this._requestTracingEnabled = value; } } private System.DateTime? _requestTracingExpirationTime; /// <summary> /// Optional. Time remaining until request tracing expires. /// </summary> public System.DateTime? RequestTracingExpirationTime { get { return this._requestTracingExpirationTime; } set { this._requestTracingExpirationTime = value; } } private string _scmType; /// <summary> /// Optional. The source control method that the web site is using (for /// example, Local Git). If deployment from source control has not /// been set up for the web site, this value is None. /// </summary> public string ScmType { get { return this._scmType; } set { this._scmType = value; } } private bool? _use32BitWorkerProcess; /// <summary> /// Optional. True if 32-bit mode is enabled; otherwise, false. /// </summary> public bool? Use32BitWorkerProcess { get { return this._use32BitWorkerProcess; } set { this._use32BitWorkerProcess = value; } } private bool? _webSocketsEnabled; /// <summary> /// Optional. True if Web Sockets are enabled; otherwise, false. /// </summary> public bool? WebSocketsEnabled { get { return this._webSocketsEnabled; } set { this._webSocketsEnabled = value; } } /// <summary> /// Initializes a new instance of the WebSiteGetConfigurationResponse /// class. /// </summary> public WebSiteGetConfigurationResponse() { this.AppSettings = new LazyDictionary<string, string>(); this.ConnectionStrings = new LazyList<ConnectionStringInfo>(); this.DefaultDocuments = new LazyList<string>(); this.HandlerMappings = new LazyList<WebSiteGetConfigurationResponse.HandlerMapping>(); this.Metadata = new LazyDictionary<string, string>(); } /// <summary> /// Specifies a custom executable program for handling requests for /// specific file name extensions. /// </summary> public partial class HandlerMapping { private string _arguments; /// <summary> /// Optional. A string that contains optional arguments for the /// script processor specified by the /// SiteConfig.HandlerMappings.HandlerMapping.ScriptProcessor /// element. /// </summary> public string Arguments { get { return this._arguments; } set { this._arguments = value; } } private string _extension; /// <summary> /// Optional. A string that specifies the extension of the file /// type that the script processor will handle (for example, /// *.php). /// </summary> public string Extension { get { return this._extension; } set { this._extension = value; } } private string _scriptProcessor; /// <summary> /// Optional. The absolute path to the location of the executable /// file that will handle the files specified in the /// SiteConfig.HandlerMappings.HandlerMapping.Extension element. /// </summary> public string ScriptProcessor { get { return this._scriptProcessor; } set { this._scriptProcessor = value; } } /// <summary> /// Initializes a new instance of the HandlerMapping class. /// </summary> public HandlerMapping() { } } } }
/* * REST API Documentation for the MOTI Hired Equipment Tracking System (HETS) Application * * The Hired Equipment Program is for owners/operators who have a dump truck, bulldozer, backhoe or other piece of equipment they want to hire out to the transportation ministry for day labour and emergency projects. The Hired Equipment Program distributes available work to local equipment owners. The program is based on seniority and is designed to deliver work to registered users fairly and efficiently through the development of local area call-out lists. * * OpenAPI spec version: v1 * * */ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Xunit; using HETSAPI; using System.Text; using HETSAPI.Models; using Newtonsoft.Json; using System.Net; using HETSAPI.ViewModels; using Microsoft.AspNetCore.WebUtilities; namespace HETSAPI.Test { public class OwnerIntegrationTest : ApiIntegrationTestBase { [Fact] /// <summary> /// Integration test for OwnersBulkPost /// </summary> public async void TestOwnersBulkPost() { var request = new HttpRequestMessage(HttpMethod.Post, "/api/owners/bulk"); request.Content = new StringContent("[]", Encoding.UTF8, "application/json"); var response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); } [Fact] /// <summary> /// Basic Integration test for Owners /// </summary> public async void TestOwnersBasic() { string initialName = "InitialName"; string changedName = "ChangedName"; // first test the POST. var request = new HttpRequestMessage(HttpMethod.Post, "/api/owners"); // create a new object. Owner owner = new Owner(); owner.OrganizationName = initialName; string jsonString = owner.ToJson(); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); var response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); owner = JsonConvert.DeserializeObject<Owner>(jsonString); // get the id var id = owner.Id; // change the name owner.OrganizationName = changedName; // now do an update. request = new HttpRequestMessage(HttpMethod.Put, "/api/owners/" + id); request.Content = new StringContent(owner.ToJson(), Encoding.UTF8, "application/json"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // do a get. request = new HttpRequestMessage(HttpMethod.Get, "/api/owners/" + id); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); owner = JsonConvert.DeserializeObject<Owner>(jsonString); // verify the change went through. Assert.Equal(owner.OrganizationName, changedName); // do a delete. request = new HttpRequestMessage(HttpMethod.Post, "/api/owners/" + id + "/delete"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // should get a 404 if we try a get now. request = new HttpRequestMessage(HttpMethod.Get, "/api/owners/" + id); response = await _client.SendAsync(request); Assert.Equal(response.StatusCode, HttpStatusCode.NotFound); } [Fact] /// <summary> /// Basic Integration test for Owners /// </summary> public async void TestOwnerContacts() { string initialName = "InitialName"; string changedName = "ChangedName"; // first test the POST. var request = new HttpRequestMessage(HttpMethod.Post, "/api/owners"); // create a new object. Owner owner = new Owner(); owner.OrganizationName = initialName; string jsonString = owner.ToJson(); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); var response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); owner = JsonConvert.DeserializeObject<Owner>(jsonString); // get the id var id = owner.Id; // change the name owner.OrganizationName = changedName; // get contacts should be empty. request = new HttpRequestMessage(HttpMethod.Get, "/api/owners/" + id + "/contacts"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); List<Contact> contacts = JsonConvert.DeserializeObject<List<Contact>>(jsonString); // verify the list is empty. Assert.Equal(contacts.Count(), 0); // add a contact. Contact contact = new Contact(); contact.GivenName = initialName; contacts.Add(contact); request = new HttpRequestMessage(HttpMethod.Put, "/api/owners/" + id + "/contacts"); request.Content = new StringContent(JsonConvert.SerializeObject(contacts), Encoding.UTF8, "application/json"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); contacts = JsonConvert.DeserializeObject<List<Contact>>(jsonString); // verify the list has one element. Assert.Equal(contacts.Count, 1); Assert.Equal(contacts[0].GivenName, initialName); // get contacts should be 1 request = new HttpRequestMessage(HttpMethod.Get, "/api/owners/" + id + "/contacts"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); contacts = JsonConvert.DeserializeObject<List<Contact>>(jsonString); // verify the list has a record. Assert.Equal(contacts.Count, 1); Assert.Equal(contacts[0].GivenName, initialName); // test removing the contact. contacts.Clear(); request = new HttpRequestMessage(HttpMethod.Put, "/api/owners/" + id + "/contacts"); request.Content = new StringContent(JsonConvert.SerializeObject(contacts), Encoding.UTF8, "application/json"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); contacts = JsonConvert.DeserializeObject<List<Contact>>(jsonString); // should be 0 Assert.Equal(contacts.Count, 0); // test the get request = new HttpRequestMessage(HttpMethod.Get, "/api/owners/" + id + "/contacts"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); contacts = JsonConvert.DeserializeObject<List<Contact>>(jsonString); // verify the list has no records. Assert.Equal(contacts.Count, 0); // test the post. Contact newContact = new Contact(); newContact.OrganizationName = "asdf"; request = new HttpRequestMessage(HttpMethod.Post, "/api/owners/" + id + "/contacts"); request.Content = new StringContent(JsonConvert.SerializeObject(newContact), Encoding.UTF8, "application/json"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); newContact = JsonConvert.DeserializeObject<Contact>(jsonString); // should be 0 Assert.NotEqual(newContact.Id, 0); request = new HttpRequestMessage(HttpMethod.Put, "/api/owners/" + id + "/contacts"); request.Content = new StringContent(JsonConvert.SerializeObject(contacts), Encoding.UTF8, "application/json"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); contacts = JsonConvert.DeserializeObject<List<Contact>>(jsonString); // should be 0 Assert.Equal(contacts.Count, 0); // delete the owner. request = new HttpRequestMessage(HttpMethod.Post, "/api/owners/" + id + "/delete"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // should get a 404 if we try a get now. request = new HttpRequestMessage(HttpMethod.Get, "/api/owners/" + id); response = await _client.SendAsync(request); Assert.Equal(response.StatusCode, HttpStatusCode.NotFound); } private Equipment createEquipment(Owner owner, string model) { var request = new HttpRequestMessage(HttpMethod.Post, "/api/equipment"); // create a new object. Equipment equipment = new Equipment(); equipment.Model = model; equipment.Owner = owner; string jsonString = equipment.ToJson(); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); Task<HttpResponseMessage> responseTask = _client.SendAsync(request); responseTask.Wait(); HttpResponseMessage response = responseTask.Result; response.EnsureSuccessStatusCode(); Task<string> stringTask = response.Content.ReadAsStringAsync(); stringTask.Wait(); // parse as JSON. jsonString = stringTask.Result; equipment = JsonConvert.DeserializeObject<Equipment>(jsonString); return equipment; } private void deleteEquipment(int id) { // do a delete. var request = new HttpRequestMessage(HttpMethod.Post, "/api/equipments/" + id + "/delete"); Task<HttpResponseMessage> responseTask = _client.SendAsync(request); responseTask.Wait(); } [Fact] /// <summary> /// TestOwnerEquipmentList /// </summary> /// public async void TestOwnerEquipmentList() { /* * Create Owner * Create several pieces of equipment * Populate the equipment list * Verify that all items in the equipment list still have owner. */ string initialName = "InitialName"; // first test the POST. var request = new HttpRequestMessage(HttpMethod.Post, "/api/owners"); // create a new object. Owner owner = new Owner(); owner.OrganizationName = initialName; string jsonString = owner.ToJson(); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); var response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); owner = JsonConvert.DeserializeObject<Owner>(jsonString); // get the id var owner_id = owner.Id; // create equipment. Equipment e1 = createEquipment(owner, "test1"); Equipment e2 = createEquipment(owner, "test2"); Equipment e3 = createEquipment(owner, "test3"); Equipment[] equipmentList = new Equipment[3]; equipmentList[0] = e1; equipmentList[1] = e2; equipmentList[2] = e3; // update the equipment list. request = new HttpRequestMessage(HttpMethod.Put, "/api/owners/" + owner_id + "/equipment"); jsonString = JsonConvert.SerializeObject(equipmentList, Formatting.Indented); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); jsonString = await response.Content.ReadAsStringAsync(); Equipment[] putReceived = JsonConvert.DeserializeObject<Equipment[]>(jsonString); Assert.Equal(putReceived[0].Owner.Id, owner_id); // now get the equipment list. request = new HttpRequestMessage(HttpMethod.Get, "/api/owners/" + owner_id + "/equipment"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); jsonString = await response.Content.ReadAsStringAsync(); Equipment[] getReceived = JsonConvert.DeserializeObject<Equipment[]>(jsonString); Assert.Equal(getReceived.Length, 3); Assert.Equal(getReceived[0].Owner.Id, owner_id); // clean up equipment Equipment[] blankList = new Equipment[0]; request = new HttpRequestMessage(HttpMethod.Put, "/api/owners/" + owner_id + "/equipment"); jsonString = JsonConvert.SerializeObject(blankList, Formatting.Indented); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); deleteEquipment(e1.Id); deleteEquipment(e2.Id); deleteEquipment(e3.Id); // delete owner request = new HttpRequestMessage(HttpMethod.Post, "/api/owners/" + owner_id + "/delete"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // should get a 404 if we try a get now. request = new HttpRequestMessage(HttpMethod.Get, "/api/owners/" + owner_id); response = await _client.SendAsync(request); Assert.Equal(response.StatusCode, HttpStatusCode.NotFound); } [Fact] /// <summary> /// TestOwnerEquipmentList /// </summary> /// public async void TestOwnerEquipmentListDateVerified() { /* * Create Owner * Create several pieces of equipment * Populate the equipment list * Verify that all items in the equipment list still have owner. */ string initialName = "InitialName"; // first test the POST. var request = new HttpRequestMessage(HttpMethod.Post, "/api/owners"); // create a new object. Owner owner = new Owner(); owner.OrganizationName = initialName; owner.OwnerEquipmentCodePrefix = "TST"; string jsonString = owner.ToJson(); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); var response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); owner = JsonConvert.DeserializeObject<Owner>(jsonString); // get the id var owner_id = owner.Id; // create equipment. Equipment e1 = createEquipment(owner, "test1"); Equipment e2 = createEquipment(owner, "test2"); Equipment e3 = createEquipment(owner, "test3"); // validate equipment number. Assert.Equal("TST-0003", e3.EquipmentCode); Equipment[] equipmentList = new Equipment[3]; DateTime dateVerified = DateTime.UtcNow; e1.LastVerifiedDate = dateVerified; e2.LastVerifiedDate = dateVerified; e3.LastVerifiedDate = dateVerified; equipmentList[0] = e1; equipmentList[1] = e2; equipmentList[2] = e3; // update the equipment list. request = new HttpRequestMessage(HttpMethod.Put, "/api/owners/" + owner_id + "/equipment"); jsonString = JsonConvert.SerializeObject(equipmentList, Formatting.Indented); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); jsonString = await response.Content.ReadAsStringAsync(); Equipment[] putReceived = JsonConvert.DeserializeObject<Equipment[]>(jsonString); Assert.Equal(putReceived[0].Owner.Id, owner_id); // now get the equipment list. request = new HttpRequestMessage(HttpMethod.Get, "/api/owners/" + owner_id + "/equipment"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); jsonString = await response.Content.ReadAsStringAsync(); Equipment[] getReceived = JsonConvert.DeserializeObject<Equipment[]>(jsonString); Assert.Equal(getReceived[0].LastVerifiedDate.ToString("MM/dd/yyyy HH:mm"), dateVerified.ToString("MM/dd/yyyy HH:mm")); // clean up equipment Equipment[] blankList = new Equipment[0]; request = new HttpRequestMessage(HttpMethod.Put, "/api/owners/" + owner_id + "/equipment"); jsonString = JsonConvert.SerializeObject(blankList, Formatting.Indented); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); deleteEquipment(e1.Id); deleteEquipment(e2.Id); deleteEquipment(e3.Id); // delete owner request = new HttpRequestMessage(HttpMethod.Post, "/api/owners/" + owner_id + "/delete"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // should get a 404 if we try a get now. request = new HttpRequestMessage(HttpMethod.Get, "/api/owners/" + owner_id); response = await _client.SendAsync(request); Assert.Equal(response.StatusCode, HttpStatusCode.NotFound); } [Fact] /// <summary> /// TestOwnerEquipmentList /// </summary> /// public async void TestOwnerEquipmentCode() { /* * Create Owner * Create several pieces of equipment * Populate the equipment list * Verify that all items in the equipment list still have owner. */ string initialName = "InitialName"; // first test the POST. var request = new HttpRequestMessage(HttpMethod.Post, "/api/owners"); // create a new object. Owner owner = new Owner(); owner.OrganizationName = initialName; owner.OwnerEquipmentCodePrefix = "TST"; string jsonString = owner.ToJson(); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); var response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); owner = JsonConvert.DeserializeObject<Owner>(jsonString); // get the id var owner_id = owner.Id; // This test will be enabled when the new workflow for equipment code is implemented // Assert.Equal(equipmentCode.EquipmentCode, "TST-0001"); // delete owner request = new HttpRequestMessage(HttpMethod.Post, "/api/owners/" + owner_id + "/delete"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // should get a 404 if we try a get now. request = new HttpRequestMessage(HttpMethod.Get, "/api/owners/" + owner_id); response = await _client.SendAsync(request); Assert.Equal(response.StatusCode, HttpStatusCode.NotFound); } private ServiceArea CreateServiceArea( string name ) { ServiceArea result = new ServiceArea(); var request = new HttpRequestMessage(HttpMethod.Post, "/api/serviceareas"); result.Name = name; string jsonString = result.ToJson(); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); Task<HttpResponseMessage> responseTask = _client.SendAsync(request); responseTask.Wait(); HttpResponseMessage response = responseTask.Result; response.EnsureSuccessStatusCode(); Task<string> stringTask = response.Content.ReadAsStringAsync(); stringTask.Wait(); // parse as JSON. jsonString = stringTask.Result; result = JsonConvert.DeserializeObject<ServiceArea>(jsonString); return result; } private LocalArea CreateLocalArea(ServiceArea serviceArea, string name) { LocalArea result = new LocalArea(); var request = new HttpRequestMessage(HttpMethod.Post, "/api/localareas"); result.Name = name; result.ServiceArea = serviceArea; string jsonString = result.ToJson(); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); Task<HttpResponseMessage> responseTask = _client.SendAsync(request); responseTask.Wait(); HttpResponseMessage response = responseTask.Result; response.EnsureSuccessStatusCode(); Task<string> stringTask = response.Content.ReadAsStringAsync(); stringTask.Wait(); // parse as JSON. jsonString = stringTask.Result; result = JsonConvert.DeserializeObject<LocalArea>(jsonString); return result; } private Owner CreateOwner(LocalArea localArea, string name) { Owner result = new Owner(); var request = new HttpRequestMessage(HttpMethod.Post, "/api/owners"); result.OrganizationName = name; result.LocalArea = localArea; string jsonString = result.ToJson(); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); Task<HttpResponseMessage> responseTask = _client.SendAsync(request); responseTask.Wait(); HttpResponseMessage response = responseTask.Result; response.EnsureSuccessStatusCode(); Task<string> stringTask = response.Content.ReadAsStringAsync(); stringTask.Wait(); // parse as JSON. jsonString = stringTask.Result; result = JsonConvert.DeserializeObject<Owner>(jsonString); return result; } private void DeleteOwner(Owner owner) { var request = new HttpRequestMessage(HttpMethod.Post, "/api/owners/" + owner.Id + "/delete"); Task<HttpResponseMessage> responseTask = _client.SendAsync(request); responseTask.Wait(); HttpResponseMessage response = responseTask.Result; response.EnsureSuccessStatusCode(); } private void DeleteLocalArea(LocalArea localArea) { var request = new HttpRequestMessage(HttpMethod.Post, "/api/localareas/" + localArea.Id + "/delete"); Task<HttpResponseMessage> responseTask = _client.SendAsync(request); responseTask.Wait(); HttpResponseMessage response = responseTask.Result; response.EnsureSuccessStatusCode(); } private void DeleteServiceArea(ServiceArea serviceArea) { var request = new HttpRequestMessage(HttpMethod.Post, "/api/serviceareas/" + serviceArea.Id + "/delete"); Task<HttpResponseMessage> responseTask = _client.SendAsync(request); responseTask.Wait(); HttpResponseMessage response = responseTask.Result; response.EnsureSuccessStatusCode(); } // automates the search private async Task<Owner[]> OwnerSearchHelper(string parameters) { var targetUrl = "/api/owners/search"; var request = new HttpRequestMessage(HttpMethod.Get, targetUrl + parameters); var response = await _client.SendAsync(request); // parse as JSON. var jsonString = await response.Content.ReadAsStringAsync(); // should be an array of schoolbus records. Owner[] searchresults = JsonConvert.DeserializeObject<Owner[]>(jsonString); return searchresults; } [Fact] /// <summary> /// Test the owner search. Specifically test that searches for two items on a multi-select show the expected number of results. /// </summary> /// public async void TestOwnerSearch() { /* Test plan: * 1. create 3 local areas. * 2. put 2 owners in each area. * 3. search for owners in local area 1 - should get 2 results. * 4. search for owners in local area 2 - should get 2 results. * 5. search for owners in local areas 1,2 - should get 4 results. * remove the owners * remove the local areas. */ string initialName = "InitialName"; // create 3 local areas. ServiceArea serviceArea = CreateServiceArea(initialName); LocalArea localArea1 = CreateLocalArea(serviceArea, "Local Area 1"); LocalArea localArea2 = CreateLocalArea(serviceArea, "Local Area 2"); LocalArea localArea3 = CreateLocalArea(serviceArea, "Local Area 3"); // create 2 owners in each. Owner owner1 = CreateOwner(localArea1, "Owner 1"); Owner owner2 = CreateOwner(localArea1, "Owner 2"); Owner owner3 = CreateOwner(localArea2, "Owner 3"); Owner owner4 = CreateOwner(localArea2, "Owner 4"); Owner owner5 = CreateOwner(localArea3, "Owner 5"); Owner owner6 = CreateOwner(localArea3, "Owner 6"); Owner[] searchresults = await OwnerSearchHelper("?localareas=" + localArea2.Id); Assert.Equal(searchresults.Length, 2); searchresults = await OwnerSearchHelper("?localareas=" + localArea2.Id ); Assert.Equal(searchresults.Length, 2); searchresults = await OwnerSearchHelper("?localareas=" + localArea1.Id + "%2C" + localArea2.Id); Assert.Equal(searchresults.Length, 4); searchresults = await OwnerSearchHelper("?owner=" + owner1.Id); Assert.Equal(searchresults.Length, 1); // cleanup DeleteOwner(owner1); DeleteOwner(owner2); DeleteOwner(owner3); DeleteOwner(owner4); DeleteOwner(owner5); DeleteOwner(owner6); DeleteLocalArea(localArea1); DeleteLocalArea(localArea2); DeleteLocalArea(localArea3); DeleteServiceArea(serviceArea); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using System; using System.Collections.ObjectModel; using System.Diagnostics; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal sealed class CustomTypeInfoTypeArgumentMap { private static readonly CustomTypeInfoTypeArgumentMap s_empty = new CustomTypeInfoTypeArgumentMap(); private readonly Type _typeDefinition; private readonly ReadOnlyCollection<byte> _dynamicFlags; private readonly int[] _dynamicFlagStartIndices; private readonly ReadOnlyCollection<string> _tupleElementNames; private readonly int[] _tupleElementNameStartIndices; private CustomTypeInfoTypeArgumentMap() { } private CustomTypeInfoTypeArgumentMap( Type typeDefinition, ReadOnlyCollection<byte> dynamicFlags, int[] dynamicFlagStartIndices, ReadOnlyCollection<string> tupleElementNames, int[] tupleElementNameStartIndices) { Debug.Assert(typeDefinition != null); Debug.Assert((dynamicFlags != null) == (dynamicFlagStartIndices != null)); Debug.Assert((tupleElementNames != null) == (tupleElementNameStartIndices != null)); #if DEBUG Debug.Assert(typeDefinition.IsGenericTypeDefinition); int n = typeDefinition.GetGenericArguments().Length; Debug.Assert(dynamicFlagStartIndices == null || dynamicFlagStartIndices.Length == n + 1); Debug.Assert(tupleElementNameStartIndices == null || tupleElementNameStartIndices.Length == n + 1); #endif _typeDefinition = typeDefinition; _dynamicFlags = dynamicFlags; _dynamicFlagStartIndices = dynamicFlagStartIndices; _tupleElementNames = tupleElementNames; _tupleElementNameStartIndices = tupleElementNameStartIndices; } internal static CustomTypeInfoTypeArgumentMap Create(TypeAndCustomInfo typeAndInfo) { var typeInfo = typeAndInfo.Info; if (typeInfo == null) { return s_empty; } var type = typeAndInfo.Type; Debug.Assert(type != null); if (!type.IsGenericType) { return s_empty; } ReadOnlyCollection<byte> dynamicFlags; ReadOnlyCollection<string> tupleElementNames; CustomTypeInfo.Decode(typeInfo.PayloadTypeId, typeInfo.Payload, out dynamicFlags, out tupleElementNames); if (dynamicFlags == null && tupleElementNames == null) { return s_empty; } var typeDefinition = type.GetGenericTypeDefinition(); Debug.Assert(typeDefinition != null); var dynamicFlagStartIndices = (dynamicFlags == null) ? null : GetStartIndices(type, t => 1); var tupleElementNameStartIndices = (tupleElementNames == null) ? null : GetStartIndices(type, TypeHelpers.GetTupleCardinalityIfAny); return new CustomTypeInfoTypeArgumentMap( typeDefinition, dynamicFlags, dynamicFlagStartIndices, tupleElementNames, tupleElementNameStartIndices); } internal ReadOnlyCollection<string> TupleElementNames => _tupleElementNames; internal DkmClrCustomTypeInfo SubstituteCustomTypeInfo(Type type, DkmClrCustomTypeInfo customInfo) { if (_typeDefinition == null) { return customInfo; } ReadOnlyCollection<byte> dynamicFlags = null; ReadOnlyCollection<string> tupleElementNames = null; if (customInfo != null) { CustomTypeInfo.Decode( customInfo.PayloadTypeId, customInfo.Payload, out dynamicFlags, out tupleElementNames); } var substitutedFlags = SubstituteDynamicFlags(type, dynamicFlags); var substitutedNames = SubstituteTupleElementNames(type, tupleElementNames); return CustomTypeInfo.Create(substitutedFlags, substitutedNames); } private ReadOnlyCollection<byte> SubstituteDynamicFlags(Type type, ReadOnlyCollection<byte> dynamicFlagsOpt) { var builder = ArrayBuilder<bool>.GetInstance(); int f = 0; foreach (Type curr in new TypeWalker(type)) { if (curr.IsGenericParameter && curr.DeclaringType.Equals(_typeDefinition)) { AppendRangeFor( curr, _dynamicFlags, _dynamicFlagStartIndices, DynamicFlagsCustomTypeInfo.GetFlag, builder); } else { builder.Add(DynamicFlagsCustomTypeInfo.GetFlag(dynamicFlagsOpt, f)); } f++; } var result = DynamicFlagsCustomTypeInfo.ToBytes(builder); builder.Free(); return result; } private ReadOnlyCollection<string> SubstituteTupleElementNames(Type type, ReadOnlyCollection<string> tupleElementNamesOpt) { var builder = ArrayBuilder<string>.GetInstance(); int i = 0; foreach (Type curr in new TypeWalker(type)) { if (curr.IsGenericParameter && curr.DeclaringType.Equals(_typeDefinition)) { AppendRangeFor( curr, _tupleElementNames, _tupleElementNameStartIndices, CustomTypeInfo.GetTupleElementNameIfAny, builder); } else { int n = curr.GetTupleCardinalityIfAny(); AppendRange(tupleElementNamesOpt, i, i + n, CustomTypeInfo.GetTupleElementNameIfAny, builder); i += n; } } var result = (builder.Count == 0) ? null : builder.ToImmutable(); builder.Free(); return result; } private delegate int GetIndexCount(Type type); private static int[] GetStartIndices(Type type, GetIndexCount getIndexCount) { var typeArgs = type.GetGenericArguments(); Debug.Assert(typeArgs.Length > 0); int pos = getIndexCount(type); // Consider "type" to have already been consumed. var startsBuilder = ArrayBuilder<int>.GetInstance(); foreach (var typeArg in typeArgs) { startsBuilder.Add(pos); foreach (Type curr in new TypeWalker(typeArg)) { pos += getIndexCount(curr); } } startsBuilder.Add(pos); return startsBuilder.ToArrayAndFree(); } private delegate U Map<T, U>(ReadOnlyCollection<T> collection, int index); private static void AppendRangeFor<T, U>( Type type, ReadOnlyCollection<T> collection, int[] startIndices, Map<T, U> map, ArrayBuilder<U> builder) { Debug.Assert(type.IsGenericParameter); if (startIndices == null) { return; } var genericParameterPosition = type.GenericParameterPosition; AppendRange( collection, startIndices[genericParameterPosition], startIndices[genericParameterPosition + 1], map, builder); } private static void AppendRange<T, U>( ReadOnlyCollection<T> collection, int start, int end, Map<T, U> map, ArrayBuilder<U> builder) { for (int i = start; i < end; i++) { builder.Add(map(collection, i)); } } } }
// 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.Contracts; using System.IO; using System.Net; using System.Net.Http; using System.Runtime; using System.Text; using System.Threading; using System.Threading.Tasks; namespace System.ServiceModel.Channels { internal enum HttpAbortReason { None, Aborted, TimedOut } internal static class HttpChannelUtilities { internal static class StatusDescriptionStrings { internal const string HttpContentTypeMissing = "Missing Content Type"; internal const string HttpContentTypeMismatch = "Cannot process the message because the content type '{0}' was not the expected type '{1}'."; internal const string HttpStatusServiceActivationException = "System.ServiceModel.ServiceActivationException"; } internal const string HttpStatusCodeExceptionKey = "System.ServiceModel.Channels.HttpInput.HttpStatusCode"; internal const string HttpStatusDescriptionExceptionKey = "System.ServiceModel.Channels.HttpInput.HttpStatusDescription"; internal const string HttpRequestHeadersTypeName = "System.Net.Http.Headers.HttpRequestHeaders"; internal const int ResponseStreamExcerptSize = 1024; internal const string MIMEVersionHeader = "MIME-Version"; internal const string ContentEncodingHeader = "Content-Encoding"; internal const uint WININET_E_NAME_NOT_RESOLVED = 0x80072EE7; internal const uint WININET_E_CONNECTION_RESET = 0x80072EFF; internal const uint WININET_E_INCORRECT_HANDLE_STATE = 0x80072EF3; public static HttpResponseMessage ProcessGetResponseWebException(HttpRequestException requestException, HttpRequestMessage request, HttpAbortReason abortReason) { var inner = requestException.InnerException; if (inner != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ConvertHttpRequestException(requestException, request, abortReason)); } else { // There is no inner exception so there's not enough information to be able to convert to the correct WCF exception. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(requestException.Message, requestException)); } } public static Exception ConvertHttpRequestException(HttpRequestException exception, HttpRequestMessage request, HttpAbortReason abortReason) { Contract.Assert(exception.InnerException != null, "InnerException must be set to be able to convert"); uint hresult = (uint)exception.InnerException.HResult; switch (hresult) { // .Net Native HttpClientHandler sometimes reports an incorrect handle state when a connection is aborted, so we treat it as a connection reset error case WININET_E_INCORRECT_HANDLE_STATE: goto case WININET_E_CONNECTION_RESET; case WININET_E_CONNECTION_RESET: return new CommunicationException(SR.Format(SR.HttpReceiveFailure, request.RequestUri), exception); case WININET_E_NAME_NOT_RESOLVED: return new EndpointNotFoundException(SR.Format(SR.EndpointNotFound, request.RequestUri.AbsoluteUri), exception); default: return new CommunicationException(exception.Message, exception); } } internal static Exception CreateUnexpectedResponseException(HttpResponseMessage response) { string statusDescription = response.ReasonPhrase; if (string.IsNullOrEmpty(statusDescription)) statusDescription = response.StatusCode.ToString(); return TraceResponseException( new ProtocolException(SR.Format(SR.UnexpectedHttpResponseCode, (int)response.StatusCode, statusDescription))); } internal static string GetResponseStreamExcerptString(Stream responseStream, ref int bytesToRead) { long bufferSize = bytesToRead; if (bufferSize < 0 || bufferSize > ResponseStreamExcerptSize) { bufferSize = ResponseStreamExcerptSize; } byte[] responseBuffer = Fx.AllocateByteArray(checked((int)bufferSize)); bytesToRead = responseStream.Read(responseBuffer, 0, (int)bufferSize); responseStream.Dispose(); return Encoding.UTF8.GetString(responseBuffer, 0, bytesToRead); } internal static Exception TraceResponseException(Exception exception) { return exception; } internal static ProtocolException CreateHttpProtocolException(string message, HttpStatusCode statusCode, string statusDescription) { ProtocolException exception = new ProtocolException(message); exception.Data.Add(HttpChannelUtilities.HttpStatusCodeExceptionKey, statusCode); if (statusDescription != null && statusDescription.Length > 0) { exception.Data.Add(HttpChannelUtilities.HttpStatusDescriptionExceptionKey, statusDescription); } return exception; } } internal class PreReadStream : DelegatingStream { private byte[] _preReadBuffer; public PreReadStream(Stream stream, byte[] preReadBuffer) : base(stream) { _preReadBuffer = preReadBuffer; } private bool ReadFromBuffer(byte[] buffer, int offset, int count, out int bytesRead) { if (_preReadBuffer != null) { if (buffer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("buffer"); } if (offset >= buffer.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", offset, SR.Format(SR.OffsetExceedsBufferBound, buffer.Length - 1))); } if (count < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", count, SR.ValueMustBeNonNegative)); } if (count == 0) { bytesRead = 0; } else { buffer[offset] = _preReadBuffer[0]; _preReadBuffer = null; bytesRead = 1; } return true; } bytesRead = -1; return false; } public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { int bytesRead; if (ReadFromBuffer(buffer, offset, count, out bytesRead)) { return Task.FromResult<int>(bytesRead); } return base.ReadAsync(buffer, offset, count, cancellationToken); } public override int Read(byte[] buffer, int offset, int count) { int bytesRead; if (ReadFromBuffer(buffer, offset, count, out bytesRead)) { return bytesRead; } return base.Read(buffer, offset, count); } public override int ReadByte() { if (_preReadBuffer != null) { byte[] tempBuffer = new byte[1]; int bytesRead; if (ReadFromBuffer(tempBuffer, 0, 1, out bytesRead)) { return tempBuffer[0]; } } return base.ReadByte(); } } }
/* * Copyright (c) 2006, Clutch, Inc. * Original Author: Jeff Cesnik * 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. * - Neither the name of the openmetaverse.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. */ using System; using System.Net; using System.Net.Sockets; using System.Threading; using log4net; using OpenMetaverse; namespace OpenSim.Region.ClientStack.LindenUDP { /// <summary> /// Base UDP server /// </summary> public abstract class OpenSimUDPBase { private static readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// This method is called when an incoming packet is received /// </summary> /// <param name="buffer">Incoming packet buffer</param> protected abstract void PacketReceived(UDPPacketBuffer buffer); /// <summary> /// Called when the base is through with the given packet /// </summary> /// <param name="packet"></param> protected abstract void SendCompleted(OutgoingPacket packet); /// <summary>UDP port to bind to in server mode</summary> protected int m_udpPort; /// <summary>Local IP address to bind to in server mode</summary> protected IPAddress m_localBindAddress; /// <summary>UDP socket, used in either client or server mode</summary> private Socket m_udpSocket; /// <summary>Flag to process packets asynchronously or synchronously</summary> private bool m_asyncPacketHandling; /// <summary>The all important shutdown flag</summary> private volatile bool m_shutdownFlag = true; /// <summary>Returns true if the server is currently listening, otherwise false</summary> public bool IsRunning { get { return !m_shutdownFlag; } } /// <summary> /// About 8MB maximum for recv pools /// </summary> private const int MAX_POOLED_BUFFERS = 2048; /// <summary> /// Pool of UDP buffers to use for receive operations /// </summary> private OpenSim.Framework.ObjectPool<UDPPacketBuffer> _recvBufferPool = new OpenSim.Framework.ObjectPool<UDPPacketBuffer>(MAX_POOLED_BUFFERS); /// <summary> /// UDP socket buffer size /// </summary> private const int UDP_BUFSZ = 32768; /// <summary> /// Default constructor /// </summary> /// <param name="bindAddress">Local IP address to bind the server to</param> /// <param name="port">Port to listening for incoming UDP packets on</param> public OpenSimUDPBase(IPAddress bindAddress, int port) { m_localBindAddress = bindAddress; m_udpPort = port; } /// <summary> /// Start the UDP server /// </summary> /// <param name="recvBufferSize">The size of the receive buffer for /// the UDP socket. This value is passed up to the operating system /// and used in the system networking stack. Use zero to leave this /// value as the default</param> /// <param name="asyncPacketHandling">Set this to true to start /// receiving more packets while current packet handler callbacks are /// still running. Setting this to false will complete each packet /// callback before the next packet is processed</param> /// <remarks>This method will attempt to set the SIO_UDP_CONNRESET flag /// on the socket to get newer versions of Windows to behave in a sane /// manner (not throwing an exception when the remote side resets the /// connection). This call is ignored on Mono where the flag is not /// necessary</remarks> public void Start(int recvBufferSize, bool asyncPacketHandling) { m_asyncPacketHandling = asyncPacketHandling; if (m_shutdownFlag) { const int SIO_UDP_CONNRESET = -1744830452; IPEndPoint ipep = new IPEndPoint(m_localBindAddress, m_udpPort); m_udpSocket = new Socket( AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); try { // This udp socket flag is not supported under mono, // so we'll catch the exception and continue m_udpSocket.IOControl(SIO_UDP_CONNRESET, new byte[] { 0 }, null); m_log.Debug("[UDPBASE]: SIO_UDP_CONNRESET flag set"); } catch (SocketException) { m_log.Debug("[UDPBASE]: SIO_UDP_CONNRESET flag not supported on this platform, ignoring"); } if (recvBufferSize != 0) { m_udpSocket.ReceiveBufferSize = recvBufferSize; } else { m_udpSocket.ReceiveBufferSize = UDP_BUFSZ; } m_udpSocket.SendBufferSize = UDP_BUFSZ; m_udpSocket.Bind(ipep); // we're not shutting down, we're starting up m_shutdownFlag = false; // kick off an async receive. The Start() method will return, the // actual receives will occur asynchronously and will be caught in // AsyncEndRecieve(). AsyncBeginReceive(); } } /// <summary> /// Stops the UDP server /// </summary> public void Stop() { if (!m_shutdownFlag) { // wait indefinitely for a writer lock. Once this is called, the .NET runtime // will deny any more reader locks, in effect blocking all other send/receive // threads. Once we have the lock, we set shutdownFlag to inform the other // threads that the socket is closed. m_shutdownFlag = true; m_udpSocket.Close(); } } private void AsyncBeginReceive() { // allocate a packet buffer //WrappedObject<UDPPacketBuffer> wrappedBuffer = Pool.CheckOut(); UDPPacketBuffer buf = _recvBufferPool.LeaseObject(); if (!m_shutdownFlag) { bool recvFromRunning = false; while (!recvFromRunning) { try { // kick off an async read m_udpSocket.BeginReceiveFrom( //wrappedBuffer.Instance.Data, buf.Data, 0, UDPPacketBuffer.BUFFER_SIZE, SocketFlags.None, ref buf.RemoteEndPoint, AsyncEndReceive, buf); recvFromRunning = true; } catch (SocketException e) { m_log.ErrorFormat("[LLUDP] SocketException thrown from UDP BeginReceiveFrom, retrying: {0}", e); } catch (Exception e) { m_log.ErrorFormat("[LLUDP] Exception thrown from UDP BeginReceiveFrom: {0}", e); //UDP is toast and will not recover. The sim is for all intents and purposes, dead. throw; } } } } /// <summary> /// Called when the packet is built and this buffer is no longer in use /// </summary> /// <param name="buffer"></param> protected void PacketBuildingFinished(UDPPacketBuffer buffer) { buffer.ResetEndpoint(); _recvBufferPool.ReturnObject(buffer); } private void AsyncEndReceive(IAsyncResult iar) { // Asynchronous receive operations will complete here through the call // to AsyncBeginReceive if (!m_shutdownFlag) { // Asynchronous mode will start another receive before the // callback for this packet is even fired. Very parallel :-) if (m_asyncPacketHandling) AsyncBeginReceive(); // get the buffer that was created in AsyncBeginReceive // this is the received data //WrappedObject<UDPPacketBuffer> wrappedBuffer = (WrappedObject<UDPPacketBuffer>)iar.AsyncState; //UDPPacketBuffer buffer = wrappedBuffer.Instance; UDPPacketBuffer buffer = (UDPPacketBuffer)iar.AsyncState; try { // get the length of data actually read from the socket, store it with the // buffer buffer.DataLength = m_udpSocket.EndReceiveFrom(iar, ref buffer.RemoteEndPoint); // call the abstract method PacketReceived(), passing the buffer that // has just been filled from the socket read. PacketReceived(buffer); } catch (Exception e) { m_log.ErrorFormat("[LLUDP] Exception thrown from UDP EndReceiveFrom: {0}", e); } finally { //wrappedBuffer.Dispose(); // Synchronous mode waits until the packet callback completes // before starting the receive to fetch another packet if (!m_asyncPacketHandling) AsyncBeginReceive(); } } } public void AsyncBeginSend(OutgoingPacket packet) { if (!m_shutdownFlag) { try { packet.AddRef(); m_udpSocket.BeginSendTo( packet.Buffer, 0, packet.DataSize, SocketFlags.None, packet.Destination, AsyncEndSend, packet); } catch (SocketException) { } catch (ObjectDisposedException) { } } } void AsyncEndSend(IAsyncResult result) { OutgoingPacket packet = (OutgoingPacket)result.AsyncState; try { m_udpSocket.EndSendTo(result); } catch (SocketException) { } catch (ObjectDisposedException) { } finally { this.SendCompleted(packet); } } } }
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace WebApplication2 { /// <summary> /// Summary description for frmAddProcedure. /// </summary> public partial class frmUpdTask : System.Web.UI.Page { private static string strURL = System.Configuration.ConfigurationSettings.AppSettings["local_url"]; private static string strDB = System.Configuration.ConfigurationSettings.AppSettings["local_db"]; public SqlConnection epsDbConn=new SqlConnection(strDB); private String Id; private string I; private int GetIndexOfLocs (string s) { return (lstLocations.Items.IndexOf (lstLocations.Items.FindByValue(s))); } private int GetIndexOfProcs (string s) { return (lstProcs.Items.IndexOf (lstProcs.Items.FindByValue(s))); } private int GetIndexOfStatus (string item) { if (btnAction.Text == "Update") { if (item.Trim() == "Planned") { return 0; } else if (item.Trim() == "Open") { return 1; } else if (item.Trim() == "Closed") { return 2; } else if (item.Trim() == "Cancelled") { return 3; } else { return 0; } } else { return 0; } } protected void Page_Load(object sender, System.EventArgs e) { Id=Request.Params["Id"]; if (!IsPostBack) { //loadLocations(); //loadProcs(); lblOrg.Text=(Session["OrgName"]).ToString(); btnAction.Text= Request.Params["btnAction"]; lblContent.Text=btnAction.Text + " Task"; txtName.Text=Request.Params["Name"]; txtStartTime.Text=Request.Params["StartTime"]; txtEndTime.Text=Request.Params["EndTime"]; /*rblStatus.SelectedIndex = GetIndexOfStatus (Request.Params["Status"]); lstProcs.SelectedIndex = GetIndexOfProcs (Request.Params["ProcId"]); if (Request.Params["btnAction"] == "Add") { lstLocations.Visible=false; lblLocs.Text="Location: " + Session["LocationName"].ToString(); } else { lstLocations.SelectedIndex= GetIndexOfLocs (Request.Params["LocId"]); }*/ } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { } #endregion private void loadLocations() { SqlCommand cmd=new SqlCommand(); cmd.Connection=this.epsDbConn; cmd.CommandType=CommandType.Text; cmd.CommandText="Select Locations.Id, Locations.Name from Locations" + " inner join Organizations on Locations.OrgId=Organizations.Id" + " Where LicenseId =" + Session["LicenseId"].ToString() + " Order by Locations.Name"; DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter (cmd); da.Fill(ds,"Locations"); lstLocations.DataSource = ds; lstLocations.DataMember= "Locations"; lstLocations.DataTextField = "Name"; lstLocations.DataValueField = "Id"; lstLocations.DataBind(); } private void loadProcs() { SqlCommand cmd=new SqlCommand(); cmd.Connection=this.epsDbConn; cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="eps_RetrieveProcs"; cmd.Parameters.Add ("@DomainId", SqlDbType.Int); cmd.Parameters["@DomainId"].Value=Session["DomainId"].ToString(); cmd.Parameters.Add ("@Visibility", SqlDbType.Int); cmd.Parameters["@Visibility"].Value="1"; DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter (cmd); da.Fill(ds,"Processes"); lstProcs.DataSource = ds; lstProcs.DataMember= "Processes"; lstProcs.DataTextField = "Name"; lstProcs.DataValueField = "Id"; lstProcs.DataBind(); } protected void btnAction_Click(object sender, System.EventArgs e) { /*if (btnAction.Text == "Update") //{ //try //{*/ SqlCommand cmd = new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="eps_UpdateTask2"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add ("@Id",SqlDbType.Int); cmd.Parameters["@Id"].Value=Int32.Parse(Id); cmd.Parameters.Add ("@Name",SqlDbType.NVarChar); cmd.Parameters["@Name"].Value=txtName.Text; cmd.Parameters.Add ("@StartTime",SqlDbType.DateTime); if (txtStartTime.Text != "") cmd.Parameters["@StartTime"].Value=txtStartTime.Text; else cmd.Parameters["@StartTime"].Value = null; cmd.Parameters.Add ("@EndTime",SqlDbType.DateTime); if (txtEndTime.Text != "") cmd.Parameters["@EndTime"].Value=txtEndTime.Text; else cmd.Parameters["@EndTime"].Value = null; cmd.Parameters.Add ("@Status",SqlDbType.NVarChar); cmd.Parameters["@Status"].Value=rblStatus.SelectedItem.Value; cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); Done(); //} /*catch (SqlException err) { if (err.Message.StartsWith ("String was not recognized as a valid DateTime.")) lblContent.Text = "Please enter Start and End Time in form mm/dd/yy (e.g. 10/11/08."; else lblContent.Text = err.Message; } } else if (btnAction.Text == "Add") { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; //cmd.CommandText="eps_AddActivation"; cmd.CommandText = EPSBase.headingOrg(1); cmd.Connection=this.epsDbConn; cmd.Parameters.Add ("@Name",SqlDbType.NVarChar); cmd.Parameters["@Name"].Value= txtName.Text; cmd.Parameters.Add ("@StartTime",SqlDbType.DateTime); if (txtStartTime.Text != "") cmd.Parameters["@StartTime"].Value=txtStartTime.Text; else cmd.Parameters["@StartTime"].Value = null; cmd.Parameters.Add ("@EndTime",SqlDbType.DateTime); if (txtEndTime.Text != "") cmd.Parameters["@EndTime"].Value=txtEndTime.Text; else cmd.Parameters["@EndTime"].Value = null; cmd.Parameters.Add ("@Status",SqlDbType.NVarChar); cmd.Parameters["@Status"].Value=rblStatus.SelectedItem.Value; cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); if (Session["CallerUpdTask"].ToString() == "frmTasks") { addPeople(); }*/ Done(); //} } private void addPeople() { SqlCommand cmd1=new SqlCommand(); cmd1.Connection=this.epsDbConn; cmd1.CommandType=CommandType.Text; cmd1.CommandText="Select Max(Id) from Tasks " + " Where ServiceId =" + Session["ServiceId"].ToString(); cmd1.Connection.Open(); I=cmd1.ExecuteScalar().ToString(); cmd1.Connection.Close(); SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="eps_UpdateTaskPeopleAuto"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add ("@TaskId",SqlDbType.Int); cmd.Parameters["@TaskId"].Value= I; cmd.Parameters.Add ("@ServiceId",SqlDbType.Int); cmd.Parameters["@ServiceId"].Value= Session["ServiceId"].ToString(); cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } private void Done() { Response.Redirect (strURL + Session["CallerUpdTask"].ToString() + ".aspx?"); } protected void btnCancel_Click(object sender, System.EventArgs e) { Done(); } protected void btnLoc_Click(object sender, System.EventArgs e) { /*Session["CUpdLocs"]="frmUpdTask"; Response.Redirect (strURL + "frmUpdLoc.aspx?" + "&btnAction=" + "Add");*/ } protected void btnDetails_Click(object sender, System.EventArgs e) { Session["CallerTaskDetail"]="frmUpdTask"; Response.Redirect (strURL + "frmTaskDetail.aspx?" //+ "&ServiceName=" + e.Item.Cells[1].Text //+ "&Start=" + e.Item.Cells[2].Text //+ "&End=" + e.Item.Cells[3].Text //+ "&RegStatus=" + e.Item.Cells[4].Text + "&Desc=" //+ "&StaffClient=" + e.Item.Cells[8].Text //+ "&TaskName=" + e.Item.Cells[6].Text //+ "&EventName=" + e.Item.Cells[11].Text //+ "&LicOrg=" + e.Item.Cells[12].Text //+ "&MgrOrg=" + e.Item.Cells[12].Text //+ "&LicId=" + e.Item.Cells[14].Text //+ "&Status=" + e.Item.Cells[15].Text // //+ "&Loc=" + e.Item.Cells[16].Text //+ "&LocAddress=" + e.Item.Cells[17].Text //+ "&Comment=" + e.Item.Cells[18].Text ); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Versions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.TodoComments { internal partial class TodoCommentIncrementalAnalyzer : IIncrementalAnalyzer { public const string Name = "Todo Comment Document Worker"; private readonly TodoCommentIncrementalAnalyzerProvider _owner; private readonly Workspace _workspace; private readonly IOptionService _optionService; private readonly TodoCommentTokens _todoCommentTokens; private readonly TodoCommentState _state; public TodoCommentIncrementalAnalyzer(Workspace workspace, IOptionService optionService, TodoCommentIncrementalAnalyzerProvider owner, TodoCommentTokens todoCommentTokens) { _workspace = workspace; _optionService = optionService; _owner = owner; _todoCommentTokens = todoCommentTokens; _state = new TodoCommentState(); } public Task DocumentResetAsync(Document document, CancellationToken cancellationToken) { // remove cache _state.Remove(document.Id); return _state.PersistAsync(document, new Data(VersionStamp.Default, VersionStamp.Default, ImmutableArray<ITaskItem>.Empty), cancellationToken); } public async Task AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken) { Contract.ThrowIfFalse(document.IsFromPrimaryBranch()); // it has an assumption that this will not be called concurrently for same document. // in fact, in current design, it won't be even called concurrently for different documents. // but, can be called concurrently for different documents in future if we choose to. if (!_optionService.GetOption(InternalFeatureOnOffOptions.TodoComments)) { return; } // use tree version so that things like compiler option changes are considered var textVersion = await document.GetTextVersionAsync(cancellationToken).ConfigureAwait(false); var syntaxVersion = await document.GetSyntaxVersionAsync(cancellationToken).ConfigureAwait(false); var existingData = await _state.TryGetExistingDataAsync(document, cancellationToken).ConfigureAwait(false); if (existingData != null) { // check whether we can use the data as it is (can happen when re-using persisted data from previous VS session) if (CheckVersions(document, textVersion, syntaxVersion, existingData)) { Contract.Requires(_workspace == document.Project.Solution.Workspace); RaiseTaskListUpdated(_workspace, document.Id, existingData.Items); return; } } var service = document.GetLanguageService<ITodoCommentService>(); if (service == null) { return; } var comments = await service.GetTodoCommentsAsync(document, _todoCommentTokens.GetTokens(_workspace), cancellationToken).ConfigureAwait(false); var items = await CreateItemsAsync(document, comments, cancellationToken).ConfigureAwait(false); var data = new Data(textVersion, syntaxVersion, items); await _state.PersistAsync(document, data, cancellationToken).ConfigureAwait(false); // * NOTE * cancellation can't throw after this point. if (existingData == null || existingData.Items.Length > 0 || data.Items.Length > 0) { Contract.Requires(_workspace == document.Project.Solution.Workspace); RaiseTaskListUpdated(_workspace, document.Id, data.Items); } } private async Task<ImmutableArray<ITaskItem>> CreateItemsAsync(Document document, IList<TodoComment> comments, CancellationToken cancellationToken) { var items = ImmutableArray.CreateBuilder<ITaskItem>(); if (comments != null) { var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var syntaxTree = document.SupportsSyntaxTree ? await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false) : null; foreach (var comment in comments) { items.Add(CreateItem(document, text, syntaxTree, comment)); } } return items.ToImmutable(); } private ITaskItem CreateItem(Document document, SourceText text, SyntaxTree tree, TodoComment comment) { var textSpan = new TextSpan(comment.Position, 0); var location = tree == null ? Location.Create(document.FilePath, textSpan, text.Lines.GetLinePositionSpan(textSpan)) : tree.GetLocation(textSpan); var originalLineInfo = location.GetLineSpan(); var mappedLineInfo = location.GetMappedLineSpan(); return new TodoTaskItem( comment.Descriptor.Priority, comment.Message, document.Project.Solution.Workspace, document.Id, mappedLine: mappedLineInfo.StartLinePosition.Line, originalLine: originalLineInfo.StartLinePosition.Line, mappedColumn: mappedLineInfo.StartLinePosition.Character, originalColumn: originalLineInfo.StartLinePosition.Character, mappedFilePath: mappedLineInfo.GetMappedFilePathIfExist(), originalFilePath: document.FilePath); } public ImmutableArray<ITaskItem> GetTodoItems(Workspace workspace, DocumentId id, CancellationToken cancellationToken) { var document = workspace.CurrentSolution.GetDocument(id); if (document == null) { return ImmutableArray<ITaskItem>.Empty; } // TODO let's think about what to do here. for now, let call it synchronously. also, there is no actual asynch-ness for the // TryGetExistingDataAsync, API just happen to be async since our persistent API is async API. but both caller and implementor are // actually not async. var existingData = _state.TryGetExistingDataAsync(document, cancellationToken).WaitAndGetResult(cancellationToken); if (existingData == null) { return ImmutableArray<ITaskItem>.Empty; } return existingData.Items; } private static bool CheckVersions(Document document, VersionStamp textVersion, VersionStamp syntaxVersion, Data existingData) { // first check full version to see whether we can reuse data in same session, if we can't, check timestamp only version to see whether // we can use it cross-session. return document.CanReusePersistedTextVersion(textVersion, existingData.TextVersion) && document.CanReusePersistedSyntaxTreeVersion(syntaxVersion, existingData.SyntaxVersion); } internal ImmutableArray<ITaskItem> GetItems_TestingOnly(DocumentId documentId) { return _state.GetItems_TestingOnly(documentId); } private void RaiseTaskListUpdated(Workspace workspace, DocumentId documentId, ImmutableArray<ITaskItem> items) { if (_owner != null) { _owner.RaiseTaskListUpdated(documentId, workspace, documentId.ProjectId, documentId, items); } } public void RemoveDocument(DocumentId documentId) { _state.Remove(documentId); RaiseTaskListUpdated(_workspace, documentId, ImmutableArray<ITaskItem>.Empty); } public bool NeedsReanalysisOnOptionChanged(object sender, OptionChangedEventArgs e) { return e.Option == TodoCommentOptions.TokenList; } private class Data { public readonly VersionStamp TextVersion; public readonly VersionStamp SyntaxVersion; public readonly ImmutableArray<ITaskItem> Items; public Data(VersionStamp textVersion, VersionStamp syntaxVersion, ImmutableArray<ITaskItem> items) { this.TextVersion = textVersion; this.SyntaxVersion = syntaxVersion; this.Items = items; } } #region not used public Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public Task DocumentOpenAsync(Document document, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public Task DocumentCloseAsync(Document document, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public Task AnalyzeProjectAsync(Project project, bool semanticsChanged, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public void RemoveProject(ProjectId projectId) { } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace WebApiHttpBatchServer.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// // Copyright (c) 2008-2012, Kenneth Bell // Copyright (c) 2017, Bianco Veigel // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.IO; using DiscUtils.Internal; using DiscUtils.Streams; namespace DiscUtils.Vhdx { /// <summary> /// Represents a single .VHDX file. /// </summary> public sealed class DiskImageFile : VirtualDiskLayer { /// <summary> /// Which VHDX header is active. /// </summary> private int _activeHeader; /// <summary> /// Block Allocation Table for disk content. /// </summary> private Stream _batStream; /// <summary> /// The object that can be used to locate relative file paths. /// </summary> private readonly FileLocator _fileLocator; /// <summary> /// The file name of this VHDX. /// </summary> private readonly string _fileName; /// <summary> /// The stream containing the VHDX file. /// </summary> private Stream _fileStream; /// <summary> /// Table of all free space in the file. /// </summary> private FreeSpaceTable _freeSpace; /// <summary> /// Value of the active VHDX header. /// </summary> private VhdxHeader _header; /// <summary> /// The stream containing the logical VHDX content and metadata allowing for log replay. /// </summary> private Stream _logicalStream; /// <summary> /// VHDX metadata region content. /// </summary> private Metadata _metadata; /// <summary> /// Indicates if this object controls the lifetime of the stream. /// </summary> private readonly Ownership _ownsStream; /// <summary> /// The set of VHDX regions. /// </summary> private RegionTable _regionTable; /// <summary> /// Initializes a new instance of the DiskImageFile class. /// </summary> /// <param name="stream">The stream to interpret.</param> public DiskImageFile(Stream stream) { _fileStream = stream; Initialize(); } /// <summary> /// Initializes a new instance of the DiskImageFile class. /// </summary> /// <param name="stream">The stream to interpret.</param> /// <param name="ownsStream">Indicates if the new instance should control the lifetime of the stream.</param> public DiskImageFile(Stream stream, Ownership ownsStream) { _fileStream = stream; _ownsStream = ownsStream; Initialize(); } /// <summary> /// Initializes a new instance of the DiskImageFile class. /// </summary> /// <param name="path">The file path to open.</param> /// <param name="access">Controls how the file can be accessed.</param> public DiskImageFile(string path, FileAccess access) : this(new LocalFileLocator(Path.GetDirectoryName(path)), Path.GetFileName(path), access) {} internal DiskImageFile(FileLocator locator, string path, Stream stream, Ownership ownsStream) : this(stream, ownsStream) { _fileLocator = locator.GetRelativeLocator(locator.GetDirectoryFromPath(path)); _fileName = locator.GetFileFromPath(path); } internal DiskImageFile(FileLocator locator, string path, FileAccess access) { FileShare share = access == FileAccess.Read ? FileShare.Read : FileShare.None; _fileStream = locator.Open(path, FileMode.Open, access, share); _ownsStream = Ownership.Dispose; try { _fileLocator = locator.GetRelativeLocator(locator.GetDirectoryFromPath(path)); _fileName = locator.GetFileFromPath(path); Initialize(); } catch { _fileStream.Dispose(); throw; } } internal override long Capacity { get { return (long)_metadata.DiskSize; } } /// <summary> /// Gets the extent that comprises this file. /// </summary> public override IList<VirtualDiskExtent> Extents { get { List<VirtualDiskExtent> result = new List<VirtualDiskExtent>(); result.Add(new DiskExtent(this)); return result; } } /// <summary> /// Gets the full path to this disk layer, or empty string. /// </summary> public override string FullPath { get { if (_fileLocator != null && _fileName != null) { return _fileLocator.GetFullPath(_fileName); } return string.Empty; } } /// <summary> /// Gets the geometry of the virtual disk. /// </summary> public override Geometry Geometry { get { return Geometry.FromCapacity(Capacity, (int)_metadata.LogicalSectorSize); } } /// <summary> /// Gets detailed information about the VHDX file. /// </summary> public DiskImageFileInfo Information { get { _fileStream.Position = 0; FileHeader fileHeader = StreamUtilities.ReadStruct<FileHeader>(_fileStream); _fileStream.Position = 64 * Sizes.OneKiB; VhdxHeader vhdxHeader1 = StreamUtilities.ReadStruct<VhdxHeader>(_fileStream); _fileStream.Position = 128 * Sizes.OneKiB; VhdxHeader vhdxHeader2 = StreamUtilities.ReadStruct<VhdxHeader>(_fileStream); LogSequence activeLogSequence = FindActiveLogSequence(); return new DiskImageFileInfo(fileHeader, vhdxHeader1, vhdxHeader2, _regionTable, _metadata, activeLogSequence); } } /// <summary> /// Gets a value indicating if the layer only stores meaningful sectors. /// </summary> public override bool IsSparse { get { return true; } } /// <summary> /// Gets the logical sector size of the virtual disk. /// </summary> public long LogicalSectorSize { get { return _metadata.LogicalSectorSize; } } /// <summary> /// Gets a value indicating whether the file is a differencing disk. /// </summary> public override bool NeedsParent { get { return (_metadata.FileParameters.Flags & FileParametersFlags.HasParent) != 0; } } /// <summary> /// Gets the unique id of the parent disk. /// </summary> public Guid ParentUniqueId { get { if ((_metadata.FileParameters.Flags & FileParametersFlags.HasParent) == 0) { return Guid.Empty; } string parentLinkage; if (_metadata.ParentLocator.Entries.TryGetValue("parent_linkage", out parentLinkage)) { return new Guid(parentLinkage); } return Guid.Empty; } } internal override FileLocator RelativeFileLocator { get { return _fileLocator; } } internal long StoredSize { get { return _fileStream.Length; } } /// <summary> /// Gets the unique id of this file. /// </summary> public Guid UniqueId { get { return _header.DataWriteGuid; } } /// <summary> /// Initializes a stream as a fixed-sized VHDX file. /// </summary> /// <param name="stream">The stream to initialize.</param> /// <param name="ownsStream">Indicates if the new instance controls the lifetime of the stream.</param> /// <param name="capacity">The desired capacity of the new disk.</param> /// <returns>An object that accesses the stream as a VHDX file.</returns> public static DiskImageFile InitializeFixed(Stream stream, Ownership ownsStream, long capacity) { return InitializeFixed(stream, ownsStream, capacity, null); } /// <summary> /// Initializes a stream as a fixed-sized VHDX file. /// </summary> /// <param name="stream">The stream to initialize.</param> /// <param name="ownsStream">Indicates if the new instance controls the lifetime of the stream.</param> /// <param name="capacity">The desired capacity of the new disk.</param> /// <param name="geometry">The desired geometry of the new disk, or <c>null</c> for default.</param> /// <returns>An object that accesses the stream as a VHDX file.</returns> public static DiskImageFile InitializeFixed(Stream stream, Ownership ownsStream, long capacity, Geometry geometry) { InitializeFixedInternal(stream, capacity, geometry); return new DiskImageFile(stream, ownsStream); } /// <summary> /// Initializes a stream as a dynamically-sized VHDX file. /// </summary> /// <param name="stream">The stream to initialize.</param> /// <param name="ownsStream">Indicates if the new instance controls the lifetime of the stream.</param> /// <param name="capacity">The desired capacity of the new disk.</param> /// <returns>An object that accesses the stream as a VHDX file.</returns> public static DiskImageFile InitializeDynamic(Stream stream, Ownership ownsStream, long capacity) { InitializeDynamicInternal(stream, capacity, FileParameters.DefaultDynamicBlockSize); return new DiskImageFile(stream, ownsStream); } /// <summary> /// Initializes a stream as a dynamically-sized VHDX file. /// </summary> /// <param name="stream">The stream to initialize.</param> /// <param name="ownsStream">Indicates if the new instance controls the lifetime of the stream.</param> /// <param name="capacity">The desired capacity of the new disk.</param> /// <param name="blockSize">The size of each block (unit of allocation).</param> /// <returns>An object that accesses the stream as a VHDX file.</returns> public static DiskImageFile InitializeDynamic(Stream stream, Ownership ownsStream, long capacity, long blockSize) { InitializeDynamicInternal(stream, capacity, blockSize); return new DiskImageFile(stream, ownsStream); } /// <summary> /// Initializes a stream as a differencing disk VHDX file. /// </summary> /// <param name="stream">The stream to initialize.</param> /// <param name="ownsStream">Indicates if the new instance controls the lifetime of the stream.</param> /// <param name="parent">The disk this file is a different from.</param> /// <param name="parentAbsolutePath">The full path to the parent disk.</param> /// <param name="parentRelativePath">The relative path from the new disk to the parent disk.</param> /// <param name="parentModificationTimeUtc">The time the parent disk's file was last modified (from file system).</param> /// <returns>An object that accesses the stream as a VHDX file.</returns> public static DiskImageFile InitializeDifferencing( Stream stream, Ownership ownsStream, DiskImageFile parent, string parentAbsolutePath, string parentRelativePath, DateTime parentModificationTimeUtc) { InitializeDifferencingInternal(stream, parent, parentAbsolutePath, parentRelativePath, parentModificationTimeUtc); return new DiskImageFile(stream, ownsStream); } /// <summary> /// Opens an existing region within the VHDX file. /// </summary> /// <param name="region">Identifier for the region to open.</param> /// <returns>A stream containing the region data.</returns> /// <remarks>Regions are an extension mechanism in VHDX - with some regions defined by /// the VHDX specification to hold metadata and the block allocation data.</remarks> public Stream OpenRegion(Guid region) { RegionEntry metadataRegion = _regionTable.Regions[region]; return new SubStream(_logicalStream, metadataRegion.FileOffset, metadataRegion.Length); } /// <summary> /// Opens the content of the disk image file as a stream. /// </summary> /// <param name="parent">The parent file's content (if any).</param> /// <param name="ownsParent">Whether the created stream assumes ownership of parent stream.</param> /// <returns>The new content stream.</returns> public override SparseStream OpenContent(SparseStream parent, Ownership ownsParent) { return DoOpenContent(parent, ownsParent); } /// <summary> /// Gets the location of the parent file, given a base path. /// </summary> /// <returns>Array of candidate file locations.</returns> public override string[] GetParentLocations() { return GetParentLocations(_fileLocator); } /// <summary> /// Gets the location of the parent file, given a base path. /// </summary> /// <param name="basePath">The full path to this file.</param> /// <returns>Array of candidate file locations.</returns> [Obsolete("Use GetParentLocations() by preference")] public string[] GetParentLocations(string basePath) { return GetParentLocations(new LocalFileLocator(basePath)); } internal static DiskImageFile InitializeFixed(FileLocator locator, string path, long capacity, Geometry geometry) { DiskImageFile result = null; Stream stream = locator.Open(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None); try { InitializeFixedInternal(stream, capacity, geometry); result = new DiskImageFile(locator, path, stream, Ownership.Dispose); stream = null; } finally { if (stream != null) { stream.Dispose(); } } return result; } internal static DiskImageFile InitializeDynamic(FileLocator locator, string path, long capacity, long blockSize) { DiskImageFile result = null; Stream stream = locator.Open(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None); try { InitializeDynamicInternal(stream, capacity, blockSize); result = new DiskImageFile(locator, path, stream, Ownership.Dispose); stream = null; } finally { if (stream != null) { stream.Dispose(); } } return result; } internal DiskImageFile CreateDifferencing(FileLocator fileLocator, string path) { Stream stream = fileLocator.Open(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None); string fullPath = _fileLocator.GetFullPath(_fileName); string relativePath = fileLocator.MakeRelativePath(_fileLocator, _fileName); DateTime lastWriteTime = _fileLocator.GetLastWriteTimeUtc(_fileName); InitializeDifferencingInternal(stream, this, fullPath, relativePath, lastWriteTime); return new DiskImageFile(fileLocator, path, stream, Ownership.Dispose); } internal MappedStream DoOpenContent(SparseStream parent, Ownership ownsParent) { SparseStream theParent = parent; Ownership theOwnership = ownsParent; if (parent == null) { theParent = new ZeroStream(Capacity); theOwnership = Ownership.Dispose; } ContentStream contentStream = new ContentStream(SparseStream.FromStream(_logicalStream, Ownership.None), _fileStream.CanWrite, _batStream, _freeSpace, _metadata, Capacity, theParent, theOwnership); return new AligningStream(contentStream, Ownership.Dispose, (int)_metadata.LogicalSectorSize); } /// <summary> /// Disposes of underlying resources. /// </summary> /// <param name="disposing">Set to <c>true</c> if called within Dispose(), /// else <c>false</c>.</param> protected override void Dispose(bool disposing) { try { if (disposing) { if (_logicalStream != _fileStream && _logicalStream != null) { _logicalStream.Dispose(); } _logicalStream = null; if (_ownsStream == Ownership.Dispose && _fileStream != null) { _fileStream.Dispose(); } _fileStream = null; } } finally { base.Dispose(disposing); } } private static void InitializeFixedInternal(Stream stream, long capacity, Geometry geometry) { throw new NotImplementedException(); } private static void InitializeDynamicInternal(Stream stream, long capacity, long blockSize) { if (blockSize < Sizes.OneMiB || blockSize > Sizes.OneMiB * 256 || !Utilities.IsPowerOfTwo(blockSize)) { throw new ArgumentOutOfRangeException(nameof(blockSize), blockSize, "BlockSize must be a power of 2 between 1MB and 256MB"); } int logicalSectorSize = 512; int physicalSectorSize = 4096; long chunkRatio = 0x800000L * logicalSectorSize / blockSize; long dataBlocksCount = MathUtilities.Ceil(capacity, blockSize); long sectorBitmapBlocksCount = MathUtilities.Ceil(dataBlocksCount, chunkRatio); long totalBatEntriesDynamic = dataBlocksCount + (dataBlocksCount - 1) / chunkRatio; FileHeader fileHeader = new FileHeader { Creator = ".NET DiscUtils" }; long fileEnd = Sizes.OneMiB; VhdxHeader header1 = new VhdxHeader(); header1.SequenceNumber = 0; header1.FileWriteGuid = Guid.NewGuid(); header1.DataWriteGuid = Guid.NewGuid(); header1.LogGuid = Guid.Empty; header1.LogVersion = 0; header1.Version = 1; header1.LogLength = (uint)Sizes.OneMiB; header1.LogOffset = (ulong)fileEnd; header1.CalcChecksum(); fileEnd += header1.LogLength; VhdxHeader header2 = new VhdxHeader(header1); header2.SequenceNumber = 1; header2.CalcChecksum(); RegionTable regionTable = new RegionTable(); RegionEntry metadataRegion = new RegionEntry(); metadataRegion.Guid = RegionEntry.MetadataRegionGuid; metadataRegion.FileOffset = fileEnd; metadataRegion.Length = (uint)Sizes.OneMiB; metadataRegion.Flags = RegionFlags.Required; regionTable.Regions.Add(metadataRegion.Guid, metadataRegion); fileEnd += metadataRegion.Length; RegionEntry batRegion = new RegionEntry(); batRegion.Guid = RegionEntry.BatGuid; batRegion.FileOffset = 3 * Sizes.OneMiB; batRegion.Length = (uint)MathUtilities.RoundUp(totalBatEntriesDynamic * 8, Sizes.OneMiB); batRegion.Flags = RegionFlags.Required; regionTable.Regions.Add(batRegion.Guid, batRegion); fileEnd += batRegion.Length; stream.Position = 0; StreamUtilities.WriteStruct(stream, fileHeader); stream.Position = 64 * Sizes.OneKiB; StreamUtilities.WriteStruct(stream, header1); stream.Position = 128 * Sizes.OneKiB; StreamUtilities.WriteStruct(stream, header2); stream.Position = 192 * Sizes.OneKiB; StreamUtilities.WriteStruct(stream, regionTable); stream.Position = 256 * Sizes.OneKiB; StreamUtilities.WriteStruct(stream, regionTable); // Set stream to min size stream.Position = fileEnd - 1; stream.WriteByte(0); // Metadata FileParameters fileParams = new FileParameters { BlockSize = (uint)blockSize, Flags = FileParametersFlags.None }; ParentLocator parentLocator = new ParentLocator(); Stream metadataStream = new SubStream(stream, metadataRegion.FileOffset, metadataRegion.Length); Metadata metadata = Metadata.Initialize(metadataStream, fileParams, (ulong)capacity, (uint)logicalSectorSize, (uint)physicalSectorSize, null); } private static void InitializeDifferencingInternal(Stream stream, DiskImageFile parent, string parentAbsolutePath, string parentRelativePath, DateTime parentModificationTimeUtc) { throw new NotImplementedException(); } private void Initialize() { _fileStream.Position = 0; FileHeader fileHeader = StreamUtilities.ReadStruct<FileHeader>(_fileStream); if (!fileHeader.IsValid) { throw new IOException("Invalid VHDX file - file signature mismatch"); } _freeSpace = new FreeSpaceTable(_fileStream.Length); ReadHeaders(); ReplayLog(); ReadRegionTable(); ReadMetadata(); _batStream = OpenRegion(RegionTable.BatGuid); _freeSpace.Reserve(BatControlledFileExtents()); // Indicate the file is open for modification if (_fileStream.CanWrite) { _header.FileWriteGuid = Guid.NewGuid(); WriteHeader(); } } private IEnumerable<StreamExtent> BatControlledFileExtents() { _batStream.Position = 0; byte[] batData = StreamUtilities.ReadExact(_batStream, (int)_batStream.Length); uint blockSize = _metadata.FileParameters.BlockSize; long chunkSize = (1L << 23) * _metadata.LogicalSectorSize; int chunkRatio = (int)(chunkSize / _metadata.FileParameters.BlockSize); List<StreamExtent> extents = new List<StreamExtent>(); for (int i = 0; i < batData.Length; i += 8) { ulong entry = EndianUtilities.ToUInt64LittleEndian(batData, i); long filePos = (long)((entry >> 20) & 0xFFFFFFFFFFF) * Sizes.OneMiB; if (filePos != 0) { if (i % ((chunkRatio + 1) * 8) == chunkRatio * 8) { // This is a sector bitmap block (always 1MB in size) extents.Add(new StreamExtent(filePos, Sizes.OneMiB)); } else { extents.Add(new StreamExtent(filePos, blockSize)); } } } extents.Sort(); return extents; } private void ReadMetadata() { Stream regionStream = OpenRegion(RegionTable.MetadataRegionGuid); _metadata = new Metadata(regionStream); } private void ReplayLog() { _freeSpace.Reserve((long)_header.LogOffset, _header.LogLength); _logicalStream = _fileStream; // If log is empty, skip. if (_header.LogGuid == Guid.Empty) { return; } LogSequence activeLogSequence = FindActiveLogSequence(); if (activeLogSequence == null || activeLogSequence.Count == 0) { throw new IOException("Unable to replay VHDX log, suspected corrupt VHDX file"); } if (activeLogSequence.Head.FlushedFileOffset > (ulong)_logicalStream.Length) { throw new IOException("truncated VHDX file found while replaying log"); } if (activeLogSequence.Count > 1 || !activeLogSequence.Head.IsEmpty) { // However, have seen VHDX with a non-empty log with no data to replay. These are // 'safe' to open. if (!_fileStream.CanWrite) { SnapshotStream replayStream = new SnapshotStream(_fileStream, Ownership.None); replayStream.Snapshot(); _logicalStream = replayStream; } foreach (LogEntry logEntry in activeLogSequence) { if (logEntry.LogGuid != _header.LogGuid) throw new IOException("Invalid log entry in VHDX log, suspected currupt VHDX file"); if (logEntry.IsEmpty) continue; logEntry.Replay(_logicalStream); } _logicalStream.Seek((long)activeLogSequence.Head.LastFileOffset, SeekOrigin.Begin); } } private LogSequence FindActiveLogSequence() { using ( Stream logStream = new CircularStream(new SubStream(_fileStream, (long)_header.LogOffset, _header.LogLength), Ownership.Dispose)) { LogSequence candidateActiveSequence = new LogSequence(); LogEntry logEntry = null; long oldTail; long currentTail = 0; do { oldTail = currentTail; logStream.Position = currentTail; LogSequence currentSequence = new LogSequence(); while (LogEntry.TryRead(logStream, out logEntry) && logEntry.LogGuid == _header.LogGuid && (currentSequence.Count == 0 || logEntry.SequenceNumber == currentSequence.Head.SequenceNumber + 1)) { currentSequence.Add(logEntry); logEntry = null; } if (currentSequence.Count > 0 && currentSequence.Contains(currentSequence.Head.Tail) && currentSequence.HigherSequenceThan(candidateActiveSequence)) { candidateActiveSequence = currentSequence; } if (currentSequence.Count == 0) { currentTail += LogEntry.LogSectorSize; } else { currentTail = currentSequence.Head.Position + LogEntry.LogSectorSize; } currentTail = currentTail % logStream.Length; } while (currentTail > oldTail); return candidateActiveSequence; } } private void ReadRegionTable() { _fileStream.Position = 192 * Sizes.OneKiB; _regionTable = StreamUtilities.ReadStruct<RegionTable>(_fileStream); foreach (RegionEntry entry in _regionTable.Regions.Values) { if ((entry.Flags & RegionFlags.Required) != 0) { if (entry.Guid != RegionTable.BatGuid && entry.Guid != RegionTable.MetadataRegionGuid) { throw new IOException("Invalid VHDX file - unrecognised required region"); } } _freeSpace.Reserve(entry.FileOffset, entry.Length); } } private void ReadHeaders() { _freeSpace.Reserve(0, Sizes.OneMiB); _activeHeader = 0; _fileStream.Position = 64 * Sizes.OneKiB; VhdxHeader vhdxHeader1 = StreamUtilities.ReadStruct<VhdxHeader>(_fileStream); if (vhdxHeader1.IsValid) { _header = vhdxHeader1; _activeHeader = 1; } _fileStream.Position = 128 * Sizes.OneKiB; VhdxHeader vhdxHeader2 = StreamUtilities.ReadStruct<VhdxHeader>(_fileStream); if (vhdxHeader2.IsValid && (_activeHeader == 0 || _header.SequenceNumber < vhdxHeader2.SequenceNumber)) { _header = vhdxHeader2; _activeHeader = 2; } if (_activeHeader == 0) { throw new IOException("Invalid VHDX file - no valid VHDX headers found"); } } private void WriteHeader() { long otherPos; _header.SequenceNumber++; _header.CalcChecksum(); if (_activeHeader == 1) { _fileStream.Position = 128 * Sizes.OneKiB; otherPos = 64 * Sizes.OneKiB; } else { _fileStream.Position = 64 * Sizes.OneKiB; otherPos = 128 * Sizes.OneKiB; } StreamUtilities.WriteStruct(_fileStream, _header); _fileStream.Flush(); _header.SequenceNumber++; _header.CalcChecksum(); _fileStream.Position = otherPos; StreamUtilities.WriteStruct(_fileStream, _header); _fileStream.Flush(); } /// <summary> /// Gets the locations of the parent file. /// </summary> /// <param name="fileLocator">The file locator to use.</param> /// <returns>Array of candidate file locations.</returns> private string[] GetParentLocations(FileLocator fileLocator) { if (!NeedsParent) { throw new InvalidOperationException("Only differencing disks contain parent locations"); } if (fileLocator == null) { // Use working directory by default fileLocator = new LocalFileLocator(string.Empty); } List<string> paths = new List<string>(); ParentLocator locator = _metadata.ParentLocator; string value; if (locator.Entries.TryGetValue("relative_path", out value)) { paths.Add(fileLocator.ResolveRelativePath(value)); } if (locator.Entries.TryGetValue("volume_path", out value)) { paths.Add(value); } if (locator.Entries.TryGetValue("absolute_win32_path", out value)) { paths.Add(value); } return paths.ToArray(); } } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email [email protected] or visit the website www.fyiReporting.com. */ using System; using System.Xml; using System.Data; using System.Data.SqlClient; using System.Data.SqlTypes; using System.Collections; using System.Collections.Specialized; using System.Collections.Generic; using System.Text; using System.Globalization; using System.Reflection; namespace fyiReporting.RDL { ///<summary> /// Query representation against a data source. Holds the data at runtime. ///</summary> [Serializable] internal class Query : ReportLink { string _DataSourceName; // Name of the data source to execute the query against DataSourceDefn _DataSourceDefn; // the data source object the DataSourceName references. QueryCommandTypeEnum _QueryCommandType; // Indicates what type of query is contained in the CommandText Expression _CommandText; // (string) The query to execute to obtain the data for the report QueryParameters _QueryParameters; // A list of parameters that are passed to the data // source as part of the query. int _Timeout; // Number of seconds to allow the query to run before // timing out. Must be >= 0; If omitted or zero; no timeout int _RowLimit; // Number of rows to retrieve before stopping retrieval; 0 means no limit IDictionary _Columns; // QueryColumn (when SQL) internal Query(ReportDefn r, ReportLink p, XmlNode xNode) : base(r, p) { _DataSourceName=null; _QueryCommandType=QueryCommandTypeEnum.Text; _CommandText=null; _QueryParameters=null; _Timeout=0; _RowLimit=0; // Loop thru all the child nodes foreach(XmlNode xNodeLoop in xNode.ChildNodes) { if (xNodeLoop.NodeType != XmlNodeType.Element) continue; switch (xNodeLoop.Name) { case "DataSourceName": _DataSourceName = xNodeLoop.InnerText; break; case "CommandType": _QueryCommandType = fyiReporting.RDL.QueryCommandType.GetStyle(xNodeLoop.InnerText, OwnerReport.rl); break; case "CommandText": _CommandText = new Expression(r, this, xNodeLoop, ExpressionType.String); break; case "QueryParameters": _QueryParameters = new QueryParameters(r, this, xNodeLoop); break; case "Timeout": _Timeout = XmlUtil.Integer(xNodeLoop.InnerText); break; case "RowLimit": // Extension of RDL specification _RowLimit = XmlUtil.Integer(xNodeLoop.InnerText); break; default: // don't know this element - log it OwnerReport.rl.LogError(4, "Unknown Query element '" + xNodeLoop.Name + "' ignored."); break; } // end of switch } // end of foreach // Resolve the data source name to the object if (_DataSourceName == null) { r.rl.LogError(8, "DataSourceName element not specified for Query."); return; } } // Handle parsing of function in final pass override internal void FinalPass() { if (_CommandText != null) _CommandText.FinalPass(); if (_QueryParameters != null) _QueryParameters.FinalPass(); // verify the data source DataSourceDefn ds=null; if (OwnerReport.DataSourcesDefn != null && OwnerReport.DataSourcesDefn.Items != null) { ds = OwnerReport.DataSourcesDefn[_DataSourceName]; } if (ds == null) { OwnerReport.rl.LogError(8, "Query references unknown data source '" + _DataSourceName + "'"); return; } _DataSourceDefn = ds; IDbConnection cnSQL = ds.SqlConnect(null); if (cnSQL == null || _CommandText == null) return; // Treat this as a SQL statement String sql = _CommandText.EvaluateString(null, null); IDbCommand cmSQL=null; IDataReader dr=null; try { cmSQL = cnSQL.CreateCommand(); cmSQL.CommandText = AddParametersAsLiterals(null, cnSQL, sql, false); if (this._QueryCommandType == QueryCommandTypeEnum.StoredProcedure) cmSQL.CommandType = CommandType.StoredProcedure; AddParameters(null, cnSQL, cmSQL, false); dr = cmSQL.ExecuteReader(CommandBehavior.SchemaOnly); if (dr.FieldCount < 10) _Columns = new ListDictionary(); // Hashtable is overkill for small lists else _Columns = new Hashtable(dr.FieldCount); for (int i=0; i < dr.FieldCount; i++) { QueryColumn qc = new QueryColumn(i, dr.GetName(i), Type.GetTypeCode(dr.GetFieldType(i)) ); try { _Columns.Add(qc.colName, qc); } catch // name has already been added to list: { // According to the RDL spec SQL names are matched by Name not by relative // position: this seems wrong to me and causes this problem; but // user can fix by using "as" keyword to name columns in Select // e.g. Select col as "col1", col as "col2" from tableA OwnerReport.rl.LogError(8, String.Format("Column '{0}' is not uniquely defined within the SQL Select columns.", qc.colName)); } } } catch (Exception e) { OwnerReport.rl.LogError(4, "SQL Exception during report compilation: " + e.Message + "\r\nSQL: " + sql); } finally { if (cmSQL != null) { cmSQL.Dispose(); if (dr != null) dr.Close(); } } return; } internal bool GetData(Report rpt, Fields flds, Filters f) { Rows uData = this.GetMyUserData(rpt); if (uData != null) { this.SetMyData(rpt, uData); return uData.Data == null || uData.Data.Count == 0 ? false : true; } // Treat this as a SQL statement DataSourceDefn ds = _DataSourceDefn; if (ds == null || _CommandText == null) { this.SetMyData(rpt, null); return false; } IDbConnection cnSQL = ds.SqlConnect(rpt); if (cnSQL == null) { this.SetMyData(rpt, null); return false; } Rows _Data = new Rows(rpt, null,null,null); // no sorting and grouping at base data String sql = _CommandText.EvaluateString(rpt, null); IDbCommand cmSQL=null; IDataReader dr=null; try { cmSQL = cnSQL.CreateCommand(); cmSQL.CommandText = AddParametersAsLiterals(rpt, cnSQL, sql, true); if (this._QueryCommandType == QueryCommandTypeEnum.StoredProcedure) cmSQL.CommandType = CommandType.StoredProcedure; if (this._Timeout > 0) cmSQL.CommandTimeout = this._Timeout; AddParameters(rpt, cnSQL, cmSQL, true); dr = cmSQL.ExecuteReader(CommandBehavior.SingleResult); List<Row> ar = new List<Row>(); _Data.Data = ar; int rowCount=0; int maxRows = _RowLimit > 0? _RowLimit: int.MaxValue; int fieldCount = flds.Items.Count; // Determine the query column number for each field int[] qcn = new int[flds.Items.Count]; foreach (Field fld in flds) { qcn[fld.ColumnNumber] = -1; if (fld.Value != null) continue; try { qcn[fld.ColumnNumber] = dr.GetOrdinal(fld.DataField); } catch { qcn[fld.ColumnNumber] = -1; } } while (dr.Read()) { Row or = new Row(_Data, fieldCount); foreach (Field fld in flds) { if (qcn[fld.ColumnNumber] != -1) { or.Data[fld.ColumnNumber] = dr.GetValue(qcn[fld.ColumnNumber]); } } // Apply the filters if (f == null || f.Apply(rpt, or)) { or.RowNumber = rowCount; // rowCount++; ar.Add(or); } if (--maxRows <= 0) // don't retrieve more than max break; } ar.TrimExcess(); // free up any extraneous space; can be sizeable for large # rows if (f != null) f.ApplyFinalFilters(rpt, _Data, false); //#if DEBUG // rpt.rl.LogError(4, "Rows Read:" + ar.Count.ToString() + " SQL:" + sql ); //#endif } catch (Exception e) { rpt.rl.LogError(8, "SQL Exception" + e.Message + "\r\n" + e.StackTrace); } finally { if (cmSQL != null) { cmSQL.Dispose(); if (dr != null) dr.Close(); } } this.SetMyData(rpt, _Data); return _Data == null || _Data.Data == null || _Data.Data.Count == 0 ? false : true; } // Obtain the data from the XML internal bool GetData(Report rpt, string xmlData, Fields flds, Filters f) { Rows uData = this.GetMyUserData(rpt); if (uData != null) { this.SetMyData(rpt, uData); return uData.Data == null || uData.Data.Count == 0? false: true; } int fieldCount = flds.Items.Count; XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = false; doc.LoadXml(xmlData); XmlNode xNode; xNode = doc.LastChild; if (xNode == null || !(xNode.Name == "Rows" || xNode.Name == "fyi:Rows")) { throw new Exception("Error: XML Data must contain top level rows."); } Rows _Data = new Rows(rpt, null,null,null); List<Row> ar = new List<Row>(); _Data.Data = ar; int rowCount=0; foreach(XmlNode xNodeRow in xNode.ChildNodes) { if (xNodeRow.NodeType != XmlNodeType.Element) continue; if (xNodeRow.Name != "Row") continue; Row or = new Row(_Data, fieldCount); foreach (XmlNode xNodeColumn in xNodeRow.ChildNodes) { Field fld = (Field) (flds.Items[xNodeColumn.Name]); // Find the column if (fld == null) continue; // Extraneous data is ignored TypeCode tc = fld.qColumn != null? fld.qColumn.colType: fld.Type; if (xNodeColumn.InnerText == null || xNodeColumn.InnerText.Length == 0) or.Data[fld.ColumnNumber] = null; else if (tc == TypeCode.String) or.Data[fld.ColumnNumber] = xNodeColumn.InnerText; else if (tc == TypeCode.DateTime) { try { or.Data[fld.ColumnNumber] = Convert.ToDateTime(xNodeColumn.InnerText, System.Globalization.DateTimeFormatInfo.InvariantInfo); } catch // all conversion errors result in a null value { or.Data[fld.ColumnNumber] = null; } } else { try { or.Data[fld.ColumnNumber] = Convert.ChangeType(xNodeColumn.InnerText, tc, NumberFormatInfo.InvariantInfo); } catch // all conversion errors result in a null value { or.Data[fld.ColumnNumber] = null; } } } // Apply the filters if (f == null || f.Apply(rpt, or)) { or.RowNumber = rowCount; // rowCount++; ar.Add(or); } } ar.TrimExcess(); // free up any extraneous space; can be sizeable for large # rows if (f != null) f.ApplyFinalFilters(rpt, _Data, false); SetMyData(rpt, _Data); return _Data == null || _Data.Data == null || _Data.Data.Count == 0 ? false : true; } internal void SetData(Report rpt, IEnumerable ie, Fields flds, Filters f) { if (ie == null) // Does user want to remove user data? { SetMyUserData(rpt, null); return; } Rows rows = new Rows(rpt, null,null,null); // no sorting and grouping at base data List<Row> ar = new List<Row>(); rows.Data = ar; int rowCount=0; int maxRows = _RowLimit > 0? _RowLimit: int.MaxValue; int fieldCount = flds.Items.Count; foreach (object dt in ie) { // Get the type. Type myType = dt.GetType(); // Build the row Row or = new Row(rows, fieldCount); // Go thru each field and try to obtain a value foreach (Field fld in flds) { // Get the type and fields of FieldInfoClass. FieldInfo fi = myType.GetField(fld.Name.Nm, BindingFlags.Instance | BindingFlags.Public); if (fi != null) { or.Data[fld.ColumnNumber] = fi.GetValue(dt); } else { // Try getting it as a property as well PropertyInfo pi = myType.GetProperty(fld.Name.Nm, BindingFlags.Instance | BindingFlags.Public); if (pi != null) { or.Data[fld.ColumnNumber] = pi.GetValue(dt, null); } } } // Apply the filters if (f == null || f.Apply(rpt, or)) { or.RowNumber = rowCount; // rowCount++; ar.Add(or); } if (--maxRows <= 0) // don't retrieve more than max break; } ar.TrimExcess(); // free up any extraneous space; can be sizeable for large # rows if (f != null) f.ApplyFinalFilters(rpt, rows, false); SetMyUserData(rpt, rows); } internal void SetData(Report rpt, IDataReader dr, Fields flds, Filters f) { if (dr == null) // Does user want to remove user data? { SetMyUserData(rpt, null); return; } Rows rows = new Rows(rpt,null,null,null); // no sorting and grouping at base data List<Row> ar = new List<Row>(); rows.Data = ar; int rowCount=0; int maxRows = _RowLimit > 0? _RowLimit: int.MaxValue; while (dr.Read()) { Row or = new Row(rows, dr.FieldCount); dr.GetValues(or.Data); // Apply the filters if (f == null || f.Apply(rpt, or)) { or.RowNumber = rowCount; // rowCount++; ar.Add(or); } if (--maxRows <= 0) // don't retrieve more than max break; } ar.TrimExcess(); // free up any extraneous space; can be sizeable for large # rows if (f != null) f.ApplyFinalFilters(rpt, rows, false); SetMyUserData(rpt, rows); } internal void SetData(Report rpt, DataTable dt, Fields flds, Filters f) { if (dt == null) // Does user want to remove user data? { SetMyUserData(rpt, null); return; } Rows rows = new Rows(rpt,null,null,null); // no sorting and grouping at base data List<Row> ar = new List<Row>(); rows.Data = ar; int rowCount=0; int maxRows = _RowLimit > 0? _RowLimit: int.MaxValue; int fieldCount = flds.Items.Count; foreach (DataRow dr in dt.Rows) { Row or = new Row(rows, fieldCount); // Loop thru the columns obtaining the data values by name foreach (Field fld in flds.Items.Values) { or.Data[fld.ColumnNumber] = dr[fld.DataField]; } // Apply the filters if (f == null || f.Apply(rpt, or)) { or.RowNumber = rowCount; // rowCount++; ar.Add(or); } if (--maxRows <= 0) // don't retrieve more than max break; } ar.TrimExcess(); // free up any extraneous space; can be sizeable for large # rows if (f != null) f.ApplyFinalFilters(rpt, rows, false); SetMyUserData(rpt, rows); } internal void SetData(Report rpt, XmlDocument xmlDoc, Fields flds, Filters f) { if (xmlDoc == null) // Does user want to remove user data? { SetMyUserData(rpt, null); return; } Rows rows = new Rows(rpt,null,null,null); // no sorting and grouping at base data XmlNode xNode; xNode = xmlDoc.LastChild; if (xNode == null || !(xNode.Name == "Rows" || xNode.Name == "fyi:Rows")) { throw new Exception("XML Data must contain top level element Rows."); } List<Row> ar = new List<Row>(); rows.Data = ar; int rowCount=0; int fieldCount = flds.Items.Count; foreach(XmlNode xNodeRow in xNode.ChildNodes) { if (xNodeRow.NodeType != XmlNodeType.Element) continue; if (xNodeRow.Name != "Row") continue; Row or = new Row(rows, fieldCount); foreach (XmlNode xNodeColumn in xNodeRow.ChildNodes) { Field fld = (Field) (flds.Items[xNodeColumn.Name]); // Find the column if (fld == null) continue; // Extraneous data is ignored if (xNodeColumn.InnerText == null || xNodeColumn.InnerText.Length == 0) or.Data[fld.ColumnNumber] = null; else if (fld.Type == TypeCode.String) or.Data[fld.ColumnNumber] = xNodeColumn.InnerText; else { try { or.Data[fld.ColumnNumber] = Convert.ChangeType(xNodeColumn.InnerText, fld.Type, NumberFormatInfo.InvariantInfo); } catch // all conversion errors result in a null value { or.Data[fld.ColumnNumber] = null; } } } // Apply the filters if (f == null || f.Apply(rpt, or)) { or.RowNumber = rowCount; // rowCount++; ar.Add(or); } } ar.TrimExcess(); // free up any extraneous space; can be sizeable for large # rows if (f != null) f.ApplyFinalFilters(rpt, rows, false); SetMyUserData(rpt, rows); } private void AddParameters(Report rpt, IDbConnection cn, IDbCommand cmSQL, bool bValue) { // any parameters to substitute if (this._QueryParameters == null || this._QueryParameters.Items == null || this._QueryParameters.Items.Count == 0 || this._QueryParameters.ContainsArray) // arrays get handled by AddParametersAsLiterals return; // AddParametersAsLiterals handles it when there is replacement if (RdlEngineConfig.DoParameterReplacement(Provider, cn)) return; foreach(QueryParameter qp in this._QueryParameters.Items) { string paramName; // force the name to start with @ if (qp.Name.Nm[0] == '@') paramName = qp.Name.Nm; else paramName = "@" + qp.Name.Nm; object pvalue= bValue? qp.Value.Evaluate(rpt, null): null; IDbDataParameter dp = cmSQL.CreateParameter(); dp.ParameterName = paramName; if (pvalue is ArrayList) // Probably a MultiValue Report parameter result { ArrayList ar = (ArrayList) pvalue; dp.Value = ar.ToArray(ar[0].GetType()); } else dp.Value = pvalue; cmSQL.Parameters.Add(dp); } } private string AddParametersAsLiterals(Report rpt, IDbConnection cn, string sql, bool bValue) { // No parameters means nothing to do if (this._QueryParameters == null || this._QueryParameters.Items == null || this._QueryParameters.Items.Count == 0) return sql; // Only do this for ODBC datasources - AddParameters handles it in other cases if (!RdlEngineConfig.DoParameterReplacement(Provider, cn)) { if (!_QueryParameters.ContainsArray) // when array we do substitution return sql; } StringBuilder sb = new StringBuilder(sql); List<QueryParameter> qlist; if (_QueryParameters.Items.Count <= 1) qlist = _QueryParameters.Items; else { // need to sort the list so that longer items are first in the list // otherwise substitution could be done incorrectly qlist = new List<QueryParameter>(_QueryParameters.Items); qlist.Sort(); } foreach(QueryParameter qp in qlist) { string paramName; // force the name to start with @ if (qp.Name.Nm[0] == '@') paramName = qp.Name.Nm; else paramName = "@" + qp.Name.Nm; // build the replacement value string svalue; if (bValue) { // use the value provided svalue = this.ParameterValue(rpt, qp); } else { // just need a place holder value that will pass parsing switch (qp.Value.Expr.GetTypeCode()) { case TypeCode.Char: svalue = "' '"; break; case TypeCode.DateTime: svalue = "'1900-01-01 00:00:00'"; break; case TypeCode.Decimal: case TypeCode.Double: case TypeCode.Int32: case TypeCode.Int64: svalue = "0"; break; case TypeCode.Boolean: svalue = "'false'"; break; case TypeCode.String: default: svalue = "' '"; break; } } sb.Replace(paramName, svalue); } return sb.ToString(); } private string ParameterValue(Report rpt, QueryParameter qp) { if (!qp.IsArray) { // handle non-array string svalue = qp.Value.EvaluateString(rpt, null); if (svalue == null) svalue = "null"; else switch (qp.Value.Expr.GetTypeCode()) { case TypeCode.Char: case TypeCode.DateTime: case TypeCode.String: // need to double up on "'" and then surround by ' svalue = svalue.Replace("'", "''"); svalue = "'" + svalue + "'"; break; } return svalue; } StringBuilder sb = new StringBuilder(); ArrayList ar = qp.Value.Evaluate(rpt, null) as ArrayList; if (ar == null) return null; bool bFirst = true; foreach (object v in ar) { if (!bFirst) sb.Append(", "); if (v == null) { sb.Append("null"); } else { string sv = v.ToString(); if (v is string || v is char || v is DateTime) { // need to double up on "'" and then surround by ' sv = sv.Replace("'", "''"); sb.Append("'"); sb.Append(sv); sb.Append("'"); } else sb.Append(sv); } bFirst = false; } return sb.ToString(); } private string Provider { get { if (this.DataSourceDefn == null || this.DataSourceDefn.ConnectionProperties == null) return ""; return this.DataSourceDefn.ConnectionProperties.DataProvider; } } internal string DataSourceName { get { return _DataSourceName; } } internal DataSourceDefn DataSourceDefn { get { return _DataSourceDefn; } } internal QueryCommandTypeEnum QueryCommandType { get { return _QueryCommandType; } set { _QueryCommandType = value; } } internal Expression CommandText { get { return _CommandText; } set { _CommandText = value; } } internal QueryParameters QueryParameters { get { return _QueryParameters; } set { _QueryParameters = value; } } internal int Timeout { get { return _Timeout; } set { _Timeout = value; } } internal IDictionary Columns { get { return _Columns; } } // Runtime data internal Rows GetMyData(Report rpt) { return rpt.Cache.Get(this, "data") as Rows; } private void SetMyData(Report rpt, Rows data) { if (data == null) rpt.Cache.Remove(this, "data"); else rpt.Cache.AddReplace(this, "data", data); } private Rows GetMyUserData(Report rpt) { return rpt.Cache.Get(this, "userdata") as Rows; } private void SetMyUserData(Report rpt, Rows data) { if (data == null) rpt.Cache.Remove(this, "userdata"); else rpt.Cache.AddReplace(this, "userdata", data); } } }
// 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 gagvc = Google.Ads.GoogleAds.V8.Common; using gagve = Google.Ads.GoogleAds.V8.Enums; using gagvr = Google.Ads.GoogleAds.V8.Resources; using gaxgrpc = Google.Api.Gax.Grpc; using gr = Google.Rpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using NUnit.Framework; using Google.Ads.GoogleAds.V8.Services; namespace Google.Ads.GoogleAds.Tests.V8.Services { /// <summary>Generated unit tests.</summary> public sealed class GeneratedBiddingStrategyServiceClientTest { [Category("Autogenerated")][Test] public void GetBiddingStrategyRequestObject() { moq::Mock<BiddingStrategyService.BiddingStrategyServiceClient> mockGrpcClient = new moq::Mock<BiddingStrategyService.BiddingStrategyServiceClient>(moq::MockBehavior.Strict); GetBiddingStrategyRequest request = new GetBiddingStrategyRequest { ResourceNameAsBiddingStrategyName = gagvr::BiddingStrategyName.FromCustomerBiddingStrategy("[CUSTOMER_ID]", "[BIDDING_STRATEGY_ID]"), }; gagvr::BiddingStrategy expectedResponse = new gagvr::BiddingStrategy { ResourceNameAsBiddingStrategyName = gagvr::BiddingStrategyName.FromCustomerBiddingStrategy("[CUSTOMER_ID]", "[BIDDING_STRATEGY_ID]"), Type = gagve::BiddingStrategyTypeEnum.Types.BiddingStrategyType.MaximizeConversionValue, EnhancedCpc = new gagvc::EnhancedCpc(), TargetCpa = new gagvc::TargetCpa(), TargetRoas = new gagvc::TargetRoas(), TargetSpend = new gagvc::TargetSpend(), Status = gagve::BiddingStrategyStatusEnum.Types.BiddingStrategyStatus.Enabled, Id = -6774108720365892680L, BiddingStrategyName = gagvr::BiddingStrategyName.FromCustomerBiddingStrategy("[CUSTOMER_ID]", "[BIDDING_STRATEGY_ID]"), CampaignCount = 7086295369533367171L, NonRemovedCampaignCount = 8279371121198864414L, EffectiveCurrencyCode = "effective_currency_code0045faae", MaximizeConversionValue = new gagvc::MaximizeConversionValue(), MaximizeConversions = new gagvc::MaximizeConversions(), CurrencyCode = "currency_code7f81e352", TargetImpressionShare = new gagvc::TargetImpressionShare(), }; mockGrpcClient.Setup(x => x.GetBiddingStrategy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); BiddingStrategyServiceClient client = new BiddingStrategyServiceClientImpl(mockGrpcClient.Object, null); gagvr::BiddingStrategy response = client.GetBiddingStrategy(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetBiddingStrategyRequestObjectAsync() { moq::Mock<BiddingStrategyService.BiddingStrategyServiceClient> mockGrpcClient = new moq::Mock<BiddingStrategyService.BiddingStrategyServiceClient>(moq::MockBehavior.Strict); GetBiddingStrategyRequest request = new GetBiddingStrategyRequest { ResourceNameAsBiddingStrategyName = gagvr::BiddingStrategyName.FromCustomerBiddingStrategy("[CUSTOMER_ID]", "[BIDDING_STRATEGY_ID]"), }; gagvr::BiddingStrategy expectedResponse = new gagvr::BiddingStrategy { ResourceNameAsBiddingStrategyName = gagvr::BiddingStrategyName.FromCustomerBiddingStrategy("[CUSTOMER_ID]", "[BIDDING_STRATEGY_ID]"), Type = gagve::BiddingStrategyTypeEnum.Types.BiddingStrategyType.MaximizeConversionValue, EnhancedCpc = new gagvc::EnhancedCpc(), TargetCpa = new gagvc::TargetCpa(), TargetRoas = new gagvc::TargetRoas(), TargetSpend = new gagvc::TargetSpend(), Status = gagve::BiddingStrategyStatusEnum.Types.BiddingStrategyStatus.Enabled, Id = -6774108720365892680L, BiddingStrategyName = gagvr::BiddingStrategyName.FromCustomerBiddingStrategy("[CUSTOMER_ID]", "[BIDDING_STRATEGY_ID]"), CampaignCount = 7086295369533367171L, NonRemovedCampaignCount = 8279371121198864414L, EffectiveCurrencyCode = "effective_currency_code0045faae", MaximizeConversionValue = new gagvc::MaximizeConversionValue(), MaximizeConversions = new gagvc::MaximizeConversions(), CurrencyCode = "currency_code7f81e352", TargetImpressionShare = new gagvc::TargetImpressionShare(), }; mockGrpcClient.Setup(x => x.GetBiddingStrategyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::BiddingStrategy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); BiddingStrategyServiceClient client = new BiddingStrategyServiceClientImpl(mockGrpcClient.Object, null); gagvr::BiddingStrategy responseCallSettings = await client.GetBiddingStrategyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::BiddingStrategy responseCancellationToken = await client.GetBiddingStrategyAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetBiddingStrategy() { moq::Mock<BiddingStrategyService.BiddingStrategyServiceClient> mockGrpcClient = new moq::Mock<BiddingStrategyService.BiddingStrategyServiceClient>(moq::MockBehavior.Strict); GetBiddingStrategyRequest request = new GetBiddingStrategyRequest { ResourceNameAsBiddingStrategyName = gagvr::BiddingStrategyName.FromCustomerBiddingStrategy("[CUSTOMER_ID]", "[BIDDING_STRATEGY_ID]"), }; gagvr::BiddingStrategy expectedResponse = new gagvr::BiddingStrategy { ResourceNameAsBiddingStrategyName = gagvr::BiddingStrategyName.FromCustomerBiddingStrategy("[CUSTOMER_ID]", "[BIDDING_STRATEGY_ID]"), Type = gagve::BiddingStrategyTypeEnum.Types.BiddingStrategyType.MaximizeConversionValue, EnhancedCpc = new gagvc::EnhancedCpc(), TargetCpa = new gagvc::TargetCpa(), TargetRoas = new gagvc::TargetRoas(), TargetSpend = new gagvc::TargetSpend(), Status = gagve::BiddingStrategyStatusEnum.Types.BiddingStrategyStatus.Enabled, Id = -6774108720365892680L, BiddingStrategyName = gagvr::BiddingStrategyName.FromCustomerBiddingStrategy("[CUSTOMER_ID]", "[BIDDING_STRATEGY_ID]"), CampaignCount = 7086295369533367171L, NonRemovedCampaignCount = 8279371121198864414L, EffectiveCurrencyCode = "effective_currency_code0045faae", MaximizeConversionValue = new gagvc::MaximizeConversionValue(), MaximizeConversions = new gagvc::MaximizeConversions(), CurrencyCode = "currency_code7f81e352", TargetImpressionShare = new gagvc::TargetImpressionShare(), }; mockGrpcClient.Setup(x => x.GetBiddingStrategy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); BiddingStrategyServiceClient client = new BiddingStrategyServiceClientImpl(mockGrpcClient.Object, null); gagvr::BiddingStrategy response = client.GetBiddingStrategy(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetBiddingStrategyAsync() { moq::Mock<BiddingStrategyService.BiddingStrategyServiceClient> mockGrpcClient = new moq::Mock<BiddingStrategyService.BiddingStrategyServiceClient>(moq::MockBehavior.Strict); GetBiddingStrategyRequest request = new GetBiddingStrategyRequest { ResourceNameAsBiddingStrategyName = gagvr::BiddingStrategyName.FromCustomerBiddingStrategy("[CUSTOMER_ID]", "[BIDDING_STRATEGY_ID]"), }; gagvr::BiddingStrategy expectedResponse = new gagvr::BiddingStrategy { ResourceNameAsBiddingStrategyName = gagvr::BiddingStrategyName.FromCustomerBiddingStrategy("[CUSTOMER_ID]", "[BIDDING_STRATEGY_ID]"), Type = gagve::BiddingStrategyTypeEnum.Types.BiddingStrategyType.MaximizeConversionValue, EnhancedCpc = new gagvc::EnhancedCpc(), TargetCpa = new gagvc::TargetCpa(), TargetRoas = new gagvc::TargetRoas(), TargetSpend = new gagvc::TargetSpend(), Status = gagve::BiddingStrategyStatusEnum.Types.BiddingStrategyStatus.Enabled, Id = -6774108720365892680L, BiddingStrategyName = gagvr::BiddingStrategyName.FromCustomerBiddingStrategy("[CUSTOMER_ID]", "[BIDDING_STRATEGY_ID]"), CampaignCount = 7086295369533367171L, NonRemovedCampaignCount = 8279371121198864414L, EffectiveCurrencyCode = "effective_currency_code0045faae", MaximizeConversionValue = new gagvc::MaximizeConversionValue(), MaximizeConversions = new gagvc::MaximizeConversions(), CurrencyCode = "currency_code7f81e352", TargetImpressionShare = new gagvc::TargetImpressionShare(), }; mockGrpcClient.Setup(x => x.GetBiddingStrategyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::BiddingStrategy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); BiddingStrategyServiceClient client = new BiddingStrategyServiceClientImpl(mockGrpcClient.Object, null); gagvr::BiddingStrategy responseCallSettings = await client.GetBiddingStrategyAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::BiddingStrategy responseCancellationToken = await client.GetBiddingStrategyAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetBiddingStrategyResourceNames() { moq::Mock<BiddingStrategyService.BiddingStrategyServiceClient> mockGrpcClient = new moq::Mock<BiddingStrategyService.BiddingStrategyServiceClient>(moq::MockBehavior.Strict); GetBiddingStrategyRequest request = new GetBiddingStrategyRequest { ResourceNameAsBiddingStrategyName = gagvr::BiddingStrategyName.FromCustomerBiddingStrategy("[CUSTOMER_ID]", "[BIDDING_STRATEGY_ID]"), }; gagvr::BiddingStrategy expectedResponse = new gagvr::BiddingStrategy { ResourceNameAsBiddingStrategyName = gagvr::BiddingStrategyName.FromCustomerBiddingStrategy("[CUSTOMER_ID]", "[BIDDING_STRATEGY_ID]"), Type = gagve::BiddingStrategyTypeEnum.Types.BiddingStrategyType.MaximizeConversionValue, EnhancedCpc = new gagvc::EnhancedCpc(), TargetCpa = new gagvc::TargetCpa(), TargetRoas = new gagvc::TargetRoas(), TargetSpend = new gagvc::TargetSpend(), Status = gagve::BiddingStrategyStatusEnum.Types.BiddingStrategyStatus.Enabled, Id = -6774108720365892680L, BiddingStrategyName = gagvr::BiddingStrategyName.FromCustomerBiddingStrategy("[CUSTOMER_ID]", "[BIDDING_STRATEGY_ID]"), CampaignCount = 7086295369533367171L, NonRemovedCampaignCount = 8279371121198864414L, EffectiveCurrencyCode = "effective_currency_code0045faae", MaximizeConversionValue = new gagvc::MaximizeConversionValue(), MaximizeConversions = new gagvc::MaximizeConversions(), CurrencyCode = "currency_code7f81e352", TargetImpressionShare = new gagvc::TargetImpressionShare(), }; mockGrpcClient.Setup(x => x.GetBiddingStrategy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); BiddingStrategyServiceClient client = new BiddingStrategyServiceClientImpl(mockGrpcClient.Object, null); gagvr::BiddingStrategy response = client.GetBiddingStrategy(request.ResourceNameAsBiddingStrategyName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetBiddingStrategyResourceNamesAsync() { moq::Mock<BiddingStrategyService.BiddingStrategyServiceClient> mockGrpcClient = new moq::Mock<BiddingStrategyService.BiddingStrategyServiceClient>(moq::MockBehavior.Strict); GetBiddingStrategyRequest request = new GetBiddingStrategyRequest { ResourceNameAsBiddingStrategyName = gagvr::BiddingStrategyName.FromCustomerBiddingStrategy("[CUSTOMER_ID]", "[BIDDING_STRATEGY_ID]"), }; gagvr::BiddingStrategy expectedResponse = new gagvr::BiddingStrategy { ResourceNameAsBiddingStrategyName = gagvr::BiddingStrategyName.FromCustomerBiddingStrategy("[CUSTOMER_ID]", "[BIDDING_STRATEGY_ID]"), Type = gagve::BiddingStrategyTypeEnum.Types.BiddingStrategyType.MaximizeConversionValue, EnhancedCpc = new gagvc::EnhancedCpc(), TargetCpa = new gagvc::TargetCpa(), TargetRoas = new gagvc::TargetRoas(), TargetSpend = new gagvc::TargetSpend(), Status = gagve::BiddingStrategyStatusEnum.Types.BiddingStrategyStatus.Enabled, Id = -6774108720365892680L, BiddingStrategyName = gagvr::BiddingStrategyName.FromCustomerBiddingStrategy("[CUSTOMER_ID]", "[BIDDING_STRATEGY_ID]"), CampaignCount = 7086295369533367171L, NonRemovedCampaignCount = 8279371121198864414L, EffectiveCurrencyCode = "effective_currency_code0045faae", MaximizeConversionValue = new gagvc::MaximizeConversionValue(), MaximizeConversions = new gagvc::MaximizeConversions(), CurrencyCode = "currency_code7f81e352", TargetImpressionShare = new gagvc::TargetImpressionShare(), }; mockGrpcClient.Setup(x => x.GetBiddingStrategyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::BiddingStrategy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); BiddingStrategyServiceClient client = new BiddingStrategyServiceClientImpl(mockGrpcClient.Object, null); gagvr::BiddingStrategy responseCallSettings = await client.GetBiddingStrategyAsync(request.ResourceNameAsBiddingStrategyName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::BiddingStrategy responseCancellationToken = await client.GetBiddingStrategyAsync(request.ResourceNameAsBiddingStrategyName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateBiddingStrategiesRequestObject() { moq::Mock<BiddingStrategyService.BiddingStrategyServiceClient> mockGrpcClient = new moq::Mock<BiddingStrategyService.BiddingStrategyServiceClient>(moq::MockBehavior.Strict); MutateBiddingStrategiesRequest request = new MutateBiddingStrategiesRequest { CustomerId = "customer_id3b3724cb", Operations = { new BiddingStrategyOperation(), }, PartialFailure = false, ValidateOnly = true, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, }; MutateBiddingStrategiesResponse expectedResponse = new MutateBiddingStrategiesResponse { Results = { new MutateBiddingStrategyResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateBiddingStrategies(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); BiddingStrategyServiceClient client = new BiddingStrategyServiceClientImpl(mockGrpcClient.Object, null); MutateBiddingStrategiesResponse response = client.MutateBiddingStrategies(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateBiddingStrategiesRequestObjectAsync() { moq::Mock<BiddingStrategyService.BiddingStrategyServiceClient> mockGrpcClient = new moq::Mock<BiddingStrategyService.BiddingStrategyServiceClient>(moq::MockBehavior.Strict); MutateBiddingStrategiesRequest request = new MutateBiddingStrategiesRequest { CustomerId = "customer_id3b3724cb", Operations = { new BiddingStrategyOperation(), }, PartialFailure = false, ValidateOnly = true, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, }; MutateBiddingStrategiesResponse expectedResponse = new MutateBiddingStrategiesResponse { Results = { new MutateBiddingStrategyResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateBiddingStrategiesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateBiddingStrategiesResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); BiddingStrategyServiceClient client = new BiddingStrategyServiceClientImpl(mockGrpcClient.Object, null); MutateBiddingStrategiesResponse responseCallSettings = await client.MutateBiddingStrategiesAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateBiddingStrategiesResponse responseCancellationToken = await client.MutateBiddingStrategiesAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateBiddingStrategies() { moq::Mock<BiddingStrategyService.BiddingStrategyServiceClient> mockGrpcClient = new moq::Mock<BiddingStrategyService.BiddingStrategyServiceClient>(moq::MockBehavior.Strict); MutateBiddingStrategiesRequest request = new MutateBiddingStrategiesRequest { CustomerId = "customer_id3b3724cb", Operations = { new BiddingStrategyOperation(), }, }; MutateBiddingStrategiesResponse expectedResponse = new MutateBiddingStrategiesResponse { Results = { new MutateBiddingStrategyResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateBiddingStrategies(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); BiddingStrategyServiceClient client = new BiddingStrategyServiceClientImpl(mockGrpcClient.Object, null); MutateBiddingStrategiesResponse response = client.MutateBiddingStrategies(request.CustomerId, request.Operations); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateBiddingStrategiesAsync() { moq::Mock<BiddingStrategyService.BiddingStrategyServiceClient> mockGrpcClient = new moq::Mock<BiddingStrategyService.BiddingStrategyServiceClient>(moq::MockBehavior.Strict); MutateBiddingStrategiesRequest request = new MutateBiddingStrategiesRequest { CustomerId = "customer_id3b3724cb", Operations = { new BiddingStrategyOperation(), }, }; MutateBiddingStrategiesResponse expectedResponse = new MutateBiddingStrategiesResponse { Results = { new MutateBiddingStrategyResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateBiddingStrategiesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateBiddingStrategiesResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); BiddingStrategyServiceClient client = new BiddingStrategyServiceClientImpl(mockGrpcClient.Object, null); MutateBiddingStrategiesResponse responseCallSettings = await client.MutateBiddingStrategiesAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateBiddingStrategiesResponse responseCancellationToken = await client.MutateBiddingStrategiesAsync(request.CustomerId, request.Operations, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// =========================================================== // Copyright (C) 2014-2015 Kendar.org // // 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 SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS // BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF // OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // =========================================================== using System.Collections.Specialized; using System.Dynamic; using System.Reflection; using System.Web.Security; using ClassWrapper; using ConcurrencyHelpers.Utils; using CoroutinesLib.Shared; using GenericHelpers; using Http.Contexts; using Http.Controllers; using Http.Coroutines; using Http.Shared; using Http.Shared.Authorization; using Http.Shared.Contexts; using Http.Shared.Controllers; using Http.Shared.Optimizations; using Http.Shared.PathProviders; using Http.Shared.Renderers; using Http.Shared.Routing; using NodeCs.Shared; using NodeCs.Shared.Caching; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Threading; namespace Http { public sealed class HttpModule : NodeModuleBase, IRunnableModule { private const int WAIT_INCOMING_MS = 100; private int _port; private string _virtualDir; private string _host; private Thread _thread; private HttpListener _listener; private SecurityDefinition _securityDefinition = new SecurityDefinition(); private readonly List<IPathProvider> _pathProviders = new List<IPathProvider>(); private readonly List<IRenderer> _renderers = new List<IRenderer>(); private IRoutingHandler _routingHandler; private ConcurrentBool _running; private readonly Dictionary<string, ControllerWrapperDescriptor> _controllers = new Dictionary<string, ControllerWrapperDescriptor>(StringComparer.OrdinalIgnoreCase); private readonly IConversionService _conversionService; private string _errorPageString; private readonly List<IResponseHandler> _responseHandlers = new List<IResponseHandler>(); private readonly List<string> _defaulList = new List<string>(); private readonly IFilterHandler _filtersHandler; private bool _fallBackResult; private string _fallBackResultMessage; public HttpModule() { _virtualDir = string.Empty; _errorPageString = ResourceContentLoader.LoadText("errorTemplate.html"); _conversionService = new ConversionService(); ServiceLocator.Locator.Register<IConversionService>(_conversionService); ServiceLocator.Locator.Register<HttpModule>(this); ServiceLocator.Locator.Register<SecurityDefinition>(_securityDefinition); _filtersHandler = ServiceLocator.Locator.Resolve<IFilterHandler>(); if (_filtersHandler == null) { _filtersHandler = new FilterHandler(); ServiceLocator.Locator.Register<IFilterHandler>(_filtersHandler); } SetParameter(HttpParameters.HttpShowDirectoryContent, true); RegisterDefaultFiles("index.htm"); RegisterDefaultFiles("index.html"); } public void SetAuthentication(string authType, string realm, string loginPage) { _securityDefinition.AuthenticationType = authType; _securityDefinition.Realm = realm; _securityDefinition.LoginPage = loginPage; } public override void Initialize() { _port = GetParameter<int>(HttpParameters.HttpPort); _virtualDir = UrlUtils.CleanUpUrl(GetParameter<string>(HttpParameters.HttpVirtualDir)); if (_virtualDir == string.Empty) { _virtualDir = "/"; } else { _virtualDir = "/" + _virtualDir + "/"; } _host = GetParameter<string>(HttpParameters.HttpHost); var main = ServiceLocator.Locator.Resolve<IMain>(); main.RegisterCommand("http.show", new CommandDefinition((Action)Httpshow)); } private void Httpshow() { var listenAddress = string.Format("http://{0}:{1}{2}", _host, _port, _virtualDir); Process.Start("IExplore.exe", listenAddress); } public void Start() { if (IsRunning) return; ExecuteRequestCoroutine.ErrorPageString = _errorPageString; _thread = new Thread(RunHttpModule); _running = true; _thread.Start(); } public bool IsRunning { get { if (_thread == null) return false; return _running.Value; } } public void Stop() { if (_thread == null) return; _running = false; Thread.Sleep(WAIT_INCOMING_MS * 2); } public void RunHttpModule() { var listenAddress = string.Format("http://{0}:{1}{2}", _host, _port, _virtualDir); _listener = new HttpListener(); _listener.Prefixes.Add(listenAddress); _listener.Start(); NodeRoot.CWriteLine("Started listening from " + listenAddress + "."); _fallBackResultMessage = string.Empty; _fallBackResult = false; #if DEBUG_ if (_routingHandler == null) { _fallBackResultMessage += "Missing Routing handler.<br>"; _fallBackResult = true; } if (_renderers.Count == 0) { _fallBackResultMessage += "Missing Renderes.<br>"; _fallBackResult = true; } if (_pathProviders.Count == 0) { _fallBackResultMessage += "Missing Path providers.<br>"; _fallBackResult = true; } #endif while (_running.Value) { var context = _listener.BeginGetContext(ListenerCallback, _listener); context.AsyncWaitHandle.WaitOne(WAIT_INCOMING_MS); } _listener.Close(); _listener = null; } protected override void Dispose(bool disposing) { Stop(); var main = ServiceLocator.Locator.Resolve<IMain>(); main.UnregisterCommand("https.how", 0); } public override string ToString() { return string.Join(":", _host, _virtualDir, _port); } /// <summary> /// This is the first entry point when the server receives the data from /// the client. /// </summary> /// <param name="result"></param> private void ListenerCallback(IAsyncResult result) { var listener = (HttpListener)result.AsyncState; if (!listener.IsListening) return; IHttpContext context = null; try { context = new ListenerHttpContext(listener.EndGetContext(result)); context.ForceRootDir(_virtualDir); } catch (Exception) { return; } if (!IsRunning) { //It's a dead coroutine. No need to handle other things. context.Response.Close(); return; } try { //If no real module exists to serve the content, simply return a server courtesy page. if (_fallBackResult) { var now = DateTime.UtcNow; var responseString = "<HTML><BODY>" + _fallBackResultMessage + "Timestamp:" + now + ":" + NodeRoot.Lpad(now.Millisecond.ToString(), 4, "0") + "</BODY></HTML>"; byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString); context.Response.BinaryWrite(buffer); _filtersHandler.OnPostExecute(context); context.Response.Close(); } else { // ReSharper disable once PossibleNullReferenceException ExecuteRequest(context); } } catch (HttpException httpException) { ExecuteRequestCoroutine.WriteException(context, httpException); } catch (Exception ex) { var httpException = ExecuteRequestCoroutine.FindHttpException(ex); if (httpException != null) { ExecuteRequestCoroutine.WriteException(context, (HttpException)httpException); } else { ExecuteRequestCoroutine.WriteException(context, 500, ex); } } } //private Exception FindHttpException(Exception exception) //{ // if (exception is HttpException) // { // return exception; // } // if (exception.InnerException != null) // { // if (exception.InnerException is HttpException) // { // return exception.InnerException; // } // var tmpEx = FindHttpException(exception.InnerException); // if (tmpEx == null) return null; // } // return null; //} internal IControllerWrapperInstance CreateController(RouteInstance instance) { if (!_controllers.ContainsKey(instance.Controller.Name)) return null; var cld = _controllers[instance.Controller.Name]; var controller = (IController)ServiceLocator.Locator.Resolve(instance.Controller); if (controller == null) return null; return cld.CreateWrapper(controller); } public IEnumerable<ICoroutineResult> HandleResponse(IHttpContext context, IResponse response, object viewBag) { var functionalResponse = response as IFunctionalResponse; if (functionalResponse != null) { foreach (var item in functionalResponse.ExecuteResult(context)) { if (item != null) { response = item; break; } yield return CoroutineResult.Wait; } } for (int index = 0; index < _responseHandlers.Count; index++) { var handler = _responseHandlers[index]; if (handler.CanHandle(response)) { foreach (var item in handler.Handle(context, response,viewBag)) { yield return item; yield break; } } } } /* internal bool HttpListenerExceptionHandler(Exception ex, IHttpContext context) { var httpException = FindHttpException(ex); if (httpException != null) { WriteException(context, (HttpException)httpException); } else { WriteException(context, 500, ex); } return true; }*/ /* private IRenderer FindRenderer(ref string relativePath, IPathProvider pathProvider, bool isDir) { if (isDir) { string tmpPath = null; for (int i = 0; i < _defaulList.Count; i++) { var def = _defaulList[i]; tmpPath = relativePath.TrimEnd('/') + '/' + def; if (pathProvider.Exists(tmpPath, out isDir)) { if (!isDir) break; } tmpPath = null; } if (tmpPath != null) { relativePath = tmpPath; } } var renderer = GetPossibleRenderer(relativePath); return renderer; }*/ /// <summary> /// Main entry point for the http request. This will be called only upon REAL REQUESTS. Not by /// forwarded items. /// </summary> /// <param name="context"></param> /// <param name="specialHandler"></param> internal void ExecuteRequest(IHttpContext context) { var runner = ServiceLocator.Locator.Resolve<ICoroutinesManager>(); if (context.Request.Url == null) { throw new HttpException(500, string.Format("Missing url.")); } var requestPath = context.Request.Url.LocalPath.Trim(); var relativePath = requestPath; if (requestPath.StartsWith(_virtualDir.TrimEnd('/'))) { relativePath = requestPath.Substring(_virtualDir.Length - 1); } _filtersHandler.OnPreExecute(context); if (_routingHandler != null) { var match = _routingHandler.Resolve(relativePath, context); if (match != null /*&& match.StaticRoute && !match.BlockRoute*/) { if (match.BlockRoute) { ExecuteRequestCoroutine.WriteException(context, new HttpException(404, "Missing " + context.Request.Url)); return; } if (!match.StaticRoute) { var controller = CreateController(match); if (controller != null) { context.RouteParams = match.Parameters ?? new Dictionary<string, object>(); controller.Instance.Set("Httpcontext", context); runner.StartCoroutine( new RoutedItemCoroutine(match, controller, context, _conversionService, null)); return; } } } } var executeRequestCoroutine = new ExecuteRequestCoroutine( _virtualDir, context, null, new ModelStateDictionary(), _pathProviders, _renderers, _defaulList,new ExpandoObject()); executeRequestCoroutine.Initialize(); runner.StartCoroutine(executeRequestCoroutine); } private IRenderer GetPossibleRenderer(string relativePath) { var file = UrlUtils.GetFileName(relativePath); var extension = PathUtils.GetExtension(file); for (int index = 0; index < _renderers.Count; index++) { var renderer = _renderers[index]; if (renderer.CanHandle(extension)) { return renderer; } } return null; } public IRoutingHandler RoutingHandler { get { return _routingHandler; } } public void RegisterRouting(IRoutingHandler routingService) { _routingHandler = routingService; ServiceLocator.Locator.Register<IRoutingHandler>(routingService); CallClientInitializers(); } public void UnregisterRouting(IRoutingHandler routingService) { if (_routingHandler == routingService) { _routingHandler = null; } } public void AddConverter(ISerializer converter, string firstMime, params string[] mimes) { _conversionService.AddConverter(converter, firstMime, mimes); } public void RegisterConverter(string mime, ISerializer converter) { _conversionService.AddConverter(converter, mime); } public void RegisterPathProvider(IPathProvider pathProvider) { if (!_pathProviders.Contains(pathProvider)) { var showDirectoryContent = GetParameter<bool>(HttpParameters.HttpShowDirectoryContent); pathProvider.ShowDirectoryContent(showDirectoryContent); _pathProviders.Add(pathProvider); } } public void UnregisterPathProvider(IPathProvider pathProvider) { if (_pathProviders.Contains(pathProvider)) { _pathProviders.Remove(pathProvider); } } public void RegisterResponseHandler(IResponseHandler renderer) { _responseHandlers.Add(renderer); } public void UnregisterResponseHandler(IResponseHandler renderer) { if (_responseHandlers.Contains(renderer)) { _responseHandlers.Remove(renderer); } } public void RegisterRenderer(IRenderer renderer) { if (!_renderers.Contains(renderer)) { _renderers.Add(renderer); } } public void UnregisterRenderer(IRenderer renderer) { if (_renderers.Contains(renderer)) { _renderers.Remove(renderer); } } public void RegisterDefaultFiles(string fileName) { if (!_defaulList.Any((f) => string.Equals(f, fileName, StringComparison.OrdinalIgnoreCase))) { _defaulList.Add(fileName); } } public void UnregisterDefaultFiles(string fileName) { var idx = _defaulList.FindIndex((f) => string.Equals(f, fileName, StringComparison.OrdinalIgnoreCase)); if (idx >= 0) { _defaulList.RemoveAt(idx); } } private void CallClientInitializers() { var par = GetParameter<string>("authenticationType"); if (!string.IsNullOrEmpty(par)) _securityDefinition.AuthenticationType = par; par = GetParameter<string>("realm"); if (!string.IsNullOrEmpty(par)) _securityDefinition.Realm = par; par = GetParameter<string>("loginPage"); if (!string.IsNullOrEmpty(par)) _securityDefinition.LoginPage = par; foreach (var type in AssembliesManager.LoadTypesInheritingFrom<ILocatorInitialize>()) { var initializer = (ILocatorInitialize)ServiceLocator.Locator.Resolve(type); initializer.InitializeLocator(ServiceLocator.Locator); } IAuthenticationDataProvider authenticationDataProvider = null; foreach (var type in AssembliesManager.LoadTypesInheritingFrom<IAuthenticationDataProviderFactory>()) { var initializer = (IAuthenticationDataProviderFactory)ServiceLocator.Locator.Resolve(type); authenticationDataProvider = initializer.CreateAuthenticationDataProvider(); ServiceLocator.Locator.Register<IAuthenticationDataProvider>(authenticationDataProvider); break; } if (authenticationDataProvider == null) { ServiceLocator.Locator.Register<IAuthenticationDataProvider>(NullAuthenticationDataProvider.Instance); } ForceMemebershipProvider(ServiceLocator.Locator.Resolve<IAuthenticationDataProvider>()); ISessionManager sessionManager = null; foreach (var type in AssembliesManager.LoadTypesInheritingFrom<ISessionManagerFactory>()) { var initializer = (ISessionManagerFactory)ServiceLocator.Locator.Resolve(type); sessionManager = initializer.CreateSessionManager(); ServiceLocator.Locator.Register<ISessionManager>(sessionManager); break; } if (sessionManager == null) { ServiceLocator.Locator.Register<ISessionManager>(new BasicSessionManager()); } var sessionCache = GetParameter<INodeModule>(HttpParameters.HttpSessionCache); if (sessionCache != null) { ServiceLocator.Locator.Resolve<ISessionManager>().SetCachingEngine(sessionCache.GetParameter<ICacheEngine>(HttpParameters.CacheInstance)); } if (_routingHandler == null) return; foreach (var type in AssembliesManager.LoadTypesInheritingFrom<IRouteInitializer>()) { var initializer = (IRouteInitializer)ServiceLocator.Locator.Resolve(type); initializer.RegisterRoutes(_routingHandler); } var controllers = AssembliesManager.LoadTypesInheritingFrom<IController>().ToArray(); _routingHandler.LoadControllers(controllers); foreach (var controller in controllers) { ServiceLocator.Locator.Register(controller); var cld = new ClassWrapperDescriptor(controller, true); cld.Load(); foreach (var method in cld.Methods) { var methodGroup = cld.GetMethodGroup(method); foreach (var meth in methodGroup) { if (meth.Visibility != ItemVisibility.Public) continue; if (meth.Parameters.Count == 0) continue; foreach (var param in meth.Parameters) { var paramType = param.ParameterType; if (!paramType.IsValueType && paramType.Namespace != null && !paramType.Namespace.StartsWith("System")) { ValidationService.RegisterModelType(param.ParameterType); } } } } _controllers.Add(controller.Name, new ControllerWrapperDescriptor(cld)); } foreach (var type in AssembliesManager.LoadTypesInheritingFrom<IFiltersInitializer>()) { var initializer = (IFiltersInitializer)ServiceLocator.Locator.Resolve(type); initializer.InitializeFilters(_filtersHandler); } var resourceBundler = new ResourceBundles(_virtualDir,_pathProviders); ServiceLocator.Locator.Register<IResourceBundles>(resourceBundler); foreach (var type in AssembliesManager.LoadTypesInheritingFrom<IResourceBundleInitializer>()) { var initializer = (IResourceBundleInitializer)ServiceLocator.Locator.Resolve(type); initializer.RegisterBundles(resourceBundler); } } private void ForceMemebershipProvider(IAuthenticationDataProvider authenticationDataProvider) { var objSqlMembershipProvider = new MembershipProviderWrapper(authenticationDataProvider); var colMembershipProviders = new MembershipProviderCollection { objSqlMembershipProvider }; colMembershipProviders.SetReadOnly(); const BindingFlags enuBindingFlags = BindingFlags.NonPublic | BindingFlags.Static; Type objMembershipType = typeof(Membership); // ReSharper disable PossibleNullReferenceException objMembershipType.GetField("s_Initialized", enuBindingFlags).SetValue(null, true); objMembershipType.GetField("s_InitializeException", enuBindingFlags).SetValue(null, null); objMembershipType.GetField("s_HashAlgorithmType", enuBindingFlags).SetValue(null, "SHA1"); objMembershipType.GetField("s_HashAlgorithmFromConfig", enuBindingFlags).SetValue(null, false); objMembershipType.GetField("s_UserIsOnlineTimeWindow", enuBindingFlags).SetValue(null, 15); objMembershipType.GetField("s_Provider", enuBindingFlags).SetValue(null, objSqlMembershipProvider); objMembershipType.GetField("s_Providers", enuBindingFlags).SetValue(null, colMembershipProviders); // ReSharper restore PossibleNullReferenceException } /// <summary> /// This Execute request /// </summary> /// <param name="context"></param> /// <param name="model"></param> /// <param name="modelStateDictionary"></param> /// <param name="o"></param> public ICoroutineResult ExecuteRequestInternal(IHttpContext context, object model, ModelStateDictionary modelStateDictionary, object viewBag) { var executeRequestCoroutine = SetupInternalRequestCoroutine(context, model, viewBag); return CoroutineResult.RunCoroutine(executeRequestCoroutine) .WithTimeout(TimeSpan.FromSeconds(60)) .AndWait(); } public ExecuteRequestCoroutine SetupInternalRequestCoroutine(IHttpContext context, object model, object viewBag) { var executeRequestCoroutine = new ExecuteRequestCoroutine( _virtualDir, context, model, new ModelStateDictionary(), _pathProviders, _renderers, _defaulList, viewBag); executeRequestCoroutine.Initialize(); return executeRequestCoroutine; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using OpenMetaverse; using InWorldz.Phlox.Types; namespace InWorldz.Phlox.Glue { public interface ISystemAPI { void SetScriptEventFlags(); void ShoutError(string errorText); void OnScriptReset(); void OnStateChange(); void OnScriptUnloaded(ScriptUnloadReason reason, VM.RuntimeState.LocalDisableFlag localFlag); void AddExecutionTime(double ms); void OnScriptInjected(bool fromCrossing); void OnGroupCrossedAvatarReady(UUID avatarId); float GetAverageScriptTime(); float llSin(float theta); float llCos(float theta); float llTan(float theta); float llAtan2(float y,float x); float llSqrt(float val); float llPow(float decbase,float exponent); int llAbs(int val); float llFabs(float val); float llFrand(float mag); int llFloor(float val); int llCeil(float val); int llRound(float val); float llVecMag(Vector3 v); Vector3 llVecNorm(Vector3 v); float llVecDist(Vector3 v1,Vector3 v2); Vector3 llRot2Euler(Quaternion q); Quaternion llEuler2Rot(Vector3 v); Quaternion llAxes2Rot(Vector3 fwd,Vector3 left,Vector3 up); Vector3 llRot2Fwd(Quaternion q); Vector3 llRot2Left(Quaternion q); Vector3 llRot2Up(Quaternion q); Quaternion llRotBetween(Vector3 v1,Vector3 v2); void llWhisper(int channel,string msg); void llSay(int channel,string msg); void llShout(int channel,string msg); int llListen(int channel,string name,string id,string msg); void llListenControl(int number,int active); void llListenRemove(int number); void llSensor(string name,string id,int type,float range,float arc); void llSensorRepeat(string name,string id,int type,float range,float arc,float rate); void llSensorRemove(); string llDetectedName(int number); string llDetectedKey(int number); string llDetectedOwner(int number); int llDetectedType(int number); Vector3 llDetectedPos(int number); Vector3 llDetectedVel(int number); Vector3 llDetectedGrab(int number); Quaternion llDetectedRot(int number); int llDetectedGroup(int number); int llDetectedLinkNumber(int number); void llDie(); float llGround(Vector3 offset); float llCloud(Vector3 offset); Vector3 llWind(Vector3 offset); void llSetStatus(int status,int value); int llGetStatus(int status); void llSetScale(Vector3 scale); Vector3 llGetScale(); void llSetColor(Vector3 color,int face); float llGetAlpha(int face); void llSetAlpha(float alpha,int face); Vector3 llGetColor(int face); void llSetTexture(string texture,int face); void llScaleTexture(float u,float v,int face); void llOffsetTexture(float u,float v,int face); void llRotateTexture(float rot,int face); string llGetTexture(int face); void llSetPos(Vector3 pos); Vector3 llGetPos(); Vector3 llGetLocalPos(); void llSetRot(Quaternion rot); Quaternion llGetRot(); Quaternion llGetLocalRot(); void llSetForce(Vector3 force,int local); Vector3 llGetForce(); int llTarget(Vector3 position,float range); void llTargetRemove(int number); int llRotTarget(Quaternion rot,float error); void llRotTargetRemove(int number); void llMoveToTarget(Vector3 target,float tau); void llStopMoveToTarget(); void llApplyImpulse(Vector3 force,int local); void llApplyRotationalImpulse(Vector3 force,int local); void llSetTorque(Vector3 torque,int local); Vector3 llGetTorque(); void llSetForceAndTorque(Vector3 force,Vector3 torque,int local); Vector3 llGetVel(); Vector3 iwGetAngularVelocity(); Vector3 llGetAccel(); Vector3 llGetOmega(); float llGetTimeOfDay(); float llGetWallclock(); float llGetTime(); void llResetTime(); float llGetAndResetTime(); void llSound(string sound,float volume,int queue,int loop); void llPlaySound(string sound,float volume); void llLoopSound(string sound,float volume); void llLoopSoundMaster(string sound,float volume); void llLoopSoundSlave(string sound,float volume); void llPlaySoundSlave(string sound,float volume); void llTriggerSound(string sound,float volume); void llStopSound(); void llPreloadSound(string sound); string llGetSubString(string src,int start,int end); string llDeleteSubString(string src,int start,int end); string llInsertString(string dst,int position,string src); string llToUpper(string src); string llToLower(string src); int llGiveMoney(string destination,int amount); void llMakeExplosion(int particles,float scale,float vel,float lifetime,float arc,string texture,Vector3 offset); void llMakeFountain(int particles,float scale,float vel,float lifetime,float arc,int bounce,string texture,Vector3 offset,float bounce_offset); void llMakeSmoke(int particles,float scale,float vel,float lifetime,float arc,string texture,Vector3 offset); void llMakeFire(int particles,float scale,float vel,float lifetime,float arc,string texture,Vector3 offset); void llRezObject(string inventory,Vector3 pos,Vector3 vel,Quaternion rot,int param); void llLookAt(Vector3 target,float strength,float damping); void llStopLookAt(); void llSetTimerEvent(float sec); void llSleep(float sec); float llGetMass(); void llCollisionFilter(string name,string id,int accept); void llTakeControls(int controls,int accept,int pass_on); void llReleaseControls(); void llAttachToAvatar(int attach_point); void llDetachFromAvatar(); void llTakeCamera(string avatar); void llReleaseCamera(string avatar); string llGetOwner(); void llInstantMessage(string user,string message); void llEmail(string address,string subject,string message); void llGetNextEmail(string address,string subject); string llGetKey(); void llSetBuoyancy(float buoyancy); void llSetHoverHeight(float height,int water,float tau); void llStopHover(); void llMinEventDelay(float delay); void llSoundPreload(string sound); void llRotLookAt(Quaternion target,float strength,float damping); int llStringLength(string str); void llStartAnimation(string anim); void llStopAnimation(string anim); void llPointAt(Vector3 pos); void llStopPointAt(); void llTargetOmega(Vector3 axis,float spinrate,float gain); int llGetStartParameter(); void llGodLikeRezObject(string inventory,Vector3 pos); void llRequestPermissions(string agent,int perm); string llGetPermissionsKey(); int llGetPermissions(); int llGetLinkNumber(); void llSetLinkColor(int linknumber,Vector3 color,int face); void llCreateLink(string target,int parent); void llBreakLink(int linknum); void llBreakAllLinks(); string llGetLinkKey(int linknumber); string llGetLinkName(int linknumber); int llGetInventoryNumber(int type); string llGetInventoryName(int type,int number); void llSetScriptState(string name,int run); float llGetEnergy(); void llGiveInventory(string destination,string inventory); void llRemoveInventory(string item); void llSetText(string text,Vector3 color,float alpha); float llWater(Vector3 offset); void llPassTouches(int pass); void llRequestAgentData(string id,int data); string llRequestInventoryData(string name); void llSetDamage(float damage); void llTeleportAgentHome(string id); void llModifyLand(int action,int brush); void llCollisionSound(string impact_sound,float impact_volume); void llCollisionSprite(string impact_sprite); string llGetAnimation(string id); void llResetScript(); void llMessageLinked(int linknum,int num,string str,string id); void llPushObject(string id,Vector3 impulse,Vector3 ang_impulse,int local); void llPassCollisions(int pass); string llGetScriptName(); int llGetNumberOfSides(); Quaternion llAxisAngle2Rot(Vector3 axis,float angle); Vector3 llRot2Axis(Quaternion rot); float llRot2Angle(Quaternion rot); float llAcos(float val); float llAsin(float val); float llAngleBetween(Quaternion a,Quaternion b); string llGetInventoryKey(string name); void llAllowInventoryDrop(int add); Vector3 llGetSunDirection(); Vector3 llGetTextureOffset(int face); Vector3 llGetTextureScale(int side); float llGetTextureRot(int side); int llSubStringIndex(string source,string pattern); string llGetOwnerKey(string id); Vector3 llGetCenterOfMass(); LSLList llListSort(LSLList src,int stride,int ascending); int llGetListLength(LSLList src); int llList2Integer(LSLList src,int index); float llList2Float(LSLList src,int index); string llList2String(LSLList src,int index); string llList2Key(LSLList src,int index); Vector3 llList2Vector(LSLList src,int index); Quaternion llList2Rot(LSLList src,int index); LSLList llList2List(LSLList src,int start,int end); LSLList llDeleteSubList(LSLList src,int start,int end); int llGetListEntryType(LSLList src,int index); string llList2CSV(LSLList src); LSLList llCSV2List(string src); LSLList llListRandomize(LSLList src,int stride); LSLList llList2ListStrided(LSLList src,int start,int end,int stride); Vector3 llGetRegionCorner(); LSLList llListInsertList(LSLList dest,LSLList src,int start); int llListFindList(LSLList src,LSLList test); string llGetObjectName(); void llSetObjectName(string name); string llGetDate(); int llEdgeOfWorld(Vector3 pos,Vector3 dir); int llGetAgentInfo(string id); void llAdjustSoundVolume(float volume); void llSetSoundQueueing(int queue); void llSetSoundRadius(float radius); string llKey2Name(string id); void llSetTextureAnim(int mode,int face,int sizex,int sizey,float start,float length,float rate); void llTriggerSoundLimited(string sound,float volume,Vector3 top_north_east,Vector3 bottom_south_west); void llEjectFromLand(string avatar); LSLList iwParseString2List(string src, LSLList separators, LSLList spacers, LSLList args); LSLList llParseString2List(string src,LSLList separators,LSLList spacers); int llOverMyLand(string id); string llGetLandOwnerAt(Vector3 pos); string llGetNotecardLine(string name,int line); Vector3 llGetAgentSize(string id); int llSameGroup(string id); void llUnSit(string id); Vector3 llGroundSlope(Vector3 offset); Vector3 llGroundNormal(Vector3 offset); Vector3 llGroundContour(Vector3 offset); int llGetAttached(); int llGetFreeMemory(); int llGetUsedMemory(); string llGetRegionName(); float llGetRegionTimeDilation(); float llGetRegionFPS(); void llParticleSystem(LSLList rules); void llGroundRepel(float height,int water,float tau); void llGiveInventoryList(string target,string folder,LSLList inventory); void llSetVehicleType(int type); void llSetVehicleFloatParam(int param,float value); void llSetVehicleVectorParam(int param,Vector3 vec); void llSetVehicleRotationParam(int param, Quaternion rot); void llSetVehicleFlags(int flags); void llRemoveVehicleFlags(int flags); void llSitTarget(Vector3 offset,Quaternion rot); string llAvatarOnSitTarget(); void llAddToLandPassList(string avatar,float hours); void llSetTouchText(string text); void llSetSitText(string text); void llSetCameraEyeOffset(Vector3 offset); void llSetCameraAtOffset(Vector3 offset); string llDumpList2String(LSLList src,string separator); int llScriptDanger(Vector3 pos); void llDialog(string avatar,string message,LSLList buttons,int chat_channel); void llVolumeDetect(int detect); void llResetOtherScript(string name); int llGetScriptState(string name); void llSetRemoteScriptAccessPin(int pin); void llRemoteLoadScriptPin(string target,string name,int pin,int running,int start_param); void llOpenRemoteDataChannel(); string llSendRemoteData(string channel,string dest,int idata,string sdata); void llRemoteDataReply(string channel,string message_id,string sdata,int idata); void llCloseRemoteDataChannel(string channel); string llMD5String(string src,int nonce); void llSetPrimitiveParams(LSLList rules); string llStringToBase64(string str); string llBase64ToString(string str); string llXorBase64Strings(string s1,string s2); float llLog10(float val); float llLog(float val); LSLList llGetAnimationList(string id); void llSetParcelMusicURL(string url); string llGetParcelMusicURL(); Vector3 llGetRootPosition(); Quaternion llGetRootRotation(); string llGetObjectDesc(); void llSetObjectDesc(string name); string llGetCreator(); string llGetTimestamp(); void llSetLinkAlpha(int linknumber,float alpha,int face); int llGetNumberOfPrims(); string llGetNumberOfNotecardLines(string name); LSLList llGetBoundingBox(string obj); Vector3 llGetGeometricCenter(); LSLList llGetPrimitiveParams(LSLList parms); string llIntegerToBase64(int number); int llBase64ToInteger(string str); float llGetGMTclock(); string llGetSimulatorHostname(); void llSetLocalRot(Quaternion rot); LSLList llParseStringKeepNulls(string src,LSLList separators,LSLList spacers); void llRezAtRoot(string inventory,Vector3 pos,Vector3 vel,Quaternion rot,int param); int llGetObjectPermMask(int mask); void llSetObjectPermMask(int mask,int value); int llGetInventoryPermMask(string item,int mask); void llSetInventoryPermMask(string item,int mask,int value); string llGetInventoryCreator(string item); void llOwnerSay(string msg); string llRequestSimulatorData(string simulator,int data); void llForceMouselook(int mouselook); float llGetObjectMass(string id); LSLList llListReplaceList(LSLList dest,LSLList src,int start,int end); void llLoadURL(string avatar,string message,string url); void llParcelMediaCommandList(LSLList command); LSLList llParcelMediaQuery(LSLList query); int llModPow(int a,int b,int c); int llGetInventoryType(string name); void llSetPayPrice(int price,LSLList quick_pay_buttons); Vector3 llGetCameraPos(); Quaternion llGetCameraRot(); void llSetPrimURL(string url); void llRefreshPrimURL(); string llEscapeURL(string url); string llUnescapeURL(string url); void llMapDestination(string simname,Vector3 pos,Vector3 look_at); void llAddToLandBanList(string avatar,float hours); void llRemoveFromLandPassList(string avatar); void llRemoveFromLandBanList(string avatar); void llSetCameraParams(LSLList rules); void llClearCameraParams(); float llListStatistics(int operation,LSLList src); int llGetUnixTime(); int llGetParcelFlags(Vector3 pos); int llGetRegionFlags(); string llXorBase64StringsCorrect(string s1,string s2); string llHTTPRequest(string url,LSLList parameters,string body); void llResetLandBanList(); void llResetLandPassList(); int llGetObjectPrimCount(string object_id); LSLList llGetParcelPrimOwners(Vector3 pos); int llGetParcelPrimCount(Vector3 pos,int category,int sim_wide); int llGetParcelMaxPrims(Vector3 pos,int sim_wide); LSLList llGetParcelDetails(Vector3 pos,LSLList parms); void llSetLinkPrimitiveParams(int linknumber,LSLList rules); void llSetLinkTexture(int linknumber,string texture,int face); string llStringTrim(string src,int trim_type); void llRegionSay(int channel,string msg); LSLList llGetObjectDetails(string id,LSLList parms); void llSetClickAction(int action); int llGetRegionAgentCount(); void llTextBox(string avatar,string message,int chat_channel); string llGetAgentLanguage(string avatar); Vector3 llDetectedTouchUV(int index); int llDetectedTouchFace(int index); Vector3 llDetectedTouchPos(int index); Vector3 llDetectedTouchNormal(int index); Vector3 llDetectedTouchBinormal(int index); Vector3 llDetectedTouchST(int index); string llSHA1String(string src); int llGetFreeURLs(); string llRequestURL(); string llRequestSecureURL(); void llReleaseURL(string url); void llHTTPResponse(string request_id,int status,string body); string llGetHTTPHeader(string request_id,string header); int llSetPrimMediaParams(int face,LSLList parms); int llSetLinkMedia(int link, int face, LSLList parms); LSLList llGetPrimMediaParams(int face,LSLList parms); LSLList llGetLinkMedia(int link, int face, LSLList parms); int llClearPrimMedia(int face); int llClearLinkMedia(int link, int face); void llSetLinkPrimitiveParamsFast(int linknumber,LSLList rules); LSLList llGetLinkPrimitiveParams(int linknumber,LSLList rules); void llLinkParticleSystem(int linknumber,LSLList rules); void llSetLinkTextureAnim(int link,int mode,int face,int sizex,int sizey,float start,float length,float rate); int llGetLinkNumberOfSides(int link); string llGetUsername(string id); void llRequestUsername(string id); string llGetDisplayName(string id); void llRequestDisplayName(string id); void iwMakeNotecard(string name,LSLList data); void iwAvatarName2Key(string firstName,string lastName); void iwLinkTargetOmega(int linknumber, Vector3 axis, float spinrate, float gain); int llSetRegionPos(Vector3 position); int iwGetLinkInventoryNumber(int linknumber, int type); int iwGetLinkInventoryType(int linknumber, string name); int iwGetLinkInventoryPermMask(int linknumber, string item, int mask); string iwGetLinkInventoryName(int linknumber, int type, int number); string iwGetLinkInventoryKey(int linknumber, string name); string iwGetLinkInventoryCreator(int linknumber, string item); string iwSHA256String(string src); void iwTeleportAgent(string agent, string region, Vector3 pos, Vector3 lookat); string llAvatarOnLinkSitTarget(int linknumber); string iwGetLastOwner(); void iwRemoveLinkInventory(int linknumber, string item); void iwGiveLinkInventory(int linknumber, string destination, string inventory); void iwGiveLinkInventoryList(int linknumber, string target, string folder, LSLList inventory); string iwGetNotecardSegment(string name, int line, int startOffset, int maxLength); string iwGetLinkNumberOfNotecardLines(int linknumber, string name); string iwGetLinkNotecardLine(int linknumber, string name, int line); string iwGetLinkNotecardSegment(int linknumber, string name, int line, int startOffset, int maxLength); int iwActiveGroup(string agent, string group); string iwAvatarOnLink(int linknumber); void llRegionSayTo(string destId, int channel, string msg); string iwGetLinkInventoryDesc(int linknumber, string name); string llGenerateKey(); string iwGetLinkInventoryLastOwner(int linknumber, string name); string llGetEnv(string name); void llSetAngularVelocity(Vector3 force, int local); LSLList llGetPhysicsMaterial(); void llSetPhysicsMaterial(int mask, float gravityMultiplier, float restitution, float friction, float density); void llSetVelocity(Vector3 force, int local); void iwRezObject(string inventory, Vector3 pos, Vector3 vel, Quaternion rot, int param); void iwRezAtRoot(string inventory, Vector3 pos, Vector3 vel, Quaternion rot, int param); string iwRezPrim(LSLList primParams, LSLList particleSystem, LSLList inventory, Vector3 pos, Vector3 vel, Quaternion rot, int param); LSLList llGetAgentList(int scope, LSLList options); LSLList iwGetAgentList(int scope, Vector3 minPos, Vector3 maxPos, LSLList paramList); LSLList iwGetWorldBoundingBox(string obj); int llSetMemoryLimit(int limit); int llGetMemoryLimit(); void llManageEstateAccess(int action, string avatar); int iwSubStringIndex(string source, string pattern, int offset, int isCaseSensitive); void llLinkSitTarget(int link, Vector3 offset, Quaternion rot); float llGetMassMKS(); float iwGetObjectMassMKS(string id); void llSetLinkCamera(int link, Vector3 eyeOffset, Vector3 cameraAt); void iwSetGround(int x1, int y1, int x2, int y2, float height); void llSetContentType(string request_id, int content_type); string llJsonGetValue(string json, LSLList specifiers); string llJsonValueType(string json, LSLList specifiers); string llJsonSetValue(string json, LSLList specifiers, string value); string llList2Json(string type, LSLList values); LSLList llJson2List(string src); void iwSetWind(int type, Vector3 offset, Vector3 speed); Vector3 iwWind(Vector3 offset); int iwHasParcelPowers(int groupPower); Vector3 iwGroundSurfaceNormal(Vector3 offset); string iwRequestAnimationData(string name); LSLList llCastRay(Vector3 start, Vector3 end, LSLList options); void llSetKeyframedMotion(LSLList keyframes, LSLList options); int iwGetLocalTime(); int iwGetLocalTimeOffset(); string iwFormatTime(int unixtime, int isUTC, string format); int iwCheckRezError(Vector3 pos, int isTemp, int landImpact); void botCreateBot(string FirstName, string LastName, string outfitName, Vector3 startPos, int options);//Returns string via async return void botAddTag(string botID, string tag); void botRemoveTag(string botID, string tag); LSLList botGetBotsWithTag(string tag); void botRemoveBotsWithTag(string tag); void botRemoveBot(string botID); void botPauseMovement(string botID); void botResumeMovement(string botID); void botWhisper(string botID, int channel, string message); void botSay(string botID, int channel, string message); void botShout(string botID, int channel, string message); void botStartTyping(string botID); void botStopTyping(string botID); void botSendInstantMessage(string botID, string userID, string message); void botSitObject(string botID, string objectID); void botStandUp(string botID); string botGetOwner(string botID); int botIsBot(string userID); void botTouchObject(string bot, string objectID); void botSetMovementSpeed(string botID, float speed); Vector3 botGetPos(string botID); string botGetName(string botID); void botStartAnimation(string botID, string animation); void botStopAnimation(string botID, string animation); void botTeleportTo(string botID, Vector3 position); void botChangeOwner(string botID, string newOwnerID); LSLList botGetAllBotsInRegion(); LSLList botGetAllMyBotsInRegion(); int botFollowAvatar(string botID, string avatar, LSLList options); void botStopMovement(string botID); void botSetNavigationPoints(string botID, LSLList positions, LSLList movementTypes, LSLList options); void botRegisterForNavigationEvents(string botID); void botSetProfile(string botID, string aboutText, string email, string firstLifeAboutText, string firstLifeImageUUID, string imageUUID, string profileURL); void botSetRotation(string botID, Quaternion rotation); void botGiveInventory(string botID, string destination, string inventory); void botSensor(string botID, string name, string id, int type, float range, float arc); void botSensorRepeat(string botID, string name, string id, int type, float range, float arc, float rate); void botSensorRemove(); string iwDetectedBot(); int botListen(string botID, int channel, string name, string id, string msg); void botRegisterForCollisionEvents(string botID); void botDeregisterFromCollisionEvents(string botID); void botDeregisterFromNavigationEvents(string botID); void botSetOutfit(string outfitName); void botRemoveOutfit(string outfitName); void botChangeOutfit(string botID, string outfitName); void botGetBotOutfits();//Returns LSLList via async return void botWanderWithin(string botID, Vector3 origin, float xDistance, float yDistance, LSLList options); void botMessageLinked(string botID, int num, string msg, string id); void botSetProfileParams(string botID, LSLList profileInformation); LSLList botGetProfileParams(string botID, LSLList profileInformation); int iwGetAppearanceParam(string who, int which); int iwChar2Int(string src, int index); string iwInt2Char(int num); string iwReplaceString(string str, string pattern, string replacement); string iwFormatString(string str, LSLList values); int iwMatchString(string str, string pattern, int matchType); string iwStringCodec(string str, string pattern, int operation, LSLList extraParams); int iwMatchList(LSLList list1, LSLList list2, int matchType); Vector3 iwColorConvert(Vector3 input, int color1, int color2); Vector3 iwNameToColor(string name); int iwVerifyType(string str, int type); int iwGroupInvite(string group, string user, string role); int iwGroupEject(string group, string user); string iwGetAgentData(string id, int data); int iwIsPlusUser(string id); void llAttachToAvatarTemp(int attachPoint); } }
namespace AngleSharp.Html.Parser { using AngleSharp.Dom; using AngleSharp.Html.Parser.Tokens; using AngleSharp.Mathml.Dom; using AngleSharp.Svg.Dom; using AngleSharp.Text; using System; using System.Collections.Generic; /// <summary> /// A collection of useful helpers when working with foreign content. /// </summary> static class HtmlForeignExtensions { #region Fields private static readonly Dictionary<String, String> svgAttributeNames = new Dictionary<String, String>(StringComparer.Ordinal) { { "attributename", "attributeName" }, { "attributetype", "attributeType" }, { "basefrequency", "baseFrequency" }, { "baseprofile", "baseProfile" }, { "calcmode", "calcMode" }, { "clippathunits", "clipPathUnits" }, { "contentscripttype", "contentScriptType" }, { "contentstyletype", "contentStyleType" }, { "diffuseconstant", "diffuseConstant" }, { "edgemode", "edgeMode" }, { "externalresourcesrequired", "externalResourcesRequired" }, { "filterres", "filterRes" }, { "filterunits", "filterUnits" }, { "glyphref", "glyphRef" }, { "gradienttransform", "gradientTransform" }, { "gradientunits", "gradientUnits" }, { "kernelmatrix", "kernelMatrix" }, { "kernelunitlength", "kernelUnitLength" }, { "keypoints", "keyPoints" }, { "keysplines", "keySplines" }, { "keytimes", "keyTimes" }, { "lengthadjust", "lengthAdjust" }, { "limitingconeangle", "limitingConeAngle" }, { "markerheight", "markerHeight" }, { "markerunits", "markerUnits" }, { "markerwidth", "markerWidth" }, { "maskcontentunits", "maskContentUnits" }, { "maskunits", "maskUnits" }, { "numoctaves", "numOctaves" }, { "pathlength", "pathLength" }, { "patterncontentunits", "patternContentUnits" }, { "patterntransform", "patternTransform" }, { "patternunits", "patternUnits" }, { "pointsatx", "pointsAtX" }, { "pointsaty", "pointsAtY" }, { "pointsatz", "pointsAtZ" }, { "preservealpha", "preserveAlpha" }, { "preserveaspectratio", "preserveAspectRatio" }, { "primitiveunits", "primitiveUnits" }, { "refx", "refX" }, { "refy", "refY" }, { "repeatcount", "repeatCount" }, { "repeatdur", "repeatDur" }, { "requiredextensions", "requiredExtensions" }, { "requiredfeatures", "requiredFeatures" }, { "specularconstant", "specularConstant" }, { "specularexponent", "specularExponent" }, { "spreadmethod", "spreadMethod" }, { "startoffset", "startOffset" }, { "stddeviation", "stdDeviation" }, { "stitchtiles", "stitchTiles" }, { "surfacescale", "surfaceScale" }, { "systemlanguage", "systemLanguage" }, { "tablevalues", "tableValues" }, { "targetx", "targetX" }, { "targety", "targetY" }, { "textlength", "textLength" }, { "viewbox", "viewBox" }, { "viewtarget", "viewTarget" }, { "xchannelselector", "xChannelSelector" }, { "ychannelselector", "yChannelSelector" }, { "zoomandpan", "zoomAndPan" }, }; private static readonly Dictionary<String, String> svgAdjustedTagNames = new Dictionary<String, String>(StringComparer.Ordinal) { { "altglyph", "altGlyph" }, { "altglyphdef", "altGlyphDef" }, { "altglyphitem", "altGlyphItem" }, { "animatecolor", "animateColor" }, { "animatemotion", "animateMotion" }, { "animatetransform", "animateTransform" }, { "clippath", "clipPath" }, { "feblend", "feBlend" }, { "fecolormatrix", "feColorMatrix" }, { "fecomponenttransfer", "feComponentTransfer" }, { "fecomposite", "feComposite" }, { "feconvolvematrix", "feConvolveMatrix" }, { "fediffuselighting", "feDiffuseLighting" }, { "fedisplacementmap", "feDisplacementMap" }, { "fedistantlight", "feDistantLight" }, { "feflood", "feFlood" }, { "fefunca", "feFuncA" }, { "fefuncb", "feFuncB" }, { "fefuncg", "feFuncG" }, { "fefuncr", "feFuncR" }, { "fegaussianblur", "feGaussianBlur" }, { "feimage", "feImage" }, { "femerge", "feMerge" }, { "femergenode", "feMergeNode" }, { "femorphology", "feMorphology" }, { "feoffset", "feOffset" }, { "fepointlight", "fePointLight" }, { "fespecularlighting", "feSpecularLighting" }, { "fespotlight", "feSpotLight" }, { "fetile", "feTile" }, { "feturbulence", "feTurbulence" }, { "foreignobject", "foreignObject" }, { "glyphref", "glyphRef" }, { "lineargradient", "linearGradient" }, { "radialgradient", "radialGradient" }, { "textpath", "textPath" } }; #endregion #region Methods /// <summary> /// Adjusts the tag name to the correct capitalization. /// </summary> /// <param name="localName">The name of adjust.</param> /// <returns>The name with the correct capitalization.</returns> public static String SanatizeSvgTagName(this String localName) { if (svgAdjustedTagNames.TryGetValue(localName, out var adjustedTagName)) { return adjustedTagName; } return localName; } /// <summary> /// Setups a new math element with the attributes from the token. /// </summary> /// <param name="element">The element to setup.</param> /// <param name="tag">The tag token to use.</param> /// <returns>The finished element.</returns> public static MathElement Setup(this MathElement element, HtmlTagToken tag) { var count = tag.Attributes.Count; for (var i = 0; i < count; i++) { var attr = tag.Attributes[i]; var name = attr.Name; var value = attr.Value; element.AdjustAttribute(name.AdjustToMathAttribute(), value); } return element; } /// <summary> /// Setups a new SVG element with the attributes from the token. /// </summary> /// <param name="element">The element to setup.</param> /// <param name="tag">The tag token to use.</param> /// <returns>The finished element.</returns> public static SvgElement Setup(this SvgElement element, HtmlTagToken tag) { var count = tag.Attributes.Count; for (var i = 0; i < count; i++) { var attr = tag.Attributes[i]; var name = attr.Name; var value = attr.Value; element.AdjustAttribute(name.AdjustToSvgAttribute(), value); } return element; } /// <summary> /// Adds the attribute with the adjusted prefix, namespace and name. /// </summary> /// <param name="element">The element to host the attribute.</param> /// <param name="name">The name of the attribute.</param> /// <param name="value">The value of the attribute.</param> public static void AdjustAttribute(this Element element, String name, String value) { var ns = default(String); if (IsXLinkAttribute(name)) { var newName = name.Substring(name.IndexOf(Symbols.Colon) + 1); if (newName.IsXmlName() && newName.IsQualifiedName()) { ns = NamespaceNames.XLinkUri; name = newName; } } else if (IsXmlAttribute(name)) { ns = NamespaceNames.XmlUri; } else if (IsXmlNamespaceAttribute(name)) { ns = NamespaceNames.XmlNsUri; } if (ns is null) { element.SetOwnAttribute(name, value); } else { element.SetAttribute(ns, name, value); } } /// <summary> /// Adjusts the attribute name to the correct capitalization. /// </summary> /// <param name="attributeName">The name of adjust.</param> /// <returns>The name with the correct capitalization.</returns> public static String AdjustToMathAttribute(this String attributeName) { if (attributeName is "definitionurl") { return "definitionURL"; } return attributeName; } /// <summary> /// Adjusts the attribute name to the correct capitalization. /// </summary> /// <param name="attributeName">The name of adjust.</param> /// <returns>The name with the correct capitalization.</returns> public static String AdjustToSvgAttribute(this String attributeName) { if (svgAttributeNames.TryGetValue(attributeName, out var adjustedAttributeName)) { return adjustedAttributeName; } return attributeName; } #endregion #region Helpers private static Boolean IsXmlNamespaceAttribute(String name) => name.Length > 4 && (name.Is(NamespaceNames.XmlNsPrefix) || name is "xmlns:xlink"); private static Boolean IsXmlAttribute(String name) => (name.Length > 7 && "xml:".EqualsSubset(name, 0, 4)) && (TagNames.Base.EqualsSubset(name, 4, 4) || AttributeNames.Lang.EqualsSubset(name, 4, 4) || AttributeNames.Space.EqualsSubset(name, 4, 5)); private static Boolean IsXLinkAttribute(String name) => (name.Length > 9 && "xlink:".EqualsSubset(name, 0, 6)) && (AttributeNames.Actuate.EqualsSubset(name, 6, 7) || AttributeNames.Arcrole.EqualsSubset(name, 6, 7) || AttributeNames.Href.EqualsSubset(name, 6, 4) || AttributeNames.Role.EqualsSubset(name, 6, 4) || AttributeNames.Show.EqualsSubset(name, 6, 4) || AttributeNames.Type.EqualsSubset(name, 6, 4) || AttributeNames.Title.EqualsSubset(name, 6, 5)); private static Boolean EqualsSubset(this String a, String b, Int32 index, Int32 length) => String.Compare(a, 0, b, index, length, StringComparison.Ordinal) == 0; #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace SpaStore.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { private const int DefaultCollectionSize = 3; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// // Copyright (c) 2004-2021 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.Collections.Generic; using System.Linq; using NLog.Config; using NLog.Targets; using Xunit; namespace NLog.UnitTests.Targets { public class MethodCallTests : NLogTestBase { private const string CorrectClassName = "NLog.UnitTests.Targets.MethodCallTests, NLog.UnitTests"; #region ToBeCalled Methods #pragma warning disable xUnit1013 //we need public methods here private static MethodCallRecord LastCallTest; public static void StaticAndPublic(string param1, int param2) { LastCallTest = new MethodCallRecord("StaticAndPublic", param1, param2); } public static void StaticAndPublicWrongParameters(string param1, string param2) { LastCallTest = new MethodCallRecord("StaticAndPublic", param1, param2); } public static void StaticAndPublicTooLessParameters(string param1) { LastCallTest = new MethodCallRecord("StaticAndPublicTooLessParameters", param1); } public static void StaticAndPublicTooManyParameters(string param1, int param2, string param3) { LastCallTest = new MethodCallRecord("StaticAndPublicTooManyParameters", param1, param2); } public static void StaticAndPublicOptional(string param1, int param2, string param3 = "fixedValue") { LastCallTest = new MethodCallRecord("StaticAndPublicOptional", param1, param2, param3); } public void NonStaticAndPublic() { LastCallTest = new MethodCallRecord("NonStaticAndPublic"); } public static void StaticAndPrivate() { LastCallTest = new MethodCallRecord("StaticAndPrivate"); } #pragma warning restore xUnit1013 #endregion [Fact] public void TestMethodCall1() { TestMethodCall(new MethodCallRecord("StaticAndPublic", "test1", 2), "StaticAndPublic", CorrectClassName); } [Fact] public void TestMethodCall2() { //Type AssemblyQualifiedName //to find, use typeof(MethodCallTests).AssemblyQualifiedName TestMethodCall(new MethodCallRecord("StaticAndPublic", "test1", 2), "StaticAndPublic", "NLog.UnitTests.Targets.MethodCallTests, NLog.UnitTests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b793d3de60bec2b9"); } [Fact] public void PrivateMethodDontThrow() { using (new NoThrowNLogExceptions()) { TestMethodCall(null, "NonStaticAndPublic", CorrectClassName); } } [Fact] public void WrongClassDontThrow() { TestMethodCall(null, "StaticAndPublic", "NLog.UnitTests222.Targets.CallTest, NLog.UnitTests"); } [Fact] public void WrongParametersDontThrow() { using (new NoThrowNLogExceptions()) { TestMethodCall(null, "StaticAndPublicWrongParameters", CorrectClassName); } } [Fact] public void TooLessParametersDontThrow() { using (new NoThrowNLogExceptions()) { TestMethodCall(null, "StaticAndPublicTooLessParameters", CorrectClassName); } } [Fact] public void TooManyParametersDontThrow() { using (new NoThrowNLogExceptions()) { TestMethodCall(null, "StaticAndPublicTooManyParameters", CorrectClassName); } } [Fact] public void OptionalParameters() { TestMethodCall(new MethodCallRecord("StaticAndPublicOptional", "test1", 2, "fixedValue"), "StaticAndPublicOptional", CorrectClassName); } [Fact] public void FluentDelegateConfiguration() { var configuration = new LoggingConfiguration(); string expectedMessage = "Hello World"; string actualMessage = string.Empty; configuration.AddRuleForAllLevels(new MethodCallTarget("Hello", (logEvent, parameters) => { actualMessage = logEvent.Message; })); LogManager.Configuration = configuration; LogManager.GetCurrentClassLogger().Debug(expectedMessage); Assert.Equal(expectedMessage, actualMessage); } private static void TestMethodCall(MethodCallRecord expected, string methodName, string className) { var target = new MethodCallTarget { Name = "t1", ClassName = className, MethodName = methodName }; target.Parameters.Add(new MethodCallParameter("param1", "test1")); target.Parameters.Add(new MethodCallParameter("param2", "2", typeof(int))); var configuration = new LoggingConfiguration(); configuration.AddTarget(target); configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, target)); LogManager.Configuration = configuration; LastCallTest = null; LogManager.GetCurrentClassLogger().Debug("test method 1"); Assert.Equal(expected, LastCallTest); } private class MethodCallRecord { /// <summary> /// Initializes a new instance of the <see cref="T:System.Object"/> class. /// </summary> public MethodCallRecord(string method, params object[] parameterValues) { Method = method; if (parameterValues != null) ParameterValues = parameterValues.ToList(); } public string Method { get; set; } public List<object> ParameterValues { get; set; } protected bool Equals(MethodCallRecord other) { return string.Equals(Method, other.Method) && ParameterValues.SequenceEqual(other.ParameterValues); } /// <summary> /// Determines whether the specified object is equal to the current object. /// </summary> /// <returns> /// true if the specified object is equal to the current object; otherwise, false. /// </returns> /// <param name="obj">The object to compare with the current object. </param> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return Equals((MethodCallRecord)obj); } /// <summary> /// Serves as the default hash function. /// </summary> /// <returns> /// A hash code for the current object. /// </returns> public override int GetHashCode() { unchecked { return ((Method != null ? Method.GetHashCode() : 0) * 397) ^ (ParameterValues != null ? ParameterValues.GetHashCode() : 0); } } } } }
using Xunit; namespace NeinLinq.Tests; public class PredicateTranslatorTest { [Fact] public void Translate_NullArgument_Throws() { var error = Assert.Throws<ArgumentNullException>(() => PredicateTranslator.Translate<Model>(null!)); Assert.Equal("predicate", error.ParamName); } [Fact] public void And_NullArgument_Throws() { Expression<Func<IModel, bool>> p = _ => false; Expression<Func<IModel, bool>> q = _ => false; var leftError = Assert.Throws<ArgumentNullException>(() => PredicateTranslator.And(null!, q)); var rightError = Assert.Throws<ArgumentNullException>(() => PredicateTranslator.And(p, null!)); Assert.Equal("left", leftError.ParamName); Assert.Equal("right", rightError.ParamName); } [Fact] public void And_Combines() { Expression<Func<IModel, bool>> p = d => d.Id % 2 == 1; Expression<Func<IModel, bool>> q = d => d.Name == "Narf"; var r = CreateQuery().Where(p).Count(); var s = CreateQuery().Where(q).Count(); var t = CreateQuery().Where(p.And(q)).Count(); Assert.Equal(6, r); Assert.Equal(4, s); Assert.Equal(2, t); } [Fact] public void Or_NullArgument_Throws() { Expression<Func<IModel, bool>> p = _ => false; Expression<Func<IModel, bool>> q = _ => false; var leftError = Assert.Throws<ArgumentNullException>(() => PredicateTranslator.Or(null!, q)); var rightError = Assert.Throws<ArgumentNullException>(() => PredicateTranslator.Or(p, null!)); Assert.Equal("left", leftError.ParamName); Assert.Equal("right", rightError.ParamName); } [Fact] public void Or_Combines() { Expression<Func<IModel, bool>> p = d => d.Id % 2 == 1; Expression<Func<IModel, bool>> q = d => d.Name == "Narf"; var r = CreateQuery().Where(p).Count(); var s = CreateQuery().Where(q).Count(); var t = CreateQuery().Where(p.Or(q)).Count(); Assert.Equal(6, r); Assert.Equal(4, s); Assert.Equal(8, t); } [Fact] public void Not_NullArgument_Throws() { var error = Assert.Throws<ArgumentNullException>(() => PredicateTranslator.Not<IModel>(null!)); Assert.Equal("predicate", error.ParamName); } [Fact] public void Not_Negates() { Expression<Func<IModel, bool>> p = d => d.Name == "Narf"; var r = CreateQuery().Where(p).Count(); var s = CreateQuery().Where(p.Not()).Count(); Assert.Equal(4, r); Assert.Equal(8, s); } [Fact] public void To_Substitutes() { Expression<Func<Model, bool>> p = d => d.Name == "Narf"; var r = CreateQuery().OfType<Model>().Where(p).Count(); var s = CreateQuery().OfType<SpecialModel>().Where(p.Translate().To<SpecialModel>()).Count(); Assert.Equal(2, r); Assert.Equal(1, s); } [Fact] public void ToPath_NullArgument_Throws() { Expression<Func<ParentModel, bool>> p = _ => false; var error = Assert.Throws<ArgumentNullException>(() => p.Translate().To((Expression<Func<ChildModel, ParentModel>>)null!)); Assert.Equal("path", error.ParamName); } [Fact] public void ToPath_Substitutes() { Expression<Func<ParentModel, bool>> p = d => d.Name == "Narf"; var r = CreateQuery().OfType<ParentModel>().Where(p).Count(); var s = CreateQuery().OfType<ChildModel>().Where(p.Translate().To<ChildModel>(c => c.Parent)).Count(); Assert.Equal(1, r); Assert.Equal(1, s); } [Fact] public void ToTranslation_NullArgument_Throws() { Expression<Func<ChildModel, bool>> p = _ => false; var error = Assert.Throws<ArgumentNullException>(() => p.Translate().To((Expression<Func<ParentModel, Func<ChildModel, bool>, bool>>)null!)); Assert.Equal("translation", error.ParamName); } [Fact] public void ToTranslation_Substitutes() { Expression<Func<ChildModel, bool>> p = d => d.Name == "Narf"; var r = CreateQuery().OfType<ChildModel>().Where(p).Count(); var s = CreateQuery().OfType<ParentModel>().Where(p.Translate().To<ParentModel>((b, q) => b.Children.Any(q))).Count(); Assert.Equal(1, r); Assert.Equal(2, s); } private static IQueryable<IModel> CreateQuery() { var d = new[] { new Model { Id = 1, Name = "Asdf" }, new Model { Id = 2, Name = "Narf" }, new Model { Id = 3, Name = "Qwer" } }; var s = new[] { new SpecialModel { Id = 4, Name = "Asdf" }, new SpecialModel { Id = 5, Name = "Narf" }, new SpecialModel { Id = 6, Name = "Qwer" } }; var p = new[] { new ParentModel { Id = 7, Name = "Asdf" }, new ParentModel { Id = 8, Name = "Narf" }, new ParentModel { Id = 9, Name = "Qwer" } }; var c = new[] { new ChildModel { Id = 10, Name = "Asdf", Parent = p[1] }, new ChildModel { Id = 11, Name = "Narf", Parent = p[2] }, new ChildModel { Id = 12, Name = "Qwer", Parent = p[0] } }; p[0].Children = new[] { c[0], c[1] }; p[1].Children = new[] { c[1], c[2] }; p[2].Children = new[] { c[0], c[2] }; return d.Concat<IModel>(s).Concat(p).Concat(c).AsQueryable(); } private interface IModel { int Id { get; set; } string Name { get; set; } } private class Model : IModel { public int Id { get; set; } public string Name { get; set; } = null!; } private class SpecialModel : Model { public string Description { get; set; } = null!; } private class ParentModel : IModel { public int Id { get; set; } public string Name { get; set; } = null!; public ICollection<ChildModel> Children { get; set; } = null!; } private class ChildModel : IModel { public int Id { get; set; } public string Name { get; set; } = null!; public ParentModel Parent { get; set; } = null!; } }
using System; using System.Diagnostics; using NS_IDraw; using Curve=NS_GMath.I_CurveD; using LCurve=NS_GMath.I_LCurveD; namespace NS_GMath { public class RayD : LCurve { /* * ENUMS */ public enum TypeParity { ParityUndef=-1, ParityEven, ParityOdd }; /* * MEMBERS */ private VecD[] cp; /* * CONSTRUCTORS */ private RayD() { this.cp=new VecD[2]; } public RayD(VecD start, VecD end): this() { this.cp[0]=new VecD(start); this.cp[1]=new VecD(end); } public RayD(RayD ray) : this() { this.cp[0]=new VecD(ray.Start); this.cp[1]=new VecD(ray.End); } /* * METHODS : GEOMETRY */ VecD LCurve.DirTang { get { if (this.IsDegen) return null; return ((1/(this.cp[1]-this.cp[0]).Norm)*(this.cp[1]-this.cp[0])); } } VecD LCurve.DirNorm { get { VecD dirTang=(this as LCurve).DirTang; if (dirTang==null) return null; return new VecD(-dirTang.Y, dirTang.X); } } Curve Curve.Copy() { return new RayD(this); } public VecD Cp(int i) { if ((i<0)||(i>=1)) return null; return this.cp[i]; } public bool IsSimple { get { return true; } } public bool IsBounded { get { return false; } } public bool IsDegen { get { return (this.cp[0]==this.cp[1]); } } public int LComplexity { get { return 1; } } public bool IsValid { get { return (!this.IsDegen); } } public double CurveLength(Param parS, Param parE) { if ((!this.IsEvaluableStrict(parS))||(!this.IsEvaluableStrict(parE))) { throw new ExceptionGMath("RayD","CurveLength",null); } double length=Math.Abs(parE-parS)*(this.cp[1]-this.cp[0]).Norm; if (Math.Abs(length)>=MConsts.Infinity) { length=MConsts.Infinity*Math.Sign(length); } return length; } public double CurveLength() { return MConsts.Infinity; } public void Reverse() { this.cp[1].From(-this.cp[1].X,-this.cp[1].Y); } public Curve Reversed { get { RayD rayRev=new RayD(this); rayRev.Reverse(); return rayRev; } } VecD Curve.DirTang(Param par) { return ((LCurve)this).DirTang; } VecD Curve.DirNorm(Param par) { return ((LCurve)this).DirNorm; } public double Curvature(Param par) { return 0; } public VecD Start { get { return this.cp[0]; } } public VecD End { get { return this.cp[1]; } } public double ParamStart { get { return 0; } } public double ParamEnd { get { return Param.Infinity; } } public double ParamReverse { get { return 0; } } public Param.TypeParam ParamClassify(Param par) { par.Clip(-Param.Infinity,Param.Infinity); par.Round(0); double val=par.Val; if (val==Param.Degen) return Param.TypeParam.Invalid; if (val==Param.Invalid) return Param.TypeParam.Invalid; if (val<0) { return Param.TypeParam.Before; } else if (val==0) { return Param.TypeParam.Start; } else { return Param.TypeParam.Inner; } } public RayD.TypeParity RayParity(RayD ray, bool isStartOnGeom) { throw new ExceptionGMath("RayD","RayParity","NOT IMPLEMENTED"); //return RayD.TypeParity.ParityUndef; } public void Transform(MatrixD m) { throw new ExceptionGMath("RayD","Transform","NOT IMPLEMENTED"); } public void PowerCoeff(out VecD[] pcf) { pcf=new VecD[2]; pcf[1]=this.cp[1]-this.cp[0]; pcf[0]=this.cp[0]; } public BoxD BBox { get { if (this.IsDegen) { throw new ExceptionGMath("RayD","BBox",null); } double xMin, yMin, xMax, yMax; if (this.Cp(0).X<this.Cp(1).X) { xMin=this.Cp(0).X; xMax=MConsts.Infinity; } else { xMin=-MConsts.Infinity; xMax=this.Cp(0).X; } if (this.Cp(0).Y<this.Cp(1).Y) { yMin=this.Cp(0).Y; yMax=MConsts.Infinity; } else { yMin=-MConsts.Infinity; yMax=this.Cp(0).Y; } BoxD box=new BoxD(xMin,yMin,xMax,yMax); return box; } } public bool IsEvaluableWide(Param par) { return ((par.IsValid)&&(!par.IsDegen)); } public bool IsEvaluableStrict(Param par) { if ((par.IsDegen)||(!par.IsValid)) return false; par.Round(this.ParamStart,this.ParamEnd); if (par.Val<0) return false; return true; } public VecD Evaluate(Param par) { if (!this.IsEvaluableWide(par)) { throw new ExceptionGMath("RayD","Evaluate",null); //return null; } if (par.IsInfinite) return null; return (1-par)*this.cp[0]+par*this.cp[1]; } /* * METHODS: I_DRAWABLE */ public void Draw(I_Draw i_draw, DrawParam dp) { DrawParamCurve dpCurve= dp as DrawParamCurve; if (dpCurve!=null) { if (!this.IsDegen) { VecD endToDraw=this.Start+i_draw.DrawWorldInfinity*(this as LCurve).DirTang; i_draw.DrawSeg(this.cp[0].X, this.cp[0].Y, endToDraw.X, endToDraw.Y, dpCurve.StrColor,dpCurve.ScrWidth); } } if (dpCurve.ToDrawEndPoints) { this.Cp(0).Draw(i_draw,dpCurve.DPEndPoints); this.Cp(1).Draw(i_draw,dpCurve.DPEndPoints); } } } }
#if UNITY_EDITOR using UnityEngine; using UnityEditor; using System; using System.IO; using System.Text.RegularExpressions; namespace UMA.AssetBundles { public class UMAAssetBundleManagerSettings : EditorWindow { #region PUBLIC FIELDS public const string DEFAULT_ENCRYPTION_SUFFIX = "encrypted"; #endregion #region PRIVATE FIELDS //AssetBundle settings related string currentEncryptionPassword = ""; string newEncryptionPassword = ""; string currentEncryptionSuffix = ""; string newEncryptionSuffix = ""; bool currentEncodeNamesSetting = false; #if ENABLE_IOS_APP_SLICING bool currentAppSlicingSetting = false; #endif bool newEncodeNamesSetting = false; //DOS MODIFIED 14/11/2017 added a ability to set the new bundlesPlayerVersion value bool _enableBundleIndexVersioning; //either automatically use the Buildversion from player settings or specify a value here UMAABMSettingsStore.BundleIndexVersioningOpts _bundleIndexVersioningMethod = UMAABMSettingsStore.BundleIndexVersioningOpts.UseBuildVersion; //if useBundlesVersioning is set to Custom this value is used when the bundles are built string _bundleIndexCustomValue = "0.0"; //server related bool _enableLocalAssetBundleServer; int _port; string _statusMessage; string[] _hosts; string _activeHost; bool portError = false; bool serverException = false; //Testing Build related bool developmentBuild = false; //GUI related Vector2 scrollPos; bool serverRequestLogOpen = true; bool manualEditEncryptionKey = false; bool encryptionSaveButEnabled = false; bool manualEditEncryptionSuffix = false; bool encryptionKeysEnabled = false; #endregion #region PUBLIC PROPERTIES #endregion #region PRIVATE PROPERTIES //server related bool EnableLocalAssetBundleServer { get { return _enableLocalAssetBundleServer; } set { if (_enableLocalAssetBundleServer == value) return; _enableLocalAssetBundleServer = value; EditorPrefs.SetBool(Application.dataPath+"LocalAssetBundleServerEnabled", value); UpdateServer(); } } int Port { get { return _port; } set { if (_port == value) return; _port = value; EditorPrefs.SetInt(Application.dataPath+"LocalAssetBundleServerPort", _port); UpdateServer(); } } string ActiveHost { get { return _activeHost; } set { if (_activeHost == value) return; _activeHost = value; EditorPrefs.SetString(Application.dataPath+"LocalAssetBundleServerURL", _activeHost); } } #endregion #region BASE METHODS [MenuItem("Assets/AssetBundles/UMA Asset Bundle Manager Settings")] [MenuItem("UMA/UMA Asset Bundle Manager Settings")] static void Init() { UMAAssetBundleManagerSettings window = (UMAAssetBundleManagerSettings)EditorWindow.GetWindow<UMAAssetBundleManagerSettings>("UMA AssetBundle Manager"); window.Show(); } void OnFocus() { encryptionKeysEnabled = UMAABMSettings.GetEncryptionEnabled(); currentEncryptionPassword = newEncryptionPassword = UMAABMSettings.GetEncryptionPassword(); currentEncryptionSuffix = newEncryptionSuffix = UMAABMSettings.GetEncryptionSuffix(); if (currentEncryptionSuffix == "") currentEncryptionSuffix = newEncryptionSuffix = DEFAULT_ENCRYPTION_SUFFIX; currentEncodeNamesSetting = newEncodeNamesSetting = UMAABMSettings.GetEncodeNames(); #if ENABLE_IOS_APP_SLICING currentAppSlicingSetting = UMAABMSettings.GetBuildForSlicing(); #endif _enableBundleIndexVersioning = UMAABMSettings.EnableBundleIndexVersioning; } void OnEnable() { encryptionKeysEnabled = UMAABMSettings.GetEncryptionEnabled(); currentEncryptionPassword = newEncryptionPassword = UMAABMSettings.GetEncryptionPassword(); currentEncryptionSuffix = newEncryptionSuffix = UMAABMSettings.GetEncryptionSuffix(); if (currentEncryptionSuffix == "") currentEncryptionSuffix = newEncryptionSuffix = DEFAULT_ENCRYPTION_SUFFIX; currentEncodeNamesSetting = newEncodeNamesSetting = UMAABMSettings.GetEncodeNames(); #if ENABLE_IOS_APP_SLICING currentAppSlicingSetting = UMAABMSettings.GetBuildForSlicing(); #endif _enableBundleIndexVersioning = UMAABMSettings.EnableBundleIndexVersioning; //localAssetBundleServer status _enableLocalAssetBundleServer = EditorPrefs.GetBool(Application.dataPath+"LocalAssetBundleServerEnabled"); _port = EditorPrefs.GetInt(Application.dataPath + "LocalAssetBundleServerPort", 7888); //When the window is opened we still need to tell the user if the port is available so if (!_enableLocalAssetBundleServer) { UpdateServer(true); ServerStop(); if (serverException) portError = true; } else { UpdateServer(); } } void Start() { ServerStart(); } void OnDisable() { //Makes the Local server stop when the window is closed //also prevents the 'Listener already in use' error when the window is closed and opened ServerStop(); } #endregion #region SERVER RELATED METHODS void ServerStart() { SimpleWebServer.Start(_port); _statusMessage = "Server Running"; UpdateHosts(); if (_activeHost == null) { ActiveHost = _hosts[0]; } SimpleWebServer.ServerURL = ActiveHost; } void ServerStop() { if (SimpleWebServer.Instance != null) { SimpleWebServer.Instance.Stop(); SimpleWebServer.ServerURL = ""; _statusMessage = "Server Stopped"; _hosts = null; } } void UpdateHosts() { var strHostName = System.Net.Dns.GetHostName(); var list = new System.Collections.Generic.List<string>(); try { var ipEntry = System.Net.Dns.GetHostEntry(strHostName); foreach (var addr in ipEntry.AddressList) { if (addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { list.Add(string.Format("http://{0}:{1}/", addr, Port)); } } } catch(Exception ex) { Debug.Log(ex.Message); strHostName = "localhost"; } if (list.Count == 0) { list.Add(string.Format("http://localhost:{0}/", Port)); } portError = false; _hosts = list.ToArray(); } private void UpdateServer(bool test = false) { serverException = false; try { if (SimpleWebServer.Instance != null) { if (!EnableLocalAssetBundleServer) { ServerStop(); Debug.Log("Server Stopped"); } else if (SimpleWebServer.Instance.Port != _port) { ServerStop(); ServerStart(); Debug.Log("Server Started"); } } else if (EnableLocalAssetBundleServer || test) { ServerStart(); if (!test) Debug.Log("Server Started"); } } catch (Exception e) { _statusMessage = string.Format("Simple Webserver Exception: {0}\nStack Trace\n{1}", e.ToString(), e.StackTrace); Debug.LogException(e); EditorPrefs.SetBool(Application.dataPath + "LocalAssetBundleServerEnabled", false); EnableLocalAssetBundleServer = false; serverException = true; ServerStop(); } } #endregion void OnGUI() { scrollPos = EditorGUILayout.BeginScrollView(scrollPos, false, true); EditorGUILayout.BeginVertical(GUILayout.Width(EditorGUIUtility.currentViewWidth - 20f)); EditorGUILayout.Space(); GUILayout.Label("UMA AssetBundle Manager", EditorStyles.boldLabel); BeginVerticalPadded(5, new Color(0.75f, 0.875f, 1f)); GUILayout.Label("AssetBundle Options", EditorStyles.boldLabel); //AssetBundle Build versioning EditorGUI.BeginChangeCheck(); _enableBundleIndexVersioning = EditorGUILayout.ToggleLeft("Enable AssetBundle Index Versioning", _enableBundleIndexVersioning); if (EditorGUI.EndChangeCheck()) { UMAABMSettings.EnableBundleIndexVersioning = _enableBundleIndexVersioning; } if (_enableBundleIndexVersioning) { BeginVerticalIndented(10, new Color(0.75f, 0.875f, 1f)); EditorGUILayout.HelpBox("Sets the 'bundlesPlayerVersion' value of the AssetBundleIndex when you build your bundles. You can use this to determine if your app needs to force the user to go online to update their bundles and/or application (its up to you how you do that though!). ", MessageType.Info); EditorGUI.BeginChangeCheck(); _bundleIndexVersioningMethod = (UMAABMSettingsStore.BundleIndexVersioningOpts)EditorGUILayout.EnumPopup("Bundles Versioning Method", _bundleIndexVersioningMethod); if (EditorGUI.EndChangeCheck()) { UMAABMSettings.BundleIndexVersioningMethod = _bundleIndexVersioningMethod; } if(_bundleIndexVersioningMethod == UMAABMSettingsStore.BundleIndexVersioningOpts.Custom) { EditorGUI.BeginChangeCheck(); _bundleIndexCustomValue = EditorGUILayout.TextField("Bundles Index Player Version", _bundleIndexCustomValue); if (EditorGUI.EndChangeCheck()) { UMAABMSettings.BundleIndexCustomValue = _bundleIndexCustomValue; } } else { var currentBuildVersion = Application.version; if (string.IsNullOrEmpty(currentBuildVersion)) { EditorGUILayout.HelpBox("Please be sure to set a 'Version' number (eg 1.0, 2.1.0) in Edit->ProjectSettings->Player->Version", MessageType.Warning); } else { EditorGUILayout.HelpBox("Current 'Version' number ("+currentBuildVersion+ ") will be used. You can change this in Edit->ProjectSettings->Player->Version.", MessageType.Info); } } EditorGUILayout.Space(); EndVerticalIndented(); } //Asset Bundle Encryption //defined here so we can modify the message if encryption settings change string buildBundlesMsg = ""; MessageType buildBundlesMsgType = MessageType.Info; EditorGUI.BeginChangeCheck(); encryptionKeysEnabled = EditorGUILayout.ToggleLeft("Enable AssetBundle Encryption", encryptionKeysEnabled); if (EditorGUI.EndChangeCheck()) { //If encryption was turned ON generate the encryption password if necessary if (encryptionKeysEnabled) { if (currentEncryptionPassword == "") { if (UMAABMSettings.GetEncryptionPassword() != "") currentEncryptionPassword = UMAABMSettings.GetEncryptionPassword(); else currentEncryptionPassword = EncryptionUtil.GenerateRandomPW(); } UMAABMSettings.SetEncryptionPassword(currentEncryptionPassword); buildBundlesMsg = "You have turned on encryption and need to Rebuild your bundles to encrypt them."; buildBundlesMsgType = MessageType.Warning; } else { UMAABMSettings.DisableEncryption(); currentEncryptionPassword = ""; } } if (encryptionKeysEnabled) { BeginVerticalIndented(10, new Color(0.75f, 0.875f, 1f)); //tip EditorGUILayout.HelpBox("Make sure you turn on 'Use Encrypted Bundles' in the 'DynamicAssetLoader' components in your scenes.", MessageType.Info); //Encryption key //If we can work out a way for people to download a key we can use this tip and the 'EncryptionKeyURL' field //string encryptionKeyToolTip = "This key is used to generate the required encryption keys used when encrypting your bundles. If you change this key you will need to rebuild your bundles otherwise they wont decrypt. If you use the 'Encryption Key URL' field below you MUST ensure this field is set to the same key the url will return."; string encryptionKeyToolTip = "This key is used to generate the required encryption keys used when encrypting your bundles. If you change this key you will need to rebuild your bundles otherwise they wont decrypt."; EditorGUILayout.LabelField(new GUIContent("Bundle Encryption Password", encryptionKeyToolTip)); EditorGUILayout.BeginHorizontal(); if (!manualEditEncryptionKey) { if(GUILayout.Button(new GUIContent("Edit", encryptionKeyToolTip))) { manualEditEncryptionKey = true; } EditorGUI.BeginDisabledGroup(!manualEditEncryptionKey); EditorGUILayout.TextField("", UMAABMSettings.GetEncryptionPassword());//THis bloody field WILL NOT update when you click edit, then canel, the value stays EditorGUI.EndDisabledGroup(); } else { EditorGUI.BeginChangeCheck(); newEncryptionPassword = EditorGUILayout.TextArea(newEncryptionPassword); if (EditorGUI.EndChangeCheck()) { encryptionSaveButEnabled = EncryptionUtil.PasswordValid(newEncryptionPassword); } if (encryptionSaveButEnabled) { if (GUILayout.Button(new GUIContent("Save"), GUILayout.MaxWidth(60))) { currentEncryptionPassword = newEncryptionPassword; UMAABMSettings.SetEncryptionPassword(newEncryptionPassword); EditorGUIUtility.keyboardControl = 0; manualEditEncryptionKey = false; } } else { GUI.enabled = false; if (GUILayout.Button(new GUIContent("Save", "Your Encryptiom Password should be at least 16 characters long"), GUILayout.MaxWidth(60))) { //Do nothing } GUI.enabled = true; } if (GUILayout.Button(new GUIContent("Cancel", "Reset to previous value: "+ currentEncryptionPassword), GUILayout.MaxWidth(60))) { manualEditEncryptionKey = false; newEncryptionPassword = currentEncryptionPassword = UMAABMSettings.GetEncryptionPassword(); encryptionSaveButEnabled = false; EditorGUIUtility.keyboardControl = 0; } } EditorGUILayout.EndHorizontal(); //EncryptionKey URL //not sure how this would work- the delivered key would itself need to be encrypted probably //Encrypted bundle suffix string encryptionSuffixToolTip = "This suffix is appled to the end of your encrypted bundle names when they are built. Must be lower case and alphaNumeric. Cannot be empty. Defaults to "+DEFAULT_ENCRYPTION_SUFFIX; EditorGUILayout.LabelField(new GUIContent("Encrypted Bundle Suffix", encryptionSuffixToolTip)); EditorGUILayout.BeginHorizontal(); if (!manualEditEncryptionSuffix) { if (GUILayout.Button(new GUIContent("Edit", encryptionSuffixToolTip))) { manualEditEncryptionSuffix = true; } EditorGUI.BeginDisabledGroup(!manualEditEncryptionSuffix); EditorGUILayout.TextField(new GUIContent("", encryptionSuffixToolTip), currentEncryptionSuffix); EditorGUI.EndDisabledGroup(); } else { newEncryptionSuffix = EditorGUILayout.TextArea(newEncryptionSuffix); if (GUILayout.Button(new GUIContent("Save"))) { if (newEncryptionSuffix != "") { Regex rgx = new Regex("[^a-zA-Z0-9 -]"); var suffixToSend = rgx.Replace(newEncryptionSuffix, ""); currentEncryptionSuffix = suffixToSend; UMAABMSettings.SetEncryptionSuffix(suffixToSend.ToLower()); EditorGUIUtility.keyboardControl = 0; manualEditEncryptionSuffix = false; } } } EditorGUILayout.EndHorizontal(); //Encode Bundle Names string encodeBundleNamesTooltip = "If true encrypted bundle names will be base64 encoded"; EditorGUI.BeginChangeCheck(); newEncodeNamesSetting = EditorGUILayout.ToggleLeft(new GUIContent("Encode Bundle Names", encodeBundleNamesTooltip), currentEncodeNamesSetting); if (EditorGUI.EndChangeCheck()) { currentEncodeNamesSetting = newEncodeNamesSetting; UMAABMSettings.SetEncodeNames(newEncodeNamesSetting); } EndVerticalIndented(); } #if ENABLE_IOS_APP_SLICING string AppSlicingTooltip = "If true will build bundles uncompressed for use with iOS Resources Catalogs"; EditorGUI.BeginChangeCheck(); bool newAppSlicingSetting = EditorGUILayout.ToggleLeft(new GUIContent("Build for iOS App Slicing", AppSlicingTooltip), currentAppSlicingSetting); if (EditorGUI.EndChangeCheck()) { currentAppSlicingSetting = newAppSlicingSetting; UMAABMSettings.SetBuildForSlicing(newAppSlicingSetting); } #endif //Asset Bundle Building EditorGUILayout.Space(); string buttonBuildAssetBundlesText = "Build AssetBundles"; //Now defined above the encryption //string buildBundlesText = "Click the button below to build your bundles if you have not done so already."; string fullPathToBundles = Path.Combine(Directory.GetParent(Application.dataPath).FullName, Utility.AssetBundlesOutputPath); string fullPathToPlatformBundles = Path.Combine(fullPathToBundles, Utility.GetPlatformName()); //if we have not built any asset bundles there wont be anything in the cache to clear bool showClearCache = false; if (Directory.Exists(fullPathToPlatformBundles)) { buttonBuildAssetBundlesText = "Rebuild AssetBundles"; buildBundlesMsg = buildBundlesMsg == "" ? "Rebuild your assetBundles to reflect your latest changes" : buildBundlesMsg; showClearCache = true; } else { buildBundlesMsg = "You have not built your asset bundles for " + EditorUserBuildSettings.activeBuildTarget.ToString() + " yet. Click this button to build them."; buildBundlesMsgType = MessageType.Warning; showClearCache = false; } EditorGUILayout.HelpBox(buildBundlesMsg, buildBundlesMsgType); if (GUILayout.Button(buttonBuildAssetBundlesText)) { BuildScript.BuildAssetBundles(); #if UNITY_2017_1_OR_NEWER Caching.ClearCache (); #else Caching.CleanCache(); #endif return; } EndVerticalPadded(5); EditorGUILayout.Space(); //Local AssetBundleServer BeginVerticalPadded(5f, new Color(0.75f, 0.875f, 1f)); GUILayout.Label("AssetBundle Testing Server", EditorStyles.boldLabel); EditorGUILayout.HelpBox("Once you have built your bundles this local Testing Server can be enabled and it will load those AssetBundles rather than the files inside the project.", MessageType.Info); if (!BuildScript.CanRunLocally(EditorUserBuildSettings.activeBuildTarget)) { EditorGUILayout.HelpBox("Builds for " + EditorUserBuildSettings.activeBuildTarget.ToString() + " cannot access this local server, but you can still use it in the editor.", MessageType.Warning); } bool updateURL = false; EnableLocalAssetBundleServer = EditorGUILayout.Toggle("Start Server", EnableLocalAssetBundleServer); //If the server is off we need to show the user a message telling them that they will have to have uploaded their bundles to an external server //and that they need to set the address of that server in DynamicAssetLoader int newPort = Port; EditorGUI.BeginChangeCheck(); newPort = EditorGUILayout.IntField("Port", Port); if (EditorGUI.EndChangeCheck()) { if (newPort != Port) { if (_activeHost != null && _activeHost != "") ActiveHost = _activeHost.Replace(":" + Port.ToString(), ":" + newPort.ToString()); Port = newPort; UpdateHosts(); //we need to start the server to see if it works with this port- regardless of whether it is turned on or not. if (!EnableLocalAssetBundleServer) { UpdateServer(true); } else { UpdateServer(); } if (serverException == false) { //We can use the set IP with this port so update it if (EnableLocalAssetBundleServer) SimpleWebServer.ServerURL = ActiveHost; } else { //We CANT use the set IP with this port so set the saved URL to "" and tell the user the Port is in use elsewhere SimpleWebServer.ServerURL = ""; EnableLocalAssetBundleServer = false; portError = true; } } } if (!EnableLocalAssetBundleServer) { if (portError) EditorGUILayout.HelpBox("There are no hosts available for that port. Its probably in use by another application. Try another.", MessageType.Warning); else { EditorGUILayout.HelpBox("When the local server is not running the game will play in Simulation Mode OR if you have set the 'RemoteServerURL' for each DynamicAssetLoader, bundles will be downloaded from that location.", MessageType.Warning); if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.WebGL) { EditorGUILayout.HelpBox("WARNING: AssetBundles in WebGL builds that you run locally WILL NOT WORK unless the local server is turned on, and you build using the button below!", MessageType.Warning); } } } EditorGUILayout.Space(); if (_hosts != null && _hosts.Length > 0 && EnableLocalAssetBundleServer) { if (_activeHost == null || _activeHost == "") { ActiveHost = _hosts[0]; } int activeHostInt = 0; string[] hostsStrings = new string[_hosts.Length]; for (int i = 0; i < _hosts.Length; i++) { hostsStrings[i] = _hosts[i].Replace("http://", "").TrimEnd(new char[] { '/' }); if (_hosts[i] == _activeHost) { activeHostInt = i; } } EditorGUI.BeginChangeCheck(); int newActiveHostInt = EditorGUILayout.Popup("Host Address: http://", activeHostInt, hostsStrings); if (EditorGUI.EndChangeCheck()) { if (newActiveHostInt != activeHostInt) { ActiveHost = _hosts[newActiveHostInt]; updateURL = true; } } } EditorGUILayout.Space(); if (showClearCache)//no point in showing a button for bundles that dont exist - or is there? The user might be using a remote url to download assetbundles without the localserver? { EditorGUILayout.HelpBox("You can clear the cache to force asset bundles to be redownloaded.", MessageType.Info); if (GUILayout.Button("Clean the Cache")) { #if UNITY_2017_1_OR_NEWER _statusMessage = Caching.ClearCache() ? "Cache Cleared." : "Error clearing cache."; #else _statusMessage = Caching.CleanCache() ? "Cache Cleared." : "Error clearing cache."; #endif } EditorGUILayout.Space(); } EditorGUILayout.Space(); GUILayout.Label("Server Status"); if (_statusMessage != null) { EditorGUILayout.HelpBox(_statusMessage, MessageType.None); } if (SimpleWebServer.Instance != null) { //GUILayout.Label("Server Request Log"); serverRequestLogOpen = EditorGUILayout.Foldout(serverRequestLogOpen, "Server Request Log"); if(serverRequestLogOpen) EditorGUILayout.HelpBox(SimpleWebServer.Instance.GetLog(), MessageType.Info); } if (updateURL) { SimpleWebServer.ServerURL = ActiveHost; } EndVerticalPadded(5); EditorGUILayout.Space(); //Testing Build- only show this if we can run a build for the current platform (i.e. if its not iOS or Android) if (BuildScript.CanRunLocally (EditorUserBuildSettings.activeBuildTarget)) { BeginVerticalPadded (5, new Color (0.75f, 0.875f, 1f)); GUILayout.Label ("Local Testing Build", EditorStyles.boldLabel); //if the bundles are built and the server is turned on then the user can use this option otherwise there is no point //But we will show them that this option is available even if this is not the case if (!showClearCache || !EnableLocalAssetBundleServer) { EditorGUI.BeginDisabledGroup (true); } EditorGUILayout.HelpBox ("Make a testing Build that uses the Local Server using the button below.", MessageType.Info); developmentBuild = EditorGUILayout.Toggle ("Development Build", developmentBuild); if (GUILayout.Button ("Build and Run!")) { BuildScript.BuildAndRunPlayer (developmentBuild); } if (!showClearCache || !EnableLocalAssetBundleServer) {// EditorGUI.EndDisabledGroup (); } EditorGUILayout.Space (); EndVerticalPadded (5); EditorGUILayout.Space (); } //END SCROLL VIEW //for some reason when we build or build assetbundles when this window is open we get an error //InvalidOperationException: Operation is not valid due to the current state of the object //so try catch is here as a nasty hack to get rid of it try { EditorGUILayout.EndVertical(); EditorGUILayout.EndScrollView(); } catch { } } #region GUI HELPERS //these are copied from UMAs GUI Helper- but that is in an editor folder public static void BeginVerticalPadded(float padding, Color backgroundColor) { //for some reason when we build or build assetbundles when this window is open we get an error //InvalidOperationException: Operation is not valid due to the current state of the object //so try catch is here as a nasty hack to get rid of it try { GUI.color = backgroundColor; GUILayout.BeginHorizontal(EditorStyles.textField); GUI.color = Color.white; GUILayout.Space(padding); GUILayout.BeginVertical(); GUILayout.Space(padding); } catch { } } public static void EndVerticalPadded(float padding) { //for some reason when we build or build assetbundles when this window is open we get an error //InvalidOperationException: Operation is not valid due to the current state of the object //so try catch is here as a nasty hack to get rid of it try { GUILayout.Space(padding); GUILayout.EndVertical(); GUILayout.Space(padding); GUILayout.EndHorizontal(); } catch { } } public static void BeginVerticalIndented(float indentation, Color backgroundColor) { GUI.color = backgroundColor; GUILayout.BeginHorizontal(); GUILayout.Space(indentation); GUI.color = Color.white; GUILayout.BeginVertical(); } public static void EndVerticalIndented() { GUILayout.EndVertical(); GUILayout.EndHorizontal(); } #endregion } [System.Serializable] public class UMAABMSettingsStore { public enum BundleIndexVersioningOpts { UseBuildVersion, Custom } public bool encryptionEnabled = false; public string encryptionPassword = ""; public string encryptionSuffix = ""; public bool encodeNames = false; [Tooltip("If true will build uncompressed assetBundles for use with iOS resource catalogs")] public bool buildForAppSlicing = false; public bool enableBundleIndexVersioning; //either automatically use the Buildversion from player settings or specify a value here public BundleIndexVersioningOpts bundleIndexVersioningMethod = BundleIndexVersioningOpts.UseBuildVersion; //if useBundlesVersioning is set to Custom this value is used when the bundles are built public string bundleIndexCustomValue = "0.0"; public UMAABMSettingsStore() { } public UMAABMSettingsStore(bool _encryptionEnabled, string _encryptionPassword, string _encryptionSuffix, bool _encodeNames) { _encryptionEnabled = encryptionEnabled; encryptionPassword = _encryptionPassword; encryptionSuffix = _encryptionSuffix; encodeNames = _encodeNames; } } public static class UMAABMSettings { #region PUBLIC FIELDS //This is not just for Encryption settings any more so it has the wrong name- its editor only so we can change it... public const string SETTINGS_FILENAME = "UMAABMSettings-DoNotDelete.txt"; public const string SETTINGS_OLD_FILENAME = "UMAEncryptionSettings-DoNotDelete.txt"; private static UMAABMSettingsStore thisSettings; #endregion #region PROPERTIES //pretty much all of these should have been properties- sorry I didn't uderstand those very well at the time //This is better but we dont want to be doing GetThisSettings() either we want another property that does it once /// <summary> /// Is BundlesIndexVersioning enabled /// </summary> public static bool EnableBundleIndexVersioning { get { return GetThisSettings().enableBundleIndexVersioning; } set{ GetThisSettings().enableBundleIndexVersioning = value; File.WriteAllText(Path.Combine(GetSettingsFolderPath(), SETTINGS_FILENAME), JsonUtility.ToJson(thisSettings)); AssetDatabase.Refresh(); } } /// <summary> /// Does BundlesIndexversioning use a custom value or the Player build Value /// </summary> public static UMAABMSettingsStore.BundleIndexVersioningOpts BundleIndexVersioningMethod { get { return GetThisSettings().bundleIndexVersioningMethod; } set { GetThisSettings().bundleIndexVersioningMethod = value; File.WriteAllText(Path.Combine(GetSettingsFolderPath(), SETTINGS_FILENAME), JsonUtility.ToJson(thisSettings)); AssetDatabase.Refresh(); } } /// <summary> /// A custom value for bundleIndexVersioning /// </summary> public static string BundleIndexCustomValue { get { return GetThisSettings().bundleIndexCustomValue; } set { GetThisSettings().bundleIndexCustomValue = value; File.WriteAllText(Path.Combine(GetSettingsFolderPath(), SETTINGS_FILENAME), JsonUtility.ToJson(thisSettings)); AssetDatabase.Refresh(); } } #endregion #region STATIC LOAD SAVE Methods private static UMAABMSettingsStore GetThisSettings() { thisSettings = GetEncryptionSettings(); if (thisSettings == null) thisSettings = new UMAABMSettingsStore(); return thisSettings; } private static string GetSettingsFolderPath() { return FileUtils.GetInternalDataStoreFolder(false,true); } //we are saving the encryptions settings to a text file so that teams working on the same project/ github etc/ can all use the same settings public static UMAABMSettingsStore GetEncryptionSettings() { if(File.Exists(Path.Combine(GetSettingsFolderPath(), SETTINGS_OLD_FILENAME))) { //we need to write the data from the old file into the new file and delete the old one... File.WriteAllText(Path.Combine(GetSettingsFolderPath(), SETTINGS_FILENAME), File.ReadAllText(Path.Combine(GetSettingsFolderPath(), SETTINGS_OLD_FILENAME))); File.Delete(Path.Combine(GetSettingsFolderPath(), SETTINGS_OLD_FILENAME)); } if (!File.Exists(Path.Combine(GetSettingsFolderPath(), SETTINGS_FILENAME))) return null; else return JsonUtility.FromJson<UMAABMSettingsStore>(File.ReadAllText(Path.Combine(GetSettingsFolderPath(), SETTINGS_FILENAME))); } public static bool GetEncryptionEnabled() { var thisSettings = GetEncryptionSettings(); if (thisSettings == null) return false; else if (thisSettings.encryptionEnabled && thisSettings.encryptionPassword != "") return true; else return false; } public static string GetEncryptionPassword() { var thisSettings = GetEncryptionSettings(); if (thisSettings == null) return ""; else return thisSettings.encryptionPassword; } public static string GetEncryptionSuffix() { var thisSettings = GetEncryptionSettings(); if (thisSettings == null) return ""; else return thisSettings.encryptionSuffix; } public static bool GetEncodeNames() { var thisSettings = GetEncryptionSettings(); if (thisSettings == null) return false; else return thisSettings.encodeNames; } /// <summary> /// Should the bundles be built for use with iOS app slicing /// </summary> public static bool GetBuildForSlicing() { var thisSettings = GetEncryptionSettings(); if (thisSettings == null) return false; else return thisSettings.buildForAppSlicing; } public static void ClearEncryptionSettings() { var thisSettings = GetEncryptionSettings(); var newSettings = new UMAABMSettingsStore(); newSettings.buildForAppSlicing = thisSettings.buildForAppSlicing; newSettings.bundleIndexCustomValue = thisSettings.bundleIndexCustomValue; newSettings.bundleIndexVersioningMethod = thisSettings.bundleIndexVersioningMethod; newSettings.enableBundleIndexVersioning = thisSettings.enableBundleIndexVersioning; File.WriteAllText(Path.Combine(GetSettingsFolderPath(), SETTINGS_FILENAME), JsonUtility.ToJson(newSettings)); } public static void SetEncryptionSettings(bool encryptionEnabled, string encryptionPassword = "", string encryptionSuffix = "", bool? encodeNames = null) { var thisSettings = GetEncryptionSettings(); if (thisSettings == null) thisSettings = new UMAABMSettingsStore(); thisSettings.encryptionEnabled = encryptionEnabled; thisSettings.encryptionPassword = encryptionPassword != "" ? encryptionPassword : thisSettings.encryptionPassword; thisSettings.encryptionSuffix = encryptionSuffix != "" ? encryptionSuffix : thisSettings.encryptionSuffix; thisSettings.encodeNames = encodeNames != null ? (bool)encodeNames : thisSettings.encodeNames; File.WriteAllText(Path.Combine(GetSettingsFolderPath(), SETTINGS_FILENAME), JsonUtility.ToJson(thisSettings)); AssetDatabase.Refresh(); } /// <summary> /// Turns encryption OFF /// </summary> public static void DisableEncryption() { SetEncryptionSettings(false); } /// <summary> /// Turns encryption ON ands sets the given password (cannot be blank) /// </summary> public static void SetEncryptionPassword(string encryptionPassword) { if (encryptionPassword != "") { SetEncryptionSettings(true, encryptionPassword); } } /// <summary> /// Turns encryption OFF ands unsets any existing password /// </summary> public static void UnsetEncryptionPassword() { var thisSettings = GetEncryptionSettings(); if (thisSettings == null) thisSettings = new UMAABMSettingsStore(); thisSettings.encryptionEnabled = false; thisSettings.encryptionPassword = ""; File.WriteAllText(Path.Combine(GetSettingsFolderPath(), SETTINGS_FILENAME), JsonUtility.ToJson(thisSettings)); AssetDatabase.Refresh(); } /// <summary> /// Turns encryption ON ands sets the given encryption suffix (cannot be blank) /// </summary> public static void SetEncryptionSuffix(string encryptionSuffix) { if (encryptionSuffix != "") { SetEncryptionSettings(true, "", encryptionSuffix); } } /// <summary> /// Turns encryption ON ands sets the encode names setting /// </summary> public static void SetEncodeNames(bool encodeNames) { SetEncryptionSettings(true,"", "", encodeNames); } /// <summary> /// Should the bundles be built for use with iOS app slicing /// </summary> public static void SetBuildForSlicing(bool enabled) { var thisSettings = GetEncryptionSettings(); if (thisSettings == null) thisSettings = new UMAABMSettingsStore(); thisSettings.buildForAppSlicing = enabled; } #endregion } } #endif
/* 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 java.lang; using java.util; using org.eclipse.jface.text; using org.eclipse.jface.text.contentassist; using org.eclipse.swt.graphics; using stab.query; using stab.reflection; using cnatural.compiler; namespace cnatural.eclipse.editors { public class CompletionProposalHelper { private static CompletionProposalComparator completionProposalComparator = new CompletionProposalComparator(); private class CompletionProposalComparator : Comparator<ICompletionProposal> { public int compare(ICompletionProposal cp1, ICompletionProposal cp2) { return cp1.getDisplayString().toLowerCase().compareTo(cp2.getDisplayString().toLowerCase()); } } public static ICompletionProposal[] createEmpty() { return new[] { new EmptyCompletionProposal() }; } public static ICompletionProposal[] createCompletionProposals(int offset, int length, String prefix, Iterable<String> packages, Iterable<MemberInfo> members, Iterable<String> texts) { var proposals = new ArrayList<ICompletionProposal>(); foreach (var pkg in packages.where(p => p.startsWith(prefix))) { proposals.add(createPackage(offset, length, pkg.substring(prefix.length()), pkg)); } foreach (var member in members) { switch (member.MemberKind) { case Type: var Type = member.Type; if (Type.Name.startsWith(prefix)) { proposals.add(createType(offset, length, Type.Name.substring(prefix.length()), Type)); } break; case Field: var Field = member.Field; if (Field.Name.startsWith(prefix)) { proposals.add(createField(offset, length, Field.Name.substring(prefix.length()), Field)); } break; case Property: if (member.Name.startsWith(prefix)) { proposals.add(createProperty(offset, length, member.Name.substring(prefix.length()), member)); } break; case Method: var Method = member.Method; if (Method.Name.startsWith(prefix)) { proposals.add(createMethod(offset, length, Method.Name.substring(prefix.length()), Method)); } break; case Local: if (member.Name.startsWith(prefix)) { proposals.add(createLocal(offset, length, member.Name.substring(prefix.length()), member)); } break; } } foreach (var text in texts.where(p => p.startsWith(prefix))) { proposals.add(createText(offset, length, text.substring(prefix.length()), text)); } if (proposals.size() == 0) { return createEmpty(); } Collections.sort(proposals, completionProposalComparator); return proposals.toArray(new ICompletionProposal[proposals.size()]); } private static String getDisplayName(TypeInfo type) { var plen = type.PackageName.length(); if (plen == 0) { return type.Name; } else { return type.Name + " - " + type.PackageName.substring(0, plen - 1).replace('/', '.'); } } private static String getDisplayName(FieldInfo field) { return field.Name + " - " + getName(field.DeclaringType); } private static String getDisplayName(MethodInfo method) { return method.Name + getParameters(method) + ": " + getName(method.ReturnType) + " - " + getName(method.DeclaringType); } private static String getDisplayName(MemberInfo member) { return member.Name + " - " + getName(member.Type); } private static String getPropertyDisplayName(MemberInfo member) { return member.Name + ": " + getName(member.Type) + " - " + getName(member.DeclaringType); } private static String getParameters(MethodInfo method) { var sb = new StringBuilder(); sb.append('('); var first = true; foreach (var p in method.Parameters) { if (first) { first = false; } else { sb.append(", "); } sb.append(getName(p.Type)); } sb.append(')'); return sb.toString(); } private static String getName(TypeInfo type) { switch (type.TypeKind) { case Void: case Boolean: case Byte: case Char: case Short: case Int: case Long: case Float: case Double: return type.TypeKind.toString().toLowerCase(); case Array: return getName(type.ElementType) + "[]"; case UnboundedWildcard: return "?"; case LowerBoundedWildcard: return "? : " + getName(type.WildcardBound); case UpperBoundedWildcard: return getName(type.WildcardBound) + " : ?"; } var sb = new StringBuilder(); sb.append(type.FullName.replace('/', '.').replace('$', '.')); if (type.GenericArguments.any()) { sb.append("<"); var first = true; foreach (var t in type.GenericArguments) { if (first) { first = false; } else { sb.append(", "); } sb.append(getName(t)); } sb.append(">"); } return sb.toString(); } private static ICompletionProposal createPackage(int offset, int length, String text, String displayName) { return new CompletionProposal(text, offset, length, text.length(), Environment.getIcon(Icon.Package), displayName, null, null); } private static ICompletionProposal createType(int offset, int length, String text, TypeInfo type) { Image image; if (type.IsEnum) { image = Environment.getIcon(Icon.Enum); } else if (type.IsInterface) { image = Environment.getIcon(Icon.Interface); } else { image = Environment.getIcon(Icon.Class); } return new CompletionProposal(text, offset, length, text.length(), image, getDisplayName(type), null, null); } private static ICompletionProposal createText(int offset, int length, String text, String displayName) { return new CompletionProposal(text, offset, length, text.length(), Environment.getIcon(Icon.Source), displayName, null, null); } private static ICompletionProposal createField(int offset, int length, String text, FieldInfo field) { Image image; if (field.IsPublic) { image = Environment.getIcon(Icon.PublicField); } else if (field.IsProtected) { image = Environment.getIcon(Icon.ProtectedField); } else if (field.IsPrivate) { image = Environment.getIcon(Icon.PrivateField); } else { image = Environment.getIcon(Icon.DefaultField); } return new CompletionProposal(text, offset, length, text.length(), image, getDisplayName(field), null, null); } private static ICompletionProposal createProperty(int offset, int length, String text, MemberInfo property) { Image image; if (property.IsPublic) { image = Environment.getIcon(Icon.PublicProperty); } else if (property.IsProtected) { image = Environment.getIcon(Icon.ProtectedProperty); } else if (property.IsPrivate) { image = Environment.getIcon(Icon.PrivateProperty); } else { image = Environment.getIcon(Icon.DefaultProperty); } return new CompletionProposal(text, offset, length, text.length(), image, getPropertyDisplayName(property), null, null); } private static ICompletionProposal createMethod(int offset, int length, String text, MethodInfo method) { Image image; if (method.IsPublic) { image = Environment.getIcon(Icon.PublicMethod); } else if (method.IsProtected) { image = Environment.getIcon(Icon.ProtectedMethod); } else if (method.IsPrivate) { image = Environment.getIcon(Icon.PrivateMethod); } else { image = Environment.getIcon(Icon.DefaultMethod); } return new CompletionProposal(text, offset, length, text.length(), image, getDisplayName(method), null, null); } private static ICompletionProposal createLocal(int offset, int length, String text, MemberInfo member) { return new CompletionProposal(text, offset, length, text.length(), Environment.getIcon(Icon.LocalVariable), getDisplayName(member), null, null); } private class EmptyCompletionProposal : ICompletionProposal { public Point getSelection(IDocument document) { return null; } public Image getImage() { return null; } public String getDisplayString() { return Messages.emptyCompletionText; } public IContextInformation getContextInformation() { return null; } public String getAdditionalProposalInfo() { return null; } public void apply(IDocument document) { } } } }
// // TimeSpanTest.cs - NUnit Test Cases for the System.TimeSpan struct // // Authors: // Duco Fijma ([email protected]) // Sebastien Pouliot <[email protected]> // // (C) 2001 Duco Fijma // Copyright (C) 2004 Novell (http://www.novell.com) // using NUnit.Framework; using System; namespace MonoTests.System { [TestFixture] public class TimeSpanTest : Assertion { private void Debug (TimeSpan ts) { Console.Out.WriteLine ("Days {0}", ts.Days); Console.Out.WriteLine ("Hours {0}", ts.Hours); Console.Out.WriteLine ("Minutes {0}", ts.Minutes); Console.Out.WriteLine ("Seconds {0}", ts.Seconds); Console.Out.WriteLine ("Milliseconds {0}", ts.Milliseconds); Console.Out.WriteLine ("Ticks {0}", ts.Ticks); } public void TestCtors () { TimeSpan t1 = new TimeSpan (1234567890); AssertEquals ("A1", "00:02:03.4567890", t1.ToString ()); t1 = new TimeSpan (1,2,3); AssertEquals ("A2", "01:02:03", t1.ToString ()); t1 = new TimeSpan (1,2,3,4); AssertEquals ("A3", "1.02:03:04", t1.ToString ()); t1 = new TimeSpan (1,2,3,4,5); AssertEquals ("A4", "1.02:03:04.0050000", t1.ToString ()); t1 = new TimeSpan (-1,2,-3,4,-5); AssertEquals ("A5", "-22:02:56.0050000", t1.ToString ()); t1 = new TimeSpan (0,25,0,0,0); AssertEquals ("A6", "1.01:00:00", t1.ToString ()); } [Test] [ExpectedException (typeof (ArgumentOutOfRangeException))] public void DaysOverflow () { int days = (int) (Int64.MaxValue / TimeSpan.TicksPerDay) + 1; TimeSpan ts = new TimeSpan (days, 0, 0, 0, 0); } [Test] public void TemporaryOverflow () { // calculating part of this results in overflow (days) // but the negative hours, minutes, seconds & ms correct this int days = (int) (Int64.MaxValue / TimeSpan.TicksPerDay) + 1; TimeSpan ts = new TimeSpan (days, Int32.MinValue, Int32.MinValue, Int32.MinValue, Int32.MinValue); AssertEquals ("Days", 10650320, ts.Days); AssertEquals ("Hours", 0, ts.Hours); AssertEquals ("Minutes", 14, ts.Minutes); AssertEquals ("Seconds", 28, ts.Seconds); AssertEquals ("Milliseconds", 352, ts.Milliseconds); AssertEquals ("Ticks", 9201876488683520000, ts.Ticks); } [Test] public void NoOverflowInHoursMinsSecondsMS () { TimeSpan ts = new TimeSpan (0, Int32.MaxValue, Int32.MaxValue, Int32.MaxValue, Int32.MaxValue); AssertEquals ("Days", 24879, ts.Days); AssertEquals ("Hours", 22, ts.Hours); AssertEquals ("Minutes", 44, ts.Minutes); AssertEquals ("Seconds", 30, ts.Seconds); AssertEquals ("Milliseconds", 647, ts.Milliseconds); AssertEquals ("Ticks", 21496274706470000, ts.Ticks); } [Test] [ExpectedException (typeof (ArgumentOutOfRangeException))] public void MaxDays () { new TimeSpan (Int32.MaxValue, 0, 0, 0, 0); } [Test] [ExpectedException (typeof (ArgumentOutOfRangeException))] public void MinDays () { new TimeSpan (Int32.MinValue, 0, 0, 0, 0); } [Test] [Ignore ("too long")] public void MaxHours_TooLong () { // LAMESPEC: the highest hours are "special" for (int i=0; i < 596523; i++) { TimeSpan ts = new TimeSpan (0, Int32.MaxValue - i, 0, 0, 0); int h = i + 1; string prefix = i.ToString () + '-'; AssertEquals (prefix + "Days", -(h / 24), ts.Days); AssertEquals (prefix + "Hours", -(h % 24), ts.Hours); AssertEquals (prefix + "Minutes", 0, ts.Minutes); AssertEquals (prefix + "Seconds", 0, ts.Seconds); AssertEquals (prefix + "Milliseconds", 0, ts.Milliseconds); AssertEquals (prefix + "Ticks", -36000000000 * h, ts.Ticks); } } [Test] public void MaxHours () { // LAMESPEC: the highest hours are "special" TimeSpan ts = new TimeSpan (0, Int32.MaxValue, 0, 0, 0); AssertEquals ("Max-Days", 0, ts.Days); AssertEquals ("Max-Hours", -1, ts.Hours); AssertEquals ("Max-Minutes", 0, ts.Minutes); AssertEquals ("Max-Seconds", 0, ts.Seconds); AssertEquals ("Max-Milliseconds", 0, ts.Milliseconds); AssertEquals ("Max-Ticks", -36000000000, ts.Ticks); ts = new TimeSpan (0, Int32.MaxValue - 596522, 0, 0, 0); AssertEquals ("Days", -24855, ts.Days); AssertEquals ("Hours", -3, ts.Hours); AssertEquals ("Minutes", 0, ts.Minutes); AssertEquals ("Seconds", 0, ts.Seconds); AssertEquals ("Milliseconds", 0, ts.Milliseconds); AssertEquals ("Ticks", -21474828000000000, ts.Ticks); } [Test] public void MaxHours_BreakPoint () { TimeSpan ts = new TimeSpan (0, Int32.MaxValue - 596523, 0, 0, 0); AssertEquals ("Days", 24855, ts.Days); AssertEquals ("Hours", 2, ts.Hours); AssertEquals ("Minutes", 28, ts.Minutes); AssertEquals ("Seconds", 16, ts.Seconds); AssertEquals ("Milliseconds", 0, ts.Milliseconds); AssertEquals ("Ticks", 21474808960000000, ts.Ticks); } [Test] [Ignore ("too long")] public void MinHours_TooLong () { // LAMESPEC: the lowest hours are "special" for (int i=Int32.MinValue; i < -2146887124; i++) { TimeSpan ts = new TimeSpan (0, i, 0, 0, 0); int h = i + Int32.MaxValue + 1; string prefix = i.ToString () + '-'; AssertEquals (prefix + "Days", (h / 24), ts.Days); AssertEquals (prefix + "Hours", (h % 24), ts.Hours); AssertEquals (prefix + "Minutes", 0, ts.Minutes); AssertEquals (prefix + "Seconds", 0, ts.Seconds); AssertEquals (prefix + "Milliseconds", 0, ts.Milliseconds); AssertEquals (prefix + "Ticks", 36000000000 * h, ts.Ticks); } } [Test] public void MinHours () { // LAMESPEC: the lowest hours are "special" TimeSpan ts = new TimeSpan (0, Int32.MinValue, 0, 0, 0); AssertEquals ("Min-Days", 0, ts.Days); AssertEquals ("Min-Hours", 0, ts.Hours); AssertEquals ("Min-Minutes", 0, ts.Minutes); AssertEquals ("Min-Seconds", 0, ts.Seconds); AssertEquals ("Min-Milliseconds", 0, ts.Milliseconds); AssertEquals ("Min-Ticks", 0, ts.Ticks); ts = new TimeSpan (0, -2146887125, 0, 0, 0); AssertEquals ("Days", 24855, ts.Days); AssertEquals ("Hours", 3, ts.Hours); AssertEquals ("Minutes", 0, ts.Minutes); AssertEquals ("Seconds", 0, ts.Seconds); AssertEquals ("Milliseconds", 0, ts.Milliseconds); AssertEquals ("Ticks", 21474828000000000, ts.Ticks); } [Test] public void MinHours_BreakPoint () { TimeSpan ts = new TimeSpan (0, -2146887124, 0, 0, 0); AssertEquals ("Days", -24855, ts.Days); AssertEquals ("Hours", -2, ts.Hours); AssertEquals ("Minutes", -28, ts.Minutes); AssertEquals ("Seconds", -16, ts.Seconds); AssertEquals ("Milliseconds", 0, ts.Milliseconds); AssertEquals ("Ticks", -21474808960000000, ts.Ticks); } [Test] [Ignore ("too long")] public void MaxMinutes_TooLong () { // LAMESPEC: the highest minutes are "special" for (int i=0; i < 35791394; i++) { TimeSpan ts = new TimeSpan (0, 0, Int32.MaxValue - i, 0, 0); long h = -(i + 1); string prefix = i.ToString () + '-'; AssertEquals (prefix + "Days", (h / 1440), ts.Days); AssertEquals (prefix + "Hours", ((h / 60) % 24), ts.Hours); AssertEquals (prefix + "Minutes", (h % 60), ts.Minutes); AssertEquals (prefix + "Seconds", 0, ts.Seconds); AssertEquals (prefix + "Milliseconds", 0, ts.Milliseconds); AssertEquals (prefix + "Ticks", (600000000L * h), ts.Ticks); } } [Test] public void MaxMinutes () { // LAMESPEC: the highest minutes are "special" TimeSpan ts = new TimeSpan (0, 0, Int32.MaxValue, 0, 0); AssertEquals ("Max-Days", 0, ts.Days); AssertEquals ("Max-Hours", 0, ts.Hours); AssertEquals ("Max-Minutes", -1, ts.Minutes); AssertEquals ("Max-Seconds", 0, ts.Seconds); AssertEquals ("Max-Milliseconds", 0, ts.Milliseconds); AssertEquals ("Max-Ticks", -600000000, ts.Ticks); ts = new TimeSpan (0, 0, Int32.MaxValue - 35791393, 0, 0); AssertEquals ("Days", -24855, ts.Days); AssertEquals ("Hours", -3, ts.Hours); AssertEquals ("Minutes", -14, ts.Minutes); AssertEquals ("Seconds", 0, ts.Seconds); AssertEquals ("Milliseconds", 0, ts.Milliseconds); AssertEquals ("Ticks", -21474836400000000, ts.Ticks); } [Test] public void MaxMinutes_BreakPoint () { TimeSpan ts = new TimeSpan (0, Int32.MaxValue - 35791394, 0, 0, 0); AssertEquals ("Days", 0, ts.Days); AssertEquals ("Hours", 0, ts.Hours); AssertEquals ("Minutes", -52, ts.Minutes); AssertEquals ("Seconds", 0, ts.Seconds); AssertEquals ("Milliseconds", 0, ts.Milliseconds); AssertEquals ("Ticks", -31200000000, ts.Ticks); } [Test] [Ignore ("too long")] public void MinMinutes_TooLong () { // LAMESPEC: the highest minutes are "special" for (int i=Int32.MinValue; i < -2111692253; i++) { TimeSpan ts = new TimeSpan (0, 0, i, 0, 0); long h = i + Int32.MaxValue + 1; string prefix = i.ToString () + '-'; AssertEquals (prefix + "Days", (h / 1440), ts.Days); AssertEquals (prefix + "Hours", ((h / 60) % 24), ts.Hours); AssertEquals (prefix + "Minutes", (h % 60), ts.Minutes); AssertEquals (prefix + "Seconds", 0, ts.Seconds); AssertEquals (prefix + "Milliseconds", 0, ts.Milliseconds); AssertEquals (prefix + "Ticks", (600000000L * h), ts.Ticks); } } [Test] public void MinMinutes () { // LAMESPEC: the highest minutes are "special" TimeSpan ts = new TimeSpan (0, 0, Int32.MinValue, 0, 0); AssertEquals ("Min-Days", 0, ts.Days); AssertEquals ("Min-Hours", 0, ts.Hours); AssertEquals ("Min-Minutes", 0, ts.Minutes); AssertEquals ("Min-Seconds", 0, ts.Seconds); AssertEquals ("Min-Milliseconds", 0, ts.Milliseconds); AssertEquals ("Min-Ticks", 0, ts.Ticks); ts = new TimeSpan (0, 0, -2111692254, 0, 0); AssertEquals ("Days", 24855, ts.Days); AssertEquals ("Hours", 3, ts.Hours); AssertEquals ("Minutes", 14, ts.Minutes); AssertEquals ("Seconds", 0, ts.Seconds); AssertEquals ("Milliseconds", 0, ts.Milliseconds); AssertEquals ("Ticks", 21474836400000000, ts.Ticks); } [Test] public void MinMinutes_BreakPoint () { TimeSpan ts = new TimeSpan (0, 0, -2111692253, 0, 0); AssertEquals ("Days", -24855, ts.Days); AssertEquals ("Hours", -3, ts.Hours); AssertEquals ("Minutes", -13, ts.Minutes); AssertEquals ("Seconds", -16, ts.Seconds); AssertEquals ("Milliseconds", 0, ts.Milliseconds); AssertEquals ("Ticks", -21474835960000000, ts.Ticks); } [Test] public void MaxSeconds () { TimeSpan ts = new TimeSpan (0, 0, 0, Int32.MaxValue, 0); AssertEquals ("Days", 24855, ts.Days); AssertEquals ("Hours", 3, ts.Hours); AssertEquals ("Minutes", 14, ts.Minutes); AssertEquals ("Seconds", 7, ts.Seconds); AssertEquals ("Milliseconds", 0, ts.Milliseconds); AssertEquals ("Ticks", 21474836470000000, ts.Ticks); } [Test] public void MinSeconds () { TimeSpan ts = new TimeSpan (0, 0, 0, Int32.MinValue, 0); AssertEquals ("Days", -24855, ts.Days); AssertEquals ("Hours", -3, ts.Hours); AssertEquals ("Minutes", -14, ts.Minutes); AssertEquals ("Seconds", -8, ts.Seconds); AssertEquals ("Milliseconds", 0, ts.Milliseconds); AssertEquals ("Ticks", -21474836480000000, ts.Ticks); } [Test] public void MaxMilliseconds () { TimeSpan ts = new TimeSpan (0, 0, 0, 0, Int32.MaxValue); AssertEquals ("Days", 24, ts.Days); AssertEquals ("Hours", 20, ts.Hours); AssertEquals ("Minutes", 31, ts.Minutes); AssertEquals ("Seconds", 23, ts.Seconds); AssertEquals ("Milliseconds", 647, ts.Milliseconds); AssertEquals ("Ticks", 21474836470000, ts.Ticks); } [Test] public void MinMilliseconds () { TimeSpan ts = new TimeSpan (0, 0, 0, 0, Int32.MinValue); AssertEquals ("Days", -24, ts.Days); AssertEquals ("Hours", -20, ts.Hours); AssertEquals ("Minutes", -31, ts.Minutes); AssertEquals ("Seconds", -23, ts.Seconds); AssertEquals ("Milliseconds", -648, ts.Milliseconds); AssertEquals ("Ticks", -21474836480000, ts.Ticks); } [Test] public void NegativeTimeSpan () { TimeSpan ts = new TimeSpan (-23, -59, -59); AssertEquals ("Days", 0, ts.Days); AssertEquals ("Hours", -23, ts.Hours); AssertEquals ("Minutes", -59, ts.Minutes); AssertEquals ("Seconds", -59, ts.Seconds); AssertEquals ("Milliseconds", 0, ts.Milliseconds); AssertEquals ("Ticks", -863990000000, ts.Ticks); } public void TestProperties () { TimeSpan t1 = new TimeSpan (1,2,3,4,5); TimeSpan t2 = -t1; AssertEquals ("A1", 1, t1.Days); AssertEquals ("A2", 2, t1.Hours); AssertEquals ("A3", 3, t1.Minutes); AssertEquals ("A4", 4, t1.Seconds); AssertEquals ("A5", 5, t1.Milliseconds); AssertEquals ("A6", -1, t2.Days); AssertEquals ("A7", -2, t2.Hours); AssertEquals ("A8", -3, t2.Minutes); AssertEquals ("A9", -4, t2.Seconds); AssertEquals ("A10", -5, t2.Milliseconds); } public void TestAdd () { TimeSpan t1 = new TimeSpan (2,3,4,5,6); TimeSpan t2 = new TimeSpan (1,2,3,4,5); TimeSpan t3 = t1 + t2; TimeSpan t4 = t1.Add (t2); TimeSpan t5; bool exception; AssertEquals ("A1", 3, t3.Days); AssertEquals ("A2", 5, t3.Hours); AssertEquals ("A3", 7, t3.Minutes); AssertEquals ("A4", 9, t3.Seconds); AssertEquals ("A5", 11, t3.Milliseconds); AssertEquals ("A6", "3.05:07:09.0110000", t4.ToString ()); try { t5 = TimeSpan.MaxValue + new TimeSpan (1); exception = false; } catch (OverflowException) { exception = true; } Assert ("A7", exception); } public void TestCompare () { TimeSpan t1 = new TimeSpan (-1); TimeSpan t2 = new TimeSpan (1); int res; bool exception; AssertEquals ("A1", -1, TimeSpan.Compare (t1, t2)); AssertEquals ("A2", 1, TimeSpan.Compare (t2, t1)); AssertEquals ("A3", 0, TimeSpan.Compare (t2, t2)); AssertEquals ("A4", -1, TimeSpan.Compare (TimeSpan.MinValue, TimeSpan.MaxValue)); AssertEquals ("A5", -1, t1.CompareTo (t2)); AssertEquals ("A6", 1, t2.CompareTo (t1)); AssertEquals ("A7", 0, t2.CompareTo (t2)); AssertEquals ("A8", -1, TimeSpan.Compare (TimeSpan.MinValue, TimeSpan.MaxValue)); AssertEquals ("A9", 1, TimeSpan.Zero.CompareTo (null)); try { res = TimeSpan.Zero.CompareTo(""); exception = false; } catch (ArgumentException) { exception = true; } Assert ("A10", exception); AssertEquals ("A11", false, t1 == t2); AssertEquals ("A12", false, t1 > t2); AssertEquals ("A13", false, t1 >= t2); AssertEquals ("A14", true, t1 != t2); AssertEquals ("A15", true, t1 < t2); AssertEquals ("A16", true, t1 <= t2); } [Test] [ExpectedException (typeof (OverflowException))] public void NoNegateMinValue() { TimeSpan t1 = TimeSpan.MinValue.Negate (); } public void TestNegateAndDuration () { TimeSpan t1; bool exception; AssertEquals ("A1", "-00:00:00.0012345", new TimeSpan (12345).Negate ().ToString ()); AssertEquals ("A2", "00:00:00.0012345", new TimeSpan (-12345).Duration ().ToString ()); try { t1 = TimeSpan.MinValue.Duration (); exception = false; } catch (OverflowException) { exception = true; } Assert ("A4", exception); AssertEquals ("A5", "-00:00:00.0000077", (-(new TimeSpan (77))).ToString ()); AssertEquals("A6", "00:00:00.0000077", (+(new TimeSpan(77))).ToString()); } public void TestEquals () { TimeSpan t1 = new TimeSpan (1); TimeSpan t2 = new TimeSpan (2); string s = "justastring"; AssertEquals ("A1", true, t1.Equals (t1)); AssertEquals ("A2", false, t1.Equals (t2)); AssertEquals ("A3", false, t1.Equals (s)); AssertEquals ("A4", false, t1.Equals (null)); AssertEquals ("A5", true, TimeSpan.Equals (t1, t1)); AssertEquals ("A6", false, TimeSpan.Equals (t1, t2)); AssertEquals ("A7", false, TimeSpan.Equals (t1, null)); AssertEquals ("A8", false, TimeSpan.Equals (t1, s)); AssertEquals ("A9", false, TimeSpan.Equals (s, t2)); AssertEquals ("A10", true, TimeSpan.Equals (null,null)); } public void TestFromXXXX () { AssertEquals ("A1", "12.08:16:48", TimeSpan.FromDays (12.345).ToString ()); AssertEquals ("A2", "12:20:42", TimeSpan.FromHours (12.345).ToString ()); AssertEquals ("A3", "00:12:20.7000000", TimeSpan.FromMinutes (12.345).ToString ()); AssertEquals ("A4", "00:00:12.3450000", TimeSpan.FromSeconds (12.345).ToString ()); AssertEquals ("A5", "00:00:00.0120000", TimeSpan.FromMilliseconds (12.345).ToString ()); AssertEquals ("A6", "00:00:00.0012345", TimeSpan.FromTicks (12345).ToString ()); } [Test] [ExpectedException (typeof (OverflowException))] public void FromDays_MinValue () { TimeSpan.FromDays (Double.MinValue); } [Test] [ExpectedException (typeof (OverflowException))] public void FromDays_MaxValue () { TimeSpan.FromDays (Double.MaxValue); } [Test] [ExpectedException (typeof (ArgumentException))] public void FromDays_NaN () { TimeSpan.FromDays (Double.NaN); } [Test] [ExpectedException (typeof (OverflowException))] public void FromDays_PositiveInfinity () { // LAMESPEC: Document to return TimeSpan.MaxValue AssertEquals (TimeSpan.MaxValue, TimeSpan.FromDays (Double.PositiveInfinity)); } [Test] [ExpectedException (typeof (OverflowException))] public void FromDays_NegativeInfinity () { // LAMESPEC: Document to return TimeSpan.MinValue AssertEquals (TimeSpan.MinValue, TimeSpan.FromDays (Double.NegativeInfinity)); } [Test] [ExpectedException (typeof (OverflowException))] public void FromHours_MinValue () { TimeSpan.FromHours (Double.MinValue); } [Test] [ExpectedException (typeof (OverflowException))] public void FromHours_MaxValue () { TimeSpan.FromHours (Double.MaxValue); } [Test] [ExpectedException (typeof (ArgumentException))] public void FromHours_NaN () { TimeSpan.FromHours (Double.NaN); } [Test] [ExpectedException (typeof (OverflowException))] public void FromHours_PositiveInfinity () { // LAMESPEC: Document to return TimeSpan.MaxValue AssertEquals (TimeSpan.MaxValue, TimeSpan.FromHours (Double.PositiveInfinity)); } [Test] [ExpectedException (typeof (OverflowException))] public void FromHours_NegativeInfinity () { // LAMESPEC: Document to return TimeSpan.MinValue AssertEquals (TimeSpan.MinValue, TimeSpan.FromHours (Double.NegativeInfinity)); } [Test] [ExpectedException (typeof (OverflowException))] public void FromMilliseconds_MinValue () { TimeSpan.FromMilliseconds (Double.MinValue); } [Test] [ExpectedException (typeof (OverflowException))] public void FromMilliseconds_MaxValue () { TimeSpan.FromMilliseconds (Double.MaxValue); } [Test] [ExpectedException (typeof (ArgumentException))] public void FromMilliseconds_NaN () { TimeSpan.FromMilliseconds (Double.NaN); } [Test] [ExpectedException (typeof (OverflowException))] public void FromMilliseconds_PositiveInfinity () { // LAMESPEC: Document to return TimeSpan.MaxValue AssertEquals (TimeSpan.MaxValue, TimeSpan.FromMilliseconds (Double.PositiveInfinity)); } [Test] [ExpectedException (typeof (OverflowException))] public void FromMilliseconds_NegativeInfinity () { // LAMESPEC: Document to return TimeSpan.MinValue AssertEquals (TimeSpan.MinValue, TimeSpan.FromMilliseconds (Double.NegativeInfinity)); } [Test] [ExpectedException (typeof (OverflowException))] public void FromMinutes_MinValue () { TimeSpan.FromMinutes (Double.MinValue); } [Test] [ExpectedException (typeof (OverflowException))] public void FromMinutes_MaxValue () { TimeSpan.FromMinutes (Double.MaxValue); } [Test] [ExpectedException (typeof (ArgumentException))] public void FromMinutes_NaN () { TimeSpan.FromMinutes (Double.NaN); } [Test] [ExpectedException (typeof (OverflowException))] public void FromMinutes_PositiveInfinity () { // LAMESPEC: Document to return TimeSpan.MaxValue AssertEquals (TimeSpan.MaxValue, TimeSpan.FromMinutes (Double.PositiveInfinity)); } [Test] [ExpectedException (typeof (OverflowException))] public void FromMinutes_NegativeInfinity () { // LAMESPEC: Document to return TimeSpan.MinValue AssertEquals (TimeSpan.MinValue, TimeSpan.FromMinutes (Double.NegativeInfinity)); } [Test] [ExpectedException (typeof (OverflowException))] public void FromSeconds_MinValue () { TimeSpan.FromSeconds (Double.MinValue); } [Test] [ExpectedException (typeof (OverflowException))] public void FromSeconds_MaxValue () { TimeSpan.FromSeconds (Double.MaxValue); } [Test] [ExpectedException (typeof (ArgumentException))] public void FromSeconds_NaN () { TimeSpan.FromSeconds (Double.NaN); } [Test] [ExpectedException (typeof (OverflowException))] public void FromSeconds_PositiveInfinity () { // LAMESPEC: Document to return TimeSpan.MaxValue AssertEquals (TimeSpan.MaxValue, TimeSpan.FromSeconds (Double.PositiveInfinity)); } [Test] [ExpectedException (typeof (OverflowException))] public void FromSeconds_NegativeInfinity () { // LAMESPEC: Document to return TimeSpan.MinValue AssertEquals (TimeSpan.MinValue, TimeSpan.FromSeconds (Double.NegativeInfinity)); } public void TestGetHashCode () { AssertEquals ("A1", 77, new TimeSpan (77).GetHashCode ()); } private void ParseHelper (string s, bool expectFormat, bool expectOverflow, string expect) { bool formatException = false; bool overflowException = false; string result = "junk "; try { result = TimeSpan.Parse (s).ToString (); } catch (OverflowException) { overflowException = true; } catch (FormatException) { formatException = true; } AssertEquals ("A1", expectFormat, formatException); AssertEquals ("A2", expectOverflow, overflowException); if (!expectOverflow && !expectFormat) { AssertEquals ("A3", expect, result); } } public void TestParse () { ParseHelper (" 13:45:15 ",false, false, "13:45:15"); ParseHelper (" -1:2:3 ", false, false, "-01:02:03"); ParseHelper (" 25:0:0 ",false, true, "dontcare"); ParseHelper ("aaa", true, false, "dontcare"); ParseHelper ("-21.23:59:59.9999999", false, false, "-21.23:59:59.9999999"); ParseHelper ("100000000000000.1:1:1", false, true, "dontcare"); ParseHelper ("24:60:60", false, true, "dontcare"); ParseHelper ("0001:0002:0003.12 ", false, false, "01:02:03.1200000"); ParseHelper (" 1:2:3:12345678 ", true, false, "dontcare"); } // LAMESPEC: timespan in documentation is wrong - hh:mm:ss isn't mandatory [Test] public void Parse_Days_WithoutColon () { TimeSpan ts = TimeSpan.Parse ("1"); AssertEquals ("Days", 1, ts.Days); } public void TestSubstract () { TimeSpan t1 = new TimeSpan (2,3,4,5,6); TimeSpan t2 = new TimeSpan (1,2,3,4,5); TimeSpan t3 = t1 - t2; TimeSpan t4 = t1.Subtract (t2); TimeSpan t5; bool exception; AssertEquals ("A1", "1.01:01:01.0010000", t3.ToString ()); AssertEquals ("A2", "1.01:01:01.0010000", t4.ToString ()); try { t5 = TimeSpan.MinValue - new TimeSpan (1); exception = false; } catch (OverflowException) { exception = true; } Assert ("A3", exception); } public void TestToString () { TimeSpan t1 = new TimeSpan (1,2,3,4,5); TimeSpan t2 = -t1; AssertEquals ("A1", "1.02:03:04.0050000", t1.ToString ()); AssertEquals ("A2", "-1.02:03:04.0050000", t2.ToString ()); AssertEquals ("A3", "10675199.02:48:05.4775807", TimeSpan.MaxValue.ToString ()); AssertEquals ("A4", "-10675199.02:48:05.4775808", TimeSpan.MinValue.ToString ()); } [Test] public void ToString_Constants () { AssertEquals ("Zero", "00:00:00", TimeSpan.Zero.ToString ()); AssertEquals ("MaxValue", "10675199.02:48:05.4775807", TimeSpan.MaxValue.ToString ()); AssertEquals ("MinValue", "-10675199.02:48:05.4775808", TimeSpan.MinValue.ToString ()); } [Test] [ExpectedException (typeof (OverflowException))] public void Parse_InvalidValuesAndFormat_ExceptionOrder () { // hours should be between 0 and 23 but format is also invalid (too many dots) TimeSpan.Parse ("0.99.99.0"); } [Test] public void Parse_MinMaxValues () { AssertEquals ("MaxValue", TimeSpan.MaxValue, TimeSpan.Parse ("10675199.02:48:05.4775807")); AssertEquals ("MinValue", TimeSpan.MinValue, TimeSpan.Parse ("-10675199.02:48:05.4775808")); } [Test] [ExpectedException (typeof (OverflowException))] public void Parse_OverMaxValue() { TimeSpan.Parse ("10675199.02:48:05.4775808"); } [Test] [ExpectedException (typeof (OverflowException))] public void Parse_UnderMinValue() { TimeSpan.Parse ("-10675199.02:48:05.4775809"); } } }
/* Copyright (c) 2010 by Genstein This file is (or was originally) part of Trizbort, the Interactive Fiction Mapper. 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.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.Globalization; using PdfSharp.Drawing; namespace Trizbort { /// <summary> /// A connection between elements or points in space. /// </summary> /// <remarks> /// Connections are multi-segment lines between vertices. /// Each vertex is fixed either to a point in space or /// to an element's port. /// </remarks> internal class Connection : Element { public Connection(Project project) : base(project) { m_vertexList.Added += OnVertexAdded; m_vertexList.Removed += OnVertexRemoved; } // Added this second constructor to be used when loading a room // This constructor is significantly faster as it doesn't look for gap in the element IDs public Connection(Project project, int TotalIDs) : base(project, TotalIDs) { m_vertexList.Added += OnVertexAdded; m_vertexList.Removed += OnVertexRemoved; } public Connection(Project project, Vertex a, Vertex b) : this(project) { VertexList.Add(a); VertexList.Add(b); } // Added to ignore ID gaps public Connection(Project project, Vertex a, Vertex b, int TotalIDs) : this(project, TotalIDs) { VertexList.Add(a); VertexList.Add(b); } public Connection(Project project, Vertex a, Vertex b, params Vertex[] args) : this(project, a, b) { foreach (var vertex in args) { VertexList.Add(vertex); } } // Added to ignore ID gaps public Connection(Project project, Vertex a, Vertex b, int TotalIDs, params Vertex[] args) : this(project, a, b, TotalIDs) { foreach (var vertex in args) { VertexList.Add(vertex); } } private void OnVertexAdded(object sender, ItemEventArgs<Vertex> e) { e.Item.Connection = this; e.Item.Changed += OnVertexChanged; PortList.Add(new VertexPort(e.Item, this)); } private void OnVertexRemoved(object sender, ItemEventArgs<Vertex> e) { e.Item.Connection = null; e.Item.Changed -= OnVertexChanged; foreach (VertexPort port in PortList) { if (port.Vertex == e.Item) { PortList.Remove(port); break; } } } private void OnVertexChanged(object sender, EventArgs e) { RaiseChanged(); } public ConnectionStyle Style { get { return m_style; } set { if (m_style != value) { m_style = value; RaiseChanged(); } } } public ConnectionFlow Flow { get { return m_flow; } set { if (m_flow != value) { m_flow = value; RaiseChanged(); } } } public string StartText { get { return m_startText.Text; } set { if (m_startText.Text != value) { m_startText.Text = value; RaiseChanged(); } } } public string MidText { get { return m_midText.Text; } set { if (m_midText.Text != value) { m_midText.Text = value; RaiseChanged(); } } } public string EndText { get { return m_endText.Text; } set { if (m_endText.Text != value) { m_endText.Text = value; RaiseChanged(); } } } public void SetText(string start, string mid, string end) { StartText = start; MidText = mid ?? MidText; EndText = end; } public static void GetText(ConnectionLabel label, out string start, out string end) { start = string.Empty; end = string.Empty; switch (label) { case ConnectionLabel.None: start = string.Empty; end = string.Empty; break; case ConnectionLabel.Up: start = Up; end = Down; break; case ConnectionLabel.Down: start = Down; end = Up; break; case ConnectionLabel.In: start = In; end = Out; break; case ConnectionLabel.Out: start = Out; end = In; break; } } public void SetText(ConnectionLabel label) { string start, end; GetText(label, out start, out end); SetText(start, null, end); } public BoundList<Vertex> VertexList { get { return m_vertexList; } } public override Depth Depth { get { return Depth.Low; } } private List<LineSegment> GetSegments() { var list = new List<LineSegment>(); if (VertexList.Count > 0) { var first = VertexList[0]; var last = VertexList[VertexList.Count - 1]; int index = 0; Vector a = VertexList[index++].Position; if (first.Port != null && first.Port.HasStalk) { var stalkPos = first.Port.StalkPosition; list.Add(new LineSegment(a, stalkPos)); a = stalkPos; } while (index < VertexList.Count) { Vertex v = VertexList[index++]; Vector b = v.Position; if (index == VertexList.Count && v.Port != null && v.Port.HasStalk) { var stalkPos = v.Port.StalkPosition; list.Add(new LineSegment(a, stalkPos)); a = stalkPos; } list.Add(new LineSegment(a, b)); a = b; } } return list; } /// <summary> /// Split the given line segment if it crosses line segments we've already drawn. /// </summary> /// <param name="lineSegment">The line segment to consider.</param> /// <param name="context">The context in which we've been drawing line segments.</param> /// <param name="newSegments">The results of splitting the given line segment, if any. Call with a reference to a null list.</param> /// <returns>True if the line segment was split and newSegments now exists and contains line segments; false otherwise.</returns> private bool Split(LineSegment lineSegment, DrawingContext context, ref List<LineSegment> newSegments) { foreach (var previousSegment in context.LinesDrawn) { float amount = Math.Max(1,Settings.LineWidth) * 3; List<LineSegmentIntersect> intersects; if (lineSegment.Intersect(previousSegment, true, out intersects)) { foreach (var intersect in intersects) { switch (intersect.Type) { case LineSegmentIntersectType.MidPointA: var one = new LineSegment(lineSegment.Start, intersect.Position); if (one.Shorten(amount)) { if (!Split(one, context, ref newSegments)) { if (newSegments == null) { newSegments = new List<LineSegment>(); } newSegments.Add(one); } } var two = new LineSegment(intersect.Position, lineSegment.End); if (two.Forshorten(amount)) { if (!Split(two, context, ref newSegments)) { if (newSegments == null) { newSegments = new List<LineSegment>(); } newSegments.Add(two); } } break; case LineSegmentIntersectType.StartA: if (lineSegment.Forshorten(amount)) { if (!Split(lineSegment, context, ref newSegments)) { if (newSegments == null) { newSegments = new List<LineSegment>(); } newSegments.Add(lineSegment); } } break; case LineSegmentIntersectType.EndA: if (lineSegment.Shorten(amount)) { if (!Split(lineSegment, context, ref newSegments)) { if (newSegments == null) { newSegments = new List<LineSegment>(); } newSegments.Add(lineSegment); } } break; } // don't check other intersects; // we've already split this line, and tested the parts for further intersects. return newSegments != null; } } } return false; } public override void RecomputeSmartLineSegments(DrawingContext context) { m_smartSegments.Clear(); foreach (var lineSegment in GetSegments()) { List<LineSegment> newSegments = null; if (Split(lineSegment, context, ref newSegments)) { foreach (var newSegment in newSegments) { m_smartSegments.Add(newSegment); } } else { m_smartSegments.Add(lineSegment); } } foreach (var segment in m_smartSegments) { context.LinesDrawn.Add(segment); } } public override void Draw(XGraphics graphics, Palette palette, DrawingContext context) { List<LineSegment> lineSegments; if (context.UseSmartLineSegments) { lineSegments = m_smartSegments; } else { lineSegments = GetSegments(); } var path = palette.Path(); var random = new Random(GetHashCode()); foreach (var lineSegment in lineSegments) { var pen = palette.GetLinePen(context.Selected, context.Hover, Style == ConnectionStyle.Dashed); if (!Settings.DebugDisableLineRendering) { graphics.DrawLine(pen, lineSegment.Start.ToPointF(), lineSegment.End.ToPointF()); } var delta = lineSegment.Delta; if (Flow == ConnectionFlow.OneWay && delta.Length > Settings.ConnectionArrowSize) { var brush = palette.GetLineBrush(context.Selected, context.Hover); Drawing.DrawChevron(graphics, lineSegment.Mid.ToPointF(), (float)(Math.Atan2(delta.Y, delta.X) / Math.PI * 180), Settings.ConnectionArrowSize, brush); } context.LinesDrawn.Add(lineSegment); } Annotate(graphics, palette, lineSegments); } private void Annotate(XGraphics graphics, Palette palette, List<LineSegment> lineSegments) { if (lineSegments.Count == 0) return; if (!string.IsNullOrEmpty(StartText)) { Annotate(graphics, palette, lineSegments[0], m_startText, StringAlignment.Near); } if (!string.IsNullOrEmpty(EndText)) { Annotate(graphics, palette, lineSegments[lineSegments.Count - 1], m_endText, StringAlignment.Far); } if (!string.IsNullOrEmpty(MidText)) { float totalLength = 0; foreach (var lineSegment in lineSegments) { totalLength += lineSegment.Length; } float middle = totalLength / 2; foreach (var lineSegment in lineSegments) { var length = lineSegment.Length; if (middle > length) { middle -= length; } else { middle /= length; var pos = lineSegment.Start + lineSegment.Delta * middle; var fakeSegment = new LineSegment(pos - lineSegment.Delta * Numeric.Small, pos + lineSegment.Delta * Numeric.Small); Annotate(graphics, palette, fakeSegment, m_midText, StringAlignment.Center); break; } } } } private static void Annotate(XGraphics graphics, Palette palette, LineSegment lineSegment, TextBlock text, StringAlignment alignment) { Vector point; var delta = lineSegment.Delta; switch (alignment) { case StringAlignment.Near: default: point = lineSegment.Start; delta.Negate(); break; case StringAlignment.Center: point = lineSegment.Mid; break; case StringAlignment.Far: point = lineSegment.End; break; } var bounds = new Rect(point, Vector.Zero); bounds.Inflate(Settings.TextOffsetFromConnection); var angle = (float)-(Math.Atan2(delta.Y, delta.X) / Math.PI * 180.0); var compassPoint = CompassPoint.East; if (Numeric.InRange(angle, 0, 45)) { compassPoint = CompassPoint.NorthWest; } else if (Numeric.InRange(angle, 45, 90)) { compassPoint = CompassPoint.SouthEast; } else if (Numeric.InRange(angle, 90, 135)) { compassPoint = CompassPoint.SouthWest; } else if (Numeric.InRange(angle, 135, 180)) { compassPoint = CompassPoint.NorthEast; } else if (Numeric.InRange(angle, 0, -45)) { compassPoint = CompassPoint.NorthEast; } else if (Numeric.InRange(angle, -45, -90)) { compassPoint = CompassPoint.NorthEast; } else if (Numeric.InRange(angle, -90, -135)) { compassPoint = CompassPoint.NorthWest; } else if (Numeric.InRange(angle, -135, -180)) { compassPoint = CompassPoint.SouthEast; } var pos = bounds.GetCorner(compassPoint); XStringFormat format = new XStringFormat(); Drawing.SetAlignmentFromCardinalOrOrdinalDirection(format, compassPoint); if (alignment == StringAlignment.Center && Numeric.InRange(angle, -10, 10)) { // HACK: if the line segment is pretty horizontal and we're drawing mid-line text, // move text below the line to get it out of the way of any labels at the ends, // and center the text so it fits onto a line between two proximal rooms. pos = bounds.GetCorner(CompassPoint.South); format.Alignment = XStringAlignment.Center; format.LineAlignment = XLineAlignment.Near; } text.Draw(graphics, Settings.LineFont, palette.LineBrush, pos, Vector.Zero, format); } public override Rect UnionBoundsWith(Rect rect, bool includeMargins) { foreach (var vertex in VertexList) { rect = rect.Union(vertex.Position); } return rect; } public override Vector GetPortPosition(Port port) { var vertexPort = (VertexPort)port; return vertexPort.Vertex.Position; } public override Vector GetPortStalkPosition(Port port) { return GetPortPosition(port); } public override float Distance(Vector pos, bool includeMargins) { float distance = float.MaxValue; foreach (var segment in GetSegments()) { distance = Math.Min(distance, pos.DistanceFromLineSegment(segment)); } return distance; } public override bool Intersects(Rect rect) { foreach (var segment in GetSegments()) { if (segment.IntersectsWith(rect)) { return true; } } return false; } internal class VertexPort : MoveablePort { public VertexPort(Vertex vertex, Connection connection) : base(connection) { Vertex = vertex; Connection = connection; } public override string ID { get { return Connection.VertexList.IndexOf(Vertex).ToString(CultureInfo.InvariantCulture); } } public override void SetPosition(Vector pos) { Vertex.Position = pos; Connection.RaiseChanged(); } public override void DockAt(Port port) { Vertex.Port = port; Connection.RaiseChanged(); } public override Port DockedAt { get { return Vertex.Port; } } public Vertex Vertex { get; private set; } public Connection Connection { get; private set; } } public override bool HasDialog { get { return true; } } public override void ShowDialog() { using (var dialog = new ConnectionPropertiesDialog()) { dialog.IsDotted = Style == ConnectionStyle.Dashed; dialog.IsDirectional = Flow == ConnectionFlow.OneWay; dialog.StartText = StartText; dialog.MidText = MidText; dialog.EndText = EndText; if (dialog.ShowDialog() == DialogResult.OK) { Style = dialog.IsDotted ? ConnectionStyle.Dashed : ConnectionStyle.Solid; Flow = dialog.IsDirectional ? ConnectionFlow.OneWay : ConnectionFlow.TwoWay; StartText = dialog.StartText; MidText = dialog.MidText; EndText = dialog.EndText; } } } public void Save(XmlScribe scribe) { if (Style != DefaultStyle) { switch (Style) { case ConnectionStyle.Solid: scribe.Attribute("style", "solid"); break; case ConnectionStyle.Dashed: scribe.Attribute("style", "dashed"); break; } } if (Flow != DefaultFlow) { switch (Flow) { case ConnectionFlow.OneWay: scribe.Attribute("flow", "oneWay"); break; case ConnectionFlow.TwoWay: scribe.Attribute("flow", "twoWay"); break; } } if (!string.IsNullOrEmpty(StartText)) { scribe.Attribute("startText", StartText); } if (!string.IsNullOrEmpty(MidText)) { scribe.Attribute("midText", MidText); } if (!string.IsNullOrEmpty(EndText)) { scribe.Attribute("endText", EndText); } int index = 0; foreach (var vertex in VertexList) { if (vertex.Port != null) { scribe.StartElement("dock"); scribe.Attribute("index", index); scribe.Attribute("id", vertex.Port.Owner.ID); scribe.Attribute("port", vertex.Port.ID); scribe.EndElement(); } else { scribe.StartElement("point"); scribe.Attribute("index", index); scribe.Attribute("x", vertex.Position.X); scribe.Attribute("y", vertex.Position.Y); scribe.EndElement(); } ++index; } } public object BeginLoad(XmlElementReader element) { switch (element.Attribute("style").Text) { case "solid": default: Style = ConnectionStyle.Solid; break; case "dashed": Style = ConnectionStyle.Dashed; break; } switch (element.Attribute("flow").Text) { case "twoWay": default: Flow = ConnectionFlow.TwoWay; break; case "oneWay": Flow = ConnectionFlow.OneWay; break; } StartText = element.Attribute("startText").Text; MidText = element.Attribute("midText").Text; EndText = element.Attribute("endText").Text; var vertexElementList = new List<XmlElementReader>(); vertexElementList.AddRange(element.Children); vertexElementList.Sort((a, b) => { return a.Attribute("index").ToInt().CompareTo(b.Attribute("index").ToInt()); }); foreach (var vertexElement in vertexElementList) { if (vertexElement.HasName("point")) { var vertex = new Vertex(); vertex.Position = new Vector(vertexElement.Attribute("x").ToFloat(), vertexElement.Attribute("y").ToFloat()); VertexList.Add(vertex); } else if (vertexElement.HasName("dock")) { var vertex = new Vertex(); // temporarily leave this vertex as a positional vertex; // we can't safely dock it to a port until EndLoad(). VertexList.Add(vertex); } } return vertexElementList; } public void EndLoad(object state) { var elements = (List<XmlElementReader>)(state); for (int index=0; index<elements.Count; ++index) { var element = elements[index]; if (element.HasName("dock")) { Element target; if (Project.FindElement(element.Attribute("id").ToInt(), out target)) { var portID = element.Attribute("port").Text; foreach (var port in target.Ports) { if (StringComparer.InvariantCultureIgnoreCase.Compare(portID, port.ID) == 0) { var vertex = VertexList[index]; vertex.Port = port; break; } } } } } } public void Reverse() { VertexList.Reverse(); RaiseChanged(); } public Room GetSourceRoom(out CompassPoint sourceCompassPoint) { if (m_vertexList.Count > 0) { var port = m_vertexList[0].Port; if (port is Room.CompassPort) { var compassPort = (Room.CompassPort)port; sourceCompassPoint = compassPort.CompassPoint; return port.Owner as Room; } } sourceCompassPoint = CompassPoint.North; return null; } public Room GetTargetRoom(out CompassPoint targetCompassPoint) { if (m_vertexList.Count > 1) { var port = m_vertexList[m_vertexList.Count - 1].Port; if (port is Room.CompassPort) { var compassPort = (Room.CompassPort)port; targetCompassPoint = compassPort.CompassPoint; return compassPort.Owner as Room; } } targetCompassPoint = CompassPoint.North; return null; } public String ClipboardPrint() { String clipboardText = ""; switch (Style) { case ConnectionStyle.Solid: clipboardText += "solid" + ":"; break; case ConnectionStyle.Dashed: clipboardText += "dashed" + ":"; break; default: clipboardText += "default" + ":"; break; } switch (Flow) { case ConnectionFlow.OneWay: clipboardText += "oneWay" + ":"; break; case ConnectionFlow.TwoWay: clipboardText += "twoWay" + ":"; break; default: clipboardText += "default" + ":"; break; } clipboardText += StartText + ":"; clipboardText += MidText + ":"; clipboardText += EndText; int index = 0; foreach (var vertex in VertexList) { clipboardText += ":"; if (vertex.Port != null) { clipboardText += "dock" + ":"; clipboardText += index + ":"; clipboardText += vertex.Port.Owner.ID + ":"; clipboardText += vertex.Port.ID; } else { clipboardText += "point" + ":"; clipboardText += index + ":"; clipboardText += vertex.Position.X + ":"; clipboardText += vertex.Position.Y; } ++index; } clipboardText += ""; return clipboardText; } private static readonly ConnectionStyle DefaultStyle = ConnectionStyle.Solid; private static readonly ConnectionFlow DefaultFlow = ConnectionFlow.TwoWay; public const string Up = "up"; public const string Down = "down"; public const string In = "in"; public const string Out = "out"; private ConnectionStyle m_style = DefaultStyle; private ConnectionFlow m_flow = DefaultFlow; private BoundList<Vertex> m_vertexList = new BoundList<Vertex>(); private List<LineSegment> m_smartSegments = new List<LineSegment>(); private TextBlock m_startText = new TextBlock(); private TextBlock m_midText = new TextBlock(); private TextBlock m_endText = new TextBlock(); } /// <summary> /// The visual style of a connection. /// </summary> internal enum ConnectionStyle { Solid, Dashed, } /// <summary> /// The direction in which a connection flows. /// </summary> internal enum ConnectionFlow { TwoWay, OneWay } /// <summary> /// The style of label to display on a line. /// This is a simple set of defaults; lines may have entirely custom labels. /// </summary> internal enum ConnectionLabel { None, Up, Down, In, Out } }
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // using System; using System.Collections.Generic; using System.Text; using Autodesk.Revit.DB; using Autodesk.Revit.UI; using Autodesk.Revit; using Autodesk.Revit.DB.Architecture; using System.Drawing.Design; using System.ComponentModel; namespace Revit.SDK.Samples.NewHostedSweep.CS { /// <summary> /// This class contains the data for hosted sweep modification. /// </summary> public class ModificationData { /// <summary> /// Element to modify. /// </summary> private HostedSweep m_elemToModify; /// <summary> /// Creation data can be modified. /// </summary> private CreationData m_creationData; /// <summary> /// Revit active document. /// </summary> private Document m_rvtDoc; /// <summary> /// Revit UI document. /// </summary> private UIDocument m_rvtUIDoc; /// <summary> /// Sub transaction /// </summary> Transaction m_transaction; /// <summary> /// Constructor with HostedSweep and CreationData as parameters. /// </summary> /// <param name="elem">Element to modify</param> /// <param name="creationData">CreationData</param> public ModificationData(HostedSweep elem, CreationData creationData) { m_rvtDoc = creationData.Creator.RvtDocument; m_rvtUIDoc = creationData.Creator.RvtUIDocument; m_elemToModify = elem; m_creationData = creationData; m_transaction = new Transaction(m_rvtDoc, "External Tool"); m_creationData.EdgeAdded += new CreationData.EdgeEventHandler(m_creationData_EdgeAdded); m_creationData.EdgeRemoved += new CreationData.EdgeEventHandler(m_creationData_EdgeRemoved); m_creationData.SymbolChanged += new CreationData.SymbolChangedEventHandler(m_creationData_SymbolChanged); } /// <summary> /// Name of the Creator. /// </summary> public string CreatorName { get { return m_creationData.Creator.Name; } } /// <summary> /// Change the symbol of the HostedSweep. /// </summary> /// <param name="sym"></param> private void m_creationData_SymbolChanged(ElementType sym) { try { StartTransaction(); m_elemToModify.ChangeTypeId(sym.Id); CommitTransaction(); } catch { RollbackTransaction(); } } /// <summary> /// Remove the edge from the HostedSweep. /// </summary> /// <param name="edge"></param> private void m_creationData_EdgeRemoved(Edge edge) { try { StartTransaction(); m_elemToModify.RemoveSegment(edge.Reference); CommitTransaction(); } catch { RollbackTransaction(); } } /// <summary> /// Add the edge to the HostedSweep. /// </summary> /// <param name="edge"></param> private void m_creationData_EdgeAdded(Edge edge) { try { StartTransaction(); if (m_elemToModify is Fascia) { (m_elemToModify as Fascia).AddSegment(edge.Reference); } else if (m_elemToModify is Gutter) { (m_elemToModify as Gutter).AddSegment(edge.Reference); } else if (m_elemToModify is SlabEdge) { (m_elemToModify as SlabEdge).AddSegment(edge.Reference); } CommitTransaction(); } catch { RollbackTransaction(); } } /// <summary> /// Show the element in a good view. /// </summary> public void ShowElement() { try { StartTransaction(); m_rvtUIDoc.ShowElements(m_elemToModify); CommitTransaction(); } catch { RollbackTransaction(); } } /// <summary> /// Name will be displayed in property grid. /// </summary> [Category("Identity Data")] public String Name { get { String result = "[Id:" + m_elemToModify.Id.IntegerValue + "] "; return result + m_elemToModify.Name; } } /// <summary> /// HostedSweep Angle property. /// </summary> [Category("Profile")] public String Angle { get { Parameter angle = GetParameter("Angle"); if (angle != null) return angle.AsValueString(); else return m_elemToModify.Angle.ToString(); } set { try { StartTransaction(); Parameter angle = GetParameter("Angle"); if (angle != null) angle.SetValueString(value); else m_elemToModify.Angle = double.Parse(value); CommitTransaction(); } catch { RollbackTransaction(); } } } /// <summary> /// HostedSweep profiles edges, the edges can be removed or added in the /// pop up dialog. /// </summary> [TypeConverter(typeof(CreationDataTypeConverter)), Editor(typeof(EdgeFormUITypeEditor), typeof(UITypeEditor)), Category("Profile"), DisplayName("Profile Edges")] public CreationData AddOrRemoveSegments { get { return m_creationData; } } /// <summary> /// HostedSweep Length property. /// </summary> [Category("Dimensions")] public string Length { get { Parameter length = GetParameter("Length"); if (length != null) return length.AsValueString(); else return m_elemToModify.Length.ToString(); } } /// <summary> /// HostedSweep HorizontalFlipped property. /// </summary> [Category("Constraints"), DisplayName("Horizontal Profile Flipped")] public bool HorizontalFlipped { get { return m_elemToModify.HorizontalFlipped; } set { if (value != m_elemToModify.HorizontalFlipped) { try { StartTransaction(); m_elemToModify.HorizontalFlip(); CommitTransaction(); } catch { RollbackTransaction(); } } } } /// <summary> /// HostedSweep HorizontalOffset property. /// </summary> [Category("Constraints"), DisplayName("Horizontal Profile Offset")] public String HorizontalOffset { get { Parameter horiOff = GetParameter("Horizontal Profile Offset"); if (horiOff != null) return horiOff.AsValueString(); else return m_elemToModify.HorizontalOffset.ToString(); } set { try { StartTransaction(); Parameter horiOff = GetParameter("Horizontal Profile Offset"); if (horiOff != null) horiOff.SetValueString(value); else m_elemToModify.HorizontalOffset = double.Parse(value); CommitTransaction(); } catch { RollbackTransaction(); } } } /// <summary> /// HostedSweep VerticalFlipped property. /// </summary> [Category("Constraints"), DisplayName("Vertical Profile Flipped")] public bool VerticalFlipped { get { return m_elemToModify.VerticalFlipped; } set { if (value != m_elemToModify.VerticalFlipped) { try { StartTransaction(); m_elemToModify.VerticalFlip(); CommitTransaction(); } catch { RollbackTransaction(); } } } } /// <summary> /// HostedSweep VerticalOffset property. /// </summary> [Category("Constraints"), DisplayName("Vertical Profile Offset")] public String VerticalOffset { get { Parameter vertOff = GetParameter("Vertical Profile Offset"); if (vertOff != null) return vertOff.AsValueString(); else return m_elemToModify.VerticalOffset.ToString(); } set { try { StartTransaction(); Parameter vertOff = GetParameter("Vertical Profile Offset"); if (vertOff != null) vertOff.SetValueString(value); else m_elemToModify.VerticalOffset = double.Parse(value); CommitTransaction(); } catch { RollbackTransaction(); } } } /// <summary> /// Get parameter by given name. /// </summary> /// <param name="name">name of parameter</param> /// <returns>parameter whose definition name is the given name.</returns> protected Parameter GetParameter(String name) { return m_elemToModify.get_Parameter(name); } public TransactionStatus StartTransaction() { return m_transaction.Start(); } public TransactionStatus CommitTransaction() { return m_transaction.Commit(); } public TransactionStatus RollbackTransaction() { return m_transaction.RollBack(); } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Diagnostics.CodeAnalysis; using System.Text; namespace System.Management.Automation { /// <summary> /// A ProxyCommand class used to represent a Command constructed Dynamically /// </summary> public sealed class ProxyCommand { #region Private Constructor /// <summary> /// Private Constructor to restrict inheritance /// </summary> private ProxyCommand() { } #endregion #region Public Static Methods /// <summary> /// This method constructs a string representing the command specified by <paramref name="commandMetadata"/>. /// The returned string is a ScriptBlock which can be used to configure a Cmdlet/Function in a Runspace. /// </summary> /// <param name="commandMetadata"> /// An instance of CommandMetadata representing a command. /// </param> /// <returns> /// A string representing Command ScriptBlock. /// </returns> /// <exception cref="ArgumentNullException"> /// commandMetadata is null. /// </exception> public static string Create(CommandMetadata commandMetadata) { if (null == commandMetadata) { throw PSTraceSource.NewArgumentNullException("commandMetaData"); } return commandMetadata.GetProxyCommand("", true); } /// <summary> /// This method constructs a string representing the command specified by <paramref name="commandMetadata"/>. /// The returned string is a ScriptBlock which can be used to configure a Cmdlet/Function in a Runspace. /// </summary> /// <param name="commandMetadata"> /// An instance of CommandMetadata representing a command. /// </param> /// <param name="helpComment"> /// The string to be used as the help comment. /// </param> /// <returns> /// A string representing Command ScriptBlock. /// </returns> /// <exception cref="ArgumentNullException"> /// commandMetadata is null. /// </exception> public static string Create(CommandMetadata commandMetadata, string helpComment) { if (null == commandMetadata) { throw PSTraceSource.NewArgumentNullException("commandMetaData"); } return commandMetadata.GetProxyCommand(helpComment, true); } /// <summary> /// This method constructs a string representing the command specified by <paramref name="commandMetadata"/>. /// The returned string is a ScriptBlock which can be used to configure a Cmdlet/Function in a Runspace. /// </summary> /// <param name="commandMetadata"> /// An instance of CommandMetadata representing a command. /// </param> /// <param name="helpComment"> /// The string to be used as the help comment. /// </param> /// <param name="generateDynamicParameters"> /// A boolean that determines whether the generated proxy command should include the functionality required /// to proxy dynamic parameters of the underlying command. /// </param> /// <returns> /// A string representing Command ScriptBlock. /// </returns> /// <exception cref="ArgumentNullException"> /// commandMetadata is null. /// </exception> public static string Create(CommandMetadata commandMetadata, string helpComment, bool generateDynamicParameters) { if (null == commandMetadata) { throw PSTraceSource.NewArgumentNullException("commandMetaData"); } return commandMetadata.GetProxyCommand(helpComment, generateDynamicParameters); } /// <summary> /// This method constructs a string representing the CmdletBinding attribute of the command /// specified by <paramref name="commandMetadata"/>. /// </summary> /// <param name="commandMetadata"> /// An instance of CommandMetadata representing a command. /// </param> /// <returns> /// A string representing the CmdletBinding attribute of the command. /// </returns> /// <exception cref="ArgumentNullException"> /// commandMetadata is null. /// </exception> public static string GetCmdletBindingAttribute(CommandMetadata commandMetadata) { if (null == commandMetadata) { throw PSTraceSource.NewArgumentNullException("commandMetaData"); } return commandMetadata.GetDecl(); } /// <summary> /// This method constructs a string representing the param block of the command /// specified by <paramref name="commandMetadata"/>. The returned string only contains the /// parameters, it is not enclosed in "param()". /// </summary> /// <param name="commandMetadata"> /// An instance of CommandMetadata representing a command. /// </param> /// <returns> /// A string representing the parameters of the command. /// </returns> /// <exception cref="ArgumentNullException"> /// commandMetadata is null. /// </exception> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] public static string GetParamBlock(CommandMetadata commandMetadata) { if (null == commandMetadata) { throw PSTraceSource.NewArgumentNullException("commandMetaData"); } return commandMetadata.GetParamBlock(); } /// <summary> /// This method constructs a string representing the begin block of the command /// specified by <paramref name="commandMetadata"/>. The returned string only contains the /// script, it is not enclosed in "begin { }". /// </summary> /// <param name="commandMetadata"> /// An instance of CommandMetadata representing a command. /// </param> /// <returns> /// A string representing the begin block of the command. /// </returns> /// <exception cref="ArgumentNullException"> /// commandMetadata is null. /// </exception> public static string GetBegin(CommandMetadata commandMetadata) { if (null == commandMetadata) { throw PSTraceSource.NewArgumentNullException("commandMetaData"); } return commandMetadata.GetBeginBlock(); } /// <summary> /// This method constructs a string representing the process block of the command /// specified by <paramref name="commandMetadata"/>. The returned string only contains the /// script, it is not enclosed in "process { }". /// </summary> /// <param name="commandMetadata"> /// An instance of CommandMetadata representing a command. /// </param> /// <returns> /// A string representing the process block of the command. /// </returns> /// <exception cref="ArgumentNullException"> /// commandMetadata is null. /// </exception> public static string GetProcess(CommandMetadata commandMetadata) { if (null == commandMetadata) { throw PSTraceSource.NewArgumentNullException("commandMetaData"); } return commandMetadata.GetProcessBlock(); } /// <summary> /// This method constructs a string representing the dynamic parameter block of the command /// specified by <paramref name="commandMetadata"/>. The returned string only contains the /// script, it is not enclosed in "dynamicparam { }". /// </summary> /// <param name="commandMetadata"> /// An instance of CommandMetadata representing a command. /// </param> /// <returns> /// A string representing the dynamic parameter block of the command. /// </returns> /// <exception cref="ArgumentNullException"> /// commandMetadata is null. /// </exception> public static string GetDynamicParam(CommandMetadata commandMetadata) { if (null == commandMetadata) { throw PSTraceSource.NewArgumentNullException("commandMetaData"); } return commandMetadata.GetDynamicParamBlock(); } /// <summary> /// This method constructs a string representing the end block of the command /// specified by <paramref name="commandMetadata"/>. The returned string only contains the /// script, it is not enclosed in "end { }". /// </summary> /// <param name="commandMetadata"> /// An instance of CommandMetadata representing a command. /// </param> /// <returns> /// A string representing the end block of the command. /// </returns> /// <exception cref="ArgumentNullException"> /// commandMetadata is null. /// </exception> public static string GetEnd(CommandMetadata commandMetadata) { if (null == commandMetadata) { throw PSTraceSource.NewArgumentNullException("commandMetaData"); } return commandMetadata.GetEndBlock(); } private static T GetProperty<T>(PSObject obj, string property) where T : class { T result = null; if (obj != null && obj.Properties[property] != null) { result = obj.Properties[property].Value as T; } return result; } private static string GetObjText(object obj) { string text = null; PSObject psobj = obj as PSObject; if (psobj != null) { text = GetProperty<string>(psobj, "Text"); } return text ?? obj.ToString(); } private static void AppendContent(StringBuilder sb, string section, object obj) { if (obj != null) { string text = GetObjText(obj); if (!string.IsNullOrEmpty(text)) { sb.Append("\n"); sb.Append(section); sb.Append("\n\n"); sb.Append(text); sb.Append("\n"); } } } private static void AppendContent(StringBuilder sb, string section, PSObject[] array) { if (array != null) { bool first = true; foreach (PSObject obj in array) { string text = GetObjText(obj); if (!string.IsNullOrEmpty(text)) { if (first) { first = false; sb.Append("\n\n"); sb.Append(section); sb.Append("\n\n"); } sb.Append(text); sb.Append("\n"); } } if (!first) { sb.Append("\n"); } } } private static void AppendType(StringBuilder sb, string section, PSObject parent) { PSObject type = GetProperty<PSObject>(parent, "type"); PSObject name = GetProperty<PSObject>(type, "name"); if (name != null) { sb.Append("\n\n"); sb.Append(section); sb.Append("\n\n"); sb.Append(GetObjText(name)); sb.Append("\n"); } else { PSObject uri = GetProperty<PSObject>(type, "uri"); if (uri != null) { sb.Append("\n\n"); sb.Append(section); sb.Append("\n\n"); sb.Append(GetObjText(uri)); sb.Append("\n"); } } } /// <summary> /// Construct the text that can be used in a multi-line comment for get-help. /// </summary> /// <param name="help">A custom PSObject created by Get-Help.</param> /// <returns>A string that can be used as the help comment for script for the input HelpInfo object.</returns> /// <exception cref="System.ArgumentNullException">When the help argument is null.</exception> /// <exception cref="System.InvalidOperationException">When the help argument is not recognized as a HelpInfo object.</exception> public static string GetHelpComments(PSObject help) { if (help == null) { throw new ArgumentNullException("help"); } bool isHelpObject = false; foreach (string typeName in help.InternalTypeNames) { if (typeName.Contains("HelpInfo")) { isHelpObject = true; break; } } if (!isHelpObject) { string error = ProxyCommandStrings.HelpInfoObjectRequired; throw new InvalidOperationException(error); } StringBuilder sb = new StringBuilder(); AppendContent(sb, ".SYNOPSIS", GetProperty<string>(help, "Synopsis")); AppendContent(sb, ".DESCRIPTION", GetProperty<PSObject[]>(help, "Description")); PSObject parameters = GetProperty<PSObject>(help, "Parameters"); PSObject[] parameter = GetProperty<PSObject[]>(parameters, "Parameter"); if (parameter != null) { foreach (PSObject param in parameter) { PSObject name = GetProperty<PSObject>(param, "Name"); PSObject[] description = GetProperty<PSObject[]>(param, "Description"); sb.Append("\n.PARAMETER "); sb.Append(name); sb.Append("\n\n"); foreach (PSObject obj in description) { string text = GetProperty<string>(obj, "Text") ?? obj.ToString(); if (!string.IsNullOrEmpty(text)) { sb.Append(text); sb.Append("\n"); } } } } PSObject examples = GetProperty<PSObject>(help, "examples"); PSObject[] example = GetProperty<PSObject[]>(examples, "example"); if (example != null) { foreach (PSObject ex in example) { StringBuilder exsb = new StringBuilder(); PSObject[] introduction = GetProperty<PSObject[]>(ex, "introduction"); if (introduction != null) { foreach (PSObject intro in introduction) { if (intro != null) { exsb.Append(GetObjText(intro)); } } } PSObject code = GetProperty<PSObject>(ex, "code"); if (code != null) { exsb.Append(code.ToString()); } PSObject[] remarks = GetProperty<PSObject[]>(ex, "remarks"); if (remarks != null) { exsb.Append("\n"); foreach (PSObject remark in remarks) { string remarkText = GetProperty<string>(remark, "text"); exsb.Append(remarkText.ToString()); } } if (exsb.Length > 0) { sb.Append("\n\n.EXAMPLE\n\n"); sb.Append(exsb.ToString()); } } } PSObject alertSet = GetProperty<PSObject>(help, "alertSet"); AppendContent(sb, ".NOTES", GetProperty<PSObject[]>(alertSet, "alert")); PSObject inputtypes = GetProperty<PSObject>(help, "inputTypes"); PSObject inputtype = GetProperty<PSObject>(inputtypes, "inputType"); AppendType(sb, ".INPUTS", inputtype); PSObject returnValues = GetProperty<PSObject>(help, "returnValues"); PSObject returnValue = GetProperty<PSObject>(returnValues, "returnValue"); AppendType(sb, ".OUTPUTS", returnValue); PSObject relatedLinks = GetProperty<PSObject>(help, "relatedLinks"); PSObject[] navigationLink = GetProperty<PSObject[]>(relatedLinks, "navigationLink"); if (navigationLink != null) { foreach (PSObject link in navigationLink) { // Most likely only one of these will append anything, but it // isn't wrong to append them both. AppendContent(sb, ".LINK", GetProperty<PSObject>(link, "uri")); AppendContent(sb, ".LINK", GetProperty<PSObject>(link, "linkText")); } } AppendContent(sb, ".COMPONENT", GetProperty<PSObject>(help, "Component")); AppendContent(sb, ".ROLE", GetProperty<PSObject>(help, "Role")); AppendContent(sb, ".FUNCTIONALITY", GetProperty<PSObject>(help, "Functionality")); return sb.ToString(); } #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.Net.Test.Common; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.WebSockets.Client.Tests { public class ConnectTest : ClientWebSocketTestBase { public ConnectTest(ITestOutputHelper output) : base(output) { } [ActiveIssue(20360, TargetFrameworkMonikers.NetFramework)] [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(UnavailableWebSocketServers))] public async Task ConnectAsync_NotWebSocketServer_ThrowsWebSocketExceptionWithMessage(Uri server) { using (var cws = new ClientWebSocket()) { var cts = new CancellationTokenSource(TimeOutMilliseconds); WebSocketException ex = await Assert.ThrowsAsync<WebSocketException>(() => cws.ConnectAsync(server, cts.Token)); Assert.Equal(WebSocketError.Success, ex.WebSocketErrorCode); Assert.Equal(WebSocketState.Closed, cws.State); Assert.Equal(ResourceHelper.GetExceptionMessage("net_webstatus_ConnectFailure"), ex.Message); } } [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task EchoBinaryMessage_Success(Uri server) { await WebSocketHelper.TestEcho(server, WebSocketMessageType.Binary, TimeOutMilliseconds, _output); } [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task EchoTextMessage_Success(Uri server) { await WebSocketHelper.TestEcho(server, WebSocketMessageType.Text, TimeOutMilliseconds, _output); } [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoHeadersServers))] public async Task ConnectAsync_AddCustomHeaders_Success(Uri server) { using (var cws = new ClientWebSocket()) { cws.Options.SetRequestHeader("X-CustomHeader1", "Value1"); cws.Options.SetRequestHeader("X-CustomHeader2", "Value2"); using (var cts = new CancellationTokenSource(TimeOutMilliseconds)) { Task taskConnect = cws.ConnectAsync(server, cts.Token); Assert.True( (cws.State == WebSocketState.None) || (cws.State == WebSocketState.Connecting) || (cws.State == WebSocketState.Open), "State immediately after ConnectAsync incorrect: " + cws.State); await taskConnect; } Assert.Equal(WebSocketState.Open, cws.State); byte[] buffer = new byte[65536]; WebSocketReceiveResult recvResult; using (var cts = new CancellationTokenSource(TimeOutMilliseconds)) { recvResult = await ReceiveEntireMessageAsync(cws, new ArraySegment<byte>(buffer), cts.Token); } Assert.Equal(WebSocketMessageType.Text, recvResult.MessageType); string headers = WebSocketData.GetTextFromBuffer(new ArraySegment<byte>(buffer, 0, recvResult.Count)); Assert.True(headers.Contains("X-CustomHeader1:Value1")); Assert.True(headers.Contains("X-CustomHeader2:Value2")); await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None); } } [ActiveIssue(18784, TargetFrameworkMonikers.NetFramework)] [OuterLoop] [ConditionalTheory(nameof(WebSocketsSupported))] public async Task ConnectAsync_AddHostHeader_Success() { Uri server = System.Net.Test.Common.Configuration.WebSockets.RemoteEchoServer; // Send via the physical address such as "corefx-net.cloudapp.net" // Set the Host header to logical address like "subdomain.corefx-net.cloudapp.net" // Verify the scenario works and the remote server received "Host: subdomain.corefx-net.cloudapp.net" string logicalHost = "subdomain." + server.Host; using (var cws = new ClientWebSocket()) { // Set the Host header to the logical address cws.Options.SetRequestHeader("Host", logicalHost); using (var cts = new CancellationTokenSource(TimeOutMilliseconds)) { // Connect using the physical address Task taskConnect = cws.ConnectAsync(server, cts.Token); Assert.True( (cws.State == WebSocketState.None) || (cws.State == WebSocketState.Connecting) || (cws.State == WebSocketState.Open), "State immediately after ConnectAsync incorrect: " + cws.State); await taskConnect; } Assert.Equal(WebSocketState.Open, cws.State); byte[] buffer = new byte[65536]; WebSocketReceiveResult recvResult; using (var cts = new CancellationTokenSource(TimeOutMilliseconds)) { recvResult = await ReceiveEntireMessageAsync(cws, new ArraySegment<byte>(buffer), cts.Token); } Assert.Equal(WebSocketMessageType.Text, recvResult.MessageType); string headers = WebSocketData.GetTextFromBuffer(new ArraySegment<byte>(buffer, 0, recvResult.Count)); Assert.Contains($"Host:{logicalHost}", headers, StringComparison.Ordinal); await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None); } } [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoHeadersServers))] public async Task ConnectAsync_CookieHeaders_Success(Uri server) { using (var cws = new ClientWebSocket()) { Assert.Null(cws.Options.Cookies); cws.Options.Cookies = new CookieContainer(); Cookie cookie1 = new Cookie("Cookies", "Are Yummy"); Cookie cookie2 = new Cookie("Especially", "Chocolate Chip"); Cookie secureCookie = new Cookie("Occasionally", "Raisin"); secureCookie.Secure = true; cws.Options.Cookies.Add(server, cookie1); cws.Options.Cookies.Add(server, cookie2); cws.Options.Cookies.Add(server, secureCookie); using (var cts = new CancellationTokenSource(TimeOutMilliseconds)) { Task taskConnect = cws.ConnectAsync(server, cts.Token); Assert.True( cws.State == WebSocketState.None || cws.State == WebSocketState.Connecting || cws.State == WebSocketState.Open, "State immediately after ConnectAsync incorrect: " + cws.State); await taskConnect; } Assert.Equal(WebSocketState.Open, cws.State); byte[] buffer = new byte[65536]; WebSocketReceiveResult recvResult; using (var cts = new CancellationTokenSource(TimeOutMilliseconds)) { recvResult = await ReceiveEntireMessageAsync(cws, new ArraySegment<byte>(buffer), cts.Token); } Assert.Equal(WebSocketMessageType.Text, recvResult.MessageType); string headers = WebSocketData.GetTextFromBuffer(new ArraySegment<byte>(buffer, 0, recvResult.Count)); Assert.True(headers.Contains("Cookies=Are Yummy")); Assert.True(headers.Contains("Especially=Chocolate Chip")); Assert.Equal(server.Scheme == "wss", headers.Contains("Occasionally=Raisin")); await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None); } } [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task ConnectAsync_PassNoSubProtocol_ServerRequires_ThrowsWebSocketExceptionWithMessage(Uri server) { const string AcceptedProtocol = "CustomProtocol"; using (var cws = new ClientWebSocket()) { var cts = new CancellationTokenSource(TimeOutMilliseconds); var ub = new UriBuilder(server); ub.Query = "subprotocol=" + AcceptedProtocol; WebSocketException ex = await Assert.ThrowsAsync<WebSocketException>(() => cws.ConnectAsync(ub.Uri, cts.Token)); Assert.Equal(WebSocketError.Success, ex.WebSocketErrorCode); Assert.Equal(WebSocketState.Closed, cws.State); Assert.Equal(ResourceHelper.GetExceptionMessage("net_webstatus_ConnectFailure"), ex.Message); } } [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task ConnectAsync_PassMultipleSubProtocols_ServerRequires_ConnectionUsesAgreedSubProtocol(Uri server) { const string AcceptedProtocol = "AcceptedProtocol"; const string OtherProtocol = "OtherProtocol"; using (var cws = new ClientWebSocket()) { cws.Options.AddSubProtocol(AcceptedProtocol); cws.Options.AddSubProtocol(OtherProtocol); var cts = new CancellationTokenSource(TimeOutMilliseconds); var ub = new UriBuilder(server); ub.Query = "subprotocol=" + AcceptedProtocol; await cws.ConnectAsync(ub.Uri, cts.Token); Assert.Equal(WebSocketState.Open, cws.State); Assert.Equal(AcceptedProtocol, cws.SubProtocol); } } } }
// Prexonite // // Copyright (c) 2014, Christian Klauser // 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. // The names of the contributors may be used to endorse or // promote products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING // IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Diagnostics; using System.Globalization; using Prexonite.Compiler.Cil; using Prexonite.Modular; using Prexonite.Properties; using Prexonite.Types; using NoDebug = System.Diagnostics.DebuggerNonUserCodeAttribute; namespace Prexonite.Compiler.Ast { public class AstForeachLoop : AstLoop { public AstForeachLoop(ISourcePosition position, AstBlock parentBlock) : base(position, parentBlock) { } public AstExpr List; public AstGetSet Element; public bool IsInitialized { [DebuggerStepThrough] get { return List != null && Element != null; } } #region IAstHasExpressions Members public override AstExpr[] Expressions { get { return new[] {List}; } } #endregion protected override void DoEmitCode(CompilerTarget target, StackSemantics stackSemantics) { if(stackSemantics == StackSemantics.Value) throw new NotSupportedException("Foreach loops don't produce values and can thus not be emitted with value semantics."); if (!IsInitialized) throw new PrexoniteException("AstForeachLoop requires List and Element to be set."); //Optimize expression _OptimizeNode(target, ref List); //Create the enumerator variable var enumVar = Block.CreateLabel("enumerator"); target.Function.Variables.Add(enumVar); //Create the element assignment statement var element = Element.GetCopy(); AstExpr optElem; if (element.TryOptimize(target, out optElem)) { element = optElem as AstGetSet; if (element == null) { target.Loader.ReportMessage(Message.Error(Resources.AstForeachLoop_DoEmitCode_ElementTooComplicated,Position,MessageClasses.ForeachElementTooComplicated)); return; } } var ldEnumVar = target.Factory.Call(Position, EntityRef.Variable.Local.Create(enumVar)); var getCurrent = new AstGetSetMemberAccess(File, Line, Column, ldEnumVar, "Current"); element.Arguments.Add(getCurrent); element.Call = PCall.Set; //Actual Code Generation var moveNextAddr = -1; var getCurrentAddr = -1; var disposeAddr = -1; //Get the enumerator target.BeginBlock(Block); List.EmitValueCode(target); target.EmitGetCall(List.Position, 0, "GetEnumerator"); var castAddr = target.Code.Count; target.Emit(List.Position, OpCode.cast_const, "Object(\"System.Collections.IEnumerator\")"); target.EmitStoreLocal(List.Position, enumVar); //check whether an enhanced CIL implementation is possible bool emitHint; if (element.DefaultAdditionalArguments + element.Arguments.Count > 1) //has additional arguments emitHint = false; else emitHint = true; var @try = new AstTryCatchFinally(Position, Block); @try.TryBlock = new AstActionBlock ( Position, @try, delegate { target.EmitJump(Position, Block.ContinueLabel); //Assignment (begin) target.EmitLabel(Position, Block.BeginLabel); getCurrentAddr = target.Code.Count; element.EmitEffectCode(target); //Code block Block.EmitEffectCode(target); //Condition (continue) target.EmitLabel(Position, Block.ContinueLabel); moveNextAddr = target.Code.Count; target.EmitLoadLocal(List.Position, enumVar); target.EmitGetCall(List.Position, 0, "MoveNext"); target.EmitJumpIfTrue(Position, Block.BeginLabel); //Break target.EmitLabel(Position, Block.BreakLabel); }); @try.FinallyBlock = new AstActionBlock ( Position, @try, delegate { disposeAddr = target.Code.Count; target.EmitLoadLocal(List.Position, enumVar); target.EmitCommandCall(List.Position, 1, Engine.DisposeAlias, true); }); @try.EmitEffectCode(target); target.EndBlock(); if (getCurrentAddr < 0 || moveNextAddr < 0 || disposeAddr < 0) throw new PrexoniteException( "Could not capture addresses within foreach construct for CIL compiler hint."); else if (emitHint) { var hint = new ForeachHint(enumVar, castAddr, getCurrentAddr, moveNextAddr, disposeAddr); Cil.Compiler.AddCilHint(target, hint); Action<int, int> mkHook = (index, original) => { AddressChangeHook hook = null; hook = new AddressChangeHook( original, newAddr => { foreach ( var hintEntry in target.Meta[Loader.CilHintsKey].List) { var entry = hintEntry.List; if (entry[0] == ForeachHint.Key && entry[index].Text == original.ToString(CultureInfo.InvariantCulture)) { entry[index] = newAddr.ToString(CultureInfo.InvariantCulture); // AddressChangeHook.ctor can be trusted not to call the closure. // ReSharper disable PossibleNullReferenceException // ReSharper disable AccessToModifiedClosure hook.InstructionIndex = newAddr; // ReSharper restore AccessToModifiedClosure // ReSharper restore PossibleNullReferenceException original = newAddr; } } }); target.AddressChangeHooks.Add(hook); }; mkHook(ForeachHint.CastAddressIndex + 1, castAddr); mkHook(ForeachHint.GetCurrentAddressIndex + 1, getCurrentAddr); mkHook(ForeachHint.MoveNextAddressIndex + 1, moveNextAddr); mkHook(ForeachHint.DisposeAddressIndex + 1, disposeAddr); } // else nothing } } }
#region License // // Author: Nate Kohari <[email protected]> // Copyright (c) 2007-2008, Enkari, Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion #region Using Directives using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using Ninject.Core.Activation; using Ninject.Core.Infrastructure; #endregion namespace Ninject.Core.Parameters { /// <summary> /// An adapter for a parameter collection that provides a fluent interface. /// </summary> public class ParameterCollectionBuilder : IParameterCollection { /*----------------------------------------------------------------------------------------*/ #region Fields private readonly IParameterCollection _collection = new ParameterCollection(); #endregion /*----------------------------------------------------------------------------------------*/ #region Public Methods /// <summary> /// Determines whether this object is equal to the specified object. /// </summary> /// <param name="obj">The object to compare.</param> /// <returns><see langword="True"/> if the objects are equal, otherwise <see langword="false"/>.</returns> [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) { return base.Equals(obj); } /*----------------------------------------------------------------------------------------*/ /// <summary> /// Creates a hash code for the object. /// </summary> /// <returns>A hash code for the object.</returns> [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { return base.GetHashCode(); } /*----------------------------------------------------------------------------------------*/ /// <summary> /// Returns a string that represents the object. /// </summary> /// <returns>A string that represents the object.</returns> [EditorBrowsable(EditorBrowsableState.Never)] public override string ToString() { return base.ToString(); } /*----------------------------------------------------------------------------------------*/ /// <summary> /// Gets the type of the object. /// </summary> /// <returns>The object's type.</returns> [EditorBrowsable(EditorBrowsableState.Never)] public new Type GetType() { return base.GetType(); } #endregion /*----------------------------------------------------------------------------------------*/ #region Public Methods: Constructor Arguments /// <summary> /// Adds a transient value for the constructor argument with the specified name. /// </summary> /// <param name="name">The name of the argument.</param> /// <param name="value">The value to inject.</param> public ParameterCollectionBuilder ConstructorArgument(string name, object value) { _collection.Add(new ConstructorArgumentParameter(name, value)); return this; } /*----------------------------------------------------------------------------------------*/ /// <summary> /// Adds a transient value for the constructor argument with the specified name. /// </summary> /// <param name="name">The name of the argument.</param> /// <param name="valueProvider">The callback to trigger to get the value to inject.</param> public ParameterCollectionBuilder ConstructorArgument(string name, Func<IContext, object> valueProvider) { _collection.Add(new ConstructorArgumentParameter(name, valueProvider)); return this; } /*----------------------------------------------------------------------------------------*/ /// <summary> /// Adds transient values for the arguments defined in the dictionary. /// </summary> /// <param name="arguments">A dictionary of argument names and values to define.</param> public ParameterCollectionBuilder ConstructorArguments(IDictionary arguments) { _collection.AddRange(ParameterHelper.CreateFromDictionary(arguments, (name, value) => new ConstructorArgumentParameter(name, value))); return this; } /*----------------------------------------------------------------------------------------*/ /// <summary> /// Adds transient values for constructor arguments matching the properties defined on the object. /// </summary> /// <param name="arguments">An object containing the values to define as arguments.</param> public ParameterCollectionBuilder ConstructorArguments(object arguments) { _collection.AddRange(ParameterHelper.CreateFromDictionary(arguments, (name, value) => new ConstructorArgumentParameter(name, value))); return this; } #endregion /*----------------------------------------------------------------------------------------*/ #region Public Methods: Property Values /// <summary> /// Adds a transient value for the property with the specified name. /// </summary> /// <param name="name">The name of the property.</param> /// <param name="value">The value to inject.</param> public ParameterCollectionBuilder PropertyValue(string name, object value) { _collection.Add(new PropertyValueParameter(name, value)); return this; } /*----------------------------------------------------------------------------------------*/ /// <summary> /// Adds a transient value for the property with the specified name. /// </summary> /// <param name="name">The name of the property.</param> /// <param name="valueProvider">The callback to trigger to get the value to inject.</param> public ParameterCollectionBuilder PropertyValue(string name, Func<IContext, object> valueProvider) { _collection.Add(new PropertyValueParameter(name, valueProvider)); return this; } /*----------------------------------------------------------------------------------------*/ /// <summary> /// Adds transient values for the properties defined in the dictionary. /// </summary> /// <param name="values">A dictionary of property names and values to define.</param> public ParameterCollectionBuilder PropertyValues(IDictionary values) { _collection.AddRange(ParameterHelper.CreateFromDictionary(values, (name, value) => new PropertyValueParameter(name, value))); return this; } /*----------------------------------------------------------------------------------------*/ /// <summary> /// Adds transient values for properties matching those defined on the object. /// </summary> /// <param name="values">An object containing the values to define as arguments.</param> public ParameterCollectionBuilder PropertyValues(object values) { _collection.AddRange(ParameterHelper.CreateFromDictionary(values, (name, value) => new PropertyValueParameter(name, value))); return this; } #endregion /*----------------------------------------------------------------------------------------*/ #region Public Methods: Context Variable /// <summary> /// Adds a variable to the context. /// </summary> /// <param name="name">The name of the variable.</param> /// <param name="value">The value for the variable.</param> public ParameterCollectionBuilder Variable(string name, object value) { _collection.Add(new VariableParameter(name, value)); return this; } /*----------------------------------------------------------------------------------------*/ /// <summary> /// Adds a late-bound variable to the context. The callback will be triggered when the /// variable's value is requested during activation. /// </summary> /// <param name="name">The name of the variable.</param> /// <param name="valueProvider">The callback that will return the value for the variable.</param> public ParameterCollectionBuilder Variable(string name, Func<IContext, object> valueProvider) { _collection.Add(new VariableParameter(name, valueProvider)); return this; } /*----------------------------------------------------------------------------------------*/ /// <summary> /// Adds context variables for the properties defined in the dictionary. /// </summary> /// <param name="values">A dictionary of context variables and their associated values.</param> public ParameterCollectionBuilder Variables(IDictionary values) { _collection.AddRange(ParameterHelper.CreateFromDictionary(values, (name, value) => new VariableParameter(name, value))); return this; } /*----------------------------------------------------------------------------------------*/ /// <summary> /// Adds context variables for the properties defined on the object. /// </summary> /// <param name="values">An object containing the values to define as context variables.</param> public ParameterCollectionBuilder Variables(object values) { _collection.AddRange(ParameterHelper.CreateFromDictionary(values, (name, value) => new VariableParameter(name, value))); return this; } #endregion /*----------------------------------------------------------------------------------------*/ #region Public Methods: Custom Parameter Types /// <summary> /// Adds the specified custom parameter to the collection. /// </summary> /// <typeparam name="T">The type of the parameter.</typeparam> /// <param name="parameter">The parameter to add.</param> public ParameterCollectionBuilder Custom<T>(T parameter) where T : class, IParameter { _collection.Add(parameter); return this; } /*----------------------------------------------------------------------------------------*/ /// <summary> /// Adds the specified custom parameters to the collection. /// </summary> /// <typeparam name="T">The type of the parameters.</typeparam> /// <param name="parameters">The parameters to add.</param> public ParameterCollectionBuilder Custom<T>(IEnumerable<T> parameters) where T : class, IParameter { _collection.AddRange(parameters); return this; } #endregion /*----------------------------------------------------------------------------------------*/ #region ITypedCollection Implementation void ITypedCollection<string, IParameter>.Add<T>(T item) { _collection.Add(item); } /*----------------------------------------------------------------------------------------*/ void ITypedCollection<string, IParameter>.Add(Type type, IParameter item) { _collection.Add(type, item); } /*----------------------------------------------------------------------------------------*/ void ITypedCollection<string, IParameter>.AddRange<T>(IEnumerable<T> items) { _collection.AddRange(items); } /*----------------------------------------------------------------------------------------*/ void ITypedCollection<string, IParameter>.AddRange(Type type, IEnumerable<IParameter> items) { _collection.AddRange(type, items); } /*----------------------------------------------------------------------------------------*/ bool ITypedCollection<string, IParameter>.Has<T>(string key) { return _collection.Has<T>(key); } /*----------------------------------------------------------------------------------------*/ bool ITypedCollection<string, IParameter>.Has(Type type, string key) { return _collection.Has(type, key); } /*----------------------------------------------------------------------------------------*/ bool ITypedCollection<string, IParameter>.HasOneOrMore<T>() { return _collection.HasOneOrMore<T>(); } /*----------------------------------------------------------------------------------------*/ bool ITypedCollection<string, IParameter>.HasOneOrMore(Type type) { return _collection.HasOneOrMore(type); } /*----------------------------------------------------------------------------------------*/ T ITypedCollection<string, IParameter>.Get<T>(string key) { return _collection.Get<T>(key); } /*----------------------------------------------------------------------------------------*/ IParameter ITypedCollection<string, IParameter>.Get(Type type, string key) { return _collection.Get(type, key); } /*----------------------------------------------------------------------------------------*/ T ITypedCollection<string, IParameter>.GetOne<T>() { return _collection.GetOne<T>(); } /*----------------------------------------------------------------------------------------*/ IParameter ITypedCollection<string, IParameter>.GetOne(Type type) { return _collection.GetOne(type); } /*----------------------------------------------------------------------------------------*/ IList<T> ITypedCollection<string, IParameter>.GetAll<T>() { return _collection.GetAll<T>(); } /*----------------------------------------------------------------------------------------*/ IList<IParameter> ITypedCollection<string, IParameter>.GetAll(Type type) { return _collection.GetAll(type); } /*----------------------------------------------------------------------------------------*/ IList<Type> ITypedCollection<string, IParameter>.GetTypes() { return _collection.GetTypes(); } #endregion /*----------------------------------------------------------------------------------------*/ #region IParameterCollection Implementation void IParameterCollection.CopyFrom(IParameterCollection parameters) { _collection.CopyFrom(parameters); } /*----------------------------------------------------------------------------------------*/ void IParameterCollection.InheritFrom(IParameterCollection parameters) { _collection.InheritFrom(parameters); } /*----------------------------------------------------------------------------------------*/ object IParameterCollection.GetValueOf<T>(string name, IContext context) { return _collection.GetValueOf<T>(name, context); } /*----------------------------------------------------------------------------------------*/ object IParameterCollection.GetValueOf(Type type, string name, IContext context) { return _collection.GetValueOf(type, name, context); } #endregion /*----------------------------------------------------------------------------------------*/ } }
using System; using System.Collections.Generic; using System.Linq; using InAudioSystem.ExtensionMethods; using UnityEditor; using UnityEngine; using Object = UnityEngine.Object; namespace InAudioSystem.InAudioEditor { public static class AudioNodeWorker { public static InAudioNode CreateNode(GameObject go, InAudioNode parent, int guid, AudioNodeType type) { var node = go.AddComponentUndo<InAudioNode>(); node._guid = guid; node._type = type; node.Name = parent.Name + " Child"; node.MixerGroup = parent.MixerGroup; node.AssignParent(parent); return node; } public static InAudioNode CreateRoot(GameObject go, int guid) { var node = go.AddComponent<InAudioNode>(); AddDataClass(node); node._guid = guid; node._type = AudioNodeType.Root; node.EditorSettings.IsFoldedOut = true; node.Name = "Audio Root"; return node; } public static InAudioNode CreateTree(GameObject go, int numberOfChildren) { var Tree = CreateRoot(go, GUIDCreator.Create()); for (int i = 0; i < numberOfChildren; ++i) { var newNode = CreateNode(go, Tree, GUIDCreator.Create(), AudioNodeType.Folder); newNode.Name = "Audio Folder " + i; AddDataClass(newNode); } Tree.EditorSettings.IsFoldedOut = true; return Tree; } public static InAudioNode CreateNode(GameObject go, InAudioNode parent, AudioNodeType type) { var newNode = CreateNode(go, parent, GUIDCreator.Create(), type); AddDataClass(newNode); return newNode; } public static InAudioNodeBaseData AddDataClass(InAudioNode node) { switch (node._type) { case AudioNodeType.Root: node._nodeData = node.gameObject.AddComponentUndo<InFolderData>(); break; case AudioNodeType.Audio: node._nodeData = node.gameObject.AddComponentUndo<InAudioData>(); break; case AudioNodeType.Random: var randomData = node.gameObject.AddComponentUndo<RandomData>(); node._nodeData = randomData; for (int i = 0; i < node._children.Count; ++i) randomData.weights.Add(50); break; case AudioNodeType.Sequence: node._nodeData = node.gameObject.AddComponentUndo<InSequenceData>(); break; case AudioNodeType.Multi: node._nodeData = node.gameObject.AddComponentUndo<MultiData>(); break; case AudioNodeType.Track: node._nodeData = node.gameObject.AddComponentUndo<InTrackData>(); break; case AudioNodeType.Folder: var folderData = node.gameObject.AddComponentUndo<InFolderData>(); //folderData.BankLink = node.GetBank(); node._nodeData = folderData; break; } return node._nodeData; } public static void AddNewParent(InAudioNode node, AudioNodeType parentType) { InUndoHelper.RecordObject(new Object[] { node, node._parent }, "Undo Add New Parent for " + node.Name); var newParent = CreateNode(node.gameObject, node._parent, parentType); var oldParent = node._parent; newParent.MixerGroup = node.MixerGroup; newParent.EditorSettings.IsFoldedOut = true; int index = oldParent._children.FindIndex(node); NodeWorker.RemoveFromParent(node); node.AssignParent(newParent); OnRandomNode(newParent); NodeWorker.RemoveFromParent(newParent); oldParent._children.Insert(index, newParent); } private static void OnRandomNode(InAudioNode parent) { if (parent._type == AudioNodeType.Random) (parent._nodeData as RandomData).weights.Add(50); } public static InAudioNode CreateChild(InAudioNode parent, AudioNodeType newNodeType, string name) { var node = CreateChild(parent, newNodeType); node.Name = name; return node; } public static InAudioNode CreateChild(InAudioNode parent, AudioNodeType newNodeType) { return CreateChild(parent.gameObject, parent, newNodeType); } public static InAudioNode CreateChild(GameObject go, InAudioNode parent, AudioNodeType newNodeType) { InUndoHelper.RecordObject(InUndoHelper.Array(parent).Concat(parent.GetAuxData()).ToArray(), "Undo Node Creation"); OnRandomNode(parent); var child = CreateNode(go, parent, GUIDCreator.Create(), newNodeType); parent.EditorSettings.IsFoldedOut = true; child.Name = parent.Name + " Child"; AddDataClass(child); return child; } public static void ConvertNodeType(InAudioNode node, AudioNodeType newType) { if (newType == node._type) return; InUndoHelper.DoInGroup(() => { InUndoHelper.RecordObjectFull(new Object[] { node, node._nodeData }, "Change Node Type"); node._type = newType; InUndoHelper.Destroy(node._nodeData); AddDataClass(node); }); } public static void Duplicate(InAudioNode audioNode) { InUndoHelper.DoInGroup(() => { List<Object> toUndo = new List<Object>(); toUndo.Add(audioNode._parent); toUndo.AddRange(audioNode._parent.GetAuxData()); InUndoHelper.RecordObjectFull(toUndo.ToArray(), "Undo Duplication Of " + audioNode.Name); if (audioNode._parent._type == AudioNodeType.Random) { (audioNode._parent._nodeData as RandomData).weights.Add(50); } NodeWorker.DuplicateHierarchy(audioNode, (@oldNode, newNode) => { var gameObject = audioNode.gameObject; if (oldNode._nodeData != null) { NodeDuplicate(oldNode, newNode, gameObject); } }); }); } public static void CopyTo(InAudioNode audioNode, InAudioNode newParent) { List<Object> toUndo = new List<Object>(); toUndo.Add(audioNode._parent); toUndo.AddRange(audioNode._parent.GetAuxData()); InUndoHelper.RecordObjectFull(toUndo.ToArray(), "Undo Move"); NodeWorker.DuplicateHierarchy(audioNode, newParent, newParent.gameObject, (@oldNode, newNode) => { var gameObject = newParent.gameObject; if (oldNode._nodeData != null) { NodeDuplicate(oldNode, newNode, gameObject); } }); } private static void NodeDuplicate(InAudioNode oldNode, InAudioNode newNode, GameObject gameObject) { Type type = oldNode._nodeData.GetType(); newNode._nodeData = gameObject.AddComponentUndo(type) as InAudioNodeBaseData; EditorUtility.CopySerialized(oldNode._nodeData, newNode._nodeData); } public static void DeleteNodeNoGroup(InAudioNode node) { InUndoHelper.RecordObjects("Undo Deletion of " + node.Name, node, node._nodeData, node._parent, node._parent._nodeData); if (node._parent._type == AudioNodeType.Random) //We also need to remove the child from the weight list { var data = node._parent._nodeData as RandomData; if (data != null) data.weights.RemoveAt(node._parent._children.FindIndex(node)); //Find in parent, and then remove the weight in the random node node._parent._children.Remove(node); } DeleteNodeRec(node); } public static void DeleteNode(InAudioNode node) { InUndoHelper.DoInGroup(() => { InUndoHelper.RecordObjects("Undo Deletion of " + node.Name, node, node._nodeData, node._parent, node._parent._nodeData); if (node._parent._type == AudioNodeType.Random) //We also need to remove the child from the weight list { var data = node._parent._nodeData as RandomData; if (data != null) data.weights.RemoveAt(node._parent._children.FindIndex(node)); //Find in parent, and then remove the weight in the random node node._parent._children.Remove(node); } DeleteNodeRec(node); }); } private static void DeleteNodeRec(InAudioNode node) { for (int i = 0; i < node._children.Count; i++) { DeleteNodeRec(node._children[i]); } InUndoHelper.Destroy(node._nodeData); InUndoHelper.Destroy(node); } } }
using System; using System.Collections.Generic; using System.Net; using System.Text; using System.Threading.Tasks; using NSubstitute; using Octokit; using Octokit.Tests.Helpers; using Xunit; namespace Octokit.Tests.Clients { /// <summary> /// Client tests mostly just need to make sure they call the IApiConnection with the correct /// relative Uri. No need to fake up the response. All *those* tests are in ApiConnectionTests.cs. /// </summary> public class RepositoriesClientTests { public class TheConstructor { [Fact] public void EnsuresNonNullArguments() { Assert.Throws<ArgumentNullException>(() => new RepositoriesClient(null)); } } public class TheCreateMethodForUser { [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await AssertEx.Throws<ArgumentNullException>(async () => await client.Create(null)); await AssertEx.Throws<ArgumentException>(async () => await client.Create(new NewRepository { Name = null })); } [Fact] public void UsesTheUserReposUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.Create(new NewRepository { Name = "aName" }); connection.Received().Post<Repository>(Arg.Is<Uri>(u => u.ToString() == "user/repos"), Arg.Any<NewRepository>()); } [Fact] public void TheNewRepositoryDescription() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var newRepository = new NewRepository { Name = "aName" }; client.Create(newRepository); connection.Received().Post<Repository>(Args.Uri, newRepository); } [Fact] public async Task ThrowsRepositoryExistsExceptionWhenRepositoryExistsForCurrentUser() { var newRepository = new NewRepository { Name = "aName" }; var response = Substitute.For<IResponse>(); response.StatusCode.Returns((HttpStatusCode)422); response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":" + @"""http://developer.github.com/v3/repos/#create"",""errors"":[{""resource"":""Repository""," + @"""code"":""custom"",""field"":""name"",""message"":""name already exists on this account""}]}"); var credentials = new Credentials("haacked", "pwd"); var connection = Substitute.For<IApiConnection>(); connection.Connection.BaseAddress.Returns(GitHubClient.GitHubApiUrl); connection.Connection.Credentials.Returns(credentials); connection.Post<Repository>(Args.Uri, newRepository) .Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); }); var client = new RepositoriesClient(connection); var exception = await AssertEx.Throws<RepositoryExistsException>( async () => await client.Create(newRepository)); Assert.False(exception.OwnerIsOrganization); Assert.Null(exception.Owner); Assert.Equal("aName", exception.RepositoryName); Assert.Null(exception.ExistingRepositoryWebUrl); } [Fact] public async Task ThrowsExceptionWhenPrivateRepositoryQuotaExceeded() { var newRepository = new NewRepository { Name = "aName", Private = true }; var response = Substitute.For<IResponse>(); response.StatusCode.Returns((HttpStatusCode)422); response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":" + @"""http://developer.github.com/v3/repos/#create"",""errors"":[{""resource"":""Repository""," + @"""code"":""custom"",""field"":""name"",""message"":" + @"""name can't be private. You are over your quota.""}]}"); var credentials = new Credentials("haacked", "pwd"); var connection = Substitute.For<IApiConnection>(); connection.Connection.BaseAddress.Returns(GitHubClient.GitHubApiUrl); connection.Connection.Credentials.Returns(credentials); connection.Post<Repository>(Args.Uri, newRepository) .Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); }); var client = new RepositoriesClient(connection); var exception = await AssertEx.Throws<PrivateRepositoryQuotaExceededException>( async () => await client.Create(newRepository)); Assert.NotNull(exception); } } public class TheCreateMethodForOrganization { [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await AssertEx.Throws<ArgumentNullException>(async () => await client.Create(null, new NewRepository { Name = "aName" })); await AssertEx.Throws<ArgumentException>(async () => await client.Create("aLogin", null)); await AssertEx.Throws<ArgumentException>(async () => await client.Create("aLogin", new NewRepository { Name = null })); } [Fact] public async Task UsesTheOrganizatinosReposUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.Create("theLogin", new NewRepository { Name = "aName" }); connection.Received().Post<Repository>( Arg.Is<Uri>(u => u.ToString() == "orgs/theLogin/repos"), Args.NewRepository); } [Fact] public async Task TheNewRepositoryDescription() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var newRepository = new NewRepository { Name = "aName" }; await client.Create("aLogin", newRepository); connection.Received().Post<Repository>(Args.Uri, newRepository); } [Fact] public async Task ThrowsRepositoryExistsExceptionWhenRepositoryExistsForSpecifiedOrg() { var newRepository = new NewRepository { Name = "aName" }; var response = Substitute.For<IResponse>(); response.StatusCode.Returns((HttpStatusCode)422); response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":" + @"""http://developer.github.com/v3/repos/#create"",""errors"":[{""resource"":""Repository""," + @"""code"":""custom"",""field"":""name"",""message"":""name already exists on this account""}]}"); var connection = Substitute.For<IApiConnection>(); connection.Connection.BaseAddress.Returns(GitHubClient.GitHubApiUrl); connection.Post<Repository>(Args.Uri, newRepository) .Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); }); var client = new RepositoriesClient(connection); var exception = await AssertEx.Throws<RepositoryExistsException>( async () => await client.Create("illuminati", newRepository)); Assert.True(exception.OwnerIsOrganization); Assert.Equal("illuminati", exception.Owner); Assert.Equal("aName", exception.RepositoryName); Assert.Equal(new Uri("https://github.com/illuminati/aName"), exception.ExistingRepositoryWebUrl); Assert.Equal("There is already a repository named 'aName' in the organization 'illuminati'.", exception.Message); } [Fact] public async Task ThrowsValidationException() { var newRepository = new NewRepository { Name = "aName" }; var response = Substitute.For<IResponse>(); response.StatusCode.Returns((HttpStatusCode)422); response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":" + @"""http://developer.github.com/v3/repos/#create"",""errors"":[]}"); var connection = Substitute.For<IApiConnection>(); connection.Connection.BaseAddress.Returns(GitHubClient.GitHubApiUrl); connection.Post<Repository>(Args.Uri, newRepository) .Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); }); var client = new RepositoriesClient(connection); var exception = await AssertEx.Throws<ApiValidationException>( async () => await client.Create("illuminati", newRepository)); Assert.Null(exception as RepositoryExistsException); } [Fact] public async Task ThrowsRepositoryExistsExceptionForEnterpriseInstance() { var newRepository = new NewRepository { Name = "aName" }; var response = Substitute.For<IResponse>(); response.StatusCode.Returns((HttpStatusCode)422); response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":" + @"""http://developer.github.com/v3/repos/#create"",""errors"":[{""resource"":""Repository""," + @"""code"":""custom"",""field"":""name"",""message"":""name already exists on this account""}]}"); var connection = Substitute.For<IApiConnection>(); connection.Connection.BaseAddress.Returns(new Uri("https://example.com")); connection.Post<Repository>(Args.Uri, newRepository) .Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); }); var client = new RepositoriesClient(connection); var exception = await AssertEx.Throws<RepositoryExistsException>( async () => await client.Create("illuminati", newRepository)); Assert.Equal("aName", exception.RepositoryName); Assert.Equal(new Uri("https://example.com/illuminati/aName"), exception.ExistingRepositoryWebUrl); } } public class TheDeleteMethod { [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await AssertEx.Throws<ArgumentNullException>(async () => await client.Delete(null, "aRepoName")); await AssertEx.Throws<ArgumentNullException>(async () => await client.Delete("anOwner", null)); } [Fact] public async Task RequestsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.Delete("theOwner", "theRepoName"); connection.Received().Delete(Arg.Is<Uri>(u => u.ToString() == "repos/theOwner/theRepoName")); } } public class TheGetMethod { [Fact] public void RequestsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.Get("fake", "repo"); connection.Received().Get<Repository>(Arg.Is<Uri>(u => u.ToString() == "repos/fake/repo"), null); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await AssertEx.Throws<ArgumentNullException>(async () => await client.Get(null, "name")); await AssertEx.Throws<ArgumentNullException>(async () => await client.Get("owner", null)); } } public class TheGetAllForCurrentMethod { [Fact] public void RequestsTheCorrectUrlAndReturnsOrganizations() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllForCurrent(); connection.Received() .GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "user/repos")); } } public class TheGetAllForUserMethod { [Fact] public void RequestsTheCorrectUrlAndReturnsOrganizations() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllForUser("username"); connection.Received() .GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "users/username/repos")); } [Fact] public void EnsuresNonNullArguments() { var reposEndpoint = new RepositoriesClient(Substitute.For<IApiConnection>()); Assert.Throws<ArgumentNullException>(() => reposEndpoint.GetAllForUser(null)); } } public class TheGetAllForOrgMethod { [Fact] public void RequestsTheCorrectUrlAndReturnsOrganizations() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllForOrg("orgname"); connection.Received() .GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "orgs/orgname/repos")); } [Fact] public void EnsuresNonNullArguments() { var reposEndpoint = new RepositoriesClient(Substitute.For<IApiConnection>()); Assert.Throws<ArgumentNullException>(() => reposEndpoint.GetAllForOrg(null)); } } public class TheGetReadmeMethod { [Fact] public async Task ReturnsReadme() { string encodedContent = Convert.ToBase64String(Encoding.UTF8.GetBytes("Hello world")); var readmeInfo = new ReadmeResponse { Content = encodedContent, Encoding = "base64", Name = "README.md", Url = "https://github.example.com/readme.md", HtmlUrl = "https://github.example.com/readme" }; var connection = Substitute.For<IApiConnection>(); connection.Get<ReadmeResponse>(Args.Uri, null).Returns(Task.FromResult(readmeInfo)); connection.GetHtml(Args.Uri, null).Returns(Task.FromResult("<html>README</html>")); var reposEndpoint = new RepositoriesClient(connection); var readme = await reposEndpoint.GetReadme("fake", "repo"); Assert.Equal("README.md", readme.Name); connection.Received().Get<ReadmeResponse>(Arg.Is<Uri>(u => u.ToString() == "repos/fake/repo/readme"), null); connection.DidNotReceive().GetHtml(Arg.Is<Uri>(u => u.ToString() == "https://github.example.com/readme"), null); var htmlReadme = await readme.GetHtmlContent(); Assert.Equal("<html>README</html>", htmlReadme); connection.Received().GetHtml(Arg.Is<Uri>(u => u.ToString() == "https://github.example.com/readme"), null); } } public class TheGetReadmeHtmlMethod { [Fact] public async Task ReturnsReadmeHtml() { var connection = Substitute.For<IApiConnection>(); connection.GetHtml(Args.Uri, null).Returns(Task.FromResult("<html>README</html>")); var reposEndpoint = new RepositoriesClient(connection); var readme = await reposEndpoint.GetReadmeHtml("fake", "repo"); connection.Received().GetHtml(Arg.Is<Uri>(u => u.ToString() == "repos/fake/repo/readme"), null); Assert.Equal("<html>README</html>", readme); } } public class TheGetAllBranchesMethod { [Fact] public void ReturnsBranches() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllBranches("owner", "name"); connection.Received() .GetAll<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/branches")); } [Fact] public void EnsuresArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); Assert.Throws<ArgumentNullException>(() => client.GetAllBranches(null, "repo")); Assert.Throws<ArgumentNullException>(() => client.GetAllBranches("owner", null)); Assert.Throws<ArgumentException>(() => client.GetAllBranches("", "repo")); Assert.Throws<ArgumentException>(() => client.GetAllBranches("owner", "")); } } public class TheGetAllContributorsMethod { [Fact] public void GetsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllContributors("owner", "name"); connection.Received() .GetAll<User>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/contributors"), Arg.Any<IDictionary<string, string>>()); } [Fact] public void EnsuresArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); Assert.Throws<ArgumentNullException>(() => client.GetAllContributors(null, "repo")); Assert.Throws<ArgumentNullException>(() => client.GetAllContributors("owner", null)); Assert.Throws<ArgumentException>(() => client.GetAllContributors("", "repo")); Assert.Throws<ArgumentException>(() => client.GetAllContributors("owner", "")); } } public class TheGetAllLanguagesMethod { [Fact] public void GetsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllLanguages("owner", "name"); connection.Received() .Get<IDictionary<string, long>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/languages"), null); } [Fact] public void EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); Assert.Throws<ArgumentNullException>(() => client.GetAllLanguages(null, "repo")); Assert.Throws<ArgumentNullException>(() => client.GetAllLanguages("owner", null)); Assert.Throws<ArgumentException>(() => client.GetAllLanguages("", "repo")); Assert.Throws<ArgumentException>(() => client.GetAllLanguages("owner", "")); } } public class TheGetAllTeamsMethod { [Fact] public void GetsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllTeams("owner", "name"); connection.Received() .GetAll<Team>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/teams")); } [Fact] public void EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); Assert.Throws<ArgumentNullException>(() => client.GetAllTeams(null, "repo")); Assert.Throws<ArgumentNullException>(() => client.GetAllTeams("owner", null)); Assert.Throws<ArgumentException>(() => client.GetAllTeams("", "repo")); Assert.Throws<ArgumentException>(() => client.GetAllTeams("owner", "")); } } public class TheGetAllTagsMethod { [Fact] public void GetsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllTags("owner", "name"); connection.Received() .GetAll<RepositoryTag>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/tags")); } [Fact] public void EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); Assert.Throws<ArgumentNullException>(() => client.GetAllTags(null, "repo")); Assert.Throws<ArgumentNullException>(() => client.GetAllTags("owner", null)); Assert.Throws<ArgumentException>(() => client.GetAllTags("", "repo")); Assert.Throws<ArgumentException>(() => client.GetAllTags("owner", "")); } } public class TheGetBranchMethod { [Fact] public void GetsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetBranch("owner", "repo", "branch"); connection.Received() .Get<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch"), null); } [Fact] public void EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); Assert.Throws<ArgumentNullException>(() => client.GetBranch(null, "repo", "branch")); Assert.Throws<ArgumentNullException>(() => client.GetBranch("owner", null, "branch")); Assert.Throws<ArgumentNullException>(() => client.GetBranch("owner", "repo", null)); Assert.Throws<ArgumentException>(() => client.GetBranch("", "repo", "branch")); Assert.Throws<ArgumentException>(() => client.GetBranch("owner", "", "branch")); Assert.Throws<ArgumentException>(() => client.GetBranch("owner", "repo", "")); } } public class TheEditMethod { [Fact] public void PatchesCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var update = new RepositoryUpdate(); client.Edit("owner", "repo", update); connection.Received() .Patch<Repository>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo"), Arg.Any<RepositoryUpdate>()); } [Fact] public void EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); var update = new RepositoryUpdate(); Assert.Throws<ArgumentNullException>(() => client.Edit(null, "repo", update)); Assert.Throws<ArgumentNullException>(() => client.Edit("owner", null, update)); Assert.Throws<ArgumentNullException>(() => client.Edit("owner", "repo", null)); Assert.Throws<ArgumentException>(() => client.Edit("", "repo", update)); Assert.Throws<ArgumentException>(() => client.Edit("owner", "", update)); } } public class TheCompareMethod { [Fact] public void EnsureNonNullArguments() { var client = new RepositoryCommitsClient(Substitute.For<IApiConnection>()); Assert.Throws<ArgumentNullException>(() => client.Compare(null, "repo", "base", "head")); Assert.Throws<ArgumentException>(() => client.Compare("", "repo", "base", "head")); Assert.Throws<ArgumentNullException>(() => client.Compare("owner", null, "base", "head")); Assert.Throws<ArgumentException>(() => client.Compare("owner", "", "base", "head")); Assert.Throws<ArgumentNullException>(() => client.Compare("owner", "repo", null, "head")); Assert.Throws<ArgumentException>(() => client.Compare("owner", "repo", "", "head")); Assert.Throws<ArgumentNullException>(() => client.Compare("owner", "repo", "base", null)); Assert.Throws<ArgumentException>(() => client.Compare("owner", "repo", "base", "")); } [Fact] public void GetsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryCommitsClient(connection); client.Compare("owner", "repo", "base", "head"); connection.Received() .Get<CompareResult>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/compare/base...head"), null); } [Fact] public void EncodesUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryCommitsClient(connection); client.Compare("owner", "repo", "base", "shiftkey/my-cool-branch"); connection.Received() .Get<CompareResult>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/compare/base...shiftkey%2Fmy-cool-branch"), null); } } public class TheGetCommitMethod { [Fact] public void EnsureNonNullArguments() { var client = new RepositoryCommitsClient(Substitute.For<IApiConnection>()); Assert.Throws<ArgumentNullException>(() => client.Get(null, "repo", "reference")); Assert.Throws<ArgumentException>(() => client.Get("", "repo", "reference")); Assert.Throws<ArgumentNullException>(() => client.Get("owner", null, "reference")); Assert.Throws<ArgumentException>(() => client.Get("owner", "", "reference")); Assert.Throws<ArgumentNullException>(() => client.Get("owner", "repo", null)); Assert.Throws<ArgumentException>(() => client.Get("owner", "repo", "")); } [Fact] public void GetsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryCommitsClient(connection); client.Get("owner", "name", "reference"); connection.Received() .Get<GitHubCommit>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/commits/reference"), null); } } public class TheGetAllCommitsMethod { [Fact] public void EnsureNonNullArguments() { var client = new RepositoryCommitsClient(Substitute.For<IApiConnection>()); Assert.Throws<ArgumentNullException>(() => client.GetAll(null, "repo")); Assert.Throws<ArgumentException>(() => client.GetAll("", "repo")); Assert.Throws<ArgumentNullException>(() => client.GetAll("owner", null)); Assert.Throws<ArgumentException>(() => client.GetAll("owner", "")); Assert.Throws<ArgumentNullException>(() => client.GetAll("owner", "repo", null)); } [Fact] public void GetsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryCommitsClient(connection); client.GetAll("owner", "name"); connection.Received() .GetAll<GitHubCommit>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/commits"), Arg.Any<Dictionary<string, string>>()); } } } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// A car rental business. /// </summary> public class AutoRental_Core : TypeCore, IAutomotiveBusiness { public AutoRental_Core() { this._TypeId = 26; this._Id = "AutoRental"; this._Schema_Org_Url = "http://schema.org/AutoRental"; string label = ""; GetLabel(out label, "AutoRental", typeof(AutoRental_Core)); this._Label = label; this._Ancestors = new int[]{266,193,155,30}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{30}; this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167}; } /// <summary> /// Physical address of the item. /// </summary> private Address_Core address; public Address_Core Address { get { return address; } set { address = value; SetPropertyInstance(address); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// The larger organization that this local business is a branch of, if any. /// </summary> private BranchOf_Core branchOf; public BranchOf_Core BranchOf { get { return branchOf; } set { branchOf = value; SetPropertyInstance(branchOf); } } /// <summary> /// A contact point for a person or organization. /// </summary> private ContactPoints_Core contactPoints; public ContactPoints_Core ContactPoints { get { return contactPoints; } set { contactPoints = value; SetPropertyInstance(contactPoints); } } /// <summary> /// The basic containment relation between places. /// </summary> private ContainedIn_Core containedIn; public ContainedIn_Core ContainedIn { get { return containedIn; } set { containedIn = value; SetPropertyInstance(containedIn); } } /// <summary> /// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>). /// </summary> private CurrenciesAccepted_Core currenciesAccepted; public CurrenciesAccepted_Core CurrenciesAccepted { get { return currenciesAccepted; } set { currenciesAccepted = value; SetPropertyInstance(currenciesAccepted); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// Email address. /// </summary> private Email_Core email; public Email_Core Email { get { return email; } set { email = value; SetPropertyInstance(email); } } /// <summary> /// People working for this organization. /// </summary> private Employees_Core employees; public Employees_Core Employees { get { return employees; } set { employees = value; SetPropertyInstance(employees); } } /// <summary> /// Upcoming or past events associated with this place or organization. /// </summary> private Events_Core events; public Events_Core Events { get { return events; } set { events = value; SetPropertyInstance(events); } } /// <summary> /// The fax number. /// </summary> private FaxNumber_Core faxNumber; public FaxNumber_Core FaxNumber { get { return faxNumber; } set { faxNumber = value; SetPropertyInstance(faxNumber); } } /// <summary> /// A person who founded this organization. /// </summary> private Founders_Core founders; public Founders_Core Founders { get { return founders; } set { founders = value; SetPropertyInstance(founders); } } /// <summary> /// The date that this organization was founded. /// </summary> private FoundingDate_Core foundingDate; public FoundingDate_Core FoundingDate { get { return foundingDate; } set { foundingDate = value; SetPropertyInstance(foundingDate); } } /// <summary> /// The geo coordinates of the place. /// </summary> private Geo_Core geo; public Geo_Core Geo { get { return geo; } set { geo = value; SetPropertyInstance(geo); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// The location of the event or organization. /// </summary> private Location_Core location; public Location_Core Location { get { return location; } set { location = value; SetPropertyInstance(location); } } /// <summary> /// A URL to a map of the place. /// </summary> private Maps_Core maps; public Maps_Core Maps { get { return maps; } set { maps = value; SetPropertyInstance(maps); } } /// <summary> /// A member of this organization. /// </summary> private Members_Core members; public Members_Core Members { get { return members; } set { members = value; SetPropertyInstance(members); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code>&lt;time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\&gt;Tuesdays and Thursdays 4-8pm&lt;/time&gt;</code>. <br/>- If a business is open 7 days a week, then it can be specified as <code>&lt;time itemprop=\openingHours\ datetime=\Mo-Su\&gt;Monday through Sunday, all day&lt;/time&gt;</code>. /// </summary> private OpeningHours_Core openingHours; public OpeningHours_Core OpeningHours { get { return openingHours; } set { openingHours = value; SetPropertyInstance(openingHours); } } /// <summary> /// Cash, credit card, etc. /// </summary> private PaymentAccepted_Core paymentAccepted; public PaymentAccepted_Core PaymentAccepted { get { return paymentAccepted; } set { paymentAccepted = value; SetPropertyInstance(paymentAccepted); } } /// <summary> /// Photographs of this place. /// </summary> private Photos_Core photos; public Photos_Core Photos { get { return photos; } set { photos = value; SetPropertyInstance(photos); } } /// <summary> /// The price range of the business, for example <code>$$$</code>. /// </summary> private PriceRange_Core priceRange; public PriceRange_Core PriceRange { get { return priceRange; } set { priceRange = value; SetPropertyInstance(priceRange); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The telephone number. /// </summary> private Telephone_Core telephone; public Telephone_Core Telephone { get { return telephone; } set { telephone = value; SetPropertyInstance(telephone); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.UnitTests.TypeInferrer; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.TypeInferrer { public partial class TypeInferrerTests : TypeInferrerTestBase<CSharpTestWorkspaceFixture> { public TypeInferrerTests(CSharpTestWorkspaceFixture workspaceFixture) : base(workspaceFixture) { } protected override async Task TestWorkerAsync(Document document, TextSpan textSpan, string expectedType, bool useNodeStartPosition) { var root = await document.GetSyntaxRootAsync(); var node = FindExpressionSyntaxFromSpan(root, textSpan); var typeInference = document.GetLanguageService<ITypeInferenceService>(); var inferredType = useNodeStartPosition ? typeInference.InferType(await document.GetSemanticModelForSpanAsync(new TextSpan(node?.SpanStart ?? textSpan.Start, 0), CancellationToken.None), node?.SpanStart ?? textSpan.Start, objectAsDefault: true, cancellationToken: CancellationToken.None) : typeInference.InferType(await document.GetSemanticModelForSpanAsync(node?.Span ?? textSpan, CancellationToken.None), node, objectAsDefault: true, cancellationToken: CancellationToken.None); var typeSyntax = inferredType.GenerateTypeSyntax(); Assert.Equal(expectedType, typeSyntax.ToString()); } private async Task TestInClassAsync(string text, string expectedType) { text = @"class C { $ }".Replace("$", text); await TestAsync(text, expectedType); } private async Task TestInMethodAsync(string text, string expectedType, bool testNode = true, bool testPosition = true) { text = @"class C { void M() { $ } }".Replace("$", text); await TestAsync(text, expectedType, testNode: testNode, testPosition: testPosition); } private ExpressionSyntax FindExpressionSyntaxFromSpan(SyntaxNode root, TextSpan textSpan) { var token = root.FindToken(textSpan.Start); var currentNode = token.Parent; while (currentNode != null) { ExpressionSyntax result = currentNode as ExpressionSyntax; if (result != null && result.Span == textSpan) { return result; } currentNode = currentNode.Parent; } return null; } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConditional1() { // We do not support position inference here as we're before the ? and we only look // backwards to infer a type here. await TestInMethodAsync("var q = [|Foo()|] ? 1 : 2;", "global::System.Boolean", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConditional2() { await TestInMethodAsync("var q = a ? [|Foo()|] : 2;", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConditional3() { await TestInMethodAsync(@"var q = a ? """" : [|Foo()|];", "global::System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestVariableDeclarator1() { await TestInMethodAsync("int q = [|Foo()|];", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestVariableDeclarator2() { await TestInMethodAsync("var q = [|Foo()|];", "global::System.Object"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCoalesce1() { await TestInMethodAsync("var q = [|Foo()|] ?? 1;", "global::System.Int32?", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCoalesce2() { await TestInMethodAsync(@"bool? b; var q = b ?? [|Foo()|];", "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCoalesce3() { await TestInMethodAsync(@"string s; var q = s ?? [|Foo()|];", "global::System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCoalesce4() { await TestInMethodAsync("var q = [|Foo()|] ?? string.Empty;", "global::System.String", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestBinaryExpression1() { await TestInMethodAsync(@"string s; var q = s + [|Foo()|];", "global::System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestBinaryExpression2() { await TestInMethodAsync(@"var s; var q = s || [|Foo()|];", "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestBinaryOperator1() { await TestInMethodAsync(@"var q = x << [|Foo()|];", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestBinaryOperator2() { await TestInMethodAsync(@"var q = x >> [|Foo()|];", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestAssignmentOperator3() { await TestInMethodAsync(@"var q <<= [|Foo()|];", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestAssignmentOperator4() { await TestInMethodAsync(@"var q >>= [|Foo()|];", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestOverloadedConditionalLogicalOperatorsInferBool() { await TestAsync(@"using System; class C { public static C operator &(C c, C d) { return null; } public static bool operator true(C c) { return true; } public static bool operator false(C c) { return false; } static void Main(string[] args) { var c = new C() && [|Foo()|]; } }", "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestConditionalLogicalOrOperatorAlwaysInfersBool() { var text = @"using System; class C { static void Main(string[] args) { var x = a || [|7|]; } }"; await TestAsync(text, "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestConditionalLogicalAndOperatorAlwaysInfersBool() { var text = @"using System; class C { static void Main(string[] args) { var x = a && [|7|]; } }"; await TestAsync(text, "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalOrOperatorInference1() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] | true; } }"; await TestAsync(text, "global::System.Boolean", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalOrOperatorInference2() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] | b | c || d; } }"; await TestAsync(text, "global::System.Boolean", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalOrOperatorInference3() { var text = @"using System; class C { static void Main(string[] args) { var x = a | b | [|c|] || d; } }"; await TestAsync(text, "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalOrOperatorInference4() { var text = @"using System; class C { static void Main(string[] args) { var x = Foo([|a|] | b); } static object Foo(Program p) { return p; } }"; await TestAsync(text, "Program", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalOrOperatorInference5() { var text = @"using System; class C { static void Main(string[] args) { var x = Foo([|a|] | b); } static object Foo(bool p) { return p; } }"; await TestAsync(text, "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalOrOperatorInference6() { var text = @"using System; class C { static void Main(string[] args) { if (([|x|] | y) != 0) {} } }"; await TestAsync(text, "global::System.Int32", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalOrOperatorInference7() { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] | y) {} } }"; await TestAsync(text, "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalAndOperatorInference1() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] & true; } }"; await TestAsync(text, "global::System.Boolean", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalAndOperatorInference2() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] & b & c && d; } }"; await TestAsync(text, "global::System.Boolean", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalAndOperatorInference3() { var text = @"using System; class C { static void Main(string[] args) { var x = a & b & [|c|] && d; } }"; await TestAsync(text, "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalAndOperatorInference4() { var text = @"using System; class C { static void Main(string[] args) { var x = Foo([|a|] & b); } static object Foo(Program p) { return p; } }"; await TestAsync(text, "Program", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalAndOperatorInference5() { var text = @"using System; class C { static void Main(string[] args) { var x = Foo([|a|] & b); } static object Foo(bool p) { return p; } }"; await TestAsync(text, "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalAndOperatorInference6() { var text = @"using System; class C { static void Main(string[] args) { if (([|x|] & y) != 0) {} } }"; await TestAsync(text, "global::System.Int32", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalAndOperatorInference7() { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] & y) {} } }"; await TestAsync(text, "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalXorOperatorInference1() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] ^ true; } }"; await TestAsync(text, "global::System.Boolean", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalXorOperatorInference2() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] ^ b ^ c && d; } }"; await TestAsync(text, "global::System.Boolean", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalXorOperatorInference3() { var text = @"using System; class C { static void Main(string[] args) { var x = a ^ b ^ [|c|] && d; } }"; await TestAsync(text, "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalXorOperatorInference4() { var text = @"using System; class C { static void Main(string[] args) { var x = Foo([|a|] ^ b); } static object Foo(Program p) { return p; } }"; await TestAsync(text, "Program", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalXorOperatorInference5() { var text = @"using System; class C { static void Main(string[] args) { var x = Foo([|a|] ^ b); } static object Foo(bool p) { return p; } }"; await TestAsync(text, "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalXorOperatorInference6() { var text = @"using System; class C { static void Main(string[] args) { if (([|x|] ^ y) != 0) {} } }"; await TestAsync(text, "global::System.Int32", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalXorOperatorInference7() { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] ^ y) {} } }"; await TestAsync(text, "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalOrEqualsOperatorInference1() { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] |= y) {} } }"; await TestAsync(text, "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalOrEqualsOperatorInference2() { var text = @"using System; class C { static void Main(string[] args) { int z = [|x|] |= y; } }"; await TestAsync(text, "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalAndEqualsOperatorInference1() { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] &= y) {} } }"; await TestAsync(text, "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalAndEqualsOperatorInference2() { var text = @"using System; class C { static void Main(string[] args) { int z = [|x|] &= y; } }"; await TestAsync(text, "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalXorEqualsOperatorInference1() { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] ^= y) {} } }"; await TestAsync(text, "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")] public async Task TestLogicalXorEqualsOperatorInference2() { var text = @"using System; class C { static void Main(string[] args) { int z = [|x|] ^= y; } }"; await TestAsync(text, "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturn1() { await TestInClassAsync(@"int M() { return [|Foo()|]; }", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturn2() { await TestInMethodAsync("return [|Foo()|];", "void"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturn3() { await TestInClassAsync(@"int Property { get { return [|Foo()|]; } }", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(827897, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827897")] public async Task TestYieldReturn() { var markup = @"using System.Collections.Generic; class Program { IEnumerable<int> M() { yield return [|abc|] } }"; await TestAsync(markup, "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestReturnInLambda() { await TestInMethodAsync("System.Func<string,int> f = s => { return [|Foo()|]; };", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestLambda() { await TestInMethodAsync("System.Func<string, int> f = s => [|Foo()|];", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestThrow() { await TestInMethodAsync("throw [|Foo()|];", "global::System.Exception"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCatch() { await TestInMethodAsync("try { } catch ([|Foo|] ex) { }", "global::System.Exception"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestIf() { await TestInMethodAsync(@"if ([|Foo()|]) { }", "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestWhile() { await TestInMethodAsync(@"while ([|Foo()|]) { }", "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestDo() { await TestInMethodAsync(@"do { } while ([|Foo()|])", "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestFor1() { await TestInMethodAsync(@"for (int i = 0; [|Foo()|]; i++) { }", "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestFor2() { await TestInMethodAsync(@"for (string i = [|Foo()|]; ; ) { }", "global::System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestFor3() { await TestInMethodAsync(@"for (var i = [|Foo()|]; ; ) { }", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestUsing1() { await TestInMethodAsync(@"using ([|Foo()|]) { }", "global::System.IDisposable"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestUsing2() { await TestInMethodAsync(@"using (int i = [|Foo()|]) { }", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestUsing3() { await TestInMethodAsync(@"using (var v = [|Foo()|]) { }", "global::System.IDisposable"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestForEach() { await TestInMethodAsync(@"foreach (int v in [|Foo()|]) { }", "global::System.Collections.Generic.IEnumerable<global::System.Int32>"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestPrefixExpression1() { await TestInMethodAsync(@"var q = +[|Foo()|];", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestPrefixExpression2() { await TestInMethodAsync(@"var q = -[|Foo()|];", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestPrefixExpression3() { await TestInMethodAsync(@"var q = ~[|Foo()|];", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestPrefixExpression4() { await TestInMethodAsync(@"var q = ![|Foo()|];", "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestPrefixExpression5() { await TestInMethodAsync(@"var q = System.DayOfWeek.Monday & ~[|Foo()|];", "global::System.DayOfWeek"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayRankSpecifier() { await TestInMethodAsync(@"var q = new string[[|Foo()|]];", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestSwitch1() { await TestInMethodAsync(@"switch ([|Foo()|]) { }", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestSwitch2() { await TestInMethodAsync(@"switch ([|Foo()|]) { default: }", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestSwitch3() { await TestInMethodAsync(@"switch ([|Foo()|]) { case ""a"": }", "global::System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestMethodCall1() { await TestInMethodAsync(@"Bar([|Foo()|]);", "global::System.Object"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestMethodCall2() { await TestInClassAsync(@"void M() { Bar([|Foo()|]); } void Bar(int i);", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestMethodCall3() { await TestInClassAsync(@"void M() { Bar([|Foo()|]); } void Bar();", "global::System.Object"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestMethodCall4() { await TestInClassAsync(@"void M() { Bar([|Foo()|]); } void Bar(int i, string s);", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestMethodCall5() { await TestInClassAsync(@"void M() { Bar(s: [|Foo()|]); } void Bar(int i, string s);", "global::System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConstructorCall1() { await TestInMethodAsync(@"new C([|Foo()|]);", "global::System.Object"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConstructorCall2() { await TestInClassAsync(@"void M() { new C([|Foo()|]); } C(int i) { }", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConstructorCall3() { await TestInClassAsync(@"void M() { new C([|Foo()|]); } C() { }", "global::System.Object"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConstructorCall4() { await TestInClassAsync(@"void M() { new C([|Foo()|]); } C(int i, string s) { }", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestConstructorCall5() { await TestInClassAsync(@"void M() { new C(s: [|Foo()|]); } C(int i, string s) { }", "global::System.String"); } [WorkItem(858112, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858112")] [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestThisConstructorInitializer1() { await TestAsync(@"class MyClass { public MyClass(int x) : this([|test|]) { } }", "global::System.Int32"); } [WorkItem(858112, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858112")] [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestThisConstructorInitializer2() { await TestAsync(@"class MyClass { public MyClass(int x, string y) : this(5, [|test|]) { } }", "global::System.String"); } [WorkItem(858112, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858112")] [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestBaseConstructorInitializer() { await TestAsync(@"class B { public B(int x) { } } class D : B { public D() : base([|test|]) { } }", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestIndexAccess1() { await TestInMethodAsync(@"string[] i; i[[|Foo()|]];", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestIndexerCall1() { await TestInMethodAsync(@"this[[|Foo()|]];", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestIndexerCall2() { // Update this when binding of indexers is working. await TestInClassAsync(@"void M() { this[[|Foo()|]]; } int this [int i] { get; }", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestIndexerCall3() { // Update this when binding of indexers is working. await TestInClassAsync(@"void M() { this[[|Foo()|]]; } int this [int i, string s] { get; }", "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestIndexerCall5() { await TestInClassAsync(@"void M() { this[s: [|Foo()|]]; } int this [int i, string s] { get; }", "global::System.String"); } [Fact] public async Task TestArrayInitializerInImplicitArrayCreationSimple() { var text = @"using System.Collections.Generic; class C { void M() { var a = new[] { 1, [|2|] }; } }"; await TestAsync(text, "global::System.Int32"); } [Fact] public async Task TestArrayInitializerInImplicitArrayCreation1() { var text = @"using System.Collections.Generic; class C { void M() { var a = new[] { Bar(), [|Foo()|] }; } int Bar() { return 1; } int Foo() { return 2; } }"; await TestAsync(text, "global::System.Int32"); } [Fact] public async Task TestArrayInitializerInImplicitArrayCreation2() { var text = @"using System.Collections.Generic; class C { void M() { var a = new[] { Bar(), [|Foo()|] }; } int Bar() { return 1; } }"; await TestAsync(text, "global::System.Int32"); } [Fact] public async Task TestArrayInitializerInImplicitArrayCreation3() { var text = @"using System.Collections.Generic; class C { void M() { var a = new[] { Bar(), [|Foo()|] }; } }"; await TestAsync(text, "global::System.Object"); } [Fact] public async Task TestArrayInitializerInEqualsValueClauseSimple() { var text = @"using System.Collections.Generic; class C { void M() { int[] a = { 1, [|2|] }; } }"; await TestAsync(text, "global::System.Int32"); } [Fact] public async Task TestArrayInitializerInEqualsValueClause() { var text = @"using System.Collections.Generic; class C { void M() { int[] a = { Bar(), [|Foo()|] }; } int Bar() { return 1; } }"; await TestAsync(text, "global::System.Int32"); } [Fact] [WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCollectionInitializer1() { var text = @"using System.Collections.Generic; class C { void M() { new List<int>() { [|Foo()|] }; } }"; await TestAsync(text, "global::System.Int32"); } [Fact] [WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCollectionInitializer2() { var text = @" using System.Collections.Generic; class C { void M() { new Dictionary<int,string>() { { [|Foo()|], """" } }; } }"; await TestAsync(text, "global::System.Int32"); } [Fact] [WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCollectionInitializer3() { var text = @" using System.Collections.Generic; class C { void M() { new Dictionary<int,string>() { { 0, [|Foo()|] } }; } }"; await TestAsync(text, "global::System.String"); } [Fact] [WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCustomCollectionInitializerAddMethod1() { var text = @"class C : System.Collections.IEnumerable { void M() { var x = new C() { [|a|] }; } void Add(int i) { } void Add(string s, bool b) { } public System.Collections.IEnumerator GetEnumerator() { throw new System.NotImplementedException(); } }"; await TestAsync(text, "global::System.Int32", testPosition: false); } [Fact] [WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCustomCollectionInitializerAddMethod2() { var text = @"class C : System.Collections.IEnumerable { void M() { var x = new C() { { ""test"", [|b|] } }; } void Add(int i) { } void Add(string s, bool b) { } public System.Collections.IEnumerator GetEnumerator() { throw new System.NotImplementedException(); } }"; await TestAsync(text, "global::System.Boolean"); } [Fact] [WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestCustomCollectionInitializerAddMethod3() { var text = @"class C : System.Collections.IEnumerable { void M() { var x = new C() { { [|s|], true } }; } void Add(int i) { } void Add(string s, bool b) { } public System.Collections.IEnumerator GetEnumerator() { throw new System.NotImplementedException(); } }"; await TestAsync(text, "global::System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInference1() { var text = @" class A { void Foo() { A[] x = new [|C|][] { }; } }"; await TestAsync(text, "global::A", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInference1_Position() { var text = @" class A { void Foo() { A[] x = new [|C|][] { }; } }"; await TestAsync(text, "global::A[]", testNode: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInference2() { var text = @" class A { void Foo() { A[][] x = new [|C|][][] { }; } }"; await TestAsync(text, "global::A", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInference2_Position() { var text = @" class A { void Foo() { A[][] x = new [|C|][][] { }; } }"; await TestAsync(text, "global::A[][]", testNode: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInference3() { var text = @" class A { void Foo() { A[][] x = new [|C|][] { }; } }"; await TestAsync(text, "global::A[]", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInference3_Position() { var text = @" class A { void Foo() { A[][] x = new [|C|][] { }; } }"; await TestAsync(text, "global::A[][]", testNode: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestArrayInference4() { var text = @" using System; class A { void Foo() { Func<int, int>[] x = new Func<int, int>[] { [|Bar()|] }; } }"; await TestAsync(text, "global::System.Func<global::System.Int32,global::System.Int32>"); } [WorkItem(538993, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538993")] [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestInsideLambda2() { var text = @"using System; class C { void M() { Func<int,int> f = i => [|here|] } }"; await TestAsync(text, "global::System.Int32"); } [WorkItem(539813, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539813")] [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestPointer1() { var text = @"class C { void M(int* i) { var q = i[[|Foo()|]]; } }"; await TestAsync(text, "global::System.Int32"); } [WorkItem(539813, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539813")] [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestDynamic1() { var text = @"class C { void M(dynamic i) { var q = i[[|Foo()|]]; } }"; await TestAsync(text, "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestChecked1() { var text = @"class C { void M() { string q = checked([|Foo()|]); } }"; await TestAsync(text, "global::System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(553584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553584")] public async Task TestAwaitTaskOfT() { var text = @"using System.Threading.Tasks; class C { void M() { int x = await [|Foo()|]; } }"; await TestAsync(text, "global::System.Threading.Tasks.Task<global::System.Int32>"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(553584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553584")] public async Task TestAwaitTaskOfTaskOfT() { var text = @"using System.Threading.Tasks; class C { void M() { Task<int> x = await [|Foo()|]; } }"; await TestAsync(text, "global::System.Threading.Tasks.Task<global::System.Threading.Tasks.Task<global::System.Int32>>"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(553584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553584")] public async Task TestAwaitTask() { var text = @"using System.Threading.Tasks; class C { void M() { await [|Foo()|]; } }"; await TestAsync(text, "global::System.Threading.Tasks.Task"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617622, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617622")] public async Task TestLockStatement() { var text = @"class C { void M() { lock([|Foo()|]) { } } }"; await TestAsync(text, "global::System.Object"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617622, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617622")] public async Task TestAwaitExpressionInLockStatement() { var text = @"class C { async void M() { lock(await [|Foo()|]) { } } }"; await TestAsync(text, "global::System.Threading.Tasks.Task<global::System.Object>"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(827897, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827897")] public async Task TestReturnFromAsyncTaskOfT() { var markup = @"using System.Threading.Tasks; class Program { async Task<int> M() { await Task.Delay(1); return [|ab|] } }"; await TestAsync(markup, "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(853840, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/853840")] public async Task TestAttributeArguments1() { var markup = @"[A([|dd|], ee, Y = ff)] class AAttribute : System.Attribute { public int X; public string Y; public AAttribute(System.DayOfWeek a, double b) { } }"; await TestAsync(markup, "global::System.DayOfWeek"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(853840, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/853840")] public async Task TestAttributeArguments2() { var markup = @"[A(dd, [|ee|], Y = ff)] class AAttribute : System.Attribute { public int X; public string Y; public AAttribute(System.DayOfWeek a, double b) { } }"; await TestAsync(markup, "global::System.Double"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(853840, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/853840")] public async Task TestAttributeArguments3() { var markup = @"[A(dd, ee, Y = [|ff|])] class AAttribute : System.Attribute { public int X; public string Y; public AAttribute(System.DayOfWeek a, double b) { } }"; await TestAsync(markup, "global::System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(757111, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/757111")] public async Task TestReturnStatementWithinDelegateWithinAMethodCall() { var text = @"using System; class Program { delegate string A(int i); static void Main(string[] args) { B(delegate(int i) { return [|M()|]; }); } private static void B(A a) { } }"; await TestAsync(text, "global::System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(994388, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994388")] public async Task TestCatchFilterClause() { var text = @" try { } catch (Exception) if ([|M()|]) }"; await TestInMethodAsync(text, "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(994388, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994388")] public async Task TestCatchFilterClause1() { var text = @" try { } catch (Exception) if ([|M|]) }"; await TestInMethodAsync(text, "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(994388, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994388")] public async Task TestCatchFilterClause2() { var text = @" try { } catch (Exception) if ([|M|].N) }"; await TestInMethodAsync(text, "global::System.Object", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(643, "https://github.com/dotnet/roslyn/issues/643")] public async Task TestAwaitExpressionWithChainingMethod() { var text = @"using System; using System.Threading.Tasks; class C { static async void T() { bool x = await [|M()|].ConfigureAwait(false); } }"; await TestAsync(text, "global::System.Threading.Tasks.Task<global::System.Boolean>", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(643, "https://github.com/dotnet/roslyn/issues/643")] public async Task TestAwaitExpressionWithChainingMethod2() { var text = @"using System; using System.Threading.Tasks; class C { static async void T() { bool x = await [|M|].ContinueWith(a => { return true; }).ContinueWith(a => { return false; }); } }"; await TestAsync(text, "global::System.Threading.Tasks.Task<global::System.Object>", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4233, "https://github.com/dotnet/roslyn/issues/4233")] public async Task TestAwaitExpressionWithGenericMethod1() { var text = @"using System.Threading.Tasks; public class C { private async void M() { bool merged = await X([|Test()|]); } private async Task<T> X<T>(T t) { return t; } }"; await TestAsync(text, "global::System.Boolean", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4233, "https://github.com/dotnet/roslyn/issues/4233")] public async Task TestAwaitExpressionWithGenericMethod2() { var text = @"using System.Threading.Tasks; public class C { private async void M() { bool merged = await Task.Run(() => [|Test()|]);; } private async Task<T> X<T>(T t) { return t; } }"; await TestAsync(text, "global::System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4483, "https://github.com/dotnet/roslyn/issues/4483")] public async Task TestNullCoalescingOperator1() { var text = @"class C { void M() { object z = [|a|]?? null; } }"; await TestAsync(text, "global::System.Object"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4483, "https://github.com/dotnet/roslyn/issues/4483")] public async Task TestNullCoalescingOperator2() { var text = @"class C { void M() { object z = [|a|] ?? b ?? c; } }"; await TestAsync(text, "global::System.Object"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4483, "https://github.com/dotnet/roslyn/issues/4483")] public async Task TestNullCoalescingOperator3() { var text = @"class C { void M() { object z = a ?? [|b|] ?? c; } }"; await TestAsync(text, "global::System.Object"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(5126, "https://github.com/dotnet/roslyn/issues/5126")] public async Task TestSelectLambda() { var text = @"using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<string> args) { args = args.Select(a =>[||]) } }"; await TestAsync(text, "global::System.Object", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(5126, "https://github.com/dotnet/roslyn/issues/5126")] public async Task TestSelectLambda2() { var text = @"using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<string> args) { args = args.Select(a =>[|b|]) } }"; await TestAsync(text, "global::System.String", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(1903, "https://github.com/dotnet/roslyn/issues/1903")] public async Task TestSelectLambda3() { var text = @"using System.Collections.Generic; using System.Linq; class A { } class B { } class C { IEnumerable<B> GetB(IEnumerable<A> a) { return a.Select(i => [|Foo(i)|]); } }"; await TestAsync(text, "global::B"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4486, "https://github.com/dotnet/roslyn/issues/4486")] public async Task TestReturnInAsyncLambda1() { var text = @"using System; using System.IO; using System.Threading.Tasks; public class C { public async void M() { Func<Task<int>> t2 = async () => { return [|a|]; }; } }"; await TestAsync(text, "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4486, "https://github.com/dotnet/roslyn/issues/4486")] public async Task TestReturnInAsyncLambda2() { var text = @"using System; using System.IO; using System.Threading.Tasks; public class C { public async void M() { Func<Task<int>> t2 = async delegate () { return [|a|]; }; } }"; await TestAsync(text, "global::System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(6765, "https://github.com/dotnet/roslyn/issues/6765")] public async Task TestDefaultStatement1() { var text = @"class C { static void Main(string[] args) { System.ConsoleModifiers c = default([||]) } }"; await TestAsync(text, "global::System.ConsoleModifiers", testNode: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(6765, "https://github.com/dotnet/roslyn/issues/6765")] public async Task TestDefaultStatement2() { var text = @"class C { static void Foo(System.ConsoleModifiers arg) { Foo(default([||]) } }"; await TestAsync(text, "global::System.ConsoleModifiers", testNode: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestWhereCall() { var text = @" using System.Collections.Generic; class C { void Foo() { [|ints|].Where(i => i > 10); } }"; await TestAsync(text, "global::System.Collections.Generic.IEnumerable<global::System.Int32>", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public async Task TestWhereCall2() { var text = @" using System.Collections.Generic; class C { void Foo() { [|ints|].Where(i => null); } }"; await TestAsync(text, "global::System.Collections.Generic.IEnumerable<global::System.Object>", testPosition: false); } } }
namespace android.net { [global::MonoJavaBridge.JavaClass(typeof(global::android.net.Uri_))] public abstract partial class Uri : java.lang.Object, android.os.Parcelable, java.lang.Comparable { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static Uri() { InitJNI(); } protected Uri(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaClass()] public sealed partial class Builder : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static Builder() { InitJNI(); } internal Builder(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _toString5266; public sealed override global::java.lang.String toString() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.Uri.Builder._toString5266)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.Uri.Builder.staticClass, global::android.net.Uri.Builder._toString5266)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _path5267; public global::android.net.Uri.Builder path(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.Uri.Builder._path5267, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.net.Uri.Builder; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.Uri.Builder.staticClass, global::android.net.Uri.Builder._path5267, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.net.Uri.Builder; } internal static global::MonoJavaBridge.MethodId _query5268; public global::android.net.Uri.Builder query(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.Uri.Builder._query5268, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.net.Uri.Builder; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.Uri.Builder.staticClass, global::android.net.Uri.Builder._query5268, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.net.Uri.Builder; } internal static global::MonoJavaBridge.MethodId _authority5269; public global::android.net.Uri.Builder authority(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.Uri.Builder._authority5269, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.net.Uri.Builder; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.Uri.Builder.staticClass, global::android.net.Uri.Builder._authority5269, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.net.Uri.Builder; } internal static global::MonoJavaBridge.MethodId _scheme5270; public global::android.net.Uri.Builder scheme(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.Uri.Builder._scheme5270, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.net.Uri.Builder; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.Uri.Builder.staticClass, global::android.net.Uri.Builder._scheme5270, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.net.Uri.Builder; } internal static global::MonoJavaBridge.MethodId _fragment5271; public global::android.net.Uri.Builder fragment(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.Uri.Builder._fragment5271, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.net.Uri.Builder; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.Uri.Builder.staticClass, global::android.net.Uri.Builder._fragment5271, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.net.Uri.Builder; } internal static global::MonoJavaBridge.MethodId _build5272; public global::android.net.Uri build() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.Uri.Builder._build5272)) as android.net.Uri; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.Uri.Builder.staticClass, global::android.net.Uri.Builder._build5272)) as android.net.Uri; } internal static global::MonoJavaBridge.MethodId _opaquePart5273; public global::android.net.Uri.Builder opaquePart(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.Uri.Builder._opaquePart5273, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.net.Uri.Builder; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.Uri.Builder.staticClass, global::android.net.Uri.Builder._opaquePart5273, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.net.Uri.Builder; } internal static global::MonoJavaBridge.MethodId _encodedOpaquePart5274; public global::android.net.Uri.Builder encodedOpaquePart(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.Uri.Builder._encodedOpaquePart5274, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.net.Uri.Builder; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.Uri.Builder.staticClass, global::android.net.Uri.Builder._encodedOpaquePart5274, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.net.Uri.Builder; } internal static global::MonoJavaBridge.MethodId _encodedAuthority5275; public global::android.net.Uri.Builder encodedAuthority(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.Uri.Builder._encodedAuthority5275, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.net.Uri.Builder; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.Uri.Builder.staticClass, global::android.net.Uri.Builder._encodedAuthority5275, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.net.Uri.Builder; } internal static global::MonoJavaBridge.MethodId _encodedPath5276; public global::android.net.Uri.Builder encodedPath(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.Uri.Builder._encodedPath5276, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.net.Uri.Builder; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.Uri.Builder.staticClass, global::android.net.Uri.Builder._encodedPath5276, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.net.Uri.Builder; } internal static global::MonoJavaBridge.MethodId _appendPath5277; public global::android.net.Uri.Builder appendPath(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.Uri.Builder._appendPath5277, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.net.Uri.Builder; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.Uri.Builder.staticClass, global::android.net.Uri.Builder._appendPath5277, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.net.Uri.Builder; } internal static global::MonoJavaBridge.MethodId _appendEncodedPath5278; public global::android.net.Uri.Builder appendEncodedPath(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.Uri.Builder._appendEncodedPath5278, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.net.Uri.Builder; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.Uri.Builder.staticClass, global::android.net.Uri.Builder._appendEncodedPath5278, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.net.Uri.Builder; } internal static global::MonoJavaBridge.MethodId _encodedQuery5279; public global::android.net.Uri.Builder encodedQuery(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.Uri.Builder._encodedQuery5279, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.net.Uri.Builder; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.Uri.Builder.staticClass, global::android.net.Uri.Builder._encodedQuery5279, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.net.Uri.Builder; } internal static global::MonoJavaBridge.MethodId _encodedFragment5280; public global::android.net.Uri.Builder encodedFragment(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.Uri.Builder._encodedFragment5280, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.net.Uri.Builder; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.Uri.Builder.staticClass, global::android.net.Uri.Builder._encodedFragment5280, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.net.Uri.Builder; } internal static global::MonoJavaBridge.MethodId _appendQueryParameter5281; public global::android.net.Uri.Builder appendQueryParameter(java.lang.String arg0, java.lang.String arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.Uri.Builder._appendQueryParameter5281, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.net.Uri.Builder; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.Uri.Builder.staticClass, global::android.net.Uri.Builder._appendQueryParameter5281, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.net.Uri.Builder; } internal static global::MonoJavaBridge.MethodId _Builder5282; public Builder() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.net.Uri.Builder.staticClass, global::android.net.Uri.Builder._Builder5282); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.net.Uri.Builder.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/net/Uri$Builder")); global::android.net.Uri.Builder._toString5266 = @__env.GetMethodIDNoThrow(global::android.net.Uri.Builder.staticClass, "toString", "()Ljava/lang/String;"); global::android.net.Uri.Builder._path5267 = @__env.GetMethodIDNoThrow(global::android.net.Uri.Builder.staticClass, "path", "(Ljava/lang/String;)Landroid/net/Uri$Builder;"); global::android.net.Uri.Builder._query5268 = @__env.GetMethodIDNoThrow(global::android.net.Uri.Builder.staticClass, "query", "(Ljava/lang/String;)Landroid/net/Uri$Builder;"); global::android.net.Uri.Builder._authority5269 = @__env.GetMethodIDNoThrow(global::android.net.Uri.Builder.staticClass, "authority", "(Ljava/lang/String;)Landroid/net/Uri$Builder;"); global::android.net.Uri.Builder._scheme5270 = @__env.GetMethodIDNoThrow(global::android.net.Uri.Builder.staticClass, "scheme", "(Ljava/lang/String;)Landroid/net/Uri$Builder;"); global::android.net.Uri.Builder._fragment5271 = @__env.GetMethodIDNoThrow(global::android.net.Uri.Builder.staticClass, "fragment", "(Ljava/lang/String;)Landroid/net/Uri$Builder;"); global::android.net.Uri.Builder._build5272 = @__env.GetMethodIDNoThrow(global::android.net.Uri.Builder.staticClass, "build", "()Landroid/net/Uri;"); global::android.net.Uri.Builder._opaquePart5273 = @__env.GetMethodIDNoThrow(global::android.net.Uri.Builder.staticClass, "opaquePart", "(Ljava/lang/String;)Landroid/net/Uri$Builder;"); global::android.net.Uri.Builder._encodedOpaquePart5274 = @__env.GetMethodIDNoThrow(global::android.net.Uri.Builder.staticClass, "encodedOpaquePart", "(Ljava/lang/String;)Landroid/net/Uri$Builder;"); global::android.net.Uri.Builder._encodedAuthority5275 = @__env.GetMethodIDNoThrow(global::android.net.Uri.Builder.staticClass, "encodedAuthority", "(Ljava/lang/String;)Landroid/net/Uri$Builder;"); global::android.net.Uri.Builder._encodedPath5276 = @__env.GetMethodIDNoThrow(global::android.net.Uri.Builder.staticClass, "encodedPath", "(Ljava/lang/String;)Landroid/net/Uri$Builder;"); global::android.net.Uri.Builder._appendPath5277 = @__env.GetMethodIDNoThrow(global::android.net.Uri.Builder.staticClass, "appendPath", "(Ljava/lang/String;)Landroid/net/Uri$Builder;"); global::android.net.Uri.Builder._appendEncodedPath5278 = @__env.GetMethodIDNoThrow(global::android.net.Uri.Builder.staticClass, "appendEncodedPath", "(Ljava/lang/String;)Landroid/net/Uri$Builder;"); global::android.net.Uri.Builder._encodedQuery5279 = @__env.GetMethodIDNoThrow(global::android.net.Uri.Builder.staticClass, "encodedQuery", "(Ljava/lang/String;)Landroid/net/Uri$Builder;"); global::android.net.Uri.Builder._encodedFragment5280 = @__env.GetMethodIDNoThrow(global::android.net.Uri.Builder.staticClass, "encodedFragment", "(Ljava/lang/String;)Landroid/net/Uri$Builder;"); global::android.net.Uri.Builder._appendQueryParameter5281 = @__env.GetMethodIDNoThrow(global::android.net.Uri.Builder.staticClass, "appendQueryParameter", "(Ljava/lang/String;Ljava/lang/String;)Landroid/net/Uri$Builder;"); global::android.net.Uri.Builder._Builder5282 = @__env.GetMethodIDNoThrow(global::android.net.Uri.Builder.staticClass, "<init>", "()V"); } } internal static global::MonoJavaBridge.MethodId _writeToParcel5283; public abstract void writeToParcel(android.os.Parcel arg0, int arg1); internal static global::MonoJavaBridge.MethodId _describeContents5284; public abstract int describeContents(); internal static global::MonoJavaBridge.MethodId _equals5285; public override bool equals(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.net.Uri._equals5285, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.net.Uri.staticClass, global::android.net.Uri._equals5285, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _toString5286; public abstract new global::java.lang.String toString(); internal static global::MonoJavaBridge.MethodId _hashCode5287; public override int hashCode() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.net.Uri._hashCode5287); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.net.Uri.staticClass, global::android.net.Uri._hashCode5287); } internal static global::MonoJavaBridge.MethodId _compareTo5288; public virtual int compareTo(android.net.Uri arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.net.Uri._compareTo5288, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.net.Uri.staticClass, global::android.net.Uri._compareTo5288, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _compareTo5289; public virtual int compareTo(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.net.Uri._compareTo5289, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.net.Uri.staticClass, global::android.net.Uri._compareTo5289, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _decode5290; public static global::java.lang.String decode(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.net.Uri.staticClass, global::android.net.Uri._decode5290, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _encode5291; public static global::java.lang.String encode(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.net.Uri.staticClass, global::android.net.Uri._encode5291, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _encode5292; public static global::java.lang.String encode(java.lang.String arg0, java.lang.String arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.net.Uri.staticClass, global::android.net.Uri._encode5292, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _isAbsolute5293; public virtual bool isAbsolute() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.net.Uri._isAbsolute5293); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.net.Uri.staticClass, global::android.net.Uri._isAbsolute5293); } internal static global::MonoJavaBridge.MethodId _getPath5294; public abstract global::java.lang.String getPath(); internal static global::MonoJavaBridge.MethodId _isOpaque5295; public virtual bool isOpaque() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.net.Uri._isOpaque5295); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.net.Uri.staticClass, global::android.net.Uri._isOpaque5295); } internal static global::MonoJavaBridge.MethodId _getScheme5296; public abstract global::java.lang.String getScheme(); internal static global::MonoJavaBridge.MethodId _getAuthority5297; public abstract global::java.lang.String getAuthority(); internal static global::MonoJavaBridge.MethodId _getFragment5298; public abstract global::java.lang.String getFragment(); internal static global::MonoJavaBridge.MethodId _getQuery5299; public abstract global::java.lang.String getQuery(); internal static global::MonoJavaBridge.MethodId _parse5300; public static global::android.net.Uri parse(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.net.Uri.staticClass, global::android.net.Uri._parse5300, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.net.Uri; } internal static global::MonoJavaBridge.MethodId _getUserInfo5301; public abstract global::java.lang.String getUserInfo(); internal static global::MonoJavaBridge.MethodId _getPort5302; public abstract int getPort(); internal static global::MonoJavaBridge.MethodId _getHost5303; public abstract global::java.lang.String getHost(); internal static global::MonoJavaBridge.MethodId _writeToParcel5304; public static void writeToParcel(android.os.Parcel arg0, android.net.Uri arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; @__env.CallStaticVoidMethod(android.net.Uri.staticClass, global::android.net.Uri._writeToParcel5304, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _isHierarchical5305; public abstract bool isHierarchical(); internal static global::MonoJavaBridge.MethodId _isRelative5306; public abstract bool isRelative(); internal static global::MonoJavaBridge.MethodId _getSchemeSpecificPart5307; public abstract global::java.lang.String getSchemeSpecificPart(); internal static global::MonoJavaBridge.MethodId _getEncodedSchemeSpecificPart5308; public abstract global::java.lang.String getEncodedSchemeSpecificPart(); internal static global::MonoJavaBridge.MethodId _getEncodedAuthority5309; public abstract global::java.lang.String getEncodedAuthority(); internal static global::MonoJavaBridge.MethodId _getEncodedUserInfo5310; public abstract global::java.lang.String getEncodedUserInfo(); internal static global::MonoJavaBridge.MethodId _getEncodedPath5311; public abstract global::java.lang.String getEncodedPath(); internal static global::MonoJavaBridge.MethodId _getEncodedQuery5312; public abstract global::java.lang.String getEncodedQuery(); internal static global::MonoJavaBridge.MethodId _getEncodedFragment5313; public abstract global::java.lang.String getEncodedFragment(); internal static global::MonoJavaBridge.MethodId _getPathSegments5314; public abstract global::java.util.List getPathSegments(); internal static global::MonoJavaBridge.MethodId _getLastPathSegment5315; public abstract global::java.lang.String getLastPathSegment(); internal static global::MonoJavaBridge.MethodId _buildUpon5316; public abstract global::android.net.Uri.Builder buildUpon(); internal static global::MonoJavaBridge.MethodId _fromFile5317; public static global::android.net.Uri fromFile(java.io.File arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.net.Uri.staticClass, global::android.net.Uri._fromFile5317, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.net.Uri; } internal static global::MonoJavaBridge.MethodId _fromParts5318; public static global::android.net.Uri fromParts(java.lang.String arg0, java.lang.String arg1, java.lang.String arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.net.Uri.staticClass, global::android.net.Uri._fromParts5318, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as android.net.Uri; } internal static global::MonoJavaBridge.MethodId _getQueryParameters5319; public virtual global::java.util.List getQueryParameters(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.List>(@__env.CallObjectMethod(this.JvmHandle, global::android.net.Uri._getQueryParameters5319, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.util.List; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.List>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.Uri.staticClass, global::android.net.Uri._getQueryParameters5319, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.util.List; } internal static global::MonoJavaBridge.MethodId _getQueryParameter5320; public virtual global::java.lang.String getQueryParameter(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.Uri._getQueryParameter5320, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.Uri.staticClass, global::android.net.Uri._getQueryParameter5320, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _withAppendedPath5321; public static global::android.net.Uri withAppendedPath(android.net.Uri arg0, java.lang.String arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.net.Uri.staticClass, global::android.net.Uri._withAppendedPath5321, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.net.Uri; } internal static global::MonoJavaBridge.FieldId _EMPTY5322; public static global::android.net.Uri EMPTY { get { return default(global::android.net.Uri); } } internal static global::MonoJavaBridge.FieldId _CREATOR5323; public static global::android.os.Parcelable_Creator CREATOR { get { return default(global::android.os.Parcelable_Creator); } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.net.Uri.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/net/Uri")); global::android.net.Uri._writeToParcel5283 = @__env.GetMethodIDNoThrow(global::android.net.Uri.staticClass, "writeToParcel", "(Landroid/os/Parcel;I)V"); global::android.net.Uri._describeContents5284 = @__env.GetMethodIDNoThrow(global::android.net.Uri.staticClass, "describeContents", "()I"); global::android.net.Uri._equals5285 = @__env.GetMethodIDNoThrow(global::android.net.Uri.staticClass, "equals", "(Ljava/lang/Object;)Z"); global::android.net.Uri._toString5286 = @__env.GetMethodIDNoThrow(global::android.net.Uri.staticClass, "toString", "()Ljava/lang/String;"); global::android.net.Uri._hashCode5287 = @__env.GetMethodIDNoThrow(global::android.net.Uri.staticClass, "hashCode", "()I"); global::android.net.Uri._compareTo5288 = @__env.GetMethodIDNoThrow(global::android.net.Uri.staticClass, "compareTo", "(Landroid/net/Uri;)I"); global::android.net.Uri._compareTo5289 = @__env.GetMethodIDNoThrow(global::android.net.Uri.staticClass, "compareTo", "(Ljava/lang/Object;)I"); global::android.net.Uri._decode5290 = @__env.GetStaticMethodIDNoThrow(global::android.net.Uri.staticClass, "decode", "(Ljava/lang/String;)Ljava/lang/String;"); global::android.net.Uri._encode5291 = @__env.GetStaticMethodIDNoThrow(global::android.net.Uri.staticClass, "encode", "(Ljava/lang/String;)Ljava/lang/String;"); global::android.net.Uri._encode5292 = @__env.GetStaticMethodIDNoThrow(global::android.net.Uri.staticClass, "encode", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"); global::android.net.Uri._isAbsolute5293 = @__env.GetMethodIDNoThrow(global::android.net.Uri.staticClass, "isAbsolute", "()Z"); global::android.net.Uri._getPath5294 = @__env.GetMethodIDNoThrow(global::android.net.Uri.staticClass, "getPath", "()Ljava/lang/String;"); global::android.net.Uri._isOpaque5295 = @__env.GetMethodIDNoThrow(global::android.net.Uri.staticClass, "isOpaque", "()Z"); global::android.net.Uri._getScheme5296 = @__env.GetMethodIDNoThrow(global::android.net.Uri.staticClass, "getScheme", "()Ljava/lang/String;"); global::android.net.Uri._getAuthority5297 = @__env.GetMethodIDNoThrow(global::android.net.Uri.staticClass, "getAuthority", "()Ljava/lang/String;"); global::android.net.Uri._getFragment5298 = @__env.GetMethodIDNoThrow(global::android.net.Uri.staticClass, "getFragment", "()Ljava/lang/String;"); global::android.net.Uri._getQuery5299 = @__env.GetMethodIDNoThrow(global::android.net.Uri.staticClass, "getQuery", "()Ljava/lang/String;"); global::android.net.Uri._parse5300 = @__env.GetStaticMethodIDNoThrow(global::android.net.Uri.staticClass, "parse", "(Ljava/lang/String;)Landroid/net/Uri;"); global::android.net.Uri._getUserInfo5301 = @__env.GetMethodIDNoThrow(global::android.net.Uri.staticClass, "getUserInfo", "()Ljava/lang/String;"); global::android.net.Uri._getPort5302 = @__env.GetMethodIDNoThrow(global::android.net.Uri.staticClass, "getPort", "()I"); global::android.net.Uri._getHost5303 = @__env.GetMethodIDNoThrow(global::android.net.Uri.staticClass, "getHost", "()Ljava/lang/String;"); global::android.net.Uri._writeToParcel5304 = @__env.GetStaticMethodIDNoThrow(global::android.net.Uri.staticClass, "writeToParcel", "(Landroid/os/Parcel;Landroid/net/Uri;)V"); global::android.net.Uri._isHierarchical5305 = @__env.GetMethodIDNoThrow(global::android.net.Uri.staticClass, "isHierarchical", "()Z"); global::android.net.Uri._isRelative5306 = @__env.GetMethodIDNoThrow(global::android.net.Uri.staticClass, "isRelative", "()Z"); global::android.net.Uri._getSchemeSpecificPart5307 = @__env.GetMethodIDNoThrow(global::android.net.Uri.staticClass, "getSchemeSpecificPart", "()Ljava/lang/String;"); global::android.net.Uri._getEncodedSchemeSpecificPart5308 = @__env.GetMethodIDNoThrow(global::android.net.Uri.staticClass, "getEncodedSchemeSpecificPart", "()Ljava/lang/String;"); global::android.net.Uri._getEncodedAuthority5309 = @__env.GetMethodIDNoThrow(global::android.net.Uri.staticClass, "getEncodedAuthority", "()Ljava/lang/String;"); global::android.net.Uri._getEncodedUserInfo5310 = @__env.GetMethodIDNoThrow(global::android.net.Uri.staticClass, "getEncodedUserInfo", "()Ljava/lang/String;"); global::android.net.Uri._getEncodedPath5311 = @__env.GetMethodIDNoThrow(global::android.net.Uri.staticClass, "getEncodedPath", "()Ljava/lang/String;"); global::android.net.Uri._getEncodedQuery5312 = @__env.GetMethodIDNoThrow(global::android.net.Uri.staticClass, "getEncodedQuery", "()Ljava/lang/String;"); global::android.net.Uri._getEncodedFragment5313 = @__env.GetMethodIDNoThrow(global::android.net.Uri.staticClass, "getEncodedFragment", "()Ljava/lang/String;"); global::android.net.Uri._getPathSegments5314 = @__env.GetMethodIDNoThrow(global::android.net.Uri.staticClass, "getPathSegments", "()Ljava/util/List;"); global::android.net.Uri._getLastPathSegment5315 = @__env.GetMethodIDNoThrow(global::android.net.Uri.staticClass, "getLastPathSegment", "()Ljava/lang/String;"); global::android.net.Uri._buildUpon5316 = @__env.GetMethodIDNoThrow(global::android.net.Uri.staticClass, "buildUpon", "()Landroid/net/Uri$Builder;"); global::android.net.Uri._fromFile5317 = @__env.GetStaticMethodIDNoThrow(global::android.net.Uri.staticClass, "fromFile", "(Ljava/io/File;)Landroid/net/Uri;"); global::android.net.Uri._fromParts5318 = @__env.GetStaticMethodIDNoThrow(global::android.net.Uri.staticClass, "fromParts", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Landroid/net/Uri;"); global::android.net.Uri._getQueryParameters5319 = @__env.GetMethodIDNoThrow(global::android.net.Uri.staticClass, "getQueryParameters", "(Ljava/lang/String;)Ljava/util/List;"); global::android.net.Uri._getQueryParameter5320 = @__env.GetMethodIDNoThrow(global::android.net.Uri.staticClass, "getQueryParameter", "(Ljava/lang/String;)Ljava/lang/String;"); global::android.net.Uri._withAppendedPath5321 = @__env.GetStaticMethodIDNoThrow(global::android.net.Uri.staticClass, "withAppendedPath", "(Landroid/net/Uri;Ljava/lang/String;)Landroid/net/Uri;"); } } [global::MonoJavaBridge.JavaProxy(typeof(global::android.net.Uri))] public sealed partial class Uri_ : android.net.Uri { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static Uri_() { InitJNI(); } internal Uri_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _writeToParcel5324; public override void writeToParcel(android.os.Parcel arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.net.Uri_._writeToParcel5324, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.net.Uri_.staticClass, global::android.net.Uri_._writeToParcel5324, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _describeContents5325; public override int describeContents() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.net.Uri_._describeContents5325); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.net.Uri_.staticClass, global::android.net.Uri_._describeContents5325); } internal static global::MonoJavaBridge.MethodId _toString5326; public override global::java.lang.String toString() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.Uri_._toString5326)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.Uri_.staticClass, global::android.net.Uri_._toString5326)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _getPath5327; public override global::java.lang.String getPath() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.Uri_._getPath5327)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.Uri_.staticClass, global::android.net.Uri_._getPath5327)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _getScheme5328; public override global::java.lang.String getScheme() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.Uri_._getScheme5328)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.Uri_.staticClass, global::android.net.Uri_._getScheme5328)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _getAuthority5329; public override global::java.lang.String getAuthority() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.Uri_._getAuthority5329)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.Uri_.staticClass, global::android.net.Uri_._getAuthority5329)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _getFragment5330; public override global::java.lang.String getFragment() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.Uri_._getFragment5330)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.Uri_.staticClass, global::android.net.Uri_._getFragment5330)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _getQuery5331; public override global::java.lang.String getQuery() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.Uri_._getQuery5331)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.Uri_.staticClass, global::android.net.Uri_._getQuery5331)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _getUserInfo5332; public override global::java.lang.String getUserInfo() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.Uri_._getUserInfo5332)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.Uri_.staticClass, global::android.net.Uri_._getUserInfo5332)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _getPort5333; public override int getPort() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.net.Uri_._getPort5333); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.net.Uri_.staticClass, global::android.net.Uri_._getPort5333); } internal static global::MonoJavaBridge.MethodId _getHost5334; public override global::java.lang.String getHost() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.Uri_._getHost5334)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.Uri_.staticClass, global::android.net.Uri_._getHost5334)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _isHierarchical5335; public override bool isHierarchical() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.net.Uri_._isHierarchical5335); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.net.Uri_.staticClass, global::android.net.Uri_._isHierarchical5335); } internal static global::MonoJavaBridge.MethodId _isRelative5336; public override bool isRelative() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.net.Uri_._isRelative5336); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.net.Uri_.staticClass, global::android.net.Uri_._isRelative5336); } internal static global::MonoJavaBridge.MethodId _getSchemeSpecificPart5337; public override global::java.lang.String getSchemeSpecificPart() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.Uri_._getSchemeSpecificPart5337)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.Uri_.staticClass, global::android.net.Uri_._getSchemeSpecificPart5337)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _getEncodedSchemeSpecificPart5338; public override global::java.lang.String getEncodedSchemeSpecificPart() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.Uri_._getEncodedSchemeSpecificPart5338)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.Uri_.staticClass, global::android.net.Uri_._getEncodedSchemeSpecificPart5338)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _getEncodedAuthority5339; public override global::java.lang.String getEncodedAuthority() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.Uri_._getEncodedAuthority5339)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.Uri_.staticClass, global::android.net.Uri_._getEncodedAuthority5339)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _getEncodedUserInfo5340; public override global::java.lang.String getEncodedUserInfo() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.Uri_._getEncodedUserInfo5340)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.Uri_.staticClass, global::android.net.Uri_._getEncodedUserInfo5340)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _getEncodedPath5341; public override global::java.lang.String getEncodedPath() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.Uri_._getEncodedPath5341)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.Uri_.staticClass, global::android.net.Uri_._getEncodedPath5341)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _getEncodedQuery5342; public override global::java.lang.String getEncodedQuery() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.Uri_._getEncodedQuery5342)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.Uri_.staticClass, global::android.net.Uri_._getEncodedQuery5342)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _getEncodedFragment5343; public override global::java.lang.String getEncodedFragment() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.Uri_._getEncodedFragment5343)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.Uri_.staticClass, global::android.net.Uri_._getEncodedFragment5343)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _getPathSegments5344; public override global::java.util.List getPathSegments() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.List>(@__env.CallObjectMethod(this.JvmHandle, global::android.net.Uri_._getPathSegments5344)) as java.util.List; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.List>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.Uri_.staticClass, global::android.net.Uri_._getPathSegments5344)) as java.util.List; } internal static global::MonoJavaBridge.MethodId _getLastPathSegment5345; public override global::java.lang.String getLastPathSegment() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.Uri_._getLastPathSegment5345)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.Uri_.staticClass, global::android.net.Uri_._getLastPathSegment5345)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _buildUpon5346; public override global::android.net.Uri.Builder buildUpon() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.Uri_._buildUpon5346)) as android.net.Uri.Builder; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.Uri_.staticClass, global::android.net.Uri_._buildUpon5346)) as android.net.Uri.Builder; } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.net.Uri_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/net/Uri")); global::android.net.Uri_._writeToParcel5324 = @__env.GetMethodIDNoThrow(global::android.net.Uri_.staticClass, "writeToParcel", "(Landroid/os/Parcel;I)V"); global::android.net.Uri_._describeContents5325 = @__env.GetMethodIDNoThrow(global::android.net.Uri_.staticClass, "describeContents", "()I"); global::android.net.Uri_._toString5326 = @__env.GetMethodIDNoThrow(global::android.net.Uri_.staticClass, "toString", "()Ljava/lang/String;"); global::android.net.Uri_._getPath5327 = @__env.GetMethodIDNoThrow(global::android.net.Uri_.staticClass, "getPath", "()Ljava/lang/String;"); global::android.net.Uri_._getScheme5328 = @__env.GetMethodIDNoThrow(global::android.net.Uri_.staticClass, "getScheme", "()Ljava/lang/String;"); global::android.net.Uri_._getAuthority5329 = @__env.GetMethodIDNoThrow(global::android.net.Uri_.staticClass, "getAuthority", "()Ljava/lang/String;"); global::android.net.Uri_._getFragment5330 = @__env.GetMethodIDNoThrow(global::android.net.Uri_.staticClass, "getFragment", "()Ljava/lang/String;"); global::android.net.Uri_._getQuery5331 = @__env.GetMethodIDNoThrow(global::android.net.Uri_.staticClass, "getQuery", "()Ljava/lang/String;"); global::android.net.Uri_._getUserInfo5332 = @__env.GetMethodIDNoThrow(global::android.net.Uri_.staticClass, "getUserInfo", "()Ljava/lang/String;"); global::android.net.Uri_._getPort5333 = @__env.GetMethodIDNoThrow(global::android.net.Uri_.staticClass, "getPort", "()I"); global::android.net.Uri_._getHost5334 = @__env.GetMethodIDNoThrow(global::android.net.Uri_.staticClass, "getHost", "()Ljava/lang/String;"); global::android.net.Uri_._isHierarchical5335 = @__env.GetMethodIDNoThrow(global::android.net.Uri_.staticClass, "isHierarchical", "()Z"); global::android.net.Uri_._isRelative5336 = @__env.GetMethodIDNoThrow(global::android.net.Uri_.staticClass, "isRelative", "()Z"); global::android.net.Uri_._getSchemeSpecificPart5337 = @__env.GetMethodIDNoThrow(global::android.net.Uri_.staticClass, "getSchemeSpecificPart", "()Ljava/lang/String;"); global::android.net.Uri_._getEncodedSchemeSpecificPart5338 = @__env.GetMethodIDNoThrow(global::android.net.Uri_.staticClass, "getEncodedSchemeSpecificPart", "()Ljava/lang/String;"); global::android.net.Uri_._getEncodedAuthority5339 = @__env.GetMethodIDNoThrow(global::android.net.Uri_.staticClass, "getEncodedAuthority", "()Ljava/lang/String;"); global::android.net.Uri_._getEncodedUserInfo5340 = @__env.GetMethodIDNoThrow(global::android.net.Uri_.staticClass, "getEncodedUserInfo", "()Ljava/lang/String;"); global::android.net.Uri_._getEncodedPath5341 = @__env.GetMethodIDNoThrow(global::android.net.Uri_.staticClass, "getEncodedPath", "()Ljava/lang/String;"); global::android.net.Uri_._getEncodedQuery5342 = @__env.GetMethodIDNoThrow(global::android.net.Uri_.staticClass, "getEncodedQuery", "()Ljava/lang/String;"); global::android.net.Uri_._getEncodedFragment5343 = @__env.GetMethodIDNoThrow(global::android.net.Uri_.staticClass, "getEncodedFragment", "()Ljava/lang/String;"); global::android.net.Uri_._getPathSegments5344 = @__env.GetMethodIDNoThrow(global::android.net.Uri_.staticClass, "getPathSegments", "()Ljava/util/List;"); global::android.net.Uri_._getLastPathSegment5345 = @__env.GetMethodIDNoThrow(global::android.net.Uri_.staticClass, "getLastPathSegment", "()Ljava/lang/String;"); global::android.net.Uri_._buildUpon5346 = @__env.GetMethodIDNoThrow(global::android.net.Uri_.staticClass, "buildUpon", "()Landroid/net/Uri$Builder;"); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Xml; using System.Xml.Linq; using Examine; using Examine.LuceneEngine; using Lucene.Net.Documents; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Sync; using Umbraco.Web.Cache; using UmbracoExamine; using Content = umbraco.cms.businesslogic.Content; using Document = umbraco.cms.businesslogic.web.Document; namespace Umbraco.Web.Search { /// <summary> /// Used to wire up events for Examine /// </summary> public sealed class ExamineEvents : ApplicationEventHandler { /// <summary> /// Once the application has started we should bind to all events and initialize the providers. /// </summary> /// <param name="httpApplication"></param> /// <param name="applicationContext"></param> /// <remarks> /// We need to do this on the Started event as to guarantee that all resolvers are setup properly. /// </remarks> protected override void ApplicationStarted(UmbracoApplicationBase httpApplication, ApplicationContext applicationContext) { LogHelper.Info<ExamineEvents>("Initializing Examine and binding to business logic events"); var registeredProviders = ExamineManager.Instance.IndexProviderCollection .OfType<BaseUmbracoIndexer>().Count(x => x.EnableDefaultEventHandler); LogHelper.Info<ExamineEvents>("Adding examine event handlers for index providers: {0}", () => registeredProviders); //don't bind event handlers if we're not suppose to listen if (registeredProviders == 0) return; //Bind to distributed cache events - this ensures that this logic occurs on ALL servers that are taking part // in a load balanced environment. CacheRefresherBase<UnpublishedPageCacheRefresher>.CacheUpdated += UnpublishedPageCacheRefresherCacheUpdated; CacheRefresherBase<PageCacheRefresher>.CacheUpdated += PublishedPageCacheRefresherCacheUpdated; CacheRefresherBase<MediaCacheRefresher>.CacheUpdated += MediaCacheRefresherCacheUpdated; CacheRefresherBase<MemberCacheRefresher>.CacheUpdated += MemberCacheRefresherCacheUpdated; CacheRefresherBase<ContentTypeCacheRefresher>.CacheUpdated += ContentTypeCacheRefresherCacheUpdated; var contentIndexer = ExamineManager.Instance.IndexProviderCollection[Constants.Examine.InternalIndexer] as UmbracoContentIndexer; if (contentIndexer != null) { contentIndexer.DocumentWriting += IndexerDocumentWriting; } var memberIndexer = ExamineManager.Instance.IndexProviderCollection[Constants.Examine.InternalMemberIndexer] as UmbracoMemberIndexer; if (memberIndexer != null) { memberIndexer.DocumentWriting += IndexerDocumentWriting; } } /// <summary> /// This is used to refresh content indexers IndexData based on the DataService whenever a content type is changed since /// properties may have been added/removed, then we need to re-index any required data if aliases have been changed /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// <remarks> /// See: http://issues.umbraco.org/issue/U4-4798, http://issues.umbraco.org/issue/U4-7833 /// </remarks> static void ContentTypeCacheRefresherCacheUpdated(ContentTypeCacheRefresher sender, CacheRefresherEventArgs e) { var indexersToUpdated = ExamineManager.Instance.IndexProviderCollection.OfType<UmbracoContentIndexer>(); foreach (var provider in indexersToUpdated) { provider.RefreshIndexerDataFromDataService(); } if (e.MessageType == MessageType.RefreshByJson) { var contentTypesChanged = new HashSet<string>(); var mediaTypesChanged = new HashSet<string>(); var memberTypesChanged = new HashSet<string>(); var payloads = ContentTypeCacheRefresher.DeserializeFromJsonPayload(e.MessageObject.ToString()); foreach (var payload in payloads) { if (payload.IsNew == false && (payload.WasDeleted || payload.AliasChanged || payload.PropertyRemoved || payload.PropertyTypeAliasChanged)) { //if we get here it means that some aliases have changed and the indexes for those particular doc types will need to be updated if (payload.Type == typeof(IContentType).Name) { //if it is content contentTypesChanged.Add(payload.Alias); } else if (payload.Type == typeof(IMediaType).Name) { //if it is media mediaTypesChanged.Add(payload.Alias); } else if (payload.Type == typeof(IMemberType).Name) { //if it is members memberTypesChanged.Add(payload.Alias); } } } //TODO: We need to update Examine to support re-indexing multiple items at once instead of one by one which will speed up // the re-indexing process, we don't want to revert to rebuilding the whole thing! if (contentTypesChanged.Count > 0) { foreach (var alias in contentTypesChanged) { var ctType = ApplicationContext.Current.Services.ContentTypeService.GetContentType(alias); if (ctType != null) { var contentItems = ApplicationContext.Current.Services.ContentService.GetContentOfContentType(ctType.Id); foreach (var contentItem in contentItems) { ReIndexForContent(contentItem, contentItem.HasPublishedVersion && contentItem.Trashed == false); } } } } if (mediaTypesChanged.Count > 0) { foreach (var alias in mediaTypesChanged) { var ctType = ApplicationContext.Current.Services.ContentTypeService.GetMediaType(alias); if (ctType != null) { var mediaItems = ApplicationContext.Current.Services.MediaService.GetMediaOfMediaType(ctType.Id); foreach (var mediaItem in mediaItems) { ReIndexForMedia(mediaItem, mediaItem.Trashed == false); } } } } if (memberTypesChanged.Count > 0) { foreach (var alias in memberTypesChanged) { var ctType = ApplicationContext.Current.Services.MemberTypeService.Get(alias); if (ctType != null) { var memberItems = ApplicationContext.Current.Services.MemberService.GetMembersByMemberType(ctType.Id); foreach (var memberItem in memberItems) { ReIndexForMember(memberItem); } } } } } } static void MemberCacheRefresherCacheUpdated(MemberCacheRefresher sender, CacheRefresherEventArgs e) { switch (e.MessageType) { case MessageType.RefreshById: var c1 = ApplicationContext.Current.Services.MemberService.GetById((int)e.MessageObject); if (c1 != null) { ReIndexForMember(c1); } break; case MessageType.RemoveById: // This is triggered when the item is permanently deleted DeleteIndexForEntity((int)e.MessageObject, false); break; case MessageType.RefreshByInstance: var c3 = e.MessageObject as IMember; if (c3 != null) { ReIndexForMember(c3); } break; case MessageType.RemoveByInstance: // This is triggered when the item is permanently deleted var c4 = e.MessageObject as IMember; if (c4 != null) { DeleteIndexForEntity(c4.Id, false); } break; case MessageType.RefreshAll: case MessageType.RefreshByJson: default: //We don't support these, these message types will not fire for unpublished content break; } } /// <summary> /// Handles index management for all media events - basically handling saving/copying/trashing/deleting /// </summary> /// <param name="sender"></param> /// <param name="e"></param> static void MediaCacheRefresherCacheUpdated(MediaCacheRefresher sender, CacheRefresherEventArgs e) { switch (e.MessageType) { case MessageType.RefreshById: var c1 = ApplicationContext.Current.Services.MediaService.GetById((int)e.MessageObject); if (c1 != null) { ReIndexForMedia(c1, c1.Trashed == false); } break; case MessageType.RemoveById: var c2 = ApplicationContext.Current.Services.MediaService.GetById((int)e.MessageObject); if (c2 != null) { //This is triggered when the item has trashed. // So we need to delete the index from all indexes not supporting unpublished content. DeleteIndexForEntity(c2.Id, true); //We then need to re-index this item for all indexes supporting unpublished content ReIndexForMedia(c2, false); } break; case MessageType.RefreshByJson: var jsonPayloads = MediaCacheRefresher.DeserializeFromJsonPayload((string)e.MessageObject); if (jsonPayloads.Any()) { foreach (var payload in jsonPayloads) { switch (payload.Operation) { case MediaCacheRefresher.OperationType.Saved: var media1 = ApplicationContext.Current.Services.MediaService.GetById(payload.Id); if (media1 != null) { ReIndexForMedia(media1, media1.Trashed == false); } break; case MediaCacheRefresher.OperationType.Trashed: //keep if trashed for indexes supporting unpublished //(delete the index from all indexes not supporting unpublished content) DeleteIndexForEntity(payload.Id, true); //We then need to re-index this item for all indexes supporting unpublished content var media2 = ApplicationContext.Current.Services.MediaService.GetById(payload.Id); if (media2 != null) { ReIndexForMedia(media2, false); } break; case MediaCacheRefresher.OperationType.Deleted: //permanently remove from all indexes DeleteIndexForEntity(payload.Id, false); break; default: throw new ArgumentOutOfRangeException(); } } } break; case MessageType.RefreshByInstance: case MessageType.RemoveByInstance: case MessageType.RefreshAll: default: //We don't support these, these message types will not fire for media break; } } /// <summary> /// Handles index management for all published content events - basically handling published/unpublished /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// <remarks> /// This will execute on all servers taking part in load balancing /// </remarks> static void PublishedPageCacheRefresherCacheUpdated(PageCacheRefresher sender, CacheRefresherEventArgs e) { switch (e.MessageType) { case MessageType.RefreshById: var c1 = ApplicationContext.Current.Services.ContentService.GetById((int)e.MessageObject); if (c1 != null) { ReIndexForContent(c1, true); } break; case MessageType.RemoveById: //This is triggered when the item has been unpublished or trashed (which also performs an unpublish). var c2 = ApplicationContext.Current.Services.ContentService.GetById((int)e.MessageObject); if (c2 != null) { // So we need to delete the index from all indexes not supporting unpublished content. DeleteIndexForEntity(c2.Id, true); // We then need to re-index this item for all indexes supporting unpublished content ReIndexForContent(c2, false); } break; case MessageType.RefreshByInstance: var c3 = e.MessageObject as IContent; if (c3 != null) { ReIndexForContent(c3, true); } break; case MessageType.RemoveByInstance: //This is triggered when the item has been unpublished or trashed (which also performs an unpublish). var c4 = e.MessageObject as IContent; if (c4 != null) { // So we need to delete the index from all indexes not supporting unpublished content. DeleteIndexForEntity(c4.Id, true); // We then need to re-index this item for all indexes supporting unpublished content ReIndexForContent(c4, false); } break; case MessageType.RefreshAll: case MessageType.RefreshByJson: default: //We don't support these for examine indexing break; } } /// <summary> /// Handles index management for all unpublished content events - basically handling saving/copying/deleting /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// <remarks> /// This will execute on all servers taking part in load balancing /// </remarks> static void UnpublishedPageCacheRefresherCacheUpdated(UnpublishedPageCacheRefresher sender, CacheRefresherEventArgs e) { switch (e.MessageType) { case MessageType.RefreshById: var c1 = ApplicationContext.Current.Services.ContentService.GetById((int) e.MessageObject); if (c1 != null) { ReIndexForContent(c1, false); } break; case MessageType.RemoveById: // This is triggered when the item is permanently deleted DeleteIndexForEntity((int)e.MessageObject, false); break; case MessageType.RefreshByInstance: var c3 = e.MessageObject as IContent; if (c3 != null) { ReIndexForContent(c3, false); } break; case MessageType.RemoveByInstance: // This is triggered when the item is permanently deleted var c4 = e.MessageObject as IContent; if (c4 != null) { DeleteIndexForEntity(c4.Id, false); } break; case MessageType.RefreshByJson: var jsonPayloads = UnpublishedPageCacheRefresher.DeserializeFromJsonPayload((string)e.MessageObject); if (jsonPayloads.Any()) { foreach (var payload in jsonPayloads) { switch (payload.Operation) { case UnpublishedPageCacheRefresher.OperationType.Deleted: //permanently remove from all indexes DeleteIndexForEntity(payload.Id, false); break; default: throw new ArgumentOutOfRangeException(); } } } break; case MessageType.RefreshAll: default: //We don't support these, these message types will not fire for unpublished content break; } } private static void ReIndexForMember(IMember member) { ExamineManager.Instance.ReIndexNode( member.ToXml(), IndexTypes.Member, ExamineManager.Instance.IndexProviderCollection.OfType<BaseUmbracoIndexer>() //ensure that only the providers are flagged to listen execute .Where(x => x.EnableDefaultEventHandler)); } /// <summary> /// Event handler to create a lower cased version of the node name, this is so we can support case-insensitive searching and still /// use the Whitespace Analyzer /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private static void IndexerDocumentWriting(object sender, DocumentWritingEventArgs e) { if (e.Fields.Keys.Contains("nodeName")) { //TODO: This logic should really be put into the content indexer instead of hidden here!! //add the lower cased version e.Document.Add(new Field("__nodeName", e.Fields["nodeName"].ToLower(), Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.NO )); } } private static void ReIndexForMedia(IMedia sender, bool isMediaPublished) { var xml = sender.ToXml(); //add an icon attribute to get indexed xml.Add(new XAttribute("icon", sender.ContentType.Icon)); ExamineManager.Instance.ReIndexNode( xml, IndexTypes.Media, ExamineManager.Instance.IndexProviderCollection.OfType<BaseUmbracoIndexer>() //Index this item for all indexers if the media is not trashed, otherwise if the item is trashed // then only index this for indexers supporting unpublished media .Where(x => isMediaPublished || (x.SupportUnpublishedContent)) .Where(x => x.EnableDefaultEventHandler)); } /// <summary> /// Remove items from any index that doesn't support unpublished content /// </summary> /// <param name="entityId"></param> /// <param name="keepIfUnpublished"> /// If true, indicates that we will only delete this item from indexes that don't support unpublished content. /// If false it will delete this from all indexes regardless. /// </param> private static void DeleteIndexForEntity(int entityId, bool keepIfUnpublished) { ExamineManager.Instance.DeleteFromIndex( entityId.ToString(CultureInfo.InvariantCulture), ExamineManager.Instance.IndexProviderCollection.OfType<BaseUmbracoIndexer>() //if keepIfUnpublished == true then only delete this item from indexes not supporting unpublished content, // otherwise if keepIfUnpublished == false then remove from all indexes .Where(x => keepIfUnpublished == false || x.SupportUnpublishedContent == false) .Where(x => x.EnableDefaultEventHandler)); } /// <summary> /// Re-indexes a content item whether published or not but only indexes them for indexes supporting unpublished content /// </summary> /// <param name="sender"></param> /// <param name="isContentPublished"> /// Value indicating whether the item is published or not /// </param> private static void ReIndexForContent(IContent sender, bool isContentPublished) { var xml = sender.ToXml(); //add an icon attribute to get indexed xml.Add(new XAttribute("icon", sender.ContentType.Icon)); ExamineManager.Instance.ReIndexNode( xml, IndexTypes.Content, ExamineManager.Instance.IndexProviderCollection.OfType<BaseUmbracoIndexer>() //Index this item for all indexers if the content is published, otherwise if the item is not published // then only index this for indexers supporting unpublished content .Where(x => isContentPublished || (x.SupportUnpublishedContent)) .Where(x => x.EnableDefaultEventHandler)); } /// <summary> /// Converts a content node to XDocument /// </summary> /// <param name="node"></param> /// <param name="cacheOnly">true if data is going to be returned from cache</param> /// <returns></returns> [Obsolete("This method is no longer used and will be removed from the core in future versions, the cacheOnly parameter has no effect. Use the other ToXDocument overload instead")] public static XDocument ToXDocument(Content node, bool cacheOnly) { return ToXDocument(node); } /// <summary> /// Converts a content node to Xml /// </summary> /// <param name="node"></param> /// <returns></returns> private static XDocument ToXDocument(Content node) { if (TypeHelper.IsTypeAssignableFrom<Document>(node)) { return new XDocument(((Document) node).ContentEntity.ToXml()); } if (TypeHelper.IsTypeAssignableFrom<global::umbraco.cms.businesslogic.media.Media>(node)) { return new XDocument(((global::umbraco.cms.businesslogic.media.Media) node).MediaItem.ToXml()); } var xDoc = new XmlDocument(); var xNode = xDoc.CreateNode(XmlNodeType.Element, "node", ""); node.XmlPopulate(xDoc, ref xNode, false); if (xNode.Attributes["nodeTypeAlias"] == null) { //we'll add the nodeTypeAlias ourselves XmlAttribute d = xDoc.CreateAttribute("nodeTypeAlias"); d.Value = node.ContentType.Alias; xNode.Attributes.Append(d); } return new XDocument(ExamineXmlExtensions.ToXElement(xNode)); } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Globalization; using System.ComponentModel; #if HAVE_BIG_INTEGER using System.Numerics; #endif using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json.Serialization; using System.Reflection; #if !HAVE_LINQ using Newtonsoft.Json.Utilities.LinqBridge; #endif #if HAVE_ADO_NET using System.Data.SqlTypes; #endif namespace Newtonsoft.Json.Utilities { internal enum PrimitiveTypeCode { Empty = 0, Object = 1, Char = 2, CharNullable = 3, Boolean = 4, BooleanNullable = 5, SByte = 6, SByteNullable = 7, Int16 = 8, Int16Nullable = 9, UInt16 = 10, UInt16Nullable = 11, Int32 = 12, Int32Nullable = 13, Byte = 14, ByteNullable = 15, UInt32 = 16, UInt32Nullable = 17, Int64 = 18, Int64Nullable = 19, UInt64 = 20, UInt64Nullable = 21, Single = 22, SingleNullable = 23, Double = 24, DoubleNullable = 25, DateTime = 26, DateTimeNullable = 27, DateTimeOffset = 28, DateTimeOffsetNullable = 29, Decimal = 30, DecimalNullable = 31, Guid = 32, GuidNullable = 33, TimeSpan = 34, TimeSpanNullable = 35, BigInteger = 36, BigIntegerNullable = 37, Uri = 38, String = 39, Bytes = 40, DBNull = 41 } internal class TypeInformation { public Type Type { get; set; } public PrimitiveTypeCode TypeCode { get; set; } } internal enum ParseResult { None = 0, Success = 1, Overflow = 2, Invalid = 3 } internal static class ConvertUtils { private static readonly Dictionary<Type, PrimitiveTypeCode> TypeCodeMap = new Dictionary<Type, PrimitiveTypeCode> { { typeof(char), PrimitiveTypeCode.Char }, { typeof(char?), PrimitiveTypeCode.CharNullable }, { typeof(bool), PrimitiveTypeCode.Boolean }, { typeof(bool?), PrimitiveTypeCode.BooleanNullable }, { typeof(sbyte), PrimitiveTypeCode.SByte }, { typeof(sbyte?), PrimitiveTypeCode.SByteNullable }, { typeof(short), PrimitiveTypeCode.Int16 }, { typeof(short?), PrimitiveTypeCode.Int16Nullable }, { typeof(ushort), PrimitiveTypeCode.UInt16 }, { typeof(ushort?), PrimitiveTypeCode.UInt16Nullable }, { typeof(int), PrimitiveTypeCode.Int32 }, { typeof(int?), PrimitiveTypeCode.Int32Nullable }, { typeof(byte), PrimitiveTypeCode.Byte }, { typeof(byte?), PrimitiveTypeCode.ByteNullable }, { typeof(uint), PrimitiveTypeCode.UInt32 }, { typeof(uint?), PrimitiveTypeCode.UInt32Nullable }, { typeof(long), PrimitiveTypeCode.Int64 }, { typeof(long?), PrimitiveTypeCode.Int64Nullable }, { typeof(ulong), PrimitiveTypeCode.UInt64 }, { typeof(ulong?), PrimitiveTypeCode.UInt64Nullable }, { typeof(float), PrimitiveTypeCode.Single }, { typeof(float?), PrimitiveTypeCode.SingleNullable }, { typeof(double), PrimitiveTypeCode.Double }, { typeof(double?), PrimitiveTypeCode.DoubleNullable }, { typeof(DateTime), PrimitiveTypeCode.DateTime }, { typeof(DateTime?), PrimitiveTypeCode.DateTimeNullable }, #if HAVE_DATE_TIME_OFFSET { typeof(DateTimeOffset), PrimitiveTypeCode.DateTimeOffset }, { typeof(DateTimeOffset?), PrimitiveTypeCode.DateTimeOffsetNullable }, #endif { typeof(decimal), PrimitiveTypeCode.Decimal }, { typeof(decimal?), PrimitiveTypeCode.DecimalNullable }, { typeof(Guid), PrimitiveTypeCode.Guid }, { typeof(Guid?), PrimitiveTypeCode.GuidNullable }, { typeof(TimeSpan), PrimitiveTypeCode.TimeSpan }, { typeof(TimeSpan?), PrimitiveTypeCode.TimeSpanNullable }, #if HAVE_BIG_INTEGER { typeof(BigInteger), PrimitiveTypeCode.BigInteger }, { typeof(BigInteger?), PrimitiveTypeCode.BigIntegerNullable }, #endif { typeof(Uri), PrimitiveTypeCode.Uri }, { typeof(string), PrimitiveTypeCode.String }, { typeof(byte[]), PrimitiveTypeCode.Bytes }, #if HAVE_ADO_NET { typeof(DBNull), PrimitiveTypeCode.DBNull } #endif }; #if HAVE_ICONVERTIBLE private static readonly TypeInformation[] PrimitiveTypeCodes = { // need all of these. lookup against the index with TypeCode value new TypeInformation { Type = typeof(object), TypeCode = PrimitiveTypeCode.Empty }, new TypeInformation { Type = typeof(object), TypeCode = PrimitiveTypeCode.Object }, new TypeInformation { Type = typeof(object), TypeCode = PrimitiveTypeCode.DBNull }, new TypeInformation { Type = typeof(bool), TypeCode = PrimitiveTypeCode.Boolean }, new TypeInformation { Type = typeof(char), TypeCode = PrimitiveTypeCode.Char }, new TypeInformation { Type = typeof(sbyte), TypeCode = PrimitiveTypeCode.SByte }, new TypeInformation { Type = typeof(byte), TypeCode = PrimitiveTypeCode.Byte }, new TypeInformation { Type = typeof(short), TypeCode = PrimitiveTypeCode.Int16 }, new TypeInformation { Type = typeof(ushort), TypeCode = PrimitiveTypeCode.UInt16 }, new TypeInformation { Type = typeof(int), TypeCode = PrimitiveTypeCode.Int32 }, new TypeInformation { Type = typeof(uint), TypeCode = PrimitiveTypeCode.UInt32 }, new TypeInformation { Type = typeof(long), TypeCode = PrimitiveTypeCode.Int64 }, new TypeInformation { Type = typeof(ulong), TypeCode = PrimitiveTypeCode.UInt64 }, new TypeInformation { Type = typeof(float), TypeCode = PrimitiveTypeCode.Single }, new TypeInformation { Type = typeof(double), TypeCode = PrimitiveTypeCode.Double }, new TypeInformation { Type = typeof(decimal), TypeCode = PrimitiveTypeCode.Decimal }, new TypeInformation { Type = typeof(DateTime), TypeCode = PrimitiveTypeCode.DateTime }, new TypeInformation { Type = typeof(object), TypeCode = PrimitiveTypeCode.Empty }, // no 17 in TypeCode for some reason new TypeInformation { Type = typeof(string), TypeCode = PrimitiveTypeCode.String } }; #endif public static PrimitiveTypeCode GetTypeCode(Type t) { bool isEnum; return GetTypeCode(t, out isEnum); } public static PrimitiveTypeCode GetTypeCode(Type t, out bool isEnum) { PrimitiveTypeCode typeCode; if (TypeCodeMap.TryGetValue(t, out typeCode)) { isEnum = false; return typeCode; } if (t.IsEnum()) { isEnum = true; return GetTypeCode(Enum.GetUnderlyingType(t)); } // performance? if (ReflectionUtils.IsNullableType(t)) { Type nonNullable = Nullable.GetUnderlyingType(t); if (nonNullable.IsEnum()) { Type nullableUnderlyingType = typeof(Nullable<>).MakeGenericType(Enum.GetUnderlyingType(nonNullable)); isEnum = true; return GetTypeCode(nullableUnderlyingType); } } isEnum = false; return PrimitiveTypeCode.Object; } #if HAVE_ICONVERTIBLE public static TypeInformation GetTypeInformation(IConvertible convertable) { TypeInformation typeInformation = PrimitiveTypeCodes[(int)convertable.GetTypeCode()]; return typeInformation; } #endif public static bool IsConvertible(Type t) { #if HAVE_ICONVERTIBLE return typeof(IConvertible).IsAssignableFrom(t); #else return ( t == typeof(bool) || t == typeof(byte) || t == typeof(char) || t == typeof(DateTime) || t == typeof(decimal) || t == typeof(double) || t == typeof(short) || t == typeof(int) || t == typeof(long) || t == typeof(sbyte) || t == typeof(float) || t == typeof(string) || t == typeof(ushort) || t == typeof(uint) || t == typeof(ulong) || t.IsEnum()); #endif } public static TimeSpan ParseTimeSpan(string input) { #if HAVE_TIME_SPAN_PARSE_WITH_CULTURE return TimeSpan.Parse(input, CultureInfo.InvariantCulture); #else return TimeSpan.Parse(input); #endif } internal struct TypeConvertKey : IEquatable<TypeConvertKey> { private readonly Type _initialType; private readonly Type _targetType; public Type InitialType { get { return _initialType; } } public Type TargetType { get { return _targetType; } } public TypeConvertKey(Type initialType, Type targetType) { _initialType = initialType; _targetType = targetType; } public override int GetHashCode() { return _initialType.GetHashCode() ^ _targetType.GetHashCode(); } public override bool Equals(object obj) { if (!(obj is TypeConvertKey)) { return false; } return Equals((TypeConvertKey)obj); } public bool Equals(TypeConvertKey other) { return (_initialType == other._initialType && _targetType == other._targetType); } } private static readonly ThreadSafeStore<TypeConvertKey, Func<object, object>> CastConverters = new ThreadSafeStore<TypeConvertKey, Func<object, object>>(CreateCastConverter); private static Func<object, object> CreateCastConverter(TypeConvertKey t) { MethodInfo castMethodInfo = t.TargetType.GetMethod("op_Implicit", new[] { t.InitialType }); if (castMethodInfo == null) { castMethodInfo = t.TargetType.GetMethod("op_Explicit", new[] { t.InitialType }); } if (castMethodInfo == null) { return null; } MethodCall<object, object> call = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(castMethodInfo); return o => call(null, o); } #if HAVE_BIG_INTEGER internal static BigInteger ToBigInteger(object value) { if (value is BigInteger) { return (BigInteger)value; } string s = value as string; if (s != null) { return BigInteger.Parse(s, CultureInfo.InvariantCulture); } if (value is float) { return new BigInteger((float)value); } if (value is double) { return new BigInteger((double)value); } if (value is decimal) { return new BigInteger((decimal)value); } if (value is int) { return new BigInteger((int)value); } if (value is long) { return new BigInteger((long)value); } if (value is uint) { return new BigInteger((uint)value); } if (value is ulong) { return new BigInteger((ulong)value); } byte[] bytes = value as byte[]; if (bytes != null) { return new BigInteger(bytes); } throw new InvalidCastException("Cannot convert {0} to BigInteger.".FormatWith(CultureInfo.InvariantCulture, value.GetType())); } public static object FromBigInteger(BigInteger i, Type targetType) { if (targetType == typeof(decimal)) { return (decimal)i; } if (targetType == typeof(double)) { return (double)i; } if (targetType == typeof(float)) { return (float)i; } if (targetType == typeof(ulong)) { return (ulong)i; } if (targetType == typeof(bool)) { return i != 0; } try { return System.Convert.ChangeType((long)i, targetType, CultureInfo.InvariantCulture); } catch (Exception ex) { throw new InvalidOperationException("Can not convert from BigInteger to {0}.".FormatWith(CultureInfo.InvariantCulture, targetType), ex); } } #endif #region TryConvert internal enum ConvertResult { Success = 0, CannotConvertNull = 1, NotInstantiableType = 2, NoValidConversion = 3 } public static object Convert(object initialValue, CultureInfo culture, Type targetType) { object value; switch (TryConvertInternal(initialValue, culture, targetType, out value)) { case ConvertResult.Success: return value; case ConvertResult.CannotConvertNull: throw new Exception("Can not convert null {0} into non-nullable {1}.".FormatWith(CultureInfo.InvariantCulture, initialValue.GetType(), targetType)); case ConvertResult.NotInstantiableType: throw new ArgumentException("Target type {0} is not a value type or a non-abstract class.".FormatWith(CultureInfo.InvariantCulture, targetType), nameof(targetType)); case ConvertResult.NoValidConversion: throw new InvalidOperationException("Can not convert from {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, initialValue.GetType(), targetType)); default: throw new InvalidOperationException("Unexpected conversion result."); } } private static bool TryConvert(object initialValue, CultureInfo culture, Type targetType, out object value) { try { if (TryConvertInternal(initialValue, culture, targetType, out value) == ConvertResult.Success) { return true; } value = null; return false; } catch { value = null; return false; } } private static ConvertResult TryConvertInternal(object initialValue, CultureInfo culture, Type targetType, out object value) { if (initialValue == null) { throw new ArgumentNullException(nameof(initialValue)); } if (ReflectionUtils.IsNullableType(targetType)) { targetType = Nullable.GetUnderlyingType(targetType); } Type initialType = initialValue.GetType(); if (targetType == initialType) { value = initialValue; return ConvertResult.Success; } // use Convert.ChangeType if both types are IConvertible if (ConvertUtils.IsConvertible(initialValue.GetType()) && ConvertUtils.IsConvertible(targetType)) { if (targetType.IsEnum()) { if (initialValue is string) { value = Enum.Parse(targetType, initialValue.ToString(), true); return ConvertResult.Success; } else if (IsInteger(initialValue)) { value = Enum.ToObject(targetType, initialValue); return ConvertResult.Success; } } value = System.Convert.ChangeType(initialValue, targetType, culture); return ConvertResult.Success; } #if HAVE_DATE_TIME_OFFSET if (initialValue is DateTime && targetType == typeof(DateTimeOffset)) { value = new DateTimeOffset((DateTime)initialValue); return ConvertResult.Success; } #endif byte[] bytes = initialValue as byte[]; if (bytes != null && targetType == typeof(Guid)) { value = new Guid(bytes); return ConvertResult.Success; } if (initialValue is Guid && targetType == typeof(byte[])) { value = ((Guid)initialValue).ToByteArray(); return ConvertResult.Success; } string s = initialValue as string; if (s != null) { if (targetType == typeof(Guid)) { value = new Guid(s); return ConvertResult.Success; } if (targetType == typeof(Uri)) { value = new Uri(s, UriKind.RelativeOrAbsolute); return ConvertResult.Success; } if (targetType == typeof(TimeSpan)) { value = ParseTimeSpan(s); return ConvertResult.Success; } if (targetType == typeof(byte[])) { value = System.Convert.FromBase64String(s); return ConvertResult.Success; } if (targetType == typeof(Version)) { Version result; if (VersionTryParse(s, out result)) { value = result; return ConvertResult.Success; } value = null; return ConvertResult.NoValidConversion; } if (typeof(Type).IsAssignableFrom(targetType)) { value = Type.GetType(s, true); return ConvertResult.Success; } } #if HAVE_BIG_INTEGER if (targetType == typeof(BigInteger)) { value = ToBigInteger(initialValue); return ConvertResult.Success; } if (initialValue is BigInteger) { value = FromBigInteger((BigInteger)initialValue, targetType); return ConvertResult.Success; } #endif #if HAVE_TYPE_DESCRIPTOR // see if source or target types have a TypeConverter that converts between the two TypeConverter toConverter = TypeDescriptor.GetConverter(initialType); if (toConverter != null && toConverter.CanConvertTo(targetType)) { value = toConverter.ConvertTo(null, culture, initialValue, targetType); return ConvertResult.Success; } TypeConverter fromConverter = TypeDescriptor.GetConverter(targetType); if (fromConverter != null && fromConverter.CanConvertFrom(initialType)) { value = fromConverter.ConvertFrom(null, culture, initialValue); return ConvertResult.Success; } #endif #if HAVE_ADO_NET // handle DBNull and INullable if (initialValue == DBNull.Value) { if (ReflectionUtils.IsNullable(targetType)) { value = EnsureTypeAssignable(null, initialType, targetType); return ConvertResult.Success; } // cannot convert null to non-nullable value = null; return ConvertResult.CannotConvertNull; } #endif #if HAVE_ADO_NET INullable nullable = initialValue as INullable; if (nullable != null) { value = EnsureTypeAssignable(ToValue(nullable), initialType, targetType); return ConvertResult.Success; } #endif if (targetType.IsInterface() || targetType.IsGenericTypeDefinition() || targetType.IsAbstract()) { value = null; return ConvertResult.NotInstantiableType; } value = null; return ConvertResult.NoValidConversion; } #endregion #region ConvertOrCast /// <summary> /// Converts the value to the specified type. If the value is unable to be converted, the /// value is checked whether it assignable to the specified type. /// </summary> /// <param name="initialValue">The value to convert.</param> /// <param name="culture">The culture to use when converting.</param> /// <param name="targetType">The type to convert or cast the value to.</param> /// <returns> /// The converted type. If conversion was unsuccessful, the initial value /// is returned if assignable to the target type. /// </returns> public static object ConvertOrCast(object initialValue, CultureInfo culture, Type targetType) { object convertedValue; if (targetType == typeof(object)) { return initialValue; } if (initialValue == null && ReflectionUtils.IsNullable(targetType)) { return null; } if (TryConvert(initialValue, culture, targetType, out convertedValue)) { return convertedValue; } return EnsureTypeAssignable(initialValue, ReflectionUtils.GetObjectType(initialValue), targetType); } #endregion private static object EnsureTypeAssignable(object value, Type initialType, Type targetType) { Type valueType = value?.GetType(); if (value != null) { if (targetType.IsAssignableFrom(valueType)) { return value; } Func<object, object> castConverter = CastConverters.Get(new TypeConvertKey(valueType, targetType)); if (castConverter != null) { return castConverter(value); } } else { if (ReflectionUtils.IsNullable(targetType)) { return null; } } throw new ArgumentException("Could not cast or convert from {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, initialType?.ToString() ?? "{null}", targetType)); } #if HAVE_ADO_NET public static object ToValue(INullable nullableValue) { if (nullableValue == null) { return null; } else if (nullableValue is SqlInt32) { return ToValue((SqlInt32)nullableValue); } else if (nullableValue is SqlInt64) { return ToValue((SqlInt64)nullableValue); } else if (nullableValue is SqlBoolean) { return ToValue((SqlBoolean)nullableValue); } else if (nullableValue is SqlString) { return ToValue((SqlString)nullableValue); } else if (nullableValue is SqlDateTime) { return ToValue((SqlDateTime)nullableValue); } throw new ArgumentException("Unsupported INullable type: {0}".FormatWith(CultureInfo.InvariantCulture, nullableValue.GetType())); } #endif public static bool VersionTryParse(string input, out Version result) { #if HAVE_VERSION_TRY_PARSE return Version.TryParse(input, out result); #else // improve failure performance with regex? try { result = new Version(input); return true; } catch { result = null; return false; } #endif } public static bool IsInteger(object value) { switch (GetTypeCode(value.GetType())) { case PrimitiveTypeCode.SByte: case PrimitiveTypeCode.Byte: case PrimitiveTypeCode.Int16: case PrimitiveTypeCode.UInt16: case PrimitiveTypeCode.Int32: case PrimitiveTypeCode.UInt32: case PrimitiveTypeCode.Int64: case PrimitiveTypeCode.UInt64: return true; default: return false; } } public static ParseResult Int32TryParse(char[] chars, int start, int length, out int value) { value = 0; if (length == 0) { return ParseResult.Invalid; } bool isNegative = (chars[start] == '-'); if (isNegative) { // text just a negative sign if (length == 1) { return ParseResult.Invalid; } start++; length--; } int end = start + length; // Int32.MaxValue and MinValue are 10 chars // Or is 10 chars and start is greater than two // Need to improve this! if (length > 10 || (length == 10 && chars[start] - '0' > 2)) { // invalid result takes precedence over overflow for (int i = start; i < end; i++) { int c = chars[i] - '0'; if (c < 0 || c > 9) { return ParseResult.Invalid; } } return ParseResult.Overflow; } for (int i = start; i < end; i++) { int c = chars[i] - '0'; if (c < 0 || c > 9) { return ParseResult.Invalid; } int newValue = (10 * value) - c; // overflow has caused the number to loop around if (newValue > value) { i++; // double check the rest of the string that there wasn't anything invalid // invalid result takes precedence over overflow result for (; i < end; i++) { c = chars[i] - '0'; if (c < 0 || c > 9) { return ParseResult.Invalid; } } return ParseResult.Overflow; } value = newValue; } // go from negative to positive to avoids overflow // negative can be slightly bigger than positive if (!isNegative) { // negative integer can be one bigger than positive if (value == int.MinValue) { return ParseResult.Overflow; } value = -value; } return ParseResult.Success; } public static ParseResult Int64TryParse(char[] chars, int start, int length, out long value) { value = 0; if (length == 0) { return ParseResult.Invalid; } bool isNegative = (chars[start] == '-'); if (isNegative) { // text just a negative sign if (length == 1) { return ParseResult.Invalid; } start++; length--; } int end = start + length; // Int64.MaxValue and MinValue are 19 chars if (length > 19) { // invalid result takes precedence over overflow for (int i = start; i < end; i++) { int c = chars[i] - '0'; if (c < 0 || c > 9) { return ParseResult.Invalid; } } return ParseResult.Overflow; } for (int i = start; i < end; i++) { int c = chars[i] - '0'; if (c < 0 || c > 9) { return ParseResult.Invalid; } long newValue = (10 * value) - c; // overflow has caused the number to loop around if (newValue > value) { i++; // double check the rest of the string that there wasn't anything invalid // invalid result takes precedence over overflow result for (; i < end; i++) { c = chars[i] - '0'; if (c < 0 || c > 9) { return ParseResult.Invalid; } } return ParseResult.Overflow; } value = newValue; } // go from negative to positive to avoids overflow // negative can be slightly bigger than positive if (!isNegative) { // negative integer can be one bigger than positive if (value == long.MinValue) { return ParseResult.Overflow; } value = -value; } return ParseResult.Success; } #if HAS_CUSTOM_DOUBLE_PARSE private static class IEEE754 { /// <summary> /// Exponents for both powers of 10 and 0.1 /// </summary> private static readonly int[] MultExp64Power10 = new int[] { 4, 7, 10, 14, 17, 20, 24, 27, 30, 34, 37, 40, 44, 47, 50 }; /// <summary> /// Normalized powers of 10 /// </summary> private static readonly ulong[] MultVal64Power10 = new ulong[] { 0xa000000000000000, 0xc800000000000000, 0xfa00000000000000, 0x9c40000000000000, 0xc350000000000000, 0xf424000000000000, 0x9896800000000000, 0xbebc200000000000, 0xee6b280000000000, 0x9502f90000000000, 0xba43b74000000000, 0xe8d4a51000000000, 0x9184e72a00000000, 0xb5e620f480000000, 0xe35fa931a0000000, }; /// <summary> /// Normalized powers of 0.1 /// </summary> private static readonly ulong[] MultVal64Power10Inv = new ulong[] { 0xcccccccccccccccd, 0xa3d70a3d70a3d70b, 0x83126e978d4fdf3c, 0xd1b71758e219652e, 0xa7c5ac471b478425, 0x8637bd05af6c69b7, 0xd6bf94d5e57a42be, 0xabcc77118461ceff, 0x89705f4136b4a599, 0xdbe6fecebdedd5c2, 0xafebff0bcb24ab02, 0x8cbccc096f5088cf, 0xe12e13424bb40e18, 0xb424dc35095cd813, 0x901d7cf73ab0acdc, }; /// <summary> /// Exponents for both powers of 10^16 and 0.1^16 /// </summary> private static readonly int[] MultExp64Power10By16 = new int[] { 54, 107, 160, 213, 266, 319, 373, 426, 479, 532, 585, 638, 691, 745, 798, 851, 904, 957, 1010, 1064, 1117, }; /// <summary> /// Normalized powers of 10^16 /// </summary> private static readonly ulong[] MultVal64Power10By16 = new ulong[] { 0x8e1bc9bf04000000, 0x9dc5ada82b70b59e, 0xaf298d050e4395d6, 0xc2781f49ffcfa6d4, 0xd7e77a8f87daf7fa, 0xefb3ab16c59b14a0, 0x850fadc09923329c, 0x93ba47c980e98cde, 0xa402b9c5a8d3a6e6, 0xb616a12b7fe617a8, 0xca28a291859bbf90, 0xe070f78d39275566, 0xf92e0c3537826140, 0x8a5296ffe33cc92c, 0x9991a6f3d6bf1762, 0xaa7eebfb9df9de8a, 0xbd49d14aa79dbc7e, 0xd226fc195c6a2f88, 0xe950df20247c83f8, 0x81842f29f2cce373, 0x8fcac257558ee4e2, }; /// <summary> /// Normalized powers of 0.1^16 /// </summary> private static readonly ulong[] MultVal64Power10By16Inv = new ulong[] { 0xe69594bec44de160, 0xcfb11ead453994c3, 0xbb127c53b17ec165, 0xa87fea27a539e9b3, 0x97c560ba6b0919b5, 0x88b402f7fd7553ab, 0xf64335bcf065d3a0, 0xddd0467c64bce4c4, 0xc7caba6e7c5382ed, 0xb3f4e093db73a0b7, 0xa21727db38cb0053, 0x91ff83775423cc29, 0x8380dea93da4bc82, 0xece53cec4a314f00, 0xd5605fcdcf32e217, 0xc0314325637a1978, 0xad1c8eab5ee43ba2, 0x9becce62836ac5b0, 0x8c71dcd9ba0b495c, 0xfd00b89747823938, 0xe3e27a444d8d991a, }; /// <summary> /// Packs <paramref name="val"/>*10^<paramref name="scale"/> as 64-bit floating point value according to IEEE 754 standard /// </summary> /// <param name="negative">Sign</param> /// <param name="val">Mantissa</param> /// <param name="scale">Exponent</param> /// <remarks> /// Adoption of native function NumberToDouble() from coreclr sources, /// see https://github.com/dotnet/coreclr/blob/master/src/classlibnative/bcltype/number.cpp#L451 /// </remarks> public static double PackDouble(bool negative, ulong val, int scale) { // handle zero value if (val == 0) { return negative ? -0.0 : 0.0; } // normalize the mantissa int exp = 64; if ((val & 0xFFFFFFFF00000000) == 0) { val <<= 32; exp -= 32; } if ((val & 0xFFFF000000000000) == 0) { val <<= 16; exp -= 16; } if ((val & 0xFF00000000000000) == 0) { val <<= 8; exp -= 8; } if ((val & 0xF000000000000000) == 0) { val <<= 4; exp -= 4; } if ((val & 0xC000000000000000) == 0) { val <<= 2; exp -= 2; } if ((val & 0x8000000000000000) == 0) { val <<= 1; exp -= 1; } if (scale < 0) { scale = -scale; // check scale bounds if (scale >= 22 * 16) { // underflow return negative ? -0.0 : 0.0; } // perform scaling int index = scale & 15; if (index != 0) { exp -= MultExp64Power10[index - 1] - 1; val = Mul64Lossy(val, MultVal64Power10Inv[index - 1], ref exp); } index = scale >> 4; if (index != 0) { exp -= MultExp64Power10By16[index - 1] - 1; val = Mul64Lossy(val, MultVal64Power10By16Inv[index - 1], ref exp); } } else { // check scale bounds if (scale >= 22 * 16) { // overflow return negative ? double.NegativeInfinity : double.PositiveInfinity; } // perform scaling int index = scale & 15; if (index != 0) { exp += MultExp64Power10[index - 1]; val = Mul64Lossy(val, MultVal64Power10[index - 1], ref exp); } index = scale >> 4; if (index != 0) { exp += MultExp64Power10By16[index - 1]; val = Mul64Lossy(val, MultVal64Power10By16[index - 1], ref exp); } } // round & scale down if ((val & (1 << 10)) != 0) { // IEEE round to even ulong tmp = val + ((1UL << 10) - 1 + ((val >> 11) & 1)); if (tmp < val) { // overflow tmp = (tmp >> 1) | 0x8000000000000000; exp++; } val = tmp; } // return the exponent to a biased state exp += 0x3FE; // handle overflow, underflow, "Epsilon - 1/2 Epsilon", denormalized, and the normal case if (exp <= 0) { if (exp == -52 && (val >= 0x8000000000000058)) { // round X where {Epsilon > X >= 2.470328229206232730000000E-324} up to Epsilon (instead of down to zero) val = 0x0000000000000001; } else if (exp <= -52) { // underflow val = 0; } else { // denormalized value val >>= (-exp + 12); } } else if (exp >= 0x7FF) { // overflow val = 0x7FF0000000000000; } else { // normal positive exponent case val = ((ulong)exp << 52) | ((val >> 11) & 0x000FFFFFFFFFFFFF); } // apply sign if (negative) { val |= 0x8000000000000000; } return BitConverter.Int64BitsToDouble((long)val); } private static ulong Mul64Lossy(ulong a, ulong b, ref int exp) { ulong a_hi = (a >> 32); uint a_lo = (uint)a; ulong b_hi = (b >> 32); uint b_lo = (uint)b; ulong result = a_hi * b_hi; // save some multiplications if lo-parts aren't big enough to produce carry // (hi-parts will be always big enough, since a and b are normalized) if ((b_lo & 0xFFFF0000) != 0) { result += (a_hi * b_lo) >> 32; } if ((a_lo & 0xFFFF0000) != 0) { result += (a_lo * b_hi) >> 32; } // normalize if ((result & 0x8000000000000000) == 0) { result <<= 1; exp--; } return result; } } public static ParseResult DoubleTryParse(char[] chars, int start, int length, out double value) { value = 0; if (length == 0) { return ParseResult.Invalid; } bool isNegative = (chars[start] == '-'); if (isNegative) { // text just a negative sign if (length == 1) { return ParseResult.Invalid; } start++; length--; } int i = start; int end = start + length; int numDecimalStart = end; int numDecimalEnd = end; int exponent = 0; ulong mantissa = 0UL; int mantissaDigits = 0; int exponentFromMantissa = 0; for (; i < end; i++) { char c = chars[i]; switch (c) { case '.': if (i == start) { return ParseResult.Invalid; } if (i + 1 == end) { return ParseResult.Invalid; } if (numDecimalStart != end) { // multiple decimal points return ParseResult.Invalid; } numDecimalStart = i + 1; break; case 'e': case 'E': if (i == start) { return ParseResult.Invalid; } if (i == numDecimalStart) { // E follows decimal point return ParseResult.Invalid; } i++; if (i == end) { return ParseResult.Invalid; } if (numDecimalStart < end) { numDecimalEnd = i - 1; } c = chars[i]; bool exponentNegative = false; switch (c) { case '-': exponentNegative = true; i++; break; case '+': i++; break; } // parse 3 digit for (; i < end; i++) { c = chars[i]; if (c < '0' || c > '9') { return ParseResult.Invalid; } int newExponent = (10 * exponent) + (c - '0'); // stops updating exponent when overflowing if (exponent < newExponent) { exponent = newExponent; } } if (exponentNegative) { exponent = -exponent; } break; default: if (c < '0' || c > '9') { return ParseResult.Invalid; } if (i == start && c == '0') { i++; if (i != end) { c = chars[i]; if (c == '.') { goto case '.'; } if (c == 'e' || c == 'E') { goto case 'E'; } return ParseResult.Invalid; } } if (mantissaDigits < 19) { mantissa = (10 * mantissa) + (ulong)(c - '0'); if (mantissa > 0) { ++mantissaDigits; } } else { ++exponentFromMantissa; } break; } } exponent += exponentFromMantissa; // correct the decimal point exponent -= (numDecimalEnd - numDecimalStart); value = IEEE754.PackDouble(isNegative, mantissa, exponent); return double.IsInfinity(value) ? ParseResult.Overflow : ParseResult.Success; } #endif public static ParseResult DecimalTryParse(char[] chars, int start, int length, out decimal value) { value = 0M; const decimal decimalMaxValueHi28 = 7922816251426433759354395033M; const ulong decimalMaxValueHi19 = 7922816251426433759UL; const ulong decimalMaxValueLo9 = 354395033UL; const char decimalMaxValueLo1 = '5'; if (length == 0) { return ParseResult.Invalid; } bool isNegative = (chars[start] == '-'); if (isNegative) { // text just a negative sign if (length == 1) { return ParseResult.Invalid; } start++; length--; } int i = start; int end = start + length; int numDecimalStart = end; int numDecimalEnd = end; int exponent = 0; ulong hi19 = 0UL; ulong lo10 = 0UL; int mantissaDigits = 0; int exponentFromMantissa = 0; bool? roundUp = null; bool? storeOnly28Digits = null; for (; i < end; i++) { char c = chars[i]; switch (c) { case '.': if (i == start) { return ParseResult.Invalid; } if (i + 1 == end) { return ParseResult.Invalid; } if (numDecimalStart != end) { // multiple decimal points return ParseResult.Invalid; } numDecimalStart = i + 1; break; case 'e': case 'E': if (i == start) { return ParseResult.Invalid; } if (i == numDecimalStart) { // E follows decimal point return ParseResult.Invalid; } i++; if (i == end) { return ParseResult.Invalid; } if (numDecimalStart < end) { numDecimalEnd = i - 1; } c = chars[i]; bool exponentNegative = false; switch (c) { case '-': exponentNegative = true; i++; break; case '+': i++; break; } // parse 3 digit for (; i < end; i++) { c = chars[i]; if (c < '0' || c > '9') { return ParseResult.Invalid; } int newExponent = (10 * exponent) + (c - '0'); // stops updating exponent when overflowing if (exponent < newExponent) { exponent = newExponent; } } if (exponentNegative) { exponent = -exponent; } break; default: if (c < '0' || c > '9') { return ParseResult.Invalid; } if (i == start && c == '0') { i++; if (i != end) { c = chars[i]; if (c == '.') { goto case '.'; } if (c == 'e' || c == 'E') { goto case 'E'; } return ParseResult.Invalid; } } if (mantissaDigits < 29 && (mantissaDigits != 28 || !(storeOnly28Digits ?? (storeOnly28Digits = (hi19 > decimalMaxValueHi19 || (hi19 == decimalMaxValueHi19 && (lo10 > decimalMaxValueLo9 || (lo10 == decimalMaxValueLo9 && c > decimalMaxValueLo1))))).GetValueOrDefault()))) { if (mantissaDigits < 19) { hi19 = (hi19 * 10UL) + (ulong)(c - '0'); } else { lo10 = (lo10 * 10UL) + (ulong)(c - '0'); } ++mantissaDigits; } else { if (!roundUp.HasValue) { roundUp = c >= '5'; } ++exponentFromMantissa; } break; } } exponent += exponentFromMantissa; // correct the decimal point exponent -= (numDecimalEnd - numDecimalStart); if (mantissaDigits <= 19) { value = hi19; } else { value = (hi19 / new decimal(1, 0, 0, false, (byte)(mantissaDigits - 19))) + lo10; } if (exponent > 0) { mantissaDigits += exponent; if (mantissaDigits > 29) { return ParseResult.Overflow; } if (mantissaDigits == 29) { if (exponent > 1) { value /= new decimal(1, 0, 0, false, (byte)(exponent - 1)); if (value > decimalMaxValueHi28) { return ParseResult.Overflow; } } value *= 10M; } else { value /= new decimal(1, 0, 0, false, (byte)exponent); } } else { if (roundUp == true && exponent >= -28) { ++value; } if (exponent < 0) { if (mantissaDigits + exponent + 28 <= 0) { value = isNegative ? -0M : 0M; return ParseResult.Success; } if (exponent >= -28) { value *= new decimal(1, 0, 0, false, (byte)(-exponent)); } else { value /= 1e28M; value *= new decimal(1, 0, 0, false, (byte)(-exponent - 28)); } } } if (isNegative) { value = -value; } return ParseResult.Success; } public static bool TryConvertGuid(string s, out Guid g) { // GUID has to have format 00000000-0000-0000-0000-000000000000 #if !HAVE_GUID_TRY_PARSE if (s == null) { throw new ArgumentNullException("s"); } Regex format = new Regex("^[A-Fa-f0-9]{8}-([A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}$"); Match match = format.Match(s); if (match.Success) { g = new Guid(s); return true; } g = Guid.Empty; return false; #else return Guid.TryParseExact(s, "D", out g); #endif } public static bool TryHexTextToInt(char[] text, int start, int end, out int value) { value = 0; for (int i = start; i < end; i++) { char ch = text[i]; int chValue; if (ch <= 57 && ch >= 48) { chValue = ch - 48; } else if (ch <= 70 && ch >= 65) { chValue = ch - 55; } else if (ch <= 102 && ch >= 97) { chValue = ch - 87; } else { value = 0; return false; } value += chValue << ((end - 1 - i) * 4); } return true; } } }
// Copyright 2007 MbUnit Project - http://www.mbunit.com/ // Portions Copyright 2000-2004 Jonathan De Halleux, Jamie Cansdale // // 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.Reflection; using System.Reflection.Emit; using MbUnit.Framework; using MbUnit.Framework.Kernel.Utilities; using Mono.Cecil; using Mono.Cecil.Cil; namespace MbUnit.Plugin.CecilInstrumentation { /// <summary> /// Builds methods in a dynamic assembly from Cecil definitions. /// </summary> internal sealed class DynamicMethodBuilder { private readonly DynamicAssemblyBuilder outer; private readonly Dictionary<VariableDefinition, LocalBuilder> locals; private readonly Dictionary<Instruction, Block> actions; private readonly Dictionary<Instruction, Label> labels; private MethodBase method; private ILGenerator generator; public DynamicMethodBuilder(DynamicAssemblyBuilder outer) { this.outer = outer; locals = new Dictionary<VariableDefinition, LocalBuilder>(); actions = new Dictionary<Instruction, Block>(); labels = new Dictionary<Instruction, Label>(); } public void BuildIL(MethodBase method, ILGenerator generator, Mono.Cecil.Cil.MethodBody body) { try { this.method = method; this.generator = generator; DeclareLocals(body.Variables); MarkExceptionHandlers(body.ExceptionHandlers); CreateLabels(body); EmitInstructions(body); } finally { this.method = null; this.generator = null; locals.Clear(); actions.Clear(); labels.Clear(); } } private void DeclareLocals(VariableDefinitionCollection variableDefinitions) { foreach (VariableDefinition variableDefinition in variableDefinitions) { Type type = outer.ResolveType(variableDefinition.VariableType); LocalBuilder localBuilder = generator.DeclareLocal(type); locals.Add(variableDefinition, localBuilder); } } private void MarkExceptionHandlers(ExceptionHandlerCollection exceptionHandlers) { foreach (ExceptionHandler exceptionHandler in exceptionHandlers) { AddActionAfter(exceptionHandler.TryStart, delegate { generator.BeginExceptionBlock(); }); if (exceptionHandler.Type == ExceptionHandlerType.Filter) { AddActionAfter(exceptionHandler.FilterStart, delegate { generator.BeginExceptFilterBlock(); }); } AddActionAfter(exceptionHandler.HandlerStart, delegate { switch (exceptionHandler.Type) { case ExceptionHandlerType.Catch: generator.BeginCatchBlock(outer.ResolveType(exceptionHandler.CatchType)); break; case ExceptionHandlerType.Fault: generator.BeginFaultBlock(); break; case ExceptionHandlerType.Finally: generator.BeginFinallyBlock(); break; } }); AddActionBefore(exceptionHandler.HandlerEnd, delegate { generator.EndExceptionBlock(); }); } } private void CreateLabels(Mono.Cecil.Cil.MethodBody body) { foreach (Instruction instruction in body.Instructions) { labels.Add(instruction, generator.DefineLabel()); } } private void EmitInstructions(Mono.Cecil.Cil.MethodBody body) { // This loop is loosely based on some code in Mono.Cecil // that clones a method body. foreach (Instruction instruction in body.Instructions) { RunActions(instruction); generator.MarkLabel(labels[instruction]); switch (instruction.OpCode.OperandType) { case Mono.Cecil.Cil.OperandType.InlineParam: case Mono.Cecil.Cil.OperandType.ShortInlineParam: generator.Emit(MapOpCode(instruction.OpCode), MapParameter((ParameterDefinition)instruction.Operand)); break; case Mono.Cecil.Cil.OperandType.InlineVar: case Mono.Cecil.Cil.OperandType.ShortInlineVar: generator.Emit(MapOpCode(instruction.OpCode), MapLocal((VariableDefinition)instruction.Operand)); break; case Mono.Cecil.Cil.OperandType.InlineField: generator.Emit(MapOpCode(instruction.OpCode), MapField((FieldReference)instruction.Operand)); break; case Mono.Cecil.Cil.OperandType.InlineMethod: EmitWithMethodOperand(MapOpCode(instruction.OpCode), MapMethod((MethodReference)instruction.Operand)); break; case Mono.Cecil.Cil.OperandType.InlineType: generator.Emit(MapOpCode(instruction.OpCode), MapType((TypeReference)instruction.Operand)); break; case Mono.Cecil.Cil.OperandType.InlineTok: if (instruction.Operand is TypeReference) generator.Emit(MapOpCode(instruction.OpCode), MapType((TypeReference)instruction.Operand)); else if (instruction.Operand is FieldReference) generator.Emit(MapOpCode(instruction.OpCode), MapField((FieldReference)instruction.Operand)); else if (instruction.Operand is MethodReference) EmitWithMethodOperand(MapOpCode(instruction.OpCode), MapMethod((MethodReference)instruction.Operand)); else throw new NotSupportedException(string.Format("Unexpected token operand type: {0}.", instruction.Operand.GetType())); break; case Mono.Cecil.Cil.OperandType.ShortInlineI: generator.Emit(MapOpCode(instruction.OpCode), (sbyte) instruction.Operand); break; case Mono.Cecil.Cil.OperandType.InlineI: generator.Emit(MapOpCode(instruction.OpCode), (int)instruction.Operand); break; case Mono.Cecil.Cil.OperandType.InlineI8: generator.Emit(MapOpCode(instruction.OpCode), (long) instruction.Operand); break; case Mono.Cecil.Cil.OperandType.ShortInlineR: generator.Emit(MapOpCode(instruction.OpCode), (float) instruction.Operand); break; case Mono.Cecil.Cil.OperandType.InlineR: generator.Emit(MapOpCode(instruction.OpCode), (double) instruction.Operand); break; case Mono.Cecil.Cil.OperandType.InlineString: generator.Emit(MapOpCode(instruction.OpCode), (string) instruction.Operand); break; case Mono.Cecil.Cil.OperandType.InlineSwitch: generator.Emit(MapOpCode(instruction.OpCode), MapLabels((Instruction[])instruction.Operand)); break; case Mono.Cecil.Cil.OperandType.InlineSig: generator.Emit(MapOpCode(instruction.OpCode), MapSignature((CallSite)instruction.Operand)); break; case Mono.Cecil.Cil.OperandType.InlineNone: generator.Emit(MapOpCode(instruction.OpCode)); break; case Mono.Cecil.Cil.OperandType.ShortInlineBrTarget: case Mono.Cecil.Cil.OperandType.InlineBrTarget: generator.Emit(MapOpCode(instruction.OpCode), MapLabel((Instruction)instruction.Operand)); break; case Mono.Cecil.Cil.OperandType.InlinePhi: default: throw new NotSupportedException(string.Format("Unexpected operand type: {0}.", instruction.OpCode.OperandType)); } } } private void EmitWithMethodOperand(System.Reflection.Emit.OpCode opcode, MethodBase methodBase) { MethodInfo methodInfo = methodBase as MethodInfo; if (methodInfo != null) generator.Emit(opcode, methodInfo); else generator.Emit(opcode, (ConstructorInfo)methodBase); } private void AddActionBefore(Instruction instruction, Block block) { Block oldBlock; if (actions.TryGetValue(instruction, out oldBlock)) actions[instruction] = (Block) Delegate.Combine(block, oldBlock); else actions.Add(instruction, block); } private void AddActionAfter(Instruction instruction, Block block) { Block oldBlock; if (actions.TryGetValue(instruction, out oldBlock)) actions[instruction] = (Block)Delegate.Combine(oldBlock, block); else actions.Add(instruction, block); } private void RunActions(Instruction instruction) { Block block; if (actions.TryGetValue(instruction, out block)) block(); } private int MapParameter(ParameterDefinition parameterDefinition) { return parameterDefinition.Sequence; } private LocalBuilder MapLocal(VariableDefinition variableDefinition) { return locals[variableDefinition]; } private MethodBase MapMethod(MethodReference methodReference) { return outer.ResolveMethod(methodReference); } private FieldInfo MapField(FieldReference fieldReference) { return outer.ResolveField(fieldReference); } private Type MapType(TypeReference typeReference) { return outer.ResolveType(typeReference); } private Type MapReturnType(MethodReturnType returnType) { return outer.ResolveReturnType(returnType); } private SignatureHelper MapSignature(CallSite signature) { Type returnType = MapReturnType(signature.ReturnType); // TODO... SignatureHelper helper; switch (signature.MetadataToken.TokenType) { /* case TokenType.Method: helper = SignatureHelper.GetMethodSigHelper(module, (System.Reflection.CallingConventions) signature.CallingConvention, returnType); break; case TokenType.Field: helper = SignatureHelper.GetFieldSigHelper(module); break; case TokenType.Param: helper = SignatureHelper.GetLocalVarSigHelper(module); break; case TokenType.Property: helper = SignatureHelper.GetPropertySigHelper(module, returnType, parameterTypes); break; */ default: throw new NotSupportedException(string.Format("Unexpected metadata token type: {0}.", signature.MetadataToken.TokenType)); } return helper; } private Label MapLabel(Instruction instruction) { return labels[instruction]; } private Label[] MapLabels(Instruction[] instructions) { return GenericUtils.ConvertAllToArray<Instruction, Label>(instructions, MapLabel); } private static System.Reflection.Emit.OpCode MapOpCode(Mono.Cecil.Cil.OpCode cecilOpcode) { switch (cecilOpcode.Code) { case Code.Nop: return System.Reflection.Emit.OpCodes.Nop; case Code.Break: return System.Reflection.Emit.OpCodes.Break; case Code.Ldarg_0: return System.Reflection.Emit.OpCodes.Ldarg_0; case Code.Ldarg_1: return System.Reflection.Emit.OpCodes.Ldarg_1; case Code.Ldarg_2: return System.Reflection.Emit.OpCodes.Ldarg_2; case Code.Ldarg_3: return System.Reflection.Emit.OpCodes.Ldarg_3; case Code.Ldloc_0: return System.Reflection.Emit.OpCodes.Ldloc_0; case Code.Ldloc_1: return System.Reflection.Emit.OpCodes.Ldloc_1; case Code.Ldloc_2: return System.Reflection.Emit.OpCodes.Ldloc_2; case Code.Ldloc_3: return System.Reflection.Emit.OpCodes.Ldloc_3; case Code.Stloc_0: return System.Reflection.Emit.OpCodes.Stloc_0; case Code.Stloc_1: return System.Reflection.Emit.OpCodes.Stloc_1; case Code.Stloc_2: return System.Reflection.Emit.OpCodes.Stloc_2; case Code.Stloc_3: return System.Reflection.Emit.OpCodes.Stloc_3; case Code.Ldarg_S: return System.Reflection.Emit.OpCodes.Ldarg_S; case Code.Ldarga_S: return System.Reflection.Emit.OpCodes.Ldarga_S; case Code.Starg_S: return System.Reflection.Emit.OpCodes.Starg_S; case Code.Ldloc_S: return System.Reflection.Emit.OpCodes.Ldloc_S; case Code.Ldloca_S: return System.Reflection.Emit.OpCodes.Ldloca_S; case Code.Stloc_S: return System.Reflection.Emit.OpCodes.Stloc_S; case Code.Ldnull: return System.Reflection.Emit.OpCodes.Ldnull; case Code.Ldc_I4_M1: return System.Reflection.Emit.OpCodes.Ldc_I4_M1; case Code.Ldc_I4_0: return System.Reflection.Emit.OpCodes.Ldc_I4_0; case Code.Ldc_I4_1: return System.Reflection.Emit.OpCodes.Ldc_I4_1; case Code.Ldc_I4_2: return System.Reflection.Emit.OpCodes.Ldc_I4_2; case Code.Ldc_I4_3: return System.Reflection.Emit.OpCodes.Ldc_I4_3; case Code.Ldc_I4_4: return System.Reflection.Emit.OpCodes.Ldc_I4_4; case Code.Ldc_I4_5: return System.Reflection.Emit.OpCodes.Ldc_I4_5; case Code.Ldc_I4_6: return System.Reflection.Emit.OpCodes.Ldc_I4_6; case Code.Ldc_I4_7: return System.Reflection.Emit.OpCodes.Ldc_I4_7; case Code.Ldc_I4_8: return System.Reflection.Emit.OpCodes.Ldc_I4_8; case Code.Ldc_I4_S: return System.Reflection.Emit.OpCodes.Ldc_I4_S; case Code.Ldc_I4: return System.Reflection.Emit.OpCodes.Ldc_I4; case Code.Ldc_I8: return System.Reflection.Emit.OpCodes.Ldc_I8; case Code.Ldc_R4: return System.Reflection.Emit.OpCodes.Ldc_R4; case Code.Ldc_R8: return System.Reflection.Emit.OpCodes.Ldc_R8; case Code.Dup: return System.Reflection.Emit.OpCodes.Dup; case Code.Pop: return System.Reflection.Emit.OpCodes.Pop; case Code.Jmp: return System.Reflection.Emit.OpCodes.Jmp; case Code.Call: return System.Reflection.Emit.OpCodes.Call; case Code.Calli: return System.Reflection.Emit.OpCodes.Calli; case Code.Ret: return System.Reflection.Emit.OpCodes.Ret; case Code.Br_S: return System.Reflection.Emit.OpCodes.Br_S; case Code.Brfalse_S: return System.Reflection.Emit.OpCodes.Brfalse_S; case Code.Brtrue_S: return System.Reflection.Emit.OpCodes.Brtrue_S; case Code.Beq_S: return System.Reflection.Emit.OpCodes.Beq_S; case Code.Bge_S: return System.Reflection.Emit.OpCodes.Bge_S; case Code.Bgt_S: return System.Reflection.Emit.OpCodes.Bgt_S; case Code.Ble_S: return System.Reflection.Emit.OpCodes.Ble_S; case Code.Blt_S: return System.Reflection.Emit.OpCodes.Blt_S; case Code.Bne_Un_S: return System.Reflection.Emit.OpCodes.Bne_Un_S; case Code.Bge_Un_S: return System.Reflection.Emit.OpCodes.Bge_Un_S; case Code.Bgt_Un_S: return System.Reflection.Emit.OpCodes.Bgt_Un_S; case Code.Ble_Un_S: return System.Reflection.Emit.OpCodes.Ble_Un_S; case Code.Blt_Un_S: return System.Reflection.Emit.OpCodes.Blt_Un_S; case Code.Br: return System.Reflection.Emit.OpCodes.Br; case Code.Brfalse: return System.Reflection.Emit.OpCodes.Brfalse; case Code.Brtrue: return System.Reflection.Emit.OpCodes.Brtrue; case Code.Beq: return System.Reflection.Emit.OpCodes.Beq; case Code.Bge: return System.Reflection.Emit.OpCodes.Bge; case Code.Bgt: return System.Reflection.Emit.OpCodes.Bgt; case Code.Ble: return System.Reflection.Emit.OpCodes.Ble; case Code.Blt: return System.Reflection.Emit.OpCodes.Blt; case Code.Bne_Un: return System.Reflection.Emit.OpCodes.Bne_Un; case Code.Bge_Un: return System.Reflection.Emit.OpCodes.Bge_Un; case Code.Bgt_Un: return System.Reflection.Emit.OpCodes.Bgt_Un; case Code.Ble_Un: return System.Reflection.Emit.OpCodes.Ble_Un; case Code.Blt_Un: return System.Reflection.Emit.OpCodes.Blt_Un; case Code.Switch: return System.Reflection.Emit.OpCodes.Switch; case Code.Ldind_I1: return System.Reflection.Emit.OpCodes.Ldind_I1; case Code.Ldind_U1: return System.Reflection.Emit.OpCodes.Ldind_U1; case Code.Ldind_I2: return System.Reflection.Emit.OpCodes.Ldind_I2; case Code.Ldind_U2: return System.Reflection.Emit.OpCodes.Ldind_U2; case Code.Ldind_I4: return System.Reflection.Emit.OpCodes.Ldind_I4; case Code.Ldind_U4: return System.Reflection.Emit.OpCodes.Ldind_U4; case Code.Ldind_I8: return System.Reflection.Emit.OpCodes.Ldind_I8; case Code.Ldind_I: return System.Reflection.Emit.OpCodes.Ldind_I; case Code.Ldind_R4: return System.Reflection.Emit.OpCodes.Ldind_R4; case Code.Ldind_R8: return System.Reflection.Emit.OpCodes.Ldind_R8; case Code.Ldind_Ref: return System.Reflection.Emit.OpCodes.Ldind_Ref; case Code.Stind_Ref: return System.Reflection.Emit.OpCodes.Stind_Ref; case Code.Stind_I1: return System.Reflection.Emit.OpCodes.Stind_I1; case Code.Stind_I2: return System.Reflection.Emit.OpCodes.Stind_I2; case Code.Stind_I4: return System.Reflection.Emit.OpCodes.Stind_I4; case Code.Stind_I8: return System.Reflection.Emit.OpCodes.Stind_I8; case Code.Stind_R4: return System.Reflection.Emit.OpCodes.Stind_R4; case Code.Stind_R8: return System.Reflection.Emit.OpCodes.Stind_R8; case Code.Add: return System.Reflection.Emit.OpCodes.Add; case Code.Sub: return System.Reflection.Emit.OpCodes.Sub; case Code.Mul: return System.Reflection.Emit.OpCodes.Mul; case Code.Div: return System.Reflection.Emit.OpCodes.Div; case Code.Div_Un: return System.Reflection.Emit.OpCodes.Div_Un; case Code.Rem: return System.Reflection.Emit.OpCodes.Rem; case Code.Rem_Un: return System.Reflection.Emit.OpCodes.Rem_Un; case Code.And: return System.Reflection.Emit.OpCodes.And; case Code.Or: return System.Reflection.Emit.OpCodes.Or; case Code.Xor: return System.Reflection.Emit.OpCodes.Xor; case Code.Shl: return System.Reflection.Emit.OpCodes.Shl; case Code.Shr: return System.Reflection.Emit.OpCodes.Shr; case Code.Shr_Un: return System.Reflection.Emit.OpCodes.Shr_Un; case Code.Neg: return System.Reflection.Emit.OpCodes.Neg; case Code.Not: return System.Reflection.Emit.OpCodes.Not; case Code.Conv_I1: return System.Reflection.Emit.OpCodes.Conv_I1; case Code.Conv_I2: return System.Reflection.Emit.OpCodes.Conv_I2; case Code.Conv_I4: return System.Reflection.Emit.OpCodes.Conv_I4; case Code.Conv_I8: return System.Reflection.Emit.OpCodes.Conv_I8; case Code.Conv_R4: return System.Reflection.Emit.OpCodes.Conv_R4; case Code.Conv_R8: return System.Reflection.Emit.OpCodes.Conv_R8; case Code.Conv_U4: return System.Reflection.Emit.OpCodes.Conv_U4; case Code.Conv_U8: return System.Reflection.Emit.OpCodes.Conv_U8; case Code.Callvirt: return System.Reflection.Emit.OpCodes.Callvirt; case Code.Cpobj: return System.Reflection.Emit.OpCodes.Cpobj; case Code.Ldobj: return System.Reflection.Emit.OpCodes.Ldobj; case Code.Ldstr: return System.Reflection.Emit.OpCodes.Ldstr; case Code.Newobj: return System.Reflection.Emit.OpCodes.Newobj; case Code.Castclass: return System.Reflection.Emit.OpCodes.Castclass; case Code.Isinst: return System.Reflection.Emit.OpCodes.Isinst; case Code.Conv_R_Un: return System.Reflection.Emit.OpCodes.Conv_R_Un; case Code.Unbox: return System.Reflection.Emit.OpCodes.Unbox; case Code.Throw: return System.Reflection.Emit.OpCodes.Throw; case Code.Ldfld: return System.Reflection.Emit.OpCodes.Ldfld; case Code.Ldflda: return System.Reflection.Emit.OpCodes.Ldflda; case Code.Stfld: return System.Reflection.Emit.OpCodes.Stfld; case Code.Ldsfld: return System.Reflection.Emit.OpCodes.Ldsfld; case Code.Ldsflda: return System.Reflection.Emit.OpCodes.Ldsflda; case Code.Stsfld: return System.Reflection.Emit.OpCodes.Stsfld; case Code.Stobj: return System.Reflection.Emit.OpCodes.Stobj; case Code.Conv_Ovf_I1_Un: return System.Reflection.Emit.OpCodes.Conv_Ovf_I1_Un; case Code.Conv_Ovf_I2_Un: return System.Reflection.Emit.OpCodes.Conv_Ovf_I2_Un; case Code.Conv_Ovf_I4_Un: return System.Reflection.Emit.OpCodes.Conv_Ovf_I4_Un; case Code.Conv_Ovf_I8_Un: return System.Reflection.Emit.OpCodes.Conv_Ovf_I8_Un; case Code.Conv_Ovf_U1_Un: return System.Reflection.Emit.OpCodes.Conv_Ovf_U1_Un; case Code.Conv_Ovf_U2_Un: return System.Reflection.Emit.OpCodes.Conv_Ovf_U2_Un; case Code.Conv_Ovf_U4_Un: return System.Reflection.Emit.OpCodes.Conv_Ovf_U4_Un; case Code.Conv_Ovf_U8_Un: return System.Reflection.Emit.OpCodes.Conv_Ovf_U8_Un; case Code.Conv_Ovf_I_Un: return System.Reflection.Emit.OpCodes.Conv_Ovf_I_Un; case Code.Conv_Ovf_U_Un: return System.Reflection.Emit.OpCodes.Conv_Ovf_U_Un; case Code.Box: return System.Reflection.Emit.OpCodes.Box; case Code.Newarr: return System.Reflection.Emit.OpCodes.Newarr; case Code.Ldlen: return System.Reflection.Emit.OpCodes.Ldlen; case Code.Ldelema: return System.Reflection.Emit.OpCodes.Ldelema; case Code.Ldelem_I1: return System.Reflection.Emit.OpCodes.Ldelem_I1; case Code.Ldelem_U1: return System.Reflection.Emit.OpCodes.Ldelem_U1; case Code.Ldelem_I2: return System.Reflection.Emit.OpCodes.Ldelem_I2; case Code.Ldelem_U2: return System.Reflection.Emit.OpCodes.Ldelem_U2; case Code.Ldelem_I4: return System.Reflection.Emit.OpCodes.Ldelem_I4; case Code.Ldelem_U4: return System.Reflection.Emit.OpCodes.Ldelem_U4; case Code.Ldelem_I8: return System.Reflection.Emit.OpCodes.Ldelem_I8; case Code.Ldelem_I: return System.Reflection.Emit.OpCodes.Ldelem_I; case Code.Ldelem_R4: return System.Reflection.Emit.OpCodes.Ldelem_R4; case Code.Ldelem_R8: return System.Reflection.Emit.OpCodes.Ldelem_R8; case Code.Ldelem_Ref: return System.Reflection.Emit.OpCodes.Ldelem_Ref; case Code.Stelem_I: return System.Reflection.Emit.OpCodes.Stelem_I; case Code.Stelem_I1: return System.Reflection.Emit.OpCodes.Stelem_I1; case Code.Stelem_I2: return System.Reflection.Emit.OpCodes.Stelem_I2; case Code.Stelem_I4: return System.Reflection.Emit.OpCodes.Stelem_I4; case Code.Stelem_I8: return System.Reflection.Emit.OpCodes.Stelem_I8; case Code.Stelem_R4: return System.Reflection.Emit.OpCodes.Stelem_R4; case Code.Stelem_R8: return System.Reflection.Emit.OpCodes.Stelem_R8; case Code.Stelem_Ref: return System.Reflection.Emit.OpCodes.Stelem_Ref; case Code.Ldelem_Any: return System.Reflection.Emit.OpCodes.Ldelem; // * case Code.Stelem_Any: return System.Reflection.Emit.OpCodes.Stelem; // * case Code.Unbox_Any: return System.Reflection.Emit.OpCodes.Unbox_Any; case Code.Conv_Ovf_I1: return System.Reflection.Emit.OpCodes.Conv_Ovf_I1; case Code.Conv_Ovf_U1: return System.Reflection.Emit.OpCodes.Conv_Ovf_U1; case Code.Conv_Ovf_I2: return System.Reflection.Emit.OpCodes.Conv_Ovf_I2; case Code.Conv_Ovf_U2: return System.Reflection.Emit.OpCodes.Conv_Ovf_U2; case Code.Conv_Ovf_I4: return System.Reflection.Emit.OpCodes.Conv_Ovf_I4; case Code.Conv_Ovf_U4: return System.Reflection.Emit.OpCodes.Conv_Ovf_U4; case Code.Conv_Ovf_I8: return System.Reflection.Emit.OpCodes.Conv_Ovf_I8; case Code.Conv_Ovf_U8: return System.Reflection.Emit.OpCodes.Conv_Ovf_U8; case Code.Refanyval: return System.Reflection.Emit.OpCodes.Refanyval; case Code.Ckfinite: return System.Reflection.Emit.OpCodes.Ckfinite; case Code.Mkrefany: return System.Reflection.Emit.OpCodes.Mkrefany; case Code.Ldtoken: return System.Reflection.Emit.OpCodes.Ldtoken; case Code.Conv_U2: return System.Reflection.Emit.OpCodes.Conv_U2; case Code.Conv_U1: return System.Reflection.Emit.OpCodes.Conv_U1; case Code.Conv_I: return System.Reflection.Emit.OpCodes.Conv_I; case Code.Conv_Ovf_I: return System.Reflection.Emit.OpCodes.Conv_Ovf_I; case Code.Conv_Ovf_U: return System.Reflection.Emit.OpCodes.Conv_Ovf_U; case Code.Add_Ovf: return System.Reflection.Emit.OpCodes.Add_Ovf; case Code.Add_Ovf_Un: return System.Reflection.Emit.OpCodes.Add_Ovf_Un; case Code.Mul_Ovf: return System.Reflection.Emit.OpCodes.Mul_Ovf; case Code.Mul_Ovf_Un: return System.Reflection.Emit.OpCodes.Mul_Ovf_Un; case Code.Sub_Ovf: return System.Reflection.Emit.OpCodes.Sub_Ovf; case Code.Sub_Ovf_Un: return System.Reflection.Emit.OpCodes.Sub_Ovf_Un; case Code.Endfinally: return System.Reflection.Emit.OpCodes.Endfinally; case Code.Leave: return System.Reflection.Emit.OpCodes.Leave; case Code.Leave_S: return System.Reflection.Emit.OpCodes.Leave_S; case Code.Stind_I: return System.Reflection.Emit.OpCodes.Stind_I; case Code.Conv_U: return System.Reflection.Emit.OpCodes.Conv_U; case Code.Arglist: return System.Reflection.Emit.OpCodes.Arglist; case Code.Ceq: return System.Reflection.Emit.OpCodes.Ceq; case Code.Cgt: return System.Reflection.Emit.OpCodes.Cgt; case Code.Cgt_Un: return System.Reflection.Emit.OpCodes.Cgt_Un; case Code.Clt: return System.Reflection.Emit.OpCodes.Clt; case Code.Clt_Un: return System.Reflection.Emit.OpCodes.Clt_Un; case Code.Ldftn: return System.Reflection.Emit.OpCodes.Ldftn; case Code.Ldvirtftn: return System.Reflection.Emit.OpCodes.Ldvirtftn; case Code.Ldarg: return System.Reflection.Emit.OpCodes.Ldarg; case Code.Ldarga: return System.Reflection.Emit.OpCodes.Ldarga; case Code.Starg: return System.Reflection.Emit.OpCodes.Starg; case Code.Ldloc: return System.Reflection.Emit.OpCodes.Ldloc; case Code.Ldloca: return System.Reflection.Emit.OpCodes.Ldloca; case Code.Stloc: return System.Reflection.Emit.OpCodes.Stloc; case Code.Localloc: return System.Reflection.Emit.OpCodes.Localloc; case Code.Endfilter: return System.Reflection.Emit.OpCodes.Endfilter; case Code.Unaligned: return System.Reflection.Emit.OpCodes.Unaligned; case Code.Volatile: return System.Reflection.Emit.OpCodes.Volatile; case Code.Tail: return System.Reflection.Emit.OpCodes.Tailcall; // * case Code.Initobj: return System.Reflection.Emit.OpCodes.Initobj; case Code.Constrained: return System.Reflection.Emit.OpCodes.Constrained; case Code.Cpblk: return System.Reflection.Emit.OpCodes.Cpblk; case Code.Initblk: return System.Reflection.Emit.OpCodes.Initblk; //case Code.No: return System.Reflection.Emit.OpCodes.No; // no such opcode case Code.Rethrow: return System.Reflection.Emit.OpCodes.Rethrow; case Code.Sizeof: return System.Reflection.Emit.OpCodes.Sizeof; case Code.Refanytype: return System.Reflection.Emit.OpCodes.Refanytype; case Code.Readonly: return System.Reflection.Emit.OpCodes.Readonly; default: throw new NotSupportedException(string.Format("Unsupported opcode: {0}.", cecilOpcode)); } } } }
// // CGContext.cs: Implements the managed CGContext // // Authors: Mono Team // // Copyright 2009 Novell, Inc // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Drawing; using System.Runtime.InteropServices; using MonoMac.ObjCRuntime; using MonoMac.Foundation; namespace MonoMac.CoreGraphics { public enum CGLineJoin { Miter, Round, Bevel } public enum CGLineCap { Butt, Round, Square } public enum CGPathDrawingMode { Fill, EOFill, Stroke, FillStroke, EOFillStroke } public enum CGTextDrawingMode { Fill, Stroke, FillStroke, Invisible, FillClip, StrokeClip, FillStrokeClip, Clip } public enum CGTextEncoding { FontSpecific, MacRoman } public enum CGInterpolationQuality { Default, None, Low, High, Medium /* Yes, in this order, since Medium was added in 4 */ } public enum CGBlendMode { Normal, Multiply, Screen, Overlay, Darken, Lighten, ColorDodge, ColorBurn, SoftLight, HardLight, Difference, Exclusion, Hue, Saturation, Color, Luminosity, Clear, Copy, SourceIn, SourceOut, SourceAtop, DestinationOver, DestinationIn, DestinationOut, DestinationAtop, XOR, PlusDarker, PlusLighter } public class CGContext : INativeObject, IDisposable { internal IntPtr handle; public CGContext (IntPtr handle) { if (handle == IntPtr.Zero) throw new Exception ("Invalid parameters to context creation"); CGContextRetain (handle); this.handle = handle; } internal CGContext () { } [Preserve (Conditional=true)] internal CGContext (IntPtr handle, bool owns) { if (!owns) CGContextRetain (handle); if (handle == IntPtr.Zero) throw new Exception ("Invalid handle"); this.handle = handle; } ~CGContext () { Dispose (false); } public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } public IntPtr Handle { get { return handle; } } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextRelease (IntPtr handle); [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextRetain (IntPtr handle); protected virtual void Dispose (bool disposing) { if (handle != IntPtr.Zero){ CGContextRelease (handle); handle = IntPtr.Zero; } } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSaveGState (IntPtr context); [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextRestoreGState (IntPtr context); public void SaveState () { CGContextSaveGState (handle); } public void RestoreState () { CGContextRestoreGState (handle); } // // Transformation matrix // [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextScaleCTM (IntPtr ctx, float sx, float sy); public void ScaleCTM (float sx, float sy) { CGContextScaleCTM (handle, sx, sy); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextTranslateCTM (IntPtr ctx, float tx, float ty); public void TranslateCTM (float tx, float ty) { CGContextTranslateCTM (handle, tx, ty); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextRotateCTM (IntPtr ctx, float angle); public void RotateCTM (float angle) { CGContextRotateCTM (handle, angle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextConcatCTM (IntPtr ctx, CGAffineTransform transform); public void ConcatCTM (CGAffineTransform transform) { CGContextConcatCTM (handle, transform); } // Settings [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetLineWidth(IntPtr c, float width); public void SetLineWidth (float w) { CGContextSetLineWidth (handle, w); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetLineCap(IntPtr c, CGLineCap cap); public void SetLineCap (CGLineCap cap) { CGContextSetLineCap (handle, cap); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetLineJoin(IntPtr c, CGLineJoin join); public void SetLineJoin (CGLineJoin join) { CGContextSetLineJoin (handle, join); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetMiterLimit(IntPtr c, float limit); public void SetMiterLimit (float limit) { CGContextSetMiterLimit (handle, limit); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetLineDash(IntPtr c, float phase, float [] lenghts, int count); public void SetLineDash (float phase, float [] lenghts) { if (lenghts == null) throw new ArgumentNullException ("lenghts"); CGContextSetLineDash (handle, phase, lenghts, lenghts.Length); } public void SetLineDash (float phase, float [] lenghts, int n) { if (lenghts == null) throw new ArgumentNullException ("lenghts"); if (n > lenghts.Length) throw new ArgumentNullException ("n"); CGContextSetLineDash (handle, phase, lenghts, n); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetFlatness(IntPtr c, float flatness); public void SetFlatness (float flatness) { CGContextSetFlatness (handle, flatness); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetAlpha(IntPtr c, float alpha); public void SetAlpha (float alpha) { CGContextSetAlpha (handle, alpha); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetBlendMode(IntPtr context, CGBlendMode mode); public void SetBlendMode (CGBlendMode mode) { CGContextSetBlendMode (handle, mode); } [DllImport (Constants.CoreGraphicsLibrary)] extern static CGAffineTransform CGContextGetCTM (IntPtr c); public CGAffineTransform GetCTM () { return CGContextGetCTM (handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextBeginPath(IntPtr c); public void BeginPath () { CGContextBeginPath (handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextMoveToPoint(IntPtr c, float x, float y); public void MoveTo (float x, float y) { CGContextMoveToPoint (handle, x, y); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextAddLineToPoint(IntPtr c, float x, float y); public void AddLineToPoint (float x, float y) { CGContextAddLineToPoint (handle, x, y); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextAddCurveToPoint(IntPtr c, float cp1x, float cp1y, float cp2x, float cp2y, float x, float y); public void AddCurveToPoint (float cp1x, float cp1y, float cp2x, float cp2y, float x, float y) { CGContextAddCurveToPoint (handle, cp1x, cp1y, cp2x, cp2y, x, y); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextAddQuadCurveToPoint(IntPtr c, float cpx, float cpy, float x, float y); public void AddQuadCurveToPoint (float cpx, float cpy, float x, float y) { CGContextAddQuadCurveToPoint (handle, cpx, cpy, x, y); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextClosePath(IntPtr c); public void ClosePath () { CGContextClosePath (handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextAddRect(IntPtr c, RectangleF rect); public void AddRect (RectangleF rect) { CGContextAddRect (handle, rect); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextAddRects(IntPtr c, RectangleF [] rects, int size_t_count) ; public void AddRects (RectangleF [] rects) { CGContextAddRects (handle, rects, rects.Length); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextAddLines(IntPtr c, PointF [] points, int size_t_count) ; public void AddLines (PointF [] points) { CGContextAddLines (handle, points, points.Length); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextAddEllipseInRect(IntPtr context, RectangleF rect); public void AddEllipseInRect (RectangleF rect) { CGContextAddEllipseInRect (handle, rect); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextAddArc(IntPtr c, float x, float y, float radius, float startAngle, float endAngle, int clockwise); public void AddArc (float x, float y, float radius, float startAngle, float endAngle, bool clockwise) { CGContextAddArc (handle, x, y, radius, startAngle, endAngle, clockwise ? 1 : 0); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextAddArcToPoint(IntPtr c, float x1, float y1, float x2, float y2, float radius); public void AddArcToPoint (float x1, float y1, float x2, float y2, float radius) { CGContextAddArcToPoint (handle, x1, y1, x2, y2, radius); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextAddPath(IntPtr context, IntPtr path_ref); public void AddPath (CGPath path) { CGContextAddPath (handle, path.handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextReplacePathWithStrokedPath(IntPtr c); public void ReplacePathWithStrokedPath () { CGContextReplacePathWithStrokedPath (handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static int CGContextIsPathEmpty(IntPtr c); public bool IsPathEmpty () { return CGContextIsPathEmpty (handle) != 0; } [DllImport (Constants.CoreGraphicsLibrary)] extern static PointF CGContextGetPathCurrentPoint(IntPtr c); public PointF GetPathCurrentPoint () { return CGContextGetPathCurrentPoint (handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static RectangleF CGContextGetPathBoundingBox(IntPtr c); public RectangleF GetPathBoundingBox () { return CGContextGetPathBoundingBox (handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static int CGContextPathContainsPoint(IntPtr context, PointF point, CGPathDrawingMode mode); public bool PathContainsPoint (PointF point, CGPathDrawingMode mode) { return CGContextPathContainsPoint (handle, point, mode) != 0; } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextDrawPath(IntPtr c, CGPathDrawingMode mode); public void DrawPath (CGPathDrawingMode mode) { CGContextDrawPath (handle, mode); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextFillPath(IntPtr c); public void FillPath () { CGContextFillPath (handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextEOFillPath(IntPtr c); public void EOFillPath () { CGContextEOFillPath (handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextStrokePath(IntPtr c); public void StrokePath () { CGContextStrokePath (handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextFillRect(IntPtr c, RectangleF rect); public void FillRect (RectangleF rect) { CGContextFillRect (handle, rect); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextFillRects(IntPtr c, RectangleF [] rects, int size_t_count); public void ContextFillRects (RectangleF [] rects) { CGContextFillRects (handle, rects, rects.Length); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextStrokeRect(IntPtr c, RectangleF rect); public void StrokeRect (RectangleF rect) { CGContextStrokeRect (handle, rect); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextStrokeRectWithWidth(IntPtr c, RectangleF rect, float width); public void StrokeRectWithWidth (RectangleF rect, float width) { CGContextStrokeRectWithWidth (handle, rect, width); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextClearRect(IntPtr c, RectangleF rect); public void ClearRect (RectangleF rect) { CGContextClearRect (handle, rect); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextFillEllipseInRect(IntPtr context, RectangleF rect); public void FillEllipseInRect (RectangleF rect) { CGContextFillEllipseInRect (handle, rect); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextStrokeEllipseInRect(IntPtr context, RectangleF rect); public void StrokeEllipseInRect (RectangleF rect) { CGContextStrokeEllipseInRect (handle, rect); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextStrokeLineSegments(IntPtr c, PointF [] points, int size_t_count); public void StrokeLineSegments (PointF [] points) { CGContextStrokeLineSegments (handle, points, points.Length); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextClip(IntPtr c); public void Clip () { CGContextClip (handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextEOClip(IntPtr c); public void EOClip () { CGContextEOClip (handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextClipToMask(IntPtr c, RectangleF rect, IntPtr mask); public void ClipToMask (RectangleF rect, CGImage mask) { CGContextClipToMask (handle, rect, mask.handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static RectangleF CGContextGetClipBoundingBox(IntPtr c); public RectangleF GetClipBoundingBox () { return CGContextGetClipBoundingBox (handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextClipToRect(IntPtr c, RectangleF rect); public void ClipToRect (RectangleF rect) { CGContextClipToRect (handle, rect); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextClipToRects(IntPtr c, RectangleF [] rects, int size_t_count); public void ClipToRects (RectangleF [] rects) { CGContextClipToRects (handle, rects, rects.Length); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetFillColorWithColor(IntPtr c, IntPtr color); public void SetFillColor (CGColor color) { CGContextSetFillColorWithColor (handle, color.handle); } [Obsolete ("Use SetFillColor() instead.")] public void SetFillColorWithColor (CGColor color) { CGContextSetFillColorWithColor (handle, color.handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetStrokeColorWithColor(IntPtr c, IntPtr color); public void SetStrokeColor (CGColor color) { CGContextSetStrokeColorWithColor (handle, color.handle); } [Obsolete ("Use SetStrokeColor() instead.")] public void SetStrokeColorWithColor (CGColor color) { CGContextSetStrokeColorWithColor (handle, color.handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetFillColorSpace(IntPtr context, IntPtr space); public void SetFillColorSpace (CGColorSpace space) { CGContextSetFillColorSpace (handle, space.handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetStrokeColorSpace(IntPtr context, IntPtr space); public void SetStrokeColorSpace (CGColorSpace space) { CGContextSetStrokeColorSpace (handle, space.handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetFillColor(IntPtr context, float [] components); public void SetFillColor (float [] components) { if (components == null) throw new ArgumentNullException ("components"); CGContextSetFillColor (handle, components); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetStrokeColor(IntPtr context, float [] components); public void SetStrokeColor (float [] components) { if (components == null) throw new ArgumentNullException ("components"); CGContextSetStrokeColor (handle, components); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetFillPattern(IntPtr context, IntPtr pattern, float [] components); public void SetFillPattern (CGPattern pattern, float [] components) { if (components == null) throw new ArgumentNullException ("components"); CGContextSetFillPattern (handle, pattern.handle, components); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetStrokePattern(IntPtr context, IntPtr pattern, float [] components); public void SetStrokePattern (CGPattern pattern, float [] components) { if (components == null) throw new ArgumentNullException ("components"); CGContextSetStrokePattern (handle, pattern.handle, components); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetPatternPhase(IntPtr context, SizeF phase); public void SetPatternPhase (SizeF phase) { CGContextSetPatternPhase (handle, phase); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetGrayFillColor(IntPtr context, float gray, float alpha); public void SetFillColor (float gray, float alpha) { CGContextSetGrayFillColor (handle, gray, alpha); } [Obsolete ("Use SetFillColor() instead.")] public void SetGrayFillColor (float gray, float alpha) { CGContextSetGrayFillColor (handle, gray, alpha); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetGrayStrokeColor(IntPtr context, float gray, float alpha); public void SetStrokeColor (float gray, float alpha) { CGContextSetGrayStrokeColor (handle, gray, alpha); } [Obsolete ("Use SetStrokeColor() instead.")] public void SetGrayStrokeColor (float gray, float alpha) { CGContextSetGrayStrokeColor (handle, gray, alpha); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetRGBFillColor(IntPtr context, float red, float green, float blue, float alpha); public void SetFillColor (float red, float green, float blue, float alpha) { CGContextSetRGBFillColor (handle, red, green, blue, alpha); } [Obsolete ("Use SetFillColor() instead.")] public void SetRGBFillColor (float red, float green, float blue, float alpha) { CGContextSetRGBFillColor (handle, red, green, blue, alpha); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetRGBStrokeColor(IntPtr context, float red, float green, float blue, float alpha); public void SetStrokeColor (float red, float green, float blue, float alpha) { CGContextSetRGBStrokeColor (handle, red, green, blue, alpha); } [Obsolete ("Use SetStrokeColor() instead.")] public void SetRGBStrokeColor (float red, float green, float blue, float alpha) { CGContextSetRGBStrokeColor (handle, red, green, blue, alpha); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetCMYKFillColor(IntPtr context, float cyan, float magenta, float yellow, float black, float alpha); public void SetFillColor (float cyan, float magenta, float yellow, float black, float alpha) { CGContextSetCMYKFillColor (handle, cyan, magenta, yellow, black, alpha); } [Obsolete ("Use SetFillColor() instead.")] public void SetCMYKFillColor (float cyan, float magenta, float yellow, float black, float alpha) { CGContextSetCMYKFillColor (handle, cyan, magenta, yellow, black, alpha); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetCMYKStrokeColor(IntPtr context, float cyan, float magenta, float yellow, float black, float alpha); public void SetStrokeColor (float cyan, float magenta, float yellow, float black, float alpha) { CGContextSetCMYKStrokeColor (handle, cyan, magenta, yellow, black, alpha); } [Obsolete ("Use SetStrokeColor() instead.")] public void SetCMYKStrokeColor (float cyan, float magenta, float yellow, float black, float alpha) { CGContextSetCMYKStrokeColor (handle, cyan, magenta, yellow, black, alpha); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetRenderingIntent(IntPtr context, CGColorRenderingIntent intent); public void SetRenderingIntent (CGColorRenderingIntent intent) { CGContextSetRenderingIntent (handle, intent); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextDrawImage(IntPtr c, RectangleF rect, IntPtr image); public void DrawImage (RectangleF rect, CGImage image) { CGContextDrawImage (handle, rect, image.handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextDrawTiledImage(IntPtr c, RectangleF rect, IntPtr image); public void DrawTiledImage (RectangleF rect, CGImage image) { CGContextDrawTiledImage (handle, rect, image.handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static CGInterpolationQuality CGContextGetInterpolationQuality(IntPtr context); [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetInterpolationQuality(IntPtr context, CGInterpolationQuality quality); public CGInterpolationQuality InterpolationQuality { get { return CGContextGetInterpolationQuality (handle); } set { CGContextSetInterpolationQuality (handle, value); } } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetShadowWithColor(IntPtr context, SizeF offset, float blur, IntPtr color); public void SetShadowWithColor (SizeF offset, float blur, CGColor color) { CGContextSetShadowWithColor (handle, offset, blur, color.handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetShadow(IntPtr context, SizeF offset, float blur); public void SetShadow (SizeF offset, float blur) { CGContextSetShadow (handle, offset, blur); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextDrawLinearGradient(IntPtr context, IntPtr gradient, PointF startPoint, PointF endPoint, CGGradientDrawingOptions options); public void DrawLinearGradient (CGGradient gradient, PointF startPoint, PointF endPoint, CGGradientDrawingOptions options) { CGContextDrawLinearGradient (handle, gradient.handle, startPoint, endPoint, options); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextDrawRadialGradient (IntPtr context, IntPtr gradient, PointF startCenter, float startRadius, PointF endCenter, float endRadius, CGGradientDrawingOptions options); public void DrawRadialGradient (CGGradient gradient, PointF startCenter, float startRadius, PointF endCenter, float endRadius, CGGradientDrawingOptions options) { CGContextDrawRadialGradient (handle, gradient.handle, startCenter, startRadius, endCenter, endRadius, options); } //[DllImport (Constants.CoreGraphicsLibrary)] //extern static void CGContextDrawShading(IntPtr context, IntPtr shading); //public void DrawShading (CGShading shading) //{ // CGContextDrawShading (handle, shading.handle); //} [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetCharacterSpacing(IntPtr context, float spacing); public void SetCharacterSpacing (float spacing) { CGContextSetCharacterSpacing (handle, spacing); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetTextPosition(IntPtr c, float x, float y); [DllImport (Constants.CoreGraphicsLibrary)] extern static PointF CGContextGetTextPosition(IntPtr context); public PointF TextPosition { get { return CGContextGetTextPosition (handle); } set { CGContextSetTextPosition (handle, value.X, value.Y); } } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetTextMatrix(IntPtr c, CGAffineTransform t); [DllImport (Constants.CoreGraphicsLibrary)] extern static CGAffineTransform CGContextGetTextMatrix(IntPtr c); public CGAffineTransform TextMatrix { get { return CGContextGetTextMatrix (handle); } set { CGContextSetTextMatrix (handle, value); } } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetTextDrawingMode(IntPtr c, CGTextDrawingMode mode); public void SetTextDrawingMode (CGTextDrawingMode mode) { CGContextSetTextDrawingMode (handle, mode); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetFont(IntPtr c, IntPtr font); public void SetFont (CGFont font) { CGContextSetFont (handle, font.handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetFontSize(IntPtr c, float size); public void SetFontSize (float size) { CGContextSetFontSize (handle, size); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSelectFont(IntPtr c, string name, float size, CGTextEncoding textEncoding); public void SelectFont (string name, float size, CGTextEncoding textEncoding) { if (name == null) throw new ArgumentNullException ("name"); CGContextSelectFont (handle, name, size, textEncoding); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextShowGlyphsAtPositions(IntPtr context, ushort [] glyphs, PointF [] positions, int size_t_count); public void ShowGlyphsAtPositions (ushort [] glyphs, PointF [] positions, int size_t_count) { if (positions == null) throw new ArgumentNullException ("positions"); if (glyphs == null) throw new ArgumentNullException ("glyphs"); CGContextShowGlyphsAtPositions (handle, glyphs, positions, size_t_count); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextShowText(IntPtr c, string s, int size_t_length); public void ShowText (string str, int count) { if (str == null) throw new ArgumentNullException ("str"); if (count > str.Length) throw new ArgumentException ("count"); CGContextShowText (handle, str, count); } public void ShowText (string str) { if (str == null) throw new ArgumentNullException ("str"); CGContextShowText (handle, str, str.Length); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextShowText(IntPtr c, byte[] bytes, int size_t_length); public void ShowText (byte[] bytes, int count) { if (bytes == null) throw new ArgumentNullException ("bytes"); if (count > bytes.Length) throw new ArgumentException ("count"); CGContextShowText (handle, bytes, count); } public void ShowText (byte[] bytes) { if (bytes == null) throw new ArgumentNullException ("bytes"); CGContextShowText (handle, bytes, bytes.Length); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextShowTextAtPoint(IntPtr c, float x, float y, string str, int size_t_length); public void ShowTextAtPoint (float x, float y, string str, int length) { if (str == null) throw new ArgumentNullException ("str"); CGContextShowTextAtPoint (handle, x, y, str, length); } public void ShowTextAtPoint (float x, float y, string str) { if (str == null) throw new ArgumentNullException ("str"); CGContextShowTextAtPoint (handle, x, y, str, str.Length); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextShowTextAtPoint(IntPtr c, float x, float y, byte[] bytes, int size_t_length); public void ShowTextAtPoint (float x, float y, byte[] bytes, int length) { if (bytes == null) throw new ArgumentNullException ("bytes"); CGContextShowTextAtPoint (handle, x, y, bytes, length); } public void ShowTextAtPoint (float x, float y, byte[] bytes) { if (bytes == null) throw new ArgumentNullException ("bytes"); CGContextShowTextAtPoint (handle, x, y, bytes, bytes.Length); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextShowGlyphs(IntPtr c, ushort [] glyphs, int size_t_count); public void ShowGlyphs (ushort [] glyphs) { if (glyphs == null) throw new ArgumentNullException ("glyphs"); CGContextShowGlyphs (handle, glyphs, glyphs.Length); } public void ShowGlyphs (ushort [] glyphs, int count) { if (glyphs == null) throw new ArgumentNullException ("glyphs"); if (count > glyphs.Length) throw new ArgumentException ("count"); CGContextShowGlyphs (handle, glyphs, count); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextShowGlyphsAtPoint(IntPtr context, float x, float y, ushort [] glyphs, int size_t_count); public void ShowGlyphsAtPoint (float x, float y, ushort [] glyphs, int count) { if (glyphs == null) throw new ArgumentNullException ("glyphs"); if (count > glyphs.Length) throw new ArgumentException ("count"); CGContextShowGlyphsAtPoint (handle, x, y, glyphs, count); } public void ShowGlyphsAtPoint (float x, float y, ushort [] glyphs) { if (glyphs == null) throw new ArgumentNullException ("glyphs"); CGContextShowGlyphsAtPoint (handle, x, y, glyphs, glyphs.Length); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextShowGlyphsWithAdvances(IntPtr c, ushort [] glyphs, SizeF [] advances, int size_t_count); public void ShowGlyphsWithAdvances (ushort [] glyphs, SizeF [] advances, int count) { if (glyphs == null) throw new ArgumentNullException ("glyphs"); if (advances == null) throw new ArgumentNullException ("advances"); if (count > glyphs.Length || count > advances.Length) throw new ArgumentException ("count"); CGContextShowGlyphsWithAdvances (handle, glyphs, advances, count); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextDrawPDFPage(IntPtr c, IntPtr page); public void DrawPDFPage (CGPDFPage page) { CGContextDrawPDFPage (handle, page.handle); } [DllImport (Constants.CoreGraphicsLibrary)] unsafe extern static void CGContextBeginPage(IntPtr c, ref RectangleF mediaBox); [DllImport (Constants.CoreGraphicsLibrary)] unsafe extern static void CGContextBeginPage(IntPtr c, IntPtr zero); public void BeginPage (RectangleF? rect) { if (rect.HasValue){ RectangleF v = rect.Value; CGContextBeginPage (handle, ref v); } else { CGContextBeginPage (handle, IntPtr.Zero); } } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextEndPage(IntPtr c); public void EndPage () { CGContextEndPage (handle); } //[DllImport (Constants.CoreGraphicsLibrary)] //extern static IntPtr CGContextRetain(IntPtr c); [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextFlush(IntPtr c); public void Flush () { CGContextFlush (handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSynchronize(IntPtr c); public void Synchronize () { CGContextSynchronize (handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetShouldAntialias(IntPtr c, int shouldAntialias); public void SetShouldAntialias (bool shouldAntialias) { CGContextSetShouldAntialias (handle, shouldAntialias ? 1 : 0); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetAllowsAntialiasing(IntPtr context, int allowsAntialiasing); public void SetAllowsAntialiasing (bool allowsAntialiasing) { CGContextSetAllowsAntialiasing (handle, allowsAntialiasing ? 1 : 0); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetShouldSmoothFonts(IntPtr c, int shouldSmoothFonts); public void SetShouldSmoothFonts (bool shouldSmoothFonts) { CGContextSetShouldSmoothFonts (handle, shouldSmoothFonts ? 1 : 0); } //[DllImport (Constants.CoreGraphicsLibrary)] //extern static void CGContextBeginTransparencyLayer(IntPtr context, CFDictionaryRef auxiliaryInfo); //[DllImport (Constants.CoreGraphicsLibrary)] //extern static void CGContextBeginTransparencyLayerWithRect(IntPtr context, RectangleF rect, CFDictionaryRef auxiliaryInfo) //[DllImport (Constants.CoreGraphicsLibrary)] //extern static void CGContextEndTransparencyLayer(IntPtr context); [DllImport (Constants.CoreGraphicsLibrary)] extern static CGAffineTransform CGContextGetUserSpaceToDeviceSpaceTransform(IntPtr context); public CGAffineTransform GetUserSpaceToDeviceSpaceTransform() { return CGContextGetUserSpaceToDeviceSpaceTransform (handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static PointF CGContextConvertPointToDeviceSpace(IntPtr context, PointF point); public PointF PointToDeviceSpace (PointF point) { return CGContextConvertPointToDeviceSpace (handle, point); } [DllImport (Constants.CoreGraphicsLibrary)] extern static PointF CGContextConvertPointToUserSpace(IntPtr context, PointF point); public PointF ConvertPointToUserSpace (PointF point) { return CGContextConvertPointToUserSpace (handle, point); } [DllImport (Constants.CoreGraphicsLibrary)] extern static SizeF CGContextConvertSizeToDeviceSpace(IntPtr context, SizeF size); public SizeF ConvertSizeToDeviceSpace (SizeF size) { return CGContextConvertSizeToDeviceSpace (handle, size); } [DllImport (Constants.CoreGraphicsLibrary)] extern static SizeF CGContextConvertSizeToUserSpace(IntPtr context, SizeF size); public SizeF ConvertSizeToUserSpace (SizeF size) { return CGContextConvertSizeToUserSpace (handle, size); } [DllImport (Constants.CoreGraphicsLibrary)] extern static RectangleF CGContextConvertRectToDeviceSpace(IntPtr context, RectangleF rect); public RectangleF ConvertRectToDeviceSpace (RectangleF rect) { return CGContextConvertRectToDeviceSpace (handle, rect); } [DllImport (Constants.CoreGraphicsLibrary)] extern static RectangleF CGContextConvertRectToUserSpace(IntPtr context, RectangleF rect); public RectangleF ConvertRectToUserSpace (RectangleF rect) { return CGContextConvertRectToUserSpace (handle, rect); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextDrawLayerInRect (IntPtr context, RectangleF rect, IntPtr layer); public void DrawLayer (CGLayer layer, RectangleF rect) { if (layer == null) throw new ArgumentNullException ("layer"); CGContextDrawLayerInRect (handle, rect, layer.Handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextDrawLayerAtPoint (IntPtr context, PointF rect, IntPtr layer); public void DrawLayer (CGLayer layer, PointF point) { if (layer == null) throw new ArgumentNullException ("layer"); CGContextDrawLayerAtPoint (handle, point, layer.Handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGContextCopyPath (IntPtr context); [Since (4,0)] public CGPath CopyPath () { var r = CGContextCopyPath (handle); return new CGPath (r, true); } [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGContextSetAllowsFontSmoothing (IntPtr context, bool allows); [Since (4,0)] public void SetAllowsFontSmoothing (bool allows) { CGContextSetAllowsFontSmoothing (handle, allows); } [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGContextSetAllowsFontSubpixelPositioning (IntPtr context, bool allows); [Since (4,0)] public void SetAllowsSubpixelPositioning (bool allows) { CGContextSetAllowsFontSubpixelPositioning (handle, allows); } [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGContextSetAllowsFontSubpixelQuantization (IntPtr context, bool allows); [Since (4,0)] public void SetAllowsFontSubpixelQuantization (bool allows) { CGContextSetAllowsFontSubpixelQuantization (handle, allows); } [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGContextSetShouldSubpixelPositionFonts (IntPtr context, bool should); [Since (4,0)] public void SetShouldSubpixelPositionFonts (bool shouldSubpixelPositionFonts) { CGContextSetShouldSubpixelPositionFonts (handle, shouldSubpixelPositionFonts); } [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGContextSetShouldSubpixelQuantizeFonts (IntPtr context, bool should); [Since (4,0)] public void ShouldSubpixelQuantizeFonts (bool shouldSubpixelQuantizeFonts) { CGContextSetShouldSubpixelQuantizeFonts (handle, shouldSubpixelQuantizeFonts); } #if !COREBUILD [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGContextBeginTransparencyLayer (IntPtr context, IntPtr dictionary); public void BeginTransparencyLayer () { CGContextBeginTransparencyLayer (handle, IntPtr.Zero); } public void BeginTransparencyLayer (NSDictionary auxiliaryInfo = null) { CGContextBeginTransparencyLayer (handle, auxiliaryInfo == null ? IntPtr.Zero : auxiliaryInfo.Handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGContextBeginTransparencyLayerWithRect (IntPtr context, RectangleF rect, IntPtr dictionary); public void BeginTransparencyLayer (RectangleF rectangle, NSDictionary auxiliaryInfo = null) { CGContextBeginTransparencyLayerWithRect (handle, rectangle, auxiliaryInfo == null ? IntPtr.Zero : auxiliaryInfo.Handle); } public void BeginTransparencyLayer (RectangleF rectangle) { CGContextBeginTransparencyLayerWithRect (handle, rectangle, IntPtr.Zero); } [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGContextEndTransparencyLayer (IntPtr context); public void EndTransparencyLayer () { CGContextEndTransparencyLayer (handle); } #endif } }
using NUnit.Framework; namespace Moq.Sequences.Tests { public class LoopTest { [Test] public void A_new_loop_should_be_added_directly_if_it_contains_no_child_loops() { using (var loop = new Loop(Times.Once())) { using (var child = loop.CreateLoop(Times.Once())) { Assert.That(loop.Steps.Contains(child)); } } } [Test] public void A_new_loop_should_be_added_to_most_recently_created_child_loop() { using (var loop = new Loop(Times.Once())) { using (var child1 = loop.CreateLoop(Times.Once())) { using (loop.CreateLoop(Times.Once())) { } using (var child2 = loop.CreateLoop(Times.Once())) { Assert.That(child1.Steps.Contains(child2)); using (var child3 = loop.CreateLoop(Times.Once())) { Assert.That(child2.Steps.Contains(child3)); } } } } } [Test] public void A_new_step_should_be_added_directly_if_it_contains_no_child_loops() { using (var loop = new Loop(Times.Once())) { var step = loop.CreateStep("", Times.Once()); Assert.That(loop.Steps.Contains(step)); } } [Test] public void A_new_step_should_be_added_to_most_recently_created_child_loop() { using (var loop = new Loop(Times.Once())) { using (loop.CreateLoop(Times.Once())) { using (loop.CreateLoop(Times.Once())) { } using (var child2 = loop.CreateLoop(Times.Once())) { var step2 = loop.CreateStep("", Times.Once()); Assert.That(child2.Steps.Contains(step2)); using (var child3 = loop.CreateLoop(Times.Once())) { var step3 = loop.CreateStep("", Times.Once()); Assert.That(child3.Steps.Contains(step3)); } } } } } [Test] public void RecordCall_should_throw_when_step_count_exceeded() { using (var loop = new Loop(Times.Once())) { var step = loop.CreateStep("", Times.Exactly(2)); loop.RecordCall(step); loop.RecordCall(step); Assert.Throws<SequenceException>(() => loop.RecordCall(step)); } } [Test] public void RecordCall_should_throw_when_loop_count_exceeded() { using (var loop = new Loop(Times.Exactly(2))) { var step1 = loop.CreateStep("", Times.Once()); var step2 = loop.CreateStep("", Times.Once()); loop.RecordCall(step1); loop.RecordCall(step2); loop.RecordCall(step1); loop.RecordCall(step2); Assert.Throws<SequenceException>(() => loop.RecordCall(step1)); } } [Test] public void RecordCall_should_throw_if_steps_called_out_of_sequence() { using (var loop = new Loop(Times.Once())) { loop.CreateStep("", Times.Once()); var step = loop.CreateStep("", Times.Once()); Assert.Throws<SequenceException>(() => loop.RecordCall(step)); } } [Test] public void RecordCall_should_throw_when_child_loop_count_exceeded() { using (var loop = new Loop(Times.Once())) { Step step1; Step step2; using (loop.CreateLoop(Times.Exactly(2))) { step1 = loop.CreateStep("", Times.Once()); step2 = loop.CreateStep("", Times.Once()); } loop.RecordCall(step1); loop.RecordCall(step2); loop.RecordCall(step1); loop.RecordCall(step2); Assert.Throws<SequenceException>(() => loop.RecordCall(step1)); } } [Test] public void Record_call_should_ensure_all_previous_steps_completed() { using (var loop = new Loop(Times.Once())) { var stepBefore = loop.CreateStep("", Times.AtMostOnce()); Loop nested; Step stepNested; using (nested = loop.CreateLoop(Times.Once())) { stepNested = loop.CreateStep("", Times.Once()); } var stepAfter = loop.CreateStep("", Times.Once()); loop.RecordCall(stepNested); Assert.That(stepBefore.Complete, Is.True); Assert.That(loop.Complete, Is.False); Assert.That(stepNested.Complete, Is.False); Assert.That(stepAfter.Complete, Is.False); loop.RecordCall(stepAfter); Assert.That(stepBefore.Complete, Is.True); Assert.That(nested.Complete, Is.True); Assert.That(stepNested.Complete, Is.True); Assert.That(stepAfter.Complete, Is.False); } } [Test] public void EnsureComplete_should_throw_if_minimum_count_not_met() { using (var loop = new Loop(Times.Once())) { Assert.Throws<SequenceException>(() => loop.EnsureComplete("")); Assert.That(loop.Complete, Is.False); } } [Test] public void EnsureComplete_should_throw_if_maximum_count_not_met() { using (var loop = new Loop(Times.AtLeastOnce())) { Assert.Throws<SequenceException>(() => loop.EnsureComplete("")); Assert.That(loop.Complete, Is.False); } } [Test] public void EnsureComplete_should_not_throw_if_minimum_and_maximum_count_met() { using (var loop = new Loop(Times.Never())) { loop.EnsureComplete(""); Assert.That(loop.Complete, Is.True); } } [Test] public void Dispose_should_throw_if_child_loops_not_disposed() { Assert.Throws<SequenceUsageException>(delegate { using (var loop = new Loop(Times.Once())) { loop.CreateLoop(Times.Exactly(2)); } }); } [Test] public void Dispose_should_do_nothing_if_called_multiple_times() { using (var loop = new Loop(Times.Once())) { loop.Dispose(); loop.Dispose(); } } } }
using System; using System.Linq; using System.Runtime.CompilerServices; //TODO: JavaCompatability using DotNet; using IllegalArgumentException = System.ArgumentException; using boolean = System.Boolean; using System.Collections.Generic; namespace lanterna.input { /** * Represents the user pressing a key on the keyboard. If the user held down ctrl and/or alt before pressing the key, * this may be recorded in this class, depending on the terminal implementation and if such information in available. * KeyStroke objects are normally constructed by a KeyDecodingProfile, which works off a character stream that likely * coming from the system's standard input. Because of this, the class can only represent what can be read and * interpreted from the input stream; for example, certain key-combinations like ctrl+i is indistinguishable from a tab * key press. * <p> * Use the <tt>keyType</tt> field to determine what kind of key was pressed. For ordinary letters, numbers and symbols, the * <tt>keyType</tt> will be <tt>KeyType.Character</tt> and the actual character value of the key is in the * <tt>character</tt> field. Please note that return (\n) and tab (\t) are not sorted under type <tt>KeyType.getCharacter</tt> * but <tt>KeyType.Enter</tt> and <tt>KeyType.Tab</tt> instead. * @author martin */ public class KeyStroke { private KeyType keyType; private char character; private bool ctrlDown; private bool altDown; private bool shiftDown; private long eventTime; /** * Constructs a KeyStroke based on a supplied keyType; character will be null and both ctrl and alt will be * considered not pressed. If you try to construct a KeyStroke with type KeyType.Character with this constructor, it * will always throw an exception; use another overload that allows you to specify the character value instead. * @param keyType Type of the key pressed by this keystroke */ public KeyStroke(KeyType keyType) : this(keyType, false, false) { } /** * Constructs a KeyStroke based on a supplied keyType; character will be null. * If you try to construct a KeyStroke with type KeyType.Character with this constructor, it * will always throw an exception; use another overload that allows you to specify the character value instead. * @param keyType Type of the key pressed by this keystroke * @param ctrlDown Was ctrl held down when the main key was pressed? * @param altDown Was alt held down when the main key was pressed? */ public KeyStroke(KeyType keyType, boolean ctrlDown, boolean altDown) : this(keyType, null, ctrlDown, altDown, false) { } /** * Constructs a KeyStroke based on a supplied keyType; character will be null. * If you try to construct a KeyStroke with type KeyType.Character with this constructor, it * will always throw an exception; use another overload that allows you to specify the character value instead. * @param keyType Type of the key pressed by this keystroke * @param ctrlDown Was ctrl held down when the main key was pressed? * @param altDown Was alt held down when the main key was pressed? * @param shiftDown Was shift held down when the main key was pressed? */ public KeyStroke(KeyType keyType, boolean ctrlDown, boolean altDown, boolean shiftDown) : this(keyType, null, ctrlDown, altDown, shiftDown) { } /** * Constructs a KeyStroke based on a supplied character, keyType is implicitly KeyType.Character. * <p> * A character-based KeyStroke does not support the shiftDown flag, as the shift state has * already been accounted for in the character itself, depending on user's keyboard layout. * @param character Character that was typed on the keyboard * @param ctrlDown Was ctrl held down when the main key was pressed? * @param altDown Was alt held down when the main key was pressed? */ public KeyStroke(char character, boolean ctrlDown, boolean altDown) : this(KeyType.Character, character, ctrlDown, altDown, false) { } private KeyStroke(KeyType keyType, char? character, boolean ctrlDown, bool altDown, bool shiftDown) { if (keyType == KeyType.Character && character == null) { throw new IllegalArgumentException("Cannot construct a KeyStroke with type KeyType.Character but no character information"); } //Enforce character for some key types switch (keyType) { case KeyType.Backspace: character = '\b'; break; case KeyType.Enter: character = '\n'; break; case KeyType.Tab: character = '\t'; break; } this.keyType = keyType; this.character = character ?? ' '; this.shiftDown = shiftDown; this.ctrlDown = ctrlDown; this.altDown = altDown; this.eventTime = DateTime.Now.Millisecond; } /** * Type of key that was pressed on the keyboard, as represented by the KeyType enum. If the value if * KeyType.Character, you need to call getCharacter() to find out which letter, number or symbol that was actually * pressed. * @return Type of key on the keyboard that was pressed */ public KeyType getKeyType() { return keyType; } /** * For keystrokes of ordinary keys (letters, digits, symbols), this method returns the actual character value of the * key. For all other key types, it returns null. * @return Character value of the key pressed, or null if it was a special key */ public char getCharacter() { return character; } /** * @return Returns true if ctrl was help down while the key was typed (depending on terminal implementation) */ public boolean isCtrlDown() { return ctrlDown; } /** * @return Returns true if alt was help down while the key was typed (depending on terminal implementation) */ public boolean isAltDown() { return altDown; } /** * @return Returns true if shift was help down while the key was typed (depending on terminal implementation) */ public boolean isShiftDown() { return shiftDown; } /** * Gets the time when the keystroke was recorded. This isn't necessarily the time the keystroke happened, but when * Lanterna received the event, so it may not be accurate down to the millisecond. * @return The unix time of when the keystroke happened, in milliseconds */ public long getEventTime() { return eventTime; } //@Override public override string ToString() { return "KeyStroke{" + "keyType=" + keyType + ", character=" + character + ", ctrlDown=" + ctrlDown + ", altDown=" + altDown + ", shiftDown=" + shiftDown + "}"; } //@Override public override int GetHashCode() { int hash = 3; hash = 41 * hash + ((this.keyType == null) ? 0 : this.keyType.GetHashCode()); hash = 41 * hash + ((this.character == null) ? 0 : this.character.GetHashCode()); hash = 41 * hash + ((!this.ctrlDown) ? 0 : 1); hash = 41 * hash + ((!this.altDown) ? 0 : 1); hash = 41 * hash + ((!this.shiftDown) ? 0 : 1); return hash; } //@SuppressWarnings("SimplifiableIfStatement") //@Override public override boolean Equals(Object obj) { if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } KeyStroke other = (KeyStroke)obj; return this.keyType == other.keyType && (this.character == other.character || (this.character != null && this.character.Equals(other.character)) ) && (this.ctrlDown == other.ctrlDown && this.altDown == other.altDown && this.shiftDown == other.shiftDown); } /** * Creates a Key from a string representation in Vim's key notation. * * @param keyStr the string representation of this key * @return the created {@link KeyType} */ public static KeyStroke fromString(string keyStr) { String keyStrLC = keyStr.toLowerCase(); KeyStroke k; if (keyStr.length() == 1) { k = new KeyStroke(KeyType.Character, keyStr.charAt(0), false, false, false); } else if (keyStr.startsWith("<") && keyStr.endsWith(">")) { if (keyStrLC.equals("<s-tab>")) { k = new KeyStroke(KeyType.ReverseTab); } else if (keyStr.Contains("-")) { List<String> segments = keyStr.substring(1, keyStr.length() - 1).split('-').ToList(); if (segments.size() < 2) { throw new IllegalArgumentException("Invalid vim notation: " + keyStr); } String characterStr = segments.remove(segments.size() - 1); boolean altPressed = false; boolean ctrlPressed = false; foreach (String modifier in segments) { if ("c".equals(modifier.toLowerCase())) { ctrlPressed = true; } else if ("a".equals(modifier.toLowerCase())) { altPressed = true; } else if ("s".equals(modifier.toLowerCase())) { characterStr = characterStr.toUpperCase(); } } k = new KeyStroke(characterStr.charAt(0), ctrlPressed, altPressed); } else { if (keyStrLC.StartsWith("<esc")) { k = new KeyStroke(KeyType.Escape); } else if (keyStrLC.equals("<cr>") || keyStrLC.equals("<enter>") || keyStrLC.equals("<return>")) { k = new KeyStroke(KeyType.Enter); } else if (keyStrLC.equals("<bs>")) { k = new KeyStroke(KeyType.Backspace); } else if (keyStrLC.equals("<tab>")) { k = new KeyStroke(KeyType.Tab); } else if (keyStrLC.equals("<space>")) { k = new KeyStroke(' ', false, false); } else if (keyStrLC.equals("<up>")) { k = new KeyStroke(KeyType.ArrowUp); } else if (keyStrLC.equals("<down>")) { k = new KeyStroke(KeyType.ArrowDown); } else if (keyStrLC.equals("<left>")) { k = new KeyStroke(KeyType.ArrowLeft); } else if (keyStrLC.equals("<right>")) { k = new KeyStroke(KeyType.ArrowRight); } else if (keyStrLC.equals("<insert>")) { k = new KeyStroke(KeyType.Insert); } else if (keyStrLC.equals("<del>")) { k = new KeyStroke(KeyType.Delete); } else if (keyStrLC.equals("<home>")) { k = new KeyStroke(KeyType.Home); } else if (keyStrLC.equals("<end>")) { k = new KeyStroke(KeyType.End); } else if (keyStrLC.equals("<pageup>")) { k = new KeyStroke(KeyType.PageUp); } else if (keyStrLC.equals("<pagedown>")) { k = new KeyStroke(KeyType.PageDown); } else if (keyStrLC.equals("<f1>")) { k = new KeyStroke(KeyType.F1); } else if (keyStrLC.equals("<f2>")) { k = new KeyStroke(KeyType.F2); } else if (keyStrLC.equals("<f3>")) { k = new KeyStroke(KeyType.F3); } else if (keyStrLC.equals("<f4>")) { k = new KeyStroke(KeyType.F4); } else if (keyStrLC.equals("<f5>")) { k = new KeyStroke(KeyType.F5); } else if (keyStrLC.equals("<f6>")) { k = new KeyStroke(KeyType.F6); } else if (keyStrLC.equals("<f7>")) { k = new KeyStroke(KeyType.F7); } else if (keyStrLC.equals("<f8>")) { k = new KeyStroke(KeyType.F8); } else if (keyStrLC.equals("<f9>")) { k = new KeyStroke(KeyType.F9); } else if (keyStrLC.equals("<f10>")) { k = new KeyStroke(KeyType.F10); } else if (keyStrLC.equals("<f11>")) { k = new KeyStroke(KeyType.F11); } else if (keyStrLC.equals("<f12>")) { k = new KeyStroke(KeyType.F12); } else { throw new IllegalArgumentException("Invalid vim notation: " + keyStr); } } } else { throw new IllegalArgumentException("Invalid vim notation: " + keyStr); } return k; } } }
using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using NServiceKit.Common.Tests.Models; using NServiceKit.DataAnnotations; namespace NServiceKit.OrmLite.Tests { /// <summary>An ORM lite query tests.</summary> [TestFixture] public class OrmLiteQueryTests : OrmLiteTestBase { /// <summary> /// Can get by identifier int from model with fields of different types table. /// </summary> [Test] public void Can_GetById_int_from_ModelWithFieldsOfDifferentTypes_table() { using (var db = OpenDbConnection()) { db.DropAndCreateTable<ModelWithFieldsOfDifferentTypes>(); var rowIds = new List<int>(new[] { 1, 2, 3 }); rowIds.ForEach(x => db.Insert(ModelWithFieldsOfDifferentTypes.Create(x))); var row = db.QueryById<ModelWithFieldsOfDifferentTypes>(1); Assert.That(row.Id, Is.EqualTo(1)); } } /// <summary>Can get by identifier string from model with only string fields table.</summary> [Test] public void Can_GetById_string_from_ModelWithOnlyStringFields_table() { using (var db = OpenDbConnection()) { db.DropAndCreateTable<ModelWithOnlyStringFields>(); var rowIds = new List<string>(new[] { "id-1", "id-2", "id-3" }); rowIds.ForEach(x => db.Insert(ModelWithOnlyStringFields.Create(x))); var row = db.QueryById<ModelWithOnlyStringFields>("id-1"); Assert.That(row.Id, Is.EqualTo("id-1")); } } /// <summary>Can select with filter from model with only string fields table.</summary> [Test] public void Can_select_with_filter_from_ModelWithOnlyStringFields_table() { using (var db = OpenDbConnection()) { db.DropAndCreateTable<ModelWithOnlyStringFields>(); var rowIds = new List<string>(new[] { "id-1", "id-2", "id-3" }); rowIds.ForEach(x => db.Insert(ModelWithOnlyStringFields.Create(x))); var filterRow = ModelWithOnlyStringFields.Create("id-4"); filterRow.AlbumName = "FilteredName"; db.Insert(filterRow); var rows = db.Where<ModelWithOnlyStringFields>(new { filterRow.AlbumName }); var dbRowIds = rows.ConvertAll(x => x.Id); Assert.That(dbRowIds, Has.Count.EqualTo(1)); Assert.That(dbRowIds[0], Is.EqualTo(filterRow.Id)); rows = db.Where<ModelWithOnlyStringFields>(new { filterRow.AlbumName }); dbRowIds = rows.ConvertAll(x => x.Id); Assert.That(dbRowIds, Has.Count.EqualTo(1)); Assert.That(dbRowIds[0], Is.EqualTo(filterRow.Id)); var queryByExample = new ModelWithOnlyStringFields { AlbumName = filterRow.AlbumName }; rows = db.ByExampleWhere<ModelWithOnlyStringFields>(queryByExample); dbRowIds = rows.ConvertAll(x => x.Id); Assert.That(dbRowIds, Has.Count.EqualTo(1)); Assert.That(dbRowIds[0], Is.EqualTo(filterRow.Id)); rows = db.Query<ModelWithOnlyStringFields>( "SELECT * FROM ModelWithOnlyStringFields WHERE AlbumName = @AlbumName", new { filterRow.AlbumName }); dbRowIds = rows.ConvertAll(x => x.Id); Assert.That(dbRowIds, Has.Count.EqualTo(1)); Assert.That(dbRowIds[0], Is.EqualTo(filterRow.Id)); } } /// <summary>Can loop each with filter from model with only string fields table.</summary> [Test] public void Can_loop_each_with_filter_from_ModelWithOnlyStringFields_table() { using (var db = OpenDbConnection()) { db.DropAndCreateTable<ModelWithOnlyStringFields>(); var rowIds = new List<string>(new[] { "id-1", "id-2", "id-3" }); rowIds.ForEach(x => db.Insert(ModelWithOnlyStringFields.Create(x))); var filterRow = ModelWithOnlyStringFields.Create("id-4"); filterRow.AlbumName = "FilteredName"; db.Insert(filterRow); var dbRowIds = new List<string>(); var rows = db.EachWhere<ModelWithOnlyStringFields>(new { filterRow.AlbumName }); foreach (var row in rows) { dbRowIds.Add(row.Id); } Assert.That(dbRowIds, Has.Count.EqualTo(1)); Assert.That(dbRowIds[0], Is.EqualTo(filterRow.Id)); } } /// <summary>Can get single with filter from model with only string fields table.</summary> [Test] public void Can_GetSingle_with_filter_from_ModelWithOnlyStringFields_table() { using (var db = OpenDbConnection()) { db.DropAndCreateTable<ModelWithOnlyStringFields>(); var rowIds = new List<string>(new[] { "id-1", "id-2", "id-3" }); rowIds.ForEach(x => db.Insert(ModelWithOnlyStringFields.Create(x))); var filterRow = ModelWithOnlyStringFields.Create("id-4"); filterRow.AlbumName = "FilteredName"; db.Insert(filterRow); var row = db.QuerySingle<ModelWithOnlyStringFields>(new { filterRow.AlbumName }); Assert.That(row.Id, Is.EqualTo(filterRow.Id)); row = db.QuerySingle<ModelWithOnlyStringFields>(new { filterRow.AlbumName }); Assert.That(row.AlbumName, Is.EqualTo(filterRow.AlbumName)); row = db.QuerySingle<ModelWithOnlyStringFields>(new { AlbumName = "Junk", Id = (object)null }); Assert.That(row, Is.Null); } } /// <summary>A note.</summary> class Note { /// <summary>Gets or sets the identifier.</summary> /// <value>The identifier.</value> [AutoIncrement] // Creates Auto primary key public int Id { get; set; } /// <summary>Gets or sets URI of the schema.</summary> /// <value>The schema URI.</value> public string SchemaUri { get; set; } /// <summary>Gets or sets the note text.</summary> /// <value>The note text.</value> public string NoteText { get; set; } /// <summary>Gets or sets the Date/Time of the last updated.</summary> /// <value>The last updated.</value> public DateTime? LastUpdated { get; set; } /// <summary>Gets or sets who updated this object.</summary> /// <value>Describes who updated this object.</value> public string UpdatedBy { get; set; } } /// <summary>Can query where and select notes.</summary> [Test] public void Can_query_where_and_select_Notes() { using (var db = OpenDbConnection()) { db.DropAndCreateTable<Note>(); db.Insert(new Note { SchemaUri = "tcm:0-0-0", NoteText = "Hello world 5", LastUpdated = new DateTime(2013, 1, 5), UpdatedBy = "RC" }); var notes = db.Where<Note>(new { SchemaUri = "tcm:0-0-0" }); Assert.That(notes[0].Id, Is.EqualTo(1)); Assert.That(notes[0].NoteText, Is.EqualTo("Hello world 5")); notes = db.Select<Note>("SchemaUri={0}", "tcm:0-0-0"); Assert.That(notes[0].Id, Is.EqualTo(1)); Assert.That(notes[0].NoteText, Is.EqualTo("Hello world 5")); notes = db.Query<Note>("SELECT * FROM Note WHERE SchemaUri=@schemaUri", new { schemaUri = "tcm:0-0-0" }); Assert.That(notes[0].Id, Is.EqualTo(1)); Assert.That(notes[0].NoteText, Is.EqualTo("Hello world 5")); notes = db.Query<Note>("SchemaUri=@schemaUri", new { schemaUri = "tcm:0-0-0" }); Assert.That(notes[0].Id, Is.EqualTo(1)); Assert.That(notes[0].NoteText, Is.EqualTo("Hello world 5")); } } /// <summary>A note dto.</summary> class NoteDto { /// <summary>Gets or sets the identifier.</summary> /// <value>The identifier.</value> public int Id { get; set; } /// <summary>Gets or sets URI of the schema.</summary> /// <value>The schema URI.</value> public string SchemaUri { get; set; } /// <summary>Gets or sets the note text.</summary> /// <value>The note text.</value> public string NoteText { get; set; } } /// <summary>Can select notes dto with pretty SQL.</summary> [Test] public void Can_select_NotesDto_with_pretty_sql() { using (var db = OpenDbConnection()) { db.DropAndCreateTable<Note>(); db.Insert(new Note { SchemaUri = "tcm:0-0-0", NoteText = "Hello world 5", LastUpdated = new DateTime(2013, 1, 5), UpdatedBy = "RC" }); var sql = @" SELECT Id, SchemaUri, NoteText FROM Note WHERE SchemaUri=@schemaUri "; var notes = db.Query<NoteDto>(sql, new { schemaUri = "tcm:0-0-0" }); Assert.That(notes[0].Id, Is.EqualTo(1)); Assert.That(notes[0].NoteText, Is.EqualTo("Hello world 5")); } } /// <summary>A customer dto.</summary> class CustomerDto { /// <summary>Gets or sets the identifier of the customer.</summary> /// <value>The identifier of the customer.</value> public int CustomerId { get; set; } /// <summary>Gets or sets the name of the customer.</summary> /// <value>The name of the customer.</value> public string @CustomerName { get; set; } /// <summary>Gets or sets the customer birth date.</summary> /// <value>The customer birth date.</value> public DateTime Customer_Birth_Date { get; set; } } /// <summary> /// Can query customer dto and map database fields not identical by guessing the mapping. /// </summary> /// <param name="field1Name">Name of the field 1.</param> /// <param name="field2Name">Name of the field 2.</param> /// <param name="field3Name">Name of the field 3.</param> [Test] [TestCase("customer_id", "customer_name", "customer_birth_date")] [TestCase("customerid%", "@customername", "customer_b^irth_date")] [TestCase("customerid_%", "@customer_name", "customer$_birth_#date")] [TestCase("c!u@s#t$o%m^e&r*i(d_%", "__cus_tomer__nam_e__", "~cus`tomer$_birth_#date")] [TestCase("t030CustomerId", "t030CustomerName", "t030Customer_birth_date")] [TestCase("t030_customer_id", "t030_customer_name", "t130_customer_birth_date")] [TestCase("t030#Customer_I#d", "t030CustomerNa$^me", "t030Cust^omer_birth_date")] public void Can_query_CustomerDto_and_map_db_fields_not_identical_by_guessing_the_mapping(string field1Name, string field2Name, string field3Name) { using (var db = OpenDbConnection()) { var sql = string.Format(@" SELECT 1 AS [{0}], 'John' AS [{1}], '1970-01-01' AS [{2}] UNION ALL SELECT 2 AS [{0}], 'Jane' AS [{1}], '1980-01-01' AS [{2}]", field1Name, field2Name, field3Name); var customers = db.Query<CustomerDto>(sql); Assert.That(customers.Count, Is.EqualTo(2)); Assert.That(customers[0].CustomerId, Is.EqualTo(1)); Assert.That(customers[0].CustomerName, Is.EqualTo("John")); Assert.That(customers[0].Customer_Birth_Date, Is.EqualTo(new DateTime(1970, 01, 01))); Assert.That(customers[1].CustomerId, Is.EqualTo(2)); Assert.That(customers[1].CustomerName, Is.EqualTo("Jane")); Assert.That(customers[1].Customer_Birth_Date, Is.EqualTo(new DateTime(1980, 01, 01))); } } [Test] public void QueryAndQueryEachEachMustExecuteTheQueryPassedToTheMethod() { using (var db = OpenDbConnection()) { const string query = @"SELECT CustomerId, CustomerName FROM CustomerDto WHERE CustomerName IS NOT NULL AND CustomerName <> ''"; db.CreateTableIfNotExists<CustomerDto>(); DateTime birthDate = DateTime.Now; db.Insert(new CustomerDto {CustomerId = 1, CustomerName = "", Customer_Birth_Date = birthDate}); db.Insert(new CustomerDto {CustomerId = 2, CustomerName = "Test", Customer_Birth_Date = birthDate}); IList<CustomerDto> customers = db.Query<CustomerDto>(query); Assert.AreEqual(1, customers.Count); CustomerDto customer = customers.First(); Assert.AreEqual(2, customer.CustomerId); Assert.AreEqual("Test", customer.CustomerName); Assert.AreNotEqual(birthDate, customer.Customer_Birth_Date); Assert.AreEqual(DateTime.MinValue, customer.Customer_Birth_Date); Assert.AreEqual(query, db.GetLastSql()); customers = db.QueryEach<CustomerDto>(query).ToList(); Assert.AreEqual(1, customers.Count); customer = customers.First(); Assert.AreEqual(2, customer.CustomerId); Assert.AreEqual("Test", customer.CustomerName); Assert.AreNotEqual(birthDate, customer.Customer_Birth_Date); Assert.AreEqual(DateTime.MinValue, customer.Customer_Birth_Date); Assert.AreEqual(query, db.GetLastSql()); } } } }
// 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.Diagnostics.CodeAnalysis; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Reflection; using System.Threading; namespace System.Drawing { public class ColorConverter : TypeConverter { private static object s_valuesLock = new object(); private static StandardValuesCollection s_values; public ColorConverter() { } public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) { return true; } return base.CanConvertFrom(context, sourceType); } public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { #if FEATURE_INSTANCEDESCRIPTOR if (destinationType == typeof(InstanceDescriptor)) { return true; } #endif return base.CanConvertTo(context, destinationType); } [SuppressMessage("Microsoft.Performance", "CA1808:AvoidCallsThatBoxValueTypes")] public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { string strValue = value as string; if (strValue != null) { string text = strValue.Trim(); if (text.Length == 0) { return Color.Empty; } { Color c; // First, check to see if this is a standard name. // if (ColorTable.TryGetNamedColor(text, out c)) { return c; } } if (culture == null) { culture = CultureInfo.CurrentCulture; } char sep = culture.TextInfo.ListSeparator[0]; TypeConverter intConverter = TypeDescriptor.GetConverter(typeof(int)); // If the value is a 6 digit hex number only, then // we want to treat the Alpha as 255, not 0 // if (text.IndexOf(sep) == -1) { // text can be '' (empty quoted string) if (text.Length >= 2 && (text[0] == '\'' || text[0] == '"') && text[0] == text[text.Length - 1]) { // In quotes means a named value string colorName = text.Substring(1, text.Length - 2); return Color.FromName(colorName); } else if ((text.Length == 7 && text[0] == '#') || (text.Length == 8 && (text.StartsWith("0x") || text.StartsWith("0X"))) || (text.Length == 8 && (text.StartsWith("&h") || text.StartsWith("&H")))) { // Note: ConvertFromString will raise exception if value cannot be converted. return PossibleKnownColor(Color.FromArgb(unchecked((int)(0xFF000000 | (uint)(int)intConverter.ConvertFromString(context, culture, text))))); } } // Nope. Parse the RGBA from the text. // string[] tokens = text.Split(sep); int[] values = new int[tokens.Length]; for (int i = 0; i < values.Length; i++) { values[i] = unchecked((int)intConverter.ConvertFromString(context, culture, tokens[i])); } // We should now have a number of parsed integer values. // We support 1, 3, or 4 arguments: // // 1 -- full ARGB encoded // 3 -- RGB // 4 -- ARGB // switch (values.Length) { case 1: return PossibleKnownColor(Color.FromArgb(values[0])); case 3: return PossibleKnownColor(Color.FromArgb(values[0], values[1], values[2])); case 4: return PossibleKnownColor(Color.FromArgb(values[0], values[1], values[2], values[3])); } throw new ArgumentException(SR.Format(SR.InvalidColor, text)); } return base.ConvertFrom(context, culture, value); } private Color PossibleKnownColor(Color color) { // Now check to see if this color matches one of our known colors. // If it does, then substitute it. We can only do this for "Colors" // because system colors morph with user settings. // int targetARGB = color.ToArgb(); foreach (Color c in ColorTable.Colors.Values) { if (c.ToArgb() == targetARGB) { return c; } } return color; } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == null) { throw new ArgumentNullException(nameof(destinationType)); } if (value is Color) { if (destinationType == typeof(string)) { Color c = (Color)value; if (c == Color.Empty) { return string.Empty; } else { // If this is a known color, then Color can provide its own // name. Otherwise, we fabricate an ARGB value for it. // if (c.IsKnownColor) { return c.Name; } else if (c.IsNamedColor) { return "'" + c.Name + "'"; } else { if (culture == null) { culture = CultureInfo.CurrentCulture; } string sep = culture.TextInfo.ListSeparator + " "; TypeConverter intConverter = TypeDescriptor.GetConverter(typeof(int)); string[] args; int nArg = 0; if (c.A < 255) { args = new string[4]; args[nArg++] = intConverter.ConvertToString(context, culture, (object)c.A); } else { args = new string[3]; } // Note: ConvertToString will raise exception if value cannot be converted. args[nArg++] = intConverter.ConvertToString(context, culture, (object)c.R); args[nArg++] = intConverter.ConvertToString(context, culture, (object)c.G); args[nArg++] = intConverter.ConvertToString(context, culture, (object)c.B); // Now slam all of these together with the fantastic Join // method. // return string.Join(sep, args); } } } #if FEATURE_INSTANCEDESCRIPTOR if (destinationType == typeof(InstanceDescriptor)) { MemberInfo member = null; object[] args = null; Color c = (Color)value; if (c.IsEmpty) { member = typeof(Color).GetField("Empty"); } else if (c.IsSystemColor) { member = typeof(SystemColors).GetProperty(c.Name); } else if (c.IsKnownColor) { member = typeof(Color).GetProperty(c.Name); } else if (c.A != 255) { member = typeof(Color).GetMethod("FromArgb", new Type[] { typeof(int), typeof(int), typeof(int), typeof(int) }); args = new object[] { c.A, c.R, c.G, c.B }; } else if (c.IsNamedColor) { member = typeof(Color).GetMethod("FromName", new Type[] { typeof(string) }); args = new object[] { c.Name }; } else { member = typeof(Color).GetMethod("FromArgb", new Type[] { typeof(int), typeof(int), typeof(int) }); args = new object[] { c.R, c.G, c.B }; } Debug.Assert(member != null, "Could not convert color to member. Did someone change method name / signature and not update Colorconverter?"); if (member != null) { return new InstanceDescriptor(member, args); } else { return null; } } #endif } return base.ConvertTo(context, culture, value, destinationType); } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { if (s_values == null) { lock (s_valuesLock) { if (s_values == null) { // We must take the value from each hashtable and combine them. // HashSet<Color> set = new HashSet<Color>(ColorTable.Colors.Values.Concat(ColorTable.SystemColors.Values)); s_values = new StandardValuesCollection(set.OrderBy(c => c, new ColorComparer()).ToList()); } } } return s_values; } public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } private class ColorComparer : IComparer<Color> { public int Compare(Color left, Color right) { return string.CompareOrdinal(left.Name, right.Name); } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using BTDB.Buffer; using BTDB.Encrypted; using BTDB.FieldHandler; using BTDB.IL; using BTDB.KVDBLayer; using BTDB.StreamLayer; namespace BTDB.ODBLayer { delegate void SkipperFun(ref SpanReader reader); delegate object? LoaderFun(ref SpanReader reader); public class ODBIterator { readonly IInternalObjectDBTransaction _tr; IODBFastVisitor _fastVisitor; IODBVisitor? _visitor; Dictionary<uint, string> _tableId2Name; readonly IKeyValueDBTransaction _trkv; Dictionary<uint, ulong> _singletons; readonly HashSet<uint> _usedTableIds; readonly HashSet<ulong> _visitedOids; readonly HashSet<TableIdVersionId> _usedTableVersions; readonly Dictionary<TableIdVersionId, TableVersionInfo> _tableVersionInfos; readonly Dictionary<IFieldHandler, SkipperFun> _skippers; readonly Dictionary<IFieldHandler, LoaderFun> _loaders; //relations Dictionary<uint, ODBIteratorRelationInfo> _relationId2Info; public IDictionary<uint, string> TableId2Name => _tableId2Name; public IReadOnlyDictionary<uint, ulong> TableId2SingletonOid => _singletons; public IReadOnlyDictionary<uint, ODBIteratorRelationInfo> RelationId2Info => _relationId2Info; public IReadOnlyDictionary<TableIdVersionId, TableVersionInfo> TableVersionInfos => _tableVersionInfos; public bool SkipAlreadyVisitedOidChecks; public ODBIterator(IObjectDBTransaction tr, IODBFastVisitor visitor) { _tr = (IInternalObjectDBTransaction)tr; _trkv = _tr.KeyValueDBTransaction; _fastVisitor = visitor; _visitor = visitor as IODBVisitor; _usedTableIds = new HashSet<uint>(); _visitedOids = new HashSet<ulong>(); _usedTableVersions = new HashSet<TableIdVersionId>(); _tableVersionInfos = new Dictionary<TableIdVersionId, TableVersionInfo>(); _skippers = new Dictionary<IFieldHandler, SkipperFun>(ReferenceEqualityComparer<IFieldHandler>.Instance); _loaders = new Dictionary<IFieldHandler, LoaderFun>(ReferenceEqualityComparer<IFieldHandler>.Instance); } public void LoadGlobalInfo(bool sortTableByNameAsc = false) { LoadTableNamesDict(); LoadRelationInfoDict(); MarkLastDictId(); _trkv.InvalidateCurrentKey(); _singletons = new Dictionary<uint, ulong>(); while (_trkv.FindNextKey(ObjectDB.TableSingletonsPrefix)) { _singletons.Add(new SpanReader(_trkv.GetKey().Slice((int)ObjectDB.TableSingletonsPrefixLen)).ReadVUInt32(), new SpanReader(_trkv.GetValue()).ReadVUInt64()); } if (sortTableByNameAsc) { _singletons = _singletons.OrderBy(item => _tableId2Name.TryGetValue(item.Key, out var name) ? name : "").ToDictionary(item => item.Key, item => item.Value); } } public void Iterate(bool sortTableByNameAsc = false) { LoadGlobalInfo(sortTableByNameAsc); foreach (var singleton in _singletons) { if (_visitor != null && !_visitor.VisitSingleton(singleton.Key, _tableId2Name.TryGetValue(singleton.Key, out var name) ? name : null, singleton.Value)) continue; MarkTableName(singleton.Key); if (_trkv.Find(Vuint2ByteBuffer(ObjectDB.TableSingletonsPrefix, singleton.Key), 0) == FindResult.Exact) { _fastVisitor.MarkCurrentKeyAsUsed(_trkv); } IterateOid(singleton.Value); } foreach (var relation in _relationId2Info) { if (_visitor != null && !_visitor.StartRelation(relation.Value)) continue; MarkRelationName(relation.Key); IterateRelation(relation.Value); _visitor?.EndRelation(); } } public void IterateUnseenOid(ulong oid, IODBFastVisitor visitor) { var visitorBackup = _visitor; var fastVisitorBackup = _fastVisitor; try { _visitor = visitor as IODBVisitor; _fastVisitor = visitor; IterateOid(oid); } finally { _visitor = visitorBackup; _fastVisitor = fastVisitorBackup; } } public void IterateOid(ulong oid) { if (!SkipAlreadyVisitedOidChecks && !_visitedOids.Add(oid)) return; if (!_trkv.FindExactKey(Vuint2ByteBuffer(ObjectDB.AllObjectsPrefix, oid))) return; // Object oid was deleted _fastVisitor.MarkCurrentKeyAsUsed(_trkv); var reader = new SpanReader(_trkv.GetValue()); var tableId = reader.ReadVUInt32(); var version = reader.ReadVUInt32(); MarkTableIdVersionFieldInfo(tableId, version); if (_visitor != null && !_visitor.StartObject(oid, tableId, _tableId2Name.TryGetValue(tableId, out var tableName) ? tableName : null, version)) return; var tvi = GetTableVersionInfo(tableId, version); var knownInlineId = new HashSet<int>(); for (var i = 0; i < tvi.FieldCount; i++) { var fi = tvi[i]; if (_visitor == null || _visitor.StartField(fi.Name)) { IterateHandler(ref reader, fi.Handler!, false, knownInlineId); _visitor?.EndField(); } else { IterateHandler(ref reader, fi.Handler!, true, knownInlineId); } } _visitor?.EndObject(); } public void IterateRelationRow(ODBIteratorRelationInfo relation, long pos) { var prefix = BuildRelationPrefix(relation.Id); if (!_trkv.SetKeyIndex(prefix, pos)) return; var prevProtectionCounter = _trkv.CursorMovedCounter; if (_visitor == null || _visitor.StartRelationKey()) { var keyReader = new SpanReader(_trkv.GetKey().Slice(prefix.Length)); var relationInfo = relation.VersionInfos[relation.LastPersistedVersion]; IterateFields(ref keyReader, relationInfo.PrimaryKeyFields.Span, null); _visitor?.EndRelationKey(); } if (_trkv.CursorMovedCounter != prevProtectionCounter) { if (!_trkv.SetKeyIndex(prefix, pos)) return; } if (_visitor == null || _visitor.StartRelationValue()) { var valueReader = new SpanReader(_trkv.GetValue()); var version = valueReader.ReadVUInt32(); var relationInfo = relation.VersionInfos[version]; IterateFields(ref valueReader, relationInfo.Fields.Span, new HashSet<int>()); _visitor?.EndRelationValue(); } } public void IterateRelation(ODBIteratorRelationInfo relation) { IterateSecondaryIndexes(relation); var prefix = BuildRelationPrefix(relation.Id); long prevProtectionCounter = 0; long pos = 0; while (true) { if (pos == 0) { if (!_trkv.FindFirstKey(prefix)) break; } else { if (_trkv.CursorMovedCounter != prevProtectionCounter) { if (!_trkv.SetKeyIndex(prefix, pos)) break; } else { if (!_trkv.FindNextKey(prefix)) break; } } _fastVisitor.MarkCurrentKeyAsUsed(_trkv); prevProtectionCounter = _trkv.CursorMovedCounter; if (_visitor == null || _visitor.StartRelationKey()) { var keyReader = new SpanReader(_trkv.GetKey().Slice(prefix.Length)); var relationInfo = relation.VersionInfos[relation.LastPersistedVersion]; IterateFields(ref keyReader, relationInfo.PrimaryKeyFields.Span, null); _visitor?.EndRelationKey(); } if (_trkv.CursorMovedCounter != prevProtectionCounter) { if (!_trkv.SetKeyIndex(prefix, pos)) break; } if (_visitor == null || _visitor.StartRelationValue()) { var valueReader = new SpanReader(_trkv.GetValue()); var version = valueReader.ReadVUInt32(); var relationInfo = relation.VersionInfos[version]; IterateFields(ref valueReader, relationInfo.Fields.Span, new HashSet<int>()); _visitor?.EndRelationValue(); } pos++; } } void IterateSecondaryIndexes(ODBIteratorRelationInfo relation) { var version = relation.VersionInfos[relation.LastPersistedVersion]; foreach (var (secKeyName, secKeyIdx) in version.SecondaryKeysNames) { var secondaryKeyFields = version.GetSecondaryKeyFields(secKeyIdx); if (_visitor == null || _visitor.StartSecondaryIndex(secKeyName)) { var prefix = BuildRelationSecondaryKeyPrefix(relation.Id, secKeyIdx); long prevProtectionCounter = 0; long pos = 0; while (true) { if (pos == 0) { if (!_trkv.FindFirstKey(prefix)) break; } else { if (_trkv.CursorMovedCounter != prevProtectionCounter) { if (!_trkv.SetKeyIndex(prefix, pos)) break; } else { if (!_trkv.FindNextKey(prefix)) break; } } var reader = new SpanReader(_trkv.GetKey().Slice(prefix.Length)); foreach (var fi in secondaryKeyFields) { if (_visitor == null || !_visitor.StartField(fi.Name)) continue; IterateHandler(ref reader, fi.Handler!, false, null); } _visitor?.NextSecondaryKey(); pos++; } _visitor?.EndSecondaryIndex(); } } } static byte[] BuildRelationSecondaryKeyPrefix(uint relationIndex, uint secondaryKeyIndex) { var prefix = new byte[1 + PackUnpack.LengthVUInt(relationIndex) + PackUnpack.LengthVUInt(secondaryKeyIndex)]; prefix[0] = ObjectDB.AllRelationsSKPrefixByte; int pos = 1; PackUnpack.PackVUInt(prefix, ref pos, relationIndex); PackUnpack.PackVUInt(prefix, ref pos, secondaryKeyIndex); return prefix; } static byte[] BuildRelationPrefix(uint relationIndex) { var o = ObjectDB.AllRelationsPKPrefix.Length; var prefix = new byte[o + PackUnpack.LengthVUInt(relationIndex)]; Array.Copy(ObjectDB.AllRelationsPKPrefix, prefix, o); PackUnpack.PackVUInt(prefix, ref o, relationIndex); return prefix; } void IterateFields(ref SpanReader reader, ReadOnlySpan<TableFieldInfo> fields, HashSet<int>? knownInlineRefs) { foreach (var fi in fields) { if (_visitor == null || _visitor.StartField(fi.Name)) { IterateHandler(ref reader, fi.Handler!, false, knownInlineRefs); _visitor?.EndField(); } else { IterateHandler(ref reader, fi.Handler!, true, knownInlineRefs); } } } uint ReadRelationVersions(uint relationIndex, string name, Dictionary<uint, RelationVersionInfo> relationVersions) { uint lastPersistedVersion = 0; var relationInfoResolver = new RelationInfoResolver((ObjectDB)_tr.Owner); var writer = new SpanWriter(); writer.WriteByteArrayRaw(ObjectDB.RelationVersionsPrefix); writer.WriteVUInt32(relationIndex); var prefix = writer.GetSpan().ToArray(); if (!_trkv.FindFirstKey(prefix)) { return lastPersistedVersion; } do { var keyReader = new SpanReader(_trkv.GetKey().Slice(prefix.Length)); var valueReader = new SpanReader(_trkv.GetValue()); lastPersistedVersion = keyReader.ReadVUInt32(); var relationVersionInfo = RelationVersionInfo.LoadUnresolved(ref valueReader, name); relationVersionInfo.ResolveFieldHandlers(relationInfoResolver.FieldHandlerFactory); relationVersions[lastPersistedVersion] = relationVersionInfo; } while (_trkv.FindNextKey(prefix)); return lastPersistedVersion; } [SkipLocalsInit] void IterateDict(ulong dictId, IFieldHandler keyHandler, IFieldHandler valueHandler) { if (_visitor != null && !_visitor.StartDictionary()) return; var o = ObjectDB.AllDictionariesPrefix.Length; var prefix = new byte[o + PackUnpack.LengthVUInt(dictId)]; Array.Copy(ObjectDB.AllDictionariesPrefix, prefix, o); PackUnpack.PackVUInt(prefix, ref o, dictId); long prevProtectionCounter = 0; long pos = 0; Span<byte> keyBuffer = stackalloc byte[512]; while (true) { if (pos == 0) { if (!_trkv.FindFirstKey(prefix)) break; } else { if (_trkv.CursorMovedCounter != prevProtectionCounter) { if (!_trkv.SetKeyIndex(prefix, pos)) break; } else { if (!_trkv.FindNextKey(prefix)) break; } } _fastVisitor.MarkCurrentKeyAsUsed(_trkv); prevProtectionCounter = _trkv.CursorMovedCounter; if (_visitor == null || _visitor.StartDictKey()) { var keyReader = new SpanReader(_trkv.GetKey(ref MemoryMarshal.GetReference(keyBuffer), keyBuffer.Length).Slice(prefix.Length)); IterateHandler(ref keyReader, keyHandler, false, null); _visitor?.EndDictKey(); } if (_trkv.CursorMovedCounter != prevProtectionCounter) { if (!_trkv.SetKeyIndex(prefix, pos)) break; } if (_visitor == null || _visitor.StartDictValue()) { var valueReader = new SpanReader(_trkv.GetValue()); IterateHandler(ref valueReader, valueHandler, false, null); _visitor?.EndDictValue(); } pos++; } _visitor?.EndDictionary(); } void IterateSet(ulong dictId, IFieldHandler keyHandler) { if (_visitor != null && !_visitor.StartSet()) return; var o = ObjectDB.AllDictionariesPrefix.Length; var prefix = new byte[o + PackUnpack.LengthVUInt(dictId)]; Array.Copy(ObjectDB.AllDictionariesPrefix, prefix, o); PackUnpack.PackVUInt(prefix, ref o, dictId); long prevProtectionCounter = 0; long pos = 0; while (true) { if (pos == 0) { if (!_trkv.FindFirstKey(prefix)) break; } else { if (_trkv.CursorMovedCounter != prevProtectionCounter) { if (!_trkv.SetKeyIndex(prefix, pos)) break; } else { if (!_trkv.FindNextKey(prefix)) break; } } _fastVisitor.MarkCurrentKeyAsUsed(_trkv); prevProtectionCounter = _trkv.CursorMovedCounter; if (_visitor == null || _visitor.StartSetKey()) { var keyReader = new SpanReader(_trkv.GetKey().Slice(prefix.Length)); IterateHandler(ref keyReader, keyHandler, false, null); _visitor?.EndSetKey(); } pos++; } _visitor?.EndSet(); } void IterateHandler(ref SpanReader reader, IFieldHandler handler, bool skipping, HashSet<int>? knownInlineRefs) { if (handler is ODBDictionaryFieldHandler) { var dictId = reader.ReadVUInt64(); if (!skipping) { var kvHandlers = ((IFieldHandlerWithNestedFieldHandlers)handler).EnumerateNestedFieldHandlers().ToArray(); IterateDict(dictId, kvHandlers[0], kvHandlers[1]); } } else if (handler is ODBSetFieldHandler) { var dictId = reader.ReadVUInt64(); if (!skipping) { var keyHandler = ((IFieldHandlerWithNestedFieldHandlers)handler).EnumerateNestedFieldHandlers().First(); IterateSet(dictId, keyHandler); } } else if (handler is DBObjectFieldHandler) { var oid = reader.ReadVInt64(); if (oid == 0) { if (!skipping) _visitor?.OidReference(0); } else if (oid <= int.MinValue || oid > 0) { if (!skipping) { _visitor?.OidReference((ulong)oid); IterateOid((ulong)oid); } } else { if (knownInlineRefs != null) { if (knownInlineRefs.Contains((int)oid)) { if (!skipping) _visitor?.InlineBackRef((int)oid); return; } if (!skipping) _visitor?.InlineRef((int)oid); knownInlineRefs.Add((int)oid); } var tableId = reader.ReadVUInt32(); var version = reader.ReadVUInt32(); if (!skipping) MarkTableIdVersionFieldInfo(tableId, version); var skip = skipping || _visitor != null && !_visitor.StartInlineObject(tableId, _tableId2Name.TryGetValue(tableId, out var tableName) ? tableName : null, version); var tvi = GetTableVersionInfo(tableId, version); var knownInlineRefsNested = new HashSet<int>(); for (var i = 0; i < tvi.FieldCount; i++) { var fi = tvi[i]; var skipField = skip || _visitor != null && !_visitor.StartField(fi.Name); IterateHandler(ref reader, fi.Handler!, skipField, knownInlineRefsNested); if (!skipField) _visitor?.EndField(); } if (!skip) _visitor?.EndInlineObject(); } } else if (handler is ListFieldHandler) { var oid = reader.ReadVInt64(); if (oid == 0) { if (!skipping) _visitor?.OidReference(0); } else if (oid <= int.MinValue || oid > 0) { if (!skipping) { _visitor?.OidReference((ulong)oid); IterateOid((ulong)oid); } } else { var itemHandler = ((IFieldHandlerWithNestedFieldHandlers)handler).EnumerateNestedFieldHandlers().First(); IterateInlineList(ref reader, itemHandler, skipping, knownInlineRefs); } } else if (handler is DictionaryFieldHandler) { var oid = reader.ReadVInt64(); if (oid == 0) { if (!skipping) _visitor?.OidReference(0); } else if (oid <= int.MinValue || oid > 0) { if (!skipping) { _visitor?.OidReference((ulong)oid); IterateOid((ulong)oid); } } else { var kvHandlers = ((IFieldHandlerWithNestedFieldHandlers)handler).EnumerateNestedFieldHandlers().ToArray(); IterateInlineDict(ref reader, kvHandlers[0], kvHandlers[1], skipping, knownInlineRefs); } } else if (handler is NullableFieldHandler) { var hasValue = reader.ReadBool(); if (hasValue) { var itemHandler = ((IFieldHandlerWithNestedFieldHandlers)handler).EnumerateNestedFieldHandlers().First(); IterateHandler(ref reader, itemHandler, skipping, null); } } else if (handler is OrderedEncryptedStringHandler) { var cipher = _tr.Owner.GetSymmetricCipher(); if (cipher is InvalidSymmetricCipher) { var length = reader.ReadVUInt32(); _visitor?.ScalarAsText($"Encrypted[{length}]"); if (length > 0) reader.SkipBlock(length - 1); } else { var enc = reader.ReadByteArray(); var size = cipher.CalcOrderedPlainSizeFor(enc); var dec = new byte[size]; if (!cipher.OrderedDecrypt(enc, dec)) { _visitor?.ScalarAsText($"Encrypted[{enc!.Length}] failed to decrypt"); } var r = new SpanReader(dec); _visitor?.ScalarAsText(r.ReadString()!); } } else if (handler is EncryptedStringHandler) { var cipher = _tr.Owner.GetSymmetricCipher(); if (cipher is InvalidSymmetricCipher) { var length = reader.ReadVUInt32(); _visitor?.ScalarAsText($"Encrypted[{length}]"); if (length > 0) reader.SkipBlock(length - 1); } else { var enc = reader.ReadByteArray(); var size = cipher.CalcPlainSizeFor(enc); var dec = new byte[size]; if (!cipher.Decrypt(enc, dec)) { _visitor?.ScalarAsText($"Encrypted[{enc!.Length}] failed to decrypt"); } var r = new SpanReader(dec); _visitor?.ScalarAsText(r.ReadString()!); } } else if (handler is TupleFieldHandler tupleFieldHandler) { foreach (var fieldHandler in tupleFieldHandler.EnumerateNestedFieldHandlers()) { var skipField = _visitor != null && !_visitor.StartItem(); IterateHandler(ref reader, fieldHandler, skipField, knownInlineRefs); if (!skipField) _visitor?.EndItem(); } } else if (handler.NeedsCtx() || handler.HandledType() == null) { throw new BTDBException("Don't know how to iterate " + handler.Name); } else { if (skipping || _visitor == null) { if (!_skippers.TryGetValue(handler, out var skipper)) { var meth = ILBuilder.Instance.NewMethod<SkipperFun>("Skip" + handler.Name); var il = meth.Generator; handler.Skip(il, il2 => il2.Ldarg(0), null); il.Ret(); skipper = meth.Create(); _skippers.Add(handler, skipper); } skipper(ref reader); } else { if (!_loaders.TryGetValue(handler, out var loader)) { var meth = ILBuilder.Instance.NewMethod<LoaderFun>("Load" + handler.Name); var il = meth.Generator; handler.Load(il, il2 => il2.Ldarg(0), null); il.Box(handler.HandledType()!).Ret(); loader = meth.Create(); _loaders.Add(handler, loader); } var obj = loader(ref reader); if (_visitor.NeedScalarAsObject()) { _visitor.ScalarAsObject(obj); } if (_visitor.NeedScalarAsText()) { _visitor.ScalarAsText(obj == null ? "null" : string.Format(CultureInfo.InvariantCulture, "{0}", obj)); } } } } void IterateInlineDict(ref SpanReader reader, IFieldHandler keyHandler, IFieldHandler valueHandler, bool skipping, HashSet<int>? knownInlineRefs) { var skip = skipping || _visitor != null && !_visitor.StartDictionary(); var count = reader.ReadVUInt32(); while (count-- > 0) { var skipKey = skip || _visitor != null && !_visitor.StartDictKey(); IterateHandler(ref reader, keyHandler, skipKey, knownInlineRefs); if (!skipKey) _visitor?.EndDictKey(); var skipValue = skip || _visitor != null && !_visitor.StartDictValue(); IterateHandler(ref reader, valueHandler, skipValue, knownInlineRefs); if (!skipValue) _visitor?.EndDictValue(); } if (!skip) _visitor?.EndDictionary(); } void IterateInlineList(ref SpanReader reader, IFieldHandler itemHandler, bool skipping, HashSet<int>? knownInlineRefs) { var skip = skipping || _visitor != null && !_visitor.StartList(); var count = reader.ReadVUInt32(); while (count-- > 0) { var skipItem = skip || _visitor != null && !_visitor.StartItem(); IterateHandler(ref reader, itemHandler, skipItem, knownInlineRefs); if (!skipItem) _visitor?.EndItem(); } if (!skip) _visitor?.EndList(); } void MarkTableIdVersionFieldInfo(uint tableId, uint version) { if (!_usedTableVersions.Add(new TableIdVersionId(tableId, version))) return; MarkTableName(tableId); if (_trkv.Find(TwiceVuint2ByteBuffer(ObjectDB.TableVersionsPrefix, tableId, version), 0) == FindResult.Exact) { _fastVisitor.MarkCurrentKeyAsUsed(_trkv); } } void MarkLastDictId() { if (_trkv.FindExactKey(ObjectDB.LastDictIdKey)) { _fastVisitor.MarkCurrentKeyAsUsed(_trkv); } } void MarkTableName(uint tableId) { if (!_usedTableIds.Add(tableId)) return; if (_trkv.FindExactKey(Vuint2ByteBuffer(ObjectDB.TableNamesPrefix, tableId))) { _fastVisitor.MarkCurrentKeyAsUsed(_trkv); } } void MarkRelationName(uint relationId) { if (_trkv.FindExactKey(Vuint2ByteBuffer(ObjectDB.RelationNamesPrefix, relationId))) { _fastVisitor.MarkCurrentKeyAsUsed(_trkv); } } ReadOnlySpan<byte> Vuint2ByteBuffer(in ReadOnlySpan<byte> prefix, ulong value) { var writer = new SpanWriter(); writer.WriteBlock(prefix); writer.WriteVUInt64(value); return writer.GetSpan(); } ReadOnlySpan<byte> TwiceVuint2ByteBuffer(in ReadOnlySpan<byte> prefix, uint v1, uint v2) { var writer = new SpanWriter(); writer.WriteBlock(prefix); writer.WriteVUInt32(v1); writer.WriteVUInt32(v2); return writer.GetSpan(); } void LoadTableNamesDict() { _tableId2Name = ObjectDB.LoadTablesEnum(_tr.KeyValueDBTransaction) .ToDictionary(pair => pair.Key, pair => pair.Value); } void LoadRelationInfoDict() { _relationId2Info = ObjectDB.LoadRelationNamesEnum(_tr.KeyValueDBTransaction).ToList() .ToDictionary(pair => pair.Key, pair => LoadRelationInfo(pair)); } ODBIteratorRelationInfo LoadRelationInfo(KeyValuePair<uint, string> idName) { var res = new ODBIteratorRelationInfo { Id = idName.Key, Name = idName.Value, }; var relationVersions = new Dictionary<uint, RelationVersionInfo>(); res.LastPersistedVersion = ReadRelationVersions(res.Id, res.Name, relationVersions); res.VersionInfos = relationVersions; res.RowCount = _trkv.GetKeyValueCount(BuildRelationPrefix(res.Id)); return res; } TableVersionInfo GetTableVersionInfo(uint tableId, uint version) { if (_tableVersionInfos.TryGetValue(new TableIdVersionId(tableId, version), out var res)) return res; if (_trkv.FindExactKey(TwiceVuint2ByteBuffer(ObjectDB.TableVersionsPrefix, tableId, version))) { var reader = new SpanReader(_trkv.GetValue()); res = TableVersionInfo.Load(ref reader, _tr.Owner.FieldHandlerFactory, _tableId2Name[tableId]); _tableVersionInfos.Add(new TableIdVersionId(tableId, version), res); return res; } throw new ArgumentException($"TableVersionInfo not found {tableId}-{version}"); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Linq; namespace Prism.Regions { /// <summary> /// Implementation of <see cref="IViewsCollection"/> that takes an <see cref="ObservableCollection{T}"/> of <see cref="ItemMetadata"/> /// and filters it to display an <see cref="INotifyCollectionChanged"/> collection of /// <see cref="object"/> elements (the items which the <see cref="ItemMetadata"/> wraps). /// </summary> public partial class ViewsCollection : IViewsCollection { private readonly ObservableCollection<ItemMetadata> subjectCollection; private readonly Dictionary<ItemMetadata, MonitorInfo> monitoredItems = new Dictionary<ItemMetadata, MonitorInfo>(); private readonly Predicate<ItemMetadata> filter; private Comparison<object> sort; private List<object> filteredItems = new List<object>(); /// <summary> /// Initializes a new instance of the <see cref="ViewsCollection"/> class. /// </summary> /// <param name="list">The list to wrap and filter.</param> /// <param name="filter">A predicate to filter the <paramref name="list"/> collection.</param> public ViewsCollection(ObservableCollection<ItemMetadata> list, Predicate<ItemMetadata> filter) { this.subjectCollection = list; this.filter = filter; this.MonitorAllMetadataItems(); this.subjectCollection.CollectionChanged += this.SourceCollectionChanged; this.UpdateFilteredItemsList(); } /// <summary> /// Occurs when the collection changes. /// </summary> public event NotifyCollectionChangedEventHandler CollectionChanged; /// <summary> /// Gets or sets the comparison used to sort the views. /// </summary> /// <value>The comparison to use.</value> public Comparison<object> SortComparison { get { return this.sort; } set { if (this.sort != value) { this.sort = value; this.UpdateFilteredItemsList(); this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } } } private IEnumerable<object> FilteredItems { get { return this.filteredItems; } } /// <summary> /// Determines whether the collection contains a specific value. /// </summary> /// <param name="value">The object to locate in the collection.</param> /// <returns><see langword="true" /> if <paramref name="value"/> is found in the collection; otherwise, <see langword="false" />.</returns> public bool Contains(object value) { return this.FilteredItems.Contains(value); } ///<summary> ///Returns an enumerator that iterates through the collection. ///</summary> ///<returns> ///A <see cref="T:System.Collections.Generic.IEnumerator`1" /> that can be used to iterate through the collection. ///</returns> public IEnumerator<object> GetEnumerator() { return this.FilteredItems.GetEnumerator(); } ///<summary> ///Returns an enumerator that iterates through a collection. ///</summary> ///<returns> ///An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection. ///</returns> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } /// <summary> /// Used to invoked the <see cref="CollectionChanged"/> event. /// </summary> /// <param name="e"></param> private void OnCollectionChanged(NotifyCollectionChangedEventArgs e) { NotifyCollectionChangedEventHandler handler = this.CollectionChanged; if (handler != null) handler(this, e); } private void NotifyReset() { this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } /// <summary> /// Removes all monitoring of underlying MetadataItems and re-adds them. /// </summary> private void ResetAllMonitors() { this.RemoveAllMetadataMonitors(); this.MonitorAllMetadataItems(); } /// <summary> /// Adds all underlying MetadataItems to the list from the subjectCollection /// </summary> private void MonitorAllMetadataItems() { foreach (var item in this.subjectCollection) { this.AddMetadataMonitor(item, this.filter(item)); } } /// <summary> /// Removes all monitored items from our monitoring list. /// </summary> private void RemoveAllMetadataMonitors() { foreach (var item in this.monitoredItems) { item.Key.MetadataChanged -= this.OnItemMetadataChanged; } this.monitoredItems.Clear(); } /// <summary> /// Adds handler to monitor the MetadatItem and adds it to our monitoring list. /// </summary> /// <param name="itemMetadata"></param> /// <param name="isInList"></param> private void AddMetadataMonitor(ItemMetadata itemMetadata, bool isInList) { itemMetadata.MetadataChanged += this.OnItemMetadataChanged; this.monitoredItems.Add( itemMetadata, new MonitorInfo { IsInList = isInList }); } /// <summary> /// Unhooks from the MetadataItem change event and removes from our monitoring list. /// </summary> /// <param name="itemMetadata"></param> private void RemoveMetadataMonitor(ItemMetadata itemMetadata) { itemMetadata.MetadataChanged -= this.OnItemMetadataChanged; this.monitoredItems.Remove(itemMetadata); } /// <summary> /// Invoked when any of the underlying ItemMetadata items we're monitoring changes. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnItemMetadataChanged(object sender, EventArgs e) { ItemMetadata itemMetadata = (ItemMetadata) sender; // Our monitored item may have been removed during another event before // our OnItemMetadataChanged got called back, so it's not unexpected // that we may not have it in our list. MonitorInfo monitorInfo; bool foundInfo = this.monitoredItems.TryGetValue(itemMetadata, out monitorInfo); if (!foundInfo) return; if (this.filter(itemMetadata)) { if (!monitorInfo.IsInList) { // This passes our filter and wasn't marked // as in our list so we can consider this // an Add. monitorInfo.IsInList = true; this.UpdateFilteredItemsList(); NotifyAdd(itemMetadata.Item); } } else { // This doesn't fit our filter, we remove from our // tracking list, but should not remove any monitoring in // case it fits our filter in the future. monitorInfo.IsInList = false; this.RemoveFromFilteredList(itemMetadata.Item); } } /// <summary> /// The event handler due to changes in the underlying collection. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void SourceCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { switch (e.Action) { case NotifyCollectionChangedAction.Add: this.UpdateFilteredItemsList(); foreach (ItemMetadata itemMetadata in e.NewItems) { bool isInFilter = this.filter(itemMetadata); this.AddMetadataMonitor(itemMetadata, isInFilter); if (isInFilter) { NotifyAdd(itemMetadata.Item); } } // If we're sorting we can't predict how // the collection has changed on an add so we // resort to a reset notification. if (this.sort != null) { this.NotifyReset(); } break; case NotifyCollectionChangedAction.Remove: foreach (ItemMetadata itemMetadata in e.OldItems) { this.RemoveMetadataMonitor(itemMetadata); if (this.filter(itemMetadata)) { this.RemoveFromFilteredList(itemMetadata.Item); } } break; default: this.ResetAllMonitors(); this.UpdateFilteredItemsList(); this.NotifyReset(); break; } } private void NotifyAdd(object item) { int newIndex = this.filteredItems.IndexOf(item); this.NotifyAdd(new[] { item }, newIndex); } private void RemoveFromFilteredList(object item) { int index = this.filteredItems.IndexOf(item); this.UpdateFilteredItemsList(); this.NotifyRemove(new[] { item }, index); } private void UpdateFilteredItemsList() { this.filteredItems = this.subjectCollection.Where(i => this.filter(i)).Select(i => i.Item) .OrderBy<object, object>(o => o, new RegionItemComparer(this.SortComparison)).ToList(); } private class MonitorInfo { public bool IsInList { get; set; } } private class RegionItemComparer : Comparer<object> { private readonly Comparison<object> comparer; public RegionItemComparer(Comparison<object> comparer) { this.comparer = comparer; } public override int Compare(object x, object y) { if (this.comparer == null) { return 0; } return this.comparer(x, y); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace FlexTimeKeeper.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.2.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace AwesomeNamespace { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// UsageOperations operations. /// </summary> internal partial class UsageOperations : IServiceOperations<StorageManagementClient>, IUsageOperations { /// <summary> /// Initializes a new instance of the UsageOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal UsageOperations(StorageManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the StorageManagementClient /// </summary> public StorageManagementClient Client { get; private set; } /// <summary> /// Gets the current usage count and the limit for the resources under the /// subscription. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IEnumerable<Usage>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Storage/usages").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IEnumerable<Usage>>(); _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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Usage>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics.Log; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Versions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.EngineV1 { internal partial class DiagnosticIncrementalAnalyzer : BaseDiagnosticIncrementalAnalyzer { private readonly int _correlationId; private readonly MemberRangeMap _memberRangeMap; private readonly AnalyzerExecutor _executor; private readonly StateManager _stateManager; /// <summary> /// PERF: Always run analyzers sequentially for background analysis. /// </summary> private const bool ConcurrentAnalysis = false; /// <summary> /// Always compute suppressed diagnostics - diagnostic clients may or may not request for suppressed diagnostics. /// </summary> private const bool ReportSuppressedDiagnostics = true; public DiagnosticIncrementalAnalyzer( DiagnosticAnalyzerService owner, int correlationId, Workspace workspace, HostAnalyzerManager analyzerManager, AbstractHostDiagnosticUpdateSource hostDiagnosticUpdateSource) : base(owner, workspace, analyzerManager, hostDiagnosticUpdateSource) { _correlationId = correlationId; _memberRangeMap = new MemberRangeMap(); _executor = new AnalyzerExecutor(this); _stateManager = new StateManager(analyzerManager); _stateManager.ProjectAnalyzerReferenceChanged += OnProjectAnalyzerReferenceChanged; } private void OnProjectAnalyzerReferenceChanged(object sender, ProjectAnalyzerReferenceChangedEventArgs e) { if (e.Removed.Length == 0) { // nothing to refresh return; } // events will be automatically serialized. var project = e.Project; var stateSets = e.Removed; // first remove all states foreach (var stateSet in stateSets) { foreach (var document in project.Documents) { stateSet.Remove(document.Id); } stateSet.Remove(project.Id); } // now raise events Owner.RaiseBulkDiagnosticsUpdated(raiseEvents => { foreach (var document in project.Documents) { RaiseDocumentDiagnosticsRemoved(document, stateSets, includeProjectState: true, raiseEvents: raiseEvents); } RaiseProjectDiagnosticsRemoved(project, stateSets, raiseEvents); }); } public override Task DocumentOpenAsync(Document document, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Diagnostics_DocumentOpen, GetOpenLogMessage, document, cancellationToken)) { return ClearOnlyDocumentStates(document); } } public override Task DocumentCloseAsync(Document document, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Diagnostics_DocumentClose, GetResetLogMessage, document, cancellationToken)) { // we don't need the info for closed file _memberRangeMap.Remove(document.Id); return ClearOnlyDocumentStates(document); } } public override Task DocumentResetAsync(Document document, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Diagnostics_DocumentReset, GetResetLogMessage, document, cancellationToken)) { // clear states for re-analysis and raise events about it. otherwise, some states might not updated on re-analysis // due to our build-live de-duplication logic where we put all state in Documents state. return ClearOnlyDocumentStates(document); } } private Task ClearOnlyDocumentStates(Document document) { // since managing states and raising events are separated, it can't be cancelled. var stateSets = _stateManager.GetStateSets(document.Project); // we remove whatever information we used to have on document open/close and re-calculate diagnostics // we had to do this since some diagnostic analyzer changes its behavior based on whether the document is opened or not. // so we can't use cached information. // clean up states foreach (var stateSet in stateSets) { stateSet.Remove(document.Id, onlyDocumentStates: true); } // raise events Owner.RaiseBulkDiagnosticsUpdated(raiseEvents => { RaiseDocumentDiagnosticsRemoved(document, stateSets, includeProjectState: false, raiseEvents: raiseEvents); }); return SpecializedTasks.EmptyTask; } private bool CheckOptions(Project project, bool forceAnalysis) { var workspace = project.Solution.Workspace; if (workspace.Options.GetOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic, project.Language) && workspace.Options.GetOption(RuntimeOptions.FullSolutionAnalysis)) { return true; } if (forceAnalysis) { return true; } return false; } internal CompilationWithAnalyzers GetCompilationWithAnalyzers( Project project, IEnumerable<DiagnosticAnalyzer> analyzers, Compilation compilation, bool concurrentAnalysis, bool reportSuppressedDiagnostics) { Contract.ThrowIfFalse(project.SupportsCompilation); Contract.ThrowIfNull(compilation); Func<Exception, bool> analyzerExceptionFilter = ex => { if (project.Solution.Workspace.Options.GetOption(InternalDiagnosticsOptions.CrashOnAnalyzerException)) { // if option is on, crash the host to get crash dump. FatalError.ReportUnlessCanceled(ex); } return true; }; var analysisOptions = new CompilationWithAnalyzersOptions( new WorkspaceAnalyzerOptions(project.AnalyzerOptions, project.Solution.Workspace), GetOnAnalyzerException(project.Id), analyzerExceptionFilter: analyzerExceptionFilter, concurrentAnalysis: concurrentAnalysis, logAnalyzerExecutionTime: true, reportSuppressedDiagnostics: reportSuppressedDiagnostics); var filteredAnalyzers = analyzers .Where(a => !CompilationWithAnalyzers.IsDiagnosticAnalyzerSuppressed(a, compilation.Options, analysisOptions.OnAnalyzerException)) .Distinct() .ToImmutableArray(); if (filteredAnalyzers.IsEmpty) { return null; } return new CompilationWithAnalyzers(compilation, filteredAnalyzers, analysisOptions); } public override async Task AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken) { await AnalyzeSyntaxAsync(document, diagnosticIds: null, cancellationToken: cancellationToken).ConfigureAwait(false); } private async Task AnalyzeSyntaxAsync(Document document, ImmutableHashSet<string> diagnosticIds, CancellationToken cancellationToken) { try { if (!CheckOptions(document.Project, document.IsOpen())) { return; } var textVersion = await document.GetTextVersionAsync(cancellationToken).ConfigureAwait(false); var dataVersion = await document.GetSyntaxVersionAsync(cancellationToken).ConfigureAwait(false); var versions = new VersionArgument(textVersion, dataVersion); var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var fullSpan = root == null ? null : (TextSpan?)root.FullSpan; var openedDocument = document.IsOpen(); var stateSets = _stateManager.GetOrUpdateStateSets(document.Project); var analyzers = stateSets.Select(s => s.Analyzer); var userDiagnosticDriver = new DiagnosticAnalyzerDriver( document, fullSpan, root, this, analyzers, ConcurrentAnalysis, ReportSuppressedDiagnostics, cancellationToken); foreach (var stateSet in stateSets) { if (await SkipRunningAnalyzerAsync(document.Project, stateSet.Analyzer, openedDocument, skipClosedFileCheck: false, cancellationToken: cancellationToken).ConfigureAwait(false)) { await ClearExistingDiagnostics(document, stateSet, StateType.Syntax, cancellationToken).ConfigureAwait(false); continue; } if (ShouldRunAnalyzerForStateType(stateSet.Analyzer, StateType.Syntax, diagnosticIds)) { var data = await _executor.GetSyntaxAnalysisDataAsync(userDiagnosticDriver, stateSet, versions).ConfigureAwait(false); if (data.FromCache) { RaiseDiagnosticsCreatedFromCacheIfNeeded(StateType.Syntax, document, stateSet, data.Items); continue; } var state = stateSet.GetState(StateType.Syntax); await state.PersistAsync(document, data.ToPersistData(), cancellationToken).ConfigureAwait(false); RaiseDocumentDiagnosticsUpdatedIfNeeded(StateType.Syntax, document, stateSet, data.OldItems, data.Items); } } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } public override async Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, CancellationToken cancellationToken) { await AnalyzeDocumentAsync(document, bodyOpt, diagnosticIds: null, cancellationToken: cancellationToken).ConfigureAwait(false); } private async Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, ImmutableHashSet<string> diagnosticIds, CancellationToken cancellationToken) { try { if (!CheckOptions(document.Project, document.IsOpen())) { return; } var textVersion = await document.GetTextVersionAsync(cancellationToken).ConfigureAwait(false); var projectVersion = await document.Project.GetDependentVersionAsync(cancellationToken).ConfigureAwait(false); var dataVersion = await document.Project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false); var versions = new VersionArgument(textVersion, dataVersion, projectVersion); if (bodyOpt == null) { await AnalyzeDocumentAsync(document, versions, diagnosticIds, cancellationToken).ConfigureAwait(false); } else { // only open file can go this route await AnalyzeBodyDocumentAsync(document, bodyOpt, versions, cancellationToken).ConfigureAwait(false); } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } private async Task AnalyzeBodyDocumentAsync(Document document, SyntaxNode member, VersionArgument versions, CancellationToken cancellationToken) { try { // syntax facts service must exist, otherwise, this method won't have called. var syntaxFacts = document.Project.LanguageServices.GetService<ISyntaxFactsService>(); var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var memberId = syntaxFacts.GetMethodLevelMemberId(root, member); var stateSets = _stateManager.GetOrUpdateStateSets(document.Project); var analyzers = stateSets.Select(s => s.Analyzer); var spanBasedDriver = new DiagnosticAnalyzerDriver( document, member.FullSpan, root, this, analyzers, ConcurrentAnalysis, ReportSuppressedDiagnostics, cancellationToken); var documentBasedDriver = new DiagnosticAnalyzerDriver( document, root.FullSpan, root, this, analyzers, ConcurrentAnalysis, ReportSuppressedDiagnostics, cancellationToken); foreach (var stateSet in stateSets) { if (Owner.IsAnalyzerSuppressed(stateSet.Analyzer, document.Project)) { await ClearExistingDiagnostics(document, stateSet, StateType.Document, cancellationToken).ConfigureAwait(false); continue; } if (ShouldRunAnalyzerForStateType(stateSet.Analyzer, StateType.Document)) { var supportsSemanticInSpan = stateSet.Analyzer.SupportsSpanBasedSemanticDiagnosticAnalysis(); var userDiagnosticDriver = supportsSemanticInSpan ? spanBasedDriver : documentBasedDriver; var ranges = _memberRangeMap.GetSavedMemberRange(stateSet.Analyzer, document); var data = await _executor.GetDocumentBodyAnalysisDataAsync( stateSet, versions, userDiagnosticDriver, root, member, memberId, supportsSemanticInSpan, ranges).ConfigureAwait(false); _memberRangeMap.UpdateMemberRange(stateSet.Analyzer, document, versions.TextVersion, memberId, member.FullSpan, ranges); var state = stateSet.GetState(StateType.Document); await state.PersistAsync(document, data.ToPersistData(), cancellationToken).ConfigureAwait(false); if (data.FromCache) { RaiseDiagnosticsCreatedFromCacheIfNeeded(StateType.Document, document, stateSet, data.Items); continue; } RaiseDocumentDiagnosticsUpdatedIfNeeded(StateType.Document, document, stateSet, data.OldItems, data.Items); } } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } private async Task AnalyzeDocumentAsync(Document document, VersionArgument versions, ImmutableHashSet<string> diagnosticIds, CancellationToken cancellationToken) { try { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var fullSpan = root == null ? null : (TextSpan?)root.FullSpan; bool openedDocument = document.IsOpen(); var stateSets = _stateManager.GetOrUpdateStateSets(document.Project); var analyzers = stateSets.Select(s => s.Analyzer); var userDiagnosticDriver = new DiagnosticAnalyzerDriver( document, fullSpan, root, this, analyzers, ConcurrentAnalysis, ReportSuppressedDiagnostics, cancellationToken); foreach (var stateSet in stateSets) { if (await SkipRunningAnalyzerAsync(document.Project, stateSet.Analyzer, openedDocument, skipClosedFileCheck: false, cancellationToken: cancellationToken).ConfigureAwait(false)) { await ClearExistingDiagnostics(document, stateSet, StateType.Document, cancellationToken).ConfigureAwait(false); continue; } if (ShouldRunAnalyzerForStateType(stateSet.Analyzer, StateType.Document, diagnosticIds)) { var data = await _executor.GetDocumentAnalysisDataAsync(userDiagnosticDriver, stateSet, versions).ConfigureAwait(false); if (data.FromCache) { RaiseDiagnosticsCreatedFromCacheIfNeeded(StateType.Document, document, stateSet, data.Items); continue; } if (openedDocument) { _memberRangeMap.Touch(stateSet.Analyzer, document, versions.TextVersion); } var state = stateSet.GetState(StateType.Document); await state.PersistAsync(document, data.ToPersistData(), cancellationToken).ConfigureAwait(false); RaiseDocumentDiagnosticsUpdatedIfNeeded(StateType.Document, document, stateSet, data.OldItems, data.Items); } } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } public override async Task AnalyzeProjectAsync(Project project, bool semanticsChanged, CancellationToken cancellationToken) { await AnalyzeProjectAsync(project, cancellationToken).ConfigureAwait(false); } private async Task AnalyzeProjectAsync(Project project, CancellationToken cancellationToken) { try { if (!CheckOptions(project, forceAnalysis: false)) { return; } var projectTextVersion = await project.GetLatestDocumentVersionAsync(cancellationToken).ConfigureAwait(false); var semanticVersion = await project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false); var projectVersion = await project.GetDependentVersionAsync(cancellationToken).ConfigureAwait(false); var versions = new VersionArgument(projectTextVersion, semanticVersion, projectVersion); var stateSets = _stateManager.GetOrUpdateStateSets(project); var analyzers = stateSets.Select(s => s.Analyzer); var analyzerDriver = new DiagnosticAnalyzerDriver(project, this, analyzers, ConcurrentAnalysis, ReportSuppressedDiagnostics, cancellationToken); foreach (var stateSet in stateSets) { // Compilation actions can report diagnostics on open files, so we skipClosedFileChecks. if (await SkipRunningAnalyzerAsync(project, stateSet.Analyzer, openedDocument: false, skipClosedFileCheck: true, cancellationToken: cancellationToken).ConfigureAwait(false)) { await ClearExistingDiagnostics(project, stateSet, cancellationToken).ConfigureAwait(false); continue; } if (ShouldRunAnalyzerForStateType(stateSet.Analyzer, StateType.Project, diagnosticIds: null)) { var data = await _executor.GetProjectAnalysisDataAsync(analyzerDriver, stateSet, versions).ConfigureAwait(false); if (data.FromCache) { RaiseProjectDiagnosticsUpdatedIfNeeded(project, stateSet, ImmutableArray<DiagnosticData>.Empty, data.Items); continue; } var state = stateSet.GetState(StateType.Project); await PersistProjectData(project, state, data).ConfigureAwait(false); RaiseProjectDiagnosticsUpdatedIfNeeded(project, stateSet, data.OldItems, data.Items); } } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } private async Task<bool> SkipRunningAnalyzerAsync(Project project, DiagnosticAnalyzer analyzer, bool openedDocument, bool skipClosedFileCheck, CancellationToken cancellationToken) { // this project is not in a good state. only continue if it is opened document. if (!await project.HasSuccessfullyLoadedAsync(cancellationToken).ConfigureAwait(false) && !openedDocument) { return true; } if (Owner.IsAnalyzerSuppressed(analyzer, project)) { return true; } if (skipClosedFileCheck || ShouldRunAnalyzerForClosedFile(analyzer, project.CompilationOptions, openedDocument)) { return false; } return true; } private static async Task PersistProjectData(Project project, DiagnosticState state, AnalysisData data) { // TODO: Cancellation is not allowed here to prevent data inconsistency. But there is still a possibility of data inconsistency due to // things like exception. For now, I am letting it go and let v2 engine take care of it properly. If v2 doesn't come online soon enough // more refactoring is required on project state. // clear all existing data state.Remove(project.Id); foreach (var document in project.Documents) { state.Remove(document.Id); } // quick bail out if (data.Items.Length == 0) { return; } // save new data var group = data.Items.GroupBy(d => d.DocumentId); foreach (var kv in group) { if (kv.Key == null) { // save project scope diagnostics await state.PersistAsync(project, new AnalysisData(data.TextVersion, data.DataVersion, kv.ToImmutableArrayOrEmpty()), CancellationToken.None).ConfigureAwait(false); continue; } // save document scope diagnostics var document = project.GetDocument(kv.Key); if (document == null) { continue; } await state.PersistAsync(document, new AnalysisData(data.TextVersion, data.DataVersion, kv.ToImmutableArrayOrEmpty()), CancellationToken.None).ConfigureAwait(false); } } public override void RemoveDocument(DocumentId documentId) { using (Logger.LogBlock(FunctionId.Diagnostics_RemoveDocument, GetRemoveLogMessage, documentId, CancellationToken.None)) { _memberRangeMap.Remove(documentId); var stateSets = _stateManager.GetStateSets(documentId.ProjectId); foreach (var stateSet in stateSets) { stateSet.Remove(documentId); } Owner.RaiseBulkDiagnosticsUpdated(raiseEvents => { foreach (var stateSet in stateSets) { var solutionArgs = new SolutionArgument(null, documentId.ProjectId, documentId); for (var stateType = 0; stateType < s_stateTypeCount; stateType++) { RaiseDiagnosticsRemoved((StateType)stateType, documentId, stateSet, solutionArgs, raiseEvents); } } }); } } public override void RemoveProject(ProjectId projectId) { using (Logger.LogBlock(FunctionId.Diagnostics_RemoveProject, GetRemoveLogMessage, projectId, CancellationToken.None)) { var stateSets = _stateManager.GetStateSets(projectId); foreach (var stateSet in stateSets) { stateSet.Remove(projectId); } _stateManager.RemoveStateSet(projectId); Owner.RaiseBulkDiagnosticsUpdated(raiseEvents => { foreach (var stateSet in stateSets) { var solutionArgs = new SolutionArgument(null, projectId, null); RaiseDiagnosticsRemoved(StateType.Project, projectId, stateSet, solutionArgs, raiseEvents); } }); } } public override async Task<bool> TryAppendDiagnosticsForSpanAsync(Document document, TextSpan range, List<DiagnosticData> diagnostics, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default(CancellationToken)) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var getter = new LatestDiagnosticsForSpanGetter(this, document, root, range, blockForData: false, diagnostics: diagnostics, includeSuppressedDiagnostics: includeSuppressedDiagnostics, cancellationToken: cancellationToken); return await getter.TryGetAsync().ConfigureAwait(false); } public override async Task<IEnumerable<DiagnosticData>> GetDiagnosticsForSpanAsync(Document document, TextSpan range, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default(CancellationToken)) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var getter = new LatestDiagnosticsForSpanGetter(this, document, root, range, blockForData: true, includeSuppressedDiagnostics: includeSuppressedDiagnostics, cancellationToken: cancellationToken); var result = await getter.TryGetAsync().ConfigureAwait(false); Contract.Requires(result); return getter.Diagnostics; } public override bool ContainsDiagnostics(Workspace workspace, ProjectId projectId) { // need to improve perf in v2. foreach (var stateSet in _stateManager.GetStateSets(projectId)) { for (var stateType = 0; stateType < s_stateTypeCount; stateType++) { var state = stateSet.GetState((StateType)stateType); if (state.Count == 0) { continue; } if (state.GetDataCount(projectId) > 0) { return true; } var project = workspace.CurrentSolution.GetProject(projectId); if (project == null) { continue; } foreach (var documentId in project.DocumentIds) { if (state.GetDataCount(documentId) > 0) { return true; } } } } return false; } private bool ShouldRunAnalyzerForClosedFile(DiagnosticAnalyzer analyzer, CompilationOptions options, bool openedDocument) { // we have opened document, doesn't matter // PERF: Don't query descriptors for compiler analyzer, always execute it. if (openedDocument || analyzer.IsCompilerAnalyzer()) { return true; } // most of analyzers, number of descriptor is quite small, so this should be cheap. return Owner.GetDiagnosticDescriptors(analyzer).Any(d => GetEffectiveSeverity(d, options) != ReportDiagnostic.Hidden); } private static ReportDiagnostic GetEffectiveSeverity(DiagnosticDescriptor descriptor, CompilationOptions options) { return options == null ? MapSeverityToReport(descriptor.DefaultSeverity) : descriptor.GetEffectiveSeverity(options); } private static ReportDiagnostic MapSeverityToReport(DiagnosticSeverity severity) { switch (severity) { case DiagnosticSeverity.Hidden: return ReportDiagnostic.Hidden; case DiagnosticSeverity.Info: return ReportDiagnostic.Info; case DiagnosticSeverity.Warning: return ReportDiagnostic.Warn; case DiagnosticSeverity.Error: return ReportDiagnostic.Error; default: throw ExceptionUtilities.Unreachable; } } private bool ShouldRunAnalyzerForStateType(DiagnosticAnalyzer analyzer, StateType stateTypeId, ImmutableHashSet<string> diagnosticIds) { return ShouldRunAnalyzerForStateType(analyzer, stateTypeId, diagnosticIds, Owner.GetDiagnosticDescriptors); } private static bool ShouldRunAnalyzerForStateType(DiagnosticAnalyzer analyzer, StateType stateTypeId, ImmutableHashSet<string> diagnosticIds = null, Func<DiagnosticAnalyzer, ImmutableArray<DiagnosticDescriptor>> getDescriptors = null) { // PERF: Don't query descriptors for compiler analyzer, always execute it for all state types. if (analyzer.IsCompilerAnalyzer()) { return true; } if (diagnosticIds != null && getDescriptors(analyzer).All(d => !diagnosticIds.Contains(d.Id))) { return false; } switch (stateTypeId) { case StateType.Syntax: return analyzer.SupportsSyntaxDiagnosticAnalysis(); case StateType.Document: return analyzer.SupportsSemanticDiagnosticAnalysis(); case StateType.Project: return analyzer.SupportsProjectDiagnosticAnalysis(); default: throw ExceptionUtilities.Unreachable; } } public override void LogAnalyzerCountSummary() { DiagnosticAnalyzerLogger.LogAnalyzerCrashCountSummary(_correlationId, DiagnosticLogAggregator); DiagnosticAnalyzerLogger.LogAnalyzerTypeCountSummary(_correlationId, DiagnosticLogAggregator); // reset the log aggregator ResetDiagnosticLogAggregator(); } private static bool CheckSyntaxVersions(Document document, AnalysisData existingData, VersionArgument versions) { if (existingData == null) { return false; } return document.CanReusePersistedTextVersion(versions.TextVersion, existingData.TextVersion) && document.CanReusePersistedSyntaxTreeVersion(versions.DataVersion, existingData.DataVersion); } private static bool CheckSemanticVersions(Document document, AnalysisData existingData, VersionArgument versions) { if (existingData == null) { return false; } return document.CanReusePersistedTextVersion(versions.TextVersion, existingData.TextVersion) && document.Project.CanReusePersistedDependentSemanticVersion(versions.ProjectVersion, versions.DataVersion, existingData.DataVersion); } private static bool CheckSemanticVersions(Project project, AnalysisData existingData, VersionArgument versions) { if (existingData == null) { return false; } return VersionStamp.CanReusePersistedVersion(versions.TextVersion, existingData.TextVersion) && project.CanReusePersistedDependentSemanticVersion(versions.ProjectVersion, versions.DataVersion, existingData.DataVersion); } private void RaiseDiagnosticsCreatedFromCacheIfNeeded(StateType type, Document document, StateSet stateSet, ImmutableArray<DiagnosticData> items) { RaiseDocumentDiagnosticsUpdatedIfNeeded(type, document, stateSet, ImmutableArray<DiagnosticData>.Empty, items); } private void RaiseDocumentDiagnosticsUpdatedIfNeeded( StateType type, Document document, StateSet stateSet, ImmutableArray<DiagnosticData> existingItems, ImmutableArray<DiagnosticData> newItems) { var noItems = existingItems.Length == 0 && newItems.Length == 0; if (noItems) { return; } RaiseDiagnosticsCreated(type, document.Id, stateSet, new SolutionArgument(document), newItems); } private void RaiseProjectDiagnosticsUpdatedIfNeeded( Project project, StateSet stateSet, ImmutableArray<DiagnosticData> existingItems, ImmutableArray<DiagnosticData> newItems) { var noItems = existingItems.Length == 0 && newItems.Length == 0; if (noItems) { return; } RaiseProjectDiagnosticsRemovedIfNeeded(project, stateSet, existingItems, newItems); RaiseProjectDiagnosticsUpdated(project, stateSet, newItems); } private void RaiseProjectDiagnosticsRemovedIfNeeded( Project project, StateSet stateSet, ImmutableArray<DiagnosticData> existingItems, ImmutableArray<DiagnosticData> newItems) { if (existingItems.Length == 0) { return; } Owner.RaiseBulkDiagnosticsUpdated(raiseEvents => { var removedItems = existingItems.GroupBy(d => d.DocumentId).Select(g => g.Key).Except(newItems.GroupBy(d => d.DocumentId).Select(g => g.Key)); foreach (var documentId in removedItems) { if (documentId == null) { RaiseDiagnosticsRemoved(StateType.Project, project.Id, stateSet, new SolutionArgument(project), raiseEvents); continue; } var document = project.GetDocument(documentId); var argument = document == null ? new SolutionArgument(null, documentId.ProjectId, documentId) : new SolutionArgument(document); RaiseDiagnosticsRemoved(StateType.Project, documentId, stateSet, argument, raiseEvents); } }); } private void RaiseProjectDiagnosticsUpdated(Project project, StateSet stateSet, ImmutableArray<DiagnosticData> diagnostics) { Owner.RaiseBulkDiagnosticsUpdated(raiseEvents => { var group = diagnostics.GroupBy(d => d.DocumentId); foreach (var kv in group) { if (kv.Key == null) { RaiseDiagnosticsCreated(StateType.Project, project.Id, stateSet, new SolutionArgument(project), kv.ToImmutableArrayOrEmpty(), raiseEvents); continue; } RaiseDiagnosticsCreated(StateType.Project, kv.Key, stateSet, new SolutionArgument(project.GetDocument(kv.Key)), kv.ToImmutableArrayOrEmpty(), raiseEvents); } }); } private static ImmutableArray<DiagnosticData> GetDiagnosticData(ILookup<DocumentId, DiagnosticData> lookup, DocumentId documentId) { return lookup.Contains(documentId) ? lookup[documentId].ToImmutableArrayOrEmpty() : ImmutableArray<DiagnosticData>.Empty; } private void RaiseDiagnosticsCreated( StateType type, object key, StateSet stateSet, SolutionArgument solution, ImmutableArray<DiagnosticData> diagnostics) { RaiseDiagnosticsCreated(type, key, stateSet, solution, diagnostics, Owner.RaiseDiagnosticsUpdated); } private void RaiseDiagnosticsCreated( StateType type, object key, StateSet stateSet, SolutionArgument solution, ImmutableArray<DiagnosticData> diagnostics, Action<DiagnosticsUpdatedArgs> raiseEvents) { // get right arg id for the given analyzer var id = new LiveDiagnosticUpdateArgsId(stateSet.Analyzer, key, (int)type, stateSet.ErrorSourceName); raiseEvents(DiagnosticsUpdatedArgs.DiagnosticsCreated(id, Workspace, solution.Solution, solution.ProjectId, solution.DocumentId, diagnostics)); } private void RaiseDiagnosticsRemoved( StateType type, object key, StateSet stateSet, SolutionArgument solution) { RaiseDiagnosticsRemoved(type, key, stateSet, solution, Owner.RaiseDiagnosticsUpdated); } private void RaiseDiagnosticsRemoved( StateType type, object key, StateSet stateSet, SolutionArgument solution, Action<DiagnosticsUpdatedArgs> raiseEvents) { // get right arg id for the given analyzer var id = new LiveDiagnosticUpdateArgsId(stateSet.Analyzer, key, (int)type, stateSet.ErrorSourceName); raiseEvents(DiagnosticsUpdatedArgs.DiagnosticsRemoved(id, Workspace, solution.Solution, solution.ProjectId, solution.DocumentId)); } private void RaiseDocumentDiagnosticsRemoved(Document document, IEnumerable<StateSet> stateSets, bool includeProjectState, Action<DiagnosticsUpdatedArgs> raiseEvents) { foreach (var stateSet in stateSets) { for (var stateType = 0; stateType < s_stateTypeCount; stateType++) { if (!includeProjectState && stateType == (int)StateType.Project) { // don't re-set project state type continue; } // raise diagnostic updated event RaiseDiagnosticsRemoved((StateType)stateType, document.Id, stateSet, new SolutionArgument(document), raiseEvents); } } } private void RaiseProjectDiagnosticsRemoved(Project project, IEnumerable<StateSet> stateSets, Action<DiagnosticsUpdatedArgs> raiseEvents) { foreach (var stateSet in stateSets) { RaiseDiagnosticsRemoved(StateType.Project, project.Id, stateSet, new SolutionArgument(project), raiseEvents); } } private ImmutableArray<DiagnosticData> UpdateDocumentDiagnostics( AnalysisData existingData, ImmutableArray<TextSpan> range, ImmutableArray<DiagnosticData> memberDiagnostics, SyntaxTree tree, SyntaxNode member, int memberId) { // get old span var oldSpan = range[memberId]; // get old diagnostics var diagnostics = existingData.Items; // check quick exit cases if (diagnostics.Length == 0 && memberDiagnostics.Length == 0) { return diagnostics; } // simple case if (diagnostics.Length == 0 && memberDiagnostics.Length > 0) { return memberDiagnostics; } // regular case var result = new List<DiagnosticData>(); // update member location Contract.Requires(member.FullSpan.Start == oldSpan.Start); var delta = member.FullSpan.End - oldSpan.End; var replaced = false; foreach (var diagnostic in diagnostics) { if (diagnostic.TextSpan.Start < oldSpan.Start) { result.Add(diagnostic); continue; } if (!replaced) { result.AddRange(memberDiagnostics); replaced = true; } if (oldSpan.End <= diagnostic.TextSpan.Start) { result.Add(UpdatePosition(diagnostic, tree, delta)); continue; } } // if it haven't replaced, replace it now if (!replaced) { result.AddRange(memberDiagnostics); replaced = true; } return result.ToImmutableArray(); } private DiagnosticData UpdatePosition(DiagnosticData diagnostic, SyntaxTree tree, int delta) { Debug.Assert(diagnostic.AdditionalLocations == null || diagnostic.AdditionalLocations.Count == 0); var newDiagnosticLocation = UpdateDiagnosticLocation(diagnostic.DataLocation, tree, delta); return new DiagnosticData( diagnostic.Id, diagnostic.Category, diagnostic.Message, diagnostic.ENUMessageForBingSearch, diagnostic.Severity, diagnostic.DefaultSeverity, diagnostic.IsEnabledByDefault, diagnostic.WarningLevel, diagnostic.CustomTags, diagnostic.Properties, diagnostic.Workspace, diagnostic.ProjectId, newDiagnosticLocation, additionalLocations: diagnostic.AdditionalLocations, description: diagnostic.Description, helpLink: diagnostic.HelpLink, isSuppressed: diagnostic.IsSuppressed); } private DiagnosticDataLocation UpdateDiagnosticLocation( DiagnosticDataLocation dataLocation, SyntaxTree tree, int delta) { var span = dataLocation.SourceSpan.Value; var start = Math.Min(Math.Max(span.Start + delta, 0), tree.Length); var newSpan = new TextSpan(start, start >= tree.Length ? 0 : span.Length); var mappedLineInfo = tree.GetMappedLineSpan(newSpan); var originalLineInfo = tree.GetLineSpan(newSpan); return new DiagnosticDataLocation(dataLocation.DocumentId, newSpan, originalFilePath: originalLineInfo.Path, originalStartLine: originalLineInfo.StartLinePosition.Line, originalStartColumn: originalLineInfo.StartLinePosition.Character, originalEndLine: originalLineInfo.EndLinePosition.Line, originalEndColumn: originalLineInfo.EndLinePosition.Character, mappedFilePath: mappedLineInfo.GetMappedFilePathIfExist(), mappedStartLine: mappedLineInfo.StartLinePosition.Line, mappedStartColumn: mappedLineInfo.StartLinePosition.Character, mappedEndLine: mappedLineInfo.EndLinePosition.Line, mappedEndColumn: mappedLineInfo.EndLinePosition.Character); } private static IEnumerable<DiagnosticData> GetDiagnosticData(Document document, SyntaxTree tree, TextSpan? span, IEnumerable<Diagnostic> diagnostics) { return diagnostics != null ? diagnostics.Where(dx => ShouldIncludeDiagnostic(dx, tree, span)).Select(d => DiagnosticData.Create(document, d)) : null; } private static bool ShouldIncludeDiagnostic(Diagnostic diagnostic, SyntaxTree tree, TextSpan? span) { if (diagnostic == null) { return false; } if (diagnostic.Location == null || diagnostic.Location == Location.None) { return false; } if (diagnostic.Location.SourceTree != tree) { return false; } if (span == null) { return true; } return span.Value.Contains(diagnostic.Location.SourceSpan); } private static IEnumerable<DiagnosticData> GetDiagnosticData(Project project, IEnumerable<Diagnostic> diagnostics) { if (diagnostics == null) { yield break; } foreach (var diagnostic in diagnostics) { if (diagnostic.Location == null || diagnostic.Location == Location.None) { yield return DiagnosticData.Create(project, diagnostic); continue; } var document = project.GetDocument(diagnostic.Location.SourceTree); if (document == null) { continue; } yield return DiagnosticData.Create(document, diagnostic); } } private static async Task<IEnumerable<DiagnosticData>> GetSyntaxDiagnosticsAsync(DiagnosticAnalyzerDriver userDiagnosticDriver, DiagnosticAnalyzer analyzer) { using (Logger.LogBlock(FunctionId.Diagnostics_SyntaxDiagnostic, GetSyntaxLogMessage, userDiagnosticDriver.Document, userDiagnosticDriver.Span, analyzer, userDiagnosticDriver.CancellationToken)) { try { Contract.ThrowIfNull(analyzer); var tree = await userDiagnosticDriver.Document.GetSyntaxTreeAsync(userDiagnosticDriver.CancellationToken).ConfigureAwait(false); var diagnostics = await userDiagnosticDriver.GetSyntaxDiagnosticsAsync(analyzer).ConfigureAwait(false); return GetDiagnosticData(userDiagnosticDriver.Document, tree, userDiagnosticDriver.Span, diagnostics); } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } } private static async Task<IEnumerable<DiagnosticData>> GetSemanticDiagnosticsAsync(DiagnosticAnalyzerDriver userDiagnosticDriver, DiagnosticAnalyzer analyzer) { using (Logger.LogBlock(FunctionId.Diagnostics_SemanticDiagnostic, GetSemanticLogMessage, userDiagnosticDriver.Document, userDiagnosticDriver.Span, analyzer, userDiagnosticDriver.CancellationToken)) { try { Contract.ThrowIfNull(analyzer); var tree = await userDiagnosticDriver.Document.GetSyntaxTreeAsync(userDiagnosticDriver.CancellationToken).ConfigureAwait(false); var diagnostics = await userDiagnosticDriver.GetSemanticDiagnosticsAsync(analyzer).ConfigureAwait(false); return GetDiagnosticData(userDiagnosticDriver.Document, tree, userDiagnosticDriver.Span, diagnostics); } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } } private static async Task<IEnumerable<DiagnosticData>> GetProjectDiagnosticsAsync(DiagnosticAnalyzerDriver userDiagnosticDriver, DiagnosticAnalyzer analyzer) { using (Logger.LogBlock(FunctionId.Diagnostics_ProjectDiagnostic, GetProjectLogMessage, userDiagnosticDriver.Project, analyzer, userDiagnosticDriver.CancellationToken)) { try { Contract.ThrowIfNull(analyzer); var diagnostics = await userDiagnosticDriver.GetProjectDiagnosticsAsync(analyzer).ConfigureAwait(false); return GetDiagnosticData(userDiagnosticDriver.Project, diagnostics); } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } } private async Task ClearExistingDiagnostics(Document document, StateSet stateSet, StateType type, CancellationToken cancellationToken) { var state = stateSet.GetState(type); var existingData = await state.TryGetExistingDataAsync(document, cancellationToken).ConfigureAwait(false); if (existingData?.Items.Length > 0) { // remove saved info state.Remove(document.Id); // raise diagnostic updated event RaiseDiagnosticsRemoved(type, document.Id, stateSet, new SolutionArgument(document)); } } private async Task ClearExistingDiagnostics(Project project, StateSet stateSet, CancellationToken cancellationToken) { var state = stateSet.GetState(StateType.Project); var existingData = await state.TryGetExistingDataAsync(project, cancellationToken).ConfigureAwait(false); if (existingData?.Items.Length > 0) { // remove saved cache state.Remove(project.Id); // raise diagnostic updated event RaiseDiagnosticsRemoved(StateType.Project, project.Id, stateSet, new SolutionArgument(project)); } } private static string GetSyntaxLogMessage(Document document, TextSpan? span, DiagnosticAnalyzer analyzer) { return string.Format("syntax: {0}, {1}, {2}", document.FilePath ?? document.Name, span.HasValue ? span.Value.ToString() : "Full", analyzer.ToString()); } private static string GetSemanticLogMessage(Document document, TextSpan? span, DiagnosticAnalyzer analyzer) { return string.Format("semantic: {0}, {1}, {2}", document.FilePath ?? document.Name, span.HasValue ? span.Value.ToString() : "Full", analyzer.ToString()); } private static string GetProjectLogMessage(Project project, DiagnosticAnalyzer analyzer) { return string.Format("project: {0}, {1}", project.FilePath ?? project.Name, analyzer.ToString()); } private static string GetResetLogMessage(Document document) { return string.Format("document reset: {0}", document.FilePath ?? document.Name); } private static string GetOpenLogMessage(Document document) { return string.Format("document open: {0}", document.FilePath ?? document.Name); } private static string GetRemoveLogMessage(DocumentId id) { return string.Format("document remove: {0}", id.ToString()); } private static string GetRemoveLogMessage(ProjectId id) { return string.Format("project remove: {0}", id.ToString()); } public override Task NewSolutionSnapshotAsync(Solution newSolution, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } } }
/* ----------------------------------------------------------------- * Copyright (c) 2015 Robert Adams * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of the author nor the names of * 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 AUTHOR 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. * * EXPORT LAWS: THIS LICENSE ADDS NO RESTRICTIONS TO THE EXPORT LAWS OF * YOUR JURISDICTION. It is licensee's responsibility to comply with any * export regulations applicable in licensee's jurisdiction. Under * CURRENT (May 2000) U.S. export regulations this software is eligible * for export from the U.S. and can be downloaded by or otherwise * exported or reexported worldwide EXCEPT to U.S. embargoed destinations * which include Cuba, Iraq, Libya, North Korea, Iran, Syria, Sudan, * Afghanistan and any other country to which the U.S. has embargoed * goods and services. * ----------------------------------------------------------------- */ using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Text; using System.Text.RegularExpressions; using MySql.Data.MySqlClient; using ParameterParsing; using Logging; namespace importWP { class ImportWP { Dictionary<string, string> m_Parameters; int m_verbose = 0; string m_dbHost; string m_dbName; string m_dbUser; string m_dbPass; string m_tablePrefix = "wp_"; bool m_cleanEntities = false; private string Invocation() { return @"Invocation: INVOCATION: ImportWP -H|--dbHost databaseHost -D|--dbName databaseName -U|--dbUser databaseUser -P|--dbPass databaseUserPassword -o|--output outputFilename --tablePrefix prefix --cleanEntities --verbose "; } static void Main(string[] args) { ImportWP prog = new ImportWP(); prog.Start(args); return; } public ImportWP() { } public class PageName { public ulong ID; public string post_title; public string post_name; public ulong post_parent; public PageName() { ID = 0; post_title = String.Empty; post_name = String.Empty; post_parent = 0; } } public Dictionary<ulong, PageName> m_pageNameList = new Dictionary<ulong, PageName>(); public class PostInfo { public ulong ID; public string guid; public string post_type; public string post_status; public string post_title; public string post_slug; public string post_name; public DateTime post_date; public DateTime post_date_gmt; public string post_content; public string post_excerpt; public int comment_count; public string display_name; public string user_login; public string user_email; public string user_url; public PostInfo() { ID = 0; guid = String.Empty; post_type = String.Empty; post_status = String.Empty; post_title = String.Empty; post_slug = String.Empty; post_name = String.Empty; post_date = DateTime.Now; post_date_gmt = DateTime.Now; post_content = String.Empty; post_excerpt = String.Empty; comment_count = 0; display_name = String.Empty; user_login = String.Empty; user_email = String.Empty; user_url = String.Empty; } } public Dictionary<ulong, PostInfo> m_posts = new Dictionary<ulong, PostInfo>(); public class CommentInfo { public ulong comment_ID; public string author; public string author_email; public string author_url; public DateTime date; public DateTime date_gmt; public string content; public CommentInfo() { comment_ID = 0; author = String.Empty; author_email = String.Empty; author_url = String.Empty; date = DateTime.Now; date_gmt = DateTime.Now; content = String.Empty; } } public void Start(string[] args) { m_Parameters = ParameterParse.ParseArguments(args, false /* firstOpFlag */, true /* multipleFiles */); foreach (KeyValuePair<string, string> kvp in m_Parameters) { switch (kvp.Key) { case "-H": case "--dbHost": m_dbHost = kvp.Value; break; case "-D": case "--dbName": m_dbName = kvp.Value; break; case "-U": case "--dbUser": m_dbUser = kvp.Value; break; case "-P": case "--dbPass": m_dbPass = kvp.Value; break; case "--tablePrefix": m_tablePrefix = kvp.Value; break; case "--cleanEntities": m_cleanEntities = true; break; case "--verbose": m_verbose++; break; // case ParameterParse.LAST_PARAM: // break; case ParameterParse.ERROR_PARAM: // if we get here, the parser found an error Logger.Log("Parameter error: " + kvp.Value); Logger.Log(Invocation()); return; default: Logger.Log("ERROR: UNKNOWN PARAMETER: " + kvp.Key); Logger.Log(Invocation()); return; } } string m_connectionString = String.Format("Data Source={0};Database={1};User ID={2};Password={3}", m_dbHost, m_dbName, m_dbUser, m_dbPass); Logger.Log("Connection string = {0}", m_connectionString); Dictionary<ulong, Dictionary<string, string>> pageNameList = new Dictionary<ulong, Dictionary<string, string>>(); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); // populate m_pageNameList GetPageNameList(dbcon); // populate m_posts GetPosts(dbcon); // Got through all the posts and output post files ProcessPosts(dbcon); } } private void ProcessPosts(MySqlConnection dbcon) { List<string> categories; List<string> tags; List<CommentInfo> comments; foreach (PostInfo post in m_posts.Values) { GetTagsAndCategoriesForPost(dbcon, post.ID, out categories, out tags); if (post.comment_count > 0) GetCommentsForPost(dbcon, post.ID, out comments); else comments = new List<CommentInfo>(); var data = new { layout = post.post_type, status = post.post_status, published = post.post_status == "draft" ? String.Empty : "publish", title = post.post_title, author = new { display_name = post.display_name, login = post.user_login, email = post.user_email, url = post.user_url, }, author_login = post.user_login, author_email = post.user_email, author_url = post.user_url, excerpt = post.post_excerpt, // more_anchor = post.more_anchor, // Seems like but in the Ruby code but I don't use More so not a problem // more_anchor = string.Empty, wordpress_id = post.ID.ToString(), wordpress_url = post.guid, date = post.post_date.ToString(), // date_gmt = post.post_date_gmt.ToString(), categories = categories, tags = tags, comments = comments }; string filename = String.Empty; if (post.post_type == "page") { filename = Path.Combine(BuildPagePath(post.ID), "index.md"); } else if (post.post_type == "draft") { filename = "_drafts/" + post.post_slug + ".md"; } else { filename = "_posts/" + post.post_name; } string fileDir = Path.GetDirectoryName(filename); if (m_verbose > 0) Logger.Log("==== Filename={0}, fileDir={1}", filename, fileDir); if (!Directory.Exists(fileDir)) Directory.CreateDirectory(fileDir); using (StreamWriter outt = File.CreateText(filename)) { var serializer = new YamlDotNet.Serialization.Serializer(); serializer.Serialize(outt, data); outt.WriteLine("---"); outt.Write(post.post_content); } } } private void GetPageNameList(MySqlConnection dbcon) { // Find the Pages using (MySqlCommand cmd = new MySqlCommand( String.Format("SELECT " + "ID," + "post_title," + "post_name," + "post_parent" + " FROM {0}posts WHERE post_type = 'page'", m_tablePrefix), dbcon)) { try { using (MySqlDataReader dbReader = cmd.ExecuteReader()) { while (dbReader.Read()) { PageName pn = new PageName(); ulong pageID = dbReader.GetUInt64("ID"); pn.ID = pageID; pn.post_title = dbReader.GetString("post_title"); pn.post_name = Sluggify(dbReader.GetString("post_name")); pn.post_parent = dbReader.GetUInt64("post_parent"); m_pageNameList[pageID] = pn; if (m_verbose > 0) { Logger.Log("Pages: ID={0}, title={1}, slug={2}, parent={3}", pageID, pn.post_title, pn.post_name, pn.post_parent); } } } } catch (Exception e) { Logger.Log("Error reading page names from DB: {0}", e); } } } private void GetPosts(MySqlConnection dbcon) { using (MySqlCommand cmd = new MySqlCommand( String.Format("SELECT " + "{0}posts.ID," + "{0}posts.guid," + "{0}posts.post_type," + "{0}posts.post_status," + "{0}posts.post_title," + "{0}posts.post_name," + "{0}posts.post_date," + "{0}posts.post_date_gmt," + "{0}posts.post_content," + "{0}posts.post_excerpt," + "{0}posts.comment_count," + "{0}users.display_name," + "{0}users.user_login," + "{0}users.user_email," + "{0}users.user_url" + " FROM {0}posts LEFT JOIN {0}users ON {0}posts.post_author = {0}users.ID" + " WHERE {0}posts.post_status = 'publish'", m_tablePrefix) , dbcon)) { try { using (MySqlDataReader dbReader = cmd.ExecuteReader()) { while (dbReader.Read()) { PostInfo post = new PostInfo(); ulong postID = dbReader.GetUInt64("ID"); post.ID = postID; post.post_title = dbReader.GetString("post_title"); if (m_cleanEntities) post.post_title = CleanEntities(post.post_title); post.guid = dbReader.GetString("guid"); post.post_type = dbReader.GetString("post_type"); post.post_status = dbReader.GetString("post_status"); post.comment_count = dbReader.GetInt32("comment_count"); post.display_name = dbReader.GetString("display_name"); if (m_verbose > 0) { Logger.Log("Post: ID={0}, title={1}", post.ID, post.post_title); } post.post_slug = dbReader.GetString("post_name"); if (String.IsNullOrEmpty(post.post_slug)) post.post_slug = Sluggify(post.post_title); post.post_date = parseTheDate(dbReader, "post_date"); post.post_date_gmt = parseTheDate(dbReader, "post_date_gmt"); post.post_name = String.Format("{0:d2}-{1:d2}-{2:d2}-{3}.md", post.post_date.Year, post.post_date.Month, post.post_date.Day, post.post_slug); post.post_content = dbReader.GetString("post_content"); if (m_cleanEntities) post.post_content = CleanEntities(post.post_content); post.post_excerpt = dbReader.GetString("post_excerpt"); int moreIndex = post.post_content.IndexOf("<!--- more --->"); string moreAnchor = String.Empty; if (String.IsNullOrEmpty(post.post_excerpt) && moreIndex > 0) { post.post_excerpt = post.post_content.Substring(0, moreIndex); } if (moreIndex > 0) { string content = post.post_content.Replace("<!--- more --->", "<a id=\"more\"></a>"); content = content.Replace("<!--- more --->", String.Format("<a id=\"more\"></a><a id=\"more-{0}\"></a>", ((ulong)dbReader["ID"]) )); post.post_content = content; } if (m_verbose > 0) Logger.Log("title='{0}', slug='{1}', date={2}, name='{3}'", post.post_title, post.post_slug, post.post_date, post.post_name); m_posts.Add(postID, post); } } } catch (Exception e) { Logger.Log("Error reading posts DB: {0}", e); } } } private void GetTagsAndCategoriesForPost(MySqlConnection dbcon, ulong postID, out List<string> categories, out List<string> tags) { List<string> tcategories = new List<string>(); List<string> ttags = new List<string>(); using (MySqlCommand cmd = new MySqlCommand( String.Format("SELECT " + "{0}terms.name," + "{0}term_taxonomy.taxonomy" + " FROM " + "{0}terms," + "{0}term_relationships," + "{0}term_taxonomy " + " WHERE " + "{0}term_relationships.object_id = '{1}' AND " + "{0}term_relationships.term_taxonomy_id = {0}term_taxonomy.term_taxonomy_id AND " + "{0}terms.term_id = {0}term_taxonomy.term_id", m_tablePrefix, postID) , dbcon) ) { try { using (MySqlDataReader dbReader = cmd.ExecuteReader()) { while (dbReader.Read()) { if (((string)dbReader["taxonomy"]) == "category") { string cat = (string)dbReader["name"]; if (m_cleanEntities) tcategories.Add(CleanEntities(cat)); else tcategories.Add(cat); if (m_verbose > 0) Logger.Log("Category = {0}", cat); } if (((string)dbReader["taxonomy"]) == "post_tag") { string tag = (string)dbReader["name"]; if (m_cleanEntities) ttags.Add(CleanEntities(tag)); else ttags.Add(tag); if (m_verbose > 0) Logger.Log("Tag = {0}", tag); } } } } catch (Exception e) { Logger.Log("Error reading tags and categories from DB: {0}", e); } } categories = tcategories; tags = ttags; } private void GetCommentsForPost(MySqlConnection dbcon, ulong postID, out List<CommentInfo> comments) { // HashSet<CommentInfo> tcomments = new HashSet<CommentInfo>(); SortedDictionary<ulong, CommentInfo> tcomments = new SortedDictionary<ulong, CommentInfo>(); using (MySqlCommand cmd = new MySqlCommand( String.Format("SELECT " + "{0}comments.comment_ID," + "{0}comments.comment_author," + "{0}comments.comment_author_email," + "{0}comments.comment_author_url," + "{0}comments.comment_date," + "{0}comments.comment_date_gmt," + "{0}comments.comment_content" + " FROM " + "{0}comments" + " WHERE " + "{0}comments.comment_post_ID = '{1}' AND " + "{0}comments.comment_approved <> 'spam'", m_tablePrefix, postID) , dbcon) ) { try { using (MySqlDataReader dbReader = cmd.ExecuteReader()) { while (dbReader.Read()) { CommentInfo comm = new CommentInfo(); comm.comment_ID = dbReader.GetUInt64("comment_ID"); comm.author = dbReader.GetString("comment_author"); comm.author_email = dbReader.GetString("comment_author_email"); comm.author_url = dbReader.GetString("comment_author_url"); comm.date = dbReader.GetDateTime("comment_date"); // comm.date_gmt = dbReader.GetDateTime("comment_date_gmt"); comm.content = dbReader.GetString("comment_content"); if (m_cleanEntities) { CleanEntities(comm.content); CleanEntities(comm.author); } tcomments.Add(comm.comment_ID, comm); } } } catch (Exception e) { Logger.Log("Error reading comments from DB: {0}", e); } } List<CommentInfo> temp = new List<CommentInfo>(); foreach (KeyValuePair<ulong, CommentInfo> kvp in tcomments) { temp.Add(kvp.Value); } comments = temp; } private string BuildPagePath(ulong postID) { string ret = String.Empty; PageName pn; if (m_pageNameList.TryGetValue(postID, out pn)) { ret = Path.Combine(BuildPagePath(pn.post_parent), pn.post_name); } return ret; } private DateTime parseTheDate(MySqlDataReader reader, string column) { DateTime ret = DateTime.Now; try { ret = reader.GetDateTime("post_date"); } catch { ret = DateTime.Now; } return ret; } private string CleanEntities(string ent) { return ent; } // Turn a title into a URLable slug // def self.sluggify( title ) // title = title.to_ascii.downcase.gsub(/[^0-9A-Za-z]+/, " ").strip.gsub(" ", "-") // end private string Sluggify(string title) { string ret = title.ToLower(); ret = ret.Replace("[^0-9A-Za-z]+", " "); ret = ret.Trim(); ret = ret.Replace(" ", "-"); return ret; } } }
using System; using System.Net; using System.Collections.Generic; using System.ComponentModel; using System.Security.Permissions; using Microsoft.Ccr.Core; using Microsoft.Dss.Core; using Microsoft.Dss.Core.Attributes; using Microsoft.Dss.ServiceModel.Dssp; using Microsoft.Dss.Core.DsspHttp; using Microsoft.Dss.ServiceModel.DsspServiceBase; using W3C.Soap; using pxbumper = Microsoft.Robotics.Services.ContactSensor.Proxy; using submgr = Microsoft.Dss.Services.SubscriptionManager; using TrackRoamer.Robotics.Utility.LibSystem; using powerbrick = TrackRoamer.Robotics.Services.TrackRoamerBrickPower.Proxy; namespace TrackRoamer.Robotics.Services.TrackRoamerServices.Bumper { [Contract(Contract.Identifier)] [AlternateContract(pxbumper.Contract.Identifier)] [DisplayName("(User) TrackRoamer Contact Sensor - Front Whiskers")] [Description("Provides access to the TrackRoamer array of whiskers sensors used as a bumper.\n(Uses Generic Contact Sensors contract.)")] public class BumperService : DsspServiceBase { private const string _configFile = ServicePaths.Store + "/TrackRoamer.Services.Bumper.config.xml"; // C:\Microsoft Robotics Dev Studio 4\projects\TrackRoamer\TrackRoamerServices\Config\TrackRoamer.TrackRoamerBot.Bumper.Config.xml [EmbeddedResource("TrackRoamer.Robotics.Services.TrackRoamerServices.TrackRoamerBumper.xslt")] string _transform = null; [InitialStatePartner(Optional = true, ServiceUri = _configFile)] private pxbumper.ContactSensorArrayState _state = new pxbumper.ContactSensorArrayState(); private bool _subscribed = false; [ServicePort("/TrackRoamerBumper", AllowMultipleInstances = true)] private pxbumper.ContactSensorArrayOperations _mainPort = new pxbumper.ContactSensorArrayOperations(); #region Powerbrick partner - for whiskers [Partner("TrackRoamerPowerBrick", Contract = powerbrick.Contract.Identifier, CreationPolicy = PartnerCreationPolicy.UseExistingOrCreate, Optional = false)] protected powerbrick.TrackRoamerBrickPowerOperations _trackroamerbotPort = new powerbrick.TrackRoamerBrickPowerOperations(); private Port<powerbrick.UpdateWhiskers> notificationPortWhiskers = new Port<powerbrick.UpdateWhiskers>(); #endregion [Partner("SubMgr", Contract=submgr.Contract.Identifier, CreationPolicy=PartnerCreationPolicy.CreateAlways, Optional=false)] private submgr.SubscriptionManagerPort _subMgrPort = new submgr.SubscriptionManagerPort(); /// <summary> /// Cached version of the Interleave arbiter that protects concurrent access on Dssp handlers /// We use it to combine with an interleave that manages notifications from the TrackRoamerBot service /// </summary> //private Interleave _mainInterleave; public BumperService(DsspServiceCreationPort creationPort) : base(creationPort) { LogInfo("TrackRoamerBumper:BumperService() -- port: " + creationPort.ToString()); } protected override void Start() { //configure initial state if (_state == null) { LogInfo("TrackRoamerBumper:Start(): _state == null - initializing..."); _state = new pxbumper.ContactSensorArrayState(); _state.Sensors = new List<pxbumper.ContactSensor>(); pxbumper.ContactSensor leftBumper = new pxbumper.ContactSensor(); leftBumper.HardwareIdentifier = 101; leftBumper.Name = "Front Whisker Left"; _state.Sensors.Add(leftBumper); pxbumper.ContactSensor rightBumper = new pxbumper.ContactSensor(); rightBumper.HardwareIdentifier = 201; rightBumper.Name = "Front Whisker Right"; _state.Sensors.Add(rightBumper); SaveState(_state); } else { LogInfo("TrackRoamerBumper:Start(): _state is supplied by file: " + _configFile); } base.Start(); MainPortInterleave.CombineWith( new Interleave( new TeardownReceiverGroup(), new ExclusiveReceiverGroup( Arbiter.Receive<powerbrick.UpdateWhiskers>(true, notificationPortWhiskers, WhiskersNotificationHandler) ), new ConcurrentReceiverGroup() ) ); // display HTTP service Uri LogInfo("TrackRoamerBumper:Start() Service URI=" + ServiceInfo.HttpUri()); // Subscribe to the Hardware Controller for bumper notifications SubscribeToTrackRoamerBot(); } /// <summary> /// Subscribe to Whiskers notifications /// </summary> private void SubscribeToTrackRoamerBot() { Type[] notifyMeOfDistance = new Type[] { typeof(powerbrick.UpdateWhiskers) }; Tracer.Trace("TrackRoamerBumper: calling Subscribe() for UpdateWhiskers"); // Subscribe to the TrackRoamerBot and wait for a response Activate( Arbiter.Choice(_trackroamerbotPort.Subscribe(notificationPortWhiskers, notifyMeOfDistance), delegate(SubscribeResponseType Rsp) { // update our state with subscription status _subscribed = true; // Subscription was successful, update our state with subscription status: LogInfo("TrackRoamerBumper: Subscription to Power Brick Service for UpdateWhiskers succeeded"); }, delegate(Fault F) { LogError("TrackRoamerBumper: Subscription to Power Brick Service for UpdateWhiskers failed"); } ) ); } /// <summary> /// receiving Whiskers notifications here /// </summary> /// <param name="notification"></param> public void WhiskersNotificationHandler(powerbrick.UpdateWhiskers notification) { /* HardwareIdentifier coding: 1st digit 1=Left 2=Right 2d digit 0=Front 1=Rear 3d digit 1=Whisker 2=IRBumper 3=StepSensor */ foreach (pxbumper.ContactSensor bumper in _state.Sensors) { bool changed = false; switch (bumper.HardwareIdentifier) { case 101: if (notification.Body.FrontWhiskerLeft != null && bumper.Pressed != notification.Body.FrontWhiskerLeft) { bumper.Pressed = (bool)notification.Body.FrontWhiskerLeft; changed = true; } break; case 201: if (notification.Body.FrontWhiskerRight != null && bumper.Pressed != notification.Body.FrontWhiskerRight) { bumper.Pressed = (bool)notification.Body.FrontWhiskerRight; changed = true; } break; } if (changed) { this.SendNotification<pxbumper.Update>(_subMgrPort, new pxbumper.Update(bumper)); } } } [ServiceHandler(ServiceHandlerBehavior.Concurrent)] public virtual IEnumerator<ITask> GetHandler(pxbumper.Get get) { get.ResponsePort.Post(_state); yield break; } [ServiceHandler(ServiceHandlerBehavior.Concurrent)] public virtual IEnumerator<ITask> HttpGetHandler(HttpGet httpGet) { httpGet.ResponsePort.Post(new HttpResponseType( HttpStatusCode.OK, _state, _transform) ); yield break; } [ServiceHandler(ServiceHandlerBehavior.Exclusive)] public virtual IEnumerator<ITask> UpdateHandler(pxbumper.Update updateBumper) { throw new InvalidOperationException("Track Roamer Bumper Sensors are not updateable"); } [ServiceHandler(ServiceHandlerBehavior.Exclusive)] public virtual IEnumerator<ITask> ReplaceHandler(pxbumper.Replace replace) { _state = replace.Body; replace.ResponsePort.Post(DefaultReplaceResponseType.Instance); yield break; } [ServiceHandler(ServiceHandlerBehavior.Exclusive)] public virtual IEnumerator<ITask> SubscribeHandler(pxbumper.Subscribe subscribe) { LogInfo("TrackRoamerBumper received Subscription request from Subscriber=" + subscribe.Body.Subscriber); base.SubscribeHelper(_subMgrPort, subscribe.Body, subscribe.ResponsePort); yield break; } [ServiceHandler(ServiceHandlerBehavior.Exclusive)] public virtual IEnumerator<ITask> ReliableSubscribeHandler(pxbumper.ReliableSubscribe subscribe) { LogInfo("TrackRoamerBumper received Reliable Subscription request from Subscriber=" + subscribe.Body.Subscriber); base.SubscribeHelper(_subMgrPort, subscribe.Body, subscribe.ResponsePort); yield break; } [ServiceHandler(ServiceHandlerBehavior.Teardown)] public virtual IEnumerator<ITask> DropHandler(DsspDefaultDrop drop) { LogInfo("TrackRoamerBumper:DropHandler()"); base.DefaultDropHandler(drop); yield break; } } }
//----------------------------------------------------------------------- // <copyright file="TimeoutsSpec.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Akka.Streams.Dsl; using Akka.Streams.TestKit; using Akka.Streams.TestKit.Tests; using Akka.TestKit; using FluentAssertions; using Xunit; using Xunit.Abstractions; namespace Akka.Streams.Tests.Implementation { public class TimeoutsSpec : AkkaSpec { private ActorMaterializer Materializer { get; } public TimeoutsSpec(ITestOutputHelper helper = null) : base(helper) { Materializer = ActorMaterializer.Create(Sys); } [Fact] public void InitialTimeout_must_pass_through_elements_unmodified() { this.AssertAllStagesStopped(() => { var t = Source.From(Enumerable.Range(1, 100)) .InitialTimeout(TimeSpan.FromSeconds(2)).Grouped(200) .RunWith(Sink.First<IEnumerable<int>>(), Materializer); t.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); t.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1, 100)); }, Materializer); } [Fact] public void InitialTimeout_must_pass_through_error_unmodified() { this.AssertAllStagesStopped(() => { var task = Source.From(Enumerable.Range(1, 100)) .Concat(Source.Failed<int>(new TestException("test"))) .InitialTimeout(TimeSpan.FromSeconds(2)).Grouped(200) .RunWith(Sink.First<IEnumerable<int>>(), Materializer); task.Invoking(t => t.Wait(TimeSpan.FromSeconds(3))) .ShouldThrow<TestException>().WithMessage("test"); }, Materializer); } [Fact] public void InitialTimeout_must_fail_if_no_initial_element_passes_until_timeout() { this.AssertAllStagesStopped(() => { var downstreamProbe = this.CreateSubscriberProbe<int>(); Source.Maybe<int>() .InitialTimeout(TimeSpan.FromSeconds(1)) .RunWith(Sink.FromSubscriber(downstreamProbe), Materializer); downstreamProbe.ExpectSubscription(); downstreamProbe.ExpectNoMsg(TimeSpan.FromMilliseconds(500)); var ex = downstreamProbe.ExpectError(); ex.Message.Should().Be($"The first element has not yet passed through in {TimeSpan.FromSeconds(1)}."); }, Materializer); } [Fact] public void CompletionTimeout_must_pass_through_elemnts_unmodified() { this.AssertAllStagesStopped(() => { var t = Source.From(Enumerable.Range(1, 100)) .CompletionTimeout(TimeSpan.FromSeconds(2)).Grouped(200) .RunWith(Sink.First<IEnumerable<int>>(), Materializer); t.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); t.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1, 100)); }, Materializer); } [Fact] public void CompletionTimeout_must_pass_through_error_unmodified() { this.AssertAllStagesStopped(() => { var task = Source.From(Enumerable.Range(1, 100)) .Concat(Source.Failed<int>(new TestException("test"))) .CompletionTimeout(TimeSpan.FromSeconds(2)).Grouped(200) .RunWith(Sink.First<IEnumerable<int>>(), Materializer); task.Invoking(t => t.Wait(TimeSpan.FromSeconds(3))) .ShouldThrow<TestException>().WithMessage("test"); }, Materializer); } [Fact] public void CompletionTimeout_must_fail_if_not_completed_until_timeout() { this.AssertAllStagesStopped(() => { var upstreamProbe = this.CreatePublisherProbe<int>(); var downstreamProbe = this.CreateSubscriberProbe<int>(); Source.FromPublisher(upstreamProbe) .CompletionTimeout(TimeSpan.FromSeconds(2)) .RunWith(Sink.FromSubscriber(downstreamProbe), Materializer); upstreamProbe.SendNext(1); downstreamProbe.RequestNext(1); downstreamProbe.ExpectNoMsg(TimeSpan.FromMilliseconds(500)); // No timeout yet upstreamProbe.SendNext(2); downstreamProbe.RequestNext(2); downstreamProbe.ExpectNoMsg(TimeSpan.FromMilliseconds(500)); // No timeout yet var ex = downstreamProbe.ExpectError(); ex.Message.Should().Be($"The stream has not been completed in {TimeSpan.FromSeconds(2)}."); }, Materializer); } [Fact] public void IdleTimeout_must_pass_through_elements_unmodified() { this.AssertAllStagesStopped(() => { var t = Source.From(Enumerable.Range(1, 100)) .IdleTimeout(TimeSpan.FromSeconds(2)).Grouped(200) .RunWith(Sink.First<IEnumerable<int>>(), Materializer); t.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); t.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1, 100)); }, Materializer); } [Fact] public void IdleTimeout_must_pass_through_error_unmodified() { this.AssertAllStagesStopped(() => { var task = Source.From(Enumerable.Range(1, 100)) .Concat(Source.Failed<int>(new TestException("test"))) .IdleTimeout(TimeSpan.FromSeconds(2)).Grouped(200) .RunWith(Sink.First<IEnumerable<int>>(), Materializer); task.Invoking(t => t.Wait(TimeSpan.FromSeconds(3))) .ShouldThrow<TestException>().WithMessage("test"); }, Materializer); } [Fact] public void IdleTimeout_must_fail_if_time_between_elements_is_too_large() { this.AssertAllStagesStopped(() => { var upstreamProbe = this.CreatePublisherProbe<int>(); var downstreamProbe = this.CreateSubscriberProbe<int>(); Source.FromPublisher(upstreamProbe) .IdleTimeout(TimeSpan.FromSeconds(1)) .RunWith(Sink.FromSubscriber(downstreamProbe), Materializer); // Two seconds in overall, but won't timeout until time between elements is large enough // (i.e. this works differently from completionTimeout) for (var i = 1; i <= 4; i++) { upstreamProbe.SendNext(1); downstreamProbe.RequestNext(1); downstreamProbe.ExpectNoMsg(TimeSpan.FromMilliseconds(500)); // No timeout yet } var ex = downstreamProbe.ExpectError(); ex.Message.Should().Be($"No elements passed in the last {TimeSpan.FromSeconds(1)}."); }, Materializer); } [Fact] public void BackpressureTimeout_must_pass_through_elements_unmodified() { this.AssertAllStagesStopped(() => { Source.From(Enumerable.Range(1, 100)) .BackpressureTimeout(TimeSpan.FromSeconds(1)) .Grouped(200) .RunWith(Sink.First<IEnumerable<int>>(), Materializer) .AwaitResult() .ShouldAllBeEquivalentTo(Enumerable.Range(1, 100)); }, Materializer); } [Fact] public void BackpressureTimeout_must_suceed_if_subscriber_demand_arrives() { this.AssertAllStagesStopped(() => { var subscriber = this.CreateSubscriberProbe<int>(); Source.From(new[] { 1, 2, 3, 4 }) .BackpressureTimeout(TimeSpan.FromSeconds(1)) .RunWith(Sink.FromSubscriber(subscriber), Materializer); for (var i = 1; i < 4; i++) { subscriber.RequestNext(i); subscriber.ExpectNoMsg(TimeSpan.FromMilliseconds(250)); } subscriber.RequestNext(4); subscriber.ExpectComplete(); }, Materializer); } [Fact] public void BackpressureTimeout_must_not_throw_if_publisher_is_less_frequent_than_timeout() { this.AssertAllStagesStopped(() => { var publisher = this.CreatePublisherProbe<string>(); var subscriber = this.CreateSubscriberProbe<string>(); Source.FromPublisher(publisher) .BackpressureTimeout(TimeSpan.FromSeconds(1)) .RunWith(Sink.FromSubscriber(subscriber), Materializer); subscriber.Request(2).ExpectNoMsg(TimeSpan.FromSeconds(1)); publisher.SendNext("Quick Msg"); subscriber.ExpectNext("Quick Msg"); subscriber.ExpectNoMsg(TimeSpan.FromSeconds(3)); publisher.SendNext("Slow Msg"); subscriber.ExpectNext("Slow Msg"); publisher.SendComplete(); subscriber.ExpectComplete(); }, Materializer); } [Fact] public void BackpressureTimeout_must_not_throw_if_publisher_wont_perform_emission_ever() { this.AssertAllStagesStopped(() => { var publisher = this.CreatePublisherProbe<string>(); var subscriber = this.CreateSubscriberProbe<string>(); Source.FromPublisher(publisher) .BackpressureTimeout(TimeSpan.FromSeconds(1)) .RunWith(Sink.FromSubscriber(subscriber), Materializer); subscriber.Request(16).ExpectNoMsg(TimeSpan.FromSeconds(2)); publisher.SendComplete(); subscriber.ExpectComplete(); }, Materializer); } [Fact] public void BackpressureTimeout_must_throw_if_subscriber_wont_generate_demand_on_time() { this.AssertAllStagesStopped(() => { var publisher = this.CreatePublisherProbe<int>(); var subscriber = this.CreateSubscriberProbe<int>(); Source.FromPublisher(publisher) .BackpressureTimeout(TimeSpan.FromSeconds(1)) .RunWith(Sink.FromSubscriber(subscriber), Materializer); subscriber.Request(1); publisher.SendNext(1); subscriber.ExpectNext(1); Thread.Sleep(3000); subscriber.ExpectError().Message.Should().Be("No demand signalled in the last 00:00:01."); }, Materializer); } [Fact] public void BackpressureTimeout_must_throw_if_subscriber_never_generate_demand() { this.AssertAllStagesStopped(() => { var publisher = this.CreatePublisherProbe<int>(); var subscriber = this.CreateSubscriberProbe<int>(); Source.FromPublisher(publisher) .BackpressureTimeout(TimeSpan.FromSeconds(1)) .RunWith(Sink.FromSubscriber(subscriber), Materializer); subscriber.ExpectSubscription(); Thread.Sleep(3000); subscriber.ExpectError().Message.Should().Be("No demand signalled in the last 00:00:01."); }, Materializer); } [Fact] public void BackpressureTimeout_must_not_throw_if_publisher_completes_without_fulfilling_subscribers_demand() { this.AssertAllStagesStopped(() => { var publisher = this.CreatePublisherProbe<int>(); var subscriber = this.CreateSubscriberProbe<int>(); Source.FromPublisher(publisher) .BackpressureTimeout(TimeSpan.FromSeconds(1)) .RunWith(Sink.FromSubscriber(subscriber), Materializer); subscriber.Request(2); publisher.SendNext(1); subscriber.ExpectNext(1); subscriber.ExpectNoMsg(TimeSpan.FromSeconds(2)); publisher.SendComplete(); subscriber.ExpectComplete(); }, Materializer); } [Fact] public void IdleTimeoutBidi_must_not_signal_error_in_simple_loopback_case_and_pass_through_elements_unmodified() { this.AssertAllStagesStopped(() => { var timeoutIdentity = BidiFlow.BidirectionalIdleTimeout<int, int>(TimeSpan.FromSeconds(2)).Join(Flow.Create<int>()); var t = Source.From(Enumerable.Range(1, 100)) .Via(timeoutIdentity).Grouped(200) .RunWith(Sink.First<IEnumerable<int>>(), Materializer); t.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); t.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1, 100)); }, Materializer); } [Fact] public void IdleTimeoutBidi_must_not_signal_error_if_traffic_is_one_way() { this.AssertAllStagesStopped(() => { var upstreamWriter = this.CreatePublisherProbe<int>(); var downstreamWriter = this.CreatePublisherProbe<string>(); var upstream = Flow.FromSinkAndSource(Sink.Ignore<string>(), Source.FromPublisher(upstreamWriter), Keep.Left); var downstream = Flow.FromSinkAndSource(Sink.Ignore<int>(), Source.FromPublisher(downstreamWriter), Keep.Left); var assembly = upstream.JoinMaterialized( BidiFlow.BidirectionalIdleTimeout<int, string>(TimeSpan.FromSeconds(2)), Keep.Left).JoinMaterialized(downstream, Keep.Both); var r = assembly.Run(Materializer); var upFinished = r.Item1; var downFinished = r.Item2; upstreamWriter.SendNext(1); Thread.Sleep(1000); upstreamWriter.SendNext(1); Thread.Sleep(1000); upstreamWriter.SendNext(1); Thread.Sleep(1000); upstreamWriter.SendComplete(); downstreamWriter.SendComplete(); upFinished.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); downFinished.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); }, Materializer); } [Fact] public void IdleTimeoutBidi_must_be_able_to_signal_timeout_once_no_traffic_on_either_sides() { this.AssertAllStagesStopped(() => { var upWrite = this.CreatePublisherProbe<string>(); var upRead = this.CreateSubscriberProbe<int>(); var downWrite = this.CreatePublisherProbe<int>(); var downRead = this.CreateSubscriberProbe<string>(); RunnableGraph.FromGraph(GraphDsl.Create(b => { var timeoutStage = b.Add(BidiFlow.BidirectionalIdleTimeout<string, int>(TimeSpan.FromSeconds(2))); b.From(Source.FromPublisher(upWrite)).To(timeoutStage.Inlet1); b.From(timeoutStage.Outlet1).To(Sink.FromSubscriber(downRead)); b.From(timeoutStage.Outlet2).To(Sink.FromSubscriber(upRead)); b.From(Source.FromPublisher(downWrite)).To(timeoutStage.Inlet2); return ClosedShape.Instance; })).Run(Materializer); // Request enough for the whole test upRead.Request(100); downRead.Request(100); upWrite.SendNext("DATA1"); downRead.ExpectNext("DATA1"); Thread.Sleep(1500); downWrite.SendNext(1); upRead.ExpectNext(1); Thread.Sleep(1500); upWrite.SendNext("DATA2"); downRead.ExpectNext("DATA2"); Thread.Sleep(1000); downWrite.SendNext(2); upRead.ExpectNext(2); upRead.ExpectNoMsg(TimeSpan.FromMilliseconds(500)); var error1 = upRead.ExpectError(); var error2 = downRead.ExpectError(); error1.Should().BeOfType<TimeoutException>(); error1.Message.Should().Be($"No elements passed in the last {TimeSpan.FromSeconds(2)}."); error2.ShouldBeEquivalentTo(error1); upWrite.ExpectCancellation(); downWrite.ExpectCancellation(); }, Materializer); } [Fact] public void IdleTimeoutBidi_must_signal_error_to_all_outputs() { this.AssertAllStagesStopped(() => { var upWrite = this.CreatePublisherProbe<string>(); var upRead = this.CreateSubscriberProbe<int>(); var downWrite = this.CreatePublisherProbe<int>(); var downRead = this.CreateSubscriberProbe<string>(); RunnableGraph.FromGraph(GraphDsl.Create(b => { var timeoutStage = b.Add(BidiFlow.BidirectionalIdleTimeout<string, int>(TimeSpan.FromSeconds(2))); b.From(Source.FromPublisher(upWrite)).To(timeoutStage.Inlet1); b.From(timeoutStage.Outlet1).To(Sink.FromSubscriber(downRead)); b.From(timeoutStage.Outlet2).To(Sink.FromSubscriber(upRead)); b.From(Source.FromPublisher(downWrite)).To(timeoutStage.Inlet2); return ClosedShape.Instance; })).Run(Materializer); var te = new TestException("test"); upWrite.SendError(te); upRead.ExpectSubscriptionAndError().ShouldBeEquivalentTo(te); downRead.ExpectSubscriptionAndError().ShouldBeEquivalentTo(te); downWrite.ExpectCancellation(); }, Materializer); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Media; using System.Windows.Media.Animation; namespace FontAwesome.Sharp { public static class Awesome { #region Animation public static readonly DependencyProperty SpinProperty = DependencyProperty.RegisterAttached("Spin", typeof(bool), typeof(Awesome), new PropertyMetadata(false, SpinChanged)); public static readonly DependencyProperty SpinDurationProperty = DependencyProperty.RegisterAttached("SpinDuration", typeof(double), typeof(Awesome), new PropertyMetadata(1.0d, SpinDurationChanged, SpinDurationCoerceValue)); public static readonly DependencyProperty RotationProperty = DependencyProperty.RegisterAttached("Rotation", typeof(double), typeof(Awesome), new PropertyMetadata(0.0d, RotationChanged, RotationCoerceValue)); public static readonly DependencyProperty FlipProperty = DependencyProperty.RegisterAttached("Flip", typeof(FlipOrientation), typeof(Awesome), new PropertyMetadata(FlipOrientation.Normal, FlipChanged)); // ReSharper disable once UnusedMember.Global public static bool GetSpin(DependencyObject target) { return (bool)target.GetValue(SpinProperty); } public static void SetSpin(DependencyObject target, bool value) { target.SetValue(SpinProperty, value); } public static double GetSpinDuration(DependencyObject target) { return (double)target.GetValue(SpinDurationProperty); } public static void SetSpinDuration(DependencyObject target, double value) { target.SetValue(SpinDurationProperty, value); } public static double GetRotation(DependencyObject target) { return (double)target.GetValue(RotationProperty); } public static void SetRotation(DependencyObject target, double value) { target.SetValue(RotationProperty, value); } // ReSharper disable once UnusedMember.Global public static FlipOrientation GetFlip(DependencyObject target) { return (FlipOrientation)target.GetValue(FlipProperty); } public static void SetFlip(DependencyObject target, FlipOrientation value) { target.SetValue(FlipProperty, value); } private static void SpinChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (!(d is FrameworkElement control)) return; if (!(e.NewValue is bool) || e.NewValue.Equals(e.OldValue)) return; var spin = (bool)e.NewValue; if (spin) { var spinDuration = GetSpinDuration(control); BeginSpin(control, spinDuration); } else { StopSpin(control); var rotation = GetRotation(control); SetRotation(control, rotation); } } private static void SpinDurationChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (!(d is FrameworkElement control)) return; if (!(e.NewValue is double) || e.NewValue.Equals(e.OldValue)) return; var spinDuration = (double)e.NewValue; StopSpin(control); BeginSpin(control, spinDuration); } private static object SpinDurationCoerceValue(DependencyObject d, object value) { var val = (double)value; return val < 0 ? 0d : value; } private static void RotationChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (!(d is FrameworkElement control)) return; if (!(e.NewValue is double) || e.NewValue.Equals(e.OldValue)) return; var rotation = (double)e.NewValue; SetRotation(control, rotation); } private static object RotationCoerceValue(DependencyObject d, object value) { return Math.Max(0.0, Math.Min(360.0, (double)value)); } private static void FlipChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (!(d is FrameworkElement control)) return; if (!(e.NewValue is FlipOrientation) || e.NewValue.Equals(e.OldValue)) return; var flipOrientation = (FlipOrientation)e.NewValue; SetFlipOrientation(control, flipOrientation); } private static readonly string SpinnerStoryBoardName = $"{typeof(Awesome).Namespace}.SpinnerStoryBoard"; private static void BeginSpin(FrameworkElement control, double duration) { var transformGroup = control.RenderTransform as TransformGroup ?? new TransformGroup(); var rotateTransform = transformGroup.Children.OfType<RotateTransform>().FirstOrDefault(); if (rotateTransform != null) { rotateTransform.Angle = 0; } else { transformGroup.Children.Add(new RotateTransform(0.0)); control.RenderTransform = transformGroup; control.RenderTransformOrigin = new Point(0.5, 0.5); } var storyboard = GetStoryboard(control); if (storyboard != null) return; storyboard = new Storyboard(); var initialRotation = GetRotation(control); var animation = new DoubleAnimation { From = initialRotation, To = initialRotation + 360.0, AutoReverse = false, RepeatBehavior = RepeatBehavior.Forever, Duration = new Duration(TimeSpan.FromSeconds(duration)) }; storyboard.Children.Add(animation); Storyboard.SetTarget(animation, control); Storyboard.SetTargetProperty(animation, new PropertyPath("(0).(1)[0].(2)", UIElement.RenderTransformProperty, TransformGroup.ChildrenProperty, RotateTransform.AngleProperty)); storyboard.Begin(); control.Resources.Add(SpinnerStoryBoardName, storyboard); } private static void StopSpin(FrameworkElement control) { var storyboard = GetStoryboard(control); if (storyboard == null) return; storyboard.Stop(); control.Resources.Remove(SpinnerStoryBoardName); } private static void SetRotation(UIElement control, double rotation) { var transformGroup = control.RenderTransform as TransformGroup ?? new TransformGroup(); var rotateTransform = transformGroup.Children.OfType<RotateTransform>().FirstOrDefault(); if (rotateTransform != null) { rotateTransform.Angle = rotation; } else { transformGroup.Children.Add(new RotateTransform(rotation)); control.RenderTransform = transformGroup; control.RenderTransformOrigin = new Point(0.5, 0.5); } } private static void SetFlipOrientation(UIElement control, FlipOrientation flipOrientation) { var transformGroup = control.RenderTransform as TransformGroup ?? new TransformGroup(); var scaleX = flipOrientation == FlipOrientation.Horizontal ? -1 : 1; var scaleY = flipOrientation == FlipOrientation.Vertical ? -1 : 1; var scaleTransform = transformGroup.Children.OfType<ScaleTransform>().FirstOrDefault(); if (scaleTransform != null) { scaleTransform.ScaleX = scaleX; scaleTransform.ScaleY = scaleY; } else { transformGroup.Children.Add(new ScaleTransform(scaleX, scaleY)); control.RenderTransform = transformGroup; control.RenderTransformOrigin = new Point(0.5, 0.5); } } private static Storyboard GetStoryboard(FrameworkElement control) { return control.Resources[SpinnerStoryBoardName] as Storyboard; } #endregion Animation #region Inline text public static readonly DependencyProperty InlineProperty = DependencyProperty.RegisterAttached( "Inline", typeof(string), typeof(Awesome), new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.AffectsMeasure, InlinePropertyChanged)); public const string DefaultPattern = @":(\w+):"; public static readonly DependencyProperty PatternProperty = DependencyProperty.RegisterAttached( "Pattern", typeof(string), typeof(Awesome), new PropertyMetadata(DefaultPattern)); public static void SetInline(DependencyObject textBlock, string value) { textBlock.SetValue(InlineProperty, value); } // ReSharper disable once UnusedMember.Global public static string GetInline(DependencyObject textBlock) { return (string)textBlock.GetValue(InlineProperty); } public static void SetPattern(DependencyObject textBlock, string value) { textBlock.SetValue(PatternProperty, value); } public static string GetPattern(DependencyObject textBlock) { return (string)textBlock.GetValue(PatternProperty); } private static void InlinePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (!(d is TextBlock textBlock)) return; var text = (string)e.NewValue ?? string.Empty; var pattern = GetPattern(textBlock) ?? DefaultPattern; var inLines = FormatText(text, pattern).ToList(); if (inLines.Any()) { textBlock.Inlines.Clear(); inLines.ForEach(textBlock.Inlines.Add); } else { textBlock.Text = text; } } public static IEnumerable<Inline> FormatText(string text, string pattern = DefaultPattern) { var tokens = Regex.Split(text, pattern); if (tokens.Length == 1) return Enumerable.Empty<Inline>(); var inlines = new List<Inline>(); for (var i = 0; i < tokens.Length; i += 2) { var t = tokens[i]; if (!string.IsNullOrWhiteSpace(t)) inlines.Add(new Run(t)); if (i + 1 >= tokens.Length) break; t = tokens[i + 1]; inlines.Add(RunFor(t)); } return inlines; } private static Run RunFor(string token) { if (string.IsNullOrWhiteSpace(token)) throw new ArgumentException("token must not be null, empty or whitespace"); return Enum.TryParse<IconChar>(token, true, out var icon) ? new Run(icon.ToChar()) { FontFamily = IconHelper.FontFor(icon) } : new Run(token); } #endregion Inline text } }
/* * Image.cs - Basic image handling for X applications. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace Xsharp { using System; using DotGNU.Images; using OpenSystem.Platform.X11; /// <summary> /// <para>The <see cref="T:Xsharp.Image"/> class manages an image /// consisting of a pixmap and an optional mask. Images may be /// created in memory or loaded from a file.</para> /// </summary> public sealed class Image : IDisposable { // Internal state. private Screen screen; private Xsharp.Pixmap pixmap; private Bitmap mask; private IntPtr pixmapXImage; private IntPtr maskXImage; /// <summary> /// <para>Constructs a new <see cref="T:Xsharp.Image"/> instance /// that represents an off-screen image.</para> /// </summary> /// /// <param name="width"> /// <para>The width of the new image.</para> /// </param> /// /// <param name="height"> /// <para>The height of the new image.</para> /// </param> /// /// <param name="hasMask"> /// <para>Set to <see langword="null"/> if the optional mask /// should also be created.</para> /// </param> /// /// <exception cref="T:Xsharp.XException"> /// <para>The <paramref name="width"/> or <paramref name="height"/> /// values are out of range.</para> /// </exception> public Image(int width, int height, bool hasMask) { pixmap = new Pixmap(width, height); screen = pixmap.screen; if(hasMask) { mask = new Bitmap(width, height); } else { mask = null; } } /// <summary> /// <para>Constructs a new <see cref="T:Xsharp.Image"/> instance /// that represents an off-screen image on a particular screen.</para> /// </summary> /// /// <param name="screen"> /// <para>The screen upon which to create the new pixmap.</para> /// </param> /// /// <param name="width"> /// <para>The width of the new image.</para> /// </param> /// /// <param name="height"> /// <para>The height of the new image.</para> /// </param> /// /// <param name="hasMask"> /// <para>Set to <see langword="null"/> if the optional mask /// should also be created.</para> /// </param> /// /// <exception cref="T:Xsharp.XException"> /// <para>The <paramref name="width"/> or <paramref name="height"/> /// values are out of range.</para> /// </exception> public Image(Screen screen, int width, int height, bool hasMask) { pixmap = new Xsharp.Pixmap(screen, width, height); screen = pixmap.screen; if(hasMask) { mask = new Bitmap(screen, width, height); } else { mask = null; } } /// <summary> /// <para>Constructs a new <see cref="T:Xsharp.Image"/> instance /// that represents an off-screen image on a particular screen.</para> /// </summary> /// /// <param name="screen"> /// <para>The screen upon which to create the new pixmap.</para> /// </param> /// /// <param name="width"> /// <para>The width of the new image.</para> /// </param> /// /// <param name="height"> /// <para>The height of the new image.</para> /// </param> /// /// <param name="image"> /// <para>The bits that make up the image.</para> /// </param> /// /// <param name="mask"> /// <para>The bits that make up the mask.</para> /// </param> /// /// <exception cref="T:Xsharp.XException"> /// <para>The <paramref name="width"/> or <paramref name="height"/> /// values are out of range.</para> /// </exception> public Image(Screen screen, int width, int height, byte[] image, byte[] mask) { Display dpy; if(screen != null) { dpy = screen.DisplayOfScreen; } else { dpy = Application.Primary.Display; screen = dpy.DefaultScreenOfDisplay; } this.screen = screen; if(width < 1 || width > 32767 || height < 1 || height > 32767) { throw new XException(S._("X_InvalidBitmapSize")); } if(image == null) { throw new ArgumentNullException("bits"); } if(((((width + 15) & ~15) * height) / 8) > image.Length) { throw new XException(S._("X_InvalidBitmapBits")); } try { IntPtr display = dpy.Lock(); XDrawable drawable = (XDrawable) Xlib.XRootWindowOfScreen(screen.screen); XPixmap pixmap = Xlib.XCreateBitmapFromData (display, drawable, image, (uint)width, (uint)height); this.pixmap = new Pixmap(dpy, screen, pixmap); } finally { dpy.Unlock(); } if (mask != null) this.mask = new Bitmap(screen, width, height, mask); } /// <summary> /// <para>Constructs a new <see cref="T:Xsharp.Image"/> instance /// that represents an off-screen image that was loaded /// from a file.</para> /// </summary> /// /// <param name="filename"> /// <para>The file to load the image from.</para> /// </param> /// /// <exception cref="T:System.ArgumentNullException"> /// <para>The <paramref name="filename"/> parameter is /// <see langword="null"/>.</para> /// </exception> /// /// <exception cref="T:System.FormatException"> /// <para>The image format is not recognized.</para> /// </exception> /// /// <exception cref="T:Xsharp.XInvalidOperationException"> /// <para>Raised if <paramref name="filename"/> could not be /// loaded for some reason.</para> /// </exception> public Image(String filename) : this(null, filename) {} /// <summary> /// <para>Constructs a new <see cref="T:Xsharp.Image"/> instance /// that represents an off-screen image that was loaded /// from a file.</para> /// </summary> /// /// <param name="screen"> /// <para>The screen upon which to create the new pixmap.</para> /// </param> /// /// <param name="filename"> /// <para>The file to load the image from.</para> /// </param> /// /// <exception cref="T:System.ArgumentNullException"> /// <para>The <paramref name="filename"/> parameter is /// <see langword="null"/>.</para> /// </exception> /// /// <exception cref="T:System.FormatException"> /// <para>The image format is not recognized.</para> /// </exception> /// /// <exception cref="T:Xsharp.XInvalidOperationException"> /// <para>Raised if <paramref name="filename"/> could not be /// loaded for some reason.</para> /// </exception> public Image(Screen screen, String filename) { Display dpy; if(filename == null) { throw new ArgumentNullException("filename"); } if(screen != null) { dpy = screen.DisplayOfScreen; } else { dpy = Application.Primary.Display; screen = dpy.DefaultScreenOfDisplay; } this.screen = screen; DotGNU.Images.Image img = new DotGNU.Images.Image(); img.Load(filename); Frame frame = img.GetFrame(0); try { dpy.Lock(); pixmapXImage = ConvertImage.FrameToXImage(screen, frame); maskXImage = ConvertImage.MaskToXImage(screen, frame); } finally { dpy.Unlock(); } } /// <summary> /// <para>Constructs a new <see cref="T:Xsharp.Image"/> instance /// from a <see cref="T:DotGNU.Images.Frame"/> instance.</para> /// </summary> /// /// <param name="frame"> /// <para>The frame to load the image from.</para> /// </param> /// /// <exception cref="T:System.ArgumentNullException"> /// <para>The <paramref name="frame"/> parameter is /// <see langword="null"/>.</para> /// </exception> /// /// <exception cref="T:Xsharp.XInvalidOperationException"> /// <para>Raised if <paramref name="filename"/> could not be /// loaded for some reason.</para> /// </exception> public Image(Frame frame) : this(null, frame) {} /// <summary> /// <para>Constructs a new <see cref="T:Xsharp.Image"/> instance /// from a <see cref="T:DotGNU.Images.Frame"/> instance.</para> /// </summary> /// /// <param name="screen"> /// <para>The screen upon which to create the new image.</para> /// </param> /// /// <param name="frame"> /// <para>The frame to load the image from.</para> /// </param> /// /// <exception cref="T:System.ArgumentNullException"> /// <para>The <paramref name="frame"/> parameter is /// <see langword="null"/>.</para> /// </exception> /// /// <exception cref="T:Xsharp.XInvalidOperationException"> /// <para>Raised if <paramref name="filename"/> could not be /// loaded for some reason.</para> /// </exception> public Image(Screen screen, Frame frame) { Display dpy; if(frame == null) { throw new ArgumentNullException("frame"); } if(screen != null) { dpy = screen.DisplayOfScreen; } else { dpy = Application.Primary.Display; screen = dpy.DefaultScreenOfDisplay; } this.screen = screen; try { dpy.Lock(); pixmapXImage = ConvertImage.FrameToXImage(screen, frame); maskXImage = ConvertImage.MaskToXImage(screen, frame); } finally { dpy.Unlock(); } } /// <summary> /// <para>Retrieve the pixmap that is associated with this image.</para> /// </summary> /// /// <value> /// <para>The pixmap instance, or <see langword="null"/> if disposed. /// </para> /// </value> public Xsharp.Pixmap Pixmap { get { if(pixmap == null && pixmapXImage != IntPtr.Zero) { pixmap = ConvertImage.XImageToPixmap (screen, pixmapXImage); } return pixmap; } } /// <summary> /// <para>Retrieve the mask that is associated with this image.</para> /// </summary> /// /// <value> /// <para>The mask instance, or <see langword="null"/> if disposed. /// </para> /// </value> public Bitmap Mask { get { if(mask == null && maskXImage != IntPtr.Zero) { mask = ConvertImage.XImageMaskToBitmap (screen, maskXImage); } return mask; } } /// <summary> /// <para>Get the width of the image.</para> /// </summary> /// /// <value> /// <para>The image's width.</para> /// </para> /// </value> public int Width { get { if(pixmap != null) { return pixmap.Width; } else if(pixmapXImage != IntPtr.Zero) { int width, height; Xlib.XSharpGetImageSize (pixmapXImage, out width, out height); return width; } else { return 0; } } } /// <summary> /// <para>Get the height of the image.</para> /// </summary> /// /// <value> /// <para>The image's height.</para> /// </para> /// </value> public int Height { get { if(pixmap != null) { return pixmap.Height; } else if(pixmapXImage != IntPtr.Zero) { int width, height; Xlib.XSharpGetImageSize (pixmapXImage, out width, out height); return height; } else { return 0; } } } /// <summary> /// <para>Destroy this image if it is currently active.</para> /// </summary> public void Destroy() { if(pixmap != null) { pixmap.Destroy(); pixmap = null; } if(mask != null) { mask.Destroy(); mask = null; } if(pixmapXImage != IntPtr.Zero) { Xlib.XSharpDestroyImage(pixmapXImage); pixmapXImage = IntPtr.Zero; } if(maskXImage != IntPtr.Zero) { Xlib.XSharpDestroyImage(maskXImage); maskXImage = IntPtr.Zero; } } /// <summary> /// <para>Dispose this image if it is currently active.</para> /// </summary> /// /// <remarks> /// <para>This method implements the <see cref="T:System.IDisposable"/> /// interface.</para> /// </remarks> public void Dispose() { if(pixmap != null) { pixmap.Dispose(); } if(mask != null) { mask.Dispose(); } Destroy(); } // Get the image as an XImage, if possible. internal IntPtr XImage { get { return pixmapXImage; } } // Determine if we should use the XImage. If the image is small, // we want to convert it into a "Pixmap", as it will probably be // used over and over again (e.g. toolbar icons). internal bool ShouldUseXImage { get { if(pixmap != null) { return false; } else if(pixmapXImage != IntPtr.Zero) { int width, height; Xlib.XSharpGetImageSize (pixmapXImage, out width, out height); if(width > 32 || height > 32) { return true; } return false; } else { return false; } } } } // class Image } // namespace Xsharp
namespace Nancy { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Cookies; using Nancy.Helpers; /// <summary> /// Encapsulates HTTP-response information from an Nancy operation. /// </summary> public class Response: IDisposable { /// <summary> /// Null object representing no body /// </summary> public static Action<Stream> NoBody = s => { }; private string contentType; /// <summary> /// Initializes a new instance of the <see cref="Response"/> class. /// </summary> public Response() { this.Contents = NoBody; this.ContentType = "text/html"; this.Headers = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); this.StatusCode = HttpStatusCode.OK; this.Cookies = new List<INancyCookie>(2); } /// <summary> /// Gets or sets the type of the content. /// </summary> /// <value>The type of the content.</value> /// <remarks>The default value is <c>text/html</c>.</remarks> public string ContentType { get { return Headers.ContainsKey("content-type") ? Headers["content-type"] : this.contentType; } set { this.contentType = value; } } /// <summary> /// Gets the delegate that will render contents to the response stream. /// </summary> /// <value>An <see cref="Action{T}"/> delegate, containing the code that will render contents to the response stream.</value> /// <remarks>The host of Nancy will pass in the output stream after the response has been handed back to it by Nancy.</remarks> public Action<Stream> Contents { get; set; } /// <summary> /// Gets the collection of HTTP response headers that should be sent back to the client. /// </summary> /// <value>An <see cref="IDictionary{TKey,TValue}"/> instance, containing the key/value pair of headers.</value> public IDictionary<string, string> Headers { get; set; } /// <summary> /// Gets or sets the HTTP status code that should be sent back to the client. /// </summary> /// <value>A <see cref="HttpStatusCode"/> value.</value> public HttpStatusCode StatusCode { get; set; } /// <summary> /// Gets or sets a text description of the HTTP status code returned to the client. /// </summary> /// <value>The HTTP status code description.</value> public string ReasonPhrase { get; set; } /// <summary> /// Gets the <see cref="INancyCookie"/> instances that are associated with the response. /// </summary> /// <value>A <see cref="IList{T}"/> instance, containing <see cref="INancyCookie"/> instances.</value> public IList<INancyCookie> Cookies { get; private set; } /// <summary> /// Executes at the end of the nancy execution pipeline and before control is passed back to the hosting. /// Can be used to pre-render/validate views while still inside the main pipeline/error handling. /// </summary> /// <param name="context">Nancy context</param> /// <returns>Task for completion/erroring</returns> public virtual Task PreExecute(NancyContext context) { return TaskHelpers.GetCompletedTask(); } /// <summary> /// Adds a <see cref="INancyCookie"/> to the response. /// </summary> /// <param name="name">The name of the cookie.</param> /// <param name="value">The value of the cookie.</param> /// <returns>The <see cref="Response"/> instance.</returns> [Obsolete("This method has been replaced with Response.WithCookie and will be removed in a subsequent release.")] public Response AddCookie(string name, string value) { return AddCookie(name, value, null, null, null); } /// <summary> /// Adds a <see cref="INancyCookie"/> to the response. /// </summary> /// <param name="name">The name of the cookie.</param> /// <param name="value">The value of the cookie.</param> /// <param name="expires">The expiration date of the cookie. Can be <see langword="null" /> if it should expire at the end of the session.</param> /// <returns>The <see cref="Response"/> instance.</returns> [Obsolete("This method has been replaced with Response.WithCookie and will be removed in a subsequent release.")] public Response AddCookie(string name, string value, DateTime? expires) { return AddCookie(name, value, expires, null, null); } /// <summary> /// Adds a <see cref="INancyCookie"/> to the response. /// </summary> /// <param name="name">The name of the cookie.</param> /// <param name="value">The value of the cookie.</param> /// <param name="expires">The expiration date of the cookie. Can be <see langword="null" /> if it should expire at the end of the session.</param> /// <param name="domain">The domain of the cookie.</param> /// <param name="path">The path of the cookie.</param> /// <returns>The <see cref="Response"/> instance.</returns> [Obsolete("This method has been replaced with Response.WithCookie and will be removed in a subsequent release.")] public Response AddCookie(string name, string value, DateTime? expires, string domain, string path) { return AddCookie(new NancyCookie(name, value){ Expires = expires, Domain = domain, Path = path }); } /// <summary> /// Adds a <see cref="INancyCookie"/> to the response. /// </summary> /// <param name="nancyCookie">A <see cref="INancyCookie"/> instance.</param> /// <returns></returns> [Obsolete("This method has been replaced with Response.WithCookie and will be removed in a subsequent release.")] public Response AddCookie(INancyCookie nancyCookie) { Cookies.Add(nancyCookie); return this; } /// <summary> /// Implicitly cast an <see cref="HttpStatusCode"/> value to a <see cref="Response"/> instance, with the <see cref="StatusCode"/> /// set to the value of the <see cref="HttpStatusCode"/>. /// </summary> /// <param name="statusCode">The <see cref="HttpStatusCode"/> value that is being cast from.</param> /// <returns>A <see cref="Response"/> instance.</returns> public static implicit operator Response(HttpStatusCode statusCode) { return new Response { StatusCode = statusCode }; } /// <summary> /// Implicitly cast an int value to a <see cref="Response"/> instance, with the <see cref="StatusCode"/> /// set to the value of the int. /// </summary> /// <param name="statusCode">The int value that is being cast from.</param> /// <returns>A <see cref="Response"/> instance.</returns> public static implicit operator Response(int statusCode) { return new Response { StatusCode = (HttpStatusCode)statusCode }; } /// <summary> /// Implicitly cast an string instance to a <see cref="Response"/> instance, with the <see cref="Contents"/> /// set to the value of the string. /// </summary> /// <param name="contents">The string that is being cast from.</param> /// <returns>A <see cref="Response"/> instance.</returns> public static implicit operator Response(string contents) { return new Response { Contents = GetStringContents(contents) }; } /// <summary> /// Implicitly cast an <see cref="Action{T}"/>, where T is a <see cref="Stream"/>, instance to /// a <see cref="Response"/> instance, with the <see cref="Contents"/> set to the value of the action. /// </summary> /// <param name="streamFactory">The <see cref="Action{T}"/> instance that is being cast from.</param> /// <returns>A <see cref="Response"/> instance.</returns> public static implicit operator Response(Action<Stream> streamFactory) { return new Response { Contents = streamFactory }; } /// <summary> /// Implicitly cast a <see cref="DynamicDictionaryValue"/> instance to a <see cref="Response"/> instance, /// with the <see cref="Contents"/> set to the value of the <see cref="DynamicDictionaryValue"/>. /// </summary> /// <param name="value">The <see cref="DynamicDictionaryValue"/> instance that is being cast from.</param> /// <returns>A <see cref="Response"/> instance.</returns> public static implicit operator Response(DynamicDictionaryValue value) { return new Response { Contents = GetStringContents(value) }; } /// <summary> /// Converts a string content value to a response action. /// </summary> /// <param name="contents">The string containing the content.</param> /// <returns>A response action that will write the content of the string to the response stream.</returns> protected static Action<Stream> GetStringContents(string contents) { return stream => { var writer = new StreamWriter(stream) { AutoFlush = true }; writer.Write(contents); }; } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> /// <remarks>This method can be overridden in sub-classes to dispose of response specific resources.</remarks> public virtual void Dispose() { } } }
using System; using System.IO; using System.ComponentModel; using System.Collections.Generic; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using ChargeBee.Internal; using ChargeBee.Api; using ChargeBee.Models.Enums; namespace ChargeBee.Models { public class Transaction : Resource { #region Methods public static ListRequest List(ApiConfig apiConfig) { string url = ApiUtil.BuildUrl(apiConfig, "transactions"); return new ListRequest(url); } public static ListRequest TransactionsForCustomer(ApiConfig apiConfig,string id) { string url = ApiUtil.BuildUrl(apiConfig, "customers", CheckNull(id), "transactions"); return new ListRequest(url); } public static ListRequest TransactionsForSubscription(ApiConfig apiConfig,string id) { string url = ApiUtil.BuildUrl(apiConfig, "subscriptions", CheckNull(id), "transactions"); return new ListRequest(url); } public static ListRequest TransactionsForInvoice(ApiConfig apiConfig,string id) { string url = ApiUtil.BuildUrl(apiConfig, "invoices", CheckNull(id), "transactions"); return new ListRequest(url); } public static EntityRequest<Type> Retrieve(ApiConfig apiConfig,string id) { string url = ApiUtil.BuildUrl(apiConfig, "transactions", CheckNull(id)); return new EntityRequest<Type>(url, HttpMethod.GET); } public static RecordPaymentRequest RecordPayment(ApiConfig apiConfig,string id) { string url = ApiUtil.BuildUrl(apiConfig, "invoices", CheckNull(id), "record_payment"); return new RecordPaymentRequest(url, HttpMethod.POST); } #endregion #region Properties public string Id { get { return GetValue<string>("id", true); } } public string CustomerId { get { return GetValue<string>("customer_id", false); } } public string SubscriptionId { get { return GetValue<string>("subscription_id", false); } } public PaymentMethodEnum PaymentMethod { get { return GetEnum<PaymentMethodEnum>("payment_method", true); } } public string ReferenceNumber { get { return GetValue<string>("reference_number", false); } } public GatewayEnum Gateway { get { return GetEnum<GatewayEnum>("gateway", true); } } [Obsolete] public string Description { get { return GetValue<string>("description", false); } } public TypeEnum TransactionType { get { return GetEnum<TypeEnum>("type", true); } } public DateTime? Date { get { return GetDateTime("date", false); } } public int? Amount { get { return GetValue<int?>("amount", false); } } public string IdAtGateway { get { return GetValue<string>("id_at_gateway", false); } } public StatusEnum? Status { get { return GetEnum<StatusEnum>("status", false); } } public string ErrorCode { get { return GetValue<string>("error_code", false); } } public string ErrorText { get { return GetValue<string>("error_text", false); } } public DateTime? VoidedAt { get { return GetDateTime("voided_at", false); } } [Obsolete] public string VoidDescription { get { return GetValue<string>("void_description", false); } } public string MaskedCardNumber { get { return GetValue<string>("masked_card_number", true); } } public string RefundedTxnId { get { return GetValue<string>("refunded_txn_id", false); } } public List<TransactionLinkedInvoice> LinkedInvoices { get { return GetResourceList<TransactionLinkedInvoice>("linked_invoices"); } } #endregion #region Requests public class RecordPaymentRequest : EntityRequest<RecordPaymentRequest> { public RecordPaymentRequest(string url, HttpMethod method) : base(url, method) { } public RecordPaymentRequest Amount(int amount) { m_params.AddOpt("amount", amount); return this; } public RecordPaymentRequest PaymentMethod(PaymentMethodEnum paymentMethod) { m_params.Add("payment_method", paymentMethod); return this; } public RecordPaymentRequest PaidAt(long paidAt) { m_params.Add("paid_at", paidAt); return this; } public RecordPaymentRequest ReferenceNumber(string referenceNumber) { m_params.AddOpt("reference_number", referenceNumber); return this; } public RecordPaymentRequest Memo(string memo) { m_params.AddOpt("memo", memo); return this; } } #endregion public enum TypeEnum { UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a dotnet-client version incompatibility. We suggest you to upgrade to the latest version */ [Description("authorization")] Authorization, [Description("payment")] Payment, [Description("refund")] Refund, } public enum StatusEnum { UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a dotnet-client version incompatibility. We suggest you to upgrade to the latest version */ [Description("success")] Success, [Description("voided")] Voided, [Description("failure")] Failure, [Description("timeout")] Timeout, [Description("needs_attention")] NeedsAttention, } #region Subclasses public class TransactionLinkedInvoice : Resource { public string InvoiceId() { return GetValue<string>("invoice_id", true); } public int AppliedAmount() { return GetValue<int>("applied_amount", true); } public DateTime? InvoiceDate() { return GetDateTime("invoice_date", false); } public int? InvoiceAmount() { return GetValue<int?>("invoice_amount", false); } } #endregion } }
#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.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Grpc.Core.Internal; using Grpc.Core.Utils; namespace Grpc.Core.Internal { /// <summary> /// Manages client side native call lifecycle. /// </summary> internal class AsyncCall<TRequest, TResponse> : AsyncCallBase<TRequest, TResponse> { readonly CompletionCallbackDelegate unaryResponseHandler; readonly CompletionCallbackDelegate finishedHandler; // Completion of a pending unary response if not null. TaskCompletionSource<TResponse> unaryResponseTcs; // Set after status is received. Only used for streaming response calls. Status? finishedStatus; bool readObserverCompleted; // True if readObserver has already been completed. public AsyncCall(Func<TRequest, byte[]> serializer, Func<byte[], TResponse> deserializer) : base(serializer, deserializer) { this.unaryResponseHandler = CreateBatchCompletionCallback(HandleUnaryResponse); this.finishedHandler = CreateBatchCompletionCallback(HandleFinished); } public void Initialize(Channel channel, CompletionQueueSafeHandle cq, string methodName) { var call = CallSafeHandle.Create(channel.Handle, cq, methodName, channel.Target, Timespec.InfFuture); DebugStats.ActiveClientCalls.Increment(); InitializeInternal(call); } // TODO: this method is not Async, so it shouldn't be in AsyncCall class, but // it is reusing fair amount of code in this class, so we are leaving it here. // TODO: for other calls, you need to call Initialize, this methods calls initialize // on its own, so there's a usage inconsistency. /// <summary> /// Blocking unary request - unary response call. /// </summary> public TResponse UnaryCall(Channel channel, string methodName, TRequest msg, Metadata headers) { using (CompletionQueueSafeHandle cq = CompletionQueueSafeHandle.Create()) { byte[] payload = UnsafeSerialize(msg); unaryResponseTcs = new TaskCompletionSource<TResponse>(); lock (myLock) { Initialize(channel, cq, methodName); started = true; halfcloseRequested = true; readingDone = true; } using (var metadataArray = MetadataArraySafeHandle.Create(headers)) { call.BlockingUnary(cq, payload, unaryResponseHandler, metadataArray); } try { // Once the blocking call returns, the result should be available synchronously. return unaryResponseTcs.Task.Result; } catch (AggregateException ae) { throw ExceptionHelper.UnwrapRpcException(ae); } } } /// <summary> /// Starts a unary request - unary response call. /// </summary> public Task<TResponse> UnaryCallAsync(TRequest msg, Metadata headers) { lock (myLock) { Preconditions.CheckNotNull(call); started = true; halfcloseRequested = true; readingDone = true; byte[] payload = UnsafeSerialize(msg); unaryResponseTcs = new TaskCompletionSource<TResponse>(); using (var metadataArray = MetadataArraySafeHandle.Create(headers)) { call.StartUnary(payload, unaryResponseHandler, metadataArray); } return unaryResponseTcs.Task; } } /// <summary> /// Starts a streamed request - unary response call. /// Use StartSendMessage and StartSendCloseFromClient to stream requests. /// </summary> public Task<TResponse> ClientStreamingCallAsync(Metadata headers) { lock (myLock) { Preconditions.CheckNotNull(call); started = true; readingDone = true; unaryResponseTcs = new TaskCompletionSource<TResponse>(); using (var metadataArray = MetadataArraySafeHandle.Create(headers)) { call.StartClientStreaming(unaryResponseHandler, metadataArray); } return unaryResponseTcs.Task; } } /// <summary> /// Starts a unary request - streamed response call. /// </summary> public void StartServerStreamingCall(TRequest msg, Metadata headers) { lock (myLock) { Preconditions.CheckNotNull(call); started = true; halfcloseRequested = true; halfclosed = true; // halfclose not confirmed yet, but it will be once finishedHandler is called. byte[] payload = UnsafeSerialize(msg); using (var metadataArray = MetadataArraySafeHandle.Create(headers)) { call.StartServerStreaming(payload, finishedHandler, metadataArray); } } } /// <summary> /// Starts a streaming request - streaming response call. /// Use StartSendMessage and StartSendCloseFromClient to stream requests. /// </summary> public void StartDuplexStreamingCall(Metadata headers) { lock (myLock) { Preconditions.CheckNotNull(call); started = true; using (var metadataArray = MetadataArraySafeHandle.Create(headers)) { call.StartDuplexStreaming(finishedHandler, metadataArray); } } } /// <summary> /// Sends a streaming request. Only one pending send action is allowed at any given time. /// completionDelegate is called when the operation finishes. /// </summary> public void StartSendMessage(TRequest msg, AsyncCompletionDelegate<object> completionDelegate) { StartSendMessageInternal(msg, completionDelegate); } /// <summary> /// Receives a streaming response. Only one pending read action is allowed at any given time. /// completionDelegate is called when the operation finishes. /// </summary> public void StartReadMessage(AsyncCompletionDelegate<TResponse> completionDelegate) { StartReadMessageInternal(completionDelegate); } /// <summary> /// Sends halfclose, indicating client is done with streaming requests. /// Only one pending send action is allowed at any given time. /// completionDelegate is called when the operation finishes. /// </summary> public void StartSendCloseFromClient(AsyncCompletionDelegate<object> completionDelegate) { lock (myLock) { Preconditions.CheckNotNull(completionDelegate, "Completion delegate cannot be null"); CheckSendingAllowed(); call.StartSendCloseFromClient(halfclosedHandler); halfcloseRequested = true; sendCompletionDelegate = completionDelegate; } } /// <summary> /// On client-side, we only fire readCompletionDelegate once all messages have been read /// and status has been received. /// </summary> protected override void ProcessLastRead(AsyncCompletionDelegate<TResponse> completionDelegate) { if (completionDelegate != null && readingDone && finishedStatus.HasValue) { bool shouldComplete; lock (myLock) { shouldComplete = !readObserverCompleted; readObserverCompleted = true; } if (shouldComplete) { var status = finishedStatus.Value; if (status.StatusCode != StatusCode.OK) { FireCompletion(completionDelegate, default(TResponse), new RpcException(status)); } else { FireCompletion(completionDelegate, default(TResponse), null); } } } } protected override void OnReleaseResources() { DebugStats.ActiveClientCalls.Decrement(); } /// <summary> /// Handler for unary response completion. /// </summary> private void HandleUnaryResponse(bool success, BatchContextSafeHandleNotOwned ctx) { lock (myLock) { finished = true; halfclosed = true; ReleaseResourcesIfPossible(); } if (!success) { unaryResponseTcs.SetException(new RpcException(new Status(StatusCode.Internal, "Internal error occured."))); return; } var status = ctx.GetReceivedStatus(); if (status.StatusCode != StatusCode.OK) { unaryResponseTcs.SetException(new RpcException(status)); return; } // TODO: handle deserialization error TResponse msg; TryDeserialize(ctx.GetReceivedMessage(), out msg); unaryResponseTcs.SetResult(msg); } /// <summary> /// Handles receive status completion for calls with streaming response. /// </summary> private void HandleFinished(bool success, BatchContextSafeHandleNotOwned ctx) { var status = ctx.GetReceivedStatus(); AsyncCompletionDelegate<TResponse> origReadCompletionDelegate = null; lock (myLock) { finished = true; finishedStatus = status; origReadCompletionDelegate = readCompletionDelegate; ReleaseResourcesIfPossible(); } ProcessLastRead(origReadCompletionDelegate); } } }
// Copyright (C) 2014 dot42 // // Original filename: Org.Apache.Http.Util.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma warning disable 1717 namespace Org.Apache.Http.Util { /// <summary> /// <para>Provides access to version information for HTTP components. Instances of this class provide version information for a single module or informal unit, as explained . Static methods are used to extract version information from property files that are automatically packaged with HTTP component release JARs. <br></br> All available version information is provided in strings, where the string format is informal and subject to change without notice. Version information is provided for debugging output and interpretation by humans, not for automated processing in applications.</para><para><para> </para><simplesectsep></simplesectsep><para>and others </para></para> /// </summary> /// <java-name> /// org/apache/http/util/VersionInfo /// </java-name> [Dot42.DexImport("org/apache/http/util/VersionInfo", AccessFlags = 33)] public partial class VersionInfo /* scope: __dot42__ */ { /// <summary> /// <para>A string constant for unavailable information. </para> /// </summary> /// <java-name> /// UNAVAILABLE /// </java-name> [Dot42.DexImport("UNAVAILABLE", "Ljava/lang/String;", AccessFlags = 25)] public const string UNAVAILABLE = "UNAVAILABLE"; /// <summary> /// <para>The filename of the version information files. </para> /// </summary> /// <java-name> /// VERSION_PROPERTY_FILE /// </java-name> [Dot42.DexImport("VERSION_PROPERTY_FILE", "Ljava/lang/String;", AccessFlags = 25)] public const string VERSION_PROPERTY_FILE = "version.properties"; /// <java-name> /// PROPERTY_MODULE /// </java-name> [Dot42.DexImport("PROPERTY_MODULE", "Ljava/lang/String;", AccessFlags = 25)] public const string PROPERTY_MODULE = "info.module"; /// <java-name> /// PROPERTY_RELEASE /// </java-name> [Dot42.DexImport("PROPERTY_RELEASE", "Ljava/lang/String;", AccessFlags = 25)] public const string PROPERTY_RELEASE = "info.release"; /// <java-name> /// PROPERTY_TIMESTAMP /// </java-name> [Dot42.DexImport("PROPERTY_TIMESTAMP", "Ljava/lang/String;", AccessFlags = 25)] public const string PROPERTY_TIMESTAMP = "info.timestamp"; /// <summary> /// <para>Instantiates version information.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/la" + "ng/String;)V", AccessFlags = 4)] protected internal VersionInfo(string pckg, string module, string release, string time, string clsldr) /* MethodBuilder.Create */ { } /// <summary> /// <para>Obtains the package name. The package name identifies the module or informal unit.</para><para></para> /// </summary> /// <returns> /// <para>the package name, never <code>null</code> </para> /// </returns> /// <java-name> /// getPackage /// </java-name> [Dot42.DexImport("getPackage", "()Ljava/lang/String;", AccessFlags = 17)] public string GetPackage() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Obtains the name of the versioned module or informal unit. This data is read from the version information for the package.</para><para></para> /// </summary> /// <returns> /// <para>the module name, never <code>null</code> </para> /// </returns> /// <java-name> /// getModule /// </java-name> [Dot42.DexImport("getModule", "()Ljava/lang/String;", AccessFlags = 17)] public string GetModule() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Obtains the release of the versioned module or informal unit. This data is read from the version information for the package.</para><para></para> /// </summary> /// <returns> /// <para>the release version, never <code>null</code> </para> /// </returns> /// <java-name> /// getRelease /// </java-name> [Dot42.DexImport("getRelease", "()Ljava/lang/String;", AccessFlags = 17)] public string GetRelease() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Obtains the timestamp of the versioned module or informal unit. This data is read from the version information for the package.</para><para></para> /// </summary> /// <returns> /// <para>the timestamp, never <code>null</code> </para> /// </returns> /// <java-name> /// getTimestamp /// </java-name> [Dot42.DexImport("getTimestamp", "()Ljava/lang/String;", AccessFlags = 17)] public string GetTimestamp() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Obtains the classloader used to read the version information. This is just the <code>toString</code> output of the classloader, since the version information should not keep a reference to the classloader itself. That could prevent garbage collection.</para><para></para> /// </summary> /// <returns> /// <para>the classloader description, never <code>null</code> </para> /// </returns> /// <java-name> /// getClassloader /// </java-name> [Dot42.DexImport("getClassloader", "()Ljava/lang/String;", AccessFlags = 17)] public string GetClassloader() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Provides the version information in human-readable format.</para><para></para> /// </summary> /// <returns> /// <para>a string holding this version information </para> /// </returns> /// <java-name> /// toString /// </java-name> [Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)] public override string ToString() /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// loadVersionInfo /// </java-name> [Dot42.DexImport("loadVersionInfo", "([Ljava/lang/String;Ljava/lang/ClassLoader;)[Lorg/apache/http/util/VersionInfo;", AccessFlags = 25)] public static global::Org.Apache.Http.Util.VersionInfo[] LoadVersionInfo(string[] @string, global::Java.Lang.ClassLoader classLoader) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Util.VersionInfo[]); } /// <java-name> /// loadVersionInfo /// </java-name> [Dot42.DexImport("loadVersionInfo", "(Ljava/lang/String;Ljava/lang/ClassLoader;)Lorg/apache/http/util/VersionInfo;", AccessFlags = 25)] public static global::Org.Apache.Http.Util.VersionInfo LoadVersionInfo(string @string, global::Java.Lang.ClassLoader classLoader) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Util.VersionInfo); } /// <summary> /// <para>Instantiates version information from properties.</para><para></para> /// </summary> /// <returns> /// <para>the version information </para> /// </returns> /// <java-name> /// fromMap /// </java-name> [Dot42.DexImport("fromMap", "(Ljava/lang/String;Ljava/util/Map;Ljava/lang/ClassLoader;)Lorg/apache/http/util/V" + "ersionInfo;", AccessFlags = 28)] protected internal static global::Org.Apache.Http.Util.VersionInfo FromMap(string pckg, global::Java.Util.IMap<object, object> info, global::Java.Lang.ClassLoader clsldr) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Util.VersionInfo); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal VersionInfo() /* TypeBuilder.AddDefaultConstructor */ { } /// <summary> /// <para>Obtains the package name. The package name identifies the module or informal unit.</para><para></para> /// </summary> /// <returns> /// <para>the package name, never <code>null</code> </para> /// </returns> /// <java-name> /// getPackage /// </java-name> public string Package { [Dot42.DexImport("getPackage", "()Ljava/lang/String;", AccessFlags = 17)] get{ return GetPackage(); } } /// <summary> /// <para>Obtains the name of the versioned module or informal unit. This data is read from the version information for the package.</para><para></para> /// </summary> /// <returns> /// <para>the module name, never <code>null</code> </para> /// </returns> /// <java-name> /// getModule /// </java-name> public string Module { [Dot42.DexImport("getModule", "()Ljava/lang/String;", AccessFlags = 17)] get{ return GetModule(); } } /// <summary> /// <para>Obtains the release of the versioned module or informal unit. This data is read from the version information for the package.</para><para></para> /// </summary> /// <returns> /// <para>the release version, never <code>null</code> </para> /// </returns> /// <java-name> /// getRelease /// </java-name> public string Release { [Dot42.DexImport("getRelease", "()Ljava/lang/String;", AccessFlags = 17)] get{ return GetRelease(); } } /// <summary> /// <para>Obtains the timestamp of the versioned module or informal unit. This data is read from the version information for the package.</para><para></para> /// </summary> /// <returns> /// <para>the timestamp, never <code>null</code> </para> /// </returns> /// <java-name> /// getTimestamp /// </java-name> public string Timestamp { [Dot42.DexImport("getTimestamp", "()Ljava/lang/String;", AccessFlags = 17)] get{ return GetTimestamp(); } } /// <summary> /// <para>Obtains the classloader used to read the version information. This is just the <code>toString</code> output of the classloader, since the version information should not keep a reference to the classloader itself. That could prevent garbage collection.</para><para></para> /// </summary> /// <returns> /// <para>the classloader description, never <code>null</code> </para> /// </returns> /// <java-name> /// getClassloader /// </java-name> public string Classloader { [Dot42.DexImport("getClassloader", "()Ljava/lang/String;", AccessFlags = 17)] get{ return GetClassloader(); } } } /// <summary> /// <para>The home for utility methods that handle various encoding tasks.</para><para><para>Michael Becke </para><simplesectsep></simplesectsep><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/util/EncodingUtils /// </java-name> [Dot42.DexImport("org/apache/http/util/EncodingUtils", AccessFlags = 49)] public sealed partial class EncodingUtils /* scope: __dot42__ */ { /// <summary> /// <para>This class should not be instantiated. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 0)] internal EncodingUtils() /* MethodBuilder.Create */ { } /// <summary> /// <para>Converts the byte array of HTTP content characters to a string. If the specified charset is not supported, default system encoding is used.</para><para></para> /// </summary> /// <returns> /// <para>The result of the conversion. </para> /// </returns> /// <java-name> /// getString /// </java-name> [Dot42.DexImport("getString", "([BIILjava/lang/String;)Ljava/lang/String;", AccessFlags = 9)] public static string GetString(sbyte[] data, int offset, int length, string charset) /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Converts the byte array of HTTP content characters to a string. If the specified charset is not supported, default system encoding is used.</para><para></para> /// </summary> /// <returns> /// <para>The result of the conversion. </para> /// </returns> /// <java-name> /// getString /// </java-name> [Dot42.DexImport("getString", "([BIILjava/lang/String;)Ljava/lang/String;", AccessFlags = 9, IgnoreFromJava = true)] public static string GetString(byte[] data, int offset, int length, string charset) /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Converts the byte array of HTTP content characters to a string. If the specified charset is not supported, default system encoding is used.</para><para></para> /// </summary> /// <returns> /// <para>The result of the conversion. </para> /// </returns> /// <java-name> /// getString /// </java-name> [Dot42.DexImport("getString", "([BLjava/lang/String;)Ljava/lang/String;", AccessFlags = 9)] public static string GetString(sbyte[] data, string charset) /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Converts the byte array of HTTP content characters to a string. If the specified charset is not supported, default system encoding is used.</para><para></para> /// </summary> /// <returns> /// <para>The result of the conversion. </para> /// </returns> /// <java-name> /// getString /// </java-name> [Dot42.DexImport("getString", "([BLjava/lang/String;)Ljava/lang/String;", AccessFlags = 9, IgnoreFromJava = true)] public static string GetString(byte[] data, string charset) /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Converts the specified string to a byte array. If the charset is not supported the default system charset is used.</para><para></para> /// </summary> /// <returns> /// <para>The resulting byte array. </para> /// </returns> /// <java-name> /// getBytes /// </java-name> [Dot42.DexImport("getBytes", "(Ljava/lang/String;Ljava/lang/String;)[B", AccessFlags = 9)] public static sbyte[] JavaGetBytes(string data, string charset) /* MethodBuilder.Create */ { return default(sbyte[]); } /// <summary> /// <para>Converts the specified string to a byte array. If the charset is not supported the default system charset is used.</para><para></para> /// </summary> /// <returns> /// <para>The resulting byte array. </para> /// </returns> /// <java-name> /// getBytes /// </java-name> [Dot42.DexImport("getBytes", "(Ljava/lang/String;Ljava/lang/String;)[B", AccessFlags = 9, IgnoreFromJava = true)] public static byte[] GetBytes(string data, string charset) /* MethodBuilder.Create */ { return default(byte[]); } /// <summary> /// <para>Converts the specified string to byte array of ASCII characters.</para><para></para> /// </summary> /// <returns> /// <para>The string as a byte array. </para> /// </returns> /// <java-name> /// getAsciiBytes /// </java-name> [Dot42.DexImport("getAsciiBytes", "(Ljava/lang/String;)[B", AccessFlags = 9)] public static sbyte[] JavaGetAsciiBytes(string data) /* MethodBuilder.Create */ { return default(sbyte[]); } /// <summary> /// <para>Converts the specified string to byte array of ASCII characters.</para><para></para> /// </summary> /// <returns> /// <para>The string as a byte array. </para> /// </returns> /// <java-name> /// getAsciiBytes /// </java-name> [Dot42.DexImport("getAsciiBytes", "(Ljava/lang/String;)[B", AccessFlags = 9, IgnoreFromJava = true)] public static byte[] GetAsciiBytes(string data) /* MethodBuilder.Create */ { return default(byte[]); } /// <summary> /// <para>Converts the byte array of ASCII characters to a string. This method is to be used when decoding content of HTTP elements (such as response headers)</para><para></para> /// </summary> /// <returns> /// <para>The string representation of the byte array </para> /// </returns> /// <java-name> /// getAsciiString /// </java-name> [Dot42.DexImport("getAsciiString", "([BII)Ljava/lang/String;", AccessFlags = 9)] public static string GetAsciiString(sbyte[] data, int offset, int length) /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Converts the byte array of ASCII characters to a string. This method is to be used when decoding content of HTTP elements (such as response headers)</para><para></para> /// </summary> /// <returns> /// <para>The string representation of the byte array </para> /// </returns> /// <java-name> /// getAsciiString /// </java-name> [Dot42.DexImport("getAsciiString", "([BII)Ljava/lang/String;", AccessFlags = 9, IgnoreFromJava = true)] public static string GetAsciiString(byte[] data, int offset, int length) /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Converts the byte array of ASCII characters to a string. This method is to be used when decoding content of HTTP elements (such as response headers)</para><para></para> /// </summary> /// <returns> /// <para>The string representation of the byte array </para> /// </returns> /// <java-name> /// getAsciiString /// </java-name> [Dot42.DexImport("getAsciiString", "([B)Ljava/lang/String;", AccessFlags = 9)] public static string GetAsciiString(sbyte[] data) /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Converts the byte array of ASCII characters to a string. This method is to be used when decoding content of HTTP elements (such as response headers)</para><para></para> /// </summary> /// <returns> /// <para>The string representation of the byte array </para> /// </returns> /// <java-name> /// getAsciiString /// </java-name> [Dot42.DexImport("getAsciiString", "([B)Ljava/lang/String;", AccessFlags = 9, IgnoreFromJava = true)] public static string GetAsciiString(byte[] data) /* MethodBuilder.Create */ { return default(string); } } /// <summary> /// <para>A resizable byte array.</para><para><para></para><para></para><title>Revision:</title><para>496070 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/util/ByteArrayBuffer /// </java-name> [Dot42.DexImport("org/apache/http/util/ByteArrayBuffer", AccessFlags = 49)] public sealed partial class ByteArrayBuffer /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(I)V", AccessFlags = 1)] public ByteArrayBuffer(int capacity) /* MethodBuilder.Create */ { } /// <java-name> /// append /// </java-name> [Dot42.DexImport("append", "([BII)V", AccessFlags = 1)] public void Append(sbyte[] b, int off, int len) /* MethodBuilder.Create */ { } /// <java-name> /// append /// </java-name> [Dot42.DexImport("append", "([BII)V", AccessFlags = 1, IgnoreFromJava = true)] public void Append(byte[] b, int off, int len) /* MethodBuilder.Create */ { } /// <java-name> /// append /// </java-name> [Dot42.DexImport("append", "(I)V", AccessFlags = 1)] public void Append(int b) /* MethodBuilder.Create */ { } /// <java-name> /// append /// </java-name> [Dot42.DexImport("append", "([CII)V", AccessFlags = 1)] public void Append(char[] b, int off, int len) /* MethodBuilder.Create */ { } /// <java-name> /// append /// </java-name> [Dot42.DexImport("append", "(Lorg/apache/http/util/CharArrayBuffer;II)V", AccessFlags = 1)] public void Append(global::Org.Apache.Http.Util.CharArrayBuffer b, int off, int len) /* MethodBuilder.Create */ { } /// <java-name> /// clear /// </java-name> [Dot42.DexImport("clear", "()V", AccessFlags = 1)] public void Clear() /* MethodBuilder.Create */ { } /// <java-name> /// toByteArray /// </java-name> [Dot42.DexImport("toByteArray", "()[B", AccessFlags = 1)] public sbyte[] JavaToByteArray() /* MethodBuilder.Create */ { return default(sbyte[]); } /// <java-name> /// toByteArray /// </java-name> [Dot42.DexImport("toByteArray", "()[B", AccessFlags = 1, IgnoreFromJava = true)] public byte[] ToByteArray() /* MethodBuilder.Create */ { return default(byte[]); } /// <java-name> /// byteAt /// </java-name> [Dot42.DexImport("byteAt", "(I)I", AccessFlags = 1)] public int ByteAt(int i) /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// capacity /// </java-name> [Dot42.DexImport("capacity", "()I", AccessFlags = 1)] public int Capacity() /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// length /// </java-name> [Dot42.DexImport("length", "()I", AccessFlags = 1)] public int Length() /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// buffer /// </java-name> [Dot42.DexImport("buffer", "()[B", AccessFlags = 1)] public sbyte[] JavaBuffer() /* MethodBuilder.Create */ { return default(sbyte[]); } /// <java-name> /// buffer /// </java-name> [Dot42.DexImport("buffer", "()[B", AccessFlags = 1, IgnoreFromJava = true)] public byte[] Buffer() /* MethodBuilder.Create */ { return default(byte[]); } /// <java-name> /// setLength /// </java-name> [Dot42.DexImport("setLength", "(I)V", AccessFlags = 1)] public void SetLength(int len) /* MethodBuilder.Create */ { } /// <java-name> /// isEmpty /// </java-name> [Dot42.DexImport("isEmpty", "()Z", AccessFlags = 1)] public bool IsEmpty() /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// isFull /// </java-name> [Dot42.DexImport("isFull", "()Z", AccessFlags = 1)] public bool IsFull() /* MethodBuilder.Create */ { return default(bool); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal ByteArrayBuffer() /* TypeBuilder.AddDefaultConstructor */ { } } /// <summary> /// <para>A set of utility methods to help produce consistent equals and hashCode methods.</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/util/LangUtils /// </java-name> [Dot42.DexImport("org/apache/http/util/LangUtils", AccessFlags = 49)] public sealed partial class LangUtils /* scope: __dot42__ */ { /// <java-name> /// HASH_SEED /// </java-name> [Dot42.DexImport("HASH_SEED", "I", AccessFlags = 25)] public const int HASH_SEED = 17; /// <java-name> /// HASH_OFFSET /// </java-name> [Dot42.DexImport("HASH_OFFSET", "I", AccessFlags = 25)] public const int HASH_OFFSET = 37; /// <summary> /// <para>Disabled default constructor. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 0)] internal LangUtils() /* MethodBuilder.Create */ { } /// <java-name> /// hashCode /// </java-name> [Dot42.DexImport("hashCode", "(II)I", AccessFlags = 9)] public static int GetHashCode(int int32, int int321) /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// hashCode /// </java-name> [Dot42.DexImport("hashCode", "(IZ)I", AccessFlags = 9)] public static int GetHashCode(int int32, bool boolean) /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// hashCode /// </java-name> [Dot42.DexImport("hashCode", "(ILjava/lang/Object;)I", AccessFlags = 9)] public static int GetHashCode(int int32, object @object) /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// equals /// </java-name> [Dot42.DexImport("equals", "(Ljava/lang/Object;Ljava/lang/Object;)Z", AccessFlags = 9)] public static bool Equals(object @object, object object1) /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// equals /// </java-name> [Dot42.DexImport("equals", "([Ljava/lang/Object;[Ljava/lang/Object;)Z", AccessFlags = 9)] public static bool Equals(object[] @object, object[] object1) /* MethodBuilder.Create */ { return default(bool); } } /// <summary> /// <para>Static helpers for dealing with entities.</para><para><para></para><para></para><title>Revision:</title><para>569637 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/util/EntityUtils /// </java-name> [Dot42.DexImport("org/apache/http/util/EntityUtils", AccessFlags = 49)] public sealed partial class EntityUtils /* scope: __dot42__ */ { /// <summary> /// <para>Disabled default constructor. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 0)] internal EntityUtils() /* MethodBuilder.Create */ { } /// <java-name> /// toByteArray /// </java-name> [Dot42.DexImport("toByteArray", "(Lorg/apache/http/HttpEntity;)[B", AccessFlags = 9)] public static sbyte[] JavaToByteArray(global::Org.Apache.Http.IHttpEntity entity) /* MethodBuilder.Create */ { return default(sbyte[]); } /// <java-name> /// toByteArray /// </java-name> [Dot42.DexImport("toByteArray", "(Lorg/apache/http/HttpEntity;)[B", AccessFlags = 9, IgnoreFromJava = true)] public static byte[] ToByteArray(global::Org.Apache.Http.IHttpEntity entity) /* MethodBuilder.Create */ { return default(byte[]); } /// <java-name> /// getContentCharSet /// </java-name> [Dot42.DexImport("getContentCharSet", "(Lorg/apache/http/HttpEntity;)Ljava/lang/String;", AccessFlags = 9)] public static string GetContentCharSet(global::Org.Apache.Http.IHttpEntity entity) /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// toString /// </java-name> [Dot42.DexImport("toString", "(Lorg/apache/http/HttpEntity;Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 9)] public static string ToString(global::Org.Apache.Http.IHttpEntity entity, string defaultCharset) /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// toString /// </java-name> [Dot42.DexImport("toString", "(Lorg/apache/http/HttpEntity;)Ljava/lang/String;", AccessFlags = 9)] public static string ToString(global::Org.Apache.Http.IHttpEntity entity) /* MethodBuilder.Create */ { return default(string); } } /// <summary> /// <para>The home for utility methods that handle various exception-related tasks.</para><para><para> </para><simplesectsep></simplesectsep><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/util/ExceptionUtils /// </java-name> [Dot42.DexImport("org/apache/http/util/ExceptionUtils", AccessFlags = 49)] public sealed partial class ExceptionUtils /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 0)] internal ExceptionUtils() /* MethodBuilder.Create */ { } /// <summary> /// <para>If we're running on JDK 1.4 or later, initialize the cause for the given throwable.</para><para></para> /// </summary> /// <java-name> /// initCause /// </java-name> [Dot42.DexImport("initCause", "(Ljava/lang/Throwable;Ljava/lang/Throwable;)V", AccessFlags = 9)] public static void InitCause(global::System.Exception throwable, global::System.Exception cause) /* MethodBuilder.Create */ { } } /// <summary> /// <para>A resizable char array.</para><para><para></para><para></para><title>Revision:</title><para>496070 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/util/CharArrayBuffer /// </java-name> [Dot42.DexImport("org/apache/http/util/CharArrayBuffer", AccessFlags = 49)] public sealed partial class CharArrayBuffer /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(I)V", AccessFlags = 1)] public CharArrayBuffer(int capacity) /* MethodBuilder.Create */ { } /// <java-name> /// append /// </java-name> [Dot42.DexImport("append", "([CII)V", AccessFlags = 1)] public void Append(char[] b, int off, int len) /* MethodBuilder.Create */ { } /// <java-name> /// append /// </java-name> [Dot42.DexImport("append", "(Ljava/lang/String;)V", AccessFlags = 1)] public void Append(string b) /* MethodBuilder.Create */ { } /// <java-name> /// append /// </java-name> [Dot42.DexImport("append", "(Lorg/apache/http/util/CharArrayBuffer;II)V", AccessFlags = 1)] public void Append(global::Org.Apache.Http.Util.CharArrayBuffer b, int off, int len) /* MethodBuilder.Create */ { } /// <java-name> /// append /// </java-name> [Dot42.DexImport("append", "(Lorg/apache/http/util/CharArrayBuffer;)V", AccessFlags = 1)] public void Append(global::Org.Apache.Http.Util.CharArrayBuffer b) /* MethodBuilder.Create */ { } /// <java-name> /// append /// </java-name> [Dot42.DexImport("append", "(C)V", AccessFlags = 1)] public void Append(char b) /* MethodBuilder.Create */ { } /// <java-name> /// append /// </java-name> [Dot42.DexImport("append", "([BII)V", AccessFlags = 1)] public void Append(sbyte[] b, int off, int len) /* MethodBuilder.Create */ { } /// <java-name> /// append /// </java-name> [Dot42.DexImport("append", "([BII)V", AccessFlags = 1, IgnoreFromJava = true)] public void Append(byte[] b, int off, int len) /* MethodBuilder.Create */ { } /// <java-name> /// append /// </java-name> [Dot42.DexImport("append", "(Lorg/apache/http/util/ByteArrayBuffer;II)V", AccessFlags = 1)] public void Append(global::Org.Apache.Http.Util.ByteArrayBuffer b, int off, int len) /* MethodBuilder.Create */ { } /// <java-name> /// append /// </java-name> [Dot42.DexImport("append", "(Ljava/lang/Object;)V", AccessFlags = 1)] public void Append(object b) /* MethodBuilder.Create */ { } /// <java-name> /// clear /// </java-name> [Dot42.DexImport("clear", "()V", AccessFlags = 1)] public void Clear() /* MethodBuilder.Create */ { } /// <java-name> /// toCharArray /// </java-name> [Dot42.DexImport("toCharArray", "()[C", AccessFlags = 1)] public char[] ToCharArray() /* MethodBuilder.Create */ { return default(char[]); } /// <java-name> /// charAt /// </java-name> [Dot42.DexImport("charAt", "(I)C", AccessFlags = 1)] public char CharAt(int i) /* MethodBuilder.Create */ { return default(char); } /// <java-name> /// buffer /// </java-name> [Dot42.DexImport("buffer", "()[C", AccessFlags = 1)] public char[] Buffer() /* MethodBuilder.Create */ { return default(char[]); } /// <java-name> /// capacity /// </java-name> [Dot42.DexImport("capacity", "()I", AccessFlags = 1)] public int Capacity() /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// length /// </java-name> [Dot42.DexImport("length", "()I", AccessFlags = 1)] public int Length() /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// ensureCapacity /// </java-name> [Dot42.DexImport("ensureCapacity", "(I)V", AccessFlags = 1)] public void EnsureCapacity(int required) /* MethodBuilder.Create */ { } /// <java-name> /// setLength /// </java-name> [Dot42.DexImport("setLength", "(I)V", AccessFlags = 1)] public void SetLength(int len) /* MethodBuilder.Create */ { } /// <java-name> /// isEmpty /// </java-name> [Dot42.DexImport("isEmpty", "()Z", AccessFlags = 1)] public bool IsEmpty() /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// isFull /// </java-name> [Dot42.DexImport("isFull", "()Z", AccessFlags = 1)] public bool IsFull() /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// indexOf /// </java-name> [Dot42.DexImport("indexOf", "(III)I", AccessFlags = 1)] public int IndexOf(int ch, int beginIndex, int endIndex) /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// indexOf /// </java-name> [Dot42.DexImport("indexOf", "(I)I", AccessFlags = 1)] public int IndexOf(int ch) /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// substring /// </java-name> [Dot42.DexImport("substring", "(II)Ljava/lang/String;", AccessFlags = 1)] public string Substring(int beginIndex, int endIndex) /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// substringTrimmed /// </java-name> [Dot42.DexImport("substringTrimmed", "(II)Ljava/lang/String;", AccessFlags = 1)] public string SubstringTrimmed(int beginIndex, int endIndex) /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// toString /// </java-name> [Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)] public override string ToString() /* MethodBuilder.Create */ { return default(string); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal CharArrayBuffer() /* TypeBuilder.AddDefaultConstructor */ { } } }
#pragma warning disable 0168 using System; using System.Collections.Generic; using System.Linq; using nHydrate.Dsl; namespace nHydrate.DslPackage { partial class nHydrateClipboardCommandSet { protected override void OnMenuCopy(object sender, EventArgs args) { base.OnMenuCopy(sender, args); } protected override void OnStatusPaste(object sender, EventArgs args) { base.OnStatusPaste(sender, args); } protected override void OnMenuPaste(object sender, global::System.EventArgs args) { nHydrateModel model = null; try { nHydrateDiagram diagram = null; nHydrate.Dsl.Entity selectedEntity = null; foreach (var item in this.CurrentSelection) { if (diagram == null && item is nHydrateDiagram) diagram = item as nHydrateDiagram; if (diagram == null && item is Microsoft.VisualStudio.Modeling.Diagrams.ShapeElement) { diagram = (item as Microsoft.VisualStudio.Modeling.Diagrams.ShapeElement).Diagram as nHydrateDiagram; if (item is EntityShape) selectedEntity = (item as EntityShape).ModelElement as nHydrate.Dsl.Entity; } } if (diagram != null) { model = diagram.ModelElement as nHydrateModel; model.IsLoading = true; } var beforeList = model.Entities.ToList(); base.OnMenuPaste(sender, args); var afterList = model.Entities.ToList().Except(beforeList).ToList(); #region Check indexes after Entity paste to make sure they are setup foreach (var item in afterList) { try { var settings = Extensions.FromXml<CopyStateSettings>(item.CopyStateInfo); using (var transaction = item.Store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString())) { //Now reset all indexes item.Indexes.Clear(); foreach (var indexDef in settings.Indexes) { var newIndex = item.Indexes.AddNew() as nHydrate.Dsl.Index; newIndex.Clustered = indexDef.Clustered; newIndex.IsUnique = indexDef.IsUnique; newIndex.Summary = indexDef.Summary; newIndex.IndexType = indexDef.IndexType; foreach (var columnDef in indexDef.Columns) { var newColumn = newIndex.IndexColumns.AddNew() as IndexColumn; newColumn.Ascending = columnDef.Acending; var fieldRef = item.FieldList.FirstOrDefault(x => x.Name == columnDef.Name); if (fieldRef != null) newColumn.FieldID = (fieldRef as Microsoft.VisualStudio.Modeling.ModelElement).Id; } } transaction.Commit(); } } catch (Exception ex) { } } #endregion #region We have pasted some fields so verify indexes //THIS DOES NOT WORK. NEED TO SAVE FIELDS BEFORE/AFTER AND COMPARE //if (afterList.Count == 0 && this.CurrentSelection.Count == 1 && selectedEntity != null) //{ // var item = selectedEntity; // using (var transaction = item.Store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString())) // { // foreach (Field field in item.FieldList) // { // if (field.IsIndexed) // { // if (!item.Indexes.Any(x => x.FieldList.Any(z => z.Id == field.Id) && x.IndexType == IndexTypeConstants.IsIndexed)) // { // var newIndex = item.Indexes.AddNew() as nHydrate.Dsl.Index; // newIndex.Clustered = false; // newIndex.IsUnique = false; // newIndex.IndexType = IndexTypeConstants.IsIndexed; // var newColumn = newIndex.IndexColumns.AddNew() as IndexColumn; // newColumn.Ascending = true; // newColumn.FieldID = field.Id; // } // } // } // transaction.Commit(); // } //} #endregion } catch (Exception ex) { throw; } finally { if (model != null) model.IsLoading = false; } } protected override void ProcessOnMenuPasteCommand() { base.ProcessOnMenuPasteCommand(); } protected override void ProcessOnMenuCopyCommand() { try { var diagram = (this.CurrentModelingDocView as Microsoft.VisualStudio.Modeling.Shell.SingleDiagramDocView).Diagram; foreach (EntityShape shape in this.CurrentDocumentSelection.ToList<object>().Where(x => x is EntityShape).ToList()) { using (var transaction = shape.Store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString())) { var entity = shape.ModelElement as Entity; var cache = new CopyStateSettings(); foreach (var item in entity.Indexes) { var indexCache = new CopyStateSettings.CopyStateIndex { Clustered = item.Clustered, IsUnique = item.IsUnique, Summary = item.Summary, IndexType = item.IndexType, }; cache.Indexes.Add(indexCache); foreach (var col in item.IndexColumns) { indexCache.Columns.Add(new CopyStateSettings.CopyStateIndexColumn { Acending = col.Ascending, Name = col.Field.Name, }); } } var xml = Extensions.ToXml(cache); entity.CopyStateInfo = xml; transaction.Commit(); } } base.ProcessOnMenuCopyCommand(); } catch (Exception ex) { throw; } } } [Serializable] public class CopyStateSettings { public CopyStateSettings() { this.Indexes = new List<CopyStateIndex>(); } public List<CopyStateIndex> Indexes { get; set; } [Serializable] public class CopyStateIndex { public CopyStateIndex() { this.Columns = new List<CopyStateIndexColumn>(); } public bool Clustered { get; set; } public bool IsUnique { get; set; } public string Summary { get; set; } public IndexTypeConstants IndexType { get; set; } public List<CopyStateIndexColumn> Columns { get; set; } } [Serializable] public class CopyStateIndexColumn { public bool Acending { get; set; } public string Name { get; set; } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Datastream { using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Apache.Ignite.Core.Datastream; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Common; /// <summary> /// Data streamer internal interface to get rid of generics. /// </summary> internal interface IDataStreamer { /// <summary> /// Callback invoked on topology size change. /// </summary> /// <param name="topVer">New topology version.</param> /// <param name="topSize">New topology size.</param> void TopologyChange(long topVer, int topSize); } /// <summary> /// Data streamer implementation. /// </summary> internal class DataStreamerImpl<TK, TV> : PlatformDisposableTargetAdapter, IDataStreamer, IDataStreamer<TK, TV> { #pragma warning disable 0420 /** Policy: continue. */ internal const int PlcContinue = 0; /** Policy: close. */ internal const int PlcClose = 1; /** Policy: cancel and close. */ internal const int PlcCancelClose = 2; /** Policy: flush. */ internal const int PlcFlush = 3; /** Operation: update. */ private const int OpUpdate = 1; /** Operation: set receiver. */ private const int OpReceiver = 2; /** */ private const int OpAllowOverwrite = 3; /** */ private const int OpSetAllowOverwrite = 4; /** */ private const int OpSkipStore = 5; /** */ private const int OpSetSkipStore = 6; /** */ private const int OpPerNodeBufferSize = 7; /** */ private const int OpSetPerNodeBufferSize = 8; /** */ private const int OpPerNodeParallelOps = 9; /** */ private const int OpSetPerNodeParallelOps = 10; /** */ private const int OpListenTopology = 11; /** */ private const int OpGetTimeout = 12; /** */ private const int OpSetTimeout = 13; /** */ private const int OpPerThreadBufferSize = 14; /** */ private const int OpSetPerThreadBufferSize = 15; /** Cache name. */ private readonly string _cacheName; /** Lock. */ private readonly ReaderWriterLockSlim _rwLock = new ReaderWriterLockSlim(); /** Closed event. */ private readonly ManualResetEventSlim _closedEvt = new ManualResetEventSlim(false); /** Close future. */ private readonly Future<object> _closeFut = new Future<object>(); /** GC handle to this streamer. */ private readonly long _hnd; /** Topology version. */ private long _topVer; /** Topology size. */ private int _topSize = 1; /** Buffer send size. */ private volatile int _bufSndSize; /** Current data streamer batch. */ private volatile DataStreamerBatch<TK, TV> _batch; /** Flusher. */ private readonly Flusher<TK, TV> _flusher; /** Receiver. */ private volatile IStreamReceiver<TK, TV> _rcv; /** Receiver handle. */ private long _rcvHnd; /** Receiver binary mode. */ private readonly bool _keepBinary; /// <summary> /// Constructor. /// </summary> /// <param name="target">Target.</param> /// <param name="marsh">Marshaller.</param> /// <param name="cacheName">Cache name.</param> /// <param name="keepBinary">Binary flag.</param> public DataStreamerImpl(IPlatformTargetInternal target, Marshaller marsh, string cacheName, bool keepBinary) : base(target) { _cacheName = cacheName; _keepBinary = keepBinary; // Create empty batch. _batch = new DataStreamerBatch<TK, TV>(); // Allocate GC handle so that this data streamer could be easily dereferenced from native code. WeakReference thisRef = new WeakReference(this); _hnd = marsh.Ignite.HandleRegistry.Allocate(thisRef); // Start topology listening. This call will ensure that buffer size member is updated. DoOutInOp(OpListenTopology, _hnd); // Membar to ensure fields initialization before leaving constructor. Thread.MemoryBarrier(); // Start flusher after everything else is initialized. _flusher = new Flusher<TK, TV>(thisRef); _flusher.RunThread(); } /** <inheritDoc /> */ public string CacheName { get { return _cacheName; } } /** <inheritDoc /> */ public bool AllowOverwrite { get { _rwLock.EnterReadLock(); try { ThrowIfDisposed(); return DoOutInOp(OpAllowOverwrite) == True; } finally { _rwLock.ExitReadLock(); } } set { _rwLock.EnterWriteLock(); try { ThrowIfDisposed(); DoOutInOp(OpSetAllowOverwrite, value ? True : False); } finally { _rwLock.ExitWriteLock(); } } } /** <inheritDoc /> */ public bool SkipStore { get { _rwLock.EnterReadLock(); try { ThrowIfDisposed(); return DoOutInOp(OpSkipStore) == True; } finally { _rwLock.ExitReadLock(); } } set { _rwLock.EnterWriteLock(); try { ThrowIfDisposed(); DoOutInOp(OpSetSkipStore, value ? True : False); } finally { _rwLock.ExitWriteLock(); } } } /** <inheritDoc /> */ public int PerNodeBufferSize { get { _rwLock.EnterReadLock(); try { ThrowIfDisposed(); return (int) DoOutInOp(OpPerNodeBufferSize); } finally { _rwLock.ExitReadLock(); } } set { _rwLock.EnterWriteLock(); try { ThrowIfDisposed(); DoOutInOp(OpSetPerNodeBufferSize, value); _bufSndSize = _topSize * value; } finally { _rwLock.ExitWriteLock(); } } } /** <inheritDoc /> */ public int PerThreadBufferSize { get { _rwLock.EnterReadLock(); try { ThrowIfDisposed(); return (int) DoOutInOp(OpPerThreadBufferSize); } finally { _rwLock.ExitReadLock(); } } set { _rwLock.EnterWriteLock(); try { ThrowIfDisposed(); DoOutInOp(OpSetPerThreadBufferSize, value); } finally { _rwLock.ExitWriteLock(); } } } /** <inheritDoc /> */ public int PerNodeParallelOperations { get { _rwLock.EnterReadLock(); try { ThrowIfDisposed(); return (int) DoOutInOp(OpPerNodeParallelOps); } finally { _rwLock.ExitReadLock(); } } set { _rwLock.EnterWriteLock(); try { ThrowIfDisposed(); DoOutInOp(OpSetPerNodeParallelOps, value); } finally { _rwLock.ExitWriteLock(); } } } /** <inheritDoc /> */ public long AutoFlushFrequency { get { _rwLock.EnterReadLock(); try { ThrowIfDisposed(); return _flusher.Frequency; } finally { _rwLock.ExitReadLock(); } } set { _rwLock.EnterWriteLock(); try { ThrowIfDisposed(); _flusher.Frequency = value; } finally { _rwLock.ExitWriteLock(); } } } /** <inheritDoc /> */ public Task Task { get { return _closeFut.Task; } } /** <inheritDoc /> */ public IStreamReceiver<TK, TV> Receiver { get { ThrowIfDisposed(); return _rcv; } set { IgniteArgumentCheck.NotNull(value, "value"); var handleRegistry = Marshaller.Ignite.HandleRegistry; _rwLock.EnterWriteLock(); try { ThrowIfDisposed(); if (_rcv == value) return; var rcvHolder = new StreamReceiverHolder(value, (rec, grid, cache, stream, keepBinary) => StreamReceiverHolder.InvokeReceiver((IStreamReceiver<TK, TV>) rec, grid, cache, stream, keepBinary)); var rcvHnd0 = handleRegistry.Allocate(rcvHolder); try { DoOutOp(OpReceiver, w => { w.WriteLong(rcvHnd0); w.WriteObject(rcvHolder); }); } catch (Exception) { handleRegistry.Release(rcvHnd0); throw; } if (_rcv != null) handleRegistry.Release(_rcvHnd); _rcv = value; _rcvHnd = rcvHnd0; } finally { _rwLock.ExitWriteLock(); } } } /** <inheritDoc /> */ public Task AddData(TK key, TV val) { ThrowIfDisposed(); IgniteArgumentCheck.NotNull(key, "key"); return Add0(new DataStreamerEntry<TK, TV>(key, val), 1); } /** <inheritDoc /> */ public Task AddData(KeyValuePair<TK, TV> pair) { ThrowIfDisposed(); return Add0(new DataStreamerEntry<TK, TV>(pair.Key, pair.Value), 1); } /** <inheritDoc /> */ public Task AddData(ICollection<KeyValuePair<TK, TV>> entries) { ThrowIfDisposed(); IgniteArgumentCheck.NotNull(entries, "entries"); return Add0(entries, entries.Count); } /** <inheritDoc /> */ public Task RemoveData(TK key) { ThrowIfDisposed(); IgniteArgumentCheck.NotNull(key, "key"); return Add0(new DataStreamerRemoveEntry<TK>(key), 1); } /** <inheritDoc /> */ public void TryFlush() { ThrowIfDisposed(); DataStreamerBatch<TK, TV> batch0 = _batch; if (batch0 != null) Flush0(batch0, false, PlcFlush); } /** <inheritDoc /> */ public void Flush() { ThrowIfDisposed(); DataStreamerBatch<TK, TV> batch0 = _batch; if (batch0 != null) Flush0(batch0, true, PlcFlush); else { // Batch is null, i.e. data streamer is closing. Wait for close to complete. _closedEvt.Wait(); } } /** <inheritDoc /> */ public void Close(bool cancel) { _flusher.Stop(); while (true) { DataStreamerBatch<TK, TV> batch0 = _batch; if (batch0 == null) { // Wait for concurrent close to finish. _closedEvt.Wait(); return; } if (Flush0(batch0, true, cancel ? PlcCancelClose : PlcClose)) { _closeFut.OnDone(null, null); _rwLock.EnterWriteLock(); try { base.Dispose(true); if (_rcv != null) Marshaller.Ignite.HandleRegistry.Release(_rcvHnd); _closedEvt.Set(); } finally { _rwLock.ExitWriteLock(); } Marshaller.Ignite.HandleRegistry.Release(_hnd); break; } } } /** <inheritDoc /> */ public IDataStreamer<TK1, TV1> WithKeepBinary<TK1, TV1>() { if (_keepBinary) { var result = this as IDataStreamer<TK1, TV1>; if (result == null) throw new InvalidOperationException( "Can't change type of binary streamer. WithKeepBinary has been called on an instance of " + "binary streamer with incompatible generic arguments."); return result; } return Marshaller.Ignite.GetDataStreamer<TK1, TV1>(_cacheName, true); } /** <inheritDoc /> */ public TimeSpan Timeout { get { _rwLock.EnterReadLock(); try { ThrowIfDisposed(); return BinaryUtils.LongToTimeSpan(DoOutInOp(OpGetTimeout)); } finally { _rwLock.ExitReadLock(); } } set { _rwLock.EnterWriteLock(); try { ThrowIfDisposed(); DoOutInOp(OpSetTimeout, (long) value.TotalMilliseconds); } finally { _rwLock.ExitWriteLock(); } } } /** <inheritDoc /> */ [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] protected override void Dispose(bool disposing) { if (disposing) Close(false); // Normal dispose: do not cancel else { // Finalizer: just close Java streamer try { if (_batch != null) _batch.Send(this, PlcCancelClose); } // ReSharper disable once EmptyGeneralCatchClause catch (Exception) { // Finalizers should never throw } Marshaller.Ignite.HandleRegistry.Release(_hnd, true); Marshaller.Ignite.HandleRegistry.Release(_rcvHnd, true); } base.Dispose(false); } /** <inheritDoc /> */ ~DataStreamerImpl() { Dispose(false); } /** <inheritDoc /> */ public void TopologyChange(long topVer, int topSize) { _rwLock.EnterWriteLock(); try { ThrowIfDisposed(); if (_topVer < topVer) { _topVer = topVer; _topSize = topSize > 0 ? topSize : 1; // Do not set to 0 to avoid 0 buffer size. _bufSndSize = (int) (_topSize * DoOutInOp(OpPerNodeBufferSize)); } } finally { _rwLock.ExitWriteLock(); } } /// <summary> /// Internal add/remove routine. /// </summary> /// <param name="val">Value.</param> /// <param name="cnt">Items count.</param> /// <returns>Future.</returns> private Task Add0(object val, int cnt) { int bufSndSize0 = _bufSndSize; Debug.Assert(bufSndSize0 > 0); while (true) { var batch0 = _batch; if (batch0 == null) throw new InvalidOperationException("Data streamer is stopped."); int size = batch0.Add(val, cnt); if (size == -1) { // Batch is blocked, perform CAS. Interlocked.CompareExchange(ref _batch, new DataStreamerBatch<TK, TV>(batch0), batch0); continue; } if (size >= bufSndSize0) // Batch is too big, schedule flush. Flush0(batch0, false, PlcContinue); return batch0.Task; } } /// <summary> /// Internal flush routine. /// </summary> /// <param name="curBatch"></param> /// <param name="wait">Whether to wait for flush to complete.</param> /// <param name="plc">Whether this is the last batch.</param> /// <returns>Whether this call was able to CAS previous batch</returns> private bool Flush0(DataStreamerBatch<TK, TV> curBatch, bool wait, int plc) { // 1. Try setting new current batch to help further adders. bool res = Interlocked.CompareExchange(ref _batch, (plc == PlcContinue || plc == PlcFlush) ? new DataStreamerBatch<TK, TV>(curBatch) : null, curBatch) == curBatch; // 2. Perform actual send. curBatch.Send(this, plc); if (wait) // 3. Wait for all futures to finish. curBatch.AwaitCompletion(); return res; } /// <summary> /// Start write. /// </summary> /// <returns>Writer.</returns> internal void Update(Action<BinaryWriter> action) { _rwLock.EnterReadLock(); try { ThrowIfDisposed(); DoOutOp(OpUpdate, action); } finally { _rwLock.ExitReadLock(); } } /// <summary> /// Flusher. /// </summary> private class Flusher<TK1, TV1> { /** State: running. */ private const int StateRunning = 0; /** State: stopping. */ private const int StateStopping = 1; /** State: stopped. */ private const int StateStopped = 2; /** Data streamer. */ [SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields", Justification = "Incorrect warning")] private readonly WeakReference _ldrRef; /** Finish flag. */ [SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields", Justification = "Incorrect warning")] private int _state; /** Flush frequency. */ [SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields", Justification = "Incorrect warning")] private long _freq; /// <summary> /// Constructor. /// </summary> /// <param name="ldrRef">Data streamer weak reference..</param> public Flusher(WeakReference ldrRef) { _ldrRef = ldrRef; lock (this) { _state = StateRunning; } } /// <summary> /// Main flusher routine. /// </summary> private void Run() { bool force = false; long curFreq = 0; try { while (true) { if (curFreq > 0 || force) { var ldr = _ldrRef.Target as DataStreamerImpl<TK1, TV1>; if (ldr == null) return; ldr.TryFlush(); force = false; } lock (this) { // Stop immediately. if (_state == StateStopping) return; if (curFreq == _freq) { // Frequency is unchanged if (curFreq == 0) // Just wait for a second and re-try. Monitor.Wait(this, 1000); else { // Calculate remaining time. DateTime now = DateTime.Now; long ticks; try { ticks = now.AddMilliseconds(curFreq).Ticks - now.Ticks; if (ticks > int.MaxValue) ticks = int.MaxValue; } catch (ArgumentOutOfRangeException) { // Handle possible overflow. ticks = int.MaxValue; } Monitor.Wait(this, TimeSpan.FromTicks(ticks)); } } else { if (curFreq != 0) force = true; curFreq = _freq; } } } } finally { // Let streamer know about stop. lock (this) { _state = StateStopped; Monitor.PulseAll(this); } } } /// <summary> /// Frequency. /// </summary> public long Frequency { get { return Interlocked.Read(ref _freq); } set { lock (this) { if (_freq != value) { _freq = value; Monitor.PulseAll(this); } } } } /// <summary> /// Stop flusher. /// </summary> public void Stop() { lock (this) { if (_state == StateRunning) { _state = StateStopping; Monitor.PulseAll(this); } while (_state != StateStopped) Monitor.Wait(this); } } /// <summary> /// Runs the flusher thread. /// </summary> public void RunThread() { TaskRunner.Run(Run); } } #pragma warning restore 0420 } }
#region LGPL License /* Axiom Game Engine Library Copyright (C) 2003 Axiom Project Team The overall design, and a majority of the core engine and rendering code contained within this library is a derivative of the open source Object Oriented Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net. Many thanks to the OGRE team for maintaining such a high quality project. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #endregion using System; using System.IO; using Axiom.Core; using Axiom.FileSystem; using Axiom.Scripting; namespace Axiom.Fonts { /// <summary> /// Manages Font resources, parsing .fontdef files and generally organizing them. /// </summary> public class FontManager : ResourceManager { #region Singleton implementation /// <summary> /// Singleton instance of this class. /// </summary> private static FontManager instance; /// <summary> /// Internal constructor. This class cannot be instantiated externally. /// </summary> internal FontManager() { if (instance == null) { instance = this; } } /// <summary> /// Gets the singleton instance of this class. /// </summary> public static FontManager Instance { get { return instance; } } #endregion Singleton implementation #region Methods /// <summary> /// Parses all .fontdef scripts available in all resource locations. /// </summary> public void ParseAllSources() { string extension = ".fontdef"; // search archives for(int i = 0; i < archives.Count; i++) { Archive archive = (Archive)archives[i]; string[] files = archive.GetFileNamesLike("", extension); for(int j = 0; j < files.Length; j++) { Stream data = archive.ReadFile(files[j]); // parse the materials ParseScript(data); } } // search common archives for(int i = 0; i < commonArchives.Count; i++) { Archive archive = (Archive)commonArchives[i]; string[] files = archive.GetFileNamesLike("", extension); for(int j = 0; j < files.Length; j++) { Stream data = archive.ReadFile(files[j]); // parse the materials ParseScript(data); } } } /// <summary> /// Parse a .fontdef script passed in as a chunk. /// </summary> /// <param name="script"></param> public void ParseScript(Stream stream) { StreamReader script = new StreamReader(stream, System.Text.Encoding.ASCII); Font font = null; string line = ""; // parse through the data to the end while((line = ParseHelper.ReadLine(script)) != null) { // ignore blank lines and comments if(line.Length == 0 || line.StartsWith("//")) { continue; } else { if(font == null) { // first valid data should be the font name font = (Font)Create(line); ParseHelper.SkipToNextOpenBrace(script); } else { // currently in a font if(line == "}") { // finished font = null; } else { ParseAttribute(line, font); } } } } } /// <summary> /// Parses an attribute of the font definitions. /// </summary> /// <param name="line"></param> /// <param name="font"></param> private void ParseAttribute(string line, Font font) { string[] parms = line.Split(new char[] {' ', '\t'}); string attrib = parms[0].ToLower(); switch(attrib) { case "type": if(parms.Length != 2) { ParseHelper.LogParserError(attrib, font.Name, "Invalid number of params for glyph "); return; } else { if(parms[0].ToLower() == "truetype") { font.Type = FontType.TrueType; } else { font.Type = FontType.Image; } } break; case "source": if(parms.Length != 2) { ParseHelper.LogParserError("source", font.Name, "Invalid number of params."); return; } // set the source of the font font.Source = parms[1]; break; case "glyph": if(parms.Length != 6) { ParseHelper.LogParserError("glyph", font.Name, "Invalid number of params."); return; } char glyph = parms[1][0]; // set the texcoords for this glyph font.SetGlyphTexCoords( glyph, StringConverter.ParseFloat(parms[2]), StringConverter.ParseFloat(parms[3]), StringConverter.ParseFloat(parms[4]), StringConverter.ParseFloat(parms[5])); break; case "size": if(parms.Length != 2) { ParseHelper.LogParserError("size", font.Name, "Invalid number of params."); return; } font.TrueTypeSize = int.Parse(parms[1]); break; case "resolution": if(parms.Length != 2) { ParseHelper.LogParserError("resolution", font.Name, "Invalid number of params."); return; } font.TrueTypeResolution = int.Parse(parms[1]); break; case "antialias_colour": if(parms.Length != 2) { ParseHelper.LogParserError("antialias_colour", font.Name, "Invalid number of params."); return; } font.AntialiasColor = bool.Parse(parms[1]); break; } } #endregion Methods #region Implementation of ResourceManager public override void Load(Resource resource, int priority) { base.Load (resource, priority); } public override Resource Create(string name, bool isManual) { // either return an existing font if already created, or create a new one if(GetByName(name) != null) { return GetByName(name); } else { // create a new font and add it to the list of resources Font font = new Font(name); Add(font); return font; } } public override void Dispose() { base.Dispose(); instance = null; } #endregion } }
using System; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; using Should; using Xunit; namespace AutoMapper.UnitTests { using Execution; public class DelegateFactoryTests { protected DelegateFactory DelegateFactory => new DelegateFactory(); [Fact] public void MethodTests() { MethodInfo method = typeof(String).GetMethod("StartsWith", new[] { typeof(string) }); LateBoundMethod callback = DelegateFactory.CreateGet(method); string foo = "this is a test"; bool result = (bool)callback(foo, new[] { "this" }); result.ShouldBeTrue(); } [Fact] public void PropertyTests() { PropertyInfo property = typeof(Source).GetProperty("Value", typeof(int)); LateBoundPropertyGet callback = DelegateFactory.CreateGet(property); var source = new Source {Value = 5}; int result = (int)callback(source); result.ShouldEqual(5); } [Fact] public void FieldTests() { FieldInfo field = typeof(Source).GetField("Value2"); LateBoundFieldGet callback = DelegateFactory.CreateGet(field); var source = new Source {Value2 = 15}; int result = (int)callback(source); result.ShouldEqual(15); } [Fact] public void Should_set_field_when_field_is_a_value_type() { var sourceType = typeof (Source); FieldInfo field = sourceType.GetField("Value2"); LateBoundFieldSet callback = DelegateFactory.CreateSet(field); var source = new Source(); callback(source, 5); source.Value2.ShouldEqual(5); } [Fact] public void Should_set_field_when_field_is_a_reference_type() { var sourceType = typeof (Source); FieldInfo field = sourceType.GetField("Value3"); LateBoundFieldSet callback = DelegateFactory.CreateSet(field); var source = new Source(); callback(source, "hello"); source.Value3.ShouldEqual("hello"); } [Fact] public void Should_set_property_when_property_is_a_value_type() { var sourceType = typeof (Source); PropertyInfo property = sourceType.GetProperty("Value"); LateBoundPropertySet callback = DelegateFactory.CreateSet(property); var source = new Source(); callback(source, 5); source.Value.ShouldEqual(5); } [Fact] public void Should_set_property_when_property_is_a_value_type_and_type_is_interface() { var sourceType = typeof (ISource); PropertyInfo property = sourceType.GetProperty("Value"); LateBoundPropertySet callback = DelegateFactory.CreateSet(property); var source = new Source(); callback(source, 5); source.Value.ShouldEqual(5); } [Fact] public void Should_set_property_when_property_is_a_reference_type() { var sourceType = typeof(Source); PropertyInfo property = sourceType.GetProperty("Value4"); LateBoundPropertySet callback = DelegateFactory.CreateSet(property); var source = new Source(); callback(source, "hello"); source.Value4.ShouldEqual("hello"); } internal delegate void DoIt3(ref ValueSource source, string value); private void SetValue(object thing, object value) { var source = ((ValueSource) thing); source.Value = (string)value; } [Fact] public void Test_with_create_ctor() { var sourceType = typeof(Source); LateBoundCtor ctor = DelegateFactory.CreateCtor(sourceType); var target = ctor(); target.ShouldBeType<Source>(); } [Fact] public void Test_with_value_object_create_ctor() { var sourceType = typeof(ValueSource); LateBoundCtor ctor = DelegateFactory.CreateCtor(sourceType); var target = ctor(); target.ShouldBeType<ValueSource>(); } [Fact] public void Create_ctor_should_throw_when_default_constructor_is_missing() { var type = typeof(NoDefaultConstructor); new Action(()=>DelegateFactory.CreateCtor(type)).ShouldThrow<ArgumentException>(ex=> { ex.Message.ShouldStartWith(type.FullName); }); } public object CreateValueSource() { return new ValueSource(); } public delegate void SetValueDelegate(ref ValueSource source, string value); private static void SetValue2(ref object thing, object value) { var source = ((ValueSource)thing); source.Value = (string)value; thing = source; } private void SetValue(ref ValueSource thing, string value) { thing.Value = value; } private void DoIt(object source, object value) { ((Source)source).Value2 = (int)value; } private void DoIt4(object source, object value) { var valueSource = ((ValueSource)source); valueSource.Value = (string)value; } private void DoIt2(object source, object value) { int toSet = value == null ? default(int) : (int) value; ((Source)source).Value = toSet; } private void DoIt4(ref object source, object value) { var valueSource = (ValueSource) source; valueSource.Value = (string) value; } private static class Test<T> { private static T DoIt() { return default(T); } } public class NoDefaultConstructor { public NoDefaultConstructor(int x) { } } public struct ValueSource { public string Value { get; set; } } public interface ISource { int Value { get; set; } } public class Source : ISource { public int Value { get; set; } public int Value2; public string Value3; public string Value4 { get; set; } } } }
using System; using System.Text; namespace Lucene.Net.Index { using Lucene.Net.Util; using System.IO; /* * 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 Analyzer = Lucene.Net.Analysis.Analyzer; using Codec = Lucene.Net.Codecs.Codec; using IndexingChain = Lucene.Net.Index.DocumentsWriterPerThread.IndexingChain; using IndexReaderWarmer = Lucene.Net.Index.IndexWriter.IndexReaderWarmer; using InfoStream = Lucene.Net.Util.InfoStream; using PrintStreamInfoStream = Lucene.Net.Util.PrintStreamInfoStream; using Similarity = Lucene.Net.Search.Similarities.Similarity; /// <summary> /// Holds all the configuration that is used to create an <seealso cref="IndexWriter"/>. /// Once <seealso cref="IndexWriter"/> has been created with this object, changes to this /// object will not affect the <seealso cref="IndexWriter"/> instance. For that, use /// <seealso cref="LiveIndexWriterConfig"/> that is returned from <seealso cref="IndexWriter#getConfig()"/>. /// /// <p> /// All setter methods return <seealso cref="IndexWriterConfig"/> to allow chaining /// settings conveniently, for example: /// /// <pre class="prettyprint"> /// IndexWriterConfig conf = new IndexWriterConfig(analyzer); /// conf.setter1().setter2(); /// </pre> /// </summary> /// <seealso cref= IndexWriter#getConfig() /// /// @since 3.1 </seealso> public sealed class IndexWriterConfig : LiveIndexWriterConfig, ICloneable { /// <summary> /// Specifies the open mode for <seealso cref="IndexWriter"/>. /// </summary> public enum OpenMode_e { /// <summary> /// Creates a new index or overwrites an existing one. /// </summary> CREATE, /// <summary> /// Opens an existing index. /// </summary> APPEND, /// <summary> /// Creates a new index if one does not exist, /// otherwise it opens the index and documents will be appended. /// </summary> CREATE_OR_APPEND } /// <summary> /// Default value is 32. Change using <seealso cref="#setTermIndexInterval(int)"/>. </summary> public const int DEFAULT_TERM_INDEX_INTERVAL = 32; // TODO: this should be private to the codec, not settable here /// <summary> /// Denotes a flush trigger is disabled. </summary> public const int DISABLE_AUTO_FLUSH = -1; /// <summary> /// Disabled by default (because IndexWriter flushes by RAM usage by default). </summary> public const int DEFAULT_MAX_BUFFERED_DELETE_TERMS = DISABLE_AUTO_FLUSH; /// <summary> /// Disabled by default (because IndexWriter flushes by RAM usage by default). </summary> public const int DEFAULT_MAX_BUFFERED_DOCS = DISABLE_AUTO_FLUSH; /// <summary> /// Default value is 16 MB (which means flush when buffered docs consume /// approximately 16 MB RAM). /// </summary> public const double DEFAULT_RAM_BUFFER_SIZE_MB = 16.0; /// <summary> /// Default value for the write lock timeout (1,000 ms). /// </summary> /// <seealso cref= #setDefaultWriteLockTimeout(long) </seealso> public static long WRITE_LOCK_TIMEOUT = 1000; /// <summary> /// Default setting for <seealso cref="#setReaderPooling"/>. </summary> public const bool DEFAULT_READER_POOLING = false; /// <summary> /// Default value is 1. Change using <seealso cref="#setReaderTermsIndexDivisor(int)"/>. </summary> public const int DEFAULT_READER_TERMS_INDEX_DIVISOR = DirectoryReader.DEFAULT_TERMS_INDEX_DIVISOR; /// <summary> /// Default value is 1945. Change using <seealso cref="#setRAMPerThreadHardLimitMB(int)"/> </summary> public const int DEFAULT_RAM_PER_THREAD_HARD_LIMIT_MB = 1945; /// <summary> /// The maximum number of simultaneous threads that may be /// indexing documents at once in IndexWriter; if more /// than this many threads arrive they will wait for /// others to finish. Default value is 8. /// </summary> public const int DEFAULT_MAX_THREAD_STATES = 8; /// <summary> /// Default value for compound file system for newly written segments /// (set to <code>true</code>). For batch indexing with very large /// ram buffers use <code>false</code> /// </summary> public const bool DEFAULT_USE_COMPOUND_FILE_SYSTEM = true; /// <summary> /// Default value for calling <seealso cref="AtomicReader#checkIntegrity()"/> before /// merging segments (set to <code>false</code>). You can set this /// to <code>true</code> for additional safety. /// </summary> public const bool DEFAULT_CHECK_INTEGRITY_AT_MERGE = false; /// <summary> /// Sets the default (for any instance) maximum time to wait for a write lock /// (in milliseconds). /// </summary> public static long DefaultWriteLockTimeout { set { WRITE_LOCK_TIMEOUT = value; } get { return WRITE_LOCK_TIMEOUT; } } // indicates whether this config instance is already attached to a writer. // not final so that it can be cloned properly. private SetOnce<IndexWriter> Writer = new SetOnce<IndexWriter>(); /// <summary> /// Sets the <seealso cref="IndexWriter"/> this config is attached to. /// </summary> /// <exception cref="AlreadySetException"> /// if this config is already attached to a writer. </exception> internal IndexWriterConfig SetIndexWriter(IndexWriter writer) { this.Writer.Set(writer); return this; } /// <summary> /// Creates a new config that with defaults that match the specified /// <seealso cref="LuceneVersion"/> as well as the default {@link /// Analyzer}. If matchVersion is >= {@link /// Version#LUCENE_32}, <seealso cref="TieredMergePolicy"/> is used /// for merging; else <seealso cref="LogByteSizeMergePolicy"/>. /// Note that <seealso cref="TieredMergePolicy"/> is free to select /// non-contiguous merges, which means docIDs may not /// remain monotonic over time. If this is a problem you /// should switch to <seealso cref="LogByteSizeMergePolicy"/> or /// <seealso cref="LogDocMergePolicy"/>. /// </summary> public IndexWriterConfig(LuceneVersion matchVersion, Analyzer analyzer) : base(analyzer, matchVersion) { } public object Clone() { try { IndexWriterConfig clone = (IndexWriterConfig)this.MemberwiseClone(); clone.Writer = (SetOnce<IndexWriter>)Writer.Clone(); // Mostly shallow clone, but do a deepish clone of // certain objects that have state that cannot be shared // across IW instances: clone.delPolicy = (IndexDeletionPolicy)delPolicy.Clone(); clone.flushPolicy = (FlushPolicy)flushPolicy.Clone(); clone.indexerThreadPool = (DocumentsWriterPerThreadPool)indexerThreadPool.Clone(); // we clone the infoStream because some impls might have state variables // such as line numbers, message throughput, ... clone.infoStream = (InfoStream)infoStream.Clone(); clone.mergePolicy = (MergePolicy)mergePolicy.Clone(); clone.mergeScheduler = (MergeScheduler)mergeScheduler.Clone(); return clone; } catch { // .NET port: no need to deal with checked exceptions here throw; } } /// <summary> /// Specifies <seealso cref="OpenMode"/> of the index. /// /// <p>Only takes effect when IndexWriter is first created. /// </summary> public IndexWriterConfig SetOpenMode(OpenMode_e? openMode) { if (openMode == null) { throw new System.ArgumentException("openMode must not be null"); } this.openMode = openMode; return this; } public override OpenMode_e? OpenMode { get { return openMode; } } /// <summary> /// Expert: allows an optional <seealso cref="IndexDeletionPolicy"/> implementation to be /// specified. You can use this to control when prior commits are deleted from /// the index. The default policy is <seealso cref="KeepOnlyLastCommitDeletionPolicy"/> /// which removes all prior commits as soon as a new commit is done (this /// matches behavior before 2.2). Creating your own policy can allow you to /// explicitly keep previous "point in time" commits alive in the index for /// some time, to allow readers to refresh to the new commit without having the /// old commit deleted out from under them. this is necessary on filesystems /// like NFS that do not support "delete on last close" semantics, which /// Lucene's "point in time" search normally relies on. /// <p> /// <b>NOTE:</b> the deletion policy cannot be null. /// /// <p>Only takes effect when IndexWriter is first created. /// </summary> public IndexWriterConfig SetIndexDeletionPolicy(IndexDeletionPolicy deletionPolicy) { if (deletionPolicy == null) { throw new System.ArgumentException("indexDeletionPolicy must not be null"); } this.delPolicy = deletionPolicy; return this; } public override IndexDeletionPolicy DelPolicy { get { return delPolicy; } } /// <summary> /// Expert: allows to open a certain commit point. The default is null which /// opens the latest commit point. /// /// <p>Only takes effect when IndexWriter is first created. /// </summary> public IndexWriterConfig SetIndexCommit(IndexCommit commit) { this.Commit = commit; return this; } public override IndexCommit IndexCommit { get { return Commit; } } /// <summary> /// Expert: set the <seealso cref="Similarity"/> implementation used by this IndexWriter. /// <p> /// <b>NOTE:</b> the similarity cannot be null. /// /// <p>Only takes effect when IndexWriter is first created. /// </summary> public IndexWriterConfig SetSimilarity(Similarity similarity) { if (similarity == null) { throw new System.ArgumentException("similarity must not be null"); } this.similarity = similarity; return this; } public override Similarity Similarity { get { return similarity; } } /// <summary> /// Expert: sets the merge scheduler used by this writer. The default is /// <seealso cref="ConcurrentMergeScheduler"/>. /// <p> /// <b>NOTE:</b> the merge scheduler cannot be null. /// /// <p>Only takes effect when IndexWriter is first created. /// </summary> public IndexWriterConfig SetMergeScheduler(MergeScheduler mergeScheduler) { if (mergeScheduler == null) { throw new System.ArgumentException("mergeScheduler must not be null"); } this.mergeScheduler = mergeScheduler; return this; } public override MergeScheduler MergeScheduler { get { return mergeScheduler; } } /// <summary> /// Sets the maximum time to wait for a write lock (in milliseconds) for this /// instance. You can change the default value for all instances by calling /// <seealso cref="#setDefaultWriteLockTimeout(long)"/>. /// /// <p>Only takes effect when IndexWriter is first created. /// </summary> public IndexWriterConfig SetWriteLockTimeout(long writeLockTimeout) { this.writeLockTimeout = writeLockTimeout; return this; } public override long WriteLockTimeout { get { return writeLockTimeout; } } /// <summary> /// Expert: <seealso cref="MergePolicy"/> is invoked whenever there are changes to the /// segments in the index. Its role is to select which merges to do, if any, /// and return a <seealso cref="MergePolicy.MergeSpecification"/> describing the merges. /// It also selects merges to do for forceMerge. /// /// <p>Only takes effect when IndexWriter is first created. /// </summary> public IndexWriterConfig SetMergePolicy(MergePolicy mergePolicy) { if (mergePolicy == null) { throw new System.ArgumentException("mergePolicy must not be null"); } this.mergePolicy = mergePolicy; return this; } /// <summary> /// Set the <seealso cref="Codec"/>. /// /// <p> /// Only takes effect when IndexWriter is first created. /// </summary> public IndexWriterConfig SetCodec(Codec codec) { if (codec == null) { throw new System.ArgumentException("codec must not be null"); } this.codec = codec; return this; } public override Codec Codec { get { return codec; } } public override MergePolicy MergePolicy { get { return mergePolicy; } } /// <summary> /// Expert: Sets the <seealso cref="DocumentsWriterPerThreadPool"/> instance used by the /// IndexWriter to assign thread-states to incoming indexing threads. If no /// <seealso cref="DocumentsWriterPerThreadPool"/> is set <seealso cref="IndexWriter"/> will use /// <seealso cref="ThreadAffinityDocumentsWriterThreadPool"/> with max number of /// thread-states set to <seealso cref="#DEFAULT_MAX_THREAD_STATES"/> (see /// <seealso cref="#DEFAULT_MAX_THREAD_STATES"/>). /// </p> /// <p> /// NOTE: The given <seealso cref="DocumentsWriterPerThreadPool"/> instance must not be used with /// other <seealso cref="IndexWriter"/> instances once it has been initialized / associated with an /// <seealso cref="IndexWriter"/>. /// </p> /// <p> /// NOTE: this only takes effect when IndexWriter is first created.</p> /// </summary> public IndexWriterConfig SetIndexerThreadPool(DocumentsWriterPerThreadPool threadPool) { if (threadPool == null) { throw new System.ArgumentException("threadPool must not be null"); } this.indexerThreadPool = threadPool; return this; } public override DocumentsWriterPerThreadPool IndexerThreadPool { get { return indexerThreadPool; } } /// <summary> /// Sets the max number of simultaneous threads that may be indexing documents /// at once in IndexWriter. Values &lt; 1 are invalid and if passed /// <code>maxThreadStates</code> will be set to /// <seealso cref="#DEFAULT_MAX_THREAD_STATES"/>. /// /// <p>Only takes effect when IndexWriter is first created. /// </summary> public IndexWriterConfig SetMaxThreadStates(int maxThreadStates) { this.indexerThreadPool = new ThreadAffinityDocumentsWriterThreadPool(maxThreadStates); return this; } public override int MaxThreadStates { get { try { return ((ThreadAffinityDocumentsWriterThreadPool)indexerThreadPool).MaxThreadStates; } catch (System.InvalidCastException cce) { throw new InvalidOperationException(cce.Message, cce); } } } /// <summary> /// By default, IndexWriter does not pool the /// SegmentReaders it must open for deletions and /// merging, unless a near-real-time reader has been /// obtained by calling <seealso cref="DirectoryReader#open(IndexWriter, boolean)"/>. /// this method lets you enable pooling without getting a /// near-real-time reader. NOTE: if you set this to /// false, IndexWriter will still pool readers once /// <seealso cref="DirectoryReader#open(IndexWriter, boolean)"/> is called. /// /// <p>Only takes effect when IndexWriter is first created. /// </summary> public IndexWriterConfig SetReaderPooling(bool readerPooling) { this.readerPooling = readerPooling; return this; } public override bool ReaderPooling { get { return readerPooling; } } /// <summary> /// Expert: sets the <seealso cref="DocConsumer"/> chain to be used to process documents. /// /// <p>Only takes effect when IndexWriter is first created. /// </summary> public IndexWriterConfig SetIndexingChain(IndexingChain indexingChain) { if (indexingChain == null) { throw new System.ArgumentException("indexingChain must not be null"); } this.indexingChain = indexingChain; return this; } public override IndexingChain IndexingChain { get { return indexingChain; } } /// <summary> /// Expert: Controls when segments are flushed to disk during indexing. /// The <seealso cref="FlushPolicy"/> initialized during <seealso cref="IndexWriter"/> instantiation and once initialized /// the given instance is bound to this <seealso cref="IndexWriter"/> and should not be used with another writer. </summary> /// <seealso cref= #setMaxBufferedDeleteTerms(int) </seealso> /// <seealso cref= #setMaxBufferedDocs(int) </seealso> /// <seealso cref= #setRAMBufferSizeMB(double) </seealso> public IndexWriterConfig SetFlushPolicy(FlushPolicy flushPolicy) { if (flushPolicy == null) { throw new System.ArgumentException("flushPolicy must not be null"); } this.flushPolicy = flushPolicy; return this; } /// <summary> /// Expert: Sets the maximum memory consumption per thread triggering a forced /// flush if exceeded. A <seealso cref="DocumentsWriterPerThread"/> is forcefully flushed /// once it exceeds this limit even if the <seealso cref="#getRAMBufferSizeMB()"/> has /// not been exceeded. this is a safety limit to prevent a /// <seealso cref="DocumentsWriterPerThread"/> from address space exhaustion due to its /// internal 32 bit signed integer based memory addressing. /// The given value must be less that 2GB (2048MB) /// </summary> /// <seealso cref= #DEFAULT_RAM_PER_THREAD_HARD_LIMIT_MB </seealso> public IndexWriterConfig SetRAMPerThreadHardLimitMB(int perThreadHardLimitMB) { if (perThreadHardLimitMB <= 0 || perThreadHardLimitMB >= 2048) { throw new System.ArgumentException("PerThreadHardLimit must be greater than 0 and less than 2048MB"); } this.PerThreadHardLimitMB = perThreadHardLimitMB; return this; } public override int RAMPerThreadHardLimitMB { get { return PerThreadHardLimitMB; } } public override FlushPolicy FlushPolicy { get { return flushPolicy; } } public override InfoStream InfoStream { get { return infoStream; } } public override Analyzer Analyzer { get { return base.Analyzer; } } public override int MaxBufferedDeleteTerms { get { return base.MaxBufferedDeleteTerms; } } public override int MaxBufferedDocs { get { return base.MaxBufferedDocs; } } public override IndexReaderWarmer MergedSegmentWarmer { get { return base.MergedSegmentWarmer; } } public override double RAMBufferSizeMB { get { return base.RAMBufferSizeMB; } } public override int ReaderTermsIndexDivisor { get { return base.ReaderTermsIndexDivisor; } } public override int TermIndexInterval { get { return base.TermIndexInterval; } } /// <summary> /// Information about merges, deletes and a /// message when maxFieldLength is reached will be printed /// to this. Must not be null, but <seealso cref="InfoStream#NO_OUTPUT"/> /// may be used to supress output. /// </summary> public IndexWriterConfig SetInfoStream(InfoStream infoStream) { if (infoStream == null) { throw new System.ArgumentException("Cannot set InfoStream implementation to null. " + "To disable logging use InfoStream.NO_OUTPUT"); } this.infoStream = infoStream; return this; } /// <summary> /// Convenience method that uses <seealso cref="PrintStreamInfoStream"/>. Must not be null. /// </summary> public IndexWriterConfig SetInfoStream(TextWriter printStream) { if (printStream == null) { throw new System.ArgumentException("printStream must not be null"); } return SetInfoStream(new PrintStreamInfoStream(printStream)); } public IndexWriterConfig SetMaxBufferedDeleteTerms(int maxBufferedDeleteTerms) { return (IndexWriterConfig)base.SetMaxBufferedDeleteTerms(maxBufferedDeleteTerms); } public IndexWriterConfig SetMaxBufferedDocs(int maxBufferedDocs) { return (IndexWriterConfig)base.SetMaxBufferedDocs(maxBufferedDocs); } public IndexWriterConfig SetMergedSegmentWarmer(IndexReaderWarmer mergeSegmentWarmer) { return (IndexWriterConfig)base.SetMergedSegmentWarmer(mergeSegmentWarmer); } public IndexWriterConfig SetRAMBufferSizeMB(double ramBufferSizeMB) { return (IndexWriterConfig)base.SetRAMBufferSizeMB(ramBufferSizeMB); } public IndexWriterConfig SetReaderTermsIndexDivisor(int divisor) { return (IndexWriterConfig)base.SetReaderTermsIndexDivisor(divisor); } public IndexWriterConfig SetTermIndexInterval(int interval) { return (IndexWriterConfig)base.SetTermIndexInterval(interval); } public IndexWriterConfig SetUseCompoundFile(bool useCompoundFile) { return (IndexWriterConfig)base.SetUseCompoundFile(useCompoundFile); } public IndexWriterConfig SetCheckIntegrityAtMerge(bool checkIntegrityAtMerge) { return (IndexWriterConfig)base.SetCheckIntegrityAtMerge(checkIntegrityAtMerge); } public override string ToString() { StringBuilder sb = new StringBuilder(base.ToString()); sb.Append("writer=").Append(Writer).Append("\n"); return sb.ToString(); } } }
using System; using System.Drawing; using System.Windows.Forms; using System.Drawing.Drawing2D; namespace WeifenLuo.WinFormsUI.Docking { internal class VS2012LightAutoHideStrip : AutoHideStripBase { private class TabVS2012Light : Tab { internal TabVS2012Light(IDockContent content) : base(content) { } private int m_tabX = 0; public int TabX { get { return m_tabX; } set { m_tabX = value; } } private int m_tabWidth = 0; public int TabWidth { get { return m_tabWidth; } set { m_tabWidth = value; } } public bool IsMouseOver { get; set; } } private const int _ImageHeight = 16; private const int _ImageWidth = 0; private const int _ImageGapTop = 2; private const int _ImageGapLeft = 4; private const int _ImageGapRight = 2; private const int _ImageGapBottom = 2; private const int _TextGapLeft = 0; private const int _TextGapRight = 0; private const int _TabGapTop = 3; private const int _TabGapBottom = 8; private const int _TabGapLeft = 4; private const int _TabGapBetween = 10; #region Customizable Properties public Font TextFont { get { return DockPanel.Skin.AutoHideStripSkin.TextFont; } } private static StringFormat _stringFormatTabHorizontal; private StringFormat StringFormatTabHorizontal { get { if (_stringFormatTabHorizontal == null) { _stringFormatTabHorizontal = new StringFormat(); _stringFormatTabHorizontal.Alignment = StringAlignment.Near; _stringFormatTabHorizontal.LineAlignment = StringAlignment.Center; _stringFormatTabHorizontal.FormatFlags = StringFormatFlags.NoWrap; _stringFormatTabHorizontal.Trimming = StringTrimming.None; } if (RightToLeft == RightToLeft.Yes) _stringFormatTabHorizontal.FormatFlags |= StringFormatFlags.DirectionRightToLeft; else _stringFormatTabHorizontal.FormatFlags &= ~StringFormatFlags.DirectionRightToLeft; return _stringFormatTabHorizontal; } } private static StringFormat _stringFormatTabVertical; private StringFormat StringFormatTabVertical { get { if (_stringFormatTabVertical == null) { _stringFormatTabVertical = new StringFormat(); _stringFormatTabVertical.Alignment = StringAlignment.Near; _stringFormatTabVertical.LineAlignment = StringAlignment.Center; _stringFormatTabVertical.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.DirectionVertical; _stringFormatTabVertical.Trimming = StringTrimming.None; } if (RightToLeft == RightToLeft.Yes) _stringFormatTabVertical.FormatFlags |= StringFormatFlags.DirectionRightToLeft; else _stringFormatTabVertical.FormatFlags &= ~StringFormatFlags.DirectionRightToLeft; return _stringFormatTabVertical; } } private static int ImageHeight { get { return _ImageHeight; } } private static int ImageWidth { get { return _ImageWidth; } } private static int ImageGapTop { get { return _ImageGapTop; } } private static int ImageGapLeft { get { return _ImageGapLeft; } } private static int ImageGapRight { get { return _ImageGapRight; } } private static int ImageGapBottom { get { return _ImageGapBottom; } } private static int TextGapLeft { get { return _TextGapLeft; } } private static int TextGapRight { get { return _TextGapRight; } } private static int TabGapTop { get { return _TabGapTop; } } private static int TabGapBottom { get { return _TabGapBottom; } } private static int TabGapLeft { get { return _TabGapLeft; } } private static int TabGapBetween { get { return _TabGapBetween; } } private static Pen PenTabBorder { get { return SystemPens.GrayText; } } #endregion private static Matrix _matrixIdentity = new Matrix(); private static Matrix MatrixIdentity { get { return _matrixIdentity; } } private static DockState[] _dockStates; private static DockState[] DockStates { get { if (_dockStates == null) { _dockStates = new DockState[4]; _dockStates[0] = DockState.DockLeftAutoHide; _dockStates[1] = DockState.DockRightAutoHide; _dockStates[2] = DockState.DockTopAutoHide; _dockStates[3] = DockState.DockBottomAutoHide; } return _dockStates; } } private static GraphicsPath _graphicsPath; internal static GraphicsPath GraphicsPath { get { if (_graphicsPath == null) _graphicsPath = new GraphicsPath(); return _graphicsPath; } } public VS2012LightAutoHideStrip(DockPanel panel) : base(panel) { SetStyle(ControlStyles.ResizeRedraw | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true); BackColor = SystemColors.ControlLight; } protected override void OnPaint(PaintEventArgs e) { Graphics g = e.Graphics; //SystemBrushes.Control var backgroundBrush = new SolidBrush(DockPanel.Skin.AutoHideStripSkin.DockStripBackground.StartColor); g.FillRectangle(backgroundBrush, ClientRectangle); DrawTabStrip(g); } protected override void OnLayout(LayoutEventArgs levent) { CalculateTabs(); base.OnLayout(levent); } private void DrawTabStrip(Graphics g) { DrawTabStrip(g, DockState.DockTopAutoHide); DrawTabStrip(g, DockState.DockBottomAutoHide); DrawTabStrip(g, DockState.DockLeftAutoHide); DrawTabStrip(g, DockState.DockRightAutoHide); } private void DrawTabStrip(Graphics g, DockState dockState) { Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); if (rectTabStrip.IsEmpty) return; Matrix matrixIdentity = g.Transform; if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide) { Matrix matrixRotated = new Matrix(); matrixRotated.RotateAt(90, new PointF((float)rectTabStrip.X + (float)rectTabStrip.Height / 2, (float)rectTabStrip.Y + (float)rectTabStrip.Height / 2)); g.Transform = matrixRotated; } foreach (Pane pane in GetPanes(dockState)) { foreach (TabVS2012Light tab in pane.AutoHideTabs) DrawTab(g, tab); } g.Transform = matrixIdentity; } private void CalculateTabs() { CalculateTabs(DockState.DockTopAutoHide); CalculateTabs(DockState.DockBottomAutoHide); CalculateTabs(DockState.DockLeftAutoHide); CalculateTabs(DockState.DockRightAutoHide); } private void CalculateTabs(DockState dockState) { Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); int imageHeight = rectTabStrip.Height - ImageGapTop - ImageGapBottom; int imageWidth = ImageWidth; if (imageHeight > ImageHeight) imageWidth = ImageWidth * (imageHeight / ImageHeight); int x = TabGapLeft + rectTabStrip.X; foreach (Pane pane in GetPanes(dockState)) { foreach (TabVS2012Light tab in pane.AutoHideTabs) { int width = imageWidth + ImageGapLeft + ImageGapRight + TextRenderer.MeasureText(tab.Content.DockHandler.TabText, TextFont).Width + TextGapLeft + TextGapRight; tab.TabX = x; tab.TabWidth = width; x += width; } x += TabGapBetween; } } private Rectangle RtlTransform(Rectangle rect, DockState dockState) { Rectangle rectTransformed; if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide) rectTransformed = rect; else rectTransformed = DrawHelper.RtlTransform(this, rect); return rectTransformed; } private GraphicsPath GetTabOutline(TabVS2012Light tab, bool transformed, bool rtlTransform) { DockState dockState = tab.Content.DockHandler.DockState; Rectangle rectTab = GetTabRectangle(tab, transformed); if (rtlTransform) rectTab = RtlTransform(rectTab, dockState); if (GraphicsPath != null) { GraphicsPath.Reset(); GraphicsPath.AddRectangle(rectTab); } return GraphicsPath; } private void DrawTab(Graphics g, TabVS2012Light tab) { Rectangle rectTabOrigin = GetTabRectangle(tab); if (rectTabOrigin.IsEmpty) return; DockState dockState = tab.Content.DockHandler.DockState; IDockContent content = tab.Content; Color textColor; if (tab.Content.DockHandler.IsActivated || tab.IsMouseOver) textColor = DockPanel.Skin.AutoHideStripSkin.DockStripGradient.StartColor; else textColor = DockPanel.Skin.AutoHideStripSkin.DockStripGradient.EndColor; Rectangle rectThickLine = rectTabOrigin; rectThickLine.X += _TabGapLeft + _TextGapLeft + _ImageGapLeft + _ImageWidth; rectThickLine.Width = TextRenderer.MeasureText(tab.Content.DockHandler.TabText, TextFont).Width - 8; rectThickLine.Height = Measures.AutoHideTabLineWidth; if (dockState == DockState.DockBottomAutoHide || dockState == DockState.DockLeftAutoHide) rectThickLine.Y += rectTabOrigin.Height - Measures.AutoHideTabLineWidth; else if (dockState == DockState.DockTopAutoHide || dockState == DockState.DockRightAutoHide) rectThickLine.Y += 0; g.FillRectangle(new SolidBrush(textColor), rectThickLine); //Set no rotate for drawing icon and text Matrix matrixRotate = g.Transform; g.Transform = MatrixIdentity; // Draw the icon Rectangle rectImage = rectTabOrigin; rectImage.X += ImageGapLeft; rectImage.Y += ImageGapTop; int imageHeight = rectTabOrigin.Height - ImageGapTop - ImageGapBottom; int imageWidth = ImageWidth; if (imageHeight > ImageHeight) imageWidth = ImageWidth * (imageHeight / ImageHeight); rectImage.Height = imageHeight; rectImage.Width = imageWidth; rectImage = GetTransformedRectangle(dockState, rectImage); if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide) { // The DockState is DockLeftAutoHide or DockRightAutoHide, so rotate the image 90 degrees to the right. Rectangle rectTransform = RtlTransform(rectImage, dockState); Point[] rotationPoints = { new Point(rectTransform.X + rectTransform.Width, rectTransform.Y), new Point(rectTransform.X + rectTransform.Width, rectTransform.Y + rectTransform.Height), new Point(rectTransform.X, rectTransform.Y) }; using (Icon rotatedIcon = new Icon(((Form)content).Icon, 16, 16)) { g.DrawImage(rotatedIcon.ToBitmap(), rotationPoints); } } else { // Draw the icon normally without any rotation. g.DrawIcon(((Form)content).Icon, RtlTransform(rectImage, dockState)); } // Draw the text Rectangle rectText = rectTabOrigin; rectText.X += ImageGapLeft + imageWidth + ImageGapRight + TextGapLeft; rectText.Width -= ImageGapLeft + imageWidth + ImageGapRight + TextGapLeft; rectText = RtlTransform(GetTransformedRectangle(dockState, rectText), dockState); if (DockPanel.ActiveContent == content || tab.IsMouseOver) textColor = DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.HoverTabGradient.TextColor; else textColor = DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.TextColor; if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide) g.DrawString(content.DockHandler.TabText, TextFont, new SolidBrush(textColor), rectText, StringFormatTabVertical); else g.DrawString(content.DockHandler.TabText, TextFont, new SolidBrush(textColor), rectText, StringFormatTabHorizontal); // Set rotate back g.Transform = matrixRotate; } private Rectangle GetLogicalTabStripRectangle(DockState dockState) { return GetLogicalTabStripRectangle(dockState, false); } private Rectangle GetLogicalTabStripRectangle(DockState dockState, bool transformed) { if (!DockHelper.IsDockStateAutoHide(dockState)) return Rectangle.Empty; int leftPanes = GetPanes(DockState.DockLeftAutoHide).Count; int rightPanes = GetPanes(DockState.DockRightAutoHide).Count; int topPanes = GetPanes(DockState.DockTopAutoHide).Count; int bottomPanes = GetPanes(DockState.DockBottomAutoHide).Count; int x, y, width, height; height = MeasureHeight(); if (dockState == DockState.DockLeftAutoHide && leftPanes > 0) { x = 0; y = (topPanes == 0) ? 0 : height; width = Height - (topPanes == 0 ? 0 : height) - (bottomPanes == 0 ? 0 : height); } else if (dockState == DockState.DockRightAutoHide && rightPanes > 0) { x = Width - height; if (leftPanes != 0 && x < height) x = height; y = (topPanes == 0) ? 0 : height; width = Height - (topPanes == 0 ? 0 : height) - (bottomPanes == 0 ? 0 : height); } else if (dockState == DockState.DockTopAutoHide && topPanes > 0) { x = leftPanes == 0 ? 0 : height; y = 0; width = Width - (leftPanes == 0 ? 0 : height) - (rightPanes == 0 ? 0 : height); } else if (dockState == DockState.DockBottomAutoHide && bottomPanes > 0) { x = leftPanes == 0 ? 0 : height; y = Height - height; if (topPanes != 0 && y < height) y = height; width = Width - (leftPanes == 0 ? 0 : height) - (rightPanes == 0 ? 0 : height); } else return Rectangle.Empty; if (width == 0 || height == 0) { return Rectangle.Empty; } var rect = new Rectangle(x, y, width, height); return transformed ? GetTransformedRectangle(dockState, rect) : rect; } private Rectangle GetTabRectangle(TabVS2012Light tab) { return GetTabRectangle(tab, false); } private Rectangle GetTabRectangle(TabVS2012Light tab, bool transformed) { DockState dockState = tab.Content.DockHandler.DockState; Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); if (rectTabStrip.IsEmpty) return Rectangle.Empty; int x = tab.TabX; int y = rectTabStrip.Y + (dockState == DockState.DockTopAutoHide || dockState == DockState.DockRightAutoHide ? 0 : TabGapTop); int width = tab.TabWidth; int height = rectTabStrip.Height - TabGapTop; if (!transformed) return new Rectangle(x, y, width, height); else return GetTransformedRectangle(dockState, new Rectangle(x, y, width, height)); } private Rectangle GetTransformedRectangle(DockState dockState, Rectangle rect) { if (dockState != DockState.DockLeftAutoHide && dockState != DockState.DockRightAutoHide) return rect; PointF[] pts = new PointF[1]; // the center of the rectangle pts[0].X = (float)rect.X + (float)rect.Width / 2; pts[0].Y = (float)rect.Y + (float)rect.Height / 2; Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); using (var matrix = new Matrix()) { matrix.RotateAt(90, new PointF((float)rectTabStrip.X + (float)rectTabStrip.Height / 2, (float)rectTabStrip.Y + (float)rectTabStrip.Height / 2)); matrix.TransformPoints(pts); } return new Rectangle((int)(pts[0].X - (float)rect.Height / 2 + .5F), (int)(pts[0].Y - (float)rect.Width / 2 + .5F), rect.Height, rect.Width); } protected override IDockContent HitTest(Point ptMouse) { Tab tab = TabHitTest(ptMouse); if (tab != null) return tab.Content; else return null; } protected Tab TabHitTest(Point ptMouse) { foreach (DockState state in DockStates) { Rectangle rectTabStrip = GetLogicalTabStripRectangle(state, true); if (!rectTabStrip.Contains(ptMouse)) continue; foreach (Pane pane in GetPanes(state)) { foreach (TabVS2012Light tab in pane.AutoHideTabs) { GraphicsPath path = GetTabOutline(tab, true, true); if (path.IsVisible(ptMouse)) return tab; } } } return null; } private TabVS2012Light lastSelectedTab = null; protected override void OnMouseHover(EventArgs e) { var tab = (TabVS2012Light)TabHitTest(PointToClient(MousePosition)); if (tab != null) { tab.IsMouseOver = true; Invalidate(); } if (lastSelectedTab != tab) { if (lastSelectedTab != null) lastSelectedTab.IsMouseOver = false; lastSelectedTab = tab; } base.OnMouseHover(e); } protected override void OnMouseLeave(EventArgs e) { base.OnMouseLeave(e); if (lastSelectedTab != null) lastSelectedTab.IsMouseOver = false; Invalidate(); } protected internal override int MeasureHeight() { return Math.Max(ImageGapBottom + ImageGapTop + ImageHeight, TextFont.Height) + TabGapTop + TabGapBottom; } protected override void OnRefreshChanges() { CalculateTabs(); Invalidate(); } protected override AutoHideStripBase.Tab CreateTab(IDockContent content) { return new TabVS2012Light(content); } } }
// 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 gaxgrpc = Google.Api.Gax.Grpc; using gciv = Google.Cloud.Iam.V1; using lro = Google.LongRunning; using proto = Google.Protobuf; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.ResourceManager.V3.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedTagValuesClientTest { [xunit::FactAttribute] public void GetTagValueRequestObject() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetTagValueRequest request = new GetTagValueRequest { TagValueName = TagValueName.FromTagValue("[TAG_VALUE]"), }; TagValue expectedResponse = new TagValue { TagValueName = TagValueName.FromTagValue("[TAG_VALUE]"), Parent = "parent7858e4d0", ShortName = "short_namec7ba9846", NamespacedName = "namespaced_namea4453147", Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Etag = "etage8ad7218", }; mockGrpcClient.Setup(x => x.GetTagValue(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); TagValue response = client.GetTagValue(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTagValueRequestObjectAsync() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetTagValueRequest request = new GetTagValueRequest { TagValueName = TagValueName.FromTagValue("[TAG_VALUE]"), }; TagValue expectedResponse = new TagValue { TagValueName = TagValueName.FromTagValue("[TAG_VALUE]"), Parent = "parent7858e4d0", ShortName = "short_namec7ba9846", NamespacedName = "namespaced_namea4453147", Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Etag = "etage8ad7218", }; mockGrpcClient.Setup(x => x.GetTagValueAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TagValue>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); TagValue responseCallSettings = await client.GetTagValueAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TagValue responseCancellationToken = await client.GetTagValueAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetTagValue() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetTagValueRequest request = new GetTagValueRequest { TagValueName = TagValueName.FromTagValue("[TAG_VALUE]"), }; TagValue expectedResponse = new TagValue { TagValueName = TagValueName.FromTagValue("[TAG_VALUE]"), Parent = "parent7858e4d0", ShortName = "short_namec7ba9846", NamespacedName = "namespaced_namea4453147", Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Etag = "etage8ad7218", }; mockGrpcClient.Setup(x => x.GetTagValue(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); TagValue response = client.GetTagValue(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTagValueAsync() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetTagValueRequest request = new GetTagValueRequest { TagValueName = TagValueName.FromTagValue("[TAG_VALUE]"), }; TagValue expectedResponse = new TagValue { TagValueName = TagValueName.FromTagValue("[TAG_VALUE]"), Parent = "parent7858e4d0", ShortName = "short_namec7ba9846", NamespacedName = "namespaced_namea4453147", Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Etag = "etage8ad7218", }; mockGrpcClient.Setup(x => x.GetTagValueAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TagValue>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); TagValue responseCallSettings = await client.GetTagValueAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TagValue responseCancellationToken = await client.GetTagValueAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetTagValueResourceNames() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetTagValueRequest request = new GetTagValueRequest { TagValueName = TagValueName.FromTagValue("[TAG_VALUE]"), }; TagValue expectedResponse = new TagValue { TagValueName = TagValueName.FromTagValue("[TAG_VALUE]"), Parent = "parent7858e4d0", ShortName = "short_namec7ba9846", NamespacedName = "namespaced_namea4453147", Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Etag = "etage8ad7218", }; mockGrpcClient.Setup(x => x.GetTagValue(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); TagValue response = client.GetTagValue(request.TagValueName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTagValueResourceNamesAsync() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetTagValueRequest request = new GetTagValueRequest { TagValueName = TagValueName.FromTagValue("[TAG_VALUE]"), }; TagValue expectedResponse = new TagValue { TagValueName = TagValueName.FromTagValue("[TAG_VALUE]"), Parent = "parent7858e4d0", ShortName = "short_namec7ba9846", NamespacedName = "namespaced_namea4453147", Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Etag = "etage8ad7218", }; mockGrpcClient.Setup(x => x.GetTagValueAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TagValue>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); TagValue responseCallSettings = await client.GetTagValueAsync(request.TagValueName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TagValue responseCancellationToken = await client.GetTagValueAsync(request.TagValueName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetIamPolicyRequestObject() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Options = new gciv::GetPolicyOptions(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); gciv::Policy response = client.GetIamPolicy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetIamPolicyRequestObjectAsync() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Options = new gciv::GetPolicyOptions(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); gciv::Policy responseCallSettings = await client.GetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::Policy responseCancellationToken = await client.GetIamPolicyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetIamPolicy() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); gciv::Policy response = client.GetIamPolicy(request.Resource); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetIamPolicyAsync() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); gciv::Policy responseCallSettings = await client.GetIamPolicyAsync(request.Resource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::Policy responseCancellationToken = await client.GetIamPolicyAsync(request.Resource, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetIamPolicyResourceNames() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); gciv::Policy response = client.GetIamPolicy(request.ResourceAsResourceName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetIamPolicyResourceNamesAsync() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); gciv::Policy responseCallSettings = await client.GetIamPolicyAsync(request.ResourceAsResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::Policy responseCancellationToken = await client.GetIamPolicyAsync(request.ResourceAsResourceName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SetIamPolicyRequestObject() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Policy = new gciv::Policy(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); gciv::Policy response = client.SetIamPolicy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetIamPolicyRequestObjectAsync() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Policy = new gciv::Policy(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); gciv::Policy responseCallSettings = await client.SetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::Policy responseCancellationToken = await client.SetIamPolicyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SetIamPolicy() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Policy = new gciv::Policy(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); gciv::Policy response = client.SetIamPolicy(request.Resource, request.Policy); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetIamPolicyAsync() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Policy = new gciv::Policy(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); gciv::Policy responseCallSettings = await client.SetIamPolicyAsync(request.Resource, request.Policy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::Policy responseCancellationToken = await client.SetIamPolicyAsync(request.Resource, request.Policy, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SetIamPolicyResourceNames() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Policy = new gciv::Policy(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); gciv::Policy response = client.SetIamPolicy(request.ResourceAsResourceName, request.Policy); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetIamPolicyResourceNamesAsync() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Policy = new gciv::Policy(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); gciv::Policy responseCallSettings = await client.SetIamPolicyAsync(request.ResourceAsResourceName, request.Policy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::Policy responseCancellationToken = await client.SetIamPolicyAsync(request.ResourceAsResourceName, request.Policy, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissionsRequestObject() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Permissions = { "permissions535a2741", }, }; gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); gciv::TestIamPermissionsResponse response = client.TestIamPermissions(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsRequestObjectAsync() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Permissions = { "permissions535a2741", }, }; gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::TestIamPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); gciv::TestIamPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::TestIamPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissions() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Permissions = { "permissions535a2741", }, }; gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); gciv::TestIamPermissionsResponse response = client.TestIamPermissions(request.Resource, request.Permissions); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsAsync() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Permissions = { "permissions535a2741", }, }; gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::TestIamPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); gciv::TestIamPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request.Resource, request.Permissions, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::TestIamPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request.Resource, request.Permissions, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissionsResourceNames() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Permissions = { "permissions535a2741", }, }; gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); gciv::TestIamPermissionsResponse response = client.TestIamPermissions(request.ResourceAsResourceName, request.Permissions); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsResourceNamesAsync() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Permissions = { "permissions535a2741", }, }; gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::TestIamPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); gciv::TestIamPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request.ResourceAsResourceName, request.Permissions, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::TestIamPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request.ResourceAsResourceName, request.Permissions, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
using System; using System.Collections.Specialized; using System.Diagnostics; using System.Linq; using System.Runtime.ExceptionServices; using System.Windows.Forms; using Bloom.Collection; using Newtonsoft.Json; namespace Bloom.Api { public delegate void EndpointHandler(ApiRequest request); public class EndpointRegistration { public bool HandleOnUIThread = true; public EndpointHandler Handler; } /// <summary> /// When the Bloom UI makes an API call, a method that has been registered to handle that /// endpoint is called and given one of these. That method uses this class to get information /// on the request, and also to reply to the caller. /// </summary> /// <remarks>The goal here is to reduce code while increasing clarity and error catching.</remarks> public class ApiRequest { private readonly IRequestInfo _requestInfo; public readonly CollectionSettings CurrentCollectionSettings; public readonly Book.Book CurrentBook; public NameValueCollection Parameters; public ApiRequest(IRequestInfo requestinfo, CollectionSettings currentCollectionSettings, Book.Book currentBook) { _requestInfo = requestinfo; CurrentCollectionSettings = currentCollectionSettings; CurrentBook = currentBook; Parameters = requestinfo.GetQueryParameters(); } /// <summary> /// Get the actual local path that the server would retrieve given a Bloom URL /// that ends up at a local file. For now it is mainly useful for things in the book folder; it doesn't have /// all the smarts to locate files shipped with the application, it is just concerned with reversing /// the various tricks we use to encode paths as URLs. /// </summary> public string LocalPath() { return ServerBase.GetLocalPathWithoutQuery(this._requestInfo); } public HttpMethods HttpMethod { get { return _requestInfo.HttpMethod; } } /// <summary> /// This is safe to use with axios.Post. See BL-4901. There, not returning any text at all /// caused some kind of problem in axios.post(), after the screen had been shut down. /// </summary> public void PostSucceeded() { _requestInfo.ContentType = "text/plain"; _requestInfo.WriteCompleteOutput("OK"); } //Used when an anchor has given us info, but we don't actually want the browser to navigate //For example, anchors that lead to help lead to an api handler that opens help but then //calls this so that the browser just stays where it was. public void ExternalLinkSucceeded() { _requestInfo.ExternalLinkSucceeded(); } public void ReplyWithText(string text) { //Debug.WriteLine(this.Requestinfo.LocalPathWithoutQuery + ": " + text); _requestInfo.ContentType = "text/plain"; _requestInfo.WriteCompleteOutput(text); } public void ReplyWithJson(string json) { //Debug.WriteLine(this.Requestinfo.LocalPathWithoutQuery + ": " + json); _requestInfo.ContentType = "application/json"; _requestInfo.WriteCompleteOutput(json); } public void ReplyWithJson(object objectToMakeJson) { //Debug.WriteLine(this.Requestinfo.LocalPathWithoutQuery + ": " + json); _requestInfo.ContentType = "application/json"; _requestInfo.WriteCompleteOutput(JsonConvert.SerializeObject(objectToMakeJson)); } public void ReplyWithImage(string imagePath) { _requestInfo.ReplyWithImage(imagePath); } public void Failed(string text) { //Debug.WriteLine(this.Requestinfo.LocalPathWithoutQuery+": "+text); _requestInfo.ContentType = "text/plain"; _requestInfo.WriteError(503, text); } public static bool Handle(EndpointRegistration endpointRegistration, IRequestInfo info, CollectionSettings collectionSettings, Book.Book currentBook) { var request = new ApiRequest(info, collectionSettings, currentBook); try { if (Program.RunningUnitTests) { endpointRegistration.Handler(request); } else { var formForSynchronizing = Application.OpenForms.Cast<Form>().Last(); if (endpointRegistration.HandleOnUIThread && formForSynchronizing.InvokeRequired) { InvokeWithErrorHandling(endpointRegistration, formForSynchronizing, request); } else { endpointRegistration.Handler(request); } } if (!info.HaveOutput) { throw new ApplicationException(string.Format("The EndpointHandler for {0} never called a Succeeded(), Failed(), or ReplyWith() Function.", info.RawUrl.ToString())); } } catch (System.IO.IOException e) { var shortMsg = String.Format(L10NSharp.LocalizationManager.GetDynamicString("Bloom", "Errors.CannotAccessFile", "Cannot access {0}"), info.RawUrl); var longMsg = String.Format("Bloom could not access {0}. The file may be open in another program.", info.RawUrl); NonFatalProblem.Report(ModalIf.None, PassiveIf.All, shortMsg, longMsg, e); return false; } catch (Exception e) { //Hard to reproduce, but I got one of these supertooltip disposal errors in a yellow box //while switching between publish tabs (e.g. /bloom/api/publish/android/cleanup). //I don't think these are worth alarming the user about, so let's be sensitive to what channel we're on. NonFatalProblem.Report(ModalIf.Alpha, PassiveIf.All, "Error in " + info.RawUrl, exception: e); return false; } return true; } // If you just Invoke(), the stack trace of any generated exception gets lost. // The stacktrace instead just ends with the invoke(), which isn't useful. So here we wrap // the call to the handler in a delegate that catches the exception and saves it // in our local scope, where we can then use it for error reporting. private static bool InvokeWithErrorHandling(EndpointRegistration endpointRegistration, Form formForSynchronizing, ApiRequest request) { Exception handlerException = null; formForSynchronizing.Invoke(new Action<ApiRequest>((req) => { try { endpointRegistration.Handler(req); } catch (Exception error) { handlerException = error; } }), request); if (handlerException != null) { ExceptionDispatchInfo.Capture(handlerException).Throw(); } return true; } public UrlPathString RequiredFileNameOrPath(string name) { if (Parameters.AllKeys.Contains(name)) return UrlPathString.CreateFromUnencodedString(Parameters[name]); throw new ApplicationException("The query " + _requestInfo.RawUrl + " should have parameter " + name); } public string RequiredParam(string name) { if (Parameters.AllKeys.Contains(name)) return Parameters[name]; throw new ApplicationException("The query " + _requestInfo.RawUrl + " should have parameter " + name); } public string RequiredPostJson() { Debug.Assert(_requestInfo.HttpMethod == HttpMethods.Post); var json = _requestInfo.GetPostJson(); if (!string.IsNullOrWhiteSpace(json)) { return json; } throw new ApplicationException("The query " + _requestInfo.RawUrl + " should have post json"); } public string RequiredPostString() { Debug.Assert(_requestInfo.HttpMethod == HttpMethods.Post); var s = _requestInfo.GetPostString(); if (!string.IsNullOrWhiteSpace(s)) { return s; } throw new ApplicationException("The query " + _requestInfo.RawUrl + " should have post string"); } public string RequiredPostValue(string key) { Debug.Assert(_requestInfo.HttpMethod == HttpMethods.Post); var values = _requestInfo.GetPostDataWhenFormEncoded().GetValues(key); if (values == null || values.Length != 1) throw new ApplicationException("The query " + _requestInfo.RawUrl + " should have 1 value for " + key); return values[0]; } public byte[] RawPostData => _requestInfo.GetRawPostData(); } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // 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.Diagnostics; using System.Text; using Gallio.Common; using Gallio.Common.Collections; using Gallio.Model; using Gallio.Common.Markup; using Gallio.Model.Schema; using Gallio.Runner.Events; using Gallio.Runner.Extensions; using Gallio.Runner.Reports.Schema; using Gallio.Runtime.Logging; using Gallio.Runner; namespace Gallio.TeamCityIntegration { /// <summary> /// Monitors <see cref="ITestRunner" /> events and writes debug messages to the /// runner's logger. /// </summary> public class TeamCityExtension : TestRunnerExtension { private delegate string Continuation(); private ServiceMessageWriter writer; private readonly string flowId; private readonly Stack<string> currentStepStack; private readonly MultiMap<string, Continuation> continuationMap; /// <summary> /// Creates a TeamCity logging extension. /// </summary> public TeamCityExtension() : this(null) { } internal TeamCityExtension(string flowId) { this.flowId = flowId ?? Hash64.CreateUniqueHash().ToString(); currentStepStack = new Stack<string>(); continuationMap = new MultiMap<string, Continuation>(); } /// <inheritdoc /> protected override void Initialize() { writer = new ServiceMessageWriter(output => Logger.Log(LogSeverity.Important, output)); Events.InitializeStarted += delegate(object sender, InitializeStartedEventArgs e) { writer.WriteProgressMessage(flowId, "Initializing test runner."); }; Events.ExploreStarted += delegate(object sender, ExploreStartedEventArgs e) { writer.WriteProgressStart(flowId, "Exploring tests."); }; Events.ExploreFinished += delegate(object sender, ExploreFinishedEventArgs e) { writer.WriteProgressFinish(flowId, "Exploring tests."); // nb: message must be same as specified in progress start }; Events.RunStarted += delegate(object sender, RunStartedEventArgs e) { writer.WriteProgressStart(flowId, "Running tests."); }; Events.RunFinished += delegate(object sender, RunFinishedEventArgs e) { ClearStep(); writer.WriteProgressFinish(flowId, "Running tests."); // nb: message must be same as specified in progress start }; Events.DisposeFinished += delegate(object sender, DisposeFinishedEventArgs e) { writer.WriteProgressMessage(flowId, "Disposed test runner."); }; Events.TestStepStarted += delegate(object sender, TestStepStartedEventArgs e) { TestStepData step = e.TestStepRun.Step; BeginStep(step, () => { string name = step.Name; if (step.FullName.Length != 0 && name.Length != 0) { if (step.IsTestCase) { writer.WriteTestStarted(flowId, name, false); } else if (step.IsPrimary) { writer.WriteTestSuiteStarted(flowId, name); } } }); }; Events.TestStepFinished += delegate(object sender, TestStepFinishedEventArgs e) { TestStepRun stepRun = e.TestStepRun; TestStepData step = e.TestStepRun.Step; EndStep(step, () => { string name = step.Name; if (step.FullName.Length != 0 && name.Length != 0) { if (step.IsTestCase) { TestOutcome outcome = stepRun.Result.Outcome; var outputText = new StringBuilder(); var errorText = new StringBuilder(); var warningText = new StringBuilder(); var failureText = new StringBuilder(); foreach (StructuredStream stream in stepRun.TestLog.Streams) { switch (stream.Name) { default: case MarkupStreamNames.ConsoleInput: case MarkupStreamNames.ConsoleOutput: case MarkupStreamNames.DebugTrace: case MarkupStreamNames.Default: AppendWithSeparator(outputText, stream.ToString()); break; case MarkupStreamNames.ConsoleError: AppendWithSeparator(errorText, stream.ToString()); break; case MarkupStreamNames.Failures: AppendWithSeparator(failureText, stream.ToString()); break; case MarkupStreamNames.Warnings: AppendWithSeparator(warningText, stream.ToString()); break; } } if (outcome.Status != TestStatus.Skipped && warningText.Length != 0) AppendWithSeparator(errorText, warningText.ToString()); if (outcome.Status != TestStatus.Failed && failureText.Length != 0) AppendWithSeparator(errorText, failureText.ToString()); if (outputText.Length != 0) writer.WriteTestStdOut(flowId, name, outputText.ToString()); if (errorText.Length != 0) writer.WriteTestStdErr(flowId, name, errorText.ToString()); // TODO: Handle inconclusive. if (outcome.Status == TestStatus.Failed) { writer.WriteTestFailed(flowId, name, outcome.ToString(), failureText.ToString()); } else if (outcome.Status == TestStatus.Skipped) { writer.WriteTestIgnored(flowId, name, warningText.ToString()); } writer.WriteTestFinished(flowId, name, stepRun.Result.Duration); } else if (step.IsPrimary) { writer.WriteTestSuiteFinished(flowId, name); } } }); }; } private void ClearStep() { currentStepStack.Clear(); continuationMap.Clear(); } private void BeginStep(TestStepData step, Action action) { string nextContinuationId = BeginStepContinuation(step, action); ResumeContinuation(nextContinuationId); } private void EndStep(TestStepData step, Action action) { string nextContinuationId = EndStepContinuation(step, action); ResumeContinuation(nextContinuationId); } private string BeginStepContinuation(TestStepData step, Action action) { if (currentStepStack.Count == 0 || step.ParentId == currentStepStack.Peek()) { currentStepStack.Push(step.Id); action(); return step.Id; } SaveContinuation(SanitizeContinuationId(step.ParentId), () => BeginStepContinuation(step, action)); return null; } private string EndStepContinuation(TestStepData step, Action action) { if (step.Id == currentStepStack.Peek()) { currentStepStack.Pop(); action(); return SanitizeContinuationId(step.ParentId); } SaveContinuation(step.Id, () => EndStepContinuation(step, action)); return null; } private static string SanitizeContinuationId(string id) { return id ?? "<null>"; } private void SaveContinuation(string continuationId, Continuation action) { continuationMap.Add(continuationId, action); } private void ResumeContinuation(string continuationId) { while (continuationId != null) { IList<Continuation> continuations = continuationMap[continuationId]; if (continuations.Count == 0) break; continuationMap.Remove(continuationId); string nextContinuationId = null; foreach (Continuation continuation in continuations) { if (nextContinuationId == null) { nextContinuationId = continuation(); } else { continuationMap.Add(continuationId, continuation); } } continuationId = nextContinuationId; } } private static void AppendWithSeparator(StringBuilder builder, string text) { if (text.Length != 0) { if (builder.Length != 0) builder.Append("\n\n"); builder.Append(text); while (builder.Length > 0 && char.IsWhiteSpace(builder[builder.Length - 1])) builder.Length -= 1; } } } }
// // https://github.com/ServiceStack/ServiceStack.Text // ServiceStack.Text: .NET C# POCO JSON, JSV and CSV Text Serializers. // // Authors: // Demis Bellot ([email protected]) // // Copyright 2012 Service Stack LLC. All Rights Reserved. // // Licensed under the same terms of ServiceStack. // using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Reflection; using ServiceStack.Text.Common; using ServiceStack.Text.Jsv; namespace ServiceStack.Text { /// <summary> /// Creates an instance of a Type from a string value /// </summary> public static class TypeSerializer { private static readonly UTF8Encoding UTF8EncodingWithoutBom = new UTF8Encoding(false); public const string DoubleQuoteString = "\"\""; /// <summary> /// Determines whether the specified type is convertible from string. /// </summary> /// <param name="type">The type.</param> /// <returns> /// <c>true</c> if the specified type is convertible from string; otherwise, <c>false</c>. /// </returns> public static bool CanCreateFromString(Type type) { return JsvReader.GetParseFn(type) != null; } /// <summary> /// Parses the specified value. /// </summary> /// <param name="value">The value.</param> /// <returns></returns> public static T DeserializeFromString<T>(string value) { if (string.IsNullOrEmpty(value)) return default(T); return (T)JsvReader<T>.Parse(value); } public static T DeserializeFromReader<T>(TextReader reader) { return DeserializeFromString<T>(reader.ReadToEnd()); } /// <summary> /// Parses the specified type. /// </summary> /// <param name="type">The type.</param> /// <param name="value">The value.</param> /// <returns></returns> public static object DeserializeFromString(string value, Type type) { return value == null ? null : JsvReader.GetParseFn(type)(value); } public static object DeserializeFromReader(TextReader reader, Type type) { return DeserializeFromString(reader.ReadToEnd(), type); } [ThreadStatic] //Reuse the thread static StringBuilder when serializing to strings private static StringBuilderWriter LastWriter; internal class StringBuilderWriter : IDisposable { protected StringBuilder sb; protected StringWriter writer; public StringWriter Writer { get { return writer; } } public StringBuilderWriter() { this.sb = new StringBuilder(); this.writer = new StringWriter(sb, CultureInfo.InvariantCulture); } public static StringBuilderWriter Create() { var ret = LastWriter; if (JsConfig.ReuseStringBuffer && ret != null) { LastWriter = null; ret.sb.Clear(); return ret; } return new StringBuilderWriter(); } public override string ToString() { return sb.ToString(); } public void Dispose() { if (JsConfig.ReuseStringBuffer) { LastWriter = this; } else { Writer.Dispose(); } } } public static string SerializeToString<T>(T value) { if (value == null || value is Delegate) return null; if (typeof(T) == typeof(object)) { return SerializeToString(value, value.GetType()); } if (typeof(T).IsAbstract() || typeof(T).IsInterface()) { JsState.IsWritingDynamic = true; var result = SerializeToString(value, value.GetType()); JsState.IsWritingDynamic = false; return result; } using (var sb = StringBuilderWriter.Create()) { JsvWriter<T>.WriteRootObject(sb.Writer, value); return sb.ToString(); } } public static string SerializeToString(object value, Type type) { if (value == null) return null; if (type == typeof(string)) return value as string; using (var sb = StringBuilderWriter.Create()) { JsvWriter.GetWriteFn(type)(sb.Writer, value); return sb.ToString(); } } public static void SerializeToWriter<T>(T value, TextWriter writer) { if (value == null) return; if (typeof(T) == typeof(string)) { writer.Write(value); } else if (typeof(T) == typeof(object)) { SerializeToWriter(value, value.GetType(), writer); } else if (typeof(T).IsAbstract() || typeof(T).IsInterface()) { JsState.IsWritingDynamic = false; SerializeToWriter(value, value.GetType(), writer); JsState.IsWritingDynamic = true; } else { JsvWriter<T>.WriteRootObject(writer, value); } } public static void SerializeToWriter(object value, Type type, TextWriter writer) { if (value == null) return; if (type == typeof(string)) { writer.Write(value); return; } JsvWriter.GetWriteFn(type)(writer, value); } public static void SerializeToStream<T>(T value, Stream stream) { if (value == null) return; if (typeof(T) == typeof(object)) { SerializeToStream(value, value.GetType(), stream); } else if (typeof(T).IsAbstract() || typeof(T).IsInterface()) { JsState.IsWritingDynamic = false; SerializeToStream(value, value.GetType(), stream); JsState.IsWritingDynamic = true; } else { var writer = new StreamWriter(stream, UTF8EncodingWithoutBom); JsvWriter<T>.WriteRootObject(writer, value); writer.Flush(); } } public static void SerializeToStream(object value, Type type, Stream stream) { var writer = new StreamWriter(stream, UTF8EncodingWithoutBom); JsvWriter.GetWriteFn(type)(writer, value); writer.Flush(); } public static T Clone<T>(T value) { var serializedValue = SerializeToString(value); var cloneObj = DeserializeFromString<T>(serializedValue); return cloneObj; } public static T DeserializeFromStream<T>(Stream stream) { using (var reader = new StreamReader(stream, UTF8EncodingWithoutBom)) { return DeserializeFromString<T>(reader.ReadToEnd()); } } public static object DeserializeFromStream(Type type, Stream stream) { using (var reader = new StreamReader(stream, UTF8EncodingWithoutBom)) { return DeserializeFromString(reader.ReadToEnd(), type); } } /// <summary> /// Useful extension method to get the Dictionary[string,string] representation of any POCO type. /// </summary> /// <returns></returns> public static Dictionary<string, string> ToStringDictionary<T>(this T obj) { var jsv = SerializeToString(obj); var map = DeserializeFromString<Dictionary<string, string>>(jsv); return map; } /// <summary> /// Recursively prints the contents of any POCO object in a human-friendly, readable format /// </summary> /// <returns></returns> public static string Dump<T>(this T instance) { return SerializeAndFormat(instance); } /// <summary> /// Print Dump to Console.WriteLine /// </summary> public static void PrintDump<T>(this T instance) { PclExport.Instance.WriteLine(SerializeAndFormat(instance)); } /// <summary> /// Print string.Format to Console.WriteLine /// </summary> public static void Print(this string text, params object[] args) { if (args.Length > 0) PclExport.Instance.WriteLine(text, args); else PclExport.Instance.WriteLine(text); } public static string SerializeAndFormat<T>(this T instance) { var fn = instance as Delegate; if (fn != null) return Dump(fn); var dtoStr = SerializeToString(instance); var formatStr = JsvFormatter.Format(dtoStr); return formatStr; } public static string Dump(this Delegate fn) { var method = fn.GetType().GetMethod("Invoke"); var sb = new StringBuilder(); foreach (var param in method.GetParameters()) { if (sb.Length > 0) sb.Append(", "); sb.AppendFormat("{0} {1}", param.ParameterType.Name, param.Name); } var methodName = fn.Method().Name; var info = "{0} {1}({2})".Fmt(method.ReturnType.Name, methodName, sb); return info; } } public class JsvStringSerializer : IStringSerializer { public To DeserializeFromString<To>(string serializedText) { return TypeSerializer.DeserializeFromString<To>(serializedText); } public object DeserializeFromString(string serializedText, Type type) { return TypeSerializer.DeserializeFromString(serializedText, type); } public string SerializeToString<TFrom>(TFrom @from) { return TypeSerializer.SerializeToString(@from); } } }
/* * 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; using System.Collections.Generic; using System.Reflection; using log4net; using Nini.Config; using Mono.Addins; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; // using OpenSim.Services.Interfaces; using Caps = OpenSim.Framework.Capabilities.Caps; namespace OpenSim.Region.ClientStack.Linden { /// <summary> /// SimulatorFeatures capability. /// </summary> /// <remarks> /// This is required for uploading Mesh. /// Since is accepts an open-ended response, we also send more information /// for viewers that care to interpret it. /// /// NOTE: Part of this code was adapted from the Aurora project, specifically /// the normal part of the response in the capability handler. /// </remarks> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "SimulatorFeaturesModule")] public class SimulatorFeaturesModule : INonSharedRegionModule, ISimulatorFeaturesModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public event SimulatorFeaturesRequestDelegate OnSimulatorFeaturesRequest; private Scene m_scene; /// <summary> /// Simulator features /// </summary> private OSDMap m_features = new OSDMap(); private string m_SearchURL = string.Empty; private string m_DestinationGuideURL = string.Empty; private bool m_ExportSupported = false; private string m_GridName = string.Empty; private string m_GridURL = string.Empty; #region ISharedRegionModule Members public void Initialise(IConfigSource source) { IConfig config = source.Configs["SimulatorFeatures"]; if (config != null) { // // All this is obsolete since getting these features from the grid service!! // Will be removed after the next release // m_SearchURL = config.GetString("SearchServerURI", m_SearchURL); m_DestinationGuideURL = config.GetString ("DestinationGuideURI", m_DestinationGuideURL); if (m_DestinationGuideURL == string.Empty) // Make this consistent with the variable in the LoginService config m_DestinationGuideURL = config.GetString("DestinationGuide", m_DestinationGuideURL); m_ExportSupported = config.GetBoolean("ExportSupported", m_ExportSupported); m_GridURL = Util.GetConfigVarFromSections<string>( source, "GatekeeperURI", new string[] { "Startup", "Hypergrid", "SimulatorFeatures" }, String.Empty); m_GridName = config.GetString("GridName", string.Empty); if (m_GridName == string.Empty) m_GridName = Util.GetConfigVarFromSections<string>( source, "gridname", new string[] { "GridInfo", "SimulatorFeatures" }, String.Empty); } AddDefaultFeatures(); } public void AddRegion(Scene s) { m_scene = s; m_scene.EventManager.OnRegisterCaps += RegisterCaps; m_scene.RegisterModuleInterface<ISimulatorFeaturesModule>(this); } public void RemoveRegion(Scene s) { m_scene.EventManager.OnRegisterCaps -= RegisterCaps; } public void RegionLoaded(Scene s) { GetGridExtraFeatures(s); } public void Close() { } public string Name { get { return "SimulatorFeaturesModule"; } } public Type ReplaceableInterface { get { return null; } } #endregion /// <summary> /// Add default features /// </summary> /// <remarks> /// TODO: These should be added from other modules rather than hardcoded. /// </remarks> private void AddDefaultFeatures() { lock (m_features) { m_features["MeshRezEnabled"] = true; m_features["MeshUploadEnabled"] = true; m_features["MeshXferEnabled"] = true; m_features["PhysicsMaterialsEnabled"] = true; OSDMap typesMap = new OSDMap(); typesMap["convex"] = true; typesMap["none"] = true; typesMap["prim"] = true; m_features["PhysicsShapeTypes"] = typesMap; // Extra information for viewers that want to use it // TODO: Take these out of here into their respective modules, like map-server-url OSDMap extrasMap; if(m_features.ContainsKey("OpenSimExtras")) { extrasMap = (OSDMap)m_features["OpenSimExtras"]; } else extrasMap = new OSDMap(); extrasMap["AvatarSkeleton"] = true; extrasMap["AnimationSet"] = true; // TODO: Take these out of here into their respective modules, like map-server-url if (m_SearchURL != string.Empty) extrasMap["search-server-url"] = m_SearchURL; if (!string.IsNullOrEmpty(m_DestinationGuideURL)) extrasMap["destination-guide-url"] = m_DestinationGuideURL; if (m_ExportSupported) extrasMap["ExportSupported"] = true; if (m_GridURL != string.Empty) extrasMap["GridURL"] = m_GridURL; if (m_GridName != string.Empty) extrasMap["GridName"] = m_GridName; if (extrasMap.Count > 0) m_features["OpenSimExtras"] = extrasMap; } } public void RegisterCaps(UUID agentID, Caps caps) { IRequestHandler reqHandler = new RestHTTPHandler( "GET", "/CAPS/" + UUID.Random(), x => { return HandleSimulatorFeaturesRequest(x, agentID); }, "SimulatorFeatures", agentID.ToString()); caps.RegisterHandler("SimulatorFeatures", reqHandler); } public void AddFeature(string name, OSD value) { lock (m_features) m_features[name] = value; } public bool RemoveFeature(string name) { lock (m_features) return m_features.Remove(name); } public bool TryGetFeature(string name, out OSD value) { lock (m_features) return m_features.TryGetValue(name, out value); } public OSDMap GetFeatures() { lock (m_features) return new OSDMap(m_features); } private OSDMap DeepCopy() { // This isn't the cheapest way of doing this but the rate // of occurrence is low (on sim entry only) and it's a sure // way to get a true deep copy. OSD copy = OSDParser.DeserializeLLSDXml(OSDParser.SerializeLLSDXmlString(m_features)); return (OSDMap)copy; } private Hashtable HandleSimulatorFeaturesRequest(Hashtable mDhttpMethod, UUID agentID) { // m_log.DebugFormat("[SIMULATOR FEATURES MODULE]: SimulatorFeatures request"); OSDMap copy = DeepCopy(); // Let's add the agentID to the destination guide, if it is expecting that. if (copy.ContainsKey("OpenSimExtras") && ((OSDMap)(copy["OpenSimExtras"])).ContainsKey("destination-guide-url")) ((OSDMap)copy["OpenSimExtras"])["destination-guide-url"] = Replace(((OSDMap)copy["OpenSimExtras"])["destination-guide-url"], "[USERID]", agentID.ToString()); SimulatorFeaturesRequestDelegate handlerOnSimulatorFeaturesRequest = OnSimulatorFeaturesRequest; if (handlerOnSimulatorFeaturesRequest != null) handlerOnSimulatorFeaturesRequest(agentID, ref copy); //Send back data Hashtable responsedata = new Hashtable(); responsedata["int_response_code"] = 200; responsedata["content_type"] = "text/plain"; responsedata["keepalive"] = false; responsedata["str_response_string"] = OSDParser.SerializeLLSDXmlString(copy); return responsedata; } /// <summary> /// Gets the grid extra features. /// </summary> /// <param name='featuresURI'> /// The URI Robust uses to handle the get_extra_features request /// </param> private void GetGridExtraFeatures(Scene scene) { Dictionary<string, object> extraFeatures = scene.GridService.GetExtraFeatures(); if (extraFeatures.ContainsKey("Result") && extraFeatures["Result"] != null && extraFeatures["Result"].ToString() == "Failure") { m_log.WarnFormat("[SIMULATOR FEATURES MODULE]: Unable to retrieve grid-wide features"); return; } lock (m_features) { OSDMap extrasMap = new OSDMap(); foreach(string key in extraFeatures.Keys) { extrasMap[key] = (string)extraFeatures[key]; if (key == "ExportSupported") { bool.TryParse(extraFeatures[key].ToString(), out m_ExportSupported); } } m_features["OpenSimExtras"] = extrasMap; } } private string Replace(string url, string substring, string replacement) { if (!String.IsNullOrEmpty(url) && url.Contains(substring)) return url.Replace(substring, replacement); return url; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; namespace Lucene.Net.Search { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using IBits = Lucene.Net.Util.IBits; using IndexReader = Lucene.Net.Index.IndexReader; using Term = Lucene.Net.Index.Term; using ToStringUtils = Lucene.Net.Util.ToStringUtils; /// <summary> /// A query that applies a filter to the results of another query. /// /// <para/>Note: the bits are retrieved from the filter each time this /// query is used in a search - use a <see cref="CachingWrapperFilter"/> to avoid /// regenerating the bits every time. /// <para/> /// @since 1.4 </summary> /// <seealso cref="CachingWrapperFilter"/> public class FilteredQuery : Query { private readonly Query query; private readonly Filter filter; private readonly FilterStrategy strategy; /// <summary> /// Constructs a new query which applies a filter to the results of the original query. /// <see cref="Filter.GetDocIdSet(AtomicReaderContext, IBits)"/> will be called every time this query is used in a search. </summary> /// <param name="query"> Query to be filtered, cannot be <c>null</c>. </param> /// <param name="filter"> Filter to apply to query results, cannot be <c>null</c>. </param> public FilteredQuery(Query query, Filter filter) : this(query, filter, RANDOM_ACCESS_FILTER_STRATEGY) { } /// <summary> /// Expert: Constructs a new query which applies a filter to the results of the original query. /// <see cref="Filter.GetDocIdSet(AtomicReaderContext, IBits)"/> will be called every time this query is used in a search. </summary> /// <param name="query"> Query to be filtered, cannot be <c>null</c>. </param> /// <param name="filter"> Filter to apply to query results, cannot be <c>null</c>. </param> /// <param name="strategy"> A filter strategy used to create a filtered scorer. /// </param> /// <seealso cref="FilterStrategy"/> public FilteredQuery(Query query, Filter filter, FilterStrategy strategy) { if (query == null || filter == null) { throw new System.ArgumentException("Query and filter cannot be null."); } if (strategy == null) { throw new System.ArgumentException("FilterStrategy can not be null"); } this.strategy = strategy; this.query = query; this.filter = filter; } /// <summary> /// Returns a <see cref="Weight"/> that applies the filter to the enclosed query's <see cref="Weight"/>. /// this is accomplished by overriding the <see cref="Scorer"/> returned by the <see cref="Weight"/>. /// </summary> public override Weight CreateWeight(IndexSearcher searcher) { Weight weight = query.CreateWeight(searcher); return new WeightAnonymousInnerClassHelper(this, weight); } private class WeightAnonymousInnerClassHelper : Weight { private readonly FilteredQuery outerInstance; private Lucene.Net.Search.Weight weight; public WeightAnonymousInnerClassHelper(FilteredQuery outerInstance, Lucene.Net.Search.Weight weight) { this.outerInstance = outerInstance; this.weight = weight; } public override bool ScoresDocsOutOfOrder { get { return true; } } public override float GetValueForNormalization() { return weight.GetValueForNormalization() * outerInstance.Boost * outerInstance.Boost; // boost sub-weight } public override void Normalize(float norm, float topLevelBoost) { weight.Normalize(norm, topLevelBoost * outerInstance.Boost); // incorporate boost } public override Explanation Explain(AtomicReaderContext ir, int i) { Explanation inner = weight.Explain(ir, i); Filter f = outerInstance.filter; DocIdSet docIdSet = f.GetDocIdSet(ir, ir.AtomicReader.LiveDocs); DocIdSetIterator docIdSetIterator = docIdSet == null ? DocIdSetIterator.GetEmpty() : docIdSet.GetIterator(); if (docIdSetIterator == null) { docIdSetIterator = DocIdSetIterator.GetEmpty(); } if (docIdSetIterator.Advance(i) == i) { return inner; } else { Explanation result = new Explanation(0.0f, "failure to match filter: " + f.ToString()); result.AddDetail(inner); return result; } } // return this query public override Query Query { get { return outerInstance; } } // return a filtering scorer public override Scorer GetScorer(AtomicReaderContext context, IBits acceptDocs) { Debug.Assert(outerInstance.filter != null); DocIdSet filterDocIdSet = outerInstance.filter.GetDocIdSet(context, acceptDocs); if (filterDocIdSet == null) { // this means the filter does not accept any documents. return null; } return outerInstance.strategy.FilteredScorer(context, weight, filterDocIdSet); } // return a filtering top scorer public override BulkScorer GetBulkScorer(AtomicReaderContext context, bool scoreDocsInOrder, IBits acceptDocs) { Debug.Assert(outerInstance.filter != null); DocIdSet filterDocIdSet = outerInstance.filter.GetDocIdSet(context, acceptDocs); if (filterDocIdSet == null) { // this means the filter does not accept any documents. return null; } return outerInstance.strategy.FilteredBulkScorer(context, weight, scoreDocsInOrder, filterDocIdSet); } } /// <summary> /// A scorer that consults the filter if a document was matched by the /// delegate scorer. This is useful if the filter computation is more expensive /// than document scoring or if the filter has a linear running time to compute /// the next matching doc like exact geo distances. /// </summary> private sealed class QueryFirstScorer : Scorer { private readonly Scorer scorer; private int scorerDoc = -1; private readonly IBits filterBits; internal QueryFirstScorer(Weight weight, IBits filterBits, Scorer other) : base(weight) { this.scorer = other; this.filterBits = filterBits; } public override int NextDoc() { int doc; for (; ; ) { doc = scorer.NextDoc(); if (doc == Scorer.NO_MORE_DOCS || filterBits.Get(doc)) { return scorerDoc = doc; } } } public override int Advance(int target) { int doc = scorer.Advance(target); if (doc != Scorer.NO_MORE_DOCS && !filterBits.Get(doc)) { return scorerDoc = NextDoc(); } else { return scorerDoc = doc; } } public override int DocID { get { return scorerDoc; } } public override float GetScore() { return scorer.GetScore(); } public override int Freq { get { return scorer.Freq; } } public override ICollection<ChildScorer> GetChildren() { return new[] { new ChildScorer(scorer, "FILTERED") }; } public override long GetCost() { return scorer.GetCost(); } } private class QueryFirstBulkScorer : BulkScorer { private readonly Scorer scorer; private readonly IBits filterBits; public QueryFirstBulkScorer(Scorer scorer, IBits filterBits) { this.scorer = scorer; this.filterBits = filterBits; } public override bool Score(ICollector collector, int maxDoc) { // the normalization trick already applies the boost of this query, // so we can use the wrapped scorer directly: collector.SetScorer(scorer); if (scorer.DocID == -1) { scorer.NextDoc(); } while (true) { int scorerDoc = scorer.DocID; if (scorerDoc < maxDoc) { if (filterBits.Get(scorerDoc)) { collector.Collect(scorerDoc); } scorer.NextDoc(); } else { break; } } return scorer.DocID != Scorer.NO_MORE_DOCS; } } /// <summary> /// A <see cref="Scorer"/> that uses a "leap-frog" approach (also called "zig-zag join"). The scorer and the filter /// take turns trying to advance to each other's next matching document, often /// jumping past the target document. When both land on the same document, it's /// collected. /// </summary> private class LeapFrogScorer : Scorer { private readonly DocIdSetIterator secondary; private readonly DocIdSetIterator primary; private readonly Scorer scorer; protected int m_primaryDoc = -1; protected int m_secondaryDoc = -1; protected internal LeapFrogScorer(Weight weight, DocIdSetIterator primary, DocIdSetIterator secondary, Scorer scorer) : base(weight) { this.primary = primary; this.secondary = secondary; this.scorer = scorer; } private int AdvanceToNextCommonDoc() { for (; ; ) { if (m_secondaryDoc < m_primaryDoc) { m_secondaryDoc = secondary.Advance(m_primaryDoc); } else if (m_secondaryDoc == m_primaryDoc) { return m_primaryDoc; } else { m_primaryDoc = primary.Advance(m_secondaryDoc); } } } public override sealed int NextDoc() { m_primaryDoc = PrimaryNext(); return AdvanceToNextCommonDoc(); } protected virtual int PrimaryNext() { return primary.NextDoc(); } public override sealed int Advance(int target) { if (target > m_primaryDoc) { m_primaryDoc = primary.Advance(target); } return AdvanceToNextCommonDoc(); } public override sealed int DocID { get { return m_secondaryDoc; } } public override sealed float GetScore() { return scorer.GetScore(); } public override sealed int Freq { get { return scorer.Freq; } } public override sealed ICollection<ChildScorer> GetChildren() { return new[] { new ChildScorer(scorer, "FILTERED") }; } public override long GetCost() { return Math.Min(primary.GetCost(), secondary.GetCost()); } } // TODO once we have way to figure out if we use RA or LeapFrog we can remove this scorer private sealed class PrimaryAdvancedLeapFrogScorer : LeapFrogScorer { private readonly int firstFilteredDoc; internal PrimaryAdvancedLeapFrogScorer(Weight weight, int firstFilteredDoc, DocIdSetIterator filterIter, Scorer other) : base(weight, filterIter, other, other) { this.firstFilteredDoc = firstFilteredDoc; this.m_primaryDoc = firstFilteredDoc; // initialize to prevent and advance call to move it further } protected override int PrimaryNext() { if (m_secondaryDoc != -1) { return base.PrimaryNext(); } else { return firstFilteredDoc; } } } /// <summary> /// Rewrites the query. If the wrapped is an instance of /// <see cref="MatchAllDocsQuery"/> it returns a <see cref="ConstantScoreQuery"/>. Otherwise /// it returns a new <see cref="FilteredQuery"/> wrapping the rewritten query. /// </summary> public override Query Rewrite(IndexReader reader) { Query queryRewritten = query.Rewrite(reader); if (queryRewritten != query) { // rewrite to a new FilteredQuery wrapping the rewritten query Query rewritten = new FilteredQuery(queryRewritten, filter, strategy); rewritten.Boost = this.Boost; return rewritten; } else { // nothing to rewrite, we are done! return this; } } /// <summary> /// Returns this <see cref="FilteredQuery"/>'s (unfiltered) <see cref="Query"/> </summary> public Query Query { get { return query; } } /// <summary> /// Returns this <see cref="FilteredQuery"/>'s filter </summary> public Filter Filter { get { return filter; } } /// <summary> /// Returns this <see cref="FilteredQuery"/>'s <seealso cref="FilterStrategy"/> </summary> public virtual FilterStrategy Strategy { get { return this.strategy; } } /// <summary> /// Expert: adds all terms occurring in this query to the terms set. Only /// works if this query is in its rewritten (<see cref="Rewrite(IndexReader)"/>) form. /// </summary> /// <exception cref="InvalidOperationException"> If this query is not yet rewritten </exception> public override void ExtractTerms(ISet<Term> terms) { Query.ExtractTerms(terms); } /// <summary> /// Prints a user-readable version of this query. </summary> public override string ToString(string s) { StringBuilder buffer = new StringBuilder(); buffer.Append("filtered("); buffer.Append(query.ToString(s)); buffer.Append(")->"); buffer.Append(filter); buffer.Append(ToStringUtils.Boost(Boost)); return buffer.ToString(); } /// <summary> /// Returns true if <paramref name="o"/> is equal to this. </summary> public override bool Equals(object o) { if (o == this) { return true; } if (!base.Equals(o)) { return false; } Debug.Assert(o is FilteredQuery); FilteredQuery fq = (FilteredQuery)o; return fq.query.Equals(this.query) && fq.filter.Equals(this.filter) && fq.strategy.Equals(this.strategy); } /// <summary> /// Returns a hash code value for this object. </summary> public override int GetHashCode() { int hash = base.GetHashCode(); hash = hash * 31 + strategy.GetHashCode(); hash = hash * 31 + query.GetHashCode(); hash = hash * 31 + filter.GetHashCode(); return hash; } /// <summary> /// A <see cref="FilterStrategy"/> that conditionally uses a random access filter if /// the given <see cref="DocIdSet"/> supports random access (returns a non-null value /// from <see cref="DocIdSet.Bits"/>) and /// <see cref="RandomAccessFilterStrategy.UseRandomAccess(IBits, int)"/> returns /// <c>true</c>. Otherwise this strategy falls back to a "zig-zag join" ( /// <see cref="FilteredQuery.LEAP_FROG_FILTER_FIRST_STRATEGY"/>) strategy. /// /// <para> /// Note: this strategy is the default strategy in <see cref="FilteredQuery"/> /// </para> /// </summary> public static readonly FilterStrategy RANDOM_ACCESS_FILTER_STRATEGY = new RandomAccessFilterStrategy(); /// <summary> /// A filter strategy that uses a "leap-frog" approach (also called "zig-zag join"). /// The scorer and the filter /// take turns trying to advance to each other's next matching document, often /// jumping past the target document. When both land on the same document, it's /// collected. /// <para> /// Note: this strategy uses the filter to lead the iteration. /// </para> /// </summary> public static readonly FilterStrategy LEAP_FROG_FILTER_FIRST_STRATEGY = new LeapFrogFilterStrategy(false); /// <summary> /// A filter strategy that uses a "leap-frog" approach (also called "zig-zag join"). /// The scorer and the filter /// take turns trying to advance to each other's next matching document, often /// jumping past the target document. When both land on the same document, it's /// collected. /// <para> /// Note: this strategy uses the query to lead the iteration. /// </para> /// </summary> public static readonly FilterStrategy LEAP_FROG_QUERY_FIRST_STRATEGY = new LeapFrogFilterStrategy(true); /// <summary> /// A filter strategy that advances the <see cref="Search.Query"/> or rather its <see cref="Scorer"/> first and consults the /// filter <see cref="DocIdSet"/> for each matched document. /// <para> /// Note: this strategy requires a <see cref="DocIdSet.Bits"/> to return a non-null value. Otherwise /// this strategy falls back to <see cref="FilteredQuery.LEAP_FROG_QUERY_FIRST_STRATEGY"/> /// </para> /// <para> /// Use this strategy if the filter computation is more expensive than document /// scoring or if the filter has a linear running time to compute the next /// matching doc like exact geo distances. /// </para> /// </summary> public static readonly FilterStrategy QUERY_FIRST_FILTER_STRATEGY = new QueryFirstFilterStrategy(); /// <summary> /// Abstract class that defines how the filter (<see cref="DocIdSet"/>) applied during document collection. </summary> public abstract class FilterStrategy { /// <summary> /// Returns a filtered <see cref="Scorer"/> based on this strategy. /// </summary> /// <param name="context"> /// the <see cref="AtomicReaderContext"/> for which to return the <see cref="Scorer"/>. </param> /// <param name="weight"> the <see cref="FilteredQuery"/> <see cref="Weight"/> to create the filtered scorer. </param> /// <param name="docIdSet"> the filter <see cref="DocIdSet"/> to apply </param> /// <returns> a filtered scorer /// </returns> /// <exception cref="System.IO.IOException"> if an <see cref="System.IO.IOException"/> occurs </exception> public abstract Scorer FilteredScorer(AtomicReaderContext context, Weight weight, DocIdSet docIdSet); /// <summary> /// Returns a filtered <see cref="BulkScorer"/> based on this /// strategy. this is an optional method: the default /// implementation just calls <see cref="FilteredScorer(AtomicReaderContext, Weight, DocIdSet)"/> and /// wraps that into a <see cref="BulkScorer"/>. /// </summary> /// <param name="context"> /// the <seealso cref="AtomicReaderContext"/> for which to return the <seealso cref="Scorer"/>. </param> /// <param name="weight"> the <seealso cref="FilteredQuery"/> <seealso cref="Weight"/> to create the filtered scorer. </param> /// <param name="scoreDocsInOrder"> <c>true</c> to score docs in order </param> /// <param name="docIdSet"> the filter <seealso cref="DocIdSet"/> to apply </param> /// <returns> a filtered top scorer </returns> public virtual BulkScorer FilteredBulkScorer(AtomicReaderContext context, Weight weight, bool scoreDocsInOrder, DocIdSet docIdSet) { Scorer scorer = FilteredScorer(context, weight, docIdSet); if (scorer == null) { return null; } // this impl always scores docs in order, so we can // ignore scoreDocsInOrder: return new Weight.DefaultBulkScorer(scorer); } } /// <summary> /// A <see cref="FilterStrategy"/> that conditionally uses a random access filter if /// the given <see cref="DocIdSet"/> supports random access (returns a non-null value /// from <see cref="DocIdSet.Bits"/>) and /// <see cref="RandomAccessFilterStrategy.UseRandomAccess(IBits, int)"/> returns /// <code>true</code>. Otherwise this strategy falls back to a "zig-zag join" ( /// <see cref="FilteredQuery.LEAP_FROG_FILTER_FIRST_STRATEGY"/>) strategy . /// </summary> public class RandomAccessFilterStrategy : FilterStrategy { public override Scorer FilteredScorer(AtomicReaderContext context, Weight weight, DocIdSet docIdSet) { DocIdSetIterator filterIter = docIdSet.GetIterator(); if (filterIter == null) { // this means the filter does not accept any documents. return null; } int firstFilterDoc = filterIter.NextDoc(); if (firstFilterDoc == DocIdSetIterator.NO_MORE_DOCS) { return null; } IBits filterAcceptDocs = docIdSet.Bits; // force if RA is requested bool useRandomAccess = filterAcceptDocs != null && UseRandomAccess(filterAcceptDocs, firstFilterDoc); if (useRandomAccess) { // if we are using random access, we return the inner scorer, just with other acceptDocs return weight.GetScorer(context, filterAcceptDocs); } else { Debug.Assert(firstFilterDoc > -1); // we are gonna advance() this scorer, so we set inorder=true/toplevel=false // we pass null as acceptDocs, as our filter has already respected acceptDocs, no need to do twice Scorer scorer = weight.GetScorer(context, null); // TODO once we have way to figure out if we use RA or LeapFrog we can remove this scorer return (scorer == null) ? null : new PrimaryAdvancedLeapFrogScorer(weight, firstFilterDoc, filterIter, scorer); } } /// <summary> /// Expert: decides if a filter should be executed as "random-access" or not. /// Random-access means the filter "filters" in a similar way as deleted docs are filtered /// in Lucene. This is faster when the filter accepts many documents. /// However, when the filter is very sparse, it can be faster to execute the query+filter /// as a conjunction in some cases. /// <para/> /// The default implementation returns <c>true</c> if the first document accepted by the /// filter is &lt; 100. /// <para/> /// @lucene.internal /// </summary> protected virtual bool UseRandomAccess(IBits bits, int firstFilterDoc) { //TODO once we have a cost API on filters and scorers we should rethink this heuristic return firstFilterDoc < 100; } } private sealed class LeapFrogFilterStrategy : FilterStrategy { private readonly bool scorerFirst; internal LeapFrogFilterStrategy(bool scorerFirst) { this.scorerFirst = scorerFirst; } public override Scorer FilteredScorer(AtomicReaderContext context, Weight weight, DocIdSet docIdSet) { DocIdSetIterator filterIter = docIdSet.GetIterator(); if (filterIter == null) { // this means the filter does not accept any documents. return null; } // we pass null as acceptDocs, as our filter has already respected acceptDocs, no need to do twice Scorer scorer = weight.GetScorer(context, null); if (scorer == null) { return null; } if (scorerFirst) { return new LeapFrogScorer(weight, scorer, filterIter, scorer); } else { return new LeapFrogScorer(weight, filterIter, scorer, scorer); } } } /// <summary> /// A filter strategy that advances the <see cref="Scorer"/> first and consults the /// <see cref="DocIdSet"/> for each matched document. /// <para> /// Note: this strategy requires a <see cref="DocIdSet.Bits"/> to return a non-null value. Otherwise /// this strategy falls back to <see cref="FilteredQuery.LEAP_FROG_QUERY_FIRST_STRATEGY"/> /// </para> /// <para> /// Use this strategy if the filter computation is more expensive than document /// scoring or if the filter has a linear running time to compute the next /// matching doc like exact geo distances. /// </para> /// </summary> private sealed class QueryFirstFilterStrategy : FilterStrategy { public override Scorer FilteredScorer(AtomicReaderContext context, Weight weight, DocIdSet docIdSet) { IBits filterAcceptDocs = docIdSet.Bits; if (filterAcceptDocs == null) { // Filter does not provide random-access Bits; we // must fallback to leapfrog: return LEAP_FROG_QUERY_FIRST_STRATEGY.FilteredScorer(context, weight, docIdSet); } Scorer scorer = weight.GetScorer(context, null); return scorer == null ? null : new QueryFirstScorer(weight, filterAcceptDocs, scorer); } public override BulkScorer FilteredBulkScorer(AtomicReaderContext context, Weight weight, bool scoreDocsInOrder, DocIdSet docIdSet) // ignored (we always top-score in order) { IBits filterAcceptDocs = docIdSet.Bits; if (filterAcceptDocs == null) { // Filter does not provide random-access Bits; we // must fallback to leapfrog: return LEAP_FROG_QUERY_FIRST_STRATEGY.FilteredBulkScorer(context, weight, scoreDocsInOrder, docIdSet); } Scorer scorer = weight.GetScorer(context, null); return scorer == null ? null : new QueryFirstBulkScorer(scorer, filterAcceptDocs); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Windows; using EnvDTE; using Microsoft.VisualStudio.ExtensionsExplorer; using NuGet.Dialog.PackageManagerUI; using NuGet.VisualStudio; namespace NuGet.Dialog.Providers { internal class UpdatesProvider : OnlineProvider { private readonly Project _project; private readonly IUpdateAllUIService _updateAllUIService; public UpdatesProvider( Project project, IPackageRepository localRepository, ResourceDictionary resources, IPackageRepositoryFactory packageRepositoryFactory, IPackageSourceProvider packageSourceProvider, IVsPackageManagerFactory packageManagerFactory, ProviderServices providerServices, IProgressProvider progressProvider, ISolutionManager solutionManager) : base( project, localRepository, resources, packageRepositoryFactory, packageSourceProvider, packageManagerFactory, providerServices, progressProvider, solutionManager) { _project = project; _updateAllUIService = providerServices.UpdateAllUIService; } public override string Name { get { return Resources.Dialog_UpdateProvider; } } public override float SortOrder { get { return 3.0f; } } public override bool RefreshOnNodeSelection { get { return true; } } public override bool SupportsExecuteAllCommand { get { return true; } } public override string OperationName { get { return RepositoryOperationNames.Update; } } protected override PackagesTreeNodeBase CreateTreeNodeForPackageSource(PackageSource source, IPackageRepository sourceRepository) { return new UpdatesTreeNode(this, source.Name, RootNode, LocalRepository, sourceRepository); } public override bool CanExecute(PackageItem item) { IPackage package = item.PackageIdentity; if (package == null) { return false; } // only enable command on a Package in the Update provider if it not updated yet. // the specified package can be updated if the local repository contains a package // with matching id and smaller version number. // Optimization due to bug #2008: if the LocalRepository is backed by a packages.config file, // check the packages information directly from the file, instead of going through // the IPackageRepository interface, which could potentially connect to TFS. var packageLookup = LocalRepository as ILatestPackageLookup; if (packageLookup != null) { SemanticVersion localPackageVersion; return packageLookup.TryFindLatestPackageById(item.Id, out localPackageVersion) && localPackageVersion < package.Version; } return LocalRepository.GetPackages().Any( p => p.Id.Equals(package.Id, StringComparison.OrdinalIgnoreCase) && p.Version < package.Version); } protected override void ExecuteCommand(IProjectManager projectManager, PackageItem item, IVsPackageManager activePackageManager, IList<PackageOperation> operations) { activePackageManager.UpdatePackages( projectManager, new [] { item.PackageIdentity }, operations, updateDependencies: true, allowPrereleaseVersions: IncludePrerelease, logger: this); } protected override bool ExecuteAllCore() { if (SelectedNode == null || SelectedNode.Extensions == null || SelectedNode.Extensions.Count == 0) { return false; } ShowProgressWindow(); IVsPackageManager activePackageManager = GetActivePackageManager(); Debug.Assert(activePackageManager != null); IDisposable action = activePackageManager.SourceRepository.StartOperation(OperationName, mainPackageId: null, mainPackageVersion: null); IProjectManager projectManager = activePackageManager.GetProjectManager(_project); List<PackageOperation> allOperations; bool accepted = ShowLicenseAgreementForAllPackages(activePackageManager, out allOperations); if (!accepted) { return false; } try { RegisterPackageOperationEvents(activePackageManager, projectManager); var allUpdatePackages = SelectedNode.GetPackages(String.Empty, IncludePrerelease); activePackageManager.UpdatePackages( projectManager, allUpdatePackages, allOperations, updateDependencies: true, allowPrereleaseVersions: IncludePrerelease, logger: this); return true; } finally { UnregisterPackageOperationEvents(activePackageManager, projectManager); action.Dispose(); } } protected bool ShowLicenseAgreementForAllPackages(IVsPackageManager activePackageManager, out List<PackageOperation> allOperations) { allOperations = new List<PackageOperation>(); var installWalker = new InstallWalker( LocalRepository, activePackageManager.SourceRepository, _project.GetTargetFrameworkName(), logger: this, ignoreDependencies: false, allowPrereleaseVersions: IncludePrerelease); var allPackages = SelectedNode.GetPackages(String.Empty, IncludePrerelease); foreach (var package in allPackages) { if (allOperations.FindIndex( operation => operation.Action == PackageAction.Install && operation.Package.Id == package.Id && operation.Package.Version == package.Version) == -1) { var operations = installWalker.ResolveOperations(package); allOperations.AddRange(operations); } } allOperations = (List<PackageOperation>)allOperations.Reduce(); return ShowLicenseAgreement(activePackageManager, allOperations); } protected override void OnExecuteCompleted(PackageItem item) { base.OnExecuteCompleted(item); // When this was the Update All command execution, // an individual Update command may have updated all remaining packages. // If there are no more updates left, we hide the Update All button. // // However, we only want to do so if there's only one page of result, because // we don't want to download all packages in all pages just to check for this condition. if (SelectedNode != null && SelectedNode.TotalNumberOfPackages > 1 && SelectedNode.TotalPages == 1) { if (SelectedNode.Extensions.OfType<PackageItem>().All(p => !p.IsEnabled)) { _updateAllUIService.Hide(); } } } public override void OnPackageLoadCompleted(PackagesTreeNodeBase selectedNode) { base.OnPackageLoadCompleted(selectedNode); UpdateNumberOfPackages(selectedNode); } private void UpdateNumberOfPackages(PackagesTreeNodeBase selectedNode) { if (selectedNode != null && !selectedNode.IsSearchResultsNode && selectedNode.TotalNumberOfPackages > 1) { // After performing Update All, if user switches to another page, we don't want to show // the Update All button again. Here we check to make sure there's at least one enabled package. if (selectedNode.Extensions.OfType<PackageItem>().Any(p => p.IsEnabled)) { _updateAllUIService.Show(); } else { _updateAllUIService.Hide(); } } else { _updateAllUIService.Hide(); } } public override IVsExtension CreateExtension(IPackage package) { var localPackage = LocalRepository.FindPackagesById(package.Id) .OrderByDescending(p => p.Version) .FirstOrDefault(); return new PackageItem(this, package, localPackage != null ? localPackage.Version : null) { CommandName = Resources.Dialog_UpdateButton, TargetFramework = _project.GetTargetFrameworkName() }; } public override string NoItemsMessage { get { return Resources.Dialog_UpdatesProviderNoItem; } } public override string ProgressWindowTitle { get { return Dialog.Resources.Dialog_UpdateProgress; } } protected override string GetProgressMessage(IPackage package) { if (package == null) { return Resources.Dialog_UpdateAllProgress; } return Resources.Dialog_UpdateProgress + package.ToString(); } } }
//----------------------------------------------------------------------- // // Microsoft Windows Client Platform // Copyright (C) Microsoft Corporation, 2002 // // File: TypefaceCollection.cs // // Contents: Collection of typefaces // // Created: 5-15-2003 Michael Leonov (mleonov) // //------------------------------------------------------------------------ using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Windows; using System.Windows.Media; using MS.Internal.FontCache; using System.Globalization; using System.Security; using SR = MS.Internal.PresentationCore.SR; using SRID = MS.Internal.PresentationCore.SRID; namespace MS.Internal.FontFace { internal unsafe struct TypefaceCollection : ICollection<Typeface> { private FontFamily _fontFamily; // setting _family and _familyTypefaceCollection are mutually exclusive. private Text.TextInterface.FontFamily _family; private FamilyTypefaceCollection _familyTypefaceCollection; public TypefaceCollection(FontFamily fontFamily, Text.TextInterface.FontFamily family) { _fontFamily = fontFamily; _family = family; _familyTypefaceCollection = null; } public TypefaceCollection(FontFamily fontFamily, FamilyTypefaceCollection familyTypefaceCollection) { _fontFamily = fontFamily; _familyTypefaceCollection = familyTypefaceCollection; _family = null; } #region ICollection<Typeface> Members public void Add(Typeface item) { throw new NotSupportedException(); } public void Clear() { throw new NotSupportedException(); } public bool Contains(Typeface item) { foreach (Typeface t in this) { if (t.Equals(item)) return true; } return false; } public void CopyTo(Typeface[] array, int arrayIndex) { if (array == null) { throw new ArgumentNullException("array"); } if (array.Rank != 1) { throw new ArgumentException(SR.Get(SRID.Collection_BadRank)); } // The extra "arrayIndex >= array.Length" check in because even if _collection.Count // is 0 the index is not allowed to be equal or greater than the length // (from the MSDN ICollection docs) if (arrayIndex < 0 || arrayIndex >= array.Length || (arrayIndex + Count) > array.Length) { throw new ArgumentOutOfRangeException("arrayIndex"); } foreach (Typeface t in this) { array[arrayIndex++] = t; } } /// <SecurityNote> /// Critical - calls into critical Text.TextInterface.FontFamily property /// TreatAsSafe - Count is safe to expose /// </SecurityNote> public int Count { [SecurityCritical, SecurityTreatAsSafe] get { Debug.Assert((_family != null && _familyTypefaceCollection == null)|| (_familyTypefaceCollection != null && _family == null)); if (_family != null) { return checked((int)_family.Count); } else { return _familyTypefaceCollection.Count; } } } public bool IsReadOnly { get { return true; } } public bool Remove(Typeface item) { throw new NotSupportedException(); } #endregion #region IEnumerable<Typeface> Members public IEnumerator<Typeface> GetEnumerator() { return new Enumerator(this); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new Enumerator(this); } #endregion private struct Enumerator : IEnumerator<Typeface> { public Enumerator(TypefaceCollection typefaceCollection) { _typefaceCollection = typefaceCollection; Debug.Assert((typefaceCollection._family != null && typefaceCollection._familyTypefaceCollection == null) || (typefaceCollection._familyTypefaceCollection != null && typefaceCollection._family == null)); if (typefaceCollection._family != null) { _familyEnumerator = ((IEnumerable<Text.TextInterface.Font>)typefaceCollection._family).GetEnumerator(); _familyTypefaceEnumerator = null; } else { _familyTypefaceEnumerator = ((IEnumerable<FamilyTypeface>)typefaceCollection._familyTypefaceCollection).GetEnumerator(); _familyEnumerator = null; } } #region IEnumerator<Typeface> Members /// <SecurityNote> /// Critical - calls into critical Text.TextInterface.Font properties /// TreatAsSafe - data used to initialize the new Typeface is safe to expose /// </SecurityNote> public Typeface Current { [SecurityCritical, SecurityTreatAsSafe] get { if (_typefaceCollection._family != null) { Text.TextInterface.Font face = _familyEnumerator.Current; return new Typeface(_typefaceCollection._fontFamily, new FontStyle((int)face.Style), new FontWeight((int)face.Weight), new FontStretch((int)face.Stretch)); } else { FamilyTypeface familyTypeface = _familyTypefaceEnumerator.Current; return new Typeface(_typefaceCollection._fontFamily, familyTypeface.Style, familyTypeface.Weight, familyTypeface.Stretch); } } } #endregion #region IDisposable Members public void Dispose() {} #endregion #region IEnumerator Members object System.Collections.IEnumerator.Current { get { return ((IEnumerator<Typeface>)this).Current; } } public bool MoveNext() { if (_familyEnumerator != null) { return _familyEnumerator.MoveNext(); } else { return _familyTypefaceEnumerator.MoveNext(); } } public void Reset() { if (_typefaceCollection._family != null) { _familyEnumerator = ((IEnumerable<Text.TextInterface.Font>)_typefaceCollection._family).GetEnumerator(); _familyTypefaceEnumerator = null; } else { _familyTypefaceEnumerator = ((IEnumerable<FamilyTypeface>)_typefaceCollection._familyTypefaceCollection).GetEnumerator(); _familyEnumerator = null; } } #endregion // setting _familyEnumerator and _familyTypefaceEnumerator are mutually exclusive. private IEnumerator<Text.TextInterface.Font> _familyEnumerator; private IEnumerator<FamilyTypeface> _familyTypefaceEnumerator; private TypefaceCollection _typefaceCollection; } } }
using System.Collections.Generic; using System.Linq; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Resources.Annotations; using JsonApiDotNetCore.Serialization.Building; using JsonApiDotNetCore.Serialization.Objects; using UnitTests.TestModels; using Xunit; namespace UnitTests.Serialization.Common { public sealed class ResourceObjectBuilderTests : SerializerTestsSetup { private readonly ResourceObjectBuilder _builder; public ResourceObjectBuilderTests() { _builder = new ResourceObjectBuilder(ResourceGraph, new JsonApiOptions()); } [Fact] public void ResourceToResourceObject_EmptyResource_CanBuild() { // Arrange var resource = new TestResource(); // Act ResourceObject resourceObject = _builder.Build(resource); // Assert Assert.Null(resourceObject.Attributes); Assert.Null(resourceObject.Relationships); Assert.Null(resourceObject.Id); Assert.Equal("testResource", resourceObject.Type); } [Fact] public void ResourceToResourceObject_ResourceWithId_CanBuild() { // Arrange var resource = new TestResource { Id = 1 }; // Act ResourceObject resourceObject = _builder.Build(resource); // Assert Assert.Equal("1", resourceObject.Id); Assert.Null(resourceObject.Attributes); Assert.Null(resourceObject.Relationships); Assert.Equal("testResource", resourceObject.Type); } [Theory] [InlineData(null, null)] [InlineData("string field", 1)] public void ResourceToResourceObject_ResourceWithIncludedAttrs_CanBuild(string stringFieldValue, int? intFieldValue) { // Arrange var resource = new TestResource { StringField = stringFieldValue, NullableIntField = intFieldValue }; IReadOnlyCollection<AttrAttribute> attrs = ResourceGraph.GetAttributes<TestResource>(tr => new { tr.StringField, tr.NullableIntField }); // Act ResourceObject resourceObject = _builder.Build(resource, attrs); // Assert Assert.NotNull(resourceObject.Attributes); Assert.Equal(2, resourceObject.Attributes.Keys.Count); Assert.Equal(stringFieldValue, resourceObject.Attributes["stringField"]); Assert.Equal(intFieldValue, resourceObject.Attributes["nullableIntField"]); } [Fact] public void ResourceWithRelationshipsToResourceObject_EmptyResource_CanBuild() { // Arrange var resource = new MultipleRelationshipsPrincipalPart(); // Act ResourceObject resourceObject = _builder.Build(resource); // Assert Assert.Null(resourceObject.Attributes); Assert.Null(resourceObject.Relationships); Assert.Null(resourceObject.Id); Assert.Equal("multiPrincipals", resourceObject.Type); } [Fact] public void ResourceWithRelationshipsToResourceObject_ResourceWithId_CanBuild() { // Arrange var resource = new MultipleRelationshipsPrincipalPart { PopulatedToOne = new OneToOneDependent { Id = 10 } }; // Act ResourceObject resourceObject = _builder.Build(resource); // Assert Assert.Null(resourceObject.Attributes); Assert.Null(resourceObject.Relationships); Assert.Null(resourceObject.Id); Assert.Equal("multiPrincipals", resourceObject.Type); } [Fact] public void ResourceWithRelationshipsToResourceObject_WithIncludedRelationshipsAttributes_CanBuild() { // Arrange var resource = new MultipleRelationshipsPrincipalPart { PopulatedToOne = new OneToOneDependent { Id = 10 }, PopulatedToManies = new HashSet<OneToManyDependent> { new() { Id = 20 } } }; IReadOnlyCollection<RelationshipAttribute> relationships = ResourceGraph.GetRelationships<MultipleRelationshipsPrincipalPart>(tr => new { tr.PopulatedToManies, tr.PopulatedToOne, tr.EmptyToOne, tr.EmptyToManies }); // Act ResourceObject resourceObject = _builder.Build(resource, relationships: relationships); // Assert Assert.Equal(4, resourceObject.Relationships.Count); Assert.Null(resourceObject.Relationships["emptyToOne"].Data.SingleValue); Assert.Empty(resourceObject.Relationships["emptyToManies"].Data.ManyValue); ResourceIdentifierObject populatedToOneData = resourceObject.Relationships["populatedToOne"].Data.SingleValue; Assert.NotNull(populatedToOneData); Assert.Equal("10", populatedToOneData.Id); Assert.Equal("oneToOneDependents", populatedToOneData.Type); IList<ResourceIdentifierObject> populatedToManyData = resourceObject.Relationships["populatedToManies"].Data.ManyValue; Assert.Single(populatedToManyData); Assert.Equal("20", populatedToManyData.First().Id); Assert.Equal("oneToManyDependents", populatedToManyData.First().Type); } [Fact] public void ResourceWithRelationshipsToResourceObject_DeviatingForeignKeyWhileRelationshipIncluded_IgnoresForeignKeyDuringBuild() { // Arrange var resource = new OneToOneDependent { Principal = new OneToOnePrincipal { Id = 10 }, PrincipalId = 123 }; IReadOnlyCollection<RelationshipAttribute> relationships = ResourceGraph.GetRelationships<OneToOneDependent>(tr => tr.Principal); // Act ResourceObject resourceObject = _builder.Build(resource, relationships: relationships); // Assert Assert.Single(resourceObject.Relationships); Assert.NotNull(resourceObject.Relationships["principal"].Data.Value); ResourceIdentifierObject ro = resourceObject.Relationships["principal"].Data.SingleValue; Assert.Equal("10", ro.Id); } [Fact] public void ResourceWithRelationshipsToResourceObject_DeviatingForeignKeyAndNoNavigationWhileRelationshipIncluded_IgnoresForeignKeyDuringBuild() { // Arrange var resource = new OneToOneDependent { Principal = null, PrincipalId = 123 }; IReadOnlyCollection<RelationshipAttribute> relationships = ResourceGraph.GetRelationships<OneToOneDependent>(tr => tr.Principal); // Act ResourceObject resourceObject = _builder.Build(resource, relationships: relationships); // Assert Assert.Null(resourceObject.Relationships["principal"].Data.Value); } [Fact] public void ResourceWithRequiredRelationshipsToResourceObject_DeviatingForeignKeyWhileRelationshipIncluded_IgnoresForeignKeyDuringBuild() { // Arrange var resource = new OneToOneRequiredDependent { Principal = new OneToOnePrincipal { Id = 10 }, PrincipalId = 123 }; IReadOnlyCollection<RelationshipAttribute> relationships = ResourceGraph.GetRelationships<OneToOneRequiredDependent>(tr => tr.Principal); // Act ResourceObject resourceObject = _builder.Build(resource, relationships: relationships); // Assert Assert.Single(resourceObject.Relationships); Assert.NotNull(resourceObject.Relationships["principal"].Data.SingleValue); ResourceIdentifierObject ro = resourceObject.Relationships["principal"].Data.SingleValue; Assert.Equal("10", ro.Id); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ProductCatalogPresenter.cs" company="Sitecore Corporation"> // Copyright (c) Sitecore Corporation 1999-2015 // </copyright> // <summary> // The product catalog presenter. // </summary> // -------------------------------------------------------------------------------------------------------------------- // Copyright 2015 Sitecore Corporation A/S // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. // ------------------------------------------------------------------------------------------- namespace Sitecore.Ecommerce.Shell.Applications.Catalogs.Presenters { using System; using System.Collections.Generic; using System.Linq; using Diagnostics; using DomainModel.Configurations; using Ecommerce.Search; using Globalization; using Models; using Models.Search; using Sitecore.Data; using Text; using Views; /// <summary> /// The product catalog presenter. /// </summary> public class ProductCatalogPresenter : CatalogPresenter { /// <summary> /// Initializes a new instance of the <see cref="ProductCatalogPresenter"/> class. /// </summary> /// <param name="view">The product catalog view.</param> public ProductCatalogPresenter(IProductCatalogView view) : base(view) { this.View = view; this.View.Save += this.Save; this.View.Search += this.Search; this.View.SelectedProductsGridRowDoubleClick += this.SelectedProductsGridRowDoubleClick; this.View.AddButtonClick += this.AddButtonClick; Catalog = new ProductCatalog { ItemUri = view.CatalogUri, Database = Database.GetDatabase(this.View.CurrentItemUri.DatabaseName), Language = this.View.CurrentItemUri.Language }; this.CatalogSettings = new ProductCatalogSettings { ItemUri = this.View.CurrentItemUri }; } /// <summary> /// Gets or sets the catalog settings. /// </summary> /// <value>The catalog settings.</value> public ProductCatalogSettings CatalogSettings { get; set; } /// <summary> /// Gets or sets the product catalog view. /// </summary> /// <value>The product catalog view.</value> public new IProductCatalogView View { get; protected set; } /// <summary> /// Gets or sets the product catalog definition. /// </summary> /// <value>The product catalog definition.</value> public ProductCatalog ProductCatalog { get { return (ProductCatalog)Catalog; } set { Catalog = value; } } /// <summary> /// Initializes the view. /// </summary> public override void InitializeView() { List<SearchMethod> searchMethods = this.ProductCatalog.GetSearchMethods(); foreach (SearchMethod searchMethod in searchMethods) { this.View.InitializeSearchMethod(searchMethod.ID.ToString(), searchMethod.Title); } if (searchMethods.Count > 0 && !ID.IsNullOrEmpty(this.CatalogSettings.SelectionMethod)) { this.View.SelectedSearchMethod = this.CatalogSettings.SelectionMethod.ToString(); } base.InitializeView(); IEnumerable<GridColumn> columns = this.ProductCatalog.GetGridColumns(); this.View.InitializeSelectedProductsGrid(columns); if (!this.View.IsCallBack) { this.View.SelectedProducts = this.CatalogSettings.ProductIDs; } } /// <summary> /// Called when the view save button clicked. /// </summary> public void Save() { this.CatalogSettings.TextBoxes = this.View.TextBoxes; this.CatalogSettings.Checklists = this.View.Checklists; if (!string.IsNullOrEmpty(this.View.SelectedSearchMethod)) { this.CatalogSettings.SelectionMethod = new ID(this.View.SelectedSearchMethod); } this.CatalogSettings.ProductIDs = this.View.SelectedProducts; } /// <summary> /// Search click event handler. /// </summary> public override void Search() { SearchOptions options = CreateSearchOptions(); SiteSettingsResolver settingsResolver = Context.Entity.Resolve<SiteSettingsResolver>(); BusinessCatalogSettings settings = null; Ecommerce.Search.ISearchProvider provider = Context.Entity.Resolve<Ecommerce.Search.ISearchProvider>(); try { settings = settingsResolver.GetSiteSettings(this.View.CurrentItemUri); } catch (InvalidOperationException ex) { Log.Error("Unable to resolve Business Catalog settings.", ex, this); return; } options.SearchRoot = settings.ProductsLink; base.Search(options); if (this.CatalogSettings.ProductIDs.Count > 0) { ItemIDListQueryBuilder builder = new ItemIDListQueryBuilder(this.CatalogSettings.ProductIDs); ItemResultDataConverter converter = new ItemResultDataConverter(); using (new LanguageSwitcher(this.View.CurrentItemUri.Language)) { var arrangedProducts = this.CatalogSettings.ProductIDs.Join(provider.Search(builder.GetResultQuery()), productId => productId, productItem => productItem.ID.ToString(), (productId, productItem) => productItem); GridData data = converter.Convert(arrangedProducts, this.ProductCatalog.GetGridColumns()); this.View.FillSelectedProductsGrid(data); } } } /// <summary> /// Handles textbox creating event. /// </summary> /// <param name="args">The arguments.</param> public override void TextBoxCreating(TextBoxEventArgs args) { base.TextBoxCreating(args); string text = this.CatalogSettings.TextBoxes[args.TextBoxDefinition.Field]; if (!string.IsNullOrEmpty(text)) { args.Text = text; } } /// <summary> /// Handles checklist creating event. /// </summary> /// <param name="args">The arguments.</param> public override void ChecklistCreating(ChecklistEventArgs args) { base.ChecklistCreating(args); string values = this.CatalogSettings.Checklists[args.ChecklistDefinition.Field]; if (!string.IsNullOrEmpty(values)) { args.CheckedValues = new ListString(values); } } /// <summary> /// Search method click event handler. /// </summary> /// <param name="shortId">The search method short ID.</param> public void SearchMethodClicked(string shortId) { if (this.View.SelectedSearchMethod != shortId) { this.View.SelectedSearchMethod = shortId; } } /// <summary> /// Handles the grid row double click event. /// </summary> /// <param name="args">The arguments.</param> public override void GridRowDoubleClick(GridCommandEventArgs args) { Assert.ArgumentNotNull(args, "args"); if (!ID.IsID(args.RowID)) { return; } if (this.View.SelectedProducts.Contains(args.RowID)) { this.View.ShowProductGridItemDublicatedAlert(); return; } this.View.AddRowToSelectedProductsGrid(args.RowID); } /// <summary> /// Handles the grid row double click event. /// </summary> /// <param name="args">The arguments.</param> public virtual void SelectedProductsGridRowDoubleClick(GridCommandEventArgs args) { Assert.ArgumentNotNull(args, "args"); if (!ID.IsID(args.RowID)) { return; } this.View.RemoveProductFromSelectedProductsGrid(args.RowID); } /// <summary> /// Handles the grid row double click event. /// </summary> /// <param name="args">The arguments.</param> public virtual void AddButtonClick(GridCommandEventArgs args) { Assert.ArgumentNotNull(args, "args"); if (args.RowsID == null) { return; } ListString rowIDs = new ListString(); bool showProductGridItemDublicatedAlert = false; foreach (string id in args.RowsID) { if (ID.IsID(id)) { if (this.View.SelectedProducts.Contains(id)) { showProductGridItemDublicatedAlert = true; } else { rowIDs.Add(id); } } } if (rowIDs.Count > 0) { this.View.AddRowToSelectedProductsGrid(rowIDs.ToString()); } if (showProductGridItemDublicatedAlert) { this.View.ShowProductGridItemDublicatedAlert(); } } } }
using System; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Orleans.Runtime.Scheduler; namespace Orleans.Runtime { internal class GrainTimer : IGrainTimer { private Func<object, Task> asyncCallback; private AsyncTaskSafeTimer timer; private readonly TimeSpan dueTime; private readonly TimeSpan timerFrequency; private DateTime previousTickTime; private int totalNumTicks; private static readonly Logger logger = LogManager.GetLogger("GrainTimer", LoggerType.Runtime); private Task currentlyExecutingTickTask; private readonly OrleansTaskScheduler scheduler; private readonly IActivationData activationData; public string Name { get; } private bool TimerAlreadyStopped { get { return timer == null || asyncCallback == null; } } private GrainTimer(OrleansTaskScheduler scheduler, IActivationData activationData, Func<object, Task> asyncCallback, object state, TimeSpan dueTime, TimeSpan period, string name) { var ctxt = RuntimeContext.CurrentActivationContext; scheduler.CheckSchedulingContextValidity(ctxt); this.scheduler = scheduler; this.activationData = activationData; this.Name = name; this.asyncCallback = asyncCallback; timer = new AsyncTaskSafeTimer( stateObj => TimerTick(stateObj, ctxt), state); this.dueTime = dueTime; timerFrequency = period; previousTickTime = DateTime.UtcNow; totalNumTicks = 0; } internal static GrainTimer FromTimerCallback( OrleansTaskScheduler scheduler, TimerCallback callback, object state, TimeSpan dueTime, TimeSpan period, string name = null) { return new GrainTimer( scheduler, null, ob => { if (callback != null) callback(ob); return Task.CompletedTask; }, state, dueTime, period, name); } internal static IGrainTimer FromTaskCallback( OrleansTaskScheduler scheduler, Func<object, Task> asyncCallback, object state, TimeSpan dueTime, TimeSpan period, string name = null, IActivationData activationData = null) { return new GrainTimer(scheduler, activationData, asyncCallback, state, dueTime, period, name); } public void Start() { if (TimerAlreadyStopped) throw new ObjectDisposedException(String.Format("The timer {0} was already disposed.", GetFullName())); timer.Start(dueTime, timerFrequency); } public void Stop() { asyncCallback = null; } private async Task TimerTick(object state, ISchedulingContext context) { if (TimerAlreadyStopped) return; try { // Schedule call back to grain context await this.scheduler.QueueNamedTask(() => ForwardToAsyncCallback(state), context, this.Name); } catch (InvalidSchedulingContextException exc) { logger.Error(ErrorCode.Timer_InvalidContext, string.Format("Caught an InvalidSchedulingContextException on timer {0}, context is {1}. Going to dispose this timer!", GetFullName(), context), exc); DisposeTimer(); } } private async Task ForwardToAsyncCallback(object state) { // AsyncSafeTimer ensures that calls to this method are serialized. if (TimerAlreadyStopped) return; totalNumTicks++; if (logger.IsVerbose3) logger.Verbose3(ErrorCode.TimerBeforeCallback, "About to make timer callback for timer {0}", GetFullName()); try { RequestContext.Clear(); // Clear any previous RC, so it does not leak into this call by mistake. currentlyExecutingTickTask = asyncCallback(state); await currentlyExecutingTickTask; if (logger.IsVerbose3) logger.Verbose3(ErrorCode.TimerAfterCallback, "Completed timer callback for timer {0}", GetFullName()); } catch (Exception exc) { logger.Error( ErrorCode.Timer_GrainTimerCallbackError, string.Format( "Caught and ignored exception: {0} with mesagge: {1} thrown from timer callback {2}", exc.GetType(), exc.Message, GetFullName()), exc); } finally { previousTickTime = DateTime.UtcNow; currentlyExecutingTickTask = null; // if this is not a repeating timer, then we can // dispose of the timer. if (timerFrequency == Constants.INFINITE_TIMESPAN) DisposeTimer(); } } public Task GetCurrentlyExecutingTickTask() { return currentlyExecutingTickTask ?? Task.CompletedTask; } private string GetFullName() { var callbackTarget = string.Empty; var callbackMethodInfo = string.Empty; if (asyncCallback != null) { if (asyncCallback.Target != null) { callbackTarget = asyncCallback.Target.ToString(); } var methodInfo = asyncCallback.GetMethodInfo(); if (methodInfo != null) { callbackMethodInfo = methodInfo.ToString(); } } return string.Format("GrainTimer.{0} TimerCallbackHandler:{1}->{2}", Name == null ? "" : Name + ".", callbackTarget, callbackMethodInfo); } public int GetNumTicks() { return totalNumTicks; } // The reason we need to check CheckTimerFreeze on both the SafeTimer and this GrainTimer // is that SafeTimer may tick OK (no starvation by .NET thread pool), but then scheduler.QueueWorkItem // may not execute and starve this GrainTimer callback. public bool CheckTimerFreeze(DateTime lastCheckTime) { if (TimerAlreadyStopped) return true; // check underlying SafeTimer (checking that .NET thread pool does not starve this timer) if (!timer.CheckTimerFreeze(lastCheckTime, () => Name)) return false; // if SafeTimer failed the check, no need to check GrainTimer too, since it will fail as well. // check myself (checking that scheduler.QueueWorkItem does not starve this timer) return SafeTimerBase.CheckTimerDelay(previousTickTime, totalNumTicks, dueTime, timerFrequency, logger, GetFullName, ErrorCode.Timer_TimerInsideGrainIsNotTicking, true); } public bool CheckTimerDelay() { return SafeTimerBase.CheckTimerDelay(previousTickTime, totalNumTicks, dueTime, timerFrequency, logger, GetFullName, ErrorCode.Timer_TimerInsideGrainIsNotTicking, false); } #region IDisposable Members public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } // Maybe called by finalizer thread with disposing=false. As per guidelines, in such a case do not touch other objects. // Dispose() may be called multiple times protected virtual void Dispose(bool disposing) { if (disposing) DisposeTimer(); asyncCallback = null; } private void DisposeTimer() { var tmp = timer; if (tmp == null) return; Utils.SafeExecute(tmp.Dispose); timer = null; asyncCallback = null; activationData?.OnTimerDisposed(this); } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using System.Diagnostics; namespace System.Threading.Tasks.Tests { public class AsyncTaskMethodBuilderTests { // building tasks [Fact] public static void RunAsyncMethodBuilderTests() { // AsyncVoidMethodBuilder { // Test captured sync context with successful completion (SetResult) { SynchronizationContext previousContext = SynchronizationContext.Current; var trackedContext = new TrackOperationsSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(trackedContext); // Completing in opposite order as created var avmb1 = AsyncVoidMethodBuilder.Create(); Assert.True(trackedContext.TrackedCount == 1, "RunAsyncMethodBuilderTests > FAILED: Should have been one active builder (SetResult, opposite order)."); var avmb2 = AsyncVoidMethodBuilder.Create(); Assert.True(trackedContext.TrackedCount == 2, "RunAsyncMethodBuilderTests > FAILED: Should have been two active builders (SetResult, opposite order)."); avmb2.SetResult(); Assert.True(trackedContext.TrackedCount == 1, "RunAsyncMethodBuilderTests > FAILED: Completed builder should have decremented count (SetResult, opposite order)."); avmb1.SetResult(); Assert.True(trackedContext.TrackedCount == 0, "RunAsyncMethodBuilderTests > FAILED: Completed builder should have returned count to 0 (SetResult, opposite order)."); // Completing in same order as created avmb1 = AsyncVoidMethodBuilder.Create(); Assert.True(trackedContext.TrackedCount == 1, "RunAsyncMethodBuilderTests > FAILED: Should have been one active builder (SetResult, same order)."); avmb2 = AsyncVoidMethodBuilder.Create(); Assert.True(trackedContext.TrackedCount == 2, "RunAsyncMethodBuilderTests > FAILED: Should have been two active builders (SetResult, same order)."); avmb1.SetResult(); Assert.True(trackedContext.TrackedCount == 1, "RunAsyncMethodBuilderTests > FAILED: Completed builder should have decremented count (SetResult, same order)."); avmb2.SetResult(); Assert.True(trackedContext.TrackedCount == 0, "RunAsyncMethodBuilderTests > FAILED: Completed builder should have returned count to 0 (SetResult, same order)."); SynchronizationContext.SetSynchronizationContext(previousContext); } // Test not having a sync context with successful completion (SetResult) { SynchronizationContext previousContext = SynchronizationContext.Current; try { // Make sure not having a sync context doesn't cause us to blow up SynchronizationContext.SetSynchronizationContext(null); var avmb = AsyncVoidMethodBuilder.Create(); avmb.SetResult(); } catch (Exception) { Assert.True(false, string.Format("RunAsyncMethodBuilderTests > FAILURE. Sync context caused us to blow up with Create/SetResult")); } finally { SynchronizationContext.SetSynchronizationContext(previousContext); } } } // AsyncTaskMethodBuilder { // Creating a task builder, building it, completing it successfully { var atmb = AsyncTaskMethodBuilder.Create(); var t = atmb.Task; Assert.True(t.Status == TaskStatus.WaitingForActivation, " > FAILURE. Builder should still be active (ATMB, build then set"); atmb.SetResult(); Assert.True(t.Status == TaskStatus.RanToCompletion, "Task status should equal RanToCompletion"); } // Verify that AsyncTaskMethodBuilder is not touching sync context { SynchronizationContext previousContext = SynchronizationContext.Current; var trackedContext = new TrackOperationsSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(trackedContext); var atmb = AsyncTaskMethodBuilder.Create(); Assert.True(trackedContext.TrackedCount == 0, " > FAILURE. Builder should not interact with the sync context (before ATMB set)"); atmb.SetResult(); Assert.True(trackedContext.TrackedCount == 0, " > FAILURE. Builder should not interact with the sync context (after ATMB set)"); SynchronizationContext.SetSynchronizationContext(previousContext); } } // AsyncTaskMethodBuilder<T> { // Creating a task builder, building it, completing it successfully { var atmb = AsyncTaskMethodBuilder<int>.Create(); var t = atmb.Task; Assert.True(t.Status == TaskStatus.WaitingForActivation, " > FAILURE. Builder should still be active (ATMBT, build then set)"); atmb.SetResult(43); Assert.True(t.Status == TaskStatus.RanToCompletion, " > FAILURE. Builder should have successfully completed (ATMBT, build then set)"); Assert.True(t.Result == 43, " > FAILURE. Builder should completed with the set result (ATMBT, build then set)"); } // Verify that AsyncTaskMethodBuilder<T> is not touching sync context { SynchronizationContext previousContext = SynchronizationContext.Current; var trackedContext = new TrackOperationsSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(trackedContext); var atmb = AsyncTaskMethodBuilder<string>.Create(); Assert.True(trackedContext.TrackedCount == 0, " > FAILURE. Builder should not interact with the sync context (before ATMBT set)"); atmb.SetResult("async"); Assert.True(trackedContext.TrackedCount == 0, " > FAILURE. Builder should not interact with the sync context (after ATMBT set)"); SynchronizationContext.SetSynchronizationContext(previousContext); } } } [Fact] [ActiveIssue("Hangs")] public static void RunAsyncMethodBuilderTests_NegativeTests() { // Incorrect usage for AsyncVoidMethodBuilder { var atmb = new AsyncTaskMethodBuilder(); Assert.Throws<ArgumentNullException>( () => { atmb.SetException(null); }); } // Incorrect usage for AsyncTaskMethodBuilder { var avmb = AsyncVoidMethodBuilder.Create(); Assert.Throws<ArgumentNullException>( () => { avmb.SetException(null); }); } // Creating a task builder, building it, completing it successfully, and making sure it can't be reset { var atmb = AsyncTaskMethodBuilder.Create(); atmb.SetResult(); Assert.Throws<InvalidOperationException>( () => { atmb.SetResult(); }); Assert.Throws<InvalidOperationException>( () => { atmb.SetException(new Exception()); }); } // Incorrect usage for AsyncTaskMethodBuilder<T> { var atmb = new AsyncTaskMethodBuilder<int>(); Assert.Throws<ArgumentNullException>( () => { atmb.SetException(null); }); } // Creating a task builder <T>, building it, completing it successfully, and making sure it can't be reset { var atmb = AsyncTaskMethodBuilder<int>.Create(); atmb.SetResult(43); Assert.Throws<InvalidOperationException>( () => { atmb.SetResult(44); }); Assert.Throws<InvalidOperationException>( () => { atmb.SetException(new Exception()); }); } } [Fact] public static void AsyncMethodBuilderCreate_SetExceptionTest() { // Creating a task builder, building it, completing it faulted, and making sure it can't be reset { var atmb = AsyncTaskMethodBuilder.Create(); var t = atmb.Task; Assert.True(t.Status == TaskStatus.WaitingForActivation, " > FAILURE. Builder should still be active (ATMB, build then fault)"); atmb.SetException(new InvalidCastException()); Assert.True(t.Status == TaskStatus.Faulted, " > FAILURE. Builder should be faulted after an exception occurs (ATMB, build then fault)"); Assert.True(t.Exception.InnerException is InvalidCastException, " > FAILURE. Wrong exception found in builder (ATMB, build then fault)"); Assert.Throws<InvalidOperationException>( () => { atmb.SetResult(); }); Assert.Throws<InvalidOperationException>( () => { atmb.SetException(new Exception()); }); } // Creating a task builder, completing it faulted, building it, and making sure it can't be reset { var atmb = AsyncTaskMethodBuilder.Create(); atmb.SetException(new InvalidCastException()); var t = atmb.Task; Assert.True(t.Status == TaskStatus.Faulted, " > FAILURE. Builder should be faulted after an exception occurs (ATMB, fault then build)"); Assert.True(t.Exception.InnerException is InvalidCastException, " > FAILURE. Wrong exception found in builder (ATMB, fault then build)"); Assert.Throws<InvalidOperationException>( () => { atmb.SetResult(); }); Assert.Throws<InvalidOperationException>( () => { atmb.SetException(new Exception()); }); } // Test cancellation { var atmb = AsyncTaskMethodBuilder.Create(); var oce = new OperationCanceledException(); atmb.SetException(oce); var t = atmb.Task; Assert.True(t.Status == TaskStatus.Canceled, " > FAILURE. Builder should be canceled from an unhandled OCE (ATMB cancellation)"); try { t.GetAwaiter().GetResult(); Assert.True(false, " > FAILURE. Excepted GetResult to throw. (ATMB cancellation)"); } catch (Exception exc) { Assert.True(Object.ReferenceEquals(oce, exc), " > FAILURE. Excepted original OCE to be thrown. (ATMB cancellation)"); } Assert.Throws<InvalidOperationException>( () => { atmb.SetResult(); }); Assert.Throws<InvalidOperationException>( () => { atmb.SetException(new Exception()); }); } } [Fact] public static void AsyncMethodBuilderCreate_SetExceptionTest2() { // Test captured sync context with exceptional completion SynchronizationContext previousContext = SynchronizationContext.Current; var trackedContext = new TrackOperationsSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(trackedContext); // Completing in opposite order as created var avmb1 = AsyncVoidMethodBuilder.Create(); Assert.True(trackedContext.TrackedCount == 1, "RunAsyncMethodBuilderTests > FAILED: Should have been one active builder (SetException, opposite order)."); var avmb2 = AsyncVoidMethodBuilder.Create(); Assert.True(trackedContext.TrackedCount == 2, "RunAsyncMethodBuilderTests > FAILED: Should have been two active builders (SetException, opposite order)."); avmb2.SetException(new InvalidOperationException("uh oh 1")); Assert.True(trackedContext.TrackedCount == 1, "RunAsyncMethodBuilderTests > FAILED: Completed builder should have decremented count (SetException, opposite order)."); avmb1.SetException(new InvalidCastException("uh oh 2")); Assert.True(trackedContext.TrackedCount == 0, "RunAsyncMethodBuilderTests > FAILED: Completed builder should have returned count to 0 (SetException, opposite order)."); Assert.True( trackedContext.PostExceptions.Count == 2 && trackedContext.PostExceptions[0] is InvalidOperationException && trackedContext.PostExceptions[1] is InvalidCastException, " > FAILED: Expected two exceptions of the right types."); // Completing in same order as created var avmb3 = AsyncVoidMethodBuilder.Create(); Assert.True(trackedContext.TrackedCount == 1, "RunAsyncMethodBuilderTests > FAILED: Should have been one active builder (SetException, same order)."); var avmb4 = AsyncVoidMethodBuilder.Create(); Assert.True(trackedContext.TrackedCount == 2, "RunAsyncMethodBuilderTests > FAILED: Should have been two active builders (SetException, same order)."); avmb3.SetException(new InvalidOperationException("uh oh 3")); Assert.True(trackedContext.TrackedCount == 1, "RunAsyncMethodBuilderTests > FAILED: Completed builder should have decremented count (SetException, same order)."); avmb4.SetException(new InvalidCastException("uh oh 4")); Assert.True(trackedContext.TrackedCount == 0, "RunAsyncMethodBuilderTests > FAILED: Completed builder should have returned count to 0 (SetException, same order)."); Assert.True( trackedContext.PostExceptions.Count == 4 && trackedContext.PostExceptions[2] is InvalidOperationException && trackedContext.PostExceptions[3] is InvalidCastException, "RunAsyncMethodBuilderTests > FAILED: Expected two more exceptions of the right types."); SynchronizationContext.SetSynchronizationContext(previousContext); } [Fact] public static void AsyncMethodBuilderTCreate_SetExceptionTest() { // Creating a task builder, building it, completing it faulted, and making sure it can't be reset { var atmb = AsyncTaskMethodBuilder<int>.Create(); var t = atmb.Task; Assert.True(t.Status == TaskStatus.WaitingForActivation, " > FAILURE. Builder should still be active (ATMBT, build then fault)"); atmb.SetException(new InvalidCastException()); Assert.True(t.Status == TaskStatus.Faulted, " > FAILURE. Builder should be faulted after an exception occurs (ATMBT, build then fault)"); Assert.True(t.Exception.InnerException is InvalidCastException, " > FAILURE. Wrong exception found in builder (ATMBT, build then fault)"); Assert.Throws<InvalidOperationException>( () => { atmb.SetResult(44); }); Assert.Throws<InvalidOperationException>( () => { atmb.SetException(new Exception()); }); } // Creating a task builder, completing it faulted, building it, and making sure it can't be reset { var atmb = AsyncTaskMethodBuilder<int>.Create(); atmb.SetException(new InvalidCastException()); var t = atmb.Task; Assert.True(t.Status == TaskStatus.Faulted, " > FAILURE. Builder should be faulted after an exception occurs (ATMBT, fault then build)"); Assert.True(t.Exception.InnerException is InvalidCastException, " > FAILURE. Wrong exception found in builder (ATMBT, fault then build)"); Assert.Throws<InvalidOperationException>( () => { atmb.SetResult(44); }); Assert.Throws<InvalidOperationException>( () => { atmb.SetException(new Exception()); }); } // Test cancellation { var atmb = AsyncTaskMethodBuilder<int>.Create(); var oce = new OperationCanceledException(); atmb.SetException(oce); var t = atmb.Task; Assert.True(t.Status == TaskStatus.Canceled, " > FAILURE. Builder should be canceled from an unhandled OCE (ATMBT cancellation)"); try { t.GetAwaiter().GetResult(); Assert.True(false, " > FAILURE. Excepted GetResult to throw. (ATMBT cancellation)"); } catch (Exception exc) { Assert.True(Object.ReferenceEquals(oce, exc), " > FAILURE. Excepted original OCE to be thrown. (ATMBT cancellation)"); } Assert.Throws<InvalidOperationException>( () => { atmb.SetResult(44); }); Assert.Throws<InvalidOperationException>( () => { atmb.SetException(new Exception()); }); } } // random other stuff, e.g. exception dispatch info [Fact] public static void RunAsyncAdditionalBehaviorsTests() { { var atmb = new AsyncTaskMethodBuilder(); var t1 = atmb.Task; var t2 = atmb.Task; Assert.True(t1 != null, " > FAILURE. Task should have been initialized."); Assert.True(t2 != null, " > FAILURE. Task should have been initialized."); Assert.True(t1 == t2, " > FAILURE. Task should be cached once initialized."); } { var atmb = new AsyncTaskMethodBuilder<int>(); var t1 = atmb.Task; var t2 = atmb.Task; Assert.True(t1 != null, " > FAILURE. Task should have been initialized."); Assert.True(t2 != null, " > FAILURE. Task should have been initialized."); Assert.True(t1 == t2, " > FAILURE. Task should be cached once initialized."); } } [Fact] public static void RunAsyncAdditionalBehaviorsTests_NegativeCases() { // Test ExceptionDispatchInfo usage //if (Thread.CurrentThread.CurrentCulture.ThreeLetterWindowsLanguageName == "ENU") // only on ENU because of string comparisons //{ { var tcs = new TaskCompletionSource<int>(); try { throw new InvalidOperationException(); } catch (Exception e) { tcs.SetException(e); } Assert.True(ValidateFaultedTask(tcs.Task), " > FAILURE. Task's stack trace is incorrect"); } { var atmb = AsyncTaskMethodBuilder.Create(); try { throw new InvalidOperationException(); } catch (Exception e) { atmb.SetException(e); } Assert.True(ValidateFaultedTask(atmb.Task), " > FAILURE. Task's stack trace is incorrect"); } { var atmbtr = AsyncTaskMethodBuilder<object>.Create(); try { throw new InvalidOperationException(); } catch (Exception e) { atmbtr.SetException(e); } Assert.True(ValidateFaultedTask(atmbtr.Task), " > FAILURE. Task's stack trace is incorrect"); } { SynchronizationContext previousContext = SynchronizationContext.Current; var tosc = new TrackOperationsSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(tosc); var avmb = AsyncVoidMethodBuilder.Create(); try { throw new InvalidOperationException(); } catch (Exception exc) { avmb.SetException(exc); } Assert.True( tosc.PostExceptions.Count > 0 && ValidateException(tosc.PostExceptions[0]), " > FAILURE. AVMB task should have posted exceptions to the sync context"); SynchronizationContext.SetSynchronizationContext(previousContext); } } [Fact] public static void RunAsyncAdditionalBehaviorsTests_NegativeCases2() { // Running tasks with exceptions. { var twa1 = Task.Run(() => { throw new Exception("uh oh"); }); var twa2 = Task.Factory.StartNew(() => { throw new Exception("uh oh"); }); var tasks = new Task[] { Task.Run(() => { throw new Exception("uh oh"); }), Task.Factory.StartNew<int>(() => { throw new Exception("uh oh"); }), Task.WhenAll(Task.Run(() => { throw new Exception("uh oh"); }), Task.Run(() => { throw new Exception("uh oh"); })), Task.WhenAll<int>(Task.Run(new Func<int>(() => { throw new Exception("uh oh"); })), Task.Run(new Func<int>(() => { throw new Exception("uh oh"); }))), Task.WhenAny(twa1, twa2).Unwrap(), Task.WhenAny<int>(Task.Run(new Func<Task<int>>(() => { throw new Exception("uh oh"); }))).Unwrap(), Task.Factory.StartNew(() => Task.Factory.StartNew(() => { throw new Exception("uh oh"); })).Unwrap(), Task.Factory.StartNew<Task<int>>(() => Task.Factory.StartNew<int>(() => { throw new Exception("uh oh"); })).Unwrap(), Task.Run(() => Task.Run(() => { throw new Exception("uh oh"); })), Task.Run(() => Task.Run(new Func<int>(() => { throw new Exception("uh oh"); }))), Task.Run(new Func<Task>(() => { throw new Exception("uh oh"); })), Task.Run(new Func<Task<int>>(() => { throw new Exception("uh oh"); })) }; for (int i = 0; i < tasks.Length; i++) { var task = tasks[i]; Assert.True(ValidateFaultedTask(task), " > FAILURE. Task " + i + " didn't fault with the right stack trace."); } ((IAsyncResult)twa1).AsyncWaitHandle.WaitOne(); ((IAsyncResult)twa2).AsyncWaitHandle.WaitOne(); Exception ignored = twa1.Exception; ignored = twa2.Exception; } // Test that OCEs don't result in the unobserved event firing { var cts = new CancellationTokenSource(); var oce = new OperationCanceledException(cts.Token); // A Task that throws an exception to cancel var b = new Barrier(2); Task t1 = Task.Factory.StartNew(() => { b.SignalAndWait(); b.SignalAndWait(); throw oce; }, cts.Token); b.SignalAndWait(); // make sure task is started before we cancel cts.Cancel(); b.SignalAndWait(); // release task to complete // This test may be run concurrently with other tests in the suite, // which can be problematic as TaskScheduler.UnobservedTaskException // is global state. The handler is carefully written to be non-problematic // if it happens to be set during the execution of another test that has // an unobserved exception. EventHandler<UnobservedTaskExceptionEventArgs> handler = (s, e) => Assert.DoesNotContain(oce, e.Exception.InnerExceptions); TaskScheduler.UnobservedTaskException += handler; ((IAsyncResult)t1).AsyncWaitHandle.WaitOne(); t1 = null; for (int i = 0; i < 10; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); } TaskScheduler.UnobservedTaskException -= handler; } } #region Helper Methods / Classes private static bool ValidateFaultedTask(Task t) { ((IAsyncResult)t).AsyncWaitHandle.WaitOne(); bool localPassed = t.IsFaulted; try { t.GetAwaiter().GetResult(); Debug.WriteLine(" > FAILURE. Faulted task's GetResult should have thrown."); } catch (Exception e) { localPassed &= ValidateException(e); } return localPassed; } private static bool ValidateException(Exception e) { return e != null && e.StackTrace != null && e.StackTrace.Contains("End of stack trace"); } private class TrackOperationsSynchronizationContext : SynchronizationContext { private int _trackedCount; private int _postCount; //ConcurrentQueue private List<Exception> _postExceptions = new List<Exception>(); public int TrackedCount { get { return _trackedCount; } } public List<Exception> PostExceptions { get { List<Exception> returnValue; lock (_postExceptions) { returnValue = new List<Exception>(_postExceptions); return returnValue; } } } public int PostCount { get { return _postCount; } } public override void OperationStarted() { Interlocked.Increment(ref _trackedCount); } public override void OperationCompleted() { Interlocked.Decrement(ref _trackedCount); } public override void Post(SendOrPostCallback callback, object state) { try { Interlocked.Increment(ref _postCount); callback(state); } catch (Exception exc) { lock (_postExceptions) { _postExceptions.Add(exc); } } } } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Net; using System.Reflection; using System.Security.Cryptography; using log4net; using Nwc.XmlRpc; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Data; using OpenSim.Framework.Communications; using OpenSim.Framework.Statistics; using OpenSim.Services.Interfaces; namespace OpenSim.Framework.Communications { /// <summary> /// Base class for user management (create, read, etc) /// </summary> public abstract class UserManagerBase : IUserService, IUserAdminService, IAvatarService, IMessagingService, IAuthentication { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <value> /// List of plugins to search for user data /// </value> private List<IUserDataPlugin> m_plugins = new List<IUserDataPlugin>(); protected CommunicationsManager m_commsManager; protected IInventoryService m_InventoryService; /// <summary> /// Constructor /// </summary> /// <param name="commsManager"></param> public UserManagerBase(CommunicationsManager commsManager) { m_commsManager = commsManager; } public virtual void SetInventoryService(IInventoryService invService) { m_InventoryService = invService; } /// <summary> /// Add a new user data plugin - plugins will be requested in the order they were added. /// </summary> /// <param name="plugin">The plugin that will provide user data</param> public void AddPlugin(IUserDataPlugin plugin) { m_plugins.Add(plugin); } /// <summary> /// Adds a list of user data plugins, as described by `provider' and /// `connect', to `_plugins'. /// </summary> /// <param name="provider"> /// The filename of the inventory server plugin DLL. /// </param> /// <param name="connect"> /// The connection string for the storage backend. /// </param> public void AddPlugin(string provider, string connect) { m_plugins.AddRange(DataPluginFactory.LoadDataPlugins<IUserDataPlugin>(provider, connect)); } #region UserProfile public virtual void AddTemporaryUserProfile(UserProfileData userProfile) { foreach (IUserDataPlugin plugin in m_plugins) { plugin.AddTemporaryUserProfile(userProfile); } } public virtual UserProfileData GetUserProfile(string fname, string lname) { foreach (IUserDataPlugin plugin in m_plugins) { UserProfileData profile = plugin.GetUserByName(fname, lname); if (profile != null) { profile.CurrentAgent = GetUserAgent(profile.ID); return profile; } } return null; } public void LogoutUsers(UUID regionID) { foreach (IUserDataPlugin plugin in m_plugins) { plugin.LogoutUsers(regionID); } } public void ResetAttachments(UUID userID) { foreach (IUserDataPlugin plugin in m_plugins) { plugin.ResetAttachments(userID); } } public UserProfileData GetUserProfile(Uri uri) { foreach (IUserDataPlugin plugin in m_plugins) { UserProfileData profile = plugin.GetUserByUri(uri); if (null != profile) return profile; } return null; } public virtual UserAgentData GetAgentByUUID(UUID userId) { foreach (IUserDataPlugin plugin in m_plugins) { UserAgentData agent = plugin.GetAgentByUUID(userId); if (agent != null) { return agent; } } return null; } public Uri GetUserUri(UserProfileData userProfile) { throw new NotImplementedException(); } // see IUserService public virtual UserProfileData GetUserProfile(UUID uuid) { foreach (IUserDataPlugin plugin in m_plugins) { UserProfileData profile = plugin.GetUserByUUID(uuid); if (null != profile) { profile.CurrentAgent = GetUserAgent(profile.ID); return profile; } } return null; } public virtual List<AvatarPickerAvatar> GenerateAgentPickerRequestResponse(UUID queryID, string query) { List<AvatarPickerAvatar> allPickerList = new List<AvatarPickerAvatar>(); foreach (IUserDataPlugin plugin in m_plugins) { try { List<AvatarPickerAvatar> pickerList = plugin.GeneratePickerResults(queryID, query); if (pickerList != null) allPickerList.AddRange(pickerList); } catch (Exception) { m_log.Error( "[USERSTORAGE]: Unable to generate AgentPickerData via " + plugin.Name + "(" + query + ")"); } } return allPickerList; } public virtual bool UpdateUserProfile(UserProfileData data) { bool result = false; foreach (IUserDataPlugin plugin in m_plugins) { try { plugin.UpdateUserProfile(data); result = true; } catch (Exception e) { m_log.ErrorFormat( "[USERSTORAGE]: Unable to set user {0} {1} via {2}: {3}", data.FirstName, data.SurName, plugin.Name, e.ToString()); } } return result; } #endregion #region Get UserAgent /// <summary> /// Loads a user agent by uuid (not called directly) /// </summary> /// <param name="uuid">The agent's UUID</param> /// <returns>Agent profiles</returns> public UserAgentData GetUserAgent(UUID uuid) { foreach (IUserDataPlugin plugin in m_plugins) { try { UserAgentData result = plugin.GetAgentByUUID(uuid); if (result != null) return result; } catch (Exception e) { m_log.Error("[USERSTORAGE]: Unable to find user via " + plugin.Name + "(" + e.ToString() + ")"); } } return null; } /// <summary> /// Loads a user agent by name (not called directly) /// </summary> /// <param name="name">The agent's name</param> /// <returns>A user agent</returns> public UserAgentData GetUserAgent(string name) { foreach (IUserDataPlugin plugin in m_plugins) { try { UserAgentData result = plugin.GetAgentByName(name); if (result != null) return result; } catch (Exception e) { m_log.Error("[USERSTORAGE]: Unable to find user via " + plugin.Name + "(" + e.ToString() + ")"); } } return null; } /// <summary> /// Loads a user agent by name (not called directly) /// </summary> /// <param name="fname">The agent's firstname</param> /// <param name="lname">The agent's lastname</param> /// <returns>A user agent</returns> public UserAgentData GetUserAgent(string fname, string lname) { foreach (IUserDataPlugin plugin in m_plugins) { try { UserAgentData result = plugin.GetAgentByName(fname, lname); if (result != null) return result; } catch (Exception e) { m_log.Error("[USERSTORAGE]: Unable to find user via " + plugin.Name + "(" + e.ToString() + ")"); } } return null; } public virtual List<FriendListItem> GetUserFriendList(UUID ownerID) { List<FriendListItem> allFriends = new List<FriendListItem>(); foreach (IUserDataPlugin plugin in m_plugins) { try { List<FriendListItem> friends = plugin.GetUserFriendList(ownerID); if (friends != null) allFriends.AddRange(friends); } catch (Exception e) { m_log.Error("[USERSTORAGE]: Unable to GetUserFriendList via " + plugin.Name + "(" + e.ToString() + ")"); } } return allFriends; } public virtual Dictionary<UUID, FriendRegionInfo> GetFriendRegionInfos (List<UUID> uuids) { //Dictionary<UUID, FriendRegionInfo> allFriendRegions = new Dictionary<UUID, FriendRegionInfo>(); foreach (IUserDataPlugin plugin in m_plugins) { try { Dictionary<UUID, FriendRegionInfo> friendRegions = plugin.GetFriendRegionInfos(uuids); if (friendRegions != null) return friendRegions; } catch (Exception e) { m_log.Error("[USERSTORAGE]: Unable to GetFriendRegionInfos via " + plugin.Name + "(" + e.ToString() + ")"); } } return new Dictionary<UUID, FriendRegionInfo>(); } public void StoreWebLoginKey(UUID agentID, UUID webLoginKey) { foreach (IUserDataPlugin plugin in m_plugins) { try { plugin.StoreWebLoginKey(agentID, webLoginKey); } catch (Exception e) { m_log.Error("[USERSTORAGE]: Unable to Store WebLoginKey via " + plugin.Name + "(" + e.ToString() + ")"); } } } public virtual void AddNewUserFriend(UUID friendlistowner, UUID friend, uint perms) { foreach (IUserDataPlugin plugin in m_plugins) { try { plugin.AddNewUserFriend(friendlistowner, friend, perms); } catch (Exception e) { m_log.Error("[USERSTORAGE]: Unable to AddNewUserFriend via " + plugin.Name + "(" + e.ToString() + ")"); } } } public virtual void RemoveUserFriend(UUID friendlistowner, UUID friend) { foreach (IUserDataPlugin plugin in m_plugins) { try { plugin.RemoveUserFriend(friendlistowner, friend); } catch (Exception e) { m_log.Error("[USERSTORAGE]: Unable to RemoveUserFriend via " + plugin.Name + "(" + e.ToString() + ")"); } } } public virtual void UpdateUserFriendPerms(UUID friendlistowner, UUID friend, uint perms) { foreach (IUserDataPlugin plugin in m_plugins) { try { plugin.UpdateUserFriendPerms(friendlistowner, friend, perms); } catch (Exception e) { m_log.Error("[USERSTORAGE]: Unable to UpdateUserFriendPerms via " + plugin.Name + "(" + e.ToString() + ")"); } } } /// <summary> /// Resets the currentAgent in the user profile /// </summary> /// <param name="agentID">The agent's ID</param> public virtual void ClearUserAgent(UUID agentID) { UserProfileData profile = GetUserProfile(agentID); if (profile == null) { return; } profile.CurrentAgent = null; UpdateUserProfile(profile); } #endregion #region CreateAgent /// <summary> /// Creates and initialises a new user agent - make sure to use CommitAgent when done to submit to the DB /// </summary> /// <param name="profile">The users profile</param> /// <param name="request">The users loginrequest</param> public void CreateAgent(UserProfileData profile, XmlRpcRequest request) { //m_log.DebugFormat("[USER MANAGER]: Creating agent {0} {1}", profile.Name, profile.ID); UserAgentData agent = new UserAgentData(); // User connection agent.AgentOnline = true; if (request.Params.Count > 1) { if (request.Params[1] != null) { IPEndPoint RemoteIPEndPoint = (IPEndPoint)request.Params[1]; agent.AgentIP = RemoteIPEndPoint.Address.ToString(); agent.AgentPort = (uint)RemoteIPEndPoint.Port; } } // Generate sessions RNGCryptoServiceProvider rand = new RNGCryptoServiceProvider(); byte[] randDataS = new byte[16]; byte[] randDataSS = new byte[16]; rand.GetBytes(randDataS); rand.GetBytes(randDataSS); agent.SecureSessionID = new UUID(randDataSS, 0); agent.SessionID = new UUID(randDataS, 0); // Profile UUID agent.ProfileID = profile.ID; // Current location/position/alignment if (profile.CurrentAgent != null) { agent.Region = profile.CurrentAgent.Region; agent.Handle = profile.CurrentAgent.Handle; agent.Position = profile.CurrentAgent.Position; agent.LookAt = profile.CurrentAgent.LookAt; } else { agent.Region = profile.HomeRegionID; agent.Handle = profile.HomeRegion; agent.Position = profile.HomeLocation; agent.LookAt = profile.HomeLookAt; } // What time did the user login? agent.LoginTime = Util.UnixTimeSinceEpoch(); agent.LogoutTime = 0; profile.CurrentAgent = agent; } public void CreateAgent(UserProfileData profile, OSD request) { //m_log.DebugFormat("[USER MANAGER]: Creating agent {0} {1}", profile.Name, profile.ID); UserAgentData agent = new UserAgentData(); // User connection agent.AgentOnline = true; //if (request.Params.Count > 1) //{ // IPEndPoint RemoteIPEndPoint = (IPEndPoint)request.Params[1]; // agent.AgentIP = RemoteIPEndPoint.Address.ToString(); // agent.AgentPort = (uint)RemoteIPEndPoint.Port; //} // Generate sessions RNGCryptoServiceProvider rand = new RNGCryptoServiceProvider(); byte[] randDataS = new byte[16]; byte[] randDataSS = new byte[16]; rand.GetBytes(randDataS); rand.GetBytes(randDataSS); agent.SecureSessionID = new UUID(randDataSS, 0); agent.SessionID = new UUID(randDataS, 0); // Profile UUID agent.ProfileID = profile.ID; // Current location/position/alignment if (profile.CurrentAgent != null) { agent.Region = profile.CurrentAgent.Region; agent.Handle = profile.CurrentAgent.Handle; agent.Position = profile.CurrentAgent.Position; agent.LookAt = profile.CurrentAgent.LookAt; } else { agent.Region = profile.HomeRegionID; agent.Handle = profile.HomeRegion; agent.Position = profile.HomeLocation; agent.LookAt = profile.HomeLookAt; } // What time did the user login? agent.LoginTime = Util.UnixTimeSinceEpoch(); agent.LogoutTime = 0; profile.CurrentAgent = agent; } /// <summary> /// Saves a target agent to the database /// </summary> /// <param name="profile">The users profile</param> /// <returns>Successful?</returns> public bool CommitAgent(ref UserProfileData profile) { //m_log.DebugFormat("[USER MANAGER]: Committing agent {0} {1}", profile.Name, profile.ID); // TODO: how is this function different from setUserProfile? -> Add AddUserAgent() here and commit both tables "users" and "agents" // TODO: what is the logic should be? bool ret = false; ret = AddUserAgent(profile.CurrentAgent); ret = ret & UpdateUserProfile(profile); return ret; } /// <summary> /// Process a user logoff from OpenSim. /// </summary> /// <param name="userid"></param> /// <param name="regionid"></param> /// <param name="regionhandle"></param> /// <param name="position"></param> /// <param name="lookat"></param> public virtual void LogOffUser(UUID userid, UUID regionid, ulong regionhandle, Vector3 position, Vector3 lookat) { if (StatsManager.UserStats != null) StatsManager.UserStats.AddLogout(); UserProfileData userProfile = GetUserProfile(userid); if (userProfile != null) { UserAgentData userAgent = userProfile.CurrentAgent; if (userAgent != null) { userAgent.AgentOnline = false; userAgent.LogoutTime = Util.UnixTimeSinceEpoch(); //userAgent.sessionID = UUID.Zero; if (regionid != UUID.Zero) { userAgent.Region = regionid; } userAgent.Handle = regionhandle; userAgent.Position = position; userAgent.LookAt = lookat; //userProfile.CurrentAgent = userAgent; userProfile.LastLogin = userAgent.LogoutTime; CommitAgent(ref userProfile); } else { // If currentagent is null, we can't reference it here or the UserServer crashes! m_log.Info("[LOGOUT]: didn't save logout position: " + userid.ToString()); } } else { m_log.Warn("[LOGOUT]: Unknown User logged out"); } } public void LogOffUser(UUID userid, UUID regionid, ulong regionhandle, float posx, float posy, float posz) { LogOffUser(userid, regionid, regionhandle, new Vector3(posx, posy, posz), new Vector3()); } #endregion /// <summary> /// Add a new user /// </summary> /// <param name="firstName">first name</param> /// <param name="lastName">last name</param> /// <param name="password">password</param> /// <param name="email">email</param> /// <param name="regX">location X</param> /// <param name="regY">location Y</param> /// <returns>The UUID of the created user profile. On failure, returns UUID.Zero</returns> public virtual UUID AddUser(string firstName, string lastName, string password, string email, uint regX, uint regY) { return AddUser(firstName, lastName, password, email, regX, regY, UUID.Random()); } /// <summary> /// Add a new user /// </summary> /// <param name="firstName">first name</param> /// <param name="lastName">last name</param> /// <param name="password">password</param> /// <param name="email">email</param> /// <param name="regX">location X</param> /// <param name="regY">location Y</param> /// <param name="SetUUID">UUID of avatar.</param> /// <returns>The UUID of the created user profile. On failure, returns UUID.Zero</returns> public virtual UUID AddUser( string firstName, string lastName, string password, string email, uint regX, uint regY, UUID SetUUID) { UserProfileData user = new UserProfileData(); user.PasswordSalt = Util.Md5Hash(UUID.Random().ToString()); string md5PasswdHash = Util.Md5Hash(Util.Md5Hash(password) + ":" + user.PasswordSalt); user.HomeLocation = new Vector3(128, 128, 100); user.ID = SetUUID; user.FirstName = firstName; user.SurName = lastName; user.PasswordHash = md5PasswdHash; user.Created = Util.UnixTimeSinceEpoch(); user.HomeLookAt = new Vector3(100, 100, 100); user.HomeRegionX = regX; user.HomeRegionY = regY; user.Email = email; foreach (IUserDataPlugin plugin in m_plugins) { try { plugin.AddNewUserProfile(user); } catch (Exception e) { m_log.Error("[USERSTORAGE]: Unable to add user via " + plugin.Name + "(" + e.ToString() + ")"); } } UserProfileData userProf = GetUserProfile(firstName, lastName); if (userProf == null) { return UUID.Zero; } else { // // WARNING: This is a horrible hack // The purpose here is to avoid touching the user server at this point. // There are dragons there that I can't deal with right now. // diva 06/09/09 // if (m_InventoryService != null) { // local service (standalone) m_log.Debug("[USERSTORAGE]: using IInventoryService to create user's inventory"); m_InventoryService.CreateUserInventory(userProf.ID); } else if (m_commsManager.InterServiceInventoryService != null) { // used by the user server m_log.Debug("[USERSTORAGE]: using m_commsManager.InterServiceInventoryService to create user's inventory"); m_commsManager.InterServiceInventoryService.CreateNewUserInventory(userProf.ID); } return userProf.ID; } } /// <summary> /// Reset a user password. /// </summary> /// <param name="firstName"></param> /// <param name="lastName"></param> /// <param name="newPassword"></param> /// <returns>true if the update was successful, false otherwise</returns> public virtual bool ResetUserPassword(string firstName, string lastName, string newPassword) { string md5PasswdHash = Util.Md5Hash(Util.Md5Hash(newPassword) + ":" + String.Empty); UserProfileData profile = GetUserProfile(firstName, lastName); if (null == profile) { m_log.ErrorFormat("[USERSTORAGE]: Could not find user {0} {1}", firstName, lastName); return false; } profile.PasswordHash = md5PasswdHash; profile.PasswordSalt = String.Empty; UpdateUserProfile(profile); return true; } public abstract UserProfileData SetupMasterUser(string firstName, string lastName); public abstract UserProfileData SetupMasterUser(string firstName, string lastName, string password); public abstract UserProfileData SetupMasterUser(UUID uuid); /// <summary> /// Add an agent using data plugins. /// </summary> /// <param name="agentdata">The agent data to be added</param> /// <returns> /// true if at least one plugin added the user agent. false if no plugin successfully added the agent /// </returns> public virtual bool AddUserAgent(UserAgentData agentdata) { bool result = false; foreach (IUserDataPlugin plugin in m_plugins) { try { plugin.AddNewUserAgent(agentdata); result = true; } catch (Exception e) { m_log.Error("[USERSTORAGE]: Unable to add agent via " + plugin.Name + "(" + e.ToString() + ")"); } } return result; } /// <summary> /// Get avatar appearance information /// </summary> /// <param name="user"></param> /// <returns></returns> public virtual AvatarAppearance GetUserAppearance(UUID user) { foreach (IUserDataPlugin plugin in m_plugins) { try { AvatarAppearance appearance = plugin.GetUserAppearance(user); if (appearance != null) return appearance; } catch (Exception e) { m_log.ErrorFormat( "[USERSTORAGE]: Unable to find user appearance {0} via {1} ({2})", user, plugin.Name, e); } } return null; } public virtual void UpdateUserAppearance(UUID user, AvatarAppearance appearance) { foreach (IUserDataPlugin plugin in m_plugins) { try { plugin.UpdateUserAppearance(user, appearance); } catch (Exception e) { m_log.ErrorFormat("[USERSTORAGE]: Unable to update user appearance {0} via {1} ({2})", user.ToString(), plugin.Name, e.ToString()); } } } #region IAuthentication protected Dictionary<UUID, List<string>> m_userKeys = new Dictionary<UUID, List<string>>(); /// <summary> /// This generates authorization keys in the form /// http://userserver/uuid /// after verifying that the caller is, indeed, authorized to request a key /// </summary> /// <param name="url">URL of the user server</param> /// <param name="userID">The user ID requesting the new key</param> /// <param name="authToken">The original authorization token for that user, obtained during login</param> /// <returns></returns> public string GetNewKey(string url, UUID userID, UUID authToken) { UserProfileData profile = GetUserProfile(userID); string newKey = string.Empty; if (!url.EndsWith("/")) url = url + "/"; if (profile != null) { // I'm overloading webloginkey for this, so that no changes are needed in the DB // The uses of webloginkey are fairly mutually exclusive if (profile.WebLoginKey.Equals(authToken)) { newKey = UUID.Random().ToString(); List<string> keys; lock (m_userKeys) { if (m_userKeys.ContainsKey(userID)) { keys = m_userKeys[userID]; } else { keys = new List<string>(); m_userKeys.Add(userID, keys); } keys.Add(newKey); } m_log.InfoFormat("[USERAUTH]: Successfully generated new auth key for user {0}", userID); } else m_log.Warn("[USERAUTH]: Unauthorized key generation request. Denying new key."); } else m_log.Warn("[USERAUTH]: User not found."); return url + newKey; } /// <summary> /// This verifies the uuid portion of the key given out by GenerateKey /// </summary> /// <param name="userID"></param> /// <param name="key"></param> /// <returns></returns> public bool VerifyKey(UUID userID, string key) { lock (m_userKeys) { if (m_userKeys.ContainsKey(userID)) { List<string> keys = m_userKeys[userID]; if (keys.Contains(key)) { // Keys are one-time only, so remove it keys.Remove(key); return true; } return false; } else return false; } } public virtual bool VerifySession(UUID userID, UUID sessionID) { UserProfileData userProfile = GetUserProfile(userID); if (userProfile != null && userProfile.CurrentAgent != null) { m_log.DebugFormat( "[USER AUTH]: Verifying session {0} for {1}; current session {2}", sessionID, userID, userProfile.CurrentAgent.SessionID); if (userProfile.CurrentAgent.SessionID == sessionID) { return true; } } return false; } public virtual bool AuthenticateUserByPassword(UUID userID, string password) { // m_log.DebugFormat("[USER AUTH]: Authenticating user {0} given password {1}", userID, password); UserProfileData userProfile = GetUserProfile(userID); if (null == userProfile) return false; string md5PasswordHash = Util.Md5Hash(Util.Md5Hash(password) + ":" + userProfile.PasswordSalt); // m_log.DebugFormat( // "[USER AUTH]: Submitted hash {0}, stored hash {1}", md5PasswordHash, userProfile.PasswordHash); if (md5PasswordHash == userProfile.PasswordHash) return true; else return false; } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // using AutoRest.Core; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Threading.Tasks; using AutoRest.Core.Utilities; using Microsoft.CodeAnalysis; using Microsoft.Rest.CSharp.Compiler.Compilation; using Xunit.Abstractions; using OutputKind = Microsoft.Rest.CSharp.Compiler.Compilation.OutputKind; namespace AutoRest.CSharp.Unit.Tests { public class BugTest { private ITestOutputHelper _output; internal static string[] SuppressWarnings = {"CS1701", "CS1591" , "CS1573"}; //Todo: Remove CS1591 when issue https://github.com/Azure/autorest/issues/1387 is fixed internal static string[] VsCode = new string[] { @"C:\Program Files (x86)\Microsoft VS Code Insiders\Code - Insiders.exe", @"C:\Program Files (x86)\Microsoft VS Code\Code.exe" }; internal static char Q = '"'; internal static string Quote(string text) => $"{Q}{text}{Q}"; /// <summary> /// Tries to run VSCode /// </summary> /// <param name="args"></param> internal bool StartVsCode(params object[] args) { ProcessStartInfo startInfo = null; foreach (var exe in VsCode) { if (File.Exists(exe)) { startInfo = new ProcessStartInfo(exe, args.Aggregate( // $@"""{Path.Combine(exe, @"..\resources\app\out\cli.js")}""", "", (s, o) => $"{s} {Q}{o}{Q}")); startInfo.EnvironmentVariables.Add("ATOM_SHELL_INTERNAL_RUN_AS_NODE", "1"); startInfo.UseShellExecute = false; break; } } if (startInfo != null) { return Process.Start(startInfo) != null; } return false; } internal void ShowGeneratedCode(IFileSystem fileSystem) { InspectWithFavoriteCodeEditor(fileSystem.SaveFilesToTemp(GetType().Name)); } internal void InspectWithFavoriteCodeEditor(string folder, FileLinePositionSpan? span = null) { if (span != null) { FileLinePositionSpan s = (FileLinePositionSpan)span; // when working locally on windows we can pop up vs code to see if the code failure. if (!StartVsCode( folder, "-g", $"{Path.Combine(folder, s.Path)}:{s.StartLinePosition.Line + 1}:{s.StartLinePosition.Character + 1}")) { // todo: add code here to try another editor? } } else { StartVsCode(folder); } } public BugTest(ITestOutputHelper output) { _output = output; } public BugTest() { } protected virtual MemoryFileSystem CreateMockFilesystem() { var fs = new MemoryFileSystem(); fs.CopyFile(Path.Combine("Resource", "AutoRest.json"), "AutoRest.json"); return fs; } protected virtual MemoryFileSystem GenerateCodeForTestFromSpec(string codeGenerator = "CSharp", string modeler = "Swagger") { return GenerateCodeForTestFromSpec($"{GetType().Name}", codeGenerator, modeler); } protected virtual MemoryFileSystem GenerateCodeForTestFromSpec(string dirName, string codeGenerator="CSharp", string modeler = "Swagger") { var fs = CreateMockFilesystem(); dirName.GenerateCodeInto(fs, codeGenerator, modeler); return fs; } protected virtual void WriteLine(object value) { if (value != null) { _output?.WriteLine(value.ToString()); Debug.WriteLine(value.ToString()); } else { _output?.WriteLine("<null>"); Debug.WriteLine("<null>"); } } protected virtual void WriteLine(string format, params object[] values) { if (format != null) { if (values != null && values.Length > 0) { _output?.WriteLine(format, values); Debug.WriteLine(format, values); } else { _output?.WriteLine(format); Debug.WriteLine(format); } } else { _output?.WriteLine("<null>"); Debug.WriteLine("<null>"); } } protected void Write(IEnumerable<Diagnostic> messages, MemoryFileSystem fileSystem) { if (messages.Any()) { foreach (var file in messages.GroupBy(each => each.Location?.SourceTree?.FilePath, each => each)) { var text = file.Key != null ? fileSystem.VirtualStore[file.Key].ToString() : string.Empty; foreach (var error in file) { WriteLine(error.ToString()); // WriteLine(text.Substring(error.Location.SourceSpan.Start, error.Location.SourceSpan.Length)); } } } } protected async Task<CompilationResult> Compile(IFileSystem fileSystem) { string dllPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var assemblies = new[] { Path.Combine(dllPath, "Microsoft.Rest.ClientRuntime.dll"), Path.Combine(dllPath, "Microsoft.Rest.ClientRuntime.Azure.dll") }; assemblies = assemblies.ToList().Concat(System.IO.Directory.GetFiles(dllPath, "*.dll", System.IO.SearchOption.TopDirectoryOnly).Where(f => Path.GetFileName(f).StartsWith("Microsoft.AspNetCore."))).ToArray(); var compiler = new CSharpCompiler( fileSystem.GetFiles("GeneratedCode", "*.cs", SearchOption.AllDirectories) .Select(each => new KeyValuePair<string, string>(each, fileSystem.ReadFileAsText(each))).ToArray(), ManagedAssets.FrameworkAssemblies.Concat( AppDomain.CurrentDomain.GetAssemblies() .Where(each => !each.IsDynamic && !string.IsNullOrEmpty(each.Location) ) .Select(each => each.Location) .Concat(assemblies) )); var result = await compiler.Compile(OutputKind.DynamicallyLinkedLibrary); // if it failed compiling and we're in an interactive session if (!result.Succeeded && System.Environment.OSVersion.Platform == PlatformID.Win32NT && System.Environment.UserInteractive) { var error = result.Messages.FirstOrDefault(each => each.Severity == DiagnosticSeverity.Error); if (error != null) { // use this to dump the files to disk for examination // open in Favorite Code Editor InspectWithFavoriteCodeEditor(fileSystem.SaveFilesToTemp(GetType().Name), error.Location.GetMappedLineSpan()); } } return result; } } }
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) using System; using System.Diagnostics; using Org.BouncyCastle.Crypto.Utilities; namespace Org.BouncyCastle.Math.Raw { internal abstract class Nat128 { private const ulong M = 0xFFFFFFFFUL; public static uint Add(uint[] x, uint[] y, uint[] z) { ulong c = 0; c += (ulong)x[0] + y[0]; z[0] = (uint)c; c >>= 32; c += (ulong)x[1] + y[1]; z[1] = (uint)c; c >>= 32; c += (ulong)x[2] + y[2]; z[2] = (uint)c; c >>= 32; c += (ulong)x[3] + y[3]; z[3] = (uint)c; c >>= 32; return (uint)c; } public static uint AddBothTo(uint[] x, uint[] y, uint[] z) { ulong c = 0; c += (ulong)x[0] + y[0] + z[0]; z[0] = (uint)c; c >>= 32; c += (ulong)x[1] + y[1] + z[1]; z[1] = (uint)c; c >>= 32; c += (ulong)x[2] + y[2] + z[2]; z[2] = (uint)c; c >>= 32; c += (ulong)x[3] + y[3] + z[3]; z[3] = (uint)c; c >>= 32; return (uint)c; } public static uint AddTo(uint[] x, uint[] z) { ulong c = 0; c += (ulong)x[0] + z[0]; z[0] = (uint)c; c >>= 32; c += (ulong)x[1] + z[1]; z[1] = (uint)c; c >>= 32; c += (ulong)x[2] + z[2]; z[2] = (uint)c; c >>= 32; c += (ulong)x[3] + z[3]; z[3] = (uint)c; c >>= 32; return (uint)c; } public static uint AddTo(uint[] x, int xOff, uint[] z, int zOff, uint cIn) { ulong c = cIn; c += (ulong)x[xOff + 0] + z[zOff + 0]; z[zOff + 0] = (uint)c; c >>= 32; c += (ulong)x[xOff + 1] + z[zOff + 1]; z[zOff + 1] = (uint)c; c >>= 32; c += (ulong)x[xOff + 2] + z[zOff + 2]; z[zOff + 2] = (uint)c; c >>= 32; c += (ulong)x[xOff + 3] + z[zOff + 3]; z[zOff + 3] = (uint)c; c >>= 32; return (uint)c; } public static uint AddToEachOther(uint[] u, int uOff, uint[] v, int vOff) { ulong c = 0; c += (ulong)u[uOff + 0] + v[vOff + 0]; u[uOff + 0] = (uint)c; v[vOff + 0] = (uint)c; c >>= 32; c += (ulong)u[uOff + 1] + v[vOff + 1]; u[uOff + 1] = (uint)c; v[vOff + 1] = (uint)c; c >>= 32; c += (ulong)u[uOff + 2] + v[vOff + 2]; u[uOff + 2] = (uint)c; v[vOff + 2] = (uint)c; c >>= 32; c += (ulong)u[uOff + 3] + v[vOff + 3]; u[uOff + 3] = (uint)c; v[vOff + 3] = (uint)c; c >>= 32; return (uint)c; } public static void Copy(uint[] x, uint[] z) { z[0] = x[0]; z[1] = x[1]; z[2] = x[2]; z[3] = x[3]; } public static void Copy64(ulong[] x, ulong[] z) { z[0] = x[0]; z[1] = x[1]; } public static uint[] Create() { return new uint[4]; } public static ulong[] Create64() { return new ulong[2]; } public static uint[] CreateExt() { return new uint[8]; } public static ulong[] CreateExt64() { return new ulong[4]; } public static bool Diff(uint[] x, int xOff, uint[] y, int yOff, uint[] z, int zOff) { bool pos = Gte(x, xOff, y, yOff); if (pos) { Sub(x, xOff, y, yOff, z, zOff); } else { Sub(y, yOff, x, xOff, z, zOff); } return pos; } public static bool Eq(uint[] x, uint[] y) { for (int i = 3; i >= 0; --i) { if (x[i] != y[i]) return false; } return true; } public static bool Eq64(ulong[] x, ulong[] y) { for (int i = 1; i >= 0; --i) { if (x[i] != y[i]) return false; } return true; } public static uint[] FromBigInteger(BigInteger x) { if (x.SignValue < 0 || x.BitLength > 128) throw new ArgumentException(); uint[] z = Create(); int i = 0; while (x.SignValue != 0) { z[i++] = (uint)x.IntValue; x = x.ShiftRight(32); } return z; } public static ulong[] FromBigInteger64(BigInteger x) { if (x.SignValue < 0 || x.BitLength > 128) throw new ArgumentException(); ulong[] z = Create64(); int i = 0; while (x.SignValue != 0) { z[i++] = (ulong)x.LongValue; x = x.ShiftRight(64); } return z; } public static uint GetBit(uint[] x, int bit) { if (bit == 0) { return x[0] & 1; } if ((bit & 127) != bit) { return 0; } int w = bit >> 5; int b = bit & 31; return (x[w] >> b) & 1; } public static bool Gte(uint[] x, uint[] y) { for (int i = 3; i >= 0; --i) { uint x_i = x[i], y_i = y[i]; if (x_i < y_i) return false; if (x_i > y_i) return true; } return true; } public static bool Gte(uint[] x, int xOff, uint[] y, int yOff) { for (int i = 3; i >= 0; --i) { uint x_i = x[xOff + i], y_i = y[yOff + i]; if (x_i < y_i) return false; if (x_i > y_i) return true; } return true; } public static bool IsOne(uint[] x) { if (x[0] != 1) { return false; } for (int i = 1; i < 4; ++i) { if (x[i] != 0) { return false; } } return true; } public static bool IsOne64(ulong[] x) { if (x[0] != 1UL) { return false; } for (int i = 1; i < 2; ++i) { if (x[i] != 0UL) { return false; } } return true; } public static bool IsZero(uint[] x) { for (int i = 0; i < 4; ++i) { if (x[i] != 0) { return false; } } return true; } public static bool IsZero64(ulong[] x) { for (int i = 0; i < 2; ++i) { if (x[i] != 0UL) { return false; } } return true; } public static void Mul(uint[] x, uint[] y, uint[] zz) { ulong y_0 = y[0]; ulong y_1 = y[1]; ulong y_2 = y[2]; ulong y_3 = y[3]; { ulong c = 0, x_0 = x[0]; c += x_0 * y_0; zz[0] = (uint)c; c >>= 32; c += x_0 * y_1; zz[1] = (uint)c; c >>= 32; c += x_0 * y_2; zz[2] = (uint)c; c >>= 32; c += x_0 * y_3; zz[3] = (uint)c; c >>= 32; zz[4] = (uint)c; } for (int i = 1; i < 4; ++i) { ulong c = 0, x_i = x[i]; c += x_i * y_0 + zz[i + 0]; zz[i + 0] = (uint)c; c >>= 32; c += x_i * y_1 + zz[i + 1]; zz[i + 1] = (uint)c; c >>= 32; c += x_i * y_2 + zz[i + 2]; zz[i + 2] = (uint)c; c >>= 32; c += x_i * y_3 + zz[i + 3]; zz[i + 3] = (uint)c; c >>= 32; zz[i + 4] = (uint)c; } } public static void Mul(uint[] x, int xOff, uint[] y, int yOff, uint[] zz, int zzOff) { ulong y_0 = y[yOff + 0]; ulong y_1 = y[yOff + 1]; ulong y_2 = y[yOff + 2]; ulong y_3 = y[yOff + 3]; { ulong c = 0, x_0 = x[xOff + 0]; c += x_0 * y_0; zz[zzOff + 0] = (uint)c; c >>= 32; c += x_0 * y_1; zz[zzOff + 1] = (uint)c; c >>= 32; c += x_0 * y_2; zz[zzOff + 2] = (uint)c; c >>= 32; c += x_0 * y_3; zz[zzOff + 3] = (uint)c; c >>= 32; zz[zzOff + 4] = (uint)c; } for (int i = 1; i < 4; ++i) { ++zzOff; ulong c = 0, x_i = x[xOff + i]; c += x_i * y_0 + zz[zzOff + 0]; zz[zzOff + 0] = (uint)c; c >>= 32; c += x_i * y_1 + zz[zzOff + 1]; zz[zzOff + 1] = (uint)c; c >>= 32; c += x_i * y_2 + zz[zzOff + 2]; zz[zzOff + 2] = (uint)c; c >>= 32; c += x_i * y_3 + zz[zzOff + 3]; zz[zzOff + 3] = (uint)c; c >>= 32; zz[zzOff + 4] = (uint)c; } } public static uint MulAddTo(uint[] x, uint[] y, uint[] zz) { ulong y_0 = y[0]; ulong y_1 = y[1]; ulong y_2 = y[2]; ulong y_3 = y[3]; ulong zc = 0; for (int i = 0; i < 4; ++i) { ulong c = 0, x_i = x[i]; c += x_i * y_0 + zz[i + 0]; zz[i + 0] = (uint)c; c >>= 32; c += x_i * y_1 + zz[i + 1]; zz[i + 1] = (uint)c; c >>= 32; c += x_i * y_2 + zz[i + 2]; zz[i + 2] = (uint)c; c >>= 32; c += x_i * y_3 + zz[i + 3]; zz[i + 3] = (uint)c; c >>= 32; c += zc + zz[i + 4]; zz[i + 4] = (uint)c; zc = c >> 32; } return (uint)zc; } public static uint MulAddTo(uint[] x, int xOff, uint[] y, int yOff, uint[] zz, int zzOff) { ulong y_0 = y[yOff + 0]; ulong y_1 = y[yOff + 1]; ulong y_2 = y[yOff + 2]; ulong y_3 = y[yOff + 3]; ulong zc = 0; for (int i = 0; i < 4; ++i) { ulong c = 0, x_i = x[xOff + i]; c += x_i * y_0 + zz[zzOff + 0]; zz[zzOff + 0] = (uint)c; c >>= 32; c += x_i * y_1 + zz[zzOff + 1]; zz[zzOff + 1] = (uint)c; c >>= 32; c += x_i * y_2 + zz[zzOff + 2]; zz[zzOff + 2] = (uint)c; c >>= 32; c += x_i * y_3 + zz[zzOff + 3]; zz[zzOff + 3] = (uint)c; c >>= 32; c += zc + zz[zzOff + 4]; zz[zzOff + 4] = (uint)c; zc = c >> 32; ++zzOff; } return (uint)zc; } public static ulong Mul33Add(uint w, uint[] x, int xOff, uint[] y, int yOff, uint[] z, int zOff) { Debug.Assert(w >> 31 == 0); ulong c = 0, wVal = w; ulong x0 = x[xOff + 0]; c += wVal * x0 + y[yOff + 0]; z[zOff + 0] = (uint)c; c >>= 32; ulong x1 = x[xOff + 1]; c += wVal * x1 + x0 + y[yOff + 1]; z[zOff + 1] = (uint)c; c >>= 32; ulong x2 = x[xOff + 2]; c += wVal * x2 + x1 + y[yOff + 2]; z[zOff + 2] = (uint)c; c >>= 32; ulong x3 = x[xOff + 3]; c += wVal * x3 + x2 + y[yOff + 3]; z[zOff + 3] = (uint)c; c >>= 32; c += x3; return c; } public static uint MulWordAddExt(uint x, uint[] yy, int yyOff, uint[] zz, int zzOff) { Debug.Assert(yyOff <= 4); Debug.Assert(zzOff <= 4); ulong c = 0, xVal = x; c += xVal * yy[yyOff + 0] + zz[zzOff + 0]; zz[zzOff + 0] = (uint)c; c >>= 32; c += xVal * yy[yyOff + 1] + zz[zzOff + 1]; zz[zzOff + 1] = (uint)c; c >>= 32; c += xVal * yy[yyOff + 2] + zz[zzOff + 2]; zz[zzOff + 2] = (uint)c; c >>= 32; c += xVal * yy[yyOff + 3] + zz[zzOff + 3]; zz[zzOff + 3] = (uint)c; c >>= 32; return (uint)c; } public static uint Mul33DWordAdd(uint x, ulong y, uint[] z, int zOff) { Debug.Assert(x >> 31 == 0); Debug.Assert(zOff <= 0); ulong c = 0, xVal = x; ulong y00 = y & M; c += xVal * y00 + z[zOff + 0]; z[zOff + 0] = (uint)c; c >>= 32; ulong y01 = y >> 32; c += xVal * y01 + y00 + z[zOff + 1]; z[zOff + 1] = (uint)c; c >>= 32; c += y01 + z[zOff + 2]; z[zOff + 2] = (uint)c; c >>= 32; c += z[zOff + 3]; z[zOff + 3] = (uint)c; c >>= 32; return (uint)c; } public static uint Mul33WordAdd(uint x, uint y, uint[] z, int zOff) { Debug.Assert(x >> 31 == 0); Debug.Assert(zOff <= 1); ulong c = 0, yVal = y; c += yVal * x + z[zOff + 0]; z[zOff + 0] = (uint)c; c >>= 32; c += yVal + z[zOff + 1]; z[zOff + 1] = (uint)c; c >>= 32; c += z[zOff + 2]; z[zOff + 2] = (uint)c; c >>= 32; return c == 0 ? 0 : Nat.IncAt(4, z, zOff, 3); } public static uint MulWordDwordAdd(uint x, ulong y, uint[] z, int zOff) { Debug.Assert(zOff <= 1); ulong c = 0, xVal = x; c += xVal * y + z[zOff + 0]; z[zOff + 0] = (uint)c; c >>= 32; c += xVal * (y >> 32) + z[zOff + 1]; z[zOff + 1] = (uint)c; c >>= 32; c += z[zOff + 2]; z[zOff + 2] = (uint)c; c >>= 32; return c == 0 ? 0 : Nat.IncAt(4, z, zOff, 3); } public static uint MulWordsAdd(uint x, uint y, uint[] z, int zOff) { Debug.Assert(zOff <= 2); ulong c = 0, xVal = x, yVal = y; c += yVal * xVal + z[zOff + 0]; z[zOff + 0] = (uint)c; c >>= 32; c += z[zOff + 1]; z[zOff + 1] = (uint)c; c >>= 32; return c == 0 ? 0 : Nat.IncAt(4, z, zOff, 2); } public static uint MulWord(uint x, uint[] y, uint[] z, int zOff) { ulong c = 0, xVal = x; int i = 0; do { c += xVal * y[i]; z[zOff + i] = (uint)c; c >>= 32; } while (++i < 4); return (uint)c; } public static void Square(uint[] x, uint[] zz) { ulong x_0 = x[0]; ulong zz_1; uint c = 0, w; { int i = 3, j = 8; do { ulong xVal = x[i--]; ulong p = xVal * xVal; zz[--j] = (c << 31) | (uint)(p >> 33); zz[--j] = (uint)(p >> 1); c = (uint)p; } while (i > 0); { ulong p = x_0 * x_0; zz_1 = (ulong)(c << 31) | (p >> 33); zz[0] = (uint)p; c = (uint)(p >> 32) & 1; } } ulong x_1 = x[1]; ulong zz_2 = zz[2]; { zz_1 += x_1 * x_0; w = (uint)zz_1; zz[1] = (w << 1) | c; c = w >> 31; zz_2 += zz_1 >> 32; } ulong x_2 = x[2]; ulong zz_3 = zz[3]; ulong zz_4 = zz[4]; { zz_2 += x_2 * x_0; w = (uint)zz_2; zz[2] = (w << 1) | c; c = w >> 31; zz_3 += (zz_2 >> 32) + x_2 * x_1; zz_4 += zz_3 >> 32; zz_3 &= M; } ulong x_3 = x[3]; ulong zz_5 = zz[5]; ulong zz_6 = zz[6]; { zz_3 += x_3 * x_0; w = (uint)zz_3; zz[3] = (w << 1) | c; c = w >> 31; zz_4 += (zz_3 >> 32) + x_3 * x_1; zz_5 += (zz_4 >> 32) + x_3 * x_2; zz_6 += zz_5 >> 32; } w = (uint)zz_4; zz[4] = (w << 1) | c; c = w >> 31; w = (uint)zz_5; zz[5] = (w << 1) | c; c = w >> 31; w = (uint)zz_6; zz[6] = (w << 1) | c; c = w >> 31; w = zz[7] + (uint)(zz_6 >> 32); zz[7] = (w << 1) | c; } public static void Square(uint[] x, int xOff, uint[] zz, int zzOff) { ulong x_0 = x[xOff + 0]; ulong zz_1; uint c = 0, w; { int i = 3, j = 8; do { ulong xVal = x[xOff + i--]; ulong p = xVal * xVal; zz[zzOff + --j] = (c << 31) | (uint)(p >> 33); zz[zzOff + --j] = (uint)(p >> 1); c = (uint)p; } while (i > 0); { ulong p = x_0 * x_0; zz_1 = (ulong)(c << 31) | (p >> 33); zz[zzOff + 0] = (uint)p; c = (uint)(p >> 32) & 1; } } ulong x_1 = x[xOff + 1]; ulong zz_2 = zz[zzOff + 2]; { zz_1 += x_1 * x_0; w = (uint)zz_1; zz[zzOff + 1] = (w << 1) | c; c = w >> 31; zz_2 += zz_1 >> 32; } ulong x_2 = x[xOff + 2]; ulong zz_3 = zz[zzOff + 3]; ulong zz_4 = zz[zzOff + 4]; { zz_2 += x_2 * x_0; w = (uint)zz_2; zz[zzOff + 2] = (w << 1) | c; c = w >> 31; zz_3 += (zz_2 >> 32) + x_2 * x_1; zz_4 += zz_3 >> 32; zz_3 &= M; } ulong x_3 = x[xOff + 3]; ulong zz_5 = zz[zzOff + 5]; ulong zz_6 = zz[zzOff + 6]; { zz_3 += x_3 * x_0; w = (uint)zz_3; zz[zzOff + 3] = (w << 1) | c; c = w >> 31; zz_4 += (zz_3 >> 32) + x_3 * x_1; zz_5 += (zz_4 >> 32) + x_3 * x_2; zz_6 += zz_5 >> 32; } w = (uint)zz_4; zz[zzOff + 4] = (w << 1) | c; c = w >> 31; w = (uint)zz_5; zz[zzOff + 5] = (w << 1) | c; c = w >> 31; w = (uint)zz_6; zz[zzOff + 6] = (w << 1) | c; c = w >> 31; w = zz[zzOff + 7] + (uint)(zz_6 >> 32); zz[zzOff + 7] = (w << 1) | c; } public static int Sub(uint[] x, uint[] y, uint[] z) { long c = 0; c += (long)x[0] - y[0]; z[0] = (uint)c; c >>= 32; c += (long)x[1] - y[1]; z[1] = (uint)c; c >>= 32; c += (long)x[2] - y[2]; z[2] = (uint)c; c >>= 32; c += (long)x[3] - y[3]; z[3] = (uint)c; c >>= 32; return (int)c; } public static int Sub(uint[] x, int xOff, uint[] y, int yOff, uint[] z, int zOff) { long c = 0; c += (long)x[xOff + 0] - y[yOff + 0]; z[zOff + 0] = (uint)c; c >>= 32; c += (long)x[xOff + 1] - y[yOff + 1]; z[zOff + 1] = (uint)c; c >>= 32; c += (long)x[xOff + 2] - y[yOff + 2]; z[zOff + 2] = (uint)c; c >>= 32; c += (long)x[xOff + 3] - y[yOff + 3]; z[zOff + 3] = (uint)c; c >>= 32; return (int)c; } public static int SubBothFrom(uint[] x, uint[] y, uint[] z) { long c = 0; c += (long)z[0] - x[0] - y[0]; z[0] = (uint)c; c >>= 32; c += (long)z[1] - x[1] - y[1]; z[1] = (uint)c; c >>= 32; c += (long)z[2] - x[2] - y[2]; z[2] = (uint)c; c >>= 32; c += (long)z[3] - x[3] - y[3]; z[3] = (uint)c; c >>= 32; return (int)c; } public static int SubFrom(uint[] x, uint[] z) { long c = 0; c += (long)z[0] - x[0]; z[0] = (uint)c; c >>= 32; c += (long)z[1] - x[1]; z[1] = (uint)c; c >>= 32; c += (long)z[2] - x[2]; z[2] = (uint)c; c >>= 32; c += (long)z[3] - x[3]; z[3] = (uint)c; c >>= 32; return (int)c; } public static int SubFrom(uint[] x, int xOff, uint[] z, int zOff) { long c = 0; c += (long)z[zOff + 0] - x[xOff + 0]; z[zOff + 0] = (uint)c; c >>= 32; c += (long)z[zOff + 1] - x[xOff + 1]; z[zOff + 1] = (uint)c; c >>= 32; c += (long)z[zOff + 2] - x[xOff + 2]; z[zOff + 2] = (uint)c; c >>= 32; c += (long)z[zOff + 3] - x[xOff + 3]; z[zOff + 3] = (uint)c; c >>= 32; return (int)c; } public static BigInteger ToBigInteger(uint[] x) { byte[] bs = new byte[16]; for (int i = 0; i < 4; ++i) { uint x_i = x[i]; if (x_i != 0) { Pack.UInt32_To_BE(x_i, bs, (3 - i) << 2); } } return new BigInteger(1, bs); } public static BigInteger ToBigInteger64(ulong[] x) { byte[] bs = new byte[16]; for (int i = 0; i < 2; ++i) { ulong x_i = x[i]; if (x_i != 0UL) { Pack.UInt64_To_BE(x_i, bs, (1 - i) << 3); } } return new BigInteger(1, bs); } public static void Zero(uint[] z) { z[0] = 0; z[1] = 0; z[2] = 0; z[3] = 0; } } } #endif
// 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.Diagnostics; using System.IO; using System.Net.Http.Headers; using System.Net.Security; using System.Runtime.InteropServices; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Threading.Tasks; using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle; namespace System.Net.Http { #if HTTP_DLL internal enum WindowsProxyUsePolicy #else public enum WindowsProxyUsePolicy #endif { DoNotUseProxy = 0, // Don't use a proxy at all. UseWinHttpProxy = 1, // Use configuration as specified by "netsh winhttp" machine config command. Automatic detect not supported. UseWinInetProxy = 2, // WPAD protocol and PAC files supported. UseCustomProxy = 3 // Use the custom proxy specified in the Proxy property. } #if HTTP_DLL internal enum CookieUsePolicy #else public enum CookieUsePolicy #endif { IgnoreCookies = 0, UseInternalCookieStoreOnly = 1, UseSpecifiedCookieContainer = 2 } #if HTTP_DLL internal class WinHttpHandler : HttpMessageHandler #else public class WinHttpHandler : HttpMessageHandler #endif { // These are normally defined already in System.Net.Primitives as part of the HttpVersion type. // However, these are not part of 'netstandard'. WinHttpHandler currently builds against // 'netstandard' so we need to add these definitions here. internal static readonly Version HttpVersion20 = new Version(2, 0); internal static readonly Version HttpVersionUnknown = new Version(0, 0); private static readonly TimeSpan s_maxTimeout = TimeSpan.FromMilliseconds(int.MaxValue); private static readonly StringWithQualityHeaderValue s_gzipHeaderValue = new StringWithQualityHeaderValue("gzip"); private static readonly StringWithQualityHeaderValue s_deflateHeaderValue = new StringWithQualityHeaderValue("deflate"); [ThreadStatic] private static StringBuilder t_requestHeadersBuilder; private object _lockObject = new object(); private bool _doManualDecompressionCheck = false; private WinInetProxyHelper _proxyHelper = null; private bool _automaticRedirection = HttpHandlerDefaults.DefaultAutomaticRedirection; private int _maxAutomaticRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections; private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression; private CookieUsePolicy _cookieUsePolicy = CookieUsePolicy.UseInternalCookieStoreOnly; private CookieContainer _cookieContainer = null; private SslProtocols _sslProtocols = SslProtocols.None; // Use most secure protocols available. private Func< HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> _serverCertificateValidationCallback = null; private bool _checkCertificateRevocationList = false; private ClientCertificateOption _clientCertificateOption = ClientCertificateOption.Manual; private X509Certificate2Collection _clientCertificates = null; // Only create collection when required. private ICredentials _serverCredentials = null; private bool _preAuthenticate = false; private WindowsProxyUsePolicy _windowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinHttpProxy; private ICredentials _defaultProxyCredentials = null; private IWebProxy _proxy = null; private int _maxConnectionsPerServer = int.MaxValue; private TimeSpan _sendTimeout = TimeSpan.FromSeconds(30); private TimeSpan _receiveHeadersTimeout = TimeSpan.FromSeconds(30); private TimeSpan _receiveDataTimeout = TimeSpan.FromSeconds(30); private int _maxResponseHeadersLength = HttpHandlerDefaults.DefaultMaxResponseHeadersLength; private int _maxResponseDrainSize = 64 * 1024; private IDictionary<string, object> _properties; // Only create dictionary when required. private volatile bool _operationStarted; private volatile bool _disposed; private SafeWinHttpHandle _sessionHandle; private WinHttpAuthHelper _authHelper = new WinHttpAuthHelper(); public WinHttpHandler() { } #region Properties public bool AutomaticRedirection { get { return _automaticRedirection; } set { CheckDisposedOrStarted(); _automaticRedirection = value; } } public int MaxAutomaticRedirections { get { return _maxAutomaticRedirections; } set { if (value <= 0) { throw new ArgumentOutOfRangeException( nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _maxAutomaticRedirections = value; } } public DecompressionMethods AutomaticDecompression { get { return _automaticDecompression; } set { CheckDisposedOrStarted(); _automaticDecompression = value; } } public CookieUsePolicy CookieUsePolicy { get { return _cookieUsePolicy; } set { if (value != CookieUsePolicy.IgnoreCookies && value != CookieUsePolicy.UseInternalCookieStoreOnly && value != CookieUsePolicy.UseSpecifiedCookieContainer) { throw new ArgumentOutOfRangeException(nameof(value)); } CheckDisposedOrStarted(); _cookieUsePolicy = value; } } public CookieContainer CookieContainer { get { return _cookieContainer; } set { CheckDisposedOrStarted(); _cookieContainer = value; } } public SslProtocols SslProtocols { get { return _sslProtocols; } set { CheckDisposedOrStarted(); _sslProtocols = value; } } public Func< HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> ServerCertificateValidationCallback { get { return _serverCertificateValidationCallback; } set { CheckDisposedOrStarted(); _serverCertificateValidationCallback = value; } } public bool CheckCertificateRevocationList { get { return _checkCertificateRevocationList; } set { CheckDisposedOrStarted(); _checkCertificateRevocationList = value; } } public ClientCertificateOption ClientCertificateOption { get { return _clientCertificateOption; } set { if (value != ClientCertificateOption.Manual && value != ClientCertificateOption.Automatic) { throw new ArgumentOutOfRangeException(nameof(value)); } CheckDisposedOrStarted(); _clientCertificateOption = value; } } public X509Certificate2Collection ClientCertificates { get { if (_clientCertificateOption != ClientCertificateOption.Manual) { throw new InvalidOperationException(SR.Format(SR.net_http_invalid_enable_first, "ClientCertificateOptions", "Manual")); } if (_clientCertificates == null) { _clientCertificates = new X509Certificate2Collection(); } return _clientCertificates; } } public bool PreAuthenticate { get { return _preAuthenticate; } set { _preAuthenticate = value; } } public ICredentials ServerCredentials { get { return _serverCredentials; } set { _serverCredentials = value; } } public WindowsProxyUsePolicy WindowsProxyUsePolicy { get { return _windowsProxyUsePolicy; } set { if (value != WindowsProxyUsePolicy.DoNotUseProxy && value != WindowsProxyUsePolicy.UseWinHttpProxy && value != WindowsProxyUsePolicy.UseWinInetProxy && value != WindowsProxyUsePolicy.UseCustomProxy) { throw new ArgumentOutOfRangeException(nameof(value)); } CheckDisposedOrStarted(); _windowsProxyUsePolicy = value; } } public ICredentials DefaultProxyCredentials { get { return _defaultProxyCredentials; } set { CheckDisposedOrStarted(); _defaultProxyCredentials = value; } } public IWebProxy Proxy { get { return _proxy; } set { CheckDisposedOrStarted(); _proxy = value; } } public int MaxConnectionsPerServer { get { return _maxConnectionsPerServer; } set { if (value < 1) { // In WinHTTP, setting this to 0 results in it being reset to 2. // So, we'll only allow settings above 0. throw new ArgumentOutOfRangeException( nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _maxConnectionsPerServer = value; } } public TimeSpan SendTimeout { get { return _sendTimeout; } set { if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout)) { throw new ArgumentOutOfRangeException(nameof(value)); } CheckDisposedOrStarted(); _sendTimeout = value; } } public TimeSpan ReceiveHeadersTimeout { get { return _receiveHeadersTimeout; } set { if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout)) { throw new ArgumentOutOfRangeException(nameof(value)); } CheckDisposedOrStarted(); _receiveHeadersTimeout = value; } } public TimeSpan ReceiveDataTimeout { get { return _receiveDataTimeout; } set { if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout)) { throw new ArgumentOutOfRangeException(nameof(value)); } CheckDisposedOrStarted(); _receiveDataTimeout = value; } } public int MaxResponseHeadersLength { get { return _maxResponseHeadersLength; } set { if (value <= 0) { throw new ArgumentOutOfRangeException( nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _maxResponseHeadersLength = value; } } public int MaxResponseDrainSize { get { return _maxResponseDrainSize; } set { if (value <= 0) { throw new ArgumentOutOfRangeException( nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _maxResponseDrainSize = value; } } public IDictionary<string, object> Properties { get { if (_properties == null) { _properties = new Dictionary<string, object>(); } return _properties; } } #endregion protected override void Dispose(bool disposing) { if (!_disposed) { _disposed = true; if (disposing && _sessionHandle != null) { SafeWinHttpHandle.DisposeAndClearHandle(ref _sessionHandle); } } base.Dispose(disposing); } #if HTTP_DLL protected internal override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) #else protected override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) #endif { if (request == null) { throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest); } // Check for invalid combinations of properties. if (_proxy != null && _windowsProxyUsePolicy != WindowsProxyUsePolicy.UseCustomProxy) { throw new InvalidOperationException(SR.net_http_invalid_proxyusepolicy); } if (_windowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy && _proxy == null) { throw new InvalidOperationException(SR.net_http_invalid_proxy); } if (_cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer && _cookieContainer == null) { throw new InvalidOperationException(SR.net_http_invalid_cookiecontainer); } CheckDisposed(); SetOperationStarted(); TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>(); // Create state object and save current values of handler settings. var state = new WinHttpRequestState(); state.Tcs = tcs; state.CancellationToken = cancellationToken; state.RequestMessage = request; state.Handler = this; state.CheckCertificateRevocationList = _checkCertificateRevocationList; state.ServerCertificateValidationCallback = _serverCertificateValidationCallback; state.WindowsProxyUsePolicy = _windowsProxyUsePolicy; state.Proxy = _proxy; state.ServerCredentials = _serverCredentials; state.DefaultProxyCredentials = _defaultProxyCredentials; state.PreAuthenticate = _preAuthenticate; Task.Factory.StartNew( s => { var whrs = (WinHttpRequestState)s; _ = whrs.Handler.StartRequestAsync(whrs); }, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); return tcs.Task; } private static bool IsChunkedModeForSend(HttpRequestMessage requestMessage) { bool chunkedMode = requestMessage.Headers.TransferEncodingChunked.HasValue && requestMessage.Headers.TransferEncodingChunked.Value; HttpContent requestContent = requestMessage.Content; if (requestContent != null) { if (requestContent.Headers.ContentLength.HasValue) { if (chunkedMode) { // Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics. // Current .NET Desktop HttpClientHandler allows both headers to be specified but ends up // stripping out 'Content-Length' and using chunked semantics. WinHttpHandler will maintain // the same behavior. requestContent.Headers.ContentLength = null; } } else { if (!chunkedMode) { // Neither 'Content-Length' nor 'Transfer-Encoding: chunked' semantics was given. // Current .NET Desktop HttpClientHandler uses 'Content-Length' semantics and // buffers the content as well in some cases. But the WinHttpHandler can't access // the protected internal TryComputeLength() method of the content. So, it // will use'Transfer-Encoding: chunked' semantics. chunkedMode = true; requestMessage.Headers.TransferEncodingChunked = true; } } } else if (chunkedMode) { throw new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content); } return chunkedMode; } private static void AddRequestHeaders( SafeWinHttpHandle requestHandle, HttpRequestMessage requestMessage, CookieContainer cookies, DecompressionMethods manuallyProcessedDecompressionMethods) { // Get a StringBuilder to use for creating the request headers. // We cache one in TLS to avoid creating a new one for each request. StringBuilder requestHeadersBuffer = t_requestHeadersBuilder; if (requestHeadersBuffer != null) { requestHeadersBuffer.Clear(); } else { t_requestHeadersBuilder = requestHeadersBuffer = new StringBuilder(); } // Normally WinHttpHandler will let native WinHTTP add 'Accept-Encoding' request headers // for gzip and/or default as needed based on whether the handler should do automatic // decompression of response content. But on Windows 7, WinHTTP doesn't support this feature. // So, we need to manually add these headers since WinHttpHandler still supports automatic // decompression (by doing it within the handler). if (manuallyProcessedDecompressionMethods != DecompressionMethods.None) { if ((manuallyProcessedDecompressionMethods & DecompressionMethods.GZip) == DecompressionMethods.GZip && !requestMessage.Headers.AcceptEncoding.Contains(s_gzipHeaderValue)) { requestMessage.Headers.AcceptEncoding.Add(s_gzipHeaderValue); } if ((manuallyProcessedDecompressionMethods & DecompressionMethods.Deflate) == DecompressionMethods.Deflate && !requestMessage.Headers.AcceptEncoding.Contains(s_deflateHeaderValue)) { requestMessage.Headers.AcceptEncoding.Add(s_deflateHeaderValue); } } // Manually add cookies. if (cookies != null && cookies.Count > 0) { string cookieHeader = WinHttpCookieContainerAdapter.GetCookieHeader(requestMessage.RequestUri, cookies); if (!string.IsNullOrEmpty(cookieHeader)) { requestHeadersBuffer.AppendLine(cookieHeader); } } // Serialize general request headers. requestHeadersBuffer.AppendLine(requestMessage.Headers.ToString()); // Serialize entity-body (content) headers. if (requestMessage.Content != null) { // TODO (#5523): Content-Length header isn't getting correctly placed using ToString() // This is a bug in HttpContentHeaders that needs to be fixed. if (requestMessage.Content.Headers.ContentLength.HasValue) { long contentLength = requestMessage.Content.Headers.ContentLength.Value; requestMessage.Content.Headers.ContentLength = null; requestMessage.Content.Headers.ContentLength = contentLength; } requestHeadersBuffer.AppendLine(requestMessage.Content.Headers.ToString()); } // Add request headers to WinHTTP request handle. if (!Interop.WinHttp.WinHttpAddRequestHeaders( requestHandle, requestHeadersBuffer, (uint)requestHeadersBuffer.Length, Interop.WinHttp.WINHTTP_ADDREQ_FLAG_ADD)) { WinHttpException.ThrowExceptionUsingLastError(nameof(Interop.WinHttp.WinHttpAddRequestHeaders)); } } private void EnsureSessionHandleExists(WinHttpRequestState state) { if (_sessionHandle == null) { lock (_lockObject) { if (_sessionHandle == null) { SafeWinHttpHandle sessionHandle; uint accessType; // If a custom proxy is specified and it is really the system web proxy // (initial WebRequest.DefaultWebProxy) then we need to update the settings // since that object is only a sentinel. if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy) { Debug.Assert(state.Proxy != null); try { state.Proxy.GetProxy(state.RequestMessage.RequestUri); } catch (PlatformNotSupportedException) { // This is the system web proxy. state.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy; state.Proxy = null; } } if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.DoNotUseProxy || state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy) { // Either no proxy at all or a custom IWebProxy proxy is specified. // For a custom IWebProxy, we'll need to calculate and set the proxy // on a per request handle basis using the request Uri. For now, // we set the session handle to have no proxy. accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY; } else if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseWinHttpProxy) { // Use WinHTTP per-machine proxy settings which are set using the "netsh winhttp" command. accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_DEFAULT_PROXY; } else { // Use WinInet per-user proxy settings. accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY; } if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Proxy accessType={accessType}"); sessionHandle = Interop.WinHttp.WinHttpOpen( IntPtr.Zero, accessType, Interop.WinHttp.WINHTTP_NO_PROXY_NAME, Interop.WinHttp.WINHTTP_NO_PROXY_BYPASS, (int)Interop.WinHttp.WINHTTP_FLAG_ASYNC); if (sessionHandle.IsInvalid) { int lastError = Marshal.GetLastWin32Error(); if (NetEventSource.IsEnabled) NetEventSource.Error(this, $"error={lastError}"); if (lastError != Interop.WinHttp.ERROR_INVALID_PARAMETER) { ThrowOnInvalidHandle(sessionHandle, nameof(Interop.WinHttp.WinHttpOpen)); } // We must be running on a platform earlier than Win8.1/Win2K12R2 which doesn't support // WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY. So, we'll need to read the Wininet style proxy // settings ourself using our WinInetProxyHelper object. _proxyHelper = new WinInetProxyHelper(); sessionHandle = Interop.WinHttp.WinHttpOpen( IntPtr.Zero, _proxyHelper.ManualSettingsOnly ? Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY : Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, _proxyHelper.ManualSettingsOnly ? _proxyHelper.Proxy : Interop.WinHttp.WINHTTP_NO_PROXY_NAME, _proxyHelper.ManualSettingsOnly ? _proxyHelper.ProxyBypass : Interop.WinHttp.WINHTTP_NO_PROXY_BYPASS, (int)Interop.WinHttp.WINHTTP_FLAG_ASYNC); ThrowOnInvalidHandle(sessionHandle, nameof(Interop.WinHttp.WinHttpOpen)); } uint optionAssuredNonBlockingTrue = 1; // TRUE if (!Interop.WinHttp.WinHttpSetOption( sessionHandle, Interop.WinHttp.WINHTTP_OPTION_ASSURED_NON_BLOCKING_CALLBACKS, ref optionAssuredNonBlockingTrue, (uint)sizeof(uint))) { // This option is not available on downlevel Windows versions. While it improves // performance, we can ignore the error that the option is not available. int lastError = Marshal.GetLastWin32Error(); if (lastError != Interop.WinHttp.ERROR_WINHTTP_INVALID_OPTION) { throw WinHttpException.CreateExceptionUsingError(lastError, nameof(Interop.WinHttp.WinHttpSetOption)); } } SetSessionHandleOptions(sessionHandle); _sessionHandle = sessionHandle; } } } } private async Task StartRequestAsync(WinHttpRequestState state) { if (state.CancellationToken.IsCancellationRequested) { state.Tcs.TrySetCanceled(state.CancellationToken); state.ClearSendRequestState(); return; } SafeWinHttpHandle connectHandle = null; try { EnsureSessionHandleExists(state); SetEnableHttp2PlusClientCertificate(state.RequestMessage.RequestUri, state.RequestMessage.Version); // Specify an HTTP server. connectHandle = Interop.WinHttp.WinHttpConnect( _sessionHandle, state.RequestMessage.RequestUri.HostNameType == UriHostNameType.IPv6 ? "[" + state.RequestMessage.RequestUri.IdnHost + "]" : state.RequestMessage.RequestUri.IdnHost, (ushort)state.RequestMessage.RequestUri.Port, 0); ThrowOnInvalidHandle(connectHandle, nameof(Interop.WinHttp.WinHttpConnect)); connectHandle.SetParentHandle(_sessionHandle); // Try to use the requested version if a known/supported version was explicitly requested. // Otherwise, we simply use winhttp's default. string httpVersion = null; if (state.RequestMessage.Version == HttpVersion.Version10) { httpVersion = "HTTP/1.0"; } else if (state.RequestMessage.Version == HttpVersion.Version11) { httpVersion = "HTTP/1.1"; } // Turn off additional URI reserved character escaping (percent-encoding). This matches // .NET Framework behavior. System.Uri establishes the baseline rules for percent-encoding // of reserved characters. uint flags = Interop.WinHttp.WINHTTP_FLAG_ESCAPE_DISABLE; if (state.RequestMessage.RequestUri.Scheme == UriScheme.Https) { flags |= Interop.WinHttp.WINHTTP_FLAG_SECURE; } // Create an HTTP request handle. state.RequestHandle = Interop.WinHttp.WinHttpOpenRequest( connectHandle, state.RequestMessage.Method.Method, state.RequestMessage.RequestUri.PathAndQuery, httpVersion, Interop.WinHttp.WINHTTP_NO_REFERER, Interop.WinHttp.WINHTTP_DEFAULT_ACCEPT_TYPES, flags); ThrowOnInvalidHandle(state.RequestHandle, nameof(Interop.WinHttp.WinHttpOpenRequest)); state.RequestHandle.SetParentHandle(connectHandle); // Set callback function. SetStatusCallback(state.RequestHandle, WinHttpRequestCallback.StaticCallbackDelegate); // Set needed options on the request handle. SetRequestHandleOptions(state); bool chunkedModeForSend = IsChunkedModeForSend(state.RequestMessage); AddRequestHeaders( state.RequestHandle, state.RequestMessage, _cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer ? _cookieContainer : null, _doManualDecompressionCheck ? _automaticDecompression : DecompressionMethods.None); uint proxyAuthScheme = 0; uint serverAuthScheme = 0; state.RetryRequest = false; // The only way to abort pending async operations in WinHTTP is to close the WinHTTP handle. // We will detect a cancellation request on the cancellation token by registering a callback. // If the callback is invoked, then we begin the abort process by disposing the handle. This // will have the side-effect of WinHTTP cancelling any pending I/O and accelerating its callbacks // on the handle and thus releasing the awaiting tasks in the loop below. This helps to provide // a more timely, cooperative, cancellation pattern. using (state.CancellationToken.Register(s => ((WinHttpRequestState)s).RequestHandle.Dispose(), state)) { do { _authHelper.PreAuthenticateRequest(state, proxyAuthScheme); await InternalSendRequestAsync(state); if (state.RequestMessage.Content != null) { await InternalSendRequestBodyAsync(state, chunkedModeForSend).ConfigureAwait(false); } bool receivedResponse = await InternalReceiveResponseHeadersAsync(state) != 0; if (receivedResponse) { // If we're manually handling cookies, we need to add them to the container after // each response has been received. if (state.Handler.CookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer) { WinHttpCookieContainerAdapter.AddResponseCookiesToContainer(state); } _authHelper.CheckResponseForAuthentication( state, ref proxyAuthScheme, ref serverAuthScheme); } } while (state.RetryRequest); } state.CancellationToken.ThrowIfCancellationRequested(); // Since the headers have been read, set the "receive" timeout to be based on each read // call of the response body data. WINHTTP_OPTION_RECEIVE_TIMEOUT sets a timeout on each // lower layer winsock read. uint optionData = unchecked((uint)_receiveDataTimeout.TotalMilliseconds); SetWinHttpOption(state.RequestHandle, Interop.WinHttp.WINHTTP_OPTION_RECEIVE_TIMEOUT, ref optionData); HttpResponseMessage responseMessage = WinHttpResponseParser.CreateResponseMessage(state, _doManualDecompressionCheck ? _automaticDecompression : DecompressionMethods.None); state.Tcs.TrySetResult(responseMessage); // HttpStatusCode cast is needed for 308 Moved Permenantly, which we support but is not included in NetStandard status codes. if (NetEventSource.IsEnabled && ((responseMessage.StatusCode >= HttpStatusCode.MultipleChoices && responseMessage.StatusCode <= HttpStatusCode.SeeOther) || (responseMessage.StatusCode >= HttpStatusCode.RedirectKeepVerb && responseMessage.StatusCode <= (HttpStatusCode)308)) && state.RequestMessage.RequestUri.Scheme == Uri.UriSchemeHttps && responseMessage.Headers.Location?.Scheme == Uri.UriSchemeHttp) { NetEventSource.Error(this, $"Insecure https to http redirect from {state.RequestMessage.RequestUri.ToString()} to {responseMessage.Headers.Location.ToString()} blocked."); } } catch (Exception ex) { HandleAsyncException(state, state.SavedException ?? ex); } finally { SafeWinHttpHandle.DisposeAndClearHandle(ref connectHandle); state.ClearSendRequestState(); } } private void SetSessionHandleOptions(SafeWinHttpHandle sessionHandle) { SetSessionHandleConnectionOptions(sessionHandle); SetSessionHandleTlsOptions(sessionHandle); SetSessionHandleTimeoutOptions(sessionHandle); } private void SetSessionHandleConnectionOptions(SafeWinHttpHandle sessionHandle) { uint optionData = (uint)_maxConnectionsPerServer; SetWinHttpOption(sessionHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_CONNS_PER_SERVER, ref optionData); SetWinHttpOption(sessionHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_CONNS_PER_1_0_SERVER, ref optionData); } private void SetSessionHandleTlsOptions(SafeWinHttpHandle sessionHandle) { uint optionData = 0; SslProtocols sslProtocols = (_sslProtocols == SslProtocols.None) ? SecurityProtocol.DefaultSecurityProtocols : _sslProtocols; #pragma warning disable 0618 // SSL2/SSL3 are deprecated if ((sslProtocols & SslProtocols.Ssl2) != 0) { optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_SSL2; } if ((sslProtocols & SslProtocols.Ssl3) != 0) { optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_SSL3; } #pragma warning restore 0618 if ((sslProtocols & SslProtocols.Tls) != 0) { optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1; } if ((sslProtocols & SslProtocols.Tls11) != 0) { optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1; } if ((sslProtocols & SslProtocols.Tls12) != 0) { optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2; } // As of Win10RS5 there's no public constant for WinHTTP + TLS 1.3 // This library builds against netstandard, which doesn't define the Tls13 enum field. // If only unknown values (e.g. TLS 1.3) were asked for, report ERROR_INVALID_PARAMETER. if (optionData == 0) { throw WinHttpException.CreateExceptionUsingError( unchecked((int)Interop.WinHttp.ERROR_INVALID_PARAMETER), nameof(SetSessionHandleTlsOptions)); } SetWinHttpOption(sessionHandle, Interop.WinHttp.WINHTTP_OPTION_SECURE_PROTOCOLS, ref optionData); } private void SetSessionHandleTimeoutOptions(SafeWinHttpHandle sessionHandle) { if (!Interop.WinHttp.WinHttpSetTimeouts( sessionHandle, 0, 0, (int)_sendTimeout.TotalMilliseconds, (int)_receiveHeadersTimeout.TotalMilliseconds)) { WinHttpException.ThrowExceptionUsingLastError(nameof(Interop.WinHttp.WinHttpSetTimeouts)); } } private void SetRequestHandleOptions(WinHttpRequestState state) { SetRequestHandleProxyOptions(state); SetRequestHandleDecompressionOptions(state.RequestHandle); SetRequestHandleRedirectionOptions(state.RequestHandle); SetRequestHandleCookieOptions(state.RequestHandle); SetRequestHandleTlsOptions(state.RequestHandle); SetRequestHandleClientCertificateOptions(state.RequestHandle, state.RequestMessage.RequestUri, state.RequestMessage.Version); SetRequestHandleCredentialsOptions(state); SetRequestHandleBufferingOptions(state.RequestHandle); SetRequestHandleHttp2Options(state.RequestHandle, state.RequestMessage.Version); } private void SetRequestHandleProxyOptions(WinHttpRequestState state) { // We've already set the proxy on the session handle if we're using no proxy or default proxy settings. // We only need to change it on the request handle if we have a specific IWebProxy or need to manually // implement Wininet-style auto proxy detection. if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy || state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseWinInetProxy) { var proxyInfo = new Interop.WinHttp.WINHTTP_PROXY_INFO(); bool updateProxySettings = false; Uri uri = state.RequestMessage.RequestUri; try { if (state.Proxy != null) { Debug.Assert(state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy); updateProxySettings = true; if (state.Proxy.IsBypassed(uri)) { proxyInfo.AccessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY; } else { proxyInfo.AccessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY; Uri proxyUri = state.Proxy.GetProxy(uri); string proxyString = proxyUri.Scheme + "://" + proxyUri.Authority; proxyInfo.Proxy = Marshal.StringToHGlobalUni(proxyString); } } else if (_proxyHelper != null && _proxyHelper.AutoSettingsUsed) { if (_proxyHelper.GetProxyForUrl(_sessionHandle, uri, out proxyInfo)) { updateProxySettings = true; } } if (updateProxySettings) { GCHandle pinnedHandle = GCHandle.Alloc(proxyInfo, GCHandleType.Pinned); try { SetWinHttpOption( state.RequestHandle, Interop.WinHttp.WINHTTP_OPTION_PROXY, pinnedHandle.AddrOfPinnedObject(), (uint)Marshal.SizeOf(proxyInfo)); } finally { pinnedHandle.Free(); } } } finally { Marshal.FreeHGlobal(proxyInfo.Proxy); Marshal.FreeHGlobal(proxyInfo.ProxyBypass); } } } private void SetRequestHandleDecompressionOptions(SafeWinHttpHandle requestHandle) { uint optionData = 0; if (_automaticDecompression != DecompressionMethods.None) { if ((_automaticDecompression & DecompressionMethods.GZip) != 0) { optionData |= Interop.WinHttp.WINHTTP_DECOMPRESSION_FLAG_GZIP; } if ((_automaticDecompression & DecompressionMethods.Deflate) != 0) { optionData |= Interop.WinHttp.WINHTTP_DECOMPRESSION_FLAG_DEFLATE; } try { SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_DECOMPRESSION, ref optionData); } catch (WinHttpException ex) { if (ex.NativeErrorCode != (int)Interop.WinHttp.ERROR_WINHTTP_INVALID_OPTION) { throw; } // We are running on a platform earlier than Win8.1 for which WINHTTP.DLL // doesn't support this option. So, we'll have to do the decompression // manually. _doManualDecompressionCheck = true; } } } private void SetRequestHandleRedirectionOptions(SafeWinHttpHandle requestHandle) { uint optionData = 0; if (_automaticRedirection) { optionData = (uint)_maxAutomaticRedirections; SetWinHttpOption( requestHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_HTTP_AUTOMATIC_REDIRECTS, ref optionData); } optionData = _automaticRedirection ? Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP : Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY_NEVER; SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY, ref optionData); } private void SetRequestHandleCookieOptions(SafeWinHttpHandle requestHandle) { if (_cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer || _cookieUsePolicy == CookieUsePolicy.IgnoreCookies) { uint optionData = Interop.WinHttp.WINHTTP_DISABLE_COOKIES; SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_DISABLE_FEATURE, ref optionData); } } private void SetRequestHandleTlsOptions(SafeWinHttpHandle requestHandle) { // If we have a custom server certificate validation callback method then // we need to have WinHTTP ignore some errors so that the callback method // will have a chance to be called. uint optionData; if (_serverCertificateValidationCallback != null) { optionData = Interop.WinHttp.SECURITY_FLAG_IGNORE_UNKNOWN_CA | Interop.WinHttp.SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE | Interop.WinHttp.SECURITY_FLAG_IGNORE_CERT_CN_INVALID | Interop.WinHttp.SECURITY_FLAG_IGNORE_CERT_DATE_INVALID; SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_SECURITY_FLAGS, ref optionData); } else if (_checkCertificateRevocationList) { // If no custom validation method, then we let WinHTTP do the revocation check itself. optionData = Interop.WinHttp.WINHTTP_ENABLE_SSL_REVOCATION; SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_ENABLE_FEATURE, ref optionData); } } private void SetRequestHandleClientCertificateOptions(SafeWinHttpHandle requestHandle, Uri requestUri, Version requestVersion) { if (requestUri.Scheme != UriScheme.Https) { return; } X509Certificate2 clientCertificate = null; if (_clientCertificateOption == ClientCertificateOption.Manual) { clientCertificate = CertificateHelper.GetEligibleClientCertificate(ClientCertificates); } else { clientCertificate = CertificateHelper.GetEligibleClientCertificate(); } if (clientCertificate != null) { SetWinHttpOption( requestHandle, Interop.WinHttp.WINHTTP_OPTION_CLIENT_CERT_CONTEXT, clientCertificate.Handle, (uint)Marshal.SizeOf<Interop.Crypt32.CERT_CONTEXT>()); } else { SetNoClientCertificate(requestHandle); } } private void SetEnableHttp2PlusClientCertificate(Uri requestUri, Version requestVersion) { if (requestUri.Scheme != UriScheme.Https || requestVersion != HttpVersion20) { return; } // Newer versions of WinHTTP fully support HTTP/2 with TLS client certificates. // But the support must be opted in. uint optionData = Interop.WinHttp.WINHTTP_HTTP2_PLUS_CLIENT_CERT_FLAG; if (Interop.WinHttp.WinHttpSetOption( _sessionHandle, Interop.WinHttp.WINHTTP_OPTION_ENABLE_HTTP2_PLUS_CLIENT_CERT, ref optionData)) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, "HTTP/2 with TLS client cert supported"); } else { if (NetEventSource.IsEnabled) NetEventSource.Info(this, "HTTP/2 with TLS client cert not supported"); } } internal static void SetNoClientCertificate(SafeWinHttpHandle requestHandle) { SetWinHttpOption( requestHandle, Interop.WinHttp.WINHTTP_OPTION_CLIENT_CERT_CONTEXT, IntPtr.Zero, 0); } private void SetRequestHandleCredentialsOptions(WinHttpRequestState state) { // By default, WinHTTP sets the default credentials policy such that it automatically sends default credentials // (current user's logged on Windows credentials) to a proxy when needed (407 response). It only sends // default credentials to a server (401 response) if the server is considered to be on the Intranet. // WinHttpHandler uses a more granual opt-in model for using default credentials that can be different between // proxy and server credentials. It will explicitly allow default credentials to be sent at a later stage in // the request processing (after getting a 401/407 response) when the proxy or server credential is set as // CredentialCache.DefaultNetworkCredential. For now, we set the policy to prevent any default credentials // from being automatically sent until we get a 401/407 response. _authHelper.ChangeDefaultCredentialsPolicy( state.RequestHandle, Interop.WinHttp.WINHTTP_AUTH_TARGET_SERVER, allowDefaultCredentials:false); } private void SetRequestHandleBufferingOptions(SafeWinHttpHandle requestHandle) { uint optionData = (uint)(_maxResponseHeadersLength * 1024); SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_RESPONSE_HEADER_SIZE, ref optionData); optionData = (uint)_maxResponseDrainSize; SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_RESPONSE_DRAIN_SIZE, ref optionData); } private void SetRequestHandleHttp2Options(SafeWinHttpHandle requestHandle, Version requestVersion) { Debug.Assert(requestHandle != null); uint optionData = (requestVersion == HttpVersion20) ? Interop.WinHttp.WINHTTP_PROTOCOL_FLAG_HTTP2 : 0; if (Interop.WinHttp.WinHttpSetOption( requestHandle, Interop.WinHttp.WINHTTP_OPTION_ENABLE_HTTP_PROTOCOL, ref optionData)) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"HTTP/2 option supported, setting to {optionData}"); } else { if (NetEventSource.IsEnabled) NetEventSource.Info(this, "HTTP/2 option not supported"); } } private void SetWinHttpOption(SafeWinHttpHandle handle, uint option, ref uint optionData) { Debug.Assert(handle != null); if (!Interop.WinHttp.WinHttpSetOption( handle, option, ref optionData)) { WinHttpException.ThrowExceptionUsingLastError(nameof(Interop.WinHttp.WinHttpSetOption)); } } private static void SetWinHttpOption( SafeWinHttpHandle handle, uint option, IntPtr optionData, uint optionSize) { Debug.Assert(handle != null); if (!Interop.WinHttp.WinHttpSetOption( handle, option, optionData, optionSize)) { WinHttpException.ThrowExceptionUsingLastError(nameof(Interop.WinHttp.WinHttpSetOption)); } } private void HandleAsyncException(WinHttpRequestState state, Exception ex) { if (state.CancellationToken.IsCancellationRequested) { // If the exception was due to the cancellation token being canceled, throw cancellation exception. state.Tcs.TrySetCanceled(state.CancellationToken); } else if (ex is WinHttpException || ex is IOException || ex is InvalidOperationException) { // Wrap expected exceptions as HttpRequestExceptions since this is considered an error during // execution. All other exception types, including ArgumentExceptions and ProtocolViolationExceptions // are 'unexpected' or caused by user error and should not be wrapped. state.Tcs.TrySetException(new HttpRequestException(SR.net_http_client_execution_error, ex)); } else { state.Tcs.TrySetException(ex); } } private void SetOperationStarted() { if (!_operationStarted) { _operationStarted = true; } } private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(GetType().FullName); } } private void CheckDisposedOrStarted() { CheckDisposed(); if (_operationStarted) { throw new InvalidOperationException(SR.net_http_operation_started); } } private void SetStatusCallback( SafeWinHttpHandle requestHandle, Interop.WinHttp.WINHTTP_STATUS_CALLBACK callback) { const uint notificationFlags = Interop.WinHttp.WINHTTP_CALLBACK_FLAG_ALL_COMPLETIONS | Interop.WinHttp.WINHTTP_CALLBACK_FLAG_HANDLES | Interop.WinHttp.WINHTTP_CALLBACK_FLAG_REDIRECT | Interop.WinHttp.WINHTTP_CALLBACK_FLAG_SEND_REQUEST; IntPtr oldCallback = Interop.WinHttp.WinHttpSetStatusCallback( requestHandle, callback, notificationFlags, IntPtr.Zero); if (oldCallback == new IntPtr(Interop.WinHttp.WINHTTP_INVALID_STATUS_CALLBACK)) { int lastError = Marshal.GetLastWin32Error(); if (lastError != Interop.WinHttp.ERROR_INVALID_HANDLE) // Ignore error if handle was already closed. { throw WinHttpException.CreateExceptionUsingError(lastError, nameof(Interop.WinHttp.WinHttpSetStatusCallback)); } } } private void ThrowOnInvalidHandle(SafeWinHttpHandle handle, string nameOfCalledFunction) { if (handle.IsInvalid) { int lastError = Marshal.GetLastWin32Error(); if (NetEventSource.IsEnabled) NetEventSource.Error(this, $"error={lastError}"); throw WinHttpException.CreateExceptionUsingError(lastError, nameOfCalledFunction); } } private RendezvousAwaitable<int> InternalSendRequestAsync(WinHttpRequestState state) { lock (state.Lock) { state.Pin(); if (!Interop.WinHttp.WinHttpSendRequest( state.RequestHandle, null, 0, IntPtr.Zero, 0, 0, state.ToIntPtr())) { // WinHTTP doesn't always associate our context value (state object) to the request handle. // And thus we might not get a HANDLE_CLOSING notification which would normally cause the // state object to be unpinned and disposed. So, we manually dispose the request handle and // state object here. state.RequestHandle.Dispose(); state.Dispose(); WinHttpException.ThrowExceptionUsingLastError(nameof(Interop.WinHttp.WinHttpSendRequest)); } } return state.LifecycleAwaitable; } private async Task InternalSendRequestBodyAsync(WinHttpRequestState state, bool chunkedModeForSend) { using (var requestStream = new WinHttpRequestStream(state, chunkedModeForSend)) { await state.RequestMessage.Content.CopyToAsync( requestStream, state.TransportContext #if HTTP_DLL , state.CancellationToken #endif ).ConfigureAwait(false); await requestStream.EndUploadAsync(state.CancellationToken).ConfigureAwait(false); } } private RendezvousAwaitable<int> InternalReceiveResponseHeadersAsync(WinHttpRequestState state) { lock (state.Lock) { if (!Interop.WinHttp.WinHttpReceiveResponse(state.RequestHandle, IntPtr.Zero)) { throw WinHttpException.CreateExceptionUsingLastError(nameof(Interop.WinHttp.WinHttpReceiveResponse)); } } return state.LifecycleAwaitable; } } }
#region Copyright (c) 2003-2005, Luke T. Maxon /******************************************************************************************************************** ' ' Copyright (c) 2003-2005, Luke T. Maxon ' All rights reserved. ' ' Redistribution and use in source and binary forms, with or without modification, are permitted provided ' that the following conditions are met: ' ' * Redistributions of source code must retain the above copyright notice, this list of conditions and the ' following disclaimer. ' ' * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and ' the following disclaimer in the documentation and/or other materials provided with the distribution. ' ' * Neither the name of the author 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.ComponentModel; using System.Drawing; using System.Windows.Forms; namespace Xunit.Extensions.Forms.TestApplications { /// <summary> /// Summary description for RadioButtonTestForm. /// </summary> public class RadioButtonTestForm : Form { /// <summary> /// Required designer variable. /// </summary> private Container components = null; private GroupBox grpColors; private Label lblSelectedColor; private RadioButton rbBlue; private RadioButton rbGreen; private RadioButton rbIndigo; private RadioButton rbOrange; private RadioButton rbRed; private RadioButton rbViolet; private RadioButton rbYellow; public RadioButtonTestForm() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } private void rb_CheckedChanged(object sender, EventArgs e) { RadioButton rb = (RadioButton) sender; lblSelectedColor.Text = (string) rb.Tag; } private void RadioButtonTestForm_Load(object sender, EventArgs e) { rbRed.Tag = "Red"; rbOrange.Tag = "Orange"; rbGreen.Tag = "Green"; rbYellow.Tag = "Yellow"; rbBlue.Tag = "Blue"; rbIndigo.Tag = "Indigo"; rbViolet.Tag = "Violet"; } #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.grpColors = new GroupBox(); this.rbViolet = new RadioButton(); this.rbIndigo = new RadioButton(); this.rbBlue = new RadioButton(); this.rbYellow = new RadioButton(); this.rbGreen = new RadioButton(); this.rbOrange = new RadioButton(); this.rbRed = new RadioButton(); this.lblSelectedColor = new Label(); this.grpColors.SuspendLayout(); this.SuspendLayout(); // // grpColors // this.grpColors.Controls.Add(this.rbViolet); this.grpColors.Controls.Add(this.rbIndigo); this.grpColors.Controls.Add(this.rbBlue); this.grpColors.Controls.Add(this.rbYellow); this.grpColors.Controls.Add(this.rbGreen); this.grpColors.Controls.Add(this.rbOrange); this.grpColors.Controls.Add(this.rbRed); this.grpColors.Location = new Point(8, 16); this.grpColors.Name = "grpColors"; this.grpColors.Size = new Size(272, 248); this.grpColors.TabIndex = 0; this.grpColors.TabStop = false; this.grpColors.Text = "Colors"; // // rbViolet // this.rbViolet.Location = new Point(8, 208); this.rbViolet.Name = "rbViolet"; this.rbViolet.TabIndex = 6; this.rbViolet.Text = "Violet"; this.rbViolet.Click += new EventHandler(this.rb_CheckedChanged); // // rbIndigo // this.rbIndigo.Location = new Point(8, 176); this.rbIndigo.Name = "rbIndigo"; this.rbIndigo.TabIndex = 5; this.rbIndigo.Text = "Indigo"; this.rbIndigo.Click += new EventHandler(this.rb_CheckedChanged); // // rbBlue // this.rbBlue.Location = new Point(8, 144); this.rbBlue.Name = "rbBlue"; this.rbBlue.TabIndex = 4; this.rbBlue.Text = "Blue"; this.rbBlue.Click += new EventHandler(this.rb_CheckedChanged); // // rbYellow // this.rbYellow.Location = new Point(8, 112); this.rbYellow.Name = "rbYellow"; this.rbYellow.TabIndex = 3; this.rbYellow.Text = "Yellow"; this.rbYellow.Click += new EventHandler(this.rb_CheckedChanged); // // rbGreen // this.rbGreen.Location = new Point(8, 80); this.rbGreen.Name = "rbGreen"; this.rbGreen.TabIndex = 2; this.rbGreen.Text = "Green"; this.rbGreen.Click += new EventHandler(this.rb_CheckedChanged); // // rbOrange // this.rbOrange.Location = new Point(8, 48); this.rbOrange.Name = "rbOrange"; this.rbOrange.TabIndex = 1; this.rbOrange.Text = "Orange"; this.rbOrange.Click += new EventHandler(this.rb_CheckedChanged); // // rbRed // this.rbRed.Location = new Point(8, 16); this.rbRed.Name = "rbRed"; this.rbRed.TabIndex = 0; this.rbRed.Text = "Red"; this.rbRed.CheckedChanged += new EventHandler(this.rb_CheckedChanged); // // lblSelectedColor // this.lblSelectedColor.Location = new Point(8, 288); this.lblSelectedColor.Name = "lblSelectedColor"; this.lblSelectedColor.TabIndex = 1; // // RadioButtonTestForm // this.AutoScaleDimensions = new SizeF(6, 15); this.ClientSize = new Size(292, 336); this.Controls.Add(this.lblSelectedColor); this.Controls.Add(this.grpColors); this.Name = "RadioButtonTestForm"; this.Text = "RadioButtonTestForm"; this.Load += new EventHandler(this.RadioButtonTestForm_Load); this.grpColors.ResumeLayout(false); this.ResumeLayout(false); } #endregion } }
#region License /* Copyright (c) 2016 VulkaNet Project - Daniil Rodin Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using System; using System.Collections.Generic; namespace VulkaNet { public interface IVkCommandBuffer : IVkHandledObject, IVkDeviceChild { VkCommandBuffer.HandleType Handle { get; } VkResult Reset(VkCommandBufferResetFlags flags); VkResult Begin(VkCommandBufferBeginInfo beginInfo); VkResult End(); void CmdExecuteCommands(IReadOnlyList<IVkCommandBuffer> commandBuffers); void CmdSetEvent(IVkEvent eventObj, VkPipelineStageFlags stageMask); void CmdResetEvent(IVkEvent eventObj, VkPipelineStageFlags stageMask); void CmdWaitEvents(IReadOnlyList<IVkEvent> events, VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask, IReadOnlyList<VkMemoryBarrier> memoryBarriers, IReadOnlyList<VkBufferMemoryBarrier> bufferMemoryBarriers, IReadOnlyList<VkImageMemoryBarrier> imageMemoryBarriers); void CmdPipelineBarrier(VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags, IReadOnlyList<VkMemoryBarrier> memoryBarriers, IReadOnlyList<VkBufferMemoryBarrier> bufferMemoryBarriers, IReadOnlyList<VkImageMemoryBarrier> imageMemoryBarriers); void CmdBeginRenderPass(VkRenderPassBeginInfo renderPassBegin, VkSubpassContents contents); void CmdEndRenderPass(); void CmdNextSubpass(VkSubpassContents contents); void CmdBindPipeline(VkPipelineBindPoint pipelineBindPoint, IVkPipeline pipeline); void CmdBindDescriptorSets(VkPipelineBindPoint pipelineBindPoint, IVkPipelineLayout layout, int firstSet, IReadOnlyList<IVkDescriptorSet> descriptorSets, IReadOnlyList<int> dynamicOffsets); void CmdPushConstants(IVkPipelineLayout layout, VkShaderStage stageFlags, int offset, int size, IntPtr values); void CmdResetQueryPool(IVkQueryPool queryPool, int firstQuery, int queryCount); void CmdBeginQuery(IVkQueryPool queryPool, int query, VkQueryControlFlags flags); void CmdEndQuery(IVkQueryPool queryPool, int query); void CmdCopyQueryPoolResults(IVkQueryPool queryPool, int firstQuery, int queryCount, IVkBuffer dstBuffer, ulong dstOffset, ulong stride, VkQueryResultFlags flags); void CmdWriteTimestamp(VkPipelineStageFlags pipelineStage, IVkQueryPool queryPool, int query); void CmdClearColorImage(IVkImage image, VkImageLayout imageLayout, VkClearColorValue color, IReadOnlyList<VkImageSubresourceRange> ranges); void CmdClearDepthStencilImage(IVkImage image, VkImageLayout imageLayout, VkClearDepthStencilValue depthStencil, IReadOnlyList<VkImageSubresourceRange> ranges); void CmdClearAttachments(IReadOnlyList<VkClearAttachment> attachments, IReadOnlyList<VkClearRect> rects); void CmdFillBuffer(IVkBuffer dstBuffer, ulong dstOffset, ulong size, int data); void CmdUpdateBuffer(IVkBuffer dstBuffer, ulong dstOffset, ulong dataSize, IntPtr data); void CmdCopyBuffer(IVkBuffer srcBuffer, IVkBuffer dstBuffer, IReadOnlyList<VkBufferCopy> regions); void CmdCopyImage(IVkImage srcImage, VkImageLayout srcImageLayout, IVkImage dstImage, VkImageLayout dstImageLayout, IReadOnlyList<VkImageCopy> regions); void CmdCopyBufferToImage(IVkBuffer srcBuffer, IVkImage dstImage, VkImageLayout dstImageLayout, IReadOnlyList<VkBufferImageCopy> regions); void CmdCopyImageToBuffer(IVkImage srcImage, VkImageLayout srcImageLayout, IVkBuffer dstBuffer, IReadOnlyList<VkBufferImageCopy> regions); void CmdBlitImage(IVkImage srcImage, VkImageLayout srcImageLayout, IVkImage dstImage, VkImageLayout dstImageLayout, IReadOnlyList<VkImageBlit> regions, VkFilter filter); void CmdResolveImage(IVkImage srcImage, VkImageLayout srcImageLayout, IVkImage dstImage, VkImageLayout dstImageLayout, IReadOnlyList<VkImageResolve> regions); void CmdBindIndexBuffer(IVkBuffer buffer, ulong offset, VkIndexType indexType); void CmdDraw(int vertexCount, int instanceCount, int firstVertex, int firstInstance); void CmdDrawIndexed(int indexCount, int instanceCount, int firstIndex, int vertexOffset, int firstInstance); void CmdDrawIndirect(IVkBuffer buffer, ulong offset, int drawCount, int stride); void CmdDrawIndexedIndirect(IVkBuffer buffer, ulong offset, int drawCount, int stride); void CmdBindVertexBuffers(int firstBinding, IReadOnlyList<IVkBuffer> buffers, IReadOnlyList<ulong> offsets); void CmdSetViewport(int firstViewport, IReadOnlyList<VkViewport> viewports); void CmdSetLineWidth(float lineWidth); void CmdSetDepthBias(float depthBiasConstantFactor, float depthBiasClamp, float depthBiasSlopeFactor); void CmdSetScissor(int firstScissor, IReadOnlyList<VkRect2D> scissors); void CmdSetDepthBounds(float minDepthBounds, float maxDepthBounds); void CmdSetStencilCompareMask(VkStencilFaceFlags faceMask, int compareMask); void CmdSetStencilWriteMask(VkStencilFaceFlags faceMask, int writeMask); void CmdSetStencilReference(VkStencilFaceFlags faceMask, int reference); void CmdSetBlendConstants(VkColor4 blendConstants); void CmdDispatch(int x, int y, int z); void CmdDispatchIndirect(IVkBuffer buffer, ulong offset); void CmdDebugMarkerBeginEXT(VkDebugMarkerMarkerInfoEXT markerInfo); void CmdDebugMarkerEndEXT(); void CmdDebugMarkerInsertEXT(VkDebugMarkerMarkerInfoEXT markerInfo); } public unsafe class VkCommandBuffer : IVkCommandBuffer { public IVkDevice Device { get; } public HandleType Handle { get; } private VkDevice.DirectFunctions Direct => Device.Direct; public IntPtr RawHandle => Handle.InternalHandle; public VkCommandBuffer(IVkDevice device, HandleType handle) { Device = device; Handle = handle; } public struct HandleType { public readonly IntPtr InternalHandle; public HandleType(IntPtr internalHandle) { InternalHandle = internalHandle; } public override string ToString() => InternalHandle.ToString(); public static int SizeInBytes { get; } = IntPtr.Size; public static HandleType Null => new HandleType(default(IntPtr)); } public VkResult Reset(VkCommandBufferResetFlags flags) { var _commandBuffer = Handle; var _flags = flags; return Direct.ResetCommandBuffer(_commandBuffer, _flags); } public VkResult Begin(VkCommandBufferBeginInfo beginInfo) { var unmanagedSize = beginInfo.SizeOfMarshalIndirect(); var unmanagedArray = new byte[unmanagedSize]; fixed (byte* unmanagedStart = unmanagedArray) { var unmanaged = unmanagedStart; var _commandBuffer = Handle; var _pBeginInfo = beginInfo.MarshalIndirect(ref unmanaged); return Direct.BeginCommandBuffer(_commandBuffer, _pBeginInfo); } } public VkResult End() { var _commandBuffer = Handle; return Direct.EndCommandBuffer(_commandBuffer); } public void CmdExecuteCommands(IReadOnlyList<IVkCommandBuffer> commandBuffers) { var unmanagedSize = commandBuffers.SizeOfMarshalDirect(); var unmanagedArray = new byte[unmanagedSize]; fixed (byte* unmanagedStart = unmanagedArray) { var unmanaged = unmanagedStart; var _commandBuffer = Handle; var _commandBufferCount = commandBuffers?.Count ?? 0; var _pCommandBuffers = commandBuffers.MarshalDirect(ref unmanaged); Direct.CmdExecuteCommands(_commandBuffer, _commandBufferCount, _pCommandBuffers); } } public void CmdSetEvent(IVkEvent eventObj, VkPipelineStageFlags stageMask) { var _commandBuffer = Handle; var _eventObj = eventObj?.Handle ?? VkEvent.HandleType.Null; var _stageMask = stageMask; Direct.CmdSetEvent(_commandBuffer, _eventObj, _stageMask); } public void CmdResetEvent(IVkEvent eventObj, VkPipelineStageFlags stageMask) { var _commandBuffer = Handle; var _eventObj = eventObj?.Handle ?? VkEvent.HandleType.Null; var _stageMask = stageMask; Direct.CmdResetEvent(_commandBuffer, _eventObj, _stageMask); } public void CmdWaitEvents(IReadOnlyList<IVkEvent> events, VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask, IReadOnlyList<VkMemoryBarrier> memoryBarriers, IReadOnlyList<VkBufferMemoryBarrier> bufferMemoryBarriers, IReadOnlyList<VkImageMemoryBarrier> imageMemoryBarriers) { var unmanagedSize = events.SizeOfMarshalDirect() + memoryBarriers.SizeOfMarshalDirect() + bufferMemoryBarriers.SizeOfMarshalDirect() + imageMemoryBarriers.SizeOfMarshalDirect(); var unmanagedArray = new byte[unmanagedSize]; fixed (byte* unmanagedStart = unmanagedArray) { var unmanaged = unmanagedStart; var _commandBuffer = Handle; var _eventCount = events?.Count ?? 0; var _pEvents = events.MarshalDirect(ref unmanaged); var _srcStageMask = srcStageMask; var _dstStageMask = dstStageMask; var _memoryBarrierCount = memoryBarriers?.Count ?? 0; var _pMemoryBarriers = memoryBarriers.MarshalDirect(ref unmanaged); var _bufferMemoryBarrierCount = bufferMemoryBarriers?.Count ?? 0; var _pBufferMemoryBarriers = bufferMemoryBarriers.MarshalDirect(ref unmanaged); var _imageMemoryBarrierCount = imageMemoryBarriers?.Count ?? 0; var _pImageMemoryBarriers = imageMemoryBarriers.MarshalDirect(ref unmanaged); Direct.CmdWaitEvents(_commandBuffer, _eventCount, _pEvents, _srcStageMask, _dstStageMask, _memoryBarrierCount, _pMemoryBarriers, _bufferMemoryBarrierCount, _pBufferMemoryBarriers, _imageMemoryBarrierCount, _pImageMemoryBarriers); } } public void CmdPipelineBarrier(VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags, IReadOnlyList<VkMemoryBarrier> memoryBarriers, IReadOnlyList<VkBufferMemoryBarrier> bufferMemoryBarriers, IReadOnlyList<VkImageMemoryBarrier> imageMemoryBarriers) { var unmanagedSize = memoryBarriers.SizeOfMarshalDirect() + bufferMemoryBarriers.SizeOfMarshalDirect() + imageMemoryBarriers.SizeOfMarshalDirect(); var unmanagedArray = new byte[unmanagedSize]; fixed (byte* unmanagedStart = unmanagedArray) { var unmanaged = unmanagedStart; var _commandBuffer = Handle; var _srcStageMask = srcStageMask; var _dstStageMask = dstStageMask; var _dependencyFlags = dependencyFlags; var _memoryBarrierCount = memoryBarriers?.Count ?? 0; var _pMemoryBarriers = memoryBarriers.MarshalDirect(ref unmanaged); var _bufferMemoryBarrierCount = bufferMemoryBarriers?.Count ?? 0; var _pBufferMemoryBarriers = bufferMemoryBarriers.MarshalDirect(ref unmanaged); var _imageMemoryBarrierCount = imageMemoryBarriers?.Count ?? 0; var _pImageMemoryBarriers = imageMemoryBarriers.MarshalDirect(ref unmanaged); Direct.CmdPipelineBarrier(_commandBuffer, _srcStageMask, _dstStageMask, _dependencyFlags, _memoryBarrierCount, _pMemoryBarriers, _bufferMemoryBarrierCount, _pBufferMemoryBarriers, _imageMemoryBarrierCount, _pImageMemoryBarriers); } } public void CmdBeginRenderPass(VkRenderPassBeginInfo renderPassBegin, VkSubpassContents contents) { var unmanagedSize = renderPassBegin.SizeOfMarshalIndirect(); var unmanagedArray = new byte[unmanagedSize]; fixed (byte* unmanagedStart = unmanagedArray) { var unmanaged = unmanagedStart; var _commandBuffer = Handle; var _pRenderPassBegin = renderPassBegin.MarshalIndirect(ref unmanaged); var _contents = contents; Direct.CmdBeginRenderPass(_commandBuffer, _pRenderPassBegin, _contents); } } public void CmdEndRenderPass() { var _commandBuffer = Handle; Direct.CmdEndRenderPass(_commandBuffer); } public void CmdNextSubpass(VkSubpassContents contents) { var _commandBuffer = Handle; var _contents = contents; Direct.CmdNextSubpass(_commandBuffer, _contents); } public void CmdBindPipeline(VkPipelineBindPoint pipelineBindPoint, IVkPipeline pipeline) { var _commandBuffer = Handle; var _pipelineBindPoint = pipelineBindPoint; var _pipeline = pipeline?.Handle ?? VkPipeline.HandleType.Null; Direct.CmdBindPipeline(_commandBuffer, _pipelineBindPoint, _pipeline); } public void CmdBindDescriptorSets(VkPipelineBindPoint pipelineBindPoint, IVkPipelineLayout layout, int firstSet, IReadOnlyList<IVkDescriptorSet> descriptorSets, IReadOnlyList<int> dynamicOffsets) { var unmanagedSize = descriptorSets.SizeOfMarshalDirect() + dynamicOffsets.SizeOfMarshalDirect(); var unmanagedArray = new byte[unmanagedSize]; fixed (byte* unmanagedStart = unmanagedArray) { var unmanaged = unmanagedStart; var _commandBuffer = Handle; var _pipelineBindPoint = pipelineBindPoint; var _layout = layout?.Handle ?? VkPipelineLayout.HandleType.Null; var _firstSet = firstSet; var _descriptorSetCount = descriptorSets?.Count ?? 0; var _pDescriptorSets = descriptorSets.MarshalDirect(ref unmanaged); var _dynamicOffsetCount = dynamicOffsets?.Count ?? 0; var _pDynamicOffsets = dynamicOffsets.MarshalDirect(ref unmanaged); Direct.CmdBindDescriptorSets(_commandBuffer, _pipelineBindPoint, _layout, _firstSet, _descriptorSetCount, _pDescriptorSets, _dynamicOffsetCount, _pDynamicOffsets); } } public void CmdPushConstants(IVkPipelineLayout layout, VkShaderStage stageFlags, int offset, int size, IntPtr values) { var _commandBuffer = Handle; var _layout = layout?.Handle ?? VkPipelineLayout.HandleType.Null; var _stageFlags = stageFlags; var _offset = offset; var _size = size; var _pValues = values; Direct.CmdPushConstants(_commandBuffer, _layout, _stageFlags, _offset, _size, _pValues); } public void CmdResetQueryPool(IVkQueryPool queryPool, int firstQuery, int queryCount) { var _commandBuffer = Handle; var _queryPool = queryPool?.Handle ?? VkQueryPool.HandleType.Null; var _firstQuery = firstQuery; var _queryCount = queryCount; Direct.CmdResetQueryPool(_commandBuffer, _queryPool, _firstQuery, _queryCount); } public void CmdBeginQuery(IVkQueryPool queryPool, int query, VkQueryControlFlags flags) { var _commandBuffer = Handle; var _queryPool = queryPool?.Handle ?? VkQueryPool.HandleType.Null; var _query = query; var _flags = flags; Direct.CmdBeginQuery(_commandBuffer, _queryPool, _query, _flags); } public void CmdEndQuery(IVkQueryPool queryPool, int query) { var _commandBuffer = Handle; var _queryPool = queryPool?.Handle ?? VkQueryPool.HandleType.Null; var _query = query; Direct.CmdEndQuery(_commandBuffer, _queryPool, _query); } public void CmdCopyQueryPoolResults(IVkQueryPool queryPool, int firstQuery, int queryCount, IVkBuffer dstBuffer, ulong dstOffset, ulong stride, VkQueryResultFlags flags) { var _commandBuffer = Handle; var _queryPool = queryPool?.Handle ?? VkQueryPool.HandleType.Null; var _firstQuery = firstQuery; var _queryCount = queryCount; var _dstBuffer = dstBuffer?.Handle ?? VkBuffer.HandleType.Null; var _dstOffset = dstOffset; var _stride = stride; var _flags = flags; Direct.CmdCopyQueryPoolResults(_commandBuffer, _queryPool, _firstQuery, _queryCount, _dstBuffer, _dstOffset, _stride, _flags); } public void CmdWriteTimestamp(VkPipelineStageFlags pipelineStage, IVkQueryPool queryPool, int query) { var _commandBuffer = Handle; var _pipelineStage = pipelineStage; var _queryPool = queryPool?.Handle ?? VkQueryPool.HandleType.Null; var _query = query; Direct.CmdWriteTimestamp(_commandBuffer, _pipelineStage, _queryPool, _query); } public void CmdClearColorImage(IVkImage image, VkImageLayout imageLayout, VkClearColorValue color, IReadOnlyList<VkImageSubresourceRange> ranges) { var unmanagedSize = ranges.SizeOfMarshalDirect(); var unmanagedArray = new byte[unmanagedSize]; fixed (byte* unmanagedStart = unmanagedArray) { var unmanaged = unmanagedStart; var _commandBuffer = Handle; var _image = image?.Handle ?? VkImage.HandleType.Null; var _imageLayout = imageLayout; var _pColor = &color; var _rangeCount = ranges?.Count ?? 0; var _pRanges = ranges.MarshalDirect(ref unmanaged); Direct.CmdClearColorImage(_commandBuffer, _image, _imageLayout, _pColor, _rangeCount, _pRanges); } } public void CmdClearDepthStencilImage(IVkImage image, VkImageLayout imageLayout, VkClearDepthStencilValue depthStencil, IReadOnlyList<VkImageSubresourceRange> ranges) { var unmanagedSize = ranges.SizeOfMarshalDirect(); var unmanagedArray = new byte[unmanagedSize]; fixed (byte* unmanagedStart = unmanagedArray) { var unmanaged = unmanagedStart; var _commandBuffer = Handle; var _image = image?.Handle ?? VkImage.HandleType.Null; var _imageLayout = imageLayout; var _pDepthStencil = &depthStencil; var _rangeCount = ranges?.Count ?? 0; var _pRanges = ranges.MarshalDirect(ref unmanaged); Direct.CmdClearDepthStencilImage(_commandBuffer, _image, _imageLayout, _pDepthStencil, _rangeCount, _pRanges); } } public void CmdClearAttachments(IReadOnlyList<VkClearAttachment> attachments, IReadOnlyList<VkClearRect> rects) { var unmanagedSize = attachments.SizeOfMarshalDirect() + rects.SizeOfMarshalDirect(); var unmanagedArray = new byte[unmanagedSize]; fixed (byte* unmanagedStart = unmanagedArray) { var unmanaged = unmanagedStart; var _commandBuffer = Handle; var _attachmentCount = attachments?.Count ?? 0; var _pAttachments = attachments.MarshalDirect(ref unmanaged); var _rectCount = rects?.Count ?? 0; var _pRects = rects.MarshalDirect(ref unmanaged); Direct.CmdClearAttachments(_commandBuffer, _attachmentCount, _pAttachments, _rectCount, _pRects); } } public void CmdFillBuffer(IVkBuffer dstBuffer, ulong dstOffset, ulong size, int data) { var _commandBuffer = Handle; var _dstBuffer = dstBuffer?.Handle ?? VkBuffer.HandleType.Null; var _dstOffset = dstOffset; var _size = size; var _data = data; Direct.CmdFillBuffer(_commandBuffer, _dstBuffer, _dstOffset, _size, _data); } public void CmdUpdateBuffer(IVkBuffer dstBuffer, ulong dstOffset, ulong dataSize, IntPtr data) { var _commandBuffer = Handle; var _dstBuffer = dstBuffer?.Handle ?? VkBuffer.HandleType.Null; var _dstOffset = dstOffset; var _dataSize = dataSize; var _pData = data; Direct.CmdUpdateBuffer(_commandBuffer, _dstBuffer, _dstOffset, _dataSize, _pData); } public void CmdCopyBuffer(IVkBuffer srcBuffer, IVkBuffer dstBuffer, IReadOnlyList<VkBufferCopy> regions) { var unmanagedSize = regions.SizeOfMarshalDirect(); var unmanagedArray = new byte[unmanagedSize]; fixed (byte* unmanagedStart = unmanagedArray) { var unmanaged = unmanagedStart; var _commandBuffer = Handle; var _srcBuffer = srcBuffer?.Handle ?? VkBuffer.HandleType.Null; var _dstBuffer = dstBuffer?.Handle ?? VkBuffer.HandleType.Null; var _regionCount = regions?.Count ?? 0; var _pRegions = regions.MarshalDirect(ref unmanaged); Direct.CmdCopyBuffer(_commandBuffer, _srcBuffer, _dstBuffer, _regionCount, _pRegions); } } public void CmdCopyImage(IVkImage srcImage, VkImageLayout srcImageLayout, IVkImage dstImage, VkImageLayout dstImageLayout, IReadOnlyList<VkImageCopy> regions) { var unmanagedSize = regions.SizeOfMarshalDirect(); var unmanagedArray = new byte[unmanagedSize]; fixed (byte* unmanagedStart = unmanagedArray) { var unmanaged = unmanagedStart; var _commandBuffer = Handle; var _srcImage = srcImage?.Handle ?? VkImage.HandleType.Null; var _srcImageLayout = srcImageLayout; var _dstImage = dstImage?.Handle ?? VkImage.HandleType.Null; var _dstImageLayout = dstImageLayout; var _regionCount = regions?.Count ?? 0; var _pRegions = regions.MarshalDirect(ref unmanaged); Direct.CmdCopyImage(_commandBuffer, _srcImage, _srcImageLayout, _dstImage, _dstImageLayout, _regionCount, _pRegions); } } public void CmdCopyBufferToImage(IVkBuffer srcBuffer, IVkImage dstImage, VkImageLayout dstImageLayout, IReadOnlyList<VkBufferImageCopy> regions) { var unmanagedSize = regions.SizeOfMarshalDirect(); var unmanagedArray = new byte[unmanagedSize]; fixed (byte* unmanagedStart = unmanagedArray) { var unmanaged = unmanagedStart; var _commandBuffer = Handle; var _srcBuffer = srcBuffer?.Handle ?? VkBuffer.HandleType.Null; var _dstImage = dstImage?.Handle ?? VkImage.HandleType.Null; var _dstImageLayout = dstImageLayout; var _regionCount = regions?.Count ?? 0; var _pRegions = regions.MarshalDirect(ref unmanaged); Direct.CmdCopyBufferToImage(_commandBuffer, _srcBuffer, _dstImage, _dstImageLayout, _regionCount, _pRegions); } } public void CmdCopyImageToBuffer(IVkImage srcImage, VkImageLayout srcImageLayout, IVkBuffer dstBuffer, IReadOnlyList<VkBufferImageCopy> regions) { var unmanagedSize = regions.SizeOfMarshalDirect(); var unmanagedArray = new byte[unmanagedSize]; fixed (byte* unmanagedStart = unmanagedArray) { var unmanaged = unmanagedStart; var _commandBuffer = Handle; var _srcImage = srcImage?.Handle ?? VkImage.HandleType.Null; var _srcImageLayout = srcImageLayout; var _dstBuffer = dstBuffer?.Handle ?? VkBuffer.HandleType.Null; var _regionCount = regions?.Count ?? 0; var _pRegions = regions.MarshalDirect(ref unmanaged); Direct.CmdCopyImageToBuffer(_commandBuffer, _srcImage, _srcImageLayout, _dstBuffer, _regionCount, _pRegions); } } public void CmdBlitImage(IVkImage srcImage, VkImageLayout srcImageLayout, IVkImage dstImage, VkImageLayout dstImageLayout, IReadOnlyList<VkImageBlit> regions, VkFilter filter) { var unmanagedSize = regions.SizeOfMarshalDirect(); var unmanagedArray = new byte[unmanagedSize]; fixed (byte* unmanagedStart = unmanagedArray) { var unmanaged = unmanagedStart; var _commandBuffer = Handle; var _srcImage = srcImage?.Handle ?? VkImage.HandleType.Null; var _srcImageLayout = srcImageLayout; var _dstImage = dstImage?.Handle ?? VkImage.HandleType.Null; var _dstImageLayout = dstImageLayout; var _regionCount = regions?.Count ?? 0; var _pRegions = regions.MarshalDirect(ref unmanaged); var _filter = filter; Direct.CmdBlitImage(_commandBuffer, _srcImage, _srcImageLayout, _dstImage, _dstImageLayout, _regionCount, _pRegions, _filter); } } public void CmdResolveImage(IVkImage srcImage, VkImageLayout srcImageLayout, IVkImage dstImage, VkImageLayout dstImageLayout, IReadOnlyList<VkImageResolve> regions) { var unmanagedSize = regions.SizeOfMarshalDirect(); var unmanagedArray = new byte[unmanagedSize]; fixed (byte* unmanagedStart = unmanagedArray) { var unmanaged = unmanagedStart; var _commandBuffer = Handle; var _srcImage = srcImage?.Handle ?? VkImage.HandleType.Null; var _srcImageLayout = srcImageLayout; var _dstImage = dstImage?.Handle ?? VkImage.HandleType.Null; var _dstImageLayout = dstImageLayout; var _regionCount = regions?.Count ?? 0; var _pRegions = regions.MarshalDirect(ref unmanaged); Direct.CmdResolveImage(_commandBuffer, _srcImage, _srcImageLayout, _dstImage, _dstImageLayout, _regionCount, _pRegions); } } public void CmdBindIndexBuffer(IVkBuffer buffer, ulong offset, VkIndexType indexType) { var _commandBuffer = Handle; var _buffer = buffer?.Handle ?? VkBuffer.HandleType.Null; var _offset = offset; var _indexType = indexType; Direct.CmdBindIndexBuffer(_commandBuffer, _buffer, _offset, _indexType); } public void CmdDraw(int vertexCount, int instanceCount, int firstVertex, int firstInstance) { var _commandBuffer = Handle; var _vertexCount = vertexCount; var _instanceCount = instanceCount; var _firstVertex = firstVertex; var _firstInstance = firstInstance; Direct.CmdDraw(_commandBuffer, _vertexCount, _instanceCount, _firstVertex, _firstInstance); } public void CmdDrawIndexed(int indexCount, int instanceCount, int firstIndex, int vertexOffset, int firstInstance) { var _commandBuffer = Handle; var _indexCount = indexCount; var _instanceCount = instanceCount; var _firstIndex = firstIndex; var _vertexOffset = vertexOffset; var _firstInstance = firstInstance; Direct.CmdDrawIndexed(_commandBuffer, _indexCount, _instanceCount, _firstIndex, _vertexOffset, _firstInstance); } public void CmdDrawIndirect(IVkBuffer buffer, ulong offset, int drawCount, int stride) { var _commandBuffer = Handle; var _buffer = buffer?.Handle ?? VkBuffer.HandleType.Null; var _offset = offset; var _drawCount = drawCount; var _stride = stride; Direct.CmdDrawIndirect(_commandBuffer, _buffer, _offset, _drawCount, _stride); } public void CmdDrawIndexedIndirect(IVkBuffer buffer, ulong offset, int drawCount, int stride) { var _commandBuffer = Handle; var _buffer = buffer?.Handle ?? VkBuffer.HandleType.Null; var _offset = offset; var _drawCount = drawCount; var _stride = stride; Direct.CmdDrawIndexedIndirect(_commandBuffer, _buffer, _offset, _drawCount, _stride); } public void CmdBindVertexBuffers(int firstBinding, IReadOnlyList<IVkBuffer> buffers, IReadOnlyList<ulong> offsets) { var unmanagedSize = buffers.SizeOfMarshalDirect() + offsets.SizeOfMarshalDirect(); var unmanagedArray = new byte[unmanagedSize]; fixed (byte* unmanagedStart = unmanagedArray) { var unmanaged = unmanagedStart; var _commandBuffer = Handle; var _firstBinding = firstBinding; var _bindingCount = Math.Min(buffers?.Count ?? 0, offsets?.Count ?? 0); var _pBuffers = buffers.MarshalDirect(ref unmanaged); var _pOffsets = offsets.MarshalDirect(ref unmanaged); Direct.CmdBindVertexBuffers(_commandBuffer, _firstBinding, _bindingCount, _pBuffers, _pOffsets); } } public void CmdSetViewport(int firstViewport, IReadOnlyList<VkViewport> viewports) { var unmanagedSize = viewports.SizeOfMarshalDirect(); var unmanagedArray = new byte[unmanagedSize]; fixed (byte* unmanagedStart = unmanagedArray) { var unmanaged = unmanagedStart; var _commandBuffer = Handle; var _firstViewport = firstViewport; var _viewportCount = viewports?.Count ?? 0; var _pViewports = viewports.MarshalDirect(ref unmanaged); Direct.CmdSetViewport(_commandBuffer, _firstViewport, _viewportCount, _pViewports); } } public void CmdSetLineWidth(float lineWidth) { var _commandBuffer = Handle; var _lineWidth = lineWidth; Direct.CmdSetLineWidth(_commandBuffer, _lineWidth); } public void CmdSetDepthBias(float depthBiasConstantFactor, float depthBiasClamp, float depthBiasSlopeFactor) { var _commandBuffer = Handle; var _depthBiasConstantFactor = depthBiasConstantFactor; var _depthBiasClamp = depthBiasClamp; var _depthBiasSlopeFactor = depthBiasSlopeFactor; Direct.CmdSetDepthBias(_commandBuffer, _depthBiasConstantFactor, _depthBiasClamp, _depthBiasSlopeFactor); } public void CmdSetScissor(int firstScissor, IReadOnlyList<VkRect2D> scissors) { var unmanagedSize = scissors.SizeOfMarshalDirect(); var unmanagedArray = new byte[unmanagedSize]; fixed (byte* unmanagedStart = unmanagedArray) { var unmanaged = unmanagedStart; var _commandBuffer = Handle; var _firstScissor = firstScissor; var _scissorCount = scissors?.Count ?? 0; var _pScissors = scissors.MarshalDirect(ref unmanaged); Direct.CmdSetScissor(_commandBuffer, _firstScissor, _scissorCount, _pScissors); } } public void CmdSetDepthBounds(float minDepthBounds, float maxDepthBounds) { var _commandBuffer = Handle; var _minDepthBounds = minDepthBounds; var _maxDepthBounds = maxDepthBounds; Direct.CmdSetDepthBounds(_commandBuffer, _minDepthBounds, _maxDepthBounds); } public void CmdSetStencilCompareMask(VkStencilFaceFlags faceMask, int compareMask) { var _commandBuffer = Handle; var _faceMask = faceMask; var _compareMask = compareMask; Direct.CmdSetStencilCompareMask(_commandBuffer, _faceMask, _compareMask); } public void CmdSetStencilWriteMask(VkStencilFaceFlags faceMask, int writeMask) { var _commandBuffer = Handle; var _faceMask = faceMask; var _writeMask = writeMask; Direct.CmdSetStencilWriteMask(_commandBuffer, _faceMask, _writeMask); } public void CmdSetStencilReference(VkStencilFaceFlags faceMask, int reference) { var _commandBuffer = Handle; var _faceMask = faceMask; var _reference = reference; Direct.CmdSetStencilReference(_commandBuffer, _faceMask, _reference); } public void CmdSetBlendConstants(VkColor4 blendConstants) { var _commandBuffer = Handle; var _blendConstants = &blendConstants; Direct.CmdSetBlendConstants(_commandBuffer, _blendConstants); } public void CmdDispatch(int x, int y, int z) { var _commandBuffer = Handle; var _x = x; var _y = y; var _z = z; Direct.CmdDispatch(_commandBuffer, _x, _y, _z); } public void CmdDispatchIndirect(IVkBuffer buffer, ulong offset) { var _commandBuffer = Handle; var _buffer = buffer?.Handle ?? VkBuffer.HandleType.Null; var _offset = offset; Direct.CmdDispatchIndirect(_commandBuffer, _buffer, _offset); } public void CmdDebugMarkerBeginEXT(VkDebugMarkerMarkerInfoEXT markerInfo) { var unmanagedSize = markerInfo.SizeOfMarshalIndirect(); var unmanagedArray = new byte[unmanagedSize]; fixed (byte* unmanagedStart = unmanagedArray) { var unmanaged = unmanagedStart; var _commandBuffer = Handle; var _pMarkerInfo = markerInfo.MarshalIndirect(ref unmanaged); Direct.CmdDebugMarkerBeginEXT(_commandBuffer, _pMarkerInfo); } } public void CmdDebugMarkerEndEXT() { var _commandBuffer = Handle; Direct.CmdDebugMarkerEndEXT(_commandBuffer); } public void CmdDebugMarkerInsertEXT(VkDebugMarkerMarkerInfoEXT markerInfo) { var unmanagedSize = markerInfo.SizeOfMarshalIndirect(); var unmanagedArray = new byte[unmanagedSize]; fixed (byte* unmanagedStart = unmanagedArray) { var unmanaged = unmanagedStart; var _commandBuffer = Handle; var _pMarkerInfo = markerInfo.MarshalIndirect(ref unmanaged); Direct.CmdDebugMarkerInsertEXT(_commandBuffer, _pMarkerInfo); } } } public static unsafe class VkCommandBufferExtensions { public static int SizeOfMarshalDirect(this IReadOnlyList<IVkCommandBuffer> list) => list.SizeOfMarshalDirectDispatchable(); public static VkCommandBuffer.HandleType* MarshalDirect(this IReadOnlyList<IVkCommandBuffer> list, ref byte* unmanaged) => (VkCommandBuffer.HandleType*)list.MarshalDirectDispatchable(ref unmanaged); } }
#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.Diagnostics; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Grpc.Core.Internal; using Grpc.Core.Logging; using Grpc.Core.Utils; namespace Grpc.Core.Internal { /// <summary> /// Base for handling both client side and server side calls. /// Manages native call lifecycle and provides convenience methods. /// </summary> internal abstract class AsyncCallBase<TWrite, TRead> { static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<AsyncCallBase<TWrite, TRead>>(); protected static readonly Status DeserializeResponseFailureStatus = new Status(StatusCode.Internal, "Failed to deserialize response message."); readonly Func<TWrite, byte[]> serializer; readonly Func<byte[], TRead> deserializer; protected readonly GrpcEnvironment environment; protected readonly object myLock = new object(); protected INativeCall call; protected bool disposed; protected bool started; protected bool cancelRequested; protected AsyncCompletionDelegate<object> sendCompletionDelegate; // Completion of a pending send or sendclose if not null. protected AsyncCompletionDelegate<TRead> readCompletionDelegate; // Completion of a pending send or sendclose if not null. protected bool readingDone; // True if last read (i.e. read with null payload) was already received. protected bool halfcloseRequested; // True if send close have been initiated. protected bool finished; // True if close has been received from the peer. protected bool initialMetadataSent; protected long streamingWritesCounter; // Number of streaming send operations started so far. public AsyncCallBase(Func<TWrite, byte[]> serializer, Func<byte[], TRead> deserializer, GrpcEnvironment environment) { this.serializer = Preconditions.CheckNotNull(serializer); this.deserializer = Preconditions.CheckNotNull(deserializer); this.environment = Preconditions.CheckNotNull(environment); } /// <summary> /// Requests cancelling the call. /// </summary> public void Cancel() { lock (myLock) { Preconditions.CheckState(started); cancelRequested = true; if (!disposed) { call.Cancel(); } } } /// <summary> /// Requests cancelling the call with given status. /// </summary> protected void CancelWithStatus(Status status) { lock (myLock) { cancelRequested = true; if (!disposed) { call.CancelWithStatus(status); } } } protected void InitializeInternal(INativeCall call) { lock (myLock) { this.call = call; } } /// <summary> /// Initiates sending a message. Only one send operation can be active at a time. /// completionDelegate is invoked upon completion. /// </summary> protected void StartSendMessageInternal(TWrite msg, WriteFlags writeFlags, AsyncCompletionDelegate<object> completionDelegate) { byte[] payload = UnsafeSerialize(msg); lock (myLock) { Preconditions.CheckNotNull(completionDelegate, "Completion delegate cannot be null"); CheckSendingAllowed(); call.StartSendMessage(HandleSendFinished, payload, writeFlags, !initialMetadataSent); sendCompletionDelegate = completionDelegate; initialMetadataSent = true; streamingWritesCounter++; } } /// <summary> /// Initiates reading a message. Only one read operation can be active at a time. /// completionDelegate is invoked upon completion. /// </summary> protected void StartReadMessageInternal(AsyncCompletionDelegate<TRead> completionDelegate) { lock (myLock) { Preconditions.CheckNotNull(completionDelegate, "Completion delegate cannot be null"); CheckReadingAllowed(); call.StartReceiveMessage(HandleReadFinished); readCompletionDelegate = completionDelegate; } } /// <summary> /// If there are no more pending actions and no new actions can be started, releases /// the underlying native resources. /// </summary> protected bool ReleaseResourcesIfPossible() { if (!disposed && call != null) { bool noMoreSendCompletions = sendCompletionDelegate == null && (halfcloseRequested || cancelRequested || finished); if (noMoreSendCompletions && readingDone && finished) { ReleaseResources(); return true; } } return false; } protected abstract bool IsClient { get; } private void ReleaseResources() { if (call != null) { call.Dispose(); } disposed = true; OnAfterReleaseResources(); } protected virtual void OnAfterReleaseResources() { } protected void CheckSendingAllowed() { Preconditions.CheckState(started); CheckNotCancelled(); Preconditions.CheckState(!disposed); Preconditions.CheckState(!halfcloseRequested, "Already halfclosed."); Preconditions.CheckState(!finished, "Already finished."); Preconditions.CheckState(sendCompletionDelegate == null, "Only one write can be pending at a time"); } protected virtual void CheckReadingAllowed() { Preconditions.CheckState(started); Preconditions.CheckState(!disposed); Preconditions.CheckState(!readingDone, "Stream has already been closed."); Preconditions.CheckState(readCompletionDelegate == null, "Only one read can be pending at a time"); } protected void CheckNotCancelled() { if (cancelRequested) { throw new OperationCanceledException("Remote call has been cancelled."); } } protected byte[] UnsafeSerialize(TWrite msg) { return serializer(msg); } protected Exception TrySerialize(TWrite msg, out byte[] payload) { try { payload = serializer(msg); return null; } catch (Exception e) { payload = null; return e; } } protected Exception TryDeserialize(byte[] payload, out TRead msg) { try { msg = deserializer(payload); return null; } catch (Exception e) { msg = default(TRead); return e; } } protected void FireCompletion<T>(AsyncCompletionDelegate<T> completionDelegate, T value, Exception error) { try { completionDelegate(value, error); } catch (Exception e) { Logger.Error(e, "Exception occured while invoking completion delegate."); } } /// <summary> /// Handles send completion. /// </summary> protected void HandleSendFinished(bool success) { AsyncCompletionDelegate<object> origCompletionDelegate = null; lock (myLock) { origCompletionDelegate = sendCompletionDelegate; sendCompletionDelegate = null; ReleaseResourcesIfPossible(); } if (!success) { FireCompletion(origCompletionDelegate, null, new InvalidOperationException("Send failed")); } else { FireCompletion(origCompletionDelegate, null, null); } } /// <summary> /// Handles halfclose completion. /// </summary> protected void HandleHalfclosed(bool success) { AsyncCompletionDelegate<object> origCompletionDelegate = null; lock (myLock) { origCompletionDelegate = sendCompletionDelegate; sendCompletionDelegate = null; ReleaseResourcesIfPossible(); } if (!success) { FireCompletion(origCompletionDelegate, null, new InvalidOperationException("Halfclose failed")); } else { FireCompletion(origCompletionDelegate, null, null); } } /// <summary> /// Handles streaming read completion. /// </summary> protected void HandleReadFinished(bool success, byte[] receivedMessage) { TRead msg = default(TRead); var deserializeException = (success && receivedMessage != null) ? TryDeserialize(receivedMessage, out msg) : null; AsyncCompletionDelegate<TRead> origCompletionDelegate = null; lock (myLock) { origCompletionDelegate = readCompletionDelegate; readCompletionDelegate = null; if (receivedMessage == null) { // This was the last read. readingDone = true; } if (deserializeException != null && IsClient) { readingDone = true; CancelWithStatus(DeserializeResponseFailureStatus); } ReleaseResourcesIfPossible(); } // TODO: handle the case when success==false if (deserializeException != null && !IsClient) { FireCompletion(origCompletionDelegate, default(TRead), new IOException("Failed to deserialize request message.", deserializeException)); return; } FireCompletion(origCompletionDelegate, msg, null); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Abp.Domain.Entities; using DapperExtensions; namespace Abp.Dapper.Expressions { /// <summary> /// This class converts an Expression{Func{TEntity, bool}} into an IPredicate group that can be used with /// DapperExtension's predicate system /// </summary> /// <typeparam name="TEntity">The type of the entity.</typeparam> /// <typeparam name="TPrimaryKey">The type of the primary key.</typeparam> /// <seealso cref="System.Linq.Expressions.ExpressionVisitor" /> internal class DapperExpressionVisitor<TEntity, TPrimaryKey> : ExpressionVisitor where TEntity : class, IEntity<TPrimaryKey> { private PredicateGroup _pg; private Expression _processedProperty; private bool _unarySpecified; private Stack<PredicateGroup> _predicateGroupStack; public PredicateGroup _currentGroup { get; set; } public DapperExpressionVisitor() { Expressions = new HashSet<Expression>(); _predicateGroupStack = new Stack<PredicateGroup>(); } /// <summary> /// Holds BinaryExpressions /// </summary> public HashSet<Expression> Expressions { get; } public IPredicate Process(Expression exp) { _pg = new PredicateGroup { Predicates = new List<IPredicate>() }; _currentGroup = _pg; Visit(Evaluator.PartialEval(exp)); // the 1st expression determines root group operator if (Expressions.Any()) { _pg.Operator = Expressions.First().NodeType == ExpressionType.OrElse ? GroupOperator.Or : GroupOperator.And; } return _pg.Predicates.Count == 1 ? _pg.Predicates[0] : _pg; } private static Operator DetermineOperator(Expression binaryExpression) { switch (binaryExpression.NodeType) { case ExpressionType.Equal: return Operator.Eq; case ExpressionType.GreaterThan: return Operator.Gt; case ExpressionType.GreaterThanOrEqual: return Operator.Ge; case ExpressionType.LessThan: return Operator.Lt; case ExpressionType.LessThanOrEqual: return Operator.Le; default: return Operator.Eq; } } private IFieldPredicate GetCurrentField() { return GetCurrentField(_currentGroup); } private IFieldPredicate GetCurrentField(IPredicateGroup group) { IPredicate last = group.Predicates.Last(); if (last is IPredicateGroup) { return GetCurrentField(last as IPredicateGroup); } return last as IFieldPredicate; } private void AddField(MemberExpression exp, Operator op = Operator.Eq, object value = null, bool not = false) { PredicateGroup pg = _currentGroup; // need convert from Expression<Func<T, bool>> to Expression<Func<T, object>> as this is what Predicates.Field() requires Expression<Func<TEntity, object>> fieldExp = Expression.Lambda<Func<TEntity, object>>(Expression.Convert(exp, typeof(object)), exp.Expression as ParameterExpression); IFieldPredicate field = Predicates.Field(fieldExp, op, value, not); pg.Predicates.Add(field); } #region The visit methods override protected override Expression VisitBinary(BinaryExpression node) { Expressions.Add(node); ExpressionType nt = node.NodeType; if (nt == ExpressionType.OrElse || nt == ExpressionType.AndAlso) { var pg = new PredicateGroup { Predicates = new List<IPredicate>(), Operator = nt == ExpressionType.OrElse ? GroupOperator.Or : GroupOperator.And }; _currentGroup.Predicates.Add(pg); _predicateGroupStack.Push(_currentGroup); _currentGroup = pg; } Visit(node.Left); if (node.Left is MemberExpression) { IFieldPredicate field = GetCurrentField(); field.Operator = DetermineOperator(node); if (nt == ExpressionType.NotEqual) { field.Not = true; } } Visit(node.Right); if (nt == ExpressionType.OrElse || nt == ExpressionType.AndAlso) { _currentGroup = _predicateGroupStack.Pop(); } return node; } protected override Expression VisitMember(MemberExpression node) { if (node.Member.MemberType != MemberTypes.Property || node.Expression.Type != typeof(TEntity)) { throw new NotSupportedException($"The member '{node}' is not supported"); } // skip if prop is part of a VisitMethodCall if (_processedProperty != null && _processedProperty == node) { _processedProperty = null; return node; } AddField(node); return node; } protected override Expression VisitConstant(ConstantExpression node) { IFieldPredicate field = GetCurrentField(); field.Value = node.Value; return node; } protected override Expression VisitMethodCall(MethodCallExpression node) { if (node.Type == typeof(bool) && node.Method.DeclaringType == typeof(string)) { object arg = ((ConstantExpression)node.Arguments[0]).Value; var op = Operator.Like; switch (node.Method.Name.ToLowerInvariant()) { case "startswith": arg = arg + "%"; break; case "endswith": arg = "%" + arg; break; case "contains": arg = "%" + arg + "%"; break; case "equals": op = Operator.Eq; break; default: throw new NotSupportedException($"The method '{node}' is not supported"); } // this is a PropertyExpression but as it's internal, to use, we cast to the base MemberExpression instead (see http://social.msdn.microsoft.com/Forums/en-US/ab528f6a-a60e-4af6-bf31-d58e3f373356/resolving-propertyexpressions-and-fieldexpressions-in-a-custom-linq-provider) _processedProperty = node.Object; var me = _processedProperty as MemberExpression; AddField(me, op, arg, _unarySpecified); // reset if applicable _unarySpecified = false; return node; } throw new NotSupportedException($"The method '{node}' is not supported"); } protected override Expression VisitUnary(UnaryExpression node) { if (node.NodeType != ExpressionType.Not) { throw new NotSupportedException($"The unary operator '{node.NodeType}' is not supported"); } _unarySpecified = true; return base.VisitUnary(node); // returning base because we want to continue further processing - ie subsequent call to VisitMethodCall } #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.Net.Http; using System.Text; using System.Threading.Tasks; using Xunit; namespace System.Net.Tests { public class HttpWebRequestTest { private const string RequestBody = "This is data to POST."; private readonly byte[] _requestBodyBytes = Encoding.UTF8.GetBytes(RequestBody); private readonly NetworkCredential _explicitCredential = new NetworkCredential("user", "password", "domain"); private HttpWebRequest _savedHttpWebRequest = null; private WebHeaderCollection _savedResponseHeaders = null; private Exception _savedRequestStreamException = null; private Exception _savedResponseException = null; private int _requestStreamCallbackCallCount = 0; private int _responseCallbackCallCount = 0; public readonly static object[][] EchoServers = HttpTestServers.EchoServers; [Theory, MemberData("EchoServers")] public void Ctor_VerifyDefaults_Success(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); Assert.Null(request.Accept); Assert.False(request.AllowReadStreamBuffering); Assert.Null(request.ContentType); Assert.Equal(350, request.ContinueTimeout); Assert.Null(request.CookieContainer); Assert.Null(request.Credentials); Assert.False(request.HaveResponse); Assert.NotNull(request.Headers); Assert.Equal(0, request.Headers.Count); Assert.Equal("GET", request.Method); Assert.NotNull(request.Proxy); Assert.Equal(remoteServer, request.RequestUri); Assert.True(request.SupportsCookieContainer); Assert.False(request.UseDefaultCredentials); } [Theory, MemberData("EchoServers")] public void Ctor_CreateHttpWithString_ExpectNotNull(Uri remoteServer) { string remoteServerString = remoteServer.ToString(); HttpWebRequest request = WebRequest.CreateHttp(remoteServerString); Assert.NotNull(request); } [Theory, MemberData("EchoServers")] public void Ctor_CreateHttpWithUri_ExpectNotNull(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); Assert.NotNull(request); } [Theory, MemberData("EchoServers")] public void Accept_SetThenGetValidValue_ExpectSameValue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); string acceptType = "*/*"; request.Accept = acceptType; Assert.Equal(acceptType, request.Accept); } [Theory, MemberData("EchoServers")] public void Accept_SetThenGetEmptyValue_ExpectNull(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Accept = string.Empty; Assert.Null(request.Accept); } [Theory, MemberData("EchoServers")] public void Accept_SetThenGetNullValue_ExpectNull(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Accept = null; Assert.Null(request.Accept); } [Theory, MemberData("EchoServers")] public void AllowReadStreamBuffering_SetFalseThenGet_ExpectFalse(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.AllowReadStreamBuffering = false; Assert.False(request.AllowReadStreamBuffering); } [Theory, MemberData("EchoServers")] public void AllowReadStreamBuffering_SetTrueThenGet_ExpectTrue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.AllowReadStreamBuffering = true; Assert.True(request.AllowReadStreamBuffering); } [Theory, MemberData("EchoServers")] public async Task ContentLength_Get_ExpectSameAsGetResponseStream(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); WebResponse response = await request.GetResponseAsync(); Stream myStream = response.GetResponseStream(); String strContent; using (var sr = new StreamReader(myStream)) { strContent = sr.ReadToEnd(); } long length = response.ContentLength; Assert.Equal(strContent.Length, length); } [Theory, MemberData("EchoServers")] public void ContentType_SetThenGet_ExpectSameValue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); string myContent = "application/x-www-form-urlencoded"; request.ContentType = myContent; Assert.Equal(myContent, request.ContentType); } [Theory, MemberData("EchoServers")] public void ContentType_SetThenGetEmptyValue_ExpectNull(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.ContentType = string.Empty; Assert.Null(request.ContentType); } [Theory, MemberData("EchoServers")] public void ContinueTimeout_SetThenGetZero_ExpectZero(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.ContinueTimeout = 0; Assert.Equal(0, request.ContinueTimeout); } [Theory, MemberData("EchoServers")] public void ContinueTimeout_SetNegativeOne_Success(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.ContinueTimeout = -1; } [Theory, MemberData("EchoServers")] public void ContinueTimeout_SetNegativeTwo_ThrowsArgumentOutOfRangeException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); Assert.Throws<ArgumentOutOfRangeException>(() => request.ContinueTimeout = -2); } [Theory, MemberData("EchoServers")] public void Credentials_SetDefaultCredentialsThenGet_ValuesMatch(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Credentials = CredentialCache.DefaultCredentials; Assert.Equal(CredentialCache.DefaultCredentials, request.Credentials); } [Theory, MemberData("EchoServers")] public void Credentials_SetExplicitCredentialsThenGet_ValuesMatch(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Credentials = _explicitCredential; Assert.Equal(_explicitCredential, request.Credentials); } [Theory, MemberData("EchoServers")] public void UseDefaultCredentials_SetTrue_CredentialsEqualsDefaultCredentials(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Credentials = _explicitCredential; request.UseDefaultCredentials = true; Assert.Equal(CredentialCache.DefaultCredentials, request.Credentials); } [Theory, MemberData("EchoServers")] public void UseDefaultCredentials_SetFalse_CredentialsNull(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Credentials = _explicitCredential; request.UseDefaultCredentials = false; Assert.Equal(null, request.Credentials); } [Theory, MemberData("EchoServers")] public void BeginGetRequestStream_UseGETVerb_ThrowsProtocolViolationException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); Assert.Throws<ProtocolViolationException>(() => { request.BeginGetRequestStream(null, null); }); } [Theory, MemberData("EchoServers")] public void BeginGetRequestStream_UseHEADVerb_ThrowsProtocolViolationException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Head.Method; Assert.Throws<ProtocolViolationException>(() => { request.BeginGetRequestStream(null, null); }); } [Theory, MemberData("EchoServers")] public void BeginGetRequestStream_UseCONNECTVerb_ThrowsProtocolViolationException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = "CONNECT"; Assert.Throws<ProtocolViolationException>(() => { request.BeginGetRequestStream(null, null); }); } [Theory, MemberData("EchoServers")] public void BeginGetRequestStream_CreatePostRequestThenAbort_ThrowsWebException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Post.Method; request.Abort(); WebException ex = Assert.Throws<WebException>(() => request.BeginGetRequestStream(null, null)); Assert.Equal(WebExceptionStatus.RequestCanceled, ex.Status); } [Theory, MemberData("EchoServers")] public void BeginGetRequestStream_CreatePostRequestThenCallTwice_ThrowsInvalidOperationException(Uri remoteServer) { _savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer); _savedHttpWebRequest.Method = "POST"; IAsyncResult asyncResult = _savedHttpWebRequest.BeginGetRequestStream(null, null); Assert.Throws<InvalidOperationException>(() => { _savedHttpWebRequest.BeginGetRequestStream(null, null); }); } [Theory, MemberData("EchoServers")] public void BeginGetRequestStream_CreateRequestThenBeginGetResponsePrior_ThrowsInvalidOperationException(Uri remoteServer) { _savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer); IAsyncResult asyncResult = _savedHttpWebRequest.BeginGetResponse(null, null); Assert.Throws<InvalidOperationException>(() => { _savedHttpWebRequest.BeginGetRequestStream(null, null); }); } [Theory, MemberData("EchoServers")] public void BeginGetResponse_CreateRequestThenCallTwice_ThrowsInvalidOperationException(Uri remoteServer) { _savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer); IAsyncResult asyncResult = _savedHttpWebRequest.BeginGetResponse(null, null); Assert.Throws<InvalidOperationException>(() => { _savedHttpWebRequest.BeginGetResponse(null, null); }); } [Theory, MemberData("EchoServers")] public void BeginGetResponse_CreatePostRequestThenAbort_ThrowsWebException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Post.Method; request.Abort(); WebException ex = Assert.Throws<WebException>(() => request.BeginGetResponse(null, null)); Assert.Equal(WebExceptionStatus.RequestCanceled, ex.Status); } [Theory, MemberData("EchoServers")] public async Task GetRequestStreamAsync_WriteAndDisposeRequestStreamThenOpenRequestStream_ThrowsArgumentException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Post.Method; Stream requestStream; using (requestStream = await request.GetRequestStreamAsync()) { requestStream.Write(_requestBodyBytes, 0, _requestBodyBytes.Length); } Assert.Throws<ArgumentException>(() => { var sr = new StreamReader(requestStream); }); } [Theory, MemberData("EchoServers")] public async Task GetRequestStreamAsync_SetPOSTThenGet_ExpectNotNull(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Post.Method; Stream requestStream = await request.GetRequestStreamAsync(); Assert.NotNull(requestStream); } [Theory, MemberData("EchoServers")] public async Task GetResponseAsync_GetResponseStream_ExpectNotNull(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); WebResponse response = await request.GetResponseAsync(); Assert.NotNull(response.GetResponseStream()); } [Theory, MemberData("EchoServers")] public async Task GetResponseAsync_GetResponseStream_ContainsHost(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Get.Method; WebResponse response = await request.GetResponseAsync(); Stream myStream = response.GetResponseStream(); Assert.NotNull(myStream); String strContent; using (var sr = new StreamReader(myStream)) { strContent = sr.ReadToEnd(); } Assert.True(strContent.Contains("\"Host\": \"" + HttpTestServers.Host + "\"")); } [Theory, MemberData("EchoServers")] public async Task GetResponseAsync_PostRequestStream_ContainsData(Uri remoteServer) { HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Post.Method; using (Stream requestStream = await request.GetRequestStreamAsync()) { requestStream.Write(_requestBodyBytes, 0, _requestBodyBytes.Length); } WebResponse response = await request.GetResponseAsync(); Stream myStream = response.GetResponseStream(); String strContent; using (var sr = new StreamReader(myStream)) { strContent = sr.ReadToEnd(); } Assert.True(strContent.Contains(RequestBody)); } [Theory, MemberData("EchoServers")] public async Task GetResponseAsync_UseDefaultCredentials_ExpectSuccess(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.UseDefaultCredentials = true; WebResponse response = await request.GetResponseAsync(); } [OuterLoop] // fails on networks with DNS servers that provide a dummy page for invalid addresses [Fact] public void GetResponseAsync_ServerNameNotInDns_ThrowsWebException() { string serverUrl = string.Format("http://www.{0}.com/", Guid.NewGuid().ToString()); HttpWebRequest request = WebRequest.CreateHttp(serverUrl); WebException ex = Assert.Throws<WebException>(() => request.GetResponseAsync().GetAwaiter().GetResult()); Assert.Equal(WebExceptionStatus.NameResolutionFailure, ex.Status); } public static object[][] StatusCodeServers = { new object[] { HttpTestServers.StatusCodeUri(false, 404) }, new object[] { HttpTestServers.StatusCodeUri(true, 404) }, }; [Theory, MemberData("StatusCodeServers")] public async Task GetResponseAsync_ResourceNotFound_ThrowsWebException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); WebException ex = await Assert.ThrowsAsync<WebException>(() => request.GetResponseAsync()); Assert.Equal(WebExceptionStatus.ProtocolError, ex.Status); } [Theory, MemberData("EchoServers")] public async Task HaveResponse_GetResponseAsync_ExpectTrue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); WebResponse response = await request.GetResponseAsync(); Assert.True(request.HaveResponse); } [Theory, MemberData("EchoServers")] public async Task Headers_GetResponseHeaders_ContainsExpectedValue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); HttpWebResponse response = (HttpWebResponse) await request.GetResponseAsync(); String headersString = response.Headers.ToString(); string headersPartialContent = "Content-Type: application/json"; Assert.True(headersString.Contains(headersPartialContent)); } [Theory, MemberData("EchoServers")] public void Method_SetThenGetToGET_ExpectSameValue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Get.Method; Assert.Equal(HttpMethod.Get.Method, request.Method); } [Theory, MemberData("EchoServers")] public void Method_SetThenGetToPOST_ExpectSameValue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Post.Method; Assert.Equal(HttpMethod.Post.Method, request.Method); } [Theory, MemberData("EchoServers")] public void Proxy_GetDefault_ExpectNotNull(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); Assert.NotNull(request.Proxy); } [Theory, MemberData("EchoServers")] public void RequestUri_CreateHttpThenGet_ExpectSameUri(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); Assert.Equal(remoteServer, request.RequestUri); } [Theory, MemberData("EchoServers")] public async Task ResponseUri_GetResponseAsync_ExpectSameUri(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); WebResponse response = await request.GetResponseAsync(); Assert.Equal(remoteServer, response.ResponseUri); } [Theory, MemberData("EchoServers")] public void SupportsCookieContainer_GetDefault_ExpectTrue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); Assert.True(request.SupportsCookieContainer); } [Theory, MemberData("EchoServers")] public async Task SimpleScenario_UseGETVerb_Success(Uri remoteServer) { HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer); HttpWebResponse response = (HttpWebResponse) await request.GetResponseAsync(); Stream responseStream = response.GetResponseStream(); String responseBody; using (var sr = new StreamReader(responseStream)) { responseBody = sr.ReadToEnd(); } Assert.Equal(HttpStatusCode.OK, response.StatusCode); } [Theory, MemberData("EchoServers")] public async Task SimpleScenario_UsePOSTVerb_Success(Uri remoteServer) { HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Post.Method; using (Stream requestStream = await request.GetRequestStreamAsync()) { requestStream.Write(_requestBodyBytes, 0, _requestBodyBytes.Length); } HttpWebResponse response = (HttpWebResponse) await request.GetResponseAsync(); Stream responseStream = response.GetResponseStream(); String responseBody; using (var sr = new StreamReader(responseStream)) { responseBody = sr.ReadToEnd(); } Assert.Equal(HttpStatusCode.OK, response.StatusCode); } [Theory, MemberData("EchoServers")] public void Abort_BeginGetRequestStreamThenAbort_EndGetRequestStreamThrowsWebException(Uri remoteServer) { _savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer); _savedHttpWebRequest.Method = "POST"; _savedHttpWebRequest.BeginGetResponse(new AsyncCallback(RequestStreamCallback), null); _savedHttpWebRequest.Abort(); _savedHttpWebRequest = null; WebException wex = _savedRequestStreamException as WebException; Assert.Equal(WebExceptionStatus.RequestCanceled, wex.Status); } [Theory, MemberData("EchoServers")] public void Abort_BeginGetResponseThenAbort_ResponseCallbackCalledBeforeAbortReturns(Uri remoteServer) { _savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer); _savedHttpWebRequest.BeginGetResponse(new AsyncCallback(ResponseCallback), null); _savedHttpWebRequest.Abort(); Assert.Equal(1, _responseCallbackCallCount); } [Theory, MemberData("EchoServers")] public void Abort_BeginGetResponseThenAbort_EndGetResponseThrowsWebException(Uri remoteServer) { _savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer); _savedHttpWebRequest.BeginGetResponse(new AsyncCallback(ResponseCallback), null); _savedHttpWebRequest.Abort(); WebException wex = _savedResponseException as WebException; Assert.Equal(WebExceptionStatus.RequestCanceled, wex.Status); } [Theory, MemberData("EchoServers")] public void Abort_BeginGetResponseUsingNoCallbackThenAbort_Success(Uri remoteServer) { _savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer); _savedHttpWebRequest.BeginGetResponse(null, null); _savedHttpWebRequest.Abort(); } [Theory, MemberData("EchoServers")] public void Abort_CreateRequestThenAbort_Success(Uri remoteServer) { _savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer); _savedHttpWebRequest.Abort(); } private void RequestStreamCallback(IAsyncResult asynchronousResult) { _requestStreamCallbackCallCount++; try { Stream stream = (Stream)_savedHttpWebRequest.EndGetRequestStream(asynchronousResult); stream.Dispose(); } catch (Exception ex) { _savedRequestStreamException = ex; } } private void ResponseCallback(IAsyncResult asynchronousResult) { _responseCallbackCallCount++; try { using (HttpWebResponse response = (HttpWebResponse)_savedHttpWebRequest.EndGetResponse(asynchronousResult)) { _savedResponseHeaders = response.Headers; } } catch (Exception ex) { _savedResponseException = ex; } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: tenancy_config/phone_code.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace HOLMS.Types.TenancyConfig { /// <summary>Holder for reflection information generated from tenancy_config/phone_code.proto</summary> public static partial class PhoneCodeReflection { #region Descriptor /// <summary>File descriptor for tenancy_config/phone_code.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static PhoneCodeReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Ch90ZW5hbmN5X2NvbmZpZy9waG9uZV9jb2RlLnByb3RvEhpob2xtcy50eXBl", "cy50ZW5hbmN5X2NvbmZpZxoUcHJpbWl0aXZlL3V1aWQucHJvdG8iigEKCVBo", "b25lQ29kZRInCgJpZBgBIAEoCzIbLmhvbG1zLnR5cGVzLnByaW1pdGl2ZS5V", "dWlkEhQKDHBob25lX251bWJlchgCIAEoCRI+Cgh1c2VfY2FzZRgDIAEoDjIs", "LmhvbG1zLnR5cGVzLnRlbmFuY3lfY29uZmlnLlBob25lQ29kZVVzZUNhc2Uq", "RQoQUGhvbmVDb2RlVXNlQ2FzZRIXChNUT0xMX0ZSRUVfQVJFQV9DT0RFEAAS", "GAoURElSRUNUT1JZX0FTU0lTVEFOQ0UQAUIrWg10ZW5hbmN5Y29uZmlnqgIZ", "SE9MTVMuVHlwZXMuVGVuYW5jeUNvbmZpZ2IGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::HOLMS.Types.Primitive.UuidReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(new[] {typeof(global::HOLMS.Types.TenancyConfig.PhoneCodeUseCase), }, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.TenancyConfig.PhoneCode), global::HOLMS.Types.TenancyConfig.PhoneCode.Parser, new[]{ "Id", "PhoneNumber", "UseCase" }, null, null, null) })); } #endregion } #region Enums public enum PhoneCodeUseCase { [pbr::OriginalName("TOLL_FREE_AREA_CODE")] TollFreeAreaCode = 0, [pbr::OriginalName("DIRECTORY_ASSISTANCE")] DirectoryAssistance = 1, } #endregion #region Messages public sealed partial class PhoneCode : pb::IMessage<PhoneCode> { private static readonly pb::MessageParser<PhoneCode> _parser = new pb::MessageParser<PhoneCode>(() => new PhoneCode()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<PhoneCode> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.TenancyConfig.PhoneCodeReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PhoneCode() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PhoneCode(PhoneCode other) : this() { Id = other.id_ != null ? other.Id.Clone() : null; phoneNumber_ = other.phoneNumber_; useCase_ = other.useCase_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PhoneCode Clone() { return new PhoneCode(this); } /// <summary>Field number for the "id" field.</summary> public const int IdFieldNumber = 1; private global::HOLMS.Types.Primitive.Uuid id_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.Uuid Id { get { return id_; } set { id_ = value; } } /// <summary>Field number for the "phone_number" field.</summary> public const int PhoneNumberFieldNumber = 2; private string phoneNumber_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string PhoneNumber { get { return phoneNumber_; } set { phoneNumber_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "use_case" field.</summary> public const int UseCaseFieldNumber = 3; private global::HOLMS.Types.TenancyConfig.PhoneCodeUseCase useCase_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.TenancyConfig.PhoneCodeUseCase UseCase { get { return useCase_; } set { useCase_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as PhoneCode); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(PhoneCode other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Id, other.Id)) return false; if (PhoneNumber != other.PhoneNumber) return false; if (UseCase != other.UseCase) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (id_ != null) hash ^= Id.GetHashCode(); if (PhoneNumber.Length != 0) hash ^= PhoneNumber.GetHashCode(); if (UseCase != 0) hash ^= UseCase.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (id_ != null) { output.WriteRawTag(10); output.WriteMessage(Id); } if (PhoneNumber.Length != 0) { output.WriteRawTag(18); output.WriteString(PhoneNumber); } if (UseCase != 0) { output.WriteRawTag(24); output.WriteEnum((int) UseCase); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (id_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Id); } if (PhoneNumber.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(PhoneNumber); } if (UseCase != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) UseCase); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(PhoneCode other) { if (other == null) { return; } if (other.id_ != null) { if (id_ == null) { id_ = new global::HOLMS.Types.Primitive.Uuid(); } Id.MergeFrom(other.Id); } if (other.PhoneNumber.Length != 0) { PhoneNumber = other.PhoneNumber; } if (other.UseCase != 0) { UseCase = other.UseCase; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (id_ == null) { id_ = new global::HOLMS.Types.Primitive.Uuid(); } input.ReadMessage(id_); break; } case 18: { PhoneNumber = input.ReadString(); break; } case 24: { useCase_ = (global::HOLMS.Types.TenancyConfig.PhoneCodeUseCase) input.ReadEnum(); break; } } } } } #endregion } #endregion Designer generated code
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: src/proto/grpc/testing/test.proto // Original file comments: // 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. // // An integration test service that covers all the method signature permutations // of unary/streaming requests/responses. // #region Designer generated code using System; using System.Threading; using System.Threading.Tasks; using Grpc.Core; namespace Grpc.Testing { /// <summary> /// A simple service to test the various types of RPCs and experiment with /// performance with various types of payload. /// </summary> public static partial class TestService { static readonly string __ServiceName = "grpc.testing.TestService"; static readonly Marshaller<global::Grpc.Testing.Empty> __Marshaller_Empty = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.Empty.Parser.ParseFrom); static readonly Marshaller<global::Grpc.Testing.SimpleRequest> __Marshaller_SimpleRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.SimpleRequest.Parser.ParseFrom); static readonly Marshaller<global::Grpc.Testing.SimpleResponse> __Marshaller_SimpleResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.SimpleResponse.Parser.ParseFrom); static readonly Marshaller<global::Grpc.Testing.StreamingOutputCallRequest> __Marshaller_StreamingOutputCallRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.StreamingOutputCallRequest.Parser.ParseFrom); static readonly Marshaller<global::Grpc.Testing.StreamingOutputCallResponse> __Marshaller_StreamingOutputCallResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.StreamingOutputCallResponse.Parser.ParseFrom); static readonly Marshaller<global::Grpc.Testing.StreamingInputCallRequest> __Marshaller_StreamingInputCallRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.StreamingInputCallRequest.Parser.ParseFrom); static readonly Marshaller<global::Grpc.Testing.StreamingInputCallResponse> __Marshaller_StreamingInputCallResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.StreamingInputCallResponse.Parser.ParseFrom); static readonly Method<global::Grpc.Testing.Empty, global::Grpc.Testing.Empty> __Method_EmptyCall = new Method<global::Grpc.Testing.Empty, global::Grpc.Testing.Empty>( MethodType.Unary, __ServiceName, "EmptyCall", __Marshaller_Empty, __Marshaller_Empty); static readonly Method<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse> __Method_UnaryCall = new Method<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse>( MethodType.Unary, __ServiceName, "UnaryCall", __Marshaller_SimpleRequest, __Marshaller_SimpleResponse); static readonly Method<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> __Method_StreamingOutputCall = new Method<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse>( MethodType.ServerStreaming, __ServiceName, "StreamingOutputCall", __Marshaller_StreamingOutputCallRequest, __Marshaller_StreamingOutputCallResponse); static readonly Method<global::Grpc.Testing.StreamingInputCallRequest, global::Grpc.Testing.StreamingInputCallResponse> __Method_StreamingInputCall = new Method<global::Grpc.Testing.StreamingInputCallRequest, global::Grpc.Testing.StreamingInputCallResponse>( MethodType.ClientStreaming, __ServiceName, "StreamingInputCall", __Marshaller_StreamingInputCallRequest, __Marshaller_StreamingInputCallResponse); static readonly Method<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> __Method_FullDuplexCall = new Method<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse>( MethodType.DuplexStreaming, __ServiceName, "FullDuplexCall", __Marshaller_StreamingOutputCallRequest, __Marshaller_StreamingOutputCallResponse); static readonly Method<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> __Method_HalfDuplexCall = new Method<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse>( MethodType.DuplexStreaming, __ServiceName, "HalfDuplexCall", __Marshaller_StreamingOutputCallRequest, __Marshaller_StreamingOutputCallResponse); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Grpc.Testing.TestReflection.Descriptor.Services[0]; } } /// <summary>Base class for server-side implementations of TestService</summary> public abstract partial class TestServiceBase { /// <summary> /// One empty request followed by one empty response. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.Empty> EmptyCall(global::Grpc.Testing.Empty request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// One request followed by one response. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.SimpleResponse> UnaryCall(global::Grpc.Testing.SimpleRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// One request followed by a sequence of responses (streamed download). /// The server returns the payload with client desired type and sizes. /// </summary> public virtual global::System.Threading.Tasks.Task StreamingOutputCall(global::Grpc.Testing.StreamingOutputCallRequest request, IServerStreamWriter<global::Grpc.Testing.StreamingOutputCallResponse> responseStream, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// A sequence of requests followed by one response (streamed upload). /// The server returns the aggregated size of client payload as the result. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.StreamingInputCallResponse> StreamingInputCall(IAsyncStreamReader<global::Grpc.Testing.StreamingInputCallRequest> requestStream, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// A sequence of requests with each request served by the server immediately. /// As one request could lead to multiple responses, this interface /// demonstrates the idea of full duplexing. /// </summary> public virtual global::System.Threading.Tasks.Task FullDuplexCall(IAsyncStreamReader<global::Grpc.Testing.StreamingOutputCallRequest> requestStream, IServerStreamWriter<global::Grpc.Testing.StreamingOutputCallResponse> responseStream, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// A sequence of requests followed by a sequence of responses. /// The server buffers all the client requests and then serves them in order. A /// stream of responses are returned to the client when the server starts with /// first request. /// </summary> public virtual global::System.Threading.Tasks.Task HalfDuplexCall(IAsyncStreamReader<global::Grpc.Testing.StreamingOutputCallRequest> requestStream, IServerStreamWriter<global::Grpc.Testing.StreamingOutputCallResponse> responseStream, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } } /// <summary>Client for TestService</summary> public partial class TestServiceClient : ClientBase<TestServiceClient> { /// <summary>Creates a new client for TestService</summary> /// <param name="channel">The channel to use to make remote calls.</param> public TestServiceClient(Channel channel) : base(channel) { } /// <summary>Creates a new client for TestService that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public TestServiceClient(CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected TestServiceClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected TestServiceClient(ClientBaseConfiguration configuration) : base(configuration) { } /// <summary> /// One empty request followed by one empty response. /// </summary> public virtual global::Grpc.Testing.Empty EmptyCall(global::Grpc.Testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return EmptyCall(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// One empty request followed by one empty response. /// </summary> public virtual global::Grpc.Testing.Empty EmptyCall(global::Grpc.Testing.Empty request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_EmptyCall, null, options, request); } /// <summary> /// One empty request followed by one empty response. /// </summary> public virtual AsyncUnaryCall<global::Grpc.Testing.Empty> EmptyCallAsync(global::Grpc.Testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return EmptyCallAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// One empty request followed by one empty response. /// </summary> public virtual AsyncUnaryCall<global::Grpc.Testing.Empty> EmptyCallAsync(global::Grpc.Testing.Empty request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_EmptyCall, null, options, request); } /// <summary> /// One request followed by one response. /// </summary> public virtual global::Grpc.Testing.SimpleResponse UnaryCall(global::Grpc.Testing.SimpleRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UnaryCall(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// One request followed by one response. /// </summary> public virtual global::Grpc.Testing.SimpleResponse UnaryCall(global::Grpc.Testing.SimpleRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_UnaryCall, null, options, request); } /// <summary> /// One request followed by one response. /// </summary> public virtual AsyncUnaryCall<global::Grpc.Testing.SimpleResponse> UnaryCallAsync(global::Grpc.Testing.SimpleRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UnaryCallAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// One request followed by one response. /// </summary> public virtual AsyncUnaryCall<global::Grpc.Testing.SimpleResponse> UnaryCallAsync(global::Grpc.Testing.SimpleRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_UnaryCall, null, options, request); } /// <summary> /// One request followed by a sequence of responses (streamed download). /// The server returns the payload with client desired type and sizes. /// </summary> public virtual AsyncServerStreamingCall<global::Grpc.Testing.StreamingOutputCallResponse> StreamingOutputCall(global::Grpc.Testing.StreamingOutputCallRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return StreamingOutputCall(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// One request followed by a sequence of responses (streamed download). /// The server returns the payload with client desired type and sizes. /// </summary> public virtual AsyncServerStreamingCall<global::Grpc.Testing.StreamingOutputCallResponse> StreamingOutputCall(global::Grpc.Testing.StreamingOutputCallRequest request, CallOptions options) { return CallInvoker.AsyncServerStreamingCall(__Method_StreamingOutputCall, null, options, request); } /// <summary> /// A sequence of requests followed by one response (streamed upload). /// The server returns the aggregated size of client payload as the result. /// </summary> public virtual AsyncClientStreamingCall<global::Grpc.Testing.StreamingInputCallRequest, global::Grpc.Testing.StreamingInputCallResponse> StreamingInputCall(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return StreamingInputCall(new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// A sequence of requests followed by one response (streamed upload). /// The server returns the aggregated size of client payload as the result. /// </summary> public virtual AsyncClientStreamingCall<global::Grpc.Testing.StreamingInputCallRequest, global::Grpc.Testing.StreamingInputCallResponse> StreamingInputCall(CallOptions options) { return CallInvoker.AsyncClientStreamingCall(__Method_StreamingInputCall, null, options); } /// <summary> /// A sequence of requests with each request served by the server immediately. /// As one request could lead to multiple responses, this interface /// demonstrates the idea of full duplexing. /// </summary> public virtual AsyncDuplexStreamingCall<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> FullDuplexCall(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return FullDuplexCall(new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// A sequence of requests with each request served by the server immediately. /// As one request could lead to multiple responses, this interface /// demonstrates the idea of full duplexing. /// </summary> public virtual AsyncDuplexStreamingCall<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> FullDuplexCall(CallOptions options) { return CallInvoker.AsyncDuplexStreamingCall(__Method_FullDuplexCall, null, options); } /// <summary> /// A sequence of requests followed by a sequence of responses. /// The server buffers all the client requests and then serves them in order. A /// stream of responses are returned to the client when the server starts with /// first request. /// </summary> public virtual AsyncDuplexStreamingCall<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> HalfDuplexCall(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return HalfDuplexCall(new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// A sequence of requests followed by a sequence of responses. /// The server buffers all the client requests and then serves them in order. A /// stream of responses are returned to the client when the server starts with /// first request. /// </summary> public virtual AsyncDuplexStreamingCall<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> HalfDuplexCall(CallOptions options) { return CallInvoker.AsyncDuplexStreamingCall(__Method_HalfDuplexCall, null, options); } protected override TestServiceClient NewInstance(ClientBaseConfiguration configuration) { return new TestServiceClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> public static ServerServiceDefinition BindService(TestServiceBase serviceImpl) { return ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_EmptyCall, serviceImpl.EmptyCall) .AddMethod(__Method_UnaryCall, serviceImpl.UnaryCall) .AddMethod(__Method_StreamingOutputCall, serviceImpl.StreamingOutputCall) .AddMethod(__Method_StreamingInputCall, serviceImpl.StreamingInputCall) .AddMethod(__Method_FullDuplexCall, serviceImpl.FullDuplexCall) .AddMethod(__Method_HalfDuplexCall, serviceImpl.HalfDuplexCall).Build(); } } /// <summary> /// A simple service NOT implemented at servers so clients can test for /// that case. /// </summary> public static partial class UnimplementedService { static readonly string __ServiceName = "grpc.testing.UnimplementedService"; static readonly Marshaller<global::Grpc.Testing.Empty> __Marshaller_Empty = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.Empty.Parser.ParseFrom); static readonly Method<global::Grpc.Testing.Empty, global::Grpc.Testing.Empty> __Method_UnimplementedCall = new Method<global::Grpc.Testing.Empty, global::Grpc.Testing.Empty>( MethodType.Unary, __ServiceName, "UnimplementedCall", __Marshaller_Empty, __Marshaller_Empty); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Grpc.Testing.TestReflection.Descriptor.Services[1]; } } /// <summary>Base class for server-side implementations of UnimplementedService</summary> public abstract partial class UnimplementedServiceBase { /// <summary> /// A call that no server should implement /// </summary> public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.Empty> UnimplementedCall(global::Grpc.Testing.Empty request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } } /// <summary>Client for UnimplementedService</summary> public partial class UnimplementedServiceClient : ClientBase<UnimplementedServiceClient> { /// <summary>Creates a new client for UnimplementedService</summary> /// <param name="channel">The channel to use to make remote calls.</param> public UnimplementedServiceClient(Channel channel) : base(channel) { } /// <summary>Creates a new client for UnimplementedService that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public UnimplementedServiceClient(CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected UnimplementedServiceClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected UnimplementedServiceClient(ClientBaseConfiguration configuration) : base(configuration) { } /// <summary> /// A call that no server should implement /// </summary> public virtual global::Grpc.Testing.Empty UnimplementedCall(global::Grpc.Testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UnimplementedCall(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// A call that no server should implement /// </summary> public virtual global::Grpc.Testing.Empty UnimplementedCall(global::Grpc.Testing.Empty request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_UnimplementedCall, null, options, request); } /// <summary> /// A call that no server should implement /// </summary> public virtual AsyncUnaryCall<global::Grpc.Testing.Empty> UnimplementedCallAsync(global::Grpc.Testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UnimplementedCallAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// A call that no server should implement /// </summary> public virtual AsyncUnaryCall<global::Grpc.Testing.Empty> UnimplementedCallAsync(global::Grpc.Testing.Empty request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_UnimplementedCall, null, options, request); } protected override UnimplementedServiceClient NewInstance(ClientBaseConfiguration configuration) { return new UnimplementedServiceClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> public static ServerServiceDefinition BindService(UnimplementedServiceBase serviceImpl) { return ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_UnimplementedCall, serviceImpl.UnimplementedCall).Build(); } } /// <summary> /// A service used to control reconnect server. /// </summary> public static partial class ReconnectService { static readonly string __ServiceName = "grpc.testing.ReconnectService"; static readonly Marshaller<global::Grpc.Testing.ReconnectParams> __Marshaller_ReconnectParams = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.ReconnectParams.Parser.ParseFrom); static readonly Marshaller<global::Grpc.Testing.Empty> __Marshaller_Empty = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.Empty.Parser.ParseFrom); static readonly Marshaller<global::Grpc.Testing.ReconnectInfo> __Marshaller_ReconnectInfo = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.ReconnectInfo.Parser.ParseFrom); static readonly Method<global::Grpc.Testing.ReconnectParams, global::Grpc.Testing.Empty> __Method_Start = new Method<global::Grpc.Testing.ReconnectParams, global::Grpc.Testing.Empty>( MethodType.Unary, __ServiceName, "Start", __Marshaller_ReconnectParams, __Marshaller_Empty); static readonly Method<global::Grpc.Testing.Empty, global::Grpc.Testing.ReconnectInfo> __Method_Stop = new Method<global::Grpc.Testing.Empty, global::Grpc.Testing.ReconnectInfo>( MethodType.Unary, __ServiceName, "Stop", __Marshaller_Empty, __Marshaller_ReconnectInfo); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Grpc.Testing.TestReflection.Descriptor.Services[2]; } } /// <summary>Base class for server-side implementations of ReconnectService</summary> public abstract partial class ReconnectServiceBase { public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.Empty> Start(global::Grpc.Testing.ReconnectParams request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.ReconnectInfo> Stop(global::Grpc.Testing.Empty request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } } /// <summary>Client for ReconnectService</summary> public partial class ReconnectServiceClient : ClientBase<ReconnectServiceClient> { /// <summary>Creates a new client for ReconnectService</summary> /// <param name="channel">The channel to use to make remote calls.</param> public ReconnectServiceClient(Channel channel) : base(channel) { } /// <summary>Creates a new client for ReconnectService that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public ReconnectServiceClient(CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected ReconnectServiceClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected ReconnectServiceClient(ClientBaseConfiguration configuration) : base(configuration) { } public virtual global::Grpc.Testing.Empty Start(global::Grpc.Testing.ReconnectParams request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return Start(request, new CallOptions(headers, deadline, cancellationToken)); } public virtual global::Grpc.Testing.Empty Start(global::Grpc.Testing.ReconnectParams request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_Start, null, options, request); } public virtual AsyncUnaryCall<global::Grpc.Testing.Empty> StartAsync(global::Grpc.Testing.ReconnectParams request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return StartAsync(request, new CallOptions(headers, deadline, cancellationToken)); } public virtual AsyncUnaryCall<global::Grpc.Testing.Empty> StartAsync(global::Grpc.Testing.ReconnectParams request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_Start, null, options, request); } public virtual global::Grpc.Testing.ReconnectInfo Stop(global::Grpc.Testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return Stop(request, new CallOptions(headers, deadline, cancellationToken)); } public virtual global::Grpc.Testing.ReconnectInfo Stop(global::Grpc.Testing.Empty request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_Stop, null, options, request); } public virtual AsyncUnaryCall<global::Grpc.Testing.ReconnectInfo> StopAsync(global::Grpc.Testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return StopAsync(request, new CallOptions(headers, deadline, cancellationToken)); } public virtual AsyncUnaryCall<global::Grpc.Testing.ReconnectInfo> StopAsync(global::Grpc.Testing.Empty request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_Stop, null, options, request); } protected override ReconnectServiceClient NewInstance(ClientBaseConfiguration configuration) { return new ReconnectServiceClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> public static ServerServiceDefinition BindService(ReconnectServiceBase serviceImpl) { return ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_Start, serviceImpl.Start) .AddMethod(__Method_Stop, serviceImpl.Stop).Build(); } } } #endregion
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2009, 2010 Oracle and/or its affiliates. All rights reserved. * */ using System; using System.Collections; using System.Collections.Generic; using System.Text; using BerkeleyDB.Internal; namespace BerkeleyDB { /// <summary> /// A class representing database cursors over secondary indexes, which /// allow for traversal of database records. /// </summary> public class SecondaryCursor : BaseCursor, IEnumerable<KeyValuePair<DatabaseEntry, KeyValuePair<DatabaseEntry, DatabaseEntry>>> { private KeyValuePair<DatabaseEntry, KeyValuePair<DatabaseEntry, DatabaseEntry>> cur; /// <summary> /// The secondary key and primary key/data pair at which the cursor /// currently points. /// </summary> public KeyValuePair<DatabaseEntry, KeyValuePair<DatabaseEntry, DatabaseEntry>> Current { get { return cur; } private set { cur = value; } } internal SecondaryCursor(DBC dbc) : base(dbc) { } /// <summary> /// Protected method wrapping DBC->pget() /// </summary> /// <param name="key">The secondary key</param> /// <param name="pkey">The primary key</param> /// <param name="data">The primary data</param> /// <param name="flags">Flags to pass to DBC->pget</param> /// <param name="info">Locking parameters</param> /// <returns></returns> protected bool PGet( DatabaseEntry key, DatabaseEntry pkey, DatabaseEntry data, uint flags, LockingInfo info) { flags |= (info == null) ? 0 : info.flags; try { dbc.pget(key, pkey, data, flags); Current = new KeyValuePair<DatabaseEntry, KeyValuePair<DatabaseEntry, DatabaseEntry>>(key, new KeyValuePair<DatabaseEntry, DatabaseEntry>(pkey, data)); return true; } catch (NotFoundException) { Current = new KeyValuePair<DatabaseEntry, KeyValuePair<DatabaseEntry, DatabaseEntry>>( null, new KeyValuePair<DatabaseEntry, DatabaseEntry>()); return false; } } /// <summary> /// Delete the key/data pair to which the cursor refers from the primary /// database and all secondary indices. /// </summary> /// <remarks> /// <para> /// The cursor position is unchanged after a delete, and subsequent /// calls to cursor functions expecting the cursor to refer to an /// existing key will fail. /// </para> /// </remarks> /// <exception cref="KeyEmptyException"> /// The element has already been deleted. /// </exception> public new void Delete() { base.Delete(); Current = new KeyValuePair<DatabaseEntry, KeyValuePair<DatabaseEntry, DatabaseEntry>>( null, new KeyValuePair<DatabaseEntry, DatabaseEntry>()); } /// <summary> /// Create a new cursor that uses the same transaction and locker ID as /// the original cursor. /// </summary> /// <remarks> /// This is useful when an application is using locking and requires two /// or more cursors in the same thread of control. /// </remarks> /// <param name="keepPosition"> /// If true, the newly created cursor is initialized to refer to the /// same position in the database as the original cursor (if any) and /// hold the same locks (if any). If false, or the original cursor does /// not hold a database position and locks, the created cursor is /// uninitialized and will behave like a cursor newly created by /// <see cref="BaseDatabase.Cursor"/>.</param> /// <returns>A newly created cursor</returns> public SecondaryCursor Duplicate(bool keepPosition) { return new SecondaryCursor( dbc.dup(keepPosition ? DbConstants.DB_POSITION : 0)); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through the /// <see cref="SecondaryCursor"/>. /// </summary> /// <remarks> /// The enumerator will begin at the cursor's current position (or the /// first record if the cursor has not yet been positioned) and iterate /// forwards (i.e. in the direction of <see cref="MoveNext"/>) over the /// remaining records. /// </remarks> /// <returns>An enumerator for the SecondaryCursor.</returns> public new IEnumerator<KeyValuePair<DatabaseEntry, KeyValuePair<DatabaseEntry, DatabaseEntry>>> GetEnumerator() { while (MoveNext()) yield return Current; } /// <summary> /// Set the cursor to refer to the first key/data pair of the database, /// and store the secondary key along with the corresponding primary /// key/data pair in <see cref="Current"/>. If the first key has /// duplicate values, the first data item in the set of duplicates is /// stored in <see cref="Current"/>. /// </summary> /// <remarks> /// If positioning the cursor fails, <see cref="Current"/> will contain /// an empty <see cref="KeyValuePair{T,T}"/>. /// </remarks> /// <returns> /// True if the cursor was positioned successfully, false otherwise. /// </returns> public bool MoveFirst() { return MoveFirst(null); } /// <summary> /// Set the cursor to refer to the first key/data pair of the database, /// and store the secondary key along with the corresponding primary /// key/data pair in <see cref="Current"/>. If the first key has /// duplicate values, the first data item in the set of duplicates is /// stored in <see cref="Current"/>. /// </summary> /// <remarks> /// If positioning the cursor fails, <see cref="Current"/> will contain /// an empty <see cref="KeyValuePair{T,T}"/>. /// </remarks> /// <param name="info">The locking behavior to use.</param> /// <returns> /// True if the cursor was positioned successfully, false otherwise. /// </returns> public bool MoveFirst(LockingInfo info) { DatabaseEntry key = new DatabaseEntry(); DatabaseEntry pkey = new DatabaseEntry(); DatabaseEntry data = new DatabaseEntry(); return PGet(key, pkey, data, DbConstants.DB_FIRST, info); } /// <summary> /// Set the cursor to refer to <paramref name="key"/>, and store the /// primary key/data pair associated with the given secondary key in /// <see cref="Current"/>. In the presence of duplicate key values, the /// first data item in the set of duplicates is stored in /// <see cref="Current"/>. /// </summary> /// <remarks> /// If positioning the cursor fails, <see cref="Current"/> will contain /// an empty <see cref="KeyValuePair{T,T}"/>. /// </remarks> /// <param name="key">The key at which to position the cursor</param> /// <param name="exact"> /// If false and in a database configured for sorted duplicates, /// position the cursor at the smallest key greater than or equal to the /// specified key, permitting partial key matches and range searches. /// Otherwise, require the given key to match the key in the database /// exactly. /// </param> /// <returns> /// True if the cursor was positioned successfully, false otherwise. /// </returns> public bool Move(DatabaseEntry key, bool exact) { return Move(key, exact, null); } /// <summary> /// Set the cursor to refer to <paramref name="key"/>, and store the /// primary key/data pair associated with the given secondary key in /// <see cref="Current"/>. In the presence of duplicate key values, the /// first data item in the set of duplicates is stored in /// <see cref="Current"/>. /// </summary> /// <remarks> /// If positioning the cursor fails, <see cref="Current"/> will contain /// an empty <see cref="KeyValuePair{T,T}"/>. /// </remarks> /// <param name="key">The key at which to position the cursor</param> /// <param name="exact"> /// If false and in a database configured for sorted duplicates, /// position the cursor at the smallest key greater than or equal to the /// specified key, permitting partial key matches and range searches. /// Otherwise, require the given key to match the key in the database /// exactly. /// </param> /// <param name="info">The locking behavior to use.</param> /// <returns> /// True if the cursor was positioned successfully, false otherwise. /// </returns> public bool Move(DatabaseEntry key, bool exact, LockingInfo info) { DatabaseEntry pkey = new DatabaseEntry(); DatabaseEntry data = new DatabaseEntry(); return PGet(key, pkey, data, exact ? DbConstants.DB_SET : DbConstants.DB_SET_RANGE, info); } /// <summary> /// Move the cursor to the specified key/data pair of the database. The /// cursor is positioned to a key/data pair if both the key and data /// match the values provided on the key and data parameters. /// </summary> /// <remarks> /// <para> /// If positioning the cursor fails, <see cref="Current"/> will contain /// an empty <see cref="KeyValuePair{T,T}"/>. /// </para> /// <para> /// If this flag is specified on a database configured without sorted /// duplicate support, the value of <paramref name="exact"/> is ignored. /// </para> /// </remarks> /// <param name="pair"> /// The key/data pair at which to position the cursor. /// </param> /// <param name="exact"> /// If false and in a database configured for sorted duplicates, /// position the cursor at the smallest data value which is greater than /// or equal to the value provided by <paramref name="pair.Value"/> (as /// determined by the comparison function). Otherwise, require the given /// key and data to match the key and data in the database exactly. /// </param> /// <returns> /// True if the cursor was positioned successfully, false otherwise. /// </returns> public bool Move(KeyValuePair<DatabaseEntry, KeyValuePair<DatabaseEntry, DatabaseEntry>> pair, bool exact) { return Move(pair, exact, null); } /// <summary> /// Move the cursor to the specified key/data pair of the database. The /// cursor is positioned to a key/data pair if both the key and data /// match the values provided on the key and data parameters. /// </summary> /// <remarks> /// <para> /// If positioning the cursor fails, <see cref="Current"/> will contain /// an empty <see cref="KeyValuePair{T,T}"/>. /// </para> /// <para> /// If this flag is specified on a database configured without sorted /// duplicate support, the value of <paramref name="exact"/> is ignored. /// </para> /// </remarks> /// <param name="pair"> /// The key/data pair at which to position the cursor. /// </param> /// <param name="exact"> /// If false and in a database configured for sorted duplicates, /// position the cursor at the smallest data value which is greater than /// or equal to the value provided by <paramref name="pair.Value"/> (as /// determined by the comparison function). Otherwise, require the given /// key and data to match the key and data in the database exactly. /// </param> /// <param name="info">The locking behavior to use.</param> /// <returns> /// True if the cursor was positioned successfully, false otherwise. /// </returns> public bool Move(KeyValuePair<DatabaseEntry, KeyValuePair<DatabaseEntry, DatabaseEntry>> pair, bool exact, LockingInfo info) { return PGet(pair.Key, pair.Value.Key, pair.Value.Value, exact ? DbConstants.DB_GET_BOTH : DbConstants.DB_GET_BOTH_RANGE, info); } /// <summary> /// Set the cursor to refer to the last key/data pair of the database, /// and store the secondary key and primary key/data pair in /// <see cref="Current"/>. If the last key has duplicate values, the /// last data item in the set of duplicates is stored in /// <see cref="Current"/>. /// </summary> /// <remarks> /// If positioning the cursor fails, <see cref="Current"/> will contain /// an empty <see cref="KeyValuePair{T,T}"/>. /// </remarks> /// <returns> /// True if the cursor was positioned successfully, false otherwise. /// </returns> public bool MoveLast() { return MoveLast(null); } /// <summary> /// Set the cursor to refer to the last key/data pair of the database, /// and store the secondary key and primary key/data pair in /// <see cref="Current"/>. If the last key has duplicate values, the /// last data item in the set of duplicates is stored in /// <see cref="Current"/>. /// </summary> /// <remarks> /// If positioning the cursor fails, <see cref="Current"/> will contain /// an empty <see cref="KeyValuePair{T,T}"/>. /// </remarks> /// <param name="info">The locking behavior to use.</param> /// <returns> /// True if the cursor was positioned successfully, false otherwise. /// </returns> public bool MoveLast(LockingInfo info) { DatabaseEntry key = new DatabaseEntry(); DatabaseEntry pkey = new DatabaseEntry(); DatabaseEntry data = new DatabaseEntry(); return PGet(key, pkey, data, DbConstants.DB_LAST, info); } /// <summary> /// If the cursor is not yet initialized, MoveNext is identical to /// <see cref="MoveFirst()"/>. Otherwise, move the cursor to the next /// key/data pair of the database, and store the secondary key and /// primary key/data pair in <see cref="Current"/>. In the presence of /// duplicate key values, the value of <see cref="Current">Current.Key /// </see> may not change. /// </summary> /// <remarks> /// If positioning the cursor fails, <see cref="Current"/> will contain /// an empty <see cref="KeyValuePair{T,T}"/>. /// </remarks> /// <returns> /// True if the cursor was positioned successfully, false otherwise. /// </returns> public bool MoveNext() { return MoveNext(null); } /// <summary> /// If the cursor is not yet initialized, MoveNext is identical to /// <see cref="MoveFirst()"/>. Otherwise, move the cursor to the next /// key/data pair of the database, and store the secondary key and /// primary key/data pair in <see cref="Current"/>. In the presence of /// duplicate key values, the value of <see cref="Current">Current.Key /// </see> may not change. /// </summary> /// <remarks> /// If positioning the cursor fails, <see cref="Current"/> will contain /// an empty <see cref="KeyValuePair{T,T}"/>. /// </remarks> /// <param name="info">The locking behavior to use.</param> /// <returns> /// True if the cursor was positioned successfully, false otherwise. /// </returns> public bool MoveNext(LockingInfo info) { DatabaseEntry key = new DatabaseEntry(); DatabaseEntry pkey = new DatabaseEntry(); DatabaseEntry data = new DatabaseEntry(); return PGet(key, pkey, data, DbConstants.DB_NEXT, info); } /// <summary> /// If the next key/data pair of the database is a duplicate data record /// for the current key/data pair, move the cursor to the next key/data /// pair in the database, and store the secondary key and primary /// key/data pair in <see cref="Current"/>. MoveNextDuplicate will /// return false if the next key/data pair of the database is not a /// duplicate data record for the current key/data pair. /// </summary> /// <remarks> /// If positioning the cursor fails, <see cref="Current"/> will contain /// an empty <see cref="KeyValuePair{T,T}"/>. /// </remarks> /// <returns> /// True if the cursor was positioned successfully, false otherwise. /// </returns> public bool MoveNextDuplicate() { return MoveNextDuplicate(null); } /// <summary> /// If the next key/data pair of the database is a duplicate data record /// for the current key/data pair, move the cursor to the next key/data /// pair in the database, and store the secondary key and primary /// key/data pair in <see cref="Current"/>. MoveNextDuplicate will /// return false if the next key/data pair of the database is not a /// duplicate data record for the current key/data pair. /// </summary> /// <remarks> /// If positioning the cursor fails, <see cref="Current"/> will contain /// an empty <see cref="KeyValuePair{T,T}"/>. /// </remarks> /// <param name="info">The locking behavior to use.</param> /// <returns> /// True if the cursor was positioned successfully, false otherwise. /// </returns> public bool MoveNextDuplicate(LockingInfo info) { DatabaseEntry key = new DatabaseEntry(); DatabaseEntry pkey = new DatabaseEntry(); DatabaseEntry data = new DatabaseEntry(); return PGet(key, pkey, data, DbConstants.DB_NEXT_DUP, info); } /// <summary> /// If the cursor is not yet initialized, MoveNextUnique is identical to /// <see cref="MoveFirst()"/>. Otherwise, move the cursor to the next /// non-duplicate key in the database, and store the secondary key and /// primary key/data pair in <see cref="Current"/>. MoveNextUnique will /// return false if no non-duplicate key/data pairs exist after the /// cursor position in the database. /// </summary> /// <remarks> /// If positioning the cursor fails, <see cref="Current"/> will contain /// an empty <see cref="KeyValuePair{T,T}"/>. /// </remarks> /// <returns> /// True if the cursor was positioned successfully, false otherwise. /// </returns> public bool MoveNextUnique() { return MoveNextUnique(null); } /// <summary> /// If the cursor is not yet initialized, MoveNextUnique is identical to /// <see cref="MoveFirst()"/>. Otherwise, move the cursor to the next /// non-duplicate key in the database, and store the secondary key and /// primary key/data pair in <see cref="Current"/>. MoveNextUnique will /// return false if no non-duplicate key/data pairs exist after the /// cursor position in the database. /// </summary> /// <remarks> /// <para> /// If the database is a Queue or Recno database, MoveNextUnique will /// ignore any keys that exist but were never explicitly created by the /// application, or those that were created and later deleted. /// </para> /// <para> /// If positioning the cursor fails, <see cref="Current"/> will contain /// an empty <see cref="KeyValuePair{T,T}"/>. /// </para> /// </remarks> /// <param name="info">The locking behavior to use.</param> /// <returns> /// True if the cursor was positioned successfully, false otherwise. /// </returns> public bool MoveNextUnique(LockingInfo info) { DatabaseEntry key = new DatabaseEntry(); DatabaseEntry pkey = new DatabaseEntry(); DatabaseEntry data = new DatabaseEntry(); return PGet(key, pkey, data, DbConstants.DB_NEXT_NODUP, info); } /// <summary> /// If the cursor is not yet initialized, MovePrev is identical to /// <see cref="MoveLast()"/>. Otherwise, move the cursor to the previous /// key/data pair of the database, and store the secondary key and /// primary key/data pair in <see cref="Current"/>. In the presence of /// duplicate key values, the value of <see cref="Current">Current.Key /// </see> may not change. /// </summary> /// <remarks> /// If positioning the cursor fails, <see cref="Current"/> will contain /// an empty <see cref="KeyValuePair{T,T}"/>. /// </remarks> /// <returns> /// True if the cursor was positioned successfully, false otherwise. /// </returns> public bool MovePrev() { return MovePrev(null); } /// <summary> /// If the cursor is not yet initialized, MovePrev is identical to /// <see cref="MoveLast(LockingInfo)"/>. Otherwise, move the cursor to /// the previous key/data pair of the database, and store the secondary /// key and primary key/data pair in <see cref="Current"/>. In the /// presence of duplicate key values, the value of <see cref="Current"> /// Current.Key</see> may not change. /// </summary> /// <remarks> /// If positioning the cursor fails, <see cref="Current"/> will contain /// an empty <see cref="KeyValuePair{T,T}"/>. /// </remarks> /// <param name="info">The locking behavior to use.</param> /// <returns> /// True if the cursor was positioned successfully, false otherwise. /// </returns> public bool MovePrev(LockingInfo info) { DatabaseEntry key = new DatabaseEntry(); DatabaseEntry pkey = new DatabaseEntry(); DatabaseEntry data = new DatabaseEntry(); return PGet(key, pkey, data, DbConstants.DB_PREV, info); } /// <summary> /// If the previous key/data pair of the database is a duplicate data /// record for the current key/data pair, the cursor is moved to the /// previous key/data pair of the database, and the secondary key and /// primary key/data pair in <see cref="Current"/>. MovePrevDuplicate /// will return false if the previous key/data pair of the database is /// not a duplicate data record for the current key/data pair. /// </summary> /// <remarks> /// If positioning the cursor fails, <see cref="Current"/> will contain /// an empty <see cref="KeyValuePair{T,T}"/>. /// </remarks> /// <returns> /// True if the cursor was positioned successfully, false otherwise. /// </returns> public bool MovePrevDuplicate() { return MovePrevDuplicate(null); } /// <summary> /// If the previous key/data pair of the database is a duplicate data /// record for the current key/data pair, the cursor is moved to the /// previous key/data pair of the database, and the secondary key and /// primary key/data pair in <see cref="Current"/>. MovePrevDuplicate /// will return false if the previous key/data pair of the database is /// not a duplicate data record for the current key/data pair. /// </summary> /// <remarks> /// If positioning the cursor fails, <see cref="Current"/> will contain /// an empty <see cref="KeyValuePair{T,T}"/>. /// </remarks> /// <param name="info">The locking behavior to use.</param> /// <returns> /// True if the cursor was positioned successfully, false otherwise. /// </returns> public bool MovePrevDuplicate(LockingInfo info) { DatabaseEntry key = new DatabaseEntry(); DatabaseEntry pkey = new DatabaseEntry(); DatabaseEntry data = new DatabaseEntry(); return PGet(key, pkey, data, DbConstants.DB_PREV_DUP, info); } /// <summary> /// If the cursor is not yet initialized, MovePrevUnique is identical to /// <see cref="MoveLast()"/>. Otherwise, move the cursor to the previous /// non-duplicate key in the database, and store the secondary key and /// primary key/data pair in <see cref="Current"/>. MovePrevUnique will /// return false if no non-duplicate key/data pairs exist after the /// cursor position in the database. /// </summary> /// <remarks> /// If positioning the cursor fails, <see cref="Current"/> will contain /// an empty <see cref="KeyValuePair{T,T}"/>. /// </remarks> /// <returns> /// True if the cursor was positioned successfully, false otherwise. /// </returns> public bool MovePrevUnique() { return MovePrevUnique(null); } /// <summary> /// If the cursor is not yet initialized, MovePrevUnique is identical to /// <see cref="MoveLast(LockingInfo)"/>. Otherwise, move the cursor to /// the previous non-duplicate key in the database, and store the /// secondary key and primary key/data pair in <see cref="Current"/>. /// MovePrevUnique will return false if no non-duplicate key/data pairs /// exist after the cursor position in the database. /// </summary> /// <remarks> /// If positioning the cursor fails, <see cref="Current"/> will contain /// an empty <see cref="KeyValuePair{T,T}"/>. /// </remarks> /// <param name="info">The locking behavior to use.</param> /// <returns> /// True if the cursor was positioned successfully, false otherwise. /// </returns> public bool MovePrevUnique(LockingInfo info) { DatabaseEntry key = new DatabaseEntry(); DatabaseEntry pkey = new DatabaseEntry(); DatabaseEntry data = new DatabaseEntry(); return PGet(key, pkey, data, DbConstants.DB_PREV_NODUP, info); } /// <summary> /// Store the secondary key and primary key/data pair to which the /// cursor refers in <see cref="Current"/>. /// </summary> /// <remarks> /// If positioning the cursor fails, <see cref="Current"/> will contain /// an empty <see cref="KeyValuePair{T,T}"/>. /// </remarks> /// <returns> /// True if the cursor was positioned successfully, false otherwise. /// </returns> public bool Refresh() { return Refresh(null); } /// <summary> /// Store the secondary key and primary key/data pair to which the /// cursor refers in <see cref="Current"/>. /// </summary> /// <remarks> /// If positioning the cursor fails, <see cref="Current"/> will contain /// an empty <see cref="KeyValuePair{T,T}"/>. /// </remarks> /// <param name="info">The locking behavior to use.</param> /// <returns> /// True if the cursor was positioned successfully, false otherwise. /// </returns> public bool Refresh(LockingInfo info) { DatabaseEntry key = new DatabaseEntry(); DatabaseEntry pkey = new DatabaseEntry(); DatabaseEntry data = new DatabaseEntry(); return PGet(key, pkey, data, DbConstants.DB_CURRENT, info); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Text; using System.Threading; using System.Timers; using Timer = System.Timers.Timer; using Nini.Config; using NUnit.Framework; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.ClientStack.Linden; using OpenSim.Region.CoreModules.Framework.EntityTransfer; using OpenSim.Region.CoreModules.World.Serialiser; using OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation; using OpenSim.Tests.Common; using OpenSim.Tests.Common.Mock; using GridRegion = OpenSim.Services.Interfaces.GridRegion; namespace OpenSim.Region.Framework.Scenes.Tests { /// <summary> /// Scene presence tests /// </summary> [TestFixture] public class ScenePresenceAgentTests : OpenSimTestCase { // public Scene scene, scene2, scene3; // public UUID agent1, agent2, agent3; // public static Random random; // public ulong region1, region2, region3; // public AgentCircuitData acd1; // public TestClient testclient; // [TestFixtureSetUp] // public void Init() // { //// TestHelpers.InMethod(); //// //// SceneHelpers sh = new SceneHelpers(); //// //// scene = sh.SetupScene("Neighbour x", UUID.Random(), 1000, 1000); //// scene2 = sh.SetupScene("Neighbour x+1", UUID.Random(), 1001, 1000); //// scene3 = sh.SetupScene("Neighbour x-1", UUID.Random(), 999, 1000); //// //// ISharedRegionModule interregionComms = new LocalSimulationConnectorModule(); //// interregionComms.Initialise(new IniConfigSource()); //// interregionComms.PostInitialise(); //// SceneHelpers.SetupSceneModules(scene, new IniConfigSource(), interregionComms); //// SceneHelpers.SetupSceneModules(scene2, new IniConfigSource(), interregionComms); //// SceneHelpers.SetupSceneModules(scene3, new IniConfigSource(), interregionComms); // //// agent1 = UUID.Random(); //// agent2 = UUID.Random(); //// agent3 = UUID.Random(); // //// region1 = scene.RegionInfo.RegionHandle; //// region2 = scene2.RegionInfo.RegionHandle; //// region3 = scene3.RegionInfo.RegionHandle; // } [Test] public void TestCreateRootScenePresence() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); UUID spUuid = TestHelpers.ParseTail(0x1); TestScene scene = new SceneHelpers().SetupScene(); SceneHelpers.AddScenePresence(scene, spUuid); Assert.That(scene.AuthenticateHandler.GetAgentCircuitData(spUuid), Is.Not.Null); Assert.That(scene.AuthenticateHandler.GetAgentCircuits().Count, Is.EqualTo(1)); ScenePresence sp = scene.GetScenePresence(spUuid); Assert.That(sp, Is.Not.Null); Assert.That(sp.IsChildAgent, Is.False); Assert.That(sp.UUID, Is.EqualTo(spUuid)); Assert.That(scene.GetScenePresences().Count, Is.EqualTo(1)); } /// <summary> /// Test that duplicate complete movement calls are ignored. /// </summary> /// <remarks> /// If duplicate calls are not ignored then there is a risk of race conditions or other unexpected effects. /// </remarks> [Test] public void TestDupeCompleteMovementCalls() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); UUID spUuid = TestHelpers.ParseTail(0x1); TestScene scene = new SceneHelpers().SetupScene(); int makeRootAgentEvents = 0; scene.EventManager.OnMakeRootAgent += spi => makeRootAgentEvents++; ScenePresence sp = SceneHelpers.AddScenePresence(scene, spUuid); Assert.That(makeRootAgentEvents, Is.EqualTo(1)); // Normally these would be invoked by a CompleteMovement message coming in to the UDP stack. But for // convenience, here we will invoke it manually. sp.CompleteMovement(sp.ControllingClient, true); Assert.That(makeRootAgentEvents, Is.EqualTo(1)); // Check rest of exepcted parameters. Assert.That(scene.AuthenticateHandler.GetAgentCircuitData(spUuid), Is.Not.Null); Assert.That(scene.AuthenticateHandler.GetAgentCircuits().Count, Is.EqualTo(1)); Assert.That(sp.IsChildAgent, Is.False); Assert.That(sp.UUID, Is.EqualTo(spUuid)); Assert.That(scene.GetScenePresences().Count, Is.EqualTo(1)); } [Test] public void TestCreateDuplicateRootScenePresence() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); UUID spUuid = TestHelpers.ParseTail(0x1); // The etm is only invoked by this test to check whether an agent is still in transit if there is a dupe EntityTransferModule etm = new EntityTransferModule(); IConfigSource config = new IniConfigSource(); IConfig modulesConfig = config.AddConfig("Modules"); modulesConfig.Set("EntityTransferModule", etm.Name); IConfig entityTransferConfig = config.AddConfig("EntityTransfer"); // In order to run a single threaded regression test we do not want the entity transfer module waiting // for a callback from the destination scene before removing its avatar data. entityTransferConfig.Set("wait_for_callback", false); TestScene scene = new SceneHelpers().SetupScene(); SceneHelpers.SetupSceneModules(scene, config, etm); SceneHelpers.AddScenePresence(scene, spUuid); SceneHelpers.AddScenePresence(scene, spUuid); Assert.That(scene.AuthenticateHandler.GetAgentCircuitData(spUuid), Is.Not.Null); Assert.That(scene.AuthenticateHandler.GetAgentCircuits().Count, Is.EqualTo(1)); ScenePresence sp = scene.GetScenePresence(spUuid); Assert.That(sp, Is.Not.Null); Assert.That(sp.IsChildAgent, Is.False); Assert.That(sp.UUID, Is.EqualTo(spUuid)); } [Test] public void TestCloseClient() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); TestScene scene = new SceneHelpers().SetupScene(); ScenePresence sp = SceneHelpers.AddScenePresence(scene, TestHelpers.ParseTail(0x1)); scene.CloseAgent(sp.UUID, false); Assert.That(scene.GetScenePresence(sp.UUID), Is.Null); Assert.That(scene.AuthenticateHandler.GetAgentCircuitData(sp.UUID), Is.Null); Assert.That(scene.AuthenticateHandler.GetAgentCircuits().Count, Is.EqualTo(0)); // TestHelpers.DisableLogging(); } [Test] public void TestCreateChildScenePresence() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); LocalSimulationConnectorModule lsc = new LocalSimulationConnectorModule(); IConfigSource configSource = new IniConfigSource(); IConfig config = configSource.AddConfig("Modules"); config.Set("SimulationServices", "LocalSimulationConnectorModule"); SceneHelpers sceneHelpers = new SceneHelpers(); TestScene scene = sceneHelpers.SetupScene(); SceneHelpers.SetupSceneModules(scene, configSource, lsc); UUID agentId = TestHelpers.ParseTail(0x01); AgentCircuitData acd = SceneHelpers.GenerateAgentData(agentId); acd.child = true; GridRegion region = scene.GridService.GetRegionByName(UUID.Zero, scene.RegionInfo.RegionName); string reason; // *** This is the first stage, when a neighbouring region is told that a viewer is about to try and // establish a child scene presence. We pass in the circuit code that the client has to connect with *** // XXX: ViaLogin may not be correct here. scene.SimulationService.CreateAgent(region, acd, (uint)TeleportFlags.ViaLogin, out reason); Assert.That(scene.AuthenticateHandler.GetAgentCircuitData(agentId), Is.Not.Null); Assert.That(scene.AuthenticateHandler.GetAgentCircuits().Count, Is.EqualTo(1)); // There's no scene presence yet since only an agent circuit has been established. Assert.That(scene.GetScenePresence(agentId), Is.Null); // *** This is the second stage, where the client established a child agent/scene presence using the // circuit code given to the scene in stage 1 *** TestClient client = new TestClient(acd, scene); scene.AddNewAgent(client, PresenceType.User); Assert.That(scene.AuthenticateHandler.GetAgentCircuitData(agentId), Is.Not.Null); Assert.That(scene.AuthenticateHandler.GetAgentCircuits().Count, Is.EqualTo(1)); ScenePresence sp = scene.GetScenePresence(agentId); Assert.That(sp, Is.Not.Null); Assert.That(sp.UUID, Is.EqualTo(agentId)); Assert.That(sp.IsChildAgent, Is.True); } /// <summary> /// Test that if a root agent logs into a region, a child agent is also established in the neighbouring region /// </summary> /// <remarks> /// Please note that unlike the other tests here, this doesn't rely on anything set up in the instance fields. /// INCOMPLETE /// </remarks> [Test] public void TestChildAgentEstablishedInNeighbour() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); // UUID agent1Id = UUID.Parse("00000000-0000-0000-0000-000000000001"); TestScene myScene1 = new SceneHelpers().SetupScene("Neighbour y", UUID.Random(), 1000, 1000); TestScene myScene2 = new SceneHelpers().SetupScene("Neighbour y + 1", UUID.Random(), 1001, 1000); IConfigSource configSource = new IniConfigSource(); IConfig config = configSource.AddConfig("Startup"); config.Set("serverside_object_permissions", true); config.Set("EventQueue", true); EntityTransferModule etm = new EntityTransferModule(); EventQueueGetModule eqgm1 = new EventQueueGetModule(); SceneHelpers.SetupSceneModules(myScene1, configSource, etm, eqgm1); EventQueueGetModule eqgm2 = new EventQueueGetModule(); SceneHelpers.SetupSceneModules(myScene2, configSource, etm, eqgm2); // SceneHelpers.AddScenePresence(myScene1, agent1Id); // ScenePresence childPresence = myScene2.GetScenePresence(agent1); // // // TODO: Need to do a fair amount of work to allow synchronous establishment of child agents // Assert.That(childPresence, Is.Not.Null); // Assert.That(childPresence.IsChildAgent, Is.True); } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // Author: // Sebastien Pouliot <[email protected]> // // Copyright (C) 2005 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using Xunit; namespace System.PrivateUri.Tests { #region Test class public sealed class TestUriParser : UriParser { private bool on_new_uri_called; private int default_Port; private string scheme_name; public TestUriParser() : base() { } public new string GetComponents(Uri uri, UriComponents components, UriFormat format) => base.GetComponents(uri, components, format); public new void InitializeAndValidate(Uri uri, out UriFormatException parsingError) => base.InitializeAndValidate(uri, out parsingError); public new bool IsBaseOf(Uri baseUri, Uri relativeUri) => base.IsBaseOf(baseUri, relativeUri); public new bool IsWellFormedOriginalString(Uri uri) => base.IsWellFormedOriginalString(uri); public new string Resolve(Uri baseUri, Uri relativeUri, out UriFormatException parsingError) => base.Resolve(baseUri, relativeUri, out parsingError); public new UriParser OnNewUri() { on_new_uri_called = true; return base.OnNewUri(); } public bool OnNewUriCalled { get { return on_new_uri_called; } } protected override void OnRegister(string schemeName, int defaultPort) { scheme_name = schemeName; default_Port = defaultPort; base.OnRegister(schemeName, defaultPort); } public string SchemeName { get { return scheme_name; } } public int DefaultPort { get { return default_Port; } } } #endregion Test class public static class UriParserTest { #region UriParser tests private const string full_http = "http://www.mono-project.com/Main_Page#FAQ?Edit"; private static string prefix; private static Uri http, ftp, ftp2; [Fact] public static void GetComponents_test() { http = new Uri(full_http); TestUriParser parser = new TestUriParser(); Assert.Equal("http", parser.GetComponents(http, UriComponents.Scheme, UriFormat.SafeUnescaped)); Assert.Equal(string.Empty, parser.GetComponents(http, UriComponents.UserInfo, UriFormat.SafeUnescaped)); Assert.Equal("www.mono-project.com", parser.GetComponents(http, UriComponents.Host, UriFormat.SafeUnescaped)); Assert.Equal(string.Empty, parser.GetComponents(http, UriComponents.Port, UriFormat.SafeUnescaped)); Assert.Equal("Main_Page", parser.GetComponents(http, UriComponents.Path, UriFormat.SafeUnescaped)); Assert.Equal(string.Empty, parser.GetComponents(http, UriComponents.Query, UriFormat.SafeUnescaped)); Assert.Equal("FAQ?Edit", parser.GetComponents(http, UriComponents.Fragment, UriFormat.SafeUnescaped)); Assert.Equal("80", parser.GetComponents(http, UriComponents.StrongPort, UriFormat.SafeUnescaped)); Assert.Equal(string.Empty, parser.GetComponents(http, UriComponents.KeepDelimiter, UriFormat.SafeUnescaped)); Assert.Equal("www.mono-project.com:80", parser.GetComponents(http, UriComponents.HostAndPort, UriFormat.SafeUnescaped)); Assert.Equal("www.mono-project.com:80", parser.GetComponents(http, UriComponents.StrongAuthority, UriFormat.SafeUnescaped)); Assert.Equal(full_http, parser.GetComponents(http, UriComponents.AbsoluteUri, UriFormat.SafeUnescaped)); Assert.Equal("/Main_Page", parser.GetComponents(http, UriComponents.PathAndQuery, UriFormat.SafeUnescaped)); Assert.Equal("http://www.mono-project.com/Main_Page", parser.GetComponents(http, UriComponents.HttpRequestUrl, UriFormat.SafeUnescaped)); Assert.Equal("http://www.mono-project.com", parser.GetComponents(http, UriComponents.SchemeAndServer, UriFormat.SafeUnescaped)); Assert.Equal(full_http, parser.GetComponents(http, UriComponents.SerializationInfoString, UriFormat.SafeUnescaped)); // strange mixup Assert.Equal("http://", parser.GetComponents(http, UriComponents.Scheme | UriComponents.Port, UriFormat.SafeUnescaped)); Assert.Equal("www.mono-project.com#FAQ?Edit", parser.GetComponents(http, UriComponents.Host | UriComponents.Fragment, UriFormat.SafeUnescaped)); Assert.Equal("/Main_Page", parser.GetComponents(http, UriComponents.Port | UriComponents.Path, UriFormat.SafeUnescaped)); Assert.Equal(parser, parser.OnNewUri()); } [Fact] public static void GetComponents_Ftp() { var full_ftp = "ftp://username:[email protected]:21/with some spaces/mono.tgz"; ftp = new Uri(full_ftp); TestUriParser parser = new TestUriParser(); Assert.Equal("ftp", parser.GetComponents(ftp, UriComponents.Scheme, UriFormat.Unescaped)); Assert.Equal("username:password", parser.GetComponents(ftp, UriComponents.UserInfo, UriFormat.Unescaped)); Assert.Equal("ftp.go-mono.com", parser.GetComponents(ftp, UriComponents.Host, UriFormat.Unescaped)); Assert.Equal(string.Empty, parser.GetComponents(ftp, UriComponents.Port, UriFormat.Unescaped)); Assert.Equal("with some spaces/mono.tgz", parser.GetComponents(ftp, UriComponents.Path, UriFormat.Unescaped)); Assert.Equal("with%20some%20spaces/mono.tgz", parser.GetComponents(ftp, UriComponents.Path, UriFormat.UriEscaped)); Assert.Equal("with some spaces/mono.tgz", parser.GetComponents(ftp, UriComponents.Path, UriFormat.SafeUnescaped)); Assert.Equal(string.Empty, parser.GetComponents(ftp, UriComponents.Query, UriFormat.Unescaped)); Assert.Equal(string.Empty, parser.GetComponents(ftp, UriComponents.Fragment, UriFormat.Unescaped)); Assert.Equal("21", parser.GetComponents(ftp, UriComponents.StrongPort, UriFormat.Unescaped)); Assert.Equal(string.Empty, parser.GetComponents(ftp, UriComponents.KeepDelimiter, UriFormat.Unescaped)); Assert.Equal("ftp.go-mono.com:21", parser.GetComponents(ftp, UriComponents.HostAndPort, UriFormat.Unescaped)); Assert.Equal("username:[email protected]:21", parser.GetComponents(ftp, UriComponents.StrongAuthority, UriFormat.Unescaped)); Assert.Equal("ftp://username:[email protected]/with some spaces/mono.tgz", parser.GetComponents(ftp, UriComponents.AbsoluteUri, UriFormat.Unescaped)); Assert.Equal("/with some spaces/mono.tgz", parser.GetComponents(ftp, UriComponents.PathAndQuery, UriFormat.Unescaped)); Assert.Equal("ftp://ftp.go-mono.com/with some spaces/mono.tgz", parser.GetComponents(ftp, UriComponents.HttpRequestUrl, UriFormat.Unescaped)); Assert.Equal("ftp://ftp.go-mono.com", parser.GetComponents(ftp, UriComponents.SchemeAndServer, UriFormat.Unescaped)); Assert.Equal("ftp://username:[email protected]/with some spaces/mono.tgz", parser.GetComponents(ftp, UriComponents.SerializationInfoString, UriFormat.Unescaped)); Assert.Equal(parser, parser.OnNewUri()); // strange mixup Assert.Equal("ftp://username:password@", parser.GetComponents(ftp, UriComponents.Scheme | UriComponents.UserInfo, UriFormat.Unescaped)); Assert.Equal(":21/with some spaces/mono.tgz", parser.GetComponents(ftp, UriComponents.Path | UriComponents.StrongPort, UriFormat.Unescaped)); } [Fact] public static void GetComponents_Ftp2() { var full_ftp = "ftp://%75sername%3a%[email protected]:21/with some spaces/mono.tgz"; ftp2 = new Uri(full_ftp); TestUriParser parser = new TestUriParser(); Assert.Equal("ftp", parser.GetComponents(ftp2, UriComponents.Scheme, UriFormat.Unescaped)); Assert.Equal("username:password", parser.GetComponents(ftp2, UriComponents.UserInfo, UriFormat.Unescaped)); Assert.Equal("ftp.go-mono.com", parser.GetComponents(ftp2, UriComponents.Host, UriFormat.Unescaped)); Assert.Equal(string.Empty, parser.GetComponents(ftp2, UriComponents.Port, UriFormat.Unescaped)); Assert.Equal("with some spaces/mono.tgz", parser.GetComponents(ftp2, UriComponents.Path, UriFormat.Unescaped)); Assert.Equal("with%20some%20spaces/mono.tgz", parser.GetComponents(ftp2, UriComponents.Path, UriFormat.UriEscaped)); Assert.Equal("with some spaces/mono.tgz", parser.GetComponents(ftp2, UriComponents.Path, UriFormat.SafeUnescaped)); Assert.Equal(string.Empty, parser.GetComponents(ftp2, UriComponents.Query, UriFormat.Unescaped)); Assert.Equal(string.Empty, parser.GetComponents(ftp2, UriComponents.Fragment, UriFormat.Unescaped)); Assert.Equal("21", parser.GetComponents(ftp2, UriComponents.StrongPort, UriFormat.Unescaped)); Assert.Equal(string.Empty, parser.GetComponents(ftp2, UriComponents.KeepDelimiter, UriFormat.Unescaped)); Assert.Equal("ftp.go-mono.com:21", parser.GetComponents(ftp2, UriComponents.HostAndPort, UriFormat.Unescaped)); Assert.Equal("username:[email protected]:21", parser.GetComponents(ftp2, UriComponents.StrongAuthority, UriFormat.Unescaped)); Assert.Equal("ftp://username:[email protected]/with some spaces/mono.tgz", parser.GetComponents(ftp2, UriComponents.AbsoluteUri, UriFormat.Unescaped)); Assert.Equal("/with some spaces/mono.tgz", parser.GetComponents(ftp2, UriComponents.PathAndQuery, UriFormat.Unescaped)); Assert.Equal("ftp://ftp.go-mono.com/with some spaces/mono.tgz", parser.GetComponents(ftp2, UriComponents.HttpRequestUrl, UriFormat.Unescaped)); Assert.Equal("ftp://ftp.go-mono.com", parser.GetComponents(ftp2, UriComponents.SchemeAndServer, UriFormat.Unescaped)); Assert.Equal("ftp://username:[email protected]/with some spaces/mono.tgz", parser.GetComponents(ftp2, UriComponents.SerializationInfoString, UriFormat.Unescaped)); Assert.Equal(parser, parser.OnNewUri()); // strange mixup Assert.Equal("ftp://username:password@", parser.GetComponents(ftp2, UriComponents.Scheme | UriComponents.UserInfo, UriFormat.Unescaped)); Assert.Equal(":21/with some spaces/mono.tgz", parser.GetComponents(ftp2, UriComponents.Path | UriComponents.StrongPort, UriFormat.Unescaped)); } [Fact] public static void TestParseUserPath() { var u = new Uri("https://a.net/[email protected]"); var result = u.GetComponents(UriComponents.Scheme | UriComponents.Host | UriComponents.Port | UriComponents.Path, UriFormat.UriEscaped); Assert.Equal("https://a.net/[email protected]", result); } [Fact] public static void GetComponents_Null() { TestUriParser parser = new TestUriParser(); Assert.Throws<System.NullReferenceException>(() => { parser.GetComponents(null, UriComponents.Host, UriFormat.SafeUnescaped); }); } [Fact] public static void GetComponents_BadUriComponents() { http = new Uri(full_http); TestUriParser parser = new TestUriParser(); Assert.Equal(full_http, parser.GetComponents(http, (UriComponents)int.MinValue, UriFormat.SafeUnescaped)); } [Fact] public static void GetComponents_BadUriFormat() { http = new Uri(full_http); TestUriParser parser = new TestUriParser(); Assert.Throws<System.ArgumentOutOfRangeException>(() => { parser.GetComponents(http, UriComponents.Host, (UriFormat)int.MinValue); }); } [Fact] public static void InitializeAndValidate() { http = new Uri(full_http); UriFormatException error = null; TestUriParser parser = new TestUriParser(); parser.InitializeAndValidate(http, out error); Assert.NotNull(error); } [Fact] public static void InitializeAndValidate_Null() { UriFormatException error = null; TestUriParser parser = new TestUriParser(); Assert.Throws<System.NullReferenceException>(() => { parser.InitializeAndValidate(null, out error); }); } [Fact] public static void IsBaseOf() { http = new Uri(full_http); TestUriParser parser = new TestUriParser(); Assert.True(parser.IsBaseOf(http, http), "http-http"); Uri u = new Uri("http://www.mono-project.com/Main_Page#FAQ"); Assert.True(parser.IsBaseOf(u, http), "http-1a"); Assert.True(parser.IsBaseOf(http, u), "http-1b"); u = new Uri("http://www.mono-project.com/Main_Page"); Assert.True(parser.IsBaseOf(u, http), "http-2a"); Assert.True(parser.IsBaseOf(http, u), "http-2b"); u = new Uri("http://www.mono-project.com/"); Assert.True(parser.IsBaseOf(u, http), "http-3a"); Assert.True(parser.IsBaseOf(http, u), "http-3b"); u = new Uri("http://www.mono-project.com/Main_Page/"); Assert.False(parser.IsBaseOf(u, http), "http-4a"); Assert.True(parser.IsBaseOf(http, u), "http-4b"); // docs says the UserInfo isn't evaluated, but... u = new Uri("http://username:[email protected]/Main_Page"); Assert.False(parser.IsBaseOf(u, http), "http-5a"); Assert.False(parser.IsBaseOf(http, u), "http-5b"); // scheme case sensitive ? no u = new Uri("HTTP://www.mono-project.com/Main_Page"); Assert.True(parser.IsBaseOf(u, http), "http-6a"); Assert.True(parser.IsBaseOf(http, u), "http-6b"); // host case sensitive ? no u = new Uri("http://www.Mono-Project.com/Main_Page"); Assert.True(parser.IsBaseOf(u, http), "http-7a"); Assert.True(parser.IsBaseOf(http, u), "http-7b"); // path case sensitive ? no u = new Uri("http://www.Mono-Project.com/MAIN_Page"); Assert.True(parser.IsBaseOf(u, http), "http-8a"); Assert.True(parser.IsBaseOf(http, u), "http-8b"); // different scheme u = new Uri("ftp://www.mono-project.com/Main_Page"); Assert.False(parser.IsBaseOf(u, http), "http-9a"); Assert.False(parser.IsBaseOf(http, u), "http-9b"); // different host u = new Uri("http://www.go-mono.com/Main_Page"); Assert.False(parser.IsBaseOf(u, http), "http-10a"); Assert.False(parser.IsBaseOf(http, u), "http-10b"); // different port u = new Uri("http://www.mono-project.com:8080/"); Assert.False(parser.IsBaseOf(u, http), "http-11a"); Assert.False(parser.IsBaseOf(http, u), "http-11b"); // specify default port u = new Uri("http://www.mono-project.com:80/"); Assert.True(parser.IsBaseOf(u, http), "http-12a"); Assert.True(parser.IsBaseOf(http, u), "http-12b"); } [Fact] public static void IsWellFormedOriginalString() { http = new Uri(full_http); TestUriParser parser = new TestUriParser(); Assert.True(parser.IsWellFormedOriginalString(http), "http"); } [Fact] public static void IsWellFormedOriginalString_Null() { TestUriParser parser = new TestUriParser(); Assert.Throws<System.NullReferenceException>(() => { parser.IsWellFormedOriginalString(null); } ); } [Fact] public static void OnRegister() { prefix = "unit.test."; string scheme = prefix + "onregister"; Assert.False(UriParser.IsKnownScheme(scheme), "IsKnownScheme-false"); TestUriParser parser = new TestUriParser(); try { UriParser.Register(parser, scheme, 2005); } catch (NotSupportedException) { // special case / ordering } // if true then the registration is done before calling OnRegister Assert.True(UriParser.IsKnownScheme(scheme), "IsKnownScheme-true"); } [Fact] public static void OnRegister2() { prefix = "unit.test."; string scheme = prefix + "onregister2"; Assert.False(UriParser.IsKnownScheme(scheme), "IsKnownScheme-false"); TestUriParser parser = new TestUriParser(); try { UriParser.Register(parser, scheme, 2005); Uri uri = new Uri(scheme + "://foobar:2005"); Assert.Equal(scheme, uri.Scheme); Assert.Equal(2005, uri.Port); Assert.Equal("//foobar:2005", uri.LocalPath); } catch (NotSupportedException) { // special case / ordering } // if true then the registration is done before calling OnRegister Assert.True(UriParser.IsKnownScheme(scheme), "IsKnownScheme-true"); } [Fact] public static void Resolve() { http = new Uri(full_http); UriFormatException error = null; TestUriParser parser = new TestUriParser(); Assert.Equal(full_http, parser.Resolve(http, http, out error)); } [Fact] public static void Resolve_UriNull() { http = new Uri(full_http); UriFormatException error = null; TestUriParser parser = new TestUriParser(); Assert.Equal(full_http, parser.Resolve(http, null, out error)); } [Fact] public static void Resolve_NullUri() { http = new Uri(full_http); UriFormatException error = null; TestUriParser parser = new TestUriParser(); Assert.Throws<System.NullReferenceException>(() => { parser.Resolve(null, http, out error); } ); parser.Resolve(http, null, out error); } [Fact] public static void IsKnownScheme_WellKnown() { Assert.True(UriParser.IsKnownScheme("file"), "file"); Assert.True(UriParser.IsKnownScheme("ftp"), "ftp"); Assert.True(UriParser.IsKnownScheme("gopher"), "gopher"); Assert.True(UriParser.IsKnownScheme("http"), "http"); Assert.True(UriParser.IsKnownScheme("https"), "https"); Assert.True(UriParser.IsKnownScheme("mailto"), "mailto"); Assert.True(UriParser.IsKnownScheme("net.pipe"), "net.pipe"); Assert.True(UriParser.IsKnownScheme("net.tcp"), "net.tcp"); Assert.True(UriParser.IsKnownScheme("news"), "news"); Assert.True(UriParser.IsKnownScheme("nntp"), "nntp"); Assert.True(UriParser.IsKnownScheme("ldap"), "ldap"); Assert.False(UriParser.IsKnownScheme("ldaps"), "ldaps"); Assert.False(UriParser.IsKnownScheme("unknown"), "unknown"); Assert.True(UriParser.IsKnownScheme("FiLe"), "FiLe"); Assert.True(UriParser.IsKnownScheme("FTP"), "ftp"); Assert.False(UriParser.IsKnownScheme("tcp"), "tcp"); } [Fact] public static void IsKnownScheme_ExtraSpace() { Assert.Throws<System.ArgumentOutOfRangeException>(() => { UriParser.IsKnownScheme("ht tp"); }); } [Fact] public static void IsKnownScheme_Null() { Assert.Throws<System.ArgumentNullException>(() => { UriParser.IsKnownScheme(null); }); } [Fact] public static void IsKnownScheme_Empty() { Assert.Throws<System.ArgumentOutOfRangeException>(() => { UriParser.IsKnownScheme(string.Empty); }); } [Fact] public static void Register() { prefix = "unit.test."; string scheme = prefix + "register.mono"; Assert.False(UriParser.IsKnownScheme(scheme), "IsKnownScheme-false"); TestUriParser parser = new TestUriParser(); UriParser.Register(parser, scheme, 2005); Assert.Equal(scheme, parser.SchemeName); Assert.Equal(2005, parser.DefaultPort); Assert.True(UriParser.IsKnownScheme(scheme), "IsKnownScheme-true"); } [Fact] public static void Register_NullParser() { prefix = "unit.test."; Assert.Throws<System.ArgumentNullException>(() => { UriParser.Register(null, prefix + "null.parser", 2006); } ); } [Fact] public static void Register_NullScheme() { TestUriParser parser = new TestUriParser(); Assert.Throws<System.ArgumentNullException>(() => { UriParser.Register(parser, null, 2006); }); } [Fact] public static void Register_NegativePort() { prefix = "unit.test."; TestUriParser parser = new TestUriParser(); Assert.Throws<System.ArgumentOutOfRangeException>(() => { UriParser.Register(parser, prefix + "negative.port", -2); }); } [Fact] public static void Register_Minus1Port() { prefix = "unit.test."; TestUriParser parser = new TestUriParser(); UriParser.Register(parser, prefix + "minus1.port", -1); } [Fact] public static void Register_UInt16PortMinus1() { prefix = "unit.test."; TestUriParser parser = new TestUriParser(); UriParser.Register(parser, prefix + "uint16.minus.1.port", ushort.MaxValue - 1); } [Fact] public static void Register_TooBigPort() { prefix = "unit.test."; TestUriParser parser = new TestUriParser(); Assert.Throws<System.ArgumentOutOfRangeException>(() => { UriParser.Register(parser, prefix + "too.big.port", ushort.MaxValue); }); } [Fact] public static void ReRegister() { prefix = "unit.test."; string scheme = prefix + "re.register.mono"; Assert.False(UriParser.IsKnownScheme(scheme), "IsKnownScheme-false"); TestUriParser parser = new TestUriParser(); UriParser.Register(parser, scheme, 2005); Assert.True(UriParser.IsKnownScheme(scheme), "IsKnownScheme-true"); Assert.Throws<System.InvalidOperationException>(() => { UriParser.Register(parser, scheme, 2006); }); } #endregion UriParser tests #region GenericUriParser tests [Fact] public static void GenericUriParser_ctor() { // Make sure that constructor doesn't throw when using different types of Parser Options GenericUriParser parser; parser = new GenericUriParser(GenericUriParserOptions.AllowEmptyAuthority); parser = new GenericUriParser(GenericUriParserOptions.Default); parser = new GenericUriParser(GenericUriParserOptions.DontCompressPath); parser = new GenericUriParser(GenericUriParserOptions.DontConvertPathBackslashes); parser = new GenericUriParser(GenericUriParserOptions.DontUnescapePathDotsAndSlashes); parser = new GenericUriParser(GenericUriParserOptions.GenericAuthority); parser = new GenericUriParser(GenericUriParserOptions.Idn); parser = new GenericUriParser(GenericUriParserOptions.IriParsing); parser = new GenericUriParser(GenericUriParserOptions.NoFragment); parser = new GenericUriParser(GenericUriParserOptions.NoPort); parser = new GenericUriParser(GenericUriParserOptions.NoQuery); parser = new GenericUriParser(GenericUriParserOptions.NoUserInfo); } #endregion GenericUriParser tests #region UriParser template tests //Make sure the constructor of the UriParser templates are callable [Fact] public static void HttpStyleUriParser_ctor() { HttpStyleUriParser httpParser = new HttpStyleUriParser(); } [Fact] public static void FtpStyleUriParser_ctor() { FtpStyleUriParser httpParser = new FtpStyleUriParser(); } [Fact] public static void FileStyleUriParser_ctor() { FileStyleUriParser httpParser = new FileStyleUriParser(); } [Fact] public static void NewsStyleUriParser_ctor() { NewsStyleUriParser httpParser = new NewsStyleUriParser(); } [Fact] public static void GopherStyleUriParser_ctor() { GopherStyleUriParser httpParser = new GopherStyleUriParser(); } [Fact] public static void LdapStyleUriParser_ctor() { LdapStyleUriParser httpParser = new LdapStyleUriParser(); } [Fact] public static void NetPipeStyleUriParser_ctor() { NetPipeStyleUriParser httpParser = new NetPipeStyleUriParser(); } [Fact] public static void NetTcpStyleUriParser_ctor() { NetTcpStyleUriParser httpParser = new NetTcpStyleUriParser(); } #endregion UriParser template tests } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// A country. /// </summary> public class Country_Core : TypeCore, IAdministrativeArea { public Country_Core() { this._TypeId = 74; this._Id = "Country"; this._Schema_Org_Url = "http://schema.org/Country"; string label = ""; GetLabel(out label, "Country", typeof(Country_Core)); this._Label = label; this._Ancestors = new int[]{266,206,10}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{10}; this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196}; } /// <summary> /// Physical address of the item. /// </summary> private Address_Core address; public Address_Core Address { get { return address; } set { address = value; SetPropertyInstance(address); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// The basic containment relation between places. /// </summary> private ContainedIn_Core containedIn; public ContainedIn_Core ContainedIn { get { return containedIn; } set { containedIn = value; SetPropertyInstance(containedIn); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// Upcoming or past events associated with this place or organization. /// </summary> private Events_Core events; public Events_Core Events { get { return events; } set { events = value; SetPropertyInstance(events); } } /// <summary> /// The fax number. /// </summary> private FaxNumber_Core faxNumber; public FaxNumber_Core FaxNumber { get { return faxNumber; } set { faxNumber = value; SetPropertyInstance(faxNumber); } } /// <summary> /// The geo coordinates of the place. /// </summary> private Geo_Core geo; public Geo_Core Geo { get { return geo; } set { geo = value; SetPropertyInstance(geo); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// A URL to a map of the place. /// </summary> private Maps_Core maps; public Maps_Core Maps { get { return maps; } set { maps = value; SetPropertyInstance(maps); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// Photographs of this place. /// </summary> private Photos_Core photos; public Photos_Core Photos { get { return photos; } set { photos = value; SetPropertyInstance(photos); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The telephone number. /// </summary> private Telephone_Core telephone; public Telephone_Core Telephone { get { return telephone; } set { telephone = value; SetPropertyInstance(telephone); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
using UnityEngine; using System; public class FRadialWipeSprite : FSprite { protected float _baseAngle; protected float _percentage; protected bool _isClockwise; protected Vector2[] _meshVertices = new Vector2[7]; protected Vector2[] _uvVertices = new Vector2[7]; public FRadialWipeSprite (string elementName, bool isClockwise, float baseAngle, float percentage) : base() { _isClockwise = isClockwise; _baseAngle = (baseAngle + 36000000.0f) % 360.0f; _percentage = Mathf.Max (0.0f, Mathf.Min(1.0f, percentage)); Init(FFacetType.Triangle, Futile.atlasManager.GetElementWithName(elementName),5); _isAlphaDirty = true; UpdateLocalVertices(); } private void CalculateTheRadialVertices () { //TODO: A lot of these calculations could be offloaded to when the element (and maybe anchor?) changes. float baseAngleToUse; if(_isClockwise) { baseAngleToUse = _baseAngle; } else { baseAngleToUse = 360.0f-_baseAngle; } float startAngle = baseAngleToUse * RXMath.DTOR; float endAngle = startAngle + _percentage * RXMath.DOUBLE_PI; float halfWidth = _localRect.width*0.5f; float halfHeight = _localRect.height*0.5f; //corner 0 is the top right, the rest go clockwise from there Vector2 cornerTR = new Vector2(halfHeight, halfWidth); Vector2 cornerBR = new Vector2(-halfHeight, halfWidth); Vector2 cornerBL = new Vector2(-halfHeight, -halfWidth); Vector2 cornerTL = new Vector2(halfHeight, -halfWidth); float cornerAngleTR = -Mathf.Atan2(cornerTR.x,cornerTR.y) + RXMath.HALF_PI; float cornerAngleBR = -Mathf.Atan2(cornerBR.x,cornerBR.y) + RXMath.HALF_PI; float cornerAngleBL = -Mathf.Atan2(cornerBL.x,cornerBL.y) + RXMath.HALF_PI; float cornerAngleTL = -Mathf.Atan2(cornerTL.x,cornerTL.y) + RXMath.HALF_PI; cornerAngleTR = (cornerAngleTR + RXMath.DOUBLE_PI*10000.0f) % RXMath.DOUBLE_PI; cornerAngleBR = (cornerAngleBR + RXMath.DOUBLE_PI*10000.0f) % RXMath.DOUBLE_PI; cornerAngleBL = (cornerAngleBL + RXMath.DOUBLE_PI*10000.0f) % RXMath.DOUBLE_PI; cornerAngleTL = (cornerAngleTL + RXMath.DOUBLE_PI*10000.0f) % RXMath.DOUBLE_PI; float cornerAngle0; float cornerAngle1; float cornerAngle2; float cornerAngle3; if(startAngle < cornerAngleTR) //top right { cornerAngle0 = cornerAngleTR; cornerAngle1 = cornerAngleBR; cornerAngle2 = cornerAngleBL; cornerAngle3 = cornerAngleTL; } else if(startAngle >= cornerAngleTR && startAngle < cornerAngleBR) //right { cornerAngle0 = cornerAngleBR; cornerAngle1 = cornerAngleBL; cornerAngle2 = cornerAngleTL; cornerAngle3 = cornerAngleTR + RXMath.DOUBLE_PI; } else if(startAngle >= cornerAngleBR && startAngle < cornerAngleBL) //left { cornerAngle0 = cornerAngleBL; cornerAngle1 = cornerAngleTL; cornerAngle2 = cornerAngleTR + RXMath.DOUBLE_PI; cornerAngle3 = cornerAngleBR + RXMath.DOUBLE_PI; } else if(startAngle >= cornerAngleBL && startAngle < cornerAngleTL) { cornerAngle0 = cornerAngleTL; cornerAngle1 = cornerAngleTR + RXMath.DOUBLE_PI; cornerAngle2 = cornerAngleBR + RXMath.DOUBLE_PI; cornerAngle3 = cornerAngleBL + RXMath.DOUBLE_PI; } //else if(startAngle >= cornerAngleTL) else //top left { cornerAngle0 = cornerAngleTR + RXMath.DOUBLE_PI; cornerAngle1 = cornerAngleBR + RXMath.DOUBLE_PI; cornerAngle2 = cornerAngleBL + RXMath.DOUBLE_PI; cornerAngle3 = cornerAngleTL + RXMath.DOUBLE_PI; } float hugeRadius = 1000000.0f; for(int v = 0; v<6; v++) { float angle = 0; if(v<5) { angle = startAngle + ((endAngle - startAngle)/5.0f * v); if(v == 0) { //do nothing, 0 is gooood } else if(v == 1 && endAngle > cornerAngle0) { angle = cornerAngle0; } else if(v == 2 && endAngle > cornerAngle1) { angle = cornerAngle1; } else if(v == 3 && endAngle > cornerAngle2) { angle = cornerAngle2; } else if(v == 4 && endAngle > cornerAngle3) { angle = cornerAngle3; } else if(endAngle > cornerAngle3) { angle = Mathf.Max (angle, cornerAngle3); } else if(endAngle > cornerAngle2) { angle = Mathf.Max (angle, cornerAngle2); } else if(endAngle > cornerAngle1) { angle = Mathf.Max (angle, cornerAngle1); } else if(endAngle > cornerAngle0) { angle = Mathf.Max (angle, cornerAngle0); } } else { angle = endAngle; } angle = (angle + RXMath.DOUBLE_PI*10000.0f) % RXMath.DOUBLE_PI; float compX = Mathf.Cos(-angle + RXMath.HALF_PI) * hugeRadius; float compY = Mathf.Sin(-angle + RXMath.HALF_PI) * hugeRadius; //snap the verts to the edge of the rect if(angle < cornerAngleTR) //top right { compX = compX * (halfHeight / compY); compY = halfHeight; } else if(angle >= cornerAngleTR && angle < cornerAngleBR) //right { compY = compY * (halfWidth / compX); compX = halfWidth; } else if(angle >= cornerAngleBR && angle < cornerAngleBL) //bottom { compX = compX * (-halfHeight / compY); compY = -halfHeight; } else if(angle >= cornerAngleBL && angle < cornerAngleTL) //left { compY = compY * (-halfWidth / compX); compX = -halfWidth; } else if(angle >= cornerAngleTL) //top left { compX = compX * (halfHeight / compY); compY = halfHeight; } if(!_isClockwise) { compX = -compX; } _meshVertices[v] = new Vector2(compX, compY); } _meshVertices[6] = new Vector2(0,0); //this last vert is actually the center vert //create uv vertices Rect uvRect = _element.uvRect; Vector2 uvCenter = uvRect.center; for(int v = 0; v<7; v++) { _uvVertices[v].x = uvCenter.x + _meshVertices[v].x / _localRect.width * uvRect.width; _uvVertices[v].y = uvCenter.y + _meshVertices[v].y / _localRect.height * uvRect.height; } //put mesh vertices in the correct position float offsetX = _localRect.center.x; float offsetY = _localRect.center.y; for(int v = 0; v<7; v++) { _meshVertices[v].x += offsetX; _meshVertices[v].y += offsetY; } } override public void PopulateRenderLayer() { if(_isOnStage && _firstFacetIndex != -1) { _isMeshDirty = false; CalculateTheRadialVertices(); //now do the actual population Vector3[] vertices = _renderLayer.vertices; Vector2[] uvs = _renderLayer.uvs; Color[] colors = _renderLayer.colors; int vertexIndex0 = _firstFacetIndex*3; //set the colors for(int c = 0; c<15; c++) { colors[vertexIndex0 + c] = _alphaColor; } //vertex 6 is the center vertex //set the uvs uvs[vertexIndex0] = _uvVertices[6]; uvs[vertexIndex0 + 1] = _uvVertices[0]; uvs[vertexIndex0 + 2] = _uvVertices[1]; uvs[vertexIndex0 + 3] = _uvVertices[6]; uvs[vertexIndex0 + 4] = _uvVertices[1]; uvs[vertexIndex0 + 5] = _uvVertices[2]; uvs[vertexIndex0 + 6] = _uvVertices[6]; uvs[vertexIndex0 + 7] = _uvVertices[2]; uvs[vertexIndex0 + 8] = _uvVertices[3]; uvs[vertexIndex0 + 9] = _uvVertices[6]; uvs[vertexIndex0 + 10] = _uvVertices[3]; uvs[vertexIndex0 + 11] = _uvVertices[4]; uvs[vertexIndex0 + 12] = _uvVertices[6]; uvs[vertexIndex0 + 13] = _uvVertices[4]; uvs[vertexIndex0 + 14] = _uvVertices[5]; //set the mesh _concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex0], _meshVertices[6],0); _concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex0 + 1], _meshVertices[0],0); _concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex0 + 2], _meshVertices[1],0); _concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex0 + 3], _meshVertices[6],0); _concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex0 + 4], _meshVertices[1],0); _concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex0 + 5], _meshVertices[2],0); _concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex0 + 6], _meshVertices[6],0); _concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex0 + 7], _meshVertices[2],0); _concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex0 + 8], _meshVertices[3],0); _concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex0 + 9], _meshVertices[6],0); _concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex0 + 10], _meshVertices[3],0); _concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex0 + 11], _meshVertices[4],0); _concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex0 + 12], _meshVertices[6],0); _concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex0 + 13], _meshVertices[4],0); _concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex0 + 14], _meshVertices[5],0); _renderLayer.HandleVertsChange(); } } public float baseAngle { get { return _baseAngle;} set { value = (value + 36000000.0f) % 360.0f; if(_baseAngle != value) { _baseAngle = value; _isMeshDirty = true; } } } public float percentage { get { return _percentage;} set { value = Mathf.Max (0.0f, Mathf.Min(1.0f, value)); if(_percentage != value) { _percentage = value; _isMeshDirty = true; } } } public bool isClockwise { get { return _isClockwise;} set { if(_isClockwise != value) { _isClockwise = value; _isMeshDirty = true; } } } }
using System; using System.Security.Cryptography; namespace Enyim { /// <summary> /// Implements the Tiger hash. (http://www.cs.technion.ac.il/~biham/Reports/Tiger/) /// /// Ported (and cleaned&amp;sped up) from the Tiger.NET VB code. (http://www.hotpixel.net/software.html) /// </summary> public sealed class TigerHash : HashAlgorithm { const int PASSES = 3; const int BLOCKSIZE = 64; long totalLength; ulong a; ulong b; ulong c; byte[] internalDataBuffer; int bufferPosition; ulong[] block = new ulong[8]; /// <summary> /// Initializes a new instance of the <see cref="T:TigerHash"/> class. /// </summary> public TigerHash() { this.internalDataBuffer = new byte[BLOCKSIZE]; this.HashSizeValue = 3 * 8 * 8; this.Initialize(); } /// <summary> /// Initializes an instance of <see cref="T:TigerHash"/>. /// </summary> public override void Initialize() { this.a = 0x123456789ABCDEF; this.b = 0xFEDCBA9876543210; this.c = 0xF096A5B4C3B2E187; this.bufferPosition = 0; this.totalLength = 0; } /// <summary>Routes data written to the object into the <see cref="T:TigerHash" /> hash algorithm for computing the hash.</summary> /// <param name="array">The input data. </param> /// <param name="ibStart">The offset into the byte array from which to begin using data. </param> /// <param name="cbSize">The number of bytes in the array to use as data. </param> protected override void HashCore(byte[] array, int ibStart, int cbSize) { this.totalLength += cbSize; byte[] buffer = this.internalDataBuffer; int offset = this.bufferPosition; int end = ibStart + cbSize; while (ibStart < end) { int count = BLOCKSIZE - offset; if (count > cbSize) { count = cbSize; } Buffer.BlockCopy(array, ibStart, buffer, offset, count); ibStart += count; offset += count; cbSize -= count; if (BLOCKSIZE > offset) break; this.ProcessBlock(); offset = 0; } this.bufferPosition = offset; } /// <summary> /// Returns the computed <see cref="T:TigerHash" /> hash value after all data has been written to the object. /// </summary> /// <returns>The computed hash code.</returns> protected override byte[] HashFinal() { int bufferOffset = this.bufferPosition; byte[] buffer = this.internalDataBuffer; buffer[bufferOffset] = 1; bufferOffset += 1; if ((BLOCKSIZE - 8) <= bufferOffset) { Array.Clear(buffer, bufferOffset, BLOCKSIZE - bufferOffset); this.ProcessBlock(); bufferOffset = 0; } Array.Clear(buffer, bufferOffset, BLOCKSIZE - bufferOffset - 8); TigerHash.LongToBytes(((ulong)this.totalLength) << 3, buffer, BLOCKSIZE - 8); this.ProcessBlock(); byte[] retval = new byte[24]; TigerHash.LongToBytes(this.a, retval, 0); TigerHash.LongToBytes(this.b, retval, 8); TigerHash.LongToBytes(this.c, retval, 16); return retval; } private unsafe void ProcessBlock() { #region [ Original code for reference ] //int blockIndex = 0; //ulong[] block = this.block; //byte[] buffer = this.internalDataBuffer; //for (int offset = 0; offset < BLOCKSIZE; offset += 8) //{ // block[blockIndex] = // (((ulong)buffer[offset + 7]) << 56) | // ((((ulong)buffer[offset + 6]) & 0xFF) << 48) | // ((((ulong)buffer[offset + 5]) & 0xFF) << 40) | // ((((ulong)buffer[offset + 4]) & 0xFF) << 32) | // ((((ulong)buffer[offset + 3]) & 0xFF) << 24) | // ((((ulong)buffer[offset + 2]) & 0xFF) << 16) | // ((((ulong)buffer[offset + 1]) & 0xFF) << 8) | // (((ulong)buffer[offset]) & 0xFF); // blockIndex++; //} #endregion Buffer.BlockCopy(this.internalDataBuffer, 0, this.block, 0, BLOCKSIZE); this.Compress(); } private void Compress() { ulong aa, bb, cc; ulong[] tmpBlock; aa = this.a; bb = this.b; cc = this.c; tmpBlock = this.block; this.RoundABC(tmpBlock[0], 5); this.RoundBCA(tmpBlock[1], 5); this.RoundCAB(tmpBlock[2], 5); this.RoundABC(tmpBlock[3], 5); this.RoundBCA(tmpBlock[4], 5); this.RoundCAB(tmpBlock[5], 5); this.RoundABC(tmpBlock[6], 5); this.RoundBCA(tmpBlock[7], 5); TigerHash.Schedule(tmpBlock); this.RoundCAB(tmpBlock[0], 7); this.RoundABC(tmpBlock[1], 7); this.RoundBCA(tmpBlock[2], 7); this.RoundCAB(tmpBlock[3], 7); this.RoundABC(tmpBlock[4], 7); this.RoundBCA(tmpBlock[5], 7); this.RoundCAB(tmpBlock[6], 7); this.RoundABC(tmpBlock[7], 7); TigerHash.Schedule(tmpBlock); this.RoundBCA(tmpBlock[0], 9); this.RoundCAB(tmpBlock[1], 9); this.RoundABC(tmpBlock[2], 9); this.RoundBCA(tmpBlock[3], 9); this.RoundCAB(tmpBlock[4], 9); this.RoundABC(tmpBlock[5], 9); this.RoundBCA(tmpBlock[6], 9); this.RoundCAB(tmpBlock[7], 9); this.a = this.a ^ aa; this.b -= bb; this.c += cc; } private static void Schedule(ulong[] x) { x[0] -= x[7] ^ 0xA5A5A5A5A5A5A5A5; x[1] = x[1] ^ x[0]; x[2] += x[1]; x[3] -= x[2] ^ ((~x[1]) << 19); x[4] = x[4] ^ x[3]; x[5] += x[4]; x[6] -= x[5] ^ (((~x[4]) >> 23) & 0x1FFFFFFFFFF); x[7] = x[7] ^ x[6]; x[0] += x[7]; x[1] -= x[0] ^ ((~x[7]) << 19); x[2] = x[2] ^ x[1]; x[3] += x[2]; x[4] -= x[3] ^ (((~x[2]) >> 23) & 0x1FFFFFFFFFF); x[5] = x[5] ^ x[4]; x[6] += x[5]; x[7] -= x[6] ^ 0x123456789ABCDEF; } private void RoundABC(ulong x, uint mul) { ulong[] T = TigerHash.T; ulong tmpC = this.c ^ x; int ch = (int)(tmpC >> 32); int cl = (int)(tmpC); this.a -= T[cl & 0xFF] ^ T[((cl >> 16) & 0xFF) + 0x100] ^ T[(ch & 0xFF) + 0x200] ^ T[((ch >> 16) & 0xFF) + 0x300]; this.b += T[((cl >> 8) & 0xFF) + 0x300] ^ T[((cl >> 24) & 0xFF) + 0x200] ^ T[((ch >> 8) & 0xFF) + 0x100] ^ T[(ch >> 24) & 0xFF]; this.b *= mul; this.c = tmpC; } private void RoundBCA(ulong x, uint mul) { ulong[] T = TigerHash.T; ulong tmpA = this.a ^ x; int ah = (int)(tmpA >> 32); int al = (int)(tmpA); this.b -= T[al & 0xFF] ^ T[((al >> 16) & 0xFF) + 0x100] ^ T[(ah & 0xFF) + 0x200] ^ T[((ah >> 16) & 0xFF) + 0x300]; this.c += T[((al >> 8) & 0xFF) + 0x300] ^ T[((al >> 24) & 0xFF) + 0x200] ^ T[((ah >> 8) & 0xFF) + 0x100] ^ T[(ah >> 24) & 0xFF]; this.c *= mul; this.a = tmpA; } private void RoundCAB(ulong x, uint mul) { ulong[] T = TigerHash.T; ulong tmpB = this.b ^ x; int bh = (int)(tmpB >> 32); int bl = (int)(tmpB); this.c -= T[bl & 0xFF] ^ T[((bl >> 16) & 0xFF) + 0x100] ^ T[(bh & 0xFF) + 0x200] ^ T[((bh >> 16) & 0xFF) + 0x300]; this.a += T[((bl >> 8) & 0xFF) + 0x300] ^ T[((bl >> 24) & 0xFF) + 0x200] ^ T[((bh >> 8) & 0xFF) + 0x100] ^ T[(bh >> 24) & 0xFF]; this.a *= mul; this.b = tmpB; } private static unsafe void LongToBytes(ulong value, byte[] buffer, int offset) { fixed (byte* numRef = buffer) { *((ulong*)(numRef + offset)) = value; } } #region [ static readonly ulong[] T ] private static readonly ulong[] T = { 0x2AAB17CF7E90C5E, 0xAC424B03E243A8EC, 0x72CD5BE30DD5FCD3, 0x6D019B93F6F97F3A, 0xCD9978FFD21F9193, 0x7573A1C9708029E2, 0xB164326B922A83C3, 0x46883EEE04915870, 0xEAACE3057103ECE6, 0xC54169B808A3535C, 0x4CE754918DDEC47C, 0xAA2F4DFDC0DF40C, 0x10B76F18A74DBEFA, 0xC6CCB6235AD1AB6A, 0x13726121572FE2FF, 0x1A488C6F199D921E, 0x4BC9F9F4DA0007CA, 0x26F5E6F6E85241C7, 0x859079DBEA5947B6, 0x4F1885C5C99E8C92, 0xD78E761EA96F864B, 0x8E36428C52B5C17D, 0x69CF6827373063C1, 0xB607C93D9BB4C56E, 0x7D820E760E76B5EA, 0x645C9CC6F07FDC42, 0xBF38A078243342E0, 0x5F6B343C9D2E7D04, 0xF2C28AEB600B0EC6, 0x6C0ED85F7254BCAC, 0x71592281A4DB4FE5, 0x1967FA69CE0FED9F, 0xFD5293F8B96545DB, 0xC879E9D7F2A7600B, 0x860248920193194E, 0xA4F9533B2D9CC0B3, 0x9053836C15957613, 0xDB6DCF8AFC357BF1, 0x18BEEA7A7A370F57, 0x37117CA50B99066, 0x6AB30A9774424A35, 0xF4E92F02E325249B, 0x7739DB07061CCAE1, 0xD8F3B49CECA42A05, 0xBD56BE3F51382F73, 0x45FAED5843B0BB28, 0x1C813D5C11BF1F83, 0x8AF0E4B6D75FA169, 0x33EE18A487AD9999, 0x3C26E8EAB1C94410, 0xB510102BC0A822F9, 0x141EEF310CE6123B, 0xFC65B90059DDB154, 0xE0158640C5E0E607, 0x884E079826C3A3CF, 0x930D0D9523C535FD, 0x35638D754E9A2B00, 0x4085FCCF40469DD5, 0xC4B17AD28BE23A4C, 0xCAB2F0FC6A3E6A2E, 0x2860971A6B943FCD, 0x3DDE6EE212E30446, 0x6222F32AE01765AE, 0x5D550BB5478308FE, 0xA9EFA98DA0EDA22A, 0xC351A71686C40DA7, 0x1105586D9C867C84, 0xDCFFEE85FDA22853, 0xCCFBD0262C5EEF76, 0xBAF294CB8990D201, 0xE69464F52AFAD975, 0x94B013AFDF133E14, 0x6A7D1A32823C958, 0x6F95FE5130F61119, 0xD92AB34E462C06C0, 0xED7BDE33887C71D2, 0x79746D6E6518393E, 0x5BA419385D713329, 0x7C1BA6B948A97564, 0x31987C197BFDAC67, 0xDE6C23C44B053D02, 0x581C49FED002D64D, 0xDD474D6338261571, 0xAA4546C3E473D062, 0x928FCE349455F860, 0x48161BBACAAB94D9, 0x63912430770E6F68, 0x6EC8A5E602C6641C, 0x87282515337DDD2B, 0x2CDA6B42034B701B, 0xB03D37C181CB096D, 0xE108438266C71C6F, 0x2B3180C7EB51B255, 0xDF92B82F96C08BBC, 0x5C68C8C0A632F3BA, 0x5504CC861C3D0556, 0xABBFA4E55FB26B8F, 0x41848B0AB3BACEB4, 0xB334A273AA445D32, 0xBCA696F0A85AD881, 0x24F6EC65B528D56C, 0xCE1512E90F4524A, 0x4E9DD79D5506D35A, 0x258905FAC6CE9779, 0x2019295B3E109B33, 0xF8A9478B73A054CC, 0x2924F2F934417EB0, 0x3993357D536D1BC4, 0x38A81AC21DB6FF8B, 0x47C4FBF17D6016BF, 0x1E0FAADD7667E3F5, 0x7ABCFF62938BEB96, 0xA78DAD948FC179C9, 0x8F1F98B72911E50D, 0x61E48EAE27121A91, 0x4D62F7AD31859808, 0xECEBA345EF5CEAEB, 0xF5CEB25EBC9684CE, 0xF633E20CB7F76221, 0xA32CDF06AB8293E4, 0x985A202CA5EE2CA4, 0xCF0B8447CC8A8FB1, 0x9F765244979859A3, 0xA8D516B1A1240017, 0xBD7BA3EBB5DC726, 0xE54BCA55B86ADB39, 0x1D7A3AFD6C478063, 0x519EC608E7669EDD, 0xE5715A2D149AA23, 0x177D4571848FF194, 0xEEB55F3241014C22, 0xF5E5CA13A6E2EC2, 0x8029927B75F5C361, 0xAD139FABC3D6E436, 0xD5DF1A94CCF402F, 0x3E8BD948BEA5DFC8, 0xA5A0D357BD3FF77E, 0xA2D12E251F74F645, 0x66FD9E525E81A082, 0x2E0C90CE7F687A49, 0xC2E8BCBEBA973BC5, 0x1BCE509745F, 0x423777BBE6DAB3D6, 0xD1661C7EAEF06EB5, 0xA1781F354DAACFD8, 0x2D11284A2B16AFFC, 0xF1FC4F67FA891D1F, 0x73ECC25DCB920ADA, 0xAE610C22C2A12651, 0x96E0A810D356B78A, 0x5A9A381F2FE7870F, 0xD5AD62EDE94E5530, 0xD225E5E8368D1427, 0x65977B70C7AF4631, 0x99F889B2DE39D74F, 0x233F30BF54E1D143, 0x9A9675D3D9A63C97, 0x5470554FF334F9A8, 0x166ACB744A4F5688, 0x70C74CAAB2E4AEAD, 0xF0D091646F294D12, 0x57B82A89684031D1, 0xEFD95A5A61BE0B6B, 0x2FBD12E969F2F29A, 0x9BD37013FEFF9FE8, 0x3F9B0404D6085A06, 0x4940C1F3166CFE15, 0x9542C4DCDF3DEFB, 0xB4C5218385CD5CE3, 0xC935B7DC4462A641, 0x3417F8A68ED3B63F, 0xB80959295B215B40, 0xF99CDAEF3B8C8572, 0x18C0614F8FCB95D, 0x1B14ACCD1A3ACDF3, 0x84D471F200BB732D, 0xC1A3110E95E8DA16, 0x430A7220BF1A82B8, 0xB77E090D39DF210E, 0x5EF4BD9F3CD05E9D, 0x9D4FF6DA7E57A444, 0xDA1D60E183D4A5F8, 0xB287C38417998E47, 0xFE3EDC121BB31886, 0xC7FE3CCC980CCBEF, 0xE46FB590189BFD03, 0x3732FD469A4C57DC, 0x7EF700A07CF1AD65, 0x59C64468A31D8859, 0x762FB0B4D45B61F6, 0x155BAED099047718, 0x68755E4C3D50BAA6, 0xE9214E7F22D8B4DF, 0x2ADDBF532EAC95F4, 0x32AE3909B4BD0109, 0x834DF537B08E3450, 0xFA209DA84220728D, 0x9E691D9B9EFE23F7, 0x446D288C4AE8D7F, 0x7B4CC524E169785B, 0x21D87F0135CA1385, 0xCEBB400F137B8AA5, 0x272E2B66580796BE, 0x3612264125C2B0DE, 0x57702BDAD1EFBB2, 0xD4BABB8EACF84BE9, 0x91583139641BC67B, 0x8BDC2DE08036E024, 0x603C8156F49F68ED, 0xF7D236F7DBEF5111, 0x9727C4598AD21E80, 0xA08A0896670A5FD7, 0xCB4A8F4309EBA9CB, 0x81AF564B0F7036A1, 0xC0B99AA778199ABD, 0x959F1EC83FC8E952, 0x8C505077794A81B9, 0x3ACAAF8F056338F0, 0x7B43F50627A6778, 0x4A44AB49F5ECCC77, 0x3BC3D6E4B679EE98, 0x9CC0D4D1CF14108C, 0x4406C00B206BC8A0, 0x82A18854C8D72D89, 0x67E366B35C3C432C, 0xB923DD61102B37F2, 0x56AB2779D884271D, 0xBE83E1B0FF1525AF, 0xFB7C65D4217E49A9, 0x6BDBE0E76D48E7D4, 0x8DF828745D9179E, 0x22EA6A9ADD53BD34, 0xE36E141C5622200A, 0x7F805D1B8CB750EE, 0xAFE5C7A59F58E837, 0xE27F996A4FB1C23C, 0xD3867DFB0775F0D0, 0xD0E673DE6E88891A, 0x123AEB9EAFB86C25, 0x30F1D5D5C145B895, 0xBB434A2DEE7269E7, 0x78CB67ECF931FA38, 0xF33B0372323BBF9C, 0x52D66336FB279C74, 0x505F33AC0AFB4EAA, 0xE8A5CD99A2CCE187, 0x534974801E2D30BB, 0x8D2D5711D5876D90, 0x1F1A412891BC038E, 0xD6E2E71D82E56648, 0x74036C3A497732B7, 0x89B67ED96361F5AB, 0xFFED95D8F1EA02A2, 0xE72B3BD61464D43D, 0xA6300F170BDC4820, 0xEBC18760ED78A77A, 0xE6A6BE5A05A12138, 0xB5A122A5B4F87C98, 0x563C6089140B6990, 0x4C46CB2E391F5DD5, 0xD932ADDBC9B79434, 0x8EA70E42015AFF5, 0xD765A6673E478CF1, 0xC4FB757EAB278D99, 0xDF11C6862D6E0692, 0xDDEB84F10D7F3B16, 0x6F2EF604A665EA04, 0x4A8E0F0FF0E0DFB3, 0xA5EDEEF83DBCBA51, 0xFC4F0A2A0EA4371E, 0xE83E1DA85CB38429, 0xDC8FF882BA1B1CE2, 0xCD45505E8353E80D, 0x18D19A00D4DB0717, 0x34A0CFEDA5F38101, 0xBE77E518887CAF2, 0x1E341438B3C45136, 0xE05797F49089CCF9, 0xFFD23F9DF2591D14, 0x543DDA228595C5CD, 0x661F81FD99052A33, 0x8736E641DB0F7B76, 0x15227725418E5307, 0xE25F7F46162EB2FA, 0x48A8B2126C13D9FE, 0xAFDC541792E76EEA, 0x3D912BFC6D1898F, 0x31B1AAFA1B83F51B, 0xF1AC2796E42AB7D9, 0x40A3A7D7FCD2EBAC, 0x1056136D0AFBBCC5, 0x7889E1DD9A6D0C85, 0xD33525782A7974AA, 0xA7E25D09078AC09B, 0xBD4138B3EAC6EDD0, 0x920ABFBE71EB9E70, 0xA2A5D0F54FC2625C, 0xC054E36B0B1290A3, 0xF6DD59FF62FE932B, 0x3537354511A8AC7D, 0xCA845E9172FADCD4, 0x84F82B60329D20DC, 0x79C62CE1CD672F18, 0x8B09A2ADD124642C, 0xD0C1E96A19D9E726, 0x5A786A9B4BA9500C, 0xE020336634C43F3, 0xC17B474AEB66D822, 0x6A731AE3EC9BAAC2, 0x8226667AE0840258, 0x67D4567691CAECA5, 0x1D94155C4875ADB5, 0x6D00FD985B813FDF, 0x51286EFCB774CD06, 0x5E8834471FA744AF, 0xF72CA0AEE761AE2E, 0xBE40E4CDAEE8E09A, 0xE9970BBB5118F665, 0x726E4BEB33DF1964, 0x703B000729199762, 0x4631D816F5EF30A7, 0xB880B5B51504A6BE, 0x641793C37ED84B6C, 0x7B21ED77F6E97D96, 0x776306312EF96B73, 0xAE528948E86FF3F4, 0x53DBD7F286A3F8F8, 0x16CADCE74CFC1063, 0x5C19BDFA52C6DD, 0x68868F5D64D46AD3, 0x3A9D512CCF1E186A, 0x367E62C2385660AE, 0xE359E7EA77DCB1D7, 0x526C0773749ABE6E, 0x735AE5F9D09F734B, 0x493FC7CC8A558BA8, 0xB0B9C1533041AB45, 0x321958BA470A59BD, 0x852DB00B5F46C393, 0x91209B2BD336B0E5, 0x6E604F7D659EF19F, 0xB99A8AE2782CCB24, 0xCCF52AB6C814C4C7, 0x4727D9AFBE11727B, 0x7E950D0C0121B34D, 0x756F435670AD471F, 0xF5ADD442615A6849, 0x4E87E09980B9957A, 0x2ACFA1DF50AEE355, 0xD898263AFD2FD556, 0xC8F4924DD80C8FD6, 0xCF99CA3D754A173A, 0xFE477BACAF91BF3C, 0xED5371F6D690C12D, 0x831A5C285E687094, 0xC5D3C90A3708A0A4, 0xF7F903717D06580, 0x19F9BB13B8FDF27F, 0xB1BD6F1B4D502843, 0x1C761BA38FFF4012, 0xD1530C4E2E21F3B, 0x8943CE69A7372C8A, 0xE5184E11FEB5CE66, 0x618BDB80BD736621, 0x7D29BAD68B574D0B, 0x81BB613E25E6FE5B, 0x71C9C10BC07913F, 0xC7BEEB7909AC2D97, 0xC3E58D353BC5D757, 0xEB017892F38F61E8, 0xD4EFFB9C9B1CC21A, 0x99727D26F494F7AB, 0xA3E063A2956B3E03, 0x9D4A8B9A4AA09C30, 0x3F6AB7D500090FB4, 0x9CC0F2A057268AC0, 0x3DEE9D2DEDBF42D1, 0x330F49C87960A972, 0xC6B2720287421B41, 0xAC59EC07C00369C, 0xEF4EAC49CB353425, 0xF450244EEF0129D8, 0x8ACC46E5CAF4DEB6, 0x2FFEAB63989263F7, 0x8F7CB9FE5D7A4578, 0x5BD8F7644E634635, 0x427A7315BF2DC900, 0x17D0C4AA2125261C, 0x3992486C93518E50, 0xB4CBFEE0A2D7D4C3, 0x7C75D6202C5DDD8D, 0xDBC295D8E35B6C61, 0x60B369D302032B19, 0xCE42685FDCE44132, 0x6F3DDB9DDF65610, 0x8EA4D21DB5E148F0, 0x20B0FCE62FCD496F, 0x2C1B912358B0EE31, 0xB28317B818F5A308, 0xA89C1E189CA6D2CF, 0xC6B18576AAADBC8, 0xB65DEAA91299FAE3, 0xFB2B794B7F1027E7, 0x4E4317F443B5BEB, 0x4B852D325939D0A6, 0xD5AE6BEEFB207FFC, 0x309682B281C7D374, 0xBAE309A194C3B475, 0x8CC3F97B13B49F05, 0x98A9422FF8293967, 0x244B16B01076FF7C, 0xF8BF571C663D67EE, 0x1F0D6758EEE30DA1, 0xC9B611D97ADEB9B7, 0xB7AFD5887B6C57A2, 0x6290AE846B984FE1, 0x94DF4CDEACC1A5FD, 0x58A5BD1C5483AFF, 0x63166CC142BA3C37, 0x8DB8526EB2F76F40, 0xE10880036F0D6D4E, 0x9E0523C9971D311D, 0x45EC2824CC7CD691, 0x575B8359E62382C9, 0xFA9E400DC4889995, 0xD1823ECB45721568, 0xDAFD983B8206082F, 0xAA7D29082386A8CB, 0x269FCD4403B87588, 0x1B91F5F728BDD1E0, 0xE4669F39040201F6, 0x7A1D7C218CF04ADE, 0x65623C29D79CE5CE, 0x2368449096C00BB1, 0xAB9BF1879DA503BA, 0xBC23ECB1A458058E, 0x9A58DF01BB401ECC, 0xA070E868A85F143D, 0x4FF188307DF2239E, 0x14D565B41A641183, 0xEE13337452701602, 0x950E3DCF3F285E09, 0x59930254B9C80953, 0x3BF299408930DA6D, 0xA955943F53691387, 0xA15EDECAA9CB8784, 0x29142127352BE9A0, 0x76F0371FFF4E7AFB, 0x239F450274F2228, 0xBB073AF01D5E868B, 0xBFC80571C10E96C1, 0xD267088568222E23, 0x9671A3D48E80B5B0, 0x55B5D38AE193BB81, 0x693AE2D0A18B04B8, 0x5C48B4ECADD5335F, 0xFD743B194916A1CA, 0x2577018134BE98C4, 0xE77987E83C54A4AD, 0x28E11014DA33E1B9, 0x270CC59E226AA213, 0x71495F756D1A5F60, 0x9BE853FB60AFEF77, 0xADC786A7F7443DBF, 0x904456173B29A82, 0x58BC7A66C232BD5E, 0xF306558C673AC8B2, 0x41F639C6B6C9772A, 0x216DEFE99FDA35DA, 0x11640CC71C7BE615, 0x93C43694565C5527, 0xEA038E6246777839, 0xF9ABF3CE5A3E2469, 0x741E768D0FD312D2, 0x144B883CED652C6, 0xC20B5A5BA33F8552, 0x1AE69633C3435A9D, 0x97A28CA4088CFDEC, 0x8824A43C1E96F420, 0x37612FA66EEEA746, 0x6B4CB165F9CF0E5A, 0x43AA1C06A0ABFB4A, 0x7F4DC26FF162796B, 0x6CBACC8E54ED9B0F, 0xA6B7FFEFD2BB253E, 0x2E25BC95B0A29D4F, 0x86D6A58BDEF1388C, 0xDED74AC576B6F054, 0x8030BDBC2B45805D, 0x3C81AF70E94D9289, 0x3EFF6DDA9E3100DB, 0xB38DC39FDFCC8847, 0x123885528D17B87E, 0xF2DA0ED240B1B642, 0x44CEFADCD54BF9A9, 0x1312200E433C7EE6, 0x9FFCC84F3A78C748, 0xF0CD1F72248576BB, 0xEC6974053638CFE4, 0x2BA7B67C0CEC4E4C, 0xAC2F4DF3E5CE32ED, 0xCB33D14326EA4C11, 0xA4E9044CC77E58BC, 0x5F513293D934FCEF, 0x5DC9645506E55444, 0x50DE418F317DE40A, 0x388CB31A69DDE259, 0x2DB4A83455820A86, 0x9010A91E84711AE9, 0x4DF7F0B7B1498371, 0xD62A2EABC0977179, 0x22FAC097AA8D5C0E, 0xF49FCC2FF1DAF39B, 0x487FD5C66FF29281, 0xE8A30667FCDCA83F, 0x2C9B4BE3D2FCCE63, 0xDA3FF74B93FBBBC2, 0x2FA165D2FE70BA66, 0xA103E279970E93D4, 0xBECDEC77B0E45E71, 0xCFB41E723985E497, 0xB70AAA025EF75017, 0xD42309F03840B8E0, 0x8EFC1AD035898579, 0x96C6920BE2B2ABC5, 0x66AF4163375A9172, 0x2174ABDCCA7127FB, 0xB33CCEA64A72FF41, 0xF04A4933083066A5, 0x8D970ACDD7289AF5, 0x8F96E8E031C8C25E, 0xF3FEC02276875D47, 0xEC7BF310056190DD, 0xF5ADB0AEBB0F1491, 0x9B50F8850FD58892, 0x4975488358B74DE8, 0xA3354FF691531C61, 0x702BBE481D2C6EE, 0x89FB24057DEDED98, 0xAC3075138596E902, 0x1D2D3580172772ED, 0xEB738FC28E6BC30D, 0x5854EF8F63044326, 0x9E5C52325ADD3BBE, 0x90AA53CF325C4623, 0xC1D24D51349DD067, 0x2051CFEEA69EA624, 0x13220F0A862E7E4F, 0xCE39399404E04864, 0xD9C42CA47086FCB7, 0x685AD2238A03E7CC, 0x66484B2AB2FF1DB, 0xFE9D5D70EFBF79EC, 0x5B13B9DD9C481854, 0x15F0D475ED1509AD, 0xBEBCD060EC79851, 0xD58C6791183AB7F8, 0xD1187C5052F3EEE4, 0xC95D1192E54E82FF, 0x86EEA14CB9AC6CA2, 0x3485BEB153677D5D, 0xDD191D781F8C492A, 0xF60866BAA784EBF9, 0x518F643BA2D08C74, 0x8852E956E1087C22, 0xA768CB8DC410AE8D, 0x38047726BFEC8E1A, 0xA67738B4CD3B45AA, 0xAD16691CEC0DDE19, 0xC6D4319380462E07, 0xC5A5876D0BA61938, 0x16B9FA1FA58FD840, 0x188AB1173CA74F18, 0xABDA2F98C99C021F, 0x3E0580AB134AE816, 0x5F3B05B773645ABB, 0x2501A2BE5575F2F6, 0x1B2F74004E7E8BA9, 0x1CD7580371E8D953, 0x7F6ED89562764E30, 0xB15926FF596F003D, 0x9F65293DA8C5D6B9, 0x6ECEF04DD690F84C, 0x4782275FFF33AF88, 0xE41433083F820801, 0xFD0DFE409A1AF9B5, 0x4325A3342CDB396B, 0x8AE77E62B301B252, 0xC36F9E9F6655615A, 0x85455A2D92D32C09, 0xF2C7DEA949477485, 0x63CFB4C133A39EBA, 0x83B040CC6EBC5462, 0x3B9454C8FDB326B0, 0x56F56A9E87FFD78C, 0x2DC2940D99F42BC6, 0x98F7DF096B096E2D, 0x19A6E01E3AD852BF, 0x42A99CCBDBD4B40B, 0xA59998AF45E9C559, 0x366295E807D93186, 0x6B48181BFAA1F773, 0x1FEC57E2157A0A1D, 0x4667446AF6201AD5, 0xE615EBCACFB0F075, 0xB8F31F4F68290778, 0x22713ED6CE22D11E, 0x3057C1A72EC3C93B, 0xCB46ACC37C3F1F2F, 0xDBB893FD02AAF50E, 0x331FD92E600B9FCF, 0xA498F96148EA3AD6, 0xA8D8426E8B6A83EA, 0xA089B274B7735CDC, 0x87F6B3731E524A11, 0x118808E5CBC96749, 0x9906E4C7B19BD394, 0xAFED7F7E9B24A20C, 0x6509EADEEB3644A7, 0x6C1EF1D3E8EF0EDE, 0xB9C97D43E9798FB4, 0xA2F2D784740C28A3, 0x7B8496476197566F, 0x7A5BE3E6B65F069D, 0xF96330ED78BE6F10, 0xEEE60DE77A076A15, 0x2B4BEE4AA08B9BD0, 0x6A56A63EC7B8894E, 0x2121359BA34FEF4, 0x4CBF99F8283703FC, 0x398071350CAF30C8, 0xD0A77A89F017687A, 0xF1C1A9EB9E423569, 0x8C7976282DEE8199, 0x5D1737A5DD1F7ABD, 0x4F53433C09A9FA80, 0xFA8B0C53DF7CA1D9, 0x3FD9DCBC886CCB77, 0xC040917CA91B4720, 0x7DD00142F9D1DCDF, 0x8476FC1D4F387B58, 0x23F8E7C5F3316503, 0x32A2244E7E37339, 0x5C87A5D750F5A74B, 0x82B4CC43698992E, 0xDF917BECB858F63C, 0x3270B8FC5BF86DDA, 0x10AE72BB29B5DD76, 0x576AC94E7700362B, 0x1AD112DAC61EFB8F, 0x691BC30EC5FAA427, 0xFF246311CC327143, 0x3142368E30E53206, 0x71380E31E02CA396, 0x958D5C960AAD76F1, 0xF8D6F430C16DA536, 0xC8FFD13F1BE7E1D2, 0x7578AE66004DDBE1, 0x5833F01067BE646, 0xBB34B5AD3BFE586D, 0x95F34C9A12B97F0, 0x247AB64525D60CA8, 0xDCDBC6F3017477D1, 0x4A2E14D4DECAD24D, 0xBDB5E6D9BE0A1EEB, 0x2A7E70F7794301AB, 0xDEF42D8A270540FD, 0x1078EC0A34C22C1, 0xE5DE511AF4C16387, 0x7EBB3A52BD9A330A, 0x77697857AA7D6435, 0x4E831603AE4C32, 0xE7A21020AD78E312, 0x9D41A70C6AB420F2, 0x28E06C18EA1141E6, 0xD2B28CBD984F6B28, 0x26B75F6C446E9D83, 0xBA47568C4D418D7F, 0xD80BADBFE6183D8E, 0xE206D7F5F166044, 0xE258A43911CBCA3E, 0x723A1746B21DC0BC, 0xC7CAA854F5D7CDD3, 0x7CAC32883D261D9C, 0x7690C26423BA942C, 0x17E55524478042B8, 0xE0BE477656A2389F, 0x4D289B5E67AB2DA0, 0x44862B9C8FBBFD31, 0xB47CC8049D141365, 0x822C1B362B91C793, 0x4EB14655FB13DFD8, 0x1ECBBA0714E2A97B, 0x6143459D5CDE5F14, 0x53A8FBF1D5F0AC89, 0x97EA04D81C5E5B00, 0x622181A8D4FDB3F3, 0xE9BCD341572A1208, 0x1411258643CCE58A, 0x9144C5FEA4C6E0A4, 0xD33D06565CF620F, 0x54A48D489F219CA1, 0xC43E5EAC6D63C821, 0xA9728B3A72770DAF, 0xD7934E7B20DF87EF, 0xE35503B61A3E86E5, 0xCAE321FBC819D504, 0x129A50B3AC60BFA6, 0xCD5E68EA7E9FB6C3, 0xB01C90199483B1C7, 0x3DE93CD5C295376C, 0xAED52EDF2AB9AD13, 0x2E60F512C0A07884, 0xBC3D86A3E36210C9, 0x35269D9B163951CE, 0xC7D6E2AD0CDB5FA, 0x59E86297D87F5733, 0x298EF221898DB0E7, 0x55000029D1A5AA7E, 0x8BC08AE1B5061B45, 0xC2C31C2B6C92703A, 0x94CC596BAF25EF42, 0xA1D73DB22540456, 0x4B6A0F9D9C4179A, 0xEFFDAFA2AE3D3C60, 0xF7C8075BB49496C4, 0x9CC5C7141D1CD4E3, 0x78BD1638218E5534, 0xB2F11568F850246A, 0xEDFABCFA9502BC29, 0x796CE5F2DA23051B, 0xAAE128B0DC93537C, 0x3A493DA0EE4B29AE, 0xB5DF6B2C416895D7, 0xFCABBD25122D7F37, 0x70810B58105DC4B1, 0xE10FDD37F7882A90, 0x524DCAB5518A3F5C, 0x3C9E85878451255B, 0x4029828119BD34E2, 0x74A05B6F5D3CECCB, 0xB610021542E13ECA, 0xFF979D12F59E2AC, 0x6037DA27E4F9CC50, 0x5E92975A0DF1847D, 0xD66DE190D3E623FE, 0x5032D6B87B568048, 0x9A36B7CE8235216E, 0x80272A7A24F64B4A, 0x93EFED8B8C6916F7, 0x37DDBFF44CCE1555, 0x4B95DB5D4B99BD25, 0x92D3FDA169812FC0, 0xFB1A4A9A90660BB6, 0x730C196946A4B9B2, 0x81E289AA7F49DA68, 0x64669A0F83B1A05F, 0x27B3FF7D9644F48B, 0xCC6B615C8DB675B3, 0x674F20B9BCEBBE95, 0x6F31238275655982, 0x5AE488713E45CF05, 0xBF619F9954C21157, 0xEABAC46040A8EAE9, 0x454C6FE9F2C0C1CD, 0x419CF6496412691C, 0xD3DC3BEF265B0F70, 0x6D0E60F5C3578A9E, 0x5B0E608526323C55, 0x1A46C1A9FA1B59F5, 0xA9E245A17C4C8FFA, 0x65CA5159DB2955D7, 0x5DB0A76CE35AFC2, 0x81EAC77EA9113D45, 0x528EF88AB6AC0A0D, 0xA09EA253597BE3FF, 0x430DDFB3AC48CD56, 0xC4B3A67AF45CE46F, 0x4ECECFD8FBE2D05E, 0x3EF56F10B39935F0, 0xB22D6829CD619C6, 0x17FD460A74DF2069, 0x6CF8CC8E8510ED40, 0xD6C824BF3A6ECAA7, 0x61243D581A817049, 0x48BACB6BBC163A2, 0xD9A38AC27D44CC32, 0x7FDDFF5BAAF410AB, 0xAD6D495AA804824B, 0xE1A6A74F2D8C9F94, 0xD4F7851235DEE8E3, 0xFD4B7F886540D893, 0x247C20042AA4BFDA, 0x96EA1C517D1327C, 0xD56966B4361A6685, 0x277DA5C31221057D, 0x94D59893A43ACFF7, 0x64F0C51CCDC02281, 0x3D33BCC4FF6189DB, 0xE005CB184CE66AF1, 0xFF5CCD1D1DB99BEA, 0xB0B854A7FE42980F, 0x7BD46A6A718D4B9F, 0xD10FA8CC22A5FD8C, 0xD31484952BE4BD31, 0xC7FA975FCB243847, 0x4886ED1E5846C407, 0x28CDDB791EB70B04, 0xC2B00BE2F573417F, 0x5C9590452180F877, 0x7A6BDDFFF370EB00, 0xCE509E38D6D9D6A4, 0xEBEB0F00647FA702, 0x1DCC06CF76606F06, 0xE4D9F28BA286FF0A, 0xD85A305DC918C262, 0x475B1D8732225F54, 0x2D4FB51668CCB5FE, 0xA679B9D9D72BBA20, 0x53841C0D912D43A5, 0x3B7EAA48BF12A4E8, 0x781E0E47F22F1DDF, 0xEFF20CE60AB50973, 0x20D261D19DFFB742, 0x16A12B03062A2E39, 0x1960EB2239650495, 0x251C16FED50EB8B8, 0x9AC0C330F826016E, 0xED152665953E7671, 0x2D63194A6369570, 0x5074F08394B1C987, 0x70BA598C90B25CE1, 0x794A15810B9742F6, 0xD5925E9FCAF8C6C, 0x3067716CD868744E, 0x910AB077E8D7731B, 0x6A61BBDB5AC42F61, 0x93513EFBF0851567, 0xF494724B9E83E9D5, 0xE887E1985C09648D, 0x34B1D3C675370CFD, 0xDC35E433BC0D255D, 0xD0AAB84234131BE0, 0x8042A50B48B7EAF, 0x9997C4EE44A3AB35, 0x829A7B49201799D0, 0x263B8307B7C54441, 0x752F95F4FD6A6CA6, 0x927217402C08C6E5, 0x2A8AB754A795D9EE, 0xA442F7552F72943D, 0x2C31334E19781208, 0x4FA98D7CEAEE6291, 0x55C3862F665DB309, 0xBD0610175D53B1F3, 0x46FE6CB840413F27, 0x3FE03792DF0CFA59, 0xCFE700372EB85E8F, 0xA7BE29E7ADBCE118, 0xE544EE5CDE8431DD, 0x8A781B1B41F1873E, 0xA5C94C78A0D2F0E7, 0x39412E2877B60728, 0xA1265EF3AFC9A62C, 0xBCC2770C6A2506C5, 0x3AB66DD5DCE1CE12, 0xE65499D04A675B37, 0x7D8F523481BFD216, 0xF6F64FCEC15F389, 0x74EFBE618B5B13C8, 0xACDC82B714273E1D, 0xDD40BFE003199D17, 0x37E99257E7E061F8, 0xFA52626904775AAA, 0x8BBBF63A463D56F9, 0xF0013F1543A26E64, 0xA8307E9F879EC898, 0xCC4C27A4150177CC, 0x1B432F2CCA1D3348, 0xDE1D1F8F9F6FA013, 0x606602A047A7DDD6, 0xD237AB64CC1CB2C7, 0x9B938E7225FCD1D3, 0xEC4E03708E0FF476, 0xFEB2FBDA3D03C12D, 0xAE0BCED2EE43889A, 0x22CB8923EBFB4F43, 0x69360D013CF7396D, 0x855E3602D2D4E022, 0x73805BAD01F784C, 0x33E17A133852F546, 0xDF4874058AC7B638, 0xBA92B29C678AA14A, 0xCE89FC76CFAADCD, 0x5F9D4E0908339E34, 0xF1AFE9291F5923B9, 0x6E3480F60F4A265F, 0xEEBF3A2AB29B841C, 0xE21938A88F91B4AD, 0x57DFEFF845C6D3C3, 0x2F006B0BF62CAAF2, 0x62F479EF6F75EE78, 0x11A55AD41C8916A9, 0xF229D29084FED453, 0x42F1C27B16B000E6, 0x2B1F76749823C074, 0x4B76ECA3C2745360, 0x8C98F463B91691BD, 0x14BCC93CF1ADE66A, 0x8885213E6D458397, 0x8E177DF0274D4711, 0xB49B73B5503F2951, 0x10168168C3F96B6B, 0xE3D963B63CAB0AE, 0x8DFC4B5655A1DB14, 0xF789F1356E14DE5C, 0x683E68AF4E51DAC1, 0xC9A84F9D8D4B0FD9, 0x3691E03F52A0F9D1, 0x5ED86E46E1878E80, 0x3C711A0E99D07150, 0x5A0865B20C4E9310, 0x56FBFC1FE4F0682E, 0xEA8D5DE3105EDF9B, 0x71ABFDB12379187A, 0x2EB99DE1BEE77B9C, 0x21ECC0EA33CF4523, 0x59A4D7521805C7A1, 0x3896F5EB56AE7C72, 0xAA638F3DB18F75DC, 0x9F39358DABE9808E, 0xB7DEFA91C00B72AC, 0x6B5541FD62492D92, 0x6DC6DEE8F92E4D5B, 0x353F57ABC4BEEA7E, 0x735769D6DA5690CE, 0xA234AA642391484, 0xF6F9508028F80D9D, 0xB8E319A27AB3F215, 0x31AD9C1151341A4D, 0x773C22A57BEF5805, 0x45C7561A07968633, 0xF913DA9E249DBE36, 0xDA652D9B78A64C68, 0x4C27A97F3BC334EF, 0x76621220E66B17F4, 0x967743899ACD7D0B, 0xF3EE5BCAE0ED6782, 0x409F753600C879FC, 0x6D09A39B5926DB6, 0x6F83AEB0317AC588, 0x1E6CA4A86381F21, 0x66FF3462D19F3025, 0x72207C24DDFD3BFB, 0x4AF6B6D3E2ECE2EB, 0x9C994DBEC7EA08DE, 0x49ACE597B09A8BC4, 0xB38C4766CF0797BA, 0x131B9373C57C2A75, 0xB1822CCE61931E58, 0x9D7555B909BA1C0C, 0x127FAFDD937D11D2, 0x29DA3BADC66D92E4, 0xA2C1D57154C2ECBC, 0x58C5134D82F6FE24, 0x1C3AE3515B62274F, 0xE907C82E01CB8126, 0xF8ED091913E37FCB, 0x3249D8F9C80046C9, 0x80CF9BEDE388FB63, 0x1881539A116CF19E, 0x5103F3F76BD52457, 0x15B7E6F5AE47F7A8, 0xDBD7C6DED47E9CCF, 0x44E55C410228BB1A, 0xB647D4255EDB4E99, 0x5D11882BB8AAFC30, 0xF5098BBB29D3212A, 0x8FB5EA14E90296B3, 0x677B942157DD025A, 0xFB58E7C0A390ACB5, 0x89D3674C83BD4A01, 0x9E2DA4DF4BF3B93B, 0xFCC41E328CAB4829, 0x3F38C96BA582C52, 0xCAD1BDBD7FD85DB2, 0xBBB442C16082AE83, 0xB95FE86BA5DA9AB0, 0xB22E04673771A93F, 0x845358C9493152D8, 0xBE2A488697B4541E, 0x95A2DC2DD38E6966, 0xC02C11AC923C852B, 0x2388B1990DF2A87B, 0x7C8008FA1B4F37BE, 0x1F70D0C84D54E503, 0x5490ADEC7ECE57D4, 0x2B3C27D9063A3A, 0x7EAEA3848030A2BF, 0xC602326DED2003C0, 0x83A7287D69A94086, 0xC57A5FCB30F57A8A, 0xB56844E479EBE779, 0xA373B40F05DCBCE9, 0xD71A786E88570EE2, 0x879CBACDBDE8F6A0, 0x976AD1BCC164A32F, 0xAB21E25E9666D78B, 0x901063AAE5E5C33C, 0x9818B34448698D90, 0xE36487AE3E1E8ABB, 0xAFBDF931893BDCB4, 0x6345A0DC5FBBD519, 0x8628FE269B9465CA, 0x1E5D01603F9C51EC, 0x4DE44006A15049B7, 0xBF6C70E5F776CBB1, 0x411218F2EF552BED, 0xCB0C0708705A36A3, 0xE74D14754F986044, 0xCD56D9430EA8280E, 0xC12591D7535F5065, 0xC83223F1720AEF96, 0xC3A0396F7363A51F }; #endregion } }
using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using Wox.Plugin.Program.Programs; using System.ComponentModel; using System.Windows.Data; namespace Wox.Plugin.Program.Views { /// <summary> /// Interaction logic for ProgramSetting.xaml /// </summary> public partial class ProgramSetting : UserControl { private PluginInitContext context; private Settings _settings; private GridViewColumnHeader _lastHeaderClicked; private ListSortDirection _lastDirection; public ProgramSetting(PluginInitContext context, Settings settings, Win32[] win32s, UWP.Application[] uwps) { this.context = context; InitializeComponent(); Loaded += Setting_Loaded; _settings = settings; } private void Setting_Loaded(object sender, RoutedEventArgs e) { programSourceView.ItemsSource = _settings.ProgramSources; programIgnoreView.ItemsSource = _settings.IgnoredSequence; StartMenuEnabled.IsChecked = _settings.EnableStartMenuSource; RegistryEnabled.IsChecked = _settings.EnableRegistrySource; } private void ReIndexing() { programSourceView.Items.Refresh(); Task.Run(() => { Dispatcher.Invoke(() => { indexingPanel.Visibility = Visibility.Visible; }); Main.IndexPrograms(); Dispatcher.Invoke(() => { indexingPanel.Visibility = Visibility.Hidden; }); }); } private void btnAddProgramSource_OnClick(object sender, RoutedEventArgs e) { var add = new AddProgramSource(context, _settings); if (add.ShowDialog() ?? false) { ReIndexing(); } } private void btnEditProgramSource_OnClick(object sender, RoutedEventArgs e) { var selectedProgramSource = programSourceView.SelectedItem as ProgramSource; if (selectedProgramSource != null) { var add = new AddProgramSource(selectedProgramSource, _settings); if (add.ShowDialog() ?? false) { ReIndexing(); } } else { string msg = context.API.GetTranslation("wox_plugin_program_pls_select_program_source"); MessageBox.Show(msg); } } private void btnReindex_Click(object sender, RoutedEventArgs e) { ReIndexing(); } private void BtnProgramSuffixes_OnClick(object sender, RoutedEventArgs e) { var p = new ProgramSuffixes(context, _settings); if (p.ShowDialog() ?? false) { ReIndexing(); } } private void programSourceView_DragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) { e.Effects = DragDropEffects.Link; } else { e.Effects = DragDropEffects.None; } } private void programSourceView_Drop(object sender, DragEventArgs e) { var directories = (string[])e.Data.GetData(DataFormats.FileDrop); var directoriesToAdd = new List<ProgramSource>(); if (directories != null && directories.Length > 0) { foreach (string directory in directories) { if (Directory.Exists(directory)) { var source = new ProgramSource { Location = directory, }; directoriesToAdd.Add(source); } } if (directoriesToAdd.Count() > 0) { directoriesToAdd.ForEach(x => _settings.ProgramSources.Add(x)); ReIndexing(); } } } private void StartMenuEnabled_Click(object sender, RoutedEventArgs e) { _settings.EnableStartMenuSource = StartMenuEnabled.IsChecked ?? false; ReIndexing(); } private void RegistryEnabled_Click(object sender, RoutedEventArgs e) { _settings.EnableRegistrySource = RegistryEnabled.IsChecked ?? false; ReIndexing(); } private void btnProgramSoureDelete_OnClick(object sender, RoutedEventArgs e) { var selectedItems = programSourceView .SelectedItems.Cast<ProgramSource>() .ToList(); if (selectedItems.Count() == 0) { string msg = context.API.GetTranslation("wox_plugin_program_pls_select_program_source"); MessageBox.Show(msg); return; } else { _settings.ProgramSources.RemoveAll(s => selectedItems.Contains(s)); programSourceView.SelectedItems.Clear(); ReIndexing(); } } private void ProgramSourceView_PreviewMouseRightButtonUp(object sender, MouseButtonEventArgs e) { programSourceView.SelectedItems.Clear(); } private void GridViewColumnHeaderClickedHandler(object sender, RoutedEventArgs e) { var headerClicked = e.OriginalSource as GridViewColumnHeader; ListSortDirection direction; if (headerClicked != null) { if (headerClicked.Role != GridViewColumnHeaderRole.Padding) { if (headerClicked != _lastHeaderClicked) { direction = ListSortDirection.Ascending; } else { if (_lastDirection == ListSortDirection.Ascending) { direction = ListSortDirection.Descending; } else { direction = ListSortDirection.Ascending; } } var columnBinding = headerClicked.Column.DisplayMemberBinding as Binding; var sortBy = columnBinding?.Path.Path ?? headerClicked.Column.Header as string; Sort(sortBy, direction); _lastHeaderClicked = headerClicked; _lastDirection = direction; } } } private void Sort(string sortBy, ListSortDirection direction) { var dataView = CollectionViewSource.GetDefaultView(programSourceView.ItemsSource); dataView.SortDescriptions.Clear(); SortDescription sd = new SortDescription(sortBy, direction); dataView.SortDescriptions.Add(sd); dataView.Refresh(); } private void btnDeleteIgnored_OnClick(object sender, RoutedEventArgs e) { IgnoredEntry selectedIgnoredEntry = programIgnoreView.SelectedItem as IgnoredEntry; if (selectedIgnoredEntry != null) { string msg = string.Format(context.API.GetTranslation("wox_plugin_program_delete_ignored"), selectedIgnoredEntry); if (MessageBox.Show(msg, string.Empty, MessageBoxButton.YesNo) == MessageBoxResult.Yes) { _settings.IgnoredSequence.Remove(selectedIgnoredEntry); programIgnoreView.Items.Refresh(); } } else { string msg = context.API.GetTranslation("wox_plugin_program_pls_select_ignored"); MessageBox.Show(msg); } } private void btnEditIgnored_OnClick(object sender, RoutedEventArgs e) { IgnoredEntry selectedIgnoredEntry = programIgnoreView.SelectedItem as IgnoredEntry; if (selectedIgnoredEntry != null) { new AddIgnored(selectedIgnoredEntry, _settings).ShowDialog(); programIgnoreView.Items.Refresh(); } else { string msg = context.API.GetTranslation("wox_plugin_program_pls_select_ignored"); MessageBox.Show(msg); } } private void btnAddIgnored_OnClick(object sender, RoutedEventArgs e) { new AddIgnored(_settings).ShowDialog(); programIgnoreView.Items.Refresh(); } } }
// ReSharper disable once CheckNamespace namespace Fluent { using System; using System.Collections; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using System.Windows; using System.Windows.Automation; using System.Windows.Automation.Peers; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using Fluent.Automation.Peers; using Fluent.Extensions; using Fluent.Helpers; using Fluent.Internal; using Fluent.Internal.KnownBoxes; /// <summary> /// Represents ribbon tab item /// </summary> [TemplatePart(Name = "PART_HeaderContentHost", Type = typeof(FrameworkElement))] [TemplatePart(Name = "PART_ContentContainer", Type = typeof(Border))] [ContentProperty(nameof(Groups))] [DefaultProperty(nameof(Groups))] public class RibbonTabItem : Control, IKeyTipedControl, IHeaderedControl, ILogicalChildSupport { #region Fields // Content container private Border contentContainer; // Desired width private double desiredWidth; // Collection of ribbon groups private ObservableCollection<RibbonGroupBox> groups; // Ribbon groups container private readonly RibbonGroupsContainer groupsInnerContainer = new RibbonGroupsContainer(); // Cached width private double cachedWidth; #endregion #region Properties internal FrameworkElement HeaderContentHost { get; private set; } #region Colors/Brushes /// <summary> /// Gets or sets the <see cref="Brush"/> which is used to render the background if this <see cref="RibbonTabItem"/> is the currently active/selected one. /// </summary> public Brush ActiveTabBackground { get { return (Brush)this.GetValue(ActiveTabBackgroundProperty); } set { this.SetValue(ActiveTabBackgroundProperty, value); } } /// <summary>Identifies the <see cref="ActiveTabBackground"/> dependency property.</summary> public static readonly DependencyProperty ActiveTabBackgroundProperty = DependencyProperty.Register(nameof(ActiveTabBackground), typeof(Brush), typeof(RibbonTabItem), new PropertyMetadata()); /// <summary> /// Gets or sets the <see cref="Brush"/> which is used to render the border if this <see cref="RibbonTabItem"/> is the currently active/selected one. /// </summary> public Brush ActiveTabBorderBrush { get { return (Brush)this.GetValue(ActiveTabBorderBrushProperty); } set { this.SetValue(ActiveTabBorderBrushProperty, value); } } /// <summary>Identifies the <see cref="ActiveTabBorderBrush"/> dependency property.</summary> public static readonly DependencyProperty ActiveTabBorderBrushProperty = DependencyProperty.Register(nameof(ActiveTabBorderBrush), typeof(Brush), typeof(RibbonTabItem), new PropertyMetadata()); #endregion #region KeyTip /// <inheritdoc /> public string KeyTip { get { return (string)this.GetValue(KeyTipProperty); } set { this.SetValue(KeyTipProperty, value); } } /// <summary> /// Using a DependencyProperty as the backing store for Keys. /// This enables animation, styling, binding, etc... /// </summary> public static readonly DependencyProperty KeyTipProperty = Fluent.KeyTip.KeysProperty.AddOwner(typeof(RibbonTabItem)); #endregion /// <summary> /// Gets ribbon groups container /// </summary> public ScrollViewer GroupsContainer { get; } = new RibbonGroupsContainerScrollViewer { VerticalScrollBarVisibility = ScrollBarVisibility.Disabled }; /// <summary> /// Gets or sets whether ribbon is minimized /// </summary> public bool IsMinimized { get { return (bool)this.GetValue(IsMinimizedProperty); } set { this.SetValue(IsMinimizedProperty, value); } } /// <summary>Identifies the <see cref="IsMinimized"/> dependency property.</summary> public static readonly DependencyProperty IsMinimizedProperty = DependencyProperty.Register(nameof(IsMinimized), typeof(bool), typeof(RibbonTabItem), new PropertyMetadata(BooleanBoxes.FalseBox)); /// <summary> /// Gets or sets whether ribbon is opened /// </summary> public bool IsOpen { get { return (bool)this.GetValue(IsOpenProperty); } set { this.SetValue(IsOpenProperty, value); } } /// <summary>Identifies the <see cref="IsOpen"/> dependency property.</summary> public static readonly DependencyProperty IsOpenProperty = DependencyProperty.Register(nameof(IsOpen), typeof(bool), typeof(RibbonTabItem), new PropertyMetadata(BooleanBoxes.FalseBox)); /// <summary> /// Gets or sets reduce order /// </summary> public string ReduceOrder { get { return this.groupsInnerContainer.ReduceOrder; } set { this.groupsInnerContainer.ReduceOrder = value; } } #region IsContextual /// <summary> /// Gets or sets whether tab item is contextual /// </summary> public bool IsContextual { get { return (bool)this.GetValue(IsContextualProperty); } private set { this.SetValue(IsContextualPropertyKey, value); } } private static readonly DependencyPropertyKey IsContextualPropertyKey = DependencyProperty.RegisterReadOnly(nameof(IsContextual), typeof(bool), typeof(RibbonTabItem), new PropertyMetadata(BooleanBoxes.FalseBox)); /// <summary>Identifies the <see cref="IsContextual"/> dependency property.</summary> public static readonly DependencyProperty IsContextualProperty = IsContextualPropertyKey.DependencyProperty; #endregion /// <summary> /// Gets or sets whether tab item is selected /// </summary> [Bindable(true)] [Category("Appearance")] public bool IsSelected { get { return (bool)this.GetValue(IsSelectedProperty); } set { this.SetValue(IsSelectedProperty, value); } } /// <summary> /// Using a DependencyProperty as the backing store for IsSelected. /// This enables animation, styling, binding, etc... /// </summary> public static readonly DependencyProperty IsSelectedProperty = Selector.IsSelectedProperty.AddOwner(typeof(RibbonTabItem), new FrameworkPropertyMetadata(BooleanBoxes.FalseBox, FrameworkPropertyMetadataOptions.Journal | FrameworkPropertyMetadataOptions.BindsTwoWayByDefault | FrameworkPropertyMetadataOptions.AffectsParentMeasure, OnIsSelectedChanged)); /// <summary> /// Gets ribbon tab control parent /// </summary> internal RibbonTabControl TabControlParent => UIHelper.GetParent<RibbonTabControl>(this); /// <summary> /// Gets or sets the padding for the header. /// </summary> public Thickness HeaderPadding { get { return (Thickness)this.GetValue(HeaderPaddingProperty); } set { this.SetValue(HeaderPaddingProperty, value); } } /// <summary>Identifies the <see cref="HeaderPadding"/> dependency property.</summary> public static readonly DependencyProperty HeaderPaddingProperty = DependencyProperty.Register(nameof(HeaderPadding), typeof(Thickness), typeof(RibbonTabItem), new PropertyMetadata(new Thickness(8, 5, 8, 5))); /// <summary> /// Gets or sets whether separator is visible /// </summary> public bool IsSeparatorVisible { get { return (bool)this.GetValue(IsSeparatorVisibleProperty); } set { this.SetValue(IsSeparatorVisibleProperty, value); } } /// <summary>Identifies the <see cref="IsSeparatorVisible"/> dependency property.</summary> public static readonly DependencyProperty IsSeparatorVisibleProperty = DependencyProperty.Register(nameof(IsSeparatorVisible), typeof(bool), typeof(RibbonTabItem), new PropertyMetadata(BooleanBoxes.FalseBox)); /// <summary> /// Gets or sets ribbon contextual tab group /// </summary> public RibbonContextualTabGroup Group { get { return (RibbonContextualTabGroup)this.GetValue(GroupProperty); } set { this.SetValue(GroupProperty, value); } } /// <summary>Identifies the <see cref="Group"/> dependency property.</summary> public static readonly DependencyProperty GroupProperty = DependencyProperty.Register(nameof(Group), typeof(RibbonContextualTabGroup), typeof(RibbonTabItem), new PropertyMetadata(OnGroupChanged)); // handles Group property chanhged private static void OnGroupChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var tab = (RibbonTabItem)d; ((RibbonContextualTabGroup)e.OldValue)?.RemoveTabItem(tab); if (e.NewValue != null) { var tabGroup = (RibbonContextualTabGroup)e.NewValue; tabGroup.AppendTabItem(tab); tab.IsContextual = true; } else { tab.IsContextual = false; } } /// <summary> /// Gets or sets desired width of the tab item. /// </summary> /// <remarks>This is needed in case the width of <see cref="Group"/> is larger than it's tabs.</remarks> internal double DesiredWidth { get { return this.desiredWidth; } set { this.desiredWidth = value; this.InvalidateMeasure(); } } /// <summary> /// Gets or sets whether tab item has left group border /// </summary> public bool HasLeftGroupBorder { get { return (bool)this.GetValue(HasLeftGroupBorderProperty); } set { this.SetValue(HasLeftGroupBorderProperty, value); } } /// <summary>Identifies the <see cref="HasLeftGroupBorder"/> dependency property.</summary> public static readonly DependencyProperty HasLeftGroupBorderProperty = DependencyProperty.Register(nameof(HasLeftGroupBorder), typeof(bool), typeof(RibbonTabItem), new PropertyMetadata(BooleanBoxes.FalseBox)); /// <summary> /// Gets or sets whether tab item has right group border /// </summary> public bool HasRightGroupBorder { get { return (bool)this.GetValue(HasRightGroupBorderProperty); } set { this.SetValue(HasRightGroupBorderProperty, value); } } /// <summary>Identifies the <see cref="HasRightGroupBorder"/> dependency property.</summary> public static readonly DependencyProperty HasRightGroupBorderProperty = DependencyProperty.Register(nameof(HasRightGroupBorder), typeof(bool), typeof(RibbonTabItem), new PropertyMetadata(BooleanBoxes.FalseBox)); /// <summary> /// get collection of ribbon groups /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public ObservableCollection<RibbonGroupBox> Groups { get { if (this.groups is null) { this.groups = new ObservableCollection<RibbonGroupBox>(); this.groups.CollectionChanged += this.OnGroupsCollectionChanged; } return this.groups; } } // handles ribbon groups collection changes private void OnGroupsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (this.groupsInnerContainer is null) { return; } switch (e.Action) { case NotifyCollectionChangedAction.Add: for (var i = 0; i < e.NewItems.Count; i++) { this.groupsInnerContainer.Children.Insert(e.NewStartingIndex + i, (UIElement)e.NewItems[i]); } break; case NotifyCollectionChangedAction.Remove: foreach (var item in e.OldItems.OfType<UIElement>()) { this.groupsInnerContainer.Children.Remove(item); } break; case NotifyCollectionChangedAction.Replace: foreach (var item in e.OldItems.OfType<UIElement>()) { this.groupsInnerContainer.Children.Remove(item); } foreach (var item in e.NewItems.OfType<UIElement>()) { this.groupsInnerContainer.Children.Add(item); } break; case NotifyCollectionChangedAction.Reset: this.groupsInnerContainer.Children.Clear(); foreach (var group in this.groups) { this.groupsInnerContainer.Children.Add(group); } break; } } #region Header Property /// <inheritdoc /> public object Header { get { return this.GetValue(HeaderProperty); } set { this.SetValue(HeaderProperty, value); } } /// <summary>Identifies the <see cref="Header"/> dependency property.</summary> public static readonly DependencyProperty HeaderProperty = RibbonControl.HeaderProperty.AddOwner(typeof(RibbonTabItem), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsMeasure, LogicalChildSupportHelper.OnLogicalChildPropertyChanged)); #endregion #region HeaderTemplate Property /// <summary> /// Gets or sets header template of tab item. /// </summary> public DataTemplate HeaderTemplate { get { return (DataTemplate)this.GetValue(HeaderTemplateProperty); } set { this.SetValue(HeaderTemplateProperty, value); } } /// <summary>Identifies the <see cref="HeaderTemplate"/> dependency property.</summary> public static readonly DependencyProperty HeaderTemplateProperty = DependencyProperty.Register(nameof(HeaderTemplate), typeof(DataTemplate), typeof(RibbonTabItem), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsMeasure)); #endregion #region Focusable /// <summary> /// Handles Focusable changes /// </summary> private static void OnFocusableChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { } /// <summary> /// Coerces Focusable /// </summary> private static object CoerceFocusable(DependencyObject d, object basevalue) { var control = d as RibbonTabItem; var ribbon = control?.FindParentRibbon(); if (ribbon != null) { return (bool)basevalue && ribbon.Focusable; } return basevalue; } // Find parent ribbon private Ribbon FindParentRibbon() { var element = this.Parent; while (element != null) { if (element is Ribbon ribbon) { return ribbon; } element = VisualTreeHelper.GetParent(element); } return null; } #endregion #endregion #region Initialize /// <summary> /// Static constructor /// </summary> static RibbonTabItem() { DefaultStyleKeyProperty.OverrideMetadata(typeof(RibbonTabItem), new FrameworkPropertyMetadata(typeof(RibbonTabItem))); FocusableProperty.AddOwner(typeof(RibbonTabItem), new FrameworkPropertyMetadata(OnFocusableChanged, CoerceFocusable)); VisibilityProperty.AddOwner(typeof(RibbonTabItem), new FrameworkPropertyMetadata(OnVisibilityChanged)); KeyboardNavigation.DirectionalNavigationProperty.OverrideMetadata(typeof(RibbonTabItem), new FrameworkPropertyMetadata(KeyboardNavigationMode.Contained)); KeyboardNavigation.TabNavigationProperty.OverrideMetadata(typeof(RibbonTabItem), new FrameworkPropertyMetadata(KeyboardNavigationMode.Local)); AutomationProperties.IsOffscreenBehaviorProperty.OverrideMetadata(typeof(RibbonTabItem), new FrameworkPropertyMetadata(IsOffscreenBehavior.FromClip)); } // Handles visibility changes private static void OnVisibilityChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var item = d as RibbonTabItem; if (item is null) { return; } item.Group?.UpdateInnerVisiblityAndGroupBorders(); if (item.IsSelected && (Visibility)e.NewValue == Visibility.Collapsed) { if (item.TabControlParent != null) { if (item.TabControlParent.IsMinimized) { item.IsSelected = false; } else { item.TabControlParent.SelectedItem = item.TabControlParent.GetFirstVisibleAndEnabledItem(); } } } } /// <summary> /// Default constructor /// </summary> public RibbonTabItem() { this.AddLogicalChild(this.GroupsContainer); this.GroupsContainer.Content = this.groupsInnerContainer; // Force redirection of DataContext. This is needed, because we detach the container from the visual tree and attach it to a diffrent one (the popup/dropdown) when the ribbon is minimized. this.groupsInnerContainer.SetBinding(DataContextProperty, new Binding(nameof(this.DataContext)) { Source = this }); ContextMenuService.Coerce(this); this.Loaded += this.OnLoaded; this.Unloaded += this.OnUnloaded; } #endregion #region Overrides /// <inheritdoc /> protected override Size MeasureOverride(Size constraint) { if (this.contentContainer is null) { return base.MeasureOverride(constraint); } if (this.IsContextual && this.Group?.Visibility == Visibility.Collapsed) { return Size.Empty; } var baseConstraint = base.MeasureOverride(constraint); var totalWidth = this.contentContainer.DesiredSize.Width - (this.contentContainer.Margin.Left - this.contentContainer.Margin.Right); this.contentContainer.Child.Measure(SizeConstants.Infinite); var headerWidth = this.contentContainer.Child.DesiredSize.Width; if (totalWidth > headerWidth + (this.HeaderPadding.Left + this.HeaderPadding.Right)) { if (DoubleUtil.AreClose(this.desiredWidth, 0) == false) { // If header width is larger then tab increase tab width if (constraint.Width > this.desiredWidth && this.desiredWidth > totalWidth) { baseConstraint.Width = this.desiredWidth; } else { baseConstraint.Width = headerWidth + (this.HeaderPadding.Left + this.HeaderPadding.Right) + (this.contentContainer.Margin.Left + this.contentContainer.Margin.Right); } } } if (DoubleUtil.AreClose(this.cachedWidth, baseConstraint.Width) == false && this.IsContextual && this.Group != null) { this.cachedWidth = baseConstraint.Width; var contextualTabGroupContainer = UIHelper.GetParent<RibbonContextualGroupsContainer>(this.Group); contextualTabGroupContainer?.InvalidateMeasure(); var ribbonTitleBar = UIHelper.GetParent<RibbonTitleBar>(this.Group); ribbonTitleBar?.ForceMeasureAndArrange(); } return baseConstraint; } /// <inheritdoc /> protected override Size ArrangeOverride(Size arrangeBounds) { var result = base.ArrangeOverride(arrangeBounds); var ribbonTitleBar = UIHelper.GetParent<RibbonTitleBar>(this.Group); ribbonTitleBar?.ForceMeasureAndArrange(); return result; } /// <inheritdoc /> public override void OnApplyTemplate() { base.OnApplyTemplate(); this.HeaderContentHost = this.GetTemplateChild("PART_HeaderContentHost") as FrameworkElement; this.contentContainer = this.GetTemplateChild("PART_ContentContainer") as Border; } /// <inheritdoc /> protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) { if (ReferenceEquals(e.Source, this) && e.ClickCount == 2) { e.Handled = true; if (this.TabControlParent != null) { var canMinimize = this.TabControlParent.CanMinimize; if (canMinimize) { this.TabControlParent.IsMinimized = !this.TabControlParent.IsMinimized; } } } else if (ReferenceEquals(e.Source, this) || this.IsSelected == false) { if (this.Visibility == Visibility.Visible) { if (this.TabControlParent != null) { var newItem = this.TabControlParent.ItemContainerGenerator.ItemFromContainerOrContainerContent(this); if (ReferenceEquals(this.TabControlParent.SelectedItem, newItem)) { this.TabControlParent.IsDropDownOpen = !this.TabControlParent.IsDropDownOpen; } else { this.TabControlParent.SelectedItem = newItem; } this.TabControlParent.RaiseRequestBackstageClose(); } else { this.IsSelected = true; } e.Handled = true; } } } /// <inheritdoc /> protected override AutomationPeer OnCreateAutomationPeer() => new Fluent.Automation.Peers.RibbonTabItemAutomationPeer(this); #endregion #region Private methods // Handles IsSelected property changes private static void OnIsSelectedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var container = (RibbonTabItem)d; var newValue = (bool)e.NewValue; if (newValue) { if (container.TabControlParent?.SelectedTabItem != null && ReferenceEquals(container.TabControlParent.SelectedTabItem, container) == false) { container.TabControlParent.SelectedTabItem.IsSelected = false; } container.OnSelected(new RoutedEventArgs(Selector.SelectedEvent, container)); } else { container.OnUnselected(new RoutedEventArgs(Selector.UnselectedEvent, container)); } // Raise UI automation events on this RibbonTabItem if (AutomationPeer.ListenerExists(AutomationEvents.SelectionItemPatternOnElementSelected) || AutomationPeer.ListenerExists(AutomationEvents.SelectionItemPatternOnElementRemovedFromSelection)) { //SelectorHelper.RaiseIsSelectedChangedAutomationEvent(container.TabControlParent, container, newValue); var peer = UIElementAutomationPeer.CreatePeerForElement(container) as RibbonTabItemAutomationPeer; peer?.RaiseTabSelectionEvents(); } } /// <summary> /// Handles selected /// </summary> /// <param name="e">The event data</param> protected virtual void OnSelected(RoutedEventArgs e) { this.HandleIsSelectedChanged(e); } /// <summary> /// handles unselected /// </summary> /// <param name="e">The event data</param> protected virtual void OnUnselected(RoutedEventArgs e) { this.HandleIsSelectedChanged(e); } #endregion #region Event handling // Handles IsSelected property changes private void HandleIsSelectedChanged(RoutedEventArgs e) { this.RaiseEvent(e); } private void OnLoaded(object sender, RoutedEventArgs e) { this.SubscribeEvents(); } private void OnUnloaded(object sender, RoutedEventArgs e) { this.UnSubscribeEvents(); } private void SubscribeEvents() { // Always unsubscribe events to ensure we don't subscribe twice this.UnSubscribeEvents(); if (this.groups != null) { this.groups.CollectionChanged += this.OnGroupsCollectionChanged; } } private void UnSubscribeEvents() { if (this.groups != null) { this.groups.CollectionChanged -= this.OnGroupsCollectionChanged; } } #endregion /// <inheritdoc /> public KeyTipPressedResult OnKeyTipPressed() { if (this.TabControlParent?.SelectedItem is RibbonTabItem currentSelectedItem) { currentSelectedItem.IsSelected = false; } this.IsSelected = true; // This way keytips for delay loaded elements work correctly. Partially fixes #244. this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background, new Action(() => { })); return KeyTipPressedResult.Empty; } /// <inheritdoc /> public void OnKeyTipBack() { if (this.TabControlParent != null && this.TabControlParent.IsMinimized) { this.TabControlParent.IsDropDownOpen = false; } } /// <inheritdoc /> void ILogicalChildSupport.AddLogicalChild(object child) { this.AddLogicalChild(child); } /// <inheritdoc /> void ILogicalChildSupport.RemoveLogicalChild(object child) { this.RemoveLogicalChild(child); } /// <inheritdoc /> protected override IEnumerator LogicalChildren { get { var baseEnumerator = base.LogicalChildren; while (baseEnumerator?.MoveNext() == true) { yield return baseEnumerator.Current; } yield return this.GroupsContainer; if (this.Header != null) { yield return this.Header; } } } } }
// DeflaterOutputStream.cs // // Copyright (C) 2001 Mike Krueger // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 2001 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. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. // HISTORY // 22-12-2009 DavidPierson Added AES support using System; using System.IO; #if !NETCF_1_0 using System.Security.Cryptography; using ICSharpCode.SharpZipLib.Encryption; #endif namespace ICSharpCode.SharpZipLib.Zip.Compression.Streams { /// <summary> /// A special stream deflating or compressing the bytes that are /// written to it. It uses a Deflater to perform actual deflating.<br/> /// Authors of the original java version : Tom Tromey, Jochen Hoenicke /// </summary> public class DeflaterOutputStream : Stream { #region Constructors /// <summary> /// Creates a new DeflaterOutputStream with a default Deflater and default buffer size. /// </summary> /// <param name="baseOutputStream"> /// the output stream where deflated output should be written. /// </param> public DeflaterOutputStream(Stream baseOutputStream) : this(baseOutputStream, new Deflater(), 512) { } /// <summary> /// Creates a new DeflaterOutputStream with the given Deflater and /// default buffer size. /// </summary> /// <param name="baseOutputStream"> /// the output stream where deflated output should be written. /// </param> /// <param name="deflater"> /// the underlying deflater. /// </param> public DeflaterOutputStream(Stream baseOutputStream, Deflater deflater) : this(baseOutputStream, deflater, 512) { } /// <summary> /// Creates a new DeflaterOutputStream with the given Deflater and /// buffer size. /// </summary> /// <param name="baseOutputStream"> /// The output stream where deflated output is written. /// </param> /// <param name="deflater"> /// The underlying deflater to use /// </param> /// <param name="bufferSize"> /// The buffer size in bytes to use when deflating (minimum value 512) /// </param> /// <exception cref="ArgumentOutOfRangeException"> /// bufsize is less than or equal to zero. /// </exception> /// <exception cref="ArgumentException"> /// baseOutputStream does not support writing /// </exception> /// <exception cref="ArgumentNullException"> /// deflater instance is null /// </exception> public DeflaterOutputStream(Stream baseOutputStream, Deflater deflater, int bufferSize) { if ( baseOutputStream == null ) { throw new ArgumentNullException("baseOutputStream"); } if (baseOutputStream.CanWrite == false) { throw new ArgumentException("Must support writing", "baseOutputStream"); } if (deflater == null) { throw new ArgumentNullException("deflater"); } if (bufferSize < 512) { throw new ArgumentOutOfRangeException("bufferSize"); } baseOutputStream_ = baseOutputStream; buffer_ = new byte[bufferSize]; deflater_ = deflater; } #endregion #region Public API /// <summary> /// Finishes the stream by calling finish() on the deflater. /// </summary> /// <exception cref="SharpZipBaseException"> /// Not all input is deflated /// </exception> public virtual void Finish() { deflater_.Finish(); while (!deflater_.IsFinished) { int len = deflater_.Deflate(buffer_, 0, buffer_.Length); if (len <= 0) { break; } #if NETCF_1_0 if ( keys != null ) { #else if (cryptoTransform_ != null) { #endif EncryptBlock(buffer_, 0, len); } baseOutputStream_.Write(buffer_, 0, len); } if (!deflater_.IsFinished) { throw new SharpZipBaseException("Can't deflate all input?"); } baseOutputStream_.Flush(); #if NETCF_1_0 if ( keys != null ) { keys = null; } #else if (cryptoTransform_ != null) { #if !NET_1_1 && !NETCF_2_0 if (cryptoTransform_ is ZipAESTransform) { AESAuthCode = ((ZipAESTransform)cryptoTransform_).GetAuthCode(); } #endif cryptoTransform_.Dispose(); cryptoTransform_ = null; } #endif } /// <summary> /// Get/set flag indicating ownership of the underlying stream. /// When the flag is true <see cref="Close"></see> will close the underlying stream also. /// </summary> public bool IsStreamOwner { get { return isStreamOwner_; } set { isStreamOwner_ = value; } } /// <summary> /// Allows client to determine if an entry can be patched after its added /// </summary> public bool CanPatchEntries { get { return baseOutputStream_.CanSeek; } } #endregion #region Encryption string password; #if NETCF_1_0 uint[] keys; #else ICryptoTransform cryptoTransform_; /// <summary> /// Returns the 10 byte AUTH CODE to be appended immediately following the AES data stream. /// </summary> protected byte[] AESAuthCode; #endif /// <summary> /// Get/set the password used for encryption. /// </summary> /// <remarks>When set to null or if the password is empty no encryption is performed</remarks> public string Password { get { return password; } set { if ( (value != null) && (value.Length == 0) ) { password = null; } else { password = value; } } } /// <summary> /// Encrypt a block of data /// </summary> /// <param name="buffer"> /// Data to encrypt. NOTE the original contents of the buffer are lost /// </param> /// <param name="offset"> /// Offset of first byte in buffer to encrypt /// </param> /// <param name="length"> /// Number of bytes in buffer to encrypt /// </param> protected void EncryptBlock(byte[] buffer, int offset, int length) { #if NETCF_1_0 for (int i = offset; i < offset + length; ++i) { byte oldbyte = buffer[i]; buffer[i] ^= EncryptByte(); UpdateKeys(oldbyte); } #else cryptoTransform_.TransformBlock(buffer, 0, length, buffer, 0); #endif } /// <summary> /// Initializes encryption keys based on given <paramref name="password"/>. /// </summary> /// <param name="password">The password.</param> protected void InitializePassword(string password) { #if NETCF_1_0 keys = new uint[] { 0x12345678, 0x23456789, 0x34567890 }; byte[] rawPassword = ZipConstants.ConvertToArray(password); for (int i = 0; i < rawPassword.Length; ++i) { UpdateKeys((byte)rawPassword[i]); } #else PkzipClassicManaged pkManaged = new PkzipClassicManaged(); byte[] key = PkzipClassic.GenerateKeys(ZipConstants.ConvertToArray(password)); cryptoTransform_ = pkManaged.CreateEncryptor(key, null); #endif } #if !NET_1_1 && !NETCF_2_0 /// <summary> /// Initializes encryption keys based on given password. /// </summary> protected void InitializeAESPassword(ZipEntry entry, string rawPassword, out byte[] salt, out byte[] pwdVerifier) { salt = new byte[entry.AESSaltLen]; // Salt needs to be cryptographically random, and unique per file if (_aesRnd == null) _aesRnd = new RNGCryptoServiceProvider(); _aesRnd.GetBytes(salt); int blockSize = entry.AESKeySize / 8; // bits to bytes cryptoTransform_ = new ZipAESTransform(rawPassword, salt, blockSize, true); pwdVerifier = ((ZipAESTransform)cryptoTransform_).PwdVerifier; } #endif #if NETCF_1_0 /// <summary> /// Encrypt a single byte /// </summary> /// <returns> /// The encrypted value /// </returns> protected byte EncryptByte() { uint temp = ((keys[2] & 0xFFFF) | 2); return (byte)((temp * (temp ^ 1)) >> 8); } /// <summary> /// Update encryption keys /// </summary> protected void UpdateKeys(byte ch) { keys[0] = Crc32.ComputeCrc32(keys[0], ch); keys[1] = keys[1] + (byte)keys[0]; keys[1] = keys[1] * 134775813 + 1; keys[2] = Crc32.ComputeCrc32(keys[2], (byte)(keys[1] >> 24)); } #endif #endregion #region Deflation Support /// <summary> /// Deflates everything in the input buffers. This will call /// <code>def.deflate()</code> until all bytes from the input buffers /// are processed. /// </summary> protected void Deflate() { while (!deflater_.IsNeedingInput) { int deflateCount = deflater_.Deflate(buffer_, 0, buffer_.Length); if (deflateCount <= 0) { break; } #if NETCF_1_0 if (keys != null) #else if (cryptoTransform_ != null) #endif { EncryptBlock(buffer_, 0, deflateCount); } baseOutputStream_.Write(buffer_, 0, deflateCount); } if (!deflater_.IsNeedingInput) { throw new SharpZipBaseException("DeflaterOutputStream can't deflate all input?"); } } #endregion #region Stream Overrides /// <summary> /// Gets value indicating stream can be read from /// </summary> public override bool CanRead { get { return false; } } /// <summary> /// Gets a value indicating if seeking is supported for this stream /// This property always returns false /// </summary> public override bool CanSeek { get { return false; } } /// <summary> /// Get value indicating if this stream supports writing /// </summary> public override bool CanWrite { get { return baseOutputStream_.CanWrite; } } /// <summary> /// Get current length of stream /// </summary> public override long Length { get { return baseOutputStream_.Length; } } /// <summary> /// Gets the current position within the stream. /// </summary> /// <exception cref="NotSupportedException">Any attempt to set position</exception> public override long Position { get { return baseOutputStream_.Position; } set { throw new NotSupportedException("Position property not supported"); } } /// <summary> /// Sets the current position of this stream to the given value. Not supported by this class! /// </summary> /// <param name="offset">The offset relative to the <paramref name="origin"/> to seek.</param> /// <param name="origin">The <see cref="SeekOrigin"/> to seek from.</param> /// <returns>The new position in the stream.</returns> /// <exception cref="NotSupportedException">Any access</exception> public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException("DeflaterOutputStream Seek not supported"); } /// <summary> /// Sets the length of this stream to the given value. Not supported by this class! /// </summary> /// <param name="value">The new stream length.</param> /// <exception cref="NotSupportedException">Any access</exception> public override void SetLength(long value) { throw new NotSupportedException("DeflaterOutputStream SetLength not supported"); } /// <summary> /// Read a byte from stream advancing position by one /// </summary> /// <returns>The byte read cast to an int. THe value is -1 if at the end of the stream.</returns> /// <exception cref="NotSupportedException">Any access</exception> public override int ReadByte() { throw new NotSupportedException("DeflaterOutputStream ReadByte not supported"); } /// <summary> /// Read a block of bytes from stream /// </summary> /// <param name="buffer">The buffer to store read data in.</param> /// <param name="offset">The offset to start storing at.</param> /// <param name="count">The maximum number of bytes to read.</param> /// <returns>The actual number of bytes read. Zero if end of stream is detected.</returns> /// <exception cref="NotSupportedException">Any access</exception> public override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException("DeflaterOutputStream Read not supported"); } /// <summary> /// Asynchronous reads are not supported a NotSupportedException is always thrown /// </summary> /// <param name="buffer">The buffer to read into.</param> /// <param name="offset">The offset to start storing data at.</param> /// <param name="count">The number of bytes to read</param> /// <param name="callback">The async callback to use.</param> /// <param name="state">The state to use.</param> /// <returns>Returns an <see cref="IAsyncResult"/></returns> /// <exception cref="NotSupportedException">Any access</exception> public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { throw new NotSupportedException("DeflaterOutputStream BeginRead not currently supported"); } /// <summary> /// Asynchronous writes arent supported, a NotSupportedException is always thrown /// </summary> /// <param name="buffer">The buffer to write.</param> /// <param name="offset">The offset to begin writing at.</param> /// <param name="count">The number of bytes to write.</param> /// <param name="callback">The <see cref="AsyncCallback"/> to use.</param> /// <param name="state">The state object.</param> /// <returns>Returns an IAsyncResult.</returns> /// <exception cref="NotSupportedException">Any access</exception> public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { throw new NotSupportedException("BeginWrite is not supported"); } /// <summary> /// Flushes the stream by calling <see cref="DeflaterOutputStream.Flush">Flush</see> on the deflater and then /// on the underlying stream. This ensures that all bytes are flushed. /// </summary> public override void Flush() { deflater_.Flush(); Deflate(); baseOutputStream_.Flush(); } /// <summary> /// Calls <see cref="Finish"/> and closes the underlying /// stream when <see cref="IsStreamOwner"></see> is true. /// </summary> public override void Close() { if ( !isClosed_ ) { isClosed_ = true; try { Finish(); #if NETCF_1_0 keys=null; #else if ( cryptoTransform_ != null ) { GetAuthCodeIfAES(); cryptoTransform_.Dispose(); cryptoTransform_ = null; } #endif } finally { if( isStreamOwner_ ) { baseOutputStream_.Close(); } } } } private void GetAuthCodeIfAES() { #if !NET_1_1 && !NETCF_2_0 if (cryptoTransform_ is ZipAESTransform) { AESAuthCode = ((ZipAESTransform)cryptoTransform_).GetAuthCode(); } #endif } /// <summary> /// Writes a single byte to the compressed output stream. /// </summary> /// <param name="value"> /// The byte value. /// </param> public override void WriteByte(byte value) { byte[] b = new byte[1]; b[0] = value; Write(b, 0, 1); } /// <summary> /// Writes bytes from an array to the compressed stream. /// </summary> /// <param name="buffer"> /// The byte array /// </param> /// <param name="offset"> /// The offset into the byte array where to start. /// </param> /// <param name="count"> /// The number of bytes to write. /// </param> public override void Write(byte[] buffer, int offset, int count) { deflater_.SetInput(buffer, offset, count); Deflate(); } #endregion #region Instance Fields /// <summary> /// This buffer is used temporarily to retrieve the bytes from the /// deflater and write them to the underlying output stream. /// </summary> byte[] buffer_; /// <summary> /// The deflater which is used to deflate the stream. /// </summary> protected Deflater deflater_; /// <summary> /// Base stream the deflater depends on. /// </summary> protected Stream baseOutputStream_; bool isClosed_; bool isStreamOwner_ = true; #endregion #region Static Fields #if !NET_1_1 && !NETCF_2_0 // Static to help ensure that multiple files within a zip will get different random salt private static RNGCryptoServiceProvider _aesRnd; #endif #endregion } }
#region Apache License // // 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. // #endregion using System; using log4net.Core; using log4net.Appender; namespace log4net.Util { /// <summary> /// A straightforward implementation of the <see cref="IAppenderAttachable"/> interface. /// </summary> /// <remarks> /// <para> /// This is the default implementation of the <see cref="IAppenderAttachable"/> /// interface. Implementors of the <see cref="IAppenderAttachable"/> interface /// should aggregate an instance of this type. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public class AppenderAttachedImpl : IAppenderAttachable { #region Public Instance Constructors /// <summary> /// Constructor /// </summary> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="AppenderAttachedImpl"/> class. /// </para> /// </remarks> public AppenderAttachedImpl() { } #endregion Public Instance Constructors #region Public Instance Methods /// <summary> /// Append on on all attached appenders. /// </summary> /// <param name="loggingEvent">The event being logged.</param> /// <returns>The number of appenders called.</returns> /// <remarks> /// <para> /// Calls the <see cref="IAppender.DoAppend" /> method on all /// attached appenders. /// </para> /// </remarks> public int AppendLoopOnAppenders(LoggingEvent loggingEvent) { if (loggingEvent == null) { throw new ArgumentNullException("loggingEvent"); } // m_appenderList is null when empty if (m_appenderList == null) { return 0; } if (m_appenderArray == null) { m_appenderArray = m_appenderList.ToArray(); } foreach(IAppender appender in m_appenderArray) { try { if (!string.IsNullOrEmpty(loggingEvent.AppenderName)) { if (appender.Name != loggingEvent.AppenderName) continue; } appender.DoAppend(loggingEvent); } catch(Exception ex) { LogLog.Error(declaringType, "Failed to append to appender [" + appender.Name + "]", ex); } } return m_appenderList.Count; } /// <summary> /// Append on on all attached appenders. /// </summary> /// <param name="loggingEvents">The array of events being logged.</param> /// <returns>The number of appenders called.</returns> /// <remarks> /// <para> /// Calls the <see cref="IAppender.DoAppend" /> method on all /// attached appenders. /// </para> /// </remarks> public int AppendLoopOnAppenders(LoggingEvent[] loggingEvents) { if (loggingEvents == null) { throw new ArgumentNullException("loggingEvents"); } if (loggingEvents.Length == 0) { throw new ArgumentException("loggingEvents array must not be empty", "loggingEvents"); } if (loggingEvents.Length == 1) { // Fall back to single event path return AppendLoopOnAppenders(loggingEvents[0]); } // m_appenderList is null when empty if (m_appenderList == null) { return 0; } if (m_appenderArray == null) { m_appenderArray = m_appenderList.ToArray(); } foreach(IAppender appender in m_appenderArray) { try { CallAppend(appender, loggingEvents); } catch(Exception ex) { LogLog.Error(declaringType, "Failed to append to appender [" + appender.Name + "]", ex); } } return m_appenderList.Count; } #endregion Public Instance Methods #region Private Static Methods /// <summary> /// Calls the DoAppende method on the <see cref="IAppender"/> with /// the <see cref="LoggingEvent"/> objects supplied. /// </summary> /// <param name="appender">The appender</param> /// <param name="loggingEvents">The events</param> /// <remarks> /// <para> /// If the <paramref name="appender" /> supports the <see cref="IBulkAppender"/> /// interface then the <paramref name="loggingEvents" /> will be passed /// through using that interface. Otherwise the <see cref="LoggingEvent"/> /// objects in the array will be passed one at a time. /// </para> /// </remarks> private static void CallAppend(IAppender appender, LoggingEvent[] loggingEvents) { IBulkAppender bulkAppender = appender as IBulkAppender; if (bulkAppender != null) { bulkAppender.DoAppend(loggingEvents); } else { foreach(LoggingEvent loggingEvent in loggingEvents) { appender.DoAppend(loggingEvent); } } } #endregion #region Implementation of IAppenderAttachable /// <summary> /// Attaches an appender. /// </summary> /// <param name="newAppender">The appender to add.</param> /// <remarks> /// <para> /// If the appender is already in the list it won't be added again. /// </para> /// </remarks> public void AddAppender(IAppender newAppender) { // Null values for newAppender parameter are strictly forbidden. if (newAppender == null) { throw new ArgumentNullException("newAppender"); } m_appenderArray = null; if (m_appenderList == null) { m_appenderList = new AppenderCollection(1); } if (!m_appenderList.Contains(newAppender)) { m_appenderList.Add(newAppender); } } /// <summary> /// Gets all attached appenders. /// </summary> /// <returns> /// A collection of attached appenders, or <c>null</c> if there /// are no attached appenders. /// </returns> /// <remarks> /// <para> /// The read only collection of all currently attached appenders. /// </para> /// </remarks> public AppenderCollection Appenders { get { if (m_appenderList == null) { // We must always return a valid collection return AppenderCollection.EmptyCollection; } else { return AppenderCollection.ReadOnly(m_appenderList); } } } /// <summary> /// Gets an attached appender with the specified name. /// </summary> /// <param name="name">The name of the appender to get.</param> /// <returns> /// The appender with the name specified, or <c>null</c> if no appender with the /// specified name is found. /// </returns> /// <remarks> /// <para> /// Lookup an attached appender by name. /// </para> /// </remarks> public IAppender GetAppender(string name) { if (m_appenderList != null && name != null) { foreach(IAppender appender in m_appenderList) { if (name == appender.Name) { return appender; } } } return null; } /// <summary> /// Removes all attached appenders. /// </summary> /// <remarks> /// <para> /// Removes and closes all attached appenders /// </para> /// </remarks> public void RemoveAllAppenders() { if (m_appenderList != null) { foreach(IAppender appender in m_appenderList) { try { appender.Close(); } catch(Exception ex) { LogLog.Error(declaringType, "Failed to Close appender ["+appender.Name+"]", ex); } } m_appenderList = null; m_appenderArray = null; } } /// <summary> /// Removes the specified appender from the list of attached appenders. /// </summary> /// <param name="appender">The appender to remove.</param> /// <returns>The appender removed from the list</returns> /// <remarks> /// <para> /// The appender removed is not closed. /// If you are discarding the appender you must call /// <see cref="IAppender.Close"/> on the appender removed. /// </para> /// </remarks> public IAppender RemoveAppender(IAppender appender) { if (appender != null && m_appenderList != null) { m_appenderList.Remove(appender); if (m_appenderList.Count == 0) { m_appenderList = null; } m_appenderArray = null; } return appender; } /// <summary> /// Removes the appender with the specified name from the list of appenders. /// </summary> /// <param name="name">The name of the appender to remove.</param> /// <returns>The appender removed from the list</returns> /// <remarks> /// <para> /// The appender removed is not closed. /// If you are discarding the appender you must call /// <see cref="IAppender.Close"/> on the appender removed. /// </para> /// </remarks> public IAppender RemoveAppender(string name) { return RemoveAppender(GetAppender(name)); } #endregion #region Private Instance Fields /// <summary> /// List of appenders /// </summary> private AppenderCollection m_appenderList; /// <summary> /// Array of appenders, used to cache the m_appenderList /// </summary> private IAppender[] m_appenderArray; #endregion Private Instance Fields #region Private Static Fields /// <summary> /// The fully qualified type of the AppenderAttachedImpl class. /// </summary> /// <remarks> /// Used by the internal logger to record the Type of the /// log message. /// </remarks> private readonly static Type declaringType = typeof(AppenderAttachedImpl); #endregion Private Static Fields } }
// 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. // //////////////////////////////////////////////////////////////////////////////// #pragma warning disable 0420 // turn off 'a reference to a volatile field will not be treated as volatile' during CAS. using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security.Permissions; using System.Diagnostics.Contracts; using System.Runtime; using System.Runtime.CompilerServices; using System.Security; namespace System.Threading { /// <summary> /// Propagates notification that operations should be canceled. /// </summary> /// <remarks> /// <para> /// A <see cref="CancellationToken"/> may be created directly in an unchangeable canceled or non-canceled state /// using the CancellationToken's constructors. However, to have a CancellationToken that can change /// from a non-canceled to a canceled state, /// <see cref="System.Threading.CancellationTokenSource">CancellationTokenSource</see> must be used. /// CancellationTokenSource exposes the associated CancellationToken that may be canceled by the source through its /// <see cref="System.Threading.CancellationTokenSource.Token">Token</see> property. /// </para> /// <para> /// Once canceled, a token may not transition to a non-canceled state, and a token whose /// <see cref="CanBeCanceled"/> is false will never change to one that can be canceled. /// </para> /// <para> /// All members of this struct are thread-safe and may be used concurrently from multiple threads. /// </para> /// </remarks> [ComVisible(false)] [HostProtection(Synchronization = true, ExternalThreading = true)] [DebuggerDisplay("IsCancellationRequested = {IsCancellationRequested}")] public struct CancellationToken { // The backing TokenSource. // if null, it implicitly represents the same thing as new CancellationToken(false). // When required, it will be instantiated to reflect this. private CancellationTokenSource m_source; //!! warning. If more fields are added, the assumptions in CreateLinkedToken may no longer be valid /* Properties */ /// <summary> /// Returns an empty CancellationToken value. /// </summary> /// <remarks> /// The <see cref="CancellationToken"/> value returned by this property will be non-cancelable by default. /// </remarks> public static CancellationToken None { get { return default(CancellationToken); } } /// <summary> /// Gets whether cancellation has been requested for this token. /// </summary> /// <value>Whether cancellation has been requested for this token.</value> /// <remarks> /// <para> /// This property indicates whether cancellation has been requested for this token, /// either through the token initially being construted in a canceled state, or through /// calling <see cref="System.Threading.CancellationTokenSource.Cancel()">Cancel</see> /// on the token's associated <see cref="CancellationTokenSource"/>. /// </para> /// <para> /// If this property is true, it only guarantees that cancellation has been requested. /// It does not guarantee that every registered handler /// has finished executing, nor that cancellation requests have finished propagating /// to all registered handlers. Additional synchronization may be required, /// particularly in situations where related objects are being canceled concurrently. /// </para> /// </remarks> public bool IsCancellationRequested { get { return m_source != null && m_source.IsCancellationRequested; } } /// <summary> /// Gets whether this token is capable of being in the canceled state. /// </summary> /// <remarks> /// If CanBeCanceled returns false, it is guaranteed that the token will never transition /// into a canceled state, meaning that <see cref="IsCancellationRequested"/> will never /// return true. /// </remarks> public bool CanBeCanceled { get { return m_source != null && m_source.CanBeCanceled; } } /// <summary> /// Gets a <see cref="T:System.Threading.WaitHandle"/> that is signaled when the token is canceled.</summary> /// <remarks> /// Accessing this property causes a <see cref="T:System.Threading.WaitHandle">WaitHandle</see> /// to be instantiated. It is preferable to only use this property when necessary, and to then /// dispose the associated <see cref="CancellationTokenSource"/> instance at the earliest opportunity (disposing /// the source will dispose of this allocated handle). The handle should not be closed or disposed directly. /// </remarks> /// <exception cref="T:System.ObjectDisposedException">The associated <see /// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception> public WaitHandle WaitHandle { get { if (m_source == null) { InitializeDefaultSource(); } return m_source.WaitHandle; } } // public CancellationToken() // this constructor is implicit for structs // -> this should behaves exactly as for new CancellationToken(false) /// <summary> /// Internal constructor only a CancellationTokenSource should create a CancellationToken /// </summary> internal CancellationToken(CancellationTokenSource source) { m_source = source; } /// <summary> /// Initializes the <see cref="T:System.Threading.CancellationToken">CancellationToken</see>. /// </summary> /// <param name="canceled"> /// The canceled state for the token. /// </param> /// <remarks> /// Tokens created with this constructor will remain in the canceled state specified /// by the <paramref name="canceled"/> parameter. If <paramref name="canceled"/> is false, /// both <see cref="CanBeCanceled"/> and <see cref="IsCancellationRequested"/> will be false. /// If <paramref name="canceled"/> is true, /// both <see cref="CanBeCanceled"/> and <see cref="IsCancellationRequested"/> will be true. /// </remarks> public CancellationToken(bool canceled) : this() { if(canceled) m_source = CancellationTokenSource.InternalGetStaticSource(canceled); } /* Methods */ private readonly static Action<Object> s_ActionToActionObjShunt = new Action<Object>(ActionToActionObjShunt); private static void ActionToActionObjShunt(object obj) { Action action = obj as Action; Contract.Assert(action != null, "Expected an Action here"); action(); } /// <summary> /// Registers a delegate that will be called when this <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled. /// </summary> /// <remarks> /// <para> /// If this token is already in the canceled state, the /// delegate will be run immediately and synchronously. Any exception the delegate generates will be /// propagated out of this method call. /// </para> /// <para> /// The current <see cref="System.Threading.ExecutionContext">ExecutionContext</see>, if one exists, will be captured /// along with the delegate and will be used when executing it. /// </para> /// </remarks> /// <param name="callback">The delegate to be executed when the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled.</param> /// <returns>The <see cref="T:System.Threading.CancellationTokenRegistration"/> instance that can /// be used to deregister the callback.</returns> /// <exception cref="T:System.ArgumentNullException"><paramref name="callback"/> is null.</exception> public CancellationTokenRegistration Register(Action callback) { if (callback == null) throw new ArgumentNullException(nameof(callback)); return Register( s_ActionToActionObjShunt, callback, false, // useSync=false true // useExecutionContext=true ); } /// <summary> /// Registers a delegate that will be called when this /// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled. /// </summary> /// <remarks> /// <para> /// If this token is already in the canceled state, the /// delegate will be run immediately and synchronously. Any exception the delegate generates will be /// propagated out of this method call. /// </para> /// <para> /// The current <see cref="System.Threading.ExecutionContext">ExecutionContext</see>, if one exists, will be captured /// along with the delegate and will be used when executing it. /// </para> /// </remarks> /// <param name="callback">The delegate to be executed when the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled.</param> /// <param name="useSynchronizationContext">A Boolean value that indicates whether to capture /// the current <see cref="T:System.Threading.SynchronizationContext">SynchronizationContext</see> and use it /// when invoking the <paramref name="callback"/>.</param> /// <returns>The <see cref="T:System.Threading.CancellationTokenRegistration"/> instance that can /// be used to deregister the callback.</returns> /// <exception cref="T:System.ArgumentNullException"><paramref name="callback"/> is null.</exception> public CancellationTokenRegistration Register(Action callback, bool useSynchronizationContext) { if (callback == null) throw new ArgumentNullException(nameof(callback)); return Register( s_ActionToActionObjShunt, callback, useSynchronizationContext, true // useExecutionContext=true ); } /// <summary> /// Registers a delegate that will be called when this /// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled. /// </summary> /// <remarks> /// <para> /// If this token is already in the canceled state, the /// delegate will be run immediately and synchronously. Any exception the delegate generates will be /// propagated out of this method call. /// </para> /// <para> /// The current <see cref="System.Threading.ExecutionContext">ExecutionContext</see>, if one exists, will be captured /// along with the delegate and will be used when executing it. /// </para> /// </remarks> /// <param name="callback">The delegate to be executed when the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled.</param> /// <param name="state">The state to pass to the <paramref name="callback"/> when the delegate is invoked. This may be null.</param> /// <returns>The <see cref="T:System.Threading.CancellationTokenRegistration"/> instance that can /// be used to deregister the callback.</returns> /// <exception cref="T:System.ArgumentNullException"><paramref name="callback"/> is null.</exception> public CancellationTokenRegistration Register(Action<Object> callback, Object state) { if (callback == null) throw new ArgumentNullException(nameof(callback)); return Register( callback, state, false, // useSync=false true // useExecutionContext=true ); } /// <summary> /// Registers a delegate that will be called when this /// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled. /// </summary> /// <remarks> /// <para> /// If this token is already in the canceled state, the /// delegate will be run immediately and synchronously. Any exception the delegate generates will be /// propagated out of this method call. /// </para> /// <para> /// The current <see cref="System.Threading.ExecutionContext">ExecutionContext</see>, if one exists, /// will be captured along with the delegate and will be used when executing it. /// </para> /// </remarks> /// <param name="callback">The delegate to be executed when the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled.</param> /// <param name="state">The state to pass to the <paramref name="callback"/> when the delegate is invoked. This may be null.</param> /// <param name="useSynchronizationContext">A Boolean value that indicates whether to capture /// the current <see cref="T:System.Threading.SynchronizationContext">SynchronizationContext</see> and use it /// when invoking the <paramref name="callback"/>.</param> /// <returns>The <see cref="T:System.Threading.CancellationTokenRegistration"/> instance that can /// be used to deregister the callback.</returns> /// <exception cref="T:System.ArgumentNullException"><paramref name="callback"/> is null.</exception> /// <exception cref="T:System.ObjectDisposedException">The associated <see /// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception> public CancellationTokenRegistration Register(Action<Object> callback, Object state, bool useSynchronizationContext) { return Register( callback, state, useSynchronizationContext, true // useExecutionContext=true ); } // helper for internal registration needs that don't require an EC capture (e.g. creating linked token sources, or registering unstarted TPL tasks) // has a handy signature, and skips capturing execution context. internal CancellationTokenRegistration InternalRegisterWithoutEC(Action<object> callback, Object state) { return Register( callback, state, false, // useSyncContext=false false // useExecutionContext=false ); } // the real work.. [SecuritySafeCritical] [MethodImpl(MethodImplOptions.NoInlining)] private CancellationTokenRegistration Register(Action<Object> callback, Object state, bool useSynchronizationContext, bool useExecutionContext) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; if (callback == null) throw new ArgumentNullException(nameof(callback)); if (CanBeCanceled == false) { return new CancellationTokenRegistration(); // nothing to do for tokens than can never reach the canceled state. Give them a dummy registration. } // Capture sync/execution contexts if required. // Note: Only capture sync/execution contexts if IsCancellationRequested = false // as we know that if it is true that the callback will just be called synchronously. SynchronizationContext capturedSyncContext = null; ExecutionContext capturedExecutionContext = null; if (!IsCancellationRequested) { if (useSynchronizationContext) capturedSyncContext = SynchronizationContext.Current; if (useExecutionContext) capturedExecutionContext = ExecutionContext.Capture( ref stackMark, ExecutionContext.CaptureOptions.OptimizeDefaultCase); // ideally we'd also use IgnoreSyncCtx, but that could break compat } // Register the callback with the source. return m_source.InternalRegister(callback, state, capturedSyncContext, capturedExecutionContext); } /// <summary> /// Determines whether the current <see cref="T:System.Threading.CancellationToken">CancellationToken</see> instance is equal to the /// specified token. /// </summary> /// <param name="other">The other <see cref="T:System.Threading.CancellationToken">CancellationToken</see> to which to compare this /// instance.</param> /// <returns>True if the instances are equal; otherwise, false. Two tokens are equal if they are associated /// with the same <see cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> or if they were both constructed /// from public CancellationToken constructors and their <see cref="IsCancellationRequested"/> values are equal.</returns> public bool Equals(CancellationToken other) { //if both sources are null, then both tokens represent the Empty token. if (m_source == null && other.m_source == null) { return true; } // one is null but other has inflated the default source // these are only equal if the inflated one is the staticSource(false) if (m_source == null) { return other.m_source == CancellationTokenSource.InternalGetStaticSource(false); } if (other.m_source == null) { return m_source == CancellationTokenSource.InternalGetStaticSource(false); } // general case, we check if the sources are identical return m_source == other.m_source; } /// <summary> /// Determines whether the current <see cref="T:System.Threading.CancellationToken">CancellationToken</see> instance is equal to the /// specified <see cref="T:System.Object"/>. /// </summary> /// <param name="other">The other object to which to compare this instance.</param> /// <returns>True if <paramref name="other"/> is a <see cref="T:System.Threading.CancellationToken">CancellationToken</see> /// and if the two instances are equal; otherwise, false. Two tokens are equal if they are associated /// with the same <see cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> or if they were both constructed /// from public CancellationToken constructors and their <see cref="IsCancellationRequested"/> values are equal.</returns> /// <exception cref="T:System.ObjectDisposedException">An associated <see /// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception> public override bool Equals(Object other) { if (other is CancellationToken) { return Equals((CancellationToken) other); } return false; } /// <summary> /// Serves as a hash function for a <see cref="T:System.Threading.CancellationToken">CancellationToken</see>. /// </summary> /// <returns>A hash code for the current <see cref="T:System.Threading.CancellationToken">CancellationToken</see> instance.</returns> public override Int32 GetHashCode() { if (m_source == null) { // link to the common source so that we have a source to interrogate. return CancellationTokenSource.InternalGetStaticSource(false).GetHashCode(); } return m_source.GetHashCode(); } /// <summary> /// Determines whether two <see cref="T:System.Threading.CancellationToken">CancellationToken</see> instances are equal. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True if the instances are equal; otherwise, false.</returns> /// <exception cref="T:System.ObjectDisposedException">An associated <see /// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception> public static bool operator ==(CancellationToken left, CancellationToken right) { return left.Equals(right); } /// <summary> /// Determines whether two <see cref="T:System.Threading.CancellationToken">CancellationToken</see> instances are not equal. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True if the instances are not equal; otherwise, false.</returns> /// <exception cref="T:System.ObjectDisposedException">An associated <see /// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception> public static bool operator !=(CancellationToken left, CancellationToken right) { return !left.Equals(right); } /// <summary> /// Throws a <see cref="T:System.OperationCanceledException">OperationCanceledException</see> if /// this token has had cancellation requested. /// </summary> /// <remarks> /// This method provides functionality equivalent to: /// <code> /// if (token.IsCancellationRequested) /// throw new OperationCanceledException(token); /// </code> /// </remarks> /// <exception cref="System.OperationCanceledException">The token has had cancellation requested.</exception> /// <exception cref="T:System.ObjectDisposedException">The associated <see /// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception> public void ThrowIfCancellationRequested() { if (IsCancellationRequested) ThrowOperationCanceledException(); } // Throw an ODE if this CancellationToken's source is disposed. internal void ThrowIfSourceDisposed() { if ((m_source != null) && m_source.IsDisposed) ThrowObjectDisposedException(); } // Throws an OCE; separated out to enable better inlining of ThrowIfCancellationRequested private void ThrowOperationCanceledException() { throw new OperationCanceledException(Environment.GetResourceString("OperationCanceled"), this); } private static void ThrowObjectDisposedException() { throw new ObjectDisposedException(null, Environment.GetResourceString("CancellationToken_SourceDisposed")); } // ----------------------------------- // Private helpers private void InitializeDefaultSource() { // Lazy is slower, and although multiple threads may try and set m_source repeatedly, the race condition is benign. // Alternative: LazyInititalizer.EnsureInitialized(ref m_source, ()=>CancellationTokenSource.InternalGetStaticSource(false)); m_source = CancellationTokenSource.InternalGetStaticSource(false); } } }
using System; using Fonet.DataTypes; using Fonet.Fo.Properties; using Fonet.Layout; namespace Fonet.Fo { internal class FOText : FONode { protected char[] ca; protected int start; protected int length; private FontState fs; private float red; private float green; private float blue; private int wrapOption; private int whiteSpaceCollapse; private int verticalAlign; protected bool underlined = false; protected bool overlined = false; protected bool lineThrough = false; private TextState ts; public FOText(char[] chars, int s, int e, FObj parent) : base(parent) { this.start = 0; this.ca = new char[e - s]; for (int i = s; i < e; i++) { ca[i - s] = chars[i]; } this.length = e - s; } public void setUnderlined(bool ul) { this.underlined = ul; } public void setOverlined(bool ol) { this.overlined = ol; } public void setLineThrough(bool lt) { this.lineThrough = lt; } public bool willCreateArea() { this.whiteSpaceCollapse = this.parent.properties.GetProperty("white-space-collapse").GetEnum(); if (this.whiteSpaceCollapse == WhiteSpaceCollapse.FALSE && length > 0) { return true; } for (int i = start; i < start + length; i++) { char ch = ca[i]; if (!((ch == ' ') || (ch == '\n') || (ch == '\r') || (ch == '\t'))) { return true; } } return false; } public override bool MayPrecedeMarker() { for (int i = 0; i < ca.Length; i++) { char ch = ca[i]; if ((ch != ' ') || (ch != '\n') || (ch != '\r') || (ch != '\t')) { return true; } } return false; } public override Status Layout(Area area) { if (!(area is BlockArea)) { FonetDriver.ActiveDriver.FireFonetError( "Text outside block area" + new String(ca, start, length)); return new Status(Status.OK); } if (this.marker == MarkerStart) { string fontFamily = this.parent.properties.GetProperty("font-family").GetString(); string fontStyle = this.parent.properties.GetProperty("font-style").GetString(); string fontWeight = this.parent.properties.GetProperty("font-weight").GetString(); int fontSize = this.parent.properties.GetProperty("font-size").GetLength().MValue(); int fontVariant = this.parent.properties.GetProperty("font-variant").GetEnum(); int letterSpacing = this.parent.properties.GetProperty("letter-spacing").GetLength().MValue(); this.fs = new FontState(area.getFontInfo(), fontFamily, fontStyle, fontWeight, fontSize, fontVariant, letterSpacing); ColorType c = this.parent.properties.GetProperty("color").GetColorType(); this.red = c.Red; this.green = c.Green; this.blue = c.Blue; this.verticalAlign = this.parent.properties.GetProperty("vertical-align").GetEnum(); this.wrapOption = this.parent.properties.GetProperty("wrap-option").GetEnum(); this.whiteSpaceCollapse = this.parent.properties.GetProperty("white-space-collapse").GetEnum(); this.ts = new TextState(); ts.setUnderlined(underlined); ts.setOverlined(overlined); ts.setLineThrough(lineThrough); this.marker = this.start; } int orig_start = this.marker; this.marker = addText((BlockArea)area, fs, red, green, blue, wrapOption, this.GetLinkSet(), whiteSpaceCollapse, ca, this.marker, length, ts, verticalAlign); if (this.marker == -1) { return new Status(Status.OK); } else if (this.marker != orig_start) { return new Status(Status.AREA_FULL_SOME); } else { return new Status(Status.AREA_FULL_NONE); } } public static int addText(BlockArea ba, FontState fontState, float red, float green, float blue, int wrapOption, LinkSet ls, int whiteSpaceCollapse, char[] data, int start, int end, TextState textState, int vAlign) { if (fontState.FontVariant == FontVariant.SMALL_CAPS) { FontState smallCapsFontState; try { int smallCapsFontHeight = (int)(((double)fontState.FontSize) * 0.8d); smallCapsFontState = new FontState(fontState.FontInfo, fontState.FontFamily, fontState.FontStyle, fontState.FontWeight, smallCapsFontHeight, FontVariant.NORMAL); } catch (FonetException ex) { smallCapsFontState = fontState; FonetDriver.ActiveDriver.FireFonetError( "Error creating small-caps FontState: " + ex.Message); } char c; bool isLowerCase; int caseStart; FontState fontStateToUse; for (int i = start; i < end; ) { caseStart = i; c = data[i]; isLowerCase = (Char.IsLetter(c) && Char.IsLower(c)); while (isLowerCase == (Char.IsLetter(c) && Char.IsLower(c))) { if (isLowerCase) { data[i] = Char.ToUpper(c); } i++; if (i == end) { break; } c = data[i]; } if (isLowerCase) { fontStateToUse = smallCapsFontState; } else { fontStateToUse = fontState; } int index = addRealText(ba, fontStateToUse, red, green, blue, wrapOption, ls, whiteSpaceCollapse, data, caseStart, i, textState, vAlign); if (index != -1) { return index; } } return -1; } return addRealText(ba, fontState, red, green, blue, wrapOption, ls, whiteSpaceCollapse, data, start, end, textState, vAlign); } protected static int addRealText(BlockArea ba, FontState fontState, float red, float green, float blue, int wrapOption, LinkSet ls, int whiteSpaceCollapse, char[] data, int start, int end, TextState textState, int vAlign) { int ts, te; char[] ca; ts = start; te = end; ca = data; LineArea la = ba.getCurrentLineArea(); if (la == null) { return start; } la.changeFont(fontState); la.changeColor(red, green, blue); la.changeWrapOption(wrapOption); la.changeWhiteSpaceCollapse(whiteSpaceCollapse); la.changeVerticalAlign(vAlign); ba.setupLinkSet(ls); ts = la.addText(ca, ts, te, ls, textState); while (ts != -1) { la = ba.createNextLineArea(); if (la == null) { return ts; } la.changeFont(fontState); la.changeColor(red, green, blue); la.changeWrapOption(wrapOption); la.changeWhiteSpaceCollapse(whiteSpaceCollapse); ba.setupLinkSet(ls); ts = la.addText(ca, ts, te, ls, textState); } return -1; } } }
using System.Collections.Generic; using System.Linq; using Content.Server.Coordinates.Helpers; using Content.Server.Power.Components; using Content.Server.UserInterface; using Content.Shared.Cargo; using Content.Shared.Cargo.Components; using Content.Shared.Sound; using Robust.Server.GameObjects; using Robust.Shared.Audio; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Maths; using Robust.Shared.Player; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; namespace Content.Server.Cargo.Components { [RegisterComponent] public sealed class CargoConsoleComponent : SharedCargoConsoleComponent { [Dependency] private readonly IMapManager _mapManager = default!; [Dependency] private readonly IEntityManager _entMan = default!; private CargoBankAccount? _bankAccount; [ViewVariables] public CargoBankAccount? BankAccount { get => _bankAccount; private set { if (_bankAccount == value) { return; } if (_bankAccount != null) { _bankAccount.OnBalanceChange -= UpdateUIState; } _bankAccount = value; if (value != null) { value.OnBalanceChange += UpdateUIState; } UpdateUIState(); } } [DataField("requestOnly")] private bool _requestOnly = false; [DataField("errorSound")] private SoundSpecifier _errorSound = new SoundPathSpecifier("/Audio/Effects/error.ogg"); private bool Powered => !_entMan.TryGetComponent(Owner, out ApcPowerReceiverComponent? receiver) || receiver.Powered; private CargoSystem _cargoConsoleSystem = default!; [ViewVariables] private BoundUserInterface? UserInterface => Owner.GetUIOrNull(CargoConsoleUiKey.Key); protected override void Initialize() { base.Initialize(); Owner.EnsureComponentWarn(out GalacticMarketComponent _); Owner.EnsureComponentWarn(out CargoOrderDatabaseComponent _); if (UserInterface != null) { UserInterface.OnReceiveMessage += UserInterfaceOnOnReceiveMessage; } _cargoConsoleSystem = EntitySystem.Get<CargoSystem>(); BankAccount = _cargoConsoleSystem.StationAccount; } protected override void OnRemove() { if (UserInterface != null) { UserInterface.OnReceiveMessage -= UserInterfaceOnOnReceiveMessage; } base.OnRemove(); } private void UserInterfaceOnOnReceiveMessage(ServerBoundUserInterfaceMessage serverMsg) { if (!_entMan.TryGetComponent(Owner, out CargoOrderDatabaseComponent? orders)) { return; } var message = serverMsg.Message; if (orders.Database == null) return; if (!Powered) return; switch (message) { case CargoConsoleAddOrderMessage msg: { if (msg.Amount <= 0 || _bankAccount == null) { break; } if (!_cargoConsoleSystem.AddOrder(orders.Database.Id, msg.Requester, msg.Reason, msg.ProductId, msg.Amount, _bankAccount.Id)) { SoundSystem.Play(Filter.Pvs(Owner), _errorSound.GetSound(), Owner, AudioParams.Default); } break; } case CargoConsoleRemoveOrderMessage msg: { _cargoConsoleSystem.RemoveOrder(orders.Database.Id, msg.OrderNumber); break; } case CargoConsoleApproveOrderMessage msg: { if (_requestOnly || !orders.Database.TryGetOrder(msg.OrderNumber, out var order) || _bankAccount == null) { break; } if (msg.Session.AttachedEntity is not {Valid: true} player) break; PrototypeManager.TryIndex(order.ProductId, out CargoProductPrototype? product); if (product == null!) break; var capacity = _cargoConsoleSystem.GetCapacity(orders.Database.Id); if ( (capacity.CurrentCapacity == capacity.MaxCapacity || capacity.CurrentCapacity + order.Amount > capacity.MaxCapacity || !_cargoConsoleSystem.CheckBalance(_bankAccount.Id, (-product.PointCost) * order.Amount) || !_cargoConsoleSystem.ApproveOrder(Owner, player, orders.Database.Id, msg.OrderNumber) || !_cargoConsoleSystem.ChangeBalance(_bankAccount.Id, (-product.PointCost) * order.Amount)) ) { SoundSystem.Play(Filter.Pvs(Owner), _errorSound.GetSound(), Owner, AudioParams.Default); break; } UpdateUIState(); break; } case CargoConsoleShuttleMessage _: { // Jesus fucking christ Glass //var approvedOrders = _cargoOrderDataManager.RemoveAndGetApprovedFrom(orders.Database); //orders.Database.ClearOrderCapacity(); // TODO replace with shuttle code // TEMPORARY loop for spawning stuff on telepad (looks for a telepad adjacent to the console) EntityUid? cargoTelepad = null; var indices = _entMan.GetComponent<TransformComponent>(Owner).Coordinates.ToVector2i(_entMan, _mapManager); var offsets = new Vector2i[] { new Vector2i(0, 1), new Vector2i(1, 1), new Vector2i(1, 0), new Vector2i(1, -1), new Vector2i(0, -1), new Vector2i(-1, -1), new Vector2i(-1, 0), new Vector2i(-1, 1), }; var lookup = EntitySystem.Get<EntityLookupSystem>(); var gridId = _entMan.GetComponent<TransformComponent>(Owner).GridID; // TODO: Should use anchoring. foreach (var entity in lookup.GetEntitiesIntersecting(gridId, offsets.Select(o => o + indices))) { if (_entMan.HasComponent<CargoTelepadComponent>(entity) && _entMan.TryGetComponent<ApcPowerReceiverComponent?>(entity, out var powerReceiver) && powerReceiver.Powered) { cargoTelepad = entity; break; } } if (cargoTelepad != null) { if (_entMan.TryGetComponent<CargoTelepadComponent?>(cargoTelepad.Value, out var telepadComponent)) { var approvedOrders = _cargoConsoleSystem.RemoveAndGetApprovedOrders(orders.Database.Id); orders.Database.ClearOrderCapacity(); foreach (var order in approvedOrders) { _cargoConsoleSystem.QueueTeleport(telepadComponent, order); } } } break; } } } private void UpdateUIState() { if (_bankAccount == null || !_entMan.EntityExists(Owner)) { return; } var id = _bankAccount.Id; var name = _bankAccount.Name; var balance = _bankAccount.Balance; var capacity = _cargoConsoleSystem.GetCapacity(id); UserInterface?.SetState(new CargoConsoleInterfaceState(_requestOnly, id, name, balance, capacity)); } } }
namespace Factotum { partial class SpecialCalParamView { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (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() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SpecialCalParamView)); this.btnEdit = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.btnAdd = new System.Windows.Forms.Button(); this.btnDelete = new System.Windows.Forms.Button(); this.cboStatusFilter = new System.Windows.Forms.ComboBox(); this.label2 = new System.Windows.Forms.Label(); this.panel1 = new System.Windows.Forms.Panel(); this.label5 = new System.Windows.Forms.Label(); this.dgvSpecialCalParamsList = new Factotum.DataGridViewStd(); this.btnMoveDown = new System.Windows.Forms.Button(); this.btnMoveUp = new System.Windows.Forms.Button(); this.panel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dgvSpecialCalParamsList)).BeginInit(); this.SuspendLayout(); // // btnEdit // this.btnEdit.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.btnEdit.Location = new System.Drawing.Point(11, 226); this.btnEdit.Name = "btnEdit"; this.btnEdit.Size = new System.Drawing.Size(64, 22); this.btnEdit.TabIndex = 2; this.btnEdit.Text = "Edit"; this.btnEdit.UseVisualStyleBackColor = true; this.btnEdit.Click += new System.EventHandler(this.btnEdit_Click); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(15, 71); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(169, 13); this.label1.TabIndex = 5; this.label1.Text = "Special Calibration Parameters List"; // // btnAdd // this.btnAdd.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.btnAdd.Location = new System.Drawing.Point(81, 226); this.btnAdd.Name = "btnAdd"; this.btnAdd.Size = new System.Drawing.Size(64, 22); this.btnAdd.TabIndex = 3; this.btnAdd.Text = "Add"; this.btnAdd.UseVisualStyleBackColor = true; this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click); // // btnDelete // this.btnDelete.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.btnDelete.Location = new System.Drawing.Point(151, 226); this.btnDelete.Name = "btnDelete"; this.btnDelete.Size = new System.Drawing.Size(64, 22); this.btnDelete.TabIndex = 4; this.btnDelete.Text = "Delete"; this.btnDelete.UseVisualStyleBackColor = true; this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click); // // cboStatusFilter // this.cboStatusFilter.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.cboStatusFilter.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboStatusFilter.FormattingEnabled = true; this.cboStatusFilter.Items.AddRange(new object[] { "Active", "Inactive"}); this.cboStatusFilter.Location = new System.Drawing.Point(296, 5); this.cboStatusFilter.Name = "cboStatusFilter"; this.cboStatusFilter.Size = new System.Drawing.Size(85, 21); this.cboStatusFilter.TabIndex = 3; this.cboStatusFilter.SelectedIndexChanged += new System.EventHandler(this.cboStatus_SelectedIndexChanged); // // label2 // this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(253, 8); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(37, 13); this.label2.TabIndex = 2; this.label2.Text = "Status"; // // panel1 // this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.panel1.Controls.Add(this.cboStatusFilter); this.panel1.Controls.Add(this.label2); this.panel1.ForeColor = System.Drawing.SystemColors.ControlText; this.panel1.Location = new System.Drawing.Point(15, 18); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(388, 34); this.panel1.TabIndex = 1; // // label5 // this.label5.AutoSize = true; this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label5.ForeColor = System.Drawing.SystemColors.ControlText; this.label5.Location = new System.Drawing.Point(22, 9); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(53, 13); this.label5.TabIndex = 0; this.label5.Text = "List Filters"; // // dgvSpecialCalParamsList // this.dgvSpecialCalParamsList.AllowUserToAddRows = false; this.dgvSpecialCalParamsList.AllowUserToDeleteRows = false; this.dgvSpecialCalParamsList.AllowUserToOrderColumns = true; this.dgvSpecialCalParamsList.AllowUserToResizeRows = false; this.dgvSpecialCalParamsList.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dgvSpecialCalParamsList.Location = new System.Drawing.Point(15, 86); this.dgvSpecialCalParamsList.MultiSelect = false; this.dgvSpecialCalParamsList.Name = "dgvSpecialCalParamsList"; this.dgvSpecialCalParamsList.ReadOnly = true; this.dgvSpecialCalParamsList.RowHeadersVisible = false; this.dgvSpecialCalParamsList.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.dgvSpecialCalParamsList.Size = new System.Drawing.Size(389, 120); this.dgvSpecialCalParamsList.StandardTab = true; this.dgvSpecialCalParamsList.TabIndex = 6; this.dgvSpecialCalParamsList.DoubleClick += new System.EventHandler(this.btnEdit_Click); this.dgvSpecialCalParamsList.KeyDown += new System.Windows.Forms.KeyEventHandler(this.dgvSpecialCalParamsList_KeyDown); this.dgvSpecialCalParamsList.ColumnAdded += new System.Windows.Forms.DataGridViewColumnEventHandler(this.dgvSpecialCalParamsList_ColumnAdded); // // btnMoveDown // this.btnMoveDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnMoveDown.Location = new System.Drawing.Point(330, 226); this.btnMoveDown.Name = "btnMoveDown"; this.btnMoveDown.Size = new System.Drawing.Size(75, 22); this.btnMoveDown.TabIndex = 23; this.btnMoveDown.Text = "Move Down"; this.btnMoveDown.UseVisualStyleBackColor = true; this.btnMoveDown.Click += new System.EventHandler(this.btnMoveDown_Click); // // btnMoveUp // this.btnMoveUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnMoveUp.Location = new System.Drawing.Point(249, 226); this.btnMoveUp.Name = "btnMoveUp"; this.btnMoveUp.Size = new System.Drawing.Size(75, 22); this.btnMoveUp.TabIndex = 22; this.btnMoveUp.Text = "Move Up"; this.btnMoveUp.UseVisualStyleBackColor = true; this.btnMoveUp.Click += new System.EventHandler(this.btnMoveUp_Click); // // SpecialCalParamView // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(416, 260); this.Controls.Add(this.btnMoveDown); this.Controls.Add(this.btnMoveUp); this.Controls.Add(this.label5); this.Controls.Add(this.panel1); this.Controls.Add(this.dgvSpecialCalParamsList); this.Controls.Add(this.btnDelete); this.Controls.Add(this.btnAdd); this.Controls.Add(this.label1); this.Controls.Add(this.btnEdit); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MinimumSize = new System.Drawing.Size(404, 222); this.Name = "SpecialCalParamView"; this.Text = " View Special Calibration Parameters"; this.Load += new System.EventHandler(this.SpecialCalParamView_Load); this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.SpecialCalParamView_FormClosed); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.dgvSpecialCalParamsList)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button btnEdit; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button btnAdd; private System.Windows.Forms.Button btnDelete; private System.Windows.Forms.ComboBox cboStatusFilter; private System.Windows.Forms.Label label2; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Label label5; private DataGridViewStd dgvSpecialCalParamsList; private System.Windows.Forms.Button btnMoveDown; private System.Windows.Forms.Button btnMoveUp; } }