context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsPaging
{
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// PagingOperations operations.
/// </summary>
public partial interface IPagingOperations
{
/// <summary>
/// A paging operation that finishes on the first call without a
/// nextlink
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetSinglePagesWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesWithHttpMessagesAsync(string clientRequestId = default(string), PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = default(PagingGetMultiplePagesOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A paging operation that includes a nextLink in odata format that
/// has 10 pages
/// </summary>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetOdataMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetOdataMultiplePagesWithHttpMessagesAsync(string clientRequestId = default(string), PagingGetOdataMultiplePagesOptions pagingGetOdataMultiplePagesOptions = default(PagingGetOdataMultiplePagesOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='pagingGetMultiplePagesWithOffsetOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesWithOffsetWithHttpMessagesAsync(PagingGetMultiplePagesWithOffsetOptions pagingGetMultiplePagesWithOffsetOptions, string clientRequestId = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A paging operation that fails on the first call with 500 and then
/// retries and then get a response including a nextLink that has 10
/// pages
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesRetryFirstWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages, of
/// which the 2nd call fails first with 500. The client should retry
/// and finish all 10 pages eventually.
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesRetrySecondWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A paging operation that receives a 400 on the first call
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetSinglePagesFailureWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A paging operation that receives a 400 on the second call
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesFailureWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A paging operation that receives an invalid nextLink
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesFailureUriWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A paging operation that doesn't return a full URL, just a fragment
/// </summary>
/// <param name='apiVersion'>
/// Sets the api version to use.
/// </param>
/// <param name='tenant'>
/// Sets the tenant to use.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesFragmentNextLinkWithHttpMessagesAsync(string apiVersion, string tenant, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A paging operation that doesn't return a full URL, just a fragment
/// with parameters grouped
/// </summary>
/// <param name='customParameterGroup'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesFragmentWithGroupingNextLinkWithHttpMessagesAsync(CustomParameterGroup customParameterGroup, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A paging operation that doesn't return a full URL, just a fragment
/// </summary>
/// <param name='apiVersion'>
/// Sets the api version to use.
/// </param>
/// <param name='tenant'>
/// Sets the tenant to use.
/// </param>
/// <param name='nextLink'>
/// Next link for list operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> NextFragmentWithHttpMessagesAsync(string apiVersion, string tenant, string nextLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A paging operation that doesn't return a full URL, just a fragment
/// </summary>
/// <param name='nextLink'>
/// Next link for list operation.
/// </param>
/// <param name='customParameterGroup'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> NextFragmentWithGroupingWithHttpMessagesAsync(string nextLink, CustomParameterGroup customParameterGroup, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A paging operation that finishes on the first call without a
/// nextlink
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetSinglePagesNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesNextWithHttpMessagesAsync(string nextPageLink, string clientRequestId = default(string), PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = default(PagingGetMultiplePagesOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A paging operation that includes a nextLink in odata format that
/// has 10 pages
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetOdataMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetOdataMultiplePagesNextWithHttpMessagesAsync(string nextPageLink, string clientRequestId = default(string), PagingGetOdataMultiplePagesOptions pagingGetOdataMultiplePagesOptions = default(PagingGetOdataMultiplePagesOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetMultiplePagesWithOffsetNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesWithOffsetNextWithHttpMessagesAsync(string nextPageLink, string clientRequestId = default(string), PagingGetMultiplePagesWithOffsetNextOptions pagingGetMultiplePagesWithOffsetNextOptions = default(PagingGetMultiplePagesWithOffsetNextOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A paging operation that fails on the first call with 500 and then
/// retries and then get a response including a nextLink that has 10
/// pages
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesRetryFirstNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages, of
/// which the 2nd call fails first with 500. The client should retry
/// and finish all 10 pages eventually.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesRetrySecondNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A paging operation that receives a 400 on the first call
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetSinglePagesFailureNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A paging operation that receives a 400 on the second call
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesFailureNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A paging operation that receives an invalid nextLink
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesFailureUriNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Javax.Crypto.Interfaces.cs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma warning disable 1717
namespace Javax.Crypto.Interfaces
{
/// <summary>
/// <para>The interface to a <b>password-based-encryption</b> key. </para>
/// </summary>
/// <java-name>
/// javax/crypto/interfaces/PBEKey
/// </java-name>
[Dot42.DexImport("javax/crypto/interfaces/PBEKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class IPBEKeyConstants
/* scope: __dot42__ */
{
/// <summary>
/// <para>The serial version identifier. </para>
/// </summary>
/// <java-name>
/// serialVersionUID
/// </java-name>
[Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)]
public const long SerialVersionUID = -1430015993304333921;
}
/// <summary>
/// <para>The interface to a <b>password-based-encryption</b> key. </para>
/// </summary>
/// <java-name>
/// javax/crypto/interfaces/PBEKey
/// </java-name>
[Dot42.DexImport("javax/crypto/interfaces/PBEKey", AccessFlags = 1537)]
public partial interface IPBEKey : global::Javax.Crypto.ISecretKey
/* scope: __dot42__ */
{
/// <summary>
/// <para>Returns the iteration count, 0 if not specified.</para><para></para>
/// </summary>
/// <returns>
/// <para>the iteration count, 0 if not specified. </para>
/// </returns>
/// <java-name>
/// getIterationCount
/// </java-name>
[Dot42.DexImport("getIterationCount", "()I", AccessFlags = 1025)]
int GetIterationCount() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns a copy of the salt data or null if not specified.</para><para></para>
/// </summary>
/// <returns>
/// <para>a copy of the salt data or null if not specified. </para>
/// </returns>
/// <java-name>
/// getSalt
/// </java-name>
[Dot42.DexImport("getSalt", "()[B", AccessFlags = 1025, IgnoreFromJava = true)]
byte[] GetSalt() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns a copy to the password.</para><para></para>
/// </summary>
/// <returns>
/// <para>a copy to the password. </para>
/// </returns>
/// <java-name>
/// getPassword
/// </java-name>
[Dot42.DexImport("getPassword", "()[C", AccessFlags = 1025)]
char[] GetPassword() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>The interface for a Diffie-Hellman key. </para>
/// </summary>
/// <java-name>
/// javax/crypto/interfaces/DHKey
/// </java-name>
[Dot42.DexImport("javax/crypto/interfaces/DHKey", AccessFlags = 1537)]
public partial interface IDHKey
/* scope: __dot42__ */
{
/// <summary>
/// <para>Returns the parameters for this key.</para><para></para>
/// </summary>
/// <returns>
/// <para>the parameters for this key. </para>
/// </returns>
/// <java-name>
/// getParams
/// </java-name>
[Dot42.DexImport("getParams", "()Ljavax/crypto/spec/DHParameterSpec;", AccessFlags = 1025)]
global::Javax.Crypto.Spec.DHParameterSpec GetParams() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>The interface for a public key in the Diffie-Hellman key exchange protocol. </para>
/// </summary>
/// <java-name>
/// javax/crypto/interfaces/DHPublicKey
/// </java-name>
[Dot42.DexImport("javax/crypto/interfaces/DHPublicKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class IDHPublicKeyConstants
/* scope: __dot42__ */
{
/// <summary>
/// <para>The serial version identifier. </para>
/// </summary>
/// <java-name>
/// serialVersionUID
/// </java-name>
[Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)]
public const long SerialVersionUID = -6628103563352519193;
}
/// <summary>
/// <para>The interface for a public key in the Diffie-Hellman key exchange protocol. </para>
/// </summary>
/// <java-name>
/// javax/crypto/interfaces/DHPublicKey
/// </java-name>
[Dot42.DexImport("javax/crypto/interfaces/DHPublicKey", AccessFlags = 1537)]
public partial interface IDHPublicKey : global::Javax.Crypto.Interfaces.IDHKey, global::Java.Security.IPublicKey
/* scope: __dot42__ */
{
/// <summary>
/// <para>Returns this key's public value Y. </para>
/// </summary>
/// <returns>
/// <para>this key's public value Y. </para>
/// </returns>
/// <java-name>
/// getY
/// </java-name>
[Dot42.DexImport("getY", "()Ljava/math/BigInteger;", AccessFlags = 1025)]
global::Java.Math.BigInteger GetY() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>The interface for a private key in the Diffie-Hellman key exchange protocol. </para>
/// </summary>
/// <java-name>
/// javax/crypto/interfaces/DHPrivateKey
/// </java-name>
[Dot42.DexImport("javax/crypto/interfaces/DHPrivateKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class IDHPrivateKeyConstants
/* scope: __dot42__ */
{
/// <summary>
/// <para>The serialization version identifier. </para>
/// </summary>
/// <java-name>
/// serialVersionUID
/// </java-name>
[Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)]
public const long SerialVersionUID = 2211791113380396553;
}
/// <summary>
/// <para>The interface for a private key in the Diffie-Hellman key exchange protocol. </para>
/// </summary>
/// <java-name>
/// javax/crypto/interfaces/DHPrivateKey
/// </java-name>
[Dot42.DexImport("javax/crypto/interfaces/DHPrivateKey", AccessFlags = 1537)]
public partial interface IDHPrivateKey : global::Javax.Crypto.Interfaces.IDHKey, global::Java.Security.IPrivateKey
/* scope: __dot42__ */
{
/// <summary>
/// <para>Returns this key's private value x. </para>
/// </summary>
/// <returns>
/// <para>this key's private value x. </para>
/// </returns>
/// <java-name>
/// getX
/// </java-name>
[Dot42.DexImport("getX", "()Ljava/math/BigInteger;", AccessFlags = 1025)]
global::Java.Math.BigInteger GetX() /* MethodBuilder.Create */ ;
}
}
| |
// <copyright file="Complex32Test.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2016 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using System;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.ComplexTests
{
#if NOSYSNUMERICS
using Complex = Numerics.Complex;
#else
using Complex = System.Numerics.Complex;
#endif
/// <summary>
/// Complex32 tests.
/// </summary>
[TestFixture]
public class Complex32Test
{
/// <summary>
/// Can add a complex number and a double using operator.
/// </summary>
[Test]
public void CanAddComplexNumberAndDoubleUsingOperator()
{
Assert.That((Complex32.NaN + float.NaN).IsNaN());
Assert.That((float.NaN + Complex32.NaN).IsNaN());
Assert.That((float.PositiveInfinity + Complex32.One).IsInfinity());
Assert.That((Complex32.PositiveInfinity + 1.0f).IsInfinity());
Assert.That((Complex32.One + 0.0f) == Complex32.One);
Assert.That((0.0f + Complex32.One) == Complex32.One);
Assert.That(new Complex32(1.1f, -2.2f) + 1.1f == new Complex32(2.2f, -2.2f));
Assert.That(-2.2f + new Complex32(-1.1f, 2.2f) == new Complex32(-3.3f, 2.2f));
}
/// <summary>
/// Can add/subtract complex numbers using operator.
/// </summary>
[Test]
public void CanAddSubtractComplexNumbersUsingOperator()
{
Assert.That((Complex32.NaN - Complex32.NaN).IsNaN());
Assert.That((Complex32.PositiveInfinity - Complex32.One).IsInfinity());
Assert.That((Complex32.One - Complex32.Zero) == Complex32.One);
Assert.That((new Complex32(1.1f, -2.2f) - new Complex32(1.1f, -2.2f)) == Complex32.Zero);
}
/// <summary>
/// Can add two complex numbers.
/// </summary>
[Test]
public void CanAddTwoComplexNumbers()
{
Assert.That(Complex32.Add(Complex32.NaN, (Complex32.NaN)).IsNaN());
Assert.That(Complex32.Add(Complex32.PositiveInfinity, Complex32.One).IsInfinity());
Assert.That(Complex32.Add(Complex32.One, Complex32.Zero) == Complex32.One);
Assert.That(Complex32.Add(new Complex32(1.1f, -2.2f), new Complex32(-1.1f, 2.2f)) == Complex32.Zero);
}
/// <summary>
/// Can add two complex numbers using operator.
/// </summary>
[Test]
public void CanAddTwoComplexNumbersUsingOperator()
{
Assert.That((Complex32.NaN + Complex32.NaN).IsNaN());
Assert.That((Complex32.PositiveInfinity + Complex32.One).IsInfinity());
Assert.That((Complex32.One + Complex32.Zero) == Complex32.One);
Assert.That((new Complex32(1.1f, -2.2f) + new Complex32(-1.1f, 2.2f)) == Complex32.Zero);
}
/// <summary>
/// Can get hash code.
/// </summary>
[Test]
public void CanCalculateHashCode()
{
Assert.AreEqual(new Complex32(1, 2).GetHashCode(), new Complex32(1, 2).GetHashCode());
Assert.AreNotEqual(new Complex32(1, 0).GetHashCode(), new Complex32(0, 1).GetHashCode());
Assert.AreNotEqual(new Complex32(1, 1).GetHashCode(), new Complex32(2, 2).GetHashCode());
Assert.AreNotEqual(new Complex32(1, 0).GetHashCode(), new Complex32(-1, 0).GetHashCode());
Assert.AreNotEqual(new Complex32(0, 1).GetHashCode(), new Complex32(0, -1).GetHashCode());
}
/// <summary>
/// Can compute exponential.
/// </summary>
/// <param name="real">Real part.</param>
/// <param name="imag">Imaginary part.</param>
/// <param name="expectedReal">Expected real part.</param>
/// <param name="expectedImag">Expected imaginary part.</param>
[TestCase(0.0f, 0.0f, 1.0f, 0.0f)]
[TestCase(0.0f, 1.0f, 0.54030230586813977f, 0.8414709848078965f)]
[TestCase(-1.0f, 1.0f, 0.19876611034641295f, 0.30955987565311222f)]
[TestCase(-111.0f, 111.0f, -2.3259065941590448e-49f, -5.1181940185795617e-49f)]
public void CanComputeExponential(float real, float imag, float expectedReal, float expectedImag)
{
var value = new Complex32(real, imag);
var expected = new Complex32(expectedReal, expectedImag);
AssertHelpers.AlmostEqualRelative(expected, value.Exponential(), 6);
}
/// <summary>
/// Can compute natural logarithm.
/// </summary>
/// <param name="real">Real part.</param>
/// <param name="imag">Imaginary part.</param>
/// <param name="expectedReal">Expected real part.</param>
/// <param name="expectedImag">Expected imaginary part.</param>
[TestCase(0.0f, 0.0f, float.NegativeInfinity, 0.0f)]
[TestCase(0.0f, 1.0f, 0.0f, 1.5707963267948966f)]
[TestCase(-1.0f, 1.0f, 0.34657359027997264f, 2.3561944901923448f)]
[TestCase(-111.1f, 111.1f, 5.0570042869255571f, 2.3561944901923448f)]
[TestCase(111.1f, -111.1f, 5.0570042869255571f, -0.78539816339744828f)]
public void CanComputeNaturalLogarithm(float real, float imag, float expectedReal, float expectedImag)
{
var value = new Complex32(real, imag);
var expected = new Complex32(expectedReal, expectedImag);
AssertHelpers.AlmostEqualRelative(expected, value.NaturalLogarithm(), 7);
}
/// <summary>
/// Can compute power.
/// </summary>
[Test]
public void CanComputePower()
{
var a = new Complex32(1.19209289550780998537e-7f, 1.19209289550780998537e-7f);
var b = new Complex32(1.19209289550780998537e-7f, 1.19209289550780998537e-7f);
AssertHelpers.AlmostEqualRelative(
new Complex32(9.99998047207974718744e-1f, -1.76553541154378695012e-6f), a.Power(b), 6);
a = new Complex32(0.0f, 1.19209289550780998537e-7f);
b = new Complex32(0.0f, -1.19209289550780998537e-7f);
AssertHelpers.AlmostEqualRelative(new Complex32(1.00000018725172576491f, 1.90048076369011843105e-6f), a.Power(b), 6);
a = new Complex32(0.0f, -1.19209289550780998537e-7f);
b = new Complex32(0.0f, 0.5f);
AssertHelpers.AlmostEqualRelative(new Complex32(-2.56488189382693049636e-1f, -2.17823120666116144959f), a.Power(b), 4);
a = new Complex32(0.0f, 0.5f);
b = new Complex32(0.0f, -0.5f);
AssertHelpers.AlmostEqualRelative(new Complex32(2.06287223508090495171f, 7.45007062179724087859e-1f), a.Power(b), 6);
a = new Complex32(0.0f, -0.5f);
b = new Complex32(0.0f, 1.0f);
AssertHelpers.AlmostEqualRelative(new Complex32(3.70040633557002510874f, -3.07370876701949232239f), a.Power(b), 6);
a = new Complex32(0.0f, 2.0f);
b = new Complex32(0.0f, -2.0f);
AssertHelpers.AlmostEqualRelative(new Complex32(4.24532146387429353891f, -2.27479427903521192648e1f), a.Power(b), 5);
a = new Complex32(0.0f, -8.388608e6f);
b = new Complex32(1.19209289550780998537e-7f, 0.0f);
AssertHelpers.AlmostEqualRelative(new Complex32(1.00000190048219620166f, -1.87253870018168043834e-7f), a.Power(b), 6);
a = new Complex32(0.0f, 0.0f);
b = new Complex32(0.0f, 0.0f);
AssertHelpers.AlmostEqualRelative(new Complex32(1.0f, 0.0f), a.Power(b), 6);
a = new Complex32(0.0f, 0.0f);
b = new Complex32(1.0f, 0.0f);
AssertHelpers.AlmostEqualRelative(new Complex32(0.0f, 0.0f), a.Power(b), 6);
a = new Complex32(0.0f, 0.0f);
b = new Complex32(-1.0f, 0.0f);
AssertHelpers.AlmostEqualRelative(new Complex32(float.PositiveInfinity, 0.0f), a.Power(b), 6);
a = new Complex32(0.0f, 0.0f);
b = new Complex32(-1.0f, 1.0f);
AssertHelpers.AlmostEqualRelative(new Complex32(float.PositiveInfinity, float.PositiveInfinity), a.Power(b), 6);
a = new Complex32(0.0f, 0.0f);
b = new Complex32(0.0f, 1.0f);
Assert.That(a.Power(b).IsNaN());
}
/// <summary>
/// Can compute root.
/// </summary>
[Test]
public void CanComputeRoot()
{
var a = new Complex32(1.19209289550780998537e-7f, 1.19209289550780998537e-7f);
var b = new Complex32(1.19209289550780998537e-7f, 1.19209289550780998537e-7f);
AssertHelpers.AlmostEqualRelative(new Complex32(0.0f, 0.0f), a.Root(b), 6);
a = new Complex32(0.0f, -1.19209289550780998537e-7f);
b = new Complex32(0.0f, 0.5f);
AssertHelpers.AlmostEqualRelative(new Complex32(0.038550761943650161f, 0.019526430428319544f), a.Root(b), 5);
a = new Complex32(0.0f, 0.5f);
b = new Complex32(0.0f, -0.5f);
AssertHelpers.AlmostEqualRelative(new Complex32(0.007927894711475968f, -0.042480480425152213f), a.Root(b), 5);
a = new Complex32(0.0f, -0.5f);
b = new Complex32(0.0f, 1.0f);
AssertHelpers.AlmostEqualRelative(new Complex32(0.15990905692806806f, 0.13282699942462053f), a.Root(b), 6);
a = new Complex32(0.0f, 2.0f);
b = new Complex32(0.0f, -2.0f);
AssertHelpers.AlmostEqualRelative(new Complex32(0.42882900629436788f, 0.15487175246424678f), a.Root(b), 6);
a = new Complex32(0.0f, -8.388608e6f);
b = new Complex32(1.19209289550780998537e-7f, 0.0f);
AssertHelpers.AlmostEqualRelative(new Complex32(float.PositiveInfinity, float.NegativeInfinity), a.Root(b), 6);
}
/// <summary>
/// Can compute square.
/// </summary>
[Test]
public void CanComputeSquare()
{
var complex = new Complex32(1.19209289550780998537e-7f, 1.19209289550780998537e-7f);
AssertHelpers.AlmostEqualRelative(new Complex32(0, 2.8421709430403888e-14f), complex.Square(), 7);
complex = new Complex32(0.0f, 1.19209289550780998537e-7f);
AssertHelpers.AlmostEqualRelative(new Complex32(-1.4210854715201944e-14f, 0.0f), complex.Square(), 7);
complex = new Complex32(0.0f, -1.19209289550780998537e-7f);
AssertHelpers.AlmostEqualRelative(new Complex32(-1.4210854715201944e-14f, 0.0f), complex.Square(), 7);
complex = new Complex32(0.0f, 0.5f);
AssertHelpers.AlmostEqualRelative(new Complex32(-0.25f, 0.0f), complex.Square(), 7);
complex = new Complex32(0.0f, -0.5f);
AssertHelpers.AlmostEqualRelative(new Complex32(-0.25f, 0.0f), complex.Square(), 7);
complex = new Complex32(0.0f, -8.388608e6f);
AssertHelpers.AlmostEqualRelative(new Complex32(-70368744177664.0f, 0.0f), complex.Square(), 7);
}
/// <summary>
/// Can compute square root.
/// </summary>
[Test]
public void CanComputeSquareRoot()
{
var complex = new Complex32(1.19209289550780998537e-7f, 1.19209289550780998537e-7f);
AssertHelpers.AlmostEqualRelative(
new Complex32(0.00037933934912842666f, 0.00015712750315077684f), complex.SquareRoot(), 7);
complex = new Complex32(0.0f, 1.19209289550780998537e-7f);
AssertHelpers.AlmostEqualRelative(
new Complex32(0.00024414062499999973f, 0.00024414062499999976f), complex.SquareRoot(), 7);
complex = new Complex32(0.0f, -1.19209289550780998537e-7f);
AssertHelpers.AlmostEqualRelative(
new Complex32(0.00024414062499999973f, -0.00024414062499999976f), complex.SquareRoot(), 7);
complex = new Complex32(0.0f, 0.5f);
AssertHelpers.AlmostEqualRelative(new Complex32(0.5f, 0.5f), complex.SquareRoot(), 7);
complex = new Complex32(0.0f, -0.5f);
AssertHelpers.AlmostEqualRelative(new Complex32(0.5f, -0.5f), complex.SquareRoot(), 7);
complex = new Complex32(0.0f, -8.388608e6f);
AssertHelpers.AlmostEqualRelative(new Complex32(2048.0f, -2048.0f), complex.SquareRoot(), 7);
complex = new Complex32(8.388608e6f, 1.19209289550780998537e-7f);
AssertHelpers.AlmostEqualRelative(new Complex32(2896.3093757400989f, 2.0579515874459933e-11f), complex.SquareRoot(), 7);
complex = new Complex32(0.0f, 0.0f);
AssertHelpers.AlmostEqualRelative(Complex32.Zero, complex.SquareRoot(), 7);
}
/// <summary>
/// Can convert a double to a complex.
/// </summary>
[Test]
public void CanConvertDoubleToComplex()
{
Assert.That(((Complex32)float.NaN).IsNaN());
Assert.That(((Complex32)float.NegativeInfinity).IsInfinity());
Assert.AreEqual((Complex32)1.1f, new Complex32(1.1f, 0));
}
/// <summary>
/// Can create a complex number using constructor.
/// </summary>
[Test]
public void CanCreateComplexNumberUsingConstructor()
{
var complex = new Complex32(1.1f, -2.2f);
Assert.AreEqual(1.1f, complex.Real, "Real part is 1.1f.");
Assert.AreEqual(-2.2f, complex.Imaginary, "Imaginary part is -2.2f.");
}
/// <summary>
/// Can create a complex number with modulus argument.
/// </summary>
[Test]
public void CanCreateComplexNumberWithModulusArgument()
{
var complex = Complex32.FromPolarCoordinates(2, (float)-Math.PI / 6);
Assert.AreEqual((float)Constants.Sqrt3, complex.Real, 1e-7f, "Real part is Sqrt(3).");
Assert.AreEqual(-1.0f, complex.Imaginary, 1e-7f, "Imaginary part is -1.");
}
/// <summary>
/// Can create a complex number with real imaginary initializer.
/// </summary>
[Test]
public void CanCreateComplexNumberWithRealImaginaryInitializer()
{
var complex = new Complex32(1.1f, -2.2f);
Assert.AreEqual(1.1f, complex.Real, "Real part is 1.1f.");
Assert.AreEqual(-2.2f, complex.Imaginary, "Imaginary part is -2.2f.");
}
/// <summary>
/// Can determine if imaginary is unit.
/// </summary>
[Test]
public void CanDetermineIfImaginaryUnit()
{
var complex = new Complex32(0, 1);
Assert.IsTrue(complex.IsImaginaryOne(), "Imaginary unit");
}
/// <summary>
/// Can determine if a complex is infinity.
/// </summary>
[Test]
public void CanDetermineIfInfinity()
{
var complex = new Complex32(float.PositiveInfinity, 1);
Assert.IsTrue(complex.IsInfinity(), "Real part is infinity.");
complex = new Complex32(1, float.NegativeInfinity);
Assert.IsTrue(complex.IsInfinity(), "Imaginary part is infinity.");
complex = new Complex32(float.NegativeInfinity, float.PositiveInfinity);
Assert.IsTrue(complex.IsInfinity(), "Both parts are infinity.");
}
/// <summary>
/// Can determine if a complex is not a number.
/// </summary>
[Test]
public void CanDetermineIfNaN()
{
var complex = new Complex32(float.NaN, 1);
Assert.IsTrue(complex.IsNaN(), "Real part is NaN.");
complex = new Complex32(1, float.NaN);
Assert.IsTrue(complex.IsNaN(), "Imaginary part is NaN.");
complex = new Complex32(float.NaN, float.NaN);
Assert.IsTrue(complex.IsNaN(), "Both parts are NaN.");
}
/// <summary>
/// Can determine Complex32 number with a value of one.
/// </summary>
[Test]
public void CanDetermineIfOneValueComplexNumber()
{
var complex = new Complex32(1, 0);
Assert.IsTrue(complex.IsOne(), "Complex32 number with a value of one.");
}
/// <summary>
/// Can determine if a complex is a real non-negative number.
/// </summary>
[Test]
public void CanDetermineIfRealNonNegativeNumber()
{
var complex = new Complex32(1, 0);
Assert.IsTrue(complex.IsReal(), "Is a real non-negative number.");
}
/// <summary>
/// Can determine if a complex is a real number.
/// </summary>
[Test]
public void CanDetermineIfRealNumber()
{
var complex = new Complex32(-1, 0);
Assert.IsTrue(complex.IsReal(), "Is a real number.");
}
/// <summary>
/// Can determine if a complex is a zero number.
/// </summary>
[Test]
public void CanDetermineIfZeroValueComplexNumber()
{
var complex = new Complex32(0, 0);
Assert.IsTrue(complex.IsZero(), "Zero complex number.");
}
/// <summary>
/// Can divide a complex number and a double using operators.
/// </summary>
[Test]
public void CanDivideComplexNumberAndDoubleUsingOperators()
{
Assert.That((Complex32.NaN * 1.0f).IsNaN());
Assert.AreEqual(new Complex32(-2, 2), new Complex32(4, -4) / -2);
Assert.AreEqual(new Complex32(0.25f, 0.25f), 2 / new Complex32(4, -4));
Assert.AreEqual(Complex32.PositiveInfinity, 2.0f / Complex32.Zero);
Assert.AreEqual(Complex32.PositiveInfinity, Complex32.One / 0);
}
/// <summary>
/// Can divide two complex numbers.
/// </summary>
[Test]
public void CanDivideTwoComplexNumbers()
{
Assert.That(Complex32.Divide(Complex32.NaN, Complex32.One).IsNaN());
Assert.AreEqual(new Complex32(-2, 0), Complex32.Divide(new Complex32(4, -4), new Complex32(-2, 2)));
Assert.AreEqual(Complex32.PositiveInfinity, Complex32.Divide(Complex32.One, Complex32.Zero));
}
/// <summary>
/// Can divide two complex numbers using operators.
/// </summary>
[Test]
public void CanDivideTwoComplexNumbersUsingOperators()
{
Assert.That((Complex32.NaN / Complex32.One).IsNaN());
Assert.AreEqual(new Complex32(-2, 0), new Complex32(4, -4) / new Complex32(-2, 2));
Assert.AreEqual(Complex32.PositiveInfinity, Complex32.One / Complex32.Zero);
}
/// <summary>
/// Can divide without overflow.
/// </summary>
[Test]
public void CanDodgeOverflowDivision()
{
var first = new Complex32((float)Math.Pow(10, 37), (float)Math.Pow(10, -37));
var second = new Complex32((float)Math.Pow(10, 25), (float)Math.Pow(10, -25));
Assert.AreEqual(new Complex32((float)Math.Pow(10, 12), (float)Math.Pow(10, -38)), first / second);
first = new Complex32(-(float)Math.Pow(10, 37), (float)Math.Pow(10, -37));
second = new Complex32((float)Math.Pow(10, 25), (float)Math.Pow(10, -25));
Assert.AreEqual(new Complex32(-(float)Math.Pow(10, 12), (float)Math.Pow(10, -38)), first / second);
first = new Complex32((float)Math.Pow(10, -37), (float)Math.Pow(10, 37));
second = new Complex32((float)Math.Pow(10, -17), -(float)Math.Pow(10, 17));
Assert.AreEqual(new Complex32(-(float)Math.Pow(10, 20), (float)Math.Pow(10, -14)), first / second);
}
/// <summary>
/// Can divide float/complex without overflow
/// </summary>
[Test]
public void CanDodgeOverflowDivisionFloat()
{
var firstComplex = new Complex32((float)Math.Pow(10, 25), (float)Math.Pow(10, -25));
float firstFloat = (float)Math.Pow(10, -37);
float secondFloat = (float)Math.Pow(10, 37);
Assert.AreEqual(new Complex32(0, 0), firstFloat / firstComplex); // it's (10^-62,10^-112) thus overflow to 0
Assert.AreEqual(new Complex32((float)Math.Pow(10, 12), (float)Math.Pow(10, -38)), secondFloat / firstComplex);
var secondComplex = new Complex32((float)Math.Pow(10, -25), (float)Math.Pow(10, 25));
Assert.AreEqual(new Complex32(0, 0), firstFloat / secondComplex);// it's (10^-112,10^-62) thus overflow to 0
Assert.AreEqual(new Complex32((float)Math.Pow(10, -38), -(float)Math.Pow(10, 12)), secondFloat / secondComplex);
float thirdFloat = (float)Math.Pow(10, 13);
var thirdComplex = new Complex32((float)Math.Pow(10, -25), (float)Math.Pow(10, -25));
Assert.AreEqual(new Complex32(5.0f * (float)Math.Pow(10, 37), -5.0f * (float)Math.Pow(10, 37)), thirdFloat / thirdComplex);
var fourthFloat = (float)Math.Pow(10, -30);
var fourthComplex = new Complex32((float)Math.Pow(10, -30), (float)Math.Pow(10, -30));
Assert.AreEqual(new Complex32(0.5f, -0.5f), fourthFloat / fourthComplex);
}
/// <summary>
/// Can multiple a complex number and a double using operators.
/// </summary>
[Test]
public void CanMultipleComplexNumberAndDoubleUsingOperators()
{
Assert.That((Complex32.NaN * 1.0f).IsNaN());
Assert.AreEqual(new Complex32(8, -8), new Complex32(4, -4) * 2);
Assert.AreEqual(new Complex32(8, -8), 2 * new Complex32(4, -4));
}
/// <summary>
/// Can multiple two complex numbers.
/// </summary>
[Test]
public void CanMultipleTwoComplexNumbers()
{
Assert.That(Complex32.Multiply(Complex32.NaN, Complex32.One).IsNaN());
Assert.AreEqual(new Complex32(0, 16), Complex32.Multiply(new Complex32(4, -4), new Complex32(-2, 2)));
}
/// <summary>
/// Can multiple two complex numbers using operators.
/// </summary>
[Test]
public void CanMultipleTwoComplexNumbersUsingOperators()
{
Assert.That((Complex32.NaN * Complex32.One).IsNaN());
Assert.AreEqual(new Complex32(0, 16), new Complex32(4, -4) * new Complex32(-2, 2));
}
/// <summary>
/// Can negate.
/// </summary>
[Test]
public void CanNegateValue()
{
var complex = new Complex32(1.1f, -2.2f);
Assert.AreEqual(new Complex32(-1.1f, 2.2f), Complex32.Negate(complex));
}
/// <summary>
/// Can negate using operator.
/// </summary>
[Test]
public void CanNegateValueUsingOperator()
{
var complex = new Complex32(1.1f, -2.2f);
Assert.AreEqual(new Complex32(-1.1f, 2.2f), -complex);
}
/// <summary>
/// Can subtract a complex number and a double using operator.
/// </summary>
[Test]
public void CanSubtractComplexNumberAndDoubleUsingOperator()
{
Assert.That((Complex32.NaN - float.NaN).IsNaN());
Assert.That((float.NaN - Complex32.NaN).IsNaN());
Assert.That((float.PositiveInfinity - Complex32.One).IsInfinity());
Assert.That((Complex32.PositiveInfinity - 1.0f).IsInfinity());
Assert.That((Complex32.One - 0.0f) == Complex32.One);
Assert.That((0.0f - Complex32.One) == -Complex32.One);
Assert.That(new Complex32(1.1f, -2.2f) - 1.1f == new Complex32(0.0f, -2.2f));
Assert.That(-2.2f - new Complex32(-1.1f, 2.2f) == new Complex32(-1.1f, -2.2f));
}
/// <summary>
/// Can subtract two complex numbers.
/// </summary>
[Test]
public void CanSubtractTwoComplexNumbers()
{
Assert.That(Complex32.Subtract(Complex32.NaN, Complex32.NaN).IsNaN());
Assert.That(Complex32.Subtract(Complex32.PositiveInfinity, Complex32.One).IsInfinity());
Assert.That(Complex32.Subtract(Complex32.One, Complex32.Zero) == Complex32.One);
Assert.That(Complex32.Subtract(new Complex32(1.1f, -2.2f), new Complex32(1.1f, -2.2f)) == Complex32.Zero);
}
/// <summary>
/// Can test for equality.
/// </summary>
[Test]
public void CanTestForEquality()
{
Assert.AreNotEqual(Complex32.NaN, Complex32.NaN);
Assert.AreEqual(Complex32.PositiveInfinity, Complex32.PositiveInfinity);
Assert.AreEqual(new Complex32(1.1f, -2.2f), new Complex32(1.1f, -2.2f));
Assert.AreNotEqual(new Complex32(-1.1f, 2.2f), new Complex32(1.1f, -2.2f));
}
/// <summary>
/// Can test for equality using operators.
/// </summary>
[Test]
public void CanTestForEqualityUsingOperators()
{
#pragma warning disable 1718
Assert.That(Complex32.NaN != Complex32.NaN);
Assert.That(Complex32.PositiveInfinity == Complex32.PositiveInfinity);
#pragma warning restore 1718
Assert.That(new Complex32(1.1f, -2.2f) == new Complex32(1.1f, -2.2f));
Assert.That(new Complex32(-1.1f, 2.2f) != new Complex32(1.1f, -2.2f));
}
/// <summary>
/// Can use unary "+" operator.
/// </summary>
[Test]
public void CanUsePlusOperator()
{
var complex = new Complex32(1.1f, -2.2f);
Assert.AreEqual(complex, +complex);
}
/// <summary>
/// Can compute magnitude.
/// </summary>
/// <param name="real">Real part.</param>
/// <param name="imag">Imaginary part.</param>
/// <param name="expected">Expected value.</param>
[TestCase(0.0f, 0.0f, 0.0f)]
[TestCase(0.0f, 1.0f, 1.0f)]
[TestCase(-1.0f, 1.0f, 1.4142135623730951f)]
[TestCase(-111.1f, 111.1f, 157.11912677965086f)]
public void CanComputeMagnitude(float real, float imag, float expected)
{
Assert.AreEqual(expected, new Complex32(real, imag).Magnitude);
}
/// <summary>
/// Can calculate magnitude without overflow
/// </summary>
[Test]
public void CanDodgeOverflowMagnitude()
{
Assert.AreEqual((float)Math.Sqrt(2) * float.Epsilon, new Complex32(float.Epsilon, float.Epsilon).Magnitude);
Assert.AreEqual(float.Epsilon, new Complex32(0, float.Epsilon).Magnitude);
Assert.AreEqual((float)(Math.Pow(10, 30) * Math.Sqrt(2)), new Complex32((float)Math.Pow(10, 30), (float)Math.Pow(10, 30)).Magnitude);
}
/// <summary>
/// Can compute sign.
/// </summary>
/// <param name="real">Real part.</param>
/// <param name="imag">Imaginary part.</param>
/// <param name="expectedReal">Expected real value.</param>
/// <param name="expectedImag">Expected imaginary value.</param>
[TestCase(float.PositiveInfinity, float.PositiveInfinity, (float)Constants.Sqrt1Over2, (float)Constants.Sqrt1Over2)]
[TestCase(float.PositiveInfinity, float.NegativeInfinity, (float)Constants.Sqrt1Over2, (float)-Constants.Sqrt1Over2)]
[TestCase(float.NegativeInfinity, float.PositiveInfinity, (float)-Constants.Sqrt1Over2, (float)-Constants.Sqrt1Over2)]
[TestCase(float.NegativeInfinity, float.NegativeInfinity, (float)-Constants.Sqrt1Over2, (float)Constants.Sqrt1Over2)]
[TestCase(0.0f, 0.0f, 0.0f, 0.0f)]
[TestCase(-1.0f, 1.0f, -0.70710678118654746f, 0.70710678118654746f)]
[TestCase(-111.1f, 111.1f, -0.70710678118654746f, 0.70710678118654746f)]
public void CanComputeSign(float real, float imag, float expectedReal, float expectedImag)
{
Assert.AreEqual(new Complex32(expectedReal, expectedImag), new Complex32(real, imag).Sign);
}
/// <summary>
/// Can convert a decimal to a complex.
/// </summary>
[Test]
public void CanConvertDecimalToComplex()
{
var orginal = new decimal(1.234567890);
var complex = (Complex32)orginal;
Assert.AreEqual((float)1.234567890, complex.Real);
Assert.AreEqual(0.0f, complex.Imaginary);
}
/// <summary>
/// Can convert a byte to a complex.
/// </summary>
[Test]
public void CanConvertByteToComplex()
{
const byte Orginal = 123;
var complex = (Complex32)Orginal;
Assert.AreEqual(123, complex.Real);
Assert.AreEqual(0.0f, complex.Imaginary);
}
/// <summary>
/// Can convert a short to a complex.
/// </summary>
[Test]
public void CanConvertShortToComplex()
{
const short Orginal = 123;
var complex = (Complex32)Orginal;
Assert.AreEqual(123, complex.Real);
Assert.AreEqual(0.0f, complex.Imaginary);
}
/// <summary>
/// Can convert an int to a complex.
/// </summary>
[Test]
public void CanConvertIntToComplex()
{
const int Orginal = 123;
var complex = (Complex32)Orginal;
Assert.AreEqual(123, complex.Real);
Assert.AreEqual(0.0f, complex.Imaginary);
}
/// <summary>
/// Can convert a long to a complex.
/// </summary>
[Test]
public void CanConvertLongToComplex()
{
const long Orginal = 123;
var complex = (Complex32)Orginal;
Assert.AreEqual(123, complex.Real);
Assert.AreEqual(0.0f, complex.Imaginary);
}
/// <summary>
/// Can convert an uint to a complex.
/// </summary>
[Test]
public void CanConvertUIntToComplex()
{
const uint Orginal = 123;
var complex = (Complex32)Orginal;
Assert.AreEqual(123, complex.Real);
Assert.AreEqual(0.0f, complex.Imaginary);
}
/// <summary>
/// Can convert an ulong to complex.
/// </summary>
[Test]
public void CanConvertULongToComplex()
{
const ulong Orginal = 123;
var complex = (Complex32)Orginal;
Assert.AreEqual(123, complex.Real);
Assert.AreEqual(0.0f, complex.Imaginary);
}
/// <summary>
/// Can convert a float to a complex.
/// </summary>
[Test]
public void CanConvertFloatToComplex()
{
const float Orginal = 123.456789f;
var complex = (Complex32)Orginal;
Assert.AreEqual(123.456789f, complex.Real);
Assert.AreEqual(0.0f, complex.Imaginary);
}
/// <summary>
/// Can convert a complex to a complex32.
/// </summary>
[Test]
public void CanConvertComplexToComplex32()
{
var complex32 = new Complex(123.456, -78.9);
var complex = (Complex32)complex32;
Assert.AreEqual(123.456f, complex.Real);
Assert.AreEqual(-78.9f, complex.Imaginary);
}
/// <summary>
/// Can conjugate.
/// </summary>
[Test]
public void CanGetConjugate()
{
var complex = new Complex32(123.456f, -78.9f);
var conjugate = complex.Conjugate();
Assert.AreEqual(complex.Real, conjugate.Real);
Assert.AreEqual(-complex.Imaginary, conjugate.Imaginary);
}
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using OmniXaml;
using Avalonia.Platform;
using Avalonia.Markup.Xaml.Context;
using Avalonia.Markup.Xaml.Styling;
using OmniXaml.ObjectAssembler;
using Avalonia.Controls;
using Avalonia.Markup.Xaml.Data;
namespace Avalonia.Markup.Xaml
{
/// <summary>
/// Loads XAML for a avalonia application.
/// </summary>
public class AvaloniaXamlLoader : XmlLoader
{
private static AvaloniaParserFactory s_parserFactory;
private static IInstanceLifeCycleListener s_lifeCycleListener = new AvaloniaLifeCycleListener();
private static Stack<Uri> s_uriStack = new Stack<Uri>();
/// <summary>
/// Initializes a new instance of the <see cref="AvaloniaXamlLoader"/> class.
/// </summary>
public AvaloniaXamlLoader()
: this(GetParserFactory())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AvaloniaXamlLoader"/> class.
/// </summary>
/// <param name="xamlParserFactory">The parser factory to use.</param>
public AvaloniaXamlLoader(IParserFactory xamlParserFactory)
: base(xamlParserFactory)
{
}
/// <summary>
/// Gets the URI of the XAML file currently being loaded.
/// </summary>
/// <remarks>
/// TODO: Making this internal for now as I'm not sure that this is the correct
/// thing to do, but its needed by <see cref="StyleInclude"/> to get the URL of
/// the currently loading XAML file, as we can't use the OmniXAML parsing context
/// there. Maybe we need a way to inject OmniXAML context into the objects its
/// constructing?
/// </remarks>
internal static Uri UriContext => s_uriStack.Count > 0 ? s_uriStack.Peek() : null;
/// <summary>
/// Loads the XAML into a Avalonia component.
/// </summary>
/// <param name="obj">The object to load the XAML into.</param>
public static void Load(object obj)
{
Contract.Requires<ArgumentNullException>(obj != null);
var loader = new AvaloniaXamlLoader();
loader.Load(obj.GetType(), obj);
}
/// <summary>
/// Loads the XAML for a type.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="rootInstance">
/// The optional instance into which the XAML should be loaded.
/// </param>
/// <returns>The loaded object.</returns>
public object Load(Type type, object rootInstance = null)
{
Contract.Requires<ArgumentNullException>(type != null);
// HACK: Currently Visual Studio is forcing us to change the extension of xaml files
// in certain situations, so we try to load .xaml and if that's not found we try .xaml.
// Ideally we'd be able to use .xaml everywhere
var assetLocator = AvaloniaLocator.Current.GetService<IAssetLoader>();
if (assetLocator == null)
{
throw new InvalidOperationException(
"Could not create IAssetLoader : maybe Application.RegisterServices() wasn't called?");
}
foreach (var uri in GetUrisFor(type))
{
if (assetLocator.Exists(uri))
{
using (var stream = assetLocator.Open(uri))
{
var initialize = rootInstance as ISupportInitialize;
initialize?.BeginInit();
return Load(stream, rootInstance, uri);
}
}
}
throw new FileNotFoundException("Unable to find view for " + type.FullName);
}
/// <summary>
/// Loads XAML from a URI.
/// </summary>
/// <param name="uri">The URI of the XAML file.</param>
/// <param name="baseUri">
/// A base URI to use if <paramref name="uri"/> is relative.
/// </param>
/// <param name="rootInstance">
/// The optional instance into which the XAML should be loaded.
/// </param>
/// <returns>The loaded object.</returns>
public object Load(Uri uri, Uri baseUri = null, object rootInstance = null)
{
Contract.Requires<ArgumentNullException>(uri != null);
var assetLocator = AvaloniaLocator.Current.GetService<IAssetLoader>();
if (assetLocator == null)
{
throw new InvalidOperationException(
"Could not create IAssetLoader : maybe Application.RegisterServices() wasn't called?");
}
using (var stream = assetLocator.Open(uri, baseUri))
{
return Load(stream, rootInstance, uri);
}
}
/// <summary>
/// Loads XAML from a string.
/// </summary>
/// <param name="xaml">The string containing the XAML.</param>
/// <param name="rootInstance">
/// The optional instance into which the XAML should be loaded.
/// </param>
/// <returns>The loaded object.</returns>
public object Load(string xaml, object rootInstance = null)
{
Contract.Requires<ArgumentNullException>(xaml != null);
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(xaml)))
{
return Load(stream, rootInstance);
}
}
/// <summary>
/// Loads XAML from a stream.
/// </summary>
/// <param name="stream">The stream containing the XAML.</param>
/// <param name="rootInstance">
/// The optional instance into which the XAML should be loaded.
/// </param>
/// <param name="uri">The URI of the XAML</param>
/// <returns>The loaded object.</returns>
public object Load(Stream stream, object rootInstance = null, Uri uri = null)
{
try
{
if (uri != null)
{
s_uriStack.Push(uri);
}
var result = base.Load(stream, new Settings
{
RootInstance = rootInstance,
InstanceLifeCycleListener = s_lifeCycleListener,
ParsingContext = new Dictionary<string, object>
{
{ "Uri", uri }
}
});
var topLevel = result as TopLevel;
if (topLevel != null)
{
DelayedBinding.ApplyBindings(topLevel);
}
return result;
}
finally
{
if (uri != null)
{
s_uriStack.Pop();
}
}
}
private static AvaloniaParserFactory GetParserFactory()
{
if (s_parserFactory == null)
{
s_parserFactory = new AvaloniaParserFactory();
}
return s_parserFactory;
}
/// <summary>
/// Gets the URI for a type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The URI.</returns>
private static IEnumerable<Uri> GetUrisFor(Type type)
{
var asm = type.GetTypeInfo().Assembly.GetName().Name;
var typeName = type.FullName;
yield return new Uri("resm:" + typeName + ".xaml?assembly=" + asm);
yield return new Uri("resm:" + typeName + ".paml?assembly=" + asm);
}
}
}
| |
using System.Web;
using System.Web.Routing;
using MbUnit.Framework;
using Moq;
using Ninject;
using Subtext.Framework.Routing;
using Subtext.Infrastructure;
namespace UnitTests.Subtext.Framework.Routing
{
[TestFixture]
public class RootRouteTests
{
[Test]
public void GetRouteDataWithRequestForAppRoot_WhenAggregationEnabled_MatchesAndReturnsAggDefault()
{
//arrange
var httpContext = new Mock<HttpContextBase>();
httpContext.FakeRequest("~/", string.Empty /* subfolder */, "~/");
var route = new RootRoute(true, new Mock<IServiceLocator>().Object);
//act
RouteData routeData = route.GetRouteData(httpContext.Object);
//assert
var routeHandler = routeData.RouteHandler as PageRouteHandler;
Assert.AreEqual("~/aspx/AggDefault.aspx", routeHandler.VirtualPath);
Assert.AreSame(route, routeData.Route);
Assert.IsFalse(routeData.DataTokens.ContainsKey(PageRoute.ControlNamesKey));
}
[Test]
public void GetRouteDataWithRequestForAppRoot_WhenAggregationDisabled_MatchesAndReturnsDtp()
{
//arrange
var httpContext = new Mock<HttpContextBase>();
httpContext.FakeRequest("~/", string.Empty /* subfolder */, "~/");
var route = new RootRoute(false, new Mock<IServiceLocator>().Object);
//act
RouteData routeData = route.GetRouteData(httpContext.Object);
//assert
var routeHandler = routeData.RouteHandler as PageRouteHandler;
Assert.AreEqual("~/aspx/Dtp.aspx", routeHandler.VirtualPath);
Assert.AreSame(route, routeData.Route);
Assert.IsTrue(routeData.DataTokens.ContainsKey(PageRoute.ControlNamesKey));
}
[Test]
public void GetRouteDataWithRequestForSubfolder_WhenAggregationEnabled_MatchesRequestAndReturnsDtp()
{
//arrange
var httpContext = new Mock<HttpContextBase>();
httpContext.FakeRequest("~/subfolder", "subfolder" /* subfolder */, "~/");
var route = new RootRoute(true, new Mock<IServiceLocator>().Object);
//act
RouteData routeData = route.GetRouteData(httpContext.Object);
//assert
var routeHandler = routeData.RouteHandler as PageRouteHandler;
Assert.AreEqual("~/aspx/Dtp.aspx", routeHandler.VirtualPath);
Assert.AreSame(route, routeData.Route);
}
[Test]
public void GetRouteDataWithRequestForSubfolder_WhenAggregationDisabled_MatchesRequestAndReturnsDtp()
{
//arrange
var httpContext = new Mock<HttpContextBase>();
httpContext.FakeRequest("~/subfolder", "subfolder" /* subfolder */, "~/");
var route = new RootRoute(false, new Mock<IServiceLocator>().Object);
//act
RouteData routeData = route.GetRouteData(httpContext.Object);
//assert
var routeHandler = routeData.RouteHandler as PageRouteHandler;
Assert.AreEqual("~/aspx/Dtp.aspx", routeHandler.VirtualPath);
Assert.AreSame(route, routeData.Route);
}
[Test]
public void GetRouteDataWithRequestWithSubfolder_WhenAggregationEnabledAndBlogDoesNotHaveSubfolder_DoesNotMatch()
{
//arrange
var httpContext = new Mock<HttpContextBase>();
httpContext.FakeRequest("~/foo", string.Empty /* subfolder */, "~/");
var route = new RootRoute(true, new Mock<IServiceLocator>().Object);
//act
RouteData routeData = route.GetRouteData(httpContext.Object);
//assert
Assert.IsNull(routeData);
}
[Test]
public void GetRouteDataWithRequestWithSubfolder_WhenAggregationDisabledAndBlogDoesNotHaveSubfolder_DoesNotMatch
()
{
//arrange
var httpContext = new Mock<HttpContextBase>();
httpContext.FakeRequest("~/foo", string.Empty /* subfolder */, "~/");
var route = new RootRoute(false, new Mock<IServiceLocator>().Object);
//act
RouteData routeData = route.GetRouteData(httpContext.Object);
//assert
Assert.IsNull(routeData);
}
[Test]
public void
GetRouteDataWithRequestWithSubfolder_WhenAggregationEnabledAndSubfolderDoesNotMatchBlogSubfolder_DoesNotMatch
()
{
//arrange
var httpContext = new Mock<HttpContextBase>();
httpContext.FakeRequest("~/foo", "bar" /* subfolder */, "~/");
var route = new RootRoute(true, new Mock<IServiceLocator>().Object);
//act
RouteData routeData = route.GetRouteData(httpContext.Object);
//assert
Assert.IsNull(routeData);
}
[Test]
public void
GetRouteDataWithRequestWithSubfolder_WhenAggregationDisabledAndSubfolderDoesNotMatchBlogSubfolder_DoesNotMatch
()
{
//arrange
var httpContext = new Mock<HttpContextBase>();
httpContext.FakeRequest("~/foo", "bar" /* subfolder */, "~/");
var route = new RootRoute(false, new Mock<IServiceLocator>().Object);
//act
RouteData routeData = route.GetRouteData(httpContext.Object);
//assert
Assert.IsNull(routeData);
}
[Test]
public void GetRouteDataWithRequestForDefault_WhenAggregationEnabled_MatchesAndReturnsAggDefault()
{
//arrange
var httpContext = new Mock<HttpContextBase>();
httpContext.FakeRequest("~/Default.aspx", string.Empty /* subfolder */, "~/");
var route = new RootRoute(true, new Mock<IServiceLocator>().Object);
//act
RouteData routeData = route.GetRouteData(httpContext.Object);
//assert
var routeHandler = routeData.RouteHandler as PageRouteHandler;
Assert.AreEqual("~/aspx/AggDefault.aspx", routeHandler.VirtualPath);
Assert.AreSame(route, routeData.Route);
}
[Test]
public void GetRouteDataWithRequestForDefault_WhenAggregationDisabled_MatchesAndReturnsDtp()
{
//arrange
var httpContext = new Mock<HttpContextBase>();
httpContext.FakeRequest("~/Default.aspx", string.Empty /* subfolder */, "~/");
var route = new RootRoute(false, new Mock<IServiceLocator>().Object);
//act
RouteData routeData = route.GetRouteData(httpContext.Object);
//assert
var routeHandler = routeData.RouteHandler as PageRouteHandler;
Assert.AreEqual("~/aspx/Dtp.aspx", routeHandler.VirtualPath);
Assert.AreSame(route, routeData.Route);
}
[Test]
public void GetRouteDataWithRequestForDefaultInSubfolder_WhenAggregationEnabled_MatchesRequestAndReturnsDtp()
{
//arrange
var httpContext = new Mock<HttpContextBase>();
httpContext.FakeRequest("~/subfolder/default.aspx", "subfolder" /* subfolder */, "~/");
var route = new RootRoute(true, new Mock<IServiceLocator>().Object);
//act
RouteData routeData = route.GetRouteData(httpContext.Object);
//assert
var routeHandler = routeData.RouteHandler as PageRouteHandler;
Assert.AreEqual("~/aspx/Dtp.aspx", routeHandler.VirtualPath);
Assert.AreSame(route, routeData.Route);
}
[Test]
public void GetRouteDataWithRequestForDefaultInSubfolder_WhenAggregationDisabled_MatchesRequestAndReturnsDtp()
{
//arrange
var httpContext = new Mock<HttpContextBase>();
httpContext.FakeRequest("~/subfolder/default.aspx", "subfolder" /* subfolder */, "~/");
var route = new RootRoute(false, new Mock<IServiceLocator>().Object);
//act
RouteData routeData = route.GetRouteData(httpContext.Object);
//assert
var routeHandler = routeData.RouteHandler as PageRouteHandler;
Assert.AreEqual("~/aspx/Dtp.aspx", routeHandler.VirtualPath);
Assert.AreSame(route, routeData.Route);
}
[Test]
public void GetVirtualPath_WhenAggregationEnabledAndNoSubfolderInRouteData_ReturnsRoot()
{
//arrange
var httpContext = new Mock<HttpContextBase>();
httpContext.FakeRequest("~/default.aspx", string.Empty /* subfolder */, "~/");
var routeData = new RouteData();
var requestContext = new RequestContext(httpContext.Object, routeData);
var route = new RootRoute(true, new Mock<IServiceLocator>().Object);
var routeValues = new RouteValueDictionary();
//act
VirtualPathData virtualPathInfo = route.GetVirtualPath(requestContext, routeValues);
//assert
Assert.AreEqual(string.Empty, virtualPathInfo.VirtualPath);
}
[Test]
public void GetVirtualPath_WhenAggregationEnabledWithSubfolderInRouteData_ReturnsSubfolder()
{
//arrange
var httpContext = new Mock<HttpContextBase>();
httpContext.FakeRequest("~/subfolder/default.aspx", "subfolder" /* subfolder */, "~/");
var routeData = new RouteData();
routeData.Values.Add("subfolder", "subfolder");
var requestContext = new RequestContext(httpContext.Object, routeData);
var route = new RootRoute(true, new Mock<IServiceLocator>().Object);
var routeValues = new RouteValueDictionary();
//act
VirtualPathData virtualPathInfo = route.GetVirtualPath(requestContext, routeValues);
//assert
Assert.AreEqual("subfolder", virtualPathInfo.VirtualPath);
}
[Test]
public void GetVirtualPath_WhenAggregationEnabledWithSubfolderInRouteValues_ReturnsSubfolder()
{
//arrange
var httpContext = new Mock<HttpContextBase>();
httpContext.FakeRequest("~/subfolder/default.aspx", "subfolder" /* subfolder */, "~/");
var routeData = new RouteData();
var requestContext = new RequestContext(httpContext.Object, routeData);
var route = new RootRoute(true, new Mock<IServiceLocator>().Object);
var routeValues = new RouteValueDictionary(new {subfolder = "subfolder"});
//act
VirtualPathData virtualPathInfo = route.GetVirtualPath(requestContext, routeValues);
//assert
Assert.AreEqual("subfolder", virtualPathInfo.VirtualPath);
}
[Test]
public void GetVirtualPath_WhenSupplyingRouteValues_ReturnsNull()
{
//arrange
var httpContext = new Mock<HttpContextBase>();
httpContext.FakeRequest("~/subfolder/default.aspx", string.Empty /* subfolder */, "~/");
var routeData = new RouteData();
var requestContext = new RequestContext(httpContext.Object, routeData);
var route = new RootRoute(true, new Mock<IServiceLocator>().Object);
var routeValues = new RouteValueDictionary(new {foo = "bar"});
//act
VirtualPathData virtualPathInfo = route.GetVirtualPath(requestContext, routeValues);
//assert
Assert.IsNull(virtualPathInfo);
}
}
}
| |
// <copyright file="IluptElementSorterTest.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
//
// Copyright (c) 2009-2013 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using MathNet.Numerics.LinearAlgebra.Double;
using MathNet.Numerics.LinearAlgebra.Double.Solvers;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Double.Solvers.Preconditioners
{
/// <summary>
/// Test for element sort algorithm of Ilupt class.
/// </summary>
[TestFixture, Category("LASolver")]
public sealed class IluptElementSorterTest
{
/// <summary>
/// Heap sort with increasing integer array.
/// </summary>
[Test]
public void HeapSortWithIncreasingIntegerArray()
{
var sortedIndices = new[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
ILUTPElementSorter.SortIntegersDecreasing(sortedIndices);
for (var i = 0; i < sortedIndices.Length; i++)
{
Assert.AreEqual(sortedIndices.Length - 1 - i, sortedIndices[i], "#01-" + i);
}
}
/// <summary>
/// Heap sort with decreasing integer array.
/// </summary>
[Test]
public void HeapSortWithDecreasingIntegerArray()
{
var sortedIndices = new[] {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
ILUTPElementSorter.SortIntegersDecreasing(sortedIndices);
for (var i = 0; i < sortedIndices.Length; i++)
{
Assert.AreEqual(sortedIndices.Length - 1 - i, sortedIndices[i], "#01-" + i);
}
}
/// <summary>
/// Heap sort with random integer array.
/// </summary>
[Test]
public void HeapSortWithRandomIntegerArray()
{
var sortedIndices = new[] {5, 2, 8, 6, 0, 4, 1, 7, 3, 9};
ILUTPElementSorter.SortIntegersDecreasing(sortedIndices);
for (var i = 0; i < sortedIndices.Length; i++)
{
Assert.AreEqual(sortedIndices.Length - 1 - i, sortedIndices[i], "#01-" + i);
}
}
/// <summary>
/// Heap sort with duplicate entries.
/// </summary>
[Test]
public void HeapSortWithDuplicateEntries()
{
var sortedIndices = new[] {1, 1, 1, 1, 2, 2, 2, 2, 3, 4};
ILUTPElementSorter.SortIntegersDecreasing(sortedIndices);
for (var i = 0; i < sortedIndices.Length; i++)
{
if (i == 0)
{
Assert.AreEqual(4, sortedIndices[i], "#01-" + i);
}
else
{
if (i == 1)
{
Assert.AreEqual(3, sortedIndices[i], "#01-" + i);
}
else
{
if (i < 6)
{
if (sortedIndices[i] != 2)
{
Assert.Fail("#01-" + i);
}
}
else
{
if (sortedIndices[i] != 1)
{
Assert.Fail("#01-" + i);
}
}
}
}
}
}
/// <summary>
/// Heap sort with special constructed integer array.
/// </summary>
[Test]
public void HeapSortWithSpecialConstructedIntegerArray()
{
var sortedIndices = new[] {0, 0, 0, 0, 0, 1, 0, 0, 0, 0};
ILUTPElementSorter.SortIntegersDecreasing(sortedIndices);
for (var i = 0; i < sortedIndices.Length; i++)
{
if (i == 0)
{
Assert.AreEqual(1, sortedIndices[i], "#01-" + i);
break;
}
}
sortedIndices = new[] {1, 0, 0, 0, 0, 0, 0, 0, 0, 0};
ILUTPElementSorter.SortIntegersDecreasing(sortedIndices);
for (var i = 0; i < sortedIndices.Length; i++)
{
if (i == 0)
{
Assert.AreEqual(1, sortedIndices[i], "#02-" + i);
break;
}
}
sortedIndices = new[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
ILUTPElementSorter.SortIntegersDecreasing(sortedIndices);
for (var i = 0; i < sortedIndices.Length; i++)
{
if (i == 0)
{
Assert.AreEqual(1, sortedIndices[i], "#03-" + i);
break;
}
}
sortedIndices = new[] {1, 1, 1, 0, 1, 1, 1, 1, 1, 1};
ILUTPElementSorter.SortIntegersDecreasing(sortedIndices);
for (var i = 0; i < sortedIndices.Length; i++)
{
if (i == 9)
{
Assert.AreEqual(0, sortedIndices[i], "#04-" + i);
break;
}
}
}
/// <summary>
/// Heap sort with increasing double array.
/// </summary>
[Test]
public void HeapSortWithIncreasingDoubleArray()
{
var sortedIndices = new int[10];
var values = new DenseVector(10);
values[0] = 0;
values[1] = 1;
values[2] = 2;
values[3] = 3;
values[4] = 4;
values[5] = 5;
values[6] = 6;
values[7] = 7;
values[8] = 8;
values[9] = 9;
for (var i = 0; i < sortedIndices.Length; i++)
{
sortedIndices[i] = i;
}
ILUTPElementSorter.SortDoubleIndicesDecreasing(0, sortedIndices.Length - 1, sortedIndices, values);
for (var i = 0; i < sortedIndices.Length; i++)
{
Assert.AreEqual(sortedIndices.Length - 1 - i, sortedIndices[i], "#01-" + i);
}
}
/// <summary>
/// Heap sort with decreasing doubleArray
/// </summary>
[Test]
public void HeapSortWithDecreasingDoubleArray()
{
var sortedIndices = new int[10];
var values = new DenseVector(10);
values[0] = 9;
values[1] = 8;
values[2] = 7;
values[3] = 6;
values[4] = 5;
values[5] = 4;
values[6] = 3;
values[7] = 2;
values[8] = 1;
values[9] = 0;
for (var i = 0; i < sortedIndices.Length; i++)
{
sortedIndices[i] = i;
}
ILUTPElementSorter.SortDoubleIndicesDecreasing(0, sortedIndices.Length - 1, sortedIndices, values);
for (var i = 0; i < sortedIndices.Length; i++)
{
Assert.AreEqual(i, sortedIndices[i], "#01-" + i);
}
}
/// <summary>
/// Heap sort with random double array.
/// </summary>
[Test]
public void HeapSortWithRandomDoubleArray()
{
var sortedIndices = new int[10];
var values = new DenseVector(10);
values[0] = 5;
values[1] = 2;
values[2] = 8;
values[3] = 6;
values[4] = 0;
values[5] = 4;
values[6] = 1;
values[7] = 7;
values[8] = 3;
values[9] = 9;
for (var i = 0; i < sortedIndices.Length; i++)
{
sortedIndices[i] = i;
}
ILUTPElementSorter.SortDoubleIndicesDecreasing(0, sortedIndices.Length - 1, sortedIndices, values);
for (var i = 0; i < sortedIndices.Length; i++)
{
switch (i)
{
case 0:
Assert.AreEqual(9, sortedIndices[i], "#01-" + i);
break;
case 1:
Assert.AreEqual(2, sortedIndices[i], "#01-" + i);
break;
case 2:
Assert.AreEqual(7, sortedIndices[i], "#01-" + i);
break;
case 3:
Assert.AreEqual(3, sortedIndices[i], "#01-" + i);
break;
case 4:
Assert.AreEqual(0, sortedIndices[i], "#01-" + i);
break;
case 5:
Assert.AreEqual(5, sortedIndices[i], "#01-" + i);
break;
case 6:
Assert.AreEqual(8, sortedIndices[i], "#01-" + i);
break;
case 7:
Assert.AreEqual(1, sortedIndices[i], "#01-" + i);
break;
case 8:
Assert.AreEqual(6, sortedIndices[i], "#01-" + i);
break;
case 9:
Assert.AreEqual(4, sortedIndices[i], "#01-" + i);
break;
}
}
}
/// <summary>
/// Heap sort with duplicate double entries.
/// </summary>
[Test]
public void HeapSortWithDuplicateDoubleEntries()
{
var sortedIndices = new int[10];
var values = new DenseVector(10);
values[0] = 1;
values[1] = 1;
values[2] = 1;
values[3] = 1;
values[4] = 2;
values[5] = 2;
values[6] = 2;
values[7] = 2;
values[8] = 3;
values[9] = 4;
for (var i = 0; i < sortedIndices.Length; i++)
{
sortedIndices[i] = i;
}
ILUTPElementSorter.SortDoubleIndicesDecreasing(0, sortedIndices.Length - 1, sortedIndices, values);
for (var i = 0; i < sortedIndices.Length; i++)
{
if (i == 0)
{
Assert.AreEqual(9, sortedIndices[i], "#01-" + i);
}
else
{
if (i == 1)
{
Assert.AreEqual(8, sortedIndices[i], "#01-" + i);
}
else
{
if (i < 6)
{
if ((sortedIndices[i] != 4) &&
(sortedIndices[i] != 5) &&
(sortedIndices[i] != 6) &&
(sortedIndices[i] != 7))
{
Assert.Fail("#01-" + i);
}
}
else
{
if ((sortedIndices[i] != 0) &&
(sortedIndices[i] != 1) &&
(sortedIndices[i] != 2) &&
(sortedIndices[i] != 3))
{
Assert.Fail("#01-" + i);
}
}
}
}
}
}
/// <summary>
/// Heap sort with special constructed double array.
/// </summary>
[Test]
public void HeapSortWithSpecialConstructedDoubleArray()
{
var sortedIndices = new int[10];
var values = new DenseVector(10);
values[0] = 0;
values[1] = 0;
values[2] = 0;
values[3] = 0;
values[4] = 0;
values[5] = 1;
values[6] = 0;
values[7] = 0;
values[8] = 0;
values[9] = 0;
for (var i = 0; i < sortedIndices.Length; i++)
{
sortedIndices[i] = i;
}
ILUTPElementSorter.SortDoubleIndicesDecreasing(0, sortedIndices.Length - 1, sortedIndices, values);
for (var i = 0; i < sortedIndices.Length; i++)
{
if (i == 0)
{
Assert.AreEqual(5, sortedIndices[i], "#01-" + i);
break;
}
}
values[0] = 1;
values[1] = 0;
values[2] = 0;
values[3] = 0;
values[4] = 0;
values[5] = 0;
values[6] = 0;
values[7] = 0;
values[8] = 0;
values[9] = 0;
for (var i = 0; i < sortedIndices.Length; i++)
{
sortedIndices[i] = i;
}
ILUTPElementSorter.SortDoubleIndicesDecreasing(0, sortedIndices.Length - 1, sortedIndices, values);
for (var i = 0; i < sortedIndices.Length; i++)
{
if (i == 0)
{
Assert.AreEqual(0, sortedIndices[i], "#02-" + i);
break;
}
}
values[0] = 0;
values[1] = 0;
values[2] = 0;
values[3] = 0;
values[4] = 0;
values[5] = 0;
values[6] = 0;
values[7] = 0;
values[8] = 0;
values[9] = 1;
for (var i = 0; i < sortedIndices.Length; i++)
{
sortedIndices[i] = i;
}
ILUTPElementSorter.SortDoubleIndicesDecreasing(0, sortedIndices.Length - 1, sortedIndices, values);
for (var i = 0; i < sortedIndices.Length; i++)
{
if (i == 0)
{
Assert.AreEqual(9, sortedIndices[i], "#03-" + i);
break;
}
}
values[0] = 1;
values[1] = 1;
values[2] = 1;
values[3] = 0;
values[4] = 1;
values[5] = 1;
values[6] = 1;
values[7] = 1;
values[8] = 1;
values[9] = 1;
for (var i = 0; i < sortedIndices.Length; i++)
{
sortedIndices[i] = i;
}
ILUTPElementSorter.SortDoubleIndicesDecreasing(0, sortedIndices.Length - 1, sortedIndices, values);
for (var i = 0; i < sortedIndices.Length; i++)
{
if (i == 9)
{
Assert.AreEqual(3, sortedIndices[i], "#04-" + i);
break;
}
}
}
/// <summary>
/// Heap sort with increasing double array with lower bound
/// </summary>
[Test]
public void HeapSortWithIncreasingDoubleArrayWithLowerBound()
{
var sortedIndices = new int[10];
var values = new DenseVector(10);
values[0] = 0;
values[1] = 1;
values[2] = 2;
values[3] = 3;
values[4] = 4;
values[5] = 5;
values[6] = 6;
values[7] = 7;
values[8] = 8;
values[9] = 9;
for (var i = 0; i < sortedIndices.Length; i++)
{
sortedIndices[i] = i;
}
ILUTPElementSorter.SortDoubleIndicesDecreasing(4, sortedIndices.Length - 1, sortedIndices, values);
for (var i = 0; i < sortedIndices.Length - 4; i++)
{
Assert.AreEqual(sortedIndices.Length - 1 - i, sortedIndices[i], "#01-" + i);
}
}
/// <summary>
/// Heap sort with increasing double array with upper bound.
/// </summary>
[Test]
public void HeapSortWithIncreasingDoubleArrayWithUpperBound()
{
var sortedIndices = new int[10];
var values = new DenseVector(10);
values[0] = 0;
values[1] = 1;
values[2] = 2;
values[3] = 3;
values[4] = 4;
values[5] = 5;
values[6] = 6;
values[7] = 7;
values[8] = 8;
values[9] = 9;
for (var i = 0; i < sortedIndices.Length; i++)
{
sortedIndices[i] = i;
}
ILUTPElementSorter.SortDoubleIndicesDecreasing(0, sortedIndices.Length - 5, sortedIndices, values);
for (var i = 0; i < sortedIndices.Length - 5; i++)
{
Assert.AreEqual(sortedIndices.Length - 5 - i, sortedIndices[i], "#01-" + i);
}
}
/// <summary>
/// Heap sort with increasing double array with lower and upper bound.
/// </summary>
[Test]
public void HeapSortWithIncreasingDoubleArrayWithLowerAndUpperBound()
{
var sortedIndices = new int[10];
var values = new DenseVector(10);
values[0] = 0;
values[1] = 1;
values[2] = 2;
values[3] = 3;
values[4] = 4;
values[5] = 5;
values[6] = 6;
values[7] = 7;
values[8] = 8;
values[9] = 9;
for (var i = 0; i < sortedIndices.Length; i++)
{
sortedIndices[i] = i;
}
ILUTPElementSorter.SortDoubleIndicesDecreasing(2, sortedIndices.Length - 3, sortedIndices, values);
for (var i = 0; i < sortedIndices.Length - 4; i++)
{
Assert.AreEqual(sortedIndices.Length - 3 - i, sortedIndices[i], "#01-" + i);
}
}
}
}
| |
// Copyright 2014 The Rector & Visitors of the University of Virginia
//
// 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 Xamarin.Forms;
using Sensus.UI.UiProperties;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
using Sensus.UI.Inputs;
using Sensus.Probes.User.Scripts;
using Sensus.Exceptions;
using System.ComponentModel;
using static Sensus.UI.InputGroupPage;
using System.Timers;
// register the input effect group
[assembly: ResolutionGroupName(Input.EFFECT_RESOLUTION_GROUP_NAME)]
namespace Sensus.UI.Inputs
{
public abstract class Input : INotifyPropertyChanged
{
private const double PROGRESS_INCREMENT = 0.005;
public event PropertyChangedEventHandler PropertyChanged;
public const string EFFECT_RESOLUTION_GROUP_NAME = "InputEffects";
private string _name;
private string _id;
private string _groupId;
private string _labelText;
private int _labelFontSize;
private View _view;
private bool _displayNumber;
private bool _complete;
private double? _latitude;
private double? _longitude;
private DateTimeOffset? _locationUpdateTimestamp;
private bool _required;
private bool _viewed;
private DateTimeOffset? _completionTimestamp;
private List<InputDisplayCondition> _displayConditions;
private Color? _backgroundColor;
private Thickness? _padding;
private bool _frame;
private List<InputCompletionRecord> _completionRecords;
private DateTimeOffset? _submissionTimestamp;
private bool _correct;
private int _attempts;
protected float _score;
private InputFeedbackView _feedbackView;
private Timer _delayTimer;
private bool _enabled;
public InputGroupPage InputGroupPage { get; set; }
/// <summary>
/// The name by which this input will be referred to within the Sensus app.
/// </summary>
/// <value>The name.</value>
[EntryStringUiProperty("Name:", true, 0, true)]
public string Name
{
get { return _name; }
set
{
if (value != _name)
{
_name = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Caption)));
}
}
}
public string Id
{
get
{
return _id;
}
set
{
_id = value;
}
}
public string GroupId
{
get
{
return _groupId;
}
set
{
_groupId = value;
}
}
/// <summary>
/// The text to display next to the input when showing the field to the user for completion. If you would like to
/// use the value of a survey-triggering <see cref="Script.CurrentDatum"/> within the input's label, you can do so
/// by placing a <c>{0}</c> within <see cref="LabelText"/> as a placeholder. The placeholder will be replaced with
/// the value of the triggering <see cref="Datum"/> at runtime. You can read more about the format of the
/// placeholder [here](https://msdn.microsoft.com/en-us/library/system.string.format(v=vs.110).aspx).
/// </summary>
/// <value>The label text.</value>
[EntryStringUiProperty("Label Text:", true, 1, true)]
public string LabelText
{
get
{
return _labelText;
}
set
{
_labelText = value;
}
}
[OnOffUiProperty("Label Text is HTML:", true, 2)]
public bool IsLabelTextHtml { get; set; }
[EntryIntegerUiProperty("Label Font Size:", true, 3, false)]
public int LabelFontSize
{
get
{
return _labelFontSize;
}
set
{
_labelFontSize = value;
}
}
[EntryStringUiProperty("Label Text Color:", true, 4, false)]
public string SerializableLabelTextColor { get; set; }
[JsonIgnore]
public Color? LabelTextColor
{
get
{
if (string.IsNullOrWhiteSpace(SerializableLabelTextColor) == false)
{
return Color.FromHex(SerializableLabelTextColor);
}
return null;
}
set
{
if (value != null)
{
SerializableLabelTextColor = value.Value.ToHex();
}
else
{
SerializableLabelTextColor = null;
}
}
}
[ListUiProperty("Label Text Attributes:", true, 5, new object[] { FontAttributes.None, FontAttributes.Bold, FontAttributes.Italic }, false)]
public FontAttributes LabelFontAttributes { get; set; }
[ListUiProperty("Label Text Alignment:", true, 6, new object[] { TextAlignment.Start, TextAlignment.Center, TextAlignment.End }, false)]
public TextAlignment LabelTextAlignment { get; set; }
public bool DisplayNumber
{
get
{
return _displayNumber;
}
set
{
_displayNumber = value;
}
}
/// <summary>
/// The value that needs to be provided for the input to be considered correct.
/// </summary>
/// <value>Any string, or a Protocol variable name prefixed with an =, e.g. =SomeVariable.</value>
[EntryStringUiProperty("Correct Value:", true, 20, false)]
public virtual object CorrectValue { get; set; }
/// <summary>
/// Set whether a correct value is required to mark the <see cref="Input"/> complete.
/// </summary>
/// <value>Any string, or a Protocol variable name prefixed with an =, e.g. =SomeVariable.</value>
[OnOffUiProperty("Require Correct Value:", true, 21)]
public virtual bool RequireCorrectValue { get; set; }
/// <summary>
/// The delay in milliseconds to wait when a correct value is provided before navigating, allowing navigation or allowing the user to retry.
/// </summary>
[EntryIntegerUiProperty("Correct Delay (MS):", true, 22, false)]
public virtual int CorrectDelay { get; set; }
/// <summary>
/// The message to provide as feedback when a correct value is provided.
/// </summary>
[EntryStringUiProperty("Correct Feedback:", true, 23, false)]
public virtual string CorrectFeedbackMessage { get; set; }
/// <summary>
/// The delay in milliseconds to wait when an incorrect value is provided before navigating, allowing navigation or allowing the user to retry.
/// </summary>
[EntryIntegerUiProperty("Incorrect Delay (MS):", true, 24, false)]
public virtual int IncorrectDelay { get; set; }
/// <summary>
/// The message to provide as feedback when an incorrect value is provided.
/// </summary>
[EntryStringUiProperty("Incorrect Feedback:", true, 25, false)]
public virtual string IncorrectFeedbackMessage { get; set; }
/// <summary>
/// The <see cref="NavigationResult"/> that is set for the <see cref="UI.InputGroupPage"/> when the <see cref="Input"/> is set as complete with a correct value.
/// </summary>
[ListUiProperty("Navigate when Correct:", true, 26, new object[] { NavigationResult.None, NavigationResult.Forward, NavigationResult.Backward, NavigationResult.Cancel }, false)]
public NavigationResult NavigationOnCorrect { get; set; }
/// <summary>
/// The <see cref="NavigationResult"/> that is set for the <see cref="UI.InputGroupPage"/> when the <see cref="Input"/> is set as complete with an incorrect value.
/// </summary>
[ListUiProperty("Navigate when Incorrect:", true, 27, new object[] { NavigationResult.None, NavigationResult.Forward, NavigationResult.Backward, NavigationResult.Cancel }, false)]
public NavigationResult NavigationOnIncorrect { get; set; }
/// <summary>
/// The number of times the user can retry the <see cref="Input"/> to get a correct answer or improve their score.
/// </summary>
[EntryIntegerUiProperty("Allowed Retries:", true, 28, false)]
public virtual int? Retries { get; set; }
/// <summary>
/// The number of attempts the user has made to provide the correct value to the <see cref="Input"/>. The input is disabled after (<see cref="Retries"/> + 1) attempts.
/// </summary>
[JsonIgnore]
public int Attempts
{
get
{
return _attempts;
}
set
{
int retries = Math.Max(0, Retries ?? int.MaxValue);
_attempts = value;
// if the maximum number of attempts have been made, then disable the view
if (_attempts >= retries && _view != null)
{
_view.IsEnabled = false;
}
}
}
/// <summary>
/// The score group to associate the <see cref="ScoreInput"/> with the <see cref="Input"/>s it keeps score.
/// A <see cref="ScoreInput"/> with a ScoreGroup of <c>null</c> will accumulate the scores of every
/// <see cref="Input"/> in the collection of <see cref="InputGroup"/>s being displayed.
/// </summary>
[EntryStringUiProperty("Score Group:", true, 29, false)]
public string ScoreGroup { get; set; }
/// <summary>
/// The method used to accumulate the score for the <see cref="Input"/>.
/// </summary>
[ListUiProperty("Score Method:", true, 30, new object[] { ScoreMethods.None, ScoreMethods.First, ScoreMethods.Last, ScoreMethods.Maximum, ScoreMethods.Average }, false)]
public virtual ScoreMethods ScoreMethod { get; set; } = ScoreMethods.Last;
/// <summary>
/// The score that the user will get for providing a correct value.
/// </summary>
/// <value>A positive real number to make the <see cref="Input"/> scored or <c>0</c> to make it unscored.</value>
[EntryFloatUiProperty("Correct Score:", true, 31, false)]
public virtual float CorrectScore { get; set; }
/// <summary>
/// The score that the user will get for providing an incorrect value.
/// </summary>
/// <value>A positive real number to make the <see cref="Input"/> scored or <c>0</c> to make it unscored.</value>
[EntryFloatUiProperty("Incorrect Score:", true, 32, false)]
public virtual float IncorrectScore { get; set; }
[EntryStringUiProperty("Required Group:", true, 33, false)]
public virtual string RequiredGroup { get; set; }
[OnOffUiProperty("Keep Feedback after Delay:", true, 34)]
public virtual bool KeepFeedback { get; set; }
/// <summary>
/// The current score of the <see cref="Input"/>.
/// </summary>
public virtual float Score
{
get
{
return _score;
}
protected set
{
if (_score != value)
{
_score = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Score)));
}
}
}
/// <summary>
/// A boolean value indicating whether the <see cref="Value"/> is equal to <see cref="CorrectValue"/>.
/// </summary>
public bool Correct
{
get
{
return _correct;
}
}
[JsonIgnore]
public abstract object Value { get; }
/// <summary>
/// Gets or sets a value indicating whether the user has interacted with this <see cref="Input"/>,
/// leaving it in a state of completion. Contrast with Valid, which merely indicates that the
/// state of the input will not prevent the user from moving through an input request (e.g., in the case
/// of inputs that are not required).
/// </summary>
/// <value><c>true</c> if complete; otherwise, <c>false</c>.</value>
[JsonIgnore]
public bool Complete
{
get
{
return _complete;
}
protected set
{
_complete = value;
DateTimeOffset timestamp = DateTimeOffset.UtcNow;
object inputValue = null;
_completionTimestamp = null;
_correct = false;
if (_complete)
{
// get a deep copy of the value. some inputs have list values, and simply using the list reference wouldn't track the history, since the most up-to-date list would be used for all history values.
inputValue = JsonConvert.DeserializeObject<object>(JsonConvert.SerializeObject(Value, SensusServiceHelper.JSON_SERIALIZER_SETTINGS), SensusServiceHelper.JSON_SERIALIZER_SETTINGS);
_completionTimestamp = timestamp;
_correct = IsCorrect(inputValue);
if (_correct)
{
SetScore(CorrectScore);
}
else
{
SetScore(IncorrectScore);
}
_feedbackView?.SetFeedback(_correct);
}
if (StoreCompletionRecords)
{
// TODO: determine if completion records need to record whether the input was correct and the correct value.
_completionRecords.Add(new InputCompletionRecord(timestamp, inputValue));
}
// if this input defines a protocol variable, set that variable here.
if (this is IVariableDefiningInput)
{
IVariableDefiningInput input = this as IVariableDefiningInput;
string definedVariable = input.DefinedVariable;
if (definedVariable != null)
{
ScriptRunner runner = GetScriptRunner();
Protocol protocolForInput = runner.Probe.Protocol; // GetProtocol();
if (protocolForInput != null)
{
// if the input is complete, set the variable on the protocol
if (_complete)
{
string variableValue = inputValue.ToString();
protocolForInput.VariableValue[definedVariable] = variableValue;
if (runner.SaveState && runner.SavedState != null)
{
runner.SavedState.Variables[definedVariable] = variableValue;
}
}
// if the input is incomplete, set the value to null on the protocol
else
{
protocolForInput.VariableValue[definedVariable] = null;
if (runner.SaveState && runner.SavedState != null)
{
runner.SavedState.Variables[definedVariable] = null;
}
}
}
}
}
if (_correct)
{
NavigateOrDelay(NavigationOnCorrect, CorrectDelay);
}
else
{
NavigateOrDelay(NavigationOnIncorrect, IncorrectDelay);
}
}
}
protected void SetFeedback(bool isCorrect)
{
if (_feedbackView != null)
{
_feedbackView.SetFeedback(isCorrect);
}
}
/// <summary>
/// Gets a value indicating whether this <see cref="Input"/> is valid. A valid <see cref="Input"/>
/// is one that is complete, one that has been viewed but is not required, or one that isn't
/// displayed. It is an <see cref="Input"/> in a state that should not prevent the user from
/// proceeding through an <see cref="Input"/> request.
/// </summary>
/// <value><c>true</c> if valid; otherwise, <c>false</c>.</value>
[JsonIgnore]
public bool Valid
{
get
{
return (_complete && (_correct || !RequireCorrectValue)) || (_viewed && !_required) || !Display;
}
}
/// <summary>
/// Gets a value indicating whether this <see cref="T:Sensus.UI.Inputs.Input"/> should be stored in the <see cref="LocalDataStore"/>.
/// </summary>
/// <value><c>true</c> if store; otherwise, <c>false</c>.</value>
public virtual bool Store => true;
public double? Latitude
{
get { return _latitude; }
set { _latitude = value; }
}
public double? Longitude
{
get { return _longitude; }
set { _longitude = value; }
}
public DateTimeOffset? LocationUpdateTimestamp
{
get
{
return _locationUpdateTimestamp;
}
set
{
_locationUpdateTimestamp = value;
}
}
[JsonIgnore]
public virtual bool Enabled
{
get
{
return _enabled;
}
set
{
if (_view != null)
{
_view.IsEnabled = value;
}
_enabled = value;
}
}
[JsonIgnore]
public abstract string DefaultName { get; }
/// <summary>
/// Whether or not a valid value is required for this input. Also see <see cref="InputGroup.ForceValidInputs"/>.
/// </summary>
/// <value><c>true</c> if required; otherwise, <c>false</c>.</value>
[OnOffUiProperty(null, true, 5)]
public bool Required
{
get
{
return _required;
}
set
{
if (value != _required)
{
_required = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Caption)));
}
}
}
public bool Viewed
{
get
{
return _viewed;
}
set
{
_viewed = value;
}
}
[JsonIgnore]
public DateTimeOffset? CompletionTimestamp
{
get
{
return _completionTimestamp;
}
}
public List<InputDisplayCondition> DisplayConditions
{
get
{
return _displayConditions;
}
}
public Color? BackgroundColor
{
get
{
return _backgroundColor;
}
set
{
_backgroundColor = value;
}
}
public Thickness? Padding
{
get
{
return _padding;
}
set
{
_padding = value;
}
}
public bool Frame
{
get
{
return _frame;
}
set
{
_frame = value;
}
}
public List<InputCompletionRecord> CompletionRecords
{
get
{
return _completionRecords;
}
}
/// <summary>
/// Whether or not to record a trace of all input values from the first to the final.
/// </summary>
/// <value><c>true</c> if store completion records; otherwise, <c>false</c>.</value>
[OnOffUiProperty("Store Completion Records:", true, 6)]
public bool StoreCompletionRecords
{
get; set;
}
[JsonIgnore]
public bool Display
{
get
{
List<InputDisplayCondition> conjuncts = _displayConditions.Where(displayCondition => displayCondition.Conjunctive).ToList();
if (conjuncts.Count > 0 && conjuncts.Any(displayCondition => !displayCondition.Satisfied))
{
return false;
}
List<InputDisplayCondition> disjuncts = _displayConditions.Where(displayCondition => !displayCondition.Conjunctive).ToList();
if (disjuncts.Count > 0 && disjuncts.All(displayCondition => !displayCondition.Satisfied))
{
return false;
}
return true;
}
}
public DateTimeOffset? SubmissionTimestamp
{
get
{
return _submissionTimestamp;
}
set
{
_submissionTimestamp = value;
}
}
[JsonIgnore]
public string Caption
{
get
{
return _name + (_name == DefaultName ? "" : " -- " + DefaultName) + (_required ? "*" : "");
}
}
/// <summary>
/// Gets or sets the <see cref="Datum"/> that triggered the deployment of this <see cref="Input"/>. This
/// is what will be used when formatting placeholder text in the input <see cref="LabelText"/>.
/// </summary>
/// <value>The triggering datum.</value>
[JsonIgnore]
public Datum TriggeringDatum { get; set; }
protected virtual void SetScore(float score)
{
Attempts += 1;
if (Attempts == 1 && ScoreMethod == ScoreMethods.First)
{
Score = score;
}
else if (ScoreMethod == ScoreMethods.Last)
{
Score = score;
}
else if (ScoreMethod == ScoreMethods.Maximum && (score > Score))
{
Score = score;
}
else if (ScoreMethod == ScoreMethods.Average)
{
Score = ((Score * (Attempts - 1)) + score) / Attempts;
}
}
protected virtual bool IsCorrect(object deserializedValue)
{
if (CorrectValue != null)
{
if (CorrectValue is string stringValue && stringValue.StartsWith("=") && (stringValue.StartsWith("==") == false))
{
Protocol protocol = GetProtocol();
if (protocol.VariableValue.TryGetValue(stringValue.Substring(1), out string value) && CorrectValue.ToString() == value)
{
return true;
}
return false;
}
else if (CorrectValue.ToString() == Value.ToString() || JsonConvert.SerializeObject(CorrectValue) == deserializedValue?.ToString() || CorrectValue.ToString() == deserializedValue?.ToString())
{
return true;
}
return false;
}
return true;
}
protected virtual bool IsCorrect()
{
object inputValue = JsonConvert.DeserializeObject<object>(JsonConvert.SerializeObject(Value, SensusServiceHelper.JSON_SERIALIZER_SETTINGS), SensusServiceHelper.JSON_SERIALIZER_SETTINGS);
return IsCorrect(inputValue);
}
protected virtual void NavigateOrDelay(NavigationResult navigationResult, int delay)
{
if (InputGroupPage != null)
{
if (delay > 0)
{
InputGroupPage.SetNavigationVisibility(this);
_delayTimer?.Dispose();
_delayTimer = new Timer(delay) { AutoReset = false };
_view.IsEnabled = false;
_delayTimer.Elapsed += (o, s) =>
{
_view.IsEnabled = true;
if (navigationResult != NavigationResult.None)
{
InputGroupPage.Navigate(this, navigationResult);
}
InputGroupPage.SetNavigationVisibility(this);
};
_delayTimer.Start();
}
else
{
if (navigationResult != NavigationResult.None)
{
InputGroupPage.Navigate(this, navigationResult);
}
InputGroupPage.SetNavigationVisibility(this);
}
}
}
public Input()
{
_name = DefaultName;
_id = Guid.NewGuid().ToString();
_displayNumber = true;
_complete = false;
_required = true;
_viewed = false;
_completionTimestamp = null;
_labelFontSize = 20;
_displayConditions = new List<InputDisplayCondition>();
_backgroundColor = null;
_padding = null;
_frame = true;
_completionRecords = new List<InputCompletionRecord>();
_submissionTimestamp = null;
_enabled = true;
StoreCompletionRecords = true;
}
public Input(string labelText)
: this()
{
_labelText = labelText;
}
public Input(string labelText, int labelFontSize)
: this(labelText)
{
_labelFontSize = labelFontSize;
}
public Input(string labelText, string name)
: this(labelText)
{
_name = name;
}
protected Label CreateLabel(int index)
{
if (string.IsNullOrEmpty(LabelText))
{
return new Label { IsVisible = false };
}
Label label = new Label
{
StyleClass = new List<string> { "InputLabel" },
Text = GetLabelText(index),
FontSize = _labelFontSize,
FontAttributes = LabelFontAttributes,
HorizontalTextAlignment = LabelTextAlignment,
// set the style ID on the label so that we can retrieve it when UI testing
#if UI_TESTING
, StyleId = Name + " Label"
#endif
};
if (IsLabelTextHtml)
{
label.TextType = TextType.Html;
}
if (LabelTextColor != null && LabelTextColor != Color.Default)
{
label.TextColor = LabelTextColor.Value;
}
return label;
}
protected string GetLabelText(int index)
{
if (string.IsNullOrWhiteSpace(_labelText))
{
return "";
}
else
{
string requiredStr = _required ? "*" : "";
string indexStr = index > 0 && _displayNumber ? index + ") " : "";
string labelTextStr = _labelText;
// get the protocol that contains the current input in a script runner (if any)
Protocol protocolForInput = GetProtocol();
if (protocolForInput != null)
{
// replace all variable references in the input label text with the variables' values
foreach (string variable in protocolForInput.VariableValue.Keys)
{
// get the value for the variable as defined on the protocol
string variableValue = protocolForInput.VariableValue[variable];
// if the variable's value has not been defined, then just use the variable name as a fallback.
if (variableValue == null)
{
variableValue = variable;
}
// replace variable references with its value
labelTextStr = labelTextStr.Replace("{" + variable + "}", variableValue);
}
}
// if this input is being shown as part of a datum-triggered script, format the label
// text of the input to replace any {0} references with the triggering datum's placeholder
// value.
if (TriggeringDatum != null)
{
labelTextStr = string.Format(labelTextStr, TriggeringDatum.StringPlaceholderValue.ToString().ToLower());
}
return requiredStr + indexStr + labelTextStr;
}
}
/// <summary>
/// Gets the <see cref="Protocol"/> containing the current input.
/// </summary>
/// <returns>The <see cref="Protocol"/>.</returns>
private Protocol GetProtocol()
{
try
{
return SensusServiceHelper.Get().RegisteredProtocols.SingleOrDefault(protocol => protocol.Probes.OfType<ScriptProbe>() // get script probes
.Single() // must be only 1 script probe
.ScriptRunners // get runners
.SelectMany(runner => runner.Script.InputGroups) // get input groups for each runner
.SelectMany(inputGroup => inputGroup.Inputs) // get inputs for each input group
.Any(input => input.Id == _id)); // check if any inputs are the current one. must check ids rather than object references, as we make deep copies of inputs when instantiating scripts to run.
}
catch (Exception ex)
{
// there is only one known situation in which multiple protocols may contain inputs with the same
// ids: when the user manually set the protocol id and loads both protocols (one with the original
// id and one with the new id. when manually setting the protocol id, any script inputs do not receive
// a new id. this is by design in the use case where authentication servers wish to push out an updated
// protocol.
SensusServiceHelper.Get().Logger.Log("Exception while getting protocol for input: " + ex.Message, LoggingLevel.Normal, GetType());
return null;
}
}
/// <summary>
/// Gets the <see cref="ScriptRunner"/> containing the current input.
/// </summary>
/// <returns>The <see cref="ScriptRunner"/>.</returns>
private ScriptRunner GetScriptRunner()
{
try
{
return SensusServiceHelper.Get().RegisteredProtocols.SelectMany(protocol => protocol.Probes.OfType<ScriptProbe>()) // get script probes
.Single() // must be only 1 script probe
.ScriptRunners // get runners
.First(runner => runner.Script.InputGroups // get input groups for each runner
.SelectMany(inputGroup => inputGroup.Inputs) // get inputs for each input group
.Any(input => input.Id == _id)); // check if any inputs are the current one. must check ids rather than object references, as we make deep copies of inputs when instantiating scripts to run.
}
catch (Exception ex)
{
// there is only one known situation in which multiple protocols may contain inputs with the same
// ids: when the user manually set the protocol id and loads both protocols (one with the original
// id and one with the new id. when manually setting the protocol id, any script inputs do not receive
// a new id. this is by design in the use case where authentication servers wish to push out an updated
// protocol.
SensusServiceHelper.Get().Logger.Log("Exception while getting script runner for input: " + ex.Message, LoggingLevel.Normal, GetType());
return null;
}
}
public virtual View GetView(int index)
{
if (_view != null)
{
_view.IsEnabled = _enabled;
}
return _view;
}
[JsonIgnore]
public EventHandler<FeedbackEventArgs> DelayStarted { get; set; }
[JsonIgnore]
public EventHandler<FeedbackEventArgs> DelayEnded { get; set; }
protected virtual void SetView(View value)
{
View view = value;
if (CorrectDelay > 0 || IncorrectDelay > 0 || string.IsNullOrWhiteSpace(CorrectFeedbackMessage) == false || string.IsNullOrWhiteSpace(IncorrectFeedbackMessage) == false)
{
_feedbackView = new InputFeedbackView(PROGRESS_INCREMENT, CorrectFeedbackMessage, CorrectDelay, IncorrectFeedbackMessage, IncorrectDelay, KeepFeedback, DelayStarted, DelayEnded);
view = new StackLayout()
{
Children = { value, _feedbackView }
};
}
ContentView viewContainer = new ContentView
{
Content = view
};
if (_backgroundColor != null)
{
viewContainer.BackgroundColor = _backgroundColor.GetValueOrDefault();
}
if (_padding != null)
{
viewContainer.Padding = _padding.GetValueOrDefault();
}
_view = viewContainer;
}
public virtual void Reset()
{
_view = null;
_complete = false;
_latitude = null;
_longitude = null;
_locationUpdateTimestamp = null;
_viewed = false;
_completionTimestamp = null;
_backgroundColor = null;
_padding = null;
_attempts = 0;
Score = 0;
_feedbackView?.Reset();
}
public virtual void OnDisappearing(NavigationResult result)
{
_delayTimer?.Dispose();
}
public virtual bool ValueMatches(object conditionValue, bool conjunctive)
{
// if either is null, both must be null to be equal
if (Value == null || conditionValue == null)
{
return Value == null && conditionValue == null;
}
// if they're of the same type, compare
else if (Value.GetType().Equals(conditionValue.GetType()))
{
return Value.Equals(conditionValue);
}
else
{
// this should never happen
SensusException.Report(new Exception("Called Input.ValueMatches with conditionValue of type " + conditionValue.GetType() + ". Comparing with value of type " + Value.GetType() + "."));
return false;
}
}
public Input Copy(bool newId)
{
Input copy = JsonConvert.DeserializeObject<Input>(JsonConvert.SerializeObject(this, SensusServiceHelper.JSON_SERIALIZER_SETTINGS), SensusServiceHelper.JSON_SERIALIZER_SETTINGS);
copy.Reset();
// the reset on the previous line only resets the state of the input. it does not assign it a new/unique ID, which all inputs normally require.
if (newId)
{
copy.Id = Guid.NewGuid().ToString();
}
return copy;
}
/// <summary>
/// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:Sensus.UI.Inputs.Input"/>. This is needed
/// when adding display conditions.
/// </summary>
/// <returns>A <see cref="T:System.String"/> that represents the current <see cref="T:Sensus.UI.Inputs.Input"/>.</returns>
public override string ToString()
{
return _name;
}
}
}
| |
// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Analysis.Util;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Search;
using Lucene.Net.Util;
using NUnit.Framework;
namespace Lucene.Net.Analysis.Shingle
{
/*
* 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.
*/
/// <summary>
/// A test class for ShingleAnalyzerWrapper as regards queries and scoring.
/// </summary>
public class ShingleAnalyzerWrapperTest : BaseTokenStreamTestCase
{
private Analyzer analyzer;
private IndexSearcher searcher;
private IndexReader reader;
private Store.Directory directory;
/// <summary>
/// Set up a new index in RAM with three test phrases and the supplied Analyzer.
/// </summary>
/// <exception cref="Exception"> if an error occurs with index writer or searcher </exception>
public override void SetUp()
{
base.SetUp();
analyzer = new ShingleAnalyzerWrapper(new MockAnalyzer(Random, MockTokenizer.WHITESPACE, false), 2);
directory = NewDirectory();
IndexWriter writer = new IndexWriter(directory, new IndexWriterConfig(TEST_VERSION_CURRENT, analyzer));
Document doc;
doc = new Document();
doc.Add(new TextField("content", "please divide this sentence into shingles", Field.Store.YES));
writer.AddDocument(doc);
doc = new Document();
doc.Add(new TextField("content", "just another test sentence", Field.Store.YES));
writer.AddDocument(doc);
doc = new Document();
doc.Add(new TextField("content", "a sentence which contains no test", Field.Store.YES));
writer.AddDocument(doc);
writer.Dispose();
reader = DirectoryReader.Open(directory);
searcher = NewSearcher(reader);
}
public override void TearDown()
{
reader.Dispose();
directory.Dispose();
base.TearDown();
}
protected internal virtual void CompareRanks(ScoreDoc[] hits, int[] ranks)
{
assertEquals(ranks.Length, hits.Length);
for (int i = 0; i < ranks.Length; i++)
{
assertEquals(ranks[i], hits[i].Doc);
}
}
/*
* This shows how to construct a phrase query containing shingles.
*/
[Test]
public virtual void TestShingleAnalyzerWrapperPhraseQuery()
{
PhraseQuery q = new PhraseQuery();
TokenStream ts = analyzer.GetTokenStream("content", "this sentence");
try
{
int j = -1;
IPositionIncrementAttribute posIncrAtt = ts.AddAttribute<IPositionIncrementAttribute>();
ICharTermAttribute termAtt = ts.AddAttribute<ICharTermAttribute>();
ts.Reset();
while (ts.IncrementToken())
{
j += posIncrAtt.PositionIncrement;
string termText = termAtt.ToString();
q.Add(new Term("content", termText), j);
}
ts.End();
}
finally
{
IOUtils.DisposeWhileHandlingException(ts);
}
ScoreDoc[] hits = searcher.Search(q, null, 1000).ScoreDocs;
int[] ranks = new int[] { 0 };
CompareRanks(hits, ranks);
}
/*
* How to construct a boolean query with shingles. A query like this will
* implicitly score those documents higher that contain the words in the query
* in the right order and adjacent to each other.
*/
[Test]
public virtual void TestShingleAnalyzerWrapperBooleanQuery()
{
BooleanQuery q = new BooleanQuery();
TokenStream ts = analyzer.GetTokenStream("content", "test sentence");
try
{
ICharTermAttribute termAtt = ts.AddAttribute<ICharTermAttribute>();
ts.Reset();
while (ts.IncrementToken())
{
string termText = termAtt.ToString();
q.Add(new TermQuery(new Term("content", termText)), Occur.SHOULD);
}
ts.End();
}
finally
{
IOUtils.DisposeWhileHandlingException(ts);
}
ScoreDoc[] hits = searcher.Search(q, null, 1000).ScoreDocs;
int[] ranks = new int[] { 1, 2, 0 };
CompareRanks(hits, ranks);
}
[Test]
public virtual void TestReusableTokenStream()
{
Analyzer a = new ShingleAnalyzerWrapper(new MockAnalyzer(Random, MockTokenizer.WHITESPACE, false), 2);
AssertAnalyzesTo(a, "please divide into shingles", new string[] { "please", "please divide", "divide", "divide into", "into", "into shingles", "shingles" }, new int[] { 0, 0, 7, 7, 14, 14, 19 }, new int[] { 6, 13, 13, 18, 18, 27, 27 }, new int[] { 1, 0, 1, 0, 1, 0, 1 });
AssertAnalyzesTo(a, "divide me up again", new string[] { "divide", "divide me", "me", "me up", "up", "up again", "again" }, new int[] { 0, 0, 7, 7, 10, 10, 13 }, new int[] { 6, 9, 9, 12, 12, 18, 18 }, new int[] { 1, 0, 1, 0, 1, 0, 1 });
}
[Test]
public virtual void TestNonDefaultMinShingleSize()
{
ShingleAnalyzerWrapper analyzer = new ShingleAnalyzerWrapper(new MockAnalyzer(Random, MockTokenizer.WHITESPACE, false), 3, 4);
AssertAnalyzesTo(analyzer, "please divide this sentence into shingles", new string[] { "please", "please divide this", "please divide this sentence", "divide", "divide this sentence", "divide this sentence into", "this", "this sentence into", "this sentence into shingles", "sentence", "sentence into shingles", "into", "shingles" }, new int[] { 0, 0, 0, 7, 7, 7, 14, 14, 14, 19, 19, 28, 33 }, new int[] { 6, 18, 27, 13, 27, 32, 18, 32, 41, 27, 41, 32, 41 }, new int[] { 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1 });
analyzer = new ShingleAnalyzerWrapper(new MockAnalyzer(Random, MockTokenizer.WHITESPACE, false), 3, 4, ShingleFilter.DEFAULT_TOKEN_SEPARATOR, false, false, ShingleFilter.DEFAULT_FILLER_TOKEN);
AssertAnalyzesTo(analyzer, "please divide this sentence into shingles", new string[] { "please divide this", "please divide this sentence", "divide this sentence", "divide this sentence into", "this sentence into", "this sentence into shingles", "sentence into shingles" }, new int[] { 0, 0, 7, 7, 14, 14, 19 }, new int[] { 18, 27, 27, 32, 32, 41, 41 }, new int[] { 1, 0, 1, 0, 1, 0, 1 });
}
[Test]
public virtual void TestNonDefaultMinAndSameMaxShingleSize()
{
ShingleAnalyzerWrapper analyzer = new ShingleAnalyzerWrapper(new MockAnalyzer(Random, MockTokenizer.WHITESPACE, false), 3, 3);
AssertAnalyzesTo(analyzer, "please divide this sentence into shingles", new string[] { "please", "please divide this", "divide", "divide this sentence", "this", "this sentence into", "sentence", "sentence into shingles", "into", "shingles" }, new int[] { 0, 0, 7, 7, 14, 14, 19, 19, 28, 33 }, new int[] { 6, 18, 13, 27, 18, 32, 27, 41, 32, 41 }, new int[] { 1, 0, 1, 0, 1, 0, 1, 0, 1, 1 });
analyzer = new ShingleAnalyzerWrapper(new MockAnalyzer(Random, MockTokenizer.WHITESPACE, false), 3, 3, ShingleFilter.DEFAULT_TOKEN_SEPARATOR, false, false, ShingleFilter.DEFAULT_FILLER_TOKEN);
AssertAnalyzesTo(analyzer, "please divide this sentence into shingles", new string[] { "please divide this", "divide this sentence", "this sentence into", "sentence into shingles" }, new int[] { 0, 7, 14, 19 }, new int[] { 18, 27, 32, 41 }, new int[] { 1, 1, 1, 1 });
}
[Test]
public virtual void TestNoTokenSeparator()
{
ShingleAnalyzerWrapper analyzer = new ShingleAnalyzerWrapper(new MockAnalyzer(Random, MockTokenizer.WHITESPACE, false), ShingleFilter.DEFAULT_MIN_SHINGLE_SIZE, ShingleFilter.DEFAULT_MAX_SHINGLE_SIZE, "", true, false, ShingleFilter.DEFAULT_FILLER_TOKEN);
AssertAnalyzesTo(analyzer, "please divide into shingles", new string[] { "please", "pleasedivide", "divide", "divideinto", "into", "intoshingles", "shingles" }, new int[] { 0, 0, 7, 7, 14, 14, 19 }, new int[] { 6, 13, 13, 18, 18, 27, 27 }, new int[] { 1, 0, 1, 0, 1, 0, 1 });
analyzer = new ShingleAnalyzerWrapper(new MockAnalyzer(Random, MockTokenizer.WHITESPACE, false), ShingleFilter.DEFAULT_MIN_SHINGLE_SIZE, ShingleFilter.DEFAULT_MAX_SHINGLE_SIZE, "", false, false, ShingleFilter.DEFAULT_FILLER_TOKEN);
AssertAnalyzesTo(analyzer, "please divide into shingles", new string[] { "pleasedivide", "divideinto", "intoshingles" }, new int[] { 0, 7, 14 }, new int[] { 13, 18, 27 }, new int[] { 1, 1, 1 });
}
[Test]
public virtual void TestNullTokenSeparator()
{
ShingleAnalyzerWrapper analyzer = new ShingleAnalyzerWrapper(new MockAnalyzer(Random, MockTokenizer.WHITESPACE, false), ShingleFilter.DEFAULT_MIN_SHINGLE_SIZE, ShingleFilter.DEFAULT_MAX_SHINGLE_SIZE, null, true, false, ShingleFilter.DEFAULT_FILLER_TOKEN);
AssertAnalyzesTo(analyzer, "please divide into shingles", new string[] { "please", "pleasedivide", "divide", "divideinto", "into", "intoshingles", "shingles" }, new int[] { 0, 0, 7, 7, 14, 14, 19 }, new int[] { 6, 13, 13, 18, 18, 27, 27 }, new int[] { 1, 0, 1, 0, 1, 0, 1 });
analyzer = new ShingleAnalyzerWrapper(new MockAnalyzer(Random, MockTokenizer.WHITESPACE, false), ShingleFilter.DEFAULT_MIN_SHINGLE_SIZE, ShingleFilter.DEFAULT_MAX_SHINGLE_SIZE, "", false, false, ShingleFilter.DEFAULT_FILLER_TOKEN);
AssertAnalyzesTo(analyzer, "please divide into shingles", new string[] { "pleasedivide", "divideinto", "intoshingles" }, new int[] { 0, 7, 14 }, new int[] { 13, 18, 27 }, new int[] { 1, 1, 1 });
}
[Test]
public virtual void TestAltTokenSeparator()
{
ShingleAnalyzerWrapper analyzer = new ShingleAnalyzerWrapper(new MockAnalyzer(Random, MockTokenizer.WHITESPACE, false), ShingleFilter.DEFAULT_MIN_SHINGLE_SIZE, ShingleFilter.DEFAULT_MAX_SHINGLE_SIZE, "<SEP>", true, false, ShingleFilter.DEFAULT_FILLER_TOKEN);
AssertAnalyzesTo(analyzer, "please divide into shingles", new string[] { "please", "please<SEP>divide", "divide", "divide<SEP>into", "into", "into<SEP>shingles", "shingles" }, new int[] { 0, 0, 7, 7, 14, 14, 19 }, new int[] { 6, 13, 13, 18, 18, 27, 27 }, new int[] { 1, 0, 1, 0, 1, 0, 1 });
analyzer = new ShingleAnalyzerWrapper(new MockAnalyzer(Random, MockTokenizer.WHITESPACE, false), ShingleFilter.DEFAULT_MIN_SHINGLE_SIZE, ShingleFilter.DEFAULT_MAX_SHINGLE_SIZE, "<SEP>", false, false, ShingleFilter.DEFAULT_FILLER_TOKEN);
AssertAnalyzesTo(analyzer, "please divide into shingles", new string[] { "please<SEP>divide", "divide<SEP>into", "into<SEP>shingles" }, new int[] { 0, 7, 14 }, new int[] { 13, 18, 27 }, new int[] { 1, 1, 1 });
}
[Test]
public virtual void TestAltFillerToken()
{
Analyzer @delegate = Analyzer.NewAnonymous(createComponents: (fieldName, reader) =>
{
CharArraySet stopSet = StopFilter.MakeStopSet(TEST_VERSION_CURRENT, "into");
Tokenizer tokenizer = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false);
TokenFilter filter = new StopFilter(TEST_VERSION_CURRENT, tokenizer, stopSet);
return new TokenStreamComponents(tokenizer, filter);
});
ShingleAnalyzerWrapper analyzer = new ShingleAnalyzerWrapper(@delegate, ShingleFilter.DEFAULT_MIN_SHINGLE_SIZE, ShingleFilter.DEFAULT_MAX_SHINGLE_SIZE, ShingleFilter.DEFAULT_TOKEN_SEPARATOR, true, false, "--");
AssertAnalyzesTo(analyzer, "please divide into shingles", new string[] { "please", "please divide", "divide", "divide --", "-- shingles", "shingles" }, new int[] { 0, 0, 7, 7, 19, 19 }, new int[] { 6, 13, 13, 19, 27, 27 }, new int[] { 1, 0, 1, 0, 1, 1 });
analyzer = new ShingleAnalyzerWrapper(@delegate, ShingleFilter.DEFAULT_MIN_SHINGLE_SIZE, ShingleFilter.DEFAULT_MAX_SHINGLE_SIZE, ShingleFilter.DEFAULT_TOKEN_SEPARATOR, false, false, null);
AssertAnalyzesTo(analyzer, "please divide into shingles", new string[] { "please divide", "divide ", " shingles" }, new int[] { 0, 7, 19 }, new int[] { 13, 19, 27 }, new int[] { 1, 1, 1 });
analyzer = new ShingleAnalyzerWrapper(@delegate, ShingleFilter.DEFAULT_MIN_SHINGLE_SIZE, ShingleFilter.DEFAULT_MAX_SHINGLE_SIZE, ShingleFilter.DEFAULT_TOKEN_SEPARATOR, false, false, "");
AssertAnalyzesTo(analyzer, "please divide into shingles", new string[] { "please divide", "divide ", " shingles" }, new int[] { 0, 7, 19 }, new int[] { 13, 19, 27 }, new int[] { 1, 1, 1 });
}
[Test]
public virtual void TestOutputUnigramsIfNoShinglesSingleToken()
{
ShingleAnalyzerWrapper analyzer = new ShingleAnalyzerWrapper(new MockAnalyzer(Random, MockTokenizer.WHITESPACE, false), ShingleFilter.DEFAULT_MIN_SHINGLE_SIZE, ShingleFilter.DEFAULT_MAX_SHINGLE_SIZE, "", false, true, ShingleFilter.DEFAULT_FILLER_TOKEN);
AssertAnalyzesTo(analyzer, "please", new string[] { "please" }, new int[] { 0 }, new int[] { 6 }, new int[] { 1 });
}
}
}
| |
using PlayFab.ClientModels;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ItemViewerController : MonoBehaviour
{
public Image CurrentIcon;
public Text CurrentItemName;
public Text CurrentItemDesc;
public Text ItemCount;
public UnlockSliderController slider;
public Text ContainerItemDesc;
public Button CloseButton;
public Button NextItemButton;
public Button PrevItemButton;
public List<CatalogItem> pfItems = new List<CatalogItem>();
public CatalogItem selectedItem;
private int selectedIndex = 0;
private string currentIconId = string.Empty;
// MAKE THIS index / List<ContainerResultItem>
public Dictionary<int, List<ContainerResultItem>> openedBoxes = new Dictionary<int, List<ContainerResultItem>>();
public Transform itemList;
public Transform itemPrefab;
public Transform containerResults;
public Transform ItemMode;
public Transform ContainerMode;
#region standardControls
public void NextItem()
{
var index = selectedIndex;
index++;
if (index + 1 == pfItems.Count)
NextItemButton.interactable = false;
PrevItemButton.interactable = true;
selectedIndex = index;
SetSelectedItem(pfItems[index]);
}
public void PrevItem()
{
int index = selectedIndex;
index--;
if (index == 0)
{
PrevItemButton.interactable = false;
}
NextItemButton.interactable = true;
selectedIndex = index;
SetSelectedItem(pfItems[index]);
}
public void SetSelectedItem(CatalogItem item)
{
selectedItem = item;
CurrentItemName.text = selectedItem.DisplayName;
CurrentItemDesc.text = selectedItem.Description;
ItemCount.text = string.Format("{0}/{1}", selectedIndex + 1, pfItems.Count);
// refresh the UI
currentIconId = PF_GameData.GetIconByItemById(item.ItemId);
var icon = GameController.Instance.iconManager.GetIconById(currentIconId, IconManager.IconTypes.Item);
CurrentIcon.overrideSprite = icon;
if (openedBoxes.ContainsKey(selectedIndex))
{
// this container has been opened, show the items...
if (PF_GameData.IsContainer(selectedItem.ItemId))
CurrentIcon.overrideSprite = GameController.Instance.iconManager.GetIconById(currentIconId + "_Open", IconManager.IconTypes.Item);
EnableContainerMode(true);
return;
}
// test bundles here....
// if bundle, we need to show the contents, but not remove it from the list, as it will be unpacked and added automatically
if (selectedItem.Bundle != null && (selectedItem.Bundle.BundledItems != null || selectedItem.Bundle.BundledResultTables != null || selectedItem.Bundle.BundledVirtualCurrencies != null))
{
var bundleItems = new List<ContainerResultItem>();
if (selectedItem.Bundle.BundledItems != null && selectedItem.Bundle.BundledItems.Count > 0)
{
foreach (var award in selectedItem.Bundle.BundledItems)
{
var catalogItem = PF_GameData.GetCatalogItemById(award);
var awardIcon = PF_GameData.GetIconByItemById(award);
bundleItems.Add(new ContainerResultItem
{
displayIcon = GameController.Instance.iconManager.GetIconById(awardIcon, IconManager.IconTypes.Item),
displayName = catalogItem.DisplayName
});
}
}
if (selectedItem.Bundle.BundledResultTables != null && selectedItem.Bundle.BundledResultTables.Count > 0)
{
foreach (var award in selectedItem.Bundle.BundledResultTables)
{
bundleItems.Add(new ContainerResultItem
{
displayIcon = GameController.Instance.iconManager.GetIconById("DropTable", IconManager.IconTypes.Misc),
displayName = string.Format("Drop Table: {0}", award)
});
}
}
if (selectedItem.Bundle.BundledVirtualCurrencies != null && selectedItem.Bundle.BundledVirtualCurrencies.Count > 0)
{
foreach (var award in selectedItem.Bundle.BundledVirtualCurrencies)
{
bundleItems.Add(new ContainerResultItem
{
displayIcon = GameController.Instance.iconManager.GetIconById(award.Key, IconManager.IconTypes.Item),
displayName = string.Format("{1} Award: {0:n0}", award.Value, award.Key)
});
}
}
if (bundleItems.Count > 0)
{
openedBoxes.Add(selectedIndex, bundleItems);
EnableContainerMode(true);
// dont fall through the rest of the logic.
return;
}
}
if (PF_GameData.IsContainer(selectedItem.ItemId))
EnableContainerMode();
else
DisableContainerMode();
}
public void InitiateViewer(List<string> items) // need a new flag to determine if we should unpack to a player or a character
{
pfItems.Clear();
openedBoxes.Clear();
if (PF_GameData.catalogItems == null || PF_GameData.catalogItems.Count == 0)
return;
foreach (var item in items)
{
var catalogItem = PF_GameData.GetCatalogItemById(item);
if (catalogItem != null)
pfItems.Add(catalogItem);
}
PrevItemButton.interactable = false;
NextItemButton.interactable = pfItems.Count != 1;
//select the first in the list
SetSelectedItem(pfItems[0]);
selectedIndex = 0;
gameObject.SetActive(true);
}
public void CloseViewer()
{
PF_PlayerData.GetUserInventory();
gameObject.SetActive(false);
}
#endregion
public void EnableContainerMode(bool isAlreadyOpen = false)
{
ContainerMode.gameObject.SetActive(true);
ItemMode.gameObject.SetActive(false);
if (isAlreadyOpen)
{
ClearContainerItems();
EnableUnlockedItemsView(openedBoxes[selectedIndex]);
}
else
{
DisableUnlockedItemsView();
ContainerItemDesc.text = selectedItem.Description;
slider.SetupSlider(AfterUnlock);
slider.gameObject.SetActive(true);
}
}
public void DisableContainerMode()
{
ContainerMode.gameObject.SetActive(false);
ItemMode.gameObject.SetActive(true);
//CurrentItemDesc.text = selectedItem.Description;
}
public void AfterUnlock(UnlockContainerItemResult result)
{
// unlocking a container will automatically add the returned items, this ensures that items are not added twice.
PF_GamePlay.QuestProgress.ItemsFound.Remove(selectedItem.ItemId);
// build our list for displaying the container results
List<ContainerResultItem> items = new List<ContainerResultItem>();
foreach (var award in result.GrantedItems)
{
var awardIcon = PF_GameData.GetIconByItemById(award.ItemId);
items.Add(new ContainerResultItem
{
displayIcon = GameController.Instance.iconManager.GetIconById(awardIcon, IconManager.IconTypes.Item),
displayName = award.DisplayName
});
}
if (result.VirtualCurrency != null)
{
foreach (var award in result.VirtualCurrency)
{
string friendlyName;
switch (award.Key)
{
case GlobalStrings.GOLD_CURRENCY: friendlyName = "Gold"; break;
case GlobalStrings.HEART_CURRENCY: friendlyName = "Lives"; break;
case GlobalStrings.GEM_CURRENCY: friendlyName = "Gems"; break;
default: friendlyName = ""; break;
}
items.Add(new ContainerResultItem
{
displayIcon = GameController.Instance.iconManager.GetIconById(award.Key, IconManager.IconTypes.Item),
displayName = award.Value + " " + friendlyName
});
}
}
CurrentIcon.overrideSprite = GameController.Instance.iconManager.GetIconById(currentIconId + "_Open", IconManager.IconTypes.Item);
openedBoxes.Add(selectedIndex, items);
EnableUnlockedItemsView(items);
DialogCanvasController.RequestInventoryPrompt();
}
void EnableUnlockedItemsView(List<ContainerResultItem> unlockedItems = null)
{
ContainerItemDesc.gameObject.SetActive(false);
slider.gameObject.SetActive(false);
containerResults.gameObject.SetActive(true);
foreach (var item in unlockedItems)
{
var slot = Instantiate(itemPrefab);
var cir = slot.GetComponent<ContainerItemResult>();
cir.Icon.overrideSprite = item.displayIcon;
cir.ItemName.text = item.displayName;
slot.SetParent(itemList, false);
}
}
void DisableUnlockedItemsView()
{
ClearContainerItems();
ContainerItemDesc.gameObject.SetActive(true);
containerResults.gameObject.SetActive(false);
}
void ClearContainerItems()
{
ContainerItemResult[] children = itemList.GetComponentsInChildren<ContainerItemResult>(true);
for (int z = 0; z < children.Length; z++)
{
if (children[z].gameObject != itemList.gameObject)
{
DestroyImmediate(children[z].gameObject);
}
}
}
}
public class ContainerResultItem
{
public Sprite displayIcon;
public string displayName;
}
| |
/*
* 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.Data;
using System.Reflection;
using System.Collections.Generic;
#if CSharpSqlite
using Community.CsharpSqlite.Sqlite;
#else
using Mono.Data.Sqlite;
#endif
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
namespace OpenSim.Data.SQLite
{
/// <summary>
/// A SQLite Interface for the Asset Server
/// </summary>
public class SQLiteXInventoryData : IXInventoryData
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private SqliteFolderHandler m_Folders;
private SqliteItemHandler m_Items;
public SQLiteXInventoryData(string conn, string realm)
{
if (Util.IsWindows())
Util.LoadArchSpecificWindowsDll("sqlite3.dll");
m_Folders = new SqliteFolderHandler(
conn, "inventoryfolders", "XInventoryStore");
m_Items = new SqliteItemHandler(
conn, "inventoryitems", String.Empty);
}
public XInventoryFolder[] GetFolders(string[] fields, string[] vals)
{
return m_Folders.Get(fields, vals);
}
public XInventoryItem[] GetItems(string[] fields, string[] vals)
{
return m_Items.Get(fields, vals);
}
public bool StoreFolder(XInventoryFolder folder)
{
if (folder.folderName.Length > 64)
folder.folderName = folder.folderName.Substring(0, 64);
return m_Folders.Store(folder);
}
public bool StoreItem(XInventoryItem item)
{
if (item.inventoryName.Length > 64)
item.inventoryName = item.inventoryName.Substring(0, 64);
if (item.inventoryDescription.Length > 128)
item.inventoryDescription = item.inventoryDescription.Substring(0, 128);
return m_Items.Store(item);
}
public bool DeleteFolders(string field, string val)
{
return m_Folders.Delete(field, val);
}
public bool DeleteFolders(string[] fields, string[] vals)
{
return m_Folders.Delete(fields, vals);
}
public bool DeleteItems(string field, string val)
{
return m_Items.Delete(field, val);
}
public bool DeleteItems(string[] fields, string[] vals)
{
return m_Items.Delete(fields, vals);
}
public bool MoveItem(string id, string newParent)
{
return m_Items.MoveItem(id, newParent);
}
public bool MoveFolder(string id, string newParent)
{
return m_Folders.MoveFolder(id, newParent);
}
public XInventoryItem[] GetActiveGestures(UUID principalID)
{
return m_Items.GetActiveGestures(principalID);
}
public int GetAssetPermissions(UUID principalID, UUID assetID)
{
return m_Items.GetAssetPermissions(principalID, assetID);
}
}
public class SqliteItemHandler : SqliteInventoryHandler<XInventoryItem>
{
public SqliteItemHandler(string c, string t, string m) :
base(c, t, m)
{
}
public override bool Store(XInventoryItem item)
{
if (!base.Store(item))
return false;
IncrementFolderVersion(item.parentFolderID);
return true;
}
public override bool Delete(string field, string val)
{
XInventoryItem[] retrievedItems = Get(new string[] { field }, new string[] { val });
if (retrievedItems.Length == 0)
return false;
if (!base.Delete(field, val))
return false;
// Don't increment folder version here since Delete(string, string) calls Delete(string[], string[])
// IncrementFolderVersion(retrievedItems[0].parentFolderID);
return true;
}
public override bool Delete(string[] fields, string[] vals)
{
XInventoryItem[] retrievedItems = Get(fields, vals);
if (retrievedItems.Length == 0)
return false;
if (!base.Delete(fields, vals))
return false;
HashSet<UUID> deletedItemFolderUUIDs = new HashSet<UUID>();
Array.ForEach<XInventoryItem>(retrievedItems, i => deletedItemFolderUUIDs.Add(i.parentFolderID));
foreach (UUID deletedItemFolderUUID in deletedItemFolderUUIDs)
IncrementFolderVersion(deletedItemFolderUUID);
return true;
}
public bool MoveItem(string id, string newParent)
{
XInventoryItem[] retrievedItems = Get(new string[] { "inventoryID" }, new string[] { id });
if (retrievedItems.Length == 0)
return false;
UUID oldParent = retrievedItems[0].parentFolderID;
using (SqliteCommand cmd = new SqliteCommand())
{
cmd.CommandText = String.Format("update {0} set parentFolderID = :ParentFolderID where inventoryID = :InventoryID", m_Realm);
cmd.Parameters.Add(new SqliteParameter(":ParentFolderID", newParent));
cmd.Parameters.Add(new SqliteParameter(":InventoryID", id));
if (ExecuteNonQuery(cmd, m_Connection) == 0)
return false;
}
IncrementFolderVersion(oldParent);
IncrementFolderVersion(newParent);
return true;
}
public XInventoryItem[] GetActiveGestures(UUID principalID)
{
using (SqliteCommand cmd = new SqliteCommand())
{
cmd.CommandText = String.Format("select * from inventoryitems where avatarId = :uuid and assetType = :type and flags = 1", m_Realm);
cmd.Parameters.Add(new SqliteParameter(":uuid", principalID.ToString()));
cmd.Parameters.Add(new SqliteParameter(":type", (int)AssetType.Gesture));
return DoQuery(cmd);
}
}
public int GetAssetPermissions(UUID principalID, UUID assetID)
{
IDataReader reader;
using (SqliteCommand cmd = new SqliteCommand())
{
cmd.CommandText = String.Format("select inventoryCurrentPermissions from inventoryitems where avatarID = :PrincipalID and assetID = :AssetID", m_Realm);
cmd.Parameters.Add(new SqliteParameter(":PrincipalID", principalID.ToString()));
cmd.Parameters.Add(new SqliteParameter(":AssetID", assetID.ToString()));
reader = ExecuteReader(cmd, m_Connection);
}
int perms = 0;
while (reader.Read())
{
perms |= Convert.ToInt32(reader["inventoryCurrentPermissions"]);
}
reader.Close();
//CloseCommand(cmd);
return perms;
}
}
public class SqliteFolderHandler : SqliteInventoryHandler<XInventoryFolder>
{
public SqliteFolderHandler(string c, string t, string m) :
base(c, t, m)
{
}
public override bool Store(XInventoryFolder folder)
{
if (!base.Store(folder))
return false;
IncrementFolderVersion(folder.parentFolderID);
return true;
}
public bool MoveFolder(string id, string newParentFolderID)
{
XInventoryFolder[] folders = Get(new string[] { "folderID" }, new string[] { id });
if (folders.Length == 0)
return false;
UUID oldParentFolderUUID = folders[0].parentFolderID;
using (SqliteCommand cmd = new SqliteCommand())
{
cmd.CommandText = String.Format("update {0} set parentFolderID = :ParentFolderID where folderID = :FolderID", m_Realm);
cmd.Parameters.Add(new SqliteParameter(":ParentFolderID", newParentFolderID));
cmd.Parameters.Add(new SqliteParameter(":FolderID", id));
if (ExecuteNonQuery(cmd, m_Connection) == 0)
return false;
}
IncrementFolderVersion(oldParentFolderUUID);
IncrementFolderVersion(newParentFolderID);
return true;
}
}
public class SqliteInventoryHandler<T> : SQLiteGenericTableHandler<T> where T: class, new()
{
public SqliteInventoryHandler(string c, string t, string m) : base(c, t, m) {}
protected bool IncrementFolderVersion(UUID folderID)
{
return IncrementFolderVersion(folderID.ToString());
}
protected bool IncrementFolderVersion(string folderID)
{
// m_log.DebugFormat("[MYSQL ITEM HANDLER]: Incrementing version on folder {0}", folderID);
// Util.PrintCallStack();
using (SqliteCommand cmd = new SqliteCommand())
{
cmd.CommandText = "update inventoryfolders set version=version+1 where folderID = ?folderID";
cmd.Parameters.Add(new SqliteParameter(":folderID", folderID));
try
{
cmd.ExecuteNonQuery();
}
catch (Exception)
{
return false;
}
}
return true;
}
}
}
| |
using System;
using System.Data;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using PCSComUtils.PCSExc;
using PCSUtils.Utils;
using PCSUtils.Log;
using PCSUtils.MasterSetup;
using PCSComUtils.Common;
using PCSComUtils.Common.BO;
using PCSComProcurement.Purchase.BO;
using PCSComProcurement.Purchase.DS;
using C1.Win.C1TrueDBGrid;
namespace PCSProcurement.Purchase
{
/// <summary>
/// Summary description for POPurchaseOrderApproval.
/// </summary>
public class POPurchaseOrderApproval : System.Windows.Forms.Form
{
private System.Windows.Forms.Button btnClose;
private System.Windows.Forms.Button btnHelp;
private System.Windows.Forms.Button btnApprove;
#region My variable
const string THIS = "PCSProcurement.Purchase.POPurchaseOrderApproval";
#endregion My variable
private System.Windows.Forms.TextBox txtPONo;
private System.Windows.Forms.Button btnSearch;
private C1.Win.C1TrueDBGrid.C1TrueDBGrid gridApprove;
private const string CHECK_APPROVE = "Approved";
private const string PO_NO = "PONo";
private const string OPEN_AMOUNT = "openAmount";
private const string APPROVED_ID = "ApprovedID";
private DataTable dtbGridLayOut;
private DataSet dstGridData;
private const string AVAILABLE_QUANTITY = "AvailableQty";
private const string CURRENCY = "Currency";
private const string TRUE = "True";
private const string PO_APPROVE_TABLE = "POApprove_Table";
private DataTable dtbSource = new DataTable(GRIDSOURCE);
private const string GRIDSOURCE = "GridSource";
private const string BUYINGUM = "BuyingUM";
private const string V_PO_NOT_APPROVE = "V_PO_NOT_APPROVE";
private const string V_PO_APPROVE = "V_PO_APPROVE";
private bool blnStateOfCheck = false;
private System.Windows.Forms.CheckBox chkSelectAll;
private C1.Win.C1List.C1Combo cboCCN;
private System.Windows.Forms.Button btnPONo;
private System.Windows.Forms.Label lblCCN;
private System.Windows.Forms.Label lblPONo;
private System.Windows.Forms.Label lblApprover;
private System.Windows.Forms.Label lblApprDate;
private System.Windows.Forms.TextBox txtApprover;
private C1.Win.C1Input.C1DateEdit dtmApprDate;
private System.Windows.Forms.Button btnShowDetail;
private System.Windows.Forms.ComboBox cboStatus;
private System.Windows.Forms.Label lblApproved;
private System.Windows.Forms.Label lblNotApproved;
private System.Windows.Forms.Label lblCancelApprove;
private System.Windows.Forms.Label lblCancelDate;
private System.Windows.Forms.Label lblCanceler;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
string strlblApprovalDate, strbtnApprove, strlblApprover;
private System.Windows.Forms.Label lblStatus;
public POPurchaseOrderApproval()
{
//
// 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 );
}
#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.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(POPurchaseOrderApproval));
this.cboCCN = new C1.Win.C1List.C1Combo();
this.lblCCN = new System.Windows.Forms.Label();
this.txtPONo = new System.Windows.Forms.TextBox();
this.btnPONo = new System.Windows.Forms.Button();
this.lblPONo = new System.Windows.Forms.Label();
this.lblApprover = new System.Windows.Forms.Label();
this.chkSelectAll = new System.Windows.Forms.CheckBox();
this.lblApprDate = new System.Windows.Forms.Label();
this.btnApprove = new System.Windows.Forms.Button();
this.btnClose = new System.Windows.Forms.Button();
this.btnHelp = new System.Windows.Forms.Button();
this.gridApprove = new C1.Win.C1TrueDBGrid.C1TrueDBGrid();
this.btnSearch = new System.Windows.Forms.Button();
this.txtApprover = new System.Windows.Forms.TextBox();
this.dtmApprDate = new C1.Win.C1Input.C1DateEdit();
this.btnShowDetail = new System.Windows.Forms.Button();
this.lblStatus = new System.Windows.Forms.Label();
this.cboStatus = new System.Windows.Forms.ComboBox();
this.lblApproved = new System.Windows.Forms.Label();
this.lblNotApproved = new System.Windows.Forms.Label();
this.lblCancelApprove = new System.Windows.Forms.Label();
this.lblCancelDate = new System.Windows.Forms.Label();
this.lblCanceler = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.cboCCN)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.gridApprove)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.dtmApprDate)).BeginInit();
this.SuspendLayout();
//
// cboCCN
//
this.cboCCN.AddItemSeparator = ';';
this.cboCCN.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.cboCCN.Caption = "";
this.cboCCN.CaptionHeight = 17;
this.cboCCN.CharacterCasing = System.Windows.Forms.CharacterCasing.Normal;
this.cboCCN.ColumnCaptionHeight = 17;
this.cboCCN.ColumnFooterHeight = 17;
this.cboCCN.ComboStyle = C1.Win.C1List.ComboStyleEnum.DropdownList;
this.cboCCN.ContentHeight = 15;
this.cboCCN.DeadAreaBackColor = System.Drawing.Color.Empty;
this.cboCCN.EditorBackColor = System.Drawing.SystemColors.Window;
this.cboCCN.EditorFont = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.cboCCN.EditorForeColor = System.Drawing.SystemColors.WindowText;
this.cboCCN.EditorHeight = 15;
this.cboCCN.FlatStyle = C1.Win.C1List.FlatModeEnum.System;
this.cboCCN.GapHeight = 2;
this.cboCCN.ItemHeight = 15;
this.cboCCN.Location = new System.Drawing.Point(550, 6);
this.cboCCN.MatchEntryTimeout = ((long)(2000));
this.cboCCN.MaxDropDownItems = ((short)(5));
this.cboCCN.MaxLength = 32767;
this.cboCCN.MouseCursor = System.Windows.Forms.Cursors.Default;
this.cboCCN.Name = "cboCCN";
this.cboCCN.RowDivider.Color = System.Drawing.Color.DarkGray;
this.cboCCN.RowDivider.Style = C1.Win.C1List.LineStyleEnum.None;
this.cboCCN.RowSubDividerColor = System.Drawing.Color.DarkGray;
this.cboCCN.Size = new System.Drawing.Size(80, 21);
this.cboCCN.TabIndex = 1;
this.cboCCN.Text = "CCN";
this.cboCCN.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this.cboCCN.Enter += new System.EventHandler(this.OnEnterControl);
this.cboCCN.Leave += new System.EventHandler(this.OnLeaveControl);
this.cboCCN.PropBag = "<?xml version=\"1.0\"?><Blob><Styles type=\"C1.Win.C1List.Design.ContextWrapper\"><Da" +
"ta>Group{AlignVert:Center;Border:None,,0, 0, 0, 0;BackColor:ControlDark;}Style2{" +
"}Style5{}Style4{}Style7{}Style6{}EvenRow{BackColor:Aqua;}Selected{ForeColor:High" +
"lightText;BackColor:Highlight;}Style3{}Inactive{ForeColor:InactiveCaptionText;Ba" +
"ckColor:InactiveCaption;}Footer{}Caption{AlignHorz:Center;}Normal{BackColor:Wind" +
"ow;}HighlightRow{ForeColor:HighlightText;BackColor:Highlight;}Style1{}OddRow{}Re" +
"cordSelector{AlignImage:Center;}Heading{Wrap:True;BackColor:Control;Border:Raise" +
"d,,1, 1, 1, 1;ForeColor:ControlText;AlignVert:Center;}Style8{}Style10{}Style11{}" +
"Style9{AlignHorz:Near;}</Data></Styles><Splits><C1.Win.C1List.ListBoxView AllowC" +
"olSelect=\"False\" Name=\"\" CaptionHeight=\"17\" ColumnCaptionHeight=\"17\" ColumnFoote" +
"rHeight=\"17\" VerticalScrollGroup=\"1\" HorizontalScrollGroup=\"1\"><ClientRect>0, 0," +
" 118, 158</ClientRect><VScrollBar><Width>16</Width></VScrollBar><HScrollBar><Hei" +
"ght>16</Height></HScrollBar><CaptionStyle parent=\"Style2\" me=\"Style9\" /><EvenRow" +
"Style parent=\"EvenRow\" me=\"Style7\" /><FooterStyle parent=\"Footer\" me=\"Style3\" />" +
"<GroupStyle parent=\"Group\" me=\"Style11\" /><HeadingStyle parent=\"Heading\" me=\"Sty" +
"le2\" /><HighLightRowStyle parent=\"HighlightRow\" me=\"Style6\" /><InactiveStyle par" +
"ent=\"Inactive\" me=\"Style4\" /><OddRowStyle parent=\"OddRow\" me=\"Style8\" /><RecordS" +
"electorStyle parent=\"RecordSelector\" me=\"Style10\" /><SelectedStyle parent=\"Selec" +
"ted\" me=\"Style5\" /><Style parent=\"Normal\" me=\"Style1\" /></C1.Win.C1List.ListBoxV" +
"iew></Splits><NamedStyles><Style parent=\"\" me=\"Normal\" /><Style parent=\"Normal\" " +
"me=\"Heading\" /><Style parent=\"Heading\" me=\"Footer\" /><Style parent=\"Heading\" me=" +
"\"Caption\" /><Style parent=\"Heading\" me=\"Inactive\" /><Style parent=\"Normal\" me=\"S" +
"elected\" /><Style parent=\"Normal\" me=\"HighlightRow\" /><Style parent=\"Normal\" me=" +
"\"EvenRow\" /><Style parent=\"Normal\" me=\"OddRow\" /><Style parent=\"Heading\" me=\"Rec" +
"ordSelector\" /><Style parent=\"Caption\" me=\"Group\" /></NamedStyles><vertSplits>1<" +
"/vertSplits><horzSplits>1</horzSplits><Layout>Modified</Layout><DefaultRecSelWid" +
"th>17</DefaultRecSelWidth></Blob>";
//
// lblCCN
//
this.lblCCN.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.lblCCN.ForeColor = System.Drawing.Color.Maroon;
this.lblCCN.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblCCN.Location = new System.Drawing.Point(517, 6);
this.lblCCN.Name = "lblCCN";
this.lblCCN.Size = new System.Drawing.Size(30, 19);
this.lblCCN.TabIndex = 0;
this.lblCCN.Text = "CCN";
this.lblCCN.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// txtPONo
//
this.txtPONo.Location = new System.Drawing.Point(84, 27);
this.txtPONo.Name = "txtPONo";
this.txtPONo.Size = new System.Drawing.Size(122, 20);
this.txtPONo.TabIndex = 5;
this.txtPONo.Text = "";
this.txtPONo.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtPONo_KeyDown);
this.txtPONo.Validating += new System.ComponentModel.CancelEventHandler(this.txtPONo_Validating);
//
// btnPONo
//
this.btnPONo.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnPONo.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnPONo.Location = new System.Drawing.Point(207, 27);
this.btnPONo.Name = "btnPONo";
this.btnPONo.Size = new System.Drawing.Size(21, 20);
this.btnPONo.TabIndex = 6;
this.btnPONo.Text = "...";
this.btnPONo.Click += new System.EventHandler(this.btnPONo_Click);
//
// lblPONo
//
this.lblPONo.ForeColor = System.Drawing.Color.Black;
this.lblPONo.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblPONo.Location = new System.Drawing.Point(6, 27);
this.lblPONo.Name = "lblPONo";
this.lblPONo.Size = new System.Drawing.Size(76, 20);
this.lblPONo.TabIndex = 4;
this.lblPONo.Text = "PO No.";
this.lblPONo.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// lblApprover
//
this.lblApprover.ForeColor = System.Drawing.Color.Maroon;
this.lblApprover.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblApprover.Location = new System.Drawing.Point(231, 50);
this.lblApprover.Name = "lblApprover";
this.lblApprover.Size = new System.Drawing.Size(52, 20);
this.lblApprover.TabIndex = 9;
this.lblApprover.Text = "Approver";
this.lblApprover.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// chkSelectAll
//
this.chkSelectAll.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.chkSelectAll.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.chkSelectAll.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.chkSelectAll.Location = new System.Drawing.Point(82, 431);
this.chkSelectAll.Name = "chkSelectAll";
this.chkSelectAll.Size = new System.Drawing.Size(70, 18);
this.chkSelectAll.TabIndex = 13;
this.chkSelectAll.Text = "Se&lect All";
this.chkSelectAll.Enter += new System.EventHandler(this.chkSelectAll_Enter);
this.chkSelectAll.Leave += new System.EventHandler(this.chkSelectAll_Leave);
this.chkSelectAll.CheckedChanged += new System.EventHandler(this.chkSelectAll_CheckedChanged);
//
// lblApprDate
//
this.lblApprDate.ForeColor = System.Drawing.Color.Maroon;
this.lblApprDate.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblApprDate.Location = new System.Drawing.Point(6, 50);
this.lblApprDate.Name = "lblApprDate";
this.lblApprDate.Size = new System.Drawing.Size(76, 20);
this.lblApprDate.TabIndex = 7;
this.lblApprDate.Text = "Approval Date";
this.lblApprDate.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// btnApprove
//
this.btnApprove.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnApprove.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnApprove.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnApprove.Location = new System.Drawing.Point(4, 428);
this.btnApprove.Name = "btnApprove";
this.btnApprove.Size = new System.Drawing.Size(76, 22);
this.btnApprove.TabIndex = 12;
this.btnApprove.Text = "&Approve";
this.btnApprove.Click += new System.EventHandler(this.btnApprove_Click);
//
// btnClose
//
this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnClose.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnClose.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnClose.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnClose.Location = new System.Drawing.Point(566, 428);
this.btnClose.Name = "btnClose";
this.btnClose.Size = new System.Drawing.Size(64, 22);
this.btnClose.TabIndex = 16;
this.btnClose.Text = "&Close";
this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
//
// btnHelp
//
this.btnHelp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnHelp.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnHelp.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnHelp.Location = new System.Drawing.Point(501, 428);
this.btnHelp.Name = "btnHelp";
this.btnHelp.Size = new System.Drawing.Size(64, 22);
this.btnHelp.TabIndex = 15;
this.btnHelp.Text = "&Help";
//
// gridApprove
//
this.gridApprove.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.gridApprove.CaptionHeight = 17;
this.gridApprove.CollapseColor = System.Drawing.Color.Black;
this.gridApprove.ExpandColor = System.Drawing.Color.Black;
this.gridApprove.FlatStyle = C1.Win.C1TrueDBGrid.FlatModeEnum.System;
this.gridApprove.GroupByCaption = "Drag a column header here to group by that column";
this.gridApprove.Images.Add(((System.Drawing.Image)(resources.GetObject("resource"))));
this.gridApprove.Location = new System.Drawing.Point(4, 76);
this.gridApprove.MarqueeStyle = C1.Win.C1TrueDBGrid.MarqueeEnum.DottedCellBorder;
this.gridApprove.Name = "gridApprove";
this.gridApprove.PreviewInfo.Location = new System.Drawing.Point(0, 0);
this.gridApprove.PreviewInfo.Size = new System.Drawing.Size(0, 0);
this.gridApprove.PreviewInfo.ZoomFactor = 75;
this.gridApprove.PrintInfo.ShowOptionsDialog = false;
this.gridApprove.RecordSelectorWidth = 17;
this.gridApprove.RowDivider.Color = System.Drawing.Color.DarkGray;
this.gridApprove.RowDivider.Style = C1.Win.C1TrueDBGrid.LineStyleEnum.Single;
this.gridApprove.RowHeight = 14;
this.gridApprove.RowSubDividerColor = System.Drawing.Color.DarkGray;
this.gridApprove.Size = new System.Drawing.Size(626, 346);
this.gridApprove.TabIndex = 10;
this.gridApprove.Text = "c1TrueDBGrid1";
this.gridApprove.AfterColEdit += new C1.Win.C1TrueDBGrid.ColEventHandler(this.gridApprove_AfterColEdit);
this.gridApprove.PropBag = "<?xml version=\"1.0\"?><Blob><DataCols><C1DataColumn Level=\"0\" Caption=\"PO No.\" Dat" +
"aField=\"PONo\"><ValueItems /><GroupInfo /></C1DataColumn><C1DataColumn Level=\"0\" " +
"Caption=\"Total Amount\" DataField=\"TotalAmount\"><ValueItems /><GroupInfo /></C1Da" +
"taColumn><C1DataColumn Level=\"0\" Caption=\"Open Amount\" DataField=\"openAmount\"><V" +
"alueItems /><GroupInfo /></C1DataColumn><C1DataColumn Level=\"0\" Caption=\"Approve" +
"d\" DataField=\"Approved\"><ValueItems Presentation=\"CheckBox\" /><GroupInfo /></C1D" +
"ataColumn><C1DataColumn Level=\"0\" Caption=\"PO Line\" DataField=\"Line\"><ValueItems" +
" /><GroupInfo /></C1DataColumn><C1DataColumn Level=\"0\" Caption=\"Category\" DataFi" +
"eld=\"ITM_CategoryCode\"><ValueItems /><GroupInfo /></C1DataColumn><C1DataColumn L" +
"evel=\"0\" Caption=\"Part Number\" DataField=\"Code\"><ValueItems /><GroupInfo /></C1D" +
"ataColumn><C1DataColumn Level=\"0\" Caption=\"Part Name\" DataField=\"Description\"><V" +
"alueItems /><GroupInfo /></C1DataColumn><C1DataColumn Level=\"0\" Caption=\"Model\" " +
"DataField=\"Revision\"><ValueItems /><GroupInfo /></C1DataColumn><C1DataColumn Lev" +
"el=\"0\" Caption=\"Buying UM\" DataField=\"BuyingUM\"><ValueItems /><GroupInfo /></C1D" +
"ataColumn><C1DataColumn Level=\"0\" Caption=\"Order Quantity \" DataField=\"OrderQuan" +
"tity\"><ValueItems /><GroupInfo /></C1DataColumn><C1DataColumn Level=\"0\" Caption=" +
"\"Currency\" DataField=\"Currency\"><ValueItems /><GroupInfo /></C1DataColumn><C1Dat" +
"aColumn Level=\"0\" Caption=\"Available Qty\" DataField=\"AvailableQty\"><ValueItems /" +
"><GroupInfo /></C1DataColumn></DataCols><Styles type=\"C1.Win.C1TrueDBGrid.Design" +
".ContextWrapper\"><Data>HighlightRow{ForeColor:HighlightText;BackColor:Highlight;" +
"}Style85{}Inactive{ForeColor:InactiveCaptionText;BackColor:InactiveCaption;}Styl" +
"e78{}Style79{}Selected{ForeColor:HighlightText;BackColor:Highlight;}Editor{}Styl" +
"e72{}Style73{}Style70{AlignHorz:Center;}Style71{AlignHorz:Near;}Style76{AlignHor" +
"z:Center;}Style77{AlignHorz:Near;}Style74{}Style75{}Style84{}Style87{}Style86{}S" +
"tyle81{}Style80{}Style83{AlignHorz:Near;}Style82{AlignHorz:Center;}Footer{}Style" +
"89{AlignHorz:Near;}Style88{AlignHorz:Center;}Style94{AlignHorz:Center;}Style95{A" +
"lignHorz:Near;}Style96{}Style97{}Style90{}Style91{}Style92{}Style93{}RecordSelec" +
"tor{AlignImage:Center;}Style98{}Style99{}Heading{Wrap:True;AlignVert:Center;Bord" +
"er:Raised,,1, 1, 1, 1;ForeColor:ControlText;BackColor:Control;}Style18{}Style19{" +
"}Style14{}Style15{}Style16{AlignHorz:Center;}Style17{AlignHorz:Near;}Style10{Ali" +
"gnHorz:Near;}Style11{}Style12{}Style13{}Style29{AlignHorz:Near;}Style28{AlignHor" +
"z:Center;}Style27{}Style22{AlignHorz:Center;}Style9{}Style8{}Style26{}Style25{}S" +
"tyle5{}Style4{}Style7{}Style6{}Style24{}Style23{AlignHorz:Near;}Style3{}Style2{}" +
"Style21{}Style20{}OddRow{}Style49{}Style38{}Style39{}Style36{}FilterBar{}Style34" +
"{AlignHorz:Center;}Style35{AlignHorz:Near;}Style32{}Style33{}Style30{}Style37{}S" +
"tyle48{}Style31{}Normal{}Style41{AlignHorz:Near;}Style40{AlignHorz:Center;}Style" +
"43{}Style42{}Style45{}Style44{}Style47{AlignHorz:Near;}Style46{AlignHorz:Center;" +
"}EvenRow{BackColor:Aqua;}Style58{AlignHorz:Center;}Style59{AlignHorz:Near;}Style" +
"50{}Style51{}Caption{AlignHorz:Center;}Style69{}Style68{}Style1{}Style63{}Style6" +
"2{}Style61{}Style60{}Style67{}Style66{}Style65{AlignHorz:Near;}Style64{AlignHorz" +
":Center;}Group{BackColor:ControlDark;Border:None,,0, 0, 0, 0;AlignVert:Center;}<" +
"/Data></Styles><Splits><C1.Win.C1TrueDBGrid.MergeView Name=\"\" CaptionHeight=\"17\"" +
" ColumnCaptionHeight=\"17\" ColumnFooterHeight=\"17\" MarqueeStyle=\"DottedCellBorder" +
"\" RecordSelectorWidth=\"17\" DefRecSelWidth=\"17\" VerticalScrollGroup=\"1\" Horizonta" +
"lScrollGroup=\"1\"><ClientRect>0, 0, 622, 342</ClientRect><BorderSide>0</BorderSid" +
"e><CaptionStyle parent=\"Style2\" me=\"Style10\" /><EditorStyle parent=\"Editor\" me=\"" +
"Style5\" /><EvenRowStyle parent=\"EvenRow\" me=\"Style8\" /><FilterBarStyle parent=\"F" +
"ilterBar\" me=\"Style13\" /><FooterStyle parent=\"Footer\" me=\"Style3\" /><GroupStyle " +
"parent=\"Group\" me=\"Style12\" /><HeadingStyle parent=\"Heading\" me=\"Style2\" /><High" +
"LightRowStyle parent=\"HighlightRow\" me=\"Style7\" /><InactiveStyle parent=\"Inactiv" +
"e\" me=\"Style4\" /><OddRowStyle parent=\"OddRow\" me=\"Style9\" /><RecordSelectorStyle" +
" parent=\"RecordSelector\" me=\"Style11\" /><SelectedStyle parent=\"Selected\" me=\"Sty" +
"le6\" /><Style parent=\"Normal\" me=\"Style1\" /><internalCols><C1DisplayColumn><Head" +
"ingStyle parent=\"Style2\" me=\"Style16\" /><Style parent=\"Style1\" me=\"Style17\" /><F" +
"ooterStyle parent=\"Style3\" me=\"Style18\" /><EditorStyle parent=\"Style5\" me=\"Style" +
"19\" /><GroupHeaderStyle parent=\"Style1\" me=\"Style21\" /><GroupFooterStyle parent=" +
"\"Style1\" me=\"Style20\" /><Visible>True</Visible><ColumnDivider>DarkGray,Single</C" +
"olumnDivider><Width>126</Width><Height>15</Height><DCIdx>0</DCIdx></C1DisplayCol" +
"umn><C1DisplayColumn><HeadingStyle parent=\"Style2\" me=\"Style46\" /><Style parent=" +
"\"Style1\" me=\"Style47\" /><FooterStyle parent=\"Style3\" me=\"Style48\" /><EditorStyle" +
" parent=\"Style5\" me=\"Style49\" /><GroupHeaderStyle parent=\"Style1\" me=\"Style51\" /" +
"><GroupFooterStyle parent=\"Style1\" me=\"Style50\" /><Visible>True</Visible><Column" +
"Divider>DarkGray,Single</ColumnDivider><Width>58</Width><Height>15</Height><DCId" +
"x>4</DCIdx></C1DisplayColumn><C1DisplayColumn><HeadingStyle parent=\"Style2\" me=\"" +
"Style40\" /><Style parent=\"Style1\" me=\"Style41\" /><FooterStyle parent=\"Style3\" me" +
"=\"Style42\" /><EditorStyle parent=\"Style5\" me=\"Style43\" /><GroupHeaderStyle paren" +
"t=\"Style1\" me=\"Style45\" /><GroupFooterStyle parent=\"Style1\" me=\"Style44\" /><Visi" +
"ble>True</Visible><ColumnDivider>DarkGray,Single</ColumnDivider><Width>84</Width" +
"><Height>15</Height><DCIdx>5</DCIdx></C1DisplayColumn><C1DisplayColumn><HeadingS" +
"tyle parent=\"Style2\" me=\"Style58\" /><Style parent=\"Style1\" me=\"Style59\" /><Foote" +
"rStyle parent=\"Style3\" me=\"Style60\" /><EditorStyle parent=\"Style5\" me=\"Style61\" " +
"/><GroupHeaderStyle parent=\"Style1\" me=\"Style63\" /><GroupFooterStyle parent=\"Sty" +
"le1\" me=\"Style62\" /><Visible>True</Visible><ColumnDivider>DarkGray,Single</Colum" +
"nDivider><Width>145</Width><Height>15</Height><DCIdx>6</DCIdx></C1DisplayColumn>" +
"<C1DisplayColumn><HeadingStyle parent=\"Style2\" me=\"Style64\" /><Style parent=\"Sty" +
"le1\" me=\"Style65\" /><FooterStyle parent=\"Style3\" me=\"Style66\" /><EditorStyle par" +
"ent=\"Style5\" me=\"Style67\" /><GroupHeaderStyle parent=\"Style1\" me=\"Style69\" /><Gr" +
"oupFooterStyle parent=\"Style1\" me=\"Style68\" /><Visible>True</Visible><ColumnDivi" +
"der>DarkGray,Single</ColumnDivider><Width>150</Width><Height>15</Height><DCIdx>7" +
"</DCIdx></C1DisplayColumn><C1DisplayColumn><HeadingStyle parent=\"Style2\" me=\"Sty" +
"le70\" /><Style parent=\"Style1\" me=\"Style71\" /><FooterStyle parent=\"Style3\" me=\"S" +
"tyle72\" /><EditorStyle parent=\"Style5\" me=\"Style73\" /><GroupHeaderStyle parent=\"" +
"Style1\" me=\"Style75\" /><GroupFooterStyle parent=\"Style1\" me=\"Style74\" /><Visible" +
">True</Visible><ColumnDivider>DarkGray,Single</ColumnDivider><Width>96</Width><H" +
"eight>15</Height><DCIdx>8</DCIdx></C1DisplayColumn><C1DisplayColumn><HeadingStyl" +
"e parent=\"Style2\" me=\"Style76\" /><Style parent=\"Style1\" me=\"Style77\" /><FooterSt" +
"yle parent=\"Style3\" me=\"Style78\" /><EditorStyle parent=\"Style5\" me=\"Style79\" /><" +
"GroupHeaderStyle parent=\"Style1\" me=\"Style81\" /><GroupFooterStyle parent=\"Style1" +
"\" me=\"Style80\" /><Visible>True</Visible><ColumnDivider>DarkGray,Single</ColumnDi" +
"vider><Width>74</Width><Height>15</Height><DCIdx>9</DCIdx></C1DisplayColumn><C1D" +
"isplayColumn><HeadingStyle parent=\"Style2\" me=\"Style82\" /><Style parent=\"Style1\"" +
" me=\"Style83\" /><FooterStyle parent=\"Style3\" me=\"Style84\" /><EditorStyle parent=" +
"\"Style5\" me=\"Style85\" /><GroupHeaderStyle parent=\"Style1\" me=\"Style87\" /><GroupF" +
"ooterStyle parent=\"Style1\" me=\"Style86\" /><Visible>True</Visible><ColumnDivider>" +
"DarkGray,Single</ColumnDivider><Width>86</Width><Height>15</Height><DCIdx>10</DC" +
"Idx></C1DisplayColumn><C1DisplayColumn><HeadingStyle parent=\"Style2\" me=\"Style94" +
"\" /><Style parent=\"Style1\" me=\"Style95\" /><FooterStyle parent=\"Style3\" me=\"Style" +
"96\" /><EditorStyle parent=\"Style5\" me=\"Style97\" /><GroupHeaderStyle parent=\"Styl" +
"e1\" me=\"Style99\" /><GroupFooterStyle parent=\"Style1\" me=\"Style98\" /><Visible>Tru" +
"e</Visible><ColumnDivider>DarkGray,Single</ColumnDivider><Height>15</Height><DCI" +
"dx>12</DCIdx></C1DisplayColumn><C1DisplayColumn><HeadingStyle parent=\"Style2\" me" +
"=\"Style88\" /><Style parent=\"Style1\" me=\"Style89\" /><FooterStyle parent=\"Style3\" " +
"me=\"Style90\" /><EditorStyle parent=\"Style5\" me=\"Style91\" /><GroupHeaderStyle par" +
"ent=\"Style1\" me=\"Style93\" /><GroupFooterStyle parent=\"Style1\" me=\"Style92\" /><Vi" +
"sible>True</Visible><ColumnDivider>DarkGray,Single</ColumnDivider><Width>60</Wid" +
"th><Height>15</Height><DCIdx>11</DCIdx></C1DisplayColumn><C1DisplayColumn><Headi" +
"ngStyle parent=\"Style2\" me=\"Style22\" /><Style parent=\"Style1\" me=\"Style23\" /><Fo" +
"oterStyle parent=\"Style3\" me=\"Style24\" /><EditorStyle parent=\"Style5\" me=\"Style2" +
"5\" /><GroupHeaderStyle parent=\"Style1\" me=\"Style27\" /><GroupFooterStyle parent=\"" +
"Style1\" me=\"Style26\" /><Visible>True</Visible><ColumnDivider>DarkGray,Single</Co" +
"lumnDivider><Width>112</Width><Height>15</Height><DCIdx>1</DCIdx></C1DisplayColu" +
"mn><C1DisplayColumn><HeadingStyle parent=\"Style2\" me=\"Style28\" /><Style parent=\"" +
"Style1\" me=\"Style29\" /><FooterStyle parent=\"Style3\" me=\"Style30\" /><EditorStyle " +
"parent=\"Style5\" me=\"Style31\" /><GroupHeaderStyle parent=\"Style1\" me=\"Style33\" />" +
"<GroupFooterStyle parent=\"Style1\" me=\"Style32\" /><Visible>True</Visible><ColumnD" +
"ivider>DarkGray,Single</ColumnDivider><Width>96</Width><Height>15</Height><DCIdx" +
">2</DCIdx></C1DisplayColumn><C1DisplayColumn><HeadingStyle parent=\"Style2\" me=\"S" +
"tyle34\" /><Style parent=\"Style1\" me=\"Style35\" /><FooterStyle parent=\"Style3\" me=" +
"\"Style36\" /><EditorStyle parent=\"Style5\" me=\"Style37\" /><GroupHeaderStyle parent" +
"=\"Style1\" me=\"Style39\" /><GroupFooterStyle parent=\"Style1\" me=\"Style38\" /><Visib" +
"le>True</Visible><ColumnDivider>DarkGray,Single</ColumnDivider><Width>57</Width>" +
"<Height>15</Height><DCIdx>3</DCIdx></C1DisplayColumn></internalCols></C1.Win.C1T" +
"rueDBGrid.MergeView></Splits><NamedStyles><Style parent=\"\" me=\"Normal\" /><Style " +
"parent=\"Normal\" me=\"Heading\" /><Style parent=\"Heading\" me=\"Footer\" /><Style pare" +
"nt=\"Heading\" me=\"Caption\" /><Style parent=\"Heading\" me=\"Inactive\" /><Style paren" +
"t=\"Normal\" me=\"Selected\" /><Style parent=\"Normal\" me=\"Editor\" /><Style parent=\"N" +
"ormal\" me=\"HighlightRow\" /><Style parent=\"Normal\" me=\"EvenRow\" /><Style parent=\"" +
"Normal\" me=\"OddRow\" /><Style parent=\"Heading\" me=\"RecordSelector\" /><Style paren" +
"t=\"Normal\" me=\"FilterBar\" /><Style parent=\"Caption\" me=\"Group\" /></NamedStyles><" +
"vertSplits>1</vertSplits><horzSplits>1</horzSplits><Layout>Modified</Layout><Def" +
"aultRecSelWidth>17</DefaultRecSelWidth><ClientArea>0, 0, 622, 342</ClientArea><P" +
"rintPageHeaderStyle parent=\"\" me=\"Style14\" /><PrintPageFooterStyle parent=\"\" me=" +
"\"Style15\" /></Blob>";
//
// btnSearch
//
this.btnSearch.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnSearch.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnSearch.Location = new System.Drawing.Point(550, 49);
this.btnSearch.Name = "btnSearch";
this.btnSearch.Size = new System.Drawing.Size(80, 22);
this.btnSearch.TabIndex = 11;
this.btnSearch.Text = "&Search";
this.btnSearch.Click += new System.EventHandler(this.btnSearch_Click);
//
// txtApprover
//
this.txtApprover.Location = new System.Drawing.Point(285, 50);
this.txtApprover.Name = "txtApprover";
this.txtApprover.Size = new System.Drawing.Size(101, 20);
this.txtApprover.TabIndex = 10;
this.txtApprover.Text = "";
//
// dtmApprDate
//
this.dtmApprDate.EmptyAsNull = true;
this.dtmApprDate.Location = new System.Drawing.Point(84, 50);
this.dtmApprDate.Name = "dtmApprDate";
this.dtmApprDate.Size = new System.Drawing.Size(122, 20);
this.dtmApprDate.TabIndex = 8;
this.dtmApprDate.Tag = null;
this.dtmApprDate.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.dtmApprDate.VisibleButtons = C1.Win.C1Input.DropDownControlButtonFlags.DropDown;
//
// btnShowDetail
//
this.btnShowDetail.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnShowDetail.Location = new System.Drawing.Point(416, 428);
this.btnShowDetail.Name = "btnShowDetail";
this.btnShowDetail.Size = new System.Drawing.Size(84, 22);
this.btnShowDetail.TabIndex = 14;
this.btnShowDetail.Text = "Show D&etail";
this.btnShowDetail.Click += new System.EventHandler(this.btnShowDetail_Click);
//
// lblStatus
//
this.lblStatus.ForeColor = System.Drawing.Color.Maroon;
this.lblStatus.Location = new System.Drawing.Point(6, 5);
this.lblStatus.Name = "lblStatus";
this.lblStatus.Size = new System.Drawing.Size(76, 20);
this.lblStatus.TabIndex = 2;
this.lblStatus.Text = "Status";
this.lblStatus.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// cboStatus
//
this.cboStatus.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboStatus.Location = new System.Drawing.Point(84, 4);
this.cboStatus.Name = "cboStatus";
this.cboStatus.Size = new System.Drawing.Size(122, 21);
this.cboStatus.TabIndex = 3;
this.cboStatus.SelectedValueChanged += new System.EventHandler(this.cboStatus_SelectedValueChanged);
//
// lblApproved
//
this.lblApproved.Location = new System.Drawing.Point(414, 48);
this.lblApproved.Name = "lblApproved";
this.lblApproved.Size = new System.Drawing.Size(56, 20);
this.lblApproved.TabIndex = 18;
this.lblApproved.Text = "Approved";
this.lblApproved.Visible = false;
//
// lblNotApproved
//
this.lblNotApproved.Location = new System.Drawing.Point(472, 48);
this.lblNotApproved.Name = "lblNotApproved";
this.lblNotApproved.Size = new System.Drawing.Size(78, 20);
this.lblNotApproved.TabIndex = 19;
this.lblNotApproved.Text = "Not Approved";
this.lblNotApproved.Visible = false;
//
// lblCancelApprove
//
this.lblCancelApprove.Location = new System.Drawing.Point(414, 22);
this.lblCancelApprove.Name = "lblCancelApprove";
this.lblCancelApprove.Size = new System.Drawing.Size(88, 20);
this.lblCancelApprove.TabIndex = 20;
this.lblCancelApprove.Text = "&Cancel";
this.lblCancelApprove.Visible = false;
//
// lblCancelDate
//
this.lblCancelDate.Location = new System.Drawing.Point(336, 22);
this.lblCancelDate.Name = "lblCancelDate";
this.lblCancelDate.Size = new System.Drawing.Size(76, 20);
this.lblCancelDate.TabIndex = 21;
this.lblCancelDate.Text = "Cancel Date";
this.lblCancelDate.Visible = false;
//
// lblCanceler
//
this.lblCanceler.ForeColor = System.Drawing.Color.Maroon;
this.lblCanceler.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblCanceler.Location = new System.Drawing.Point(336, 1);
this.lblCanceler.Name = "lblCanceler";
this.lblCanceler.Size = new System.Drawing.Size(52, 20);
this.lblCanceler.TabIndex = 22;
this.lblCanceler.Text = "Canceler";
this.lblCanceler.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.lblCanceler.Visible = false;
//
// POPurchaseOrderApproval
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.btnClose;
this.ClientSize = new System.Drawing.Size(634, 457);
this.Controls.Add(this.lblCanceler);
this.Controls.Add(this.lblCancelDate);
this.Controls.Add(this.lblCancelApprove);
this.Controls.Add(this.lblNotApproved);
this.Controls.Add(this.lblApproved);
this.Controls.Add(this.cboStatus);
this.Controls.Add(this.lblStatus);
this.Controls.Add(this.btnShowDetail);
this.Controls.Add(this.dtmApprDate);
this.Controls.Add(this.txtApprover);
this.Controls.Add(this.txtPONo);
this.Controls.Add(this.btnSearch);
this.Controls.Add(this.btnHelp);
this.Controls.Add(this.btnApprove);
this.Controls.Add(this.btnClose);
this.Controls.Add(this.gridApprove);
this.Controls.Add(this.chkSelectAll);
this.Controls.Add(this.lblApprDate);
this.Controls.Add(this.cboCCN);
this.Controls.Add(this.lblCCN);
this.Controls.Add(this.btnPONo);
this.Controls.Add(this.lblPONo);
this.Controls.Add(this.lblApprover);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.KeyPreview = true;
this.Name = "POPurchaseOrderApproval";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Approve/Cancel Purchase Order Approval";
this.Load += new System.EventHandler(this.POPurchaseOrderApproval_Load);
((System.ComponentModel.ISupportInitialize)(this.cboCCN)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.gridApprove)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.dtmApprDate)).EndInit();
this.ResumeLayout(false);
}
#endregion
private void btnClose_Click(object sender, System.EventArgs e)
{
this.Close();
}
private void POPurchaseOrderApproval_Load(object sender, System.EventArgs e)
{
const string METHOD_NAME = THIS + ".POPurchaseOrderApproval_Load()";
try
{
//Set authorization for user
Security objSecurity = new Security();
this.Name = THIS;
if(objSecurity.SetRightForUserOnForm(this, SystemProperty.UserName) == 0)
{
this.Close();
// You don't have the right to view this item
PCSMessageBox.Show(ErrorCode.MESSAGE_YOU_HAVE_NO_RIGHT_TO_VIEW, MessageBoxIcon.Warning);
return;
}
dtbGridLayOut = FormControlComponents.StoreGridLayout(gridApprove);
// load form
dtmApprDate.FormatType = C1.Win.C1Input.FormatTypeEnum.CustomFormat;
dtmApprDate.CustomFormat = Constants.DATETIME_FORMAT;
InitVariable();
cboStatus.Items.Add(lblApproved.Text);
cboStatus.Items.Add(lblNotApproved.Text);
strlblApprovalDate = lblApprDate.Text.Trim();
strbtnApprove = btnApprove.Text.Trim();
strlblApprover = lblApprover.Text.Trim();
txtApprover.ReadOnly = true;
}
catch (PCSException ex)
{
// Displays the error message if throwed from PCSException.
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// Displays the error message if throwed from system.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
}
/// <summary>
/// CreatDataSet
/// </summary>
/// <author>Trada</author>
/// <date>Wednesday, October 12 2005</date>
private void CreatDataSet()
{
const string METHOD_NAME = THIS + ".CreateDataSet()";
try
{
dstGridData = new DataSet();
dstGridData.Tables.Add(PO_APPROVE_TABLE);
dstGridData.Tables[PO_APPROVE_TABLE].Columns.Add(PO_NO);
dstGridData.Tables[PO_APPROVE_TABLE].Columns.Add(PO_PurchaseOrderDetailTable.LINE_FLD);
dstGridData.Tables[PO_APPROVE_TABLE].Columns.Add(ITM_CategoryTable.TABLE_NAME + ITM_CategoryTable.CODE_FLD);
dstGridData.Tables[PO_APPROVE_TABLE].Columns.Add(ITM_ProductTable.CODE_FLD);
dstGridData.Tables[PO_APPROVE_TABLE].Columns.Add(ITM_ProductTable.DESCRIPTION_FLD);
dstGridData.Tables[PO_APPROVE_TABLE].Columns.Add(ITM_ProductTable.REVISION_FLD);
dstGridData.Tables[PO_APPROVE_TABLE].Columns.Add(BUYINGUM);
dstGridData.Tables[PO_APPROVE_TABLE].Columns.Add(PO_PurchaseOrderDetailTable.ORDERQUANTITY_FLD);
dstGridData.Tables[PO_APPROVE_TABLE].Columns.Add(AVAILABLE_QUANTITY);
dstGridData.Tables[PO_APPROVE_TABLE].Columns.Add(CURRENCY);
dstGridData.Tables[PO_APPROVE_TABLE].Columns.Add(PO_PurchaseOrderDetailTable.TOTALAMOUNT_FLD);
dstGridData.Tables[PO_APPROVE_TABLE].Columns.Add(OPEN_AMOUNT);
dstGridData.Tables[PO_APPROVE_TABLE].Columns.Add(CHECK_APPROVE, typeof(bool));
}
catch (PCSException ex)
{
throw new PCSException(ex.mCode, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
private void InitVariable()
{
const string METHOD_NAME = THIS + ".InitVariable()";
try
{
// Load combo box
UtilsBO boUtil = new UtilsBO();
DataSet dstCCN = boUtil.ListCCN();
cboCCN.DataSource = dstCCN.Tables[MST_CCNTable.TABLE_NAME];
cboCCN.DisplayMember = MST_CCNTable.CODE_FLD;
cboCCN.ValueMember = MST_CCNTable.CCNID_FLD;
FormControlComponents.PutDataIntoC1ComboBox(cboCCN,dstCCN.Tables[MST_CCNTable.TABLE_NAME],MST_CCNTable.CODE_FLD,MST_CCNTable.CCNID_FLD,MST_CCNTable.TABLE_NAME);
if (SystemProperty.CCNID != 0)
{
cboCCN.SelectedValue = SystemProperty.CCNID;
}
// Load combo box displays approving date
PO_PurchaseOrderMasterVO voMasterBlank = new PO_PurchaseOrderMasterVO();
voMasterBlank.OrderDate = boUtil.GetDBDate();
if((DateTime.MinValue < voMasterBlank.OrderDate) && (voMasterBlank.OrderDate < DateTime.MaxValue))
dtmApprDate.Value = DateTime.Parse(voMasterBlank.OrderDate.ToString());
else
dtmApprDate.Value = DBNull.Value;
// Load approver
txtApprover.Text = SystemProperty.EmployeeName;
if (SystemProperty.EmployeeID != 0)
{
txtApprover.Tag = SystemProperty.EmployeeID;
}
txtApprover.Enabled = false;
btnShowDetail.Enabled = false;
}
catch (PCSException ex)
{
// Displays the error message if throwed from PCSException.
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// Displays the error message if throwed from system.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
}
private void btnPONo_Click(object sender, System.EventArgs e)
{
const string METHOD_NAME = THIS + ".btnPONo_Click()";
try
{
Hashtable htbCriteria = new Hashtable();
DataRowView drwResult = null;
//User has selected CCN
if (cboStatus.Text.Trim() == string.Empty)
{
PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxIcon.Warning);
cboStatus.Focus();
return;
}
if (cboCCN.SelectedIndex != -1 )
{
htbCriteria.Add(PO_PurchaseOrderMasterTable.CCNID_FLD, cboCCN.SelectedValue);
}
//User has not selected CCN
else
{
PCSMessageBox.Show(ErrorCode.MESSAGE_RGA_CCN, MessageBoxIcon.Warning);
cboCCN.Focus();
return;
}
if (cboStatus.Text.Trim() == lblNotApproved.Text.Trim())
drwResult = FormControlComponents.OpenSearchForm(V_PO_NOT_APPROVE, PO_PurchaseOrderMasterTable.CODE_FLD, txtPONo.Text.Trim(), htbCriteria, true);
else
drwResult = FormControlComponents.OpenSearchForm(V_PO_APPROVE, PO_PurchaseOrderMasterTable.CODE_FLD, txtPONo.Text.Trim(), htbCriteria, true);
if (drwResult != null)
{
if ((txtPONo.Tag != null) && (txtPONo.Tag != DBNull.Value))
{
if (drwResult[PO_PurchaseOrderMasterTable.PURCHASEORDERMASTERID_FLD].ToString() != txtPONo.Tag.ToString())
{
txtPONo.Text = drwResult[PO_PurchaseOrderMasterTable.CODE_FLD].ToString();
txtPONo.Tag = drwResult[PO_PurchaseOrderMasterTable.PURCHASEORDERMASTERID_FLD];
CreatDataSet();
gridApprove.DataSource = dstGridData.Tables[0];
FormControlComponents.RestoreGridLayout(gridApprove, dtbGridLayOut);
}
}
txtPONo.Text = drwResult[PO_PurchaseOrderMasterTable.CODE_FLD].ToString();
txtPONo.Tag = drwResult[PO_PurchaseOrderMasterTable.PURCHASEORDERMASTERID_FLD];
}
else
{
txtPONo.Focus();
}
}
catch (PCSException ex)
{
// Displays the error message if throwed from PCSException.
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR,MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION,MessageBoxIcon.Error);
}
}
}
private void btnSearch_Click(object sender, System.EventArgs e)
{
const string METHOD_NAME = THIS + ".btnSearch_Click()";
try
{
if (Validate_Data())
{
BindDataToGrid();
}
}
catch (PCSException ex)
{
// Displays the error message if throwed from PCSException.
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR,MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION,MessageBoxIcon.Error);
}
}
}
private bool Validate_Data()
{
const string METHOD_NAME = THIS + ".Validate_Data()";
try
{
if (FormControlComponents.CheckMandatory(cboCCN))
{
PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID);
cboCCN.Focus();
return false;
}
if (FormControlComponents.CheckMandatory(cboStatus))
{
PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID);
cboStatus.Focus();
return false;
}
if (FormControlComponents.CheckMandatory(dtmApprDate))
{
PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID);
dtmApprDate.Focus();
return false;
}
if (FormControlComponents.CheckMandatory(txtApprover))
{
PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID);
txtApprover.Focus();
txtApprover.Select();
return false;
}
return true;
}
catch (PCSException ex)
{
throw new PCSException(ex.mCode, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
/// <summary>
/// ConfigGrid
/// </summary>
/// <param name="pblnLock"></param>
/// <author>Trada</author>
/// <date>Tuesday, Nov 29 2005</date>
private void ConfigGrid(bool pblnLock)
{
const string METHOD_NAME = THIS + ".ConfigGrid()";
try
{
gridApprove.Enabled = true;
for (int i =0; i <gridApprove.Splits[0].DisplayColumns.Count; i++)
{
gridApprove.Splits[0].DisplayColumns[i].Locked = true;
}
gridApprove.Splits[0].DisplayColumns[CHECK_APPROVE].Locked = pblnLock;
gridApprove.Splits[0].DisplayColumns[PO_PurchaseOrderDetailTable.ORDERQUANTITY_FLD].DataColumn.NumberFormat = Constants.DECIMAL_NUMBERFORMAT;
gridApprove.Splits[0].DisplayColumns[PO_PurchaseOrderDetailTable.ORDERQUANTITY_FLD].Style.HorizontalAlignment = AlignHorzEnum.Far;
gridApprove.Splits[0].DisplayColumns[AVAILABLE_QUANTITY].DataColumn.NumberFormat = Constants.DECIMAL_NUMBERFORMAT;
gridApprove.Splits[0].DisplayColumns[AVAILABLE_QUANTITY].Style.HorizontalAlignment = AlignHorzEnum.Far;
gridApprove.Splits[0].DisplayColumns[PO_PurchaseOrderDetailTable.TOTALAMOUNT_FLD].DataColumn.NumberFormat = Constants.DECIMAL_NUMBERFORMAT;
gridApprove.Splits[0].DisplayColumns[PO_PurchaseOrderDetailTable.TOTALAMOUNT_FLD].Style.HorizontalAlignment = AlignHorzEnum.Far;
gridApprove.Splits[0].DisplayColumns[OPEN_AMOUNT].DataColumn.NumberFormat = Constants.DECIMAL_NUMBERFORMAT;
gridApprove.Splits[0].DisplayColumns[OPEN_AMOUNT].Style.HorizontalAlignment = AlignHorzEnum.Far;
}
catch (PCSException ex)
{
throw new PCSException(ex.mCode, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
public void BindDataToGrid()
{
const string METHOD_NAME = THIS + ".BindDataToGrid()";
chkSelectAll.Checked = false;
try
{
POPurchaseOrderApprovalBO boPurchase = new POPurchaseOrderApprovalBO();
if (cboStatus.Text == lblApproved.Text.Trim())
{
if (txtPONo.Text.Trim() != string.Empty)
{
dtbSource = boPurchase.ListPODetailByPOMasterID(int.Parse(txtPONo.Tag.ToString()), int.Parse(cboCCN.SelectedValue.ToString()), true).Tables[1];
}
else
dtbSource = boPurchase.ListPODetailByPOMasterID(-1, int.Parse(cboCCN.SelectedValue.ToString()), true).Tables[1];
}
else
{
if (txtPONo.Text.Trim() != string.Empty)
{
dtbSource = boPurchase.ListPODetailByPOMasterID(int.Parse(txtPONo.Tag.ToString()), int.Parse(cboCCN.SelectedValue.ToString()), false).Tables[1];
}
else
dtbSource = boPurchase.ListPODetailByPOMasterID(-1, int.Parse(cboCCN.SelectedValue.ToString()), false).Tables[1];
}
dtbSource.Columns.Add(CHECK_APPROVE, typeof(bool));
dtbSource.Columns.Add(APPROVED_ID);
foreach (DataRow drow in dtbSource.Rows)
{
drow[CHECK_APPROVE] = false;
if (txtApprover.Text == string.Empty)
{
PCSMessageBox.Show(ErrorCode.MESSAGE_RGV_PURCHASE_APPROVER, MessageBoxIcon.Error);
return;
}
else
drow[APPROVED_ID] = txtApprover.Tag.ToString();;
}
gridApprove.DataSource = dtbSource;
FormControlComponents.RestoreGridLayout(gridApprove, dtbGridLayOut);
gridApprove.Splits[0].DisplayColumns[CHECK_APPROVE].DataColumn.Caption = cboStatus.Text.Trim() == lblApproved.Text.Trim() ? lblCancelApprove.Text.Trim().Substring(1) : strbtnApprove.Substring(1);
ConfigGrid(false);
btnShowDetail.Enabled = gridApprove.RowCount > 0;
}
catch (PCSException ex)
{
// Displays the error message if throwed from PCSException.
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// Displays the error message if throwed from system.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
}
private void btnApprove_Click(object sender, System.EventArgs e)
{
const string METHOD_NAME = THIS + ".btnApprove_Click()";
try
{
//Validate data
if (FormControlComponents.CheckMandatory(cboCCN))
{
PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID);
cboCCN.Focus();
return;
}
if (FormControlComponents.CheckMandatory(dtmApprDate))
{
PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID);
dtmApprDate.Focus();
return;
}
//check the PostDate in the current period
// if (!FormControlComponents.CheckDateInCurrentPeriod((DateTime)dtmApprDate.Value))
// {
// //MessageBox.Show("The Post Date you input is not in the current period");
// PCSMessageBox.Show(ErrorCode.MESSAGE_RTG_ENTRYDATE, MessageBoxIcon.Warning);
// dtmApprDate.Focus();
// return;
// }
if (!ValidateData()) return;
if (cboStatus.Text.Trim() == lblApproved.Text)
{
new POPurchaseOrderApprovalBO().UpdateAllAfterApprove(dtbSource, DateTime.Parse(dtmApprDate.Value.ToString()), 0);
}
else
new POPurchaseOrderApprovalBO().UpdateAllAfterApprove(dtbSource, DateTime.Parse(dtmApprDate.Value.ToString()), int.Parse(txtApprover.Tag.ToString().Trim()));
BindDataToGrid();
PCSMessageBox.Show(ErrorCode.MESSAGE_AFTER_SAVE_DATA);
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION,MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR,MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
}
public bool ValidateData()
{
try
{
string METHOD_NAME = THIS + ".ValidateData()";
if (gridApprove.RowCount == 0)
{
throw new PCSException(ErrorCode.MESSAGE_PO_APPROVE_NO_DATA_IN_GRID, METHOD_NAME, null);
}
int intCount = 0;
for (int i = 0; i < gridApprove.RowCount; i++)
{
if (gridApprove[i, CHECK_APPROVE].ToString() == TRUE)
{
intCount++;
break;
}
}
if (intCount == 0)
{
PCSMessageBox.Show(ErrorCode.MESSAGE_RGV_PURCHASE_APPROVER_SELECT_LINE, MessageBoxIcon.Warning);
return false;
}
for (int i =0; i < gridApprove.RowCount; i++)
{
if (gridApprove[i, CHECK_APPROVE].ToString() == TRUE)
{
if (DateTime.Parse(((DateTime) dtmApprDate.Value).ToShortDateString()) < (DateTime)gridApprove[i, PO_PurchaseOrderMasterTable.ORDERDATE_FLD]
&& cboStatus.Text.Trim() == lblNotApproved.Text.Trim())
{
PCSMessageBox.Show(ErrorCode.MESSAGE_RGV_APPROVE_DATE_MUST_OLDER_THAN_ORDER_DATE, MessageBoxIcon.Warning);
dtmApprDate.Focus();
return false;
}
if (DateTime.Parse(((DateTime) dtmApprDate.Value).ToShortDateString()) < (DateTime)gridApprove[i, PO_PurchaseOrderMasterTable.ORDERDATE_FLD]
&& cboStatus.Text.Trim() == lblApproved.Text.Trim())
{
PCSMessageBox.Show(ErrorCode.MESSAGE_RGV_CANCEL_APPROVE_DATE_MUST_OLDER_THAN_ORDER_DATE, MessageBoxIcon.Warning);
dtmApprDate.Focus();
return false;
}
}
}
//get all POMaster which was selected to approve
DataRow[] drowIDs = dtbSource.Select(CHECK_APPROVE + "=1");
ArrayList arlIDs = new ArrayList();
foreach (DataRow drowData in drowIDs)
{
bool okExisted = false;
for (int i = 0; i <arlIDs.Count; i++)
{
if (int.Parse(arlIDs[i].ToString()) == (int) drowData[PO_PurchaseOrderMasterTable.PURCHASEORDERMASTERID_FLD])
{
okExisted = true;
break;
}
}
if (!okExisted)
{
arlIDs.Add((int) drowData[PO_PurchaseOrderMasterTable.PURCHASEORDERMASTERID_FLD]);
}
}
POPurchaseOrderApprovalBO boPurchase = new POPurchaseOrderApprovalBO();
for (int i =0; i <arlIDs.Count; i++)
{
if (!(boPurchase.CheckLevelApproval(int.Parse(txtApprover.Tag.ToString().Trim()), int.Parse(arlIDs[i].ToString()), int.Parse(cboCCN.SelectedValue.ToString()))))
{
PCSMessageBox.Show(ErrorCode.MESSAGE_NO_RIGHT_TO_APPROVE, MessageBoxIcon.Stop);
}
}
return true;
}
catch (PCSException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
private void CheckOrNochkCheckAll()
{
for (int i =0; i <gridApprove.RowCount; i++)
{
if (gridApprove[i, CHECK_APPROVE].ToString().Trim() != TRUE)
{
chkSelectAll.Checked = false;
return;
}
}
chkSelectAll.Checked = true;
}
private void chkSelectAll_CheckedChanged(object sender, System.EventArgs e)
{
const string METHOD_NAME = THIS + ".chkSelectAll_CheckedChanged()";
try
{
if (blnStateOfCheck)
{
if (chkSelectAll.Checked)
{
foreach (DataRow drow in dtbSource.Rows)
{
if (drow.RowState != DataRowState.Deleted)
{
drow[CHECK_APPROVE] = true;
}
}
}
else
{
foreach (DataRow drow in dtbSource.Rows)
{
if (drow.RowState != DataRowState.Deleted)
{
drow[CHECK_APPROVE] = false;
}
}
}
}
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION,MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR,MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION,MessageBoxIcon.Error);
}
}
}
private void gridApprove_AfterColEdit(object sender, C1.Win.C1TrueDBGrid.ColEventArgs e)
{
if (e.Column.DataColumn.DataField == CHECK_APPROVE)
{
CheckOrNochkCheckAll();
}
}
#region ChangeStateOfCheck
private void chkSelectAll_Enter(object sender, System.EventArgs e)
{
blnStateOfCheck = true;
}
private void chkSelectAll_Leave(object sender, System.EventArgs e)
{
blnStateOfCheck = false;
}
#endregion
private void OnEnterControl(object sender, System.EventArgs e)
{
const string METHOD_NAME = THIS + ".OnEnterControl()";
try
{
FormControlComponents.OnEnterControl(sender, e);
}
catch (PCSException ex)
{
// Displays the error message if throwed from PCSException.
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// Displays the error message if throwed from system.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
}
private void OnLeaveControl(object sender, System.EventArgs e)
{
const string METHOD_NAME = THIS + ".OnLeaveControl()";
try
{
FormControlComponents.OnLeaveControl(sender, e);
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION,MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR,MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION,MessageBoxIcon.Error);
}
}
}
private void txtPONo_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
const string METHOD_NAME = THIS + ".txtPONo_KeyDown()";
if (e.KeyCode == Keys.F4)
{
btnPONo_Click(sender, e);
}
}
/// <summary>
/// btnShowDetail_Click
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <author>Trada</author>
/// <date>Monday, August 15 2005</date>
private void btnShowDetail_Click(object sender, System.EventArgs e)
{
const string METHOD_NAME = THIS + ".btnShowDetail_Click()";
try
{
if (gridApprove.RowCount > 0)
{
PurchaseOrder frmPurchaseOrder = new PurchaseOrder();
frmPurchaseOrder.Show();
frmPurchaseOrder.LoadMaster((int) gridApprove[gridApprove.Row, PO_PurchaseOrderMasterTable.PURCHASEORDERMASTERID_FLD]);
}
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION,MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR,MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION,MessageBoxIcon.Error);
}
}
}
private void cboStatus_SelectedValueChanged(object sender, System.EventArgs e)
{
const string METHOD_NAME = ".cboStatus_SelectedValueChanged()";
if (cboStatus.Text.Trim() == lblApproved.Text.Trim())
{
btnApprove.Text = lblCancelApprove.Text;
lblApprDate.Text = lblCancelDate.Text;
lblApprover.Text = lblCanceler.Text;
gridApprove.Splits[0].DisplayColumns[CHECK_APPROVE].DataColumn.Caption = lblCancelApprove.Text.Trim().Substring(1);
}
if (cboStatus.Text.Trim() == lblNotApproved.Text.Trim())
{
btnApprove.Text = strbtnApprove;
lblApprDate.Text = strlblApprovalDate;
lblApprover.Text = strlblApprover;
gridApprove.Splits[0].DisplayColumns[CHECK_APPROVE].DataColumn.Caption = strbtnApprove.Substring(1);
}
try
{
if (dtbSource.Columns.Count != 0)
{
dtbSource.Rows.Clear();
dtbSource.AcceptChanges();
gridApprove.Refresh();
}
}
catch (PCSException ex)
{
// Displays the error message if throwed from PCSException.
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// Displays the error message if throwed from system.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
}
private void txtPONo_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
const string METHOD_NAME = THIS + ".txtPONo_Validating()";
try
{
if (!txtPONo.Modified || txtPONo.Text.Trim() == string.Empty) return;
Hashtable htbCriteria = new Hashtable();
DataRowView drwResult = null;
//User has selected CCN
if (cboCCN.SelectedIndex != -1 )
htbCriteria.Add(PO_PurchaseOrderMasterTable.CCNID_FLD, cboCCN.SelectedValue);
else
{
PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxIcon.Warning);
cboCCN.Focus();
e.Cancel = true;
return;
}
// edited: 12-04-2006 dungla: fix bug 3702 for NganNT, dot not display search form when found only one record
if (cboStatus.SelectedIndex == -1)
{
string[] strParam = new string[2];
strParam[0] = lblStatus.Text;
strParam[1] = lblPONo.Text;
PCSMessageBox.Show(ErrorCode.MESSAGE_SELECT_ONE_BEFORE_SELECT_ONE, MessageBoxIcon.Warning, strParam);
e.Cancel = true;
return;
}
if (cboStatus.Text.Trim() == lblNotApproved.Text.Trim())
drwResult = FormControlComponents.OpenSearchForm(V_PO_NOT_APPROVE, PO_PurchaseOrderMasterTable.CODE_FLD, txtPONo.Text.Trim(), htbCriteria, false);
else
drwResult = FormControlComponents.OpenSearchForm(V_PO_APPROVE, PO_PurchaseOrderMasterTable.CODE_FLD, txtPONo.Text.Trim(), htbCriteria, false);
if (drwResult != null)
{
if ((txtPONo.Tag != null) && (txtPONo.Tag != DBNull.Value))
{
if (drwResult[PO_PurchaseOrderMasterTable.PURCHASEORDERMASTERID_FLD].ToString() != txtPONo.Tag.ToString())
{
txtPONo.Text = drwResult[PO_PurchaseOrderMasterTable.CODE_FLD].ToString();
txtPONo.Tag = drwResult[PO_PurchaseOrderMasterTable.PURCHASEORDERMASTERID_FLD];
CreatDataSet();
gridApprove.DataSource = dstGridData.Tables[0];
FormControlComponents.RestoreGridLayout(gridApprove, dtbGridLayOut);
}
}
txtPONo.Text = drwResult[PO_PurchaseOrderMasterTable.CODE_FLD].ToString();
txtPONo.Tag = drwResult[PO_PurchaseOrderMasterTable.PURCHASEORDERMASTERID_FLD];
}
else
e.Cancel = true;
}
catch (PCSException ex)
{
// Displays the error message if throwed from PCSException.
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// Displays the error message if throwed from system.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
}
}
}
| |
//---------------------------------------------------------------------------
// <copyright file="FixedPageStructure.cs" company="Microsoft">
// Copyright (C) 2003 by Microsoft Corporation. All rights reserved.
// </copyright>
//
// Description:
// FixedPageStructure represents deduced information (such as boundary,
// geometry,layout, semantic, etc.) after a fixed page is analyzed.
//
// History:
// 11/10/2004 - Zhenbin Xu (ZhenbinX) - Created.
//
//---------------------------------------------------------------------------
namespace System.Windows.Documents
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Controls;
using System.Windows.Markup;
using System.Windows.Documents.DocumentStructures;
using MS.Internal.Documents;
using CultureInfo = System.Globalization.CultureInfo;
//=====================================================================
/// <summary>
/// FixedPageStructure represents deduced information (such as boundary,
/// geometry, layout, semantic, etc.) after a fixed page is analyzed.
/// </summary>
internal sealed class FixedPageStructure
{
//--------------------------------------------------------------------
//
// Constructors
//
//---------------------------------------------------------------------
#region Constructors
internal FixedPageStructure(int pageIndex)
{
Debug.Assert(pageIndex >= 0);
_pageIndex = pageIndex;
// Initialize to virtual
_flowStart = new FlowNode(FixedFlowMap.FlowOrderVirtualScopeId, FlowNodeType.Virtual, pageIndex);
_flowEnd = _flowStart;
//
_fixedStart = FixedNode.Create(pageIndex, 1, FixedFlowMap.FixedOrderStartVisual, -1, null);
_fixedEnd = FixedNode.Create(pageIndex, 1, FixedFlowMap.FixedOrderEndVisual, -1, null);
}
#endregion Constructors
//--------------------------------------------------------------------
//
// Public Methods
//
//---------------------------------------------------------------------
#region Public Methods
#if DEBUG
/// <summary>
/// Create a string representation of this object
/// </summary>
/// <returns>string - A string representation of this object</returns>
public override string ToString()
{
return String.Format("Pg{0}- ", _pageIndex);
}
#endif
#endregion Public Methods
//--------------------------------------------------------------------
//
// Public Properties
//
//---------------------------------------------------------------------
//--------------------------------------------------------------------
//
// Public Events
//
//---------------------------------------------------------------------
//--------------------------------------------------------------------
//
// Internal Methods
//
//---------------------------------------------------------------------
#region Internal Methods
//-------------------------------------
// Line Detection
//-------------------------------------
internal void SetupLineResults(FixedLineResult[] lineResults)
{
_lineResults = lineResults;
#if DEBUG
DocumentsTrace.FixedTextOM.Builder.Trace(string.Format("----LineResults Begin Dump-----\r\n"));
foreach(FixedLineResult lineResult in _lineResults)
{
Debug.Assert(lineResult != null);
DocumentsTrace.FixedTextOM.Builder.Trace(string.Format("{0}\r\n", lineResult.ToString()));
}
DocumentsTrace.FixedTextOM.Builder.Trace(string.Format("----LineResults End Dump-----\r\n"));
#endif
}
// count: desired as input, remaining as output
// if input count == 0, return current line range.
// Return true if it can get some line range
internal FixedNode[] GetNextLine(int line, bool forward, ref int count)
{
Debug.Assert(_lineResults != null);
if (forward)
{
while (line < _lineResults.Length - 1 && count > 0)
{
line++;
count--;
}
}
else
{
while (line > 0 && count > 0)
{
line--;
count--;
}
}
if (count <= 0)
{
line = Math.Max(0, Math.Min(line, _lineResults.Length - 1));
return _lineResults[line].Nodes;
}
return null;
}
//
/// <summary>
/// If the point is in one of the lines, return that line.
/// Otherwise, return the line with smallest (modified) manhattan distance.
/// </summary>
/// <param name="pt"></param>
/// <returns></returns>
internal FixedNode[] FindSnapToLine(Point pt)
{
Debug.Assert(_lineResults != null);
FixedLineResult closestLine = null;
FixedLineResult closestManhattan = null;
double minVerDistance = double.MaxValue;
double minHorDistance = double.MaxValue;
double minManhattan = double.MaxValue;
foreach (FixedLineResult lineResult in _lineResults)
{
double absVerDistance = Math.Max(0, (pt.Y > lineResult.LayoutBox.Y) ? (pt.Y - lineResult.LayoutBox.Bottom) : (lineResult.LayoutBox.Y - pt.Y));
double absHorDistance = Math.Max(0, (pt.X > lineResult.LayoutBox.X) ? (pt.X - lineResult.LayoutBox.Right) : (lineResult.LayoutBox.X - pt.X));
if (absVerDistance == 0 && absHorDistance == 0)
{
return lineResult.Nodes;
}
//Update the closest line information. We need this if we can't find a close line below the point
if (absVerDistance < minVerDistance || (absVerDistance == minVerDistance && absHorDistance < minHorDistance))
{
minVerDistance = absVerDistance;
minHorDistance = absHorDistance;
closestLine = lineResult;
}
//Update closest manhattan. We decide which metric to choose later.
double manhattan = 5*absVerDistance + absHorDistance;
//Consider removing second condition, or perhaps come up with an exponential weighting for vertical.
if (manhattan < minManhattan && absVerDistance < lineResult.LayoutBox.Height)
{
minManhattan = manhattan;
closestManhattan = lineResult;
}
}
//We couldn't find the next line below. Return the closest line in this case
if (closestLine != null)
{
if (closestManhattan != null && (closestManhattan.LayoutBox.Left > closestLine.LayoutBox.Right || closestLine.LayoutBox.Left > closestManhattan.LayoutBox.Right))
{
// they don't overlap, so go with closer one
return closestManhattan.Nodes;
}
// no manhattan, or they overlap/are in same column
return closestLine.Nodes;
}
return null;
}
//-------------------------------------
// Flow Order
//-------------------------------------
internal void SetFlowBoundary(FlowNode flowStart, FlowNode flowEnd)
{
Debug.Assert(flowStart != null && flowStart.Type != FlowNodeType.Virtual);
Debug.Assert(flowEnd != null && flowEnd.Type != FlowNodeType.Virtual);
_flowStart = flowStart;
_flowEnd = flowEnd;
}
#if DEBUG
private void DrawRectOutline(DrawingContext dc, Pen pen, Rect rect)
{
Debug.Assert(!rect.IsEmpty);
dc.DrawLine(pen, rect.TopLeft, rect.TopRight);
dc.DrawLine(pen, rect.TopRight, rect.BottomRight);
dc.DrawLine(pen, rect.BottomRight, rect.BottomLeft);
dc.DrawLine(pen, rect.BottomLeft, rect.TopLeft);
}
internal void RenderLayoutBox(DrawingContext dc)
{
Pen pen = new Pen(Brushes.Blue, 1);
Rect rect;
for (int line = 0; line < _lineResults.Length; line++)
{
rect = _lineResults[line].LayoutBox;
if (!rect.IsEmpty)
{
DrawRectOutline(dc, pen, rect);
}
}
}
private Point CreateFromLastTextPoint(Point p)
{
// those is always in the left margin area
Point newp = new Point(1, p.Y + 10);
return newp;
}
internal void RenderFixedNode(DrawingContext dc)
{
//
//Iterate through fix node to draw red dotted line
//
CultureInfo EnglishCulture = System.Windows.Markup.TypeConverterHelper.InvariantEnglishUS;
int lineCount = _lineResults.Length;
if (lineCount == 0)
return;
FixedNode fixedStartPage = _lineResults[0].Start;
FixedNode fixedEndPage = _lineResults[lineCount-1].End;
FixedNode[] fixedNodes = _fixedTextBuilder.FixedFlowMap.FixedOrderGetRangeNodes(fixedStartPage, fixedEndPage);
FixedPage fp = _fixedTextBuilder.FixedTextContainer.FixedDocument.GetFixedPage(PageIndex);
FormattedText ft;
Point prevTextPoint = new Point(0, 0);
foreach (FixedNode currentFixedNode in fixedNodes)
{
if (currentFixedNode.Page == FixedFlowMap.FixedOrderStartPage)
{
prevTextPoint.X = prevTextPoint.Y = 0;
ft = new FormattedText("FixedOrderStartPage",
EnglishCulture,
FlowDirection.LeftToRight,
new Typeface("Courier New"),
8,
Brushes.DarkViolet);
dc.DrawText(ft, prevTextPoint);
continue;
}
if (currentFixedNode.Page == FixedFlowMap.FixedOrderEndPage)
{
prevTextPoint.X = fp.Width - 100;
prevTextPoint.Y = fp.Height - 10;
ft = new FormattedText("FixedOrderEndPage",
EnglishCulture,
FlowDirection.LeftToRight,
new Typeface("Courier New"),
8,
Brushes.DarkViolet);
dc.DrawText(ft, prevTextPoint);
continue;
}
if (currentFixedNode[1] == FixedFlowMap.FixedOrderStartVisual ||
currentFixedNode[1] == FixedFlowMap.FixedOrderEndVisual)
{
prevTextPoint.X = 2;
prevTextPoint.Y = prevTextPoint.Y + 10;
String outputString = currentFixedNode[1] == FixedFlowMap.FixedOrderStartVisual ?
"FixedOrderStartVisual" : "FixedOrderEndVisual";
ft = new FormattedText(outputString,
EnglishCulture,
FlowDirection.LeftToRight,
new Typeface("Courier New"),
8,
Brushes.DarkViolet);
dc.DrawText(ft, prevTextPoint);
continue;
}
DependencyObject dependencyObject = fp.GetElement(currentFixedNode);
Image image = dependencyObject as Image;
if (image != null)
{
GeneralTransform transform = image.TransformToAncestor(fp);
// You can't use GetContentBounds inside OnRender
Rect boundingRect = new Rect(0, 0, image.Width, image.Height);
Rect imageRect = transform.TransformBounds(boundingRect);
if (!imageRect.IsEmpty)
{
// Image might overlap, inflate the box.
imageRect.Inflate(1, 1);
Pen pen = new Pen(Brushes.DarkMagenta, 1.5);
DrawRectOutline(dc, pen, imageRect);
prevTextPoint.X = imageRect.Right;
prevTextPoint.Y = imageRect.Bottom - 10;
}
else
{
prevTextPoint.X = 2;
prevTextPoint.Y = prevTextPoint.Y + 10;
}
ft = new FormattedText(currentFixedNode.ToString(),
EnglishCulture,
FlowDirection.LeftToRight,
new Typeface("Courier New"),
8,
Brushes.DarkViolet);
dc.DrawText(ft, prevTextPoint);
continue;
}
Path path = dependencyObject as Path;
if (path != null)
{
GeneralTransform transform = path.TransformToAncestor(fp);
// You can't use GetContentBounds inside OnRender
Rect boundingRect = path.Data.Bounds;
Rect imageRect = transform.TransformBounds(boundingRect);
if (!imageRect.IsEmpty)
{
// Image might overlap, inflate the box.
imageRect.Inflate(1, 1);
Pen pen = new Pen(Brushes.DarkMagenta, 1.5);
DrawRectOutline(dc, pen, imageRect);
prevTextPoint.X = imageRect.Right;
prevTextPoint.Y = imageRect.Bottom - 10;
}
else
{
prevTextPoint.X = 2;
prevTextPoint.Y = prevTextPoint.Y + 10;
}
ft = new FormattedText(currentFixedNode.ToString(),
EnglishCulture,
FlowDirection.LeftToRight,
new Typeface("Courier New"),
8,
Brushes.DarkViolet);
dc.DrawText(ft, prevTextPoint);
continue;
}
Glyphs glyphs = dependencyObject as Glyphs;
if (glyphs != null)
{
GlyphRun run = glyphs.ToGlyphRun();
if (run != null)
{
Rect glyphBox = run.ComputeAlignmentBox();
glyphBox.Offset(glyphs.OriginX, glyphs.OriginY);
GeneralTransform transform = glyphs.TransformToAncestor(fp);
//
// Draw it using the dotted red line
//
Pen pen = new Pen(Brushes.Red, 0.5);
Transform t = transform.AffineTransform;
if (t != null)
{
dc.PushTransform(t);
}
else
{
dc.PushTransform(Transform.Identity);
}
DrawRectOutline(dc, pen, glyphBox);
prevTextPoint.X = glyphBox.Right;
prevTextPoint.Y = glyphBox.Bottom;
transform.TryTransform(prevTextPoint, out prevTextPoint);
dc.Pop(); // transform
}
else
{
prevTextPoint.X = 2;
prevTextPoint.Y = prevTextPoint.Y + 10;
}
ft = new FormattedText(currentFixedNode.ToString(),
EnglishCulture,
FlowDirection.LeftToRight,
new Typeface("Courier New"),
8,
Brushes.DarkViolet);
dc.DrawText(ft, prevTextPoint);
continue;
}
//
// For anything else, there is this code to draw ...
//
prevTextPoint.X = 2;
prevTextPoint.Y = prevTextPoint.Y + 10;
ft = new FormattedText(currentFixedNode.ToString(),
EnglishCulture,
FlowDirection.LeftToRight,
new Typeface("Courier New"),
8,
Brushes.DarkViolet);
dc.DrawText(ft, prevTextPoint);
}
}
internal void RenderFlowNode(DrawingContext dc)
{
FormattedText ft;
FixedNode fixedNode;
FixedSOMElement[] somElements;
String ouptputString;
FixedElement fixedElement;
Random random = new Random();
CultureInfo EnglishCulture = System.Windows.Markup.TypeConverterHelper.InvariantEnglishUS;
FixedPage fp = _fixedTextBuilder.FixedTextContainer.FixedDocument.GetFixedPage(PageIndex);
//
//Iterate through flow node to draw Transparent Rect and draw its index
//
Point prevTextPoint=new Point(0, 0);
for (int i = FlowStart.Fp; i <= FlowEnd.Fp; i++)
{
FlowNode fn = _fixedTextBuilder.FixedFlowMap[i];
switch (fn.Type)
{
case FlowNodeType.Boundary :
case FlowNodeType.Virtual :
// this two cases won't happen.
Debug.Assert(false);
break;
case FlowNodeType.Start :
case FlowNodeType.End :
{
fixedElement = fn.Cookie as FixedElement;
String typeString = fixedElement.Type.ToString();
int indexofDot = typeString.LastIndexOf('.');
ouptputString = String.Format("{0}-{1}",
fn.ToString(),
typeString.Substring(indexofDot+1));
ft = new FormattedText(ouptputString,
EnglishCulture,
FlowDirection.LeftToRight,
new Typeface("Courier New"),
8,
Brushes.DarkGreen);
// Ideally, for FlowNodeType.Start, this should find next FlowNode with physical location,
// and draw it around the physical location.
prevTextPoint = CreateFromLastTextPoint(prevTextPoint);
dc.DrawText(ft, prevTextPoint);
break;
}
case FlowNodeType.Noop:
ft = new FormattedText(fn.ToString(),
EnglishCulture,
FlowDirection.LeftToRight,
new Typeface("Courier New"),
8,
Brushes.DarkGreen);
prevTextPoint = CreateFromLastTextPoint(prevTextPoint);
dc.DrawText(ft, prevTextPoint);
break;
case FlowNodeType.Run :
//
// Paint the region. The rect is the union of child glyphs.
//
Glyphs glyphs;
Rect flowRunBox = Rect.Empty;
Rect glyphBox;
somElements = _fixedTextBuilder.FixedFlowMap.FlowNodes[fn.Fp].FixedSOMElements;
foreach (FixedSOMElement currentSomeElement in somElements)
{
FixedNode currentFixedNode = currentSomeElement.FixedNode;
int startIndex = currentSomeElement.StartIndex;
int endIndex = currentSomeElement.EndIndex;
// same as (_IsBoundaryFixedNode(currentFixedNode))
if (currentFixedNode.Page == FixedFlowMap.FixedOrderStartPage ||
currentFixedNode.Page == FixedFlowMap.FixedOrderEndPage ||
currentFixedNode[1] == FixedFlowMap.FixedOrderStartVisual ||
currentFixedNode[1] == FixedFlowMap.FixedOrderEndVisual)
{
continue;
}
glyphs = fp.GetGlyphsElement(currentFixedNode);
Debug.Assert(glyphs!= null);
glyphBox = FixedTextView._GetGlyphRunDesignRect(glyphs, startIndex, endIndex);
if (!glyphBox.IsEmpty)
{
GeneralTransform g = glyphs.TransformToAncestor(fp);
glyphBox = g.TransformBounds(glyphBox);
}
flowRunBox.Union(glyphBox);
}
if (flowRunBox.IsEmpty)
{
Debug.Assert(false);
}
prevTextPoint.X = flowRunBox.Right;
prevTextPoint.Y = flowRunBox.Bottom - random.Next(15);
// Draw something the upper left corner of region.
ft = new FormattedText(fn.ToString() + "-" + Convert.ToString((int)(fn.Cookie)) +
"-" + Convert.ToString(somElements.Length),
EnglishCulture,
FlowDirection.LeftToRight,
new Typeface("Courier New"),
8,
Brushes.DarkBlue);
dc.DrawText(ft, prevTextPoint);
Pen pen = new Pen(Brushes.Blue, 2);
flowRunBox.Inflate(random.Next(3), random.Next(3));
DrawRectOutline(dc, pen, flowRunBox);
break;
case FlowNodeType.Object:
//
// Find the mapping fixed node
//
somElements = _fixedTextBuilder.FixedFlowMap.FlowNodes[fn.Fp].FixedSOMElements;
foreach (FixedSOMElement currentSomeElement in somElements)
{
fixedNode = currentSomeElement.FixedNode;
DependencyObject dependencyObject = fp.GetElement(fixedNode);
Image image = dependencyObject as Image;
Path path = dependencyObject as Path;
if (image != null || path != null)
{
Rect imageRect, boundingRect = Rect.Empty;
//
// Get Image bounding box.
//
GeneralTransform transform = ((Visual)dependencyObject).TransformToAncestor(fp);
// You can't use GetContentBounds inside OnRender
if (image != null)
{
boundingRect = new Rect(0, 0, image.Width, image.Height);
}
else
{
boundingRect = path.Data.Bounds;
}
if (!boundingRect.IsEmpty)
{
imageRect = transform.TransformBounds(boundingRect);
// Image might overlap, inflate the box.
imageRect.Inflate(3, 3);
dc.DrawRectangle(Brushes.CadetBlue, null, imageRect);
prevTextPoint.X = imageRect.Right;
prevTextPoint.Y = imageRect.Top;
}
}
else
{
//
// If the object is the Image type(that is not likey).
// Use the last Point to infer a comment area!
//
Debug.Assert(false);
}
fixedElement = fn.Cookie as FixedElement;
ft = new FormattedText(fn.ToString(),
EnglishCulture,
FlowDirection.LeftToRight,
new Typeface("Courier New"),
8,
Brushes.DarkGreen);
dc.DrawText(ft, prevTextPoint);
}
break;
default:
Debug.Assert(false);
break;
}
}
}
internal void RenderLines(DrawingContext dc)
{
for (int i=0; i<_lineResults.Length; i++)
{
FixedLineResult lineResult = _lineResults[i];
Pen pen = new Pen(Brushes.Red, 1);
Rect layoutBox = lineResult.LayoutBox;
dc.DrawRectangle(null, pen , layoutBox);
CultureInfo EnglishCulture = System.Windows.Markup.TypeConverterHelper.InvariantEnglishUS;
FormattedText ft = new FormattedText(i.ToString(),
EnglishCulture,
FlowDirection.LeftToRight,
new Typeface("Arial"),
10,
Brushes.White);
Point labelLocation = new Point(layoutBox.Left-25, (layoutBox.Bottom + layoutBox.Top)/2 - 10);
Geometry geom = ft.BuildHighlightGeometry(labelLocation);
Pen backgroundPen = new Pen(Brushes.Black,1);
dc.DrawGeometry(Brushes.Black, backgroundPen, geom);
dc.DrawText(ft, labelLocation);
}
}
#endif
public void ConstructFixedSOMPage(List<FixedNode> fixedNodes)
{
Debug.Assert(_fixedSOMPageConstructor != null);
_fixedSOMPageConstructor.ConstructPageStructure(fixedNodes);
}
#endregion Internal Methods
//--------------------------------------------------------------------
//
// Internal Properties
//
//---------------------------------------------------------------------
#region Internal Properties
internal FixedNode[] LastLine
{
get
{
if (_lineResults.Length > 0)
{
return _lineResults[_lineResults.Length - 1].Nodes;
}
return null;
}
}
internal FixedNode[] FirstLine
{
get
{
if (_lineResults.Length > 0)
{
return _lineResults[0].Nodes;
}
return null;
}
}
//-------------------------------------
// Page
//-------------------------------------
internal int PageIndex
{
get
{
return _pageIndex;
}
}
//-------------------------------------
// Virtualization
//-------------------------------------
internal bool Loaded
{
get
{
return (_flowStart != null && _flowStart.Type != FlowNodeType.Virtual);
}
}
//-------------------------------------
// Flow Order
//-------------------------------------
internal FlowNode FlowStart
{
get
{
return _flowStart;
}
}
internal FlowNode FlowEnd
{
get
{
return _flowEnd;
}
}
//-------------------------------------
// Fixed Order
//-------------------------------------
internal FixedSOMPage FixedSOMPage
{
get
{
return _fixedSOMPage;
}
set
{
_fixedSOMPage = value;
}
}
internal FixedDSBuilder FixedDSBuilder
{
get
{
return _fixedDSBuilder;
}
set
{
_fixedDSBuilder = value;
}
}
internal FixedSOMPageConstructor PageConstructor
{
get
{
return _fixedSOMPageConstructor;
}
set
{
_fixedSOMPageConstructor = value;
}
}
#if DEBUG
internal FixedTextBuilder FixedTextBuilder
{
get
{
return _fixedTextBuilder;
}
set
{
_fixedTextBuilder = value;
}
}
internal FlowNode[] FlowNodes
{
get
{
if (_flowNodes == null)
{
List<FlowNode> nodes = new List<FlowNode>();
//Find the start of flow nodes
int flowCount = this.FixedTextBuilder.FixedFlowMap.FlowCount;
FlowNode flowNode = null;
int startIdx = 0;
if (flowCount > 0)
{
do
{
flowNode = this.FixedTextBuilder.FixedFlowMap.FlowNodes[startIdx++];
if (this.FlowStart == flowNode)
{
break;
}
}
while (startIdx < flowCount);
}
if (startIdx < flowCount)
{
do
{
flowNode = this.FixedTextBuilder.FixedFlowMap.FlowNodes[startIdx++];
nodes.Add(flowNode);
}while (startIdx < flowCount && this.FlowEnd != flowNode);
}
_flowNodes = nodes.ToArray();
}
return _flowNodes;
}
}
internal List<FixedNode> FixedNodes
{
get
{
return _fixedNodes;
}
set
{
_fixedNodes = value;
}
}
#endif
#endregion Internal Properties
//--------------------------------------------------------------------
//
// Private Fields
//
//---------------------------------------------------------------------
#region Private Fields
private readonly int _pageIndex;
// Flow Order Boundary
private FlowNode _flowStart;
private FlowNode _flowEnd;
// Fixed Order Boundary
private FixedNode _fixedStart;
private FixedNode _fixedEnd;
private FixedSOMPageConstructor _fixedSOMPageConstructor;
private FixedSOMPage _fixedSOMPage;
private FixedDSBuilder _fixedDSBuilder;
// Baseline sorted line results
private FixedLineResult[] _lineResults;
//Determines whether a point is close enough to a line when determining snap to line
#if DEBUG
private FixedTextBuilder _fixedTextBuilder;
private FlowNode[] _flowNodes; //Flow nodes for this page
private List<FixedNode> _fixedNodes;
#endif
#endregion Private Fields
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.3053
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
//
// This source code was auto-generated by wsdl, Version=2.0.50727.42.
//
namespace WebsitePanel.EnterpriseServer {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
using System.Data;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="esAuditLogSoap", Namespace="http://smbsaas/websitepanel/enterpriseserver")]
public partial class esAuditLog : Microsoft.Web.Services3.WebServicesClientProtocol {
private System.Threading.SendOrPostCallback GetAuditLogRecordsPagedOperationCompleted;
private System.Threading.SendOrPostCallback GetAuditLogSourcesOperationCompleted;
private System.Threading.SendOrPostCallback GetAuditLogTasksOperationCompleted;
private System.Threading.SendOrPostCallback GetAuditLogRecordOperationCompleted;
private System.Threading.SendOrPostCallback DeleteAuditLogRecordsOperationCompleted;
private System.Threading.SendOrPostCallback DeleteAuditLogRecordsCompleteOperationCompleted;
/// <remarks/>
public esAuditLog() {
this.Url = "http://127.0.0.1:9002/esAuditLog.asmx";
}
/// <remarks/>
public event GetAuditLogRecordsPagedCompletedEventHandler GetAuditLogRecordsPagedCompleted;
/// <remarks/>
public event GetAuditLogSourcesCompletedEventHandler GetAuditLogSourcesCompleted;
/// <remarks/>
public event GetAuditLogTasksCompletedEventHandler GetAuditLogTasksCompleted;
/// <remarks/>
public event GetAuditLogRecordCompletedEventHandler GetAuditLogRecordCompleted;
/// <remarks/>
public event DeleteAuditLogRecordsCompletedEventHandler DeleteAuditLogRecordsCompleted;
/// <remarks/>
public event DeleteAuditLogRecordsCompleteCompletedEventHandler DeleteAuditLogRecordsCompleteCompleted;
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetAuditLogRecordsPaged", RequestNamespace="http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace="http://smbsaas/websitepanel/enterpriseserver", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public System.Data.DataSet GetAuditLogRecordsPaged(int userId, int packageId, int itemId, string itemName, System.DateTime startDate, System.DateTime endDate, int severityId, string sourceName, string taskName, string sortColumn, int startRow, int maximumRows) {
object[] results = this.Invoke("GetAuditLogRecordsPaged", new object[] {
userId,
packageId,
itemId,
itemName,
startDate,
endDate,
severityId,
sourceName,
taskName,
sortColumn,
startRow,
maximumRows});
return ((System.Data.DataSet)(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginGetAuditLogRecordsPaged(int userId, int packageId, int itemId, string itemName, System.DateTime startDate, System.DateTime endDate, int severityId, string sourceName, string taskName, string sortColumn, int startRow, int maximumRows, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("GetAuditLogRecordsPaged", new object[] {
userId,
packageId,
itemId,
itemName,
startDate,
endDate,
severityId,
sourceName,
taskName,
sortColumn,
startRow,
maximumRows}, callback, asyncState);
}
/// <remarks/>
public System.Data.DataSet EndGetAuditLogRecordsPaged(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((System.Data.DataSet)(results[0]));
}
/// <remarks/>
public void GetAuditLogRecordsPagedAsync(int userId, int packageId, int itemId, string itemName, System.DateTime startDate, System.DateTime endDate, int severityId, string sourceName, string taskName, string sortColumn, int startRow, int maximumRows) {
this.GetAuditLogRecordsPagedAsync(userId, packageId, itemId, itemName, startDate, endDate, severityId, sourceName, taskName, sortColumn, startRow, maximumRows, null);
}
/// <remarks/>
public void GetAuditLogRecordsPagedAsync(int userId, int packageId, int itemId, string itemName, System.DateTime startDate, System.DateTime endDate, int severityId, string sourceName, string taskName, string sortColumn, int startRow, int maximumRows, object userState) {
if ((this.GetAuditLogRecordsPagedOperationCompleted == null)) {
this.GetAuditLogRecordsPagedOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetAuditLogRecordsPagedOperationCompleted);
}
this.InvokeAsync("GetAuditLogRecordsPaged", new object[] {
userId,
packageId,
itemId,
itemName,
startDate,
endDate,
severityId,
sourceName,
taskName,
sortColumn,
startRow,
maximumRows}, this.GetAuditLogRecordsPagedOperationCompleted, userState);
}
private void OnGetAuditLogRecordsPagedOperationCompleted(object arg) {
if ((this.GetAuditLogRecordsPagedCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.GetAuditLogRecordsPagedCompleted(this, new GetAuditLogRecordsPagedCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetAuditLogSources", RequestNamespace="http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace="http://smbsaas/websitepanel/enterpriseserver", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public System.Data.DataSet GetAuditLogSources() {
object[] results = this.Invoke("GetAuditLogSources", new object[0]);
return ((System.Data.DataSet)(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginGetAuditLogSources(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("GetAuditLogSources", new object[0], callback, asyncState);
}
/// <remarks/>
public System.Data.DataSet EndGetAuditLogSources(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((System.Data.DataSet)(results[0]));
}
/// <remarks/>
public void GetAuditLogSourcesAsync() {
this.GetAuditLogSourcesAsync(null);
}
/// <remarks/>
public void GetAuditLogSourcesAsync(object userState) {
if ((this.GetAuditLogSourcesOperationCompleted == null)) {
this.GetAuditLogSourcesOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetAuditLogSourcesOperationCompleted);
}
this.InvokeAsync("GetAuditLogSources", new object[0], this.GetAuditLogSourcesOperationCompleted, userState);
}
private void OnGetAuditLogSourcesOperationCompleted(object arg) {
if ((this.GetAuditLogSourcesCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.GetAuditLogSourcesCompleted(this, new GetAuditLogSourcesCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetAuditLogTasks", RequestNamespace="http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace="http://smbsaas/websitepanel/enterpriseserver", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public System.Data.DataSet GetAuditLogTasks(string sourceName) {
object[] results = this.Invoke("GetAuditLogTasks", new object[] {
sourceName});
return ((System.Data.DataSet)(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginGetAuditLogTasks(string sourceName, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("GetAuditLogTasks", new object[] {
sourceName}, callback, asyncState);
}
/// <remarks/>
public System.Data.DataSet EndGetAuditLogTasks(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((System.Data.DataSet)(results[0]));
}
/// <remarks/>
public void GetAuditLogTasksAsync(string sourceName) {
this.GetAuditLogTasksAsync(sourceName, null);
}
/// <remarks/>
public void GetAuditLogTasksAsync(string sourceName, object userState) {
if ((this.GetAuditLogTasksOperationCompleted == null)) {
this.GetAuditLogTasksOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetAuditLogTasksOperationCompleted);
}
this.InvokeAsync("GetAuditLogTasks", new object[] {
sourceName}, this.GetAuditLogTasksOperationCompleted, userState);
}
private void OnGetAuditLogTasksOperationCompleted(object arg) {
if ((this.GetAuditLogTasksCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.GetAuditLogTasksCompleted(this, new GetAuditLogTasksCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetAuditLogRecord", RequestNamespace="http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace="http://smbsaas/websitepanel/enterpriseserver", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public LogRecord GetAuditLogRecord(string recordId) {
object[] results = this.Invoke("GetAuditLogRecord", new object[] {
recordId});
return ((LogRecord)(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginGetAuditLogRecord(string recordId, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("GetAuditLogRecord", new object[] {
recordId}, callback, asyncState);
}
/// <remarks/>
public LogRecord EndGetAuditLogRecord(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((LogRecord)(results[0]));
}
/// <remarks/>
public void GetAuditLogRecordAsync(string recordId) {
this.GetAuditLogRecordAsync(recordId, null);
}
/// <remarks/>
public void GetAuditLogRecordAsync(string recordId, object userState) {
if ((this.GetAuditLogRecordOperationCompleted == null)) {
this.GetAuditLogRecordOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetAuditLogRecordOperationCompleted);
}
this.InvokeAsync("GetAuditLogRecord", new object[] {
recordId}, this.GetAuditLogRecordOperationCompleted, userState);
}
private void OnGetAuditLogRecordOperationCompleted(object arg) {
if ((this.GetAuditLogRecordCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.GetAuditLogRecordCompleted(this, new GetAuditLogRecordCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/DeleteAuditLogRecords", RequestNamespace="http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace="http://smbsaas/websitepanel/enterpriseserver", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public int DeleteAuditLogRecords(int userId, int itemId, string itemName, System.DateTime startDate, System.DateTime endDate, int severityId, string sourceName, string taskName) {
object[] results = this.Invoke("DeleteAuditLogRecords", new object[] {
userId,
itemId,
itemName,
startDate,
endDate,
severityId,
sourceName,
taskName});
return ((int)(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginDeleteAuditLogRecords(int userId, int itemId, string itemName, System.DateTime startDate, System.DateTime endDate, int severityId, string sourceName, string taskName, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("DeleteAuditLogRecords", new object[] {
userId,
itemId,
itemName,
startDate,
endDate,
severityId,
sourceName,
taskName}, callback, asyncState);
}
/// <remarks/>
public int EndDeleteAuditLogRecords(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((int)(results[0]));
}
/// <remarks/>
public void DeleteAuditLogRecordsAsync(int userId, int itemId, string itemName, System.DateTime startDate, System.DateTime endDate, int severityId, string sourceName, string taskName) {
this.DeleteAuditLogRecordsAsync(userId, itemId, itemName, startDate, endDate, severityId, sourceName, taskName, null);
}
/// <remarks/>
public void DeleteAuditLogRecordsAsync(int userId, int itemId, string itemName, System.DateTime startDate, System.DateTime endDate, int severityId, string sourceName, string taskName, object userState) {
if ((this.DeleteAuditLogRecordsOperationCompleted == null)) {
this.DeleteAuditLogRecordsOperationCompleted = new System.Threading.SendOrPostCallback(this.OnDeleteAuditLogRecordsOperationCompleted);
}
this.InvokeAsync("DeleteAuditLogRecords", new object[] {
userId,
itemId,
itemName,
startDate,
endDate,
severityId,
sourceName,
taskName}, this.DeleteAuditLogRecordsOperationCompleted, userState);
}
private void OnDeleteAuditLogRecordsOperationCompleted(object arg) {
if ((this.DeleteAuditLogRecordsCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.DeleteAuditLogRecordsCompleted(this, new DeleteAuditLogRecordsCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/DeleteAuditLogRecordsComplete", RequestNamespace="http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace="http://smbsaas/websitepanel/enterpriseserver", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public int DeleteAuditLogRecordsComplete() {
object[] results = this.Invoke("DeleteAuditLogRecordsComplete", new object[0]);
return ((int)(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginDeleteAuditLogRecordsComplete(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("DeleteAuditLogRecordsComplete", new object[0], callback, asyncState);
}
/// <remarks/>
public int EndDeleteAuditLogRecordsComplete(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((int)(results[0]));
}
/// <remarks/>
public void DeleteAuditLogRecordsCompleteAsync() {
this.DeleteAuditLogRecordsCompleteAsync(null);
}
/// <remarks/>
public void DeleteAuditLogRecordsCompleteAsync(object userState) {
if ((this.DeleteAuditLogRecordsCompleteOperationCompleted == null)) {
this.DeleteAuditLogRecordsCompleteOperationCompleted = new System.Threading.SendOrPostCallback(this.OnDeleteAuditLogRecordsCompleteOperationCompleted);
}
this.InvokeAsync("DeleteAuditLogRecordsComplete", new object[0], this.DeleteAuditLogRecordsCompleteOperationCompleted, userState);
}
private void OnDeleteAuditLogRecordsCompleteOperationCompleted(object arg) {
if ((this.DeleteAuditLogRecordsCompleteCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.DeleteAuditLogRecordsCompleteCompleted(this, new DeleteAuditLogRecordsCompleteCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
public new void CancelAsync(object userState) {
base.CancelAsync(userState);
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void GetAuditLogRecordsPagedCompletedEventHandler(object sender, GetAuditLogRecordsPagedCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class GetAuditLogRecordsPagedCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal GetAuditLogRecordsPagedCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public System.Data.DataSet Result {
get {
this.RaiseExceptionIfNecessary();
return ((System.Data.DataSet)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void GetAuditLogSourcesCompletedEventHandler(object sender, GetAuditLogSourcesCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class GetAuditLogSourcesCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal GetAuditLogSourcesCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public System.Data.DataSet Result {
get {
this.RaiseExceptionIfNecessary();
return ((System.Data.DataSet)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void GetAuditLogTasksCompletedEventHandler(object sender, GetAuditLogTasksCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class GetAuditLogTasksCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal GetAuditLogTasksCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public System.Data.DataSet Result {
get {
this.RaiseExceptionIfNecessary();
return ((System.Data.DataSet)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void GetAuditLogRecordCompletedEventHandler(object sender, GetAuditLogRecordCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class GetAuditLogRecordCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal GetAuditLogRecordCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public LogRecord Result {
get {
this.RaiseExceptionIfNecessary();
return ((LogRecord)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void DeleteAuditLogRecordsCompletedEventHandler(object sender, DeleteAuditLogRecordsCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class DeleteAuditLogRecordsCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal DeleteAuditLogRecordsCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public int Result {
get {
this.RaiseExceptionIfNecessary();
return ((int)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void DeleteAuditLogRecordsCompleteCompletedEventHandler(object sender, DeleteAuditLogRecordsCompleteCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class DeleteAuditLogRecordsCompleteCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal DeleteAuditLogRecordsCompleteCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public int Result {
get {
this.RaiseExceptionIfNecessary();
return ((int)(this.results[0]));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace WindowsGame10
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
public SpriteBatch spriteBatch;
private static Game1 instance;
LifeBoard lifeBoard;
Texture2D mouseSprite;
private List<GameEntity> entities = new List<GameEntity>();
public List<GameEntity> Entities
{
get { return entities; }
}
public int Width
{
get
{
return GraphicsDevice.Viewport.Width;
}
}
public int Height
{
get
{
return GraphicsDevice.Viewport.Height;
}
}
public static Game1 Instance
{
get
{
return instance;
}
}
public Game1()
{
graphics = new GraphicsDeviceManager(this);
graphics.PreferredBackBufferWidth = 1024;
graphics.PreferredBackBufferHeight = 768;
graphics.IsFullScreen = false;
graphics.ApplyChanges();
Content.RootDirectory = "Content";
instance = this;
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
lifeBoard = new LifeBoard();
entities.Add(lifeBoard);
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
mouseSprite = Content.Load<Texture2D>("cursor");
for (int i = 0; i < entities.Count; i++)
{
entities[i].LoadContent();
}
// TODO: use this.Content to load your game content here
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
bool wasPressed = false;
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
KeyboardState state = Keyboard.GetState();
MouseState mouseState = Mouse.GetState();
if (state.IsKeyDown(Keys.Escape))
{
Exit();
}
if (state.IsKeyDown(Keys.Space) && !wasPressed)
{
lifeBoard.Paused = !lifeBoard.Paused;
wasPressed = true;
}
if (state.IsKeyDown(Keys.F1) && !wasPressed)
{
lifeBoard.Clear();
lifeBoard.Paused = true;
wasPressed = true;
}
if (state.IsKeyDown(Keys.F2) && !wasPressed)
{
lifeBoard.Clear();
lifeBoard.RandomBoard();
lifeBoard.Paused = true;
wasPressed = true;
}
if (state.IsKeyDown(Keys.F3) && !wasPressed)
{
Vector2 cellPos = lifeBoard.ScreenToCell(mouseState.X, mouseState.Y);
lifeBoard.MakeGlider((int) cellPos.X, (int) cellPos.Y);
wasPressed = true;
}
if (state.IsKeyDown(Keys.F4) && !wasPressed)
{
Vector2 cellPos = lifeBoard.ScreenToCell(mouseState.X, mouseState.Y);
lifeBoard.MakeTumbler((int)cellPos.X, (int)cellPos.Y);
wasPressed = true;
}
if (state.IsKeyDown(Keys.F5) && !wasPressed)
{
Vector2 cellPos = lifeBoard.ScreenToCell(mouseState.X, mouseState.Y);
lifeBoard.MakeLightWeightSpaceShip((int)cellPos.X, (int)cellPos.Y);
wasPressed = true;
}
if (state.IsKeyDown(Keys.F6) && !wasPressed)
{
Vector2 cellPos = lifeBoard.ScreenToCell(mouseState.X, mouseState.Y);
lifeBoard.MakeGosperGun((int)cellPos.X, (int)cellPos.Y);
wasPressed = true;
}
if (state.GetPressedKeys().Length == 0)
{
wasPressed = false;
}
if (mouseState.LeftButton == ButtonState.Pressed)
{
Vector2 cellPos = lifeBoard.ScreenToCell(mouseState.X, mouseState.Y);
lifeBoard.On((int) cellPos.X, (int) cellPos.Y);
}
if (mouseState.RightButton == ButtonState.Pressed)
{
Vector2 cellPos = lifeBoard.ScreenToCell(mouseState.X, mouseState.Y);
lifeBoard.Off((int)cellPos.X, (int)cellPos.Y);
}
for (int i = 0; i < entities.Count; i++)
{
entities[i].Update(gameTime);
if (entities[i].Alive == false)
{
entities.Remove(entities[i]);
}
}
// TODO: Add your update logic here
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Gray);
spriteBatch.Begin();
for (int i = 0; i < entities.Count; i++)
{
entities[i].Draw(gameTime);
}
MouseState mouseState = Mouse.GetState();
spriteBatch.Draw(mouseSprite, new Vector2(mouseState.X, mouseState.Y), Color.White);
// TODO: Add your drawing code here
spriteBatch.End();
base.Draw(gameTime);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using gView.Framework.system;
using gView.Framework.IO;
using gView.Framework.Data;
using System.Windows.Forms;
using gView.Framework.Carto;
using gView.Framework.Geometry;
namespace gView.Framework.UI
{
public interface IPropertyDialog
{
System.Windows.Forms.DialogResult Show();
object PropertyDialogObject();
}
public interface IPage
{
void Commit();
}
public interface IMapOptionPage : IPage
{
System.Windows.Forms.Panel OptionPage(IMapDocument document);
string Title { get; }
System.Drawing.Image Image { get; }
bool IsAvailable(IMapDocument document);
}
public interface ILayerPropertyPage : IPage
{
System.Windows.Forms.Panel PropertyPage(IDataset dataset, ILayer layer);
bool ShowWith(IDataset dataset, ILayer layer);
string Title { get; }
}
public interface IExplorerOptionPage : IPage
{
System.Windows.Forms.Panel OptionPage();
string Title { get; }
System.Drawing.Image Image { get; }
}
public interface IShortCut
{
Keys ShortcutKeys { get; }
string ShortcutKeyDisplayString { get; }
}
public interface IToolMouseActions
{
void MouseDown(IDisplay display, MouseEventArgs e, IPoint world);
void MouseUp(IDisplay display, MouseEventArgs e, IPoint world);
void MouseClick(IDisplay display, MouseEventArgs e, IPoint world);
void MouseDoubleClick(IDisplay display, MouseEventArgs e, IPoint world);
void MouseMove(IDisplay display, MouseEventArgs e, IPoint world);
void MouseWheel(IDisplay display, MouseEventArgs e, IPoint world);
}
public interface IToolMouseActions2
{
void BeforeShowContext(IDisplay display, MouseEventArgs e, IPoint world);
}
public interface IToolKeyActions
{
void KeyDown(IDisplay display, KeyEventArgs e);
void KeyPress(IDisplay display, KeyPressEventArgs e);
void KeyUp(IDisplay display, KeyEventArgs e);
}
public interface IConstructable
{
void ConstructMouseDown(IMapDocument doc, MouseEventArgs e);
void ConstructMouseUp(IMapDocument doc, MouseEventArgs e);
void ConstructMouseClick(IMapDocument doc, MouseEventArgs e);
void ConstructMouseDoubleClick(IMapDocument doc, MouseEventArgs e);
void ConstructMouseMove(IMapDocument doc, MouseEventArgs e);
void ConstructMouseWheel(IMapDocument doc, MouseEventArgs e);
bool hasVertices { get; }
}
public interface IToolItem
{
System.Windows.Forms.ToolStripItem ToolItem { get; }
}
public enum ToolItemLabelPosition { top = 0, bottom = 1,left=2,right=3 }
public interface IToolItemLabel
{
string Label { get; }
ToolItemLabelPosition LabelPosition { get; }
}
//public enum ToolbarPanel { top = 0, bottom = 1, left = 2, right = 3, flow = 4 }
public interface IToolbar : IPersistable
{
//bool Visible { get; set; }
//ToolbarPanel ParentPanel { get; set; }
string Name { get; }
List<System.Guid> GUIDs { get; set; }
}
public class RibbonItem
{
public RibbonItem(Guid guid)
: this(guid, String.Empty)
{
}
public RibbonItem(Guid guid, string sizeDefinition)
{
this.Guid = guid;
SizeDefinition = sizeDefinition;
}
public Guid Guid { get; private set; }
public string SizeDefinition { get; private set; }
}
public class RibbonGroupBox
{
public System.Windows.RoutedEventHandler OnLauncherClick = null;
public RibbonGroupBox(string header)
{
Header = header;
Items = new List<RibbonItem>();
}
public RibbonGroupBox(string header, RibbonItem[] items)
{
Header = header;
Items = new List<RibbonItem>(items);
}
public string Header { get; private set; }
public List<RibbonItem> Items;
public class LauncherClickEventArgs : System.Windows.RoutedEventArgs
{
public LauncherClickEventArgs(object hook)
{
Hook = hook;
}
public object Hook { get; private set; }
}
}
public interface ICartoRibbonTab : IOrder
{
string Header { get; }
List<RibbonGroupBox> Groups { get; }
bool IsVisible(IMapDocument mapDocument);
}
public interface IExplorerRibbonTab
{
string Header { get; }
List<RibbonGroupBox> Groups { get; }
int Order { get; }
}
public interface IExToolbar : IPersistable
{
//bool Visible { get; set; }
//ToolbarPanel ParentPanel { get; set; }
string Name { get; }
List<System.Guid> GUIDs { get; set; }
}
public interface IToolContextMenu
{
ContextMenuStrip ContextMenu { get; }
}
public interface IToolWindow
{
IDockableWindow ToolWindow { get; }
}
public interface IDocumentWindow
{
void RefreshControls(DrawPhase phase);
void AddChildWindow(System.Windows.Forms.Form child);
System.Windows.Forms.Form GetChildWindow(string Title);
}
public interface IGUIAppWindow : IWin32Window
{
}
public interface IGUIApplication : IApplication
{
event DockWindowAddedEvent DockWindowAdded;
event OnShowDockableWindowEvent OnShowDockableWindow;
void AddDockableWindow(IDockableWindow window, DockWindowState state);
void AddDockableWindow(IDockableWindow window, string ParentDockableWindowName);
void ShowDockableWindow(IDockableWindow window);
List<IDockableWindow> DockableWindows
{
get;
}
//List<object> ToolStrips
//{
// get;
//}
ITool Tool(Guid guid);
List<ITool> Tools { get; }
ITool ActiveTool { get; set; }
IToolbar Toolbar(Guid guid);
List<IToolbar> Toolbars { get; }
IGUIAppWindow ApplicationWindow { get; }
void ValidateUI();
IStatusBar StatusBar { get; }
void SetCursor(object cursor);
void AppendContextMenuItems(ContextMenuStrip strip, object context);
void ShowBackstageMenu();
void HideBackstageMenu();
}
public interface IMapApplication : IGUIApplication
{
event AfterLoadMapDocumentEvent AfterLoadMapDocument;
event ActiveMapToolChangedEvent ActiveMapToolChanged;
event OnCursorPosChangedEvent OnCursorPosChanged;
void LoadMapDocument(string filename);
void SaveMapDocument();
void SaveMapDocument(string filename, bool performEncryption);
string DocumentFilename
{
get;
set;
}
void RefreshActiveMap(DrawPhase drawPhase);
void RefreshTOC();
void RefreshTOCElement(IDatasetElement element);
IDocumentWindow DocumentWindow
{
get;
}
IMapApplicationModule IMapApplicationModule(Guid guid);
bool ReadOnly { get; }
//void DrawReversibleGeometry(IGeometry geometry, System.Drawing.Color color);
}
public delegate void ExplorerExecuteBatchCallback();
public interface IExplorerApplication : IGUIApplication
{
void ExecuteBatch(string batch, ExplorerExecuteBatchCallback callback);
List<IExplorerObject> SelectedObjects { get; }
bool MoveToTreeNode(string path);
void RefreshContents();
}
public interface IExplorerObjectContextMenu
{
ToolStripItem[] ContextMenuItems { get; }
}
public delegate void RefreshContextDelegate();
public interface IExplorerObjectContextMenu2
{
ToolStripItem[] ContextMenuItems(RefreshContextDelegate callback);
}
public interface IExplorerObjectContentDragDropEvents
{
void Content_DragDrop(System.Windows.Forms.DragEventArgs e);
void Content_DragEnter(System.Windows.Forms.DragEventArgs e);
void Content_DragLeave(System.EventArgs e);
void Content_DragOver(System.Windows.Forms.DragEventArgs e);
void Content_GiveFeedback(System.Windows.Forms.GiveFeedbackEventArgs e);
void Content_QueryContinueDrag(System.Windows.Forms.QueryContinueDragEventArgs e);
}
public interface IExplorerObjectContentDragDropEvents2 : IExplorerObjectContentDragDropEvents
{
void Content_DragDrop(System.Windows.Forms.DragEventArgs e, IUserData userdata);
void Content_DragEnter(System.Windows.Forms.DragEventArgs e, IUserData userdata);
void Content_DragLeave(System.EventArgs e, IUserData userdata);
void Content_DragOver(System.Windows.Forms.DragEventArgs e, IUserData userdata);
void Content_GiveFeedback(System.Windows.Forms.GiveFeedbackEventArgs e, IUserData userdata);
void Content_QueryContinueDrag(System.Windows.Forms.QueryContinueDragEventArgs e, IUserData userdata);
}
public interface IExplorerTabPage : IOrder
{
System.Windows.Forms.Control Control { get; }
//System.Guid ExplorerObjectGUID { get; }
void OnCreate(object hook);
void OnShow();
void OnHide();
IExplorerObject ExplorerObject
{
get;
set;
}
bool ShowWith(IExplorerObject exObject);
string Title { get; }
void RefreshContents();
}
}
| |
//
// LogicalType.cs.cs
//
// This file was generated by XMLSPY 2004 Enterprise Edition.
//
// YOU SHOULD NOT MODIFY THIS FILE, BECAUSE IT WILL BE
// OVERWRITTEN WHEN YOU RE-RUN CODE GENERATION.
//
// Refer to the XMLSPY Documentation for further details.
// http://www.altova.com/xmlspy
//
using System;
using System.Collections;
using System.Xml;
using Altova.Types;
namespace XMLRules
{
public class LogicalType : Altova.Node
{
#region Forward constructors
public LogicalType() : base() { SetCollectionParents(); }
public LogicalType(XmlDocument doc) : base(doc) { SetCollectionParents(); }
public LogicalType(XmlNode node) : base(node) { SetCollectionParents(); }
public LogicalType(Altova.Node node) : base(node) { SetCollectionParents(); }
#endregion // Forward constructors
public override void AdjustPrefix()
{
int nCount;
nCount = DomChildCount(NodeType.Element, "", "LHSLogicalExpression");
for (int i = 0; i < nCount; i++)
{
XmlNode DOMNode = GetDomChildAt(NodeType.Element, "", "LHSLogicalExpression", i);
InternalAdjustPrefix(DOMNode, true);
new LogicalExpression(DOMNode).AdjustPrefix();
}
nCount = DomChildCount(NodeType.Element, "", "LogicalOperator");
for (int i = 0; i < nCount; i++)
{
XmlNode DOMNode = GetDomChildAt(NodeType.Element, "", "LogicalOperator", i);
InternalAdjustPrefix(DOMNode, true);
new LogicalOperator(DOMNode).AdjustPrefix();
}
nCount = DomChildCount(NodeType.Element, "", "RHSLogicalExpression");
for (int i = 0; i < nCount; i++)
{
XmlNode DOMNode = GetDomChildAt(NodeType.Element, "", "RHSLogicalExpression", i);
InternalAdjustPrefix(DOMNode, true);
new LogicalExpression(DOMNode).AdjustPrefix();
}
}
#region LHSLogicalExpression accessor methods
public int GetLHSLogicalExpressionMinCount()
{
return 1;
}
public int LHSLogicalExpressionMinCount
{
get
{
return 1;
}
}
public int GetLHSLogicalExpressionMaxCount()
{
return 1;
}
public int LHSLogicalExpressionMaxCount
{
get
{
return 1;
}
}
public int GetLHSLogicalExpressionCount()
{
return DomChildCount(NodeType.Element, "", "LHSLogicalExpression");
}
public int LHSLogicalExpressionCount
{
get
{
return DomChildCount(NodeType.Element, "", "LHSLogicalExpression");
}
}
public bool HasLHSLogicalExpression()
{
return HasDomChild(NodeType.Element, "", "LHSLogicalExpression");
}
public LogicalExpression GetLHSLogicalExpressionAt(int index)
{
return new LogicalExpression(GetDomChildAt(NodeType.Element, "", "LHSLogicalExpression", index));
}
public LogicalExpression GetLHSLogicalExpression()
{
return GetLHSLogicalExpressionAt(0);
}
public LogicalExpression LHSLogicalExpression
{
get
{
return GetLHSLogicalExpressionAt(0);
}
}
public void RemoveLHSLogicalExpressionAt(int index)
{
RemoveDomChildAt(NodeType.Element, "", "LHSLogicalExpression", index);
}
public void RemoveLHSLogicalExpression()
{
while (HasLHSLogicalExpression())
RemoveLHSLogicalExpressionAt(0);
}
public void AddLHSLogicalExpression(LogicalExpression newValue)
{
AppendDomElement("", "LHSLogicalExpression", newValue);
}
public void InsertLHSLogicalExpressionAt(LogicalExpression newValue, int index)
{
InsertDomElementAt("", "LHSLogicalExpression", index, newValue);
}
public void ReplaceLHSLogicalExpressionAt(LogicalExpression newValue, int index)
{
ReplaceDomElementAt("", "LHSLogicalExpression", index, newValue);
}
#endregion // LHSLogicalExpression accessor methods
#region LHSLogicalExpression collection
public LHSLogicalExpressionCollection MyLHSLogicalExpressions = new LHSLogicalExpressionCollection( );
public class LHSLogicalExpressionCollection: IEnumerable
{
LogicalType parent;
public LogicalType Parent
{
set
{
parent = value;
}
}
public LHSLogicalExpressionEnumerator GetEnumerator()
{
return new LHSLogicalExpressionEnumerator(parent);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public class LHSLogicalExpressionEnumerator: IEnumerator
{
int nIndex;
LogicalType parent;
public LHSLogicalExpressionEnumerator(LogicalType par)
{
parent = par;
nIndex = -1;
}
public void Reset()
{
nIndex = -1;
}
public bool MoveNext()
{
nIndex++;
return(nIndex < parent.LHSLogicalExpressionCount );
}
public LogicalExpression Current
{
get
{
return(parent.GetLHSLogicalExpressionAt(nIndex));
}
}
object IEnumerator.Current
{
get
{
return(Current);
}
}
}
#endregion // LHSLogicalExpression collection
#region LogicalOperator accessor methods
public int GetLogicalOperatorMinCount()
{
return 1;
}
public int LogicalOperatorMinCount
{
get
{
return 1;
}
}
public int GetLogicalOperatorMaxCount()
{
return 1;
}
public int LogicalOperatorMaxCount
{
get
{
return 1;
}
}
public int GetLogicalOperatorCount()
{
return DomChildCount(NodeType.Element, "", "LogicalOperator");
}
public int LogicalOperatorCount
{
get
{
return DomChildCount(NodeType.Element, "", "LogicalOperator");
}
}
public bool HasLogicalOperator()
{
return HasDomChild(NodeType.Element, "", "LogicalOperator");
}
public LogicalOperator GetLogicalOperatorAt(int index)
{
return new LogicalOperator(GetDomChildAt(NodeType.Element, "", "LogicalOperator", index));
}
public LogicalOperator GetLogicalOperator()
{
return GetLogicalOperatorAt(0);
}
public LogicalOperator LogicalOperator
{
get
{
return GetLogicalOperatorAt(0);
}
}
public void RemoveLogicalOperatorAt(int index)
{
RemoveDomChildAt(NodeType.Element, "", "LogicalOperator", index);
}
public void RemoveLogicalOperator()
{
while (HasLogicalOperator())
RemoveLogicalOperatorAt(0);
}
public void AddLogicalOperator(LogicalOperator newValue)
{
AppendDomElement("", "LogicalOperator", newValue);
}
public void InsertLogicalOperatorAt(LogicalOperator newValue, int index)
{
InsertDomElementAt("", "LogicalOperator", index, newValue);
}
public void ReplaceLogicalOperatorAt(LogicalOperator newValue, int index)
{
ReplaceDomElementAt("", "LogicalOperator", index, newValue);
}
#endregion // LogicalOperator accessor methods
#region LogicalOperator collection
public LogicalOperatorCollection MyLogicalOperators = new LogicalOperatorCollection( );
public class LogicalOperatorCollection: IEnumerable
{
LogicalType parent;
public LogicalType Parent
{
set
{
parent = value;
}
}
public LogicalOperatorEnumerator GetEnumerator()
{
return new LogicalOperatorEnumerator(parent);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public class LogicalOperatorEnumerator: IEnumerator
{
int nIndex;
LogicalType parent;
public LogicalOperatorEnumerator(LogicalType par)
{
parent = par;
nIndex = -1;
}
public void Reset()
{
nIndex = -1;
}
public bool MoveNext()
{
nIndex++;
return(nIndex < parent.LogicalOperatorCount );
}
public LogicalOperator Current
{
get
{
return(parent.GetLogicalOperatorAt(nIndex));
}
}
object IEnumerator.Current
{
get
{
return(Current);
}
}
}
#endregion // LogicalOperator collection
#region RHSLogicalExpression accessor methods
public int GetRHSLogicalExpressionMinCount()
{
return 1;
}
public int RHSLogicalExpressionMinCount
{
get
{
return 1;
}
}
public int GetRHSLogicalExpressionMaxCount()
{
return 1;
}
public int RHSLogicalExpressionMaxCount
{
get
{
return 1;
}
}
public int GetRHSLogicalExpressionCount()
{
return DomChildCount(NodeType.Element, "", "RHSLogicalExpression");
}
public int RHSLogicalExpressionCount
{
get
{
return DomChildCount(NodeType.Element, "", "RHSLogicalExpression");
}
}
public bool HasRHSLogicalExpression()
{
return HasDomChild(NodeType.Element, "", "RHSLogicalExpression");
}
public LogicalExpression GetRHSLogicalExpressionAt(int index)
{
return new LogicalExpression(GetDomChildAt(NodeType.Element, "", "RHSLogicalExpression", index));
}
public LogicalExpression GetRHSLogicalExpression()
{
return GetRHSLogicalExpressionAt(0);
}
public LogicalExpression RHSLogicalExpression
{
get
{
return GetRHSLogicalExpressionAt(0);
}
}
public void RemoveRHSLogicalExpressionAt(int index)
{
RemoveDomChildAt(NodeType.Element, "", "RHSLogicalExpression", index);
}
public void RemoveRHSLogicalExpression()
{
while (HasRHSLogicalExpression())
RemoveRHSLogicalExpressionAt(0);
}
public void AddRHSLogicalExpression(LogicalExpression newValue)
{
AppendDomElement("", "RHSLogicalExpression", newValue);
}
public void InsertRHSLogicalExpressionAt(LogicalExpression newValue, int index)
{
InsertDomElementAt("", "RHSLogicalExpression", index, newValue);
}
public void ReplaceRHSLogicalExpressionAt(LogicalExpression newValue, int index)
{
ReplaceDomElementAt("", "RHSLogicalExpression", index, newValue);
}
#endregion // RHSLogicalExpression accessor methods
#region RHSLogicalExpression collection
public RHSLogicalExpressionCollection MyRHSLogicalExpressions = new RHSLogicalExpressionCollection( );
public class RHSLogicalExpressionCollection: IEnumerable
{
LogicalType parent;
public LogicalType Parent
{
set
{
parent = value;
}
}
public RHSLogicalExpressionEnumerator GetEnumerator()
{
return new RHSLogicalExpressionEnumerator(parent);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public class RHSLogicalExpressionEnumerator: IEnumerator
{
int nIndex;
LogicalType parent;
public RHSLogicalExpressionEnumerator(LogicalType par)
{
parent = par;
nIndex = -1;
}
public void Reset()
{
nIndex = -1;
}
public bool MoveNext()
{
nIndex++;
return(nIndex < parent.RHSLogicalExpressionCount );
}
public LogicalExpression Current
{
get
{
return(parent.GetRHSLogicalExpressionAt(nIndex));
}
}
object IEnumerator.Current
{
get
{
return(Current);
}
}
}
#endregion // RHSLogicalExpression collection
private void SetCollectionParents()
{
MyLHSLogicalExpressions.Parent = this;
MyLogicalOperators.Parent = this;
MyRHSLogicalExpressions.Parent = this;
}
}
}
| |
// 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.Runtime.CompilerServices;
namespace System
{
// This file contains wrapper classes that allow ProjectN to support
// arrays of more than one dimension. This is accomplished using the
// wrapper classes here and a set of IL transforms to map "normal"
// multidimensional arrays to these classes.
//
// Special support for this is baked into at least the following places:
// * The framework libraries (these classes)
// * UTC
// * IL Transforms
// * Dependency reducer engine
// * Debugger
// * Reflection APIs
//
// When building this solution (Nov 2014) there were applications in the
// Windows app store that contained references to Arrays up to seven
// dimensions. Because of this there will be simpler but slower paths for
// the eight+ dimension arrays.
//
// The desktop CLR supports arrays of up to 32 dimensions so that provides
// an upper limit on how much this needs to be built out.
// MDArray is a middle man class to help reflection.
public abstract class MDArray : Array
{
public abstract int MDGetUpperBound(int dimension);
public abstract void MDSetValue(Object value, params int[] indices);
public abstract Object MDGetValue(params int[] indices);
public abstract int MDRank { get; }
public abstract void MDInitialize(int[] indices);
// Exposes access to the SZArray that represents the "flattened view" of the array.
// This is used to implement api's that accept multidim arrays and operate on them
// as if they were actually SZArrays that concatenate the rows of the multidim array.
internal abstract Array MDFlattenedArray { get; }
}
public abstract class MDArrayRank2 : MDArray
{
public sealed override int MDRank
{
get
{
return 2;
}
}
}
public class MDArrayRank2<T> : MDArrayRank2
{
// Do not use field initializers on these fields. The implementation of CreateInstance() bypasses the normal constructor
// and calls MDInitialize() directly, so MDInitialize() must explicitly initialize all of the fields.
// The compiler takes a dependency on field ordering of this type, m_array must be first.
private T[] _array;
// Debugger(DBI) takes dependency on the ordering and layout of these fields.
// Please update DBI whenever these fields are updated or moved around.
// see ICorDebugArrayValue methods in rh\src\debug\dbi\values.cpp
private int _upperBound1;
private int _upperBound2;
// NoInlining is currently required because NUTC does not support inling of this constructor
// during static initialization of multi-dimensional arrays.
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public MDArrayRank2(int length1, int length2)
{
Initialize(length1, length2);
}
public override Object MDGetValue(params int[] indices)
{
if (indices.Length != 2)
throw new ArgumentException(SR.Arg_RankIndices);
CheckBounds(indices[0], indices[1]);
return _array[ComputeIndex(indices[0], indices[1])];
}
public T Get(int index1, int index2)
{
CheckBounds(index1, index2);
return _array[ComputeIndex(index1, index2)];
}
public override void MDSetValue(object value, params int[] indices)
{
if (indices.Length != 2)
throw new ArgumentException(SR.Arg_RankIndices);
CheckBounds(indices[0], indices[1]);
_array.SetValue(value, ComputeIndex(indices[0], indices[1]));
}
public override int MDGetUpperBound(int dimension)
{
switch (dimension)
{
case 0:
return _upperBound1 - 1;
case 1:
return _upperBound2 - 1;
default:
throw new IndexOutOfRangeException();
}
}
public sealed override void MDInitialize(int[] indices)
{
Initialize(indices[0], indices[1]);
}
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public void CheckBounds(int index1, int index2)
{
if ((index1 < 0) || (index1 >= _upperBound1))
{
throw new IndexOutOfRangeException();
}
if ((index2 < 0) || (index2 >= _upperBound2))
{
throw new IndexOutOfRangeException();
}
}
// This logic is duplicated in Redhawk DBI (implementation of ICorDebugArrayValue::GetElement)
// We should update it too whenever this method changes.
public int ComputeIndex(int index1, int index2)
{
// This arithmatic is unchecked because it is not possible to create
// an array that would satisfy bounds checks AND overflow the math
// here.
return (_upperBound2 * index1) + index2;
}
public void Set(int index1, int index2, T value)
{
CheckBounds(index1, index2);
_array[ComputeIndex(index1, index2)] = value;
}
internal sealed override Array MDFlattenedArray
{
get
{
return _array;
}
}
private void Initialize(int length1, int length2)
{
if (length1 < 0 || length2 < 0)
throw new OverflowException();
_array = new T[checked(length1 * length2)];
_upperBound1 = length1;
_upperBound2 = length2;
SetLength(_array.Length);
}
}
public abstract class MDArrayRank3 : MDArray
{
public sealed override int MDRank
{
get
{
return 3;
}
}
}
public class MDArrayRank3<T> : MDArrayRank3
{
// Do not use field initializers on these fields. The implementation of CreateInstance() bypasses the normal constructor
// and calls MDInitialize() directly, so MDInitialize() must explicitly initialize all of the fields.
// The compiler takes a dependency on field ordering of this type, m_array must be first.
private T[] _array;
// Debugger(DBI) takes dependency on the ordering and layout of these fields.
// Please update DBI whenever these fields are updated or moved around.
// see ICorDebugArrayValue methods in rh\src\debug\dbi\values.cpp
private int _upperBound1;
private int _upperBound2;
private int _upperBound3;
// NoInlining is currently required because NUTC does not support inling of this constructor
// during static initialization of multi-dimensional arrays.
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public MDArrayRank3(int length1, int length2, int length3)
{
Initialize(length1, length2, length3);
}
public override Object MDGetValue(params int[] indices)
{
if (indices.Length != 3)
throw new ArgumentException(SR.Arg_RankIndices);
CheckBounds(indices[0], indices[1], indices[2]);
return _array[ComputeIndex(indices[0], indices[1], indices[2])];
}
public T Get(int index1, int index2, int index3)
{
CheckBounds(index1, index2, index3);
return _array[ComputeIndex(index1, index2, index3)];
}
public override void MDSetValue(object value, params int[] indices)
{
if (indices.Length != 3)
throw new ArgumentException(SR.Arg_RankIndices);
CheckBounds(indices[0], indices[1], indices[2]);
_array.SetValue(value, ComputeIndex(indices[0], indices[1], indices[2]));
}
public override int MDGetUpperBound(int dimension)
{
switch (dimension)
{
case 0:
return _upperBound1 - 1;
case 1:
return _upperBound2 - 1;
case 2:
return _upperBound3 - 1;
default:
throw new IndexOutOfRangeException();
}
}
public sealed override void MDInitialize(int[] indices)
{
Initialize(indices[0], indices[1], indices[2]);
}
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public void CheckBounds(int index1, int index2, int index3)
{
if ((index1 < 0) || (index1 >= _upperBound1))
{
throw new IndexOutOfRangeException();
}
if ((index2 < 0) || (index2 >= _upperBound2))
{
throw new IndexOutOfRangeException();
}
if ((index3 < 0) || (index3 >= _upperBound3))
{
throw new IndexOutOfRangeException();
}
}
// This logic is duplicated in Redhawk DBI (implementation of ICorDebugArrayValue::GetElement)
// We should update it too whenever this method changes.
public int ComputeIndex(int index1, int index2, int index3)
{
// This arithmatic is unchecked because it is not possible to create
// an array that would satisfy bounds checks AND overflow the math
// here.
return (_upperBound3 * _upperBound2 * index1) +
(_upperBound3 * index2) +
index3;
}
public void Set(int index1, int index2, int index3, T value)
{
CheckBounds(index1, index2, index3);
_array[ComputeIndex(index1, index2, index3)] = value;
}
internal sealed override Array MDFlattenedArray
{
get
{
return _array;
}
}
private void Initialize(int length1, int length2, int length3)
{
if (length1 < 0 || length2 < 0 || length3 < 0)
throw new OverflowException();
_array = new T[checked(length1 * length2 * length3)];
_upperBound1 = length1;
_upperBound2 = length2;
_upperBound3 = length3;
SetLength(_array.Length);
}
}
public abstract class MDArrayRank4 : MDArray
{
public sealed override int MDRank
{
get
{
return 4;
}
}
}
public class MDArrayRank4<T> : MDArrayRank4
{
// Do not use field initializers on these fields. The implementation of CreateInstance() bypasses the normal constructor
// and calls MDInitialize() directly, so MDInitialize() must explicitly initialize all of the fields.
// The compiler takes a dependency on field ordering of this type, m_array must be first.
private T[] _array;
// Debugger(DBI) takes dependency on the ordering and layout of these fields.
// Please update DBI whenever these fields are updated or moved around.
// see ICorDebugArrayValue methods in rh\src\debug\dbi\values.cpp
private int _upperBound1;
private int _upperBound2;
private int _upperBound3;
private int _upperBound4;
// NoInlining is currently required because NUTC does not support inlining of this constructor
// during static initialization of multi-dimensional arrays. See Dev12 Bug 743787.
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public MDArrayRank4(int length1, int length2, int length3, int length4)
{
Initialize(length1, length2, length3, length4);
}
public override Object MDGetValue(params int[] indices)
{
if (indices.Length != 4)
throw new ArgumentException(SR.Arg_RankIndices);
CheckBounds(indices[0], indices[1], indices[2], indices[3]);
return _array[ComputeIndex(indices[0], indices[1], indices[2], indices[3])];
}
public T Get(int index1, int index2, int index3, int index4)
{
CheckBounds(index1, index2, index3, index4);
return _array[ComputeIndex(index1, index2, index3, index4)];
}
public override void MDSetValue(object value, params int[] indices)
{
if (indices.Length != 4)
throw new ArgumentException(SR.Arg_RankIndices);
CheckBounds(indices[0], indices[1], indices[2], indices[3]);
_array.SetValue(value, ComputeIndex(indices[0], indices[1], indices[2], indices[3]));
}
public override int MDGetUpperBound(int dimension)
{
switch (dimension)
{
case 0:
return _upperBound1 - 1;
case 1:
return _upperBound2 - 1;
case 2:
return _upperBound3 - 1;
case 3:
return _upperBound4 - 1;
default:
throw new IndexOutOfRangeException();
}
}
public sealed override void MDInitialize(int[] indices)
{
Initialize(indices[0], indices[1], indices[2], indices[3]);
}
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public void CheckBounds(int index1, int index2, int index3, int index4)
{
if ((index1 < 0) || (index1 >= _upperBound1))
{
throw new IndexOutOfRangeException();
}
if ((index2 < 0) || (index2 >= _upperBound2))
{
throw new IndexOutOfRangeException();
}
if ((index3 < 0) || (index3 >= _upperBound3))
{
throw new IndexOutOfRangeException();
}
if ((index4 < 0) || (index4 >= _upperBound4))
{
throw new IndexOutOfRangeException();
}
}
// This logic is duplicated in Redhawk DBI (implementation of ICorDebugArrayValue::GetElement)
// We should update it too whenever this method changes.
public int ComputeIndex(int index1, int index2, int index3, int index4)
{
// This arithmatic is unchecked because it is not possible to create
// an array that would satisfy bounds checks AND overflow the math
// here.
return (_upperBound4 * _upperBound3 * _upperBound2 * index1) +
(_upperBound4 * _upperBound3 * index2) +
(_upperBound4 * index3) +
index4;
}
public void Set(int index1, int index2, int index3, int index4, T value)
{
CheckBounds(index1, index2, index3, index4);
_array[ComputeIndex(index1, index2, index3, index4)] = value;
}
internal sealed override Array MDFlattenedArray
{
get
{
return _array;
}
}
private void Initialize(int length1, int length2, int length3, int length4)
{
if (length1 < 0 || length2 < 0 || length3 < 0 || length4 < 0)
throw new OverflowException();
_array = new T[checked(length1 * length2 * length3 * length4)];
_upperBound1 = length1;
_upperBound2 = length2;
_upperBound3 = length3;
_upperBound4 = length4;
SetLength(_array.Length);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace UnityTest
{
public interface IListRenderer
{
void Render(IEnumerable<AssertionComponent> allAssertions, List<string> foldMarkers);
}
public abstract class AssertionListRenderer<T> : IListRenderer
{
private static class Styles
{
public static readonly GUIStyle redLabel;
static Styles()
{
redLabel = new GUIStyle(EditorStyles.label);
redLabel.normal.textColor = Color.red;
}
}
public void Render(IEnumerable<AssertionComponent> allAssertions, List<string> foldMarkers)
{
foreach (var grouping in GroupResult(allAssertions))
{
var key = GetStringKey(grouping.Key);
bool isFolded = foldMarkers.Contains(key);
if (key != "")
{
EditorGUILayout.BeginHorizontal();
EditorGUI.BeginChangeCheck();
isFolded = PrintFoldout(isFolded,
grouping.Key);
if (EditorGUI.EndChangeCheck())
{
if (isFolded)
foldMarkers.Add(key);
else
foldMarkers.Remove(key);
}
EditorGUILayout.EndHorizontal();
if (isFolded)
continue;
}
foreach (var assertionComponent in grouping)
{
EditorGUILayout.BeginVertical();
EditorGUILayout.BeginHorizontal();
if (key != "")
GUILayout.Space(15);
var assertionKey = assertionComponent.GetHashCode().ToString();
bool isDetailsFolded = foldMarkers.Contains(assertionKey);
EditorGUI.BeginChangeCheck();
if (GUILayout.Button("",
EditorStyles.foldout,
GUILayout.Width(15)))
{
isDetailsFolded = !isDetailsFolded;
}
if (EditorGUI.EndChangeCheck())
{
if (isDetailsFolded)
foldMarkers.Add(assertionKey);
else
foldMarkers.Remove(assertionKey);
}
PrintFoldedAssertionLine(assertionComponent);
EditorGUILayout.EndHorizontal();
if (isDetailsFolded)
{
EditorGUILayout.BeginHorizontal();
if (key != "")
GUILayout.Space(15);
PrintAssertionLineDetails(assertionComponent);
EditorGUILayout.EndHorizontal();
}
GUILayout.Box("", new[] {GUILayout.ExpandWidth(true), GUILayout.Height(1)});
EditorGUILayout.EndVertical();
}
}
}
protected abstract IEnumerable<IGrouping<T, AssertionComponent>> GroupResult(IEnumerable<AssertionComponent> assertionComponents);
protected virtual string GetStringKey(T key)
{
return key.GetHashCode().ToString();
}
protected virtual bool PrintFoldout(bool isFolded, T key)
{
var content = new GUIContent(GetFoldoutDisplayName(key));
var size = EditorStyles.foldout.CalcSize(content);
var rect = GUILayoutUtility.GetRect(content,
EditorStyles.foldout,
GUILayout.MaxWidth(size.x));
var res = EditorGUI.Foldout(rect,
!isFolded,
content,
true);
return !res;
}
protected virtual string GetFoldoutDisplayName(T key)
{
return key.ToString();
}
protected virtual void PrintFoldedAssertionLine(AssertionComponent assertionComponent)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.BeginVertical(GUILayout.MaxWidth(300));
EditorGUILayout.BeginHorizontal(GUILayout.MaxWidth(300));
PrintPath(assertionComponent.Action.go,
assertionComponent.Action.thisPropertyPath);
EditorGUILayout.EndHorizontal();
EditorGUILayout.EndVertical();
EditorGUILayout.BeginVertical(GUILayout.MaxWidth(250));
var labelStr = assertionComponent.Action.GetType().Name;
var labelStr2 = assertionComponent.Action.GetConfigurationDescription();
if (labelStr2 != "")
labelStr += "( " + labelStr2 + ")";
EditorGUILayout.LabelField(labelStr);
EditorGUILayout.EndVertical();
if (assertionComponent.Action is ComparerBase)
{
var comparer = assertionComponent.Action as ComparerBase;
var otherStrVal = "(no value selected)";
EditorGUILayout.BeginVertical();
EditorGUILayout.BeginHorizontal(GUILayout.MaxWidth(300));
switch (comparer.compareToType)
{
case ComparerBase.CompareToType.CompareToObject:
if (comparer.other != null)
{
PrintPath(comparer.other,
comparer.otherPropertyPath);
}
else
{
EditorGUILayout.LabelField(otherStrVal,
Styles.redLabel);
}
break;
case ComparerBase.CompareToType.CompareToConstantValue:
otherStrVal = comparer.ConstValue.ToString();
EditorGUILayout.LabelField(otherStrVal);
break;
case ComparerBase.CompareToType.CompareToNull:
otherStrVal = "null";
EditorGUILayout.LabelField(otherStrVal);
break;
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.EndVertical();
}
else
{
EditorGUILayout.LabelField("");
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
}
protected virtual void PrintAssertionLineDetails(AssertionComponent assertionComponent)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.BeginVertical(GUILayout.MaxWidth(320));
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Attached to",
GUILayout.Width(70));
var sss = EditorStyles.objectField.CalcSize(new GUIContent(assertionComponent.gameObject.name));
EditorGUILayout.ObjectField(assertionComponent.gameObject,
typeof(GameObject),
true,
GUILayout.Width(sss.x));
EditorGUILayout.EndHorizontal();
EditorGUILayout.EndVertical();
EditorGUILayout.BeginVertical(GUILayout.MaxWidth(250));
#if UNITY_2017_3_OR_NEWER
EditorGUILayout.EnumFlagsField(assertionComponent.checkMethods,
EditorStyles.popup,
GUILayout.MaxWidth(150));
#else
EditorGUILayout.EnumMaskField(assertionComponent.checkMethods,
EditorStyles.popup,
GUILayout.MaxWidth(150));
#endif
EditorGUILayout.EndVertical();
EditorGUILayout.BeginVertical();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Disabled",
GUILayout.Width(55));
assertionComponent.enabled = !EditorGUILayout.Toggle(!assertionComponent.enabled,
GUILayout.Width(15));
EditorGUILayout.EndHorizontal();
EditorGUILayout.EndVertical();
EditorGUILayout.EndHorizontal();
}
private void PrintPath(GameObject go, string propertyPath)
{
string contentString = "";
GUIStyle styleThisPath = EditorStyles.label;
if (go != null)
{
var sss = EditorStyles.objectField.CalcSize(new GUIContent(go.name));
EditorGUILayout.ObjectField(
go,
typeof(GameObject),
true,
GUILayout.Width(sss.x));
if (!string.IsNullOrEmpty(propertyPath))
contentString = "." + propertyPath;
}
else
{
contentString = "(no value selected)";
styleThisPath = Styles.redLabel;
}
var content = new GUIContent(contentString,
contentString);
var rect = GUILayoutUtility.GetRect(content,
EditorStyles.label,
GUILayout.MaxWidth(200));
EditorGUI.LabelField(rect,
content,
styleThisPath);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace Photogaleries.Services.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using Newtonsoft.Json;
namespace XenAPI
{
/// <summary>
/// Represents a patch stored on a server
/// First published in XenServer 4.0.
/// </summary>
public partial class Host_patch : XenObject<Host_patch>
{
#region Constructors
public Host_patch()
{
}
public Host_patch(string uuid,
string name_label,
string name_description,
string version,
XenRef<Host> host,
bool applied,
DateTime timestamp_applied,
long size,
XenRef<Pool_patch> pool_patch,
Dictionary<string, string> other_config)
{
this.uuid = uuid;
this.name_label = name_label;
this.name_description = name_description;
this.version = version;
this.host = host;
this.applied = applied;
this.timestamp_applied = timestamp_applied;
this.size = size;
this.pool_patch = pool_patch;
this.other_config = other_config;
}
/// <summary>
/// Creates a new Host_patch from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public Host_patch(Hashtable table)
: this()
{
UpdateFrom(table);
}
/// <summary>
/// Creates a new Host_patch from a Proxy_Host_patch.
/// </summary>
/// <param name="proxy"></param>
public Host_patch(Proxy_Host_patch proxy)
{
UpdateFrom(proxy);
}
#endregion
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given Host_patch.
/// </summary>
public override void UpdateFrom(Host_patch record)
{
uuid = record.uuid;
name_label = record.name_label;
name_description = record.name_description;
version = record.version;
host = record.host;
applied = record.applied;
timestamp_applied = record.timestamp_applied;
size = record.size;
pool_patch = record.pool_patch;
other_config = record.other_config;
}
internal void UpdateFrom(Proxy_Host_patch proxy)
{
uuid = proxy.uuid == null ? null : proxy.uuid;
name_label = proxy.name_label == null ? null : proxy.name_label;
name_description = proxy.name_description == null ? null : proxy.name_description;
version = proxy.version == null ? null : proxy.version;
host = proxy.host == null ? null : XenRef<Host>.Create(proxy.host);
applied = (bool)proxy.applied;
timestamp_applied = proxy.timestamp_applied;
size = proxy.size == null ? 0 : long.Parse(proxy.size);
pool_patch = proxy.pool_patch == null ? null : XenRef<Pool_patch>.Create(proxy.pool_patch);
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this Host_patch
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("name_label"))
name_label = Marshalling.ParseString(table, "name_label");
if (table.ContainsKey("name_description"))
name_description = Marshalling.ParseString(table, "name_description");
if (table.ContainsKey("version"))
version = Marshalling.ParseString(table, "version");
if (table.ContainsKey("host"))
host = Marshalling.ParseRef<Host>(table, "host");
if (table.ContainsKey("applied"))
applied = Marshalling.ParseBool(table, "applied");
if (table.ContainsKey("timestamp_applied"))
timestamp_applied = Marshalling.ParseDateTime(table, "timestamp_applied");
if (table.ContainsKey("size"))
size = Marshalling.ParseLong(table, "size");
if (table.ContainsKey("pool_patch"))
pool_patch = Marshalling.ParseRef<Pool_patch>(table, "pool_patch");
if (table.ContainsKey("other_config"))
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
}
public Proxy_Host_patch ToProxy()
{
Proxy_Host_patch result_ = new Proxy_Host_patch();
result_.uuid = uuid ?? "";
result_.name_label = name_label ?? "";
result_.name_description = name_description ?? "";
result_.version = version ?? "";
result_.host = host ?? "";
result_.applied = applied;
result_.timestamp_applied = timestamp_applied;
result_.size = size.ToString();
result_.pool_patch = pool_patch ?? "";
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
return result_;
}
public bool DeepEquals(Host_patch other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._name_label, other._name_label) &&
Helper.AreEqual2(this._name_description, other._name_description) &&
Helper.AreEqual2(this._version, other._version) &&
Helper.AreEqual2(this._host, other._host) &&
Helper.AreEqual2(this._applied, other._applied) &&
Helper.AreEqual2(this._timestamp_applied, other._timestamp_applied) &&
Helper.AreEqual2(this._size, other._size) &&
Helper.AreEqual2(this._pool_patch, other._pool_patch) &&
Helper.AreEqual2(this._other_config, other._other_config);
}
public override string SaveChanges(Session session, string opaqueRef, Host_patch server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
if (!Helper.AreEqual2(_other_config, server._other_config))
{
Host_patch.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given host_patch.
/// First published in XenServer 4.0.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
[Deprecated("XenServer 7.1")]
public static Host_patch get_record(Session session, string _host_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_patch_get_record(session.opaque_ref, _host_patch);
else
return new Host_patch(session.XmlRpcProxy.host_patch_get_record(session.opaque_ref, _host_patch ?? "").parse());
}
/// <summary>
/// Get a reference to the host_patch instance with the specified UUID.
/// First published in XenServer 4.0.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
[Deprecated("XenServer 7.1")]
public static XenRef<Host_patch> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_patch_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<Host_patch>.Create(session.XmlRpcProxy.host_patch_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Get all the host_patch instances with the given label.
/// First published in XenServer 4.0.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_label">label of object to return</param>
[Deprecated("XenServer 7.1")]
public static List<XenRef<Host_patch>> get_by_name_label(Session session, string _label)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_patch_get_by_name_label(session.opaque_ref, _label);
else
return XenRef<Host_patch>.Create(session.XmlRpcProxy.host_patch_get_by_name_label(session.opaque_ref, _label ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given host_patch.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static string get_uuid(Session session, string _host_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_patch_get_uuid(session.opaque_ref, _host_patch);
else
return session.XmlRpcProxy.host_patch_get_uuid(session.opaque_ref, _host_patch ?? "").parse();
}
/// <summary>
/// Get the name/label field of the given host_patch.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static string get_name_label(Session session, string _host_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_patch_get_name_label(session.opaque_ref, _host_patch);
else
return session.XmlRpcProxy.host_patch_get_name_label(session.opaque_ref, _host_patch ?? "").parse();
}
/// <summary>
/// Get the name/description field of the given host_patch.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static string get_name_description(Session session, string _host_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_patch_get_name_description(session.opaque_ref, _host_patch);
else
return session.XmlRpcProxy.host_patch_get_name_description(session.opaque_ref, _host_patch ?? "").parse();
}
/// <summary>
/// Get the version field of the given host_patch.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static string get_version(Session session, string _host_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_patch_get_version(session.opaque_ref, _host_patch);
else
return session.XmlRpcProxy.host_patch_get_version(session.opaque_ref, _host_patch ?? "").parse();
}
/// <summary>
/// Get the host field of the given host_patch.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static XenRef<Host> get_host(Session session, string _host_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_patch_get_host(session.opaque_ref, _host_patch);
else
return XenRef<Host>.Create(session.XmlRpcProxy.host_patch_get_host(session.opaque_ref, _host_patch ?? "").parse());
}
/// <summary>
/// Get the applied field of the given host_patch.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static bool get_applied(Session session, string _host_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_patch_get_applied(session.opaque_ref, _host_patch);
else
return (bool)session.XmlRpcProxy.host_patch_get_applied(session.opaque_ref, _host_patch ?? "").parse();
}
/// <summary>
/// Get the timestamp_applied field of the given host_patch.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static DateTime get_timestamp_applied(Session session, string _host_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_patch_get_timestamp_applied(session.opaque_ref, _host_patch);
else
return session.XmlRpcProxy.host_patch_get_timestamp_applied(session.opaque_ref, _host_patch ?? "").parse();
}
/// <summary>
/// Get the size field of the given host_patch.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static long get_size(Session session, string _host_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_patch_get_size(session.opaque_ref, _host_patch);
else
return long.Parse(session.XmlRpcProxy.host_patch_get_size(session.opaque_ref, _host_patch ?? "").parse());
}
/// <summary>
/// Get the pool_patch field of the given host_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static XenRef<Pool_patch> get_pool_patch(Session session, string _host_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_patch_get_pool_patch(session.opaque_ref, _host_patch);
else
return XenRef<Pool_patch>.Create(session.XmlRpcProxy.host_patch_get_pool_patch(session.opaque_ref, _host_patch ?? "").parse());
}
/// <summary>
/// Get the other_config field of the given host_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static Dictionary<string, string> get_other_config(Session session, string _host_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_patch_get_other_config(session.opaque_ref, _host_patch);
else
return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.host_patch_get_other_config(session.opaque_ref, _host_patch ?? "").parse());
}
/// <summary>
/// Set the other_config field of the given host_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _host_patch, Dictionary<string, string> _other_config)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_patch_set_other_config(session.opaque_ref, _host_patch, _other_config);
else
session.XmlRpcProxy.host_patch_set_other_config(session.opaque_ref, _host_patch ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given host_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _host_patch, string _key, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_patch_add_to_other_config(session.opaque_ref, _host_patch, _key, _value);
else
session.XmlRpcProxy.host_patch_add_to_other_config(session.opaque_ref, _host_patch ?? "", _key ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given host_patch. If the key is not in that Map, then do nothing.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _host_patch, string _key)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_patch_remove_from_other_config(session.opaque_ref, _host_patch, _key);
else
session.XmlRpcProxy.host_patch_remove_from_other_config(session.opaque_ref, _host_patch ?? "", _key ?? "").parse();
}
/// <summary>
/// Destroy the specified host patch, removing it from the disk. This does NOT reverse the patch
/// First published in XenServer 4.0.
/// Deprecated since XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
[Deprecated("XenServer 4.1")]
public static void destroy(Session session, string _host_patch)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_patch_destroy(session.opaque_ref, _host_patch);
else
session.XmlRpcProxy.host_patch_destroy(session.opaque_ref, _host_patch ?? "").parse();
}
/// <summary>
/// Destroy the specified host patch, removing it from the disk. This does NOT reverse the patch
/// First published in XenServer 4.0.
/// Deprecated since XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
[Deprecated("XenServer 4.1")]
public static XenRef<Task> async_destroy(Session session, string _host_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_patch_destroy(session.opaque_ref, _host_patch);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_patch_destroy(session.opaque_ref, _host_patch ?? "").parse());
}
/// <summary>
/// Apply the selected patch and return its output
/// First published in XenServer 4.0.
/// Deprecated since XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
[Deprecated("XenServer 4.1")]
public static string apply(Session session, string _host_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_patch_apply(session.opaque_ref, _host_patch);
else
return session.XmlRpcProxy.host_patch_apply(session.opaque_ref, _host_patch ?? "").parse();
}
/// <summary>
/// Apply the selected patch and return its output
/// First published in XenServer 4.0.
/// Deprecated since XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
[Deprecated("XenServer 4.1")]
public static XenRef<Task> async_apply(Session session, string _host_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_patch_apply(session.opaque_ref, _host_patch);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_patch_apply(session.opaque_ref, _host_patch ?? "").parse());
}
/// <summary>
/// Return a list of all the host_patchs known to the system.
/// First published in XenServer 4.0.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
[Deprecated("XenServer 7.1")]
public static List<XenRef<Host_patch>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_patch_get_all(session.opaque_ref);
else
return XenRef<Host_patch>.Create(session.XmlRpcProxy.host_patch_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the host_patch Records at once, in a single XML RPC call
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<Host_patch>, Host_patch> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_patch_get_all_records(session.opaque_ref);
else
return XenRef<Host_patch>.Create<Proxy_Host_patch>(session.XmlRpcProxy.host_patch_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// a human-readable name
/// </summary>
public virtual string name_label
{
get { return _name_label; }
set
{
if (!Helper.AreEqual(value, _name_label))
{
_name_label = value;
NotifyPropertyChanged("name_label");
}
}
}
private string _name_label = "";
/// <summary>
/// a notes field containing human-readable description
/// </summary>
public virtual string name_description
{
get { return _name_description; }
set
{
if (!Helper.AreEqual(value, _name_description))
{
_name_description = value;
NotifyPropertyChanged("name_description");
}
}
}
private string _name_description = "";
/// <summary>
/// Patch version number
/// </summary>
public virtual string version
{
get { return _version; }
set
{
if (!Helper.AreEqual(value, _version))
{
_version = value;
NotifyPropertyChanged("version");
}
}
}
private string _version = "";
/// <summary>
/// Host the patch relates to
/// </summary>
[JsonConverter(typeof(XenRefConverter<Host>))]
public virtual XenRef<Host> host
{
get { return _host; }
set
{
if (!Helper.AreEqual(value, _host))
{
_host = value;
NotifyPropertyChanged("host");
}
}
}
private XenRef<Host> _host = new XenRef<Host>(Helper.NullOpaqueRef);
/// <summary>
/// True if the patch has been applied
/// </summary>
public virtual bool applied
{
get { return _applied; }
set
{
if (!Helper.AreEqual(value, _applied))
{
_applied = value;
NotifyPropertyChanged("applied");
}
}
}
private bool _applied;
/// <summary>
/// Time the patch was applied
/// </summary>
[JsonConverter(typeof(XenDateTimeConverter))]
public virtual DateTime timestamp_applied
{
get { return _timestamp_applied; }
set
{
if (!Helper.AreEqual(value, _timestamp_applied))
{
_timestamp_applied = value;
NotifyPropertyChanged("timestamp_applied");
}
}
}
private DateTime _timestamp_applied;
/// <summary>
/// Size of the patch
/// </summary>
public virtual long size
{
get { return _size; }
set
{
if (!Helper.AreEqual(value, _size))
{
_size = value;
NotifyPropertyChanged("size");
}
}
}
private long _size;
/// <summary>
/// The patch applied
/// First published in XenServer 4.1.
/// </summary>
[JsonConverter(typeof(XenRefConverter<Pool_patch>))]
public virtual XenRef<Pool_patch> pool_patch
{
get { return _pool_patch; }
set
{
if (!Helper.AreEqual(value, _pool_patch))
{
_pool_patch = value;
NotifyPropertyChanged("pool_patch");
}
}
}
private XenRef<Pool_patch> _pool_patch = new XenRef<Pool_patch>(Helper.NullOpaqueRef);
/// <summary>
/// additional configuration
/// First published in XenServer 4.1.
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config = new Dictionary<string, string>() {};
}
}
| |
/*
The MIT License (MIT)
Copyright (c) 2007 - 2020 Microting A/S
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.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microting.eForm.Infrastructure.Constants;
using Microting.eForm.Infrastructure.Data.Entities;
using NUnit.Framework;
namespace eFormSDK.InSight.Tests
{
[TestFixture]
public class LanguageQuestionSetUTest : DbTestFixture
{
[Test]
public async Task LanguageQuestionSet_Create_DoesCreate_W_MicrotingUid()
{
//Assert
Random rnd = new Random();
bool randomBool = rnd.Next(0, 2) > 0;
QuestionSet questionSetForQuestion = new QuestionSet
{
Name = Guid.NewGuid().ToString(),
Share = randomBool,
HasChild = randomBool,
ParentId = rnd.Next(1, 255),
PossiblyDeployed = randomBool
};
await questionSetForQuestion.Create(DbContext).ConfigureAwait(false);
Language language = new Language
{
LanguageCode = Guid.NewGuid().ToString(),
Name = Guid.NewGuid().ToString()
};
await language.Create(DbContext).ConfigureAwait(false);
LanguageQuestionSet languageQuestionSet = new LanguageQuestionSet
{
LanguageId = language.Id,
QuestionSetId = questionSetForQuestion.Id,
MicrotingUid = rnd.Next(1, 255)
};
//Act
await languageQuestionSet.Create(DbContext).ConfigureAwait(false);
List<LanguageQuestionSet> languageQuestionSets = DbContext.LanguageQuestionSets.AsNoTracking().ToList();
List<LanguageQuestionSetVersion> languageQuestionSetVersions =
DbContext.LanguageQuestionSetVersions.AsNoTracking().ToList();
//Assert
Assert.NotNull(languageQuestionSets);
Assert.NotNull(languageQuestionSetVersions);
Assert.AreEqual(1, languageQuestionSets.Count);
Assert.AreEqual(1, languageQuestionSetVersions.Count);
Assert.AreEqual(languageQuestionSet.LanguageId, languageQuestionSets[0].LanguageId);
Assert.AreEqual(languageQuestionSet.QuestionSetId, languageQuestionSets[0].QuestionSetId);
Assert.AreEqual(languageQuestionSet.MicrotingUid, languageQuestionSets[0].MicrotingUid);
Assert.AreEqual(languageQuestionSet.LanguageId, languageQuestionSetVersions[0].LanguageId);
Assert.AreEqual(languageQuestionSet.QuestionSetId, languageQuestionSetVersions[0].QuestionSetId);
Assert.AreEqual(languageQuestionSet.MicrotingUid, languageQuestionSetVersions[0].MicrotingUid);
}
[Test]
public async Task LanguageQuestionSet_Create_DoesCreate_WO_MicrotingUid()
{
//Assert
Random rnd = new Random();
bool randomBool = rnd.Next(0, 2) > 0;
QuestionSet questionSetForQuestion = new QuestionSet
{
Name = Guid.NewGuid().ToString(),
Share = randomBool,
HasChild = randomBool,
ParentId = rnd.Next(1, 255),
PossiblyDeployed = randomBool
};
await questionSetForQuestion.Create(DbContext).ConfigureAwait(false);
Language language = new Language
{
LanguageCode = Guid.NewGuid().ToString(),
Name = Guid.NewGuid().ToString()
};
await language.Create(DbContext).ConfigureAwait(false);
LanguageQuestionSet languageQuestionSet = new LanguageQuestionSet
{
LanguageId = language.Id,
QuestionSetId = questionSetForQuestion.Id,
};
//Act
await languageQuestionSet.Create(DbContext).ConfigureAwait(false);
List<LanguageQuestionSet> languageQuestionSets = DbContext.LanguageQuestionSets.AsNoTracking().ToList();
List<LanguageQuestionSetVersion> languageQuestionSetVersions =
DbContext.LanguageQuestionSetVersions.AsNoTracking().ToList();
//Assert
Assert.NotNull(languageQuestionSets);
Assert.NotNull(languageQuestionSetVersions);
Assert.AreEqual(1, languageQuestionSets.Count);
Assert.AreEqual(1, languageQuestionSetVersions.Count);
Assert.AreEqual(languageQuestionSet.LanguageId, languageQuestionSets[0].LanguageId);
Assert.AreEqual(languageQuestionSet.QuestionSetId, languageQuestionSets[0].QuestionSetId);
Assert.AreEqual(null, languageQuestionSets[0].MicrotingUid);
Assert.AreEqual(languageQuestionSet.LanguageId, languageQuestionSetVersions[0].LanguageId);
Assert.AreEqual(languageQuestionSet.QuestionSetId, languageQuestionSetVersions[0].QuestionSetId);
Assert.AreEqual(null, languageQuestionSetVersions[0].MicrotingUid);
}
[Test]
public async Task LanguageQuestionSet_Update_DoesUpdate_W_MicrotingUid()
{
//Assert
Random rnd = new Random();
bool randomBool = rnd.Next(0, 2) > 0;
QuestionSet questionSetForQuestion = new QuestionSet
{
Name = Guid.NewGuid().ToString(),
Share = randomBool,
HasChild = randomBool,
ParentId = rnd.Next(1, 255),
PossiblyDeployed = randomBool
};
await questionSetForQuestion.Create(DbContext).ConfigureAwait(false);
Language language = new Language
{
LanguageCode = Guid.NewGuid().ToString(),
Name = Guid.NewGuid().ToString()
};
await language.Create(DbContext).ConfigureAwait(false);
QuestionSet questionSetForQuestion2 = new QuestionSet
{
Name = Guid.NewGuid().ToString(),
Share = randomBool,
HasChild = randomBool,
ParentId = rnd.Next(1, 255),
PossiblyDeployed = randomBool
};
await questionSetForQuestion2.Create(DbContext).ConfigureAwait(false);
Language language2 = new Language
{
LanguageCode = Guid.NewGuid().ToString(),
Name = Guid.NewGuid().ToString()
};
await language2.Create(DbContext).ConfigureAwait(false);
LanguageQuestionSet languageQuestionSet = new LanguageQuestionSet
{
LanguageId = language.Id,
QuestionSetId = questionSetForQuestion.Id,
MicrotingUid = rnd.Next(1, 255)
};
await languageQuestionSet.Create(DbContext).ConfigureAwait(false);
var oldLanguageId = languageQuestionSet.LanguageId;
var oldQuestionSetId = languageQuestionSet.QuestionSetId;
var oldMicrotingUid = languageQuestionSet.MicrotingUid;
languageQuestionSet.LanguageId = language2.Id;
languageQuestionSet.QuestionSetId = questionSetForQuestion2.Id;
languageQuestionSet.MicrotingUid = rnd.Next(1, 255);
//Act
await languageQuestionSet.Update(DbContext).ConfigureAwait(false);
List<LanguageQuestionSet> languageQuestionSets = DbContext.LanguageQuestionSets.AsNoTracking().ToList();
List<LanguageQuestionSetVersion> languageQuestionSetVersions =
DbContext.LanguageQuestionSetVersions.AsNoTracking().ToList();
//Assert
Assert.NotNull(languageQuestionSets);
Assert.NotNull(languageQuestionSetVersions);
Assert.AreEqual(1, languageQuestionSets.Count);
Assert.AreEqual(2, languageQuestionSetVersions.Count);
Assert.AreEqual(languageQuestionSet.LanguageId, languageQuestionSets[0].LanguageId);
Assert.AreEqual(languageQuestionSet.QuestionSetId, languageQuestionSets[0].QuestionSetId);
Assert.AreEqual(languageQuestionSet.MicrotingUid, languageQuestionSets[0].MicrotingUid);
Assert.AreEqual(oldLanguageId, languageQuestionSetVersions[0].LanguageId);
Assert.AreEqual(oldQuestionSetId, languageQuestionSetVersions[0].QuestionSetId);
Assert.AreEqual(oldMicrotingUid, languageQuestionSetVersions[0].MicrotingUid);
Assert.AreEqual(languageQuestionSet.LanguageId, languageQuestionSetVersions[1].LanguageId);
Assert.AreEqual(languageQuestionSet.QuestionSetId, languageQuestionSetVersions[1].QuestionSetId);
Assert.AreEqual(languageQuestionSet.MicrotingUid, languageQuestionSetVersions[1].MicrotingUid);
}
[Test]
public async Task LanguageQuestionSet_Update_DoesUpdate_WO_MicrotingUid()
{
//Assert
Random rnd = new Random();
bool randomBool = rnd.Next(0, 2) > 0;
QuestionSet questionSetForQuestion = new QuestionSet
{
Name = Guid.NewGuid().ToString(),
Share = randomBool,
HasChild = randomBool,
ParentId = rnd.Next(1, 255),
PossiblyDeployed = randomBool
};
await questionSetForQuestion.Create(DbContext).ConfigureAwait(false);
Language language = new Language
{
LanguageCode = Guid.NewGuid().ToString(),
Name = Guid.NewGuid().ToString()
};
await language.Create(DbContext).ConfigureAwait(false);
QuestionSet questionSetForQuestion2 = new QuestionSet
{
Name = Guid.NewGuid().ToString(),
Share = randomBool,
HasChild = randomBool,
ParentId = rnd.Next(1, 255),
PossiblyDeployed = randomBool
};
await questionSetForQuestion2.Create(DbContext).ConfigureAwait(false);
Language language2 = new Language
{
LanguageCode = Guid.NewGuid().ToString(),
Name = Guid.NewGuid().ToString()
};
await language2.Create(DbContext).ConfigureAwait(false);
LanguageQuestionSet languageQuestionSet = new LanguageQuestionSet
{
LanguageId = language.Id,
QuestionSetId = questionSetForQuestion.Id,
};
await languageQuestionSet.Create(DbContext).ConfigureAwait(false);
var oldLanguageId = languageQuestionSet.LanguageId;
var oldQuestionSetId = languageQuestionSet.QuestionSetId;
languageQuestionSet.LanguageId = language2.Id;
languageQuestionSet.QuestionSetId = questionSetForQuestion2.Id;
//Act
await languageQuestionSet.Update(DbContext).ConfigureAwait(false);
List<LanguageQuestionSet> languageQuestionSets = DbContext.LanguageQuestionSets.AsNoTracking().ToList();
List<LanguageQuestionSetVersion> languageQuestionSetVersions =
DbContext.LanguageQuestionSetVersions.AsNoTracking().ToList();
//Assert
Assert.NotNull(languageQuestionSets);
Assert.NotNull(languageQuestionSetVersions);
Assert.AreEqual(1, languageQuestionSets.Count);
Assert.AreEqual(2, languageQuestionSetVersions.Count);
Assert.AreEqual(languageQuestionSet.LanguageId, languageQuestionSets[0].LanguageId);
Assert.AreEqual(languageQuestionSet.QuestionSetId, languageQuestionSets[0].QuestionSetId);
Assert.AreEqual(null, languageQuestionSets[0].MicrotingUid);
Assert.AreEqual(oldLanguageId, languageQuestionSetVersions[0].LanguageId);
Assert.AreEqual(oldQuestionSetId, languageQuestionSetVersions[0].QuestionSetId);
Assert.AreEqual(null, languageQuestionSetVersions[0].MicrotingUid);
Assert.AreEqual(languageQuestionSet.LanguageId, languageQuestionSetVersions[1].LanguageId);
Assert.AreEqual(languageQuestionSet.QuestionSetId, languageQuestionSetVersions[1].QuestionSetId);
Assert.AreEqual(null, languageQuestionSetVersions[1].MicrotingUid);
}
[Test]
public async Task LanguageQuestionSet_Update_DoesUpdate_W_MicrotingUid_RemovesUid()
{
//Assert
Random rnd = new Random();
bool randomBool = rnd.Next(0, 2) > 0;
QuestionSet questionSetForQuestion = new QuestionSet
{
Name = Guid.NewGuid().ToString(),
Share = randomBool,
HasChild = randomBool,
ParentId = rnd.Next(1, 255),
PossiblyDeployed = randomBool
};
await questionSetForQuestion.Create(DbContext).ConfigureAwait(false);
Language language = new Language
{
LanguageCode = Guid.NewGuid().ToString(),
Name = Guid.NewGuid().ToString()
};
await language.Create(DbContext).ConfigureAwait(false);
QuestionSet questionSetForQuestion2 = new QuestionSet
{
Name = Guid.NewGuid().ToString(),
Share = randomBool,
HasChild = randomBool,
ParentId = rnd.Next(1, 255),
PossiblyDeployed = randomBool
};
await questionSetForQuestion2.Create(DbContext).ConfigureAwait(false);
Language language2 = new Language
{
LanguageCode = Guid.NewGuid().ToString(),
Name = Guid.NewGuid().ToString()
};
await language2.Create(DbContext).ConfigureAwait(false);
LanguageQuestionSet languageQuestionSet = new LanguageQuestionSet
{
LanguageId = language.Id,
QuestionSetId = questionSetForQuestion.Id,
MicrotingUid = rnd.Next(1, 255)
};
await languageQuestionSet.Create(DbContext).ConfigureAwait(false);
var oldLanguageId = languageQuestionSet.LanguageId;
var oldQuestionSetId = languageQuestionSet.QuestionSetId;
var oldMicrotingUid = languageQuestionSet.MicrotingUid;
languageQuestionSet.LanguageId = language2.Id;
languageQuestionSet.QuestionSetId = questionSetForQuestion2.Id;
languageQuestionSet.MicrotingUid = null;
//Act
await languageQuestionSet.Update(DbContext).ConfigureAwait(false);
List<LanguageQuestionSet> languageQuestionSets = DbContext.LanguageQuestionSets.AsNoTracking().ToList();
List<LanguageQuestionSetVersion> languageQuestionSetVersions =
DbContext.LanguageQuestionSetVersions.AsNoTracking().ToList();
//Assert
Assert.NotNull(languageQuestionSets);
Assert.NotNull(languageQuestionSetVersions);
Assert.AreEqual(1, languageQuestionSets.Count);
Assert.AreEqual(2, languageQuestionSetVersions.Count);
Assert.AreEqual(languageQuestionSet.LanguageId, languageQuestionSets[0].LanguageId);
Assert.AreEqual(languageQuestionSet.QuestionSetId, languageQuestionSets[0].QuestionSetId);
Assert.AreEqual(null, languageQuestionSets[0].MicrotingUid);
Assert.AreEqual(oldLanguageId, languageQuestionSetVersions[0].LanguageId);
Assert.AreEqual(oldQuestionSetId, languageQuestionSetVersions[0].QuestionSetId);
Assert.AreEqual(oldMicrotingUid, languageQuestionSetVersions[0].MicrotingUid);
Assert.AreEqual(languageQuestionSet.LanguageId, languageQuestionSetVersions[1].LanguageId);
Assert.AreEqual(languageQuestionSet.QuestionSetId, languageQuestionSetVersions[1].QuestionSetId);
Assert.AreEqual(null, languageQuestionSetVersions[1].MicrotingUid);
}
[Test]
public async Task LanguageQuestionSet_Update_DoesUpdate_WO_MicrotingUid_AddsUid()
{
//Assert
Random rnd = new Random();
bool randomBool = rnd.Next(0, 2) > 0;
QuestionSet questionSetForQuestion = new QuestionSet
{
Name = Guid.NewGuid().ToString(),
Share = randomBool,
HasChild = randomBool,
ParentId = rnd.Next(1, 255),
PossiblyDeployed = randomBool
};
await questionSetForQuestion.Create(DbContext).ConfigureAwait(false);
Language language = new Language
{
LanguageCode = Guid.NewGuid().ToString(), Name = Guid.NewGuid().ToString()
};
await language.Create(DbContext).ConfigureAwait(false);
QuestionSet questionSetForQuestion2 = new QuestionSet
{
Name = Guid.NewGuid().ToString(),
Share = randomBool,
HasChild = randomBool,
ParentId = rnd.Next(1, 255),
PossiblyDeployed = randomBool
};
await questionSetForQuestion2.Create(DbContext).ConfigureAwait(false);
Language language2 = new Language
{
LanguageCode = Guid.NewGuid().ToString(), Name = Guid.NewGuid().ToString()
};
await language2.Create(DbContext).ConfigureAwait(false);
LanguageQuestionSet languageQuestionSet = new LanguageQuestionSet
{
LanguageId = language.Id,
QuestionSetId = questionSetForQuestion.Id,
};
await languageQuestionSet.Create(DbContext).ConfigureAwait(false);
var oldLanguageId = languageQuestionSet.LanguageId;
var oldQuestionSetId = languageQuestionSet.QuestionSetId;
languageQuestionSet.LanguageId = language2.Id;
languageQuestionSet.QuestionSetId = questionSetForQuestion2.Id;
languageQuestionSet.MicrotingUid = rnd.Next(1, 255);
//Act
await languageQuestionSet.Update(DbContext).ConfigureAwait(false);
List<LanguageQuestionSet> languageQuestionSets = DbContext.LanguageQuestionSets.AsNoTracking().ToList();
List<LanguageQuestionSetVersion> languageQuestionSetVersions =
DbContext.LanguageQuestionSetVersions.AsNoTracking().ToList();
//Assert
Assert.NotNull(languageQuestionSets);
Assert.NotNull(languageQuestionSetVersions);
Assert.AreEqual(1, languageQuestionSets.Count);
Assert.AreEqual(2, languageQuestionSetVersions.Count);
Assert.AreEqual(languageQuestionSet.LanguageId, languageQuestionSets[0].LanguageId);
Assert.AreEqual(languageQuestionSet.QuestionSetId, languageQuestionSets[0].QuestionSetId);
Assert.AreEqual(languageQuestionSet.MicrotingUid, languageQuestionSets[0].MicrotingUid);
Assert.AreEqual(oldLanguageId, languageQuestionSetVersions[0].LanguageId);
Assert.AreEqual(oldQuestionSetId, languageQuestionSetVersions[0].QuestionSetId);
Assert.AreEqual(null, languageQuestionSetVersions[0].MicrotingUid);
Assert.AreEqual(languageQuestionSet.LanguageId, languageQuestionSetVersions[1].LanguageId);
Assert.AreEqual(languageQuestionSet.QuestionSetId, languageQuestionSetVersions[1].QuestionSetId);
Assert.AreEqual(languageQuestionSet.MicrotingUid, languageQuestionSetVersions[1].MicrotingUid);
}
[Test]
public async Task LanguageQuestionSet_Delete_DoesDelete()
{
//Assert
Random rnd = new Random();
bool randomBool = rnd.Next(0, 2) > 0;
QuestionSet questionSetForQuestion = new QuestionSet
{
Name = Guid.NewGuid().ToString(),
Share = randomBool,
HasChild = randomBool,
ParentId = rnd.Next(1, 255),
PossiblyDeployed = randomBool
};
await questionSetForQuestion.Create(DbContext).ConfigureAwait(false);
Language language = new Language
{
LanguageCode = Guid.NewGuid().ToString(),
Name = Guid.NewGuid().ToString()
};
await language.Create(DbContext).ConfigureAwait(false);
LanguageQuestionSet languageQuestionSet = new LanguageQuestionSet
{
LanguageId = language.Id,
QuestionSetId = questionSetForQuestion.Id,
MicrotingUid = rnd.Next(1, 255)
};
await languageQuestionSet.Create(DbContext).ConfigureAwait(false);
var oldLanguageId = languageQuestionSet.LanguageId;
var oldQuestionSetId = languageQuestionSet.QuestionSetId;
var oldMicrotingUid = languageQuestionSet.MicrotingUid;
//Act
await languageQuestionSet.Delete(DbContext).ConfigureAwait(false);
List<LanguageQuestionSet> languageQuestionSets = DbContext.LanguageQuestionSets.AsNoTracking().ToList();
List<LanguageQuestionSetVersion> languageQuestionSetVersions =
DbContext.LanguageQuestionSetVersions.AsNoTracking().ToList();
//Assert
Assert.NotNull(languageQuestionSets);
Assert.NotNull(languageQuestionSetVersions);
Assert.AreEqual(1, languageQuestionSets.Count);
Assert.AreEqual(2, languageQuestionSetVersions.Count);
Assert.AreEqual(languageQuestionSet.LanguageId, languageQuestionSets[0].LanguageId);
Assert.AreEqual(languageQuestionSet.QuestionSetId, languageQuestionSets[0].QuestionSetId);
Assert.AreEqual(languageQuestionSet.MicrotingUid, languageQuestionSets[0].MicrotingUid);
Assert.AreEqual(Constants.WorkflowStates.Removed, languageQuestionSets[0].WorkflowState);
Assert.AreEqual(oldLanguageId, languageQuestionSetVersions[0].LanguageId);
Assert.AreEqual(oldQuestionSetId, languageQuestionSetVersions[0].QuestionSetId);
Assert.AreEqual(oldMicrotingUid, languageQuestionSetVersions[0].MicrotingUid);
Assert.AreEqual(Constants.WorkflowStates.Created, languageQuestionSetVersions[0].WorkflowState);
Assert.AreEqual(languageQuestionSet.LanguageId, languageQuestionSetVersions[1].LanguageId);
Assert.AreEqual(languageQuestionSet.QuestionSetId, languageQuestionSetVersions[1].QuestionSetId);
Assert.AreEqual(languageQuestionSet.MicrotingUid, languageQuestionSetVersions[1].MicrotingUid);
Assert.AreEqual(Constants.WorkflowStates.Removed, languageQuestionSetVersions[1].WorkflowState);
}
}
}
| |
using MatterHackers.Agg.Image;
using MatterHackers.Agg.RasterizerScanline;
using MatterHackers.Agg.Transform;
using MatterHackers.Agg.VertexSource;
using MatterHackers.VectorMath;
//----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// C# port by: Lars Brubaker
// larsbrubaker@gmail.com
// Copyright (C) 2007
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: mcseem@antigrain.com
// mcseemagg@yahoo.com
// http://www.antigrain.com
//----------------------------------------------------------------------------
using System;
namespace MatterHackers.Agg
{
public class ImageGraphics2D : Graphics2D
{
private const int cover_full = 255;
protected IScanlineCache m_ScanlineCache;
private VertexStorage drawImageRectPath = new VertexStorage();
private MatterHackers.Agg.span_allocator destImageSpanAllocatorCache = new span_allocator();
private ScanlineCachePacked8 drawImageScanlineCache = new ScanlineCachePacked8();
private ScanlineRenderer scanlineRenderer = new ScanlineRenderer();
public ImageGraphics2D()
{
}
public ImageGraphics2D(IImageByte destImage, ScanlineRasterizer rasterizer, IScanlineCache scanlineCache)
: base(destImage, rasterizer)
{
m_ScanlineCache = scanlineCache;
}
public override IScanlineCache ScanlineCache
{
get { return m_ScanlineCache; }
set { m_ScanlineCache = value; }
}
public override int Width => destImageByte.Width;
public override int Height => destImageByte.Height;
public override void SetClippingRect(RectangleDouble clippingRect)
{
Rasterizer.SetVectorClipBox(clippingRect);
}
public override RectangleDouble GetClippingRect()
{
return Rasterizer.GetVectorClipBox();
}
public override void Render(IVertexSource vertexSource, IColorType colorBytes)
{
rasterizer.reset();
Affine transform = GetTransform();
if (!transform.is_identity())
{
vertexSource = new VertexSourceApplyTransform(vertexSource, transform);
}
rasterizer.add_path(vertexSource);
if (destImageByte != null)
{
scanlineRenderer.RenderSolid(destImageByte, rasterizer, m_ScanlineCache, colorBytes.ToColor());
DestImage.MarkImageChanged();
}
else
{
scanlineRenderer.RenderSolid(destImageFloat, rasterizer, m_ScanlineCache, colorBytes.ToColorF());
destImageFloat.MarkImageChanged();
}
}
private void DrawImageGetDestBounds(IImageByte sourceImage,
double DestX, double DestY,
double HotspotOffsetX, double HotspotOffsetY,
double ScaleX, double ScaleY,
double AngleRad, out Affine destRectTransform)
{
destRectTransform = Affine.NewIdentity();
if (HotspotOffsetX != 0.0f || HotspotOffsetY != 0.0f)
{
destRectTransform *= Affine.NewTranslation(-HotspotOffsetX, -HotspotOffsetY);
}
if (ScaleX != 1 || ScaleY != 1)
{
destRectTransform *= Affine.NewScaling(ScaleX, ScaleY);
}
if (AngleRad != 0)
{
destRectTransform *= Affine.NewRotation(AngleRad);
}
if (DestX != 0 || DestY != 0)
{
destRectTransform *= Affine.NewTranslation(DestX, DestY);
}
int SourceBufferWidth = (int)sourceImage.Width;
int SourceBufferHeight = (int)sourceImage.Height;
drawImageRectPath.remove_all();
drawImageRectPath.MoveTo(0, 0);
drawImageRectPath.LineTo(SourceBufferWidth, 0);
drawImageRectPath.LineTo(SourceBufferWidth, SourceBufferHeight);
drawImageRectPath.LineTo(0, SourceBufferHeight);
drawImageRectPath.ClosePolygon();
}
private void DrawImage(IImageByte sourceImage, ISpanGenerator spanImageFilter, Affine destRectTransform)
{
if (destImageByte.OriginOffset.X != 0 || destImageByte.OriginOffset.Y != 0)
{
destRectTransform *= Affine.NewTranslation(-destImageByte.OriginOffset.X, -destImageByte.OriginOffset.Y);
}
VertexSourceApplyTransform transformedRect = new VertexSourceApplyTransform(drawImageRectPath, destRectTransform);
Rasterizer.add_path(transformedRect);
{
ImageClippingProxy destImageWithClipping = new ImageClippingProxy(destImageByte);
scanlineRenderer.GenerateAndRender(Rasterizer, drawImageScanlineCache, destImageWithClipping, destImageSpanAllocatorCache, spanImageFilter);
}
}
public override void Render(IImageByte source,
double destX, double destY,
double angleRadians,
double inScaleX, double inScaleY)
{
Affine graphicsTransform = GetTransform();
{ // exit early if the dest and source bounds don't touch.
// TODO: <BUG> make this do rotation and scaling
RectangleInt sourceBounds = source.GetBounds();
RectangleInt destBounds = this.destImageByte.GetBounds();
sourceBounds.Offset((int)(destX + graphicsTransform.tx), (int)(destY + graphicsTransform.ty));
if (!RectangleInt.DoIntersect(sourceBounds, destBounds))
{
if (inScaleX != 1 || inScaleY != 1 || angleRadians != 0)
{
throw new NotImplementedException();
}
return;
}
}
double scaleX = inScaleX;
double scaleY = inScaleY;
if (!graphicsTransform.is_identity())
{
if (scaleX != 1 || scaleY != 1 || angleRadians != 0)
{
throw new NotImplementedException();
}
graphicsTransform.transform(ref destX, ref destY);
}
#if false // this is an optimization that eliminates the drawing of images that have their alpha set to all 0 (happens with generated images like explosions).
MaxAlphaFrameProperty maxAlphaFrameProperty = MaxAlphaFrameProperty::GetMaxAlphaFrameProperty(source);
if((maxAlphaFrameProperty.GetMaxAlpha() * color.A_Byte) / 256 <= ALPHA_CHANNEL_BITS_DIVISOR)
{
m_OutFinalBlitBounds.SetRect(0,0,0,0);
}
#endif
bool IsScaled = (scaleX != 1 || scaleY != 1);
bool IsRotated = true;
if (Math.Abs(angleRadians) < (0.1 * MathHelper.Tau / 360))
{
IsRotated = false;
angleRadians = 0;
}
//bool IsMipped = false;
double sourceOriginOffsetX = source.OriginOffset.X;
double sourceOriginOffsetY = source.OriginOffset.Y;
bool CanUseMipMaps = IsScaled;
if (scaleX > 0.5 || scaleY > 0.5)
{
CanUseMipMaps = false;
}
bool renderRequriesSourceSampling = IsScaled || IsRotated || destX != (int)destX || destY != (int)destY;
// this is the fast drawing path
if (renderRequriesSourceSampling)
{
#if false // if the scaling is small enough the results can be improved by using mip maps
if(CanUseMipMaps)
{
CMipMapFrameProperty* pMipMapFrameProperty = CMipMapFrameProperty::GetMipMapFrameProperty(source);
double OldScaleX = scaleX;
double OldScaleY = scaleY;
const CFrameInterface* pMippedFrame = pMipMapFrameProperty.GetMipMapFrame(ref scaleX, ref scaleY);
if(pMippedFrame != source)
{
IsMipped = true;
source = pMippedFrame;
sourceOriginOffsetX *= (OldScaleX / scaleX);
sourceOriginOffsetY *= (OldScaleY / scaleY);
}
HotspotOffsetX *= (inScaleX / scaleX);
HotspotOffsetY *= (inScaleY / scaleY);
}
#endif
switch (ImageRenderQuality)
{
case TransformQuality.Fastest:
{
Affine destRectTransform;
DrawImageGetDestBounds(source, destX, destY, sourceOriginOffsetX, sourceOriginOffsetY, scaleX, scaleY, angleRadians, out destRectTransform);
Affine sourceRectTransform = new Affine(destRectTransform);
// We invert it because it is the transform to make the image go to the same position as the polygon. LBB [2/24/2004]
sourceRectTransform.invert();
span_image_filter spanImageFilter;
span_interpolator_linear interpolator = new span_interpolator_linear(sourceRectTransform);
ImageBufferAccessorClip sourceAccessor = new ImageBufferAccessorClip(source, ColorF.rgba_pre(0, 0, 0, 0).ToColor());
spanImageFilter = new span_image_filter_rgba_bilinear_clip(sourceAccessor, ColorF.rgba_pre(0, 0, 0, 0), interpolator);
DrawImage(source, spanImageFilter, destRectTransform);
}
break;
case TransformQuality.Best:
{
Affine destRectTransform;
DrawImageGetDestBounds(source, destX, destY, sourceOriginOffsetX, sourceOriginOffsetY, scaleX, scaleY, angleRadians, out destRectTransform);
Affine sourceRectTransform = new Affine(destRectTransform);
// We invert it because it is the transform to make the image go to the same position as the polygon. LBB [2/24/2004]
sourceRectTransform.invert();
span_interpolator_linear interpolator = new span_interpolator_linear(sourceRectTransform);
ImageBufferAccessorClip sourceAccessor = new ImageBufferAccessorClip(source, ColorF.rgba_pre(0, 0, 0, 0).ToColor());
//spanImageFilter = new span_image_filter_rgba_bilinear_clip(sourceAccessor, RGBA_Floats.rgba_pre(0, 0, 0, 0), interpolator);
IImageFilterFunction filterFunction = null;
filterFunction = new image_filter_blackman(4);
ImageFilterLookUpTable filter = new ImageFilterLookUpTable();
filter.calculate(filterFunction, true);
span_image_filter spanGenerator = new span_image_filter_rgba(sourceAccessor, interpolator, filter);
DrawImage(source, spanGenerator, destRectTransform);
}
break;
}
#if false // this is some debug you can enable to visualize the dest bounding box
LineFloat(BoundingRect.left, BoundingRect.top, BoundingRect.right, BoundingRect.top, WHITE);
LineFloat(BoundingRect.right, BoundingRect.top, BoundingRect.right, BoundingRect.bottom, WHITE);
LineFloat(BoundingRect.right, BoundingRect.bottom, BoundingRect.left, BoundingRect.bottom, WHITE);
LineFloat(BoundingRect.left, BoundingRect.bottom, BoundingRect.left, BoundingRect.top, WHITE);
#endif
}
else // TODO: this can be even faster if we do not use an intermediate buffer
{
Affine destRectTransform;
DrawImageGetDestBounds(source, destX, destY, sourceOriginOffsetX, sourceOriginOffsetY, scaleX, scaleY, angleRadians, out destRectTransform);
Affine sourceRectTransform = new Affine(destRectTransform);
// We invert it because it is the transform to make the image go to the same position as the polygon. LBB [2/24/2004]
sourceRectTransform.invert();
span_interpolator_linear interpolator = new span_interpolator_linear(sourceRectTransform);
ImageBufferAccessorClip sourceAccessor = new ImageBufferAccessorClip(source, ColorF.rgba_pre(0, 0, 0, 0).ToColor());
span_image_filter spanImageFilter = null;
switch (source.BitDepth)
{
case 32:
spanImageFilter = new span_image_filter_rgba_nn_stepXby1(sourceAccessor, interpolator);
break;
case 24:
spanImageFilter = new span_image_filter_rgb_nn_stepXby1(sourceAccessor, interpolator);
break;
case 8:
spanImageFilter = new span_image_filter_gray_nn_stepXby1(sourceAccessor, interpolator);
break;
default:
throw new NotImplementedException();
}
//spanImageFilter = new span_image_filter_rgba_nn(sourceAccessor, interpolator);
DrawImage(source, spanImageFilter, destRectTransform);
DestImage.MarkImageChanged();
}
}
public override void Rectangle(double left, double bottom, double right, double top, Color color, double strokeWidth)
{
RoundedRect rect = new RoundedRect(left + .5, bottom + .5, right - .5, top - .5, 0);
Stroke rectOutline = new Stroke(rect, strokeWidth);
Render(rectOutline, color);
}
public override void FillRectangle(double left, double bottom, double right, double top, IColorType fillColor)
{
RoundedRect rect = new RoundedRect(left, bottom, right, top, 0);
Render(rect, fillColor.ToColor());
}
public override void Render(IImageFloat source,
double x, double y,
double angleDegrees,
double inScaleX, double inScaleY)
{
throw new NotImplementedException();
}
public override void Clear(IColorType iColor)
{
RectangleDouble clippingRect = GetClippingRect();
RectangleInt clippingRectInt = new RectangleInt((int)clippingRect.Left, (int)clippingRect.Bottom, (int)clippingRect.Right, (int)clippingRect.Top);
if (DestImage != null)
{
Color color = iColor.ToColor();
int width = DestImage.Width;
int height = DestImage.Height;
byte[] buffer = DestImage.GetBuffer();
switch (DestImage.BitDepth)
{
case 8:
{
byte byteColor = (byte)iColor.Red0To255;
for (int y = clippingRectInt.Bottom; y < clippingRectInt.Top; y++)
{
int bufferOffset = DestImage.GetBufferOffsetXY((int)clippingRect.Left, y);
int bytesBetweenPixels = DestImage.GetBytesBetweenPixelsInclusive();
for (int x = 0; x < clippingRectInt.Width; x++)
{
buffer[bufferOffset] = color.blue;
bufferOffset += bytesBetweenPixels;
}
}
}
break;
case 24:
for (int y = clippingRectInt.Bottom; y < clippingRectInt.Top; y++)
{
int bufferOffset = DestImage.GetBufferOffsetXY((int)clippingRect.Left, y);
int bytesBetweenPixels = DestImage.GetBytesBetweenPixelsInclusive();
for (int x = 0; x < clippingRectInt.Width; x++)
{
buffer[bufferOffset + 0] = color.blue;
buffer[bufferOffset + 1] = color.green;
buffer[bufferOffset + 2] = color.red;
bufferOffset += bytesBetweenPixels;
}
}
break;
case 32:
{
for (int y = clippingRectInt.Bottom; y < clippingRectInt.Top; y++)
{
int bufferOffset = DestImage.GetBufferOffsetXY((int)clippingRect.Left, y);
int bytesBetweenPixels = DestImage.GetBytesBetweenPixelsInclusive();
for (int x = 0; x < clippingRectInt.Width; x++)
{
buffer[bufferOffset + 0] = color.blue;
buffer[bufferOffset + 1] = color.green;
buffer[bufferOffset + 2] = color.red;
buffer[bufferOffset + 3] = color.alpha;
bufferOffset += bytesBetweenPixels;
}
}
}
break;
default:
throw new NotImplementedException();
}
DestImage.MarkImageChanged();
}
else // it is a float
{
if (DestImageFloat == null)
{
throw new Exception("You have to have either a byte or float DestImage.");
}
ColorF color = iColor.ToColorF();
int width = DestImageFloat.Width;
int height = DestImageFloat.Height;
float[] buffer = DestImageFloat.GetBuffer();
switch (DestImageFloat.BitDepth)
{
case 128:
for (int y = 0; y < height; y++)
{
int bufferOffset = DestImageFloat.GetBufferOffsetXY(clippingRectInt.Left, y);
int bytesBetweenPixels = DestImageFloat.GetFloatsBetweenPixelsInclusive();
for (int x = 0; x < clippingRectInt.Width; x++)
{
buffer[bufferOffset + 0] = color.blue;
buffer[bufferOffset + 1] = color.green;
buffer[bufferOffset + 2] = color.red;
buffer[bufferOffset + 3] = color.alpha;
bufferOffset += bytesBetweenPixels;
}
}
break;
default:
throw new NotImplementedException();
}
}
}
}
}
| |
//
// System.Configuration.ConfigHelper
//
// Authors:
// Gonzalo Paniagua Javier (gonzalo@ximian.com)
//
// (C) 2002 Ximian, Inc (http://www.ximian.com)
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Collections;
using System.Collections.Specialized;
#if (XML_DEP)
using System.Xml;
#endif
namespace System.Configuration
{
class ConfigHelper
{
class CollectionWrapper
{
IDictionary dict;
NameValueCollection collection;
bool isDict;
public CollectionWrapper (IDictionary dict)
{
this.dict = dict;
isDict = true;
}
public CollectionWrapper (NameValueCollection collection)
{
this.collection = collection;
isDict = false;
}
public void Remove (string s)
{
if (isDict)
dict.Remove (s);
else
collection.Remove (s);
}
public void Clear ()
{
if (isDict)
dict.Clear ();
else
collection.Clear ();
}
public string this [string key]
{
set {
if (isDict)
dict [key] = value;
else
collection [key] = value;
}
}
public object UnWrap ()
{
if (isDict)
return dict;
else
return collection;
}
}
#if (XML_DEP)
internal static IDictionary GetDictionary (IDictionary prev,
XmlNode region,
string nameAtt,
string valueAtt)
{
Hashtable hash;
if (prev == null)
hash = new Hashtable (CaseInsensitiveHashCodeProvider.Default,
CaseInsensitiveComparer.Default);
else {
Hashtable aux = (Hashtable) prev;
hash = (Hashtable) aux.Clone ();
}
CollectionWrapper result = new CollectionWrapper (hash);
result = GoGetThem (result, region, nameAtt, valueAtt);
if (result == null)
return null;
return result.UnWrap () as IDictionary;
}
internal static ConfigNameValueCollection GetNameValueCollection (NameValueCollection prev,
XmlNode region,
string nameAtt,
string valueAtt)
{
ConfigNameValueCollection coll =
new ConfigNameValueCollection (CaseInsensitiveHashCodeProvider.Default,
CaseInsensitiveComparer.Default);
if (prev != null)
coll.Add (prev);
CollectionWrapper result = new CollectionWrapper (coll);
result = GoGetThem (result, region, nameAtt, valueAtt);
if (result == null)
return null;
return result.UnWrap () as ConfigNameValueCollection;
}
private static CollectionWrapper GoGetThem (CollectionWrapper result,
XmlNode region,
string nameAtt,
string valueAtt)
{
if (region.Attributes != null && region.Attributes.Count != 0) {
if (region.Attributes.Count != 1 || region.Attributes[0].Name != "xmlns") {
throw new ConfigurationException ("Unknown attribute", region);
}
}
XmlNode keyNode;
XmlNode valueNode;
XmlNodeList childs = region.ChildNodes;
foreach (XmlNode node in childs) {
XmlNodeType ntype = node.NodeType;
if (ntype == XmlNodeType.Whitespace || ntype == XmlNodeType.Comment)
continue;
if (ntype != XmlNodeType.Element)
throw new ConfigurationException ("Only XmlElement allowed", node);
string nodeName = node.Name;
if (nodeName == "clear") {
if (node.Attributes != null && node.Attributes.Count != 0)
throw new ConfigurationException ("Unknown attribute", node);
result.Clear ();
} else if (nodeName == "remove") {
keyNode = null;
if (node.Attributes != null)
keyNode = node.Attributes.RemoveNamedItem (nameAtt);
if (keyNode == null)
throw new ConfigurationException ("Required attribute not found",
node);
if (keyNode.Value == String.Empty)
throw new ConfigurationException ("Required attribute is empty",
node);
if (node.Attributes.Count != 0)
throw new ConfigurationException ("Unknown attribute", node);
result.Remove (keyNode.Value);
} else if (nodeName == "add") {
keyNode = null;
if (node.Attributes != null)
keyNode = node.Attributes.RemoveNamedItem (nameAtt);
if (keyNode == null)
throw new ConfigurationException ("Required attribute not found",
node);
if (keyNode.Value == String.Empty)
throw new ConfigurationException ("Required attribute is empty",
node);
valueNode = node.Attributes.RemoveNamedItem (valueAtt);
if (valueNode == null)
throw new ConfigurationException ("Required attribute not found",
node);
if (node.Attributes.Count != 0)
throw new ConfigurationException ("Unknown attribute", node);
result [keyNode.Value] = valueNode.Value;
} else {
throw new ConfigurationException ("Unknown element", node);
}
}
return result;
}
#endif
}
internal class ConfigNameValueCollection: NameValueCollection
{
bool modified;
public ConfigNameValueCollection ()
{
}
public ConfigNameValueCollection (ConfigNameValueCollection col)
: base (col.Count, col)
{
}
public ConfigNameValueCollection (IHashCodeProvider hashProvider, IComparer comparer)
: base(hashProvider, comparer)
{
}
public void ResetModified ()
{
modified = false;
}
public bool IsModified {
get { return modified; }
}
public override void Set (string name, string value)
{
base.Set (name, value);
modified = true;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.WebSites
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// ManagedHostingEnvironmentsOperations operations.
/// </summary>
public partial interface IManagedHostingEnvironmentsOperations
{
/// <summary>
/// Get properties of a managed hosting environment.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of resource group
/// </param>
/// <param name='name'>
/// Name of managed hosting environment
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<ManagedHostingEnvironment>> GetManagedHostingEnvironmentWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create or update a managed hosting environment.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of resource group
/// </param>
/// <param name='name'>
/// Name of managed hosting environment
/// </param>
/// <param name='managedHostingEnvironmentEnvelope'>
/// Properties of managed hosting environment
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<HostingEnvironment>> CreateOrUpdateManagedHostingEnvironmentWithHttpMessagesAsync(string resourceGroupName, string name, HostingEnvironment managedHostingEnvironmentEnvelope, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create or update a managed hosting environment.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of resource group
/// </param>
/// <param name='name'>
/// Name of managed hosting environment
/// </param>
/// <param name='managedHostingEnvironmentEnvelope'>
/// Properties of managed hosting environment
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<HostingEnvironment>> BeginCreateOrUpdateManagedHostingEnvironmentWithHttpMessagesAsync(string resourceGroupName, string name, HostingEnvironment managedHostingEnvironmentEnvelope, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete a managed hosting environment.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of resource group
/// </param>
/// <param name='name'>
/// Name of managed hosting environment
/// </param>
/// <param name='forceDelete'>
/// Delete even if the managed hosting environment contains resources
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<object>> DeleteManagedHostingEnvironmentWithHttpMessagesAsync(string resourceGroupName, string name, bool? forceDelete = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete a managed hosting environment.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of resource group
/// </param>
/// <param name='name'>
/// Name of managed hosting environment
/// </param>
/// <param name='forceDelete'>
/// Delete even if the managed hosting environment contains resources
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<object>> BeginDeleteManagedHostingEnvironmentWithHttpMessagesAsync(string resourceGroupName, string name, bool? forceDelete = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get all managed hosting environments in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of resource group
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<HostingEnvironmentCollection>> GetManagedHostingEnvironmentsWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get list of ip addresses assigned to a managed hosting environment
/// </summary>
/// <param name='resourceGroupName'>
/// Name of resource group
/// </param>
/// <param name='name'>
/// Name of managed hosting environment
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<AddressResponse>> GetManagedHostingEnvironmentVipsWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get status of an operation on a managed hosting environment.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of resource group
/// </param>
/// <param name='name'>
/// Name of managed hosting environment
/// </param>
/// <param name='operationId'>
/// operation identifier GUID
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<object>> GetManagedHostingEnvironmentOperationWithHttpMessagesAsync(string resourceGroupName, string name, string operationId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get all sites on the managed hosting environment.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of resource group
/// </param>
/// <param name='name'>
/// Name of managed hosting environment
/// </param>
/// <param name='propertiesToInclude'>
/// Comma separated list of site properties to include
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<SiteCollection>> GetManagedHostingEnvironmentSitesWithHttpMessagesAsync(string resourceGroupName, string name, string propertiesToInclude = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get all serverfarms (App Service Plans) on the managed hosting
/// environment.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of resource group
/// </param>
/// <param name='name'>
/// Name of managed hosting environment
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<ServerFarmCollection>> GetManagedHostingEnvironmentWebHostingPlansWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get all serverfarms (App Service Plans) on the managed hosting
/// environment.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of resource group
/// </param>
/// <param name='name'>
/// Name of managed hosting environment
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<ServerFarmCollection>> GetManagedHostingEnvironmentServerFarmsWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Moq;
using NUnit.Framework;
using QuantConnect.Data.Market;
using QuantConnect.ToolBox.AlphaVantageDownloader;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
namespace QuantConnect.Tests.ToolBox.AlphaVantageDownloader
{
[TestFixture]
public class AlphaVantageDataDownloaderTests
{
private const string API_KEY = "TESTKEY";
private const string BASE_URL = "https://www.alphavantage.co/";
private Mock<IRestClient> _avClient;
private AlphaVantageDataDownloader _downloader;
private readonly TradeBarComparer _tradeBarComparer = new TradeBarComparer();
[SetUp]
public void SetUp()
{
_avClient = new Mock<IRestClient>();
_avClient.SetupAllProperties();
_downloader = new AlphaVantageDataDownloader(_avClient.Object, API_KEY);
}
[TearDown]
public void TearDown()
{
_downloader.Dispose();
}
[Test]
public void GetDailyLessThan100DaysGetsCompactDailyData()
{
var ticker = "AAPL";
var symbol = Symbol.Create(ticker, SecurityType.Equity, Market.USA);
var resolution = Resolution.Daily;
var start = DateTime.UtcNow.AddDays(-100);
var end = DateTime.UtcNow;
var expectedBars = new[]
{
new TradeBar(DateTime.Parse("2021-04-05"), symbol, 133.64m, 136.69m, 133.40m, 135.93m, 5471616),
new TradeBar(DateTime.Parse("2021-04-06"), symbol, 135.58m, 135.64m, 134.09m, 134.22m, 3620964),
};
IRestRequest request = null;
_avClient.Setup(m => m.Execute(It.IsAny<IRestRequest>(), It.IsAny<Method>()))
.Callback((IRestRequest r, Method m) => request = r)
.Returns(new RestResponse
{
StatusCode = HttpStatusCode.OK,
ContentType = "application/x-download",
Content = "timestamp,open,high,low,close,volume\n" +
"2021-04-06,135.5800,135.6400,134.0900,134.2200,3620964\n" +
"2021-04-05,133.6400,136.6900,133.4000,135.9300,5471616\n"
})
.Verifiable();
var result = _downloader.Get(new DataDownloaderGetParameters(symbol, resolution, start, end));
_avClient.Verify();
var requestUrl = BuildUrl(request);
Assert.AreEqual(Method.GET, request.Method);
Assert.AreEqual($"{BASE_URL}query?symbol=AAPL&datatype=csv&function=TIME_SERIES_DAILY", requestUrl);
Assert.IsInstanceOf<IEnumerable<TradeBar>>(result);
var bars = ((IEnumerable<TradeBar>)result).ToList();
Assert.AreEqual(2, bars.Count);
Assert.That(bars[0], Is.EqualTo(expectedBars[0]).Using(_tradeBarComparer));
Assert.That(bars[1], Is.EqualTo(expectedBars[1]).Using(_tradeBarComparer));
}
[Test]
public void GetDailyGreaterThan100DaysGetsFullDailyData()
{
var ticker = "AAPL";
var symbol = Symbol.Create(ticker, SecurityType.Equity, Market.USA);
var resolution = Resolution.Daily;
var start = DateTime.UtcNow.AddYears(-2);
var end = DateTime.UtcNow;
var expectedBars = new[]
{
new TradeBar(DateTime.Parse("2021-04-05"), symbol, 133.64m, 136.69m, 133.40m, 135.93m, 5471616),
new TradeBar(DateTime.Parse("2021-04-06"), symbol, 135.58m, 135.64m, 134.09m, 134.22m, 3620964),
};
IRestRequest request = null;
_avClient.Setup(m => m.Execute(It.IsAny<IRestRequest>(), It.IsAny<Method>()))
.Callback((IRestRequest r, Method m) => request = r)
.Returns(new RestResponse
{
StatusCode = HttpStatusCode.OK,
ContentType = "application/x-download",
Content = "timestamp,open,high,low,close,volume\n" +
"2021-04-06,135.5800,135.6400,134.0900,134.2200,3620964\n" +
"2021-04-05,133.6400,136.6900,133.4000,135.9300,5471616\n"
})
.Verifiable();
var result = _downloader.Get(new DataDownloaderGetParameters(symbol, resolution, start, end));
_avClient.Verify();
var requestUrl = BuildUrl(request);
Assert.AreEqual(Method.GET, request.Method);
Assert.AreEqual($"{BASE_URL}query?symbol=AAPL&datatype=csv&function=TIME_SERIES_DAILY&outputsize=full", requestUrl);
Assert.IsInstanceOf<IEnumerable<TradeBar>>(result);
var bars = ((IEnumerable<TradeBar>)result).ToList();
Assert.AreEqual(2, bars.Count);
Assert.That(bars[0], Is.EqualTo(expectedBars[0]).Using(_tradeBarComparer));
Assert.That(bars[1], Is.EqualTo(expectedBars[1]).Using(_tradeBarComparer));
}
[TestCase(Resolution.Minute, "1min")]
[TestCase(Resolution.Hour, "60min")]
public void GetMinuteHourGetsIntradayData(Resolution resolution, string interval)
{
var ticker = "IBM";
var symbol = Symbol.Create(ticker, SecurityType.Equity, Market.USA);
var start = new DateTime(2021, 04, 05);
var end = new DateTime(2021, 05, 06);
var expectedBars = new[]
{
new TradeBar(start.AddHours(9.5), symbol, 133.71m, 133.72m, 133.62m, 133.62m, 1977),
new TradeBar(start.AddHours(10.5), symbol, 134.30m, 134.56m, 134.245m, 134.34m, 154723),
new TradeBar(end.AddHours(9.5), symbol, 135.54m, 135.56m, 135.26m, 135.28m, 2315),
new TradeBar(end.AddHours(10.5), symbol, 134.905m,134.949m, 134.65m, 134.65m, 101997),
};
var responses = new[]
{
"time,open,high,low,close,volume\n" +
"2021-04-05 10:30:00,134.3,134.56,134.245,134.34,154723\n" +
"2021-04-05 09:30:00,133.71,133.72,133.62,133.62,1977\n",
"time,open,high,low,close,volume\n" +
"2021-05-06 10:30:00,134.905,134.949,134.65,134.65,101997\n" +
"2021-05-06 09:30:00,135.54,135.56,135.26,135.28,2315\n",
};
var requestCount = 0;
var requestUrls = new List<string>();
_avClient.Setup(m => m.Execute(It.IsAny<IRestRequest>(), It.IsAny<Method>()))
.Callback((IRestRequest r, Method m) => requestUrls.Add(BuildUrl(r)))
.Returns(() => new RestResponse
{
StatusCode = HttpStatusCode.OK,
ContentType = "application/x-download",
Content = responses[requestCount++]
})
.Verifiable();
var result = _downloader.Get(new DataDownloaderGetParameters(symbol, resolution, start, end)).ToList();
_avClient.Verify();
Assert.AreEqual(2, requestUrls.Count);
Assert.AreEqual($"{BASE_URL}query?symbol=IBM&datatype=csv&function=TIME_SERIES_INTRADAY_EXTENDED&adjusted=false&interval={interval}&slice=year1month2", requestUrls[0]);
Assert.AreEqual($"{BASE_URL}query?symbol=IBM&datatype=csv&function=TIME_SERIES_INTRADAY_EXTENDED&adjusted=false&interval={interval}&slice=year1month1", requestUrls[1]);
var bars = result.Cast<TradeBar>().ToList();
Assert.AreEqual(4, bars.Count);
Assert.That(bars[0], Is.EqualTo(expectedBars[0]).Using(_tradeBarComparer));
Assert.That(bars[1], Is.EqualTo(expectedBars[1]).Using(_tradeBarComparer));
Assert.That(bars[2], Is.EqualTo(expectedBars[2]).Using(_tradeBarComparer));
Assert.That(bars[3], Is.EqualTo(expectedBars[3]).Using(_tradeBarComparer));
}
[TestCase(Resolution.Tick)]
[TestCase(Resolution.Second)]
public void GetUnsupportedResolutionThrowsException(Resolution resolution)
{
var ticker = "IBM";
var symbol = Symbol.Create(ticker, SecurityType.Equity, Market.USA);
var start = DateTime.UtcNow.AddMonths(-2);
var end = DateTime.UtcNow;
Assert.Throws<ArgumentOutOfRangeException>(() => _downloader.Get(new DataDownloaderGetParameters(symbol, resolution, start, end)).ToList());
}
[TestCase(Resolution.Minute)]
[TestCase(Resolution.Hour)]
[TestCase(Resolution.Daily)]
public void UnexpectedResponseContentTypeThrowsException(Resolution resolution)
{
var ticker = "IBM";
var symbol = Symbol.Create(ticker, SecurityType.Equity, Market.USA);
var start = DateTime.UtcNow.AddMonths(-2);
var end = DateTime.UtcNow;
_avClient.Setup(m => m.Execute(It.IsAny<IRestRequest>(), It.IsAny<Method>()))
.Returns(() => new RestResponse
{
StatusCode = HttpStatusCode.OK,
ContentType = "application/json"
})
.Verifiable();
Assert.Throws<FormatException>(() => _downloader.Get(new DataDownloaderGetParameters(symbol, resolution, start, end)).ToList());
}
[Test]
public void GetIntradayDataGreaterThanTwoYearsThrowsException()
{
var ticker = "IBM";
var symbol = Symbol.Create(ticker, SecurityType.Equity, Market.USA);
var resolution = Resolution.Minute;
var start = DateTime.UtcNow.AddYears(-2).AddDays(-1);
var end = DateTime.UtcNow;
Assert.Throws<ArgumentOutOfRangeException>(() => _downloader.Get(new DataDownloaderGetParameters(symbol, resolution, start, end)).ToList());
}
[Test]
public void AuthenticatorAddsApiKeyToRequest()
{
var request = new Mock<IRestRequest>();
var authenticator = _avClient.Object.Authenticator;
Assert.NotNull(authenticator);
authenticator.Authenticate(_avClient.Object, request.Object);
request.Verify(m => m.AddOrUpdateParameter("apikey", API_KEY));
}
private string BuildUrl(IRestRequest request)
{
if (request == null)
throw new ArgumentNullException(nameof(request));
var client = new RestClient(BASE_URL);
var uri = client.BuildUri(request);
return uri.ToString();
}
private class TradeBarComparer : IEqualityComparer<TradeBar>
{
public bool Equals(TradeBar x, TradeBar y)
{
if (x == null || y == null)
return false;
return x.Symbol == y.Symbol &&
x.Time == y.Time &&
x.Open == y.Open &&
x.High == y.High &&
x.Low == y.Low &&
x.Close == y.Close &&
x.Volume == y.Volume;
}
public int GetHashCode(TradeBar obj) => obj.GetHashCode();
}
}
}
| |
/*
Copyright (c) 2004-2006 Jan Benda and Tomas Matousek.
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger distribution. By using this software
in any fashion, you are agreeing to be bound by the terms of this license.
You must not remove this notice from this software.
*/
using System;
using System.Text;
using System.Collections;
using System.ComponentModel;
using PHP.Core;
#if SILVERLIGHT
using PHP.CoreCLR;
using MathEx = PHP.CoreCLR.MathEx;
#else
using MathEx = System.Math;
using System.Diagnostics;
#endif
namespace PHP.Library
{
/// <summary>
/// Implements PHP mathematical functions and constants.
/// </summary>
/// <threadsafety static="true"/>
public static class PhpMath
{
#region GlobalInfo
private class StaticInfo
{
public Random Generator;
public MersenneTwister MtGenerator;
public static StaticInfo Get
{
get
{
StaticInfo info;
var properties = ThreadStatic.Properties;
if (properties.TryGetProperty<StaticInfo>(out info) == false || info == null)
{
properties.SetProperty(info = new StaticInfo());
}
return info;
}
}
}
#endregion
#region Per-request Random Number Generators
/// <summary>
/// Gets an initialized random number generator associated with the current thread.
/// </summary>
internal static Random Generator
{
get
{
var info = StaticInfo.Get;
if (info.Generator == null)
info.Generator = new Random(unchecked((int)DateTime.UtcNow.ToFileTime()));
return info.Generator;
}
}
/// <summary>
/// Gets an initialized Mersenne Twister random number generator associated with the current thread.
/// </summary>
internal static MersenneTwister MTGenerator
{
get
{
var info = StaticInfo.Get;
if (info.MtGenerator == null)
info.MtGenerator = new MersenneTwister(unchecked((uint)DateTime.UtcNow.ToFileTime()));
return info.MtGenerator;
}
}
/// <summary>
/// Registers <see cref="ClearGenerators"/> routine to be called on request end.
/// </summary>
static PhpMath()
{
RequestContext.RequestEnd += new Action(ClearGenerators);
}
/// <summary>
/// Nulls <see cref="Generator"/> and <see cref="MTGenerator"/> fields on request end.
/// </summary>
private static void ClearGenerators()
{
var info = StaticInfo.Get;
info.Generator = null;
info.MtGenerator = null;
}
#endregion
#region Constants
[ImplementsConstant("M_PI")]
public const double Pi = System.Math.PI;
[ImplementsConstant("M_E")]
public const double E = System.Math.E;
[ImplementsConstant("M_LOG2E")]
public const double Log2e = 1.4426950408889634074;
[ImplementsConstant("M_LOG10E")]
public const double Log10e = 0.43429448190325182765;
[ImplementsConstant("M_LN2")]
public const double Ln2 = 0.69314718055994530942;
[ImplementsConstant("M_LN10")]
public const double Ln10 = 2.30258509299404568402;
[ImplementsConstant("M_PI_2")]
public const double PiHalf = 1.57079632679489661923;
[ImplementsConstant("M_PI_4")]
public const double PiFourth = 0.78539816339744830962;
[ImplementsConstant("M_1_PI")]
public const double Pith = 0.31830988618379067154;
[ImplementsConstant("M_2_PI")]
public const double TwoPiths = 0.63661977236758134308;
[ImplementsConstant("M_SQRTPI")]
public const double SqrtPi = 1.77245385090551602729;
[ImplementsConstant("M_2_SQRTPI")]
public const double TwoSqrtPi = 1.12837916709551257390;
[ImplementsConstant("M_SQRT3")]
public const double Sqrt3 = 1.73205080756887729352;
[ImplementsConstant("M_SQRT1_2")]
public const double SqrtHalf = 0.70710678118654752440;
[ImplementsConstant("M_LNPI")]
public const double LnPi = 1.14472988584940017414;
[ImplementsConstant("M_EULER")]
public const double Euler = 0.57721566490153286061;
[ImplementsConstant("NAN")]
public const double NaN = Double.NaN;
[ImplementsConstant("INF")]
public const double Infinity = Double.PositiveInfinity;
#endregion
#region Absolutize Range
/// <summary>
/// Absolutizes range specified by an offset and a length relatively to a dimension of an array.
/// </summary>
/// <param name="count">The number of items in array. Should be non-negative.</param>
/// <param name="offset">
/// The offset of the range relative to the beginning (if non-negative) or the end of the array (if negative).
/// If the offset underflows or overflows the length is shortened appropriately.
/// </param>
/// <param name="length">
/// The length of the range if non-negative. Otherwise, its absolute value is the number of items
/// which will not be included in the range from the end of the array. In the latter case
/// the range ends with the |<paramref name="length"/>|-th item from the end of the array (counting from zero).
/// </param>
/// <remarks>
/// Ensures that <c>[offset,offset + length]</c> is subrange of <c>[0,count]</c>.
/// </remarks>
public static void AbsolutizeRange(ref int offset, ref int length, int count)
{
Debug.Assert(count >= 0);
// prevents overflows:
if (offset >= count || count == 0)
{
offset = count;
length = 0;
return;
}
// negative offset => offset is relative to the end of the string:
if (offset < 0)
{
offset += count;
if (offset < 0) offset = 0;
}
Debug.Assert(offset >= 0 && offset < count);
if (length < 0)
{
// there is count-offset items from offset to the end of array,
// the last |length| items is taken away:
length = count - offset + length;
if (length < 0) length = 0;
}
else if ((long)offset + length > count)
{
// interval ends on the end of array:
length = count - offset;
}
Debug.Assert(length >= 0 && offset + length <= count);
}
#endregion
#region rand, srand, getrandmax, uniqid, lcg_value
/// <summary>
/// Gets <c>0</c> or <c>1</c> randomly.
/// </summary>
static int Random01()
{
return (int)Math.Round(Generator.NextDouble());
}
/// <summary>
/// Seed the random number generator. No return value.
/// </summary>
[ImplementsFunction("srand")]
public static void Seed()
{
StaticInfo.Get.Generator = new Random();
}
/// <summary>
/// Seed the random number generator. No return value.
/// </summary>
/// <param name="seed">Optional seed value.</param>
[ImplementsFunction("srand")]
public static void Seed(int seed)
{
StaticInfo.Get.Generator = new Random(seed);
}
/// <summary>
/// Show largest possible random value.
/// </summary>
/// <returns>The largest possible random value returned by rand().</returns>
[ImplementsFunction("getrandmax")]
public static int GetMaxRandomValue()
{
return Int32.MaxValue;
}
/// <summary>
/// Generate a random integer.
/// </summary>
/// <returns>A pseudo random value between 0 and getrandmax(), inclusive.</returns>
[ImplementsFunction("rand")]
public static int Random()
{
return Generator.Next() + Random01();
}
/// <summary>
/// Generate a random integer.
/// </summary>
/// <param name="min">The lowest value to return.</param>
/// <param name="max">The highest value to return.</param>
/// <returns>A pseudo random value between min and max, inclusive. </returns>
[ImplementsFunction("rand")]
public static int Random(int min, int max)
{
if (min > max)
return Random(max, min);
if (min == max)
return min;
if (max == int.MaxValue)
return Generator.Next(min, int.MaxValue) + Random01();
return Generator.Next(min, max + 1);
}
/// <summary>
/// Generate a unique ID.
/// Gets a prefixed unique identifier based on the current time in microseconds.
/// </summary>
/// <returns>Returns the unique identifier, as a string.</returns>
[ImplementsFunction("uniqid")]
public static string UniqueId()
{
return UniqueId(null, false);
}
/// <summary>
/// Generate a unique ID.
/// Gets a prefixed unique identifier based on the current time in microseconds.
/// </summary>
/// <param name="prefix">Can be useful, for instance, if you generate identifiers simultaneously on several hosts that might happen to generate the identifier at the same microsecond.
/// With an empty prefix , the returned string will be 13 characters long.
/// </param>
/// <returns>Returns the unique identifier, as a string.</returns>
[ImplementsFunction("uniqid")]
public static string UniqueId(string prefix)
{
return UniqueId(prefix, false);
}
/// <summary>
/// Generate a unique ID.
/// </summary>
/// <remarks>
/// With an empty prefix, the returned string will be 13 characters long. If more_entropy is TRUE, it will be 23 characters.
/// </remarks>
/// <param name="prefix">Use the specified prefix.</param>
/// <param name="more_entropy">Use LCG to generate a random postfix.</param>
/// <returns>A pseudo-random string composed from the given prefix, current time and a random postfix.</returns>
[ImplementsFunction("uniqid")]
public static string UniqueId(string prefix, bool more_entropy)
{
// Note that Ticks specify time in 100nanoseconds but it is raised each 100144
// ticks which is around 10 times a second (the same for Milliseconds).
string ticks = String.Format("{0:X}", DateTime.Now.Ticks + Generator.Next());
ticks = ticks.Substring(ticks.Length - 13);
if (prefix == null) prefix = "";
if (more_entropy)
{
string rnd = LcgValue().ToString();
rnd = rnd.Substring(2, 8);
return String.Format("{0}{1}.{2}", prefix, ticks, rnd);
}
else return String.Format("{0}{1}", prefix, ticks);
}
/// <summary>
/// Generates a pseudo-random number using linear congruential generator in the range of (0,1).
/// </summary>
/// <remarks>
/// This method uses the Framwork <see cref="Random"/> generator
/// which may or may not be the same generator as the PHP one (L(CG(2^31 - 85),CG(2^31 - 249))).
/// </remarks>
/// <returns></returns>
[ImplementsFunction("lcg_value")]
public static double LcgValue()
{
return Generator.NextDouble();
}
#endregion
#region mt_getrandmax, mt_rand, mt_srand
[ImplementsFunction("mt_getrandmax")]
public static int MtGetMaxRandomValue()
{
return Int32.MaxValue;
}
[ImplementsFunction("mt_rand")]
public static int MtRandom()
{
return MTGenerator.Next();
}
[ImplementsFunction("mt_rand")]
public static int MtRandom(int min, int max)
{
return (min < max) ? MTGenerator.Next(min, max) : MTGenerator.Next(max, min);
}
/// <summary>
/// Seed the better random number generator.
/// No return value.
/// </summary>
[ImplementsFunction("mt_srand")]
public static void MtSeed()
{
MtSeed(Generator.Next());
}
/// <summary>
/// Seed the better random number generator.
/// No return value.
/// </summary>
/// <param name="seed">Optional seed value.</param>
[ImplementsFunction("mt_srand")]
public static void MtSeed(int seed)
{
MTGenerator.Seed(unchecked((uint)seed));
}
#endregion
#region is_nan,is_finite,is_infinite
[ImplementsFunction("is_nan")]
[PureFunction]
public static bool IsNaN(double x)
{
return Double.IsNaN(x);
}
[ImplementsFunction("is_finite")]
[PureFunction]
public static bool IsFinite(double x)
{
return !Double.IsInfinity(x);
}
[ImplementsFunction("is_infinite")]
[PureFunction]
public static bool IsInfinite(double x)
{
return Double.IsInfinity(x);
}
#endregion
#region decbin, bindec, decoct, octdec, dechex, hexdec, base_convert
/// <summary>
/// Converts the given number to int (if the number is whole
/// and fits into the int's range).
/// </summary>
/// <param name="number"></param>
/// <returns><c>int</c> representation of number if possible, otherwise a <c>double</c> representation.</returns>
private static object ConvertToInt(double number)
{
if ((Math.Round(number) == number) && (number <= int.MaxValue) && (number >= int.MinValue))
{
return (int)number;
}
return number;
}
/// <summary>
/// Converts the lowest 32 bits of the given number to a binary string.
/// </summary>
/// <param name="number"></param>
/// <returns></returns>
[ImplementsFunction("decbin")]
public static PhpBytes DecToBin(double number)
{
// Trim the number to the lower 32 binary digits.
uint temp = unchecked((uint)number);
return DoubleToBase(temp, 2);
}
/// <summary>
/// Converts the lowest 32 bits of the given number to a binary string.
/// </summary>
/// <param name="number"></param>
/// <returns></returns>
[ImplementsFunction("decbin_unicode")]
public static string DecToBinUnicode(double number)
{
// Trim the number to the lower 32 binary digits.
uint temp = unchecked((uint)number);
return DoubleToBaseUnicode(temp, 2);
}
/// <summary>
/// Returns the decimal equivalent of the binary number represented by the binary_string argument.
/// bindec() converts a binary number to an integer or, if needed for size reasons, double.
/// </summary>
/// <param name="str">The binary string to convert.</param>
/// <returns>The decimal value of <paramref name="str"/>.</returns>
[ImplementsFunction("bindec")]
public static object BinToDec(PhpBytes str)
{
if (str == null) return 0;
return ConvertToInt(BaseToDouble(str, 2));
}
[ImplementsFunction("bindec_unicode")]
public static object BinToDecUnicode(string str)
{
if (str == null) return 0;
return ConvertToInt(BaseToDoubleUnicode(str, 2));
}
/// <summary>
/// Returns a string containing an octal representation of the given number argument.
/// </summary>
/// <param name="number">Decimal value to convert.</param>
/// <returns>Octal string representation of <paramref name="number"/>.</returns>
[ImplementsFunction("decoct")]
public static PhpBytes DecToOct(int number)
{
return new PhpBytes(System.Convert.ToString(number, 8));
}
[ImplementsFunction("decoct_unicode")]
public static string DecToOctUnicode(int number)
{
return System.Convert.ToString(number, 8);
}
/// <summary>
/// Returns the decimal equivalent of the octal number represented by the <paramref name="str"/> argument.
/// </summary>
/// <param name="str">The octal string to convert.</param>
/// <returns>The decimal representation of <paramref name="str"/>.</returns>
[ImplementsFunction("octdec")]
public static object OctToDec(PhpBytes str)
{
if (str == null) return 0;
return ConvertToInt(BaseToDouble(str, 8));
}
[ImplementsFunction("octdec_unicode")]
public static object OctToDecUnicode(string str)
{
if (str == null) return 0;
return ConvertToInt(BaseToDoubleUnicode(str, 8));
}
/// <summary>
/// Returns a string containing a hexadecimal representation of the given number argument.
/// </summary>
/// <param name="number">Decimal value to convert.</param>
/// <returns>Hexadecimal string representation of <paramref name="number"/>.</returns>
[ImplementsFunction("dechex")]
public static PhpBytes DecToHex(int number)
{
return new PhpBytes(System.Convert.ToString(number, 16));
}
[ImplementsFunction("dechex_unicode")]
public static string DecToHexUnicode(int number)
{
return System.Convert.ToString(number, 16);
}
/// <summary>
/// Hexadecimal to decimal.
/// Returns the decimal equivalent of the hexadecimal number represented by the hex_string argument. hexdec() converts a hexadecimal string to a decimal number.
/// hexdec() will ignore any non-hexadecimal characters it encounters.
/// </summary>
/// <param name="str">The hexadecimal string to convert.</param>
/// <returns>The decimal representation of <paramref name="str"/>.</returns>
[ImplementsFunction("hexdec")]
public static object HexToDec(PhpBytes str)
{
if (str == null) return 0;
return ConvertToInt(BaseToDouble(str, 16));
}
[ImplementsFunction("hexdec_unicode")]
public static object HexToDecUnicode(string str)
{
if (str == null) return 0;
return ConvertToInt(BaseToDoubleUnicode(str, 16));
}
public static double BaseToDouble(PhpBytes number, int fromBase)
{
if (number == null)
{
PhpException.ArgumentNull("number");
return 0.0;
}
if (fromBase < 2 || fromBase > 36)
{
PhpException.InvalidArgument("toBase", LibResources.GetString("arg:out_of_bounds"));
return 0.0;
}
double fnum = 0;
for (int i = 0; i < number.Length; i++)
{
int digit = Core.Parsers.Convert.AlphaNumericToDigit((char)number.ReadonlyData[i]);
if (digit < fromBase)
fnum = fnum * fromBase + digit;
}
return fnum;
}
public static double BaseToDoubleUnicode(string number, int fromBase)
{
if (number == null)
{
PhpException.ArgumentNull("number");
return 0.0;
}
if (fromBase < 2 || fromBase > 36)
{
PhpException.InvalidArgument("toBase", LibResources.GetString("arg:out_of_bounds"));
return 0.0;
}
double fnum = 0;
for (int i = 0; i < number.Length; i++)
{
int digit = Core.Parsers.Convert.AlphaNumericToDigit(number[i]);
if (digit < fromBase)
fnum = fnum * fromBase + digit;
}
return fnum;
}
private const string digitsUnicode = "0123456789abcdefghijklmnopqrstuvwxyz";
private static byte[] digits = new byte[] {(byte)'0',(byte)'1',(byte)'2',(byte)'3',(byte)'4',(byte)'5',(byte)'6',(byte)'7',(byte)'8',(byte)'9',
(byte)'a',(byte)'b',(byte)'c',(byte)'d',(byte)'e',(byte)'f',(byte)'g',(byte)'h',(byte)'i',(byte)'j',(byte)'k',(byte)'l',(byte)'m',(byte)'n',
(byte)'o',(byte)'p',(byte)'q',(byte)'r',(byte)'s',(byte)'t',(byte)'u',(byte)'v',(byte)'w',(byte)'x',(byte)'y',(byte)'z' };
public static PhpBytes DoubleToBase(double number, int toBase)
{
if (toBase < 2 || toBase > 36)
{
PhpException.InvalidArgument("toBase", LibResources.GetString("arg:out_of_bounds"));
return PhpBytes.Empty;
}
// Don't try to convert infinity or NaN:
if (Double.IsInfinity(number) || Double.IsNaN(number))
{
PhpException.InvalidArgument("number", LibResources.GetString("arg:out_of_bounds"));
return PhpBytes.Empty;
}
double fvalue = Math.Floor(number); /* floor it just in case */
if (Math.Abs(fvalue) < 1) return new PhpBytes(new byte[]{(byte)'0'});
System.Collections.Generic.List<byte> sb = new System.Collections.Generic.List<byte>();
while (Math.Abs(fvalue) >= 1)
{
double mod = Fmod(fvalue, toBase);
int i = (int)mod;
byte b = digits[i];
//sb.Append(digits[(int) fmod(fvalue, toBase)]);
sb.Add(b);
fvalue /= toBase;
}
sb.Reverse();
return new PhpBytes(sb.ToArray());
}
public static string DoubleToBaseUnicode(double number, int toBase)
{
if (toBase < 2 || toBase > 36)
{
PhpException.InvalidArgument("toBase", LibResources.GetString("arg:out_of_bounds"));
return String.Empty;
}
// Don't try to convert infinity or NaN:
if (Double.IsInfinity(number) || Double.IsNaN(number))
{
PhpException.InvalidArgument("number", LibResources.GetString("arg:out_of_bounds"));
return String.Empty;
}
double fvalue = Math.Floor(number); /* floor it just in case */
if (Math.Abs(fvalue) < 1) return "0";
StringBuilder sb = new StringBuilder();
while (Math.Abs(fvalue) >= 1)
{
double mod = Fmod(fvalue, toBase);
int i = (int)mod;
char c = digitsUnicode[i];
//sb.Append(digits[(int) fmod(fvalue, toBase)]);
sb.Append(c);
fvalue /= toBase;
}
return PhpStrings.Reverse(sb.ToString());
}
/// <summary>
/// Convert a number between arbitrary bases.
/// Returns a string containing number represented in base tobase. The base in which number is given is specified in <paramref name="fromBase"/>. Both <paramref name="fromBase"/> and <paramref name="toBase"/> have to be between 2 and 36, inclusive. Digits in numbers with a base higher than 10 will be represented with the letters a-z, with a meaning 10, b meaning 11 and z meaning 35.
/// </summary>
/// <param name="number">The number to convert</param>
/// <param name="fromBase">The base <paramref name="number"/> is in.</param>
/// <param name="toBase">The base to convert <paramref name="number"/> to</param>
/// <returns><paramref name="number"/> converted to base <paramref name="toBase"/>.</returns>
[ImplementsFunction("base_convert")]
[return: CastToFalse]
public static string BaseConvert(string number, int fromBase, int toBase)
{
double value;
if (number == null) return "0";
try
{
value = BaseToDoubleUnicode(number, fromBase);
}
catch (ArgumentException)
{
PhpException.Throw(PhpError.Warning, LibResources.GetString("arg:invalid_value", "fromBase", fromBase));
return null;
}
try
{
return DoubleToBaseUnicode(value, toBase);
}
catch (ArgumentException)
{
PhpException.Throw(PhpError.Warning, LibResources.GetString("arg:invalid_value", "toBase", toBase));
return null;
}
}
#endregion
#region deg2rad, pi, cos, sin, tan, acos, asin, atan, atan2
/// <summary>
/// Degrees to radians.
/// </summary>
/// <param name="degrees"></param>
/// <returns></returns>
[ImplementsFunction("deg2rad"/*, FunctionImplOptions.Special*/)]
[PureFunction]
public static double DegreesToRadians(double degrees)
{
return degrees / 180 * Math.PI;
}
/// <summary>
/// Radians to degrees.
/// </summary>
/// <param name="radians"></param>
/// <returns></returns>
[ImplementsFunction("rad2deg")]
[PureFunction]
public static double RadiansToDegrees(double radians)
{
return radians / Math.PI * 180;
}
/// <summary>
/// Returns an approximation of pi.
/// </summary>
/// <returns>The value of pi as <c>double</c>.</returns>
[ImplementsFunction("pi")]
[PureFunction]
public static double PI()
{
return Math.PI;
}
/// <summary>
/// Returns the arc cosine of arg in radians.
/// acos() is the complementary function of cos(), which means that <paramref name="x"/>==cos(acos(<paramref name="x"/>)) for every value of a that is within acos()' range.
/// </summary>
/// <param name="x">The argument to process.</param>
/// <returns>The arc cosine of <paramref name="x"/> in radians.</returns>
[ImplementsFunction("acos"/*, FunctionImplOptions.Special*/)]
[PureFunction]
public static double Acos(double x)
{
return Math.Acos(x);
}
/// <summary>
/// Returns the arc sine of arg in radians. asin() is the complementary function of sin(), which means that <paramref name="x"/>==sin(asin(<paramref name="x"/>)) for every value of a that is within asin()'s range.
/// </summary>
/// <param name="x">The argument to process.</param>
/// <returns>The arc sine of <paramref name="x"/> in radians.</returns>
[ImplementsFunction("asin"/*, FunctionImplOptions.Special*/)]
[PureFunction]
public static double Asin(double x)
{
return Math.Asin(x);
}
[ImplementsFunction("atan"/*, FunctionImplOptions.Special*/)]
[PureFunction]
public static double Atan(double x)
{
return Math.Atan(x);
}
[ImplementsFunction("atan2")]
[PureFunction]
public static double Atan2(double y, double x)
{
double rv = Math.Atan(y / x);
if (x < 0)
{
return ((rv > 0) ? -Math.PI : Math.PI) + rv;
}
else return rv;
}
[ImplementsFunction("cos"/*, FunctionImplOptions.Special*/)]
[PureFunction]
public static double Cos(double x)
{
return Math.Cos(x);
}
[ImplementsFunction("sin"/*, FunctionImplOptions.Special*/)]
[PureFunction]
public static double Sin(double x)
{
return Math.Sin(x);
}
[ImplementsFunction("tan"/*, FunctionImplOptions.Special*/)]
[PureFunction]
public static double Tan(double x)
{
return Math.Tan(x);
}
#endregion
#region cosh, sinh, tanh, acosh, asinh, atanh
[ImplementsFunction("cosh")]
[PureFunction]
public static double Cosh(double x)
{
return Math.Cosh(x);
}
[ImplementsFunction("sinh")]
[PureFunction]
public static double Sinh(double x)
{
return Math.Sinh(x);
}
[ImplementsFunction("tanh")]
[PureFunction]
public static double Tanh(double x)
{
return Math.Tanh(x);
}
[ImplementsFunction("acosh")]
[PureFunction]
public static double Acosh(double x)
{
return Math.Log(x + Math.Sqrt(x * x - 1));
}
[ImplementsFunction("asinh")]
[PureFunction]
public static double Asinh(double x)
{
return Math.Log(x + Math.Sqrt(x * x + 1));
}
[ImplementsFunction("atanh")]
[PureFunction]
public static double Atanh(double x)
{
return Math.Log((1 + x) / (1 - x)) / 2;
}
#endregion
#region exp, expm1, log, log10, log1p, pow, sqrt, hypot
/// <summary>
/// Returns <c>e</c> raised to the power of <paramref name="x"/>.
/// </summary>
[ImplementsFunction("exp"/*, FunctionImplOptions.Special*/)]
[PureFunction]
public static double Exp(double x)
{
return Math.Exp(x);
}
/// <summary>
/// expm1() returns the equivalent to 'exp(arg) - 1' computed in a way that is accurate even
/// if the value of arg is near zero, a case where 'exp (arg) - 1' would be inaccurate due to
/// subtraction of two numbers that are nearly equal.
/// </summary>
/// <param name="x">The argument to process </param>
[ImplementsFunction("expm1")]
[PureFunction]
[EditorBrowsable(EditorBrowsableState.Never)]
public static double ExpM1(double x)
{
return Math.Exp(x) - 1.0; // TODO: implement exp(x)-1 for x near to zero
}
/// <summary>
/// Returns the base-10 logarithm of <paramref name="x"/>.
/// </summary>
[ImplementsFunction("log10")]
[PureFunction]
public static double Log10(double x)
{
return Math.Log10(x);
}
[ImplementsFunction("log"/*, FunctionImplOptions.Special*/)]
[PureFunction]
public static double Log(double x)
{
return Math.Log(x);
}
/// <summary>
/// If the optional <paramref name="logBase"/> parameter is specified, log() returns log(<paramref name="logBase"/>) <paramref name="x"/>, otherwise log() returns the natural logarithm of <paramref name="x"/>.
/// </summary>
[ImplementsFunction("log"/*, FunctionImplOptions.Special*/)]
[PureFunction]
public static double Log(double x, double logBase)
{
return MathEx.Log(x, logBase);
}
/// <summary>
/// log1p() returns log(1 + number) computed in a way that is accurate even when the value
/// of number is close to zero. log() might only return log(1) in this case due to lack of precision.
/// </summary>
/// <param name="x">The argument to process </param>
/// <returns></returns>
[ImplementsFunction("log1p")]
[PureFunction]
[EditorBrowsable(EditorBrowsableState.Never)]
public static double Log1P(double x)
{
return Math.Log(x + 1.0); // TODO: implement log(x+1) for x near to zero
}
/// <summary>
/// Returns <paramref name="base"/> raised to the power of <paramref name="exp"/>.
/// </summary>
[ImplementsFunction("pow")]
[PureFunction]
public static object Power(object @base, object exp)
{
double dbase, dexp;
int ibase, iexp;
long lbase, lexp;
Core.Convert.NumberInfo info_base, info_exp;
info_base = Core.Convert.ObjectToNumber(@base, out ibase, out lbase, out dbase);
info_exp = Core.Convert.ObjectToNumber(exp, out iexp, out lexp, out dexp);
if (((info_base | info_exp) & PHP.Core.Convert.NumberInfo.Double) == 0 && lexp >= 0)
{
// integer base, non-negative integer exp //
long lpower;
double dpower;
if (!Power(lbase, lexp, out lpower, out dpower))
return dpower;
if (lpower >= Int32.MinValue && lpower <= Int32.MaxValue)
return (Int32)lpower;
return lpower;
}
if (dbase < 0)
{
// cannot rount to integer:
if (Math.Ceiling(dexp) > dexp)
return Double.NaN;
double result = Math.Pow(-dbase, dexp);
return (Math.IEEERemainder(Math.Abs(dexp), 2.0) < 1.0) ? result : -result;
}
if (dexp < 0)
return 1 / Math.Pow(dbase, -dexp);
else
return Math.Pow(dbase, dexp);
}
private static bool Power(long x, long y, out long longResult, out double doubleResult)
{
long l1 = 1, l2 = x;
if (y == 0) // anything powered by 0 is 1
{
doubleResult = longResult = 1;
return true;
}
if (x == 0) // 0^(anything except 0) is 0
{
doubleResult = longResult = 0;
return true;
}
try
{
while (y >= 1)
{
if ((y & 1) != 0)
{
l1 *= l2;
y--;
}
else
{
l2 *= l2;
y /= 2;
}
}
}
catch(ArithmeticException)
{
longResult = 0;//ignored
doubleResult = (double)l1 * Math.Pow(l2, y);
return false;
}
// able to do it with longs
doubleResult = longResult = l1;
return true;
}
[ImplementsFunction("sqrt"/*, FunctionImplOptions.Special*/)]
[PureFunction]
public static double Sqrt(double x)
{
return Math.Sqrt(x);
}
[ImplementsFunction("hypot")]
[PureFunction]
public static double Hypotenuse(double x, double y)
{
return Math.Sqrt(x * x + y * y);
}
#endregion
#region ceil, floor, round, abs, fmod, max, min
/// <summary>
/// Returns the next highest integer value by rounding up <paramref name="x"/> if necessary.
/// </summary>
/// <param name="x">The value to round.</param>
/// <returns><paramref name="x"/> rounded up to the next highest integer. The return value of ceil() is still of type <c>double</c> as the value range of double is usually bigger than that of integer.</returns>
[ImplementsFunction("ceil")]
[PureFunction]
public static double Ceiling(double x)
{
return Math.Ceiling(x);
}
/// <summary>
/// Returns the next lowest integer value by rounding down <paramref name="x"/> if necessary.
/// </summary>
/// <param name="x">The numeric value to round.</param>
/// <returns><paramref name="x"/> rounded to the next lowest integer. The return value of floor() is still of type <c>double</c> because the value range of double is usually bigger than that of integer.</returns>
[ImplementsFunction("floor")]
[PureFunction]
public static double Floor(double x)
{
return Math.Floor(x);
}
/// <summary>
/// Rounds a float.
/// </summary>
/// <param name="x">The value to round.</param>
/// <returns>The rounded value.</returns>
[ImplementsFunction("round")]
[PureFunction]
public static double Round(double x)
{
return RoundInternal(x, RoundMode.HalfUp);
}
/// <summary>
/// Rounds a float.
/// </summary>
/// <param name="x">The value to round.</param>
/// <param name="precision">The optional number of decimal digits to round to. Can be less than zero to ommit digits at the end. Default is <c>0</c>.</param>
/// <returns>The rounded value.</returns>
[ImplementsFunction("round")]
[PureFunction]
public static double Round(double x, int precision /*= 0*/)
{
return Round(x, precision, RoundMode.HalfUp);
}
/// <summary>
/// <c>$mode</c> parameter for <see cref="Round(double,int,RoundMode)"/> function.
/// </summary>
public enum RoundMode : int
{
/// <summary>
/// When a number is halfway between two others, it is rounded away from zero.
/// </summary>
[ImplementsConstant("PHP_ROUND_HALF_UP")]
HalfUp = 1,
/// <summary>
/// When a number is halfway between two others, it is rounded to the zero.
/// </summary>
[ImplementsConstant("PHP_ROUND_HALF_DOWN")]
HalfDown = 2,
/// <summary>
/// When a number is halfway between two others, it is rounded toward the nearest even number.
/// </summary>
[ImplementsConstant("PHP_ROUND_HALF_EVEN")]
HalfEven = 3,
/// <summary>
/// When a number is halfway between two others, it is rounded toward the nearest odd number.
/// </summary>
[ImplementsConstant("PHP_ROUND_HALF_ODD")]
HalfOdd = 4,
}
#region Round Helpers
/// <summary>
/// Returns precise value of 10^<paramref name="power"/>.
/// </summary>
private static double Power10Value(int power)
{
switch (power)
{
case -15: return .000000000000001;
case -14: return .00000000000001;
case -13: return .0000000000001;
case -12: return .000000000001;
case -11: return .00000000001;
case -10: return .0000000001;
case -9: return .000000001;
case -8: return .00000001;
case -7: return .0000001;
case -6: return .000001;
case -5: return .00001;
case -4: return .0001;
case -3: return .001;
case -2: return .01;
case -1: return .1;
case 0: return 1.0;
case 1: return 10.0;
case 2: return 100.0;
case 3: return 1000.0;
case 4: return 10000.0;
case 5: return 100000.0;
case 6: return 1000000.0;
case 7: return 10000000.0;
case 8: return 100000000.0;
case 9: return 1000000000.0;
case 10: return 10000000000.0;
case 11: return 100000000000.0;
case 12: return 1000000000000.0;
case 13: return 10000000000000.0;
case 14: return 100000000000000.0;
case 15: return 1000000000000000.0;
default: return Math.Pow(10.0, (double)power);
}
}
private static double RoundInternal(double value, RoundMode mode)
{
double tmp_value;
if (value >= 0.0)
{
tmp_value = Math.Floor(value + 0.5);
if (mode != RoundMode.HalfUp)
{
if ((mode == RoundMode.HalfDown && value == (-0.5 + tmp_value)) ||
(mode == RoundMode.HalfEven && value == (0.5 + 2 * Math.Floor(tmp_value * .5))) ||
(mode == RoundMode.HalfOdd && value == (0.5 + 2 * Math.Floor(tmp_value * .5) - 1.0)))
{
tmp_value = tmp_value - 1.0;
}
}
}
else
{
tmp_value = Math.Ceiling(value - 0.5);
if (mode != RoundMode.HalfUp)
{
if ((mode == RoundMode.HalfDown && value == (0.5 + tmp_value)) ||
(mode == RoundMode.HalfEven && value == (-0.5 + 2 * Math.Ceiling(tmp_value * .5))) ||
(mode == RoundMode.HalfOdd && value == (-0.5 + 2 * Math.Ceiling(tmp_value * .5) + 1.0)))
{
tmp_value = tmp_value + 1.0;
}
}
}
return tmp_value;
}
private static readonly double[] _Log10AbsValues = new[]
{
1e-8, 1e-7, 1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1,
1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7,
1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15,
1e16, 1e17, 1e18, 1e19, 1e20, 1e21, 1e22, 1e23
};
private static int _Log10Abs(double value)
{
value = Math.Abs(value);
if (value < 1e-8 || value > 1e23)
{
return (int)Math.Floor(Math.Log10(value));
}
else
{
var values = _Log10AbsValues;
/* Do a binary search with 5 steps */
var result = 16;
if (value < values[result])
result -= 8;
else
result += 8;
if (value < values[result])
result -= 4;
else
result += 4;
if (value < values[result])
result -= 2;
else
result += 2;
if (value < values[result])
result -= 1;
else
result += 1;
if (value < values[result])
result -= 1;
result -= 8;
//
return result;
}
}
#endregion
/// <summary>
/// Rounds a float.
/// </summary>
/// <param name="x">The value to round.</param>
/// <param name="precision">The optional number of decimal digits to round to. Can be less than zero to ommit digits at the end. Default is <c>0</c>.</param>
/// <param name="mode">One of PHP_ROUND_HALF_UP, PHP_ROUND_HALF_DOWN, PHP_ROUND_HALF_EVEN, or PHP_ROUND_HALF_ODD. Default is <c>PHP_ROUND_HALF_UP</c>.</param>
/// <returns>The rounded value.</returns>
[ImplementsFunction("round")]
[PureFunction]
public static double Round(double x, int precision /*= 0*/, RoundMode mode /*= RoundMode.HalfUp*/)
{
if (Double.IsInfinity(x) || Double.IsNaN(x) || x == default(double))
return x;
if (precision == 0)
{
return RoundInternal(x, mode);
}
else
{
if (precision > 23 || precision < -23)
return x;
//
// Following code is taken from math.c to avoid incorrect .NET rounding
//
var precision_places = 14 - _Log10Abs(x);
var f1 = Power10Value(precision);
double tmp_value;
/* If the decimal precision guaranteed by FP arithmetic is higher than
the requested places BUT is small enough to make sure a non-zero value
is returned, pre-round the result to the precision */
if (precision_places > precision && precision_places - precision < 15)
{
var f2 = Power10Value(precision_places);
tmp_value = x * f2;
/* preround the result (tmp_value will always be something * 1e14,
thus never larger than 1e15 here) */
tmp_value = RoundInternal(tmp_value, mode);
/* now correctly move the decimal point */
f2 = Power10Value(Math.Abs(precision - precision_places));
/* because places < precision_places */
tmp_value = tmp_value / f2;
}
else
{
/* adjust the value */
tmp_value = x * f1;
/* This value is beyond our precision, so rounding it is pointless */
if (Math.Abs(tmp_value) >= 1e15)
return x;
}
/* round the temp value */
tmp_value = RoundInternal(tmp_value, mode);
/* see if it makes sense to use simple division to round the value */
//if (precision < 23 && precision > -23)
{
tmp_value = tmp_value / f1;
}
//else
//{
// /* Simple division can't be used since that will cause wrong results.
// Instead, the number is converted to a string and back again using
// strtod(). strtod() will return the nearest possible FP value for
// that string. */
// /* 40 Bytes should be more than enough for this format string. The
// float won't be larger than 1e15 anyway. But just in case, use
// snprintf() and make sure the buffer is zero-terminated */
// char buf[40];
// snprintf(buf, 39, "%15fe%d", tmp_value, -places);
// buf[39] = '\0';
// tmp_value = zend_strtod(buf, NULL);
// /* couldn't convert to string and back */
// if (!zend_finite(tmp_value) || zend_isnan(tmp_value)) {
// tmp_value = value;
// }
//}
return tmp_value;
}
}
/// <summary>
/// Returns the absolute value of <paramref name="x"/>.
/// </summary>
/// <param name="x">The numeric value to process.</param>
/// <returns></returns>
[ImplementsFunction("abs")]
[PureFunction]
public static object Abs(object x)
{
double dx;
int ix;
long lx;
switch (Core.Convert.ObjectToNumber(x, out ix, out lx, out dx) & Core.Convert.NumberInfo.TypeMask)
{
case Core.Convert.NumberInfo.Double:
return Math.Abs(dx);
case Core.Convert.NumberInfo.Integer:
if (ix == int.MinValue)
return -lx;
else
return Math.Abs(ix);
case Core.Convert.NumberInfo.LongInteger:
if (lx == long.MinValue)
return -dx;
else
return Math.Abs(lx);
}
return null;
}
/// <summary>
/// Returns the floating point remainder (modulo) of the division of the arguments.
/// </summary>
/// <param name="x">The dividend.</param>
/// <param name="y">The divisor.</param>
/// <returns>The floating point remainder of <paramref name="x"/>/<paramref name="y"/>.</returns>
[ImplementsFunction("fmod")]
[PureFunction]
public static double Fmod(double x, double y)
{
y = Math.Abs(y);
double rem = Math.IEEERemainder(Math.Abs(x), y);
if (rem < 0) rem += y;
return (x >= 0) ? rem : -rem;
}
/// <summary>
/// Find highest value.
/// If the first and only parameter is an array, max() returns the highest value in that array. If at least two parameters are provided, max() returns the biggest of these values.
/// </summary>
/// <param name="numbers">An array containing the values or values separately.</param>
/// <returns>max() returns the numerically highest of the parameter values. If multiple values can be considered of the same size, the one that is listed first will be returned.
/// When max() is given multiple arrays, the longest array is returned. If all the arrays have the same length, max() will use lexicographic ordering to find the return value.
/// When given a string it will be cast as an integer when comparing.</returns>
[ImplementsFunction("max")]
[PureFunction]
public static object Max(params object[] numbers)
{
return GetExtreme(numbers, true);
}
/// <summary>
/// Find lowest value.
/// If the first and only parameter is an array, min() returns the lowest value in that array. If at least two parameters are provided, min() returns the smallest of these values.
/// </summary>
/// <param name="numbers">An array containing the values or values separately.</param>
/// <returns>min() returns the numerically lowest of the parameter values.</returns>
[ImplementsFunction("min")]
[PureFunction]
public static object Min(params object[] numbers)
{
return GetExtreme(numbers, false);
}
internal static object GetExtreme(object[] numbers, bool maximum)
{
if ((numbers.Length == 1) && (numbers[0] is PhpArray))
{
IEnumerable e = (numbers[0] as PhpArray).Values;
Debug.Assert(e != null);
return FindExtreme(e, maximum);
}
return FindExtreme(numbers, maximum);
}
internal static object FindExtreme(IEnumerable array, bool maximum)
{
object ex = null;
int fact = maximum ? 1 : -1;
foreach (object o in array)
{
if (ex == null) ex = o;
else
{
if ((PhpComparer.Default.Compare(o, ex) * fact) > 0) ex = o;
}
}
return ex;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void MultiplyDouble()
{
var test = new SimpleBinaryOpTest__MultiplyDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__MultiplyDouble
{
private const int VectorSize = 16;
private const int ElementCount = VectorSize / sizeof(Double);
private static Double[] _data1 = new Double[ElementCount];
private static Double[] _data2 = new Double[ElementCount];
private static Vector128<Double> _clsVar1;
private static Vector128<Double> _clsVar2;
private Vector128<Double> _fld1;
private Vector128<Double> _fld2;
private SimpleBinaryOpTest__DataTable<Double> _dataTable;
static SimpleBinaryOpTest__MultiplyDouble()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__MultiplyDouble()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); }
_dataTable = new SimpleBinaryOpTest__DataTable<Double>(_data1, _data2, new Double[ElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.Multiply(
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.Multiply(
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.Multiply(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Multiply), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Multiply), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Multiply), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.Multiply(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr);
var result = Sse2.Multiply(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse2.Multiply(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse2.Multiply(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__MultiplyDouble();
var result = Sse2.Multiply(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.Multiply(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Double> left, Vector128<Double> right, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[ElementCount];
Double[] inArray2 = new Double[ElementCount];
Double[] outArray = new Double[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[ElementCount];
Double[] inArray2 = new Double[ElementCount];
Double[] outArray = new Double[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "")
{
if (BitConverter.DoubleToInt64Bits(left[0] * right[0]) != BitConverter.DoubleToInt64Bits(result[0]))
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if (BitConverter.DoubleToInt64Bits(left[i] * right[i]) != BitConverter.DoubleToInt64Bits(result[i]))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.Multiply)}<Double>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
#if BIT64
using nint = System.Int64;
#else
using nint = System.Int32;
#endif
namespace System
{
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public struct IntPtr : IEquatable<IntPtr>, ISerializable
{
// WARNING: We allow diagnostic tools to directly inspect this member (_value).
// See https://github.com/dotnet/corert/blob/master/Documentation/design-docs/diagnostics/diagnostics-tools-contract.md for more details.
// Please do not change the type, the name, or the semantic usage of this member without understanding the implication for tools.
// Get in touch with the diagnostics team if you have questions.
private unsafe void* _value; // Do not rename (binary serialization)
[Intrinsic]
public static readonly IntPtr Zero;
[Intrinsic]
[NonVersionable]
public unsafe IntPtr(int value)
{
_value = (void*)value;
}
[Intrinsic]
[NonVersionable]
public unsafe IntPtr(long value)
{
#if BIT64
_value = (void*)value;
#else
_value = (void*)checked((int)value);
#endif
}
[CLSCompliant(false)]
[Intrinsic]
[NonVersionable]
public unsafe IntPtr(void* value)
{
_value = value;
}
private unsafe IntPtr(SerializationInfo info, StreamingContext context)
{
long l = info.GetInt64("value");
if (Size == 4 && (l > int.MaxValue || l < int.MinValue))
throw new ArgumentException(SR.Serialization_InvalidPtrValue);
_value = (void*)l;
}
unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException(nameof(info));
info.AddValue("value", ToInt64());
}
public unsafe override bool Equals(Object obj)
{
if (obj is IntPtr)
{
return (_value == ((IntPtr)obj)._value);
}
return false;
}
unsafe bool IEquatable<IntPtr>.Equals(IntPtr other)
{
return _value == other._value;
}
public unsafe override int GetHashCode()
{
#if BIT64
long l = (long)_value;
return (unchecked((int)l) ^ (int)(l >> 32));
#else
return unchecked((int)_value);
#endif
}
[Intrinsic]
[NonVersionable]
public unsafe int ToInt32()
{
#if BIT64
long l = (long)_value;
return checked((int)l);
#else
return (int)_value;
#endif
}
[Intrinsic]
[NonVersionable]
public unsafe long ToInt64()
{
return (nint)_value;
}
[Intrinsic]
[NonVersionable]
public static unsafe explicit operator IntPtr(int value)
{
return new IntPtr(value);
}
[Intrinsic]
[NonVersionable]
public static unsafe explicit operator IntPtr(long value)
{
return new IntPtr(value);
}
[CLSCompliant(false)]
[Intrinsic]
[NonVersionable]
public static unsafe explicit operator IntPtr(void* value)
{
return new IntPtr(value);
}
[CLSCompliant(false)]
[Intrinsic]
[NonVersionable]
public static unsafe explicit operator void* (IntPtr value)
{
return value._value;
}
[Intrinsic]
[NonVersionable]
public static unsafe explicit operator int(IntPtr value)
{
#if BIT64
long l = (long)value._value;
return checked((int)l);
#else
return (int)value._value;
#endif
}
[Intrinsic]
[NonVersionable]
public static unsafe explicit operator long(IntPtr value)
{
return (nint)value._value;
}
[Intrinsic]
[NonVersionable]
public static unsafe bool operator ==(IntPtr value1, IntPtr value2)
{
return value1._value == value2._value;
}
[Intrinsic]
[NonVersionable]
public static unsafe bool operator !=(IntPtr value1, IntPtr value2)
{
return value1._value != value2._value;
}
[NonVersionable]
public static IntPtr Add(IntPtr pointer, int offset)
{
return pointer + offset;
}
[Intrinsic]
[NonVersionable]
public static unsafe IntPtr operator +(IntPtr pointer, int offset)
{
return new IntPtr((nint)pointer._value + offset);
}
[NonVersionable]
public static IntPtr Subtract(IntPtr pointer, int offset)
{
return pointer - offset;
}
[Intrinsic]
[NonVersionable]
public static unsafe IntPtr operator -(IntPtr pointer, int offset)
{
return new IntPtr((nint)pointer._value - offset);
}
public static int Size
{
[Intrinsic]
[NonVersionable]
get
{
return sizeof(nint);
}
}
[CLSCompliant(false)]
[Intrinsic]
[NonVersionable]
public unsafe void* ToPointer()
{
return _value;
}
public unsafe override string ToString()
{
return ((nint)_value).ToString(CultureInfo.InvariantCulture);
}
public unsafe string ToString(string format)
{
return ((nint)_value).ToString(format, CultureInfo.InvariantCulture);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Flurl;
using Microsoft.Extensions.Logging;
using Neutrino.Consensus.Entities;
using Neutrino.Consensus.Events;
using Neutrino.Consensus.Responses;
using Newtonsoft.Json;
namespace Neutrino.Consensus.States
{
public class Candidate : State
{
private int _lastVoting = int.MaxValue;
private readonly IConsensusContext _consensusContext;
private readonly ILogger<IConsensusContext> _logger;
private CancellationTokenSource _votingTokenSource;
public Candidate(IConsensusContext consensusContext, ILogger<IConsensusContext> logger)
{
_consensusContext = consensusContext;
_logger = logger;
ClearVoteGranted();
}
public override void Proceed()
{
OpenVoting();
}
public override IResponse TriggerEvent(IEvent triggeredEvent)
{
var requestVoteEvent = triggeredEvent as RequestVoteEvent;
if(requestVoteEvent != null)
{
_logger.LogInformation($"Retreived 'LeaderRequestEvent' event (currentTerm: {requestVoteEvent.Term}, node: {requestVoteEvent.Node.Id}).");
bool voteGranted = OtherNodeCanBeLeader(requestVoteEvent);
if(voteGranted)
{
_consensusContext.CurrentTerm = requestVoteEvent.Term;
_consensusContext.NodeVote.LeaderNode = requestVoteEvent.Node;
_consensusContext.NodeVote.VoteTerm = requestVoteEvent.Term;
_logger.LogInformation($"Voting for node ({requestVoteEvent.Node.Id}): GRANTED.");
StopVoting();
_consensusContext.State = new Follower(_consensusContext, _logger);
}
else
{
_logger.LogInformation($"Voting for node ({requestVoteEvent.Node.Id}): NOT GRANTED.");
}
return new RequestVoteResponse(voteGranted, _consensusContext.CurrentTerm, _consensusContext.CurrentNode);
}
return new EmptyResponse();
}
public override void DisposeCore()
{
}
private void OpenVoting()
{
if (_consensusContext.NodeStates == null || _consensusContext.NodeStates.Count == 0)
{
_consensusContext.State = new Leader(_consensusContext, _logger);
return;
}
_votingTokenSource = new CancellationTokenSource();
Task.Run(() => StartVoting(_votingTokenSource.Token), _votingTokenSource.Token);
}
private void StopVoting()
{
_votingTokenSource.Cancel();
}
private void StartVoting(CancellationToken token)
{
while(!token.IsCancellationRequested)
{
if(_lastVoting >= _consensusContext.ElectionTimeout)
{
_consensusContext.CurrentTerm++;
var tasks = SendLeaderRequestVotes();
if(!CollectVotes(tasks))
{
_logger.LogInformation($"All other nodes are disabled. Current node can be a leader.");
_consensusContext.State = new Leader(_consensusContext, _logger);
break;
}
if (CurrentNodeCanBeLeader())
{
_consensusContext.State = new Leader(_consensusContext, _logger);
break;
}
_lastVoting = 0;
}
Thread.Sleep(50);
_lastVoting += 50;
}
}
private bool CollectVotes(List<Task<HttpResponseMessage>> tasks)
{
var amountOfFailed = 0;
foreach (var task in tasks)
{
if (task.Status == TaskStatus.RanToCompletion && task.Result.IsSuccessStatusCode)
{
var responseContent = task.Result.Content.ReadAsStringAsync().GetAwaiter().GetResult();
var requestVoteResponse = JsonConvert.DeserializeObject<RequestVoteResponse>(responseContent);
_consensusContext.CurrentTerm = requestVoteResponse.CurrentTerm;
var nodeState = _consensusContext.NodeStates.FirstOrDefault(x => x.NodeAddress == requestVoteResponse.Node.Address);
if(nodeState != null)
{
nodeState.VoteGranted = requestVoteResponse.VoteGranted;
}
_logger.LogInformation($"Vote from node ({requestVoteResponse.Node.Id}): {requestVoteResponse.VoteGranted} (term: {_consensusContext.CurrentTerm}).");
}
else
{
_logger.LogWarning($"Vote failed with task status: {task.Status} (term: {_consensusContext.CurrentTerm}).");
amountOfFailed++;
}
}
return amountOfFailed < tasks.Count;
}
private void ClearVoteGranted()
{
foreach (var nodeState in _consensusContext.NodeStates)
{
nodeState.VoteGranted = false;
}
}
private List<Task<HttpResponseMessage>> SendLeaderRequestVotes()
{
var tasks = new List<Task<HttpResponseMessage>>();
try
{
foreach (var nodeState in _consensusContext.NodeStates.Where(x => x.VoteGranted == false))
{
var task = SendLeaderRequestVote(nodeState.NodeAddress);
tasks.Add(task);
}
Task.WhenAll(tasks.ToArray()).GetAwaiter().GetResult();
}
catch (Exception exception)
{
_logger.LogWarning($"Cannot connect to node. Exception type: '{exception.GetType()}'. Exception message: {exception.Message}.");
}
return tasks;
}
private Task<HttpResponseMessage> SendLeaderRequestVote(string nodeAddress)
{
var url = nodeAddress.AppendPathSegment("api/raft/request-vote");
_logger.LogInformation($"Sending leader request to node: '{nodeAddress}'. Endpoint address: '{url}'.");
var request = new HttpRequestMessage(HttpMethod.Post, url);
request.Headers.Authorization = new AuthenticationHeaderValue(
_consensusContext.ConsensusOptions.AuthenticationScheme, _consensusContext.ConsensusOptions.AuthenticationParameter);
var requestVoteEvent = new RequestVoteEvent(_consensusContext.CurrentTerm, _consensusContext.CurrentNode);
var jsonContent = JsonConvert.SerializeObject(requestVoteEvent);
var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
request.Content = content;
var task = _consensusContext.HttpClient.SendAsync(request);
return task;
}
private bool CurrentNodeCanBeLeader()
{
var amountOfGrantedVotes = _consensusContext.NodeStates.Count(x => x.VoteGranted) + 1;
var allNodes = _consensusContext.NodeStates.Count + 1;
return (amountOfGrantedVotes * 2) >= allNodes;
}
private bool OtherNodeCanBeLeader(RequestVoteEvent requestVoteEvent)
{
return requestVoteEvent.Term > _consensusContext.CurrentTerm
&& requestVoteEvent.Term > _consensusContext.NodeVote.VoteTerm;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Logic
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for IntegrationAccountsOperations.
/// </summary>
public static partial class IntegrationAccountsOperationsExtensions
{
/// <summary>
/// Gets a list of integration accounts by subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='top'>
/// The number of items to be included in the result.
/// </param>
public static IPage<IntegrationAccount> ListBySubscription(this IIntegrationAccountsOperations operations, int? top = default(int?))
{
return Task.Factory.StartNew(s => ((IIntegrationAccountsOperations)s).ListBySubscriptionAsync(top), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a list of integration accounts by subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='top'>
/// The number of items to be included in the result.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<IntegrationAccount>> ListBySubscriptionAsync(this IIntegrationAccountsOperations operations, int? top = default(int?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListBySubscriptionWithHttpMessagesAsync(top, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a list of integration accounts by resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='top'>
/// The number of items to be included in the result.
/// </param>
public static IPage<IntegrationAccount> ListByResourceGroup(this IIntegrationAccountsOperations operations, string resourceGroupName, int? top = default(int?))
{
return Task.Factory.StartNew(s => ((IIntegrationAccountsOperations)s).ListByResourceGroupAsync(resourceGroupName, top), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a list of integration accounts by resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='top'>
/// The number of items to be included in the result.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<IntegrationAccount>> ListByResourceGroupAsync(this IIntegrationAccountsOperations operations, string resourceGroupName, int? top = default(int?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, top, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets an integration account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
public static IntegrationAccount Get(this IIntegrationAccountsOperations operations, string resourceGroupName, string integrationAccountName)
{
return Task.Factory.StartNew(s => ((IIntegrationAccountsOperations)s).GetAsync(resourceGroupName, integrationAccountName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets an integration account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IntegrationAccount> GetAsync(this IIntegrationAccountsOperations operations, string resourceGroupName, string integrationAccountName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, integrationAccountName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates an integration account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='integrationAccount'>
/// The integration account.
/// </param>
public static IntegrationAccount CreateOrUpdate(this IIntegrationAccountsOperations operations, string resourceGroupName, string integrationAccountName, IntegrationAccount integrationAccount)
{
return Task.Factory.StartNew(s => ((IIntegrationAccountsOperations)s).CreateOrUpdateAsync(resourceGroupName, integrationAccountName, integrationAccount), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates an integration account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='integrationAccount'>
/// The integration account.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IntegrationAccount> CreateOrUpdateAsync(this IIntegrationAccountsOperations operations, string resourceGroupName, string integrationAccountName, IntegrationAccount integrationAccount, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, integrationAccountName, integrationAccount, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates an integration account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='integrationAccount'>
/// The integration account.
/// </param>
public static IntegrationAccount Update(this IIntegrationAccountsOperations operations, string resourceGroupName, string integrationAccountName, IntegrationAccount integrationAccount)
{
return Task.Factory.StartNew(s => ((IIntegrationAccountsOperations)s).UpdateAsync(resourceGroupName, integrationAccountName, integrationAccount), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Updates an integration account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='integrationAccount'>
/// The integration account.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IntegrationAccount> UpdateAsync(this IIntegrationAccountsOperations operations, string resourceGroupName, string integrationAccountName, IntegrationAccount integrationAccount, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, integrationAccountName, integrationAccount, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes an integration account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
public static void Delete(this IIntegrationAccountsOperations operations, string resourceGroupName, string integrationAccountName)
{
Task.Factory.StartNew(s => ((IIntegrationAccountsOperations)s).DeleteAsync(resourceGroupName, integrationAccountName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes an integration account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IIntegrationAccountsOperations operations, string resourceGroupName, string integrationAccountName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, integrationAccountName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Lists the integration account callback URL.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='notAfter'>
/// The expiry time.
/// </param>
public static CallbackUrl ListCallbackUrl(this IIntegrationAccountsOperations operations, string resourceGroupName, string integrationAccountName, DateTime? notAfter = default(DateTime?))
{
return Task.Factory.StartNew(s => ((IIntegrationAccountsOperations)s).ListCallbackUrlAsync(resourceGroupName, integrationAccountName, notAfter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists the integration account callback URL.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='notAfter'>
/// The expiry time.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<CallbackUrl> ListCallbackUrlAsync(this IIntegrationAccountsOperations operations, string resourceGroupName, string integrationAccountName, DateTime? notAfter = default(DateTime?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListCallbackUrlWithHttpMessagesAsync(resourceGroupName, integrationAccountName, notAfter, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a list of integration accounts by subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<IntegrationAccount> ListBySubscriptionNext(this IIntegrationAccountsOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IIntegrationAccountsOperations)s).ListBySubscriptionNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a list of integration accounts by subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<IntegrationAccount>> ListBySubscriptionNextAsync(this IIntegrationAccountsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListBySubscriptionNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a list of integration accounts by resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<IntegrationAccount> ListByResourceGroupNext(this IIntegrationAccountsOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IIntegrationAccountsOperations)s).ListByResourceGroupNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a list of integration accounts by resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<IntegrationAccount>> ListByResourceGroupNextAsync(this IIntegrationAccountsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using BoundingVolumeRendering;
using Camera3D;
using AxisReference;
using InputHandler;
using MenuUtility;
using MusicClasses;
using ReticuleCursor;
using Geometry;
using Games3Project2.Globals;
using Networking;
using AI;
namespace Games3Project2
{
public class JuggernautGame : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
Axis_Reference axisReference;
SpriteFont consolas;
SpriteFont tahoma;
Music music;
Texture2D splashTexture;
Texture2D background;
int splashTimer = 0;
const int SPLASH_LENGTH = 3000;
int timeInSinglePlayer = 0;
const int SINGLE_PLAYER_LENGTH = 60000;
int finalScore = 0;
Menu mainMenu;
Menu levelMenu;
Menu createGameMenu;
Menu joinGameMenu;
Level levelManager;
Boolean debug = true;
//local player joining
List<PlayerIndex> connectedPlayers = new List<PlayerIndex>();
List<PlayerIndex> joinedPlayers = new List<PlayerIndex>();
public JuggernautGame()
{
Components.Add(new GamerServicesComponent(this));
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
#if WINDOWS
//Preserves the 1.7777 aspect ratio of 1920x1080 (16/9)
//verses the 1.6 of 1280x800.
//1280 / (16/9) = 720
graphics.PreferredBackBufferWidth = 1280;
graphics.PreferredBackBufferHeight = 720;
#endif
}
protected override void Initialize()
{
Global.game = this;
Global.networkManager = new NetworkManager();
Global.graphics = graphics;
Global.graphics.GraphicsDevice.DepthStencilState = DepthStencilState.Default;
Global.viewPort = Global.graphics.GraphicsDevice.Viewport.Bounds;
Global.titleSafe = GetTitleSafeArea(.85f);
axisReference = new Axis_Reference(GraphicsDevice, 1.0f);
BoundingSphereRenderer.Initialize(GraphicsDevice, 45);
Global.heatmapKills = new Heatmap(Color.Black);
Global.heatmapDeaths = new Heatmap(Color.Red);
Global.heatmapUsedJetpack = new Heatmap(Color.Green);
this.IsMouseVisible = true;
base.Initialize();
}
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to drawWalls textures.
Global.spriteBatch = new SpriteBatch(GraphicsDevice);
Global.shot = Global.game.Content.Load<SoundEffect>(@"Audio/plasma").CreateInstance();
Global.jetpack = Global.game.Content.Load<SoundEffect>(@"Audio/cole").CreateInstance();
Global.jetpack.IsLooped = true;
Global.menusong = Global.game.Content.Load<SoundEffect>(@"Audio/menusong").CreateInstance();
Global.menusong.IsLooped = true;
Global.actionsong = Global.game.Content.Load<SoundEffect>(@"Audio/actionsong").CreateInstance();
Global.actionsong.IsLooped = true;
Global.actionsong.Volume = 0.5f;
Global.msElaspedTimeRemainingMsgDisplayed = 0;
music = new Music(this);
//music.playBackgroundMusic();
splashTexture = Content.Load<Texture2D>(@"Textures\splash");
consolas = Content.Load<SpriteFont>(@"Fonts/Consolas");
Global.consolas = consolas;
tahoma = Content.Load<SpriteFont>(@"Fonts/Tahoma");
Global.tahoma = tahoma;
background = Content.Load<Texture2D>(@"Textures\menubackground");
List<String> menuOptions = new List<String>();
menuOptions.Add("Single Player");
menuOptions.Add("Create New Multiplayer Game");
menuOptions.Add("Join Multiplayer Game");
menuOptions.Add("Heatmaps");
menuOptions.Add("Exit");
mainMenu = new Menu(menuOptions, "Juggernaut", new Vector2(Global.titleSafe.Left + 30,
Global.viewPort.Height / 2 - (menuOptions.Count / 2 * consolas.MeasureString("C").Y)));
List<String> levelOptions = new List<string>();
levelOptions.Add("Level One");
levelOptions.Add("Level Two");
levelOptions.Add("Level Three");
levelMenu = new Menu(levelOptions, "Juggernaut", new Vector2(Global.titleSafe.Left + 30,
Global.viewPort.Height / 2 - (menuOptions.Count / 2 * consolas.MeasureString("C").Y)));
List<String> gameOptions = new List<String>();
gameOptions.Add("Local");
gameOptions.Add("System Link");
gameOptions.Add("Player Match");
createGameMenu = new Menu(gameOptions, "Juggernaut", new Vector2(Global.titleSafe.Left + 30,
Global.viewPort.Height / 2 - (menuOptions.Count / 2 * consolas.MeasureString("C").Y)));
List<String> joinGameOptions = new List<string>();
joinGameOptions.Add("System Link");
joinGameOptions.Add("Player Match");
joinGameMenu = new Menu(joinGameOptions, "Juggernaut", new Vector2(Global.titleSafe.Left + 30,
Global.viewPort.Height / 2 - (menuOptions.Count / 2 * consolas.MeasureString("C").Y)));
levelManager = new Level();
Global.levelManager = levelManager;
for (int i = 0; i < Global.Constants.MAX_ALLOCATED_BULLETS; ++i)
{
Global.BulletManager.bullets.Add(new Bullet());
}
}
protected override void UnloadContent()
{
music.stopBackgroundMusic();
}
protected override void Update(GameTime gameTime)
{
Global.gameTime = gameTime;
Global.input.Update();
Global.networkManager.update();
if (Global.input.isFirstPress(Keys.OemTilde) ||
Global.input.isFirstPress(Buttons.DPadDown, PlayerIndex.One) ||
Global.input.isFirstPress(Buttons.DPadDown, PlayerIndex.Two) ||
Global.input.isFirstPress(Buttons.DPadDown, PlayerIndex.Three) ||
Global.input.isFirstPress(Buttons.DPadDown, PlayerIndex.Four))
{
Global.debugMode = !Global.debugMode; //Toggle mode
}
switch (Global.gameState)
{
#region Intro
case Global.GameState.Intro:
splashTimer += Global.gameTime.ElapsedGameTime.Milliseconds;
if (splashTimer > SPLASH_LENGTH ||
Global.input.isFirstPress(Buttons.A) ||
Global.input.isFirstPress(Buttons.Start) ||
Global.input.isFirstPress(Keys.Space) ||
Global.input.isFirstPress(Keys.Enter) ||
Global.input.isFirstPress(Keys.A))
{
splashTimer = 0;
Global.actionsong.Stop();
Global.menusong.Play();
Global.gameState = Global.GameState.Menu;
}
break;
#endregion //Intro
#region Menu
case Global.GameState.Menu:
// Allows the game to exit
if (Global.input.DetectBackPressedByAnyPlayer())
{
this.Exit();
}
switch (mainMenu.update())
{
case 0: //Single Player
Global.networkManager.hostSessionType = NetworkManager.HostSessionType.Host;
Global.gameState = Global.GameState.SetupSinglePlayer;
break;
case 1: //Create New Game (Networking or Local)
Global.networkManager.hostSessionType = NetworkManager.HostSessionType.Host;
Global.gameState = Global.GameState.SetupLocalPlayers;
break;
case 2: //Join Game
Global.gameState = Global.GameState.SetupLocalPlayers;
Global.networkManager.hostSessionType = NetworkManager.HostSessionType.Client;
break;
case 3: //Heatmaps
Global.debugMode = true;
Global.gameState = Global.GameState.SetupLocalPlayersHeatmap;
Global.networkManager.hostSessionType = NetworkManager.HostSessionType.Host;
break;
case 4: //Exit
this.Exit();
break;
}
break;
#endregion //Menu
#region CreateMenu
case Global.GameState.CreateMenu:
if (Global.input.isFirstPress(Buttons.B))
{
Global.gameState = Global.GameState.Menu;
}
switch (createGameMenu.update())
{
case 0: //Local
Global.networkManager.sessionType = NetworkSessionType.Local;
Global.gameState = Global.GameState.LevelPicking;
break;
case 1: //System Link
Global.networkManager.sessionType = NetworkSessionType.SystemLink;
Global.gameState = Global.GameState.LevelPicking;
break;
case 2: //Player Match
Global.networkManager.sessionType = NetworkSessionType.PlayerMatch;
Global.gameState = Global.GameState.LevelPicking;
break;
}
break;
#endregion //CreateMenu
#region JoinMenu
case Global.GameState.JoinMenu:
if (Global.input.isFirstPress(Buttons.B))
{
Global.gameState = Global.GameState.Menu;
}
switch (joinGameMenu.update())
{
case 0: //System Link
Global.networkManager.sessionType = NetworkSessionType.SystemLink;
Global.gameState = Global.GameState.Lobby;
int localIndex1 = 1;
if (Global.networkManager.joinSession())
{
foreach (LocalNetworkGamer gamer in Global.networkManager.networkSession.LocalGamers)
{
gamer.Tag = new LocalPlayer(Vector3.Zero, gamer.SignedInGamer.PlayerIndex, localIndex1++, gamer);
Global.localPlayers.Add((LocalPlayer)gamer.Tag);
}
}
break;
case 1: //Player Match
Global.networkManager.sessionType = NetworkSessionType.PlayerMatch;
Global.gameState = Global.GameState.Lobby;
int localIndex2 = 1;
if(Global.networkManager.joinSession())
{
foreach (LocalNetworkGamer gamer in Global.networkManager.networkSession.LocalGamers)
{
gamer.Tag = new LocalPlayer(Vector3.Zero, gamer.SignedInGamer.PlayerIndex, localIndex2++, gamer);
Global.localPlayers.Add((LocalPlayer)gamer.Tag);
}
}
break;
}
break;
#endregion //JoinMenu
#region SetupLocalPlayers
case Global.GameState.SetupLocalPlayers:
setupLocalPlayers();
break;
#endregion //SetupLocalPlayers
#region SetupSinglePlayer
case Global.GameState.SetupSinglePlayer:
setupSinglePlayer();
break;
#endregion //SetupSinglePlayer
#region LevelPicking
case Global.GameState.LevelPicking:
if (Global.input.isFirstPress(Buttons.B))
{
Global.gameState = Global.GameState.Menu;
}
switch (levelMenu.update())
{
case 0:
Global.gameState = Global.GameState.Lobby;
Global.levelManager.currentLevel = 1;
int localIndex = 1;
if (Global.networkManager.createSession())
{
foreach (LocalNetworkGamer gamer in Global.networkManager.networkSession.LocalGamers)
{
gamer.Tag = new LocalPlayer(Vector3.Zero, gamer.SignedInGamer.PlayerIndex, localIndex++, gamer);
Global.localPlayers.Add((LocalPlayer)gamer.Tag);
}
}
break;
case 1:
Global.gameState = Global.GameState.Lobby;
Global.levelManager.currentLevel = 2;
localIndex = 1;
if (Global.networkManager.createSession())
{
foreach (LocalNetworkGamer gamer in Global.networkManager.networkSession.LocalGamers)
{
gamer.Tag = new LocalPlayer(Vector3.Zero, gamer.SignedInGamer.PlayerIndex, localIndex++, gamer);
Global.localPlayers.Add((LocalPlayer)gamer.Tag);
}
}
break;
case 2:
Global.gameState = Global.GameState.Lobby;
Global.networkManager.createSession();
Global.levelManager.currentLevel = 3;
localIndex = 1;
foreach (LocalNetworkGamer gamer in Global.networkManager.networkSession.LocalGamers)
{
gamer.Tag = new LocalPlayer(Vector3.Zero, gamer.SignedInGamer.PlayerIndex, localIndex++, gamer);
Global.localPlayers.Add((LocalPlayer)gamer.Tag);
}
break;
}
break;
#endregion //LevelPicking
#region Lobby
case Global.GameState.Lobby:
if (Global.networkManager.currentState == NetworkManager.CurrentState.Running)
{
if (Global.input.isFirstPress(Buttons.B))
{
Global.gameState = Global.GameState.Menu;
Global.networkManager.disposeNetworkSession();
}
else if(Global.networkManager.hostSessionType == NetworkManager.HostSessionType.Host &&
Global.networkManager.networkSession.AllGamers.Count > 1 &&
(Global.input.isFirstPress(Buttons.A) || Global.input.isFirstPress(Buttons.Start)))
{
Global.networkManager.announceLevel(Global.levelManager.currentLevel);
Global.networkManager.networkSession.StartGame();
Global.levelManager.setupLevel();
}
}
break;
#endregion //Lobby
#region SetupLocalPlayersHeatmap
case Global.GameState.SetupLocalPlayersHeatmap:
setupLocalPlayersHeatmap();
break;
#endregion
#region ChooseHeatmap
case Global.GameState.ChooseHeatmap:
switch (levelMenu.update())
{
case 0: //Level 1
Global.levelManager.currentLevel = 1;
Global.levelManager.setupLevel();
int localIndex = 1;
if (Global.networkManager.createSession())
{
foreach (LocalNetworkGamer gamer in Global.networkManager.networkSession.LocalGamers)
{
gamer.Tag = new LocalPlayer(Vector3.Zero, gamer.SignedInGamer.PlayerIndex, localIndex++, gamer);
Global.localPlayers.Add((LocalPlayer)gamer.Tag);
}
}
Global.menusong.Stop();
Global.actionsong.Play();
Global.gameState = Global.GameState.playingHeatmap;
break;
case 1: //Level 2
Global.levelManager.currentLevel = 2;
Global.levelManager.setupLevel();
int localIndex2 = 1;
if (Global.networkManager.createSession())
{
foreach (LocalNetworkGamer gamer in Global.networkManager.networkSession.LocalGamers)
{
gamer.Tag = new LocalPlayer(Vector3.Zero, gamer.SignedInGamer.PlayerIndex, localIndex2++, gamer);
Global.localPlayers.Add((LocalPlayer)gamer.Tag);
}
}
Global.menusong.Stop();
Global.actionsong.Play();
Global.gameState = Global.GameState.playingHeatmap;
break;
case 2: //Level 3
Global.levelManager.currentLevel = 3;
Global.levelManager.setupLevel();
int localIndex3 = 1;
if (Global.networkManager.createSession())
{
foreach (LocalNetworkGamer gamer in Global.networkManager.networkSession.LocalGamers)
{
gamer.Tag = new LocalPlayer(Vector3.Zero, gamer.SignedInGamer.PlayerIndex, localIndex3++, gamer);
Global.localPlayers.Add((LocalPlayer)gamer.Tag);
}
}
Global.menusong.Stop();
Global.actionsong.Play();
Global.gameState = Global.GameState.playingHeatmap;
break;
}
break;
#endregion
#region PlayHeatmap
case Global.GameState.playingHeatmap:
//commented music
//Global.menusong.Stop();
//Global.actionsong.Play();
debug = true;
if (!Global.debugMode)
Global.debugMode = true;
foreach (LocalPlayer player in Global.localPlayers)
{
player.update();
//if(player.isJuggernaught == true) then do the bugbot check else do nothing
foreach (BugBot bot in Global.bugBots)
{
if ((bot.Position - player.Position).Length() < BugBot.ATTACK_RADIUS)
{
//shoot a bullet at the player if he is the juggernaught
Vector3 dir = player.Position - bot.Position;
dir.Normalize();
//bot.ShootBullet(dir);
debug = false;
}
}
}
Global.BulletManager.update();
levelManager.update();
// Allows the game to exit
if (Global.input.DetectBackPressedByAnyPlayer())
{
Global.actionsong.Stop();
Global.jetpack.Stop();
Global.networkManager.disposeNetworkSession();
Global.actionsong.Stop();
Global.menusong.Play();
Global.gameState = Global.GameState.Menu;
}
break;
#endregion
#region Playing
case Global.GameState.Playing:
//commented music
//Global.menusong.Stop();
//Global.actionsong.Play();
foreach (LocalPlayer player in Global.localPlayers)
{
player.update();
if (player.score >= Global.Constants.MAX_SCORE)
{
for (int i = 0; i < Global.localPlayers.Count; i++)
{
Global.localPlayers[i].score = 0;
}
Global.actionsong.Stop();
Global.menusong.Play();
Global.gameState = Global.GameState.GameOver;
Global.winningPlayer = player.gamer.Gamertag;
Global.graphics.GraphicsDevice.Viewport = new Viewport(0, 0, Global.viewPort.Width, Global.viewPort.Height);
Global.networkManager.announceWinner(player.gamer);
break;
}
}
foreach (RemotePlayer rPlayer in Global.remotePlayers)
{
rPlayer.update();
}
Global.BulletManager.update();
levelManager.update();
// Allows the game to exit
if (Global.input.DetectBackPressedByAnyPlayer())
{
Global.actionsong.Stop();
Global.menusong.Play();
Global.jetpack.Stop();
Global.networkManager.disposeNetworkSession();
Global.gameState = Global.GameState.Menu;
}
break;
#endregion //Playing
#region SinglePlayerPlaying
case Global.GameState.SinglePlayerPlaying:
timeInSinglePlayer += gameTime.ElapsedGameTime.Milliseconds;
LocalPlayer singlePlayer = Global.localPlayers[0];
singlePlayer.update();
Global.BulletManager.update();
levelManager.update();
if (timeInSinglePlayer > SINGLE_PLAYER_LENGTH)
{
finalScore = Global.localPlayers[0].score;
Global.networkManager.disposeNetworkSession();
Global.actionsong.Stop();
Global.menusong.Play();
Global.gameState = Global.GameState.SinglePlayerGameOver;
}
// Allows the game to exit
if (Global.input.DetectBackPressedByAnyPlayer())
{
Global.networkManager.disposeNetworkSession();
Global.actionsong.Stop();
Global.menusong.Play();
Global.gameState = Global.GameState.Menu;
}
break;
#endregion //SinglePlayerPlaying
#region Paused
case Global.GameState.Paused:
break;
#endregion //Paused
#region GameOver
case Global.GameState.GameOver:
if (Global.input.isAnyFirstPress(Buttons.A))
{
Global.networkManager.disposeNetworkSession();
Global.actionsong.Stop();
Global.menusong.Play();
Global.gameState = Global.GameState.Menu;
}
break;
#endregion //GameOver
#region SinglePlayerGameOver
case Global.GameState.SinglePlayerGameOver:
if (Global.input.isAnyFirstPress(Buttons.A) || Global.input.isAnyFirstPress(Buttons.Start))
{
Global.gameState = Global.GameState.Menu;
}
break;
#endregion
#region NetworkQuit
case Global.GameState.NetworkQuit:
if (Global.input.isAnyFirstPress(Buttons.A) || Global.input.isAnyFirstPress(Buttons.Start))
Global.gameState = Global.GameState.Menu;
break;
#endregion //NetworkQuit
}
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
Global.gameTime = gameTime;
GraphicsDevice.Clear(Color.CornflowerBlue);
switch (Global.gameState)
{
#region Intro
case Global.GameState.Intro:
Global.spriteBatch.Begin();
Global.spriteBatch.Draw(splashTexture, Global.viewPort, Color.White);
Global.spriteBatch.End();
break;
#endregion
#region Menu
case Global.GameState.Menu:
Global.spriteBatch.Begin();
mainMenu.draw();
Global.spriteBatch.End();
break;
#endregion
#region CreateMenu
case Global.GameState.CreateMenu:
Global.spriteBatch.Begin();
createGameMenu.draw();
Global.spriteBatch.End();
break;
#endregion //CreateMenu
#region JoinMenu
case Global.GameState.JoinMenu:
Global.spriteBatch.Begin();
joinGameMenu.draw();
Global.spriteBatch.End();
break;
#endregion //JoinMenu
#region SetupLocalPlayers
case Global.GameState.SetupLocalPlayers:
Global.spriteBatch.Begin();
drawLocalPlayerSetup();
Global.spriteBatch.End();
break;
#endregion //SetupLocalPlayers
#region SetupSinglePlayer
case Global.GameState.SetupSinglePlayer:
Global.spriteBatch.Begin();
drawLocalPlayerSetup();
Global.spriteBatch.End();
break;
#endregion //SetupSinglePlayer
#region LevelPicking:
case Global.GameState.LevelPicking:
Global.spriteBatch.Begin();
levelMenu.draw();
Global.spriteBatch.End();
break;
#endregion //LevelPicking
#region Lobby
case Global.GameState.Lobby:
Global.spriteBatch.Begin();
Global.networkManager.draw();
if (Global.networkManager.currentState == NetworkManager.CurrentState.Running)
{
Global.spriteBatch.Draw(background, Global.viewPort, Color.White);
Vector2 playerTextStarting = new Vector2(Global.viewPort.Left + 30, Global.viewPort.Height / 2 - 30);
Vector2 promptStarting = new Vector2(Global.viewPort.Left + 30, Global.viewPort.Height - 50);
float textOffset = consolas.MeasureString("A").Y + 5;
Global.spriteBatch.DrawString(consolas, "Joined Players:", playerTextStarting, Color.Black);
int off = 1;
foreach (NetworkGamer nGamer in Global.networkManager.networkSession.AllGamers)
{
Global.spriteBatch.DrawString(consolas, nGamer.Gamertag, new Vector2(playerTextStarting.X, playerTextStarting.Y + off++ * textOffset), Color.Black);
}
if (Global.networkManager.networkSession.AllGamers.Count > 1 && Global.networkManager.hostSessionType == NetworkManager.HostSessionType.Host)
{
Global.spriteBatch.DrawString(consolas, "Press A to Start the Game", promptStarting, Color.Black);
}
Global.spriteBatch.DrawString(consolas, "Press B to Return", new Vector2(promptStarting.X, promptStarting.Y + textOffset), Color.Black);
}
Global.spriteBatch.End();
break;
#endregion //Lobby
#region SetupLocalPlayersHeatmap
case Global.GameState.SetupLocalPlayersHeatmap:
Global.spriteBatch.Begin();
drawLocalPlayerSetup();
Global.spriteBatch.End();
break;
#endregion
#region ChooseHeatmap
case Global.GameState.ChooseHeatmap:
Global.spriteBatch.Begin();
levelMenu.draw();
Global.spriteBatch.End();
break;
#endregion
#region PlayHeatmap
case Global.GameState.playingHeatmap:
//3D Drawing Section
resetGraphicsDevice();
foreach (LocalPlayer player in Global.localPlayers)
{
Global.CurrentCamera = player.camera;
levelManager.draw();
foreach (LocalPlayer drawPlayer in Global.localPlayers)
{
drawPlayer.draw();
}
Global.BulletManager.draw();
}
//draw the heatmaps when debug mode is ran.
Global.heatmapKills.draw();
Global.heatmapDeaths.draw();
Global.heatmapUsedJetpack.draw();
//SpriteBatch Drawing Section
Global.spriteBatch.Begin();
if (Global.debugMode)
{
axisReference.Draw(Matrix.Identity, Global.CurrentCamera.view, Global.CurrentCamera.projection);
Global.spriteBatch.DrawString(consolas, "Press ~ to exit debug mode.",
new Vector2(5f, 35f), Color.PaleGreen);
Global.spriteBatch.DrawString(consolas, "Camera Position and View=\n" +
"X:" + Global.CurrentCamera.cameraPos.X.ToString() +
" Y:" + Global.CurrentCamera.cameraPos.Y.ToString() +
" Z:" + Global.CurrentCamera.cameraPos.Z.ToString(),
new Vector2(5f, 53f), Global.debugColor);
Global.spriteBatch.DrawString(consolas,
"Up:" + Global.CurrentCamera.view.Up.ToString() +
"\nLookAt: " + debug.ToString() +
"\nRight: " + Global.CurrentCamera.view.Right.ToString(),
new Vector2(5f, 95f), Global.debugColor);
}
foreach (LocalPlayer drawPlayer in Global.localPlayers)
{
Global.spriteBatch.End();
Global.CurrentCamera = drawPlayer.camera;
Global.spriteBatch.Begin();
drawPlayer.drawHUD();
}
Global.spriteBatch.End();
break;
#endregion //PlayHeatmap
#region Playing
case Global.GameState.Playing:
//3D Drawing Section
resetGraphicsDevice();
foreach (LocalPlayer player in Global.localPlayers)
{
Global.CurrentCamera = player.camera;
levelManager.draw();
foreach (LocalPlayer drawPlayer in Global.localPlayers)
{
drawPlayer.draw();
}
Global.BulletManager.draw();
foreach (RemotePlayer rPlayer in Global.remotePlayers)
{
rPlayer.draw();
}
}
//SpriteBatch Drawing Section
Global.spriteBatch.Begin();
if (Global.debugMode)
{
//draw the heatmaps when debug mode is ran.
Global.heatmapKills.draw();
Global.heatmapDeaths.draw();
Global.heatmapUsedJetpack.draw();
axisReference.Draw(Matrix.Identity, Global.CurrentCamera.view, Global.CurrentCamera.projection);
Global.spriteBatch.DrawString(consolas, "Press ~ to exit debug mode.",
new Vector2(5f, 35f), Color.PaleGreen);
Global.spriteBatch.DrawString(consolas, "Camera Position and View=\n" +
"X:" + Global.CurrentCamera.cameraPos.X.ToString() +
" Y:" + Global.CurrentCamera.cameraPos.Y.ToString() +
" Z:" + Global.CurrentCamera.cameraPos.Z.ToString(),
new Vector2(5f, 53f), Global.debugColor);
Global.spriteBatch.DrawString(consolas,
"Up:" + Global.CurrentCamera.view.Up.ToString() +
"\nLookAt: " + debug.ToString() +
"\nRight: " + Global.CurrentCamera.view.Right.ToString(),
new Vector2(5f, 95f), Global.debugColor);
}
foreach (LocalPlayer drawPlayer in Global.localPlayers)
{
Global.spriteBatch.End();
Global.CurrentCamera = drawPlayer.camera;
Global.spriteBatch.Begin();
drawPlayer.drawHUD();
}
Global.spriteBatch.End();
break;
#endregion
#region SinglePlayerPlaying
case Global.GameState.SinglePlayerPlaying:
//3D Drawing Section
resetGraphicsDevice();
foreach (LocalPlayer player in Global.localPlayers)
{
Global.CurrentCamera = player.camera;
levelManager.draw();
foreach (LocalPlayer drawPlayer in Global.localPlayers)
{
drawPlayer.draw();
}
Global.BulletManager.draw();
foreach (RemotePlayer rPlayer in Global.remotePlayers)
{
rPlayer.draw();
}
}
//SpriteBatch Drawing Section
Global.spriteBatch.Begin();
if (Global.debugMode)
{
//draw the heatmaps when debug mode is ran.
Global.heatmapKills.draw();
Global.heatmapDeaths.draw();
Global.heatmapUsedJetpack.draw();
axisReference.Draw(Matrix.Identity, Global.CurrentCamera.view, Global.CurrentCamera.projection);
Global.spriteBatch.DrawString(consolas, "Press ~ to exit debug mode.",
new Vector2(5f, 35f), Color.PaleGreen);
Global.spriteBatch.DrawString(consolas, "Camera Position and View=\n" +
"X:" + Global.CurrentCamera.cameraPos.X.ToString() +
" Y:" + Global.CurrentCamera.cameraPos.Y.ToString() +
" Z:" + Global.CurrentCamera.cameraPos.Z.ToString(),
new Vector2(5f, 53f), Global.debugColor);
Global.spriteBatch.DrawString(consolas,
"Up:" + Global.CurrentCamera.view.Up.ToString() +
"\nLookAt: " + debug.ToString() +
"\nRight: " + Global.CurrentCamera.view.Right.ToString(),
new Vector2(5f, 95f), Global.debugColor);
}
foreach (LocalPlayer drawPlayer in Global.localPlayers)
{
Global.spriteBatch.End();
Global.CurrentCamera = drawPlayer.camera;
Global.spriteBatch.Begin();
drawPlayer.drawHUD();
}
float time = SINGLE_PLAYER_LENGTH / 1000 - timeInSinglePlayer / 1000;
Vector2 stringMeasure = consolas.MeasureString(time.ToString());
Global.spriteBatch.DrawString(mainMenu.titleFont, time.ToString(), new Vector2(Global.viewPort.Width / 2 - stringMeasure.X / 2, Global.titleSafe.Top + 15), Color.Orange);
Global.spriteBatch.End();
break;
#endregion //SinglePlayerPlaying
#region Paused
case Global.GameState.Paused:
Global.spriteBatch.Begin();
Global.spriteBatch.End();
break;
#endregion
#region GameOver
case Global.GameState.GameOver:
Global.spriteBatch.Begin();
Global.spriteBatch.Draw(mainMenu.background, Global.viewPort, Color.White);
Global.spriteBatch.DrawString(consolas, "Player " + Global.winningPlayer + " Won!", new Vector2(20, Global.viewPort.Height / 2), Color.Black);
Global.spriteBatch.DrawString(consolas, "Press A To Continue", new Vector2(20, Global.viewPort.Height / 2 + 50), Color.Black);
Global.spriteBatch.End();
break;
#endregion
#region SinglePlayerGameOver
case Global.GameState.SinglePlayerGameOver:
Global.spriteBatch.Begin();
Global.spriteBatch.Draw(mainMenu.background, Global.viewPort, Color.White);
Global.spriteBatch.DrawString(consolas, "Your Score: " + finalScore.ToString(), new Vector2(20, Global.viewPort.Height / 2), Color.Black);
Global.spriteBatch.DrawString(consolas, "Press A To Continue", new Vector2(20, Global.viewPort.Height / 2 + 50), Color.Black);
Global.spriteBatch.End();
break;
#endregion
#region NetworkQuit
case Global.GameState.NetworkQuit:
Global.spriteBatch.Begin();
Global.spriteBatch.Draw(mainMenu.background, Global.viewPort, Color.White);
Global.spriteBatch.DrawString(consolas, "Network Session Ended", new Vector2(20, Global.viewPort.Height / 2), Color.Black);
Global.spriteBatch.DrawString(consolas, "Press A To Continue", new Vector2(20, Global.viewPort.Height / 2 + 50), Color.Black);
Global.spriteBatch.End();
break;
#endregion
}
base.Draw(gameTime);
}
protected Rectangle GetTitleSafeArea(float percent)
{
Rectangle retval = new Rectangle(Global.graphics.GraphicsDevice.Viewport.X, Global.graphics.GraphicsDevice.Viewport.Y,
Global.graphics.GraphicsDevice.Viewport.Width, Global.graphics.GraphicsDevice.Viewport.Height);
#if XBOX
float border = (1 - percent) / 2;
retval.X = (int)(border * retval.Width);
retval.Y = (int)(border * retval.Height);
retval.Width = (int)(percent * retval.Width);
retval.Height = (int)(percent * retval.Height);
#endif
return retval;
}
private void setupLocalPlayers()
{
if (Global.input.isAnyFirstPress(Buttons.A) && !Guide.IsVisible)
{
#if XBOX
Guide.ShowSignIn(4, true);
#else
Guide.ShowSignIn(1, true);
#endif
}
else if (SignedInGamer.SignedInGamers.Count > 0 && Global.input.isAnyFirstPress(Buttons.Start))
{
Global.numLocalGamers = (byte)SignedInGamer.SignedInGamers.Count;
if (Global.networkManager.hostSessionType == NetworkManager.HostSessionType.Host)
{
Global.gameState = Global.GameState.CreateMenu;
}
else
{
Global.gameState = Global.GameState.JoinMenu;
}
}
else if (Global.input.isFirstPress(Buttons.B))
{
Global.gameState = Global.GameState.Menu;
}
}
private void setupLocalPlayersHeatmap()
{
if (Global.input.isAnyFirstPress(Buttons.A) && !Guide.IsVisible)
{
Guide.ShowSignIn(1, true);
}
else if (SignedInGamer.SignedInGamers.Count > 0 && Global.input.isAnyFirstPress(Buttons.Start))
{
Global.numLocalGamers = (byte)SignedInGamer.SignedInGamers.Count;
Global.gameState = Global.GameState.ChooseHeatmap;
}
else if (Global.input.isFirstPress(Buttons.B))
{
Global.gameState = Global.GameState.Menu;
}
}
private void setupSinglePlayer()
{
if (Global.input.isAnyFirstPress(Buttons.A) && !Guide.IsVisible)
{
Guide.ShowSignIn(1, true);
}
else if (SignedInGamer.SignedInGamers.Count > 0 && Global.input.isAnyFirstPress(Buttons.Start))
{
Global.numLocalGamers = (byte)SignedInGamer.SignedInGamers.Count;
Global.networkManager.sessionType = NetworkSessionType.Local;
if (Global.networkManager.createSession())
{
timeInSinglePlayer = 0;
Global.levelManager.currentLevel = 1;
Global.levelManager.setupLevel();
LocalNetworkGamer gamer = Global.networkManager.networkSession.LocalGamers[0];
gamer.Tag = new LocalPlayer(Vector3.Zero, PlayerIndex.One, 1, gamer);
Global.localPlayers.Add((LocalPlayer)gamer.Tag);
Global.localPlayers[0].setAsJuggernaut();
Global.menusong.Stop();
Global.actionsong.Play();
Global.gameState = Global.GameState.SinglePlayerPlaying;
}
}
else if (Global.input.isFirstPress(Buttons.B))
{
Global.gameState = Global.GameState.Menu;
}
}
private void drawLocalPlayerSetup()
{
Global.spriteBatch.Draw(background, Global.viewPort, Color.White);
Global.spriteBatch.DrawString(mainMenu.titleFont, "Juggernaut", mainMenu.titlePosition, Color.Black);
Vector2 playerTextStarting = new Vector2(Global.viewPort.Left + 30, Global.viewPort.Height / 2 - 30);
Vector2 promptStarting = new Vector2(Global.viewPort.Left + 30, Global.viewPort.Height - 50);
float textOffset = consolas.MeasureString("A").Y + 5;
Global.spriteBatch.DrawString(consolas, "Signed In Players:", playerTextStarting, Color.Black);
int off = 1;
foreach (SignedInGamer gamer in SignedInGamer.SignedInGamers)
{
Global.spriteBatch.DrawString(consolas, gamer.Gamertag, new Vector2(playerTextStarting.X, playerTextStarting.Y + off++ * textOffset), Color.Black);
}
off += 2;
Global.spriteBatch.DrawString(consolas, "Press A to Sign In", new Vector2(playerTextStarting.X, playerTextStarting.Y + off++ * textOffset), Color.Black);
if (SignedInGamer.SignedInGamers.Count > 0)
{
Global.spriteBatch.DrawString(consolas, "Press Start to Continue", new Vector2(playerTextStarting.X, playerTextStarting.Y + off * textOffset), Color.Black);
}
}
private void resetGraphicsDevice()
{
Global.graphics.GraphicsDevice.BlendState = BlendState.Opaque;
Global.graphics.GraphicsDevice.DepthStencilState = DepthStencilState.Default;
Global.graphics.GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap;
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace ApplicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// SecurityRulesOperations operations.
/// </summary>
public partial interface ISecurityRulesOperations
{
/// <summary>
/// Deletes the specified network security rule.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string securityRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get the specified network security rule.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<SecurityRule>> GetWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string securityRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a security rule in the specified network
/// security group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='securityRuleParameters'>
/// Parameters supplied to the create or update network security rule
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<SecurityRule>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string securityRuleName, SecurityRule securityRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all security rules in a network security group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<SecurityRule>>> ListWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified network security rule.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string securityRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a security rule in the specified network
/// security group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='securityRuleParameters'>
/// Parameters supplied to the create or update network security rule
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<SecurityRule>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string securityRuleName, SecurityRule securityRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all security rules in a network security group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<SecurityRule>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using System;
using System.Threading.Tasks;
using IdokladSdk.ApiFilters;
using IdokladSdk.ApiModels;
using IdokladSdk.ApiModels.BaseModels;
using IdokladSdk.Enums;
namespace IdokladSdk.Clients
{
/// <summary>
/// Methods for issued invoice resources.
/// </summary>
public partial class IssuedInvoiceClient : BaseClient
{
/// <summary>
/// GET api/IssuedInvoices/Default
/// Method returns empty invoice with default values. Returned resource is suitable for new invoice creation.
/// </summary>
public async Task<IssuedInvoiceCreate> DefaultAsync()
{
return await GetAsync<IssuedInvoiceCreate>(ResourceUrl + "/Default");
}
/// <summary>
/// PUT api/IssuedInvoices/{id}/FullyPay?dateOfPayment={dateOfPayment}
/// Method sets invoice as paid.
/// </summary>
public async Task<bool> FullyPayAsync(int invoiceId, DateTime paid)
{
return await PutAsync<bool>(ResourceUrl + "/" + invoiceId + "/FullyPay" + "?dateOfPayment=" + paid.ToString(ApiContextConfiguration.DateFormat));
}
/// <summary>
/// PUT api/IssuedInvoices/{id}/FullyUnpay
/// Method sets invoice as unpaid.
/// </summary>
public async Task<bool> FullyUnpayAsync(int invoiceId)
{
return await PutAsync<bool>(ResourceUrl + "/" + invoiceId + "/FullyUnpay");
}
/// <summary>
/// GET api/IssuedInvoices/{id}/GetCashVoucherPdf
/// Returns Pdf file with Cash voucher report for the invoice. File is Base64 encoded and is returned as string.
/// </summary>
public async Task<string> CashVoucherPdfAsync(int invoiceId)
{
return await GetAsync<string>(ResourceUrl + "/" + invoiceId + "/GetCashVoucherPdf");
}
/// <summary>
/// GET api/IssuedInvoices/{id}/GetCashVoucherPdfCompressed
/// Returns zipped Pdf file with Cash voucher report for the invoice. File is Base64 encoded and is returned as string.
/// </summary>
public async Task<string> CashVoucherPdfCompressedAsync(int invoiceId)
{
return await GetAsync<string>(ResourceUrl + "/" + invoiceId + "/GetCashVoucherPdfCompressed");
}
/// <summary>
/// GET api/IssuedInvoices/Expand
/// Returns Issued invoice list with related entities such as contact information etc.
/// </summary>
public async Task<RowsResultWrapper<IssuedInvoiceExpand>> IssuedInvoicesExpandAsync(ApiFilter filter = null)
{
return await GetAsync<RowsResultWrapper<IssuedInvoiceExpand>>(ResourceUrl + "/Expand", filter);
}
/// <summary>
/// GET api/IssuedInvoices/{id}/Expand
/// Returns Issued invoice with related entities by Id.
/// </summary>
public async Task<IssuedInvoiceExpand> IssuedInvoiceExpandAsync(int invoiceId)
{
return await GetAsync<IssuedInvoiceExpand>(ResourceUrl + "/" + invoiceId + "/Expand");
}
/// <summary>
/// GET api/IssuedInvoices/{id}/GetPdf
/// Returns Pdf file with Issued Invoic. File is Base64 encoded and is returned as string.
/// </summary>
public async Task<string> IssuedInvoicePdfAsync(int invoiceId)
{
return await GetAsync<string>(ResourceUrl + "/" + invoiceId + "/GetPdf");
}
/// <summary>
/// GET api/IssuedInvoices/{id}/GetPdfCompressed
/// Returns zipped Pdf file with Issued Invoice report. File is Base64 encoded and is returned as string.
/// </summary>
public async Task<string> IssuedInvoicePdfCompressedAsync(int invoiceId)
{
return await GetAsync<string>(ResourceUrl + "/" + invoiceId + "/GetPdfCompressed");
}
/// <summary>
/// GET api/IssuedInvoices/{contactId}/IssuedInvoices
/// Returns invoice list for specific contact.
/// </summary>
public async Task<RowsResultWrapper<IssuedInvoice>> IssuedInvoicesByContactAsync(int contactId, ApiFilter filter = null)
{
return await GetAsync<RowsResultWrapper<IssuedInvoice>>(ResourceUrl + "/" + contactId + "/IssuedInvoices", filter);
}
/// <summary>
/// GET api/IssuedInvoices/{id}/MyDocumentAddress
/// Contact information of the supplier for invoice.
/// </summary>
public async Task<DocumentAddress> MyDocumentAddressAsync(int invoiceId)
{
return await GetAsync<DocumentAddress>(ResourceUrl + "/" + invoiceId + "/MyDocumentAddress");
}
/// <summary>
/// GET api/IssuedInvoices/{id}/PurchaserDocumentAddress
/// Contact information of the purchaser for invoice.
/// </summary>
public async Task<DocumentAddress> PurchaserDocumentAddressAsync(int invoiceId)
{
return await GetAsync<DocumentAddress>(ResourceUrl + "/" + invoiceId + "/PurchaserDocumentAddress");
}
/// <summary>
/// POST api/IssuedInvoices/Recount
/// Method recounts summaries of the invoice model for creation. Invoice should contains only items with ItemTypeNormal.
/// </summary>
public async Task<IssuedInvoice> RecountAsync(IssuedInvoiceCreate invoice)
{
return await PostAsync<IssuedInvoice, IssuedInvoiceCreate>(ResourceUrl + "/Recount", invoice);
}
/// <summary>
/// POST api/IssuedInvoices/{id}/Recount
/// Method recounts summaries of the invoice model for update. Invoice should contains only items with ItemTypeNormal.
/// </summary>
public async Task<IssuedInvoice> RecountAsync(int invoiceId, IssuedInvoiceUpdate invoice)
{
return await PostAsync<IssuedInvoice, IssuedInvoiceUpdate>(ResourceUrl + "/" + invoiceId + "/Recount", invoice);
}
/// <summary>
/// PUT api/IssuedInvoices/{id}/MyDocumentAddress
/// Method Updates contact informations of the supplier.
/// </summary>
public async Task<DocumentAddress> UpdateMyDocumentAddressAsync(int invoiceId, DocumentAddress address)
{
return await PutAsync<DocumentAddress, DocumentAddress>(ResourceUrl + "/" + invoiceId + "/MyDocumentAddress", address);
}
/// <summary>
/// PUT api/IssuedInvoices/{id}/PurchaserDocumentAddress
/// Method Updates contact informations of the purchaser.
/// </summary>
public async Task<DocumentAddress> UpdatePurchaserDocumentAddressAsync(int invoiceId, DocumentAddress address)
{
return await PutAsync<DocumentAddress, DocumentAddress>(ResourceUrl + "/" + invoiceId + "/PurchaserDocumentAddress", address);
}
/// <summary>
/// PUT api/IssuedInvoices/{id}/SendMailToPurchaser
/// Method sends email with issued invoice to the purchaser.
/// </summary>
public async Task<bool> SendMailToPurchaserAsync(int invoiceId)
{
return await PutAsync<bool>(ResourceUrl + "/" + invoiceId + "/SendMailToPurchaser");
}
/// <summary>
/// PUT api/IssuedInvoices/{id}/Exported/{value}
/// Method updates Exported property of the invoice.
/// </summary>
public async Task<bool> ExportedAsync(int invoiceId, ExportedStateEnum state)
{
return await PutAsync<bool>(ResourceUrl + "/" + invoiceId + "/Exported" + "/" + (int)state);
}
/// <summary>
/// DELETE api/IssuedInvoices/{id}
/// Deletes issued invoice by Id.
/// </summary>
public async Task<bool> DeleteAsync(int invoiceId)
{
return await DeleteAsync(ResourceUrl + "/" + invoiceId);
}
/// <summary>
/// GET api/IssuedInvoices
/// Returns list of issued invoices. Filters are optional.
/// </summary>
public async Task<RowsResultWrapper<IssuedInvoice>> IssuedInvoicesAsync(ApiFilter filter = null)
{
return await GetAsync<RowsResultWrapper<IssuedInvoice>>(ResourceUrl, filter);
}
/// <summary>
/// GET api/IssuedInvoices/{id}
/// Returns information about issued invoice including summaries.
/// </summary>
public async Task<IssuedInvoice> IssuedInvoiceAsync(int invoiceId)
{
return await GetAsync<IssuedInvoice>(ResourceUrl + "/" + invoiceId);
}
/// <summary>
/// POST api/IssuedInvoices
/// Create new issued invoice. Invoice should contains only items with ItemTypeNormal.
/// </summary>
public async Task<IssuedInvoice> CreateAsync(IssuedInvoiceCreate invoice)
{
return await PostAsync<IssuedInvoice, IssuedInvoiceCreate>(ResourceUrl, invoice);
}
/// <summary>
/// PUT api/IssuedInvoices/{id}
/// Method updates issued invoice by Id. Also possible to update single preperties of invoice. Invoice should contains only items with ItemTypeNormal.
/// </summary>
public async Task<IssuedInvoice> UpdateAsync(int invoiceId, IssuedInvoiceUpdate invoice)
{
return await PutAsync<IssuedInvoice, IssuedInvoiceUpdate>(ResourceUrl + "/" + invoiceId, invoice);
}
/// <summary>
/// PUT api/IssuedInvoices/SetAttachment/{invoicdId}
/// Sets an attachment to the given issued invoice. If an attachment already exists, it will be overwritten.
/// </summary>
public async Task<bool> SetAttachmentAsync(int invoiceId)
{
return await PutAsync<bool>(ResourceUrl + "/" + "SetAttachment" + "/" + invoiceId);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Buffers;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core.Pipeline;
using Azure.Storage.Shared;
namespace Azure.Storage
{
internal class PartitionedUploader<TServiceSpecificArgs, TCompleteUploadReturn>
{
#region Definitions
// delegte for getting a partition from a stream based on the selected data management stragegy
private delegate Task<SlicedStream> GetNextStreamPartition(
Stream stream,
long minCount,
long maxCount,
long absolutePosition,
bool async,
CancellationToken cancellationToken);
// injected behaviors for services to use partitioned uploads
public delegate DiagnosticScope CreateScope(string operationName);
public delegate Task InitializeDestinationInternal(TServiceSpecificArgs args, bool async, CancellationToken cancellationToken);
public delegate Task<Response<TCompleteUploadReturn>> SingleUploadInternal(
Stream contentStream,
TServiceSpecificArgs args,
IProgress<long> progressHandler,
string operationName,
bool async,
CancellationToken cancellationToken);
public delegate Task UploadPartitionInternal(Stream contentStream,
long offset,
TServiceSpecificArgs args,
IProgress<long> progressHandler,
bool async,
CancellationToken cancellationToken);
public delegate Task<Response<TCompleteUploadReturn>> CommitPartitionedUploadInternal(
List<(long Offset, long Size)> partitions,
TServiceSpecificArgs args,
bool async,
CancellationToken cancellationToken);
public struct Behaviors
{
public InitializeDestinationInternal InitializeDestination { get; set; }
public SingleUploadInternal SingleUpload { get; set; }
public UploadPartitionInternal UploadPartition { get; set; }
public CommitPartitionedUploadInternal CommitPartitionedUpload { get; set; }
public CreateScope Scope { get; set; }
}
public static readonly InitializeDestinationInternal InitializeNoOp = (args, async, cancellationToken) => Task.CompletedTask;
#endregion
private readonly InitializeDestinationInternal _initializeDestinationInternal;
private readonly SingleUploadInternal _singleUploadInternal;
private readonly UploadPartitionInternal _uploadPartitionInternal;
private readonly CommitPartitionedUploadInternal _commitPartitionedUploadInternal;
private readonly CreateScope _createScope;
/// <summary>
/// The maximum number of simultaneous workers.
/// </summary>
private readonly int _maxWorkerCount;
/// <summary>
/// A pool of memory we use to partition the stream into blocks.
/// </summary>
private readonly ArrayPool<byte> _arrayPool;
/// <summary>
/// The size we use to determine whether to upload as a one-off request or
/// a partitioned/committed upload
/// </summary>
private readonly long _singleUploadThreshold;
/// <summary>
/// The size of each staged block. If null, we'll change between 4MB
/// and 8MB depending on the size of the content.
/// </summary>
private readonly long? _blockSize;
/// <summary>
/// The name of the calling operaiton.
/// </summary>
private readonly string _operationName;
public PartitionedUploader(
Behaviors behaviors,
StorageTransferOptions transferOptions,
ArrayPool<byte> arrayPool = null,
string operationName = null)
{
// initialize isn't required for all services and can use a no-op; rest are required
_initializeDestinationInternal = behaviors.InitializeDestination ?? InitializeNoOp;
_singleUploadInternal = behaviors.SingleUpload
?? throw Errors.ArgumentNull(nameof(behaviors.SingleUpload));
_uploadPartitionInternal = behaviors.UploadPartition
?? throw Errors.ArgumentNull(nameof(behaviors.UploadPartition));
_commitPartitionedUploadInternal = behaviors.CommitPartitionedUpload
?? throw Errors.ArgumentNull(nameof(behaviors.CommitPartitionedUpload));
_createScope = behaviors.Scope
?? throw Errors.ArgumentNull(nameof(behaviors.Scope));
_arrayPool = arrayPool ?? ArrayPool<byte>.Shared;
// Set _maxWorkerCount
if (transferOptions.MaximumConcurrency.HasValue
&& transferOptions.MaximumConcurrency > 0)
{
_maxWorkerCount = transferOptions.MaximumConcurrency.Value;
}
else
{
_maxWorkerCount = Constants.Blob.Block.DefaultConcurrentTransfersCount;
}
// Set _singleUploadThreshold
if (transferOptions.InitialTransferSize.HasValue
&& transferOptions.InitialTransferSize.Value > 0)
{
_singleUploadThreshold = Math.Min(transferOptions.InitialTransferSize.Value, Constants.Blob.Block.MaxUploadBytes);
}
else
{
_singleUploadThreshold = Constants.Blob.Block.MaxUploadBytes;
}
// Set _blockSize
if (transferOptions.MaximumTransferSize.HasValue
&& transferOptions.MaximumTransferSize > 0)
{
_blockSize = Math.Min(
Constants.Blob.Block.MaxStageBytes,
transferOptions.MaximumTransferSize.Value);
}
_operationName = operationName;
}
public async Task<Response<TCompleteUploadReturn>> UploadInternal(
Stream content,
TServiceSpecificArgs args,
IProgress<long> progressHandler,
bool async,
CancellationToken cancellationToken = default)
{
if (content == default)
{
throw Errors.ArgumentNull(nameof(content));
}
Errors.VerifyStreamPosition(content, nameof(content));
if (content.CanSeek && content.Position > 0)
{
content = WindowStream.GetWindow(content, content.Length - content.Position, content.Position);
}
await _initializeDestinationInternal(args, async, cancellationToken).ConfigureAwait(false);
// some strategies are unavailable if we don't know the stream length, and some can still work
// we may introduce separately provided stream lengths in the future for unseekable streams with
// an expected length
long? length = GetLengthOrDefault(content);
// If we know the length and it's small enough
if (length < _singleUploadThreshold)
{
// Upload it in a single request
return await _singleUploadInternal(
content,
args,
progressHandler,
_operationName,
async,
cancellationToken)
.ConfigureAwait(false);
}
// If the caller provided an explicit block size, we'll use it.
// Otherwise we'll adjust dynamically based on the size of the
// content.
long blockSize = _blockSize != null
? _blockSize.Value
: length < Constants.LargeUploadThreshold ?
Constants.DefaultBufferSize :
Constants.LargeBufferSize;
// Otherwise stage individual blocks
/* We only support parallel upload in an async context to avoid issues in our overall sync story.
* We're branching on both async and max worker count, where 3 combinations lead to
* UploadInSequenceInternal and 1 combination leads to UploadInParallelAsync. We are guaranteed
* to be in an async context when we call UploadInParallelAsync, even though the analyzer can't
* detext this, and we properly pass in the async context in the else case when we haven't
* explicitly checked.
*/
#pragma warning disable AZC0109 // Misuse of 'async' parameter.
#pragma warning disable AZC0110 // DO NOT use await keyword in possibly synchronous scope.
if (async && _maxWorkerCount > 1)
{
return await UploadInParallelAsync(
content,
length,
blockSize,
args,
progressHandler,
cancellationToken)
.ConfigureAwait(false);
}
#pragma warning restore AZC0110 // DO NOT use await keyword in possibly synchronous scope.
#pragma warning restore AZC0109 // Misuse of 'async' parameter.
else
{
return await UploadInSequenceInternal(
content,
length,
blockSize,
args,
progressHandler,
async: async,
cancellationToken).ConfigureAwait(false);
}
}
private async Task<Response<TCompleteUploadReturn>> UploadInSequenceInternal(
Stream content,
long? contentLength,
long partitionSize,
TServiceSpecificArgs args,
IProgress<long> progressHandler,
bool async,
CancellationToken cancellationToken)
{
// Wrap the staging and commit calls in an Upload span for
// distributed tracing
DiagnosticScope scope = _createScope(_operationName);
try
{
scope.Start();
// Wrap progressHandler in a AggregatingProgressIncrementer to prevent
// progress from being reset with each stage blob operation.
if (progressHandler != null)
{
progressHandler = new AggregatingProgressIncrementer(progressHandler);
}
// The list tracking blocks IDs we're going to commit
List<(long Offset, long Size)> partitions = new List<(long, long)>();
// Streamed partitions only work if we can seek the stream; we need retries on individual uploads.
GetNextStreamPartition partitionGetter = content.CanSeek
? (GetNextStreamPartition)GetStreamedPartitionInternal
: /* redundant cast */GetBufferedPartitionInternal;
// Partition the stream into individual blocks and stage them
if (async)
{
await foreach (SlicedStream block in GetPartitionsAsync(
content,
contentLength,
partitionSize,
partitionGetter,
async: true,
cancellationToken).ConfigureAwait(false))
{
await StagePartitionAndDisposeInternal(
block,
block.AbsolutePosition,
args,
progressHandler,
async: true,
cancellationToken).ConfigureAwait(false);
partitions.Add((block.AbsolutePosition, block.Length));
}
}
else
{
foreach (SlicedStream block in GetPartitionsAsync(
content,
contentLength,
partitionSize,
partitionGetter,
async: false,
cancellationToken).EnsureSyncEnumerable())
{
StagePartitionAndDisposeInternal(
block,
block.AbsolutePosition,
args,
progressHandler,
async: false,
cancellationToken).EnsureCompleted();
partitions.Add((block.AbsolutePosition, block.Length));
}
}
// Commit the block list after everything has been staged to
// complete the upload
return await _commitPartitionedUploadInternal(
partitions,
args,
async,
cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
private async Task<Response<TCompleteUploadReturn>> UploadInParallelAsync(
Stream content,
long? contentLength,
long blockSize,
TServiceSpecificArgs args,
IProgress<long> progressHandler,
CancellationToken cancellationToken)
{
// Wrap the staging and commit calls in an Upload span for
// distributed tracing
DiagnosticScope scope = _createScope(_operationName);
try
{
scope.Start();
// Wrap progressHandler in a AggregatingProgressIncrementer to prevent
// progress from being reset with each stage blob operation.
if (progressHandler != null)
{
progressHandler = new AggregatingProgressIncrementer(progressHandler);
}
// The list tracking blocks IDs we're going to commit
List<(long Offset, long Size)> partitions = new List<(long, long)>();
// A list of tasks that are currently executing which will
// always be smaller than _maxWorkerCount
List<Task> runningTasks = new List<Task>();
// Partition the stream into individual blocks
await foreach (SlicedStream block in GetPartitionsAsync(
content,
contentLength,
blockSize,
GetBufferedPartitionInternal, // we always buffer for upload in parallel from stream
async: true,
cancellationToken).ConfigureAwait(false))
{
/* We need to do this first! Length is calculated on the fly based on stream buffer
* contents; We need to record the partition data first before consuming the stream
* asynchronously. */
partitions.Add((block.AbsolutePosition, block.Length));
// Start staging the next block (but don't await the Task!)
Task task = StagePartitionAndDisposeInternal(
block,
block.AbsolutePosition,
args,
progressHandler,
async: true,
cancellationToken);
// Add the block to our task and commit lists
runningTasks.Add(task);
// If we run out of workers
if (runningTasks.Count >= _maxWorkerCount)
{
// Wait for at least one of them to finish
await Task.WhenAny(runningTasks).ConfigureAwait(false);
// Clear any completed blocks from the task list
for (int i = 0; i < runningTasks.Count; i++)
{
Task runningTask = runningTasks[i];
if (!runningTask.IsCompleted)
{
continue;
}
await runningTask.ConfigureAwait(false);
runningTasks.RemoveAt(i);
i--;
}
}
}
// Wait for all the remaining blocks to finish staging and then
// commit the block list to complete the upload
await Task.WhenAll(runningTasks).ConfigureAwait(false);
// Calling internal method for easier mocking in PartitionedUploaderTests
return await _commitPartitionedUploadInternal(
partitions,
args,
async: true,
cancellationToken)
.ConfigureAwait(false);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
/// <summary>
/// Wraps both the async method and dispose call in one task.
/// </summary>
private async Task StagePartitionAndDisposeInternal(
SlicedStream partition,
long offset,
TServiceSpecificArgs args,
IProgress<long> progressHandler,
bool async,
CancellationToken cancellationToken)
{
try
{
await _uploadPartitionInternal(
partition,
offset,
args,
progressHandler,
async,
cancellationToken)
.ConfigureAwait(false);
}
finally
{
// Return the memory used by the block to our ArrayPool as soon
// as we've staged it
partition.Dispose();
}
}
/// <summary>
/// Some streams will throw if you try to access their length so we wrap
/// the check in a TryGet helper.
/// </summary>
private static long? GetLengthOrDefault(Stream content)
{
try
{
if (content.CanSeek)
{
return content.Length - content.Position;
}
}
catch (NotSupportedException)
{
}
return default;
}
#region Stream Splitters
/// <summary>
/// Partition a stream into a series of blocks buffered as needed by an array pool.
/// </summary>
private static async IAsyncEnumerable<SlicedStream> GetPartitionsAsync(
Stream stream,
long? streamLength,
long blockSize,
GetNextStreamPartition getNextPartition,
bool async,
[EnumeratorCancellation] CancellationToken cancellationToken)
{
// The minimum amount of data we'll accept from a stream before
// splitting another block. Code that sets `blockSize` will always
// set it to a positive number. Min() only avoids edge case where
// user sets their block size to 1.
long acceptableBlockSize = Math.Max(1, blockSize / 2);
// if we know the data length, assert boundaries before spending resources uploading beyond service capabilities
if (streamLength.HasValue)
{
// service has a max block count per blob
// block size * block count limit = max data length to upload
// if stream length is longer than specified max block size allows, can't upload
long minRequiredBlockSize = (long)Math.Ceiling((double)streamLength.Value / Constants.Blob.Block.MaxBlocks);
if (blockSize < minRequiredBlockSize)
{
throw Errors.InsufficientStorageTransferOptions(streamLength.Value, blockSize, minRequiredBlockSize);
}
// bring min up to our min required by the service
acceptableBlockSize = Math.Max(acceptableBlockSize, minRequiredBlockSize);
}
long read;
long absolutePosition = 0;
do
{
SlicedStream partition = await getNextPartition(
stream,
acceptableBlockSize,
blockSize,
absolutePosition,
async,
cancellationToken).ConfigureAwait(false);
read = partition.Length;
absolutePosition += read;
// If we read anything, turn it into a StreamPartition and
// return it for staging
if (partition.Length != 0)
{
// The StreamParitition is disposable and it'll be the
// user's responsibility to return the bytes used to our
// ArrayPool
yield return partition;
}
// Continue reading blocks until we've exhausted the stream
} while (read != 0);
}
/// <summary>
/// Gets a partition from the current location of the given stream.
///
/// This partition is buffered and it is safe to get many before using any of them.
/// </summary>
/// <param name="stream">
/// Stream to buffer a partition from.
/// </param>
/// <param name="minCount">
/// Minimum amount of data to wait on before finalizing buffer.
/// </param>
/// <param name="maxCount">
/// Max amount of data to buffer before cutting off for the next.
/// </param>
/// <param name="absolutePosition">
/// Offset of this stream relative to the large stream.
/// </param>
/// <param name="async">
/// Whether to buffer this partition asynchronously.
/// </param>
/// <param name="cancellationToken">
/// Cancellation token.
/// </param>
/// <returns>
/// Task containing the buffered stream partition.
/// </returns>
private async Task<SlicedStream> GetBufferedPartitionInternal(
Stream stream,
long minCount,
long maxCount,
long absolutePosition,
bool async,
CancellationToken cancellationToken)
=> await PooledMemoryStream.BufferStreamPartitionInternal(
stream,
minCount,
maxCount,
absolutePosition,
_arrayPool,
maxArrayPoolRentalSize: default,
async,
cancellationToken).ConfigureAwait(false);
/// <summary>
/// Gets a partition from the current location of the given stream.
///
/// This partition is a facade over the existing stream, and the
/// previous partition should be consumed before using the next.
/// </summary>
/// <param name="stream">
/// Stream to wrap.
/// </param>
/// <param name="minCount">
/// Unused, but part of <see cref="GetNextStreamPartition"/> definition.
/// </param>
/// <param name="maxCount">
/// Length of this facade stream.
/// </param>
/// <param name="absolutePosition">
/// Offset of this stream relative to the large stream.
/// </param>
/// <param name="async">
/// Unused, but part of <see cref="GetNextStreamPartition"/> definition.
/// </param>
/// <param name="cancellationToken"></param>
/// <returns>
/// Task containing the stream facade.
/// </returns>
private static Task<SlicedStream> GetStreamedPartitionInternal(
Stream stream,
long minCount,
long maxCount,
long absolutePosition,
bool async,
CancellationToken cancellationToken)
=> Task.FromResult((SlicedStream)WindowStream.GetWindow(stream, maxCount, absolutePosition));
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using Volte.Data.Dapper;
namespace Volte.Data.Dapper
{
public class Condition {
const string ZFILE_NAME = "Condition";
internal Condition()
{
_Parameters = new List<Criteria>();
_Conditions = new List<Condition>();
_BooleanOperator = " AND ";
}
internal Condition(string cBooleanOperator)
{
_Parameters = new List<Criteria>();
_Conditions = new List<Condition>();
_BooleanOperator = cBooleanOperator;
}
public void Equals(string _Name, object _Value)
{
AddCondition(_Name, CriteriaOperator.Equals, _Value);
}
public void EqualsField(string _Name, string _Name2)
{
AddCondition(_Name, CriteriaOperator.Equals, _Name2, true);
}
public void NotEquals(string _Name, object _Value)
{
AddCondition(_Name, CriteriaOperator.NotEquals, _Value);
}
public void NotEqualsField(string _Name, string _Name2)
{
AddCondition(_Name, CriteriaOperator.NotEquals, _Name2, true);
}
public void GreaterThan(string _Name, object _Value)
{
AddCondition(_Name, CriteriaOperator.GreaterThan, _Value);
}
public void GreaterThanField(string _Name, string _Name2)
{
AddCondition(_Name, CriteriaOperator.GreaterThanOrEquals, _Name2, true);
}
public void GreaterThanOrEquals(string _Name, object _Value)
{
AddCondition(_Name, CriteriaOperator.GreaterThanOrEquals, _Value);
}
public void GreaterThanOrEqualsField(string _Name, string _Name2)
{
AddCondition(_Name, CriteriaOperator.GreaterThanOrEquals, _Name2, true);
}
public void In(string _Name, object[] list)
{
if ((list == null) || (list.Length == 0)) {
throw new DapperException("??t?Xlist??t???0?");
}
AddCondition(_Name, CriteriaOperator.In, list);
}
public void In(string _Name, string XString)
{
this.In(_Name, XString.Split((new char[3] { ';', ',', '|' })));
}
public void LessThan(string _Name, object _Value)
{
AddCondition(_Name, CriteriaOperator.LessThan, _Value);
}
public void LessThanField(string _Name, string _Name2)
{
AddCondition(_Name, CriteriaOperator.LessThan, _Name2, true);
}
public void LessThanOrEquals(string _Name, object _Value)
{
AddCondition(_Name, CriteriaOperator.LessThanOrEquals, _Value);
}
public void LessThanOrEqualsField(string _Name, string _Name2)
{
AddCondition(_Name, CriteriaOperator.LessThanOrEquals, _Name2, true);
}
public void Like(string _Name, string _Value)
{
_Value = "%" + _Value + "%";
AddCondition(_Name, CriteriaOperator.Like, _Value);
}
public void Expression(string _Name, string cValue)
{
if (_Name.IndexOf('.') > 0) {
string[] s = _Name.Split(new char[] { '.' });
_Name = s[1];
}
if (cValue == null) {
cValue = "";
}
if (!string.IsNullOrEmpty(cValue)) {
string cExp = cValue.Substring(0, 1);
if (cExp == ">" || cExp == "<" || cExp == "=") {
if (cValue.Substring(0, 2) == ">=") {
cValue = cValue.Replace(">=", "");
AddCondition(_Name, CriteriaOperator.GreaterThanOrEquals, cValue);
} else if (cValue.Substring(0, 2) == "<=") {
cValue = cValue.Replace("<=", "");
AddCondition(_Name, CriteriaOperator.LessThanOrEquals, cValue);
} else if (cValue.Substring(0, 2) == "<>") {
cValue = cValue.Replace("<>", "");
AddCondition(_Name, CriteriaOperator.NotEquals, cValue);
} else if (cValue.Substring(0, 1) == ">") {
cValue = cValue.Replace(">", "");
AddCondition(_Name, CriteriaOperator.GreaterThan, cValue);
} else if (cValue.Substring(0, 1) == "<") {
cValue = cValue.Replace("<", "");
AddCondition(_Name, CriteriaOperator.LessThan, cValue);
} else {
cValue = cValue.Replace("=", "");
AddCondition(_Name, CriteriaOperator.Equals, cValue);
}
} else if (cValue.IndexOf('*') >= 0) {
AddCondition(_Name, CriteriaOperator.Like, cValue.Replace("*", "%"));
} else {
AddCondition(_Name, CriteriaOperator.Like, cValue + "%");
}
}
}
public void Prefix(string _Name, string _Value)
{
_Value = _Value + "%";
AddCondition(_Name, CriteriaOperator.Like, _Value);
}
public void Suffix(string _Name, string _Value)
{
_Value = "%" + _Value;
AddCondition(_Name, CriteriaOperator.Like, _Value);
}
public void NotIn(string _Name, object[] list)
{
if ((list == null) || (list.Length == 0)) {
throw new DapperException("???t??list???????0?");
}
AddCondition(_Name, CriteriaOperator.NotIn, list);
}
public void NotLike(string _Name, string _Value)
{
_Value = "%" + _Value + "%";
AddCondition(_Name, CriteriaOperator.NotLike, _Value);
}
public void NotPrefix(string _Name, string _Value)
{
_Value = _Value + "%";
AddCondition(_Name, CriteriaOperator.NotLike, _Value);
}
public void NotSuffix(string _Name, string _Value)
{
_Value = "%" + _Value;
AddCondition(_Name, CriteriaOperator.NotLike, _Value);
}
public void Where(string _Value)
{
Criteria criteria1 = new Criteria(CriteriaOperator.Where , "" , _Value);
_Parameters.Add(criteria1);
}
private void AddCondition(string _Name, CriteriaOperator _Operator, object _Value)
{
Criteria criteria1 = new Criteria(_Operator, _Name, _Value);
_Parameters.Add(criteria1);
}
private void AddCondition(string cName, CriteriaOperator _Operator, string cValue, bool field)
{
Criteria criteria1 = new Criteria(_Operator, cName, cValue, true);
_Parameters.Add(criteria1);
}
public void Clear()
{
_Parameters.Clear();
}
public Condition NewCondition()
{
return this.NewCondition(" OR ");
}
public Condition NewCondition(string BooleanOperator)
{
Condition group1 = new Condition(BooleanOperator);
_Conditions.Add(group1);
return group1;
}
internal string BooleanOperator { get { return _BooleanOperator; } }
internal List<Criteria> Parameters { get { return _Parameters; } }
internal List<Condition> Conditions { get { return _Conditions; } }
private string _BooleanOperator;
private List<Criteria> _Parameters = new List<Criteria>();
private List<Condition> _Conditions = new List<Condition>();
}
}
| |
#if (UNITY_WINRT || UNITY_WP_8_1) && !UNITY_EDITOR && !UNITY_WP8
#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 PlayFab.Json.Utilities;
using System.IO;
using System.Globalization;
namespace PlayFab.Json.Linq
{
/// <summary>
/// Represents a JSON array.
/// </summary>
/// <example>
/// <code lang="cs" source="..\Src\PlayFab.Json.Tests\Documentation\LinqToJsonTests.cs" region="LinqToJsonCreateParseArray" title="Parsing a JSON Array from Text" />
/// </example>
public class JArray : JContainer, IList<JToken>
{
private readonly List<JToken> _values = new List<JToken>();
/// <summary>
/// Gets the container's children tokens.
/// </summary>
/// <value>The container's children tokens.</value>
protected override IList<JToken> ChildrenTokens
{
get { return _values; }
}
/// <summary>
/// Gets the node type for this <see cref="JToken"/>.
/// </summary>
/// <value>The type.</value>
public override JTokenType Type
{
get { return JTokenType.Array; }
}
/// <summary>
/// Initializes a new instance of the <see cref="JArray"/> class.
/// </summary>
public JArray()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JArray"/> class from another <see cref="JArray"/> object.
/// </summary>
/// <param name="other">A <see cref="JArray"/> object to copy from.</param>
public JArray(JArray other)
: base(other)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JArray"/> class with the specified content.
/// </summary>
/// <param name="content">The contents of the array.</param>
public JArray(params object[] content)
: this((object)content)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JArray"/> class with the specified content.
/// </summary>
/// <param name="content">The contents of the array.</param>
public JArray(object content)
{
Add(content);
}
internal override bool DeepEquals(JToken node)
{
JArray t = node as JArray;
return (t != null && ContentsEqual(t));
}
internal override JToken CloneToken()
{
return new JArray(this);
}
/// <summary>
/// Loads an <see cref="JArray"/> from a <see cref="JsonReader"/>.
/// </summary>
/// <param name="reader">A <see cref="JsonReader"/> that will be read for the content of the <see cref="JArray"/>.</param>
/// <returns>A <see cref="JArray"/> that contains the JSON that was read from the specified <see cref="JsonReader"/>.</returns>
public static new JArray Load(JsonReader reader)
{
if (reader.TokenType == JsonToken.None)
{
if (!reader.Read())
throw JsonReaderException.Create(reader, "Error reading JArray from JsonReader.");
}
while (reader.TokenType == JsonToken.Comment)
{
reader.Read();
}
if (reader.TokenType != JsonToken.StartArray)
throw JsonReaderException.Create(reader, "Error reading JArray from JsonReader. Current JsonReader item is not an array: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
JArray a = new JArray();
a.SetLineInfo(reader as IJsonLineInfo);
a.ReadTokenFrom(reader);
return a;
}
/// <summary>
/// Load a <see cref="JArray"/> from a string that contains JSON.
/// </summary>
/// <param name="json">A <see cref="String"/> that contains JSON.</param>
/// <returns>A <see cref="JArray"/> populated from the string that contains JSON.</returns>
/// <example>
/// <code lang="cs" source="..\Src\PlayFab.Json.Tests\Documentation\LinqToJsonTests.cs" region="LinqToJsonCreateParseArray" title="Parsing a JSON Array from Text" />
/// </example>
public static new JArray Parse(string json)
{
JsonReader reader = new JsonTextReader(new StringReader(json));
JArray a = Load(reader);
if (reader.Read() && reader.TokenType != JsonToken.Comment)
throw JsonReaderException.Create(reader, "Additional text found in JSON string after parsing content.");
return a;
}
/// <summary>
/// Creates a <see cref="JArray"/> from an object.
/// </summary>
/// <param name="o">The object that will be used to create <see cref="JArray"/>.</param>
/// <returns>A <see cref="JArray"/> with the values of the specified object</returns>
public static new JArray FromObject(object o)
{
return FromObject(o, JsonSerializer.CreateDefault());
}
/// <summary>
/// Creates a <see cref="JArray"/> from an object.
/// </summary>
/// <param name="o">The object that will be used to create <see cref="JArray"/>.</param>
/// <param name="jsonSerializer">The <see cref="JsonSerializer"/> that will be used to read the object.</param>
/// <returns>A <see cref="JArray"/> with the values of the specified object</returns>
public static new JArray FromObject(object o, JsonSerializer jsonSerializer)
{
JToken token = FromObjectInternal(o, jsonSerializer);
if (token.Type != JTokenType.Array)
throw new ArgumentException("Object serialized to {0}. JArray instance expected.".FormatWith(CultureInfo.InvariantCulture, token.Type));
return (JArray)token;
}
/// <summary>
/// Writes this token to a <see cref="JsonWriter"/>.
/// </summary>
/// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param>
/// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param>
public override void WriteTo(JsonWriter writer, params JsonConverter[] converters)
{
writer.WriteStartArray();
for (int i = 0; i < _values.Count; i++)
{
_values[i].WriteTo(writer, converters);
}
writer.WriteEndArray();
}
/// <summary>
/// Gets the <see cref="JToken"/> with the specified key.
/// </summary>
/// <value>The <see cref="JToken"/> with the specified key.</value>
public override JToken this[object key]
{
get
{
ValidationUtils.ArgumentNotNull(key, "o");
if (!(key is int))
throw new ArgumentException("Accessed JArray values with invalid key value: {0}. Array position index expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key)));
return GetItem((int)key);
}
set
{
ValidationUtils.ArgumentNotNull(key, "o");
if (!(key is int))
throw new ArgumentException("Set JArray values with invalid key value: {0}. Array position index expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key)));
SetItem((int)key, value);
}
}
/// <summary>
/// Gets or sets the <see cref="PlayFab.Json.Linq.JToken"/> at the specified index.
/// </summary>
/// <value></value>
public JToken this[int index]
{
get { return GetItem(index); }
set { SetItem(index, value); }
}
#region IList<JToken> Members
/// <summary>
/// Determines the index of a specific item in the <see cref="T:System.Collections.Generic.IList`1"/>.
/// </summary>
/// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.IList`1"/>.</param>
/// <returns>
/// The index of <paramref name="item"/> if found in the list; otherwise, -1.
/// </returns>
public int IndexOf(JToken item)
{
return IndexOfItem(item);
}
/// <summary>
/// Inserts an item to the <see cref="T:System.Collections.Generic.IList`1"/> at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param>
/// <param name="item">The object to insert into the <see cref="T:System.Collections.Generic.IList`1"/>.</param>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>.</exception>
/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IList`1"/> is read-only.</exception>
public void Insert(int index, JToken item)
{
InsertItem(index, item, false);
}
/// <summary>
/// Removes the <see cref="T:System.Collections.Generic.IList`1"/> item at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the item to remove.</param>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>.</exception>
/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IList`1"/> is read-only.</exception>
public void RemoveAt(int index)
{
RemoveItemAt(index);
}
/// <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<JToken> GetEnumerator()
{
return Children().GetEnumerator();
}
#endregion
#region ICollection<JToken> Members
/// <summary>
/// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception>
public void Add(JToken item)
{
Add((object)item);
}
/// <summary>
/// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only. </exception>
public void Clear()
{
ClearItems();
}
/// <summary>
/// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1"/> contains a specific value.
/// </summary>
/// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
/// <returns>
/// true if <paramref name="item"/> is found in the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false.
/// </returns>
public bool Contains(JToken item)
{
return ContainsItem(item);
}
/// <summary>
/// Copies to.
/// </summary>
/// <param name="array">The array.</param>
/// <param name="arrayIndex">Index of the array.</param>
public void CopyTo(JToken[] array, int arrayIndex)
{
CopyItemsTo(array, arrayIndex);
}
/// <summary>
/// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1" /> is read-only.
/// </summary>
/// <returns>true if the <see cref="T:System.Collections.Generic.ICollection`1" /> is read-only; otherwise, false.</returns>
public bool IsReadOnly
{
get { return false; }
}
/// <summary>
/// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
/// <returns>
/// true if <paramref name="item"/> was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </returns>
/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception>
public bool Remove(JToken item)
{
return RemoveItem(item);
}
#endregion
internal override int GetDeepHashCode()
{
return ContentsHashCode();
}
}
}
#endif
| |
// The MIT License (MIT)
//
// Copyright (c) 2014-2017, Institute for Software & Systems Engineering
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
namespace ISSE.SafetyChecking.ExecutableModel
{
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using AnalysisModel;
using ExecutedModel;
using Formula;
using Modeling;
using Utilities;
/// <summary>
/// Represents a runtime model that can be used for model checking or simulation.
/// </summary>
public abstract unsafe class ExecutableModel<TExecutableModel> : DisposableObject where TExecutableModel : ExecutableModel<TExecutableModel>
{
/// <summary>
/// Deserializes a state of the model.
/// </summary>
protected SerializationDelegate _deserialize;
/// <summary>
/// The faults contained in the model.
/// </summary>
public Fault[] Faults { get; protected set; }
/// <summary>
/// Restricts the ranges of the model's state variables.
/// </summary>
protected Action _restrictRanges;
/// <summary>
/// Serializes a state of the model.
/// </summary>
protected SerializationDelegate _serialize;
/// <summary>
/// The number of bytes reserved at the beginning of each state vector by the model checker.
/// </summary>
protected int StateHeaderBytes { get; }
/// <summary>
/// The state constraints which describe allowed states. When any stateConstraint returns false the state is deleted.
/// </summary>
public Func<bool>[] StateConstraints { protected set; get; }
/// <summary>
/// Initializes a new instance.
/// </summary>
/// <param name="serializedData">The serialized data describing the model.</param>
/// <param name="stateHeaderBytes">
/// The number of bytes that should be reserved at the beginning of each state vector for the model checker tool.
/// </param>
protected ExecutableModel(int stateHeaderBytes = 0)
{
Requires.That(stateHeaderBytes % 4 == 0, nameof(stateHeaderBytes), "Expected a multiple of 4.");
StateHeaderBytes = stateHeaderBytes;
}
protected void CheckConsistencyAfterInitialization()
{
StateFormulaSet.CheckFormulaCount(AtomarPropositionFormulas.Length);
}
protected void InitializeConstructionState()
{
ConstructionState = new byte[StateVectorSize];
fixed (byte* state = ConstructionState)
{
Serialize(state);
_restrictRanges();
}
}
/// <summary>
/// Gets the construction state of the model.
/// </summary>
public byte[] ConstructionState { get; private set; }
/// <summary>
/// Gets the buffer the model was deserialized from.
/// </summary>
public byte[] SerializedModel { get; set; }
/// <summary>
/// The formulas that are checked on the model.
/// </summary>
public Formula[] Formulas { get; protected set; }
/// <summary>
/// Gets the size of the state vector in bytes. The size is always a multiple of 4.
/// </summary>
public abstract int StateVectorSize { get; }
/// <summary>
/// Gets the faults contained in the model that can be activated nondeterministically.
/// </summary>
public Fault[] NondeterministicFaults { get; private set; }
/// <summary>
/// Gets the nondeterministic faults contained in the model that are activated on the start of a step.
/// </summary>
public Fault[] OnStartOfStepFaults { get; private set; }
/// <summary>
/// Gets the nondeterministic faults contained in the model that are activated on the call of a method in the fault effect.
/// </summary>
public Fault[] OnMethodCallFaults { get; private set; }
/// <summary>
/// Gets the nondeterministic faults contained in the model that are activated at the beginning of a step when custom fault method evaluates to true.
/// </summary>
public Fault[] OnCustomFaults { get; private set; }
/// <summary>
/// Gets the faults contained in the model that can be activated nondeterministically and that must be notified about their
/// activation.
/// </summary>
internal Fault[] ActivationSensitiveFaults { get; private set; }
/// <summary>
/// Gets the state formulas of the model.
/// </summary>
public abstract AtomarPropositionFormula[] AtomarPropositionFormulas { get; }
/// <summary>
/// Updates the activation states of the model's faults.
/// </summary>
/// <param name="getActivation">The callback that should be used to determine a fault's activation state.</param>
internal void ChangeFaultActivations(Func<Fault, Activation> getActivation)
{
foreach (var fault in Faults)
fault.Activation = getActivation(fault);
UpdateFaultSets();
}
/// <summary>
/// Updates the fault sets in accordance with the fault's actual activation states.
/// </summary>
public void UpdateFaultSets()
{
NondeterministicFaults = Faults.Where(fault => fault.Activation == Activation.Nondeterministic).ToArray();
ActivationSensitiveFaults = NondeterministicFaults.Where(fault => fault.RequiresActivationNotification).ToArray();
OnStartOfStepFaults = NondeterministicFaults.Where(fault => fault.DemandType==Fault.DemandTypes.OnStartOfStep).ToArray();
OnMethodCallFaults = NondeterministicFaults.Where(fault => fault.DemandType == Fault.DemandTypes.OnMethodCall).ToArray();
OnCustomFaults = NondeterministicFaults.Where(fault => fault.DemandType == Fault.DemandTypes.OnCustom).ToArray();
}
/// <summary>
/// Copies the fault activation states of this instance to <paramref name="target" />.
/// </summary>
protected void CopyFaultActivationStates(TExecutableModel target)
{
for (var i = 0; i < Faults.Length; ++i)
target.Faults[i].Activation = Faults[i].Activation;
target.UpdateFaultSets();
}
/// <summary>
/// Deserializes the model's state from <paramref name="serializedState" />.
/// </summary>
/// <param name="serializedState">The state of the model that should be deserialized.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void Deserialize(byte* serializedState)
{
_deserialize(serializedState + StateHeaderBytes);
}
/// <summary>
/// Serializes the model's state to <paramref name="serializedState" />.
/// </summary>
/// <param name="serializedState">The memory region the model's state should be serialized into.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void Serialize(byte* serializedState)
{
_serialize(serializedState + StateHeaderBytes);
}
/// <summary>
/// Resets the model to one of its initial states.
/// </summary>
internal void Reset()
{
fixed (byte* state = ConstructionState)
{
Deserialize(state);
_restrictRanges();
}
}
/// <summary>
/// Computes an initial state of the model.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public abstract void ExecuteInitialStep();
/// <summary>
/// Updates the state of the model by executing a single step.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public abstract void ExecuteStep();
/// <summary>
/// Creates a counter example from the <paramref name="path" />.
/// </summary>
/// <param name="createModel">The factory function that can be used to create new instances of this model.</param>
/// <param name="path">
/// The path the counter example should be generated from. A value of <c>null</c> indicates that no
/// transitions could be generated for the model.
/// </param>
/// <param name="endsWithException">Indicates whether the counter example ends with an exception.</param>
public CounterExample CreateCounterExample(CoupledExecutableModelCreator<TExecutableModel> createModel, byte[][] path, bool endsWithException)
{
Requires.NotNull(createModel, nameof(createModel));
// We have to create new model instances to generate and initialize the counter example, otherwise hidden
// state variables might prevent us from doing so if they somehow influence the state
var replayModel = createModel.Create(StateHeaderBytes);
var choiceResolver = new NondeterministicChoiceResolver(true);
replayModel.SetChoiceResolver(choiceResolver);
CopyFaultActivationStates(replayModel);
var faultActivations=Faults.Select(fault => fault.Activation).ToArray();
// Prepend the construction state to the path; if the path is null, at least one further state must be added
// to enable counter example debugging.
// Also, get the replay information, i.e., the nondeterministic choices that were made on the path; if the path is null,
// we still have to get the choices that caused the problem.
if (path == null)
path = new[] { new byte[StateVectorSize] };
path = new[] { ConstructionState }.Concat(path).ToArray();
var replayInfo = replayModel.GenerateReplayInformation(choiceResolver, path, endsWithException);
return new CounterExample( path, replayInfo, endsWithException, faultActivations);
}
public abstract void SetChoiceResolver(ChoiceResolver choiceResolver);
/// <summary>
/// Generates the replay information for the <paramref name="trace" />.
/// </summary>
/// <param name="choiceResolver">The choice resolver that should be used to resolve nondeterministic choices.</param>
/// <param name="trace">The trace the replay information should be generated for.</param>
/// <param name="endsWithException">Indicates whether the trace ends with an exception being thrown.</param>
private int[][] GenerateReplayInformation(ChoiceResolver choiceResolver, byte[][] trace, bool endsWithException)
{
var info = new int[trace.Length - 1][];
var targetState = stackalloc byte[StateVectorSize];
// We have to generate the replay info for all transitions
for (var i = 0; i < trace.Length - 1; ++i)
{
choiceResolver.Clear();
choiceResolver.PrepareNextState();
// Try all transitions until we find the one that leads to the desired state
while (true)
{
try
{
if (!choiceResolver.PrepareNextPath())
break;
fixed (byte* sourceState = trace[i])
Deserialize(sourceState);
foreach (var fault in NondeterministicFaults)
fault.Reset();
if (i == 0)
ExecuteInitialStep();
else
ExecuteStep();
if (endsWithException && i == trace.Length - 2)
continue;
}
catch (Exception)
{
Requires.That(endsWithException, "Unexpected exception.");
Requires.That(i == trace.Length - 2, "Unexpected exception.");
info[i] = choiceResolver.GetChoices().ToArray();
break;
}
NotifyFaultActivations();
Serialize(targetState);
// Compare the target states; if they match, we've found the correct transition
var areEqual = true;
for (var j = StateHeaderBytes; j < StateVectorSize; ++j)
areEqual &= targetState[j] == trace[i + 1][j];
if (!areEqual)
continue;
info[i] = choiceResolver.GetChoices().ToArray();
break;
}
Requires.That(info[i] != null, $"Unable to generate replay information for step {i + 1} of {trace.Length}.");
}
return info;
}
/// <summary>
/// Notifies all activated faults of their activation. Returns <c>false</c> to indicate that no notifications were necessary.
/// </summary>
internal bool NotifyFaultActivations()
{
if (ActivationSensitiveFaults.Length == 0)
return false;
var notificationsSent = false;
foreach (var fault in ActivationSensitiveFaults)
{
if (fault.IsActivated)
{
fault.OnActivated();
notificationsSent = true;
}
}
return notificationsSent;
}
public abstract void WriteOptimizedStateVectorLayout(System.IO.TextWriter textWriter);
public abstract CounterExampleSerialization<TExecutableModel> CounterExampleSerialization { get; }
public abstract Expression CreateExecutableExpressionFromAtomarPropositionFormula(AtomarPropositionFormula formula);
/// <summary>
/// Disposes the object, releasing all managed and unmanaged resources.
/// </summary>
/// <param name="disposing">If true, indicates that the object is disposed; otherwise, the object is finalized.</param>
protected override void OnDisposing(bool disposing)
{
}
}
}
| |
// Copyright 2013 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using NodaTime.Annotations;
using NodaTime.Globalization;
using NodaTime.Text.Patterns;
using NodaTime.TimeZones;
using NodaTime.Utility;
using System.Globalization;
using System.Text;
namespace NodaTime.Text
{
/// <summary>
/// Represents a pattern for parsing and formatting <see cref="ZonedDateTime"/> values.
/// </summary>
/// <threadsafety>
/// When used with a read-only <see cref="CultureInfo" />, this type is immutable and instances
/// may be shared freely between threads. We recommend only using read-only cultures for patterns, although this is
/// not currently enforced.
/// </threadsafety>
[Immutable] // Well, assuming an immutable culture...
public sealed class ZonedDateTimePattern : IPattern<ZonedDateTime>
{
internal static ZonedDateTime DefaultTemplateValue { get; } = new LocalDateTime(2000, 1, 1, 0, 0).InUtc();
/// <summary>
/// Gets an zoned local date/time pattern based on ISO-8601 (down to the second) including offset from UTC and zone ID.
/// It corresponds to a custom pattern of "uuuu'-'MM'-'dd'T'HH':'mm':'ss z '('o<g>')'" and is available
/// as the 'G' standard pattern.
/// </summary>
/// <remarks>
/// The calendar system is not formatted as part of this pattern, and it cannot be used for parsing as no time zone
/// provider is included. Call <see cref="WithZoneProvider"/> on the value of this property to obtain a
/// pattern which can be used for parsing.
/// </remarks>
/// <value>An zoned local date/time pattern based on ISO-8601 (down to the second) including offset from UTC and zone ID.</value>
public static ZonedDateTimePattern GeneralFormatOnlyIso => Patterns.GeneralFormatOnlyPatternImpl;
/// <summary>
/// Returns an invariant zoned date/time pattern based on ISO-8601 (down to the nanosecond) including offset from UTC and zone ID.
/// It corresponds to a custom pattern of "uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFF z '('o<g>')'" and is available
/// as the 'F' standard pattern.
/// </summary>
/// <remarks>
/// The calendar system is not formatted as part of this pattern, and it cannot be used for parsing as no time zone
/// provider is included. Call <see cref="WithZoneProvider"/> on the value of this property to obtain a
/// pattern which can be used for parsing.
/// </remarks>
/// <value>An invariant zoned date/time pattern based on ISO-8601 (down to the nanosecond) including offset from UTC and zone ID.</value>
public static ZonedDateTimePattern ExtendedFormatOnlyIso => Patterns.ExtendedFormatOnlyPatternImpl;
private readonly IPattern<ZonedDateTime> pattern;
/// <summary>
/// Class whose existence is solely to avoid type initialization order issues, most of which stem
/// from needing NodaFormatInfo.InvariantInfo...
/// </summary>
internal static class Patterns
{
internal static readonly ZonedDateTimePattern GeneralFormatOnlyPatternImpl = CreateWithInvariantCulture("uuuu'-'MM'-'dd'T'HH':'mm':'ss z '('o<g>')'", null);
internal static readonly ZonedDateTimePattern ExtendedFormatOnlyPatternImpl = CreateWithInvariantCulture("uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFF z '('o<g>')'", null);
internal static readonly PatternBclSupport<ZonedDateTime> BclSupport = new PatternBclSupport<ZonedDateTime>("G", fi => fi.ZonedDateTimePatternParser);
}
/// <summary>
/// Gets the pattern text for this pattern, as supplied on creation.
/// </summary>
/// <value>The pattern text for this pattern, as supplied on creation.</value>
public string PatternText { get; }
/// <summary>
/// Gets the localization information used in this pattern.
/// </summary>
private NodaFormatInfo FormatInfo { get; }
/// <summary>
/// Gets the value used as a template for parsing: any field values unspecified
/// in the pattern are taken from the template.
/// </summary>
/// <value>The value used as a template for parsing.</value>
public ZonedDateTime TemplateValue { get; }
/// <summary>
/// Gets the resolver which is used to map local date/times to zoned date/times,
/// handling skipped and ambiguous times appropriately (where the offset isn't specified in the pattern).
/// This may be null, in which case the pattern can only be used for formatting (not parsing).
/// </summary>
/// <value>The resolver which is used to map local date/times to zoned date/times.</value>
public ZoneLocalMappingResolver? Resolver { get; }
/// <summary>
/// Gets the provider which is used to look up time zones when parsing a pattern
/// which contains a time zone identifier. This may be null, in which case the pattern can
/// only be used for formatting (not parsing).
/// </summary>
/// <value>The provider which is used to look up time zones when parsing a pattern
/// which contains a time zone identifier.</value>
public IDateTimeZoneProvider? ZoneProvider { get; }
private ZonedDateTimePattern(string patternText, NodaFormatInfo formatInfo, ZonedDateTime templateValue,
ZoneLocalMappingResolver? resolver, IDateTimeZoneProvider? zoneProvider, IPattern<ZonedDateTime> pattern)
{
this.PatternText = patternText;
this.FormatInfo = formatInfo;
this.TemplateValue = templateValue;
this.Resolver = resolver;
this.ZoneProvider = zoneProvider;
this.pattern = pattern;
}
/// <summary>
/// Parses the given text value according to the rules of this pattern.
/// </summary>
/// <remarks>
/// This method never throws an exception (barring a bug in Noda Time itself). Even errors such as
/// the argument being null are wrapped in a parse result.
/// </remarks>
/// <param name="text">The text value to parse.</param>
/// <returns>The result of parsing, which may be successful or unsuccessful.</returns>
public ParseResult<ZonedDateTime> Parse([SpecialNullHandling] string text) => pattern.Parse(text);
/// <summary>
/// Formats the given zoned date/time as text according to the rules of this pattern.
/// </summary>
/// <param name="value">The zoned date/time to format.</param>
/// <returns>The zoned date/time formatted according to this pattern.</returns>
public string Format(ZonedDateTime value) => pattern.Format(value);
/// <summary>
/// Formats the given value as text according to the rules of this pattern,
/// appending to the given <see cref="StringBuilder"/>.
/// </summary>
/// <param name="value">The value to format.</param>
/// <param name="builder">The <c>StringBuilder</c> to append to.</param>
/// <returns>The builder passed in as <paramref name="builder"/>.</returns>
public StringBuilder AppendFormat(ZonedDateTime value, StringBuilder builder) => pattern.AppendFormat(value, builder);
/// <summary>
/// Creates a pattern for the given pattern text, format info, template value, mapping resolver and time zone provider.
/// </summary>
/// <param name="patternText">Pattern text to create the pattern for</param>
/// <param name="formatInfo">The format info to use in the pattern</param>
/// <param name="templateValue">Template value to use for unspecified fields</param>
/// <param name="resolver">Resolver to apply when mapping local date/time values into the zone.</param>
/// <param name="zoneProvider">Time zone provider, used when parsing text which contains a time zone identifier.</param>
/// <returns>A pattern for parsing and formatting zoned date/times.</returns>
/// <exception cref="InvalidPatternException">The pattern text was invalid.</exception>
private static ZonedDateTimePattern Create(string patternText, NodaFormatInfo formatInfo,
ZoneLocalMappingResolver? resolver, IDateTimeZoneProvider? zoneProvider, ZonedDateTime templateValue)
{
Preconditions.CheckNotNull(patternText, nameof(patternText));
Preconditions.CheckNotNull(formatInfo, nameof(formatInfo));
var pattern = new ZonedDateTimePatternParser(templateValue, resolver, zoneProvider).ParsePattern(patternText, formatInfo);
return new ZonedDateTimePattern(patternText, formatInfo, templateValue, resolver, zoneProvider, pattern);
}
/// <summary>
/// Creates a pattern for the given pattern text, culture, resolver, time zone provider, and template value.
/// </summary>
/// <remarks>
/// See the user guide for the available pattern text options.
/// If <paramref name="zoneProvider"/> is null, the resulting pattern can be used for formatting
/// but not parsing.
/// </remarks>
/// <param name="patternText">Pattern text to create the pattern for</param>
/// <param name="cultureInfo">The culture to use in the pattern</param>
/// <param name="resolver">Resolver to apply when mapping local date/time values into the zone.</param>
/// <param name="zoneProvider">Time zone provider, used when parsing text which contains a time zone identifier.</param>
/// <param name="templateValue">Template value to use for unspecified fields</param>
/// <returns>A pattern for parsing and formatting zoned date/times.</returns>
/// <exception cref="InvalidPatternException">The pattern text was invalid.</exception>
public static ZonedDateTimePattern Create(string patternText, [ValidatedNotNull] CultureInfo cultureInfo,
ZoneLocalMappingResolver? resolver, IDateTimeZoneProvider? zoneProvider, ZonedDateTime templateValue) =>
Create(patternText, NodaFormatInfo.GetFormatInfo(cultureInfo), resolver, zoneProvider, templateValue);
/// <summary>
/// Creates a pattern for the given pattern text and time zone provider, using a strict resolver, the invariant
/// culture, and a default template value of midnight January 1st 2000 UTC.
/// </summary>
/// <remarks>
/// The resolver is only used if the pattern text doesn't include an offset.
/// If <paramref name="zoneProvider"/> is null, the resulting pattern can be used for formatting
/// but not parsing.
/// </remarks>
/// <param name="patternText">Pattern text to create the pattern for</param>
/// <param name="zoneProvider">Time zone provider, used when parsing text which contains a time zone identifier.</param>
/// <returns>A pattern for parsing and formatting zoned date/times.</returns>
public static ZonedDateTimePattern CreateWithInvariantCulture(string patternText, IDateTimeZoneProvider? zoneProvider) =>
Create(patternText, NodaFormatInfo.InvariantInfo, Resolvers.StrictResolver, zoneProvider, DefaultTemplateValue);
/// <summary>
/// Creates a pattern for the given pattern text and time zone provider, using a strict resolver, the current
/// culture, and a default template value of midnight January 1st 2000 UTC.
/// </summary>
/// <remarks>
/// The resolver is only used if the pattern text doesn't include an offset.
/// If <paramref name="zoneProvider"/> is null, the resulting pattern can be used for formatting
/// but not parsing. Note that the current culture is captured at the time this method is called
/// - it is not captured at the point of parsing or formatting values.
/// </remarks>
/// <param name="patternText">Pattern text to create the pattern for</param>
/// <param name="zoneProvider">Time zone provider, used when parsing text which contains a time zone identifier.</param>
/// <returns>A pattern for parsing and formatting zoned date/times.</returns>
public static ZonedDateTimePattern CreateWithCurrentCulture(string patternText, IDateTimeZoneProvider? zoneProvider) =>
Create(patternText, NodaFormatInfo.CurrentInfo, Resolvers.StrictResolver, zoneProvider, DefaultTemplateValue);
/// <summary>
/// Creates a pattern for the same original localization information as this pattern, but with the specified
/// pattern text.
/// </summary>
/// <param name="patternText">The pattern text to use in the new pattern.</param>
/// <returns>A new pattern with the given pattern text.</returns>
public ZonedDateTimePattern WithPatternText(string patternText) =>
Create(patternText, FormatInfo, Resolver, ZoneProvider, TemplateValue);
/// <summary>
/// Creates a pattern for the same original pattern text as this pattern, but with the specified
/// localization information.
/// </summary>
/// <param name="formatInfo">The localization information to use in the new pattern.</param>
/// <returns>A new pattern with the given localization information.</returns>
private ZonedDateTimePattern WithFormatInfo(NodaFormatInfo formatInfo) =>
Create(PatternText, formatInfo, Resolver, ZoneProvider, TemplateValue);
/// <summary>
/// Creates a pattern for the same original pattern text as this pattern, but with the specified
/// culture.
/// </summary>
/// <param name="cultureInfo">The culture to use in the new pattern.</param>
/// <returns>A new pattern with the given culture.</returns>
public ZonedDateTimePattern WithCulture([ValidatedNotNull] CultureInfo cultureInfo) =>
WithFormatInfo(NodaFormatInfo.GetFormatInfo(cultureInfo));
/// <summary>
/// Creates a pattern for the same original pattern text as this pattern, but with the specified
/// resolver.
/// </summary>
/// <param name="resolver">The new local mapping resolver to use.</param>
/// <returns>A new pattern with the given resolver.</returns>
public ZonedDateTimePattern WithResolver(ZoneLocalMappingResolver? resolver) =>
Resolver == resolver ? this : Create(PatternText, FormatInfo, resolver, ZoneProvider, TemplateValue);
/// <summary>
/// Creates a pattern for the same original pattern text as this pattern, but with the specified
/// time zone provider.
/// </summary>
/// <remarks>
/// If <paramref name="newZoneProvider"/> is null, the resulting pattern can be used for formatting
/// but not parsing.
/// </remarks>
/// <param name="newZoneProvider">The new time zone provider to use.</param>
/// <returns>A new pattern with the given time zone provider.</returns>
public ZonedDateTimePattern WithZoneProvider(IDateTimeZoneProvider? newZoneProvider) =>
newZoneProvider == ZoneProvider ? this : Create(PatternText, FormatInfo, Resolver, newZoneProvider, TemplateValue);
/// <summary>
/// Creates a pattern like this one, but with the specified template value.
/// </summary>
/// <param name="newTemplateValue">The template value for the new pattern, used to fill in unspecified fields.</param>
/// <returns>A new pattern with the given template value.</returns>
public ZonedDateTimePattern WithTemplateValue(ZonedDateTime newTemplateValue) =>
newTemplateValue == TemplateValue ? this : Create(PatternText, FormatInfo, Resolver, ZoneProvider, newTemplateValue);
/// <summary>
/// Creates a pattern like this one, but with the template value modified to use
/// the specified calendar system.
/// </summary>
/// <remarks>
/// <para>
/// Care should be taken in two (relatively rare) scenarios. Although the default template value
/// is supported by all Noda Time calendar systems, if a pattern is created with a different
/// template value and then this method is called with a calendar system which doesn't support that
/// date, an exception will be thrown. Additionally, if the pattern only specifies some date fields,
/// it's possible that the new template value will not be suitable for all values.
/// </para>
/// </remarks>
/// <param name="calendar">The calendar system to convert the template value into.</param>
/// <returns>A new pattern with a template value in the specified calendar system.</returns>
public ZonedDateTimePattern WithCalendar(CalendarSystem calendar) =>
WithTemplateValue(TemplateValue.WithCalendar(calendar));
}
}
| |
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
using System.Collections;
namespace UnityStandardAssets.Characters.FirstPerson
{
[RequireComponent(typeof (Rigidbody))]
[RequireComponent(typeof (CapsuleCollider))]
public class RigidbodyFirstPersonController : MonoBehaviour
{
[Serializable]
public class MovementSettings
{
public float ForwardSpeed = 8.0f; // Speed when walking forward
public float BackwardSpeed = 4.0f; // Speed when walking backwards
public float StrafeSpeed = 4.0f; // Speed when walking sideways
public float RunMultiplier = 2.0f; // Speed when sprinting
public KeyCode RunKey = KeyCode.LeftShift;
public float JumpForce = 30f;
public AnimationCurve SlopeCurveModifier = new AnimationCurve(new Keyframe(-90.0f, 1.0f), new Keyframe(0.0f, 1.0f), new Keyframe(90.0f, 0.0f));
[HideInInspector] public float CurrentTargetSpeed = 8f;
#if !MOBILE_INPUT
private bool m_Running;
#endif
public void UpdateDesiredTargetSpeed(Vector2 input)
{
if (input == Vector2.zero) return;
if (input.x > 0 || input.x < 0)
{
//strafe
CurrentTargetSpeed = StrafeSpeed;
}
if (input.y < 0)
{
//backwards
CurrentTargetSpeed = BackwardSpeed;
}
if (input.y > 0)
{
//forwards
//handled last as if strafing and moving forward at the same time forwards speed should take precedence
CurrentTargetSpeed = ForwardSpeed;
}
#if !MOBILE_INPUT
if (Input.GetKey(RunKey))
{
CurrentTargetSpeed *= RunMultiplier;
m_Running = true;
}
else
{
m_Running = false;
}
#endif
}
#if !MOBILE_INPUT
public bool Running
{
get { return m_Running; }
}
#endif
}
[Serializable]
public class AdvancedSettings
{
public float groundCheckDistance = 0.01f; // distance for checking if the controller is grounded ( 0.01f seems to work best for this )
public float stickToGroundHelperDistance = 0.5f; // stops the character
public float slowDownRate = 20f; // rate at which the controller comes to a stop when there is no input
public bool airControl; // can the user control the direction that is being moved in the air
}
public Camera cam;
public MovementSettings movementSettings = new MovementSettings();
public MouseLook mouseLook = new MouseLook();
public AdvancedSettings advancedSettings = new AdvancedSettings();
private Rigidbody m_RigidBody;
private CapsuleCollider m_Capsule;
private float m_YRotation;
private Vector3 m_GroundContactNormal;
private bool m_Jump, m_PreviouslyGrounded, m_Jumping, m_IsGrounded;
private int toggleMove = 0;
public Vector3 Velocity
{
get { return m_RigidBody.velocity; }
}
public bool Grounded
{
get { return m_IsGrounded; }
}
public bool Jumping
{
get { return m_Jumping; }
}
public bool Running
{
get
{
#if !MOBILE_INPUT
return movementSettings.Running;
#else
return false;
#endif
}
}
private void Start()
{
m_RigidBody = GetComponent<Rigidbody>();
m_Capsule = GetComponent<CapsuleCollider>();
mouseLook.Init (transform, cam.transform);
}
private void Update()
{
RotateView();
if (CrossPlatformInputManager.GetButtonDown("Jump") && !m_Jump)
{
m_Jump = true;
}
}
private void FixedUpdate()
{
GroundCheck();
Vector2 input = GetInput();
if ((Mathf.Abs(input.x) > float.Epsilon || Mathf.Abs(input.y) > float.Epsilon) && (advancedSettings.airControl || m_IsGrounded))
{
// always move along the camera forward as it is the direction that it being aimed at
Vector3 desiredMove = cam.transform.forward*input.y + cam.transform.right*input.x;
desiredMove = Vector3.ProjectOnPlane(desiredMove, m_GroundContactNormal).normalized;
desiredMove.x = desiredMove.x*movementSettings.CurrentTargetSpeed;
desiredMove.z = desiredMove.z*movementSettings.CurrentTargetSpeed;
desiredMove.y = desiredMove.y*movementSettings.CurrentTargetSpeed;
if (m_RigidBody.velocity.sqrMagnitude <
(movementSettings.CurrentTargetSpeed*movementSettings.CurrentTargetSpeed))
{
m_RigidBody.AddForce(desiredMove*SlopeMultiplier(), ForceMode.Impulse);
}
}
if (m_IsGrounded)
{
m_RigidBody.drag = 5f;
if (m_Jump)
{
m_RigidBody.drag = 0f;
m_RigidBody.velocity = new Vector3(m_RigidBody.velocity.x, 0f, m_RigidBody.velocity.z);
m_RigidBody.AddForce(new Vector3(0f, movementSettings.JumpForce, 0f), ForceMode.Impulse);
m_Jumping = true;
}
if (!m_Jumping && Mathf.Abs(input.x) < float.Epsilon && Mathf.Abs(input.y) < float.Epsilon && m_RigidBody.velocity.magnitude < 1f)
{
m_RigidBody.Sleep();
}
}
else
{
m_RigidBody.drag = 0f;
if (m_PreviouslyGrounded && !m_Jumping)
{
StickToGroundHelper();
}
}
m_Jump = false;
}
private float SlopeMultiplier()
{
float angle = Vector3.Angle(m_GroundContactNormal, Vector3.up);
return movementSettings.SlopeCurveModifier.Evaluate(angle);
}
private void StickToGroundHelper()
{
RaycastHit hitInfo;
if (Physics.SphereCast(transform.position, m_Capsule.radius, Vector3.down, out hitInfo,
((m_Capsule.height/2f) - m_Capsule.radius) +
advancedSettings.stickToGroundHelperDistance))
{
if (Mathf.Abs(Vector3.Angle(hitInfo.normal, Vector3.up)) < 85f)
{
m_RigidBody.velocity = Vector3.ProjectOnPlane(m_RigidBody.velocity, hitInfo.normal);
}
}
}
private Vector2 GetInput()
{
Vector2 input = new Vector2
{
x = CrossPlatformInputManager.GetAxis("Horizontal"),
y = CrossPlatformInputManager.GetAxis("Vertical")
};
// If GetAxis are empty, try alternate input methods.
if (Math.Abs (input.x) + Math.Abs (input.y) < 2 * float.Epsilon) {
input = new Vector2 (0, 1); // go straight forward by setting positive Vertical
}
movementSettings.UpdateDesiredTargetSpeed(input);
return input;
}
private void RotateView()
{
//avoids the mouse looking if the game is effectively paused
if (Mathf.Abs(Time.timeScale) < float.Epsilon) return;
// get the rotation before it's changed
float oldYRotation = transform.eulerAngles.y;
mouseLook.LookRotation (transform, cam.transform);
if (m_IsGrounded || advancedSettings.airControl)
{
// Rotate the rigidbody velocity to match the new direction that the character is looking
Quaternion velRotation = Quaternion.AngleAxis(transform.eulerAngles.y - oldYRotation, Vector3.up);
m_RigidBody.velocity = velRotation*m_RigidBody.velocity;
}
}
/// sphere cast down just beyond the bottom of the capsule to see if the capsule is colliding round the bottom
private void GroundCheck()
{
m_PreviouslyGrounded = m_IsGrounded;
RaycastHit hitInfo;
if (Physics.SphereCast(transform.position, m_Capsule.radius, Vector3.down, out hitInfo,
((m_Capsule.height/2f) - m_Capsule.radius) + advancedSettings.groundCheckDistance))
{
m_IsGrounded = true;
m_GroundContactNormal = hitInfo.normal;
}
else
{
m_IsGrounded = false;
m_GroundContactNormal = Vector3.up;
}
if (!m_PreviouslyGrounded && m_IsGrounded && m_Jumping)
{
m_Jumping = false;
}
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Pickup"))
{
Application.LoadLevel("FinalCountdown");
}
}
}
}
| |
#region License
/* **********************************************************************************
* Copyright (c) Roman Ivantsov
* This source code is subject to terms and conditions of the MIT License
* for Irony. A copy of the license can be found in the License.txt file
* at the root of this distribution.
* By using this source code in any fashion, you are agreeing to be bound by the terms of the
* MIT License.
* You must not remove this notice from this software.
* **********************************************************************************/
#endregion License
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace Irony.Interpreter
{
public delegate object BinaryOperatorMethod(object arg1, object arg2);
public delegate object UnaryOperatorMethod(object arg);
#region OperatorDispatchKey class
/// <summary>
/// The struct is used as a key for the dictionary of operator implementations.
/// Contains types of arguments for a method or operator implementation.
/// </summary>
public struct OperatorDispatchKey
{
public static readonly OperatorDispatchKeyComparer Comparer = new OperatorDispatchKeyComparer();
public readonly Type Arg1Type;
public readonly Type Arg2Type;
public readonly int HashCode;
public readonly ExpressionType Op;
/// <summary>
/// For binary operators
/// </summary>
/// <param name="op"></param>
/// <param name="arg1Type"></param>
/// <param name="arg2Type"></param>
public OperatorDispatchKey(ExpressionType op, Type arg1Type, Type arg2Type)
{
this.Op = op;
this.Arg1Type = arg1Type;
this.Arg2Type = arg2Type;
var h0 = (int) this.Op;
int h1 = this.Arg1Type.GetHashCode();
int h2 = this.Arg2Type.GetHashCode();
this.HashCode = unchecked(h0 << 8 ^ h1 << 4 ^ h2);
}
/// <summary>
/// For unary operators
/// </summary>
/// <param name="op"></param>
/// <param name="arg1Type"></param>
public OperatorDispatchKey(ExpressionType op, Type arg1Type)
{
this.Op = op;
this.Arg1Type = arg1Type;
this.Arg2Type = null;
var h0 = (int) this.Op;
int h1 = this.Arg1Type.GetHashCode();
int h2 = 0;
this.HashCode = unchecked(h0 << 8 ^ h1 << 4 ^ h2);
}
public override int GetHashCode()
{
return this.HashCode;
}
public override string ToString()
{
return this.Op + "(" + this.Arg1Type + ", " + this.Arg2Type + ")";
}
}
#endregion OperatorDispatchKey class
#region OperatorDispatchKeyComparer class
/// <summary>
/// Note: I believe (guess) that a custom Comparer provided to a Dictionary is a bit more efficient
/// than implementing IComparable on the key itself
/// </summary>
public class OperatorDispatchKeyComparer : IEqualityComparer<OperatorDispatchKey>
{
public bool Equals(OperatorDispatchKey x, OperatorDispatchKey y)
{
return x.HashCode == y.HashCode && x.Op == y.Op && x.Arg1Type == y.Arg1Type && x.Arg2Type == y.Arg2Type;
}
public int GetHashCode(OperatorDispatchKey obj)
{
return obj.HashCode;
}
}
#endregion OperatorDispatchKeyComparer class
///<summary>
///The OperatorImplementation class represents an implementation of an operator for specific argument types.
///</summary>
///<remarks>
/// The OperatorImplementation is used for holding implementation for binary operators, unary operators,
/// and type converters (special case of unary operators)
/// it holds 4 method references for binary operators:
/// converters for both arguments, implementation method and converter for the result.
/// For unary operators (and type converters) the implementation is in Arg1Converter
/// operator (arg1 is used); the converter method is stored in Arg1Converter; the target type is in CommonType
///</remarks>
public sealed class OperatorImplementation
{
public readonly BinaryOperatorMethod BaseBinaryMethod;
/// <summary>
/// The type to which arguments are converted and no-conversion method for this type.
/// </summary>
public readonly Type CommonType;
public readonly OperatorDispatchKey Key;
/// <summary>
/// A reference to the actual binary evaluator method - one of EvaluateConvXXX
/// </summary>
public BinaryOperatorMethod EvaluateBinary;
/// <summary>
/// No-box counterpart for implementations with auto-boxed output. If this field <> null, then this is
/// implementation with auto-boxed output
/// </summary>
public OperatorImplementation NoBoxImplementation;
/// <summary>
/// An overflow handler - the implementation to handle arithmetic overflow
/// </summary>
public OperatorImplementation OverflowHandler;
internal UnaryOperatorMethod Arg1Converter;
internal UnaryOperatorMethod Arg2Converter;
internal UnaryOperatorMethod ResultConverter;
/// <summary>
/// Constructor for binary operators
/// </summary>
/// <param name="key"></param>
/// <param name="resultType"></param>
/// <param name="baseBinaryMethod"></param>
/// <param name="arg1Converter"></param>
/// <param name="arg2Converter"></param>
/// <param name="resultConverter"></param>
public OperatorImplementation(OperatorDispatchKey key, Type resultType, BinaryOperatorMethod baseBinaryMethod,
UnaryOperatorMethod arg1Converter, UnaryOperatorMethod arg2Converter, UnaryOperatorMethod resultConverter)
{
this.Key = key;
this.CommonType = resultType;
this.Arg1Converter = arg1Converter;
this.Arg2Converter = arg2Converter;
this.ResultConverter = resultConverter;
this.BaseBinaryMethod = baseBinaryMethod;
this.SetupEvaluationMethod();
}
/// <summary>
/// Constructor for unary operators and type converters
/// </summary>
/// <param name="key"></param>
/// <param name="type"></param>
/// <param name="method"></param>
public OperatorImplementation(OperatorDispatchKey key, Type type, UnaryOperatorMethod method)
{
this.Key = key;
this.CommonType = type;
this.Arg1Converter = method;
this.Arg2Converter = null;
this.ResultConverter = null;
this.BaseBinaryMethod = null;
}
public void SetupEvaluationMethod()
{
if (this.BaseBinaryMethod == null)
// Special case - it is unary method, the method itself in Arg1Converter;
// LanguageRuntime.ExecuteUnaryOperator will handle this properly
return;
// Binary operator
if (this.ResultConverter == null)
{
// Without ResultConverter
if (this.Arg1Converter == null && this.Arg2Converter == null)
this.EvaluateBinary = this.EvaluateConvNone;
else if (this.Arg1Converter != null && this.Arg2Converter == null)
this.EvaluateBinary = this.EvaluateConvLeft;
else if (this.Arg1Converter == null && this.Arg2Converter != null)
this.EvaluateBinary = this.EvaluateConvRight;
else // if (this.Arg1Converter != null && this.Arg2Converter != null)
this.EvaluateBinary = this.EvaluateConvBoth;
}
else
{
// With result converter
if (this.Arg1Converter == null && this.Arg2Converter == null)
this.EvaluateBinary = this.EvaluateConvNoneConvResult;
else if (this.Arg1Converter != null && this.Arg2Converter == null)
this.EvaluateBinary = this.EvaluateConvLeftConvResult;
else if (this.Arg1Converter == null && this.Arg2Converter != null)
this.EvaluateBinary = this.EvaluateConvRightConvResult;
else // if (this.Arg1Converter != null && this.Arg2Converter != null)
this.EvaluateBinary = this.EvaluateConvBothConvResult;
}
}
public override string ToString()
{
return "[OpImpl for " + Key.ToString() + "]";
}
private object EvaluateConvBoth(object arg1, object arg2)
{
return this.BaseBinaryMethod(this.Arg1Converter(arg1), this.Arg2Converter(arg2));
}
private object EvaluateConvBothConvResult(object arg1, object arg2)
{
return this.ResultConverter(this.BaseBinaryMethod(this.Arg1Converter(arg1), this.Arg2Converter(arg2)));
}
private object EvaluateConvLeft(object arg1, object arg2)
{
return this.BaseBinaryMethod(this.Arg1Converter(arg1), arg2);
}
private object EvaluateConvLeftConvResult(object arg1, object arg2)
{
return this.ResultConverter(this.BaseBinaryMethod(this.Arg1Converter(arg1), arg2));
}
private object EvaluateConvNone(object arg1, object arg2)
{
return this.BaseBinaryMethod(arg1, arg2);
}
private object EvaluateConvNoneConvResult(object arg1, object arg2)
{
return this.ResultConverter(this.BaseBinaryMethod(arg1, arg2));
}
private object EvaluateConvRight(object arg1, object arg2)
{
return this.BaseBinaryMethod(arg1, this.Arg2Converter(arg2));
}
private object EvaluateConvRightConvResult(object arg1, object arg2)
{
return this.ResultConverter(this.BaseBinaryMethod(arg1, this.Arg2Converter(arg2)));
}
}
public class OperatorImplementationTable : Dictionary<OperatorDispatchKey, OperatorImplementation>
{
public OperatorImplementationTable(int capacity) : base(capacity, OperatorDispatchKey.Comparer)
{ }
}
public class TypeConverterTable : Dictionary<OperatorDispatchKey, UnaryOperatorMethod>
{
public TypeConverterTable(int capacity) : base(capacity, OperatorDispatchKey.Comparer)
{ }
}
}
| |
#region Using Directives
#endregion
namespace SPALM.SPSF.Library.Actions
{
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.Design;
using System.IO;
using System.Text;
using EnvDTE;
using Microsoft.Practices.Common.Services;
using Microsoft.Practices.ComponentModel;
using Microsoft.Practices.RecipeFramework;
using Microsoft.Practices.RecipeFramework.Services;
using Microsoft.Practices.RecipeFramework.VisualStudio.Library.Templates;
using Microsoft.VisualStudio.SharePoint;
/// <summary>
/// Base Action which adds an item to VS
/// </summary>
[ServiceDependency(typeof(DTE))]
public class BaseItemAction : BaseAction
{
public BaseItemAction() : base()
{
}
/// <summary>
/// template file name in the templates folder of SPSF
/// </summary>
[Input(Required = false)]
public string SourceFileName { get; set; }
/// <summary>
/// template file name in the templates folder of SPSF
/// </summary>
[Input(Required = false)]
public string TargetFolder { get; set; }
/// <summary>
/// if true the created file will be opened after creation
/// </summary>
[Input(Required = false)]
public bool Open { get; set; }
/// <summary>
/// if true the created file will be overwritten
/// </summary>
[Input(Required = false)]
public bool Overwrite { get; set; }
/// <summary>
/// Adds the item to ParentProjectItem
/// </summary>
public override void Execute()
{
if (ExcludeCondition)
{
return;
}
if (!AdditionalCondition)
{
}
DTE dte = (DTE)this.GetService(typeof(DTE));
Project project = this.GetTargetProject(dte);
if (SourceFileName.Contains(";"))
{
string evaluatedDeploymentPath = EvaluateParameterAsString(dte, DeploymentPath);
char[] sep = new char[] { ';' };
string[] allFiles = SourceFileName.Split(sep);
foreach(string file in allFiles)
{
string fullFileName = file;
fullFileName = fullFileName.Trim();
if (!string.IsNullOrEmpty(fullFileName))
{
string sourceFilePath = fullFileName;
AddFileInternal(dte, project, sourceFilePath, "", evaluatedDeploymentPath);
}
}
}
else
{
string evaluatedTargetFileName = EvaluateParameterAsString(dte, TargetFileName);
string evaluatedSourceFileName = EvaluateParameterAsString(dte, SourceFileName);
string evaluatedDeploymentPath = EvaluateParameterAsString(dte, DeploymentPath);
AddFileInternal(dte, project, evaluatedSourceFileName, evaluatedTargetFileName, evaluatedDeploymentPath);
}
}
internal string GenerateContent(string templateFilename, string targetFilename)
{
return GenerateContent(templateFilename, targetFilename, new NameValueCollection());
}
internal string GenerateContent(string templateFilename, string targetFilename, NameValueCollection overrideArguments)
{
DTE vs = this.GetService<DTE>(true);
string templateCode = string.Empty;
if (templateFilename == null)
{
throw new ArgumentNullException("Template");
}
string templateBasePath = this.GetTemplateBasePath();
if (!Path.IsPathRooted(templateFilename))
{
templateFilename = Path.Combine(templateBasePath, templateFilename);
}
if (!File.Exists(templateFilename))
{
throw new FileNotFoundException(templateFilename);
}
templateFilename = new FileInfo(templateFilename).FullName;
if (!templateFilename.StartsWith(templateBasePath))
{
throw new ArgumentException("Starts not with " + templateBasePath);
}
templateCode = File.ReadAllText(templateFilename);
//jetzt alle properties rein
StringBuilder templateCodeLines = new StringBuilder();
StringReader reader = new StringReader(templateCode);
string line = "";
bool firstlinefound = false;
bool itemadded = false;
while ((line = reader.ReadLine()) != null)
{
if (firstlinefound && !itemadded)
{
itemadded = true;
AddTargetFileNameArgument(templateCodeLines, targetFilename);
AddAllArguments(templateCodeLines, overrideArguments);
}
if (line.StartsWith("<#@ template language="))
{
firstlinefound = true;
}
templateCodeLines.AppendLine(line);
}
return this.Render(templateCodeLines.ToString(), templateFilename);
}
private void AddTargetFileNameArgument(StringBuilder templateCodeLines, string targetFilename)
{
if (!string.IsNullOrEmpty(targetFilename))
{
//remove existing value for generatefilename
if (base.additionalArguments.Contains("GeneratedFileName"))
{
base.additionalArguments.Remove("GeneratedFileName");
}
base.additionalArguments.Add("GeneratedFileName", targetFilename);
templateCodeLines.AppendLine("<#@ property processor=\"PropertyProcessor\" name=\"GeneratedFileName\" #>");
}
}
/// <summary>
/// Adds all arguments to the template code and adds all arguments with values to the arguments list
/// </summary>
/// <param name="templateCodeLines"></param>
private void AddAllArguments(StringBuilder templateCodeLines, NameValueCollection overrideArguments)
{
IDictionaryService dictionaryService = GetService<IDictionaryService>();
IConfigurationService b = (IConfigurationService)GetService(typeof(IConfigurationService));
Microsoft.Practices.RecipeFramework.Configuration.Recipe recipe = b.CurrentRecipe;
foreach (Microsoft.Practices.RecipeFramework.Configuration.Argument argument in recipe.Arguments)
{
if (!argument.Type.StartsWith("EnvDTE", StringComparison.InvariantCultureIgnoreCase))
{
object currentValue = dictionaryService.GetValue(argument.Name);
//is there a override for this key
if (overrideArguments[argument.Name] != null)
{
currentValue = overrideArguments[argument.Name];
if (!base.additionalArguments.Contains(argument.Name))
{
base.additionalArguments.Add(argument.Name, currentValue);
}
else
{
//force override of that value
base.additionalArguments[argument.Name] = currentValue;
}
}
else
{
if (!base.additionalArguments.Contains(argument.Name))
{
base.additionalArguments.Add(argument.Name, currentValue);
}
}
templateCodeLines.AppendLine("<#@ property processor=\"PropertyProcessor\" name=\"" + argument.Name + "\" #>");
}
}
templateCodeLines.AppendLine("<#@ assembly name=\"System.dll\" #>");
templateCodeLines.AppendLine("<#@ assembly name=\"SPALM.SPSF.Library.dll\" #>");
templateCodeLines.AppendLine("<#@ import namespace=\"SPALM.SPSF.Library\" #>");
}
private string Render(string templateCode, string templateFile)
{
DTE vs = this.GetService<DTE>(true);
string basePath = this.GetBasePath();
Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngine engine = new Microsoft.VisualStudio.TextTemplating.Engine();
IValueInfoService service = (IValueInfoService)this.GetService(typeof(IValueInfoService));
Dictionary<string, PropertyData> arguments = new Dictionary<string, PropertyData>();
foreach (string str2 in base.additionalArguments.Keys)
{
Type type = null;
try
{
type = service.GetInfo(str2).Type;
}
catch (ArgumentException)
{
if (base.additionalArguments[str2] != null)
{
type = base.additionalArguments[str2].GetType();
}
else
{
continue;
}
}
PropertyData data = new PropertyData(base.additionalArguments[str2], type);
arguments.Add(str2, data);
}
TemplateHost host = new TemplateHost(basePath, arguments);
host.TemplateFile = templateFile;
Helpers.LogMessage(vs, this, templateFile);
string str3 = engine.ProcessTemplate(templateCode, host);
if (host.Errors.HasErrors)
{
string errors = "";
foreach (CompilerError error in host.Errors)
{
Helpers.LogMessage(vs, this, error.ErrorText);
errors += error.ErrorText + Environment.NewLine;
}
throw new TemplateException(host.Errors);
}
if (host.Errors.HasWarnings)
{
StringBuilder builder = new StringBuilder();
foreach (CompilerError error in host.Errors)
{
builder.AppendLine(error.ErrorText);
}
//Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "CompilationWarnings", new object[] { templateFile, builder.ToString() }));
}
return str3;
}
private void AddFileInternal(DTE dte, Project project, string evaluatedSourceFileName, string evaluatedTargetFileName, string evaluatedDeploymentPath)
{
if (!Path.IsPathRooted(evaluatedSourceFileName))
{
evaluatedSourceFileName = Path.Combine(GetTemplateBasePath(), evaluatedSourceFileName);
}
//ok, check the parameters
if (!File.Exists(evaluatedSourceFileName))
{
//ignore this action if no source file is found, used e.g. in contenttype when no file is given
return;
}
if (string.IsNullOrEmpty(evaluatedTargetFileName))
{
evaluatedTargetFileName = Path.GetFileName(evaluatedSourceFileName);
}
//targetfolder specified, find the project item
if (!string.IsNullOrEmpty(TargetFolder) && (ParentProjectFolder == null))
{
//overwrite target folder
ParentProjectFolder = Helpers.GetFolder(project, TargetFolder, true);
CreatedProjectFolder = this.ParentProjectFolder;
}
if (Helpers2.IsSharePointVSTemplate(dte, project))
{
if (this.ParentProjectItem != null)
{
//used to add code files to a parent file
CreatedProjectItem = Helpers.AddFromTemplate(ParentProjectItem.ProjectItems, evaluatedSourceFileName, evaluatedTargetFileName, Overwrite);
if (DeploymentTypeIsSet)
{
SetDeploymentPath(dte, project, CreatedProjectItem, this.DeploymentType, evaluatedDeploymentPath);
}
}
else if (this.ParentProjectFolder != null)
{
//we place the file directly in the given folder
//and mapped the item to the deployment location
CreatedProjectItem = Helpers.AddFromTemplate(this.ParentProjectFolder.ProjectItems, evaluatedSourceFileName, evaluatedTargetFileName, Overwrite);
if (DeploymentTypeIsSet)
{
SetDeploymentPath(dte, project, CreatedProjectItem, this.DeploymentType, evaluatedDeploymentPath);
}
}
else if (DeploymentTypeIsSet)
{
//place the file in a mapped folder
ProjectItems whereToAdd = Helpers2.GetDeploymentPath(dte, project, this.DeploymentType, evaluatedDeploymentPath);
CreatedProjectItem = Helpers.AddFromTemplate(whereToAdd, evaluatedSourceFileName, evaluatedTargetFileName, Overwrite);
//do not set the deploymentpath as we already placed the file in the mapped folder location
}
else if (project != null)
{
CreatedProjectItem = Helpers.AddFromTemplate(project.ProjectItems, evaluatedSourceFileName, evaluatedTargetFileName, Overwrite);
}
else
{
throw new Exception("Don't know where to place the file");
}
}
if (CreatedProjectItem != null)
{
//set the build action
if (CreatedProjectItem.Name.EndsWith(".resx", StringComparison.InvariantCultureIgnoreCase))
{
CreatedProjectItem.Properties.Item("BuildAction").Value = 2;
}
}
if (this.Open)
{
if (this.CreatedProjectItem != null)
{
Window window = this.CreatedProjectItem.Open("{00000000-0000-0000-0000-000000000000}");
window.Visible = true;
window.Activate();
}
}
}
private void SetDeploymentPath(DTE dte, Project project, ProjectItem CreatedProjectItem, SPFileType sPFileType, string evaluatedDeploymentPath)
{
//set to content
if ((sPFileType != SPFileType.CustomCode))
{
CreatedProjectItem.Properties.Item("BuildAction").Value = 2;
}
//ok, file is placed, but we need set the deployment path
ISharePointProjectService projectService = Helpers2.GetSharePointProjectService(dte);
ISharePointProject sharePointProject = projectService.Convert<Project, ISharePointProject>(project);
sharePointProject.Synchronize();
if (CreatedProjectItem.Collection.Parent is ProjectItem)
{
ProjectItem parentItem = CreatedProjectItem.Collection.Parent as ProjectItem;
string name = parentItem.Name;
//is the parent element a feature?
try
{
ISharePointProjectFeature parentIsFeature = projectService.Convert<ProjectItem, ISharePointProjectFeature>(parentItem);
if (parentIsFeature != null)
{
ISharePointProjectItem addedSharePointItem = projectService.Convert<ProjectItem, ISharePointProjectItem>(CreatedProjectItem);
if (addedSharePointItem != null)
{
parentIsFeature.ProjectItems.Add(addedSharePointItem);
}
}
}
catch { }
}
try
{
//sometimes property deploymentpath is readonly
//1. new added items need to be validated before
ISharePointProjectItemFile newaddedSharePointItem = projectService.Convert<ProjectItem, ISharePointProjectItemFile>(CreatedProjectItem);
newaddedSharePointItem.DeploymentType = Helpers2.GetDeploymentTypeFromFileType(this.DeploymentType);
if (!string.IsNullOrEmpty(evaluatedDeploymentPath))
{
newaddedSharePointItem.DeploymentPath = evaluatedDeploymentPath;
}
}
catch { }
}
public override void Undo()
{
//in error case try delete dummy file
Helpers2.DeleteDummyFile((DTE)this.GetService(typeof(DTE)), null, false);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace SemVer
{
internal static class Desugarer
{
private const string versionChars = @"[0-9a-zA-Z\-\+\.\*]";
// Allows patch-level changes if a minor version is specified
// on the comparator. Allows minor-level changes if not.
public static Tuple<int, Comparator[]> TildeRange(string spec)
{
string pattern = String.Format(@"^\s*~\s*({0}+)\s*", versionChars);
var regex = new Regex(pattern);
var match = regex.Match(spec);
if (!match.Success)
{
return null;
}
Version minVersion = null;
Version maxVersion = null;
var version = new PartialVersion(match.Groups[1].Value);
if (version.Minor.HasValue)
{
// Doesn't matter whether patch version is null or not,
// the logic is the same, min patch version will be zero if null.
minVersion = version.ToZeroVersion();
maxVersion = new Version(version.Major.Value, version.Minor.Value + 1, 0);
}
else
{
minVersion = version.ToZeroVersion();
maxVersion = new Version(version.Major.Value + 1, 0, 0);
}
return Tuple.Create(
match.Length,
minMaxComparators(minVersion, maxVersion));
}
// Allows changes that do not modify the left-most non-zero digit
// in the [major, minor, patch] tuple.
public static Tuple<int, Comparator[]> CaretRange(string spec)
{
string pattern = String.Format(@"^\s*\^\s*({0}+)\s*", versionChars);
var regex = new Regex(pattern);
var match = regex.Match(spec);
if (!match.Success)
{
return null;
}
Version minVersion = null;
Version maxVersion = null;
var version = new PartialVersion(match.Groups[1].Value);
if (version.Major.Value > 0)
{
// Don't allow major version change
minVersion = version.ToZeroVersion();
maxVersion = new Version(version.Major.Value + 1, 0, 0);
}
else if (!version.Minor.HasValue)
{
// Don't allow major version change, even if it's zero
minVersion = version.ToZeroVersion();
maxVersion = new Version(version.Major.Value + 1, 0, 0);
}
else if (!version.Patch.HasValue)
{
// Don't allow minor version change, even if it's zero
minVersion = version.ToZeroVersion();
maxVersion = new Version(0, version.Minor.Value + 1, 0);
}
else if (version.Minor > 0)
{
// Don't allow minor version change
minVersion = version.ToZeroVersion();
maxVersion = new Version(0, version.Minor.Value + 1, 0);
}
else
{
// Only patch non-zero, don't allow patch change
minVersion = version.ToZeroVersion();
maxVersion = new Version(0, 0, version.Patch.Value + 1);
}
return Tuple.Create(
match.Length,
minMaxComparators(minVersion, maxVersion));
}
public static Tuple<int, Comparator[]> HyphenRange(string spec)
{
string pattern = String.Format(@"^\s*({0}+)\s+\-\s+({0}+)\s*", versionChars);
var regex = new Regex(pattern);
var match = regex.Match(spec);
if (!match.Success)
{
return null;
}
PartialVersion minPartialVersion = null;
PartialVersion maxPartialVersion = null;
// Parse versions from lower and upper ranges, which might
// be partial versions.
try
{
minPartialVersion = new PartialVersion(match.Groups[1].Value);
maxPartialVersion = new PartialVersion(match.Groups[2].Value);
}
catch (ArgumentException)
{
return null;
}
// Lower range has any non-supplied values replaced with zero
var minVersion = minPartialVersion.ToZeroVersion();
Comparator.Operator maxOperator = maxPartialVersion.IsFull()
? Comparator.Operator.LessThanOrEqual : Comparator.Operator.LessThan;
Version maxVersion = null;
// Partial upper range means supplied version values can't change
if (!maxPartialVersion.Major.HasValue)
{
// eg. upper range = "*", then maxVersion remains null
// and there's only a minimum
}
else if (!maxPartialVersion.Minor.HasValue)
{
maxVersion = new Version(maxPartialVersion.Major.Value + 1, 0, 0);
}
else if (!maxPartialVersion.Patch.HasValue)
{
maxVersion = new Version(maxPartialVersion.Major.Value, maxPartialVersion.Minor.Value + 1, 0);
}
else
{
// Fully specified max version
maxVersion = maxPartialVersion.ToZeroVersion();
}
return Tuple.Create(
match.Length,
minMaxComparators(minVersion, maxVersion, maxOperator));
}
public static Tuple<int, Comparator[]> StarRange(string spec)
{
// Also match with an equals sign, eg. "=0.7.x"
string pattern = String.Format(@"^\s*=?\s*({0}+)\s*", versionChars);
var regex = new Regex(pattern);
var match = regex.Match(spec);
if (!match.Success)
{
return null;
}
PartialVersion version = null;
try
{
version = new PartialVersion(match.Groups[1].Value);
}
catch (ArgumentException)
{
return null;
}
// If partial version match is actually a full version,
// then this isn't a star range, so return null.
if (version.IsFull())
{
return null;
}
Version minVersion = null;
Version maxVersion = null;
if (!version.Major.HasValue)
{
minVersion = version.ToZeroVersion();
// no max version
}
else if (!version.Minor.HasValue)
{
minVersion = version.ToZeroVersion();
maxVersion = new Version(version.Major.Value + 1, 0, 0);
}
else
{
minVersion = version.ToZeroVersion();
maxVersion = new Version(version.Major.Value, version.Minor.Value + 1, 0);
}
return Tuple.Create(
match.Length,
minMaxComparators(minVersion, maxVersion));
}
private static Comparator[] minMaxComparators(Version minVersion, Version maxVersion,
Comparator.Operator maxOperator=Comparator.Operator.LessThan)
{
var minComparator = new Comparator(
Comparator.Operator.GreaterThanOrEqual,
minVersion);
if (maxVersion == null)
{
return new [] { minComparator };
}
else
{
var maxComparator = new Comparator(
maxOperator, maxVersion);
return new [] { minComparator, maxComparator };
}
}
}
}
| |
namespace ShellTools
{
partial class FileRenameForm
{
/// <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()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FileRenameForm));
this.toolTip = new System.Windows.Forms.ToolTip(this.components);
this.previewButton = new System.Windows.Forms.Button();
this.folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog();
this.errorProvider = new System.Windows.Forms.ErrorProvider(this.components);
this.matchRegexTextBox = new System.Windows.Forms.RichTextBox();
this.replaceTextBox = new System.Windows.Forms.RichTextBox();
this.renameTabControl = new System.Windows.Forms.TabControl();
this.matchTabPage = new System.Windows.Forms.TabPage();
this.folderLabel = new System.Windows.Forms.Label();
this.folderTextBox = new System.Windows.Forms.TextBox();
this.browseFolderButton = new System.Windows.Forms.Button();
this.matchRegexLabel = new System.Windows.Forms.Label();
this.replaceLabel = new System.Windows.Forms.Label();
this.resultTabPage = new System.Windows.Forms.TabPage();
this.resultDataGridView = new System.Windows.Forms.DataGridView();
this.folderDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.renameButton = new System.Windows.Forms.Button();
this.cancelButton = new System.Windows.Forms.Button();
this.renameBackgroundWorker = new System.ComponentModel.BackgroundWorker();
this.renameStatusStrip = new System.Windows.Forms.StatusStrip();
this.toolStripStatusLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStripProgressBar = new System.Windows.Forms.ToolStripProgressBar();
this.mainMenuStrip = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.newToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.editToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.undoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.redoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.cutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pasteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
this.selectAllToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.ignoreCaseToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.includeSubfoldersToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.originalNameDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.newNameDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.resultBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
((System.ComponentModel.ISupportInitialize)(this.errorProvider)).BeginInit();
this.renameTabControl.SuspendLayout();
this.matchTabPage.SuspendLayout();
this.resultTabPage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.resultDataGridView)).BeginInit();
this.renameStatusStrip.SuspendLayout();
this.mainMenuStrip.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.resultBindingSource)).BeginInit();
this.SuspendLayout();
//
// previewButton
//
this.previewButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.previewButton.Location = new System.Drawing.Point(8, 277);
this.previewButton.Name = "previewButton";
this.previewButton.Size = new System.Drawing.Size(75, 23);
this.previewButton.TabIndex = 1;
this.previewButton.Text = "&Preview";
this.toolTip.SetToolTip(this.previewButton, "Preview the file rename");
this.previewButton.UseVisualStyleBackColor = true;
this.previewButton.Click += new System.EventHandler(this.previewButton_Click);
//
// errorProvider
//
this.errorProvider.ContainerControl = this;
//
// matchRegexTextBox
//
this.matchRegexTextBox.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.matchRegexTextBox.Font = new System.Drawing.Font("Lucida Console", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.errorProvider.SetIconAlignment(this.matchRegexTextBox, System.Windows.Forms.ErrorIconAlignment.TopRight);
this.matchRegexTextBox.Location = new System.Drawing.Point(8, 71);
this.matchRegexTextBox.Name = "matchRegexTextBox";
this.matchRegexTextBox.Size = new System.Drawing.Size(376, 73);
this.matchRegexTextBox.TabIndex = 4;
this.matchRegexTextBox.Text = "";
//
// replaceTextBox
//
this.replaceTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.replaceTextBox.Font = new System.Drawing.Font("Lucida Console", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.errorProvider.SetIconAlignment(this.replaceTextBox, System.Windows.Forms.ErrorIconAlignment.TopRight);
this.replaceTextBox.Location = new System.Drawing.Point(8, 168);
this.replaceTextBox.Name = "replaceTextBox";
this.replaceTextBox.Size = new System.Drawing.Size(376, 39);
this.replaceTextBox.TabIndex = 6;
this.replaceTextBox.Text = "";
//
// renameTabControl
//
this.renameTabControl.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.renameTabControl.Controls.Add(this.matchTabPage);
this.renameTabControl.Controls.Add(this.resultTabPage);
this.renameTabControl.Location = new System.Drawing.Point(4, 27);
this.renameTabControl.Name = "renameTabControl";
this.renameTabControl.SelectedIndex = 0;
this.renameTabControl.Size = new System.Drawing.Size(426, 244);
this.renameTabControl.TabIndex = 0;
//
// matchTabPage
//
this.matchTabPage.Controls.Add(this.folderLabel);
this.matchTabPage.Controls.Add(this.folderTextBox);
this.matchTabPage.Controls.Add(this.browseFolderButton);
this.matchTabPage.Controls.Add(this.matchRegexLabel);
this.matchTabPage.Controls.Add(this.matchRegexTextBox);
this.matchTabPage.Controls.Add(this.replaceLabel);
this.matchTabPage.Controls.Add(this.replaceTextBox);
this.matchTabPage.Location = new System.Drawing.Point(4, 22);
this.matchTabPage.Name = "matchTabPage";
this.matchTabPage.Padding = new System.Windows.Forms.Padding(3);
this.matchTabPage.Size = new System.Drawing.Size(418, 218);
this.matchTabPage.TabIndex = 0;
this.matchTabPage.Text = "Match";
this.matchTabPage.UseVisualStyleBackColor = true;
//
// folderLabel
//
this.folderLabel.AutoSize = true;
this.folderLabel.Location = new System.Drawing.Point(7, 13);
this.folderLabel.Name = "folderLabel";
this.folderLabel.Size = new System.Drawing.Size(39, 13);
this.folderLabel.TabIndex = 0;
this.folderLabel.Text = "&Folder:";
//
// folderTextBox
//
this.folderTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.folderTextBox.Location = new System.Drawing.Point(8, 30);
this.folderTextBox.Name = "folderTextBox";
this.folderTextBox.Size = new System.Drawing.Size(376, 20);
this.folderTextBox.TabIndex = 1;
//
// browseFolderButton
//
this.browseFolderButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.browseFolderButton.Location = new System.Drawing.Point(388, 28);
this.browseFolderButton.Name = "browseFolderButton";
this.browseFolderButton.Size = new System.Drawing.Size(24, 22);
this.browseFolderButton.TabIndex = 2;
this.browseFolderButton.Text = "...";
this.browseFolderButton.UseVisualStyleBackColor = true;
this.browseFolderButton.Click += new System.EventHandler(this.browseFolderButton_Click);
//
// matchRegexLabel
//
this.matchRegexLabel.AutoSize = true;
this.matchRegexLabel.Location = new System.Drawing.Point(7, 54);
this.matchRegexLabel.Name = "matchRegexLabel";
this.matchRegexLabel.Size = new System.Drawing.Size(134, 13);
this.matchRegexLabel.TabIndex = 3;
this.matchRegexLabel.Text = "&Match Regular Expression:";
//
// replaceLabel
//
this.replaceLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.replaceLabel.AutoSize = true;
this.replaceLabel.Location = new System.Drawing.Point(7, 151);
this.replaceLabel.Name = "replaceLabel";
this.replaceLabel.Size = new System.Drawing.Size(87, 13);
this.replaceLabel.TabIndex = 5;
this.replaceLabel.Text = "&Replace Pattern:";
//
// resultTabPage
//
this.resultTabPage.Controls.Add(this.resultDataGridView);
this.resultTabPage.Location = new System.Drawing.Point(4, 22);
this.resultTabPage.Name = "resultTabPage";
this.resultTabPage.Padding = new System.Windows.Forms.Padding(3);
this.resultTabPage.Size = new System.Drawing.Size(418, 218);
this.resultTabPage.TabIndex = 1;
this.resultTabPage.Text = "Results";
this.resultTabPage.UseVisualStyleBackColor = true;
//
// resultDataGridView
//
this.resultDataGridView.AllowUserToAddRows = false;
this.resultDataGridView.AllowUserToDeleteRows = false;
this.resultDataGridView.AllowUserToResizeRows = false;
this.resultDataGridView.AutoGenerateColumns = false;
this.resultDataGridView.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells;
this.resultDataGridView.BackgroundColor = System.Drawing.SystemColors.Window;
this.resultDataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.resultDataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.originalNameDataGridViewTextBoxColumn,
this.newNameDataGridViewTextBoxColumn,
this.folderDataGridViewTextBoxColumn});
this.resultDataGridView.DataSource = this.resultBindingSource;
this.resultDataGridView.Dock = System.Windows.Forms.DockStyle.Fill;
this.resultDataGridView.Location = new System.Drawing.Point(3, 3);
this.resultDataGridView.MultiSelect = false;
this.resultDataGridView.Name = "resultDataGridView";
this.resultDataGridView.ReadOnly = true;
this.resultDataGridView.RowHeadersVisible = false;
this.resultDataGridView.Size = new System.Drawing.Size(412, 212);
this.resultDataGridView.TabIndex = 0;
//
// folderDataGridViewTextBoxColumn
//
this.folderDataGridViewTextBoxColumn.DataPropertyName = "Folder";
this.folderDataGridViewTextBoxColumn.HeaderText = "Folder";
this.folderDataGridViewTextBoxColumn.Name = "folderDataGridViewTextBoxColumn";
this.folderDataGridViewTextBoxColumn.ReadOnly = true;
this.folderDataGridViewTextBoxColumn.Width = 61;
//
// renameButton
//
this.renameButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.renameButton.Location = new System.Drawing.Point(270, 277);
this.renameButton.Name = "renameButton";
this.renameButton.Size = new System.Drawing.Size(75, 23);
this.renameButton.TabIndex = 2;
this.renameButton.Text = "Re&name";
this.renameButton.UseVisualStyleBackColor = true;
this.renameButton.Click += new System.EventHandler(this.renameButton_Click);
//
// cancelButton
//
this.cancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.cancelButton.Location = new System.Drawing.Point(351, 277);
this.cancelButton.Name = "cancelButton";
this.cancelButton.Size = new System.Drawing.Size(75, 23);
this.cancelButton.TabIndex = 3;
this.cancelButton.Text = "&Cancel";
this.cancelButton.UseVisualStyleBackColor = true;
this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click);
//
// renameBackgroundWorker
//
this.renameBackgroundWorker.WorkerReportsProgress = true;
this.renameBackgroundWorker.WorkerSupportsCancellation = true;
this.renameBackgroundWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(this.renameBackgroundWorker_DoWork);
this.renameBackgroundWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.renameBackgroundWorker_RunWorkerCompleted);
this.renameBackgroundWorker.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.renameBackgroundWorker_ProgressChanged);
//
// renameStatusStrip
//
this.renameStatusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripStatusLabel,
this.toolStripProgressBar});
this.renameStatusStrip.Location = new System.Drawing.Point(0, 313);
this.renameStatusStrip.Name = "renameStatusStrip";
this.renameStatusStrip.Size = new System.Drawing.Size(434, 22);
this.renameStatusStrip.TabIndex = 4;
//
// toolStripStatusLabel
//
this.toolStripStatusLabel.Name = "toolStripStatusLabel";
this.toolStripStatusLabel.Size = new System.Drawing.Size(317, 17);
this.toolStripStatusLabel.Spring = true;
this.toolStripStatusLabel.Text = "Ready";
this.toolStripStatusLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// toolStripProgressBar
//
this.toolStripProgressBar.Name = "toolStripProgressBar";
this.toolStripProgressBar.Size = new System.Drawing.Size(100, 16);
//
// mainMenuStrip
//
this.mainMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.editToolStripMenuItem,
this.toolsToolStripMenuItem});
this.mainMenuStrip.Location = new System.Drawing.Point(0, 0);
this.mainMenuStrip.Name = "mainMenuStrip";
this.mainMenuStrip.Size = new System.Drawing.Size(434, 24);
this.mainMenuStrip.TabIndex = 5;
this.mainMenuStrip.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.newToolStripMenuItem,
this.openToolStripMenuItem,
this.saveToolStripMenuItem,
this.toolStripSeparator1,
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
this.fileToolStripMenuItem.Text = "&File";
//
// newToolStripMenuItem
//
this.newToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("newToolStripMenuItem.Image")));
this.newToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.newToolStripMenuItem.Name = "newToolStripMenuItem";
this.newToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N)));
this.newToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.newToolStripMenuItem.Text = "&New";
this.newToolStripMenuItem.Click += new System.EventHandler(this.newToolStripMenuItem_Click);
//
// openToolStripMenuItem
//
this.openToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("openToolStripMenuItem.Image")));
this.openToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.openToolStripMenuItem.Name = "openToolStripMenuItem";
this.openToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O)));
this.openToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.openToolStripMenuItem.Text = "&Open";
this.openToolStripMenuItem.Click += new System.EventHandler(this.openToolStripMenuItem_Click);
//
// saveToolStripMenuItem
//
this.saveToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("saveToolStripMenuItem.Image")));
this.saveToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.saveToolStripMenuItem.Name = "saveToolStripMenuItem";
this.saveToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S)));
this.saveToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.saveToolStripMenuItem.Text = "&Save";
this.saveToolStripMenuItem.Click += new System.EventHandler(this.saveToolStripMenuItem_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(149, 6);
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.exitToolStripMenuItem.Text = "E&xit";
this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
//
// editToolStripMenuItem
//
this.editToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.undoToolStripMenuItem,
this.redoToolStripMenuItem,
this.toolStripSeparator3,
this.cutToolStripMenuItem,
this.copyToolStripMenuItem,
this.pasteToolStripMenuItem,
this.toolStripSeparator4,
this.selectAllToolStripMenuItem});
this.editToolStripMenuItem.Name = "editToolStripMenuItem";
this.editToolStripMenuItem.Size = new System.Drawing.Size(39, 20);
this.editToolStripMenuItem.Text = "&Edit";
//
// undoToolStripMenuItem
//
this.undoToolStripMenuItem.Name = "undoToolStripMenuItem";
this.undoToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Z)));
this.undoToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.undoToolStripMenuItem.Text = "&Undo";
this.undoToolStripMenuItem.Click += new System.EventHandler(this.undoToolStripMenuItem_Click);
//
// redoToolStripMenuItem
//
this.redoToolStripMenuItem.Name = "redoToolStripMenuItem";
this.redoToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Y)));
this.redoToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.redoToolStripMenuItem.Text = "&Redo";
this.redoToolStripMenuItem.Click += new System.EventHandler(this.redoToolStripMenuItem_Click);
//
// toolStripSeparator3
//
this.toolStripSeparator3.Name = "toolStripSeparator3";
this.toolStripSeparator3.Size = new System.Drawing.Size(149, 6);
//
// cutToolStripMenuItem
//
this.cutToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("cutToolStripMenuItem.Image")));
this.cutToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.cutToolStripMenuItem.Name = "cutToolStripMenuItem";
this.cutToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.X)));
this.cutToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.cutToolStripMenuItem.Text = "Cu&t";
this.cutToolStripMenuItem.Click += new System.EventHandler(this.cutToolStripMenuItem_Click);
//
// copyToolStripMenuItem
//
this.copyToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("copyToolStripMenuItem.Image")));
this.copyToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.copyToolStripMenuItem.Name = "copyToolStripMenuItem";
this.copyToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.C)));
this.copyToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.copyToolStripMenuItem.Text = "&Copy";
this.copyToolStripMenuItem.Click += new System.EventHandler(this.copyToolStripMenuItem_Click);
//
// pasteToolStripMenuItem
//
this.pasteToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("pasteToolStripMenuItem.Image")));
this.pasteToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.pasteToolStripMenuItem.Name = "pasteToolStripMenuItem";
this.pasteToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.V)));
this.pasteToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.pasteToolStripMenuItem.Text = "&Paste";
this.pasteToolStripMenuItem.Click += new System.EventHandler(this.pasteToolStripMenuItem_Click);
//
// toolStripSeparator4
//
this.toolStripSeparator4.Name = "toolStripSeparator4";
this.toolStripSeparator4.Size = new System.Drawing.Size(149, 6);
//
// selectAllToolStripMenuItem
//
this.selectAllToolStripMenuItem.Name = "selectAllToolStripMenuItem";
this.selectAllToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.selectAllToolStripMenuItem.Text = "Select &All";
this.selectAllToolStripMenuItem.Click += new System.EventHandler(this.selectAllToolStripMenuItem_Click);
//
// toolsToolStripMenuItem
//
this.toolsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.ignoreCaseToolStripMenuItem,
this.includeSubfoldersToolStripMenuItem});
this.toolsToolStripMenuItem.Name = "toolsToolStripMenuItem";
this.toolsToolStripMenuItem.Size = new System.Drawing.Size(48, 20);
this.toolsToolStripMenuItem.Text = "&Tools";
//
// ignoreCaseToolStripMenuItem
//
this.ignoreCaseToolStripMenuItem.Checked = true;
this.ignoreCaseToolStripMenuItem.CheckOnClick = true;
this.ignoreCaseToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked;
this.ignoreCaseToolStripMenuItem.Name = "ignoreCaseToolStripMenuItem";
this.ignoreCaseToolStripMenuItem.Size = new System.Drawing.Size(172, 22);
this.ignoreCaseToolStripMenuItem.Text = "Ignore &Case";
//
// includeSubfoldersToolStripMenuItem
//
this.includeSubfoldersToolStripMenuItem.CheckOnClick = true;
this.includeSubfoldersToolStripMenuItem.Name = "includeSubfoldersToolStripMenuItem";
this.includeSubfoldersToolStripMenuItem.Size = new System.Drawing.Size(172, 22);
this.includeSubfoldersToolStripMenuItem.Text = "Include &Subfolders";
//
// originalNameDataGridViewTextBoxColumn
//
this.originalNameDataGridViewTextBoxColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.DisplayedCells;
this.originalNameDataGridViewTextBoxColumn.DataPropertyName = "OriginalName";
this.originalNameDataGridViewTextBoxColumn.HeaderText = "OriginalName";
this.originalNameDataGridViewTextBoxColumn.Name = "originalNameDataGridViewTextBoxColumn";
this.originalNameDataGridViewTextBoxColumn.ReadOnly = true;
this.originalNameDataGridViewTextBoxColumn.Width = 95;
//
// newNameDataGridViewTextBoxColumn
//
this.newNameDataGridViewTextBoxColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.DisplayedCells;
this.newNameDataGridViewTextBoxColumn.DataPropertyName = "NewName";
this.newNameDataGridViewTextBoxColumn.HeaderText = "NewName";
this.newNameDataGridViewTextBoxColumn.Name = "newNameDataGridViewTextBoxColumn";
this.newNameDataGridViewTextBoxColumn.ReadOnly = true;
this.newNameDataGridViewTextBoxColumn.Width = 82;
//
// resultBindingSource
//
this.resultBindingSource.AllowNew = false;
this.resultBindingSource.DataSource = typeof(ShellTools.FileRenameResult);
//
// saveFileDialog
//
this.saveFileDialog.Filter = "Xml Files (*.xml)|*.xml|All Files (*.*)|*.*";
this.saveFileDialog.SupportMultiDottedExtensions = true;
this.saveFileDialog.Title = "Save Rename Settings";
//
// openFileDialog
//
this.openFileDialog.Filter = "Xml Files (*.xml)|*.xml|All Files (*.*)|*.*";
this.openFileDialog.SupportMultiDottedExtensions = true;
this.openFileDialog.Title = "Open File Rename Settings";
//
// FileRenameForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(434, 335);
this.Controls.Add(this.mainMenuStrip);
this.Controls.Add(this.renameTabControl);
this.Controls.Add(this.renameStatusStrip);
this.Controls.Add(this.previewButton);
this.Controls.Add(this.renameButton);
this.Controls.Add(this.cancelButton);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow;
this.MainMenuStrip = this.mainMenuStrip;
this.MinimumSize = new System.Drawing.Size(450, 350);
this.Name = "FileRenameForm";
this.Text = "Bulk File Rename";
this.Load += new System.EventHandler(this.FileRenameForm_Load);
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FileRenameForm_FormClosing);
((System.ComponentModel.ISupportInitialize)(this.errorProvider)).EndInit();
this.renameTabControl.ResumeLayout(false);
this.matchTabPage.ResumeLayout(false);
this.matchTabPage.PerformLayout();
this.resultTabPage.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.resultDataGridView)).EndInit();
this.renameStatusStrip.ResumeLayout(false);
this.renameStatusStrip.PerformLayout();
this.mainMenuStrip.ResumeLayout(false);
this.mainMenuStrip.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.resultBindingSource)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ToolTip toolTip;
private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog;
private System.Windows.Forms.ErrorProvider errorProvider;
private System.Windows.Forms.TabControl renameTabControl;
private System.Windows.Forms.TabPage matchTabPage;
private System.Windows.Forms.Label matchRegexLabel;
private System.Windows.Forms.RichTextBox matchRegexTextBox;
private System.Windows.Forms.Label folderLabel;
private System.Windows.Forms.TextBox folderTextBox;
private System.Windows.Forms.Button browseFolderButton;
private System.Windows.Forms.TabPage resultTabPage;
private System.Windows.Forms.Button previewButton;
private System.Windows.Forms.Button renameButton;
private System.Windows.Forms.Button cancelButton;
private System.Windows.Forms.Label replaceLabel;
private System.Windows.Forms.RichTextBox replaceTextBox;
private System.Windows.Forms.DataGridView resultDataGridView;
private System.Windows.Forms.BindingSource resultBindingSource;
private System.ComponentModel.BackgroundWorker renameBackgroundWorker;
private System.Windows.Forms.StatusStrip renameStatusStrip;
private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel;
private System.Windows.Forms.ToolStripProgressBar toolStripProgressBar;
private System.Windows.Forms.MenuStrip mainMenuStrip;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem newToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem saveToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem editToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem undoToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem redoToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
private System.Windows.Forms.ToolStripMenuItem cutToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem pasteToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator4;
private System.Windows.Forms.ToolStripMenuItem selectAllToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem toolsToolStripMenuItem;
private System.Windows.Forms.DataGridViewTextBoxColumn originalNameDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn newNameDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn folderDataGridViewTextBoxColumn;
private System.Windows.Forms.ToolStripMenuItem ignoreCaseToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem includeSubfoldersToolStripMenuItem;
private System.Windows.Forms.SaveFileDialog saveFileDialog;
private System.Windows.Forms.OpenFileDialog openFileDialog;
}
}
| |
// Authors:
// Rafael Mizrahi <rafim@mainsoft.com>
// Erez Lotan <erezl@mainsoft.com>
// Oren Gurfinkel <oreng@mainsoft.com>
// Ofer Borstein
//
// Copyright (c) 2004 Mainsoft Co.
//
// 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.Data;
using NUnit.Framework;
using GHTUtils;
using GHTUtils.Base;
using System.Text;
using System.IO;
namespace tests.system_data_dll.System_Data
{
[TestFixture]
public class DataSet_InferXmlSchema_SS : GHTBase
{
public static void Main()
{
DataSet_InferXmlSchema_SS tc = new DataSet_InferXmlSchema_SS();
Exception exp = null;
try
{
tc.BeginTest("DataSet_InferXmlSchema_SS");
tc.run();
}
catch(Exception ex)
{
exp = ex;
}
finally
{
tc.EndTest(exp);
}
}
//Activate This Construntor to log All To Standard output
//public TestClass():base(true){}
//Activate this constructor to log Failures to a log file
//public TestClass(System.IO.TextWriter tw):base(tw, false){}
//Activate this constructor to log All to a log file
//public TestClass(System.IO.TextWriter tw):base(tw, true){}
//BY DEFAULT LOGGING IS DONE TO THE STANDARD OUTPUT ONLY FOR FAILURES
public void run()
{
Exception exp = null;
try
{
BeginCase("Test inferXmlSchema full schema 1 uri");
test();
}
catch(Exception ex)
{exp = ex;}
finally{EndCase(exp); exp = null;}
try
{
BeginCase("Test inferXmlSchema full schema 1 uri that dont exists");
test1();
}
catch(Exception ex)
{exp = ex;}
finally{EndCase(exp); exp = null;}
try
{
BeginCase("Test inferXmlSchema missing schema 2 uri");
test2();
}
catch(Exception ex)
{exp = ex;}
finally{EndCase(exp); exp = null;}
try
{
BeginCase("Test inferXmlSchema mixed schema 1 uri");
test5();
}
catch(Exception ex)
{exp = ex;}
finally{EndCase(exp); exp = null;}
inferingTables1();
inferingTables2();
inferingTables3();
inferingTables4();
inferingTables5();
inferringColumns1();
inferringColumns2();
inferringRelationships1();
elementText1();
elementText2();
}
#region test namespaces
[Test]
public void test()
{
StringBuilder sb = new StringBuilder();
sb.Append("<NewDataSet xmlns:od='urn:schemas-microsoft-com:officedata'>");
sb.Append("<Categories>");
sb.Append("<CategoryID od:adotype='3'>1</CategoryID>");
sb.Append("<CategoryName od:maxLength='15' od:adotype='130'>Beverages</CategoryName>");
sb.Append("<Description od:adotype='203'>Soft drinks and teas</Description>");
sb.Append("</Categories>");
sb.Append("<Products>");
sb.Append("<ProductID od:adotype='20'>1</ProductID>");
sb.Append("<ReorderLevel od:adotype='3'>10</ReorderLevel>");
sb.Append("<Discontinued od:adotype='11'>0</Discontinued>");
sb.Append("</Products>");
sb.Append("</NewDataSet>");
MemoryStream myStream = new MemoryStream(new ASCIIEncoding().GetBytes(sb.ToString()));
DataSet ds = new DataSet();
// ds.ReadXml(myStream);
ds.InferXmlSchema(myStream, new string[] {"urn:schemas-microsoft-com:officedata"});
Compare(ds.Tables.Count,2);
Compare(ds.Tables[0].Columns[0].ColumnName,"CategoryID");
Compare(ds.Tables[0].Columns[1].ColumnName,"CategoryName");
Compare(ds.Tables[0].Columns[2].ColumnName,"Description");
Compare(ds.Tables[1].Columns[0].ColumnName,"ProductID");
Compare(ds.Tables[1].Columns[1].ColumnName,"ReorderLevel");
Compare(ds.Tables[1].Columns[2].ColumnName,"Discontinued");
}
[Test]
public void test1()
{
StringBuilder sb = new StringBuilder();
sb.Append("<NewDataSet xmlns:od='urn:schemas-microsoft-com:officedata'>");
sb.Append("<Categories>");
sb.Append("<CategoryID od:adotype='3'>1</CategoryID>");
sb.Append("<CategoryName od:maxLength='15' od:adotype='130'>Beverages</CategoryName>");
sb.Append("<Description od:adotype='203'>Soft drinks and teas</Description>");
sb.Append("</Categories>");
sb.Append("<Products>");
sb.Append("<ProductID od:adotype='20'>1</ProductID>");
sb.Append("<ReorderLevel od:adotype='3'>10</ReorderLevel>");
sb.Append("<Discontinued od:adotype='11'>0</Discontinued>");
sb.Append("</Products>");
sb.Append("</NewDataSet>");
MemoryStream myStream = new MemoryStream(new ASCIIEncoding().GetBytes(sb.ToString()));
DataSet ds = new DataSet();
//ds.ReadXml(myStream);
ds.InferXmlSchema(myStream,new string[] {"urn:schemas-microsoft-com:officedata1"});
Compare(ds.Tables.Count,8);
}
[Test]
public void test5()
{
StringBuilder sb = new StringBuilder();
sb.Append("<NewDataSet xmlns:od='urn:schemas-microsoft-com:officedata'>");
sb.Append("<Categories>");
sb.Append("<CategoryID od:adotype='3'>1</CategoryID>");
sb.Append("<CategoryName od:maxLength='15' adotype='130'>Beverages</CategoryName>");
sb.Append("<Description od:adotype='203'>Soft drinks and teas</Description>");
sb.Append("</Categories>");
sb.Append("<Products>");
sb.Append("<ProductID od:adotype='20'>1</ProductID>");
sb.Append("<ReorderLevel od:adotype='3'>10</ReorderLevel>");
sb.Append("<Discontinued od:adotype='11'>0</Discontinued>");
sb.Append("</Products>");
sb.Append("</NewDataSet>");
MemoryStream myStream = new MemoryStream(new ASCIIEncoding().GetBytes(sb.ToString()));
DataSet ds = new DataSet();
// ds.ReadXml(myStream);
ds.InferXmlSchema(myStream, new string[] {"urn:schemas-microsoft-com:officedata"});
Compare(ds.Tables.Count,3);
Compare(ds.Tables[0].Columns.Count,3);
Compare(ds.Tables[0].Columns["CategoryID"].ColumnName,"CategoryID");
Compare(ds.Tables[0].Columns["Categories_Id"].ColumnName,"Categories_Id");//Hidden
Compare(ds.Tables[0].Columns["Description"].ColumnName,"Description");
Compare(ds.Tables[1].Columns.Count,3);
Compare(ds.Tables[1].Columns["adotype"].ColumnName,"adotype");
Compare(ds.Tables[1].Columns["CategoryName_Text"].ColumnName,"CategoryName_Text");
Compare(ds.Tables[1].Columns["Categories_Id"].ColumnName,"Categories_Id");//Hidden
Compare(ds.Tables[2].Columns.Count,3);
Compare(ds.Tables[2].Columns["ProductID"].ColumnName,"ProductID");
Compare(ds.Tables[2].Columns["ReorderLevel"].ColumnName,"ReorderLevel");
Compare(ds.Tables[2].Columns["Discontinued"].ColumnName,"Discontinued");
}
[Test]
public void test2() //Ignoring 2 namespaces
{
Exception exp = null;
try
{
StringBuilder sb = new StringBuilder();
sb.Append("<h:html xmlns:xdc='http://www.xml.com/books' xmlns:h='http://www.w3.org/HTML/1998/html4'>");
sb.Append("<h:head><h:title>Book Review</h:title></h:head>");
sb.Append("<h:body>");
sb.Append("<xdc:bookreview>");
sb.Append("<xdc:title h:attrib1='1' xdc:attrib2='2' >XML: A Primer</xdc:title>");
sb.Append("</xdc:bookreview>");
sb.Append("</h:body>");
sb.Append("</h:html>");
MemoryStream myStream = new MemoryStream(new ASCIIEncoding().GetBytes(sb.ToString()));
DataSet tempDs = new DataSet();
tempDs.ReadXml(myStream);
myStream.Seek(0,SeekOrigin.Begin);
DataSet ds = new DataSet();
ds.InferXmlSchema(myStream, new string[] {"http://www.xml.com/books","http://www.w3.org/HTML/1998/html4"});
//Compare(ds.Tables.Count,8);
// string str1 = tempDs.GetXmlSchema(); //DataProvider.GetDSSchema(tempDs);
// string str2 = ds.GetXmlSchema(); //DataProvider.GetDSSchema(ds);
Compare(ds.Tables.Count,3);
Compare(ds.Tables[2].TableName,"bookreview");
Compare(ds.Tables[2].Columns.Count,2);
}
catch(Exception ex)
{exp = ex;}
}
#endregion
#region inferingTables
[Test]
public void inferingTables1()
{
//Acroding to the msdn documantaion :
//ms-help://MS.MSDNQTR.2003FEB.1033/cpguide/html/cpconinferringtables.htm
//Elements that have attributes specified in them will result in inferred tables
BeginCase("inferingTables1");
Exception exp=null;
StringBuilder sb = new StringBuilder();
sb.Append("<DocumentElement>");
sb.Append("<Element1 attr1='value1'/>");
sb.Append("<Element1 attr1='value2'>Text1</Element1>");
sb.Append("</DocumentElement>");
DataSet ds = new DataSet();
MemoryStream myStream = new MemoryStream(new ASCIIEncoding().GetBytes(sb.ToString()));
try
{
ds.InferXmlSchema(myStream,null);
Compare(ds.DataSetName,"DocumentElement");
Compare(ds.Tables[0].TableName,"Element1");
Compare(ds.Tables.Count,1);
Compare(ds.Tables[0].Columns["attr1"].ColumnName,"attr1");
Compare(ds.Tables[0].Columns["Element1_Text"].ColumnName,"Element1_Text");
}
catch (Exception ex)
{
exp = ex;
}
finally
{
EndCase(exp);
}
}
[Test]
public void inferingTables2()
{
//Acroding to the msdn documantaion :
//ms-help://MS.MSDNQTR.2003FEB.1033/cpguide/html/cpconinferringtables.htm
//Elements that have child elements will result in inferred tables
BeginCase("inferingTables2");
Exception exp=null;
StringBuilder sb = new StringBuilder();
sb.Append("<DocumentElement>");
sb.Append("<Element1>");
sb.Append("<ChildElement1>Text1</ChildElement1>");
sb.Append("</Element1>");
sb.Append("</DocumentElement>");
DataSet ds = new DataSet();
MemoryStream myStream = new MemoryStream(new ASCIIEncoding().GetBytes(sb.ToString()));
try
{
ds.InferXmlSchema(myStream,null);
Compare(ds.DataSetName,"DocumentElement");
Compare(ds.Tables[0].TableName,"Element1");
Compare(ds.Tables.Count,1);
Compare(ds.Tables[0].Columns["ChildElement1"].ColumnName,"ChildElement1");
}
catch (Exception ex)
{
exp = ex;
}
finally
{
EndCase(exp);
}
}
[Test]
public void inferingTables3()
{
//Acroding to the msdn documantaion :
//ms-help://MS.MSDNQTR.2003FEB.1033/cpguide/html/cpconinferringtables.htm
//The document, or root, element will result in an inferred table if it has attributes
//or child elements that will be inferred as columns.
//If the document element has no attributes and no child elements that would be inferred as columns, the element will be inferred as a DataSet
BeginCase("inferingTables3");
Exception exp=null;
StringBuilder sb = new StringBuilder();
sb.Append("<DocumentElement>");
sb.Append("<Element1>Text1</Element1>");
sb.Append("<Element2>Text2</Element2>");
sb.Append("</DocumentElement>");
DataSet ds = new DataSet();
MemoryStream myStream = new MemoryStream(new ASCIIEncoding().GetBytes(sb.ToString()));
try
{
ds.InferXmlSchema(myStream,null);
Compare(ds.DataSetName,"NewDataSet");
Compare(ds.Tables[0].TableName,"DocumentElement");
Compare(ds.Tables.Count,1);
Compare(ds.Tables[0].Columns["Element1"].ColumnName,"Element1");
Compare(ds.Tables[0].Columns["Element2"].ColumnName,"Element2");
}
catch (Exception ex)
{
exp = ex;
}
finally
{
EndCase(exp);
}
}
[Test]
public void inferingTables4()
{
//Acroding to the msdn documantaion :
//ms-help://MS.MSDNQTR.2003FEB.1033/cpguide/html/cpconinferringtables.htm
//The document, or root, element will result in an inferred table if it has attributes
//or child elements that will be inferred as columns.
//If the document element has no attributes and no child elements that would be inferred as columns, the element will be inferred as a DataSet
BeginCase("inferingTables4");
Exception exp=null;
StringBuilder sb = new StringBuilder();
sb.Append("<DocumentElement>");
sb.Append("<Element1 attr1='value1' attr2='value2'/>");
sb.Append("</DocumentElement>");
DataSet ds = new DataSet();
MemoryStream myStream = new MemoryStream(new ASCIIEncoding().GetBytes(sb.ToString()));
try
{
ds.InferXmlSchema(myStream,null);
Compare(ds.DataSetName,"DocumentElement");
Compare(ds.Tables[0].TableName,"Element1");
Compare(ds.Tables.Count,1);
Compare(ds.Tables[0].Columns["attr1"].ColumnName,"attr1");
Compare(ds.Tables[0].Columns["attr2"].ColumnName,"attr2");
}
catch (Exception ex)
{
exp = ex;
}
finally
{
EndCase(exp);
}
}
[Test]
public void inferingTables5()
{
//Acroding to the msdn documantaion :
//ms-help://MS.MSDNQTR.2003FEB.1033/cpguide/html/cpconinferringtables.htm
//Elements that repeat will result in a single inferred table
BeginCase("inferingTables5");
Exception exp=null;
StringBuilder sb = new StringBuilder();
sb.Append("<DocumentElement>");
sb.Append("<Element1>Text1</Element1>");
sb.Append("<Element1>Text2</Element1>");
sb.Append("</DocumentElement>");
DataSet ds = new DataSet();
MemoryStream myStream = new MemoryStream(new ASCIIEncoding().GetBytes(sb.ToString()));
try
{
ds.InferXmlSchema(myStream,null);
Compare(ds.DataSetName,"DocumentElement");
Compare(ds.Tables[0].TableName,"Element1");
Compare(ds.Tables.Count,1);
Compare(ds.Tables[0].Columns["Element1_Text"].ColumnName,"Element1_Text");
}
catch (Exception ex)
{
exp = ex;
}
finally
{
EndCase(exp);
}
}
#endregion
#region inferringColumns
[Test]
public void inferringColumns1()
{
//ms-help://MS.MSDNQTR.2003FEB.1033/cpguide/html/cpconinferringcolumns.htm
BeginCase("inferringColumns1");
Exception exp=null;
StringBuilder sb = new StringBuilder();
sb.Append("<DocumentElement>");
sb.Append("<Element1 attr1='value1' attr2='value2'/>");
sb.Append("</DocumentElement>");
DataSet ds = new DataSet();
MemoryStream myStream = new MemoryStream(new ASCIIEncoding().GetBytes(sb.ToString()));
try
{
ds.InferXmlSchema(myStream,null);
Compare(ds.DataSetName,"DocumentElement");
Compare(ds.Tables[0].TableName,"Element1");
Compare(ds.Tables.Count,1);
Compare(ds.Tables[0].Columns["attr1"].ColumnName,"attr1");
Compare(ds.Tables[0].Columns["attr2"].ColumnName,"attr2");
Compare(ds.Tables[0].Columns["attr1"].ColumnMapping ,MappingType.Attribute);
Compare(ds.Tables[0].Columns["attr2"].ColumnMapping ,MappingType.Attribute);
Compare(ds.Tables[0].Columns["attr1"].DataType ,typeof(string));
Compare(ds.Tables[0].Columns["attr2"].DataType ,typeof(string));
}
catch (Exception ex)
{
exp = ex;
}
finally
{
EndCase(exp);
}
}
[Test]
public void inferringColumns2()
{
//ms-help://MS.MSDNQTR.2003FEB.1033/cpguide/html/cpconinferringcolumns.htm
//If an element has no child elements or attributes, it will be inferred as a column.
//The ColumnMapping property of the column will be set to MappingType.Element.
//The text for child elements is stored in a row in the table
BeginCase("inferringColumns2");
Exception exp=null;
StringBuilder sb = new StringBuilder();
sb.Append("<DocumentElement>");
sb.Append("<Element1>");
sb.Append("<ChildElement1>Text1</ChildElement1>");
sb.Append("<ChildElement2>Text2</ChildElement2>");
sb.Append("</Element1>");
sb.Append("</DocumentElement>");
DataSet ds = new DataSet();
MemoryStream myStream = new MemoryStream(new ASCIIEncoding().GetBytes(sb.ToString()));
try
{
ds.InferXmlSchema(myStream,null);
Compare(ds.DataSetName,"DocumentElement");
Compare(ds.Tables[0].TableName,"Element1");
Compare(ds.Tables.Count,1);
Compare(ds.Tables[0].Columns["ChildElement1"].ColumnName,"ChildElement1");
Compare(ds.Tables[0].Columns["ChildElement2"].ColumnName,"ChildElement2");
Compare(ds.Tables[0].Columns["ChildElement1"].ColumnMapping ,MappingType.Element);
Compare(ds.Tables[0].Columns["ChildElement2"].ColumnMapping ,MappingType.Element);
Compare(ds.Tables[0].Columns["ChildElement1"].DataType ,typeof(string));
Compare(ds.Tables[0].Columns["ChildElement2"].DataType ,typeof(string));
}
catch (Exception ex)
{
exp = ex;
}
finally
{
EndCase(exp);
}
}
#endregion
#region Inferring Relationships
[Test]
public void inferringRelationships1()
{
//ms-help://MS.MSDNQTR.2003FEB.1033/cpguide/html/cpconinferringrelationships.htm
BeginCase("inferringRelationships1");
Exception exp=null;
StringBuilder sb = new StringBuilder();
sb.Append("<DocumentElement>");
sb.Append("<Element1>");
sb.Append("<ChildElement1 attr1='value1' attr2='value2'/>");
sb.Append("<ChildElement2>Text2</ChildElement2>");
sb.Append("</Element1>");
sb.Append("</DocumentElement>");
DataSet ds = new DataSet();
MemoryStream myStream = new MemoryStream(new ASCIIEncoding().GetBytes(sb.ToString()));
try
{
ds.InferXmlSchema(myStream,null);
Compare(ds.DataSetName,"DocumentElement");
Compare(ds.Tables[0].TableName,"Element1");
Compare(ds.Tables[1].TableName,"ChildElement1");
Compare(ds.Tables.Count,2);
Compare(ds.Tables["Element1"].Columns["Element1_Id"].ColumnName,"Element1_Id");
Compare(ds.Tables["Element1"].Columns["Element1_Id"].ColumnMapping ,MappingType.Hidden);
Compare(ds.Tables["Element1"].Columns["Element1_Id"].DataType ,typeof(Int32));
Compare(ds.Tables["Element1"].Columns["ChildElement2"].ColumnName,"ChildElement2");
Compare(ds.Tables["Element1"].Columns["ChildElement2"].ColumnMapping ,MappingType.Element);
Compare(ds.Tables["Element1"].Columns["ChildElement2"].DataType ,typeof(string));
Compare(ds.Tables["ChildElement1"].Columns["attr1"].ColumnName,"attr1");
Compare(ds.Tables["ChildElement1"].Columns["attr1"].ColumnMapping ,MappingType.Attribute);
Compare(ds.Tables["ChildElement1"].Columns["attr1"].DataType ,typeof(string));
Compare(ds.Tables["ChildElement1"].Columns["attr2"].ColumnName,"attr2");
Compare(ds.Tables["ChildElement1"].Columns["attr2"].ColumnMapping ,MappingType.Attribute);
Compare(ds.Tables["ChildElement1"].Columns["attr2"].DataType ,typeof(string));
Compare(ds.Tables["ChildElement1"].Columns["Element1_Id"].ColumnName,"Element1_Id");
Compare(ds.Tables["ChildElement1"].Columns["Element1_Id"].ColumnMapping ,MappingType.Hidden);
Compare(ds.Tables["ChildElement1"].Columns["Element1_Id"].DataType ,typeof(Int32));
//Checking dataRelation :
Compare(ds.Relations["Element1_ChildElement1"].ParentTable.TableName,"Element1");
Compare(ds.Relations["Element1_ChildElement1"].ParentColumns[0].ColumnName,"Element1_Id");
Compare(ds.Relations["Element1_ChildElement1"].ChildTable.TableName,"ChildElement1");
Compare(ds.Relations["Element1_ChildElement1"].ChildColumns[0].ColumnName,"Element1_Id");
Compare(ds.Relations["Element1_ChildElement1"].Nested,true);
//Checking ForeignKeyConstraint
ForeignKeyConstraint con = (ForeignKeyConstraint)ds.Tables["ChildElement1"].Constraints["Element1_ChildElement1"];
Compare(con.Columns[0].ColumnName,"Element1_Id");
Compare(con.DeleteRule,Rule.Cascade);
Compare(con.AcceptRejectRule,AcceptRejectRule.None);
Compare(con.RelatedTable.TableName,"Element1");
Compare(con.Table.TableName,"ChildElement1");
}
catch (Exception ex)
{
exp = ex;
}
finally
{
EndCase(exp);
}
}
#endregion
#region Inferring Element Text
[Test]
public void elementText1()
{
//ms-help://MS.MSDNQTR.2003FEB.1033/cpguide/html/cpconinferringelementtext.htm
BeginCase("elementText1");
Exception exp=null;
StringBuilder sb = new StringBuilder();
sb.Append("<DocumentElement>");
sb.Append("<Element1 attr1='value1'>Text1</Element1>");
sb.Append("</DocumentElement>");
DataSet ds = new DataSet();
MemoryStream myStream = new MemoryStream(new ASCIIEncoding().GetBytes(sb.ToString()));
try
{
ds.InferXmlSchema(myStream,null);
Compare(ds.DataSetName,"DocumentElement");
Compare(ds.Tables[0].TableName,"Element1");
Compare(ds.Tables.Count,1);
Compare(ds.Tables["Element1"].Columns["attr1"].ColumnName,"attr1");
Compare(ds.Tables["Element1"].Columns["attr1"].ColumnMapping ,MappingType.Attribute);
Compare(ds.Tables["Element1"].Columns["attr1"].DataType ,typeof(string));
Compare(ds.Tables["Element1"].Columns["Element1_Text"].ColumnName,"Element1_Text");
Compare(ds.Tables["Element1"].Columns["Element1_Text"].ColumnMapping ,MappingType.SimpleContent);
Compare(ds.Tables["Element1"].Columns["Element1_Text"].DataType ,typeof(string));
}
catch (Exception ex)
{
exp = ex;
}
finally
{
EndCase(exp);
}
}
[Test]
public void elementText2()
{
//ms-help://MS.MSDNQTR.2003FEB.1033/cpguide/html/cpconinferringelementtext.htm
BeginCase("elementText1");
Exception exp=null;
StringBuilder sb = new StringBuilder();
sb.Append("<DocumentElement>");
sb.Append("<Element1>");
sb.Append("Text1");
sb.Append("<ChildElement1>Text2</ChildElement1>");
sb.Append("Text3");
sb.Append("</Element1>");
sb.Append("</DocumentElement>");
DataSet ds = new DataSet();
MemoryStream myStream = new MemoryStream(new ASCIIEncoding().GetBytes(sb.ToString()));
try
{
ds.InferXmlSchema(myStream,null);
Compare(ds.DataSetName,"DocumentElement");
Compare(ds.Tables[0].TableName,"Element1");
Compare(ds.Tables.Count,1);
Compare(ds.Tables["Element1"].Columns["ChildElement1"].ColumnName,"ChildElement1");
Compare(ds.Tables["Element1"].Columns["ChildElement1"].ColumnMapping ,MappingType.Element);
Compare(ds.Tables["Element1"].Columns["ChildElement1"].DataType ,typeof(string));
Compare(ds.Tables["Element1"].Columns.Count,1);
}
catch (Exception ex)
{
exp = ex;
}
finally
{
EndCase(exp);
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class LiftedComparisonEqualNullableTests
{
#region Test methods
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedComparisonEqualNullableBoolTest(bool useInterpreter)
{
bool?[] values = new bool?[] { null, true, false };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonEqualNullableBool(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedComparisonEqualNullableByteTest(bool useInterpreter)
{
byte?[] values = new byte?[] { null, 0, 1, byte.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonEqualNullableByte(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedComparisonEqualNullableCharTest(bool useInterpreter)
{
char?[] values = new char?[] { null, '\0', '\b', 'A', '\uffff' };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonEqualNullableChar(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedComparisonEqualNullableDecimalTest(bool useInterpreter)
{
decimal?[] values = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonEqualNullableDecimal(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedComparisonEqualNullableDoubleTest(bool useInterpreter)
{
double?[] values = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonEqualNullableDouble(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedComparisonEqualNullableFloatTest(bool useInterpreter)
{
float?[] values = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonEqualNullableFloat(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedComparisonEqualNullableIntTest(bool useInterpreter)
{
int?[] values = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonEqualNullableInt(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedComparisonEqualNullableLongTest(bool useInterpreter)
{
long?[] values = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonEqualNullableLong(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedComparisonEqualNullableSByteTest(bool useInterpreter)
{
sbyte?[] values = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonEqualNullableSByte(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedComparisonEqualNullableShortTest(bool useInterpreter)
{
short?[] values = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonEqualNullableShort(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedComparisonEqualNullableUIntTest(bool useInterpreter)
{
uint?[] values = new uint?[] { null, 0, 1, uint.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonEqualNullableUInt(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedComparisonEqualNullableULongTest(bool useInterpreter)
{
ulong?[] values = new ulong?[] { null, 0, 1, ulong.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonEqualNullableULong(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedComparisonEqualNullableUShortTest(bool useInterpreter)
{
ushort?[] values = new ushort?[] { null, 0, 1, ushort.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonEqualNullableUShort(values[i], values[j], useInterpreter);
}
}
}
#endregion
#region Test verifiers
private static void VerifyComparisonEqualNullableBool(bool? a, bool? b, bool useInterpreter)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.Equal(
Expression.Constant(a, typeof(bool?)),
Expression.Constant(b, typeof(bool?)),
true,
null));
Func<bool?> f = e.Compile(useInterpreter);
bool? expected = a == b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonEqualNullableByte(byte? a, byte? b, bool useInterpreter)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.Equal(
Expression.Constant(a, typeof(byte?)),
Expression.Constant(b, typeof(byte?)),
true,
null));
Func<bool?> f = e.Compile(useInterpreter);
bool? expected = a == b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonEqualNullableChar(char? a, char? b, bool useInterpreter)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.Equal(
Expression.Constant(a, typeof(char?)),
Expression.Constant(b, typeof(char?)),
true,
null));
Func<bool?> f = e.Compile(useInterpreter);
bool? expected = a == b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonEqualNullableDecimal(decimal? a, decimal? b, bool useInterpreter)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.Equal(
Expression.Constant(a, typeof(decimal?)),
Expression.Constant(b, typeof(decimal?)),
true,
null));
Func<bool?> f = e.Compile(useInterpreter);
bool? expected = a == b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonEqualNullableDouble(double? a, double? b, bool useInterpreter)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.Equal(
Expression.Constant(a, typeof(double?)),
Expression.Constant(b, typeof(double?)),
true,
null));
Func<bool?> f = e.Compile(useInterpreter);
bool? expected = a == b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonEqualNullableFloat(float? a, float? b, bool useInterpreter)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.Equal(
Expression.Constant(a, typeof(float?)),
Expression.Constant(b, typeof(float?)),
true,
null));
Func<bool?> f = e.Compile(useInterpreter);
bool? expected = a == b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonEqualNullableInt(int? a, int? b, bool useInterpreter)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.Equal(
Expression.Constant(a, typeof(int?)),
Expression.Constant(b, typeof(int?)),
true,
null));
Func<bool?> f = e.Compile(useInterpreter);
bool? expected = a == b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonEqualNullableLong(long? a, long? b, bool useInterpreter)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.Equal(
Expression.Constant(a, typeof(long?)),
Expression.Constant(b, typeof(long?)),
true,
null));
Func<bool?> f = e.Compile(useInterpreter);
bool? expected = a == b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonEqualNullableSByte(sbyte? a, sbyte? b, bool useInterpreter)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.Equal(
Expression.Constant(a, typeof(sbyte?)),
Expression.Constant(b, typeof(sbyte?)),
true,
null));
Func<bool?> f = e.Compile(useInterpreter);
bool? expected = a == b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonEqualNullableShort(short? a, short? b, bool useInterpreter)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.Equal(
Expression.Constant(a, typeof(short?)),
Expression.Constant(b, typeof(short?)),
true,
null));
Func<bool?> f = e.Compile(useInterpreter);
bool? expected = a == b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonEqualNullableUInt(uint? a, uint? b, bool useInterpreter)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.Equal(
Expression.Constant(a, typeof(uint?)),
Expression.Constant(b, typeof(uint?)),
true,
null));
Func<bool?> f = e.Compile(useInterpreter);
bool? expected = a == b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonEqualNullableULong(ulong? a, ulong? b, bool useInterpreter)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.Equal(
Expression.Constant(a, typeof(ulong?)),
Expression.Constant(b, typeof(ulong?)),
true,
null));
Func<bool?> f = e.Compile(useInterpreter);
bool? expected = a == b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonEqualNullableUShort(ushort? a, ushort? b, bool useInterpreter)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.Equal(
Expression.Constant(a, typeof(ushort?)),
Expression.Constant(b, typeof(ushort?)),
true,
null));
Func<bool?> f = e.Compile(useInterpreter);
bool? expected = a == b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
#endregion
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig.Emulation.Hosting
{
using System;
using Cfg = Microsoft.Zelig.Configuration.Environment;
public abstract class MemoryProvider
{
//
// State
//
AbstractHost m_owner;
Cfg.CacheControllerCategory m_cache;
//
// Constructor Methods
//
protected MemoryProvider( AbstractHost owner ,
Cfg.CacheControllerCategory cache )
{
m_cache = cache;
m_owner = owner;
m_owner.RegisterService( typeof(Emulation.Hosting.MemoryProvider), this );
}
//
// Helper Methods
//
public void Dispose()
{
m_owner.UnregisterService( this );
}
public bool CanAccess( uint address ,
uint size )
{
address = NormalizeAddress( address );
switch(size)
{
case 1: return CanAccessUInt8 ( address );
case 2: return CanAccessUInt16( address );
case 4: return CanAccessUInt32( address );
case 8: return CanAccessUInt64( address );
}
return false;
}
//--//
public bool GetUInt8( uint address ,
out byte result )
{
address = NormalizeAddress( address );
try
{
result = ReadUInt8( address );
return true;
}
catch(Exception)
{
result = 0;
return false;
}
}
public bool GetUInt16( uint address ,
out ushort result )
{
address = NormalizeAddress( address );
try
{
result = ReadUInt16( address );
return true;
}
catch(Exception)
{
result = 0;
return false;
}
}
public bool GetUInt32( uint address ,
out uint result )
{
address = NormalizeAddress( address );
try
{
result = ReadUInt32( address );
return true;
}
catch(Exception)
{
result = 0;
return false;
}
}
public bool GetUInt64( uint address ,
out ulong result )
{
address = NormalizeAddress( address );
try
{
result = ReadUInt64( address );
return true;
}
catch(Exception)
{
result = 0;
return false;
}
}
public bool GetBlock( uint address ,
int size ,
uint alignment ,
out byte[] result )
{
address = NormalizeAddress( address );
try
{
result = ReadBlock( address, size, alignment );
return true;
}
catch(Exception)
{
result = null;
return false;
}
}
//--//
public bool SetUInt8( uint address ,
byte result )
{
address = NormalizeAddress( address );
try
{
WriteUInt8( address, result );
return true;
}
catch(Exception)
{
return false;
}
}
public bool SetUInt16( uint address ,
ushort result )
{
address = NormalizeAddress( address );
try
{
WriteUInt16( address, result );
return true;
}
catch(Exception)
{
return false;
}
}
public bool SetUInt32( uint address ,
uint result )
{
address = NormalizeAddress( address );
try
{
WriteUInt32( address, result );
return true;
}
catch(Exception)
{
return false;
}
}
public bool SetUInt64( uint address ,
ulong result )
{
address = NormalizeAddress( address );
try
{
WriteUInt64( address, result );
return true;
}
catch(Exception)
{
return false;
}
}
public bool SetBlock( uint address ,
byte[] result ,
uint alignment )
{
address = NormalizeAddress( address );
try
{
WriteBlock( address, result, alignment );
return true;
}
catch(Exception)
{
return false;
}
}
//--//
protected virtual uint NormalizeAddress( uint address )
{
if(m_cache != null)
{
address = m_cache.GetUncacheableAddress( address );
}
return address;
}
protected abstract bool CanAccessUInt8 ( uint address );
protected abstract bool CanAccessUInt16( uint address );
protected abstract bool CanAccessUInt32( uint address );
protected abstract bool CanAccessUInt64( uint address );
protected abstract byte ReadUInt8 ( uint address );
protected abstract ushort ReadUInt16( uint address );
protected abstract uint ReadUInt32( uint address );
protected abstract ulong ReadUInt64( uint address );
protected abstract byte[] ReadBlock ( uint address, int size, uint alignment );
protected abstract void WriteUInt8 ( uint address, byte result );
protected abstract void WriteUInt16( uint address, ushort result );
protected abstract void WriteUInt32( uint address, uint result );
protected abstract void WriteUInt64( uint address, ulong result );
protected abstract void WriteBlock ( uint address, byte[] result, uint alignment );
}
}
| |
#region Header
/*
* JsonWriter.cs
* Stream-like facility to output JSON text.
*
* The authors disclaim copyright to this source code. For more details, see
* the COPYING file included with this distribution.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
namespace LitJson
{
internal enum Condition
{
InArray,
InObject,
NotAProperty,
Property,
Value
}
internal class WriterContext
{
public int Count;
public bool InArray;
public bool InObject;
public bool ExpectingValue;
public int Padding;
}
public class JsonWriter
{
#region Fields
private static NumberFormatInfo number_format;
private WriterContext context;
private Stack<WriterContext> ctx_stack;
private bool has_reached_end;
private char[] hex_seq;
private int indentation;
private int indent_value;
private StringBuilder inst_string_builder;
private bool pretty_print;
private bool validate;
private TextWriter writer;
#endregion
#region Properties
public int IndentValue {
get { return indent_value; }
set {
indentation = (indentation / indent_value) * value;
indent_value = value;
}
}
public bool PrettyPrint {
get { return pretty_print; }
set { pretty_print = value; }
}
public TextWriter TextWriter {
get { return writer; }
}
public bool Validate {
get { return validate; }
set { validate = value; }
}
#endregion
#region Constructors
static JsonWriter ()
{
number_format = NumberFormatInfo.InvariantInfo;
}
public JsonWriter ()
{
inst_string_builder = new StringBuilder ();
writer = new StringWriter (inst_string_builder);
Init ();
}
public JsonWriter (StringBuilder sb) :
this (new StringWriter (sb))
{
}
public JsonWriter (TextWriter writer)
{
if (writer == null)
throw new ArgumentNullException ("writer");
this.writer = writer;
Init ();
}
#endregion
#region Private Methods
private void DoValidation (Condition cond)
{
if (! context.ExpectingValue)
context.Count++;
if (! validate)
return;
if (has_reached_end)
throw new JsonException (
"A complete JSON symbol has already been written");
switch (cond) {
case Condition.InArray:
if (! context.InArray)
throw new JsonException (
"Can't close an array here");
break;
case Condition.InObject:
if (! context.InObject || context.ExpectingValue)
throw new JsonException (
"Can't close an object here");
break;
case Condition.NotAProperty:
if (context.InObject && ! context.ExpectingValue)
throw new JsonException (
"Expected a property");
break;
case Condition.Property:
if (! context.InObject || context.ExpectingValue)
throw new JsonException (
"Can't add a property here");
break;
case Condition.Value:
if (! context.InArray &&
(! context.InObject || ! context.ExpectingValue))
throw new JsonException (
"Can't add a value here");
break;
}
}
private void Init ()
{
has_reached_end = false;
hex_seq = new char[4];
indentation = 0;
indent_value = 4;
pretty_print = false;
validate = true;
ctx_stack = new Stack<WriterContext> ();
context = new WriterContext ();
ctx_stack.Push (context);
}
private static void IntToHex (int n, char[] hex)
{
int num;
for (int i = 0; i < 4; i++) {
num = n % 16;
if (num < 10)
hex[3 - i] = (char) ('0' + num);
else
hex[3 - i] = (char) ('A' + (num - 10));
n >>= 4;
}
}
private void Indent ()
{
if (pretty_print)
indentation += indent_value;
}
private void Put (string str)
{
if (pretty_print && ! context.ExpectingValue)
for (int i = 0; i < indentation; i++)
writer.Write (' ');
writer.Write (str);
}
private void PutNewline ()
{
PutNewline (true);
}
private void PutNewline (bool add_comma)
{
if (add_comma && ! context.ExpectingValue &&
context.Count > 1)
writer.Write (',');
if (pretty_print && ! context.ExpectingValue)
writer.Write ('\n');
}
private void PutString (string str)
{
Put (String.Empty);
writer.Write ('"');
int n = str.Length;
for (int i = 0; i < n; i++) {
switch (str[i]) {
case '\n':
writer.Write ("\\n");
continue;
case '\r':
writer.Write ("\\r");
continue;
case '\t':
writer.Write ("\\t");
continue;
case '"':
case '\\':
writer.Write ('\\');
writer.Write (str[i]);
continue;
case '\f':
writer.Write ("\\f");
continue;
case '\b':
writer.Write ("\\b");
continue;
}
if ((int) str[i] >= 32 && (int) str[i] <= 126) {
writer.Write (str[i]);
continue;
}
// Default, turn into a \uXXXX sequence
IntToHex ((int) str[i], hex_seq);
writer.Write ("\\u");
writer.Write (hex_seq);
}
writer.Write ('"');
}
private void Unindent ()
{
if (pretty_print)
indentation -= indent_value;
}
#endregion
public override string ToString ()
{
if (inst_string_builder == null)
return String.Empty;
return inst_string_builder.ToString ();
}
public void Reset ()
{
has_reached_end = false;
ctx_stack.Clear ();
context = new WriterContext ();
ctx_stack.Push (context);
if (inst_string_builder != null)
inst_string_builder.Remove (0, inst_string_builder.Length);
}
public void Write (bool boolean)
{
DoValidation (Condition.Value);
PutNewline ();
Put (boolean ? "true" : "false");
context.ExpectingValue = false;
}
public void Write (decimal number)
{
DoValidation (Condition.Value);
PutNewline ();
Put (Convert.ToString (number, number_format));
context.ExpectingValue = false;
}
public void Write (double number)
{
DoValidation (Condition.Value);
PutNewline ();
string str = Convert.ToString (number, number_format);
Put (str);
if (str.IndexOf ('.') == -1 &&
str.IndexOf ('E') == -1)
writer.Write (".0");
context.ExpectingValue = false;
}
public void Write (int number)
{
DoValidation (Condition.Value);
PutNewline ();
Put (Convert.ToString (number, number_format));
context.ExpectingValue = false;
}
public void Write (long number)
{
DoValidation (Condition.Value);
PutNewline ();
Put (Convert.ToString (number, number_format));
context.ExpectingValue = false;
}
public void Write (string str)
{
DoValidation (Condition.Value);
PutNewline ();
if (str == null)
Put ("null");
else
PutString (str);
context.ExpectingValue = false;
}
public void Write (ulong number)
{
DoValidation (Condition.Value);
PutNewline ();
Put (Convert.ToString (number, number_format));
context.ExpectingValue = false;
}
public void WriteArrayEnd ()
{
DoValidation (Condition.InArray);
PutNewline (false);
ctx_stack.Pop ();
if (ctx_stack.Count == 1)
has_reached_end = true;
else {
context = ctx_stack.Peek ();
context.ExpectingValue = false;
}
Unindent ();
Put ("]");
}
public void WriteArrayStart ()
{
DoValidation (Condition.NotAProperty);
PutNewline ();
Put ("[");
context = new WriterContext ();
context.InArray = true;
ctx_stack.Push (context);
Indent ();
}
public void WriteObjectEnd ()
{
DoValidation (Condition.InObject);
PutNewline (false);
ctx_stack.Pop ();
if (ctx_stack.Count == 1)
has_reached_end = true;
else {
context = ctx_stack.Peek ();
context.ExpectingValue = false;
}
Unindent ();
Put ("}");
}
public void WriteObjectStart ()
{
DoValidation (Condition.NotAProperty);
PutNewline ();
Put ("{");
context = new WriterContext ();
context.InObject = true;
ctx_stack.Push (context);
Indent ();
}
public void WritePropertyName (string property_name)
{
DoValidation (Condition.Property);
PutNewline ();
PutString (property_name);
if (pretty_print) {
if (property_name.Length > context.Padding)
context.Padding = property_name.Length;
for (int i = context.Padding - property_name.Length;
i >= 0; i--)
writer.Write (' ');
writer.Write (": ");
} else
writer.Write (':');
context.ExpectingValue = true;
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.ComponentModel.Composition.Hosting;
using System.IO;
using System.Linq;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Microsoft.PythonTools.Interpreter;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudioTools;
namespace Microsoft.PythonTools.BuildTasks {
/// <summary>
/// Resolves a project's active environment from the contents of the project
/// file.
/// </summary>
public sealed class ResolveEnvironment : ITask {
private readonly string _projectPath;
internal readonly TaskLoggingHelper _log;
internal ResolveEnvironment(string projectPath, IBuildEngine buildEngine) {
BuildEngine = buildEngine;
_projectPath = projectPath;
_log = new TaskLoggingHelper(this);
}
/// <summary>
/// The interpreter ID to resolve. If this and
/// <see cref="InterpreterVersion"/>
/// </summary>
public string InterpreterId { get; set; }
public string InterpreterVersion { get; set; }
[Output]
public string PrefixPath { get; private set; }
[Output]
public string ProjectRelativePrefixPath { get; private set; }
[Output]
public string InterpreterPath { get; private set; }
[Output]
public string WindowsInterpreterPath { get; private set; }
[Output]
public string LibraryPath { get; private set; }
[Output]
public string Architecture { get; private set; }
[Output]
public string PathEnvironmentVariable { get; private set; }
[Output]
public string Description { get; private set; }
[Output]
public string MajorVersion { get; private set; }
[Output]
public string MinorVersion { get; private set; }
internal string[] SearchPaths { get; private set; }
public bool Execute() {
bool returnActive;
Guid id;
Version version;
returnActive = !Guid.TryParse(InterpreterId, out id);
if (!Version.TryParse(InterpreterVersion, out version)) {
if (!returnActive) {
_log.LogError(
"Invalid values for InterpreterId (\"{0}\") and InterpreterVersion (\"{1}\")",
InterpreterId,
InterpreterVersion
);
return false;
}
}
MSBuildProjectInterpreterFactoryProvider provider = null;
ProjectCollection collection = null;
Project project = null;
var service = ServiceHolder.Create();
if (service == null) {
_log.LogError("Unable to obtain interpreter service.");
return false;
}
try {
try {
project = ProjectCollection.GlobalProjectCollection.GetLoadedProjects(_projectPath).Single();
} catch (InvalidOperationException) {
// Could not get exactly one project matching the path.
}
if (project == null) {
collection = new ProjectCollection();
project = collection.LoadProject(_projectPath);
}
var projectHome = CommonUtils.GetAbsoluteDirectoryPath(
project.DirectoryPath,
project.GetPropertyValue("ProjectHome")
);
var searchPath = project.GetPropertyValue("SearchPath");
if (!string.IsNullOrEmpty(searchPath)) {
SearchPaths = searchPath.Split(';')
.Select(p => CommonUtils.GetAbsoluteFilePath(projectHome, p))
.ToArray();
} else {
SearchPaths = new string[0];
}
provider = new MSBuildProjectInterpreterFactoryProvider(service.Service, project);
try {
provider.DiscoverInterpreters();
} catch (InvalidDataException ex) {
_log.LogWarning("Errors while resolving environments: {0}", ex.Message);
}
IPythonInterpreterFactory factory = null;
if (returnActive) {
factory = provider.ActiveInterpreter;
} else {
factory = provider.FindInterpreter(id, version);
}
if (!provider.IsAvailable(factory)) {
_log.LogError(
"The environment '{0}' is not available. Check your project configuration and try again.",
factory.Description
);
return false;
} else if (factory == service.Service.NoInterpretersValue) {
_log.LogError(
"No Python environments are configured. Please install or configure an environment and try " +
"again. See http://go.microsoft.com/fwlink/?LinkID=299429 for information on setting up a " +
"Python environment."
);
return false;
} else if (factory != null) {
PrefixPath = CommonUtils.EnsureEndSeparator(factory.Configuration.PrefixPath);
if (CommonUtils.IsSubpathOf(projectHome, PrefixPath)) {
ProjectRelativePrefixPath = CommonUtils.GetRelativeDirectoryPath(projectHome, PrefixPath);
} else {
ProjectRelativePrefixPath = string.Empty;
}
InterpreterPath = factory.Configuration.InterpreterPath;
WindowsInterpreterPath = factory.Configuration.WindowsInterpreterPath;
LibraryPath = CommonUtils.EnsureEndSeparator(factory.Configuration.LibraryPath);
Architecture = factory.Configuration.Architecture.ToString();
PathEnvironmentVariable = factory.Configuration.PathEnvironmentVariable;
Description = factory.Description;
MajorVersion = factory.Configuration.Version.Major.ToString();
MinorVersion = factory.Configuration.Version.Minor.ToString();
return true;
} else if (returnActive) {
_log.LogError("Unable to resolve active environment.");
} else {
_log.LogError("Unable to resolve environment {0} {1}", InterpreterId, InterpreterVersion);
}
} catch (Exception ex) {
_log.LogErrorFromException(ex);
} finally {
if (provider != null) {
provider.Dispose();
}
if (collection != null) {
collection.UnloadAllProjects();
collection.Dispose();
}
service.Dispose();
}
_log.LogError("Unable to resolve environment");
return false;
}
public IBuildEngine BuildEngine { get; set; }
public ITaskHost HostObject { get; set; }
private sealed class ServiceHolder : IDisposable {
private readonly AssemblyCatalog _catalog;
private readonly CompositionContainer _container;
private readonly IInterpreterOptionsService _service;
private static ServiceHolder FromInProc() {
if (ServiceProvider.GlobalProvider != null) {
var model = ServiceProvider.GlobalProvider.GetService(typeof(SComponentModel)) as IComponentModel;
if (model != null) {
var service = model.GetService<IInterpreterOptionsService>();
if (service != null) {
return new ServiceHolder(null, null, service);
}
}
}
return null;
}
private static ServiceHolder FromOutOfProc() {
var catalog = new AssemblyCatalog(typeof(IInterpreterOptionsService).Assembly);
var container = new CompositionContainer(catalog);
var service = container.GetExportedValue<IInterpreterOptionsService>();
if (service != null) {
return new ServiceHolder(catalog, container, service);
}
return null;
}
public static ServiceHolder Create() {
return FromInProc() ?? FromOutOfProc();
}
private ServiceHolder(
AssemblyCatalog catalog,
CompositionContainer container,
IInterpreterOptionsService service
) {
_catalog = catalog;
_container = container;
_service = service;
}
public IInterpreterOptionsService Service { get { return _service; } }
public void Dispose() {
if (_container != null) {
_container.Dispose();
}
if (_catalog != null) {
_catalog.Dispose();
}
}
}
}
/// <summary>
/// Constructs ResolveEnvironment task objects.
/// </summary>
public sealed class ResolveEnvironmentFactory : TaskFactory<ResolveEnvironment> {
public override ITask CreateTask(IBuildEngine taskFactoryLoggingHost) {
return new ResolveEnvironment(Properties["ProjectPath"], taskFactoryLoggingHost);
}
}
}
| |
using System;
using FarseerGames.FarseerPhysics.Collisions;
using FarseerGames.FarseerPhysics.Dynamics;
namespace FarseerGames.FarseerPhysics.Factories
{
/// <summary>
/// An easy to use factory for creating bodies
/// </summary>
public class BodyFactory
{
private static BodyFactory _instance;
private BodyFactory()
{
}
public static BodyFactory Instance
{
get
{
if (_instance == null)
{
_instance = new BodyFactory();
}
return _instance;
}
}
#region Rectangles
/// <summary>
/// Creates a rectangle body.
/// </summary>
/// <param name="physicsSimulator">The physics simulator.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="mass">The mass.</param>
/// <returns></returns>
public Body CreateRectangleBody(PhysicsSimulator physicsSimulator, float width, float height, float mass)
{
Body body = CreateRectangleBody(width, height, mass);
physicsSimulator.Add(body);
return body;
}
/// <summary>
/// Creates a rectangle body.
/// </summary>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="mass">The mass.</param>
/// <returns></returns>
public Body CreateRectangleBody(float width, float height, float mass)
{
if (width <= 0)
throw new ArgumentOutOfRangeException("width", "Width must be more than 0");
if (height <= 0)
throw new ArgumentOutOfRangeException("height", "Height must be more than 0");
if (mass <= 0)
throw new ArgumentOutOfRangeException("mass", "Mass must be more than 0");
Body body = new Body();
body.Mass = mass;
//MOI for rectangles.
body.MomentOfInertia = mass * (width * width + height * height) / 12;
return body;
}
#endregion
#region Circles
/// <summary>
/// Creates a circle body.
/// </summary>
/// <param name="physicsSimulator">The physics simulator.</param>
/// <param name="radius">The radius.</param>
/// <param name="mass">The mass.</param>
/// <returns></returns>
public Body CreateCircleBody(PhysicsSimulator physicsSimulator, float radius, float mass)
{
Body body = CreateCircleBody(radius, mass);
physicsSimulator.Add(body);
return body;
}
/// <summary>
/// Creates a circle body.
/// </summary>
/// <param name="radius">The radius.</param>
/// <param name="mass">The mass.</param>
/// <returns></returns>
public Body CreateCircleBody(float radius, float mass)
{
if (radius <= 0)
throw new ArgumentOutOfRangeException("radius", "Radius must be more than 0");
if (mass <= 0)
throw new ArgumentOutOfRangeException("mass", "Mass must be more than 0");
Body body = new Body();
body.Mass = mass;
//MOI for circles
body.MomentOfInertia = .5f * mass * (float)Math.Pow(radius, 2f);
return body;
}
#endregion
#region Ellipses
/// <summary>
/// Creates a ellipse body.
/// </summary>
/// <param name="physicsSimulator">The physics simulator.</param>
/// <param name="xRadius">The width.</param>
/// <param name="yRadius">The height.</param>
/// <param name="mass">The mass.</param>
/// <returns></returns>
public Body CreateEllipseBody(PhysicsSimulator physicsSimulator, float xRadius, float yRadius, float mass)
{
Body body = CreateEllipseBody(xRadius, yRadius, mass);
physicsSimulator.Add(body);
return body;
}
/// <summary>
/// Creates a ellipse body.
/// </summary>
/// <param name="xRadius">The width.</param>
/// <param name="yRadius">The height.</param>
/// <param name="mass">The mass.</param>
/// <returns></returns>
public Body CreateEllipseBody(float xRadius, float yRadius, float mass)
{
if (xRadius <= 0)
throw new ArgumentOutOfRangeException("xRadius", "xRadius must be more than 0");
if (yRadius <= 0)
throw new ArgumentOutOfRangeException("yRadius", "yRadius must be more than 0");
if (mass <= 0)
throw new ArgumentOutOfRangeException("mass", "Mass must be more than 0");
if (xRadius == yRadius)
{
return CreateCircleBody(xRadius, mass);
}
Body body = new Body();
body.Mass = mass;
//TODO: Check if this formular is correct
//body.MomentOfInertia = mass * (xRadius * xRadius + yRadius * yRadius) / 12;
body.MomentOfInertia = .25f * mass * (xRadius * xRadius + yRadius * yRadius);
return body;
}
#endregion
#region Polygons
/// <summary>
/// Creates a Body. The moment of inertia of the body is calculated from the
/// set of vertices passed in to this method. The vertices should represent a polygon.
/// </summary>
/// <param name="physicsSimulator"><see cref="PhysicsSimulator"/> to add this body to.</param>
/// <param name="vertices">Vertices representing some polygon</param>
/// <param name="mass">Mass of the Body</param>
/// <returns></returns>
public Body CreatePolygonBody(PhysicsSimulator physicsSimulator, Vertices vertices, float mass)
{
Body body = CreatePolygonBody(vertices, mass);
physicsSimulator.Add(body);
return body;
}
/// <summary>
/// Creates a Body. The moment of inertia of the body is calculated from the
/// set of vertices passed in to this method. The vertices should represent a polygon.
/// </summary>
/// <param name="vertices">Vertices representing some polygon</param>
/// <param name="mass">Mass of the Body</param>
/// <returns></returns>
public Body CreatePolygonBody(Vertices vertices, float mass)
{
if (vertices == null)
throw new ArgumentNullException("vertices", "Vertices must not be null");
if (mass <= 0)
throw new ArgumentOutOfRangeException("mass", "Mass must be more than 0");
Body body = new Body();
body.Mass = mass;
body.MomentOfInertia = mass * vertices.GetMomentOfInertia();
body.position = vertices.GetCentroid();
return body;
}
#endregion
#region General
public Body CreateBody(PhysicsSimulator physicsSimulator, float mass, float momentOfInertia)
{
Body body = CreateBody(mass, momentOfInertia);
physicsSimulator.Add(body);
return body;
}
public Body CreateBody(float mass, float momentOfInertia)
{
if (mass <= 0)
throw new ArgumentOutOfRangeException("mass", "Mass must be more than 0");
if (momentOfInertia <= 0)
throw new ArgumentOutOfRangeException("momentOfInertia", "MOI must be more than 0");
Body body = new Body();
body.Mass = mass;
body.MomentOfInertia = momentOfInertia;
return body;
}
public Body CreateBody(PhysicsSimulator physicsSimulator, Body body)
{
Body bodyClone = CreateBody(body);
physicsSimulator.Add(bodyClone);
return bodyClone;
}
public Body CreateBody(Body body)
{
Body bodyClone = new Body(body);
return bodyClone;
}
#endregion
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
Copyright (C) 2011 Peter Gill <peter@majorsilence.com>
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 info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Drawing;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Data.Odbc;
using System.Data.SqlClient;
using System.IO;
using System.Globalization;
using System.Xml;
using fyiReporting.RDL;
using fyiReporting.RdlDesign.Resources;
namespace fyiReporting.RdlDesign
{
/// <summary>
/// Summary description for DialogDatabase.
/// </summary>
public partial class DialogDatabase
{
RdlDesigner _rDesigner = null;
RdlUserControl _rUserControl = null;
static private readonly string SHARED_CONNECTION = "Shared Data Source";
string _StashConnection = null;
private List<SqlColumn> _ColumnList = null;
private string _TempFileName = null;
private string _ResultReport = "nothing";
private readonly string _Schema2003 =
"xmlns=\"http://schemas.microsoft.com/sqlserver/reporting/2003/10/reportdefinition\" xmlns:rd=\"http://schemas.microsoft.com/SQLServer/reporting/reportdesigner\"";
private readonly string _Schema2005 =
"xmlns=\"http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition\" xmlns:rd=\"http://schemas.microsoft.com/SQLServer/reporting/reportdesigner\"";
private string _TemplateChart = " some junk";
private string _TemplateMatrix = " some junk";
private string _TemplateTable = @"<?xml version='1.0' encoding='UTF-8'?>
<Report |schema| >
<Description>|description|</Description>
<Author>|author|</Author>
|orientation|
<DataSources>
<DataSource Name='DS1'>
|connectionproperties|
</DataSource>
</DataSources>
<Width>7.5in</Width>
<TopMargin>.25in</TopMargin>
<LeftMargin>.25in</LeftMargin>
<RightMargin>.25in</RightMargin>
<BottomMargin>.25in</BottomMargin>
|reportparameters|
<DataSets>
<DataSet Name='Data'>
<Query>
<DataSourceName>DS1</DataSourceName>
<CommandText>|sqltext|</CommandText>
|queryparameters|
</Query>
<Fields>
|sqlfields|
</Fields>
</DataSet>
</DataSets>
<PageHeader>
<Height>.5in</Height>
|ifdef reportname|
<ReportItems>
<Textbox><Top>.1in</Top><Left>.1in</Left><Width>6in</Width><Height>.25in</Height><Value>|reportnameasis|</Value><Style><FontSize>15pt</FontSize><FontWeight>Bold</FontWeight></Style></Textbox>
</ReportItems>
|endif|
<PrintOnFirstPage>true</PrintOnFirstPage>
<PrintOnLastPage>true</PrintOnLastPage>
</PageHeader>
<Body>
<ReportItems>
<Table>
<DataSetName>Data</DataSetName>
<NoRows>Query returned no rows!</NoRows>
<Style><BorderStyle><Default>Solid</Default></BorderStyle></Style>
<TableColumns>
|tablecolumns|
</TableColumns>
<Header>
<TableRows>
<TableRow>
<Height>12pt</Height>
<TableCells>|tableheaders|</TableCells>
</TableRow>
</TableRows>
<RepeatOnNewPage>true</RepeatOnNewPage>
</Header>
|ifdef grouping|
<TableGroups>
<TableGroup>
<Header>
<TableRows>
<TableRow>
<Height>12pt</Height>
<TableCells>
<TableCell>
<ColSpan>|columncount|</ColSpan>
<ReportItems><Textbox><Value>=Fields.|groupbycolumn|.Value</Value><Style><PaddingLeft>2pt</PaddingLeft><BorderStyle><Default>Solid</Default></BorderStyle><FontWeight>Bold</FontWeight></Style></Textbox></ReportItems>
</TableCell>
</TableCells>
</TableRow>
</TableRows>
<RepeatOnNewPage>true</RepeatOnNewPage>
</Header>
<Footer>
<TableRows>
<TableRow>
<Height>12pt</Height>
<TableCells>|gtablefooters|</TableCells>
</TableRow>
</TableRows>
</Footer>
<Grouping Name='|groupbycolumn|Group'><GroupExpressions><GroupExpression>=Fields!|groupbycolumn|.Value</GroupExpression></GroupExpressions></Grouping>
</TableGroup>
</TableGroups>
|endif|
<Details>
<TableRows>
<TableRow>
<Height>12pt</Height>
<TableCells>|tablevalues|</TableCells>
</TableRow>
</TableRows>
</Details>
|ifdef footers|
<Footer>
<TableRows>
<TableRow>
<Height>12pt</Height>
<TableCells>|tablefooters|</TableCells>
</TableRow>
</TableRows>
</Footer>
|endif|
</Table>
</ReportItems>
<Height>|bodyheight|</Height>
</Body>
<PageFooter>
<Height>14pt</Height>
<ReportItems>
<Textbox><Top>1pt</Top><Left>10pt</Left><Height>12pt</Height><Width>3in</Width>
<Value>=Globals!PageNumber + ' of ' + Globals!TotalPages</Value>
<Style><FontSize>10pt</FontSize><FontWeight>Normal</FontWeight></Style>
</Textbox>
</ReportItems>
<PrintOnFirstPage>true</PrintOnFirstPage>
<PrintOnLastPage>true</PrintOnLastPage>
</PageFooter>
</Report>";
private string _TemplateList = @"<?xml version='1.0' encoding='UTF-8'?>
<Report |schema| >
<Description>|description|</Description>
<Author>|author|</Author>
|orientation|
<DataSources>
<DataSource Name='DS1'>
|connectionproperties|
</DataSource>
</DataSources>
<Width>7.5in</Width>
<TopMargin>.25in</TopMargin>
<LeftMargin>.25in</LeftMargin>
<RightMargin>.25in</RightMargin>
<BottomMargin>.25in</BottomMargin>
|reportparameters|
<DataSets>
<DataSet Name='Data'>
<Query>
<DataSourceName>DS1</DataSourceName>
<CommandText>|sqltext|</CommandText>
|queryparameters|
</Query>
<Fields>
|sqlfields|
</Fields>
</DataSet>
</DataSets>
<PageHeader>
<Height>.5in</Height>
<ReportItems>
|ifdef reportname|
<Textbox><Top>.02in</Top><Left>.1in</Left><Width>6in</Width><Height>.25in</Height><Value>|reportname|</Value><Style><FontSize>15pt</FontSize><FontWeight>Bold</FontWeight></Style></Textbox>
|endif|
|listheaders|
</ReportItems>
<PrintOnFirstPage>true</PrintOnFirstPage>
<PrintOnLastPage>true</PrintOnLastPage>
</PageHeader>
<Body><Height>25pt</Height>
<ReportItems>
<List>
<DataSetName>Data</DataSetName>
<Height>24pt</Height>
<NoRows>Query returned no rows!</NoRows>
<ReportItems>
|listvalues|
</ReportItems>
<Width>|listwidth|</Width>
</List>
</ReportItems>
</Body>
<PageFooter>
<Height>14pt</Height>
<ReportItems>
<Textbox><Top>1pt</Top><Left>10pt</Left><Height>12pt</Height><Width>3in</Width>
<Value>=Globals!PageNumber + ' of ' + Globals!TotalPages</Value>
<Style><FontSize>10pt</FontSize><FontWeight>Normal</FontWeight></Style>
</Textbox>
</ReportItems>
<PrintOnFirstPage>true</PrintOnFirstPage>
<PrintOnLastPage>true</PrintOnLastPage>
</PageFooter>
</Report>";
public DialogDatabase(RdlDesigner rDesigner)
{
_rDesigner = rDesigner;
//
// Required for Windows Form Designer support
//
InitializeComponent();
string[] items = RdlEngineConfig.GetProviders();
Array.Sort(items);
cbConnectionTypes.Items.Add(SHARED_CONNECTION);
cbConnectionTypes.Items.AddRange(items);
cbConnectionTypes.SelectedIndex = 1;
cbOrientation.SelectedIndex = 0;
}
public DialogDatabase(RdlUserControl rDesigner)
{
_rUserControl = rDesigner;
//
// Required for Windows Form Designer support
//
InitializeComponent();
string[] items = RdlEngineConfig.GetProviders();
cbConnectionTypes.Items.Add(SHARED_CONNECTION);
cbConnectionTypes.Items.AddRange(items);
cbConnectionTypes.SelectedIndex = 1;
cbOrientation.SelectedIndex = 0;
}
public enum ConnectionType
{
MYSQL,
MSSQL,
SQLITE,
POSTGRESQL,
XML,
WEBSERVICE
}
/// <summary>
/// Pre set a connection string. This is useful when you need to create
/// a new report from a program other then RdlDesigner.
/// </summary>
/// <param name="connectionString">A full and correct database connection string</param>
/// <param name="hideConnectionTab">If true this will hide the connection string. This is useful
/// when you do not want the users to need to know this information.</param>
/// <param name="ct">The database connection type.</param>
public void SetConnection(string connectionString, bool hideConnectionTab, ConnectionType ct)
{
if (ct == ConnectionType.MSSQL)
{
cbConnectionTypes.SelectedItem = "SQL";
}
else if (ct == ConnectionType.MYSQL)
{
cbConnectionTypes.SelectedItem = "MySQL.NET";
}
else if (ct == ConnectionType.POSTGRESQL)
{
cbConnectionTypes.SelectedItem = "PostgreSQL";
}
else if (ct == ConnectionType.SQLITE)
{
cbConnectionTypes.SelectedItem = "SQLite";
}
else if (ct == ConnectionType.WEBSERVICE)
{
cbConnectionTypes.SelectedItem = "WebService";
}
else if (ct == ConnectionType.XML)
{
cbConnectionTypes.SelectedItem = "XML";
}
else
{
throw new Exception("You should not have reached this far in the SetConnection function.");
}
tbConnection.Text = connectionString;
if (hideConnectionTab == true)
{
tcDialog.TabPages.Remove(tcDialog.TabPages["DBConnection"]);
}
}
public string ResultReport
{
get { return _ResultReport; }
}
private void btnOK_Click(object sender, System.EventArgs e)
{
if (!DoReportSyntax(false))
return;
DialogResult = DialogResult.OK;
_ResultReport = tbReportSyntax.Text;
this.Close();
}
private void tabControl1_SelectedIndexChanged(object sender, System.EventArgs e)
{
TabControl tc = (TabControl)sender;
string tag = (string)tc.TabPages[tc.SelectedIndex].Tag;
switch (tag)
{
case "type": // nothing to do here
break;
case "connect": // nothing to do here
break;
case "sql": // obtain table and column information
DoSqlSchema();
break;
case "group": // obtain group by information using connection & sql
DoGrouping();
break;
case "syntax": // obtain report using connection, sql,
DoReportSyntax(false);
break;
case "preview": // run report using generated report syntax
DoReportPreview();
break;
default:
break;
}
}
// Fill out tvTablesColumns
private void DoSqlSchema()
{
// TODO be more efficient and remember schema info;
// need to mark changes to connections
if (tvTablesColumns.Nodes.Count > 0)
return;
// suppress redraw until tree view is complete
tvTablesColumns.BeginUpdate();
// Get the schema information
List<SqlSchemaInfo> si = DesignerUtility.GetSchemaInfo(GetDataProvider(), GetDataConnection());
TreeNode ndRoot = new TreeNode("Tables");
tvTablesColumns.Nodes.Add(ndRoot);
bool bView = false;
foreach (SqlSchemaInfo ssi in si)
{
if (!bView && ssi.Type == "VIEW")
{ // Switch over to views
ndRoot = new TreeNode("Views");
tvTablesColumns.Nodes.Add(ndRoot);
bView = true;
}
// Add the node to the tree
TreeNode aRoot = new TreeNode(ssi.Name);
ndRoot.Nodes.Add(aRoot);
aRoot.Nodes.Add("");
}
// Now do parameters
//if (lbParameters.Items.Count > 0)
//{
// ndRoot = new TreeNode("Parameters");
// tvTablesColumns.Nodes.Add(ndRoot);
// foreach (ReportParm rp in lbParameters.Items)
// {
// string paramName;
// // force the name to start with @
// if (rp.Name[0] == '@')
// paramName = rp.Name;
// else
// paramName = "@" + rp.Name;
// // Add the node to the tree
// TreeNode aRoot = new TreeNode(paramName);
// ndRoot.Nodes.Add(aRoot);
// }
//}
tvTablesColumns.EndUpdate();
}
private void DoGrouping()
{
if (cbColumnList.Items.Count > 0) // We already have the columns?
return;
if (_ColumnList == null)
_ColumnList = DesignerUtility.GetSqlColumns(GetDataProvider(), GetDataConnection(), tbSQL.Text, reportParameterCtl1.lbParameters.Items);
foreach (SqlColumn sq in _ColumnList)
{
cbColumnList.Items.Add(sq);
clbSubtotal.Items.Add(sq);
}
SqlColumn sqc = new SqlColumn();
sqc.Name = "";
cbColumnList.Items.Add(sqc);
return;
}
private bool DoReportSyntax(bool UseFullSharedDSName)
{
string template;
if (rbList.Checked)
template = _TemplateList;
else if (rbTable.Checked)
template = _TemplateTable;
else if (rbMatrix.Checked)
template = _TemplateMatrix;
else if (rbChart.Checked)
template = _TemplateChart;
else
template = _TemplateTable; // default to table- should never reach
if (_ColumnList == null)
_ColumnList = DesignerUtility.GetSqlColumns(GetDataProvider(), GetDataConnection(), tbSQL.Text, reportParameterCtl1.lbParameters.Items);
if (_ColumnList.Count == 0) // can only happen by an error
return false;
string[] parts = template.Split('|');
StringBuilder sb = new StringBuilder(template.Length);
decimal left = 0m;
decimal width;
decimal bodyHeight = 0;
string name;
int skip = 0; // skip is used to allow nesting of ifdef
string args;
string canGrow;
string align;
// handle the group by column
string gbcolumn;
if (this.cbColumnList.Text.Length > 0)
gbcolumn = GetFieldName(this.cbColumnList.Text);
else
gbcolumn = null;
CultureInfo cinfo = new CultureInfo("", false);
foreach (string p in parts)
{
// Handle conditional special
int length = 5;
if (p.Length < 5)
{
length = p.Length;
}
if (p.Substring(0, length) == "ifdef")
{
args = p.Substring(6);
switch (args)
{
case "reportname":
if (tbReportName.Text.Length == 0)
skip++;
break;
case "description":
if (tbReportDescription.Text.Length == 0)
skip++;
break;
case "author":
if (tbReportAuthor.Text.Length == 0)
skip++;
break;
case "grouping":
if (gbcolumn == null)
skip++;
break;
case "footers":
if (!ckbGrandTotal.Checked)
skip++;
else if (clbSubtotal.CheckedItems.Count <= 0)
skip++;
break;
default:
throw new Exception(String.Format(Strings.DialogDatabase_Error_UnknownIfdef, args));
}
continue;
}
// if skipping lines (due to ifdef) then go to next endif
if (skip > 0 && p != "endif")
continue;
switch (p)
{
case "endif":
if (skip > 0)
skip--;
break;
case "schema":
if (this.rbSchema2003.Checked)
sb.Append(_Schema2003);
else if (this.rbSchema2005.Checked)
sb.Append(_Schema2005);
break;
case "reportname":
sb.Append(tbReportName.Text.Replace('\'', '_'));
break;
case "reportnameasis":
sb.Append(tbReportName.Text);
break;
case "description":
sb.Append(tbReportDescription.Text);
break;
case "author":
sb.Append(tbReportAuthor.Text);
break;
case "connectionproperties":
if (this.cbConnectionTypes.Text == SHARED_CONNECTION)
{
string file = this.tbConnection.Text;
if (!UseFullSharedDSName)
file = Path.GetFileNameWithoutExtension(file); // when we save report we use qualified name
sb.AppendFormat("<DataSourceReference>{0}</DataSourceReference>", file);
}
else
sb.AppendFormat("<ConnectionProperties><DataProvider>{0}</DataProvider><ConnectString>{1}</ConnectString></ConnectionProperties>",
GetDataProvider(), GetDataConnection());
break;
case "dataprovider":
sb.Append(GetDataProvider());
break;
case "connectstring":
sb.Append(tbConnection.Text);
break;
case "columncount":
sb.Append(_ColumnList.Count);
break;
case "orientation":
if (this.cbOrientation.SelectedIndex == 0)
{ // Portrait is first in the list
sb.Append("<PageHeight>11in</PageHeight><PageWidth>8.5in</PageWidth>");
}
else
{
sb.Append("<PageHeight>8.5in</PageHeight><PageWidth>11in</PageWidth>");
}
break;
case "groupbycolumn":
sb.Append(gbcolumn);
break;
case "reportparameters":
DoReportSyntaxParameters(cinfo, sb);
break;
case "queryparameters":
DoReportSyntaxQParameters(cinfo, sb, tbSQL.Text);
break;
case "sqltext":
sb.Append(tbSQL.Text.Replace("<", "<"));
break;
case "sqlfields":
foreach (SqlColumn sq in _ColumnList)
{
name = GetFieldName(sq.Name);
string type = sq.DataType.FullName;
if (this.rbSchemaNo.Checked)
sb.AppendFormat(cinfo, "<Field Name='{0}'><DataField>{1}</DataField><TypeName>{2}</TypeName></Field>", name, sq.Name, type);
else
sb.AppendFormat(cinfo, "<Field Name='{0}'><DataField>{1}</DataField><rd:TypeName>{2}</rd:TypeName></Field>", name, sq.Name, type);
}
break;
case "listheaders":
left = .0m;
foreach (SqlColumn sq in _ColumnList)
{
name = sq.Name;
width = name.Length / 8m;
if (width < 1)
width = 1;
sb.AppendFormat(cinfo, @"
<Textbox><Top>.3in</Top><Left>{0}in</Left><Width>{1}in</Width><Height>.2in</Height><Value>{2}</Value>
<Style><FontWeight>Bold</FontWeight><BorderStyle><Bottom>Solid</Bottom></BorderStyle>
<BorderWidth><Bottom>3pt</Bottom></BorderWidth></Style>
</Textbox>",
left,
width,
name);
left += width;
}
break;
case "listvalues":
left = .0m;
foreach (SqlColumn sq in _ColumnList)
{
name = GetFieldName(sq.Name);
DoAlignAndCanGrow(sq.DataType, out canGrow, out align);
width = name.Length / 8m;
if (width < 1)
width = 1;
sb.AppendFormat(cinfo, @"
<Textbox Name='{2}'><Top>.1in</Top><Left>{0}in</Left><Width>{1}in</Width><Height>.25in</Height><Value>=Fields!{2}.Value</Value><CanGrow>{3}</CanGrow><Style>{4}</Style></Textbox>",
left, width, name, canGrow, align);
left += width;
}
bodyHeight = .4m;
break;
case "listwidth": // in template list width must follow something that sets left
sb.AppendFormat(cinfo, "{0}in", left);
break;
case "tableheaders":
// the group by column is always the first one in the table
if (gbcolumn != null)
{
bodyHeight += 12m;
sb.AppendFormat(cinfo, @"
<TableCell>
<ReportItems><Textbox><Value>{0}</Value><Style><TextAlign>Center</TextAlign><BorderStyle><Default>Solid</Default></BorderStyle><FontWeight>Bold</FontWeight></Style></Textbox></ReportItems>
</TableCell>",
this.cbColumnList.Text);
}
bodyHeight += 12m;
foreach (SqlColumn sq in _ColumnList)
{
name = sq.Name;
if (name == this.cbColumnList.Text)
continue;
sb.AppendFormat(cinfo, @"
<TableCell>
<ReportItems><Textbox><Value>{0}</Value><Style><TextAlign>Center</TextAlign><BorderStyle><Default>Solid</Default></BorderStyle><FontWeight>Bold</FontWeight></Style></Textbox></ReportItems>
</TableCell>",
name);
}
break;
case "tablecolumns":
if (gbcolumn != null)
{
bodyHeight += 12m;
width = gbcolumn.Length / 8m; // TODO should really use data value
if (width < 1)
width = 1;
sb.AppendFormat(cinfo, @"<TableColumn><Width>{0}in</Width></TableColumn>", width);
}
bodyHeight += 12m;
foreach (SqlColumn sq in _ColumnList)
{
name = GetFieldName(sq.Name);
if (name == gbcolumn)
continue;
width = name.Length / 8m; // TODO should really use data value
if (width < 1)
width = 1;
sb.AppendFormat(cinfo, @"<TableColumn><Width>{0}in</Width></TableColumn>", width);
}
break;
case "tablevalues":
bodyHeight += 12m;
if (gbcolumn != null)
{
sb.Append(@"<TableCell>
<ReportItems><Textbox><Value></Value><Style><BorderStyle><Default>None</Default><Left>Solid</Left></BorderStyle></Style></Textbox></ReportItems>
</TableCell>");
}
foreach (SqlColumn sq in _ColumnList)
{
name = GetFieldName(sq.Name);
if (name == gbcolumn)
continue;
DoAlignAndCanGrow(sq.DataType, out canGrow, out align);
sb.AppendFormat(cinfo, @"
<TableCell>
<ReportItems><Textbox Name='{0}'><Value>=Fields!{0}.Value</Value><CanGrow>{1}</CanGrow><Style><BorderStyle><Default>Solid</Default></BorderStyle>{2}</Style></Textbox></ReportItems>
</TableCell>",
name, canGrow, align);
}
break;
case "gtablefooters":
case "tablefooters":
bodyHeight += 12m;
canGrow = "false";
align = "";
string nameprefix = p == "gtablefooters" ? "gf" : "tf";
if (gbcolumn != null) // handle group by column first
{
int i = clbSubtotal.FindStringExact(this.cbColumnList.Text);
SqlColumn sq = i < 0 ? null : (SqlColumn)clbSubtotal.Items[i];
if (i >= 0 && clbSubtotal.GetItemChecked(i))
{
string funct = DesignerUtility.IsNumeric(sq.DataType) ? "Sum" : "Count";
DoAlignAndCanGrow(((object)0).GetType(), out canGrow, out align);
sb.AppendFormat(cinfo, @"
<TableCell>
<ReportItems><Textbox Name='{4}_{0}'><Value>={1}(Fields!{0}.Value)</Value><CanGrow>{2}</CanGrow><Style><BorderStyle><Default>Solid</Default></BorderStyle>{3}</Style></Textbox></ReportItems>
</TableCell>",
gbcolumn, funct, canGrow, align, nameprefix);
}
else
{
sb.AppendFormat(cinfo, "<TableCell><ReportItems><Textbox><Value></Value><Style><BorderStyle><Default>Solid</Default></BorderStyle></Style></Textbox></ReportItems></TableCell>");
}
}
for (int i = 0; i < this.clbSubtotal.Items.Count; i++)
{
SqlColumn sq = (SqlColumn)clbSubtotal.Items[i];
name = GetFieldName(sq.Name);
if (name == gbcolumn)
continue;
if (clbSubtotal.GetItemChecked(i))
{
string funct = DesignerUtility.IsNumeric(sq.DataType) ? "Sum" : "Count";
DoAlignAndCanGrow(((object)0).GetType(), out canGrow, out align);
sb.AppendFormat(cinfo, @"
<TableCell>
<ReportItems><Textbox Name='{4}_{0}'><Value>={1}(Fields!{0}.Value)</Value><CanGrow>{2}</CanGrow><Style><BorderStyle><Default>Solid</Default></BorderStyle>{3}</Style></Textbox></ReportItems>
</TableCell>",
name, funct, canGrow, align, nameprefix);
}
else
{
sb.AppendFormat(cinfo, "<TableCell><ReportItems><Textbox><Value></Value><Style><BorderStyle><Default>Solid</Default></BorderStyle></Style></Textbox></ReportItems></TableCell>");
}
}
break;
case "bodyheight": // Note: this must follow the table definition
sb.AppendFormat(cinfo, "{0}pt", bodyHeight);
break;
default:
sb.Append(p);
break;
}
}
try
{
tbReportSyntax.Text = DesignerUtility.FormatXml(sb.ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Strings.DialogDatabase_Show_InternalError);
tbReportSyntax.Text = sb.ToString();
}
return true;
}
private string GetFieldName(string sqlName)
{
StringBuilder sb = new StringBuilder();
foreach (char c in sqlName)
{
if (Char.IsLetterOrDigit(c) || c == '_')
sb.Append(c);
else
sb.Append('_');
}
return sb.ToString();
}
private void DoAlignAndCanGrow(Type t, out string canGrow, out string align)
{
string st = t.ToString();
switch (st)
{
case "System.String":
canGrow = "true";
align = "<PaddingLeft>2pt</PaddingLeft>";
break;
case "System.Int16":
case "System.Int32":
case "System.Single":
case "System.Double":
case "System.Decimal":
canGrow = "false";
align = "<PaddingRight>2pt</PaddingRight><TextAlign>Right</TextAlign>";
break;
default:
canGrow = "false";
align = "<PaddingLeft>2pt</PaddingLeft>";
break;
}
return;
}
private void DoReportSyntaxParameters(CultureInfo cinfo, StringBuilder sb)
{
if (reportParameterCtl1.lbParameters.Items.Count <= 0)
return;
sb.Append("<ReportParameters>");
foreach (ReportParm rp in reportParameterCtl1.lbParameters.Items)
{
sb.AppendFormat(cinfo, "<ReportParameter Name=\"{0}\">", rp.Name);
sb.AppendFormat(cinfo, "<DataType>{0}</DataType>", rp.DataType);
sb.AppendFormat(cinfo, "<Nullable>{0}</Nullable>", rp.AllowNull.ToString());
if (rp.DefaultValue != null && rp.DefaultValue.Count > 0)
{
sb.AppendFormat(cinfo, "<DefaultValue><Values>");
foreach (string dv in rp.DefaultValue)
{
sb.AppendFormat(cinfo, "<Value>{0}</Value>", XmlUtil.XmlAnsi(dv));
}
sb.AppendFormat(cinfo, "</Values></DefaultValue>");
}
sb.AppendFormat(cinfo, "<AllowBlank>{0}</AllowBlank>", rp.AllowBlank);
if (rp.Prompt != null && rp.Prompt.Length > 0)
sb.AppendFormat(cinfo, "<Prompt>{0}</Prompt>", rp.Prompt);
if (rp.ValidValues != null && rp.ValidValues.Count > 0)
{
sb.Append("<ValidValues><ParameterValues>");
foreach (ParameterValueItem pvi in rp.ValidValues)
{
sb.Append("<ParameterValue>");
sb.AppendFormat(cinfo, "<Value>{0}</Value>", XmlUtil.XmlAnsi(pvi.Value));
if (pvi.Label != null)
sb.AppendFormat(cinfo, "<Label>{0}</Label>", XmlUtil.XmlAnsi(pvi.Label));
sb.Append("</ParameterValue>");
}
sb.Append("</ParameterValues></ValidValues>");
}
sb.Append("</ReportParameter>");
}
sb.Append("</ReportParameters>");
}
private void DoReportSyntaxQParameters(CultureInfo cinfo, StringBuilder sb, string sql)
{
if (reportParameterCtl1.lbParameters.Items.Count <= 0)
return;
bool bFirst = true;
foreach (ReportParm rp in reportParameterCtl1.lbParameters.Items)
{
// force the name to start with @
string paramName;
if (rp.Name[0] == '@')
paramName = rp.Name;
else
paramName = "@" + rp.Name;
// Only create a query parameter if parameter is used in the query
if (sql.IndexOf(paramName) >= 0)
{
if (bFirst)
{ // Only put out queryparameters if we actually have one
sb.Append("<QueryParameters>");
bFirst = false;
}
sb.AppendFormat(cinfo, "<QueryParameter Name=\"{0}\">", rp.Name);
sb.AppendFormat(cinfo, "<Value>=Parameters!{0}</Value>", rp.Name);
sb.Append("</QueryParameter>");
}
}
if (!bFirst)
sb.Append("</QueryParameters>");
}
private bool DoReportPreview()
{
if (!DoReportSyntax(true))
return false;
if (_rDesigner != null)
{
rdlViewer1.GetDataSourceReferencePassword = _rDesigner.SharedDatasetPassword;
}
else if (_rUserControl != null)
{
rdlViewer1.GetDataSourceReferencePassword = _rUserControl.SharedDatasetPassword;
}
rdlViewer1.SourceRdl = tbReportSyntax.Text;
return true;
}
private string GetDataProvider()
{
string cType = cbConnectionTypes.Text;
_StashConnection = null;
if (cType == SHARED_CONNECTION)
{
if (_rDesigner != null)
{
if (!DesignerUtility.GetSharedConnectionInfo(_rDesigner, tbConnection.Text, out cType, out _StashConnection))
return null;
}
else if(_rUserControl != null)
{
if (!DesignerUtility.GetSharedConnectionInfo(_rUserControl, tbConnection.Text, out cType, out _StashConnection))
return null;
}
}
else
{
_StashConnection = tbConnection.Text;
}
return cType;
}
private string GetDataConnection()
{ // GetDataProvider must be called first to ensure the DataConnection is correct.
return _StashConnection;
}
private void tvTablesColumns_BeforeExpand(object sender, System.Windows.Forms.TreeViewCancelEventArgs e)
{
tvTablesColumns_ExpandTable(e.Node);
}
private void tvTablesColumns_ExpandTable(TreeNode tNode)
{
if (tNode.Parent == null) // Check for Tables or Views
return;
if (tNode.FirstNode.Text != "") // Have we already filled it out?
return;
// Need to obtain the column information for the requested table/view
// suppress redraw until tree view is complete
tvTablesColumns.BeginUpdate();
string sql = "SELECT * FROM " + DesignerUtility.NormalizeSqlName(tNode.Text);
List<SqlColumn> tColumns = DesignerUtility.GetSqlColumns(GetDataProvider(), GetDataConnection(), sql, null);
bool bFirstTime = true;
foreach (SqlColumn sc in tColumns)
{
if (bFirstTime)
{
bFirstTime = false;
tNode.FirstNode.Text = sc.Name;
}
else
tNode.Nodes.Add(sc.Name);
}
tvTablesColumns.EndUpdate();
}
private void tbSQL_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text)) // only accept text
e.Effect = DragDropEffects.Copy;
}
private void tbSQL_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text))
tbSQL.SelectedText = (string)e.Data.GetData(DataFormats.Text);
}
private void tvTablesColumns_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
TreeNode node = tvTablesColumns.GetNodeAt(e.X, e.Y);
if (node == null || node.Parent == null)
return;
string dragText;
if (tbSQL.Text == "")
{
if (node.Parent.Parent == null)
{ // select table; generate full select for table
tvTablesColumns_ExpandTable(node); // make sure we've obtained the columns
dragText = "SELECT ";
TreeNode next = node.FirstNode;
while (true)
{
dragText += DesignerUtility.NormalizeSqlName(next.Text);
next = next.NextNode;
if (next == null)
break;
dragText += ", ";
}
dragText += (" FROM " + DesignerUtility.NormalizeSqlName(node.Text));
}
else
{ // select column; generate select of that column
dragText = "SELECT " + DesignerUtility.NormalizeSqlName(node.Text) + " FROM " + DesignerUtility.NormalizeSqlName(node.Parent.Text);
}
}
else
dragText = node.Text;
tvTablesColumns.DoDragDrop(dragText, DragDropEffects.Copy);
}
private void DialogDatabase_Closed(object sender, System.EventArgs e)
{
if (_TempFileName != null)
File.Delete(_TempFileName);
}
private void tbSQL_TextChanged(object sender, System.EventArgs e)
{
tbReportSyntax.Text = ""; // when SQL changes get rid of report syntax
_ColumnList = null; // get rid of any column list as well
cbColumnList.Items.Clear(); // and clear out other places where columns show
cbColumnList.Text = "";
clbSubtotal.Items.Clear();
}
private void tbReportName_TextChanged(object sender, System.EventArgs e)
{
tbReportSyntax.Text = ""; // when SQL changes get rid of report syntax
}
private void tbReportDescription_TextChanged(object sender, System.EventArgs e)
{
tbReportSyntax.Text = ""; // when SQL changes get rid of report syntax
}
private void tbReportAuthor_TextChanged(object sender, System.EventArgs e)
{
tbReportSyntax.Text = ""; // when SQL changes get rid of report syntax
}
private void rbTable_CheckedChanged(object sender, System.EventArgs e)
{
tbReportSyntax.Text = ""; // when SQL changes get rid of report syntax
if (rbTable.Checked)
{
TabularGroup.Enabled = true;
}
else
{
TabularGroup.Enabled = false;
}
}
private void rbList_CheckedChanged(object sender, System.EventArgs e)
{
tbReportSyntax.Text = ""; // when SQL changes get rid of report syntax
}
private void rbMatrix_CheckedChanged(object sender, System.EventArgs e)
{
tbReportSyntax.Text = ""; // when SQL changes get rid of report syntax
}
private void rbChart_CheckedChanged(object sender, System.EventArgs e)
{
tbReportSyntax.Text = ""; // when SQL changes get rid of report syntax
}
//private void bAdd_Click(object sender, System.EventArgs e)
//{
// ReportParm rp = new ReportParm("newparm");
// int cur = reportParameterCtl1.lbParameters.Items.Add(rp);
// reportParameterCtl1.lbParameters.SelectedIndex = cur;
// this.tbParmName.Focus();
//}
//private void bRemove_Click(object sender, System.EventArgs e)
//{
// int cur = lbParameters.SelectedIndex;
// if (cur < 0)
// return;
// lbParameters.Items.RemoveAt(cur);
// if (lbParameters.Items.Count <= 0)
// return;
// cur--;
// if (cur < 0)
// cur = 0;
// lbParameters.SelectedIndex = cur;
//}
//private void lbParameters_SelectedIndexChanged(object sender, System.EventArgs e)
//{
// int cur = lbParameters.SelectedIndex;
// if (cur < 0)
// return;
// ReportParm rp = lbParameters.Items[cur] as ReportParm;
// if (rp == null)
// return;
// tbParmName.Text = rp.Name;
// cbParmType.Text = rp.DataType;
// tbParmPrompt.Text = rp.Prompt;
// tbParmDefaultValue.Text = rp.DefaultValueDisplay;
// ckbParmAllowBlank.Checked = rp.AllowBlank;
// tbParmValidValues.Text = rp.ValidValuesDisplay;
// ckbParmAllowNull.Checked = rp.AllowNull;
//}
//private void lbParameters_MoveItem(int curloc, int newloc)
//{
// ReportParm rp = lbParameters.Items[curloc] as ReportParm;
// if (rp == null)
// return;
// lbParameters.BeginUpdate();
// lbParameters.Items.RemoveAt(curloc);
// lbParameters.Items.Insert(newloc, rp);
// lbParameters.SelectedIndex = newloc;
// lbParameters.EndUpdate();
//}
//private void tbParmName_TextChanged(object sender, System.EventArgs e)
//{
// int cur = lbParameters.SelectedIndex;
// if (cur < 0)
// return;
// ReportParm rp = lbParameters.Items[cur] as ReportParm;
// if (rp == null)
// return;
// if (rp.Name == tbParmName.Text)
// return;
// rp.Name = tbParmName.Text;
// // text doesn't change in listbox; force change by removing and re-adding item
// lbParameters_MoveItem(cur, cur);
//}
//private void cbParmType_SelectedIndexChanged(object sender, System.EventArgs e)
//{
// int cur = lbParameters.SelectedIndex;
// if (cur < 0)
// return;
// ReportParm rp = lbParameters.Items[cur] as ReportParm;
// if (rp == null)
// return;
// rp.DataType = cbParmType.Text;
//}
//private void tbParmPrompt_TextChanged(object sender, System.EventArgs e)
//{
// int cur = lbParameters.SelectedIndex;
// if (cur < 0)
// return;
// ReportParm rp = lbParameters.Items[cur] as ReportParm;
// if (rp == null)
// return;
// rp.Prompt = tbParmPrompt.Text;
//}
//private void ckbParmAllowNull_CheckedChanged(object sender, System.EventArgs e)
//{
// int cur = lbParameters.SelectedIndex;
// if (cur < 0)
// return;
// ReportParm rp = lbParameters.Items[cur] as ReportParm;
// if (rp == null)
// return;
// rp.AllowNull = ckbParmAllowNull.Checked;
//}
//private void ckbParmAllowBlank_CheckedChanged(object sender, System.EventArgs e)
//{
// int cur = lbParameters.SelectedIndex;
// if (cur < 0)
// return;
// ReportParm rp = lbParameters.Items[cur] as ReportParm;
// if (rp == null)
// return;
// rp.AllowBlank = ckbParmAllowBlank.Checked;
//}
//private void bParmUp_Click(object sender, System.EventArgs e)
//{
// int cur = lbParameters.SelectedIndex;
// if (cur <= 0)
// return;
// lbParameters_MoveItem(cur, cur - 1);
//}
//private void bParmDown_Click(object sender, System.EventArgs e)
//{
// int cur = lbParameters.SelectedIndex;
// if (cur + 1 >= lbParameters.Items.Count)
// return;
// lbParameters_MoveItem(cur, cur + 1);
//}
//private void tbParmDefaultValue_TextChanged(object sender, System.EventArgs e)
//{
// int cur = lbParameters.SelectedIndex;
// if (cur < 0)
// return;
// ReportParm rp = lbParameters.Items[cur] as ReportParm;
// if (rp == null)
// return;
// if (tbParmDefaultValue.Text.Length > 0)
// {
// if (rp.DefaultValue == null)
// rp.DefaultValue = new List<string>();
// else
// rp.DefaultValue.Clear();
// rp.DefaultValue.Add(tbParmDefaultValue.Text);
// }
// else
// rp.DefaultValue = null;
//}
private void tbConnection_TextChanged(object sender, System.EventArgs e)
{
tvTablesColumns.Nodes.Clear();
}
private void emptyReportSyntax(object sender, System.EventArgs e)
{
tbReportSyntax.Text = ""; // need to generate another report
}
private void bMove_Click(object sender, System.EventArgs e)
{
if (tvTablesColumns.SelectedNode == null ||
tvTablesColumns.SelectedNode.Parent == null)
return; // this is the Tables/Views node
TreeNode node = tvTablesColumns.SelectedNode;
string t = node.Text;
if (tbSQL.Text == "")
{
if (node.Parent.Parent == null)
{ // select table; generate full select for table
tvTablesColumns_ExpandTable(node); // make sure we've obtained the columns
StringBuilder sb = new StringBuilder("SELECT ");
TreeNode next = node.FirstNode;
while (true)
{
sb.Append(DesignerUtility.NormalizeSqlName(next.Text));
next = next.NextNode;
if (next == null)
break;
sb.Append(", ");
}
sb.Append(" FROM ");
sb.Append(DesignerUtility.NormalizeSqlName(node.Text));
t = sb.ToString();
}
else
{ // select column; generate select of that column
t = "SELECT " + DesignerUtility.NormalizeSqlName(node.Text) + " FROM " + DesignerUtility.NormalizeSqlName(node.Parent.Text);
}
}
tbSQL.SelectedText = t;
}
//private void bValidValues_Click(object sender, System.EventArgs e)
//{
// int cur = lbParameters.SelectedIndex;
// if (cur < 0)
// return;
// ReportParm rp = lbParameters.Items[cur] as ReportParm;
// if (rp == null)
// return;
// DialogValidValues dvv = new DialogValidValues(rp.ValidValues);
// try
// {
// if (dvv.ShowDialog() != DialogResult.OK)
// return;
// rp.ValidValues = dvv.ValidValues;
// this.tbParmValidValues.Text = rp.ValidValuesDisplay;
// }
// finally
// {
// dvv.Dispose();
// }
//}
private void cbConnectionTypes_SelectedIndexChanged(object sender, System.EventArgs e)
{
groupBoxSqlServer.Visible = false;
buttonSqliteSelectDatabase.Visible = false;
if (cbConnectionTypes.Text == SHARED_CONNECTION)
{
lConnection.Text = Strings.DialogDatabase_cbConnectionTypes_SelectedIndexChanged_Shared_Data_Source_File;
bShared.Visible = true;
}
else
{
lConnection.Text = Strings.DialogDatabase_cbConnectionTypes_SelectedIndexChanged_Connection;
bShared.Visible = false;
}
if (cbConnectionTypes.Text == "ODBC")
{
lODBC.Visible = cbOdbcNames.Visible = true;
DesignerUtility.FillOdbcNames(cbOdbcNames);
}
else
{
lODBC.Visible = cbOdbcNames.Visible = false;
}
// this is only for ease of testing
switch (cbConnectionTypes.Text)
{
case "SQL":
tbConnection.Text = "Server=(local)\\ServerInstance;DataBase=DatabaseName;User Id=myUsername;Password=myPassword;Connect Timeout=5";
groupBoxSqlServer.Visible = true;
break;
case "ODBC":
tbConnection.Text = "dsn=world;UID=user;PWD=password;";
break;
case "Oracle":
tbConnection.Text = "User Id=SYSTEM;Password=password;Data Source=server";
break;
case "Firebird.NET":
tbConnection.Text = @"Dialect=3;User Id=SYSDBA;Database=daabaseFile.fdb;Data Source=localhost;Password=password";
break;
case "MySQL.NET":
tbConnection.Text = "database=world;user id=user;password=password;";
break;
case "iAnywhere.NET":
tbConnection.Text = "Data Source=ASA 9.0 Sample;UID=DBA;PWD=password";
break;
case "SQLite":
tbConnection.Text = "Data Source=filename;Version=3;Password=myPassword;Pooling=True;Max Pool Size=100;";
buttonSqliteSelectDatabase.Visible = true;
break;
case "PostgreSQL":
tbConnection.Text = "Server=127.0.0.1;Port=5432;Database=myDataBase;User Id=myUsername;Password=myPassword;";
break;
default:
tbConnection.Text = "";
break;
}
}
private void cbOdbcNames_SelectedIndexChanged(object sender, System.EventArgs e)
{
string name = "dsn=" + cbOdbcNames.Text + ";";
this.tbConnection.Text = name;
}
private void bTestConnection_Click(object sender, System.EventArgs e)
{
if (string.IsNullOrEmpty(tbConnection.Text))
{
MessageBox.Show(Strings.DialogDatabase_ShowD_SelectDataProvider, Strings.DesignerUtility_Show_TestConnection, MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
string cType = GetDataProvider();
if (cType == null)
return;
if (DesignerUtility.TestConnection(cType, GetDataConnection()))
MessageBox.Show(Strings.DialogDatabase_Show_ConnectionSuccessful, Strings.DesignerUtility_Show_TestConnection);
}
private void DBConnection_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
if (!DesignerUtility.TestConnection(this.GetDataConnection(), GetDataConnection()))
e.Cancel = true;
}
private void bShared_Click(object sender, System.EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = Strings.DialogDatabase_bShared_Click_DSRFilter;
ofd.FilterIndex = 1;
if (tbConnection.Text.Length > 0)
ofd.FileName = tbConnection.Text;
else
ofd.FileName = "*.dsr";
ofd.Title = Strings.DialogDatabase_bShared_Click_DSRTitle;
ofd.CheckFileExists = true;
ofd.DefaultExt = "dsr";
ofd.AddExtension = true;
try
{
if (ofd.ShowDialog() == DialogResult.OK)
tbConnection.Text = ofd.FileName;
}
finally
{
ofd.Dispose();
}
}
private void buttonSqliteSelectDatabase_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
try
{
ofd.Filter = Strings.DialogDatabase_buttonSqliteSelectDatabase_Click_AllFilesFilter;
ofd.CheckFileExists = true;
try
{
if (ofd.ShowDialog(this) != DialogResult.OK)
{
return;
}
if (tbConnection.Text.Trim() == "")
{
tbConnection.Text = "Data Source=" + ofd.FileName;
}
else
{
string[] sections = tbConnection.Text.Split(';');
foreach (string section in sections)
{
if (section.ToLower().Contains("data source"))
{
string dataSource = string.Format("Data Source={0}", ofd.FileName);
tbConnection.Text = tbConnection.Text.Replace(section, dataSource);
break;
}
}
}
}
finally
{
ofd.Dispose();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Strings.DialogDatabase_ShowD_Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonSearchSqlServers_Click(object sender, EventArgs e)
{
try
{
System.Data.Sql.SqlDataSourceEnumerator instance = System.Data.Sql.SqlDataSourceEnumerator.Instance;
DataTable dt;
dt = instance.GetDataSources();
Dictionary<string, string> dict = new Dictionary<string, string>();
foreach (System.Data.DataRow row in dt.Rows)
{
string server = row["ServerName"].ToString();
if (row["InstanceName"].ToString() != "")
{
server = server + @"\" + row["InstanceName"].ToString();
}
dict.Add(server, server);
}
comboServerList.ValueMember = "Value";
comboServerList.DisplayMember = "Key";
comboServerList.DataSource = new BindingSource(dict, null);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, Strings.DialogDatabase_ShowD_Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonDatabaseSearch_Click(object sender, EventArgs e)
{
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
System.Data.SqlClient.SqlDataAdapter da;
DataTable dt = new DataTable();
string connectionString = string.Format("server={0}; Database={1};User ID={2}; Password={3}; Trusted_Connection=False;",
comboServerList.SelectedValue.ToString(), "master", textBoxSqlUser.Text, textBoxSqlPassword.Text);
SqlConnection cn = new System.Data.SqlClient.SqlConnection(connectionString); ;
try
{
cn.Open();
cmd.Connection = cn;
cmd.CommandText = "sp_databases";
cmd.CommandType = CommandType.StoredProcedure;
da = new System.Data.SqlClient.SqlDataAdapter(cmd);
da.Fill(dt);
dt.TableName = "master";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Strings.DialogDatabase_ShowD_Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
finally
{
cn.Close();
}
try
{
Dictionary<string, string> dict = new Dictionary<string, string>();
foreach (System.Data.DataRow row in dt.Rows)
{
string database = row["DATABASE_NAME"].ToString();
dict.Add(database, database);
}
comboDatabaseList.ValueMember = "Value";
comboDatabaseList.DisplayMember = "Key";
comboDatabaseList.DataSource = new BindingSource(dict, null);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Strings.DialogDatabase_ShowD_Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void tbSQL_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.A)
{
tbSQL.SelectAll();
}
}
private void DialogDatabase_Load(object sender, EventArgs e)
{
}
private void comboServerList_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboServerList.Items.Count == 0)
{
return;
}
string[] sections = tbConnection.Text.Split(';');
foreach (string section in sections)
{
if (section.ToLower().Contains("server="))
{
string dataSource = string.Format("server={0}", comboServerList.SelectedValue.ToString());
tbConnection.Text = tbConnection.Text.Replace(section, dataSource);
break;
}
}
}
private void comboDatabaseList_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboDatabaseList.Items.Count == 0)
{
return;
}
string[] sections = tbConnection.Text.Split(';');
foreach (string section in sections)
{
if (section.ToLower().Contains("database="))
{
string dataSource = string.Format("database={0}", comboDatabaseList.SelectedValue.ToString());
tbConnection.Text = tbConnection.Text.Replace(section, dataSource);
break;
}
}
}
}
}
| |
//
// ServiceStack.OrmLite: Light-weight POCO ORM for .NET and Mono
//
// Authors:
// Demis Bellot (demis.bellot@gmail.com)
//
// Copyright 2010 Liquidbit Ltd.
//
// Licensed under the same terms of ServiceStack: new BSD license.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Text;
using NServiceKit.Logging;
using NServiceKit.Text;
using System.Linq;
namespace NServiceKit.OrmLite
{
/// <summary>Gets quoted value delegate.</summary>
/// <param name="value"> The value.</param>
/// <param name="fieldType">Type of the field.</param>
/// <returns>A string.</returns>
public delegate string GetQuotedValueDelegate(object value, Type fieldType);
/// <summary>Convert database value delegate.</summary>
/// <param name="value">The value.</param>
/// <param name="type"> The type.</param>
/// <returns>An object.</returns>
public delegate object ConvertDbValueDelegate(object value, Type type);
/// <summary>Property setter delegate.</summary>
/// <param name="instance">The instance.</param>
/// <param name="value"> The value.</param>
public delegate void PropertySetterDelegate(object instance, object value);
/// <summary>Property getter delegate.</summary>
/// <param name="instance">The instance.</param>
/// <returns>An object.</returns>
public delegate object PropertyGetterDelegate(object instance);
/// <summary>Gets value delegate.</summary>
/// <param name="i">Zero-based index of the.</param>
/// <returns>An object.</returns>
public delegate object GetValueDelegate(int i);
/// <summary>An ORM lite read extensions.</summary>
public static class OrmLiteReadExtensions
{
/// <summary>The log.</summary>
private static readonly ILog Log = LogManager.GetLogger(typeof(OrmLiteReadExtensions));
/// <summary>The use database connection extensions.</summary>
public const string UseDbConnectionExtensions = "Use IDbConnection Extensions instead";
/// <summary>(Only available in DEBUG builds) logs a debug.</summary>
/// <param name="fmt"> Describes the format to use.</param>
/// <param name="args">A variable-length parameters list containing arguments.</param>
[Conditional("DEBUG")]
private static void LogDebug(string fmt, params object[] args)
{
if (args.Length > 0)
Log.DebugFormat(fmt, args);
else
Log.Debug(fmt);
}
internal static void SetDbCommandParams(this IDbCommand dbCmd, string sql,
IEnumerable<IDataParameter> parameters = null)
{
LogDebug(sql);
dbCmd.CommandTimeout = OrmLiteConfig.CommandTimeout;
dbCmd.CommandText = sql;
if (parameters != null)
{
dbCmd.Parameters.Clear();
foreach (var param in parameters)
{
dbCmd.Parameters.Add(param);
}
}
}
/// <summary>An IDbCommand extension method that executes the reader operation.</summary>
/// <param name="dbCmd">The dbCmd to act on.</param>
/// <param name="sql"> The SQL.</param>
/// <returns>An IDataReader.</returns>
internal static IDataReader ExecReader(this IDbCommand dbCmd, string sql)
{
LogDebug(sql);
dbCmd.CommandTimeout = OrmLiteConfig.CommandTimeout;
dbCmd.CommandText = sql;
return dbCmd.ExecuteReader();
}
/// <summary>An IDbCommand extension method that executes the reader operation.</summary>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="sql"> The SQL.</param>
/// <param name="parameters">Options for controlling the operation.</param>
/// <returns>An IDataReader.</returns>
internal static IDataReader ExecReader(this IDbCommand dbCmd, string sql, IEnumerable<IDataParameter> parameters)
{
LogDebug(sql);
dbCmd.CommandTimeout = OrmLiteConfig.CommandTimeout;
dbCmd.CommandText = sql;
dbCmd.Parameters.Clear();
foreach (var param in parameters)
{
dbCmd.Parameters.Add(param);
}
return dbCmd.ExecuteReader();
}
/// <summary>Gets value function.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="reader">The reader to act on.</param>
/// <returns>The value function.</returns>
public static GetValueDelegate GetValueFn<T>(IDataRecord reader)
{
var type = typeof(T);
if (type == typeof(string))
return reader.GetString;
if (type == typeof(short))
return i => reader.GetInt16(i);
if (type == typeof(int))
return i => reader.GetInt32(i);
if (type == typeof(long))
return i => reader.GetInt64(i);
if (type == typeof(bool))
return i => reader.GetBoolean(i);
if (type == typeof(DateTime))
return i => reader.GetDateTime(i);
if (type == typeof(Guid))
return i => reader.GetGuid(i);
if (type == typeof(float))
return i => reader.GetFloat(i);
if (type == typeof(double))
return i => reader.GetDouble(i);
if (type == typeof(decimal) || type == typeof(decimal?))
return i => reader.GetDecimal(i);
return reader.GetValue;
}
/// <summary>Query if this object is scalar.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <returns>true if scalar, false if not.</returns>
public static bool IsScalar<T>()
{
return typeof(T).IsValueType || typeof(T) == typeof(string);
}
/// <summary>An IDbCommand extension method that selects.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd">The dbCmd to act on.</param>
/// <returns>A List<TModel></returns>
internal static List<T> Select<T>(this IDbCommand dbCmd)
{
return Select<T>(dbCmd, (string)null);
}
/// <summary>An IDbCommand extension method that selects.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="sqlFilter"> A filter specifying the SQL.</param>
/// <param name="filterParams">Options for controlling the filter.</param>
/// <returns>A List<TModel></returns>
internal static List<T> Select<T>(this IDbCommand dbCmd, string sqlFilter, params object[] filterParams)
{
using (var reader = dbCmd.ExecReader(
OrmLiteConfig.DialectProvider.ToSelectStatement(typeof(T), sqlFilter, filterParams)))
{
return reader.ConvertToList<T>();
}
}
/// <summary>An IDbCommand extension method that selects.</summary>
/// <typeparam name="TModel">Type of the model.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="fromTableType">Type of from table.</param>
/// <returns>A List<TModel></returns>
internal static List<TModel> Select<TModel>(this IDbCommand dbCmd, Type fromTableType)
{
return Select<TModel>(dbCmd, fromTableType, null);
}
/// <summary>An IDbCommand extension method that selects.</summary>
/// <typeparam name="TModel">Type of the model.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="fromTableType">Type of from table.</param>
/// <param name="sqlFilter"> A filter specifying the SQL.</param>
/// <param name="filterParams"> Options for controlling the filter.</param>
/// <returns>A List<TModel></returns>
internal static List<TModel> Select<TModel>(this IDbCommand dbCmd, Type fromTableType, string sqlFilter, params object[] filterParams)
{
var sql = new StringBuilder();
var modelDef = ModelDefinition<TModel>.Definition;
sql.AppendFormat("SELECT {0} FROM {1}", OrmLiteConfig.DialectProvider.GetColumnNames( modelDef),
OrmLiteConfig.DialectProvider.GetQuotedTableName(fromTableType.GetModelDefinition()));
if (!string.IsNullOrEmpty(sqlFilter))
{
sqlFilter = sqlFilter.SqlFormat(filterParams);
sql.Append(" WHERE ");
sql.Append(sqlFilter);
}
using (var reader = dbCmd.ExecReader(sql.ToString()))
{
return reader.ConvertToList<TModel>();
}
}
/// <summary>Enumerates each in this collection.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="filter"> Specifies the filter.</param>
/// <param name="filterParams">Options for controlling the filter.</param>
/// <returns>
/// An enumerator that allows foreach to be used to process each in this collection.
/// </returns>
internal static IEnumerable<T> Each<T>(this IDbCommand dbCmd, string filter, params object[] filterParams)
{
dbCmd.SetDbCommandParams(OrmLiteConfig.DialectProvider.ToSelectStatement(typeof(T), filter, filterParams));
return dbCmd.Each<T>();
}
/// <summary>An IDbCommand extension method that firsts.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="filter"> Specifies the filter.</param>
/// <param name="filterParams">Options for controlling the filter.</param>
/// <returns>A T.</returns>
internal static T First<T>(this IDbCommand dbCmd, string filter, params object[] filterParams)
{
return First<T>(dbCmd, filter.SqlFormat(filterParams));
}
/// <summary>An IDbCommand extension method that firsts.</summary>
/// <exception cref="ArgumentNullException">Thrown when one or more required arguments are null.</exception>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="filter">Specifies the filter.</param>
/// <returns>A T.</returns>
internal static T First<T>(this IDbCommand dbCmd, string filter)
{
var result = FirstOrDefault<T>(dbCmd, filter);
if (Equals(result, default(T)))
{
throw new ArgumentNullException(string.Format(
"{0}: '{1}' does not exist", typeof(T).Name, filter));
}
return result;
}
/// <summary>An IDbCommand extension method that first or default.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="filter"> Specifies the filter.</param>
/// <param name="filterParams">Options for controlling the filter.</param>
/// <returns>A T.</returns>
internal static T FirstOrDefault<T>(this IDbCommand dbCmd, string filter, params object[] filterParams)
{
return FirstOrDefault<T>(dbCmd, filter.SqlFormat(filterParams));
}
/// <summary>An IDbCommand extension method that first or default.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="filter">Specifies the filter.</param>
/// <returns>A T.</returns>
internal static T FirstOrDefault<T>(this IDbCommand dbCmd, string filter)
{
using (var dbReader = dbCmd.ExecReader(
OrmLiteConfig.DialectProvider.ToSelectStatement(typeof(T), filter)))
{
return dbReader.ConvertTo<T>();
}
}
/// <summary>An IDbCommand extension method that gets by identifier.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="idValue">The identifier value.</param>
/// <returns>The by identifier.</returns>
internal static T GetById<T>(this IDbCommand dbCmd, object idValue)
{
return First<T>(dbCmd, OrmLiteConfig.DialectProvider.GetQuotedColumnName(ModelDefinition<T>.PrimaryKeyName) + " = {0}".SqlFormat(idValue));
}
/// <summary>Type of the last query.</summary>
[ThreadStatic]
private static Type lastQueryType;
/// <summary>Sets a filter.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd">The dbCmd to act on.</param>
/// <param name="name"> The name.</param>
/// <param name="value">The value.</param>
private static void SetFilter<T>(IDbCommand dbCmd, string name, object value)
{
dbCmd.Parameters.Clear();
var p = dbCmd.CreateParameter();
p.ParameterName = name;
p.DbType = OrmLiteConfig.DialectProvider.GetColumnDbType(value.GetType());
p.Direction = ParameterDirection.Input;
dbCmd.Parameters.Add(p);
dbCmd.CommandText = GetFilterSql<T>(dbCmd);
lastQueryType = typeof(T);
}
/// <summary>An IDbCommand extension method that sets the filters.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="anonType"> Type of the anon.</param>
/// <param name="excludeNulls">true to exclude, false to include the nulls.</param>
public static void SetFilters<T>(this IDbCommand dbCmd, object anonType, bool excludeNulls)
{
SetParameters<T>(dbCmd, anonType, excludeNulls);
dbCmd.CommandText = GetFilterSql<T>(dbCmd);
}
/// <summary>An IDbCommand extension method that sets the parameters.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="anonType"> Type of the anon.</param>
/// <param name="excludeNulls">true to exclude, false to include the nulls.</param>
private static void SetParameters<T>(this IDbCommand dbCmd, object anonType, bool excludeNulls)
{
dbCmd.Parameters.Clear();
lastQueryType = null;
if (anonType == null) return;
var pis = anonType.GetType().GetSerializableProperties();
var model = ModelDefinition<T>.Definition;
foreach (var pi in pis)
{
var mi = pi.GetGetMethod();
if (mi == null) continue;
var value = mi.Invoke(anonType, new object[0]);
if (excludeNulls && value == null) continue;
var p = dbCmd.CreateParameter();
var targetField = model != null ? model.FieldDefinitions.FirstOrDefault(f => string.Equals(f.Name, pi.Name)) : null;
if (targetField != null && !string.IsNullOrEmpty(targetField.Alias))
p.ParameterName = targetField.Alias;
else
p.ParameterName = pi.Name;
p.DbType = OrmLiteConfig.DialectProvider.GetColumnDbType(pi.PropertyType);
p.Direction = ParameterDirection.Input;
p.Value = value ?? DBNull.Value;
dbCmd.Parameters.Add(p);
}
}
/// <summary>An IDbCommand extension method that sets the parameters.</summary>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="anonType"> Type of the anon.</param>
/// <param name="excludeNulls">true to exclude, false to include the nulls.</param>
private static void SetParameters(this IDbCommand dbCmd, object anonType, bool excludeNulls)
{
dbCmd.Parameters.Clear();
lastQueryType = null;
if (anonType == null)
return;
var pis = anonType.GetType().GetSerializableProperties();
foreach (var pi in pis)
{
var mi = pi.GetGetMethod();
if (mi == null)
continue;
var value = mi.Invoke(anonType, new object[0]);
if (excludeNulls && value == null)
continue;
var p = dbCmd.CreateParameter();
p.ParameterName = pi.Name;
p.DbType = OrmLiteConfig.DialectProvider.GetColumnDbType(pi.PropertyType);
p.Direction = ParameterDirection.Input;
p.Value = value ?? DBNull.Value;
dbCmd.Parameters.Add(p);
}
}
/// <summary>An IDbCommand extension method that sets the parameters.</summary>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="dict"> The dictionary.</param>
/// <param name="excludeNulls">true to exclude, false to include the nulls.</param>
private static void SetParameters(this IDbCommand dbCmd, Dictionary<string,object> dict, bool excludeNulls)
{
dbCmd.Parameters.Clear();
lastQueryType = null;
if (dict == null) return;
foreach (var kvp in dict)
{
var value = dict[kvp.Key];
if (excludeNulls && value == null) continue;
var p = dbCmd.CreateParameter();
p.ParameterName = kvp.Key;
if (value != null)
{
p.DbType = OrmLiteConfig.DialectProvider.GetColumnDbType(value.GetType());
}
p.Direction = ParameterDirection.Input;
p.Value = value ?? DBNull.Value;
dbCmd.Parameters.Add(p);
}
}
/// <summary>An IDbCommand extension method that sets the filters.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="anonType">Type of the anon.</param>
public static void SetFilters<T>(this IDbCommand dbCmd, object anonType)
{
dbCmd.SetFilters<T>(anonType, excludeNulls: false);
}
/// <summary>
/// An IDbCommand extension method that clears the filters described by dbCmd.
/// </summary>
/// <param name="dbCmd">The dbCmd to act on.</param>
public static void ClearFilters(this IDbCommand dbCmd)
{
dbCmd.Parameters.Clear();
}
/// <summary>Gets filter SQL.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd">The dbCmd to act on.</param>
/// <returns>The filter SQL.</returns>
private static string GetFilterSql<T>(IDbCommand dbCmd)
{
var sb = new StringBuilder();
for (var i = 0; i < dbCmd.Parameters.Count; i++)
{
sb.Append(i == 0 ? " " : " AND ");
var p = (IDbDataParameter)dbCmd.Parameters[i];
sb.AppendFormat("{0} = {1}{2}",
OrmLiteConfig.DialectProvider.GetQuotedColumnName(p.ParameterName),
OrmLiteConfig.DialectProvider.ParamString,
p.ParameterName);
}
return OrmLiteConfig.DialectProvider.ToSelectStatement(typeof(T), sb.ToString());
}
/// <summary>An IDbCommand extension method that queries by identifier.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd">The dbCmd to act on.</param>
/// <param name="value">The value.</param>
/// <returns>The by identifier.</returns>
internal static T QueryById<T>(this IDbCommand dbCmd, object value)
{
if (dbCmd.Parameters.Count != 1
|| ((IDbDataParameter)dbCmd.Parameters[0]).ParameterName != ModelDefinition<T>.PrimaryKeyName
|| lastQueryType != typeof(T))
SetFilter<T>(dbCmd, ModelDefinition<T>.PrimaryKeyName, value);
((IDbDataParameter)dbCmd.Parameters[0]).Value = value;
using (var dbReader = dbCmd.ExecuteReader())
return dbReader.ConvertTo<T>();
}
/// <summary>An IDbCommand extension method that single where.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd">The dbCmd to act on.</param>
/// <param name="name"> The name.</param>
/// <param name="value">The value.</param>
/// <returns>A T.</returns>
internal static T SingleWhere<T>(this IDbCommand dbCmd, string name, object value)
{
if (dbCmd.Parameters.Count != 1 || ((IDbDataParameter)dbCmd.Parameters[0]).ParameterName != name
|| lastQueryType != typeof(T))
SetFilter<T>(dbCmd, name, value);
((IDbDataParameter)dbCmd.Parameters[0]).Value = value;
using (var dbReader = dbCmd.ExecuteReader())
return dbReader.ConvertTo<T>();
}
/// <summary>An IDbCommand extension method that queries a single.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="anonType">Type of the anon.</param>
/// <returns>The single.</returns>
internal static T QuerySingle<T>(this IDbCommand dbCmd, object anonType)
{
if (IsScalar<T>()) return QueryScalar<T>(dbCmd, anonType);
dbCmd.SetFilters<T>(anonType, excludeNulls: false);
using (var dbReader = dbCmd.ExecuteReader())
return dbReader.ConvertTo<T>();
}
/// <summary>An IDbCommand extension method that queries a single.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="sql"> The SQL.</param>
/// <param name="anonType">Type of the anon.</param>
/// <returns>The single.</returns>
internal static T QuerySingle<T>(this IDbCommand dbCmd, string sql, object anonType)
{
if (IsScalar<T>()) return QueryScalar<T>(dbCmd, sql, anonType);
dbCmd.SetParameters<T>(anonType, excludeNulls: false);
dbCmd.CommandText = OrmLiteConfig.DialectProvider.ToSelectStatement(typeof(T), sql);
using (var dbReader = dbCmd.ExecuteReader())
return dbReader.ConvertTo<T>();
}
/// <summary>An IDbCommand extension method that wheres.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd">The dbCmd to act on.</param>
/// <param name="name"> The name.</param>
/// <param name="value">The value.</param>
/// <returns>A List<T></returns>
internal static List<T> Where<T>(this IDbCommand dbCmd, string name, object value)
{
if (dbCmd.Parameters.Count != 1 || ((IDbDataParameter)dbCmd.Parameters[0]).ParameterName != name
|| lastQueryType != typeof(T))
SetFilter<T>(dbCmd, name, value);
((IDbDataParameter)dbCmd.Parameters[0]).Value = value;
using (var dbReader = dbCmd.ExecuteReader())
return dbReader.ConvertToList<T>();
}
/// <summary>An IDbCommand extension method that wheres.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="anonType">Type of the anon.</param>
/// <returns>A List<T></returns>
internal static List<T> Where<T>(this IDbCommand dbCmd, object anonType)
{
dbCmd.SetFilters<T>(anonType);
using (var dbReader = dbCmd.ExecuteReader())
return IsScalar<T>()
? dbReader.GetFirstColumn<T>()
: dbReader.ConvertToList<T>();
}
/// <summary>An IDbCommand extension method that queries.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="sql"> The SQL.</param>
/// <param name="anonType">Type of the anon.</param>
/// <returns>A List<T></returns>
internal static List<T> Query<T>(this IDbCommand dbCmd, string sql, object anonType = null)
{
if (anonType != null) dbCmd.SetParameters<T>(anonType, excludeNulls: false);
dbCmd.CommandText = OrmLiteConfig.DialectProvider.ToSelectStatement(typeof(T), sql);
using (var dbReader = dbCmd.ExecuteReader())
return IsScalar<T>()
? dbReader.GetFirstColumn<T>()
: dbReader.ConvertToList<T>();
}
/// <summary>An IDbCommand extension method that queries.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd">The dbCmd to act on.</param>
/// <param name="sql"> The SQL.</param>
/// <param name="dict"> The dictionary.</param>
/// <returns>A List<T></returns>
internal static List<T> Query<T>(this IDbCommand dbCmd, string sql, Dictionary<string, object> dict)
{
if (dict != null) dbCmd.SetParameters(dict, excludeNulls: false);
dbCmd.CommandText = OrmLiteConfig.DialectProvider.ToSelectStatement(typeof(T), sql);
using (var dbReader = dbCmd.ExecuteReader())
return IsScalar<T>()
? dbReader.GetFirstColumn<T>()
: dbReader.ConvertToList<T>();
}
/// <summary>An IDbCommand extension method that executes the non query operation.</summary>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="sql"> The SQL.</param>
/// <param name="anonType">Type of the anon.</param>
/// <returns>An int.</returns>
internal static int ExecuteNonQuery(this IDbCommand dbCmd, string sql, object anonType = null)
{
if (anonType != null)
dbCmd.SetParameters(anonType, excludeNulls: false);
dbCmd.CommandText = sql;
return dbCmd.ExecuteNonQuery();
}
/// <summary>An IDbCommand extension method that executes the non query operation.</summary>
/// <param name="dbCmd">The dbCmd to act on.</param>
/// <param name="sql"> The SQL.</param>
/// <param name="dict"> The dictionary.</param>
/// <returns>An int.</returns>
internal static int ExecuteNonQuery(this IDbCommand dbCmd, string sql, Dictionary<string, object> dict)
{
if (dict != null)
dbCmd.SetParameters(dict, excludeNulls: false);
dbCmd.CommandText = sql;
return dbCmd.ExecuteNonQuery();
}
/// <summary>An IDbCommand extension method that queries a scalar.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="anonType">Type of the anon.</param>
/// <returns>The scalar.</returns>
internal static T QueryScalar<T>(this IDbCommand dbCmd, object anonType)
{
dbCmd.SetFilters<T>(anonType, excludeNulls: false);
using (var dbReader = dbCmd.ExecuteReader())
return GetScalar<T>(dbReader);
}
/// <summary>An IDbCommand extension method that queries a scalar.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="sql"> The SQL.</param>
/// <param name="anonType">Type of the anon.</param>
/// <returns>The scalar.</returns>
internal static T QueryScalar<T>(this IDbCommand dbCmd, string sql, object anonType = null)
{
if (anonType != null) dbCmd.SetParameters<T>(anonType, excludeNulls: false);
dbCmd.CommandText = OrmLiteConfig.DialectProvider.ToSelectStatement(typeof(T), sql);
using (var dbReader = dbCmd.ExecuteReader())
return GetScalar<T>(dbReader);
}
/// <summary>An IDbCommand extension method that SQL list.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="sql"> The SQL.</param>
/// <param name="anonType">Type of the anon.</param>
/// <returns>A List<T></returns>
internal static List<T> SqlList<T>(this IDbCommand dbCmd, string sql, object anonType = null)
{
if (anonType != null) dbCmd.SetParameters<T>(anonType, excludeNulls: false);
dbCmd.CommandText = sql;
using (var dbReader = dbCmd.ExecuteReader())
return IsScalar<T>()
? dbReader.GetFirstColumn<T>()
: dbReader.ConvertToList<T>();
}
/// <summary>An IDbCommand extension method that SQL list.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd">The dbCmd to act on.</param>
/// <param name="sql"> The SQL.</param>
/// <param name="dict"> The dictionary.</param>
/// <returns>A List<T></returns>
internal static List<T> SqlList<T>(this IDbCommand dbCmd, string sql, Dictionary<string, object> dict)
{
if (dict != null) dbCmd.SetParameters(dict, excludeNulls: false);
dbCmd.CommandText = sql;
using (var dbReader = dbCmd.ExecuteReader())
return IsScalar<T>()
? dbReader.GetFirstColumn<T>()
: dbReader.ConvertToList<T>();
}
/// <summary>An IDbCommand extension method that SQL scalar.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="sql"> The SQL.</param>
/// <param name="anonType">Type of the anon.</param>
/// <returns>A T.</returns>
internal static T SqlScalar<T>(this IDbCommand dbCmd, string sql, object anonType = null)
{
if (anonType != null) dbCmd.SetParameters<T>(anonType, excludeNulls: false);
dbCmd.CommandText = sql;
using (var dbReader = dbCmd.ExecuteReader())
return GetScalar<T>(dbReader);
}
/// <summary>An IDbCommand extension method that SQL scalar.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd">The dbCmd to act on.</param>
/// <param name="sql"> The SQL.</param>
/// <param name="dict"> The dictionary.</param>
/// <returns>A T.</returns>
internal static T SqlScalar<T>(this IDbCommand dbCmd, string sql, Dictionary<string, object> dict)
{
if (dict != null) dbCmd.SetParameters(dict, excludeNulls: false);
dbCmd.CommandText = sql;
using (var dbReader = dbCmd.ExecuteReader())
return GetScalar<T>(dbReader);
}
/// <summary>An IDbCommand extension method that by example where.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="anonType">Type of the anon.</param>
/// <returns>A List<T></returns>
internal static List<T> ByExampleWhere<T>(this IDbCommand dbCmd, object anonType)
{
return ByExampleWhere<T>(dbCmd, anonType, true);
}
/// <summary>An IDbCommand extension method that by example where.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="anonType"> Type of the anon.</param>
/// <param name="excludeNulls">true to exclude, false to include the nulls.</param>
/// <returns>A List<T></returns>
internal static List<T> ByExampleWhere<T>(this IDbCommand dbCmd, object anonType, bool excludeNulls)
{
dbCmd.SetFilters<T>(anonType, excludeNulls);
using (var dbReader = dbCmd.ExecuteReader())
return dbReader.ConvertToList<T>();
}
/// <summary>An IDbCommand extension method that queries by example.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="sql"> The SQL.</param>
/// <param name="anonType">Type of the anon.</param>
/// <returns>The by example.</returns>
internal static List<T> QueryByExample<T>(this IDbCommand dbCmd, string sql, object anonType = null)
{
if (anonType != null) dbCmd.SetParameters<T>(anonType, excludeNulls: false);
dbCmd.CommandText = OrmLiteConfig.DialectProvider.ToSelectStatement(typeof(T), sql);
using (var dbReader = dbCmd.ExecuteReader())
return dbReader.ConvertToList<T>();
}
/// <summary>Enumerates query each in this collection.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="sql"> The SQL.</param>
/// <param name="anonType">Type of the anon.</param>
/// <returns>
/// An enumerator that allows foreach to be used to process query each in this collection.
/// </returns>
internal static IEnumerable<T> QueryEach<T>(this IDbCommand dbCmd, string sql, object anonType = null)
{
if (anonType != null)
{
dbCmd.SetParameters<T>(anonType, excludeNulls: false);
}
dbCmd.CommandText = OrmLiteConfig.DialectProvider.ToSelectStatement(typeof(T), sql);
return dbCmd.Each<T>();
}
/// <summary>Enumerates each where in this collection.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="anonType">Type of the anon.</param>
/// <returns>
/// An enumerator that allows foreach to be used to process each where in this collection.
/// </returns>
internal static IEnumerable<T> EachWhere<T>(this IDbCommand dbCmd, object anonType)
{
dbCmd.SetFilters<T>(anonType);
return dbCmd.Each<T>();
}
/// <summary>An IDbCommand extension method that gets by identifier or default.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="idValue">The identifier value.</param>
/// <returns>The by identifier or default.</returns>
internal static T GetByIdOrDefault<T>(this IDbCommand dbCmd, object idValue)
{
return FirstOrDefault<T>(dbCmd, OrmLiteConfig.DialectProvider.GetQuotedColumnName(ModelDefinition<T>.PrimaryKeyName) + " = {0}".SqlFormat(idValue));
}
/// <summary>An IDbCommand extension method that gets by identifiers.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="idValues">The identifier values.</param>
/// <returns>The by identifiers.</returns>
internal static List<T> GetByIds<T>(this IDbCommand dbCmd, IEnumerable idValues)
{
var sql = idValues.GetIdsInSql();
return sql == null
? new List<T>()
: Select<T>(dbCmd, OrmLiteConfig.DialectProvider.GetQuotedColumnName(ModelDefinition<T>.PrimaryKeyName) + " IN (" + sql + ")");
}
/// <summary>An IDbCommand extension method that gets by identifier parameter.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd">The dbCmd to act on.</param>
/// <param name="id"> The identifier.</param>
/// <returns>The by identifier parameter.</returns>
internal static T GetByIdParam<T>(this IDbCommand dbCmd, object id)
{
var modelDef = ModelDefinition<T>.Definition;
var idParamString = OrmLiteConfig.DialectProvider.ParamString + "0";
var sql = string.Format("{0} WHERE {1} = {2}",
OrmLiteConfig.DialectProvider.ToSelectStatement(typeof(T), "", null),
OrmLiteConfig.DialectProvider.GetQuotedColumnName(modelDef.PrimaryKey.FieldName),
idParamString);
var idParam = dbCmd.CreateParameter();
idParam.ParameterName = idParamString;
idParam.Value = id;
List<IDataParameter> paramsToInsert = new List<IDataParameter>();
paramsToInsert.Add(idParam);
return dbCmd.ExecReader(sql, paramsToInsert).ConvertTo<T>();
}
/// <summary>An IDataReader extension method that gets a scalar.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="sql"> The SQL.</param>
/// <param name="sqlParams">Options for controlling the SQL.</param>
/// <returns>The scalar.</returns>
internal static T GetScalar<T>(this IDbCommand dbCmd, string sql, params object[] sqlParams)
{
using (var reader = dbCmd.ExecReader(sql.SqlFormat(sqlParams)))
return GetScalar<T>(reader);
}
/// <summary>An IDataReader extension method that gets a scalar.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="reader">The reader to act on.</param>
/// <returns>The scalar.</returns>
internal static T GetScalar<T>(this IDataReader reader)
{
while (reader.Read()){
Type t = typeof(T);
object oValue = reader.GetValue(0);
if (oValue == DBNull.Value) return default(T);
if (t== typeof(DateTime) || t== typeof(DateTime?))
return(T)(object) DateTime.Parse(oValue.ToString(), System.Globalization.CultureInfo.CurrentCulture);
if (t== typeof(decimal) || t== typeof(decimal?))
return(T)(object)decimal.Parse(oValue.ToString(), System.Globalization.CultureInfo.CurrentCulture);
if (t== typeof(double) || t== typeof(double?))
return(T)(object)double.Parse(oValue.ToString(), System.Globalization.CultureInfo.CurrentCulture);
if (t== typeof(float) || t== typeof(float?))
return(T)(object)float.Parse(oValue.ToString(), System.Globalization.CultureInfo.CurrentCulture);
object o = OrmLiteConfig.DialectProvider.ConvertDbValue(oValue, t);
return o == null ? default(T) : (T)o;
}
return default(T);
}
/// <summary>An IDbCommand extension method that gets the last insert identifier.</summary>
/// <param name="dbCmd">The dbCmd to act on.</param>
/// <returns>The last insert identifier.</returns>
internal static long GetLastInsertId(this IDbCommand dbCmd)
{
return OrmLiteConfig.DialectProvider.GetLastInsertId(dbCmd);
}
/// <summary>An IDataReader extension method that gets the first column.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="sql"> The SQL.</param>
/// <param name="sqlParams">Options for controlling the SQL.</param>
/// <returns>The first column.</returns>
internal static List<T> GetFirstColumn<T>(this IDbCommand dbCmd, string sql, params object[] sqlParams)
{
using (var dbReader = dbCmd.ExecReader(sql.SqlFormat(sqlParams)))
return GetFirstColumn<T>(dbReader);
}
/// <summary>An IDataReader extension method that gets the first column.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="reader">The reader to act on.</param>
/// <returns>The first column.</returns>
internal static List<T> GetFirstColumn<T>(this IDataReader reader)
{
var columValues = new List<T>();
var getValueFn = GetValueFn<T>(reader);
while (reader.Read())
{
var value = getValueFn(0);
if (value == DBNull.Value)
value = default(T);
columValues.Add((T)value);
}
return columValues;
}
/// <summary>Alias for GetFirstColumn. Returns the first selected column in a List.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="sql"> The SQL.</param>
/// <param name="sqlParams">Options for controlling the SQL.</param>
/// <returns>The list.</returns>
internal static List<T> GetList<T>(this IDbCommand dbCmd, string sql, params object[] sqlParams)
{
return dbCmd.GetFirstColumn<T>(sql, sqlParams);
}
/// <summary>An IDataReader extension method that gets the first column distinct.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="sql"> The SQL.</param>
/// <param name="sqlParams">Options for controlling the SQL.</param>
/// <returns>The first column distinct.</returns>
internal static HashSet<T> GetFirstColumnDistinct<T>(this IDbCommand dbCmd, string sql, params object[] sqlParams)
{
using (var dbReader = dbCmd.ExecReader(sql.SqlFormat(sqlParams)))
return GetFirstColumnDistinct<T>(dbReader);
}
/// <summary>
/// Alias for GetFirstColumnDistinct. Returns the first selected column in a HashSet.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="sql"> The SQL.</param>
/// <param name="sqlParams">Options for controlling the SQL.</param>
/// <returns>The hash set.</returns>
public static HashSet<T> GetHashSet<T>(this IDbCommand dbCmd, string sql, params object[] sqlParams)
{
return dbCmd.GetFirstColumnDistinct<T>(sql, sqlParams);
}
/// <summary>An IDataReader extension method that gets the first column distinct.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="reader">The reader to act on.</param>
/// <returns>The first column distinct.</returns>
internal static HashSet<T> GetFirstColumnDistinct<T>(this IDataReader reader)
{
var columValues = new HashSet<T>();
var getValueFn = GetValueFn<T>(reader);
while (reader.Read())
{
var value = getValueFn(0);
if (value == DBNull.Value)
value = default(T);
columValues.Add((T)value);
}
return columValues;
}
/// <summary>An IDataReader extension method that gets a lookup.</summary>
/// <typeparam name="K">Generic type parameter.</typeparam>
/// <typeparam name="V">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="sql"> The SQL.</param>
/// <param name="sqlParams">Options for controlling the SQL.</param>
/// <returns>The lookup.</returns>
internal static Dictionary<K, List<V>> GetLookup<K, V>(this IDbCommand dbCmd, string sql, params object[] sqlParams)
{
using (var dbReader = dbCmd.ExecReader(sql.SqlFormat(sqlParams)))
return GetLookup<K, V>(dbReader);
}
/// <summary>An IDataReader extension method that gets a lookup.</summary>
/// <typeparam name="K">Generic type parameter.</typeparam>
/// <typeparam name="V">Generic type parameter.</typeparam>
/// <param name="reader">The reader to act on.</param>
/// <returns>The lookup.</returns>
internal static Dictionary<K, List<V>> GetLookup<K, V>(this IDataReader reader)
{
var lookup = new Dictionary<K, List<V>>();
var getKeyFn = GetValueFn<K>(reader);
var getValueFn = GetValueFn<V>(reader);
while (reader.Read())
{
var key = (K)getKeyFn(0);
var value = (V)getValueFn(1);
List<V> values;
if (!lookup.TryGetValue(key, out values))
{
values = new List<V>();
lookup[key] = values;
}
values.Add(value);
}
return lookup;
}
/// <summary>An IDataReader extension method that gets a dictionary.</summary>
/// <typeparam name="K">Generic type parameter.</typeparam>
/// <typeparam name="V">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="sql"> The SQL.</param>
/// <param name="sqlParams">Options for controlling the SQL.</param>
/// <returns>The dictionary.</returns>
internal static Dictionary<K, V> GetDictionary<K, V>(this IDbCommand dbCmd, string sql, params object[] sqlParams)
{
using (var dbReader = dbCmd.ExecReader(sql.SqlFormat(sqlParams)))
return GetDictionary<K, V>(dbReader);
}
/// <summary>An IDataReader extension method that gets a dictionary.</summary>
/// <typeparam name="K">Generic type parameter.</typeparam>
/// <typeparam name="V">Generic type parameter.</typeparam>
/// <param name="reader">The reader to act on.</param>
/// <returns>The dictionary.</returns>
internal static Dictionary<K, V> GetDictionary<K, V>(this IDataReader reader)
{
var map = new Dictionary<K, V>();
var getKeyFn = GetValueFn<K>(reader);
var getValueFn = GetValueFn<V>(reader);
while (reader.Read())
{
var key = (K)getKeyFn(0);
var value = (V)getValueFn(1);
map.Add(key, value);
}
return map;
}
/// <summary>somo aditional methods.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="record">The record.</param>
/// <returns>true if children, false if not.</returns>
internal static bool HasChildren<T>(this IDbCommand dbCmd, object record)
{
return HasChildren<T>(dbCmd, record, string.Empty);
}
/// <summary>An IDbCommand extension method that query if this object has children.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="record"> The record.</param>
/// <param name="sqlFilter"> A filter specifying the SQL.</param>
/// <param name="filterParams">Options for controlling the filter.</param>
/// <returns>true if children, false if not.</returns>
private static bool HasChildren<T>(this IDbCommand dbCmd, object record, string sqlFilter, params object[] filterParams)
{
var fromTableType = typeof(T);
var sql = OrmLiteConfig.DialectProvider.ToExistStatement(fromTableType, record,sqlFilter, filterParams);
dbCmd.CommandText = sql;
var result = dbCmd.ExecuteScalar();
return result != null;
}
/// <summary>An IDbCommand extension method that exists.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="sqlFilter"> A filter specifying the SQL.</param>
/// <param name="filterParams">Options for controlling the filter.</param>
/// <returns>true if it succeeds, false if it fails.</returns>
internal static bool Exists<T>(this IDbCommand dbCmd, string sqlFilter, params object[] filterParams)
{
return HasChildren<T>(dbCmd, null, sqlFilter, filterParams);
}
/// <summary>An IDbCommand extension method that exists.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="record">The record.</param>
/// <returns>true if it succeeds, false if it fails.</returns>
internal static bool Exists<T>(this IDbCommand dbCmd, object record)
{
return HasChildren<T>(dbCmd, record, string.Empty);
}
/// <summary>procedures ...</summary>
/// <typeparam name="TOutputModel">Type of the output model.</typeparam>
/// <param name="dbCommand"> The dbCommand to act on.</param>
/// <param name="fromObjWithProperties">from object with properties.</param>
/// <returns>A List<TOutputModel></returns>
internal static List<TOutputModel> SelectFromProcedure<TOutputModel>(this IDbCommand dbCommand,
object fromObjWithProperties)
{
return SelectFromProcedure<TOutputModel>(dbCommand, fromObjWithProperties,string.Empty);
}
/// <summary>An IDbCommand extension method that select from procedure.</summary>
/// <typeparam name="TOutputModel">Type of the output model.</typeparam>
/// <param name="dbCommand"> The dbCommand to act on.</param>
/// <param name="fromObjWithProperties">from object with properties.</param>
/// <param name="sqlFilter"> A filter specifying the SQL.</param>
/// <param name="filterParams"> Options for controlling the filter.</param>
/// <returns>A List<TOutputModel></returns>
internal static List<TOutputModel> SelectFromProcedure<TOutputModel>(this IDbCommand dbCommand,
object fromObjWithProperties,
string sqlFilter,
params object[] filterParams)
{
var modelType = typeof(TOutputModel);
string sql = OrmLiteConfig.DialectProvider.ToSelectFromProcedureStatement(
fromObjWithProperties,modelType, sqlFilter, filterParams);
using (var reader = dbCommand.ExecReader(sql))
{
return reader.ConvertToList<TOutputModel>();
}
}
/// <summary>An IDbCommand extension method that gets long scalar.</summary>
/// <param name="dbCmd">The dbCmd to act on.</param>
/// <returns>The long scalar.</returns>
public static long GetLongScalar(this IDbCommand dbCmd)
{
var result = dbCmd.ExecuteScalar();
if (result is DBNull) return default(long);
if (result is int) return (int)result;
if (result is decimal) return Convert.ToInt64((decimal)result);
if (result is ulong) return (long)Convert.ToUInt64(result);
return (long)result;
}
private static IEnumerable<T> Each<T>(this IDbCommand dbCmd)
{
var fieldDefs = ModelDefinition<T>.Definition.FieldDefinitionsArray;
using (var reader = dbCmd.ExecuteReader())
{
var indexCache = reader.GetIndexFieldsCache(ModelDefinition<T>.Definition);
while (reader.Read())
{
var row = OrmLiteUtilExtensions.CreateInstance<T>();
row.PopulateWithSqlReader(reader, fieldDefs, indexCache);
yield return row;
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
/*============================================================
**
**
**
** Purpose: Allows developers to view the base data types as
** an arbitrary array of bits.
**
**
===========================================================*/
namespace System {
using System;
using System.Runtime.CompilerServices;
using System.Diagnostics.Contracts;
using System.Security;
// The BitConverter class contains methods for
// converting an array of bytes to one of the base data
// types, as well as for converting a base data type to an
// array of bytes.
//
// Only statics, does not need to be marked with the serializable attribute
public static class BitConverter {
// This field indicates the "endianess" of the architecture.
// The value is set to true if the architecture is
// little endian; false if it is big endian.
#if BIGENDIAN
public static readonly bool IsLittleEndian /* = false */;
#else
public static readonly bool IsLittleEndian = true;
#endif
// Converts a byte into an array of bytes with length one.
public static byte[] GetBytes(bool value) {
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 1);
byte[] r = new byte[1];
r[0] = (value ? (byte)Boolean.True : (byte)Boolean.False );
return r;
}
// Converts a char into an array of bytes with length two.
public static byte[] GetBytes(char value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 2);
return GetBytes((short)value);
}
// Converts a short into an array of bytes with length
// two.
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe static byte[] GetBytes(short value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 2);
byte[] bytes = new byte[2];
fixed(byte* b = bytes)
*((short*)b) = value;
return bytes;
}
// Converts an int into an array of bytes with length
// four.
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe static byte[] GetBytes(int value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 4);
byte[] bytes = new byte[4];
fixed(byte* b = bytes)
*((int*)b) = value;
return bytes;
}
// Converts a long into an array of bytes with length
// eight.
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe static byte[] GetBytes(long value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 8);
byte[] bytes = new byte[8];
fixed(byte* b = bytes)
*((long*)b) = value;
return bytes;
}
// Converts an ushort into an array of bytes with
// length two.
[CLSCompliant(false)]
public static byte[] GetBytes(ushort value) {
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 2);
return GetBytes((short)value);
}
// Converts an uint into an array of bytes with
// length four.
[CLSCompliant(false)]
public static byte[] GetBytes(uint value) {
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 4);
return GetBytes((int)value);
}
// Converts an unsigned long into an array of bytes with
// length eight.
[CLSCompliant(false)]
public static byte[] GetBytes(ulong value) {
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 8);
return GetBytes((long)value);
}
// Converts a float into an array of bytes with length
// four.
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe static byte[] GetBytes(float value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 4);
return GetBytes(*(int*)&value);
}
// Converts a double into an array of bytes with length
// eight.
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe static byte[] GetBytes(double value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 8);
return GetBytes(*(long*)&value);
}
// Converts an array of bytes into a char.
public static char ToChar(byte[] value, int startIndex)
{
if (value == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
}
if ((uint)startIndex >= value.Length) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
}
if (startIndex > value.Length - 2) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
Contract.EndContractBlock();
return (char)ToInt16(value, startIndex);
}
// Converts an array of bytes into a short.
[System.Security.SecuritySafeCritical] // auto-generated
public static unsafe short ToInt16(byte[] value, int startIndex) {
if( value == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
}
if ((uint) startIndex >= value.Length) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
}
if (startIndex > value.Length -2) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
Contract.EndContractBlock();
fixed( byte * pbyte = &value[startIndex]) {
if( startIndex % 2 == 0) { // data is aligned
return *((short *) pbyte);
}
else {
if( IsLittleEndian) {
return (short)((*pbyte) | (*(pbyte + 1) << 8)) ;
}
else {
return (short)((*pbyte << 8) | (*(pbyte + 1)));
}
}
}
}
// Converts an array of bytes into an int.
[System.Security.SecuritySafeCritical] // auto-generated
public static unsafe int ToInt32 (byte[] value, int startIndex) {
if( value == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
}
if ((uint) startIndex >= value.Length) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
}
if (startIndex > value.Length -4) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
Contract.EndContractBlock();
fixed( byte * pbyte = &value[startIndex]) {
if( startIndex % 4 == 0) { // data is aligned
return *((int *) pbyte);
}
else {
if( IsLittleEndian) {
return (*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24);
}
else {
return (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3));
}
}
}
}
// Converts an array of bytes into a long.
[System.Security.SecuritySafeCritical] // auto-generated
public static unsafe long ToInt64 (byte[] value, int startIndex) {
if (value == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
}
if ((uint) startIndex >= value.Length) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
}
if (startIndex > value.Length -8) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
Contract.EndContractBlock();
fixed( byte * pbyte = &value[startIndex]) {
if( startIndex % 8 == 0) { // data is aligned
return *((long *) pbyte);
}
else {
if( IsLittleEndian) {
int i1 = (*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24);
int i2 = (*(pbyte+4)) | (*(pbyte + 5) << 8) | (*(pbyte + 6) << 16) | (*(pbyte + 7) << 24);
return (uint)i1 | ((long)i2 << 32);
}
else {
int i1 = (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3));
int i2 = (*(pbyte+4) << 24) | (*(pbyte + 5) << 16) | (*(pbyte + 6) << 8) | (*(pbyte + 7));
return (uint)i2 | ((long)i1 << 32);
}
}
}
}
// Converts an array of bytes into an ushort.
//
[CLSCompliant(false)]
public static ushort ToUInt16(byte[] value, int startIndex)
{
if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
if ((uint)startIndex >= value.Length)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
if (startIndex > value.Length - 2)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
Contract.EndContractBlock();
return (ushort)ToInt16(value, startIndex);
}
// Converts an array of bytes into an uint.
//
[CLSCompliant(false)]
public static uint ToUInt32(byte[] value, int startIndex)
{
if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
if ((uint)startIndex >= value.Length)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
if (startIndex > value.Length - 4)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
Contract.EndContractBlock();
return (uint)ToInt32(value, startIndex);
}
// Converts an array of bytes into an unsigned long.
//
[CLSCompliant(false)]
public static ulong ToUInt64(byte[] value, int startIndex)
{
if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
if ((uint)startIndex >= value.Length)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
if (startIndex > value.Length - 8)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
Contract.EndContractBlock();
return (ulong)ToInt64(value, startIndex);
}
// Converts an array of bytes into a float.
[System.Security.SecuritySafeCritical] // auto-generated
unsafe public static float ToSingle (byte[] value, int startIndex)
{
if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
if ((uint)startIndex >= value.Length)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
if (startIndex > value.Length - 4)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
Contract.EndContractBlock();
int val = ToInt32(value, startIndex);
return *(float*)&val;
}
// Converts an array of bytes into a double.
[System.Security.SecuritySafeCritical] // auto-generated
unsafe public static double ToDouble (byte[] value, int startIndex)
{
if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
if ((uint)startIndex >= value.Length)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
if (startIndex > value.Length - 8)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
Contract.EndContractBlock();
long val = ToInt64(value, startIndex);
return *(double*)&val;
}
private static char GetHexValue(int i) {
Contract.Assert( i >=0 && i <16, "i is out of range.");
if (i<10) {
return (char)(i + '0');
}
return (char)(i - 10 + 'A');
}
// Converts an array of bytes into a String.
public static String ToString (byte[] value, int startIndex, int length) {
if (value == null) {
throw new ArgumentNullException("byteArray");
}
if (startIndex < 0 || startIndex >= value.Length && startIndex > 0) { // Don't throw for a 0 length array.
throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
}
if (length < 0) {
throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
}
if (startIndex > value.Length - length) {
throw new ArgumentException(Environment.GetResourceString("Arg_ArrayPlusOffTooSmall"));
}
Contract.EndContractBlock();
if (length == 0) {
return string.Empty;
}
if (length > (Int32.MaxValue / 3)) {
// (Int32.MaxValue / 3) == 715,827,882 Bytes == 699 MB
throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_LengthTooLarge", (Int32.MaxValue / 3)));
}
int chArrayLength = length * 3;
char[] chArray = new char[chArrayLength];
int i = 0;
int index = startIndex;
for (i = 0; i < chArrayLength; i += 3) {
byte b = value[index++];
chArray[i]= GetHexValue(b/16);
chArray[i+1] = GetHexValue(b%16);
chArray[i+2] = '-';
}
// We don't need the last '-' character
return new String(chArray, 0, chArray.Length - 1);
}
// Converts an array of bytes into a String.
public static String ToString(byte [] value) {
if (value == null)
throw new ArgumentNullException("value");
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
return ToString(value, 0, value.Length);
}
// Converts an array of bytes into a String.
public static String ToString (byte [] value, int startIndex) {
if (value == null)
throw new ArgumentNullException("value");
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
return ToString(value, startIndex, value.Length - startIndex);
}
/*==================================ToBoolean===================================
**Action: Convert an array of bytes to a boolean value. We treat this array
** as if the first 4 bytes were an Int4 an operate on this value.
**Returns: True if the Int4 value of the first 4 bytes is non-zero.
**Arguments: value -- The byte array
** startIndex -- The position within the array.
**Exceptions: See ToInt4.
==============================================================================*/
// Converts an array of bytes into a boolean.
public static bool ToBoolean(byte[] value, int startIndex) {
if (value==null)
throw new ArgumentNullException("value");
if (startIndex < 0)
throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (startIndex > value.Length - 1)
throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
return (value[startIndex]==0)?false:true;
}
[SecuritySafeCritical]
public static unsafe long DoubleToInt64Bits(double value) {
// If we're on a big endian machine, what should this method do? You could argue for
// either big endian or little endian, depending on whether you are writing to a file that
// should be used by other programs on that processor, or for compatibility across multiple
// formats. Because this is ambiguous, we're excluding this from the Portable Library & Win8 Profile.
// If we ever run on big endian machines, produce two versions where endianness is specified.
Contract.Assert(IsLittleEndian, "This method is implemented assuming little endian with an ambiguous spec.");
return *((long *)&value);
}
[SecuritySafeCritical]
public static unsafe double Int64BitsToDouble(long value) {
// If we're on a big endian machine, what should this method do? You could argue for
// either big endian or little endian, depending on whether you are writing to a file that
// should be used by other programs on that processor, or for compatibility across multiple
// formats. Because this is ambiguous, we're excluding this from the Portable Library & Win8 Profile.
// If we ever run on big endian machines, produce two versions where endianness is specified.
Contract.Assert(IsLittleEndian, "This method is implemented assuming little endian with an ambiguous spec.");
return *((double*)&value);
}
}
}
| |
namespace RealArtists.ChargeBee.Models {
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net.Http;
using RealArtists.ChargeBee.Api;
using RealArtists.ChargeBee.Filters.Enums;
using RealArtists.ChargeBee.Internal;
using RealArtists.ChargeBee.Models.Enums;
public class TransactionActions : ApiResourceActions {
public TransactionActions(ChargeBeeApi api) : base(api) { }
public Transaction.TransactionListRequest List() {
string url = BuildUrl("transactions");
return new Transaction.TransactionListRequest(Api, url);
}
public ListRequest PaymentsForInvoice(string id) {
string url = BuildUrl("invoices", id, "payments");
return new ListRequest(Api, url);
}
public EntityRequest<Type> Retrieve(string id) {
string url = BuildUrl("transactions", id);
return new EntityRequest<Type>(Api, url, HttpMethod.Get);
}
}
public class Transaction : Resource {
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 string GatewayAccountId {
get { return GetValue<string>("gateway_account_id", false); }
}
public string PaymentSourceId {
get { return GetValue<string>("payment_source_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); }
}
public TypeEnum TransactionType {
get { return GetEnum<TypeEnum>("type", true); }
}
public DateTime? Date {
get { return GetDateTime("date", false); }
}
public string CurrencyCode {
get { return GetValue<string>("currency_code", true); }
}
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 FraudFlagEnum? FraudFlag {
get { return GetEnum<FraudFlagEnum>("fraud_flag", 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); }
}
public long? ResourceVersion {
get { return GetValue<long?>("resource_version", false); }
}
public DateTime? UpdatedAt {
get { return GetDateTime("updated_at", false); }
}
public string FraudReason {
get { return GetValue<string>("fraud_reason", false); }
}
public int? AmountUnused {
get { return GetValue<int?>("amount_unused", false); }
}
public string MaskedCardNumber {
get { return GetValue<string>("masked_card_number", false); }
}
public string ReferenceTransactionId {
get { return GetValue<string>("reference_transaction_id", false); }
}
public string RefundedTxnId {
get { return GetValue<string>("refunded_txn_id", false); }
}
public string ReversalTransactionId {
get { return GetValue<string>("reversal_transaction_id", false); }
}
public List<TransactionLinkedInvoice> LinkedInvoices {
get { return GetResourceList<TransactionLinkedInvoice>("linked_invoices"); }
}
public List<TransactionLinkedCreditNote> LinkedCreditNotes {
get { return GetResourceList<TransactionLinkedCreditNote>("linked_credit_notes"); }
}
public List<TransactionLinkedRefund> LinkedRefunds {
get { return GetResourceList<TransactionLinkedRefund>("linked_refunds"); }
}
public bool Deleted {
get { return GetValue<bool>("deleted", true); }
}
public class TransactionListRequest : ListRequestBase<TransactionListRequest> {
public TransactionListRequest(ChargeBeeApi api, string url)
: base(api, url) {
}
public TransactionListRequest IncludeDeleted(bool includeDeleted) {
_params.AddOpt("include_deleted", includeDeleted);
return this;
}
public StringFilter<TransactionListRequest> Id() {
return new StringFilter<TransactionListRequest>("id", this).SupportsMultiOperators(true);
}
public StringFilter<TransactionListRequest> CustomerId() {
return new StringFilter<TransactionListRequest>("customer_id", this).SupportsMultiOperators(true).SupportsPresenceOperator(true);
}
public StringFilter<TransactionListRequest> SubscriptionId() {
return new StringFilter<TransactionListRequest>("subscription_id", this).SupportsMultiOperators(true).SupportsPresenceOperator(true);
}
public StringFilter<TransactionListRequest> PaymentSourceId() {
return new StringFilter<TransactionListRequest>("payment_source_id", this).SupportsMultiOperators(true).SupportsPresenceOperator(true);
}
public EnumFilter<PaymentMethodEnum, TransactionListRequest> PaymentMethod() {
return new EnumFilter<PaymentMethodEnum, TransactionListRequest>("payment_method", this);
}
public EnumFilter<GatewayEnum, TransactionListRequest> Gateway() {
return new EnumFilter<GatewayEnum, TransactionListRequest>("gateway", this);
}
public StringFilter<TransactionListRequest> GatewayAccountId() {
return new StringFilter<TransactionListRequest>("gateway_account_id", this).SupportsMultiOperators(true);
}
public StringFilter<TransactionListRequest> IdAtGateway() {
return new StringFilter<TransactionListRequest>("id_at_gateway", this);
}
public StringFilter<TransactionListRequest> ReferenceNumber() {
return new StringFilter<TransactionListRequest>("reference_number", this).SupportsPresenceOperator(true);
}
public EnumFilter<TypeEnum, TransactionListRequest> Type() {
return new EnumFilter<TypeEnum, TransactionListRequest>("type", this);
}
public TimestampFilter<TransactionListRequest> Date() {
return new TimestampFilter<TransactionListRequest>("date", this);
}
public NumberFilter<int, TransactionListRequest> Amount() {
return new NumberFilter<int, TransactionListRequest>("amount", this);
}
public EnumFilter<StatusEnum, TransactionListRequest> Status() {
return new EnumFilter<StatusEnum, TransactionListRequest>("status", this);
}
public TimestampFilter<TransactionListRequest> UpdatedAt() {
return new TimestampFilter<TransactionListRequest>("updated_at", this);
}
public TransactionListRequest SortByDate(SortOrderEnum order) {
_params.AddOpt("sort_by[" + order.ToString().ToLower() + "]", "date");
return this;
}
}
public enum TypeEnum {
Unknown,
[Description("authorization")]
Authorization,
[Description("payment")]
Payment,
[Description("refund")]
Refund,
[Description("payment_reversal")]
PaymentReversal,
}
public enum StatusEnum {
Unknown,
[Description("in_progress")]
InProgress,
[Description("success")]
Success,
[Description("voided")]
Voided,
[Description("failure")]
Failure,
[Description("timeout")]
Timeout,
[Description("needs_attention")]
NeedsAttention,
}
public enum FraudFlagEnum {
Unknown,
[Description("safe")]
Safe,
[Description("suspicious")]
Suspicious,
[Description("fraudulent")]
Fraudulent,
}
public class TransactionLinkedInvoice : Resource {
public string InvoiceId() {
return GetValue<string>("invoice_id", true);
}
public int AppliedAmount() {
return GetValue<int>("applied_amount", true);
}
public DateTime AppliedAt() {
return (DateTime)GetDateTime("applied_at", true);
}
public DateTime? InvoiceDate() {
return GetDateTime("invoice_date", false);
}
public int? InvoiceTotal() {
return GetValue<int?>("invoice_total", false);
}
public Invoice.StatusEnum InvoiceStatus() {
return GetEnum<Invoice.StatusEnum>("invoice_status", true);
}
}
public class TransactionLinkedCreditNote : Resource {
public string CnId() {
return GetValue<string>("cn_id", true);
}
public int AppliedAmount() {
return GetValue<int>("applied_amount", true);
}
public DateTime AppliedAt() {
return (DateTime)GetDateTime("applied_at", true);
}
public CreditNote.ReasonCodeEnum CnReasonCode() {
return GetEnum<CreditNote.ReasonCodeEnum>("cn_reason_code", true);
}
public DateTime? CnDate() {
return GetDateTime("cn_date", false);
}
public int? CnTotal() {
return GetValue<int?>("cn_total", false);
}
public CreditNote.StatusEnum CnStatus() {
return GetEnum<CreditNote.StatusEnum>("cn_status", true);
}
public string CnReferenceInvoiceId() {
return GetValue<string>("cn_reference_invoice_id", true);
}
}
public class TransactionLinkedRefund : Resource {
public string TxnId() {
return GetValue<string>("txn_id", true);
}
public Transaction.StatusEnum TxnStatus() {
return GetEnum<Transaction.StatusEnum>("txn_status", true);
}
public DateTime TxnDate() {
return (DateTime)GetDateTime("txn_date", true);
}
public int TxnAmount() {
return GetValue<int>("txn_amount", true);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ShiftLeftLogicalInt321()
{
var test = new ImmUnaryOpTest__ShiftLeftLogicalInt321();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmUnaryOpTest__ShiftLeftLogicalInt321
{
private struct TestStruct
{
public Vector128<Int32> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__ShiftLeftLogicalInt321 testClass)
{
var result = Sse2.ShiftLeftLogical(_fld, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static Int32[] _data = new Int32[Op1ElementCount];
private static Vector128<Int32> _clsVar;
private Vector128<Int32> _fld;
private SimpleUnaryOpTest__DataTable<Int32, Int32> _dataTable;
static ImmUnaryOpTest__ShiftLeftLogicalInt321()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
}
public ImmUnaryOpTest__ShiftLeftLogicalInt321()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new SimpleUnaryOpTest__DataTable<Int32, Int32>(_data, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.ShiftLeftLogical(
Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.ShiftLeftLogical(
Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.ShiftLeftLogical(
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical), new Type[] { typeof(Vector128<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical), new Type[] { typeof(Vector128<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical), new Type[] { typeof(Vector128<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.ShiftLeftLogical(
_clsVar,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr);
var result = Sse2.ShiftLeftLogical(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr));
var result = Sse2.ShiftLeftLogical(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr));
var result = Sse2.ShiftLeftLogical(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__ShiftLeftLogicalInt321();
var result = Sse2.ShiftLeftLogical(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.ShiftLeftLogical(_fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.ShiftLeftLogical(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Int32> firstOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Int32[] firstOp, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((int)(firstOp[0] << 1) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((int)(firstOp[i] << 1) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.ShiftLeftLogical)}<Int32>(Vector128<Int32><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
/// <summary>
/// System.MathF.Floor(System.Single)
/// </summary>
public class MathFFloor
{
public static int Main(string[] args)
{
MathFFloor floor = new MathFFloor();
TestLibrary.TestFramework.BeginTestCase("Testing System.MathF.Floor(System.Single)...");
if (floor.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
return retVal;
}
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Verify floor number should be equal to intefer part subtract one of negative number...");
try
{
float number = TestLibrary.Generator.GetSingle(-55);
while (number >= 0)
{
number = (-TestLibrary.Generator.GetSingle(-55)) * 100;
}
float floorNumber = MathF.Floor(number);
if (floorNumber < number - 1 || floorNumber > number)
{
TestLibrary.TestFramework.LogError("001", "The Ceiling number should be equal to the integer part of negative number!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Verify floor number should be equal to itself when number is negative integer...");
try
{
float number = TestLibrary.Generator.GetSingle(-55);
while (number >= 0)
{
number = (-TestLibrary.Generator.GetSingle(-55)) * 100;
}
float floorNumber = MathF.Floor(number);
if (floorNumber != MathF.Floor(floorNumber))
{
TestLibrary.TestFramework.LogError("003", "The floor number should be equal to itself when number is negative integer...");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Verify floor number should be equal to the integer part of positive number...");
try
{
float number = TestLibrary.Generator.GetSingle(-55);
while (number <= 0)
{
number = (TestLibrary.Generator.GetSingle(-55)) * 100;
}
float floorNumber = MathF.Floor(number);
if (floorNumber < number - 1 || floorNumber > number)
{
TestLibrary.TestFramework.LogError("005", "The floor number should be equal to the integer part plus one of positive number!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Verify floor number should be equal to itself when number is positive integer...");
try
{
float number = TestLibrary.Generator.GetSingle(-55);
while (number <= 0)
{
number = (TestLibrary.Generator.GetSingle(-55)) * 100;
}
float floorNumber = MathF.Floor(number);
if (floorNumber != MathF.Floor(floorNumber))
{
TestLibrary.TestFramework.LogError("007", "The floor number should be equal to itself when number is positive integer...");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest5: Verify floor number should be equal to itself when number is maxvalue...");
try
{
float floorMax = MathF.Floor(float.MaxValue);
if (floorMax != float.MaxValue)
{
TestLibrary.TestFramework.LogError("009", "The floor number should be equal to itself when number is maxvalue!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest6: Verify floor number should be equal to itself when number is minvalue...");
try
{
float floorMin = MathF.Floor(float.MinValue);
if (floorMin != float.MinValue)
{
TestLibrary.TestFramework.LogError("011", "The floor number should be equal to itself when number is minvalue!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
}
| |
using System;
using NUnit.Framework;
using StructureMap.Configuration.DSL;
using StructureMap.Exceptions;
using StructureMap.Graph;
using StructureMap.Pipeline;
using StructureMap.Testing.GenericWidgets;
using StructureMap.Testing.Widget;
using StructureMap.Testing.Widget3;
namespace StructureMap.Testing.Graph
{
[TestFixture]
public class ContainerTester : Registry
{
#region Setup/Teardown
[SetUp]
public void SetUp()
{
_container = new Container(registry =>
{
registry.Scan(x => x.Assembly("StructureMap.Testing.Widget"));
registry.For<Rule>();
registry.For<IWidget>();
registry.For<WidgetMaker>();
});
}
#endregion
private IContainer _container;
private void addColorInstance(string Color)
{
_container.Configure(r =>
{
r.For<Rule>().Use<ColorRule>().Ctor<string>("color").Is(Color).Named(Color);
r.For<IWidget>().Use<ColorWidget>().Ctor<string>("color").Is(Color).Named(
Color);
r.For<WidgetMaker>().Use<ColorWidgetMaker>().Ctor<string>("color").Is(Color).
Named(Color);
});
}
public interface IProvider
{
}
public class Provider : IProvider
{
}
public class ClassThatUsesProvider
{
private readonly IProvider _provider;
public ClassThatUsesProvider(IProvider provider)
{
_provider = provider;
}
public IProvider Provider { get { return _provider; } }
}
public class DifferentProvider : IProvider
{
}
private void assertColorIs(IContainer container, string color)
{
container.GetInstance<IService>().ShouldBeOfType<ColorService>().Color.ShouldEqual(color);
}
[Test]
public void can_inject_into_a_running_container()
{
var container = new Container();
container.Inject(typeof(ISport), new ConstructorInstance(typeof(Football)));
container.GetInstance<ISport>()
.ShouldBeOfType<Football>();
}
[Test]
public void Can_set_profile_name_and_reset_defaults()
{
var container = new Container(r =>
{
r.For<IService>()
.Use<ColorService>().Named("Orange").Ctor<string>("color").Is(
"Orange");
r.For<IService>().AddInstances(x =>
{
x.Type<ColorService>().Named("Red").Ctor<string>("color").Is("Red");
x.Type<ColorService>().Named("Blue").Ctor<string>("color").Is("Blue");
x.Type<ColorService>().Named("Green").Ctor<string>("color").Is("Green");
});
r.Profile("Red", x => {
x.For<IService>().Use("Red");
});
r.Profile("Blue", x => {
x.For<IService>().Use("Blue");
});
});
assertColorIs(container, "Orange");
assertColorIs(container.GetProfile("Red"), "Red");
assertColorIs(container.GetProfile("Blue"), "Blue");
assertColorIs(container, "Orange");
}
[Test]
public void CanBuildConcreteTypesThatAreNotPreviouslyRegistered()
{
IContainer manager = new Container(
registry => registry.For<IProvider>().Use<Provider>());
// Now, have that same Container create a ClassThatUsesProvider. StructureMap will
// see that ClassThatUsesProvider is concrete, determine its constructor args, and build one
// for you with the default IProvider. No other configuration necessary.
var classThatUsesProvider = manager.GetInstance<ClassThatUsesProvider>();
classThatUsesProvider.Provider.ShouldBeOfType<Provider>();
}
[Test]
public void CanBuildConcreteTypesThatAreNotPreviouslyRegisteredWithArgumentsProvided()
{
IContainer manager =
new Container(
registry => registry.For<IProvider>().Use<Provider>());
var differentProvider = new DifferentProvider();
var args = new ExplicitArguments();
args.Set<IProvider>(differentProvider);
var classThatUsesProvider = manager.GetInstance<ClassThatUsesProvider>(args);
Assert.AreSame(differentProvider, classThatUsesProvider.Provider);
}
[Test]
public void GetDefaultInstance()
{
addColorInstance("Red");
addColorInstance("Orange");
addColorInstance("Blue");
_container.Configure(x => { x.For<Rule>().Use("Blue"); });
_container.GetInstance<Rule>().ShouldBeOfType<ColorRule>().Color.ShouldEqual("Blue");
}
[Test]
public void GetInstanceOf3Types()
{
addColorInstance("Red");
addColorInstance("Orange");
addColorInstance("Blue");
var rule = _container.GetInstance(typeof (Rule), "Blue") as ColorRule;
Assert.IsNotNull(rule);
Assert.AreEqual("Blue", rule.Color);
var widget = _container.GetInstance(typeof (IWidget), "Red") as ColorWidget;
Assert.IsNotNull(widget);
Assert.AreEqual("Red", widget.Color);
var maker = _container.GetInstance(typeof (WidgetMaker), "Orange") as ColorWidgetMaker;
Assert.IsNotNull(maker);
Assert.AreEqual("Orange", maker.Color);
}
[Test, ExpectedException(typeof (StructureMapException))]
public void GetMissingType()
{
object o = _container.GetInstance(typeof (string));
}
[Test]
public void InjectStub_by_name()
{
IContainer container = new Container();
var red = new ColorRule("Red");
var blue = new ColorRule("Blue");
container.Configure(x =>
{
x.For<Rule>().Add(red).Named("Red");
x.For<Rule>().Add(blue).Named("Blue");
});
Assert.AreSame(red, container.GetInstance<Rule>("Red"));
Assert.AreSame(blue, container.GetInstance<Rule>("Blue"));
}
[Test]
public void TryGetInstance_returns_instance_for_an_open_generic_that_it_can_close()
{
var container =
new Container(
x =>
x.For(typeof (IOpenGeneric<>)).Use(typeof (ConcreteOpenGeneric<>)));
container.TryGetInstance<IOpenGeneric<object>>().ShouldNotBeNull();
}
[Test]
public void TryGetInstance_returns_null_for_an_open_generic_that_it_cannot_close()
{
var container =
new Container(
x =>
x.For(typeof (IOpenGeneric<>)).Use(typeof (ConcreteOpenGeneric<>)));
container.TryGetInstance<IAnotherOpenGeneric<object>>().ShouldBeNull();
}
[Test]
public void TryGetInstance_ReturnsInstance_WhenTypeFound()
{
_container.Configure(c => c.For<IProvider>().Use<Provider>());
object instance = _container.TryGetInstance(typeof (IProvider));
instance.ShouldBeOfType(typeof (Provider));
}
[Test]
public void TryGetInstance_ReturnsNull_WhenTypeNotFound()
{
object instance = _container.TryGetInstance(typeof (IProvider));
instance.ShouldBeNull();
}
[Test]
public void TryGetInstanceViaGeneric_ReturnsInstance_WhenTypeFound()
{
_container.Configure(c => c.For<IProvider>().Use<Provider>());
var instance = _container.TryGetInstance<IProvider>();
instance.ShouldBeOfType(typeof (Provider));
}
[Test]
public void TryGetInstanceViaGeneric_ReturnsNull_WhenTypeNotFound()
{
var instance = _container.TryGetInstance<IProvider>();
instance.ShouldBeNull();
}
[Test]
public void TryGetInstanceViaName_ReturnsNull_WhenNotFound()
{
addColorInstance("Red");
addColorInstance("Orange");
addColorInstance("Blue");
object rule = _container.TryGetInstance(typeof (Rule), "Yellow");
rule.ShouldBeNull();
}
[Test]
public void TryGetInstanceViaName_ReturnsTheOutInstance_WhenFound()
{
addColorInstance("Red");
addColorInstance("Orange");
addColorInstance("Blue");
object rule = _container.TryGetInstance(typeof (Rule), "Orange");
rule.ShouldBeOfType(typeof (ColorRule));
}
[Test]
public void TryGetInstanceViaNameAndGeneric_ReturnsInstance_WhenTypeFound()
{
addColorInstance("Red");
addColorInstance("Orange");
addColorInstance("Blue");
// "Orange" exists, so an object should be returned
var instance = _container.TryGetInstance<Rule>("Orange");
instance.ShouldBeOfType(typeof (ColorRule));
}
[Test]
public void TryGetInstanceViaNameAndGeneric_ReturnsNull_WhenTypeNotFound()
{
addColorInstance("Red");
addColorInstance("Orange");
addColorInstance("Blue");
// "Yellow" does not exist, so return null
var instance = _container.TryGetInstance<Rule>("Yellow");
instance.ShouldBeNull();
}
[Test, ExpectedException(typeof (StructureMapException))]
public void TryToGetDefaultInstanceWithNoInstance()
{
var manager = new Container(new PluginGraph());
manager.GetInstance<IService>();
}
}
public interface ISport{}
public class Football : ISport
{
}
public interface IOpenGeneric<T>
{
void Nop();
}
public interface IAnotherOpenGeneric<T>
{
}
public class ConcreteOpenGeneric<T> : IOpenGeneric<T>
{
public void Nop()
{
}
}
public class StringOpenGeneric : ConcreteOpenGeneric<string>
{
}
}
| |
//*******************************************************
//
// Delphi DataSnap Framework
//
// Copyright(c) 1995-2011 Embarcadero Technologies, Inc.
//
//*******************************************************
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
namespace Embarcadero.Datasnap.WindowsPhone7
{
/**
*
* Implements a JSON object.
*
*/
public class TJSONObject : TJSONValue {
protected List<TJSONPair> Elements;
public override JSONValueType getJsonValueType() {
return JSONValueType.JSONObject;
}
protected List<TJSONPair> buildElements(JObject o) {
try {
String pname;
List<TJSONPair> res = new List<TJSONPair>();
IEnumerator<KeyValuePair<String,JToken>> keys = o.GetEnumerator();
while (keys.MoveNext())
{
pname = keys.Current.Key;
JToken jtk = keys.Current.Value;
JTokenType jttype = keys.Current.Value.Type;
switch (jttype) {
case JTokenType.Null: {
res.Add(new TJSONPair(pname, new TJSONNull()));
break;
}
case JTokenType.String:
{
res.Add(new TJSONPair(pname, new TJSONString(jtk.Value<string>())));
break;
}
case JTokenType.Float:
{
res.Add(new TJSONPair(pname, new TJSONNumber(jtk.Value<float>())));
break;
}
case JTokenType.Integer:
{
res.Add(new TJSONPair(pname, new TJSONNumber(jtk.Value<Int32>())));
break;
}
case JTokenType.Array:
{
res.Add(new TJSONPair(pname, new TJSONArray(jtk.Value<JArray>())));
break;
}
case JTokenType.Object:
{
res.Add(new TJSONPair(pname, new TJSONObject(jtk.Value<JObject>())));
break;
}
case JTokenType.Boolean:
{
if (jtk.Value<bool>())
res.Add(new TJSONPair(pname, new TJSONTrue()));
else
res.Add(new TJSONPair(pname, new TJSONFalse()));
break;
}
}
}
return res;
} catch (Exception) {
return null;
}
}
protected JObject asJSONObject() {
try {
JObject j = new JObject();
foreach (TJSONPair pair in Elements) {
switch (pair.value.getJsonValueType()) {
case JSONValueType.JSONObject: {
j.Add(pair.name, ((TJSONObject) pair.value).asJSONObject());
break;
}
case JSONValueType.JSONArray:
{
j.Add(pair.name, ((TJSONArray) pair.value).asJSONArray());
break;
}
case JSONValueType.JSONString:
{
j.Add(pair.name, ((TJSONString) pair.value).getValue());
break;
}
case JSONValueType.JSONNumber:
{
if(((TJSONNumber) pair.value).isDouble == true )
j.Add(pair.name, ((TJSONNumber) pair.value).getValue());
else
j.Add(pair.name, ((TJSONNumber)pair.value).getValueInt());
break;
}
case JSONValueType.JSONTrue:
{
j.Add(pair.name, true);
break;
}
case JSONValueType.JSONFalse:
{
j.Add(pair.name, false);
break;
}
case JSONValueType.JSONNull:
{
j.Add(pair.name, null);
break;
}
}
}
return j;
} catch (Exception) {
return null;
}
}
public TJSONObject() : base()
{
Elements = new List<TJSONPair>();
}
/**
* Parse the passed String into a new TJSONObject
*
* @param value
* @return
*/
public static TJSONObject Parse(String value) {
try {
JObject o = JObject.Parse(value);
return new TJSONObject(o);
} catch (Exception) {
return null;
}
}
/**
* Initialized the instance with a JSONObject;
*
* @param json
*/
public TJSONObject(JObject json) : base()
{
Elements = buildElements(json);
}
/**
* Class constructor, create the internal list and add the passed
* {@link TJSONPair}
*
* @param pair
*/
public TJSONObject(TJSONPair pair) : base()
{
Elements = new List<TJSONPair>();
addPairs(pair);
}
public override String ToString() {
return asJSONObject().ToString(Newtonsoft.Json.Formatting.None);
}
public override Object getInternalObject() {
return asJSONObject();
}
/**
* Returns a String value by the name
* @param name
* @return String
*/
public String getString(String name) {
TJSONPair p;
return ((p = get(name)) == null) ? null : ((TJSONString) p.value)
.getValue();
}
/**
* Returns a Boolean value by the name
* @param name
* @return boolean?
*/
public Boolean? getBoolean(String name) {
TJSONPair p = get(name);
if (p == null)
return null;
if (p.value is TJSONTrue)
return true;
else
return false;
}
/**
* Returns a Double value by the name
* @param name
* @return double?
*/
public Double? getDouble(String name) {
TJSONPair p = get(name);
if (p == null)
return null;
return Convert.ToDouble(((TJSONNumber)p.value).getValue());
}
/**
* Returns a TJSONObject value by the name
* @param name
* @return TJSONObject
*/
public TJSONObject getJSONObject(String name) {
TJSONPair p;
return ((p = get(name)) == null) ? null : ((TJSONObject) (p.value));
}
/**
* Returns a Integer value by the name
* @param name
* @return int?
*/
public int? getInt(String name) {
TJSONPair p = get(name);
if (p == null)
return null;
return Convert.ToInt32(((TJSONNumber) p.value).getValue());
}
/**
* Returns a {@link TJSONArray} value by the name
* @param name
* @return TJSONArray
*/
public TJSONArray getJSONArray(String name) {
TJSONPair p;
return ((p = get(name)) == null) ? null : ((TJSONArray) p.value);
}
/**
* Detects if it has a key with the name specified.
* @param name
* @return boolean
*/
public Boolean has(String name) {
return get(name) != null;
}
/**
* Gets a {@link TJSONPair} from a name
* @param name
* @return TJSONPair
*/
public TJSONPair get(String name) {
foreach (TJSONPair v in Elements) {
if (v.name.Equals(name))
return v;
}
return null;
}
/**
* Adds {@link TJSONPair}
* @param pair
* @return TJSONObject
*/
public TJSONObject addPairs(TJSONPair pair) {
Elements.Add(pair);
return this;
}
/**
* Adds a pair with name and a {@link TJSONValue}
* @param String name
* @param TJSONValue value
* @return TJSONObject
*/
public TJSONObject addPairs(String name, TJSONValue value) {
return addPairs(new TJSONPair(name, value));
}
/**
* Adds a pair with name and an int value
* @param String name
* @param int value
* @return TJSONObject
*/
public TJSONObject addPairs(String name, int value) {
return addPairs(name, new TJSONNumber(value));
}
/**
* Adds a pair with name and a String value
* @param String name
* @param String value
* @return TJSONObject
*/
public TJSONObject addPairs(String name, String value) {
return addPairs(name, new TJSONString(value));
}
/**
* Adds a pair with name and a long value
* @param String name
* @param long value
* @return TJSONObject
*/
public TJSONObject addPairs(String name, long value) {
return addPairs(name, new TJSONNumber(value));
}
/**
* Adds a pair with name and a double value
* @param String name
* @param double value
* @return TJSONObject
*/
public TJSONObject addPairs(String name, double value) {
return addPairs(name, new TJSONNumber(value));
}
/**
* Adds a pair with name and a boolean value
* @param String name
* @param bool value
* @return TJSONObject
*/
public TJSONObject addPairs(String name, bool value) {
if (value)
return addPairs(name, new TJSONTrue());
else
return addPairs(name, new TJSONFalse());
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace csharp
{
public partial class Form1 : Form
{
[StructLayout(LayoutKind.Sequential)]
public struct TPos
{
public double X, Y, Z, Phi, Theta, Psi;
}
[DllImport("../../../../lib/win32/KNI_Wrapper.dll")]
static extern int initKatana(string configFile, string ipAddress);
//[DllImport("KNI_Wrapper.dll", CallingConvention = CallingConvention.Cdecl)]
[DllImport("../../../../lib/win32/KNI_Wrapper.dll")]
static extern int calibrate(int axis);
[DllImport("../../../../lib/win32/KNI_Wrapper.dll")]
static extern int getPosition(ref TPos position);
[DllImport("../../../../lib/win32/KNI_Wrapper.dll")]
static extern int moveToPos(ref TPos position, int vel, int accel);
[DllImport("../../../../lib/win32/KNI_Wrapper.dll")]
static extern int moveToPosLin(ref TPos position, int vel, int accel);
[DllImport("../../../../lib/win32/KNI_Wrapper.dll")]
static extern int allMotorsOn();
[DllImport("../../../../lib/win32/KNI_Wrapper.dll")]
static extern int allMotorsOff();
public Form1()
{
InitializeComponent();
}
private void initialize_Click(object sender, EventArgs e)
{
//use Socket connection:
tbOutput.AppendText("Initializing Katana...");
//katana = new KNInet.Katana(tbIpAddress.Text, comPort.Text, configurationFile.Text);
if (initKatana(toolStripConfigFile.Text, toolStripIPAddress.Text) == 1)
{
tbOutput.AppendText(" done.\n");
BtnCalibrate.Enabled = true;
MotorsOff.Enabled = true;
MotorsOn.Enabled = true;
buttonRead.Enabled = true;
toolStripConnect.Image = csharp.Properties.Resources.connect;
//return ((System.Drawing.Bitmap)(obj));
}
else
tbOutput.AppendText(" failed.\n");
}
private void configurationFile_Click(object sender, EventArgs e)
{
openConfigFileDialog.ShowDialog();
}
private void calibrate_Click(object sender, EventArgs e)
{
tbOutput.AppendText("Calibrating Katana...");
calibrate(0);
tbOutput.AppendText(" done\n");
buttonGo.Enabled = true;
buttonRead_Click(sender, e);
}
private void openConfigFileDialog_FileOk(object sender, CancelEventArgs e)
{
toolStripConfigFile.Text = openConfigFileDialog.FileName;
}
private void run_Click(object sender, EventArgs e)
{
tbOutput.AppendText("Demo:\n");
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void configurationFile_TextChanged(object sender, EventArgs e)
{
}
private void btnClose_Click(object sender, EventArgs e)
{
Close();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void buttonRead_Click(object sender, EventArgs e)
{
tbOutput.AppendText("Read Coordinates.\n");
TPos position = new TPos();
getPosition(ref position);
numericUpDownX.Value =(decimal)position.X;
numericUpDownY.Value = (decimal)position.Y;
numericUpDownZ.Value = (decimal)position.Z;
numericUpDownPhi.Value = (decimal)position.Phi;
numericUpDownTheta.Value = (decimal)position.Theta;
numericUpDownPsi.Value = (decimal)position.Psi;
}
private void buttonGo_Click(object sender, EventArgs e)
{
TPos position = new TPos();
position.X = (double)numericUpDownX.Value;
position.Y = (double)numericUpDownY.Value;
position.Z = (double)numericUpDownZ.Value;
position.Phi = (double)numericUpDownPhi.Value;
position.Theta = (double)numericUpDownTheta.Value;
position.Psi = (double)numericUpDownPsi.Value;
if (checkBoxLM.Checked == true)
{
tbOutput.AppendText("Move Linear.. ");
moveToPosLin(ref position, (int)numericUpDownVel.Value, 1);
tbOutput.AppendText("Done.\n");
}
else
{
tbOutput.AppendText("Move PTP.. ");
moveToPos(ref position, (int)numericUpDownVel.Value, 1);
tbOutput.AppendText("Done.\n");
}
}
private void numericUpDownX_ValueChanged(object sender, EventArgs e)
{
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
}
private void label7_Click(object sender, EventArgs e)
{
}
private void tbIpAddress_TextChanged(object sender, EventArgs e)
{
}
private void toolStripIPAddress_Click(object sender, EventArgs e)
{
}
private void tbOutput_TextChanged(object sender, EventArgs e)
{
}
private void MotorsOn_Click(object sender, EventArgs e)
{
tbOutput.AppendText("Motors ON.\n");
allMotorsOn();
buttonRead_Click(sender, e);
}
private void MotorsOff_Click(object sender, EventArgs e)
{
tbOutput.AppendText("Motors OFF.\n");
allMotorsOff();
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
}
}
| |
/*
* DISCLAIMER
*
* Copyright 2016 ArangoDB GmbH, Cologne, Germany
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright holder is ArangoDB GmbH, Cologne, Germany
*/
namespace ArangoDB.Internal
{
using global::ArangoDB.Entity;
using global::ArangoDB.Internal.VelocyStream;
using global::ArangoDB.Model;
using global::ArangoDB.Velocypack;
using global::ArangoDB.Velocypack.Exceptions;
using global::ArangoDB.Velocystream;
/// <author>Mark - mark at arangodb.com</author>
public class InternalArangoVertexCollection<E, R, C> : ArangoExecuteable
<E, R, C>
where E : ArangoExecutor<R, C>
where C : Connection
{
private readonly string db;
private readonly string graph;
private readonly string name;
public InternalArangoVertexCollection(E executor, string db, string graph, string
name)
: base(executor)
{
this.db = db;
this.graph = graph;
this.name = name;
}
public virtual string name()
{
return name;
}
protected internal virtual string createDocumentHandle(string key)
{
this.executor.validateDocumentKey(key);
return this.executor.createPath(name, key);
}
protected internal virtual Request dropRequest()
{
return new Request(this.db, RequestType
.DELETE, this.executor.createPath(ArangoDBConstants.PATH_API_GHARIAL
, this.graph, ArangoDBConstants.VERTEX, name));
}
protected internal virtual Request insertVertexRequest<
T>(T value, VertexCreateOptions options)
{
Request request = new Request
(this.db, RequestType.POST, this.executor.createPath(ArangoDBConstants
.PATH_API_GHARIAL, this.graph, ArangoDBConstants.VERTEX, name)
);
VertexCreateOptions @params = options != null ? options : new
VertexCreateOptions();
request.putQueryParam(ArangoDBConstants.WAIT_FOR_SYNC, @params
.getWaitForSync());
request.setBody(this.executor.Serialize(value));
return request;
}
protected internal virtual com.arangodb.@internal.ArangoExecutor.ResponseDeserializer
<VertexEntity> insertVertexResponseDeserializer<T>(T value)
{
return new _ResponseDeserializer_84(this, value);
}
private sealed class _ResponseDeserializer_84 : com.arangodb.@internal.ArangoExecutor.ResponseDeserializer
<VertexEntity>
{
public _ResponseDeserializer_84(InternalArangoVertexCollection<E, R, C> _enclosing
, T value)
{
this._enclosing = _enclosing;
this.value = value;
}
/// <exception cref="VPackException"/>
public VertexEntity deserialize(Response
response)
{
VPackSlice body = response.getBody().get(ArangoDBConstants
.VERTEX);
VertexEntity doc = this._enclosing.executor.Deserialize(body,
typeof(VertexEntity));
System.Collections.Generic.IDictionary<com.arangodb.entity.DocumentFieldAttribute.Type, string
> values = new System.Collections.Generic.Dictionary<com.arangodb.entity.DocumentFieldAttribute.Type
, string>();
values[com.arangodb.entity.DocumentFieldAttribute.Type.ID] = doc.getId();
values[com.arangodb.entity.DocumentFieldAttribute.Type.KEY] = doc.getKey();
values[com.arangodb.entity.DocumentFieldAttribute.Type.REV] = doc.getRev();
this._enclosing.executor.documentCache().setValues(this.value, values);
return doc;
}
private readonly InternalArangoVertexCollection<E, R, C> _enclosing;
private readonly T value;
}
protected internal virtual Request getVertexRequest(string
key, DocumentReadOptions options)
{
Request request = new Request
(this.db, RequestType.GET, this.executor.createPath(ArangoDBConstants
.PATH_API_GHARIAL, this.graph, ArangoDBConstants.VERTEX, this.createDocumentHandle
(key)));
DocumentReadOptions @params = options != null ? options : new
DocumentReadOptions();
request.putHeaderParam(ArangoDBConstants.IF_NONE_MATCH, @params
.getIfNoneMatch());
request.putHeaderParam(ArangoDBConstants.IF_MATCH, @params
.getIfMatch());
return request;
}
protected internal virtual com.arangodb.@internal.ArangoExecutor.ResponseDeserializer
<T> getVertexResponseDeserializer<T>()
{
System.Type type = typeof(T);
return new _ResponseDeserializer_109(this, type);
}
private sealed class _ResponseDeserializer_109 : ArangoExecutor<,>.IResponseDeserializer
<T>
{
public _ResponseDeserializer_109(InternalArangoVertexCollection<E, R, C> _enclosing
, java.lang.Class type)
{
this._enclosing = _enclosing;
this.type = type;
}
/// <exception cref="VPackException"/>
public T Deserialize(Response response)
{
return this._enclosing.executor.Deserialize(response.getBody().get(ArangoDBConstants
.VERTEX), this.type);
}
private readonly InternalArangoVertexCollection<E, R, C> _enclosing;
private readonly java.lang.Class type;
}
protected internal virtual Request replaceVertexRequest
<T>(string key, T value, VertexReplaceOptions options)
{
Request request = new Request
(this.db, RequestType.PUT, this.executor.createPath(ArangoDBConstants
.PATH_API_GHARIAL, this.graph, ArangoDBConstants.VERTEX, this.createDocumentHandle
(key)));
VertexReplaceOptions @params = options != null ? options : new
VertexReplaceOptions();
request.putQueryParam(ArangoDBConstants.WAIT_FOR_SYNC, @params
.getWaitForSync());
request.putHeaderParam(ArangoDBConstants.IF_MATCH, @params
.getIfMatch());
request.setBody(this.executor.Serialize(value));
return request;
}
protected internal virtual com.arangodb.@internal.ArangoExecutor.ResponseDeserializer
<VertexUpdateEntity> replaceVertexResponseDeserializer<T>(T
value)
{
return new _ResponseDeserializer_128(this, value);
}
private sealed class _ResponseDeserializer_128 : com.arangodb.@internal.ArangoExecutor.ResponseDeserializer
<VertexUpdateEntity>
{
public _ResponseDeserializer_128(InternalArangoVertexCollection<E, R, C> _enclosing
, T value)
{
this._enclosing = _enclosing;
this.value = value;
}
/// <exception cref="VPackException"/>
public VertexUpdateEntity deserialize(Response
response)
{
VPackSlice body = response.getBody().get(ArangoDBConstants
.VERTEX);
VertexUpdateEntity doc = this._enclosing.executor.Deserialize
(body, typeof(VertexUpdateEntity
));
System.Collections.Generic.IDictionary<com.arangodb.entity.DocumentFieldAttribute.Type, string
> values = new System.Collections.Generic.Dictionary<com.arangodb.entity.DocumentFieldAttribute.Type
, string>();
values[com.arangodb.entity.DocumentFieldAttribute.Type.REV] = doc.getRev();
this._enclosing.executor.documentCache().setValues(this.value, values);
return doc;
}
private readonly InternalArangoVertexCollection<E, R, C> _enclosing;
private readonly T value;
}
protected internal virtual Request updateVertexRequest<
T>(string key, T value, VertexUpdateOptions options)
{
Request request;
request = new Request(this.db, RequestType
.PATCH, this.executor.createPath(ArangoDBConstants.PATH_API_GHARIAL
, this.graph, ArangoDBConstants.VERTEX, this.createDocumentHandle(key
)));
VertexUpdateOptions @params = options != null ? options : new
VertexUpdateOptions();
request.putQueryParam(ArangoDBConstants.KEEP_NULL, @params
.getKeepNull());
request.putQueryParam(ArangoDBConstants.WAIT_FOR_SYNC, @params
.getWaitForSync());
request.putHeaderParam(ArangoDBConstants.IF_MATCH, @params
.getIfMatch());
request.setBody(this.executor.Serialize(value, true));
return request;
}
protected internal virtual com.arangodb.@internal.ArangoExecutor.ResponseDeserializer
<VertexUpdateEntity> updateVertexResponseDeserializer<T>(T value
)
{
return new _ResponseDeserializer_154(this);
}
private sealed class _ResponseDeserializer_154 : com.arangodb.@internal.ArangoExecutor.ResponseDeserializer
<VertexUpdateEntity>
{
public _ResponseDeserializer_154(InternalArangoVertexCollection<E, R, C> _enclosing
)
{
this._enclosing = _enclosing;
}
/// <exception cref="VPackException"/>
public VertexUpdateEntity deserialize(Response
response)
{
VPackSlice body = response.getBody().get(ArangoDBConstants
.VERTEX);
return this._enclosing.executor.Deserialize(body,
typeof(VertexUpdateEntity));
}
private readonly InternalArangoVertexCollection<E, R, C> _enclosing;
}
protected internal virtual Request deleteVertexRequest(
string key, VertexDeleteOptions options)
{
Request request = new Request
(this.db, RequestType.DELETE, this.executor.createPath(ArangoDBConstants
.PATH_API_GHARIAL, this.graph, ArangoDBConstants.VERTEX, this.createDocumentHandle
(key)));
VertexDeleteOptions @params = options != null ? options : new
VertexDeleteOptions();
request.putQueryParam(ArangoDBConstants.WAIT_FOR_SYNC, @params
.getWaitForSync());
request.putHeaderParam(ArangoDBConstants.IF_MATCH, @params
.getIfMatch());
return request;
}
}
}
| |
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;
using NUnit.Framework;
using Umbraco.Cms.Core;
using Umbraco.Extensions;
namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Core
{
[TestFixture]
public class ReflectionUtilitiesTests
{
[Test]
public void EmitCtorEmits()
{
Func<Class1> ctor1 = ReflectionUtilities.EmitConstructor<Func<Class1>>();
Assert.IsInstanceOf<Class1>(ctor1());
Func<object> ctor2 = ReflectionUtilities.EmitConstructor<Func<object>>(declaring: typeof(Class1));
Assert.IsInstanceOf<Class1>(ctor2());
Func<int, Class3> ctor3 = ReflectionUtilities.EmitConstructor<Func<int, Class3>>();
Assert.IsInstanceOf<Class3>(ctor3(42));
Func<int, object> ctor4 = ReflectionUtilities.EmitConstructor<Func<int, object>>(declaring: typeof(Class3));
Assert.IsInstanceOf<Class3>(ctor4(42));
}
[Test]
public void EmitCtorEmitsFromInfo()
{
ConstructorInfo ctorInfo = typeof(Class1).GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, CallingConventions.Any, Array.Empty<Type>(), null);
Func<Class1> ctor1 = ReflectionUtilities.EmitConstructor<Func<Class1>>(ctorInfo);
Assert.IsInstanceOf<Class1>(ctor1());
ctorInfo = typeof(Class1).GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, CallingConventions.Any, new[] { typeof(int) }, null);
Func<int, object> ctor3 = ReflectionUtilities.EmitConstructor<Func<int, object>>(ctorInfo);
Assert.IsInstanceOf<Class1>(ctor3(42));
Assert.Throws<ArgumentException>(() => ReflectionUtilities.EmitConstructor<Func<string, object>>(ctorInfo));
}
[Test]
public void EmitCtorEmitsPrivateCtor()
{
Func<string, Class3> ctor = ReflectionUtilities.EmitConstructor<Func<string, Class3>>();
Assert.IsInstanceOf<Class3>(ctor("foo"));
}
[Test]
public void EmitCtorThrowsIfNotFound() =>
Assert.Throws<InvalidOperationException>(() => ReflectionUtilities.EmitConstructor<Func<bool, Class3>>());
[Test]
public void EmitCtorThrowsIfInvalid()
{
ConstructorInfo ctorInfo = typeof(Class1).GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, CallingConventions.Any, Array.Empty<Type>(), null);
Assert.Throws<ArgumentException>(() => ReflectionUtilities.EmitConstructor<Func<Class2>>(ctorInfo));
}
[Test]
public void EmitCtorReturnsNull() =>
Assert.IsNull(ReflectionUtilities.EmitConstructor<Func<bool, Class3>>(false));
[Test]
public void EmitMethodEmitsInstance()
{
var class1 = new Class1();
Action<Class1> method1 = ReflectionUtilities.EmitMethod<Action<Class1>>("Method1");
method1(class1);
Action<Class1, int> method2 = ReflectionUtilities.EmitMethod<Action<Class1, int>>("Method2");
method2(class1, 42);
Func<Class1, int> method3 = ReflectionUtilities.EmitMethod<Func<Class1, int>>("Method3");
Assert.AreEqual(42, method3(class1));
Func<Class1, string, int> method4 = ReflectionUtilities.EmitMethod<Func<Class1, string, int>>("Method4");
Assert.AreEqual(42, method4(class1, "42"));
}
[Test]
public void EmitMethodEmitsStatic()
{
Action method1 = ReflectionUtilities.EmitMethod<Class1, Action>("SMethod1");
method1();
Action<int> method2 = ReflectionUtilities.EmitMethod<Class1, Action<int>>("SMethod2");
method2(42);
Func<int> method3 = ReflectionUtilities.EmitMethod<Class1, Func<int>>("SMethod3");
Assert.AreEqual(42, method3());
Func<string, int> method4 = ReflectionUtilities.EmitMethod<Class1, Func<string, int>>("SMethod4");
Assert.AreEqual(42, method4("42"));
}
[Test]
public void EmitMethodEmitsStaticStatic()
{
Action method = ReflectionUtilities.EmitMethod<Action>(typeof(StaticClass1), "Method");
method();
}
[Test]
public void EmitMethodEmitsFromInfo()
{
var class1 = new Class1();
MethodInfo methodInfo = typeof(Class1).GetMethod("Method1", BindingFlags.Instance | BindingFlags.Public);
Action<Class1> method1 = ReflectionUtilities.EmitMethod<Action<Class1>>(methodInfo);
method1(class1);
methodInfo = typeof(Class1).GetMethod("Method2", BindingFlags.Instance | BindingFlags.Public, null, new[] { typeof(int) }, null);
Action<Class1, int> method2 = ReflectionUtilities.EmitMethod<Action<Class1, int>>(methodInfo);
method2(class1, 42);
methodInfo = typeof(Class1).GetMethod("Method3", BindingFlags.Instance | BindingFlags.Public);
Func<Class1, int> method3 = ReflectionUtilities.EmitMethod<Func<Class1, int>>(methodInfo);
Assert.AreEqual(42, method3(class1));
methodInfo = typeof(Class1).GetMethod("Method4", BindingFlags.Instance | BindingFlags.Public, null, new[] { typeof(string) }, null);
Func<Class1, string, int> method4 = ReflectionUtilities.EmitMethod<Func<Class1, string, int>>(methodInfo);
Assert.AreEqual(42, method4(class1, "42"));
methodInfo = typeof(Class1).GetMethod("SMethod1", BindingFlags.Static | BindingFlags.Public);
Action smethod1 = ReflectionUtilities.EmitMethod<Action>(methodInfo);
smethod1();
methodInfo = typeof(Class1).GetMethod("SMethod2", BindingFlags.Static | BindingFlags.Public, null, new[] { typeof(int) }, null);
Action<int> smethod2 = ReflectionUtilities.EmitMethod<Action<int>>(methodInfo);
smethod2(42);
methodInfo = typeof(Class1).GetMethod("SMethod3", BindingFlags.Static | BindingFlags.Public);
Func<int> smethod3 = ReflectionUtilities.EmitMethod<Func<int>>(methodInfo);
Assert.AreEqual(42, smethod3());
methodInfo = typeof(Class1).GetMethod("SMethod4", BindingFlags.Static | BindingFlags.Public, null, new[] { typeof(string) }, null);
Func<string, int> smethod4 = ReflectionUtilities.EmitMethod<Func<string, int>>(methodInfo);
Assert.AreEqual(42, smethod4("42"));
methodInfo = typeof(StaticClass1).GetMethod("Method", BindingFlags.Static | BindingFlags.Public);
Action method = ReflectionUtilities.EmitMethod<Action>(methodInfo);
method();
}
[Test]
public void EmitMethodEmitsPrivateMethod()
{
var class1 = new Class1();
Action<Class1> method1 = ReflectionUtilities.EmitMethod<Action<Class1>>("MethodP1");
method1(class1);
Action method2 = ReflectionUtilities.EmitMethod<Class1, Action>("SMethodP1");
method2();
}
[Test]
public void EmitMethodThrowsIfNotFound()
{
Assert.Throws<InvalidOperationException>(() => ReflectionUtilities.EmitMethod<Action<Class1>>("ZZZ"));
Assert.Throws<InvalidOperationException>(() => ReflectionUtilities.EmitMethod<Action<Class1, int, int>>("Method1"));
}
[Test]
public void EmitMethodThrowsIfInvalid()
{
MethodInfo methodInfo = typeof(Class1).GetMethod("Method1", BindingFlags.Instance | BindingFlags.Public);
Assert.Throws<ArgumentException>(() => ReflectionUtilities.EmitMethod<Action<Class1, int, int>>(methodInfo));
}
[Test]
public void EmitMethodReturnsNull()
{
Assert.IsNull(ReflectionUtilities.EmitMethod<Action<Class1>>("ZZZ", false));
Assert.IsNull(ReflectionUtilities.EmitMethod<Action<Class1, int, int>>("Method1", false));
}
[Test]
public void EmitPropertyEmits()
{
var class1 = new Class1();
Func<Class1, int> getter1 = ReflectionUtilities.EmitPropertyGetter<Class1, int>("Value1");
Assert.AreEqual(42, getter1(class1));
Func<Class1, int> getter2 = ReflectionUtilities.EmitPropertyGetter<Class1, int>("Value3");
Assert.AreEqual(42, getter2(class1));
Action<Class1, int> setter1 = ReflectionUtilities.EmitPropertySetter<Class1, int>("Value2");
setter1(class1, 42);
Action<Class1, int> setter2 = ReflectionUtilities.EmitPropertySetter<Class1, int>("Value3");
setter2(class1, 42);
(Func<Class1, int> getter3, Action<Class1, int> setter3) = ReflectionUtilities.EmitPropertyGetterAndSetter<Class1, int>("Value3");
Assert.AreEqual(42, getter3(class1));
setter3(class1, 42);
}
[Test]
public void EmitPropertyEmitsFromInfo()
{
var class1 = new Class1();
PropertyInfo propertyInfo = typeof(Class1).GetProperty("Value1");
Func<Class1, int> getter1 = ReflectionUtilities.EmitPropertyGetter<Class1, int>(propertyInfo);
Assert.AreEqual(42, getter1(class1));
propertyInfo = typeof(Class1).GetProperty("Value3");
Func<Class1, int> getter2 = ReflectionUtilities.EmitPropertyGetter<Class1, int>(propertyInfo);
Assert.AreEqual(42, getter2(class1));
propertyInfo = typeof(Class1).GetProperty("Value2");
Action<Class1, int> setter1 = ReflectionUtilities.EmitPropertySetter<Class1, int>(propertyInfo);
setter1(class1, 42);
propertyInfo = typeof(Class1).GetProperty("Value3");
Action<Class1, int> setter2 = ReflectionUtilities.EmitPropertySetter<Class1, int>(propertyInfo);
setter2(class1, 42);
(Func<Class1, int> getter3, Action<Class1, int> setter3) = ReflectionUtilities.EmitPropertyGetterAndSetter<Class1, int>(propertyInfo);
Assert.AreEqual(42, getter3(class1));
setter3(class1, 42);
}
[Test]
public void EmitPropertyEmitsPrivateProperty()
{
var class1 = new Class1();
Func<Class1, int> getter1 = ReflectionUtilities.EmitPropertyGetter<Class1, int>("ValueP1");
Assert.AreEqual(42, getter1(class1));
}
[Test]
public void EmitPropertyThrowsIfNotFound()
{
Assert.Throws<InvalidOperationException>(() => ReflectionUtilities.EmitPropertyGetter<Class1, int>("Zalue1"));
Assert.Throws<InvalidOperationException>(() => ReflectionUtilities.EmitPropertyGetter<Class1, int>("Value2"));
PropertyInfo propertyInfo = typeof(Class1).GetProperty("Value1");
Assert.Throws<ArgumentException>(() => ReflectionUtilities.EmitPropertySetter<Class1, int>(propertyInfo));
}
[Test]
public void EmitPropertyThrowsIfInvalid() =>
Assert.Throws<ArgumentException>(() => ReflectionUtilities.EmitPropertyGetter<Class1, string>("Value1"));
[Test]
public void EmitPropertyReturnsNull()
{
Assert.IsNull(ReflectionUtilities.EmitPropertyGetter<Class1, int>("Zalue1", false));
Assert.IsNull(ReflectionUtilities.EmitPropertyGetter<Class1, int>("Value2", false));
}
[Test]
public void PropertySetterCanCastUnsafeValue()
{
// test that we can emit property setters that cast from eg 'object'
Type type4 = typeof(Class4);
PropertyInfo propInt4 = type4.GetProperty("IntValue");
PropertyInfo propString4 = type4.GetProperty("StringValue");
PropertyInfo propClassA4 = type4.GetProperty("ClassAValue");
var object4 = new Class4();
var object2A = new Class2A();
// works with a string property
Assert.IsNotNull(propString4);
Action<Class4, object> setterString4 = ReflectionUtilities.EmitPropertySetterUnsafe<Class4, object>(propString4);
Assert.IsNotNull(setterString4);
setterString4(object4, "foo");
Assert.IsNotNull(object4.StringValue);
Assert.AreEqual("foo", object4.StringValue);
// unsafe is... unsafe
Assert.Throws<InvalidCastException>(() => setterString4(object4, new Class2()));
// works with a reference property
Assert.IsNotNull(propClassA4);
Action<Class4, object> setterClassA4 = ReflectionUtilities.EmitPropertySetterUnsafe<Class4, object>(propClassA4);
Assert.IsNotNull(setterClassA4);
setterClassA4(object4, object2A);
Assert.IsNotNull(object4.ClassAValue);
Assert.AreEqual(object2A, object4.ClassAValue);
// works with a boxed value type
Assert.IsNotNull(propInt4);
Action<Class4, object> setterInt4 = ReflectionUtilities.EmitPropertySetterUnsafe<Class4, object>(propInt4);
Assert.IsNotNull(setterInt4);
setterInt4(object4, 42);
Assert.AreEqual(42, object4.IntValue);
// FIXME: the code below runs fine with ReSharper test running within VisualStudio
// but it crashes when running via vstest.console.exe - unless some settings are required?
// converting works
setterInt4(object4, 42.0);
Assert.AreEqual(42, object4.IntValue);
// unsafe is... unsafe
Assert.Throws<FormatException>(() => setterInt4(object4, "foo"));
}
[Test]
public void PropertySetterCanCastObject()
{
// Class5 inherits from Class4 and ClassValue is defined on Class4
Type type5 = typeof(Class5);
PropertyInfo propClass4 = type5.GetProperty("ClassValue");
var object2 = new Class2();
// can cast the object type from Class5 to Class4
Action<Class5, Class2> setterClass4 = ReflectionUtilities.EmitPropertySetter<Class5, Class2>(propClass4);
var object4 = new Class5();
setterClass4(object4, object2);
Assert.IsNotNull(object4.ClassValue);
Assert.AreSame(object2, object4.ClassValue);
}
[Test]
public void PropertySetterCanCastUnsafeObject()
{
Type type5 = typeof(Class5);
PropertyInfo propClass4 = type5.GetProperty("ClassValue");
var object2 = new Class2();
// can cast the object type from object to Class4
Action<object, Class2> setterClass4 = ReflectionUtilities.EmitPropertySetterUnsafe<object, Class2>(propClass4);
var object4 = new Class5();
setterClass4(object4, object2);
Assert.IsNotNull(object4.ClassValue);
Assert.AreSame(object2, object4.ClassValue);
}
[Test]
public void PropertyGetterCanCastValue()
{
Type type4 = typeof(Class4);
PropertyInfo propClassA4 = type4.GetProperty("ClassAValue");
PropertyInfo propInt4 = type4.GetProperty("IntValue");
var object2A = new Class2A();
var object4 = new Class4 { ClassAValue = object2A, IntValue = 159 };
// can cast the return type from Class2A to Class2
Func<Class4, Class2> getterClassA4 = ReflectionUtilities.EmitPropertyGetter<Class4, Class2>(propClassA4);
Class2 valueClass4A = getterClassA4(object4);
Assert.IsNotNull(valueClass4A);
Assert.AreSame(object2A, valueClass4A);
// cannot cast the return type from Class2A to Class3!
Assert.Throws<ArgumentException>(()
=> ReflectionUtilities.EmitPropertyGetter<Class4, Class3>(propClassA4));
// can cast and box the return type from int to object
Func<Class4, object> getterInt4 = ReflectionUtilities.EmitPropertyGetter<Class4, object>(propInt4);
object valueInt4 = getterInt4(object4);
Assert.IsTrue(valueInt4 is int);
Assert.AreEqual(159, valueInt4);
// cannot cast the return type from int to Class3!
Assert.Throws<ArgumentException>(()
=> ReflectionUtilities.EmitPropertyGetter<Class4, Class3>(propInt4));
}
[Test]
public void PropertyGetterCanCastObject()
{
Type type5 = typeof(Class5);
PropertyInfo propClass4 = type5.GetProperty("ClassValue");
var object2 = new Class2();
var object4 = new Class5 { ClassValue = object2 };
// can cast the object type from Class5 to Class4
Func<Class5, Class2> getterClass4 = ReflectionUtilities.EmitPropertyGetter<Class5, Class2>(propClass4);
Class2 valueClass4 = getterClass4(object4);
Assert.IsNotNull(valueClass4);
Assert.AreSame(object2, valueClass4);
// cannot cast the object type from Class3 to Class4!
Assert.Throws<ArgumentException>(()
=> ReflectionUtilities.EmitPropertyGetter<Class3, Class2>(propClass4));
}
[Test]
public void EmitPropertyCastGetterEmits()
{
// test that we can emit property getters that cast the returned value to 'object'
// test simple class
Type type4 = typeof(Class4);
var object4 = new Class4
{
IntValue = 1,
StringValue = "foo",
ClassValue = new Class2(),
};
// works with a string property
PropertyInfo propString4 = type4.GetProperty("StringValue");
Assert.IsNotNull(propString4);
Func<Class4, object> getterString4 = ReflectionUtilities.EmitPropertyGetter<Class4, object>(propString4);
Assert.IsNotNull(getterString4);
object valueString4 = getterString4(object4);
Assert.IsNotNull(valueString4);
Assert.AreEqual("foo", valueString4);
// works with a reference property
PropertyInfo propClass4 = type4.GetProperty("ClassValue");
Assert.IsNotNull(propClass4);
Func<Class4, object> getterClass4 = ReflectionUtilities.EmitPropertyGetter<Class4, object>(propClass4);
Assert.IsNotNull(getterClass4);
object valueClass4 = getterClass4(object4);
Assert.IsNotNull(valueClass4);
Assert.IsInstanceOf<Class2>(valueClass4);
// works with a value type property
PropertyInfo propInt4 = type4.GetProperty("IntValue");
Assert.IsNotNull(propInt4);
// ... if explicitly getting a value type
Func<Class4, int> getterInt4T = ReflectionUtilities.EmitPropertyGetter<Class4, int>(propInt4);
Assert.IsNotNull(getterInt4T);
int valueInt4T = getterInt4T(object4);
Assert.AreEqual(1, valueInt4T);
// ... if using a compiled getter
object valueInt4D = GetIntValue(object4);
Assert.IsNotNull(valueInt4D);
Assert.IsTrue(valueInt4D is int);
Assert.AreEqual(1, valueInt4D);
// ... if getting a non-value type (emit adds a box)
Func<Class4, object> getterInt4 = ReflectionUtilities.EmitPropertyGetter<Class4, object>(propInt4);
Assert.IsNotNull(getterInt4);
object valueInt4 = getterInt4(object4);
Assert.IsNotNull(valueInt4);
Assert.IsTrue(valueInt4 is int);
Assert.AreEqual(1, valueInt4);
var getters4 = type4
.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy)
.ToDictionary(x => x.Name, x => (object)ReflectionUtilities.EmitPropertyGetter<Class4, object>(x));
Console.WriteLine("Getting object4 values...");
var values4 = getters4.ToDictionary(kvp => kvp.Key, kvp => ((Func<Class4, object>)kvp.Value)(object4));
Console.WriteLine("Writing object4 values...");
foreach ((string name, object value) in values4)
{
Console.WriteLine($"{name}: {value}");
}
Assert.AreEqual(4, values4.Count);
Assert.AreEqual("foo", values4["StringValue"]);
Assert.IsInstanceOf<Class2>(values4["ClassValue"]);
Assert.AreEqual(1, values4["IntValue"]);
// test hierarchy
Type type5 = typeof(Class5);
var getters5 = type5
.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy)
.ToDictionary(x => x.Name, x => (object)ReflectionUtilities.EmitPropertyGetter<Class5, object>(x));
var object5 = new Class5
{
IntValue = 1,
IntValue2 = 1,
StringValue = "foo",
StringValue2 = "foo",
ClassValue = new Class2(),
ClassValue2 = new Class2()
};
Console.WriteLine("Getting object5 values...");
var values5 = getters5.ToDictionary(kvp => kvp.Key, kvp => ((Func<Class5, object>)kvp.Value)(object5));
Console.WriteLine("Writing object5 values...");
foreach ((string name, object value) in values5)
{
Console.WriteLine($"{name}: {value}");
}
Assert.AreEqual(7, values5.Count);
Assert.AreEqual("foo", values5["StringValue"]);
Assert.IsInstanceOf<Class2>(values5["ClassValue"]);
Assert.AreEqual(1, values5["IntValue"]);
Assert.AreEqual("foo", values5["StringValue2"]);
Assert.IsInstanceOf<Class2>(values5["ClassValue2"]);
Assert.AreEqual(1, values5["IntValue2"]);
// test object extensions
Console.WriteLine("Getting object5D values...");
Dictionary<string, object> values5D = ObjectJsonExtensions.ToObjectDictionary(object5);
Console.WriteLine("Writing object5D values...");
foreach ((string name, object value) in values5)
{
Console.WriteLine($"{name}: {value}");
}
Assert.AreEqual(7, values5.Count);
Assert.AreEqual("foo", values5D["StringValue"]);
Assert.IsInstanceOf<Class2>(values5D["ClassValue"]);
Assert.AreEqual(1, values5D["IntValue"]);
Assert.AreEqual("foo", values5D["StringValue2"]);
Assert.IsInstanceOf<Class2>(values5D["ClassValue2"]);
Assert.AreEqual(1, values5D["intValue2"]); // JsonProperty changes property name
}
[Test]
public void EmitFieldGetterSetterEmits()
{
Func<Class1, int> getter1 = ReflectionUtilities.EmitFieldGetter<Class1, int>("Field1");
Func<Class1, int> getter2 = ReflectionUtilities.EmitFieldGetter<Class1, int>("Field2");
var c = new Class1();
Assert.AreEqual(33, getter1(c));
Assert.AreEqual(66, getter2(c));
Action<Class1, int> setter2 = ReflectionUtilities.EmitFieldSetter<Class1, int>("Field2");
setter2(c, 99);
Assert.AreEqual(99, getter2(c));
// works on readonly fields!
(Func<Class1, int> getter3, Action<Class1, int> setter3) = ReflectionUtilities.EmitFieldGetterAndSetter<Class1, int>("Field3");
Assert.AreEqual(22, getter3(c));
setter3(c, 44);
Assert.AreEqual(44, getter3(c));
}
// FIXME: missing tests specifying 'returned' on method, property
[Test]
public void DeconstructAnonymousType()
{
var o = new { a = 1, b = "hello" };
var getters = new Dictionary<string, Func<object, object>>();
foreach (PropertyInfo prop in o.GetType().GetProperties())
{
getters[prop.Name] = ReflectionUtilities.EmitMethodUnsafe<Func<object, object>>(prop.GetMethod);
}
Assert.AreEqual(2, getters.Count);
Assert.IsTrue(getters.ContainsKey("a"));
Assert.IsTrue(getters.ContainsKey("b"));
Assert.AreEqual(1, getters["a"](o));
Assert.AreEqual("hello", getters["b"](o));
}
// these functions can be examined in eg DotPeek to understand IL works
// box [mscorlib]System.Int32
public object GetIntValue(Class4 object4) => object4.IntValue;
// unbox.any [mscorlib]System.Int32
public void SetIntValue(Class4 object4, object i) => object4.IntValue = (int)i;
// castclass [mscorlib]System.String
public void SetStringValue(Class4 object4, object s) => object4.StringValue = (string)s;
// conv.i4
public void SetIntValue(Class4 object4, double d) => object4.IntValue = (int)d;
// unbox.any [mscorlib]System.Double
// conv.i4
public void SetIntValue2(Class4 object4, object d) => object4.IntValue = (int)(double)d;
public void SetIntValue3(Class4 object4, object v)
{
if (v is int i)
{
object4.IntValue = i;
}
else
{
object4.IntValue = Convert.ToInt32(v);
}
}
public void SetIntValue4(Class4 object4, object v)
{
if (v is int i)
{
object4.IntValue = i;
}
else
{
object4.IntValue = (int)Convert.ChangeType(v, typeof(int));
}
}
// get field
public int GetIntField(Class1 object1) => object1.Field1;
// set field
public void SetIntField(Class1 object1, int i) => object1.Field1 = i;
public static class StaticClass1
{
public static void Method()
{
}
}
public class Class1
{
public Class1()
{
}
public Class1(int i)
{
}
public void Method1()
{
}
public void Method2(int i)
{
}
public int Method3() => 42;
public int Method4(string s) => int.Parse(s);
public string Method5() => "foo";
public static void SMethod1()
{
}
public static void SMethod2(int i)
{
}
public static int SMethod3() => 42;
public static int SMethod4(string s) => int.Parse(s);
private void MethodP1()
{
}
private static void SMethodP1()
{
}
public int Value1 => 42;
public int Value2
{
set { }
}
public int Value3
{
get => 42; set { }
}
private int ValueP1 => 42;
public int Field1 = 33;
private int Field2 = 66;
public readonly int Field3 = 22;
}
public class Class2
{
}
public class Class2A : Class2
{
}
public class Class3
{
public Class3(int i)
{
}
private Class3(string s)
{
}
}
public class Class4
{
public int IntValue { get; set; }
public string StringValue { get; set; }
public Class2 ClassValue { get; set; }
public Class2A ClassAValue { get; set; }
}
public class Class5 : Class4
{
[JsonProperty("intValue2")]
public int IntValue2 { get; set; }
public string StringValue2 { get; set; }
public Class2 ClassValue2 { get; set; }
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Speech.V1P1Beta1.Snippets
{
using Google.Api.Gax;
using Google.Api.Gax.ResourceNames;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedAdaptationClientSnippets
{
/// <summary>Snippet for CreatePhraseSet</summary>
public void CreatePhraseSetRequestObject()
{
// Snippet: CreatePhraseSet(CreatePhraseSetRequest, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
CreatePhraseSetRequest request = new CreatePhraseSetRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
PhraseSetId = "",
PhraseSet = new PhraseSet(),
};
// Make the request
PhraseSet response = adaptationClient.CreatePhraseSet(request);
// End snippet
}
/// <summary>Snippet for CreatePhraseSetAsync</summary>
public async Task CreatePhraseSetRequestObjectAsync()
{
// Snippet: CreatePhraseSetAsync(CreatePhraseSetRequest, CallSettings)
// Additional: CreatePhraseSetAsync(CreatePhraseSetRequest, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
CreatePhraseSetRequest request = new CreatePhraseSetRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
PhraseSetId = "",
PhraseSet = new PhraseSet(),
};
// Make the request
PhraseSet response = await adaptationClient.CreatePhraseSetAsync(request);
// End snippet
}
/// <summary>Snippet for CreatePhraseSet</summary>
public void CreatePhraseSet()
{
// Snippet: CreatePhraseSet(string, PhraseSet, string, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
PhraseSet phraseSet = new PhraseSet();
string phraseSetId = "";
// Make the request
PhraseSet response = adaptationClient.CreatePhraseSet(parent, phraseSet, phraseSetId);
// End snippet
}
/// <summary>Snippet for CreatePhraseSetAsync</summary>
public async Task CreatePhraseSetAsync()
{
// Snippet: CreatePhraseSetAsync(string, PhraseSet, string, CallSettings)
// Additional: CreatePhraseSetAsync(string, PhraseSet, string, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
PhraseSet phraseSet = new PhraseSet();
string phraseSetId = "";
// Make the request
PhraseSet response = await adaptationClient.CreatePhraseSetAsync(parent, phraseSet, phraseSetId);
// End snippet
}
/// <summary>Snippet for CreatePhraseSet</summary>
public void CreatePhraseSetResourceNames()
{
// Snippet: CreatePhraseSet(LocationName, PhraseSet, string, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
PhraseSet phraseSet = new PhraseSet();
string phraseSetId = "";
// Make the request
PhraseSet response = adaptationClient.CreatePhraseSet(parent, phraseSet, phraseSetId);
// End snippet
}
/// <summary>Snippet for CreatePhraseSetAsync</summary>
public async Task CreatePhraseSetResourceNamesAsync()
{
// Snippet: CreatePhraseSetAsync(LocationName, PhraseSet, string, CallSettings)
// Additional: CreatePhraseSetAsync(LocationName, PhraseSet, string, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
PhraseSet phraseSet = new PhraseSet();
string phraseSetId = "";
// Make the request
PhraseSet response = await adaptationClient.CreatePhraseSetAsync(parent, phraseSet, phraseSetId);
// End snippet
}
/// <summary>Snippet for GetPhraseSet</summary>
public void GetPhraseSetRequestObject()
{
// Snippet: GetPhraseSet(GetPhraseSetRequest, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
GetPhraseSetRequest request = new GetPhraseSetRequest
{
PhraseSetName = PhraseSetName.FromProjectLocationPhraseSet("[PROJECT]", "[LOCATION]", "[PHRASE_SET]"),
};
// Make the request
PhraseSet response = adaptationClient.GetPhraseSet(request);
// End snippet
}
/// <summary>Snippet for GetPhraseSetAsync</summary>
public async Task GetPhraseSetRequestObjectAsync()
{
// Snippet: GetPhraseSetAsync(GetPhraseSetRequest, CallSettings)
// Additional: GetPhraseSetAsync(GetPhraseSetRequest, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
GetPhraseSetRequest request = new GetPhraseSetRequest
{
PhraseSetName = PhraseSetName.FromProjectLocationPhraseSet("[PROJECT]", "[LOCATION]", "[PHRASE_SET]"),
};
// Make the request
PhraseSet response = await adaptationClient.GetPhraseSetAsync(request);
// End snippet
}
/// <summary>Snippet for GetPhraseSet</summary>
public void GetPhraseSet()
{
// Snippet: GetPhraseSet(string, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/phraseSets/[PHRASE_SET]";
// Make the request
PhraseSet response = adaptationClient.GetPhraseSet(name);
// End snippet
}
/// <summary>Snippet for GetPhraseSetAsync</summary>
public async Task GetPhraseSetAsync()
{
// Snippet: GetPhraseSetAsync(string, CallSettings)
// Additional: GetPhraseSetAsync(string, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/phraseSets/[PHRASE_SET]";
// Make the request
PhraseSet response = await adaptationClient.GetPhraseSetAsync(name);
// End snippet
}
/// <summary>Snippet for GetPhraseSet</summary>
public void GetPhraseSetResourceNames()
{
// Snippet: GetPhraseSet(PhraseSetName, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
PhraseSetName name = PhraseSetName.FromProjectLocationPhraseSet("[PROJECT]", "[LOCATION]", "[PHRASE_SET]");
// Make the request
PhraseSet response = adaptationClient.GetPhraseSet(name);
// End snippet
}
/// <summary>Snippet for GetPhraseSetAsync</summary>
public async Task GetPhraseSetResourceNamesAsync()
{
// Snippet: GetPhraseSetAsync(PhraseSetName, CallSettings)
// Additional: GetPhraseSetAsync(PhraseSetName, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
PhraseSetName name = PhraseSetName.FromProjectLocationPhraseSet("[PROJECT]", "[LOCATION]", "[PHRASE_SET]");
// Make the request
PhraseSet response = await adaptationClient.GetPhraseSetAsync(name);
// End snippet
}
/// <summary>Snippet for ListPhraseSet</summary>
public void ListPhraseSetRequestObject()
{
// Snippet: ListPhraseSet(ListPhraseSetRequest, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
ListPhraseSetRequest request = new ListPhraseSetRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
// Make the request
PagedEnumerable<ListPhraseSetResponse, PhraseSet> response = adaptationClient.ListPhraseSet(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (PhraseSet item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListPhraseSetResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PhraseSet item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PhraseSet> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PhraseSet item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListPhraseSetAsync</summary>
public async Task ListPhraseSetRequestObjectAsync()
{
// Snippet: ListPhraseSetAsync(ListPhraseSetRequest, CallSettings)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
ListPhraseSetRequest request = new ListPhraseSetRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
// Make the request
PagedAsyncEnumerable<ListPhraseSetResponse, PhraseSet> response = adaptationClient.ListPhraseSetAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((PhraseSet item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListPhraseSetResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PhraseSet item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PhraseSet> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PhraseSet item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListPhraseSet</summary>
public void ListPhraseSet()
{
// Snippet: ListPhraseSet(string, string, int?, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
// Make the request
PagedEnumerable<ListPhraseSetResponse, PhraseSet> response = adaptationClient.ListPhraseSet(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (PhraseSet item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListPhraseSetResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PhraseSet item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PhraseSet> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PhraseSet item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListPhraseSetAsync</summary>
public async Task ListPhraseSetAsync()
{
// Snippet: ListPhraseSetAsync(string, string, int?, CallSettings)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
// Make the request
PagedAsyncEnumerable<ListPhraseSetResponse, PhraseSet> response = adaptationClient.ListPhraseSetAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((PhraseSet item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListPhraseSetResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PhraseSet item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PhraseSet> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PhraseSet item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListPhraseSet</summary>
public void ListPhraseSetResourceNames()
{
// Snippet: ListPhraseSet(LocationName, string, int?, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
// Make the request
PagedEnumerable<ListPhraseSetResponse, PhraseSet> response = adaptationClient.ListPhraseSet(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (PhraseSet item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListPhraseSetResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PhraseSet item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PhraseSet> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PhraseSet item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListPhraseSetAsync</summary>
public async Task ListPhraseSetResourceNamesAsync()
{
// Snippet: ListPhraseSetAsync(LocationName, string, int?, CallSettings)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
// Make the request
PagedAsyncEnumerable<ListPhraseSetResponse, PhraseSet> response = adaptationClient.ListPhraseSetAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((PhraseSet item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListPhraseSetResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PhraseSet item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PhraseSet> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PhraseSet item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for UpdatePhraseSet</summary>
public void UpdatePhraseSetRequestObject()
{
// Snippet: UpdatePhraseSet(UpdatePhraseSetRequest, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
UpdatePhraseSetRequest request = new UpdatePhraseSetRequest
{
PhraseSet = new PhraseSet(),
UpdateMask = new FieldMask(),
};
// Make the request
PhraseSet response = adaptationClient.UpdatePhraseSet(request);
// End snippet
}
/// <summary>Snippet for UpdatePhraseSetAsync</summary>
public async Task UpdatePhraseSetRequestObjectAsync()
{
// Snippet: UpdatePhraseSetAsync(UpdatePhraseSetRequest, CallSettings)
// Additional: UpdatePhraseSetAsync(UpdatePhraseSetRequest, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
UpdatePhraseSetRequest request = new UpdatePhraseSetRequest
{
PhraseSet = new PhraseSet(),
UpdateMask = new FieldMask(),
};
// Make the request
PhraseSet response = await adaptationClient.UpdatePhraseSetAsync(request);
// End snippet
}
/// <summary>Snippet for UpdatePhraseSet</summary>
public void UpdatePhraseSet()
{
// Snippet: UpdatePhraseSet(PhraseSet, FieldMask, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
PhraseSet phraseSet = new PhraseSet();
FieldMask updateMask = new FieldMask();
// Make the request
PhraseSet response = adaptationClient.UpdatePhraseSet(phraseSet, updateMask);
// End snippet
}
/// <summary>Snippet for UpdatePhraseSetAsync</summary>
public async Task UpdatePhraseSetAsync()
{
// Snippet: UpdatePhraseSetAsync(PhraseSet, FieldMask, CallSettings)
// Additional: UpdatePhraseSetAsync(PhraseSet, FieldMask, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
PhraseSet phraseSet = new PhraseSet();
FieldMask updateMask = new FieldMask();
// Make the request
PhraseSet response = await adaptationClient.UpdatePhraseSetAsync(phraseSet, updateMask);
// End snippet
}
/// <summary>Snippet for DeletePhraseSet</summary>
public void DeletePhraseSetRequestObject()
{
// Snippet: DeletePhraseSet(DeletePhraseSetRequest, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
DeletePhraseSetRequest request = new DeletePhraseSetRequest
{
PhraseSetName = PhraseSetName.FromProjectLocationPhraseSet("[PROJECT]", "[LOCATION]", "[PHRASE_SET]"),
};
// Make the request
adaptationClient.DeletePhraseSet(request);
// End snippet
}
/// <summary>Snippet for DeletePhraseSetAsync</summary>
public async Task DeletePhraseSetRequestObjectAsync()
{
// Snippet: DeletePhraseSetAsync(DeletePhraseSetRequest, CallSettings)
// Additional: DeletePhraseSetAsync(DeletePhraseSetRequest, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
DeletePhraseSetRequest request = new DeletePhraseSetRequest
{
PhraseSetName = PhraseSetName.FromProjectLocationPhraseSet("[PROJECT]", "[LOCATION]", "[PHRASE_SET]"),
};
// Make the request
await adaptationClient.DeletePhraseSetAsync(request);
// End snippet
}
/// <summary>Snippet for DeletePhraseSet</summary>
public void DeletePhraseSet()
{
// Snippet: DeletePhraseSet(string, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/phraseSets/[PHRASE_SET]";
// Make the request
adaptationClient.DeletePhraseSet(name);
// End snippet
}
/// <summary>Snippet for DeletePhraseSetAsync</summary>
public async Task DeletePhraseSetAsync()
{
// Snippet: DeletePhraseSetAsync(string, CallSettings)
// Additional: DeletePhraseSetAsync(string, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/phraseSets/[PHRASE_SET]";
// Make the request
await adaptationClient.DeletePhraseSetAsync(name);
// End snippet
}
/// <summary>Snippet for DeletePhraseSet</summary>
public void DeletePhraseSetResourceNames()
{
// Snippet: DeletePhraseSet(PhraseSetName, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
PhraseSetName name = PhraseSetName.FromProjectLocationPhraseSet("[PROJECT]", "[LOCATION]", "[PHRASE_SET]");
// Make the request
adaptationClient.DeletePhraseSet(name);
// End snippet
}
/// <summary>Snippet for DeletePhraseSetAsync</summary>
public async Task DeletePhraseSetResourceNamesAsync()
{
// Snippet: DeletePhraseSetAsync(PhraseSetName, CallSettings)
// Additional: DeletePhraseSetAsync(PhraseSetName, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
PhraseSetName name = PhraseSetName.FromProjectLocationPhraseSet("[PROJECT]", "[LOCATION]", "[PHRASE_SET]");
// Make the request
await adaptationClient.DeletePhraseSetAsync(name);
// End snippet
}
/// <summary>Snippet for CreateCustomClass</summary>
public void CreateCustomClassRequestObject()
{
// Snippet: CreateCustomClass(CreateCustomClassRequest, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
CreateCustomClassRequest request = new CreateCustomClassRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
CustomClassId = "",
CustomClass = new CustomClass(),
};
// Make the request
CustomClass response = adaptationClient.CreateCustomClass(request);
// End snippet
}
/// <summary>Snippet for CreateCustomClassAsync</summary>
public async Task CreateCustomClassRequestObjectAsync()
{
// Snippet: CreateCustomClassAsync(CreateCustomClassRequest, CallSettings)
// Additional: CreateCustomClassAsync(CreateCustomClassRequest, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
CreateCustomClassRequest request = new CreateCustomClassRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
CustomClassId = "",
CustomClass = new CustomClass(),
};
// Make the request
CustomClass response = await adaptationClient.CreateCustomClassAsync(request);
// End snippet
}
/// <summary>Snippet for CreateCustomClass</summary>
public void CreateCustomClass()
{
// Snippet: CreateCustomClass(string, CustomClass, string, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
CustomClass customClass = new CustomClass();
string customClassId = "";
// Make the request
CustomClass response = adaptationClient.CreateCustomClass(parent, customClass, customClassId);
// End snippet
}
/// <summary>Snippet for CreateCustomClassAsync</summary>
public async Task CreateCustomClassAsync()
{
// Snippet: CreateCustomClassAsync(string, CustomClass, string, CallSettings)
// Additional: CreateCustomClassAsync(string, CustomClass, string, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
CustomClass customClass = new CustomClass();
string customClassId = "";
// Make the request
CustomClass response = await adaptationClient.CreateCustomClassAsync(parent, customClass, customClassId);
// End snippet
}
/// <summary>Snippet for CreateCustomClass</summary>
public void CreateCustomClassResourceNames()
{
// Snippet: CreateCustomClass(LocationName, CustomClass, string, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
CustomClass customClass = new CustomClass();
string customClassId = "";
// Make the request
CustomClass response = adaptationClient.CreateCustomClass(parent, customClass, customClassId);
// End snippet
}
/// <summary>Snippet for CreateCustomClassAsync</summary>
public async Task CreateCustomClassResourceNamesAsync()
{
// Snippet: CreateCustomClassAsync(LocationName, CustomClass, string, CallSettings)
// Additional: CreateCustomClassAsync(LocationName, CustomClass, string, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
CustomClass customClass = new CustomClass();
string customClassId = "";
// Make the request
CustomClass response = await adaptationClient.CreateCustomClassAsync(parent, customClass, customClassId);
// End snippet
}
/// <summary>Snippet for GetCustomClass</summary>
public void GetCustomClassRequestObject()
{
// Snippet: GetCustomClass(GetCustomClassRequest, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
GetCustomClassRequest request = new GetCustomClassRequest
{
CustomClassName = CustomClassName.FromProjectLocationCustomClass("[PROJECT]", "[LOCATION]", "[CUSTOM_CLASS]"),
};
// Make the request
CustomClass response = adaptationClient.GetCustomClass(request);
// End snippet
}
/// <summary>Snippet for GetCustomClassAsync</summary>
public async Task GetCustomClassRequestObjectAsync()
{
// Snippet: GetCustomClassAsync(GetCustomClassRequest, CallSettings)
// Additional: GetCustomClassAsync(GetCustomClassRequest, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
GetCustomClassRequest request = new GetCustomClassRequest
{
CustomClassName = CustomClassName.FromProjectLocationCustomClass("[PROJECT]", "[LOCATION]", "[CUSTOM_CLASS]"),
};
// Make the request
CustomClass response = await adaptationClient.GetCustomClassAsync(request);
// End snippet
}
/// <summary>Snippet for GetCustomClass</summary>
public void GetCustomClass()
{
// Snippet: GetCustomClass(string, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/customClasses/[CUSTOM_CLASS]";
// Make the request
CustomClass response = adaptationClient.GetCustomClass(name);
// End snippet
}
/// <summary>Snippet for GetCustomClassAsync</summary>
public async Task GetCustomClassAsync()
{
// Snippet: GetCustomClassAsync(string, CallSettings)
// Additional: GetCustomClassAsync(string, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/customClasses/[CUSTOM_CLASS]";
// Make the request
CustomClass response = await adaptationClient.GetCustomClassAsync(name);
// End snippet
}
/// <summary>Snippet for GetCustomClass</summary>
public void GetCustomClassResourceNames()
{
// Snippet: GetCustomClass(CustomClassName, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
CustomClassName name = CustomClassName.FromProjectLocationCustomClass("[PROJECT]", "[LOCATION]", "[CUSTOM_CLASS]");
// Make the request
CustomClass response = adaptationClient.GetCustomClass(name);
// End snippet
}
/// <summary>Snippet for GetCustomClassAsync</summary>
public async Task GetCustomClassResourceNamesAsync()
{
// Snippet: GetCustomClassAsync(CustomClassName, CallSettings)
// Additional: GetCustomClassAsync(CustomClassName, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
CustomClassName name = CustomClassName.FromProjectLocationCustomClass("[PROJECT]", "[LOCATION]", "[CUSTOM_CLASS]");
// Make the request
CustomClass response = await adaptationClient.GetCustomClassAsync(name);
// End snippet
}
/// <summary>Snippet for ListCustomClasses</summary>
public void ListCustomClassesRequestObject()
{
// Snippet: ListCustomClasses(ListCustomClassesRequest, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
ListCustomClassesRequest request = new ListCustomClassesRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
// Make the request
PagedEnumerable<ListCustomClassesResponse, CustomClass> response = adaptationClient.ListCustomClasses(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (CustomClass item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListCustomClassesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (CustomClass item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<CustomClass> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (CustomClass item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListCustomClassesAsync</summary>
public async Task ListCustomClassesRequestObjectAsync()
{
// Snippet: ListCustomClassesAsync(ListCustomClassesRequest, CallSettings)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
ListCustomClassesRequest request = new ListCustomClassesRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
// Make the request
PagedAsyncEnumerable<ListCustomClassesResponse, CustomClass> response = adaptationClient.ListCustomClassesAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((CustomClass item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListCustomClassesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (CustomClass item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<CustomClass> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (CustomClass item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListCustomClasses</summary>
public void ListCustomClasses()
{
// Snippet: ListCustomClasses(string, string, int?, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
// Make the request
PagedEnumerable<ListCustomClassesResponse, CustomClass> response = adaptationClient.ListCustomClasses(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (CustomClass item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListCustomClassesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (CustomClass item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<CustomClass> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (CustomClass item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListCustomClassesAsync</summary>
public async Task ListCustomClassesAsync()
{
// Snippet: ListCustomClassesAsync(string, string, int?, CallSettings)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
// Make the request
PagedAsyncEnumerable<ListCustomClassesResponse, CustomClass> response = adaptationClient.ListCustomClassesAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((CustomClass item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListCustomClassesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (CustomClass item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<CustomClass> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (CustomClass item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListCustomClasses</summary>
public void ListCustomClassesResourceNames()
{
// Snippet: ListCustomClasses(LocationName, string, int?, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
// Make the request
PagedEnumerable<ListCustomClassesResponse, CustomClass> response = adaptationClient.ListCustomClasses(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (CustomClass item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListCustomClassesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (CustomClass item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<CustomClass> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (CustomClass item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListCustomClassesAsync</summary>
public async Task ListCustomClassesResourceNamesAsync()
{
// Snippet: ListCustomClassesAsync(LocationName, string, int?, CallSettings)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
// Make the request
PagedAsyncEnumerable<ListCustomClassesResponse, CustomClass> response = adaptationClient.ListCustomClassesAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((CustomClass item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListCustomClassesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (CustomClass item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<CustomClass> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (CustomClass item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for UpdateCustomClass</summary>
public void UpdateCustomClassRequestObject()
{
// Snippet: UpdateCustomClass(UpdateCustomClassRequest, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
UpdateCustomClassRequest request = new UpdateCustomClassRequest
{
CustomClass = new CustomClass(),
UpdateMask = new FieldMask(),
};
// Make the request
CustomClass response = adaptationClient.UpdateCustomClass(request);
// End snippet
}
/// <summary>Snippet for UpdateCustomClassAsync</summary>
public async Task UpdateCustomClassRequestObjectAsync()
{
// Snippet: UpdateCustomClassAsync(UpdateCustomClassRequest, CallSettings)
// Additional: UpdateCustomClassAsync(UpdateCustomClassRequest, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
UpdateCustomClassRequest request = new UpdateCustomClassRequest
{
CustomClass = new CustomClass(),
UpdateMask = new FieldMask(),
};
// Make the request
CustomClass response = await adaptationClient.UpdateCustomClassAsync(request);
// End snippet
}
/// <summary>Snippet for UpdateCustomClass</summary>
public void UpdateCustomClass()
{
// Snippet: UpdateCustomClass(CustomClass, FieldMask, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
CustomClass customClass = new CustomClass();
FieldMask updateMask = new FieldMask();
// Make the request
CustomClass response = adaptationClient.UpdateCustomClass(customClass, updateMask);
// End snippet
}
/// <summary>Snippet for UpdateCustomClassAsync</summary>
public async Task UpdateCustomClassAsync()
{
// Snippet: UpdateCustomClassAsync(CustomClass, FieldMask, CallSettings)
// Additional: UpdateCustomClassAsync(CustomClass, FieldMask, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
CustomClass customClass = new CustomClass();
FieldMask updateMask = new FieldMask();
// Make the request
CustomClass response = await adaptationClient.UpdateCustomClassAsync(customClass, updateMask);
// End snippet
}
/// <summary>Snippet for DeleteCustomClass</summary>
public void DeleteCustomClassRequestObject()
{
// Snippet: DeleteCustomClass(DeleteCustomClassRequest, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
DeleteCustomClassRequest request = new DeleteCustomClassRequest
{
CustomClassName = CustomClassName.FromProjectLocationCustomClass("[PROJECT]", "[LOCATION]", "[CUSTOM_CLASS]"),
};
// Make the request
adaptationClient.DeleteCustomClass(request);
// End snippet
}
/// <summary>Snippet for DeleteCustomClassAsync</summary>
public async Task DeleteCustomClassRequestObjectAsync()
{
// Snippet: DeleteCustomClassAsync(DeleteCustomClassRequest, CallSettings)
// Additional: DeleteCustomClassAsync(DeleteCustomClassRequest, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
DeleteCustomClassRequest request = new DeleteCustomClassRequest
{
CustomClassName = CustomClassName.FromProjectLocationCustomClass("[PROJECT]", "[LOCATION]", "[CUSTOM_CLASS]"),
};
// Make the request
await adaptationClient.DeleteCustomClassAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteCustomClass</summary>
public void DeleteCustomClass()
{
// Snippet: DeleteCustomClass(string, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/customClasses/[CUSTOM_CLASS]";
// Make the request
adaptationClient.DeleteCustomClass(name);
// End snippet
}
/// <summary>Snippet for DeleteCustomClassAsync</summary>
public async Task DeleteCustomClassAsync()
{
// Snippet: DeleteCustomClassAsync(string, CallSettings)
// Additional: DeleteCustomClassAsync(string, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/customClasses/[CUSTOM_CLASS]";
// Make the request
await adaptationClient.DeleteCustomClassAsync(name);
// End snippet
}
/// <summary>Snippet for DeleteCustomClass</summary>
public void DeleteCustomClassResourceNames()
{
// Snippet: DeleteCustomClass(CustomClassName, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
CustomClassName name = CustomClassName.FromProjectLocationCustomClass("[PROJECT]", "[LOCATION]", "[CUSTOM_CLASS]");
// Make the request
adaptationClient.DeleteCustomClass(name);
// End snippet
}
/// <summary>Snippet for DeleteCustomClassAsync</summary>
public async Task DeleteCustomClassResourceNamesAsync()
{
// Snippet: DeleteCustomClassAsync(CustomClassName, CallSettings)
// Additional: DeleteCustomClassAsync(CustomClassName, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
CustomClassName name = CustomClassName.FromProjectLocationCustomClass("[PROJECT]", "[LOCATION]", "[CUSTOM_CLASS]");
// Make the request
await adaptationClient.DeleteCustomClassAsync(name);
// End snippet
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Marten.Schema.Testing.Documents;
using Marten.Services;
using Shouldly;
using Xunit;
using Xunit.Abstractions;
namespace Marten.Schema.Testing.Hierarchies
{
public class delete_by_where_for_hierarchy_Tests: end_to_end_document_hierarchy_usage_Tests
{
private readonly ITestOutputHelper _output;
public delete_by_where_for_hierarchy_Tests(ITestOutputHelper output)
{
_output = output;
DocumentTracking = DocumentTracking.None;
}
[Fact]
public void can_delete_all_subclass()
{
loadData();
theSession.DeleteWhere<SuperUser>(x => true);
theSession.SaveChanges();
theSession.Query<SuperUser>().Count().ShouldBe(0);
theSession.Query<AdminUser>().Count().ShouldBe(2);
theSession.Query<User>().Count().ShouldBe(4);
}
[Fact]
public void can_delete_by_subclass()
{
loadData();
theSession.DeleteWhere<SuperUser>(x => x.FirstName.StartsWith("D"));
theSession.SaveChanges();
theSession.Query<SuperUser>().Count().ShouldBe(1);
theSession.Query<AdminUser>().Count().ShouldBe(2);
theSession.Query<User>().Count().ShouldBe(5);
}
[Fact]
public void can_delete_by_the_hierarchy()
{
loadData();
theSession.DeleteWhere<User>(x => x.FirstName.StartsWith("D"));
theSession.SaveChanges();
// Should delete one SuperUser and one AdminUser
theSession.Query<SuperUser>().Count().ShouldBe(1);
theSession.Query<AdminUser>().Count().ShouldBe(1);
theSession.Query<User>().Count().ShouldBe(4);
}
}
public class persist_and_load_for_hierarchy_Tests: end_to_end_document_hierarchy_usage_Tests
{
public persist_and_load_for_hierarchy_Tests()
{
DocumentTracking = DocumentTracking.IdentityOnly;
}
[Fact]
public void persist_and_delete_subclass()
{
theSession.Store(admin1);
theSession.SaveChanges();
theSession.Delete(admin1);
theSession.SaveChanges();
theSession.Load<User>(admin1.Id).ShouldBeNull();
theSession.Load<AdminUser>(admin1.Id).ShouldBeNull();
}
[Fact]
public void persist_and_delete_subclass_2()
{
theSession.Logger = new TestOutputMartenLogger(_output);
theSession.Store(admin1);
theSession.SaveChanges();
theSession.Delete<AdminUser>(admin1.Id);
theSession.SaveChanges();
theSession.Load<User>(admin1.Id).ShouldBeNull();
theSession.Load<AdminUser>(admin1.Id).ShouldBeNull();
}
[Fact]
public void persist_and_delete_top()
{
theSession.Store(user1);
theSession.SaveChanges();
theSession.Delete<User>(user1.Id);
theSession.SaveChanges();
theSession.Load<User>(user1.Id).ShouldBeNull();
}
[Fact]
public void persist_and_delete_top_2()
{
theSession.Store(user1);
theSession.SaveChanges();
theSession.Delete(user1);
theSession.SaveChanges();
theSession.Load<User>(user1.Id).ShouldBeNull();
}
[Fact]
public void persist_and_load_subclass()
{
theSession.Store(admin1);
theSession.SaveChanges();
theSession.Load<User>(admin1.Id).ShouldBeTheSameAs(admin1);
theSession.Load<AdminUser>(admin1.Id).ShouldBeTheSameAs(admin1);
using (var session = theStore.QuerySession())
{
session.Load<AdminUser>(admin1.Id).ShouldNotBeTheSameAs(admin1).ShouldNotBeNull();
session.Load<User>(admin1.Id).ShouldNotBeTheSameAs(admin1).ShouldNotBeNull();
}
}
[Fact]
public async Task persist_and_load_subclass_async()
{
theSession.Store(admin1);
theSession.SaveChanges();
(await theSession.LoadAsync<User>(admin1.Id).ConfigureAwait(false)).ShouldBeTheSameAs(admin1);
(await theSession.LoadAsync<AdminUser>(admin1.Id).ConfigureAwait(false)).ShouldBeTheSameAs(admin1);
using (var session = theStore.QuerySession())
{
(await session.LoadAsync<AdminUser>(admin1.Id).ConfigureAwait(false)).ShouldNotBeTheSameAs(admin1)
.ShouldNotBeNull();
(await session.LoadAsync<User>(admin1.Id).ConfigureAwait(false)).ShouldNotBeTheSameAs(admin1)
.ShouldNotBeNull();
}
}
[Fact]
public void persist_and_load_top_level()
{
theSession.Store(user1);
theSession.SaveChanges();
theSession.Load<User>(user1.Id).ShouldBeTheSameAs(user1);
using (var session = theStore.QuerySession())
{
session.Load<User>(user1.Id).ShouldNotBeTheSameAs(user1).ShouldNotBeNull();
}
}
}
public class query_through_mixed_population_Tests: end_to_end_document_hierarchy_usage_Tests
{
public query_through_mixed_population_Tests()
{
DocumentTracking = DocumentTracking.IdentityOnly;
loadData();
}
[Fact]
public void clean_by_subclass_only_deletes_the_one_subclass()
{
theStore.Advanced.Clean.DeleteDocumentsFor(typeof(AdminUser));
theSession.Query<User>().Any().ShouldBeTrue();
theSession.Query<SuperUser>().Any().ShouldBeTrue();
theSession.Query<AdminUser>().Any().ShouldBeFalse();
}
[Fact]
public void identity_map_usage_from_select()
{
var users = theSession.Query<User>().OrderBy(x => x.FirstName).ToArray();
users[0].ShouldBeTheSameAs(admin1);
users[1].ShouldBeTheSameAs(super1);
users[5].ShouldBeTheSameAs(user2);
}
[Fact]
public void load_by_id_keys_from_base_class_clean()
{
using (var session = theStore.QuerySession())
{
session.LoadMany<AdminUser>(admin1.Id, admin2.Id)
.Select(x => x.Id)
.ShouldHaveTheSameElementsAs(admin1.Id, admin2.Id);
}
}
[Fact]
public void load_by_id_keys_from_base_class_resolved_from_identity_map()
{
theSession.LoadMany<AdminUser>(admin1.Id, admin2.Id)
.ShouldHaveTheSameElementsAs(admin1, admin2);
}
[Fact]
public async Task load_by_id_keys_from_base_class_resolved_from_identity_map_async()
{
var users = await theSession.LoadManyAsync<AdminUser>(admin1.Id, admin2.Id).ConfigureAwait(false);
users.ShouldHaveTheSameElementsAs(admin1, admin2);
}
[Fact]
public void load_by_id_with_mixed_results_fresh()
{
using (var session = theStore.QuerySession())
{
session.LoadMany<User>(admin1.Id, super1.Id, user1.Id)
.ToArray()
.OrderBy(x => x.FirstName)
.Select(x => x.Id)
.ShouldHaveTheSameElementsAs(admin1.Id, super1.Id, user1.Id);
}
}
[Fact]
public async Task load_by_id_with_mixed_results_fresh_async()
{
using (var session = theStore.QuerySession())
{
var users = await session.LoadManyAsync<User>(admin1.Id, super1.Id, user1.Id).ConfigureAwait(false);
users.OrderBy(x => x.FirstName)
.Select(x => x.Id)
.ShouldHaveTheSameElementsAs(admin1.Id, super1.Id, user1.Id);
}
}
[Fact]
public void load_by_id_with_mixed_results_from_identity_map()
{
theSession.LoadMany<User>(admin1.Id, super1.Id, user1.Id)
.ToArray().ShouldHaveTheSameElementsAs(admin1, super1, user1);
}
[Fact]
public async Task load_by_id_with_mixed_results_from_identity_map_async()
{
var users = await theSession.LoadManyAsync<User>(admin1.Id, super1.Id, user1.Id).ConfigureAwait(false);
users.OrderBy(x => x.FirstName).ShouldHaveTheSameElementsAs(admin1, super1, user1);
}
[Fact]
public void query_against_all_with_no_where()
{
var users = theSession.Query<User>().OrderBy(x => x.FirstName).ToArray();
users
.Select(x => x.Id)
.ShouldHaveTheSameElementsAs(admin1.Id, super1.Id, admin2.Id, user1.Id, super2.Id, user2.Id);
users.Select(x => x.GetType())
.ShouldHaveTheSameElementsAs(typeof(AdminUser), typeof(SuperUser), typeof(AdminUser), typeof(User),
typeof(SuperUser), typeof(User));
}
[Fact]
public void query_against_all_with_where_clause()
{
theSession.Query<User>().OrderBy(x => x.FirstName).Where(x => x.UserName.StartsWith("A"))
.ToArray().Select(x => x.Id)
.ShouldHaveTheSameElementsAs(admin1.Id, super1.Id, user1.Id);
}
[Fact]
public void query_for_only_a_subclass_with_no_where_clause()
{
theSession.Query<AdminUser>().OrderBy(x => x.FirstName).ToArray()
.Select(x => x.Id).ShouldHaveTheSameElementsAs(admin1.Id, admin2.Id);
}
[Fact]
public void query_for_only_a_subclass_with_where_clause()
{
theSession.Query<AdminUser>().Where(x => x.FirstName == "Eric").Single()
.Id.ShouldBe(admin2.Id);
}
}
public class query_through_mixed_population_Tests_tenanted: IntegrationContext
{
public query_through_mixed_population_Tests_tenanted(ITestOutputHelper output) : base(output)
{
EnableCommandLogging = true;
StoreOptions(
_ =>
{
_.Policies.AllDocumentsAreMultiTenanted();
_.Schema.For<User>().AddSubClass<SuperUser>().AddSubClass<AdminUser>().Duplicate(x => x.UserName);
});
loadData();
}
private void loadData()
{
using (var session = theStore.OpenSession("tenant_1"))
{
session.Store(new User(), new AdminUser());
session.SaveChanges();
}
}
[Fact]
public void query_tenanted_data_with_any_tenant_predicate()
{
using (var session = theStore.OpenSession())
{
var users = session.Query<AdminUser>().Where(u => u.AnyTenant()).ToArray();
users.Length.ShouldBeGreaterThan(0);
}
}
}
public class Bug_1247_end_to_end_query_with_include_and_document_hierarchy_Tests: end_to_end_document_hierarchy_usage_Tests
{
private readonly ITestOutputHelper _output;
public Bug_1247_end_to_end_query_with_include_and_document_hierarchy_Tests(ITestOutputHelper output)
{
_output = output;
DocumentTracking = DocumentTracking.IdentityOnly;
}
[Fact]
public void include_to_list_using_outer_join()
{
var user1 = new User();
var user2 = new User();
var issue1 = new Issue { AssigneeId = user1.Id, Title = "Garage Door is busted1" };
var issue2 = new Issue { AssigneeId = user2.Id, Title = "Garage Door is busted2" };
var issue3 = new Issue { AssigneeId = user2.Id, Title = "Garage Door is busted3" };
var issue4 = new Issue { AssigneeId = null, Title = "Garage Door is busted4" };
theSession.Store(user1, user2);
theSession.Store(issue1, issue2, issue3, issue4);
theSession.SaveChanges();
using (var query = theStore.QuerySession())
{
query.Logger = new TestOutputMartenLogger(_output);
var list = new List<User>();
var issues = query.Query<Issue>().Include<User>(x => x.AssigneeId, list).ToArray();
list.Count.ShouldBe(2);
list.Any(x => x.Id == user1.Id).ShouldBeTrue();
list.Any(x => x.Id == user2.Id).ShouldBeTrue();
issues.Length.ShouldBe(4);
}
}
[Fact]
public async Task include_to_list_using_outer_join_async()
{
var user1 = new User();
var user2 = new User();
var issue1 = new Issue { AssigneeId = user1.Id, Title = "Garage Door is busted1" };
var issue2 = new Issue { AssigneeId = user2.Id, Title = "Garage Door is busted2" };
var issue3 = new Issue { AssigneeId = user2.Id, Title = "Garage Door is busted3" };
var issue4 = new Issue { AssigneeId = null, Title = "Garage Door is busted4" };
theSession.Store(user1, user2);
theSession.Store(issue1, issue2, issue3, issue4);
theSession.SaveChanges();
using (var query = theStore.QuerySession())
{
var list = new List<User>();
var issues = await query.Query<Issue>().Include<User>(x => x.AssigneeId, list).ToListAsync();
list.Count.ShouldBe(2);
list.Any(x => x.Id == user1.Id).ShouldBeTrue();
list.Any(x => x.Id == user2.Id).ShouldBeTrue();
issues.Count.ShouldBe(4);
}
}
}
public class Bug_1484_store_overloads_Tests: end_to_end_document_hierarchy_usage_Tests
{
public Bug_1484_store_overloads_Tests()
{
DocumentTracking = DocumentTracking.IdentityOnly;
}
[Fact]
public void persist_and_count_single_entity()
{
theSession.Store(admin1);
theSession.SaveChanges();
theSession.Query<AdminUser>().Count().ShouldBe(1);
}
[Fact]
public void persist_mutliple_entites_as_params_and_count()
{
theSession.Store(admin1, admin2);
theSession.SaveChanges();
theSession.Query<AdminUser>().Count().ShouldBe(2);
}
[Fact]
public void persist_mutliple_entites_as_array_and_count()
{
theSession.Store(new[] { admin1, admin2 });
theSession.SaveChanges();
theSession.Query<AdminUser>().Count().ShouldBe(2);
}
[Fact]
public void persist_mutliple_entites_as_enumerable_and_count()
{
theSession.Store(new[] { admin1, admin2 }.AsEnumerable());
theSession.SaveChanges();
theSession.Query<AdminUser>().Count().ShouldBe(2);
}
}
public class end_to_end_document_hierarchy_usage_Tests: IntegrationContext
{
protected AdminUser admin1 = new AdminUser
{
UserName = "A2", FirstName = "Derrick", LastName = "Johnson", Region = "Midwest"
};
protected AdminUser admin2 = new AdminUser
{
UserName = "B2", FirstName = "Eric", LastName = "Berry", Region = "West Coast"
};
protected SuperUser super1 = new SuperUser
{
UserName = "A3", FirstName = "Dontari", LastName = "Poe", Role = "Expert"
};
protected SuperUser super2 = new SuperUser
{
UserName = "B3", FirstName = "Sean", LastName = "Smith", Role = "Master"
};
protected User user1 = new User {UserName = "A1", FirstName = "Justin", LastName = "Houston"};
protected User user2 = new User {UserName = "B1", FirstName = "Tamba", LastName = "Hali"};
protected end_to_end_document_hierarchy_usage_Tests()
{
StoreOptions(
_ =>
{
_.Schema.For<User>().AddSubClass<SuperUser>().AddSubClass<AdminUser>().Duplicate(x => x.UserName);
});
}
protected void loadData()
{
theSession.Store(user1, user2, admin1, admin2, super1, super2);
theSession.SaveChanges();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
#if USE_MDT_EVENTSOURCE
using Microsoft.Diagnostics.Tracing;
#else
using System.Diagnostics.Tracing;
#endif
using Xunit;
using System.Diagnostics;
namespace BasicEventSourceTests
{
internal enum Color { Red, Blue, Green };
internal enum ColorUInt32 : uint { Red, Blue, Green };
internal enum ColorByte : byte { Red, Blue, Green };
internal enum ColorSByte : sbyte { Red, Blue, Green };
internal enum ColorInt16 : short { Red, Blue, Green };
internal enum ColorUInt16 : ushort { Red, Blue, Green };
internal enum ColorInt64 : long { Red, Blue, Green };
internal enum ColorUInt64 : ulong { Red, Blue, Green };
public partial class TestsWrite
{
[EventData]
private struct PartB_UserInfo
{
public string UserName { get; set; }
}
/// <summary>
/// Tests the EventSource.Write[T] method (can only use the self-describing mechanism).
/// Tests the EventListener code path
/// </summary>
[Fact]
[ActiveIssue("dotnet/corefx #19455", TargetFrameworkMonikers.NetFramework)]
public void Test_Write_T_EventListener()
{
using (var listener = new EventListenerListener())
{
Test_Write_T(listener);
}
}
/// <summary>
/// Tests the EventSource.Write[T] method (can only use the self-describing mechanism).
/// Tests the EventListener code path using events instead of virtual callbacks.
/// </summary>
[Fact]
[ActiveIssue("dotnet/corefx #19455", TargetFrameworkMonikers.NetFramework)]
public void Test_Write_T_EventListener_UseEvents()
{
Test_Write_T(new EventListenerListener(true));
}
/// <summary>
/// Te
/// </summary>
/// <param name="listener"></param>
private void Test_Write_T(Listener listener)
{
TestUtilities.CheckNoEventSourcesRunning("Start");
using (var logger = new EventSource("EventSourceName"))
{
var tests = new List<SubTest>();
/*************************************************************************/
tests.Add(new SubTest("Write/Basic/String",
delegate ()
{
logger.Write("Greeting", new { msg = "Hello, world!" });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("Greeting", evt.EventName);
Assert.Equal("Hello, world!", evt.PayloadValue(0, "msg"));
}));
/*************************************************************************/
decimal myMoney = 300;
tests.Add(new SubTest("Write/Basic/decimal",
delegate ()
{
logger.Write("Decimal", new { money = myMoney });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("Decimal", evt.EventName);
var eventMoney = evt.PayloadValue(0, "money");
// TOD FIX ME - Fix TraceEvent to return decimal instead of double.
//Assert.Equal((decimal)eventMoney, (decimal)300);
}));
/*************************************************************************/
DateTime now = DateTime.Now;
tests.Add(new SubTest("Write/Basic/DateTime",
delegate ()
{
logger.Write("DateTime", new { nowTime = now });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("DateTime", evt.EventName);
var eventNow = evt.PayloadValue(0, "nowTime");
Assert.Equal(eventNow, now);
}));
/*************************************************************************/
byte[] byteArray = { 0, 1, 2, 3 };
tests.Add(new SubTest("Write/Basic/byte[]",
delegate ()
{
logger.Write("Bytes", new { bytes = byteArray });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("Bytes", evt.EventName);
var eventArray = evt.PayloadValue(0, "bytes");
Array.Equals(eventArray, byteArray);
}));
/*************************************************************************/
int? nullableInt = 12;
tests.Add(new SubTest("Write/Basic/int?/12",
delegate ()
{
logger.Write("Int12", new { nInteger = nullableInt });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("Int12", evt.EventName);
var payload = evt.PayloadValue(0, "nInteger");
Assert.Equal(nullableInt, TestUtilities.UnwrapNullable<int>(payload));
}));
/*************************************************************************/
int? nullableInt2 = null;
tests.Add(new SubTest("Write/Basic/int?/null",
delegate ()
{
logger.Write("IntNull", new { nInteger = nullableInt2 });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("IntNull", evt.EventName);
var payload = evt.PayloadValue(0, "nInteger");
Assert.Equal(nullableInt2, TestUtilities.UnwrapNullable<int>(payload));
}));
///*************************************************************************/
DateTime? nullableDate = DateTime.Now;
tests.Add(new SubTest("Write/Basic/DateTime?/Now",
delegate ()
{
logger.Write("DateTimeNow", new { nowTime = nullableDate });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("DateTimeNow", evt.EventName);
var payload = evt.PayloadValue(0, "nowTime");
Assert.Equal(nullableDate, TestUtilities.UnwrapNullable<DateTime>(payload));
}));
/*************************************************************************/
DateTime? nullableDate2 = null;
tests.Add(new SubTest("Write/Basic/DateTime?/Null",
delegate ()
{
logger.Write("DateTimeNull", new { nowTime = nullableDate2 });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("DateTimeNull", evt.EventName);
var payload = evt.PayloadValue(0, "nowTime");
Assert.Equal(nullableDate2, TestUtilities.UnwrapNullable<DateTime>(payload));
}));
/*************************************************************************/
tests.Add(new SubTest("Write/Basic/PartBOnly",
delegate ()
{
// log just a PartB
logger.Write("UserInfo", new EventSourceOptions { Keywords = EventKeywords.None },
new { _1 = new PartB_UserInfo { UserName = "Someone Else" } });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("UserInfo", evt.EventName);
var structValue = evt.PayloadValue(0, "PartB_UserInfo");
var structValueAsDictionary = structValue as IDictionary<string, object>;
Assert.NotNull(structValueAsDictionary);
Assert.Equal("Someone Else", structValueAsDictionary["UserName"]);
}));
/*************************************************************************/
tests.Add(new SubTest("Write/Basic/PartBAndC",
delegate ()
{
// log a PartB and a PartC
logger.Write("Duration", new EventSourceOptions { Keywords = EventKeywords.None },
new { _1 = new PartB_UserInfo { UserName = "Myself" }, msec = 10 });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("Duration", evt.EventName);
var structValue = evt.PayloadValue(0, "PartB_UserInfo");
var structValueAsDictionary = structValue as IDictionary<string, object>;
Assert.NotNull(structValueAsDictionary);
Assert.Equal("Myself", structValueAsDictionary["UserName"]);
Assert.Equal(10, evt.PayloadValue(1, "msec"));
}));
/*************************************************************************/
/*************************** ENUM TESTING *******************************/
/*************************************************************************/
/*************************************************************************/
GenerateEnumTest<Color>(ref tests, logger, Color.Green);
GenerateEnumTest<ColorUInt32>(ref tests, logger, ColorUInt32.Green);
GenerateEnumTest<ColorByte>(ref tests, logger, ColorByte.Green);
GenerateEnumTest<ColorSByte>(ref tests, logger, ColorSByte.Green);
GenerateEnumTest<ColorInt16>(ref tests, logger, ColorInt16.Green);
GenerateEnumTest<ColorUInt16>(ref tests, logger, ColorUInt16.Green);
GenerateEnumTest<ColorInt64>(ref tests, logger, ColorInt64.Green);
GenerateEnumTest<ColorUInt64>(ref tests, logger, ColorUInt64.Green);
/*************************************************************************/
/*************************** ARRAY TESTING *******************************/
/*************************************************************************/
/*************************************************************************/
GenerateArrayTest<bool>(ref tests, logger, new bool[] { false, true, false });
GenerateArrayTest<byte>(ref tests, logger, new byte[] { 1, 10, 100 });
GenerateArrayTest<sbyte>(ref tests, logger, new sbyte[] { 1, 10, 100 });
GenerateArrayTest<short>(ref tests, logger, new short[] { 1, 10, 100 });
GenerateArrayTest<ushort>(ref tests, logger, new ushort[] { 1, 10, 100 });
GenerateArrayTest<int>(ref tests, logger, new int[] { 1, 10, 100 });
GenerateArrayTest<uint>(ref tests, logger, new uint[] { 1, 10, 100 });
GenerateArrayTest<long>(ref tests, logger, new long[] { 1, 10, 100 });
GenerateArrayTest<ulong>(ref tests, logger, new ulong[] { 1, 10, 100 });
GenerateArrayTest<char>(ref tests, logger, new char[] { 'a', 'c', 'b' });
GenerateArrayTest<double>(ref tests, logger, new double[] { 1, 10, 100 });
GenerateArrayTest<float>(ref tests, logger, new float[] { 1, 10, 100 });
GenerateArrayTest<IntPtr>(ref tests, logger, new IntPtr[] { (IntPtr)1, (IntPtr)10, (IntPtr)100 });
GenerateArrayTest<UIntPtr>(ref tests, logger, new UIntPtr[] { (UIntPtr)1, (UIntPtr)10, (UIntPtr)100 });
GenerateArrayTest<Guid>(ref tests, logger, new Guid[] { Guid.Empty, new Guid("121a11ee-3bcb-49cc-b425-f4906fb14f72") });
/*************************************************************************/
/*********************** DICTIONARY TESTING ******************************/
/*************************************************************************/
var dict = new Dictionary<string, string>() { { "elem1", "10" }, { "elem2", "20" } };
var dictInt = new Dictionary<string, int>() { { "elem1", 10 }, { "elem2", 20 } };
/*************************************************************************/
tests.Add(new SubTest("Write/Dict/EventWithStringDict_C",
delegate ()
{
// log a dictionary
logger.Write("EventWithStringDict_C", new
{
myDict = dict,
s = "end"
});
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("EventWithStringDict_C", evt.EventName);
var keyValues = evt.PayloadValue(0, "myDict");
IDictionary<string, object> vDict = GetDictionaryFromKeyValueArray(keyValues);
Assert.Equal("10", vDict["elem1"]);
Assert.Equal("20", vDict["elem2"]);
Assert.Equal("end", evt.PayloadValue(1, "s"));
}));
/*************************************************************************/
tests.Add(new SubTest("Write/Dict/EventWithStringDict_BC",
delegate ()
{
// log a PartB and a dictionary as a PartC
logger.Write("EventWithStringDict_BC", new
{
PartB_UserInfo = new { UserName = "Me", LogTime = "Now" },
PartC_Dict = dict,
s = "end"
});
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("EventWithStringDict_BC", evt.EventName);
var structValue = evt.PayloadValue(0, "PartB_UserInfo");
var structValueAsDictionary = structValue as IDictionary<string, object>;
Assert.NotNull(structValueAsDictionary);
Assert.Equal("Me", structValueAsDictionary["UserName"]);
Assert.Equal("Now", structValueAsDictionary["LogTime"]);
var keyValues = evt.PayloadValue(1, "PartC_Dict");
var vDict = GetDictionaryFromKeyValueArray(keyValues);
Assert.NotNull(dict);
Assert.Equal("10", vDict["elem1"]); // string values.
Assert.Equal("20", vDict["elem2"]);
Assert.Equal("end", evt.PayloadValue(2, "s"));
}));
/*************************************************************************/
tests.Add(new SubTest("Write/Dict/EventWithIntDict_BC",
delegate ()
{
// log a Dict<string, int> as a PartC
logger.Write("EventWithIntDict_BC", new
{
PartB_UserInfo = new { UserName = "Me", LogTime = "Now" },
PartC_Dict = dictInt,
s = "end"
});
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("EventWithIntDict_BC", evt.EventName);
var structValue = evt.PayloadValue(0, "PartB_UserInfo");
var structValueAsDictionary = structValue as IDictionary<string, object>;
Assert.NotNull(structValueAsDictionary);
Assert.Equal("Me", structValueAsDictionary["UserName"]);
Assert.Equal("Now", structValueAsDictionary["LogTime"]);
var keyValues = evt.PayloadValue(1, "PartC_Dict");
var vDict = GetDictionaryFromKeyValueArray(keyValues);
Assert.NotNull(vDict);
Assert.Equal(10, vDict["elem1"]); // Notice they are integers, not strings.
Assert.Equal(20, vDict["elem2"]);
Assert.Equal("end", evt.PayloadValue(2, "s"));
}));
/*************************************************************************/
/**************************** Empty Event TESTING ************************/
/*************************************************************************/
tests.Add(new SubTest("Write/Basic/Message",
delegate ()
{
logger.Write("EmptyEvent");
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("EmptyEvent", evt.EventName);
}));
/*************************************************************************/
/**************************** EventSourceOptions TESTING *****************/
/*************************************************************************/
EventSourceOptions options = new EventSourceOptions();
options.Level = EventLevel.LogAlways;
options.Keywords = EventKeywords.All;
options.Opcode = EventOpcode.Info;
options.Tags = EventTags.None;
tests.Add(new SubTest("Write/Basic/MessageOptions",
delegate ()
{
logger.Write("EmptyEvent", options);
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("EmptyEvent", evt.EventName);
}));
tests.Add(new SubTest("Write/Basic/WriteOfTWithOptios",
delegate ()
{
logger.Write("OptionsEvent", options, new { OptionsEvent = "test options!" });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("OptionsEvent", evt.EventName);
Assert.Equal("test options!", evt.PayloadValue(0, "OptionsEvent"));
}));
tests.Add(new SubTest("Write/Basic/WriteOfTWithRefOptios",
delegate ()
{
var v = new { OptionsEvent = "test ref options!" };
logger.Write("RefOptionsEvent", ref options, ref v);
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("RefOptionsEvent", evt.EventName);
Assert.Equal("test ref options!", evt.PayloadValue(0, "OptionsEvent"));
}));
tests.Add(new SubTest("Write/Basic/WriteOfTWithNullString",
delegate ()
{
string nullString = null;
logger.Write("NullStringEvent", new { a = (string)null, b = nullString });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("NullStringEvent", evt.EventName);
Assert.Equal("", evt.PayloadValue(0, "a"));
Assert.Equal("", evt.PayloadValue(1, "b"));
}));
// This test only applies to ETW and will fail on EventListeners due to different behavior
// for strings with embedded NULL characters.
Test_Write_T_AddEtwTests(listener, tests, logger);
Guid activityId = new Guid("00000000-0000-0000-0000-000000000001");
Guid relActivityId = new Guid("00000000-0000-0000-0000-000000000002");
tests.Add(new SubTest("Write/Basic/WriteOfTWithOptios",
delegate ()
{
var v = new { ActivityMsg = "test activity!" };
logger.Write("ActivityEvent", ref options, ref activityId, ref relActivityId, ref v);
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("ActivityEvent", evt.EventName);
Assert.Equal("test activity!", evt.PayloadValue(0, "ActivityMsg"));
}));
// If you only wish to run one or several of the tests you can filter them here by
// Uncommenting the following line.
// tests = tests.FindAll(test => Regex.IsMatch(test.Name, "Write/Basic/EventII"));
// Here is where we actually run tests. First test the ETW path
EventTestHarness.RunTests(tests, listener, logger);
}
TestUtilities.CheckNoEventSourcesRunning("Stop");
}
static partial void Test_Write_T_AddEtwTests(Listener listener, List<SubTest> tests, EventSource logger);
[Fact]
[ActiveIssue("dotnet/corefx #18806", TargetFrameworkMonikers.NetFramework)]
[ActiveIssue("https://github.com/dotnet/corefx/issues/27106")]
public void Test_Write_T_In_Manifest_Serialization()
{
using (var eventListener = new EventListenerListener())
{
var listenerGenerators = new List<Func<Listener>> { () => eventListener };
Test_Write_T_In_Manifest_Serialization_Impl(listenerGenerators);
}
}
/// <summary>
/// This is not a user error but it is something unusual.
/// You can use the Write API in a EventSource that was did not
/// Declare SelfDescribingSerialization. In that case THOSE
/// events MUST use SelfDescribing serialization.
/// </summary>
private static void Test_Write_T_In_Manifest_Serialization_Impl(
IEnumerable<Func<Listener>> listenerGenerators)
{
foreach (var listenerGenerator in listenerGenerators)
{
var events = new List<Event>();
using (var listener = listenerGenerator())
{
Debug.WriteLine("Testing Listener " + listener);
// Create an eventSource with manifest based serialization
using (var logger = new SdtEventSources.EventSourceTest())
{
listener.OnEvent = delegate (Event data)
{ events.Add(data); };
listener.EventSourceSynchronousEnable(logger);
// Use the Write<T> API. This is OK
logger.Write("MyTestEvent", new { arg1 = 3, arg2 = "hi" });
}
}
Assert.Equal(1, events.Count);
Event _event = events[0];
Assert.Equal("MyTestEvent", _event.EventName);
Assert.Equal(3, (int)_event.PayloadValue(0, "arg1"));
Assert.Equal("hi", (string)_event.PayloadValue(1, "arg2"));
}
}
private void GenerateEnumTest<T>(ref List<SubTest> tests, EventSource logger, T enumValue)
{
string subTestName = enumValue.GetType().ToString();
tests.Add(new SubTest("Write/Enum/EnumEvent" + subTestName,
delegate ()
{
T c = enumValue;
// log an array
logger.Write("EnumEvent" + subTestName, new { b = "start", v = c, s = "end" });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("EnumEvent" + subTestName, evt.EventName);
Assert.Equal("start", evt.PayloadValue(0, "b"));
if (evt.IsEtw)
{
var value = evt.PayloadValue(1, "v");
Assert.Equal(2, int.Parse(value.ToString())); // Green has the int value of 2.
}
else
{
Assert.Equal(evt.PayloadValue(1, "v"), enumValue);
}
Assert.Equal("end", evt.PayloadValue(2, "s"));
}));
}
private void GenerateArrayTest<T>(ref List<SubTest> tests, EventSource logger, T[] array)
{
string typeName = array.GetType().GetElementType().ToString();
tests.Add(new SubTest("Write/Array/" + typeName,
delegate ()
{
// log an array
logger.Write("SomeEvent" + typeName, new { a = array, s = "end" });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("SomeEvent" + typeName, evt.EventName);
var eventArray = evt.PayloadValue(0, "a");
Array.Equals(array, eventArray);
Assert.Equal("end", evt.PayloadValue(1, "s"));
}));
}
/// <summary>
/// Convert an array of key value pairs (as ETW structs) into a dictionary with those values.
/// </summary>
/// <param name="structValue"></param>
/// <returns></returns>
private IDictionary<string, object> GetDictionaryFromKeyValueArray(object structValue)
{
var ret = new Dictionary<string, object>();
var asArray = structValue as object[];
Assert.NotNull(asArray);
foreach (var item in asArray)
{
var keyValue = item as IDictionary<string, object>;
Assert.Equal(2, keyValue.Count);
ret.Add((string)keyValue["Key"], keyValue["Value"]);
}
return ret;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
// Copyright (c) 2006 by Hugh Pyle, inguzaudio.com
// WAV file writer based originally on Garbe.Sound
namespace DSPUtil
{
public enum NormalizationType
{
PEAK_DBFS = 1,
PEAK_GAIN,
RMS_DBFS,
RMS_GAIN
}
/// <summary> Write the samples processed in a wave file </summary>
[Serializable]
public sealed class WaveWriter : SoundObj
{
// From WinBase.h
internal const int FILE_TYPE_DISK = 0x0001;
internal const int FILE_TYPE_CHAR = 0x0002;
internal const int FILE_TYPE_PIPE = 0x0003;
// Note, these are #defines used to extract handles, and are NOT handles.
internal const int STD_INPUT_HANDLE = -10;
internal const int STD_OUTPUT_HANDLE = -11;
internal const int STD_ERROR_HANDLE = -12;
[System.Runtime.InteropServices.DllImport("Kernel32.dll")]
internal static extern int GetFileType(IntPtr i_Handle);
[System.Runtime.InteropServices.DllImport("Kernel32.dll", SetLastError = true)]
internal static extern IntPtr GetStdHandle(int i_Handle); // param is NOT a handle, but it returns one!
// Members
private FileStream _fs;
private BinaryWriter _w;
private BufferedStream _bs;
private bool _raw = false;
private WaveFormat _audioFormat;
private WaveFormatEx _formatEx;
private SpeakerChannelMask _channelMask;
private DitherType _dither;
private ushort _bitsPerSample;
private int _sampleCount;
private int _iterations = 0;
private double _gain = 0;
private bool _ignoreclipping = false;
private double _normalization = double.NaN;
private NormalizationType _normType = NormalizationType.PEAK_DBFS;
private double[] _gains = null;
private bool _doneHeader;
private bool _isConsole;
// private double _scale8 = 128f;
// private double _scale16 = 32768f;
// private double _scale24 = 8388608f;
// private double _scale32 = 2147483648f;
private Dither[] _ditherProcessors;
#region Constructors
// //////////////////////////////////////////////////////////////////////////////////////////////////
// Constructors
// //////////////////////////////////////////////////////////////////////////////////////////////////
public WaveWriter(string fileName, ushort numChannels, uint sampleRate, ushort bitsPerSample, DitherType dither, WaveFormat format, bool rewrite)
{
Initialize(fileName, numChannels, sampleRate, bitsPerSample, dither, format, rewrite);
}
public WaveWriter(string fileName, ushort numChannels, uint sampleRate, ushort bitsPerSample, DitherType dither, WaveFormat format)
{
Initialize(fileName, numChannels, sampleRate, bitsPerSample, dither, format, true);
}
public WaveWriter(string fileName, ushort numChannels, uint sampleRate, ushort bitsPerSample, DitherType dither)
{
Initialize(fileName, numChannels, sampleRate, bitsPerSample, dither, WaveFormat.ANY, true);
}
public WaveWriter(string fileName, ushort numChannels, uint sampleRate, ushort bitsPerSample)
{
Initialize(fileName, numChannels, sampleRate, bitsPerSample, DitherType.NONE, WaveFormat.ANY, true);
}
public WaveWriter(string fileName)
{
Initialize(fileName, 0, 0, 0, DitherType.NONE, WaveFormat.ANY, true);
}
public WaveWriter(Stream output, ushort numChannels, uint sampleRate, ushort bitsPerSample, DitherType dither, WaveFormat format)
{
Initialize(output, numChannels, sampleRate, bitsPerSample, dither, format);
}
public WaveWriter(Stream output, ushort numChannels, uint sampleRate, ushort bitsPerSample, DitherType dither)
{
Initialize(output, numChannels, sampleRate, bitsPerSample, dither, WaveFormat.ANY);
}
public WaveWriter(Stream output, ushort numChannels, uint sampleRate, ushort bitsPerSample)
{
Initialize(output, numChannels, sampleRate, bitsPerSample, DitherType.NONE, WaveFormat.ANY);
}
public WaveWriter(Stream output)
{
Initialize(output, 0, 0, 0, DitherType.NONE, WaveFormat.ANY);
}
public WaveWriter()
{
Stream output = System.Console.OpenStandardOutput();
_isConsole = true;
Initialize(output, 0, 0, 0, DitherType.NONE, WaveFormat.ANY);
}
// //////////////////////////////////////////////////////////////////////////////////////////////////
// Helpers
// //////////////////////////////////////////////////////////////////////////////////////////////////
private void Initialize(string fileName, ushort numChannels, uint sampleRate, ushort bitsPerSample, DitherType dither, WaveFormat format, bool rewrite)
{
NumChannels = numChannels;
SampleRate = sampleRate;
BitsPerSample = bitsPerSample;
_audioFormat = format;
_dither = dither;
_sampleCount = 0;
_doneHeader = false;
if (File.Exists(fileName))
{
if (rewrite == false)
throw (new Exception("File already exists: " + fileName));
}
_fs = new FileStream(fileName, FileMode.Create);
_bs = new BufferedStream(_fs);
_w = new BinaryWriter(_bs);
}
private void Initialize(Stream output, ushort numChannels, uint sampleRate, ushort bitsPerSample, DitherType dither, WaveFormat format)
{
NumChannels = numChannels;
SampleRate = sampleRate;
BitsPerSample = bitsPerSample;
_audioFormat = format;
_dither = dither;
_sampleCount = 0;
_doneHeader = false;
_fs = null;
_bs = new BufferedStream(output);
_w = new BinaryWriter(_bs);
}
/// <summary>
/// Gain, units
/// </summary>
public double Gain
{
get
{
return _gain;
}
set
{
_gain = value;
// If you set gain, we stop applying normalization
_normalization = double.NaN;
}
}
/// <summary>
/// Set gain for individual channels.
/// This is multiplied by the global Gain if applicable.
/// </summary>
/// <param name="channel">Channel number</param>
/// <param name="gain">Gain (units), or double.NaN to reset</param>
public void SetChannelGain(ushort channel, double gain)
{
if (_gains==null)
{
_gains = new double[_nc];
for (ushort c = 0; c < _nc; c++)
{
_gains[c] = double.NaN;
}
}
_gains[channel] = gain;
_normalization = double.NaN;
}
public bool IgnoreClipping
{
get
{
return _ignoreclipping;
}
set
{
_ignoreclipping = value;
}
}
private void WriteWaveHeader()
{
if (_raw)
{
// Don't write any header for RAW files...
_doneHeader = true;
return;
}
ushort nChannels = NumChannels;
if (nChannels == 0)
{
throw new NotSupportedException("Number of channels cannot be zero");
}
ushort bPerSample = BitsPerSample;
if (bPerSample == 0)
{
throw new NotSupportedException("Bits per sample cannot be zero");
}
uint sRate = SampleRate;
if (sRate == 0)
{
throw new NotSupportedException("Sample rate cannot be zero");
}
ushort blockSize = (ushort)((nChannels * bPerSample) / 8);
uint dataSize = (uint)(Iterations * blockSize);
uint fmtSize = (uint)(_audioFormat == WaveFormat.EXTENSIBLE ? 40 : 16);
// Write Riff ///////////////////////////////////////////////
_w.Write('R');
_w.Write('I');
_w.Write('F');
_w.Write('F');
// RIFF size: size of the rest of the riff chunk following this
// = size of "WAVE" + size of 'fmt' + size of "DATA" + datasize
// = size of the entire file (bytes) - 8
uint riffSize = 4 + (8 + fmtSize) + (8 + dataSize);
_w.Write((uint)riffSize);
// Write Wave //////////////////////////////////////////////
_w.Write('W');
_w.Write('A');
_w.Write('V');
_w.Write('E');
// Write Format ////////////////////////////////////////////
_w.Write('f');
_w.Write('m');
_w.Write('t');
_w.Write(' ');
_w.Write((uint)fmtSize); // size of the fmt block
_w.Write((ushort)_audioFormat); // wave format
_w.Write((ushort)nChannels); // Number of channels
_w.Write((uint)sRate); // SampleRate (Hz)
_w.Write((uint)(blockSize * sRate)); //ByteRate
_w.Write((ushort)blockSize); //BlockAlign
_w.Write((ushort)bPerSample); //BitsPerSample
if (_audioFormat == WaveFormat.EXTENSIBLE)
{
_w.Write((UInt16)22); // size of this block
_w.Write((UInt16)bPerSample); // union{} = valid bits per sample, in this case
_w.Write((UInt32)_channelMask); // channel mask
_w.Write(_formatEx.guid.ToByteArray()); // GUID, 16 bytes
}
// Write Data ///////////////////////////////////////////////
_w.Write('d');
_w.Write('a');
_w.Write('t');
_w.Write('a');
// Write Data Size //////////////////////////////////////////
_w.Write((uint)dataSize);
_doneHeader = true;
}
#endregion
public override IEnumerator<ISample> Samples
{
get
{
bool err;
if (_audioFormat == WaveFormat.ANY)
{
throw new Exception("WaveWriter: format not specified");
}
MakeDither();
WriteWaveHeader();
foreach (ISample sample in _buff())
{
ISample s = _next(sample, out err);
if (err)
{
yield break;
}
yield return s;
}
}
}
private ISoundObj _buff()
{
if (double.IsNaN(_normalization))
{
return _input;
}
// We've been asked to normalize
SoundBuffer b = new SoundBuffer(_input);
b.ReadAll();
_gain = b.Normalize(_normalization, false);
return b;
}
private ISample _next(ISample sample, out bool err)
{
try
{
// if (_gain == 0) Gain = 1;
_sampleCount++;
if (!_ignoreclipping && (_sampleCount % _sr == 0))
{
// Every second, check for clipping and wind back the gain by 0.5dB if so
bool clipped = false;
for (int n = 0; n < _nc; n++)
{
if (_ditherProcessors[n].clipping)
{
clipped = true;
}
}
if (clipped)
{
// Reduce gain by 0.5dB to back off from clipping
Gain = _gain * 0.94406087628592338036438049660227;
// Trace.WriteLine("Gain {0} dB", MathUtil.dB(_gain));
for (int n = 0; n < _nc; n++)
{
_ditherProcessors[n].clipping = false;
}
}
}
for (int n = 0; n < _nc; n++)
{
// dither processor does the float-to-PCM conversion
// (dither is not applied to 32-f output, only to PCM)
double val = sample[n];
if (_gain != 0 && !double.IsNaN(_gain))
{
val *= _gain;
}
if (_gains != null && !double.IsNaN(_gains[n]))
{
val *= _gains[n];
}
switch (_bitsPerSample)
{
case 8:
_w.Write((byte)(_ditherProcessors[n].process(val) + 127));
break;
case 16:
_w.Write((short)_ditherProcessors[n].process(val));
break;
case 24:
// Little-endian, signed 24-bit
int c = _ditherProcessors[n].process(val);
_w.Write((ushort)(c & 0xFFFF));
_w.Write((sbyte)(c >> 16 & 0xFF));
break;
case 32:
if (_audioFormat == WaveFormat.PCM || _audioFormat == WaveFormat.EXTENSIBLE)
{
_w.Write((int)_ditherProcessors[n].process(val));
}
else if (_audioFormat == WaveFormat.IEEE_FLOAT)
{
// Internals are double; just cast to float and discard any extra resolution
// (really we should dither here too, to approx 24 bits?)
_w.Write((float)val);
}
break;
case 64:
// we only do float, not PCM, 64-bits
_w.Write((double)val);
break;
default:
throw new Exception(String.Format("Bits per sample cannot be {0}", BitsPerSample));
}
}
err = false;
if (_isConsole)
{
// Check the stdout stream is still alive
int Err = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
if (Err != 0)
{
// Err 997: "Overlapped I/O is in progress" (don't know cause)
// Err 183: cannot create a file... caused in Trace
// Err 2: cannot find a file... caused in Trace
if (Err != 997 && Err != 183 && Err != 2)
{
System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(Err);
Trace.WriteLine("Write fault " + Err + ": " + e.Message);
err = true;// yield break;
}
}
}
}
catch (Exception e)
{
if (DSPUtil.IsMono() && e.Message.Contains("Write fault on path"))
{
// This is the usual end-of-stream error on Mono
Trace.WriteLine("Write finished; " + e.Message);
err = true; // yield break
}
else if (e.GetHashCode() == 33574638)
{
// "The specified network name is no longer available", from softsqueeze
Trace.WriteLine("Write finished; " + e.Message);
err = true; // yield break
}
else
{
// Trace.WriteLine("Interrupted: " + e.Message);
throw e;
}
}
return sample;
}
/// <summary> Number of iterations expected to do the signal processing </summary>
public override int Iterations
{
get
{
if (_iterations == 0 && base._input!=null)
{
return (base._input.Iterations);
}
return _iterations;
}
}
/// <summary> Gets the number of bits per sample of the signal </summary>
public ushort BitsPerSample
{
get { return _bitsPerSample; }
set { _bitsPerSample = value; }
}
private void MakeDither()
{
_ditherProcessors = new Dither[NumChannels];
for (int j = 0; j < NumChannels; j++)
{
_ditherProcessors[j] = new Dither(_dither, SampleRate, BitsPerSample);
}
}
/// <summary>
/// Set or get the dither type
/// </summary>
public DitherType Dither
{
get
{
return _dither;
}
set
{
// Dither can be changed at runtime...
bool recreate = (value != _dither);
_dither = value;
if (recreate)
{
// Create new dither-processors.
MakeDither();
}
}
}
/// <summary>
/// Set or get the wave format
/// </summary>
public WaveFormat Format
{
get
{
return _audioFormat;
}
set
{
_audioFormat = value;
// if (_audioFormat == WaveFormat.IEEE_FLOAT)
// {
// // Float is always 32-bit
// BitsPerSample = 32;
// }
/* else */
if (_audioFormat == WaveFormat.INTERNAL_DOUBLE)
{
// Double is always 64-bit
BitsPerSample = 64;
}
}
}
/// <summary> Set or get the extensible Wave subtype </summary>
public WaveFormatEx FormatEx
{
get { return _formatEx; }
set
{
_audioFormat = WaveFormat.EXTENSIBLE;
_formatEx = value;
}
}
public SpeakerChannelMask ChannelMask
{
get { return _channelMask; }
set { _channelMask = value; }
}
public bool Raw
{
get
{
return _raw;
}
set
{
_raw = value;
}
}
// Normalization (default: peak dBFS)
/// <summary>
/// Normalization (default: peak dBFS)
/// (EXPENSIVE)
/// </summary>
public double Normalization
{
get
{
return _normalization;
}
set
{
_normalization = value;
}
}
/// <summary>
/// Type of normalization
/// </summary>
public NormalizationType NormalizationType
{
get
{
return _normType;
}
set
{
_normType = value;
}
}
/// <summary>
/// After writing some stuff - what's the peak level we wrote?
/// </summary>
public double dbfsPeak
{
get
{
double pk = -200;
for (int j = 0; j < NumChannels; j++)
{
pk = Math.Max(pk, _ditherProcessors[j].dbfsPeak);
}
return pk;
}
}
/// <summary> Close the wave file </summary>
public void Close()
{
if (_sampleCount != Iterations || !_doneHeader)
{
// Try rewind to write correct length into the header
try
{
if (_w.BaseStream.CanSeek)
{
_iterations = _sampleCount;
_w.Seek(0, SeekOrigin.Begin);
WriteWaveHeader();
}
}
catch (Exception)
{
}
}
// Flush and close silently
try
{
_bs.Flush();
_w.Close(); _w = null;
_bs.Close(); _bs = null;
if (_fs != null) { _fs.Close(); _fs = null; }
}
catch (Exception)
{
}
}
}
}
| |
#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
// .NET Compact Framework 1.0 has no support for System.Web.Mail
// SSCLI 1.0 has no support for System.Web.Mail
#if !NETCF && !SSCLI
using System;
using System.IO;
using System.Text;
#if NET_2_0
using System.Net.Mail;
#else
using System.Web.Mail;
#endif
using log4net.Layout;
using log4net.Core;
using log4net.Util;
namespace log4net.Appender
{
/// <summary>
/// Send an e-mail when a specific logging event occurs, typically on errors
/// or fatal errors.
/// </summary>
/// <remarks>
/// <para>
/// The number of logging events delivered in this e-mail depend on
/// the value of <see cref="BufferingAppenderSkeleton.BufferSize"/> option. The
/// <see cref="SmtpAppender"/> keeps only the last
/// <see cref="BufferingAppenderSkeleton.BufferSize"/> logging events in its
/// cyclic buffer. This keeps memory requirements at a reasonable level while
/// still delivering useful application context.
/// </para>
/// <note type="caution">
/// Authentication and setting the server Port are only available on the MS .NET 1.1 runtime.
/// For these features to be enabled you need to ensure that you are using a version of
/// the log4net assembly that is built against the MS .NET 1.1 framework and that you are
/// running the your application on the MS .NET 1.1 runtime. On all other platforms only sending
/// unauthenticated messages to a server listening on port 25 (the default) is supported.
/// </note>
/// <para>
/// Authentication is supported by setting the <see cref="Authentication"/> property to
/// either <see cref="SmtpAuthentication.Basic"/> or <see cref="SmtpAuthentication.Ntlm"/>.
/// If using <see cref="SmtpAuthentication.Basic"/> authentication then the <see cref="Username"/>
/// and <see cref="Password"/> properties must also be set.
/// </para>
/// <para>
/// To set the SMTP server port use the <see cref="Port"/> property. The default port is 25.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public class SmtpAppender : BufferingAppenderSkeleton
{
#region Public Instance Constructors
/// <summary>
/// Default constructor
/// </summary>
/// <remarks>
/// <para>
/// Default constructor
/// </para>
/// </remarks>
public SmtpAppender()
{
}
#endregion // Public Instance Constructors
#region Public Instance Properties
/// <summary>
/// Gets or sets a comma- or semicolon-delimited list of recipient e-mail addresses (use semicolon on .NET 1.1 and comma for later versions).
/// </summary>
/// <value>
/// <para>
/// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses.
/// </para>
/// <para>
/// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses.
/// </para>
/// </value>
/// <remarks>
/// <para>
/// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses.
/// </para>
/// <para>
/// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses.
/// </para>
/// </remarks>
public string To
{
get { return m_to; }
set { m_to = value; }
}
/// <summary>
/// Gets or sets a comma- or semicolon-delimited list of recipient e-mail addresses
/// that will be carbon copied (use semicolon on .NET 1.1 and comma for later versions).
/// </summary>
/// <value>
/// <para>
/// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses.
/// </para>
/// <para>
/// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses.
/// </para>
/// </value>
/// <remarks>
/// <para>
/// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses.
/// </para>
/// <para>
/// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses.
/// </para>
/// </remarks>
public string Cc
{
get { return m_cc; }
set { m_cc = value; }
}
/// <summary>
/// Gets or sets a semicolon-delimited list of recipient e-mail addresses
/// that will be blind carbon copied.
/// </summary>
/// <value>
/// A semicolon-delimited list of e-mail addresses.
/// </value>
/// <remarks>
/// <para>
/// A semicolon-delimited list of recipient e-mail addresses.
/// </para>
/// </remarks>
public string Bcc
{
get { return m_bcc; }
set { m_bcc = value; }
}
/// <summary>
/// Gets or sets the e-mail address of the sender.
/// </summary>
/// <value>
/// The e-mail address of the sender.
/// </value>
/// <remarks>
/// <para>
/// The e-mail address of the sender.
/// </para>
/// </remarks>
public string From
{
get { return m_from; }
set { m_from = value; }
}
/// <summary>
/// Gets or sets the subject line of the e-mail message.
/// </summary>
/// <value>
/// The subject line of the e-mail message.
/// </value>
/// <remarks>
/// <para>
/// The subject line of the e-mail message.
/// </para>
/// </remarks>
public string Subject
{
get { return m_subject; }
set { m_subject = value; }
}
/// <summary>
/// Gets or sets the name of the SMTP relay mail server to use to send
/// the e-mail messages.
/// </summary>
/// <value>
/// The name of the e-mail relay server. If SmtpServer is not set, the
/// name of the local SMTP server is used.
/// </value>
/// <remarks>
/// <para>
/// The name of the e-mail relay server. If SmtpServer is not set, the
/// name of the local SMTP server is used.
/// </para>
/// </remarks>
public string SmtpHost
{
get { return m_smtpHost; }
set { m_smtpHost = value; }
}
/// <summary>
/// Obsolete
/// </summary>
/// <remarks>
/// Use the BufferingAppenderSkeleton Fix methods instead
/// </remarks>
/// <remarks>
/// <para>
/// Obsolete property.
/// </para>
/// </remarks>
[Obsolete("Use the BufferingAppenderSkeleton Fix methods")]
public bool LocationInfo
{
get { return false; }
set { ; }
}
/// <summary>
/// The mode to use to authentication with the SMTP server
/// </summary>
/// <remarks>
/// <note type="caution">Authentication is only available on the MS .NET 1.1 runtime.</note>
/// <para>
/// Valid Authentication mode values are: <see cref="SmtpAuthentication.None"/>,
/// <see cref="SmtpAuthentication.Basic"/>, and <see cref="SmtpAuthentication.Ntlm"/>.
/// The default value is <see cref="SmtpAuthentication.None"/>. When using
/// <see cref="SmtpAuthentication.Basic"/> you must specify the <see cref="Username"/>
/// and <see cref="Password"/> to use to authenticate.
/// When using <see cref="SmtpAuthentication.Ntlm"/> the Windows credentials for the current
/// thread, if impersonating, or the process will be used to authenticate.
/// </para>
/// </remarks>
public SmtpAuthentication Authentication
{
get { return m_authentication; }
set { m_authentication = value; }
}
/// <summary>
/// The username to use to authenticate with the SMTP server
/// </summary>
/// <remarks>
/// <note type="caution">Authentication is only available on the MS .NET 1.1 runtime.</note>
/// <para>
/// A <see cref="Username"/> and <see cref="Password"/> must be specified when
/// <see cref="Authentication"/> is set to <see cref="SmtpAuthentication.Basic"/>,
/// otherwise the username will be ignored.
/// </para>
/// </remarks>
public string Username
{
get { return m_username; }
set { m_username = value; }
}
/// <summary>
/// The password to use to authenticate with the SMTP server
/// </summary>
/// <remarks>
/// <note type="caution">Authentication is only available on the MS .NET 1.1 runtime.</note>
/// <para>
/// A <see cref="Username"/> and <see cref="Password"/> must be specified when
/// <see cref="Authentication"/> is set to <see cref="SmtpAuthentication.Basic"/>,
/// otherwise the password will be ignored.
/// </para>
/// </remarks>
public string Password
{
get { return m_password; }
set { m_password = value; }
}
/// <summary>
/// The port on which the SMTP server is listening
/// </summary>
/// <remarks>
/// <note type="caution">Server Port is only available on the MS .NET 1.1 runtime.</note>
/// <para>
/// The port on which the SMTP server is listening. The default
/// port is <c>25</c>. The Port can only be changed when running on
/// the MS .NET 1.1 runtime.
/// </para>
/// </remarks>
public int Port
{
get { return m_port; }
set { m_port = value; }
}
/// <summary>
/// Gets or sets the priority of the e-mail message
/// </summary>
/// <value>
/// One of the <see cref="MailPriority"/> values.
/// </value>
/// <remarks>
/// <para>
/// Sets the priority of the e-mails generated by this
/// appender. The default priority is <see cref="MailPriority.Normal"/>.
/// </para>
/// <para>
/// If you are using this appender to report errors then
/// you may want to set the priority to <see cref="MailPriority.High"/>.
/// </para>
/// </remarks>
public MailPriority Priority
{
get { return m_mailPriority; }
set { m_mailPriority = value; }
}
#if NET_2_0
/// <summary>
/// Enable or disable use of SSL when sending e-mail message
/// </summary>
/// <remarks>
/// This is available on MS .NET 2.0 runtime and higher
/// </remarks>
public bool EnableSsl
{
get { return m_enableSsl; }
set { m_enableSsl = value; }
}
/// <summary>
/// Gets or sets the reply-to e-mail address.
/// </summary>
/// <remarks>
/// This is available on MS .NET 2.0 runtime and higher
/// </remarks>
public string ReplyTo
{
get { return m_replyTo; }
set { m_replyTo = value; }
}
#endif
/// <summary>
/// Gets or sets the subject encoding to be used.
/// </summary>
/// <remarks>
/// The default encoding is the operating system's current ANSI codepage.
/// </remarks>
public Encoding SubjectEncoding
{
get { return m_subjectEncoding; }
set { m_subjectEncoding = value; }
}
/// <summary>
/// Gets or sets the body encoding to be used.
/// </summary>
/// <remarks>
/// The default encoding is the operating system's current ANSI codepage.
/// </remarks>
public Encoding BodyEncoding
{
get { return m_bodyEncoding; }
set { m_bodyEncoding = value; }
}
#endregion // Public Instance Properties
#region Override implementation of BufferingAppenderSkeleton
/// <summary>
/// Sends the contents of the cyclic buffer as an e-mail message.
/// </summary>
/// <param name="events">The logging events to send.</param>
override protected void SendBuffer(LoggingEvent[] events)
{
// Note: this code already owns the monitor for this
// appender. This frees us from needing to synchronize again.
try
{
StringWriter writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture);
string t = Layout.Header;
if (t != null)
{
writer.Write(t);
}
for(int i = 0; i < events.Length; i++)
{
// Render the event and append the text to the buffer
RenderLoggingEvent(writer, events[i]);
}
t = Layout.Footer;
if (t != null)
{
writer.Write(t);
}
SendEmail(writer.ToString());
}
catch(Exception e)
{
ErrorHandler.Error("Error occurred while sending e-mail notification.", e);
}
}
#endregion // Override implementation of BufferingAppenderSkeleton
#region Override implementation of AppenderSkeleton
/// <summary>
/// This appender requires a <see cref="Layout"/> to be set.
/// </summary>
/// <value><c>true</c></value>
/// <remarks>
/// <para>
/// This appender requires a <see cref="Layout"/> to be set.
/// </para>
/// </remarks>
override protected bool RequiresLayout
{
get { return true; }
}
#endregion // Override implementation of AppenderSkeleton
#region Protected Methods
/// <summary>
/// Send the email message
/// </summary>
/// <param name="messageBody">the body text to include in the mail</param>
virtual protected void SendEmail(string messageBody)
{
#if NET_2_0
// .NET 2.0 has a new API for SMTP email System.Net.Mail
// This API supports credentials and multiple hosts correctly.
// The old API is deprecated.
// Create and configure the smtp client
SmtpClient smtpClient = new SmtpClient();
if (!String.IsNullOrEmpty(m_smtpHost))
{
smtpClient.Host = m_smtpHost;
}
smtpClient.Port = m_port;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = m_enableSsl;
if (m_authentication == SmtpAuthentication.Basic)
{
// Perform basic authentication
smtpClient.Credentials = new System.Net.NetworkCredential(m_username, m_password);
}
else if (m_authentication == SmtpAuthentication.Ntlm)
{
// Perform integrated authentication (NTLM)
smtpClient.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
}
using (MailMessage mailMessage = new MailMessage())
{
mailMessage.Body = messageBody;
mailMessage.BodyEncoding = m_bodyEncoding;
mailMessage.From = new MailAddress(m_from);
mailMessage.To.Add(m_to);
if (!String.IsNullOrEmpty(m_cc))
{
mailMessage.CC.Add(m_cc);
}
if (!String.IsNullOrEmpty(m_bcc))
{
mailMessage.Bcc.Add(m_bcc);
}
if (!String.IsNullOrEmpty(m_replyTo))
{
// .NET 4.0 warning CS0618: 'System.Net.Mail.MailMessage.ReplyTo' is obsolete:
// 'ReplyTo is obsoleted for this type. Please use ReplyToList instead which can accept multiple addresses. http://go.microsoft.com/fwlink/?linkid=14202'
#if !NET_4_0
mailMessage.ReplyTo = new MailAddress(m_replyTo);
#else
mailMessage.ReplyToList.Add(new MailAddress(m_replyTo));
#endif
}
mailMessage.Subject = m_subject;
mailMessage.SubjectEncoding = m_subjectEncoding;
mailMessage.Priority = m_mailPriority;
// TODO: Consider using SendAsync to send the message without blocking. This would be a change in
// behaviour compared to .NET 1.x. We would need a SendCompletedCallback to log errors.
smtpClient.Send(mailMessage);
}
#else
// .NET 1.x uses the System.Web.Mail API for sending Mail
MailMessage mailMessage = new MailMessage();
mailMessage.Body = messageBody;
mailMessage.BodyEncoding = m_bodyEncoding;
mailMessage.From = m_from;
mailMessage.To = m_to;
if (m_cc != null && m_cc.Length > 0)
{
mailMessage.Cc = m_cc;
}
if (m_bcc != null && m_bcc.Length > 0)
{
mailMessage.Bcc = m_bcc;
}
mailMessage.Subject = m_subject;
#if !MONO
mailMessage.SubjectEncoding = m_subjectEncoding;
#endif
mailMessage.Priority = m_mailPriority;
#if NET_1_1
// The Fields property on the MailMessage allows the CDO properties to be set directly.
// This property is only available on .NET Framework 1.1 and the implementation must understand
// the CDO properties. For details of the fields available in CDO see:
//
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cdosys/html/_cdosys_configuration_coclass.asp
//
try
{
if (m_authentication == SmtpAuthentication.Basic)
{
// Perform basic authentication
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 1);
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", m_username);
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", m_password);
}
else if (m_authentication == SmtpAuthentication.Ntlm)
{
// Perform integrated authentication (NTLM)
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 2);
}
// Set the port if not the default value
if (m_port != 25)
{
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", m_port);
}
}
catch(MissingMethodException missingMethodException)
{
// If we were compiled against .NET 1.1 but are running against .NET 1.0 then
// we will get a MissingMethodException when accessing the MailMessage.Fields property.
ErrorHandler.Error("SmtpAppender: Authentication and server Port are only supported when running on the MS .NET 1.1 framework", missingMethodException);
}
#else
if (m_authentication != SmtpAuthentication.None)
{
ErrorHandler.Error("SmtpAppender: Authentication is only supported on the MS .NET 1.1 or MS .NET 2.0 builds of log4net");
}
if (m_port != 25)
{
ErrorHandler.Error("SmtpAppender: Server Port is only supported on the MS .NET 1.1 or MS .NET 2.0 builds of log4net");
}
#endif // if NET_1_1
if (m_smtpHost != null && m_smtpHost.Length > 0)
{
SmtpMail.SmtpServer = m_smtpHost;
}
SmtpMail.Send(mailMessage);
#endif // if NET_2_0
}
#endregion // Protected Methods
#region Private Instance Fields
private string m_to;
private string m_cc;
private string m_bcc;
private string m_from;
private string m_subject;
private string m_smtpHost;
private Encoding m_subjectEncoding = Encoding.Default;
private Encoding m_bodyEncoding = Encoding.Default;
// authentication fields
private SmtpAuthentication m_authentication = SmtpAuthentication.None;
private string m_username;
private string m_password;
// server port, default port 25
private int m_port = 25;
private MailPriority m_mailPriority = MailPriority.Normal;
#if NET_2_0
private bool m_enableSsl = false;
private string m_replyTo;
#endif
#endregion // Private Instance Fields
#region SmtpAuthentication Enum
/// <summary>
/// Values for the <see cref="SmtpAppender.Authentication"/> property.
/// </summary>
/// <remarks>
/// <para>
/// SMTP authentication modes.
/// </para>
/// </remarks>
public enum SmtpAuthentication
{
/// <summary>
/// No authentication
/// </summary>
None,
/// <summary>
/// Basic authentication.
/// </summary>
/// <remarks>
/// Requires a username and password to be supplied
/// </remarks>
Basic,
/// <summary>
/// Integrated authentication
/// </summary>
/// <remarks>
/// Uses the Windows credentials from the current thread or process to authenticate.
/// </remarks>
Ntlm
}
#endregion // SmtpAuthentication Enum
}
}
#endif // !NETCF && !SSCLI
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Text.RegularExpressions;
namespace System.Management.Automation
{
internal class MUIFileSearcher
{
/// <summary>
/// Constructor. It is private so that MUIFileSearcher is used only internal for this class.
/// To access functionality in this class, static api should be used.
/// </summary>
/// <param name="target"></param>
/// <param name="searchPaths"></param>
/// <param name="searchMode"></param>
private MUIFileSearcher(string target, Collection<string> searchPaths, SearchMode searchMode)
{
Target = target;
SearchPaths = searchPaths;
SearchMode = searchMode;
}
/// <summary>
/// A constructor to make searchMode optional.
/// </summary>
/// <param name="target"></param>
/// <param name="searchPaths"></param>
private MUIFileSearcher(string target, Collection<string> searchPaths)
: this(target, searchPaths, SearchMode.Unique)
{
}
#region Basic Properties
/// <summary>
/// Search target. It can be
/// 1. a file name
/// 2. a search pattern
/// It can also include a path, in that case,
/// 1. the path will be searched first for the existence of the files.
/// </summary>
internal string Target { get; } = null;
/// <summary>
/// Search path as provided by user.
/// </summary>
internal Collection<string> SearchPaths { get; } = null;
/// <summary>
/// Search mode for this file search.
/// </summary>
internal SearchMode SearchMode { get; } = SearchMode.Unique;
private Collection<string> _result = null;
/// <summary>
/// Result of the search.
/// </summary>
internal Collection<string> Result
{
get
{
if (_result == null)
{
_result = new Collection<string>();
// SearchForFiles will fill the result collection.
SearchForFiles();
}
return _result;
}
}
#endregion
#region File Search
/// <summary>
/// _uniqueMatches is used to track matches already found during the search process.
/// This is useful for ignoring duplicates in the case of unique search.
/// </summary>
private Hashtable _uniqueMatches = new Hashtable(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Search for files using the target, searchPaths member of this class.
/// </summary>
private void SearchForFiles()
{
if (string.IsNullOrEmpty(this.Target))
return;
string pattern = Path.GetFileName(this.Target);
if (string.IsNullOrEmpty(pattern))
return;
Collection<string> normalizedSearchPaths = NormalizeSearchPaths(this.Target, this.SearchPaths);
foreach (string directory in normalizedSearchPaths)
{
SearchForFiles(pattern, directory);
if (this.SearchMode == SearchMode.First && this.Result.Count > 0)
{
return;
}
}
}
private string[] GetFiles(string path, string pattern)
{
#if UNIX
// On Linux, file names are case sensitive, so we need to add
// extra logic to select the files that match the given pattern.
ArrayList result = new ArrayList();
string[] files = Directory.GetFiles(path);
var wildcardPattern = WildcardPattern.ContainsWildcardCharacters(pattern)
? WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase)
: null;
foreach (string filePath in files)
{
if (filePath.IndexOf(pattern, StringComparison.OrdinalIgnoreCase) >= 0)
{
result.Add(filePath);
break;
}
if (wildcardPattern != null)
{
string fileName = Path.GetFileName(filePath);
if (wildcardPattern.IsMatch(fileName))
{
result.Add(filePath);
}
}
}
return (string[])result.ToArray(typeof(string));
#else
return Directory.GetFiles(path, pattern);
#endif
}
private void AddFiles(string muiDirectory, string directory, string pattern)
{
if (Directory.Exists(muiDirectory))
{
string[] files = GetFiles(muiDirectory, pattern);
if (files == null)
return;
foreach (string file in files)
{
string path = Path.Combine(muiDirectory, file);
switch (this.SearchMode)
{
case SearchMode.All:
_result.Add(path);
break;
case SearchMode.Unique:
// Construct a Unique filename for this directory.
// Remember the file may belong to one of the sub-culture
// directories. In this case we should not be returning
// same files that are residing in 2 or more sub-culture
// directories.
string leafFileName = Path.GetFileName(file);
string uniqueToDirectory = Path.Combine(directory, leafFileName);
if (!_result.Contains(path) && !_uniqueMatches.Contains(uniqueToDirectory))
{
_result.Add(path);
_uniqueMatches[uniqueToDirectory] = true;
}
break;
case SearchMode.First:
_result.Add(path);
return;
default:
break;
}
}
}
}
/// <summary>
/// Search for files of a particular pattern under a particular directory.
/// This will do MUI search in which appropriate language directories are
/// searched in order.
/// </summary>
/// <param name="pattern"></param>
/// <param name="directory"></param>
private void SearchForFiles(string pattern, string directory)
{
List<string> cultureNameList = new List<string>();
CultureInfo culture = CultureInfo.CurrentUICulture;
while (culture != null && !string.IsNullOrEmpty(culture.Name))
{
cultureNameList.Add(culture.Name);
culture = culture.Parent;
}
cultureNameList.Add(string.Empty);
// Add en-US and en as fallback languages
if (!cultureNameList.Contains("en-US"))
{
cultureNameList.Add("en-US");
}
if (!cultureNameList.Contains("en"))
{
cultureNameList.Add("en");
}
foreach (string name in cultureNameList)
{
string muiDirectory = Path.Combine(directory, name);
AddFiles(muiDirectory, directory, pattern);
if (this.SearchMode == SearchMode.First && this.Result.Count > 0)
{
return;
}
}
return;
}
/// <summary>
/// A help file is located in 3 steps
/// 1. If file itself contains a path itself, try to locate the file
/// from path. LocateFile will fail if this file doesn't exist.
/// 2. Try to locate the file from searchPaths. Normally the searchPaths will
/// contain the cmdlet/provider assembly directory if currently we are searching
/// help for cmdlet and providers.
/// 3. Try to locate the file in the default PowerShell installation directory.
/// </summary>
/// <param name="target"></param>
/// <param name="searchPaths"></param>
/// <returns></returns>
private static Collection<string> NormalizeSearchPaths(string target, Collection<string> searchPaths)
{
Collection<string> result = new Collection<string>();
// step 1: if target has path attached, directly locate
// file from there.
if (!string.IsNullOrEmpty(target) && !string.IsNullOrEmpty(Path.GetDirectoryName(target)))
{
string directory = Path.GetDirectoryName(target);
if (Directory.Exists(directory))
{
result.Add(Path.GetFullPath(directory));
}
// user specifically wanted to search in a particular directory
// so return..
return result;
}
// step 2: add directories specified in to search path.
if (searchPaths != null)
{
foreach (string directory in searchPaths)
{
if (!result.Contains(directory) && Directory.Exists(directory))
{
result.Add(directory);
}
}
}
// step 3: locate the file in the default PowerShell installation directory.
string defaultPSPath = Utils.GetApplicationBase(Utils.DefaultPowerShellShellID);
if (defaultPSPath != null &&
!result.Contains(defaultPSPath) &&
Directory.Exists(defaultPSPath))
{
result.Add(defaultPSPath);
}
return result;
}
#endregion
#region Static API's
/// <summary>
/// Search for files in default search paths.
/// </summary>
/// <param name="pattern"></param>
/// <returns></returns>
internal static Collection<string> SearchFiles(string pattern)
{
return SearchFiles(pattern, new Collection<string>());
}
/// <summary>
/// Search for files in specified search paths.
/// </summary>
/// <param name="pattern"></param>
/// <param name="searchPaths"></param>
/// <returns></returns>
internal static Collection<string> SearchFiles(string pattern, Collection<string> searchPaths)
{
MUIFileSearcher searcher = new MUIFileSearcher(pattern, searchPaths);
return searcher.Result;
}
/// <summary>
/// Locate a file in default search paths.
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
internal static string LocateFile(string file)
{
return LocateFile(file, new Collection<string>());
}
/// <summary>
/// Get the file in different search paths corresponding to current culture.
///
/// The file name to search is the filename part of path parameter. (Normally path
/// parameter should contain only the filename part).
/// </summary>
/// <param name="file">This is the path to the file. If it has a path, we need to search under that path first.</param>
/// <param name="searchPaths">Additional search paths.</param>
/// <returns></returns>
internal static string LocateFile(string file, Collection<string> searchPaths)
{
MUIFileSearcher searcher = new MUIFileSearcher(file, searchPaths, SearchMode.First);
if (searcher.Result == null || searcher.Result.Count == 0)
return null;
return searcher.Result[0];
}
#endregion
}
/// <summary>
/// This enum defines different search mode for the MUIFileSearcher.
/// </summary>
internal enum SearchMode
{
// return the first match
First,
// return all matches, with duplicates allowed
All,
// return all matches, with duplicates ignored
Unique
}
}
| |
using Aspose.Email;
using Aspose.Email.Mapi;
using Aspose.Email.Storage.Mbox;
using Aspose.Email.Storage.Pst;
using Aspose.Slides;
using System;
using System.IO;
namespace Aspose.Email.Live.Demos.UI.Services.Email
{
public partial class EmailService
{
public void ConvertMbox(Stream input, string shortResourceNameWithExtension, IOutputHandler handler, string outputType)
{
PrepareOutputType(ref outputType);
switch (outputType)
{
case "eml": ConvertMboxToEml(input, shortResourceNameWithExtension, handler); break;
case "msg": ConvertMboxToMsg(input, shortResourceNameWithExtension, handler); break;
case "mbox": ReturnSame(input, shortResourceNameWithExtension, handler); break;
case "pst": ConvertMboxToPst(input, shortResourceNameWithExtension, handler); break;
case "mht": ConvertMboxToMht(input, shortResourceNameWithExtension, handler); break;
case "html": ConvertMboxToHtml(input, shortResourceNameWithExtension, handler); break;
case "svg": ConvertMboxToSvg(input, shortResourceNameWithExtension, handler); break;
case "tiff": ConvertMboxToTiff(input, shortResourceNameWithExtension, handler); break;
case "jpg": ConvertMboxToJpg(input, shortResourceNameWithExtension, handler); break;
case "bmp": ConvertMboxToBmp(input, shortResourceNameWithExtension, handler); break;
case "png": ConvertMboxToPng(input, shortResourceNameWithExtension, handler); break;
case "pdf": ConvertMboxToPdf(input, shortResourceNameWithExtension, handler); break;
case "doc": ConvertMboxToDoc(input, shortResourceNameWithExtension, handler); break;
case "ppt": ConvertMboxToPpt(input, shortResourceNameWithExtension, handler); break;
case "rtf": ConvertMboxToRtf(input, shortResourceNameWithExtension, handler); break;
case "docx": ConvertMboxToDocx(input, shortResourceNameWithExtension, handler); break;
case "docm": ConvertMboxToDocm(input, shortResourceNameWithExtension, handler); break;
case "dotx": ConvertMboxToDotx(input, shortResourceNameWithExtension, handler); break;
case "dotm": ConvertMboxToDotm(input, shortResourceNameWithExtension, handler); break;
case "odt": ConvertMboxToOdt(input, shortResourceNameWithExtension, handler); break;
case "ott": ConvertMboxToOtt(input, shortResourceNameWithExtension, handler); break;
case "epub": ConvertMboxToEpub(input, shortResourceNameWithExtension, handler); break;
case "txt": ConvertMboxToTxt(input, shortResourceNameWithExtension, handler); break;
case "emf": ConvertMboxToEmf(input, shortResourceNameWithExtension, handler); break;
case "xps": ConvertMboxToXps(input, shortResourceNameWithExtension, handler); break;
case "pcl": ConvertMboxToPcl(input, shortResourceNameWithExtension, handler); break;
case "ps": ConvertMboxToPs(input, shortResourceNameWithExtension, handler); break;
case "mhtml": ConvertMboxToMhtml(input, shortResourceNameWithExtension, handler); break;
default:
throw new NotSupportedException($"Output type not supported {outputType.ToUpperInvariant()}");
}
}
public void ConvertMboxToTiff(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveMboxAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Tiff, ".tiff");
}
public void ConvertMboxToJpg(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveMboxAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Jpeg, ".jpg");
}
public void ConvertMboxToBmp(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveMboxAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Bmp, ".bmp");
}
public void ConvertMboxToPng(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveMboxAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Png, ".png");
}
public void ConvertMboxToSvg(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveMboxAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Svg, ".svg");
}
public void ConvertMboxToHtml(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveMboxAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Html, ".html");
}
public void ConvertMboxToMht(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
// Save as mht with header
var mhtSaveOptions = new MhtSaveOptions
{
//Specify formatting options required
//Here we are specifying to write header informations to output without writing extra print header
//and the output headers should display as the original headers in message
MhtFormatOptions = MhtFormatOptions.WriteHeader | MhtFormatOptions.HideExtraPrintHeader | MhtFormatOptions.DisplayAsOutlook,
// Check the body encoding for validity.
CheckBodyContentEncoding = true
};
using (var reader = new MboxrdStorageReader(input, false))
{
for (int i = 0; i < reader.GetTotalItemsCount(); i++)
{
var message = reader.ReadNextMessage();
using (var output = handler.CreateOutputStream("Message" + i + ".mht"))
message.Save(output, mhtSaveOptions);
}
}
}
///<Summary>
/// ConvertMboxToPst method to convert mbox to pst file
///</Summary>
public void ConvertMboxToPst(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
using (var personalStorage = PersonalStorage.Create(handler.CreateOutputStream(Path.ChangeExtension(shortResourceNameWithExtension, ".pst")), FileFormatVersion.Unicode))
{
var inbox = personalStorage.RootFolder.AddSubFolder("Inbox");
using (MboxrdStorageReader reader = new MboxrdStorageReader(input, false))
{
MailMessage message;
while ((message = reader.ReadNextMessage()) != null)
{
using (var mapi = MapiMessage.FromMailMessage(message, MapiConversionOptions.UnicodeFormat))
inbox.AddMessage(mapi);
}
}
}
}
///<Summary>
/// ConvertMboxToEml method to convert mbox to eml file
///</Summary>
public void ConvertMboxToEml(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
using (var reader = new MboxrdStorageReader(input, false))
{
for (int i = 0; i < reader.GetTotalItemsCount(); i++)
{
using (var message = reader.ReadNextMessage())
{
using (var output = handler.CreateOutputStream("Message" + i + ".eml"))
message.Save(output, SaveOptions.DefaultEml);
}
}
}
}
///<Summary>
/// ConvertMboxToMsg method to convert mbox to msg file
///</Summary>
public void ConvertMboxToMsg(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
using (var reader = new MboxrdStorageReader(input, false))
{
for (int i = 0; i < reader.GetTotalItemsCount(); i++)
{
using (var message = reader.ReadNextMessage())
{
using (var output = handler.CreateOutputStream("Message" + i + ".msg"))
message.Save(output, SaveOptions.DefaultMsgUnicode);
}
}
}
}
public void ConvertMboxToPdf(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Pdf);
}
public void ConvertMboxToDoc(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Doc);
}
public void ConvertMboxToPpt(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
using (var reader = new MboxrdStorageReader(input, false))
{
using (var presentation = new Presentation())
{
var firstSlide = presentation.Slides[0];
var convertOptions = new MapiConversionOptions();
var renameCallback = new ImageSavingCallback(handler);
for (int i = 0; i < reader.GetTotalItemsCount(); i++)
{
var message = reader.ReadNextMessage();
var newSlide = presentation.Slides.AddClone(firstSlide);
AddMessageInSlide(presentation, newSlide, MapiMessage.FromMailMessage(message, convertOptions), renameCallback);
}
presentation.Slides.Remove(firstSlide);
using (var output = handler.CreateOutputStream(Path.ChangeExtension(shortResourceNameWithExtension, ".ppt")))
presentation.Save(output, Aspose.Slides.Export.SaveFormat.Ppt);
}
}
}
public void ConvertMboxToRtf(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Rtf);
}
public void ConvertMboxToDocx(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Docx);
}
public void ConvertMboxToDocm(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Docm);
}
public void ConvertMboxToDotx(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Dotx);
}
public void ConvertMboxToDotm(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Dotm);
}
public void ConvertMboxToOdt(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Odt);
}
public void ConvertMboxToOtt(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Ott);
}
public void ConvertMboxToEpub(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Epub);
}
public void ConvertMboxToTxt(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Text);
}
public void ConvertMboxToEmf(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Emf);
}
public void ConvertMboxToXps(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Xps);
}
public void ConvertMboxToPcl(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Pcl);
}
public void ConvertMboxToPs(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Ps);
}
public void ConvertMboxToMhtml(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Mhtml);
}
void SaveMboxAsDocument(Stream input, string shortResourceNameWithExtension, IOutputHandler handler, Words.SaveFormat format, string saveExtension)
{
using (var reader = new MboxrdStorageReader(input, false))
{
var msgStream = new MemoryStream();
for (int i = 0; i < reader.GetTotalItemsCount(); i++)
{
var message = reader.ReadNextMessage();
message.Save(msgStream, SaveOptions.DefaultMhtml);
}
msgStream.Position = 0;
SaveDocumentStreamToFolder(msgStream, shortResourceNameWithExtension, handler, format);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections.ObjectModel;
using System.Management.Automation.Provider;
using Dbg = System.Management.Automation;
#pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings
#pragma warning disable 56500
namespace System.Management.Automation
{
/// <summary>
/// Holds the state of a Monad Shell session.
/// </summary>
internal sealed partial class SessionStateInternal
{
#region IPropertyCmdletProvider accessors
#region GetProperty
/// <summary>
/// Gets the specified properties from the specified item.
/// </summary>
/// <param name="paths">
/// The path(s) to the item(s) to get the properties from.
/// </param>
/// <param name="providerSpecificPickList">
/// A list of the properties that the provider should return.
/// </param>
/// <param name="literalPath">
/// If true, globbing is not done on paths.
/// </param>
/// <returns>
/// A property table container the properties and their values.
/// </returns>
/// <exception cref="ArgumentNullException">
/// If <paramref name="path"/> is null.
/// </exception>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
internal Collection<PSObject> GetProperty(
string[] paths,
Collection<string> providerSpecificPickList,
bool literalPath)
{
if (paths == null)
{
throw PSTraceSource.NewArgumentNullException("path");
}
CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext);
context.SuppressWildcardExpansion = literalPath;
GetProperty(paths, providerSpecificPickList, context);
context.ThrowFirstErrorOrDoNothing();
Collection<PSObject> results = context.GetAccumulatedObjects();
return results;
}
/// <summary>
/// Gets the specified properties from the specified item.
/// </summary>
/// <param name="paths">
/// The path(s) to the item(s) to get the properties from.
/// </param>
/// <param name="providerSpecificPickList">
/// A list of the properties that the provider should return.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <returns>
/// Nothing. A PSObject representing the properties should be written to the
/// context.
/// </returns>
/// <exception cref="ArgumentNullException">
/// If <paramref name="path"/> is null.
/// </exception>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
/// <exception cref="ItemNotFoundException">
/// If <paramref name="path"/> does not contain glob characters and
/// could not be found.
/// </exception>
internal void GetProperty(
string[] paths,
Collection<string> providerSpecificPickList,
CmdletProviderContext context)
{
if (paths == null)
{
throw PSTraceSource.NewArgumentNullException("paths");
}
foreach (string path in paths)
{
if (path == null)
{
throw PSTraceSource.NewArgumentNullException("paths");
}
ProviderInfo provider = null;
CmdletProvider providerInstance = null;
Collection<string> providerPaths =
Globber.GetGlobbedProviderPathsFromMonadPath(
path,
false,
context,
out provider,
out providerInstance);
foreach (string providerPath in providerPaths)
{
GetPropertyPrivate(
providerInstance,
providerPath,
providerSpecificPickList,
context);
}
}
}
/// <summary>
/// Gets the property from the item at the specified path.
/// </summary>
/// <param name="providerInstance">
/// The provider instance to use.
/// </param>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="providerSpecificPickList">
/// The names of the properties to get.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <exception cref="NotSupportedException">
/// If the <paramref name="providerInstance"/> does not support this operation.
/// </exception>
/// <exception cref="PipelineStoppedException">
/// If the pipeline is being stopped while executing the command.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
private void GetPropertyPrivate(
CmdletProvider providerInstance,
string path,
Collection<string> providerSpecificPickList,
CmdletProviderContext context)
{
// All parameters should have been validated by caller
Dbg.Diagnostics.Assert(
providerInstance != null,
"Caller should validate providerInstance before calling this method");
Dbg.Diagnostics.Assert(
path != null,
"Caller should validate path before calling this method");
Dbg.Diagnostics.Assert(
context != null,
"Caller should validate context before calling this method");
try
{
providerInstance.GetProperty(path, providerSpecificPickList, context);
}
catch (NotSupportedException)
{
throw;
}
catch (LoopFlowException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (Exception e) // Catch-all OK, 3rd party callout.
{
throw NewProviderInvocationException(
"GetPropertyProviderException",
SessionStateStrings.GetPropertyProviderException,
providerInstance.ProviderInfo,
path,
e);
}
}
/// <summary>
/// Gets the dynamic parameters for the get-itemproperty cmdlet.
/// </summary>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="providerSpecificPickList">
/// A list of the properties that the provider should return.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <returns>
/// An object that has properties and fields decorated with
/// parsing attributes similar to a cmdlet class.
/// </returns>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
/// <exception cref="ItemNotFoundException">
/// If <paramref name="path"/> does not contain glob characters and
/// could not be found.
/// </exception>
internal object GetPropertyDynamicParameters(
string path,
Collection<string> providerSpecificPickList,
CmdletProviderContext context)
{
if (path == null)
{
return null;
}
ProviderInfo provider = null;
CmdletProvider providerInstance = null;
CmdletProviderContext newContext =
new CmdletProviderContext(context);
newContext.SetFilters(
new Collection<string>(),
new Collection<string>(),
null);
Collection<string> providerPaths =
Globber.GetGlobbedProviderPathsFromMonadPath(
path,
true,
newContext,
out provider,
out providerInstance);
if (providerPaths.Count > 0)
{
// Get the dynamic parameters for the first resolved path
return GetPropertyDynamicParameters(providerInstance, providerPaths[0], providerSpecificPickList, newContext);
}
return null;
}
/// <summary>
/// Gets the dynamic parameters for the get-itemproperty cmdlet.
/// </summary>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="providerSpecificPickList">
/// The names of the properties to get.
/// </param>
/// <param name="providerInstance">
/// The instance of the provider to use.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <returns>
/// An object that has properties and fields decorated with
/// parsing attributes similar to a cmdlet class.
/// </returns>
/// <exception cref="NotSupportedException">
/// If the <paramref name="providerInstance"/> does not support this operation.
/// </exception>
/// <exception cref="PipelineStoppedException">
/// If the pipeline is being stopped while executing the command.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
private object GetPropertyDynamicParameters(
CmdletProvider providerInstance,
string path,
Collection<string> providerSpecificPickList,
CmdletProviderContext context)
{
// All parameters should have been validated by caller
Dbg.Diagnostics.Assert(
providerInstance != null,
"Caller should validate providerInstance before calling this method");
Dbg.Diagnostics.Assert(
path != null,
"Caller should validate path before calling this method");
Dbg.Diagnostics.Assert(
context != null,
"Caller should validate context before calling this method");
object result = null;
try
{
result = providerInstance.GetPropertyDynamicParameters(path, providerSpecificPickList, context);
}
catch (NotSupportedException)
{
throw;
}
catch (LoopFlowException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
catch (Exception e) // Catch-all OK, 3rd party callout.
{
throw NewProviderInvocationException(
"GetPropertyDynamicParametersProviderException",
SessionStateStrings.GetPropertyDynamicParametersProviderException,
providerInstance.ProviderInfo,
path,
e);
}
return result;
}
#endregion GetProperty
#region SetProperty
/// <summary>
/// Sets the specified properties on the specified item.
/// </summary>
/// <param name="paths">
/// The path(s) to the item(s) to set the properties on.
/// </param>
/// <param name="property">
/// A PSObject containing the properties to be changed.
/// </param>
/// <param name="force">
/// Passed on to providers to force operations.
/// </param>
/// <param name="literalPath">
/// If true, globbing is not done on paths.
/// </param>
/// <returns>
/// An array of PSObjects representing the properties that were set on each item.
/// </returns>
/// <exception cref="ArgumentNullException">
/// If <paramref name="path"/> or <paramref name="property"/> is null.
/// </exception>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
internal Collection<PSObject> SetProperty(string[] paths, PSObject property, bool force, bool literalPath)
{
if (paths == null)
{
throw PSTraceSource.NewArgumentNullException("paths");
}
if (property == null)
{
throw PSTraceSource.NewArgumentNullException("properties");
}
CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext);
context.Force = force;
context.SuppressWildcardExpansion = literalPath;
SetProperty(paths, property, context);
context.ThrowFirstErrorOrDoNothing();
Collection<PSObject> results = context.GetAccumulatedObjects();
return results;
}
/// <summary>
/// Sets the specified properties on specified item.
/// </summary>
/// <param name="paths">
/// The path(s) to the item(s) to set the properties on.
/// </param>
/// <param name="property">
/// A property table containing the properties and values to be set on the object.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <returns>
/// Nothing. A PSObject is passed to the context for the properties on each item
/// that were modified.
/// </returns>
/// <exception cref="ArgumentNullException">
/// If <paramref name="path"/> or <paramref name="property"/> is null.
/// </exception>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
/// <exception cref="ItemNotFoundException">
/// If <paramref name="path"/> does not contain glob characters and
/// could not be found.
/// </exception>
internal void SetProperty(
string[] paths,
PSObject property,
CmdletProviderContext context)
{
if (paths == null)
{
throw PSTraceSource.NewArgumentNullException("paths");
}
if (property == null)
{
throw PSTraceSource.NewArgumentNullException("property");
}
foreach (string path in paths)
{
if (path == null)
{
throw PSTraceSource.NewArgumentNullException("paths");
}
ProviderInfo provider = null;
CmdletProvider providerInstance = null;
Collection<string> providerPaths =
Globber.GetGlobbedProviderPathsFromMonadPath(
path,
false,
context,
out provider,
out providerInstance);
if (providerPaths != null)
{
foreach (string providerPath in providerPaths)
{
SetPropertyPrivate(providerInstance, providerPath, property, context);
}
}
}
}
/// <summary>
/// Sets the property of the item at the specified path.
/// </summary>
/// <param name="providerInstance">
/// The provider instance to use.
/// </param>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="property">
/// The name of the property to set.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <exception cref="NotSupportedException">
/// If the <paramref name="providerInstance"/> does not support this operation.
/// </exception>
/// <exception cref="PipelineStoppedException">
/// If the pipeline is being stopped while executing the command.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
private void SetPropertyPrivate(
CmdletProvider providerInstance,
string path,
PSObject property,
CmdletProviderContext context)
{
// All parameters should have been validated by caller
Dbg.Diagnostics.Assert(
providerInstance != null,
"Caller should validate providerInstance before calling this method");
Dbg.Diagnostics.Assert(
path != null,
"Caller should validate path before calling this method");
Dbg.Diagnostics.Assert(
property != null,
"Caller should validate properties before calling this method");
Dbg.Diagnostics.Assert(
context != null,
"Caller should validate context before calling this method");
try
{
providerInstance.SetProperty(path, property, context);
}
catch (NotSupportedException)
{
throw;
}
catch (LoopFlowException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
catch (Exception e) // Catch-all OK, 3rd party callout.
{
throw NewProviderInvocationException(
"SetPropertyProviderException",
SessionStateStrings.SetPropertyProviderException,
providerInstance.ProviderInfo,
path,
e);
}
}
/// <summary>
/// Gets the dynamic parameters for the clear-itemproperty cmdlet.
/// </summary>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="propertyValue">
/// A property table containing the properties and values to be set on the object.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <returns>
/// An object that has properties and fields decorated with
/// parsing attributes similar to a cmdlet class.
/// </returns>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
/// <exception cref="ItemNotFoundException">
/// If <paramref name="path"/> does not contain glob characters and
/// could not be found.
/// </exception>
internal object SetPropertyDynamicParameters(
string path,
PSObject propertyValue,
CmdletProviderContext context)
{
if (path == null)
{
return null;
}
ProviderInfo provider = null;
CmdletProvider providerInstance = null;
CmdletProviderContext newContext =
new CmdletProviderContext(context);
newContext.SetFilters(
new Collection<string>(),
new Collection<string>(),
null);
Collection<string> providerPaths =
Globber.GetGlobbedProviderPathsFromMonadPath(
path,
true,
newContext,
out provider,
out providerInstance);
if (providerPaths.Count > 0)
{
// Get the dynamic parameters for the first resolved path
return SetPropertyDynamicParameters(providerInstance, providerPaths[0], propertyValue, newContext);
}
return null;
}
/// <summary>
/// Gets the dynamic parameters for the set-itemproperty cmdlet.
/// </summary>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="propertyValue">
/// The value of the property to set.
/// </param>
/// <param name="providerInstance">
/// The instance of the provider to use.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <returns>
/// An object that has properties and fields decorated with
/// parsing attributes similar to a cmdlet class.
/// </returns>
/// <exception cref="NotSupportedException">
/// If the <paramref name="providerInstance"/> does not support this operation.
/// </exception>
/// <exception cref="PipelineStoppedException">
/// If the pipeline is being stopped while executing the command.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
private object SetPropertyDynamicParameters(
CmdletProvider providerInstance,
string path,
PSObject propertyValue,
CmdletProviderContext context)
{
// All parameters should have been validated by caller
Dbg.Diagnostics.Assert(
providerInstance != null,
"Caller should validate providerInstance before calling this method");
Dbg.Diagnostics.Assert(
path != null,
"Caller should validate path before calling this method");
Dbg.Diagnostics.Assert(
context != null,
"Caller should validate context before calling this method");
object result = null;
try
{
result = providerInstance.SetPropertyDynamicParameters(path, propertyValue, context);
}
catch (NotSupportedException)
{
throw;
}
catch (LoopFlowException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
catch (Exception e) // Catch-all OK, 3rd party callout.
{
throw NewProviderInvocationException(
"SetPropertyDynamicParametersProviderException",
SessionStateStrings.SetPropertyDynamicParametersProviderException,
providerInstance.ProviderInfo,
path,
e);
}
return result;
}
#endregion SetProperty
#region ClearProperty
/// <summary>
/// Clears the specified property on the specified item.
/// </summary>
/// <param name="paths">
/// The path(s) to the item(s) to clear the property on.
/// </param>
/// <param name="propertyToClear">
/// The name of the property to clear.
/// </param>
/// <param name="force">
/// Passed on to providers to force operations.
/// </param>
/// <param name="literalPath">
/// If true, globbing is not done on paths.
/// </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="path"/> or <paramref name="propertyToClear"/> is null.
/// </exception>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
internal void ClearProperty(
string[] paths,
Collection<string> propertyToClear,
bool force,
bool literalPath)
{
if (paths == null)
{
throw PSTraceSource.NewArgumentNullException("paths");
}
if (propertyToClear == null)
{
throw PSTraceSource.NewArgumentNullException("propertyToClear");
}
CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext);
context.Force = force;
context.SuppressWildcardExpansion = literalPath;
ClearProperty(paths, propertyToClear, context);
context.ThrowFirstErrorOrDoNothing();
}
/// <summary>
/// Clears the specified property in the specified item.
/// </summary>
/// <param name="paths">
/// The path(s) to the item(s) to clear the property on.
/// </param>
/// <param name="propertyToClear">
/// A property table containing the property to clear.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="path"/> or <paramref name="propertyToClear"/> is null.
/// </exception>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
/// <exception cref="ItemNotFoundException">
/// If <paramref name="path"/> does not contain glob characters and
/// could not be found.
/// </exception>
internal void ClearProperty(
string[] paths,
Collection<string> propertyToClear,
CmdletProviderContext context)
{
if (paths == null)
{
throw PSTraceSource.NewArgumentNullException("paths");
}
if (propertyToClear == null)
{
throw PSTraceSource.NewArgumentNullException("propertyToClear");
}
foreach (string path in paths)
{
if (path == null)
{
throw PSTraceSource.NewArgumentNullException("paths");
}
ProviderInfo provider = null;
CmdletProvider providerInstance = null;
Collection<string> providerPaths =
Globber.GetGlobbedProviderPathsFromMonadPath(
path,
false,
context,
out provider,
out providerInstance);
foreach (string providerPath in providerPaths)
{
ClearPropertyPrivate(providerInstance, providerPath, propertyToClear, context);
}
}
}
/// <summary>
/// Clears the value of the property from the item at the specified path.
/// </summary>
/// <param name="providerInstance">
/// The provider instance to use.
/// </param>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="propertyToClear">
/// The name of the property to clear.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <exception cref="NotSupportedException">
/// If the <paramref name="providerInstance"/> does not support this operation.
/// </exception>
/// <exception cref="PipelineStoppedException">
/// If the pipeline is being stopped while executing the command.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
private void ClearPropertyPrivate(
CmdletProvider providerInstance,
string path,
Collection<string> propertyToClear,
CmdletProviderContext context)
{
// All parameters should have been validated by caller
Dbg.Diagnostics.Assert(
providerInstance != null,
"Caller should validate providerInstance before calling this method");
Dbg.Diagnostics.Assert(
path != null,
"Caller should validate path before calling this method");
Dbg.Diagnostics.Assert(
propertyToClear != null,
"Caller should validate propertyToClear before calling this method");
Dbg.Diagnostics.Assert(
context != null,
"Caller should validate context before calling this method");
try
{
providerInstance.ClearProperty(path, propertyToClear, context);
}
catch (NotSupportedException)
{
throw;
}
catch (LoopFlowException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
catch (Exception e) // Catch-all OK, 3rd party callout.
{
throw NewProviderInvocationException(
"ClearPropertyProviderException",
SessionStateStrings.ClearPropertyProviderException,
providerInstance.ProviderInfo,
path,
e);
}
}
/// <summary>
/// Gets the dynamic parameters for the clear-itemproperty cmdlet.
/// </summary>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="propertyToClear">
/// A property table containing the property to clear.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <returns>
/// An object that has properties and fields decorated with
/// parsing attributes similar to a cmdlet class.
/// </returns>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
/// <exception cref="ItemNotFoundException">
/// If <paramref name="path"/> does not contain glob characters and
/// could not be found.
/// </exception>
internal object ClearPropertyDynamicParameters(
string path,
Collection<string> propertyToClear,
CmdletProviderContext context)
{
if (path == null)
{
return null;
}
ProviderInfo provider = null;
CmdletProvider providerInstance = null;
CmdletProviderContext newContext =
new CmdletProviderContext(context);
newContext.SetFilters(
new Collection<string>(),
new Collection<string>(),
null);
Collection<string> providerPaths =
Globber.GetGlobbedProviderPathsFromMonadPath(
path,
true,
newContext,
out provider,
out providerInstance);
if (providerPaths.Count > 0)
{
// Get the dynamic parameters for the first resolved path
return ClearPropertyDynamicParameters(providerInstance, providerPaths[0], propertyToClear, newContext);
}
return null;
}
/// <summary>
/// Gets the dynamic parameters for the clear-itemproperty cmdlet.
/// </summary>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="propertyToClear">
/// The name of the property to clear.
/// </param>
/// <param name="providerInstance">
/// The instance of the provider to use.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <returns>
/// An object that has properties and fields decorated with
/// parsing attributes similar to a cmdlet class.
/// </returns>
/// <exception cref="NotSupportedException">
/// If the <paramref name="providerInstance"/> does not support this operation.
/// </exception>
/// <exception cref="PipelineStoppedException">
/// If the pipeline is being stopped while executing the command.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
private object ClearPropertyDynamicParameters(
CmdletProvider providerInstance,
string path,
Collection<string> propertyToClear,
CmdletProviderContext context)
{
// All parameters should have been validated by caller
Dbg.Diagnostics.Assert(
providerInstance != null,
"Caller should validate providerInstance before calling this method");
Dbg.Diagnostics.Assert(
path != null,
"Caller should validate path before calling this method");
Dbg.Diagnostics.Assert(
context != null,
"Caller should validate context before calling this method");
object result = null;
try
{
result = providerInstance.ClearPropertyDynamicParameters(path, propertyToClear, context);
}
catch (NotSupportedException)
{
throw;
}
catch (LoopFlowException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
catch (Exception e) // Catch-all OK, 3rd party callout.
{
throw NewProviderInvocationException(
"ClearPropertyDynamicParametersProviderException",
SessionStateStrings.ClearPropertyDynamicParametersProviderException,
providerInstance.ProviderInfo,
path,
e);
}
return result;
}
#endregion ClearProperty
#endregion IPropertyCmdletProvider accessors
}
}
#pragma warning restore 56500
| |
// 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.Contracts;
namespace System.Threading
{
public delegate void TimerCallback(Object state);
//
// TimerQueue maintains a list of active timers in this AppDomain. We use a single native timer to schedule
// all managed timers in the process.
//
// Perf assumptions: We assume that timers are created and destroyed frequently, but rarely actually fire.
// There are roughly two types of timer:
//
// - timeouts for operations. These are created and destroyed very frequently, but almost never fire, because
// the whole point is that the timer only fires if something has gone wrong.
//
// - scheduled background tasks. These typically do fire, but they usually have quite long durations.
// So the impact of spending a few extra cycles to fire these is negligible.
//
// Because of this, we want to choose a data structure with very fast insert and delete times, but we can live
// with linear traversal times when firing timers.
//
// The data structure we've chosen is an unordered doubly-linked list of active timers. This gives O(1) insertion
// and removal, and O(N) traversal when finding expired timers.
//
// Note that all instance methods of this class require that the caller hold a lock on TimerQueue.Instance.
//
internal partial class TimerQueue
{
#region singleton pattern implementation
// The one-and-only TimerQueue for the AppDomain.
private static TimerQueue s_queue = new TimerQueue();
public static TimerQueue Instance
{
get { return s_queue; }
}
private TimerQueue()
{
// empty private constructor to ensure we remain a singleton.
}
#endregion
#region interface to native per-AppDomain timer
private int _currentNativeTimerStartTicks;
private uint _currentNativeTimerDuration = UInt32.MaxValue;
private void EnsureAppDomainTimerFiresBy(uint requestedDuration)
{
//
// The CLR VM's timer implementation does not work well for very long-duration timers.
// See kb 950807.
// So we'll limit our native timer duration to a "small" value.
// This may cause us to attempt to fire timers early, but that's ok -
// we'll just see that none of our timers has actually reached its due time,
// and schedule the native timer again.
//
const uint maxPossibleDuration = 0x0fffffff;
uint actualDuration = Math.Min(requestedDuration, maxPossibleDuration);
if (_currentNativeTimerDuration != UInt32.MaxValue)
{
uint elapsed = (uint)(TickCount - _currentNativeTimerStartTicks);
if (elapsed >= _currentNativeTimerDuration)
return; //the timer's about to fire
uint remainingDuration = _currentNativeTimerDuration - elapsed;
if (actualDuration >= remainingDuration)
return; //the timer will fire earlier than this request
}
SetTimer(actualDuration);
_currentNativeTimerDuration = actualDuration;
_currentNativeTimerStartTicks = TickCount;
}
#endregion
#region Firing timers
//
// The list of timers
//
private TimerQueueTimer _timers;
readonly internal Lock Lock = new Lock();
//
// Fire any timers that have expired, and update the native timer to schedule the rest of them.
//
private void FireNextTimers()
{
//
// we fire the first timer on this thread; any other timers that might have fired are queued
// to the ThreadPool.
//
TimerQueueTimer timerToFireOnThisThread = null;
using (LockHolder.Hold(Lock))
{
//
// since we got here, that means our previous timer has fired.
//
_currentNativeTimerDuration = UInt32.MaxValue;
bool haveTimerToSchedule = false;
uint nextAppDomainTimerDuration = uint.MaxValue;
int nowTicks = TickCount;
//
// Sweep through all timers. The ones that have reached their due time
// will fire. We will calculate the next native timer due time from the
// other timers.
//
TimerQueueTimer timer = _timers;
while (timer != null)
{
Debug.Assert(timer.m_dueTime != Timeout.UnsignedInfinite);
uint elapsed = (uint)(nowTicks - timer.m_startTicks);
if (elapsed >= timer.m_dueTime)
{
//
// Remember the next timer in case we delete this one
//
TimerQueueTimer nextTimer = timer.m_next;
if (timer.m_period != Timeout.UnsignedInfinite)
{
timer.m_startTicks = nowTicks;
uint elapsedForNextDueTime = elapsed - timer.m_dueTime;
if (elapsedForNextDueTime < timer.m_period)
{
// Discount the extra time that has elapsed since the previous firing
// to prevent the timer ticks from drifting
timer.m_dueTime = timer.m_period - elapsedForNextDueTime;
}
else
{
// Enough time has elapsed to fire the timer yet again. The timer is not able to keep up
// with the short period, have it fire 1 ms from now to avoid spnning without delay.
timer.m_dueTime = 1;
}
//
// This is a repeating timer; schedule it to run again.
//
if (timer.m_dueTime < nextAppDomainTimerDuration)
{
haveTimerToSchedule = true;
nextAppDomainTimerDuration = timer.m_dueTime;
}
}
else
{
//
// Not repeating; remove it from the queue
//
DeleteTimer(timer);
}
//
// If this is the first timer, we'll fire it on this thread. Otherwise, queue it
// to the ThreadPool.
//
if (timerToFireOnThisThread == null)
timerToFireOnThisThread = timer;
else
QueueTimerCompletion(timer);
timer = nextTimer;
}
else
{
//
// This timer hasn't fired yet. Just update the next time the native timer fires.
//
uint remaining = timer.m_dueTime - elapsed;
if (remaining < nextAppDomainTimerDuration)
{
haveTimerToSchedule = true;
nextAppDomainTimerDuration = remaining;
}
timer = timer.m_next;
}
}
if (haveTimerToSchedule)
EnsureAppDomainTimerFiresBy(nextAppDomainTimerDuration);
}
//
// Fire the user timer outside of the lock!
//
if (timerToFireOnThisThread != null)
timerToFireOnThisThread.Fire();
}
private static void QueueTimerCompletion(TimerQueueTimer timer)
{
WaitCallback callback = s_fireQueuedTimerCompletion;
if (callback == null)
s_fireQueuedTimerCompletion = callback = new WaitCallback(FireQueuedTimerCompletion);
// Can use "unsafe" variant because we take care of capturing and restoring
// the ExecutionContext.
ThreadPool.UnsafeQueueUserWorkItem(callback, timer);
}
private static WaitCallback s_fireQueuedTimerCompletion;
private static void FireQueuedTimerCompletion(object state)
{
((TimerQueueTimer)state).Fire();
}
#endregion
#region Queue implementation
public bool UpdateTimer(TimerQueueTimer timer, uint dueTime, uint period)
{
if (timer.m_dueTime == Timeout.UnsignedInfinite)
{
// the timer is not in the list; add it (as the head of the list).
timer.m_next = _timers;
timer.m_prev = null;
if (timer.m_next != null)
timer.m_next.m_prev = timer;
_timers = timer;
}
timer.m_dueTime = dueTime;
timer.m_period = (period == 0) ? Timeout.UnsignedInfinite : period;
timer.m_startTicks = TickCount;
EnsureAppDomainTimerFiresBy(dueTime);
return true;
}
public void DeleteTimer(TimerQueueTimer timer)
{
if (timer.m_dueTime != Timeout.UnsignedInfinite)
{
if (timer.m_next != null)
timer.m_next.m_prev = timer.m_prev;
if (timer.m_prev != null)
timer.m_prev.m_next = timer.m_next;
if (_timers == timer)
_timers = timer.m_next;
timer.m_dueTime = Timeout.UnsignedInfinite;
timer.m_period = Timeout.UnsignedInfinite;
timer.m_startTicks = 0;
timer.m_prev = null;
timer.m_next = null;
}
}
#endregion
}
//
// A timer in our TimerQueue.
//
internal sealed partial class TimerQueueTimer
{
//
// All fields of this class are protected by a lock on TimerQueue.Instance.
//
// The first four fields are maintained by TimerQueue itself.
//
internal TimerQueueTimer m_next;
internal TimerQueueTimer m_prev;
//
// The time, according to TimerQueue.TickCount, when this timer's current interval started.
//
internal int m_startTicks;
//
// Timeout.UnsignedInfinite if we are not going to fire. Otherwise, the offset from m_startTime when we will fire.
//
internal uint m_dueTime;
//
// Timeout.UnsignedInfinite if we are a single-shot timer. Otherwise, the repeat interval.
//
internal uint m_period;
//
// Info about the user's callback
//
private readonly TimerCallback _timerCallback;
private readonly Object _state;
private readonly ExecutionContext _executionContext;
//
// When Timer.Dispose(WaitHandle) is used, we need to signal the wait handle only
// after all pending callbacks are complete. We set _canceled to prevent any callbacks that
// are already queued from running. We track the number of callbacks currently executing in
// _callbacksRunning. We set _notifyWhenNoCallbacksRunning only when _callbacksRunning
// reaches zero.
//
private int _callbacksRunning;
private volatile bool _canceled;
private volatile WaitHandle _notifyWhenNoCallbacksRunning;
internal TimerQueueTimer(TimerCallback timerCallback, object state, uint dueTime, uint period)
{
_timerCallback = timerCallback;
_state = state;
m_dueTime = Timeout.UnsignedInfinite;
m_period = Timeout.UnsignedInfinite;
_executionContext = ExecutionContext.Capture();
//
// After the following statement, the timer may fire. No more manipulation of timer state outside of
// the lock is permitted beyond this point!
//
if (dueTime != Timeout.UnsignedInfinite)
Change(dueTime, period);
}
internal bool Change(uint dueTime, uint period)
{
bool success;
using (LockHolder.Hold(TimerQueue.Instance.Lock))
{
if (_canceled)
throw new ObjectDisposedException(null, SR.ObjectDisposed_Generic);
m_period = period;
if (dueTime == Timeout.UnsignedInfinite)
{
TimerQueue.Instance.DeleteTimer(this);
success = true;
}
else
{
success = TimerQueue.Instance.UpdateTimer(this, dueTime, period);
}
}
return success;
}
public void Close()
{
using (LockHolder.Hold(TimerQueue.Instance.Lock))
{
if (!_canceled)
{
_canceled = true;
TimerQueue.Instance.DeleteTimer(this);
}
}
}
public bool Close(WaitHandle toSignal)
{
bool success;
bool shouldSignal = false;
using (LockHolder.Hold(TimerQueue.Instance.Lock))
{
if (_canceled)
{
success = false;
}
else
{
_canceled = true;
_notifyWhenNoCallbacksRunning = toSignal;
TimerQueue.Instance.DeleteTimer(this);
if (_callbacksRunning == 0)
shouldSignal = true;
success = true;
}
}
if (shouldSignal)
SignalNoCallbacksRunning();
return success;
}
internal void Fire()
{
bool canceled = false;
lock (TimerQueue.Instance)
{
canceled = _canceled;
if (!canceled)
_callbacksRunning++;
}
if (canceled)
return;
CallCallback();
bool shouldSignal = false;
using (LockHolder.Hold(TimerQueue.Instance.Lock))
{
_callbacksRunning--;
if (_canceled && _callbacksRunning == 0 && _notifyWhenNoCallbacksRunning != null)
shouldSignal = true;
}
if (shouldSignal)
SignalNoCallbacksRunning();
}
internal void CallCallback()
{
ContextCallback callback = s_callCallbackInContext;
if (callback == null)
s_callCallbackInContext = callback = new ContextCallback(CallCallbackInContext);
// call directly if EC flow is suppressed
if (_executionContext == null)
{
_timerCallback(_state);
}
else
{
ExecutionContext.Run(_executionContext, callback, this);
}
}
private static ContextCallback s_callCallbackInContext;
private static void CallCallbackInContext(object state)
{
TimerQueueTimer t = (TimerQueueTimer)state;
t._timerCallback(t._state);
}
}
//
// TimerHolder serves as an intermediary between Timer and TimerQueueTimer, releasing the TimerQueueTimer
// if the Timer is collected.
// This is necessary because Timer itself cannot use its finalizer for this purpose. If it did,
// then users could control timer lifetimes using GC.SuppressFinalize/ReRegisterForFinalize.
// You might ask, wouldn't that be a good thing? Maybe (though it would be even better to offer this
// via first-class APIs), but Timer has never offered this, and adding it now would be a breaking
// change, because any code that happened to be suppressing finalization of Timer objects would now
// unwittingly be changing the lifetime of those timers.
//
internal sealed class TimerHolder
{
internal TimerQueueTimer m_timer;
public TimerHolder(TimerQueueTimer timer)
{
m_timer = timer;
}
~TimerHolder()
{
m_timer.Close();
}
public void Close()
{
m_timer.Close();
GC.SuppressFinalize(this);
}
public bool Close(WaitHandle notifyObject)
{
bool result = m_timer.Close(notifyObject);
GC.SuppressFinalize(this);
return result;
}
}
public sealed class Timer : MarshalByRefObject, IDisposable
{
private const UInt32 MAX_SUPPORTED_TIMEOUT = (uint)0xfffffffe;
private TimerHolder _timer;
public Timer(TimerCallback callback,
Object state,
int dueTime,
int period)
{
if (dueTime < -1)
throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (period < -1)
throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
Contract.EndContractBlock();
TimerSetup(callback, state, (UInt32)dueTime, (UInt32)period);
}
public Timer(TimerCallback callback,
Object state,
TimeSpan dueTime,
TimeSpan period)
{
long dueTm = (long)dueTime.TotalMilliseconds;
if (dueTm < -1)
throw new ArgumentOutOfRangeException(nameof(dueTm), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (dueTm > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException(nameof(dueTm), SR.ArgumentOutOfRange_TimeoutTooLarge);
long periodTm = (long)period.TotalMilliseconds;
if (periodTm < -1)
throw new ArgumentOutOfRangeException(nameof(periodTm), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (periodTm > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException(nameof(periodTm), SR.ArgumentOutOfRange_PeriodTooLarge);
TimerSetup(callback, state, (UInt32)dueTm, (UInt32)periodTm);
}
[CLSCompliant(false)]
public Timer(TimerCallback callback,
Object state,
UInt32 dueTime,
UInt32 period)
{
TimerSetup(callback, state, dueTime, period);
}
public Timer(TimerCallback callback,
Object state,
long dueTime,
long period)
{
if (dueTime < -1)
throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (period < -1)
throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (dueTime > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_TimeoutTooLarge);
if (period > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_PeriodTooLarge);
Contract.EndContractBlock();
TimerSetup(callback, state, (UInt32)dueTime, (UInt32)period);
}
public Timer(TimerCallback callback)
{
int dueTime = -1; // we want timer to be registered, but not activated. Requires caller to call
int period = -1; // Change after a timer instance is created. This is to avoid the potential
// for a timer to be fired before the returned value is assigned to the variable,
// potentially causing the callback to reference a bogus value (if passing the timer to the callback).
TimerSetup(callback, this, (UInt32)dueTime, (UInt32)period);
}
private void TimerSetup(TimerCallback callback,
Object state,
UInt32 dueTime,
UInt32 period)
{
if (callback == null)
throw new ArgumentNullException(nameof(TimerCallback));
Contract.EndContractBlock();
_timer = new TimerHolder(new TimerQueueTimer(callback, state, dueTime, period));
}
public bool Change(int dueTime, int period)
{
if (dueTime < -1)
throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (period < -1)
throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
Contract.EndContractBlock();
return _timer.m_timer.Change((UInt32)dueTime, (UInt32)period);
}
public bool Change(TimeSpan dueTime, TimeSpan period)
{
return Change((long)dueTime.TotalMilliseconds, (long)period.TotalMilliseconds);
}
[CLSCompliant(false)]
public bool Change(UInt32 dueTime, UInt32 period)
{
return _timer.m_timer.Change(dueTime, period);
}
public bool Change(long dueTime, long period)
{
if (dueTime < -1)
throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (period < -1)
throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (dueTime > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_TimeoutTooLarge);
if (period > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_PeriodTooLarge);
Contract.EndContractBlock();
return _timer.m_timer.Change((UInt32)dueTime, (UInt32)period);
}
public bool Dispose(WaitHandle notifyObject)
{
if (notifyObject == null)
throw new ArgumentNullException(nameof(notifyObject));
Contract.EndContractBlock();
return _timer.Close(notifyObject);
}
public void Dispose()
{
_timer.Close();
}
internal void KeepRootedWhileScheduled()
{
GC.SuppressFinalize(_timer);
}
}
}
| |
#region --- License ---
/*
Copyright (c) 2006 - 2008 The Open Toolkit library.
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.IO;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Xml.Serialization;
namespace Picodex.Render.Unity
{
/// <summary>
/// 3-component Vector of the Half type. Occupies 6 Byte total.
/// </summary>
[Serializable, StructLayout(LayoutKind.Sequential)]
public struct Vector3h : ISerializable, IEquatable<Vector3h>
{
#region Public Fields
/// <summary>The X component of the Half3.</summary>
public Half X;
/// <summary>The Y component of the Half3.</summary>
public Half Y;
/// <summary>The Z component of the Half3.</summary>
public Half Z;
#endregion Public Fields
#region Constructors
/// <summary>
/// Constructs a new instance.
/// </summary>
/// <param name="value">The value that will initialize this instance.</param>
public Vector3h(Half value)
{
X = value;
Y = value;
Z = value;
}
/// <summary>
/// Constructs a new instance.
/// </summary>
/// <param name="value">The value that will initialize this instance.</param>
public Vector3h(Single value)
{
X = new Half(value);
Y = new Half(value);
Z = new Half(value);
}
/// <summary>
/// The new Half3 instance will avoid conversion and copy directly from the Half parameters.
/// </summary>
/// <param name="x">An Half instance of a 16-bit half-precision floating-point number.</param>
/// <param name="y">An Half instance of a 16-bit half-precision floating-point number.</param>
/// <param name="z">An Half instance of a 16-bit half-precision floating-point number.</param>
public Vector3h(Half x, Half y, Half z)
{
this.X = x;
this.Y = y;
this.Z = z;
}
/// <summary>
/// The new Half3 instance will convert the 3 parameters into 16-bit half-precision floating-point.
/// </summary>
/// <param name="x">32-bit single-precision floating-point number.</param>
/// <param name="y">32-bit single-precision floating-point number.</param>
/// <param name="z">32-bit single-precision floating-point number.</param>
public Vector3h(Single x, Single y, Single z)
{
X = new Half(x);
Y = new Half(y);
Z = new Half(z);
}
/// <summary>
/// The new Half3 instance will convert the 3 parameters into 16-bit half-precision floating-point.
/// </summary>
/// <param name="x">32-bit single-precision floating-point number.</param>
/// <param name="y">32-bit single-precision floating-point number.</param>
/// <param name="z">32-bit single-precision floating-point number.</param>
/// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param>
public Vector3h(Single x, Single y, Single z, bool throwOnError)
{
X = new Half(x, throwOnError);
Y = new Half(y, throwOnError);
Z = new Half(z, throwOnError);
}
/// <summary>
/// The new Half3 instance will convert the Vector3 into 16-bit half-precision floating-point.
/// </summary>
/// <param name="v">OpenTK.Vector3</param>
[CLSCompliant(false)]
public Vector3h(Vector3 v)
{
X = new Half(v.X);
Y = new Half(v.Y);
Z = new Half(v.Z);
}
/// <summary>
/// The new Half3 instance will convert the Vector3 into 16-bit half-precision floating-point.
/// </summary>
/// <param name="v">OpenTK.Vector3</param>
/// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param>
[CLSCompliant(false)]
public Vector3h(Vector3 v, bool throwOnError)
{
X = new Half(v.X, throwOnError);
Y = new Half(v.Y, throwOnError);
Z = new Half(v.Z, throwOnError);
}
/// <summary>
/// The new Half3 instance will convert the Vector3 into 16-bit half-precision floating-point.
/// This is the fastest constructor.
/// </summary>
/// <param name="v">OpenTK.Vector3</param>
public Vector3h(ref Vector3 v)
{
X = new Half(v.X);
Y = new Half(v.Y);
Z = new Half(v.Z);
}
/// <summary>
/// The new Half3 instance will convert the Vector3 into 16-bit half-precision floating-point.
/// </summary>
/// <param name="v">OpenTK.Vector3</param>
/// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param>
[CLSCompliant(false)]
public Vector3h(ref Vector3 v, bool throwOnError)
{
X = new Half(v.X, throwOnError);
Y = new Half(v.Y, throwOnError);
Z = new Half(v.Z, throwOnError);
}
/// <summary>
/// The new Half3 instance will convert the Vector3d into 16-bit half-precision floating-point.
/// </summary>
/// <param name="v">OpenTK.Vector3d</param>
[CLSCompliant(false)]
public Vector3h(Vector3d v)
{
X = new Half(v.X);
Y = new Half(v.Y);
Z = new Half(v.Z);
}
/// <summary>
/// The new Half3 instance will convert the Vector3d into 16-bit half-precision floating-point.
/// </summary>
/// <param name="v">OpenTK.Vector3d</param>
/// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param>
[CLSCompliant(false)]
public Vector3h(Vector3d v, bool throwOnError)
{
X = new Half(v.X, throwOnError);
Y = new Half(v.Y, throwOnError);
Z = new Half(v.Z, throwOnError);
}
/// <summary>
/// The new Half3 instance will convert the Vector3d into 16-bit half-precision floating-point.
/// This is the faster constructor.
/// </summary>
/// <param name="v">OpenTK.Vector3d</param>
[CLSCompliant(false)]
public Vector3h(ref Vector3d v)
{
X = new Half(v.X);
Y = new Half(v.Y);
Z = new Half(v.Z);
}
/// <summary>
/// The new Half3 instance will convert the Vector3d into 16-bit half-precision floating-point.
/// </summary>
/// <param name="v">OpenTK.Vector3d</param>
/// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param>
[CLSCompliant(false)]
public Vector3h(ref Vector3d v, bool throwOnError)
{
X = new Half(v.X, throwOnError);
Y = new Half(v.Y, throwOnError);
Z = new Half(v.Z, throwOnError);
}
#endregion Constructors
#region Swizzle
#region 2-component
/// <summary>
/// Gets or sets an OpenTK.Vector2h with the X and Y components of this instance.
/// </summary>
[XmlIgnore]
public Vector2h Xy { get { return new Vector2h(X, Y); } set { X = value.X; Y = value.Y; } }
/// <summary>
/// Gets or sets an OpenTK.Vector2h with the X and Z components of this instance.
/// </summary>
[XmlIgnore]
public Vector2h Xz { get { return new Vector2h(X, Z); } set { X = value.X; Z = value.Y; } }
/// <summary>
/// Gets or sets an OpenTK.Vector2h with the Y and X components of this instance.
/// </summary>
[XmlIgnore]
public Vector2h Yx { get { return new Vector2h(Y, X); } set { Y = value.X; X = value.Y; } }
/// <summary>
/// Gets or sets an OpenTK.Vector2h with the Y and Z components of this instance.
/// </summary>
[XmlIgnore]
public Vector2h Yz { get { return new Vector2h(Y, Z); } set { Y = value.X; Z = value.Y; } }
/// <summary>
/// Gets or sets an OpenTK.Vector2h with the Z and X components of this instance.
/// </summary>
[XmlIgnore]
public Vector2h Zx { get { return new Vector2h(Z, X); } set { Z = value.X; X = value.Y; } }
/// <summary>
/// Gets or sets an OpenTK.Vector2h with the Z and Y components of this instance.
/// </summary>
[XmlIgnore]
public Vector2h Zy { get { return new Vector2h(Z, Y); } set { Z = value.X; Y = value.Y; } }
#endregion
#region 3-component
/// <summary>
/// Gets or sets an OpenTK.Vector3h with the X, Z, and Y components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Xzy { get { return new Vector3h(X, Z, Y); } set { X = value.X; Z = value.Y; Y = value.Z; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3h with the Y, X, and Z components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Yxz { get { return new Vector3h(Y, X, Z); } set { Y = value.X; X = value.Y; Z = value.Z; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3h with the Y, Z, and X components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Yzx { get { return new Vector3h(Y, Z, X); } set { Y = value.X; Z = value.Y; X = value.Z; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3h with the Z, X, and Y components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Zxy { get { return new Vector3h(Z, X, Y); } set { Z = value.X; X = value.Y; Y = value.Z; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3h with the Z, Y, and X components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Zyx { get { return new Vector3h(Z, Y, X); } set { Z = value.X; Y = value.Y; X = value.Z; } }
#endregion
#endregion
#region Half -> Single
/// <summary>
/// Returns this Half3 instance's contents as Vector3.
/// </summary>
/// <returns>OpenTK.Vector3</returns>
public Vector3 ToVector3()
{
return new Vector3(X, Y, Z);
}
/// <summary>
/// Returns this Half3 instance's contents as Vector3d.
/// </summary>
public Vector3d ToVector3d()
{
return new Vector3d(X, Y, Z);
}
#endregion Half -> Single
#region Conversions
/// <summary>Converts OpenTK.Vector3 to OpenTK.Half3.</summary>
/// <param name="v3f">The Vector3 to convert.</param>
/// <returns>The resulting Half vector.</returns>
public static explicit operator Vector3h(Vector3 v3f)
{
return new Vector3h(v3f);
}
/// <summary>Converts OpenTK.Vector3d to OpenTK.Half3.</summary>
/// <param name="v3d">The Vector3d to convert.</param>
/// <returns>The resulting Half vector.</returns>
public static explicit operator Vector3h(Vector3d v3d)
{
return new Vector3h(v3d);
}
/// <summary>Converts OpenTK.Half3 to OpenTK.Vector3.</summary>
/// <param name="h3">The Half3 to convert.</param>
/// <returns>The resulting Vector3.</returns>
public static explicit operator Vector3(Vector3h h3)
{
Vector3 result = new Vector3();
result.X = h3.X.ToSingle();
result.Y = h3.Y.ToSingle();
result.Z = h3.Z.ToSingle();
return result;
}
/// <summary>Converts OpenTK.Half3 to OpenTK.Vector3d.</summary>
/// <param name="h3">The Half3 to convert.</param>
/// <returns>The resulting Vector3d.</returns>
public static explicit operator Vector3d(Vector3h h3)
{
Vector3d result = new Vector3d();
result.X = h3.X.ToSingle();
result.Y = h3.Y.ToSingle();
result.Z = h3.Z.ToSingle();
return result;
}
#endregion Conversions
#region Constants
/// <summary>The size in bytes for an instance of the Half3 struct is 6.</summary>
public static readonly int SizeInBytes = 6;
#endregion Constants
#region ISerializable
/// <summary>Constructor used by ISerializable to deserialize the object.</summary>
/// <param name="info"></param>
/// <param name="context"></param>
public Vector3h(SerializationInfo info, StreamingContext context)
{
this.X = (Half)info.GetValue("X", typeof(Half));
this.Y = (Half)info.GetValue("Y", typeof(Half));
this.Z = (Half)info.GetValue("Z", typeof(Half));
}
/// <summary>Used by ISerialize to serialize the object.</summary>
/// <param name="info"></param>
/// <param name="context"></param>
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("X", this.X);
info.AddValue("Y", this.Y);
info.AddValue("Z", this.Z);
}
#endregion ISerializable
#region Binary dump
/// <summary>Updates the X,Y and Z components of this instance by reading from a Stream.</summary>
/// <param name="bin">A BinaryReader instance associated with an open Stream.</param>
public void FromBinaryStream(BinaryReader bin)
{
X.FromBinaryStream(bin);
Y.FromBinaryStream(bin);
Z.FromBinaryStream(bin);
}
/// <summary>Writes the X,Y and Z components of this instance into a Stream.</summary>
/// <param name="bin">A BinaryWriter instance associated with an open Stream.</param>
public void ToBinaryStream(BinaryWriter bin)
{
X.ToBinaryStream(bin);
Y.ToBinaryStream(bin);
Z.ToBinaryStream(bin);
}
#endregion Binary dump
#region IEquatable<Half3> Members
/// <summary>Returns a value indicating whether this instance is equal to a specified OpenTK.Half3 vector.</summary>
/// <param name="other">OpenTK.Half3 to compare to this instance..</param>
/// <returns>True, if other is equal to this instance; false otherwise.</returns>
public bool Equals(Vector3h other)
{
return (this.X.Equals(other.X) && this.Y.Equals(other.Y) && this.Z.Equals(other.Z));
}
#endregion
#region ToString()
private static string listSeparator = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator;
/// <summary>Returns a string that contains this Half3's numbers in human-legible form.</summary>
public override string ToString()
{
return String.Format("({0}{3} {1}{3} {2})", X.ToString(), Y.ToString(), Z.ToString(), listSeparator);
}
#endregion ToString()
#region BitConverter
/// <summary>Returns the Half3 as an array of bytes.</summary>
/// <param name="h">The Half3 to convert.</param>
/// <returns>The input as byte array.</returns>
public static byte[] GetBytes(Vector3h h)
{
byte[] result = new byte[SizeInBytes];
byte[] temp = Half.GetBytes(h.X);
result[0] = temp[0];
result[1] = temp[1];
temp = Half.GetBytes(h.Y);
result[2] = temp[0];
result[3] = temp[1];
temp = Half.GetBytes(h.Z);
result[4] = temp[0];
result[5] = temp[1];
return result;
}
/// <summary>Converts an array of bytes into Half3.</summary>
/// <param name="value">A Half3 in it's byte[] representation.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A new Half3 instance.</returns>
public static Vector3h FromBytes(byte[] value, int startIndex)
{
Vector3h h3 = new Vector3h();
h3.X = Half.FromBytes(value, startIndex);
h3.Y = Half.FromBytes(value, startIndex + 2);
h3.Z = Half.FromBytes(value, startIndex + 4);
return h3;
}
#endregion BitConverter
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsHead
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
/// <summary>
/// HttpSuccessOperations operations.
/// </summary>
internal partial class HttpSuccessOperations : IServiceOperations<AutoRestHeadTestService>, IHttpSuccessOperations
{
/// <summary>
/// Initializes a new instance of the HttpSuccessOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal HttpSuccessOperations(AutoRestHeadTestService client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestHeadTestService
/// </summary>
public AutoRestHeadTestService Client { get; private set; }
/// <summary>
/// Return 200 status code if successful
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<bool?>> Head200WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// 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, "Head200", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/success/200").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("HEAD");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 404)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<bool?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
_result.Body = (_statusCode == HttpStatusCode.OK);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Return 204 status code if successful
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<bool?>> Head204WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// 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, "Head204", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/success/204").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("HEAD");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204 && (int)_statusCode != 404)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<bool?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
_result.Body = (_statusCode == HttpStatusCode.NoContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Return 404 status code if successful
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<bool?>> Head404WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// 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, "Head404", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/success/404").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("HEAD");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204 && (int)_statusCode != 404)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<bool?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
_result.Body = (_statusCode == HttpStatusCode.NoContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Net;
using Orleans.Runtime.Configuration;
using Orleans.Serialization;
namespace Orleans.Runtime
{
/// <summary>
/// Data class encapsulating the details of silo addresses.
/// </summary>
[Serializable]
[DebuggerDisplay("SiloAddress {ToString()}")]
public class SiloAddress : IEquatable<SiloAddress>, IComparable<SiloAddress>, IComparable
{
internal static readonly int SizeBytes = 24; // 16 for the address, 4 for the port, 4 for the generation
/// <summary> Special constant value to indicate an empty SiloAddress. </summary>
public static SiloAddress Zero { get; private set; }
private const int INTERN_CACHE_INITIAL_SIZE = InternerConstants.SIZE_MEDIUM;
private static readonly TimeSpan internCacheCleanupInterval = TimeSpan.Zero;
private int hashCode = 0;
private bool hashCodeSet = false;
[NonSerialized]
private List<uint> uniformHashCache;
public IPEndPoint Endpoint { get; private set; }
public int Generation { get; private set; }
private const char SEPARATOR = '@';
private static readonly DateTime epoch = new DateTime(2010, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private static readonly Interner<SiloAddress, SiloAddress> siloAddressInterningCache;
private static readonly IPEndPoint localEndpoint = new IPEndPoint(ClusterConfiguration.GetLocalIPAddress(), 0); // non loopback local ip.
static SiloAddress()
{
siloAddressInterningCache = new Interner<SiloAddress, SiloAddress>(INTERN_CACHE_INITIAL_SIZE, internCacheCleanupInterval);
var sa = new SiloAddress(new IPEndPoint(0, 0), 0);
Zero = siloAddressInterningCache.Intern(sa, sa);
}
/// <summary>
/// Factory for creating new SiloAddresses for silo on this machine with specified generation number.
/// </summary>
/// <param name="gen">Generation number of the silo.</param>
/// <returns>SiloAddress object initialized with the non-loopback local IP address and the specified silo generation.</returns>
public static SiloAddress NewLocalAddress(int gen)
{
return New(localEndpoint, gen);
}
/// <summary>
/// Factory for creating new SiloAddresses with specified IP endpoint address and silo generation number.
/// </summary>
/// <param name="ep">IP endpoint address of the silo.</param>
/// <param name="gen">Generation number of the silo.</param>
/// <returns>SiloAddress object initialized with specified address and silo generation.</returns>
public static SiloAddress New(IPEndPoint ep, int gen)
{
var sa = new SiloAddress(ep, gen);
return siloAddressInterningCache.Intern(sa, sa);
}
private SiloAddress(IPEndPoint endpoint, int gen)
{
Endpoint = endpoint;
Generation = gen;
}
public bool IsClient { get { return Generation < 0; } }
/// <summary> Allocate a new silo generation number. </summary>
/// <returns>A new silo generation number.</returns>
public static int AllocateNewGeneration()
{
long elapsed = (DateTime.UtcNow.Ticks - epoch.Ticks) / TimeSpan.TicksPerSecond;
return unchecked((int)elapsed); // Unchecked to truncate any bits beyond the lower 32
}
/// <summary>
/// Return this SiloAddress in a standard string form, suitable for later use with the <c>FromParsableString</c> method.
/// </summary>
/// <returns>SiloAddress in a standard string format.</returns>
public string ToParsableString()
{
// This must be the "inverse" of FromParsableString, and must be the same across all silos in a deployment.
// Basically, this should never change unless the data content of SiloAddress changes
return String.Format("{0}:{1}@{2}", Endpoint.Address, Endpoint.Port, Generation);
}
/// <summary>
/// Create a new SiloAddress object by parsing string in a standard form returned from <c>ToParsableString</c> method.
/// </summary>
/// <param name="addr">String containing the SiloAddress info to be parsed.</param>
/// <returns>New SiloAddress object created from the input data.</returns>
public static SiloAddress FromParsableString(string addr)
{
// This must be the "inverse" of ToParsableString, and must be the same across all silos in a deployment.
// Basically, this should never change unless the data content of SiloAddress changes
// First is the IPEndpoint; then '@'; then the generation
int atSign = addr.LastIndexOf(SEPARATOR);
if (atSign < 0)
{
throw new FormatException("Invalid string SiloAddress: " + addr);
}
var epString = addr.Substring(0, atSign);
var genString = addr.Substring(atSign + 1);
// IPEndpoint is the host, then ':', then the port
int lastColon = epString.LastIndexOf(':');
if (lastColon < 0) throw new FormatException("Invalid string SiloAddress: " + addr);
var hostString = epString.Substring(0, lastColon);
var portString = epString.Substring(lastColon + 1);
var host = IPAddress.Parse(hostString);
int port = Int32.Parse(portString);
return New(new IPEndPoint(host, port), Int32.Parse(genString));
}
/// <summary> Object.ToString method override. </summary>
public override string ToString()
{
return String.Format("{0}{1}:{2}", (IsClient ? "C" : "S"), Endpoint, Generation);
}
/// <summary>
/// Return a long string representation of this SiloAddress.
/// </summary>
/// <remarks>
/// Note: This string value is not comparable with the <c>FromParsableString</c> method -- use the <c>ToParsableString</c> method for that purpose.
/// </remarks>
/// <returns>String representaiton of this SiloAddress.</returns>
public string ToLongString()
{
return ToString();
}
/// <summary>
/// Return a long string representation of this SiloAddress, including it's consistent hash value.
/// </summary>
/// <remarks>
/// Note: This string value is not comparable with the <c>FromParsableString</c> method -- use the <c>ToParsableString</c> method for that purpose.
/// </remarks>
/// <returns>String representaiton of this SiloAddress.</returns>
public string ToStringWithHashCode()
{
return String.Format("{0}/x{1, 8:X8}", ToString(), GetConsistentHashCode());
}
/// <summary> Object.Equals method override. </summary>
public override bool Equals(object obj)
{
return Equals(obj as SiloAddress);
}
/// <summary> Object.GetHashCode method override. </summary>
public override int GetHashCode()
{
// Note that Port cannot be used because Port==0 matches any non-zero Port value for .Equals
return Endpoint.GetHashCode() ^ Generation.GetHashCode();
}
/// <summary>Get a consistent hash value for this silo address.</summary>
/// <returns>Consistent hash value for this silo address.</returns>
public int GetConsistentHashCode()
{
if (hashCodeSet) return hashCode;
// Note that Port cannot be used because Port==0 matches any non-zero Port value for .Equals
string siloAddressInfoToHash = Endpoint + Generation.ToString(CultureInfo.InvariantCulture);
hashCode = Utils.CalculateIdHash(siloAddressInfoToHash);
hashCodeSet = true;
return hashCode;
}
public List<uint> GetUniformHashCodes(int numHashes)
{
if (uniformHashCache != null) return uniformHashCache;
var hashes = new List<uint>();
for (int i = 0; i < numHashes; i++)
{
uint hash = GetUniformHashCode(i);
hashes.Add(hash);
}
uniformHashCache = hashes;
return uniformHashCache;
}
private uint GetUniformHashCode(int extraBit)
{
var writer = new BinaryTokenStreamWriter();
writer.Write(this);
writer.Write(extraBit);
byte[] bytes = writer.ToByteArray();
writer.ReleaseBuffers();
return JenkinsHash.ComputeHash(bytes);
}
/// <summary>
/// Two silo addresses match if they are equal or if one generation or the other is 0
/// </summary>
/// <param name="other"> The other SiloAddress to compare this one with. </param>
/// <returns> Returns <c>true</c> if the two SiloAddresses are considered to match -- if they are equal or if one generation or the other is 0. </returns>
internal bool Matches(SiloAddress other)
{
return other != null && Endpoint.Address.Equals(other.Endpoint.Address) && (Endpoint.Port == other.Endpoint.Port) &&
((Generation == other.Generation) || (Generation == 0) || (other.Generation == 0));
}
#region IEquatable<SiloAddress> Members
/// <summary> IEquatable.Equals method override. </summary>
public bool Equals(SiloAddress other)
{
return other != null && Endpoint.Address.Equals(other.Endpoint.Address) && (Endpoint.Port == other.Endpoint.Port) &&
((Generation == other.Generation));
}
#endregion
// non-generic version of CompareTo is needed by some contexts. Just calls generic version.
public int CompareTo(object obj)
{
return CompareTo((SiloAddress)obj);
}
public int CompareTo(SiloAddress other)
{
if (other == null) return 1;
// Compare Generation first. It gives a cheap and fast way to compare, avoiding allocations
// and is also semantically meaningfull - older silos (with smaller Generation) will appear first in the comparison order.
// Only if Generations are the same, go on to compare Ports and IPAddress (which is more expansive to compare).
// Alternatively, we could compare ConsistentHashCode or UniformHashCode.
int comp = Generation.CompareTo(other.Generation);
if (comp != 0) return comp;
comp = Endpoint.Port.CompareTo(other.Endpoint.Port);
if (comp != 0) return comp;
return CompareIpAddresses(Endpoint.Address, other.Endpoint.Address);
}
// The comparions code is taken from: http://www.codeproject.com/Articles/26550/Extending-the-IPAddress-object-to-allow-relative-c
// Also note that this comparison does not handle semantic equivalence of IPv4 and IPv6 addresses.
// In particular, 127.0.0.1 and::1 are semanticaly the same, but not syntacticaly.
// For more information refer to: http://stackoverflow.com/questions/16618810/compare-ipv4-addresses-in-ipv6-notation
// and http://stackoverflow.com/questions/22187690/ip-address-class-getaddressbytes-method-putting-octets-in-odd-indices-of-the-byt
// and dual stack sockets, described at https://msdn.microsoft.com/en-us/library/system.net.ipaddress.maptoipv6(v=vs.110).aspx
private static int CompareIpAddresses(IPAddress one, IPAddress two)
{
int returnVal = 0;
if (one.AddressFamily == two.AddressFamily)
{
byte[] b1 = one.GetAddressBytes();
byte[] b2 = two.GetAddressBytes();
for (int i = 0; i < b1.Length; i++)
{
if (b1[i] < b2[i])
{
returnVal = -1;
break;
}
else if (b1[i] > b2[i])
{
returnVal = 1;
break;
}
}
}
else
{
returnVal = one.AddressFamily.CompareTo(two.AddressFamily);
}
return returnVal;
}
}
}
| |
using System;
using System.Diagnostics;
using HANDLE = System.IntPtr;
using System.Text;
namespace System.Data.SQLite
{
public partial class Sqlite3
{
/*
** 2006 June 7
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code used to dynamically load extensions into
** the SQLite library.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e
**
*************************************************************************
*/
#if !SQLITE_CORE
//#define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
const int SQLITE_CORE = 1;
#endif
//#include "sqlite3ext.h"
//#include "sqliteInt.h"
//#include <string.h>
#if !SQLITE_OMIT_LOAD_EXTENSION
/*
** Some API routines are omitted when various features are
** excluded from a build of SQLite. Substitute a NULL pointer
** for any missing APIs.
*/
#if !SQLITE_ENABLE_COLUMN_METADATA
//# define sqlite3_column_database_name 0
//# define sqlite3_column_database_name16 0
//# define sqlite3_column_table_name 0
//# define sqlite3_column_table_name16 0
//# define sqlite3_column_origin_name 0
//# define sqlite3_column_origin_name16 0
//# define sqlite3_table_column_metadata 0
#endif
#if SQLITE_OMIT_AUTHORIZATION
//# define sqlite3_set_authorizer 0
#endif
#if SQLITE_OMIT_UTF16
//# define sqlite3_bind_text16 0
//# define sqlite3_collation_needed16 0
//# define sqlite3_column_decltype16 0
//# define sqlite3_column_name16 0
//# define sqlite3_column_text16 0
//# define sqlite3_complete16 0
//# define sqlite3_create_collation16 0
//# define sqlite3_create_function16 0
//# define sqlite3_errmsg16 0
static string sqlite3_errmsg16(sqlite3 db)
{
return "";
}
//# define sqlite3_open16 0
//# define sqlite3_prepare16 0
//# define sqlite3_prepare16_v2 0
//# define sqlite3_result_error16 0
//# define sqlite3_result_text16 0
static void sqlite3_result_text16(sqlite3_context pCtx, string z, int n, dxDel xDel)
{
}
//# define sqlite3_result_text16be 0
//# define sqlite3_result_text16le 0
//# define sqlite3_value_text16 0
//# define sqlite3_value_text16be 0
//# define sqlite3_value_text16le 0
//# define sqlite3_column_database_name16 0
//# define sqlite3_column_table_name16 0
//# define sqlite3_column_origin_name16 0
#endif
#if SQLITE_OMIT_COMPLETE
//# define sqlite3_complete 0
//# define sqlite3_complete16 0
#endif
#if SQLITE_OMIT_DECLTYPE
//# define sqlite3_column_decltype16 0
//# define sqlite3_column_decltype 0
#endif
#if SQLITE_OMIT_PROGRESS_CALLBACK
//# define sqlite3_progress_handler 0
static void sqlite3_progress_handler (sqlite3 db, int nOps, dxProgress xProgress, object pArg){}
#endif
#if SQLITE_OMIT_VIRTUALTABLE
//# define sqlite3_create_module 0
//# define sqlite3_create_module_v2 0
//# define sqlite3_declare_vtab 0
#endif
#if SQLITE_OMIT_SHARED_CACHE
//# define sqlite3_enable_shared_cache 0
#endif
#if SQLITE_OMIT_TRACE
//# define sqlite3_profile 0
//# define sqlite3_trace 0
#endif
#if SQLITE_OMIT_GET_TABLE
//# define //sqlite3_free_table 0
//# define sqlite3_get_table 0
static public int sqlite3_get_table(
sqlite3 db, /* An open database */
string zSql, /* SQL to be evaluated */
ref string[] pazResult, /* Results of the query */
ref int pnRow, /* Number of result rows written here */
ref int pnColumn, /* Number of result columns written here */
ref string pzErrmsg /* Error msg written here */
)
{
return 0;
}
#endif
#if SQLITE_OMIT_INCRBLOB
//#define sqlite3_bind_zeroblob 0
//#define sqlite3_blob_bytes 0
//#define sqlite3_blob_close 0
//#define sqlite3_blob_open 0
//#define sqlite3_blob_read 0
//#define sqlite3_blob_write 0
#endif
/*
** The following structure contains pointers to all SQLite API routines.
** A pointer to this structure is passed into extensions when they are
** loaded so that the extension can make calls back into the SQLite
** library.
**
** When adding new APIs, add them to the bottom of this structure
** in order to preserve backwards compatibility.
**
** Extensions that use newer APIs should first call the
** sqlite3_libversion_number() to make sure that the API they
** intend to use is supported by the library. Extensions should
** also check to make sure that the pointer to the function is
** not NULL before calling it.
*/
public class sqlite3_api_routines
{
public sqlite3 context_db_handle;
};
static sqlite3_api_routines sqlite3Apis = new sqlite3_api_routines();
//{
// sqlite3_aggregate_context,
#if !SQLITE_OMIT_DEPRECATED
/ sqlite3_aggregate_count,
#else
// 0,
#endif
// sqlite3_bind_blob,
// sqlite3_bind_double,
// sqlite3_bind_int,
// sqlite3_bind_int64,
// sqlite3_bind_null,
// sqlite3_bind_parameter_count,
// sqlite3_bind_parameter_index,
// sqlite3_bind_parameter_name,
// sqlite3_bind_text,
// sqlite3_bind_text16,
// sqlite3_bind_value,
// sqlite3_busy_handler,
// sqlite3_busy_timeout,
// sqlite3_changes,
// sqlite3_close,
// sqlite3_collation_needed,
// sqlite3_collation_needed16,
// sqlite3_column_blob,
// sqlite3_column_bytes,
// sqlite3_column_bytes16,
// sqlite3_column_count,
// sqlite3_column_database_name,
// sqlite3_column_database_name16,
// sqlite3_column_decltype,
// sqlite3_column_decltype16,
// sqlite3_column_double,
// sqlite3_column_int,
// sqlite3_column_int64,
// sqlite3_column_name,
// sqlite3_column_name16,
// sqlite3_column_origin_name,
// sqlite3_column_origin_name16,
// sqlite3_column_table_name,
// sqlite3_column_table_name16,
// sqlite3_column_text,
// sqlite3_column_text16,
// sqlite3_column_type,
// sqlite3_column_value,
// sqlite3_commit_hook,
// sqlite3_complete,
// sqlite3_complete16,
// sqlite3_create_collation,
// sqlite3_create_collation16,
// sqlite3_create_function,
// sqlite3_create_function16,
// sqlite3_create_module,
// sqlite3_data_count,
// sqlite3_db_handle,
// sqlite3_declare_vtab,
// sqlite3_enable_shared_cache,
// sqlite3_errcode,
// sqlite3_errmsg,
// sqlite3_errmsg16,
// sqlite3_exec,
#if !SQLITE_OMIT_DEPRECATED
//sqlite3_expired,
#else
//0,
#endif
// sqlite3_finalize,
// //sqlite3_free,
// //sqlite3_free_table,
// sqlite3_get_autocommit,
// sqlite3_get_auxdata,
// sqlite3_get_table,
// 0, /* Was sqlite3_global_recover(), but that function is deprecated */
// sqlite3_interrupt,
// sqlite3_last_insert_rowid,
// sqlite3_libversion,
// sqlite3_libversion_number,
// sqlite3_malloc,
// sqlite3_mprintf,
// sqlite3_open,
// sqlite3_open16,
// sqlite3_prepare,
// sqlite3_prepare16,
// sqlite3_profile,
// sqlite3_progress_handler,
// sqlite3_realloc,
// sqlite3_reset,
// sqlite3_result_blob,
// sqlite3_result_double,
// sqlite3_result_error,
// sqlite3_result_error16,
// sqlite3_result_int,
// sqlite3_result_int64,
// sqlite3_result_null,
// sqlite3_result_text,
// sqlite3_result_text16,
// sqlite3_result_text16be,
// sqlite3_result_text16le,
// sqlite3_result_value,
// sqlite3_rollback_hook,
// sqlite3_set_authorizer,
// sqlite3_set_auxdata,
// sqlite3_snprintf,
// sqlite3_step,
// sqlite3_table_column_metadata,
#if !SQLITE_OMIT_DEPRECATED
//sqlite3_thread_cleanup,
#else
// 0,
#endif
// sqlite3_total_changes,
// sqlite3_trace,
#if !SQLITE_OMIT_DEPRECATED
//sqlite3_transfer_bindings,
#else
// 0,
#endif
// sqlite3_update_hook,
// sqlite3_user_data,
// sqlite3_value_blob,
// sqlite3_value_bytes,
// sqlite3_value_bytes16,
// sqlite3_value_double,
// sqlite3_value_int,
// sqlite3_value_int64,
// sqlite3_value_numeric_type,
// sqlite3_value_text,
// sqlite3_value_text16,
// sqlite3_value_text16be,
// sqlite3_value_text16le,
// sqlite3_value_type,
// sqlite3_vmprintf,
// /*
// ** The original API set ends here. All extensions can call any
// ** of the APIs above provided that the pointer is not NULL. But
// ** before calling APIs that follow, extension should check the
// ** sqlite3_libversion_number() to make sure they are dealing with
// ** a library that is new enough to support that API.
// *************************************************************************
// */
// sqlite3_overload_function,
// /*
// ** Added after 3.3.13
// */
// sqlite3_prepare_v2,
// sqlite3_prepare16_v2,
// sqlite3_clear_bindings,
// /*
// ** Added for 3.4.1
// */
// sqlite3_create_module_v2,
// /*
// ** Added for 3.5.0
// */
// sqlite3_bind_zeroblob,
// sqlite3_blob_bytes,
// sqlite3_blob_close,
// sqlite3_blob_open,
// sqlite3_blob_read,
// sqlite3_blob_write,
// sqlite3_create_collation_v2,
// sqlite3_file_control,
// sqlite3_memory_highwater,
// sqlite3_memory_used,
#if SQLITE_MUTEX_OMIT
// 0,
// 0,
// 0,
// 0,
// 0,
#else
// sqlite3MutexAlloc,
// sqlite3_mutex_enter,
// sqlite3_mutex_free,
// sqlite3_mutex_leave,
// sqlite3_mutex_try,
#endif
// sqlite3_open_v2,
// sqlite3_release_memory,
// sqlite3_result_error_nomem,
// sqlite3_result_error_toobig,
// sqlite3_sleep,
// sqlite3_soft_heap_limit,
// sqlite3_vfs_find,
// sqlite3_vfs_register,
// sqlite3_vfs_unregister,
// /*
// ** Added for 3.5.8
// */
// sqlite3_threadsafe,
// sqlite3_result_zeroblob,
// sqlite3_result_error_code,
// sqlite3_test_control,
// sqlite3_randomness,
// sqlite3_context_db_handle,
// /*
// ** Added for 3.6.0
// */
// sqlite3_extended_result_codes,
// sqlite3_limit,
// sqlite3_next_stmt,
// sqlite3_sql,
// sqlite3_status,
// /*
// ** Added for 3.7.4
// */
// sqlite3_backup_finish,
// sqlite3_backup_init,
// sqlite3_backup_pagecount,
// sqlite3_backup_remaining,
// sqlite3_backup_step,
//#if !SQLITE_OMIT_COMPILEOPTION_DIAGS
// sqlite3_compileoption_get,
// sqlite3_compileoption_used,
//#else
// 0,
// 0,
//#endif
// sqlite3_create_function_v2,
// sqlite3_db_config,
// sqlite3_db_mutex,
// sqlite3_db_status,
// sqlite3_extended_errcode,
// sqlite3_log,
// sqlite3_soft_heap_limit64,
// sqlite3_sourceid,
// sqlite3_stmt_status,
// sqlite3_strnicmp,
//#if SQLITE_ENABLE_UNLOCK_NOTIFY
// sqlite3_unlock_notify,
//#else
// 0,
//#endif
//#if !SQLITE_OMIT_WAL
// sqlite3_wal_autocheckpoint,
// sqlite3_wal_checkpoint,
// sqlite3_wal_hook,
//#else
// 0,
// 0,
// 0,
//#endif
//};
/*
** Attempt to load an SQLite extension library contained in the file
** zFile. The entry point is zProc. zProc may be 0 in which case a
** default entry point name (sqlite3_extension_init) is used. Use
** of the default name is recommended.
**
** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
**
** If an error occurs and pzErrMsg is not 0, then fill pzErrMsg with
** error message text. The calling function should free this memory
** by calling sqlite3DbFree(db, ).
*/
static int sqlite3LoadExtension(
sqlite3 db, /* Load the extension into this database connection */
string zFile, /* Name of the shared library containing extension */
string zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
ref string pzErrMsg /* Put error message here if not 0 */
)
{
sqlite3_vfs pVfs = db.pVfs;
HANDLE handle;
dxInit xInit; //int (*xInit)(sqlite3*,char**,const sqlite3_api_routines);
StringBuilder zErrmsg = new StringBuilder(100);
//object aHandle;
const int nMsg = 300;
if (pzErrMsg != null)
pzErrMsg = null;
/* Ticket #1863. To avoid a creating security problems for older
** applications that relink against newer versions of SQLite, the
** ability to run load_extension is turned off by default. One
** must call sqlite3_enable_load_extension() to turn on extension
** loading. Otherwise you get the following error.
*/
if ((db.flags & SQLITE_LoadExtension) == 0)
{
//if( pzErrMsg != null){
pzErrMsg = sqlite3_mprintf("not authorized");
//}
return SQLITE_ERROR;
}
if (zProc == null || zProc == "")
{
zProc = "sqlite3_extension_init";
}
handle = sqlite3OsDlOpen(pVfs, zFile);
if (handle == IntPtr.Zero)
{
// if( pzErrMsg ){
pzErrMsg = "";//*pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
//if( zErrmsg !=null){
sqlite3_snprintf(nMsg, zErrmsg,
"unable to open shared library [%s]", zFile);
sqlite3OsDlError(pVfs, nMsg - 1, zErrmsg.ToString());
return SQLITE_ERROR;
}
//xInit = (int()(sqlite3*,char**,const sqlite3_api_routines))
// sqlite3OsDlSym(pVfs, handle, zProc);
xInit = (dxInit)sqlite3OsDlSym(pVfs, handle, ref zProc);
Debugger.Break(); // TODO --
//if( xInit==0 ){
// if( pzErrMsg ){
// *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
// if( zErrmsg ){
// sqlite3_snprintf(nMsg, zErrmsg,
// "no entry point [%s] in shared library [%s]", zProc,zFile);
// sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
// }
// sqlite3OsDlClose(pVfs, handle);
// }
// return SQLITE_ERROR;
// }else if( xInit(db, ref zErrmsg, sqlite3Apis) ){
//// if( pzErrMsg !=null){
// pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
// //}
// sqlite3DbFree(db,ref zErrmsg);
// sqlite3OsDlClose(pVfs, ref handle);
// return SQLITE_ERROR;
// }
// /* Append the new shared library handle to the db.aExtension array. */
// aHandle = sqlite3DbMallocZero(db, sizeof(handle)*db.nExtension+1);
// if( aHandle==null ){
// return SQLITE_NOMEM;
// }
// if( db.nExtension>0 ){
// memcpy(aHandle, db.aExtension, sizeof(handle)*(db.nExtension));
// }
// sqlite3DbFree(db,ref db.aExtension);
// db.aExtension = aHandle;
// db.aExtension[db.nExtension++] = handle;
return SQLITE_OK;
}
static public int sqlite3_load_extension(
sqlite3 db, /* Load the extension into this database connection */
string zFile, /* Name of the shared library containing extension */
string zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
ref string pzErrMsg /* Put error message here if not 0 */
)
{
int rc;
sqlite3_mutex_enter(db.mutex);
rc = sqlite3LoadExtension(db, zFile, zProc, ref pzErrMsg);
rc = sqlite3ApiExit(db, rc);
sqlite3_mutex_leave(db.mutex);
return rc;
}
/*
** Call this routine when the database connection is closing in order
** to clean up loaded extensions
*/
static void sqlite3CloseExtensions(sqlite3 db)
{
int i;
Debug.Assert(sqlite3_mutex_held(db.mutex));
for (i = 0; i < db.nExtension; i++)
{
sqlite3OsDlClose(db.pVfs, (HANDLE)db.aExtension[i]);
}
sqlite3DbFree(db, ref db.aExtension);
}
/*
** Enable or disable extension loading. Extension loading is disabled by
** default so as not to open security holes in older applications.
*/
static public int sqlite3_enable_load_extension(sqlite3 db, int onoff)
{
sqlite3_mutex_enter(db.mutex);
if (onoff != 0)
{
db.flags |= SQLITE_LoadExtension;
}
else
{
db.flags &= ~SQLITE_LoadExtension;
}
sqlite3_mutex_leave(db.mutex);
return SQLITE_OK;
}
#endif //* SQLITE_OMIT_LOAD_EXTENSION */
/*
** The auto-extension code added regardless of whether or not extension
** loading is supported. We need a dummy sqlite3Apis pointer for that
** code if regular extension loading is not available. This is that
** dummy pointer.
*/
#if SQLITE_OMIT_LOAD_EXTENSION
const sqlite3_api_routines sqlite3Apis = null;
#endif
/*
** The following object holds the list of automatically loaded
** extensions.
**
** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
** mutex must be held while accessing this list.
*/
//typedef struct sqlite3AutoExtList sqlite3AutoExtList;
public class sqlite3AutoExtList
{
public int nExt = 0; /* Number of entries in aExt[] */
public dxInit[] aExt = null; /* Pointers to the extension init functions */
public sqlite3AutoExtList(int nExt, dxInit[] aExt)
{
this.nExt = nExt;
this.aExt = aExt;
}
}
static sqlite3AutoExtList sqlite3Autoext = new sqlite3AutoExtList(0, null);
/* The "wsdAutoext" macro will resolve to the autoextension
** state vector. If writable static data is unsupported on the target,
** we have to locate the state vector at run-time. In the more common
** case where writable static data is supported, wsdStat can refer directly
** to the "sqlite3Autoext" state vector declared above.
*/
#if SQLITE_OMIT_WSD
//# define wsdAutoextInit \
sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
//# define wsdAutoext x[0]
#else
//# define wsdAutoextInit
static void wsdAutoextInit()
{
}
//# define wsdAutoext sqlite3Autoext
static sqlite3AutoExtList wsdAutoext = sqlite3Autoext;
#endif
/*
** Register a statically linked extension that is automatically
** loaded by every new database connection.
*/
static int sqlite3_auto_extension(dxInit xInit)
{
int rc = SQLITE_OK;
#if !SQLITE_OMIT_AUTOINIT
rc = sqlite3_initialize();
if (rc != 0)
{
return rc;
}
else
#endif
{
int i;
#if SQLITE_THREADSAFE
sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER );
#else
sqlite3_mutex mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
#endif
wsdAutoextInit();
sqlite3_mutex_enter(mutex);
for (i = 0; i < wsdAutoext.nExt; i++)
{
if (wsdAutoext.aExt[i] == xInit)
break;
}
//if( i==wsdAutoext.nExt ){
// int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
// void **aNew;
// aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
// if( aNew==0 ){
// rc = SQLITE_NOMEM;
// }else{
Array.Resize(ref wsdAutoext.aExt, wsdAutoext.nExt + 1);// wsdAutoext.aExt = aNew;
wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
wsdAutoext.nExt++;
//}
sqlite3_mutex_leave(mutex);
Debug.Assert((rc & 0xff) == rc);
return rc;
}
}
/*
** Reset the automatic extension loading mechanism.
*/
static void sqlite3_reset_auto_extension()
{
#if !SQLITE_OMIT_AUTOINIT
if (sqlite3_initialize() == SQLITE_OK)
#endif
{
#if SQLITE_THREADSAFE
sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER );
#else
sqlite3_mutex mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
#endif
wsdAutoextInit();
sqlite3_mutex_enter(mutex);
#if SQLITE_OMIT_WSD
//sqlite3_free( ref wsdAutoext.aExt );
wsdAutoext.aExt = null;
wsdAutoext.nExt = 0;
#else
//sqlite3_free( ref sqlite3Autoext.aExt );
sqlite3Autoext.aExt = null;
sqlite3Autoext.nExt = 0;
#endif
sqlite3_mutex_leave(mutex);
}
}
/*
** Load all automatic extensions.
**
** If anything goes wrong, set an error in the database connection.
*/
static void sqlite3AutoLoadExtensions(sqlite3 db)
{
int i;
bool go = true;
dxInit xInit;//)(sqlite3*,char**,const sqlite3_api_routines);
wsdAutoextInit();
#if SQLITE_OMIT_WSD
if ( wsdAutoext.nExt == 0 )
#else
if (sqlite3Autoext.nExt == 0)
#endif
{
/* Common case: early out without every having to acquire a mutex */
return;
}
for (i = 0; go; i++)
{
string zErrmsg = "";
#if SQLITE_THREADSAFE
sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER );
#else
sqlite3_mutex mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
#endif
sqlite3_mutex_enter(mutex);
if (i >= wsdAutoext.nExt)
{
xInit = null;
go = false;
}
else
{
xInit = (dxInit)
wsdAutoext.aExt[i];
}
sqlite3_mutex_leave(mutex);
zErrmsg = "";
if (xInit != null && xInit(db, ref zErrmsg, (sqlite3_api_routines)sqlite3Apis) != 0)
{
sqlite3Error(db, SQLITE_ERROR,
"automatic extension loading failed: %s", zErrmsg);
go = false;
}
sqlite3DbFree(db, ref zErrmsg);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using Microsoft.AspNetCore.Identity;
using Umbraco.Cms.Core.Models.Entities;
namespace Umbraco.Cms.Core.Security
{
/// <summary>
/// Abstract class for use in Umbraco Identity for users and members
/// </summary>
/// <remarks>
/// <para>
/// This uses strings for the ID of the user, claims, roles. This is because aspnetcore identity's base store will
/// not support having an INT user PK and a string role PK with the way they've made the generics. So we will just use
/// string for both which makes things more flexible anyways for users and members and also if/when we transition to
/// GUID support
/// </para>
/// <para>
/// This class was originally borrowed from the EF implementation in Identity prior to netcore.
/// The new IdentityUser in netcore does not have properties such as Claims, Roles and Logins and those are instead
/// by default managed with their default user store backed by EF which utilizes EF's change tracking to track these values
/// to a user. We will continue using this approach since it works fine for what we need which does the change tracking of
/// claims, roles and logins directly on the user model.
/// </para>
/// </remarks>
public abstract class UmbracoIdentityUser : IdentityUser, IRememberBeingDirty
{
private string _name;
private string _passwordConfig;
private string _id;
private string _email;
private string _userName;
private DateTime? _lastLoginDateUtc;
private bool _emailConfirmed;
private int _accessFailedCount;
private string _passwordHash;
private DateTime? _lastPasswordChangeDateUtc;
private ObservableCollection<IIdentityUserLogin> _logins;
private ObservableCollection<IIdentityUserToken> _tokens;
private Lazy<IEnumerable<IIdentityUserLogin>> _getLogins;
private Lazy<IEnumerable<IIdentityUserToken>> _getTokens;
private ObservableCollection<IdentityUserRole<string>> _roles;
/// <summary>
/// Initializes a new instance of the <see cref="UmbracoIdentityUser"/> class.
/// </summary>
public UmbracoIdentityUser()
{
// must initialize before setting groups
_roles = new ObservableCollection<IdentityUserRole<string>>();
_roles.CollectionChanged += Roles_CollectionChanged;
Claims = new List<IdentityUserClaim<string>>();
}
public event PropertyChangedEventHandler PropertyChanged
{
add
{
BeingDirty.PropertyChanged += value;
}
remove
{
BeingDirty.PropertyChanged -= value;
}
}
// NOTE: The purpose
// of this value is to try to prevent concurrent writes in the DB but this is
// an implementation detail at the data source level that has leaked into the
// model. A good writeup of that is here:
// https://stackoverflow.com/a/37362173
// For our purposes currently we won't worry about this.
public override string ConcurrencyStamp { get => base.ConcurrencyStamp; set => base.ConcurrencyStamp = value; }
/// <summary>
/// Gets or sets last login date
/// </summary>
public DateTime? LastLoginDateUtc
{
get => _lastLoginDateUtc;
set => BeingDirty.SetPropertyValueAndDetectChanges(value, ref _lastLoginDateUtc, nameof(LastLoginDateUtc));
}
/// <summary>
/// Gets or sets email
/// </summary>
public override string Email
{
get => _email;
set => BeingDirty.SetPropertyValueAndDetectChanges(value, ref _email, nameof(Email));
}
/// <summary>
/// Gets or sets a value indicating whether the email is confirmed, default is false
/// </summary>
public override bool EmailConfirmed
{
get => _emailConfirmed;
set => BeingDirty.SetPropertyValueAndDetectChanges(value, ref _emailConfirmed, nameof(EmailConfirmed));
}
/// <summary>
/// Gets or sets the salted/hashed form of the user password
/// </summary>
public override string PasswordHash
{
get => _passwordHash;
set => BeingDirty.SetPropertyValueAndDetectChanges(value, ref _passwordHash, nameof(PasswordHash));
}
/// <summary>
/// Gets or sets dateTime in UTC when the password was last changed.
/// </summary>
public DateTime? LastPasswordChangeDateUtc
{
get => _lastPasswordChangeDateUtc;
set => BeingDirty.SetPropertyValueAndDetectChanges(value, ref _lastPasswordChangeDateUtc, nameof(LastPasswordChangeDateUtc));
}
/// <summary>
/// Gets or sets a value indicating whether is lockout enabled for this user
/// </summary>
/// <remarks>
/// Currently this is always true for users and members
/// </remarks>
public override bool LockoutEnabled
{
get => true;
set { }
}
/// <summary>
/// Gets or sets the value to record failures for the purposes of lockout
/// </summary>
public override int AccessFailedCount
{
get => _accessFailedCount;
set => BeingDirty.SetPropertyValueAndDetectChanges(value, ref _accessFailedCount, nameof(AccessFailedCount));
}
/// <summary>
/// Gets or sets the user roles collection
/// </summary>
public ICollection<IdentityUserRole<string>> Roles
{
get => _roles;
set
{
_roles.CollectionChanged -= Roles_CollectionChanged;
_roles = new ObservableCollection<IdentityUserRole<string>>(value);
_roles.CollectionChanged += Roles_CollectionChanged;
}
}
/// <summary>
/// Gets navigation the user claims collection
/// </summary>
public ICollection<IdentityUserClaim<string>> Claims { get; }
/// <summary>
/// Gets the user logins collection
/// </summary>
public ICollection<IIdentityUserLogin> Logins
{
get
{
// return if it exists
if (_logins != null)
{
return _logins;
}
_logins = new ObservableCollection<IIdentityUserLogin>();
// if the callback is there and hasn't been created yet then execute it and populate the logins
if (_getLogins != null && !_getLogins.IsValueCreated)
{
foreach (IIdentityUserLogin l in _getLogins.Value)
{
_logins.Add(l);
}
}
// now assign events
_logins.CollectionChanged += Logins_CollectionChanged;
return _logins;
}
}
/// <summary>
/// Gets the external login tokens collection
/// </summary>
public ICollection<IIdentityUserToken> LoginTokens
{
get
{
// return if it exists
if (_tokens is not null)
{
return _tokens;
}
_tokens = new ObservableCollection<IIdentityUserToken>();
// if the callback is there and hasn't been created yet then execute it and populate the logins
// if (_getTokens != null && !_getTokens.IsValueCreated)
if (_getTokens?.IsValueCreated != true)
{
foreach (IIdentityUserToken l in _getTokens.Value)
{
_tokens.Add(l);
}
}
// now assign events
_tokens.CollectionChanged += LoginTokens_CollectionChanged;
return _tokens;
}
}
/// <summary>
/// Gets or sets user ID (Primary Key)
/// </summary>
public override string Id
{
get => _id;
set
{
_id = value;
HasIdentity = true;
}
}
/// <summary>
/// Gets or sets a value indicating whether returns an Id has been set on this object this will be false if the object is new and not persisted to the database
/// </summary>
public bool HasIdentity { get; protected set; }
/// <summary>
/// Gets or sets user name
/// </summary>
public override string UserName
{
get => _userName;
set => BeingDirty.SetPropertyValueAndDetectChanges(value, ref _userName, nameof(UserName));
}
/// <summary>
/// Gets the <see cref="BeingDirty"/> for change tracking
/// </summary>
protected BeingDirty BeingDirty { get; } = new BeingDirty();
/// <summary>
/// Gets a value indicating whether the user is locked out based on the user's lockout end date
/// </summary>
public bool IsLockedOut
{
get
{
bool isLocked = LockoutEnabled && LockoutEnd.HasValue && LockoutEnd.Value.ToLocalTime() >= DateTime.Now;
return isLocked;
}
}
/// <summary>
/// Gets or sets a value indicating whether the IUser IsApproved
/// </summary>
public bool IsApproved { get; set; }
/// <summary>
/// Gets or sets the user's real name
/// </summary>
public string Name
{
get => _name;
set => BeingDirty.SetPropertyValueAndDetectChanges(value, ref _name, nameof(Name));
}
/// <summary>
/// Gets or sets the password config
/// </summary>
public string PasswordConfig
{
// TODO: Implement this for members: AB#11550
get => _passwordConfig;
set => BeingDirty.SetPropertyValueAndDetectChanges(value, ref _passwordConfig, nameof(PasswordConfig));
}
/// <inheritdoc />
public bool IsDirty() => BeingDirty.IsDirty();
/// <inheritdoc />
public bool IsPropertyDirty(string propName) => BeingDirty.IsPropertyDirty(propName);
/// <inheritdoc />
public IEnumerable<string> GetDirtyProperties() => BeingDirty.GetDirtyProperties();
/// <inheritdoc />
public void ResetDirtyProperties() => BeingDirty.ResetDirtyProperties();
/// <inheritdoc />
public bool WasDirty() => BeingDirty.WasDirty();
/// <inheritdoc />
public bool WasPropertyDirty(string propertyName) => BeingDirty.WasPropertyDirty(propertyName);
/// <inheritdoc />
public void ResetWereDirtyProperties() => BeingDirty.ResetWereDirtyProperties();
/// <inheritdoc />
public void ResetDirtyProperties(bool rememberDirty) => BeingDirty.ResetDirtyProperties(rememberDirty);
/// <inheritdoc />
public IEnumerable<string> GetWereDirtyProperties() => BeingDirty.GetWereDirtyProperties();
/// <summary>
/// Disables change tracking.
/// </summary>
public void DisableChangeTracking() => BeingDirty.DisableChangeTracking();
/// <summary>
/// Enables change tracking.
/// </summary>
public void EnableChangeTracking() => BeingDirty.EnableChangeTracking();
/// <summary>
/// Adds a role
/// </summary>
/// <param name="role">The role to add</param>
/// <remarks>
/// Adding a role this way will not reflect on the user's group's collection or it's allowed sections until the user is persisted
/// </remarks>
public void AddRole(string role) => Roles.Add(new IdentityUserRole<string>
{
UserId = Id,
RoleId = role
});
/// <summary>
/// Used to set a lazy call back to populate the user's Login list
/// </summary>
/// <param name="callback">The lazy value</param>
internal void SetLoginsCallback(Lazy<IEnumerable<IIdentityUserLogin>> callback) => _getLogins = callback ?? throw new ArgumentNullException(nameof(callback));
/// <summary>
/// Used to set a lazy call back to populate the user's token list
/// </summary>
/// <param name="callback">The lazy value</param>
internal void SetTokensCallback(Lazy<IEnumerable<IIdentityUserToken>> callback) => _getTokens = callback ?? throw new ArgumentNullException(nameof(callback));
private void Logins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) => BeingDirty.OnPropertyChanged(nameof(Logins));
private void LoginTokens_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) => BeingDirty.OnPropertyChanged(nameof(LoginTokens));
private void Roles_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) => BeingDirty.OnPropertyChanged(nameof(Roles));
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
// ReSharper disable AssignNullToNotNullAttribute
namespace Thinktecture.IO.Adapters
{
/// <summary>
/// Adapter for <see cref="Directory"/>.
/// </summary>
public class DirectoryAdapter : IDirectory
{
/// <inheritdoc />
public IDirectoryInfo CreateDirectory(string path)
{
return Directory.CreateDirectory(path).ToInterface();
}
/// <inheritdoc />
public void Delete(string path)
{
Directory.Delete(path);
}
/// <inheritdoc />
public void Delete(string path, bool recursive)
{
Directory.Delete(path, recursive);
}
/// <inheritdoc />
public IEnumerable<string> EnumerateDirectories(string path)
{
return Directory.EnumerateDirectories(path);
}
/// <inheritdoc />
public IEnumerable<string> EnumerateDirectories(string path, string searchPattern)
{
return Directory.EnumerateDirectories(path, searchPattern);
}
/// <inheritdoc />
public IEnumerable<string> EnumerateDirectories(string path, string searchPattern, SearchOption searchOption)
{
return Directory.EnumerateDirectories(path, searchPattern, searchOption);
}
/// <inheritdoc />
public IEnumerable<string> EnumerateFiles(string path)
{
return Directory.EnumerateFiles(path);
}
/// <inheritdoc />
public IEnumerable<string> EnumerateFiles(string path, string searchPattern)
{
return Directory.EnumerateFiles(path, searchPattern);
}
/// <inheritdoc />
public IEnumerable<string> EnumerateFiles(string path, string searchPattern, SearchOption searchOption)
{
return Directory.EnumerateFiles(path, searchPattern, searchOption);
}
/// <inheritdoc />
public IEnumerable<string> EnumerateFileSystemEntries(string path)
{
return Directory.EnumerateFileSystemEntries(path);
}
/// <inheritdoc />
public IEnumerable<string> EnumerateFileSystemEntries(string path, string searchPattern)
{
return Directory.EnumerateFileSystemEntries(path, searchPattern);
}
/// <inheritdoc />
public IEnumerable<string> EnumerateFileSystemEntries(string path, string searchPattern, SearchOption searchOption)
{
return Directory.EnumerateFileSystemEntries(path, searchPattern, searchOption);
}
/// <inheritdoc />
public string[] GetLogicalDrives()
{
return Directory.GetLogicalDrives();
}
/// <inheritdoc />
public bool Exists(string path)
{
return Directory.Exists(path);
}
/// <inheritdoc />
public DateTime GetCreationTime(string path)
{
return Directory.GetCreationTime(path);
}
/// <inheritdoc />
public DateTime GetCreationTimeUtc(string path)
{
return Directory.GetCreationTimeUtc(path);
}
/// <inheritdoc />
public string GetCurrentDirectory()
{
return Directory.GetCurrentDirectory();
}
/// <inheritdoc />
public string[] GetDirectories(string path)
{
return Directory.GetDirectories(path);
}
/// <inheritdoc />
public string[] GetDirectories(string path, string searchPattern)
{
return Directory.GetDirectories(path, searchPattern);
}
/// <inheritdoc />
public string[] GetDirectories(string path, string searchPattern, SearchOption searchOption)
{
return Directory.GetDirectories(path, searchPattern, searchOption);
}
/// <inheritdoc />
public string GetDirectoryRoot(string path)
{
return Directory.GetDirectoryRoot(path);
}
/// <inheritdoc />
public string[] GetFiles(string path, string searchPattern, EnumerationOptions enumerationOptions)
{
return Directory.GetFiles(path, searchPattern, enumerationOptions);
}
/// <inheritdoc />
public string[] GetDirectories(string path, string searchPattern, EnumerationOptions enumerationOptions)
{
return Directory.GetDirectories(path, searchPattern, enumerationOptions);
}
/// <inheritdoc />
public string[] GetFileSystemEntries(string path, string searchPattern, EnumerationOptions enumerationOptions)
{
return Directory.GetFileSystemEntries(path, searchPattern, enumerationOptions);
}
/// <inheritdoc />
public IEnumerable<string> EnumerateDirectories(string path, string searchPattern, EnumerationOptions enumerationOptions)
{
return Directory.EnumerateDirectories(path, searchPattern, enumerationOptions);
}
/// <inheritdoc />
public IEnumerable<string> EnumerateFiles(string path, string searchPattern, EnumerationOptions enumerationOptions)
{
return Directory.EnumerateFiles(path, searchPattern, enumerationOptions);
}
/// <inheritdoc />
public IEnumerable<string> EnumerateFileSystemEntries(string path, string searchPattern, EnumerationOptions enumerationOptions)
{
return Directory.EnumerateFileSystemEntries(path, searchPattern, enumerationOptions);
}
/// <inheritdoc />
public string[] GetFiles(string path)
{
return Directory.GetFiles(path);
}
/// <inheritdoc />
public string[] GetFiles(string path, string searchPattern)
{
return Directory.GetFiles(path, searchPattern);
}
/// <inheritdoc />
public string[] GetFiles(string path, string searchPattern, SearchOption searchOption)
{
return Directory.GetFiles(path, searchPattern, searchOption);
}
/// <inheritdoc />
public string[] GetFileSystemEntries(string path)
{
return Directory.GetFileSystemEntries(path);
}
/// <inheritdoc />
public string[] GetFileSystemEntries(string path, string searchPattern)
{
return Directory.GetFileSystemEntries(path, searchPattern);
}
/// <inheritdoc />
public string[] GetFileSystemEntries(string path, string searchPattern, SearchOption searchOption)
{
return Directory.GetFileSystemEntries(path, searchPattern, searchOption);
}
/// <inheritdoc />
public DateTime GetLastAccessTime(string path)
{
return Directory.GetLastAccessTime(path);
}
/// <inheritdoc />
public DateTime GetLastAccessTimeUtc(string path)
{
return Directory.GetLastAccessTimeUtc(path);
}
/// <inheritdoc />
public DateTime GetLastWriteTime(string path)
{
return Directory.GetLastWriteTime(path);
}
/// <inheritdoc />
public DateTime GetLastWriteTimeUtc(string path)
{
return Directory.GetLastWriteTimeUtc(path);
}
/// <inheritdoc />
public IDirectoryInfo? GetParent(string path)
{
return Directory.GetParent(path).ToInterface();
}
/// <inheritdoc />
public void Move(string sourceDirName, string destDirName)
{
Directory.Move(sourceDirName, destDirName);
}
/// <inheritdoc />
public void SetCreationTime(string path, DateTime creationTime)
{
Directory.SetCreationTime(path, creationTime);
}
/// <inheritdoc />
public void SetCreationTimeUtc(string path, DateTime creationTimeUtc)
{
Directory.SetCreationTimeUtc(path, creationTimeUtc);
}
/// <inheritdoc />
public void SetCurrentDirectory(string path)
{
Directory.SetCurrentDirectory(path);
}
/// <inheritdoc />
public void SetLastAccessTime(string path, DateTime lastAccessTime)
{
Directory.SetLastAccessTime(path, lastAccessTime);
}
/// <inheritdoc />
public void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc)
{
Directory.SetLastAccessTimeUtc(path, lastAccessTimeUtc);
}
/// <inheritdoc />
public void SetLastWriteTime(string path, DateTime lastWriteTime)
{
Directory.SetLastWriteTime(path, lastWriteTime);
}
/// <inheritdoc />
public void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc)
{
Directory.SetLastWriteTimeUtc(path, lastWriteTimeUtc);
}
}
}
| |
using System;
using System.ComponentModel;
using System.Drawing;
namespace NuiEngine.NuiControl
{
/// <summary></summary>
public class ColorUtility {
static ColorUtility() {
}
/// <summary></summary>
/// <param name="c"></param>
/// <returns></returns>
public static Color ReverseColor(Color c) {
return Color.FromArgb(ReverseInt(c.R), ReverseInt(c.G), ReverseInt(c.B));
}
private static int ReverseInt(int x) {
int val = x - 255;
if (val < 0) { val = val * -1; }
return val;
}
/// <summary></summary>
/// <param name="c"></param>
/// <returns></returns>
public static string ToHexString(Color c) {
string hex = string.Empty;
hex += DoHex(c.R);
hex += DoHex(c.G);
hex += DoHex(c.B);
return "#" + hex;
}
private static string DoHex(int xor) {
string hex = xor.ToString("x");
if (xor < 16) {
hex = "0" + hex;
}
if (xor == 0) {
hex = "00";
}
return hex.ToUpper();
}
private static int DeHex(string input) {
int val;
int result = 0;
for (int i = 0; i < input.Length; i++) {
string chunk = input.Substring(i, 1).ToUpper();
switch (chunk) {
case "A":
val = 10; break;
case "B":
val = 11; break;
case "C":
val = 12; break;
case "D":
val = 13; break;
case "E":
val = 14; break;
case "F":
val = 15; break;
default:
val = int.Parse(chunk); break;
}
if (i == 0) {
result += val * 16;
} else {
result += val;
}
}
return result;
}
}
// System.Drawing.Drawing2D.ColorBlend
/// <summary></summary>
public class ColorBlender {
private Color colorleft;
private Color colorright;
private int steps;
private float step;
private float stepsize;
/// <summary></summary>
/// <param name="numberofsteps"></param>
/// <param name="one"></param>
/// <param name="two"></param>
public ColorBlender(int numberofsteps, Color one, Color two) {
steps = numberofsteps;
colorleft = one;
colorright = two;
stepsize = 1.0f / Convert.ToSingle(steps);
step = 0;
}
/// <summary></summary>
/// <returns></returns>
public bool HasNext() {
return step < 1;
}
/// <summary></summary>
/// <returns></returns>
public Color Next() {
if (!HasNext()) { throw new Exception("Past threshold."); }
step += stepsize;
return Morph(step, colorleft, colorright);
}
/// <summary></summary>
/// <param name="ratio"></param>
/// <param name="c1"></param>
/// <param name="c2"></param>
/// <returns></returns>
public Color Morph(float ratio, Color c1, Color c2) {
int r = (int)(c1.R + ratio * (c2.R - c1.R));
int g = (int)(c1.G + ratio * (c2.G - c1.G));
int b = (int)(c1.B + ratio * (c2.B - c1.B));
return Color.FromArgb(r, g, b);
}
}
/// <summary></summary>
public struct ColorRange {
/// <summary></summary>
public Color Light;
/// <summary></summary>
public Color Lighter;
/// <summary></summary>
public Color BaseColor;
/// <summary></summary>
public Color Dark;
/// <summary></summary>
public Color Darker;
/// <summary></summary>
/// <param name="color"></param>
public ColorRange(Color color) {
BaseColor = color;
Light = ColorRange.Tint(0.6f, color);
Lighter = ColorRange.Tint(0.3f, color);
Dark = ColorRange.Shade(0.8f, color);
Darker = ColorRange.Shade(0.6f, color);
}
/// <summary></summary>
/// <param name="color"></param>
/// <param name="lightratio"></param>
/// <param name="lighterratio"></param>
public ColorRange(Color color, float lightratio, float lighterratio) {
BaseColor = color;
Light = ColorRange.Tint(lightratio, color);
Lighter = ColorRange.Tint(lighterratio, color);
Dark = ColorRange.Shade(lightratio, color);
Darker = ColorRange.Shade(lighterratio, color);
}
/// <summary></summary>
/// <param name="color"></param>
/// <param name="lightratio"></param>
/// <param name="lighterratio"></param>
/// <param name="darkratio"></param>
/// <param name="darkerratio"></param>
public ColorRange(Color color, float lightratio, float lighterratio, float darkratio, float darkerratio) {
BaseColor = color;
Light = ColorRange.Tint(lightratio, color);
Lighter = ColorRange.Tint(lighterratio, color);
Dark = ColorRange.Shade(darkratio, color);
Darker = ColorRange.Shade(darkerratio, color);
}
/// <summary></summary>
/// <param name="ratio"></param>
/// <param name="c1"></param>
/// <returns></returns>
public static Color Tint(float ratio, Color c1) {
return Morph(ratio, Color.White, c1);
}
/// <summary></summary>
/// <param name="ratio"></param>
/// <param name="c1"></param>
/// <returns></returns>
public static Color Shade(float ratio, Color c1) {
return Morph(ratio, Color.Black, c1);
}
/// <summary></summary>
/// <param name="ratio"></param>
/// <param name="c1"></param>
/// <param name="c2"></param>
/// <returns></returns>
public static Color Morph(float ratio, Color c1, Color c2) {
int r = (int)(c1.R + ratio * (c2.R - c1.R));
int g = (int)(c1.G + ratio * (c2.G - c1.G));
int b = (int)(c1.B + ratio * (c2.B - c1.B));
return Color.FromArgb(r, g, b);
}
}
/// <summary></summary>
public class ColorSet {
private bool shade;
private Color color;
private float factor;
private int colors;
private Color[] range;
/// <summary></summary>
/// <param name="shade"></param>
/// <param name="color"></param>
/// <param name="factor"></param>
/// <param name="colors"></param>
public ColorSet(bool shade, Color color, float factor, int colors) {
if (colors < 1) { throw new ArgumentException("Number of colors must be greater than 0."); }
if (factor < 0 || factor > 1) { throw new ArgumentException("Factor must be between 0 and 1."); }
this.shade = shade;
this.color = color;
this.factor = factor;
this.colors = colors;
Build();
}
private void Build() {
this.range = new Color[colors];
Color current = color;
range[0] = current;
for (int i = 1; i < colors; i++) {
if (shade) {
range[i] = ColorRange.Shade(factor, current);
} else {
range[i] = ColorRange.Tint(factor, current);
}
current = range[i];
}
}
/// <summary></summary>
public Color[] Colors {
get { return range; }
}
}
/// <summary></summary>
public class BlendSet {
private Color color1;
private Color color2;
private float factor;
private int colors;
private Color[] range;
/// <summary></summary>
/// <param name="one"></param>
/// <param name="two"></param>
/// <param name="factor"></param>
/// <param name="colors"></param>
public BlendSet(Color one, Color two, float factor, int colors) {
if (colors < 1) { throw new ArgumentException("Number of colors must be greater than 0."); }
if (factor < 0 || factor > 1) { throw new ArgumentException("Factor must be between 0 and 1."); }
this.color1 = one;
this.color2 = two;
this.factor = factor;
this.colors = colors;
Build();
}
private void Build() {
this.range = new Color[colors];
Color current = color1;
range[0] = current;
for (int i = 1; i < colors; i++) {
range[i] = ColorRange.Morph(factor, current, color2);
current = range[i];
}
}
/// <summary></summary>
public Color[] Colors {
get { return range; }
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Collections;
namespace UrlHistoryLibrary
{
/// <summary>
/// Used by QueryUrl method
/// </summary>
public enum STATURL_QUERYFLAGS : uint
{
/// <summary>
/// The specified URL is in the content cache.
/// </summary>
STATURL_QUERYFLAG_ISCACHED = 0x00010000,
/// <summary>
/// Space for the URL is not allocated when querying for STATURL.
/// </summary>
STATURL_QUERYFLAG_NOURL = 0x00020000,
/// <summary>
/// Space for the Web page's title is not allocated when querying for STATURL.
/// </summary>
STATURL_QUERYFLAG_NOTITLE = 0x00040000,
/// <summary>
/// //The item is a top-level item.
/// </summary>
STATURL_QUERYFLAG_TOPLEVEL = 0x00080000,
}
/// <summary>
/// Flag on the dwFlags parameter of the STATURL structure, used by the SetFilter method.
/// </summary>
public enum STATURLFLAGS : uint
{
/// <summary>
/// Flag on the dwFlags parameter of the STATURL structure indicating that the item is in the cache.
/// </summary>
STATURLFLAG_ISCACHED = 0x00000001,
/// <summary>
/// Flag on the dwFlags parameter of the STATURL structure indicating that the item is a top-level item.
/// </summary>
STATURLFLAG_ISTOPLEVEL = 0x00000002,
}
/// <summary>
/// Used bu the AddHistoryEntry method.
/// </summary>
public enum ADDURL_FLAG : uint
{
/// <summary>
/// Write to both the visited links and the dated containers.
/// </summary>
ADDURL_ADDTOHISTORYANDCACHE = 0,
/// <summary>
/// Write to only the visited links container.
/// </summary>
ADDURL_ADDTOCACHE = 1
}
/// <summary>
/// The structure that contains statistics about a URL.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct STATURL
{
/// <summary>
/// Struct size
/// </summary>
public int cbSize;
/// <summary>
/// URL
/// </summary>
[MarshalAs(UnmanagedType.LPWStr)] public string pwcsUrl;
/// <summary>
/// Page title
/// </summary>
[MarshalAs(UnmanagedType.LPWStr)] public string pwcsTitle;
/// <summary>
/// Last visited date (UTC)
/// </summary>
public FILETIME ftLastVisited;
/// <summary>
/// Last updated date (UTC)
/// </summary>
public FILETIME ftLastUpdated;
/// <summary>
/// The expiry date of the Web page's content (UTC)
/// </summary>
public FILETIME ftExpires;
/// <summary>
/// Flags. STATURLFLAGS Enumaration.
/// </summary>
public STATURLFLAGS dwFlags;
/// <summary>
/// sets a column header in the DataGrid control. This property is not needed if you do not use it.
/// </summary>
public string URL
{
get{return pwcsUrl;}
}
/// <summary>
/// sets a column header in the DataGrid control. This property is not needed if you do not use it.
/// </summary>
public string Title
{
get{
if(pwcsUrl.StartsWith("file:"))
return Win32api.CannonializeURL(pwcsUrl, Win32api.shlwapi_URL.URL_UNESCAPE).Substring(8).Replace('/', '\\');
else
return pwcsTitle;
}
}
/// <summary>
/// sets a column header in the DataGrid control. This property is not needed if you do not use it.
/// </summary>
public DateTime LastVisited
{
get
{
return Win32api.FileTimeToDateTime(ftLastVisited).ToLocalTime();
}
}
/// <summary>
/// sets a column header in the DataGrid control. This property is not needed if you do not use it.
/// </summary>
public DateTime LastUpdated
{
get
{
return Win32api.FileTimeToDateTime(ftLastUpdated).ToLocalTime();
}
}
/// <summary>
/// sets a column header in the DataGrid control. This property is not needed if you do not use it.
/// </summary>
public DateTime Expires
{
get
{
try
{
return Win32api.FileTimeToDateTime(ftExpires).ToLocalTime();
}
catch(Exception)
{
return DateTime.Now;
}
}
}
}
[StructLayout(LayoutKind.Sequential)]
public struct UUID
{
public int Data1;
public short Data2;
public short Data3;
public byte[] Data4;
}
//Enumerates the cached URLs
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("3C374A42-BAE4-11CF-BF7D-00AA006946EE")]
public interface IEnumSTATURL
{
void Next(int celt, ref STATURL rgelt, out int pceltFetched); //Returns the next \"celt\" URLS from the cache
void Skip(int celt); //Skips the next \"celt\" URLS from the cache. doed not work.
void Reset(); //Resets the enumeration
void Clone(out IEnumSTATURL ppenum); //Clones this object
void SetFilter([MarshalAs(UnmanagedType.LPWStr)] string poszFilter, STATURLFLAGS dwFlags); //Sets the enumeration filter
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("3C374A41-BAE4-11CF-BF7D-00AA006946EE")]
public interface IUrlHistoryStg
{
void AddUrl(string pocsUrl, string pocsTitle, ADDURL_FLAG dwFlags); //Adds a new history entry
void DeleteUrl(string pocsUrl, int dwFlags); //Deletes an entry by its URL. does not work!
void QueryUrl ([MarshalAs(UnmanagedType.LPWStr)] string pocsUrl , STATURL_QUERYFLAGS dwFlags , ref STATURL lpSTATURL ); //Returns a STATURL for a given URL
void BindToObject ([In] string pocsUrl, [In] UUID riid, IntPtr ppvOut); //Binds to an object. does not work!
object EnumUrls{[return: MarshalAs(UnmanagedType.IUnknown)] get;} //Returns an enumerator for URLs
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("AFA0DC11-C313-11D0-831A-00C04FD5AE38")]
public interface IUrlHistoryStg2 : IUrlHistoryStg
{
new void AddUrl(string pocsUrl, string pocsTitle, ADDURL_FLAG dwFlags); //Adds a new history entry
new void DeleteUrl(string pocsUrl, int dwFlags); //Deletes an entry by its URL. does not work!
new void QueryUrl ([MarshalAs(UnmanagedType.LPWStr)] string pocsUrl , STATURL_QUERYFLAGS dwFlags , ref STATURL lpSTATURL ); //Returns a STATURL for a given URL
new void BindToObject ([In] string pocsUrl, [In] UUID riid, IntPtr ppvOut); //Binds to an object. does not work!
new object EnumUrls{[return: MarshalAs(UnmanagedType.IUnknown)] get;} //Returns an enumerator for URLs
void AddUrlAndNotify(string pocsUrl, string pocsTitle, int dwFlags, int fWriteHistory, object poctNotify, object punkISFolder);//does not work!
void ClearHistory(); //Removes all history items
}
//UrlHistory class
[ComImport]
[Guid("3C374A40-BAE4-11CF-BF7D-00AA006946EE")]
public class UrlHistoryClass
{
}
}
| |
/*
* 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.
*/
// ReSharper disable UnusedMember.Local
// ReSharper disable NotAccessedField.Local
#pragma warning disable 649 // Unassigned field
namespace Apache.Ignite.Core.Tests.Cache.Query
{
using System.IO;
using System.Linq;
using System.Reflection;
using Apache.Ignite.Core.Cache.Affinity;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Client;
using NUnit.Framework;
/// <summary>
/// Tests that <see cref="QueryEntity.KeyTypeName"/> and <see cref="QueryEntity.ValueTypeName"/>
/// settings trigger binary metadata registration on cache start for the specified types.
/// <para />
/// Normally, binary metadata is registered in the cluster when an object of the given type is first serialized
/// (for cache storage or other purposes - Services, Compute, etc).
/// However, query engine requires metadata for key/value types on cache start, so an eager registration
/// should be performed.
/// </summary>
public class QueryEntityMetadataRegistrationTest
{
/** */
private const string CacheName = "cache1";
/** */
private const string CacheName2 = "cache2";
/// <summary>
/// Fixture set up.
/// </summary>
[TestFixtureSetUp]
public void StartGrids()
{
var springConfig = Path.Combine("Config", "query-entity-metadata-registration.xml");
for (int i = 0; i < 2; i++)
{
var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
SpringConfigUrl = springConfig,
IgniteInstanceName = i.ToString(),
WorkDirectory = Path.Combine(
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
"ignite_work_" + GetType().Name + "_" + i),
// Cache configs will be merged with Spring cache configs.
CacheConfiguration = new[]
{
new CacheConfiguration
{
Name = CacheName2,
QueryEntities = new[]
{
new QueryEntity
{
KeyType = typeof(Key3),
ValueType = typeof(string)
}
}
}
}
};
Ignition.Start(cfg);
}
}
/// <summary>
/// Fixture tear down.
/// </summary>
[TestFixtureTearDown]
public void StopGrids()
{
Ignition.StopAll(true);
}
/// <summary>
/// Tests that starting a cache from code with a <see cref="QueryEntity"/> causes binary type registration
/// for key and value types.
/// <para />
/// * Start a new cache with code configuration
/// * Check that query entity is populated correctly
/// * Check that key and value types are registered in the cluster
/// </summary>
[Test]
public void TestCacheStartFromCodeRegistersMetaForQueryEntityTypes()
{
var cfg = new CacheConfiguration
{
Name = TestUtils.TestName,
QueryEntities = new[]
{
new QueryEntity
{
KeyType = typeof(Key1),
ValueType = typeof(Value1)
}
}
};
var cache = Ignition.GetIgnite("0").CreateCache<Key1, Value1>(cfg);
foreach (var ignite in Ignition.GetAll())
{
// Do not use GetBinaryType which always returns something.
// Use GetBinaryTypes to make sure that types are actually registered.
var types = ignite.GetBinary().GetBinaryTypes();
var qryEntity = ignite.GetCache<object, object>(cfg.Name).GetConfiguration().QueryEntities.Single();
var keyType = types.Single(t => t.TypeName == qryEntity.KeyTypeName);
var valType = types.Single(t => t.TypeName == qryEntity.ValueTypeName);
Assert.AreEqual(typeof(Key1).FullName, qryEntity.KeyTypeName);
Assert.AreEqual(typeof(Value1).FullName, qryEntity.ValueTypeName);
Assert.AreEqual("Bar", keyType.AffinityKeyFieldName);
Assert.IsEmpty(keyType.Fields);
Assert.IsNull(valType.AffinityKeyFieldName);
Assert.IsEmpty(valType.Fields);
}
// Verify put/get on server and client.
cache[new Key1{Foo = "a", Bar = 2}] = new Value1 {Name = "x", Value = 1};
using (var client = Ignition.StartClient(new IgniteClientConfiguration("localhost")))
{
var clientCache = client.GetCache<Key1, Value1>(cache.Name);
var val = clientCache.Get(new Key1 {Foo = "a", Bar = 2});
Assert.AreEqual("x", val.Name);
Assert.AreEqual(1, val.Value);
}
}
/// <summary>
/// Tests that starting a cache from code with a <see cref="QueryEntity"/> skips binary type registration
/// for key and value types when those types can't be resolved.
/// <para />
/// * Start a new cache with code configuration and invalid key/value entity type names
/// * Check that query entity is populated correctly
/// </summary>
[Test]
public void TestCacheStartFromCodeSkipsInvalidQueryEntityTypes()
{
var cfg = new CacheConfiguration
{
Name = TestUtils.TestName,
QueryEntities = new[]
{
new QueryEntity
{
KeyTypeName = "Invalid_Name",
ValueTypeName = "Invalid_Name"
}
}
};
Ignition.GetIgnite("0").CreateCache<object, object>(cfg);
foreach (var ignite in Ignition.GetAll())
{
var types = ignite.GetBinary().GetBinaryTypes();
var qryEntity = ignite.GetCache<object, object>(cfg.Name).GetConfiguration().QueryEntities.Single();
var keyType = types.FirstOrDefault(t => t.TypeName == qryEntity.KeyTypeName);
var valType = types.FirstOrDefault(t => t.TypeName == qryEntity.ValueTypeName);
Assert.IsNull(keyType);
Assert.IsNull(valType);
}
}
/// <summary>
/// Tests that starting a cache from Spring XML with a <see cref="QueryEntity"/> causes binary type registration
/// for key and value types.
/// <para />
/// * Get the cache started from Spring XML
/// * Check that query entity is populated correctly
/// * Check that key and value types are registered in the cluster
/// </summary>
[Test]
public void TestCacheStartFromSpringRegistersMetaForQueryEntityTypes()
{
foreach (var ignite in Ignition.GetAll())
{
// Do not use GetBinaryType which always returns something.
// Use GetBinaryTypes to make sure that types are actually registered.
var types = ignite.GetBinary().GetBinaryTypes();
var qryEntity = ignite.GetCache<object, object>(CacheName).GetConfiguration().QueryEntities.Single();
var keyType = types.Single(t => t.TypeName == qryEntity.KeyTypeName);
var valType = types.Single(t => t.TypeName == qryEntity.ValueTypeName);
Assert.AreEqual(typeof(Key2).FullName, qryEntity.KeyTypeName);
Assert.AreEqual(typeof(Value2).FullName, qryEntity.ValueTypeName);
Assert.AreEqual("AffKey", keyType.AffinityKeyFieldName);
Assert.IsEmpty(keyType.Fields);
Assert.IsNull(valType.AffinityKeyFieldName);
Assert.IsEmpty(valType.Fields);
}
}
/// <summary>
/// Tests that starting a cache from <see cref="IgniteConfiguration.CacheConfiguration"/>
/// with a <see cref="QueryEntity"/> causes binary type registration for key and value types.
/// <para />
/// * Get the cache started from <see cref="IgniteConfiguration.CacheConfiguration"/>
/// * Check that query entity is populated correctly
/// * Check that key and value types are registered in the cluster
/// </summary>
[Test]
public void TestCacheStartIgniteConfigurationRegistersMetaForQueryEntityTypes()
{
foreach (var ignite in Ignition.GetAll())
{
var types = ignite.GetBinary().GetBinaryTypes();
var qryEntity = ignite.GetCache<object, object>(CacheName2).GetConfiguration().QueryEntities.Single();
var keyType = types.Single(t => t.TypeName == qryEntity.KeyTypeName);
Assert.AreEqual(typeof(Key3).FullName, qryEntity.KeyTypeName);
Assert.AreEqual("Aff", keyType.AffinityKeyFieldName);
}
}
/** */
private class Key1
{
/** */
[QuerySqlField]
public string Foo;
/** */
[AffinityKeyMapped]
public int Bar;
}
/** */
private class Value1
{
/** */
[QuerySqlField]
public string Name { get; set; }
/** */
[QuerySqlField]
public long Value { get; set; }
}
/** */
private class Key2
{
/** */
public string Baz;
/** */
[AffinityKeyMapped]
public long AffKey;
}
/** */
private class Value2
{
/** */
public string Name { get; set; }
/** */
public decimal Price { get; set; }
}
/** */
private class Key3
{
/** */
public string Qux;
/** */
[AffinityKeyMapped]
public long Aff;
}
}
}
| |
// 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
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// SlimManualResetEvent.cs
//
//
// An manual-reset event that mixes a little spinning with a true Win32 event.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Diagnostics;
using System.Runtime.InteropServices;
using Internal.Runtime.Augments;
namespace System.Threading
{
// ManualResetEventSlim wraps a manual-reset event internally with a little bit of
// spinning. When an event will be set imminently, it is often advantageous to avoid
// a 4k+ cycle context switch in favor of briefly spinning. Therefore we layer on to
// a brief amount of spinning that should, on the average, make using the slim event
// cheaper than using Win32 events directly. This can be reset manually, much like
// a Win32 manual-reset would be.
//
// Notes:
// We lazily allocate the Win32 event internally. Therefore, the caller should
// always call Dispose to clean it up, just in case. This API is a no-op of the
// event wasn't allocated, but if it was, ensures that the event goes away
// eagerly, instead of waiting for finalization.
/// <summary>
/// Provides a slimmed down version of <see cref="T:System.Threading.ManualResetEvent"/>.
/// </summary>
/// <remarks>
/// All public and protected members of <see cref="ManualResetEventSlim"/> are thread-safe and may be used
/// concurrently from multiple threads, with the exception of Dispose, which
/// must only be used when all other operations on the <see cref="ManualResetEventSlim"/> have
/// completed, and Reset, which should only be used when no other threads are
/// accessing the event.
/// </remarks>
[DebuggerDisplay("Set = {IsSet}")]
public class ManualResetEventSlim : IDisposable
{
// These are the default spin counts we use on single-proc and MP machines.
private const int DEFAULT_SPIN_SP = 1;
private const int DEFAULT_SPIN_MP = 10;
private volatile Lock m_lock;
private volatile Condition m_condition;
// A lock used for waiting and pulsing. Lazily initialized via EnsureLockObjectCreated()
private volatile ManualResetEvent m_eventObj; // A true Win32 event used for waiting.
// -- State -- //
//For a packed word a uint would seem better, but Interlocked.* doesn't support them as uint isn't CLS-compliant.
private volatile int m_combinedState; //ie a uint. Used for the state items listed below.
//1-bit for signalled state
private const int SignalledState_BitMask = unchecked((int)0x80000000);//1000 0000 0000 0000 0000 0000 0000 0000
private const int SignalledState_ShiftCount = 31;
//1-bit for disposed state
private const int Dispose_BitMask = unchecked((int)0x40000000);//0100 0000 0000 0000 0000 0000 0000 0000
//11-bits for m_spinCount
private const int SpinCountState_BitMask = unchecked((int)0x3FF80000); //0011 1111 1111 1000 0000 0000 0000 0000
private const int SpinCountState_ShiftCount = 19;
private const int SpinCountState_MaxValue = (1 << 11) - 1; //2047
//19-bits for m_waiters. This allows support of 512K threads waiting which should be ample
private const int NumWaitersState_BitMask = unchecked((int)0x0007FFFF); // 0000 0000 0000 0111 1111 1111 1111 1111
private const int NumWaitersState_ShiftCount = 0;
private const int NumWaitersState_MaxValue = (1 << 19) - 1; //512K-1
// ----------- //
#if DEBUG
private static int s_nextId; // The next id that will be given out.
private int m_id = Interlocked.Increment(ref s_nextId); // A unique id for debugging purposes only.
private long m_lastSetTime;
private long m_lastResetTime;
#endif
/// <summary>
/// Gets the underlying <see cref="T:System.Threading.WaitHandle"/> object for this <see
/// cref="ManualResetEventSlim"/>.
/// </summary>
/// <value>The underlying <see cref="T:System.Threading.WaitHandle"/> event object fore this <see
/// cref="ManualResetEventSlim"/>.</value>
/// <remarks>
/// Accessing this property forces initialization of an underlying event object if one hasn't
/// already been created. To simply wait on this <see cref="ManualResetEventSlim"/>,
/// the public Wait methods should be preferred.
/// </remarks>
public WaitHandle WaitHandle
{
get
{
ThrowIfDisposed();
if (m_eventObj == null)
{
// Lazily initialize the event object if needed.
LazyInitializeEvent();
}
return m_eventObj;
}
}
/// <summary>
/// Gets whether the event is set.
/// </summary>
/// <value>true if the event has is set; otherwise, false.</value>
public bool IsSet
{
get
{
return 0 != ExtractStatePortion(m_combinedState, SignalledState_BitMask);
}
private set
{
UpdateStateAtomically(((value) ? 1 : 0) << SignalledState_ShiftCount, SignalledState_BitMask);
}
}
/// <summary>
/// Gets the number of spin waits that will be occur before falling back to a true wait.
/// </summary>
public int SpinCount
{
get
{
return ExtractStatePortionAndShiftRight(m_combinedState, SpinCountState_BitMask, SpinCountState_ShiftCount);
}
private set
{
Debug.Assert(value >= 0, "SpinCount is a restricted-width integer. The value supplied is outside the legal range.");
Debug.Assert(value <= SpinCountState_MaxValue, "SpinCount is a restricted-width integer. The value supplied is outside the legal range.");
// Don't worry about thread safety because it's set one time from the constructor
m_combinedState = (m_combinedState & ~SpinCountState_BitMask) | (value << SpinCountState_ShiftCount);
}
}
/// <summary>
/// How many threads are waiting.
/// </summary>
private int Waiters
{
get
{
return ExtractStatePortionAndShiftRight(m_combinedState, NumWaitersState_BitMask, NumWaitersState_ShiftCount);
}
set
{
//setting to <0 would indicate an internal flaw, hence Assert is appropriate.
Debug.Assert(value >= 0, "NumWaiters should never be less than zero. This indicates an internal error.");
// it is possible for the max number of waiters to be exceeded via user-code, hence we use a real exception here.
if (value >= NumWaitersState_MaxValue)
throw new InvalidOperationException(string.Format(SR.ManualResetEventSlim_ctor_TooManyWaiters, NumWaitersState_MaxValue));
UpdateStateAtomically(value << NumWaitersState_ShiftCount, NumWaitersState_BitMask);
}
}
//-----------------------------------------------------------------------------------
// Constructs a new event, optionally specifying the initial state and spin count.
// The defaults are that the event is unsignaled and some reasonable default spin.
//
/// <summary>
/// Initializes a new instance of the <see cref="ManualResetEventSlim"/>
/// class with an initial state of nonsignaled.
/// </summary>
public ManualResetEventSlim()
: this(false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ManualResetEventSlim"/>
/// class with a Boolean value indicating whether to set the intial state to signaled.
/// </summary>
/// <param name="initialState">true to set the initial state signaled; false to set the initial state
/// to nonsignaled.</param>
public ManualResetEventSlim(bool initialState)
{
// Specify the defualt spin count, and use default spin if we're
// on a multi-processor machine. Otherwise, we won't.
Initialize(initialState, DEFAULT_SPIN_MP);
}
/// <summary>
/// Initializes a new instance of the <see cref="ManualResetEventSlim"/>
/// class with a Boolen value indicating whether to set the intial state to signaled and a specified
/// spin count.
/// </summary>
/// <param name="initialState">true to set the initial state to signaled; false to set the initial state
/// to nonsignaled.</param>
/// <param name="spinCount">The number of spin waits that will occur before falling back to a true
/// wait.</param>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="spinCount"/> is less than
/// 0 or greater than the maximum allowed value.</exception>
public ManualResetEventSlim(bool initialState, int spinCount)
{
if (spinCount < 0)
{
throw new ArgumentOutOfRangeException(nameof(spinCount));
}
if (spinCount > SpinCountState_MaxValue)
{
throw new ArgumentOutOfRangeException(
nameof(spinCount),
string.Format(SR.ManualResetEventSlim_ctor_SpinCountOutOfRange, SpinCountState_MaxValue));
}
// We will suppress default spin because the user specified a count.
Initialize(initialState, spinCount);
}
/// <summary>
/// Initializes the internal state of the event.
/// </summary>
/// <param name="initialState">Whether the event is set initially or not.</param>
/// <param name="spinCount">The spin count that decides when the event will block.</param>
private void Initialize(bool initialState, int spinCount)
{
m_combinedState = initialState ? (1 << SignalledState_ShiftCount) : 0;
//the spinCount argument has been validated by the ctors.
//but we now sanity check our predefined constants.
Debug.Assert(DEFAULT_SPIN_SP >= 0, "Internal error - DEFAULT_SPIN_SP is outside the legal range.");
Debug.Assert(DEFAULT_SPIN_SP <= SpinCountState_MaxValue, "Internal error - DEFAULT_SPIN_SP is outside the legal range.");
SpinCount = PlatformHelper.IsSingleProcessor ? DEFAULT_SPIN_SP : spinCount;
}
/// <summary>
/// Helper to ensure the lock object is created before first use.
/// </summary>
private void EnsureLockObjectCreated()
{
if (m_lock == null)
{
Lock newObj = new Lock();
Interlocked.CompareExchange(ref m_lock, newObj, null); // failure is benign.. someone else won the race.
}
if (m_condition == null)
{
Condition newCond = new Condition(m_lock);
Interlocked.CompareExchange(ref m_condition, newCond, null);
}
}
/// <summary>
/// This method lazily initializes the event object. It uses CAS to guarantee that
/// many threads racing to call this at once don't result in more than one event
/// being stored and used. The event will be signaled or unsignaled depending on
/// the state of the thin-event itself, with synchronization taken into account.
/// </summary>
/// <returns>True if a new event was created and stored, false otherwise.</returns>
private bool LazyInitializeEvent()
{
bool preInitializeIsSet = IsSet;
ManualResetEvent newEventObj = new ManualResetEvent(preInitializeIsSet);
// We have to CAS this in case we are racing with another thread. We must
// guarantee only one event is actually stored in this field.
if (Interlocked.CompareExchange(ref m_eventObj, newEventObj, null) != null)
{
// We raced with someone else and lost. Destroy the garbage event.
newEventObj.Dispose();
return false;
}
else
{
// Now that the event is published, verify that the state hasn't changed since
// we snapped the preInitializeState. Another thread could have done that
// between our initial observation above and here. The barrier incurred from
// the CAS above (in addition to m_state being volatile) prevents this read
// from moving earlier and being collapsed with our original one.
bool currentIsSet = IsSet;
if (currentIsSet != preInitializeIsSet)
{
Debug.Assert(currentIsSet,
"The only safe concurrent transition is from unset->set: detected set->unset.");
// We saw it as unsignaled, but it has since become set.
lock (newEventObj)
{
// If our event hasn't already been disposed of, we must set it.
if (m_eventObj == newEventObj)
{
newEventObj.Set();
}
}
}
return true;
}
}
/// <summary>
/// Sets the state of the event to signaled, which allows one or more threads waiting on the event to
/// proceed.
/// </summary>
public void Set()
{
Set(false);
}
/// <summary>
/// Private helper to actually perform the Set.
/// </summary>
/// <param name="duringCancellation">Indicates whether we are calling Set() during cancellation.</param>
/// <exception cref="T:System.OperationCanceledException">The object has been canceled.</exception>
private void Set(bool duringCancellation)
{
// We need to ensure that IsSet=true does not get reordered past the read of m_eventObj
// This would be a legal movement according to the .NET memory model.
// The code is safe as IsSet involves an Interlocked.CompareExchange which provides a full memory barrier.
IsSet = true;
// If there are waiting threads, we need to pulse them.
if (Waiters > 0)
{
Debug.Assert(m_lock != null && m_condition != null); //if waiters>0, then m_lock has already been created.
using (LockHolder.Hold(m_lock))
{
m_condition.SignalAll();
}
}
ManualResetEvent eventObj = m_eventObj;
//Design-decision: do not set the event if we are in cancellation -> better to deadlock than to wake up waiters incorrectly
//It would be preferable to wake up the event and have it throw OCE. This requires MRE to implement cancellation logic
if (eventObj != null && !duringCancellation)
{
// We must surround this call to Set in a lock. The reason is fairly subtle.
// Sometimes a thread will issue a Wait and wake up after we have set m_state,
// but before we have gotten around to setting m_eventObj (just below). That's
// because Wait first checks m_state and will only access the event if absolutely
// necessary. However, the coding pattern { event.Wait(); event.Dispose() } is
// quite common, and we must support it. If the waiter woke up and disposed of
// the event object before the setter has finished, however, we would try to set a
// now-disposed Win32 event. Crash! To deal with this race, we use a lock to
// protect access to the event object when setting and disposing of it. We also
// double-check that the event has not become null in the meantime when in the lock.
lock (eventObj)
{
if (m_eventObj != null)
{
// If somebody is waiting, we must set the event.
m_eventObj.Set();
}
}
}
#if DEBUG
m_lastSetTime = Environment.TickCount;
#endif
}
/// <summary>
/// Sets the state of the event to nonsignaled, which causes threads to block.
/// </summary>
/// <remarks>
/// Unlike most of the members of <see cref="ManualResetEventSlim"/>, <see cref="Reset()"/> is not
/// thread-safe and may not be used concurrently with other members of this instance.
/// </remarks>
public void Reset()
{
ThrowIfDisposed();
// If there's an event, reset it.
if (m_eventObj != null)
{
m_eventObj.Reset();
}
// There is a race here. If another thread Sets the event, we will get into a state
// where m_state will be unsignaled, yet the Win32 event object will have been signaled.
// This could cause waiting threads to wake up even though the event is in an
// unsignaled state. This is fine -- those that are calling Reset concurrently are
// responsible for doing "the right thing" -- e.g. rechecking the condition and
// resetting the event manually.
// And finally set our state back to unsignaled.
IsSet = false;
#if DEBUG
m_lastResetTime = DateTime.Now.Ticks;
#endif
}
/// <summary>
/// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set.
/// </summary>
/// <exception cref="T:System.InvalidOperationException">
/// The maximum number of waiters has been exceeded.
/// </exception>
/// <remarks>
/// The caller of this method blocks indefinitely until the current instance is set. The caller will
/// return immediately if the event is currently in a set state.
/// </remarks>
public void Wait()
{
Wait(Timeout.Infinite, new CancellationToken());
}
/// <summary>
/// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> receives a signal,
/// while observing a <see cref="T:System.Threading.CancellationToken"/>.
/// </summary>
/// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to
/// observe.</param>
/// <exception cref="T:System.InvalidOperationException">
/// The maximum number of waiters has been exceeded.
/// </exception>
/// <exception cref="T:System.OperationCanceledExcepton"><paramref name="cancellationToken"/> was
/// canceled.</exception>
/// <remarks>
/// The caller of this method blocks indefinitely until the current instance is set. The caller will
/// return immediately if the event is currently in a set state.
/// </remarks>
public void Wait(CancellationToken cancellationToken)
{
Wait(Timeout.Infinite, cancellationToken);
}
/// <summary>
/// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a
/// <see cref="T:System.TimeSpan"/> to measure the time interval.
/// </summary>
/// <param name="timeout">A <see cref="System.TimeSpan"/> that represents the number of milliseconds
/// to wait, or a <see cref="System.TimeSpan"/> that represents -1 milliseconds to wait indefinitely.
/// </param>
/// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise,
/// false.</returns>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative
/// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater
/// than <see cref="System.Int32.MaxValue"/>.</exception>
/// <exception cref="T:System.InvalidOperationException">
/// The maximum number of waiters has been exceeded.
/// </exception>
public bool Wait(TimeSpan timeout)
{
long totalMilliseconds = (long)timeout.TotalMilliseconds;
if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(timeout));
}
return Wait((int)totalMilliseconds, new CancellationToken());
}
/// <summary>
/// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a
/// <see cref="T:System.TimeSpan"/> to measure the time interval, while observing a <see
/// cref="T:System.Threading.CancellationToken"/>.
/// </summary>
/// <param name="timeout">A <see cref="System.TimeSpan"/> that represents the number of milliseconds
/// to wait, or a <see cref="System.TimeSpan"/> that represents -1 milliseconds to wait indefinitely.
/// </param>
/// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to
/// observe.</param>
/// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise,
/// false.</returns>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative
/// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater
/// than <see cref="System.Int32.MaxValue"/>.</exception>
/// <exception cref="T:System.Threading.OperationCanceledException"><paramref
/// name="cancellationToken"/> was canceled.</exception>
/// <exception cref="T:System.InvalidOperationException">
/// The maximum number of waiters has been exceeded.
/// </exception>
public bool Wait(TimeSpan timeout, CancellationToken cancellationToken)
{
long totalMilliseconds = (long)timeout.TotalMilliseconds;
if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(timeout));
}
return Wait((int)totalMilliseconds, cancellationToken);
}
/// <summary>
/// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a
/// 32-bit signed integer to measure the time interval.
/// </summary>
/// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see
/// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param>
/// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise,
/// false.</returns>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a
/// negative number other than -1, which represents an infinite time-out.</exception>
/// <exception cref="T:System.InvalidOperationException">
/// The maximum number of waiters has been exceeded.
/// </exception>
public bool Wait(int millisecondsTimeout)
{
return Wait(millisecondsTimeout, new CancellationToken());
}
/// <summary>
/// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a
/// 32-bit signed integer to measure the time interval, while observing a <see
/// cref="T:System.Threading.CancellationToken"/>.
/// </summary>
/// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see
/// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param>
/// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to
/// observe.</param>
/// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise,
/// false.</returns>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a
/// negative number other than -1, which represents an infinite time-out.</exception>
/// <exception cref="T:System.InvalidOperationException">
/// The maximum number of waiters has been exceeded.
/// </exception>
/// <exception cref="T:System.Threading.OperationCanceledException"><paramref
/// name="cancellationToken"/> was canceled.</exception>
public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken)
{
ThrowIfDisposed();
cancellationToken.ThrowIfCancellationRequested(); // an early convenience check
if (millisecondsTimeout < -1)
{
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout));
}
if (!IsSet)
{
if (millisecondsTimeout == 0)
{
// For 0-timeouts, we just return immediately.
return false;
}
// We spin briefly before falling back to allocating and/or waiting on a true event.
uint startTime = 0;
bool bNeedTimeoutAdjustment = false;
int realMillisecondsTimeout = millisecondsTimeout; //this will be adjusted if necessary.
if (millisecondsTimeout != Timeout.Infinite)
{
// We will account for time spent spinning, so that we can decrement it from our
// timeout. In most cases the time spent in this section will be negligible. But
// we can't discount the possibility of our thread being switched out for a lengthy
// period of time. The timeout adjustments only take effect when and if we actually
// decide to block in the kernel below.
startTime = TimeoutHelper.GetTime();
bNeedTimeoutAdjustment = true;
}
//spin
int HOW_MANY_SPIN_BEFORE_YIELD = 10;
int HOW_MANY_YIELD_EVERY_SLEEP_0 = 5;
int HOW_MANY_YIELD_EVERY_SLEEP_1 = 20;
int spinCount = SpinCount;
for (int i = 0; i < spinCount; i++)
{
if (IsSet)
{
return true;
}
else if (i < HOW_MANY_SPIN_BEFORE_YIELD)
{
if (i == HOW_MANY_SPIN_BEFORE_YIELD / 2)
{
Thread.Yield();
}
else
{
Thread.SpinWait(PlatformHelper.ProcessorCount * (4 << i));
}
}
else if (i % HOW_MANY_YIELD_EVERY_SLEEP_1 == 0)
{
Thread.Sleep(1);
}
else if (i % HOW_MANY_YIELD_EVERY_SLEEP_0 == 0)
{
Thread.Sleep(0);
}
else
{
Thread.Yield();
}
if (i >= 100 && i % 10 == 0) // check the cancellation token if the user passed a very large spin count
cancellationToken.ThrowIfCancellationRequested();
}
// Now enter the lock and wait.
EnsureLockObjectCreated();
// We must register and unregister the token outside of the lock, to avoid deadlocks.
using (cancellationToken.UnsafeRegister(s_cancellationTokenCallback, this))
{
using (LockHolder.Hold(m_lock))
{
// Loop to cope with spurious wakeups from other waits being canceled
while (!IsSet)
{
// If our token was canceled, we must throw and exit.
cancellationToken.ThrowIfCancellationRequested();
//update timeout (delays in wait commencement are due to spinning and/or spurious wakeups from other waits being canceled)
if (bNeedTimeoutAdjustment)
{
realMillisecondsTimeout = TimeoutHelper.UpdateTimeOut(startTime, millisecondsTimeout);
if (realMillisecondsTimeout <= 0)
return false;
}
// There is a race that Set will fail to see that there are waiters as Set does not take the lock,
// so after updating waiters, we must check IsSet again.
// Also, we must ensure there cannot be any reordering of the assignment to Waiters and the
// read from IsSet. This is guaranteed as Waiters{set;} involves an Interlocked.CompareExchange
// operation which provides a full memory barrier.
// If we see IsSet=false, then we are guaranteed that Set() will see that we are
// waiting and will pulse the monitor correctly.
Waiters = Waiters + 1;
if (IsSet) //This check must occur after updating Waiters.
{
Waiters--; //revert the increment.
return true;
}
// Now finally perform the wait.
try
{
// ** the actual wait **
if (!m_condition.Wait(realMillisecondsTimeout))
return false; //return immediately if the timeout has expired.
}
finally
{
// Clean up: we're done waiting.
Waiters = Waiters - 1;
}
// Now just loop back around, and the right thing will happen. Either:
// 1. We had a spurious wake-up due to some other wait being canceled via a different cancellationToken (rewait)
// or 2. the wait was successful. (the loop will break)
}
}
}
} // automatically disposes (and unregisters) the callback
return true; //done. The wait was satisfied.
}
/// <summary>
/// Releases all resources used by the current instance of <see cref="ManualResetEventSlim"/>.
/// </summary>
/// <remarks>
/// Unlike most of the members of <see cref="ManualResetEventSlim"/>, <see cref="Dispose()"/> is not
/// thread-safe and may not be used concurrently with other members of this instance.
/// </remarks>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// When overridden in a derived class, releases the unmanaged resources used by the
/// <see cref="ManualResetEventSlim"/>, and optionally releases the managed resources.
/// </summary>
/// <param name="disposing">true to release both managed and unmanaged resources;
/// false to release only unmanaged resources.</param>
/// <remarks>
/// Unlike most of the members of <see cref="ManualResetEventSlim"/>, <see cref="Dispose(bool)"/> is not
/// thread-safe and may not be used concurrently with other members of this instance.
/// </remarks>
protected virtual void Dispose(bool disposing)
{
if ((m_combinedState & Dispose_BitMask) != 0)
return; // already disposed
m_combinedState |= Dispose_BitMask; //set the dispose bit
if (disposing)
{
// We will dispose of the event object. We do this under a lock to protect
// against the race condition outlined in the Set method above.
ManualResetEvent eventObj = m_eventObj;
if (eventObj != null)
{
lock (eventObj)
{
eventObj.Dispose();
m_eventObj = null;
}
}
}
}
/// <summary>
/// Throw ObjectDisposedException if the MRES is disposed
/// </summary>
private void ThrowIfDisposed()
{
if ((m_combinedState & Dispose_BitMask) != 0)
throw new ObjectDisposedException(SR.ManualResetEventSlim_Disposed);
}
/// <summary>
/// Private helper method to wake up waiters when a cancellationToken gets canceled.
/// </summary>
private static Action<object> s_cancellationTokenCallback = new Action<object>(CancellationTokenCallback);
private static void CancellationTokenCallback(object obj)
{
ManualResetEventSlim mre = obj as ManualResetEventSlim;
Debug.Assert(mre != null, "Expected a ManualResetEventSlim");
Debug.Assert(mre.m_lock != null); //the lock should have been created before this callback is registered for use.
using (LockHolder.Hold(mre.m_lock))
{
mre.m_condition.SignalAll(); // awaken all waiters
}
}
/// <summary>
/// Private helper method for updating parts of a bit-string state value.
/// Mainly called from the IsSet and Waiters properties setters
/// </summary>
/// <remarks>
/// Note: the parameter types must be int as CompareExchange cannot take a Uint
/// </remarks>
/// <param name="newBits">The new value</param>
/// <param name="updateBitsMask">The mask used to set the bits</param>
private void UpdateStateAtomically(int newBits, int updateBitsMask)
{
SpinWait sw = new SpinWait();
Debug.Assert((newBits | updateBitsMask) == updateBitsMask, "newBits do not fall within the updateBitsMask.");
do
{
int oldState = m_combinedState; // cache the old value for testing in CAS
// Procedure:(1) zero the updateBits. eg oldState = [11111111] flag= [00111000] newState = [11000111]
// then (2) map in the newBits. eg [11000111] newBits=00101000, newState=[11101111]
int newState = (oldState & ~updateBitsMask) | newBits;
if (Interlocked.CompareExchange(ref m_combinedState, newState, oldState) == oldState)
{
return;
}
sw.SpinOnce();
} while (true);
}
/// <summary>
/// Private helper method - performs Mask and shift, particular helpful to extract a field from a packed word.
/// eg ExtractStatePortionAndShiftRight(0x12345678, 0xFF000000, 24) => 0x12, ie extracting the top 8-bits as a simple integer
///
/// ?? is there a common place to put this rather than being private to MRES?
/// </summary>
/// <param name="state"></param>
/// <param name="mask"></param>
/// <param name="rightBitShiftCount"></param>
/// <returns></returns>
private static int ExtractStatePortionAndShiftRight(int state, int mask, int rightBitShiftCount)
{
//convert to uint before shifting so that right-shift does not replicate the sign-bit,
//then convert back to int.
return unchecked((int)(((uint)(state & mask)) >> rightBitShiftCount));
}
/// <summary>
/// Performs a Mask operation, but does not perform the shift.
/// This is acceptable for boolean values for which the shift is unnecessary
/// eg (val & Mask) != 0 is an appropriate way to extract a boolean rather than using
/// ((val & Mask) >> shiftAmount) == 1
///
/// ?? is there a common place to put this rather than being private to MRES?
/// </summary>
/// <param name="state"></param>
/// <param name="mask"></param>
private static int ExtractStatePortion(int state, int mask)
{
return state & mask;
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Management.Automation.Remoting;
using System.Management.Automation.Runspaces;
using System.Management.Automation.Security;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// This cmdlet start invocation of jobs in background.
/// </summary>
[Cmdlet("Start", "Job", DefaultParameterSetName = StartJobCommand.ComputerNameParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113405")]
[OutputType(typeof(PSRemotingJob))]
public class StartJobCommand : PSExecutionCmdlet, IDisposable
{
#region Private members
private static readonly string s_startJobType = "BackgroundJob";
#endregion
#region Parameters
private const string DefinitionNameParameterSet = "DefinitionName";
/// <summary>
/// JobDefinition Name.
/// </summary>
[Parameter(Position = 0, Mandatory = true,
ParameterSetName = StartJobCommand.DefinitionNameParameterSet)]
[ValidateNotNullOrEmpty]
public string DefinitionName
{
get { return _definitionName; }
set { _definitionName = value; }
}
private string _definitionName;
/// <summary>
/// JobDefinition file path.
/// </summary>
[Parameter(Position = 1,
ParameterSetName = StartJobCommand.DefinitionNameParameterSet)]
[ValidateNotNullOrEmpty]
public string DefinitionPath
{
get { return _definitionPath; }
set { _definitionPath = value; }
}
private string _definitionPath;
/// <summary>
/// Job SourceAdapter type for this job definition.
/// </summary>
[Parameter(Position = 2,
ParameterSetName = StartJobCommand.DefinitionNameParameterSet)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")]
public string Type
{
get { return _definitionType; }
set { _definitionType = value; }
}
private string _definitionType;
/// <summary>
/// Friendly name for this job object
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = StartJobCommand.FilePathComputerNameParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = StartJobCommand.ComputerNameParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = StartJobCommand.LiteralFilePathComputerNameParameterSet)]
public virtual String Name
{
get
{
return _name;
}
set
{
if (!String.IsNullOrEmpty(value))
{
_name = value;
}
}
}
private String _name;
/// <summary>
/// Command to execute specified as a string. This can be a single
/// cmdlet, an expression or anything that can be internally
/// converted into a ScriptBlock
/// </summary>
/// <remarks>This is used in the in process case with a
/// "ValueFromPipelineProperty" enabled in order to maintain
/// compatibility with v1.0</remarks>
[Parameter(Position = 0,
Mandatory = true,
ParameterSetName = StartJobCommand.ComputerNameParameterSet)]
[Alias("Command")]
public override ScriptBlock ScriptBlock
{
get
{
return base.ScriptBlock;
}
set
{
base.ScriptBlock = value;
}
}
// suppress all the parameters from PSRemotingBaseCmdlet
// which should not be part of Start-PSJob
/// <summary>
/// Overriding to suppress this parameter
/// </summary>
public override PSSession[] Session
{
get
{
return null;
}
}
/// <summary>
/// Overriding to suppress this parameter
/// </summary>
public override String[] ComputerName
{
get
{
return null;
}
}
/// <summary>
/// Not used for OutOfProc jobs. Suppressing this parameter.
/// </summary>
public override SwitchParameter EnableNetworkAccess
{
get { return false; }
}
/// <summary>
/// Credential to use for this job
/// </summary>
[Parameter(ParameterSetName = StartJobCommand.FilePathComputerNameParameterSet)]
[Parameter(ParameterSetName = StartJobCommand.ComputerNameParameterSet)]
[Parameter(ParameterSetName = StartJobCommand.LiteralFilePathComputerNameParameterSet)]
[Credential()]
public override PSCredential Credential
{
get
{
return base.Credential;
}
set
{
base.Credential = value;
}
}
/// <summary>
/// Overriding to suppress this parameter
/// </summary>
public override Int32 Port
{
get
{
return 0;
}
}
/// <summary>
/// Overriding to suppress this parameter
/// </summary>
public override SwitchParameter UseSSL
{
get
{
return false;
}
}
/// <summary>
/// Overriding to suppress this parameter
/// </summary>
public override String ConfigurationName
{
get
{
return base.ConfigurationName;
}
set
{
base.ConfigurationName = value;
}
}
/// <summary>
/// Overriding to suppress this parameter
/// </summary>
public override Int32 ThrottleLimit
{
get
{
return 0;
}
}
/// <summary>
/// Overriding to suppress this parameter
/// </summary>
public override String ApplicationName
{
get
{
return null;
}
}
/// <summary>
/// Overriding to suppress this parameter
/// </summary>
public override Uri[] ConnectionUri
{
get
{
return null;
}
}
/// <summary>
/// Filepath to execute as a script
/// </summary>
[Parameter(
Position = 0,
Mandatory = true,
ParameterSetName = StartJobCommand.FilePathComputerNameParameterSet)]
public override string FilePath
{
get
{
return base.FilePath;
}
set
{
base.FilePath = value;
}
}
/// <summary>
/// Literal Filepath to execute as a script
/// </summary>
[Parameter(
Mandatory = true,
ParameterSetName = StartJobCommand.LiteralFilePathComputerNameParameterSet)]
[Alias("PSPath")]
public string LiteralPath
{
get
{
return base.FilePath;
}
set
{
base.FilePath = value;
base.IsLiteralPath = true;
}
}
/// <summary>
/// Use basic authentication to authenticate the user.
/// </summary>
[Parameter(ParameterSetName = StartJobCommand.FilePathComputerNameParameterSet)]
[Parameter(ParameterSetName = StartJobCommand.ComputerNameParameterSet)]
[Parameter(ParameterSetName = StartJobCommand.LiteralFilePathComputerNameParameterSet)]
public override AuthenticationMechanism Authentication
{
get
{
return base.Authentication;
}
set
{
base.Authentication = value;
}
}
/// <summary>
/// Overriding to suppress this parameter
/// </summary>
public override string CertificateThumbprint
{
get
{
return base.CertificateThumbprint;
}
set
{
base.CertificateThumbprint = value;
}
}
/// <summary>
/// Overriding to suppress this parameter
/// </summary>
public override SwitchParameter AllowRedirection
{
get
{
return false;
}
}
/// <summary>
/// Overriding to suppress this parameter
/// </summary>
public override Guid[] VMId
{
get
{
return null;
}
}
/// <summary>
/// Overriding to suppress this parameter
/// </summary>
public override string[] VMName
{
get
{
return null;
}
}
/// <summary>
/// Overriding to suppress this parameter
/// </summary>
public override string[] ContainerId
{
get
{
return null;
}
}
/// <summary>
/// Overriding to suppress this parameter
/// </summary>
public override SwitchParameter RunAsAdministrator
{
get
{
return false;
}
}
/// <summary>
/// Extended Session Options for controlling the session creation. Use
/// "New-WSManSessionOption" cmdlet to supply value for this parameter.
/// </summary>
/// <remarks>
/// This is not declared as a Parameter for Start-PSJob as this is not
/// used for background jobs.
/// </remarks>
public override PSSessionOption SessionOption
{
get
{
return base.SessionOption;
}
set
{
base.SessionOption = value;
}
}
/// <summary>
/// Script that is used to initialize the background job.
/// </summary>
[Parameter(Position = 1,
ParameterSetName = StartJobCommand.FilePathComputerNameParameterSet)]
[Parameter(Position = 1,
ParameterSetName = StartJobCommand.ComputerNameParameterSet)]
[Parameter(Position = 1,
ParameterSetName = StartJobCommand.LiteralFilePathComputerNameParameterSet)]
public virtual ScriptBlock InitializationScript
{
get { return _initScript; }
set { _initScript = value; }
}
private ScriptBlock _initScript;
/// <summary>
/// Launces the background job as a 32-bit process. This can be used on
/// 64-bit systems to launch a 32-bit wow process for the background job.
/// </summary>
[Parameter(ParameterSetName = StartJobCommand.FilePathComputerNameParameterSet)]
[Parameter(ParameterSetName = StartJobCommand.ComputerNameParameterSet)]
[Parameter(ParameterSetName = StartJobCommand.LiteralFilePathComputerNameParameterSet)]
public virtual SwitchParameter RunAs32
{
get { return _shouldRunAs32; }
set { _shouldRunAs32 = value; }
}
private bool _shouldRunAs32;
/// <summary>
/// Powershell Version to execute the background job
/// </summary>
[Parameter(ParameterSetName = StartJobCommand.FilePathComputerNameParameterSet)]
[Parameter(ParameterSetName = StartJobCommand.ComputerNameParameterSet)]
[Parameter(ParameterSetName = StartJobCommand.LiteralFilePathComputerNameParameterSet)]
[ValidateNotNullOrEmpty]
public virtual Version PSVersion
{
get { return _psVersion; }
set
{
PSSessionConfigurationCommandBase.CheckPSVersion(value);
// Check if specified version of PowerShell is installed
PSSessionConfigurationCommandUtilities.CheckIfPowerShellVersionIsInstalled(value);
_psVersion = value;
}
}
private Version _psVersion;
/// <summary>
/// InputObject.
/// </summary>
[Parameter(ValueFromPipeline = true,
ParameterSetName = StartJobCommand.FilePathComputerNameParameterSet)]
[Parameter(ValueFromPipeline = true,
ParameterSetName = StartJobCommand.ComputerNameParameterSet)]
[Parameter(ValueFromPipeline = true,
ParameterSetName = StartJobCommand.LiteralFilePathComputerNameParameterSet)]
public override PSObject InputObject
{
get { return base.InputObject; }
set { base.InputObject = value; }
}
/// <summary>
/// ArgumentList.
/// </summary>
[Parameter(ParameterSetName = StartJobCommand.FilePathComputerNameParameterSet)]
[Parameter(ParameterSetName = StartJobCommand.ComputerNameParameterSet)]
[Parameter(ParameterSetName = StartJobCommand.LiteralFilePathComputerNameParameterSet)]
[Alias("Args")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public override Object[] ArgumentList
{
get { return base.ArgumentList; }
set { base.ArgumentList = value; }
}
#endregion Parameters
#region Overrides
/// <summary>
/// 1. Set the throttling limit and reset operations complete
/// 2. Create helper objects
/// 3. For async case, write the async result object down the
/// pipeline
/// </summary>
protected override void BeginProcessing()
{
CommandDiscovery.AutoloadModulesWithJobSourceAdapters(this.Context, this.CommandOrigin);
if (ParameterSetName == DefinitionNameParameterSet)
{
return;
}
// since jobs no more depend on WinRM
// we will have to skip the check for the same
SkipWinRMCheck = true;
base.BeginProcessing();
} // CoreBeginProcessing
/// <summary>
/// Create a throttle operation using NewProcessConnectionInfo
/// ie., Out-Of-Process runspace.
/// </summary>
protected override void CreateHelpersForSpecifiedComputerNames()
{
// If we're in ConstrainedLanguage mode and the system is in lockdown mode,
// ensure that they haven't specified a ScriptBlock or InitScript - as
// we can't protect that boundary
if ((Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) &&
(SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Enforce) &&
((ScriptBlock != null) || (InitializationScript != null)))
{
ThrowTerminatingError(
new ErrorRecord(
new PSNotSupportedException(RemotingErrorIdStrings.CannotStartJobInconsistentLanguageMode),
"CannotStartJobInconsistentLanguageMode",
ErrorCategory.PermissionDenied,
Context.LanguageMode));
}
NewProcessConnectionInfo connectionInfo = new NewProcessConnectionInfo(this.Credential);
connectionInfo.RunAs32 = _shouldRunAs32;
connectionInfo.InitializationScript = _initScript;
connectionInfo.AuthenticationMechanism = this.Authentication;
connectionInfo.PSVersion = this.PSVersion;
RemoteRunspace remoteRunspace = (RemoteRunspace)RunspaceFactory.CreateRunspace(connectionInfo, this.Host,
Utils.GetTypeTableFromExecutionContextTLS());
remoteRunspace.Events.ReceivedEvents.PSEventReceived += OnRunspacePSEventReceived;
Pipeline pipeline = CreatePipeline(remoteRunspace);
IThrottleOperation operation =
new ExecutionCmdletHelperComputerName(remoteRunspace, pipeline);
Operations.Add(operation);
}
/// <summary>
/// The expression will be executed in the remote computer if a
/// remote runspace parameter or computer name is specified. If
/// none other than command parameter is specified, then it
/// just executes the command locally without creating a new
/// remote runspace object.
/// </summary>
protected override void ProcessRecord()
{
if (ParameterSetName == DefinitionNameParameterSet)
{
// Get the Job2 object from the Job Manager for this definition name and start the job.
string resolvedPath = null;
if (!string.IsNullOrEmpty(_definitionPath))
{
ProviderInfo provider = null;
System.Collections.ObjectModel.Collection<string> paths =
this.Context.SessionState.Path.GetResolvedProviderPathFromPSPath(_definitionPath, out provider);
// Only file system paths are allowed.
if (!provider.NameEquals(this.Context.ProviderNames.FileSystem))
{
string message = StringUtil.Format(RemotingErrorIdStrings.StartJobDefinitionPathInvalidNotFSProvider,
_definitionName,
_definitionPath,
provider.FullName);
WriteError(new ErrorRecord(new RuntimeException(message), "StartJobFromDefinitionNamePathInvalidNotFileSystemProvider",
ErrorCategory.InvalidArgument, null));
return;
}
// Only a single file path is allowed.
if (paths.Count != 1)
{
string message = StringUtil.Format(RemotingErrorIdStrings.StartJobDefinitionPathInvalidNotSingle,
_definitionName,
_definitionPath);
WriteError(new ErrorRecord(new RuntimeException(message), "StartJobFromDefinitionNamePathInvalidNotSingle",
ErrorCategory.InvalidArgument, null));
return;
}
resolvedPath = paths[0];
}
List<Job2> jobs = JobManager.GetJobToStart(_definitionName, resolvedPath, _definitionType, this, false);
if (jobs.Count == 0)
{
string message = (_definitionType != null) ?
StringUtil.Format(RemotingErrorIdStrings.StartJobDefinitionNotFound2, _definitionType, _definitionName) :
StringUtil.Format(RemotingErrorIdStrings.StartJobDefinitionNotFound1, _definitionName);
WriteError(new ErrorRecord(new RuntimeException(message), "StartJobFromDefinitionNameNotFound",
ErrorCategory.ObjectNotFound, null));
return;
}
if (jobs.Count > 1)
{
string message = StringUtil.Format(RemotingErrorIdStrings.StartJobManyDefNameMatches, _definitionName);
WriteError(new ErrorRecord(new RuntimeException(message), "StartJobFromDefinitionNameMoreThanOneMatch",
ErrorCategory.InvalidResult, null));
return;
}
// Start job.
Job2 job = jobs[0];
job.StartJob();
// Write job object to host.
WriteObject(job);
return;
}
if (_firstProcessRecord)
{
_firstProcessRecord = false;
PSRemotingJob job = new PSRemotingJob(ResolvedComputerNames, Operations,
ScriptBlock.ToString(), ThrottleLimit, _name);
job.PSJobTypeName = s_startJobType;
this.JobRepository.Add(job);
WriteObject(job);
}
// inject input
if (InputObject != AutomationNull.Value)
{
foreach (IThrottleOperation operation in Operations)
{
ExecutionCmdletHelper helper = (ExecutionCmdletHelper)operation;
helper.Pipeline.Input.Write(InputObject);
}
}
} // ProcessRecord
private bool _firstProcessRecord = true;
/// <summary>
/// InvokeAsync would have been called in ProcessRecord. Wait here
/// for all the results to become available.
/// </summary>
protected override void EndProcessing()
{
// close the input stream on all the pipelines
CloseAllInputStreams();
} // EndProcessing
#endregion Overrides
#region IDisposable Overrides
/// <summary>
/// Dispose the cmdlet
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// internal dispose method which does the actual disposing
/// </summary>
/// <param name="disposing">whether called from dispose or finalize</param>
private void Dispose(bool disposing)
{
if (disposing)
{
CloseAllInputStreams();
}
} // Dispose
#endregion IDisposable Overrides
}
}
| |
// 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 Internal.NativeCrypto;
using System.Diagnostics;
using System.IO;
namespace System.Security.Cryptography
{
public sealed class DSACryptoServiceProvider : DSA, ICspAsymmetricAlgorithm
{
private int _keySize;
private readonly CspParameters _parameters;
private readonly bool _randomKeyContainer;
private SafeKeyHandle _safeKeyHandle;
private SafeProvHandle _safeProvHandle;
private SHA1 _sha1;
private static volatile CspProviderFlags s_useMachineKeyStore = 0;
/// <summary>
/// Initializes a new instance of the DSACryptoServiceProvider class.
/// </summary>
public DSACryptoServiceProvider()
: this(
new CspParameters(CapiHelper.DefaultDssProviderType,
null,
null,
s_useMachineKeyStore))
{
}
/// <summary>
/// Initializes a new instance of the DSACryptoServiceProvider class with the specified key size.
/// </summary>
/// <param name="dwKeySize">The size of the key for the asymmetric algorithm in bits.</param>
public DSACryptoServiceProvider(int dwKeySize)
: this(dwKeySize,
new CspParameters(CapiHelper.DefaultDssProviderType,
null,
null,
s_useMachineKeyStore))
{
}
/// <summary>
/// Initializes a new instance of the DSACryptoServiceProvider class with the specified parameters
/// for the cryptographic service provider (CSP).
/// </summary>
/// <param name="parameters">The parameters for the CSP.</param>
public DSACryptoServiceProvider(CspParameters parameters)
: this(0, parameters)
{
}
/// <summary>
/// Initializes a new instance of the DSACryptoServiceProvider class with the specified key size and parameters
/// for the cryptographic service provider (CSP).
/// </summary>
/// <param name="dwKeySize">The size of the key for the cryptographic algorithm in bits.</param>
/// <param name="parameters">The parameters for the CSP.</param>
public DSACryptoServiceProvider(int dwKeySize, CspParameters parameters)
{
if (dwKeySize < 0)
throw new ArgumentOutOfRangeException(nameof(dwKeySize), SR.ArgumentOutOfRange_NeedNonNegNum);
_parameters = CapiHelper.SaveCspParameters(
CapiHelper.CspAlgorithmType.Dss,
parameters,
s_useMachineKeyStore,
out _randomKeyContainer);
_keySize = dwKeySize;
_sha1 = SHA1.Create();
// If this is not a random container we generate, create it eagerly
// in the constructor so we can report any errors now.
if (!_randomKeyContainer)
{
// Force-read the SafeKeyHandle property, which will summon it into existence.
SafeKeyHandle localHandle = SafeKeyHandle;
Debug.Assert(localHandle != null);
}
}
private SafeProvHandle SafeProvHandle
{
get
{
if (_safeProvHandle == null)
{
lock (_parameters)
{
if (_safeProvHandle == null)
{
SafeProvHandle hProv = CapiHelper.CreateProvHandle(_parameters, _randomKeyContainer);
Debug.Assert(hProv != null);
Debug.Assert(!hProv.IsInvalid);
Debug.Assert(!hProv.IsClosed);
_safeProvHandle = hProv;
}
}
return _safeProvHandle;
}
return _safeProvHandle;
}
set
{
lock (_parameters)
{
SafeProvHandle current = _safeProvHandle;
if (ReferenceEquals(value, current))
{
return;
}
if (current != null)
{
SafeKeyHandle keyHandle = _safeKeyHandle;
_safeKeyHandle = null;
keyHandle?.Dispose();
current.Dispose();
}
_safeProvHandle = value;
}
}
}
private SafeKeyHandle SafeKeyHandle
{
get
{
if (_safeKeyHandle == null)
{
lock (_parameters)
{
if (_safeKeyHandle == null)
{
SafeKeyHandle hKey = CapiHelper.GetKeyPairHelper(
CapiHelper.CspAlgorithmType.Dss,
_parameters,
_keySize,
SafeProvHandle);
Debug.Assert(hKey != null);
Debug.Assert(!hKey.IsInvalid);
Debug.Assert(!hKey.IsClosed);
_safeKeyHandle = hKey;
}
}
}
return _safeKeyHandle;
}
set
{
lock (_parameters)
{
SafeKeyHandle current = _safeKeyHandle;
if (ReferenceEquals(value, current))
{
return;
}
_safeKeyHandle = value;
current?.Dispose();
}
}
}
/// <summary>
/// Gets a CspKeyContainerInfo object that describes additional information about a cryptographic key pair.
/// </summary>
public CspKeyContainerInfo CspKeyContainerInfo
{
get
{
// Desktop compat: Read the SafeKeyHandle property to force the key to load,
// because it might throw here.
SafeKeyHandle localHandle = SafeKeyHandle;
Debug.Assert(localHandle != null);
return new CspKeyContainerInfo(_parameters, _randomKeyContainer);
}
}
public override int KeySize
{
get
{
byte[] keySize = CapiHelper.GetKeyParameter(SafeKeyHandle, Constants.CLR_KEYLEN);
_keySize = (keySize[0] | (keySize[1] << 8) | (keySize[2] << 16) | (keySize[3] << 24));
return _keySize;
}
}
public override KeySizes[] LegalKeySizes
{
get
{
return new[] { new KeySizes(512, 1024, 64) }; // per FIPS 186-2
}
}
/// <summary>
/// Gets or sets a value indicating whether the key should be persisted in the cryptographic
/// service provider (CSP).
/// </summary>
public bool PersistKeyInCsp
{
get
{
return CapiHelper.GetPersistKeyInCsp(SafeProvHandle);
}
set
{
bool oldPersistKeyInCsp = this.PersistKeyInCsp;
if (value == oldPersistKeyInCsp)
{
return; // Do nothing
}
CapiHelper.SetPersistKeyInCsp(SafeProvHandle, value);
}
}
/// <summary>
/// Gets a value that indicates whether the DSACryptoServiceProvider object contains
/// only a public key.
/// </summary>
public bool PublicOnly
{
get
{
byte[] publicKey = CapiHelper.GetKeyParameter(SafeKeyHandle, Constants.CLR_PUBLICKEYONLY);
return (publicKey[0] == 1);
}
}
/// <summary>
/// Gets or sets a value indicating whether the key should be persisted in the computer's
/// key store instead of the user profile store.
/// </summary>
public static bool UseMachineKeyStore
{
get
{
return (s_useMachineKeyStore == CspProviderFlags.UseMachineKeyStore);
}
set
{
s_useMachineKeyStore = (value ? CspProviderFlags.UseMachineKeyStore : 0);
}
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (_safeKeyHandle != null && !_safeKeyHandle.IsClosed)
{
_safeKeyHandle.Dispose();
}
if (_safeProvHandle != null && !_safeProvHandle.IsClosed)
{
_safeProvHandle.Dispose();
}
}
/// <summary>
/// Exports a blob containing the key information associated with an DSACryptoServiceProvider object.
/// </summary>
public byte[] ExportCspBlob(bool includePrivateParameters)
{
return CapiHelper.ExportKeyBlob(includePrivateParameters, SafeKeyHandle);
}
public override DSAParameters ExportParameters(bool includePrivateParameters)
{
byte[] cspBlob = ExportCspBlob(includePrivateParameters);
return cspBlob.ToDSAParameters(includePrivateParameters, SafeKeyHandle);
}
/// <summary>
/// This method helps Acquire the default CSP and avoids the need for static SafeProvHandle
/// in CapiHelper class
/// </summary>
private SafeProvHandle AcquireSafeProviderHandle()
{
SafeProvHandle safeProvHandle;
CapiHelper.AcquireCsp(new CspParameters(CapiHelper.DefaultDssProviderType), out safeProvHandle);
return safeProvHandle;
}
/// <summary>
/// Imports a blob that represents DSA key information.
/// </summary>
/// <param name="keyBlob">A byte array that represents a DSA key blob.</param>
public void ImportCspBlob(byte[] keyBlob)
{
SafeKeyHandle safeKeyHandle;
if (IsPublic(keyBlob))
{
SafeProvHandle safeProvHandleTemp = AcquireSafeProviderHandle();
CapiHelper.ImportKeyBlob(safeProvHandleTemp, (CspProviderFlags)0, keyBlob, out safeKeyHandle);
// The property set will take care of releasing any already-existing resources.
SafeProvHandle = safeProvHandleTemp;
}
else
{
CapiHelper.ImportKeyBlob(SafeProvHandle, _parameters.Flags, keyBlob, out safeKeyHandle);
}
// The property set will take care of releasing any already-existing resources.
SafeKeyHandle = safeKeyHandle;
}
public override void ImportParameters(DSAParameters parameters)
{
byte[] keyBlob = parameters.ToKeyBlob();
ImportCspBlob(keyBlob);
}
/// <summary>
/// Computes the hash value of the specified input stream and signs the resulting hash value.
/// </summary>
/// <param name="inputStream">The input data for which to compute the hash.</param>
/// <returns>The DSA signature for the specified data.</returns>
public byte[] SignData(Stream inputStream)
{
byte[] hashVal = _sha1.ComputeHash(inputStream);
return SignHash(hashVal, null);
}
/// <summary>
/// Computes the hash value of the specified input stream and signs the resulting hash value.
/// </summary>
/// <param name="buffer">The input data for which to compute the hash.</param>
/// <returns>The DSA signature for the specified data.</returns>
public byte[] SignData(byte[] buffer)
{
byte[] hashVal = _sha1.ComputeHash(buffer);
return SignHash(hashVal, null);
}
/// <summary>
/// Signs a byte array from the specified start point to the specified end point.
/// </summary>
/// <param name="buffer">The input data to sign.</param>
/// <param name="offset">The offset into the array from which to begin using data.</param>
/// <param name="count">The number of bytes in the array to use as data.</param>
/// <returns>The DSA signature for the specified data.</returns>
public byte[] SignData(byte[] buffer, int offset, int count)
{
byte[] hashVal = _sha1.ComputeHash(buffer, offset, count);
return SignHash(hashVal, null);
}
/// <summary>
/// Verifies the specified signature data by comparing it to the signature computed for the specified data.
/// </summary>
/// <param name="rgbData">The data that was signed.</param>
/// <param name="rgbSignature">The signature data to be verified.</param>
/// <returns>true if the signature verifies as valid; otherwise, false.</returns>
public bool VerifyData(byte[] rgbData, byte[] rgbSignature)
{
byte[] hashVal = _sha1.ComputeHash(rgbData);
return VerifyHash(hashVal, null, rgbSignature);
}
/// <summary>
/// Creates the DSA signature for the specified data.
/// </summary>
/// <param name="rgbHash">The data to be signed.</param>
/// <returns>The digital signature for the specified data.</returns>
override public byte[] CreateSignature(byte[] rgbHash)
{
return SignHash(rgbHash, null);
}
override public bool VerifySignature(byte[] rgbHash, byte[] rgbSignature)
{
return VerifyHash(rgbHash, null, rgbSignature);
}
protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm)
{
// we're sealed and the base should have checked this before calling us
Debug.Assert(data != null);
Debug.Assert(offset >= 0 && offset <= data.Length);
Debug.Assert(count >= 0 && count <= data.Length - offset);
Debug.Assert(!string.IsNullOrEmpty(hashAlgorithm.Name));
if (hashAlgorithm != HashAlgorithmName.SHA1)
{
throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithm.Name);
}
return _sha1.ComputeHash(data, offset, count);
}
protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm)
{
// we're sealed and the base should have checked this before calling us
Debug.Assert(data != null);
Debug.Assert(!string.IsNullOrEmpty(hashAlgorithm.Name));
if (hashAlgorithm != HashAlgorithmName.SHA1)
{
throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithm.Name);
}
return _sha1.ComputeHash(data);
}
/// <summary>
/// Computes the signature for the specified hash value by encrypting it with the private key.
/// </summary>
/// <param name="rgbHash">The hash value of the data to be signed.</param>
/// <param name="str">The name of the hash algorithm used to create the hash value of the data.</param>
/// <returns>The DSA signature for the specified hash value.</returns>
public byte[] SignHash(byte[] rgbHash, string str)
{
if (rgbHash == null)
throw new ArgumentNullException(nameof(rgbHash));
if (PublicOnly)
throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey);
int calgHash = CapiHelper.NameOrOidToHashAlgId(str);
if (rgbHash.Length != _sha1.HashSize / 8)
throw new CryptographicException(string.Format(SR.Cryptography_InvalidHashSize, "SHA1", _sha1.HashSize / 8));
return CapiHelper.SignValue(
SafeProvHandle,
SafeKeyHandle,
_parameters.KeyNumber,
CapiHelper.CALG_DSS_SIGN,
calgHash,
rgbHash);
}
/// <summary>
/// Verifies the specified signature data by comparing it to the signature computed for the specified hash value.
/// </summary>
/// <param name="rgbHash">The hash value of the data to be signed.</param>
/// <param name="str">The name of the hash algorithm used to create the hash value of the data.</param>
/// <param name="rgbSignature">The signature data to be verified.</param>
/// <returns>true if the signature verifies as valid; otherwise, false.</returns>
public bool VerifyHash(byte[] rgbHash, string str, byte[] rgbSignature)
{
if (rgbHash == null)
throw new ArgumentNullException(nameof(rgbHash));
if (rgbSignature == null)
throw new ArgumentNullException(nameof(rgbSignature));
int calgHash = CapiHelper.NameOrOidToHashAlgId(str);
return CapiHelper.VerifySign(
SafeProvHandle,
SafeKeyHandle,
CapiHelper.CALG_DSS_SIGN,
calgHash,
rgbHash,
rgbSignature);
}
/// <summary>
/// Find whether a DSS key blob is public.
/// </summary>
private static bool IsPublic(byte[] keyBlob)
{
if (keyBlob == null)
{
throw new ArgumentNullException(nameof(keyBlob));
}
// The CAPI DSS public key representation consists of the following sequence:
// - BLOBHEADER (the first byte is bType)
// - DSSPUBKEY or DSSPUBKEY_VER3 (the first field is the magic field)
// The first byte should be PUBLICKEYBLOB
if (keyBlob[0] != CapiHelper.PUBLICKEYBLOB)
{
return false;
}
// Magic should be DSS_MAGIC or DSS_PUB_MAGIC_VER3
if ((keyBlob[11] != 0x31 && keyBlob[11] != 0x33) || keyBlob[10] != 0x53 || keyBlob[9] != 0x53 || keyBlob[8] != 0x44)
{
return false;
}
return true;
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic{
/// <summary>
/// Strongly-typed collection for the ConTurnosDelDiaSinAsistencium class.
/// </summary>
[Serializable]
public partial class ConTurnosDelDiaSinAsistenciumCollection : ReadOnlyList<ConTurnosDelDiaSinAsistencium, ConTurnosDelDiaSinAsistenciumCollection>
{
public ConTurnosDelDiaSinAsistenciumCollection() {}
}
/// <summary>
/// This is Read-only wrapper class for the CON_TurnosDelDiaSinAsistencia view.
/// </summary>
[Serializable]
public partial class ConTurnosDelDiaSinAsistencium : ReadOnlyRecord<ConTurnosDelDiaSinAsistencium>, IReadOnlyRecord
{
#region Default Settings
protected static void SetSQLProps()
{
GetTableSchema();
}
#endregion
#region Schema Accessor
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
{
SetSQLProps();
}
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("CON_TurnosDelDiaSinAsistencia", TableType.View, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema);
colvarNombre.ColumnName = "nombre";
colvarNombre.DataType = DbType.String;
colvarNombre.MaxLength = 100;
colvarNombre.AutoIncrement = false;
colvarNombre.IsNullable = false;
colvarNombre.IsPrimaryKey = false;
colvarNombre.IsForeignKey = false;
colvarNombre.IsReadOnly = false;
schema.Columns.Add(colvarNombre);
TableSchema.TableColumn colvarCantidadTurnos = new TableSchema.TableColumn(schema);
colvarCantidadTurnos.ColumnName = "cantidadTurnos";
colvarCantidadTurnos.DataType = DbType.Int32;
colvarCantidadTurnos.MaxLength = 0;
colvarCantidadTurnos.AutoIncrement = false;
colvarCantidadTurnos.IsNullable = true;
colvarCantidadTurnos.IsPrimaryKey = false;
colvarCantidadTurnos.IsForeignKey = false;
colvarCantidadTurnos.IsReadOnly = false;
schema.Columns.Add(colvarCantidadTurnos);
TableSchema.TableColumn colvarIdAgenda = new TableSchema.TableColumn(schema);
colvarIdAgenda.ColumnName = "idAgenda";
colvarIdAgenda.DataType = DbType.Int32;
colvarIdAgenda.MaxLength = 0;
colvarIdAgenda.AutoIncrement = false;
colvarIdAgenda.IsNullable = false;
colvarIdAgenda.IsPrimaryKey = false;
colvarIdAgenda.IsForeignKey = false;
colvarIdAgenda.IsReadOnly = false;
schema.Columns.Add(colvarIdAgenda);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("CON_TurnosDelDiaSinAsistencia",schema);
}
}
#endregion
#region Query Accessor
public static Query CreateQuery()
{
return new Query(Schema);
}
#endregion
#region .ctors
public ConTurnosDelDiaSinAsistencium()
{
SetSQLProps();
SetDefaults();
MarkNew();
}
public ConTurnosDelDiaSinAsistencium(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
{
ForceDefaults();
}
MarkNew();
}
public ConTurnosDelDiaSinAsistencium(object keyID)
{
SetSQLProps();
LoadByKey(keyID);
}
public ConTurnosDelDiaSinAsistencium(string columnName, object columnValue)
{
SetSQLProps();
LoadByParam(columnName,columnValue);
}
#endregion
#region Props
[XmlAttribute("Nombre")]
[Bindable(true)]
public string Nombre
{
get
{
return GetColumnValue<string>("nombre");
}
set
{
SetColumnValue("nombre", value);
}
}
[XmlAttribute("CantidadTurnos")]
[Bindable(true)]
public int? CantidadTurnos
{
get
{
return GetColumnValue<int?>("cantidadTurnos");
}
set
{
SetColumnValue("cantidadTurnos", value);
}
}
[XmlAttribute("IdAgenda")]
[Bindable(true)]
public int IdAgenda
{
get
{
return GetColumnValue<int>("idAgenda");
}
set
{
SetColumnValue("idAgenda", value);
}
}
#endregion
#region Columns Struct
public struct Columns
{
public static string Nombre = @"nombre";
public static string CantidadTurnos = @"cantidadTurnos";
public static string IdAgenda = @"idAgenda";
}
#endregion
#region IAbstractRecord Members
public new CT GetColumnValue<CT>(string columnName) {
return base.GetColumnValue<CT>(columnName);
}
public object GetColumnValue(string columnName) {
return base.GetColumnValue<object>(columnName);
}
#endregion
}
}
| |
namespace Labo.TwitterMiner.Data.Services
{
using System.Linq;
using Labo.Common.Data.Repository;
using Labo.Common.Data.Session;
using Labo.TwitterMiner.Entity;
using Labo.TwitterMiner.Services;
internal sealed class TwitterTweetPersistenceProcessor : ITwitterTweetProcessor
{
private readonly ISessionScopeProvider m_SessionScopeProvider;
public TwitterTweetPersistenceProcessor(ISessionScopeProvider sessionScopeProvider)
{
m_SessionScopeProvider = sessionScopeProvider;
}
public void Process(TwitterTweet tweet)
{
using (ISessionScope sessionScope = m_SessionScopeProvider.CreateSessionScope())
{
IRepository<TwitterTweet> tweetRepository = sessionScope.GetRepository<TwitterTweet>();
if (!tweetRepository.Query().Any(x => x.ID == tweet.ID))
{
InsertUser(tweet, sessionScope);
TwitterTweet newTweet = new TwitterTweet
{
CreateDate = tweet.CreateDate,
ID = tweet.ID,
InReplyToScreenName = tweet.InReplyToScreenName,
InReplyToStatusId = tweet.InReplyToStatusId,
InReplyToUserId = tweet.InReplyToUserId,
Latitude = tweet.Latitude,
Longitude = tweet.Longitude,
PlaceID = tweet.PlaceID,
RetweetCount = tweet.RetweetCount,
Source = tweet.Source,
Text = tweet.Text,
TextAsHtml = tweet.TextAsHtml,
TextDecoded = tweet.TextDecoded,
TextClear = tweet.TextClear,
UserID = tweet.UserID,
};
InsertPlace(tweet, sessionScope);
InsertHashTags(newTweet, sessionScope, tweet);
InsertMedias(sessionScope, newTweet, tweet);
InsertUrls(sessionScope, newTweet, tweet);
tweetRepository.Insert(newTweet);
tweetRepository.SaveChanges();
sessionScope.Complete();
}
}
}
private static void InsertUser(TwitterTweet tweet, ISessionScope sessionScope)
{
TwitterUser user = tweet.TwitterUser;
IRepository<TwitterUser> userRepository = sessionScope.GetRepository<TwitterUser>();
if (!userRepository.Query().Any(x => x.ID == user.ID))
{
TwitterUser newUser = new TwitterUser
{
CreateDate = user.CreateDate,
Description = user.Description,
ID = user.ID,
LanguageID = user.LanguageID,
Location = user.Location,
Name = user.Name,
ProfileImageUrl = user.ProfileImageUrl,
ProfileImageUrlHttps = user.ProfileImageUrlHttps,
ScreenName = user.ScreenName,
Url = user.Url
};
InsertLanguage(sessionScope, newUser, user);
userRepository.Insert(newUser);
userRepository.SaveChanges();
}
}
private static void InsertLanguage(ISessionScope sessionScope, TwitterUser newUser, TwitterUser user)
{
TwitterLanguage language = user.TwitterLanguage;
if (language != null)
{
IRepository<TwitterLanguage> languageRepository = sessionScope.GetRepository<TwitterLanguage>();
int? languageID = languageRepository.Query()
.Where(x => x.Code == language.Code)
.Select(x => (int?)x.ID)
.SingleOrDefault();
if (!languageID.HasValue)
{
TwitterLanguage newLanguage = new TwitterLanguage
{
Code = language.Code
};
languageRepository.Insert(newLanguage);
languageRepository.SaveChanges();
newUser.LanguageID = newLanguage.ID;
}
else
{
newUser.LanguageID = languageID.Value;
}
}
}
private static void InsertPlace(TwitterTweet tweet, ISessionScope sessionScope)
{
TwitterPlace twitterPlace = tweet.TwitterPlace;
if (twitterPlace != null)
{
IRepository<TwitterPlace> placeRepository = sessionScope.GetRepository<TwitterPlace>();
string placeID = placeRepository.Query().Where(x => x.ID == twitterPlace.ID).Select(x => x.ID).SingleOrDefault();
if (placeID == null)
{
TwitterPlace newTwitterPlace = new TwitterPlace
{
FullName = twitterPlace.FullName,
ID = twitterPlace.ID,
Name = twitterPlace.Name,
PlaceType = twitterPlace.PlaceType,
Url = twitterPlace.Url
};
InsertCountry(sessionScope, newTwitterPlace, twitterPlace);
placeRepository.Insert(newTwitterPlace);
}
}
}
private static void InsertCountry(ISessionScope sessionScope, TwitterPlace newTwitterPlace, TwitterPlace twitterPlace)
{
TwitterCountry twitterCountry = twitterPlace.TwitterCountry;
if (twitterCountry != null)
{
IRepository<TwitterCountry> countryRepository = sessionScope.GetRepository<TwitterCountry>();
int? countryID = countryRepository
.Query()
.Where(x => x.Code == twitterCountry.Code)
.Select(x => (int?)x.ID)
.SingleOrDefault();
if (countryID.HasValue)
{
newTwitterPlace.CountryID = countryID.Value;
}
else
{
TwitterCountry newTwitterCountry = new TwitterCountry
{
Code = twitterCountry.Code,
Name = twitterCountry.Name
};
countryRepository.Insert(newTwitterCountry);
countryRepository.SaveChanges();
newTwitterPlace.CountryID = newTwitterCountry.ID;
}
}
}
private void InsertUrls(ISessionScope sessionScope, TwitterTweet newTweet, TwitterTweet tweet)
{
foreach (TwitterUrl twitterUrl in tweet.TwitterUrls)
{
IRepository<TwitterUrl> urlRepository = sessionScope.GetRepository<TwitterUrl>();
TwitterUrl currentUrl = urlRepository.Query().SingleOrDefault(x => x.ID == twitterUrl.ID);
if (currentUrl != null)
{
newTweet.TwitterUrls.Add(currentUrl);
}
else
{
string siteUrl = twitterUrl.TwitterSite.SiteUrl;
IRepository<TwitterSite> siteRepository = sessionScope.GetRepository<TwitterSite>();
TwitterSite twitterSite = siteRepository.Query().SingleOrDefault(x => x.SiteUrl == siteUrl);
if (twitterSite == null)
{
twitterSite = new TwitterSite();
twitterSite.SiteUrl = siteUrl;
siteRepository.Insert(twitterSite);
siteRepository.SaveChanges();
}
twitterUrl.TwitterSite = twitterSite;
twitterUrl.SiteID = twitterSite.ID;
urlRepository.Insert(twitterUrl);
urlRepository.SaveChanges();
newTweet.TwitterUrls.Add(twitterUrl);
}
}
}
private static void InsertMedias(ISessionScope sessionScope, TwitterTweet newTweet, TwitterTweet tweet)
{
foreach (TwitterMedia twitterMedia in tweet.TwitterMedias)
{
IRepository<TwitterMedia> mediaRepository = sessionScope.GetRepository<TwitterMedia>();
TwitterMedia currentMedia = mediaRepository.Query().SingleOrDefault(x => x.ID == twitterMedia.ID);
if (currentMedia != null)
{
newTweet.TwitterMedias.Add(currentMedia);
}
else
{
mediaRepository.Insert(twitterMedia);
mediaRepository.SaveChanges();
newTweet.TwitterMedias.Add(twitterMedia);
}
}
}
private static void InsertHashTags(TwitterTweet newTweet, ISessionScope sessionScope, TwitterTweet tweet)
{
foreach (TwitterHashTag twitterHashTag in tweet.TwitterHashTags)
{
IRepository<TwitterHashTag> twitterRepository = sessionScope.GetRepository<TwitterHashTag>();
TwitterHashTag currentHashTag = twitterRepository.Query().SingleOrDefault(x => x.Name == twitterHashTag.Name);
if (currentHashTag != null)
{
newTweet.TwitterHashTags.Add(currentHashTag);
}
else
{
TwitterHashTag newHashTag = new TwitterHashTag
{
Name = twitterHashTag.Name
};
twitterRepository.Insert(newHashTag);
twitterRepository.SaveChanges();
newTweet.TwitterHashTags.Add(newHashTag);
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Invio.Xunit;
using Xunit;
namespace Invio.Validation {
[UnitTest]
public class OperationResultTests {
[Fact]
public void Constructor_NullValidationResults_NonGeneric() {
// Act
var exception = Record.Exception(
() => new OperationResult(null)
);
// Assert
Assert.IsType<ArgumentNullException>(exception);
}
[Fact]
public void Constructor_NullValidationResults_Generic() {
// Act
var exception = Record.Exception(
() => new OperationResult<Int32>((ISet<ValidationIssue>) null)
);
// Assert
Assert.IsType<ArgumentNullException>(exception);
}
[Fact]
public void Success_IsSuccessful_NonGeneric() {
Assert.NotNull(OperationResult.Success);
Assert.True(OperationResult.Success.IsSuccessful);
Assert.NotNull(OperationResult.Success.ValidationIssues);
Assert.Empty(OperationResult.Success.ValidationIssues);
}
[Fact]
public void Success_IsSuccessful_Generic() {
var result = new OperationResult<Object>();
Assert.True(result.IsSuccessful);
Assert.Equal(default(Object), result.Value);
Assert.NotNull(OperationResult.Success.ValidationIssues);
Assert.Empty(OperationResult.Success.ValidationIssues);
}
[Fact]
public void IsSuccessful_TrueWithoutResults_NonGeneric() {
// Arrange
var validationIssues = ImmutableHashSet<ValidationIssue>.Empty;
// Act
var result = new OperationResult(validationIssues);
// Assert
Assert.True(result.IsSuccessful);
Assert.Empty(result.ValidationIssues);
}
[Fact]
public void IsSuccessful_TrueWithoutResults_Generic() {
// Arrange
var validationIssues = ImmutableHashSet<ValidationIssue>.Empty;
// Act
var result = new OperationResult<Object>(validationIssues);
// Assert
Assert.True(result.IsSuccessful);
Assert.Empty(result.ValidationIssues);
Assert.Equal(default(Object), result.Value);
}
[Fact]
public void IsSuccessful_TrueWithWarnings_NonGeneric() {
// Arrange
const string message = "WarnFoo";
var validationIssues = ImmutableHashSet.Create(ValidationIssue.Warning(message));
// Act
var result = new OperationResult(validationIssues);
// Assert
Assert.True(result.IsSuccessful);
Assert.NotEmpty(result.ValidationIssues);
}
[Fact]
public void IsSuccessful_TrueWithWarnings_Generic() {
// Arrange
const string message = "WarnFoo";
var validationIssues = ImmutableHashSet.Create(ValidationIssue.Warning(message));
// Act
var result = new OperationResult<Object>(validationIssues);
// Assert
Assert.True(result.IsSuccessful);
Assert.NotEmpty(result.ValidationIssues);
Assert.Equal(default(Object), result.Value);
}
[Fact]
public void IsSuccessful_TrueWithResult_Generic() {
// Arrange
var realResult = new Object();
// Act
var result = new OperationResult<Object>(realResult);
// Assert
Assert.True(result.IsSuccessful);
Assert.Empty(result.ValidationIssues);
Assert.Equal(realResult, result.Value);
}
[Fact]
public void IsSuccessful_FalseWithResults_NonGeneric() {
// Arrange
const string message = "Foo";
var validationIssues = ImmutableHashSet.Create(ValidationIssue.Error(message));
// Act
var result = new OperationResult(validationIssues);
// Assert
Assert.False(result.IsSuccessful);
var validationResult = Assert.Single(result.ValidationIssues);
Assert.Equal(message, validationResult.Message);
}
[Fact]
public void IsSuccessful_FalseWithResults_Generic() {
// Arrange
const string message = "Foo";
var validationIssues = ImmutableHashSet.Create(ValidationIssue.Error(message));
// Act
var result = new OperationResult<Object>(validationIssues);
// Assert
Assert.False(result.IsSuccessful);
var validationIssue = Assert.Single(result.ValidationIssues);
Assert.Equal(message, validationIssue.Message);
Assert.Equal(default(Object), result.Value);
}
[Fact]
public void AddValidationIssue_NullValidationResult_NonGeneric() {
// Arrange
var result = OperationResult.Success;
// Act
var exception = Record.Exception(
() => result.AddValidationIssue(null)
);
// Assert
Assert.IsType<ArgumentNullException>(exception);
}
[Fact]
public void AddValidationIssue_NullValidationResult_Generic() {
// Arrange
var result = new OperationResult<Object>();
// Act
var exception = Record.Exception(
() => result.AddValidationIssue(null)
);
// Assert
Assert.IsType<ArgumentNullException>(exception);
}
[Fact]
public void AddValidationIssue_ImmutableAndCombinesResults_NonGeneric() {
// Arrange
var validationIssueOne = ValidationIssue.Error("Foo");
var validationIssueTwo = ValidationIssue.Error("Bar");
var original = new OperationResult(ImmutableHashSet.Create(validationIssueOne));
// Act
var updated = original.AddValidationIssue(validationIssueTwo);
// Assert
Assert.NotEqual(original, updated);
Assert.Contains(validationIssueOne, updated.ValidationIssues);
Assert.Contains(validationIssueTwo, updated.ValidationIssues);
}
[Fact]
public void AddValidationIssue_ImmutableAndCombinesResults_Generic() {
// Arrange
var validationIssueOne = ValidationIssue.Error("Foo");
var validationIssueTwo = ValidationIssue.Error("Bar");
var original = new OperationResult<Object>(ImmutableHashSet.Create(validationIssueOne));
// Act
var updated = original.AddValidationIssue(validationIssueTwo);
// Assert
Assert.NotEqual(original, updated);
Assert.Contains(validationIssueOne, updated.ValidationIssues);
Assert.Contains(validationIssueTwo, updated.ValidationIssues);
}
[Fact]
public void AddValidationIssues_NullValidationResults_NonGeneric() {
// Arrange
var result = OperationResult.Success;
// Act
var exception = Record.Exception(
() => result.AddValidationIssues(null)
);
// Assert
Assert.IsType<ArgumentNullException>(exception);
}
[Fact]
public void AddValidationIssues_NullValidationResults_Generic() {
// Arrange
var result = new OperationResult<Object>();
// Act
var exception = Record.Exception(
() => result.AddValidationIssues(null)
);
// Assert
Assert.IsType<ArgumentNullException>(exception);
}
[Theory]
[InlineData(0, 0)]
[InlineData(1, 0)]
[InlineData(0, 1)]
[InlineData(2, 2)]
public void AddValidationIssues_ImmutableAndCombineResults_NonGeneric(
int initialNumberOfValidationResults,
int additionalNumberOfValidationResults) {
// Arrange
var initialValidationIssues =
this.GenerateValidationIssues(initialNumberOfValidationResults)
.ToImmutableHashSet();
var additionalValidationIssues =
this.GenerateValidationIssues(additionalNumberOfValidationResults)
.ToImmutableHashSet();
var initial = new OperationResult(initialValidationIssues);
// Act
var updated = initial.AddValidationIssues(additionalValidationIssues);
// Assert
Assert.Equal(
initialNumberOfValidationResults + additionalNumberOfValidationResults,
updated.ValidationIssues.Count
);
foreach (var validationIssue in initialValidationIssues) {
Assert.Contains(validationIssue, updated.ValidationIssues);
}
foreach (var validationIssue in additionalValidationIssues) {
Assert.Contains(validationIssue, updated.ValidationIssues);
Assert.DoesNotContain(validationIssue, initial.ValidationIssues);
}
}
[Theory]
[InlineData(0, 0)]
[InlineData(1, 0)]
[InlineData(0, 1)]
[InlineData(2, 2)]
public void AddValidationResults_ImmutableAndCombineResults_Generic(
int initialNumberOfValidationIssues,
int additionalNumberOfValidationIssues) {
// Arrange
var initialValidationIssues =
this.GenerateValidationIssues(initialNumberOfValidationIssues)
.ToImmutableHashSet();
var additionalValidationIssues =
this.GenerateValidationIssues(additionalNumberOfValidationIssues)
.ToImmutableHashSet();
var initial = new OperationResult<Object>(initialValidationIssues);
// Act
var updated = initial.AddValidationIssues(additionalValidationIssues);
// Assert
Assert.Equal(
initialNumberOfValidationIssues + additionalNumberOfValidationIssues,
updated.ValidationIssues.Count
);
foreach (var validationIssue in initialValidationIssues) {
Assert.Contains(validationIssue, updated.ValidationIssues);
}
foreach (var validationIssue in additionalValidationIssues) {
Assert.Contains(validationIssue, updated.ValidationIssues);
Assert.DoesNotContain(validationIssue, initial.ValidationIssues);
}
}
[Fact]
public void AddWarning_NullMessage_NonGeneric() {
// Arrange
var initial = OperationResult.Success;
// Act
var exception = Record.Exception(
() => initial.AddWarning(null)
);
// Assert
Assert.IsType<ArgumentNullException>(exception);
}
[Fact]
public void AddWarning_NullMessage_Generic() {
// Arrange
var initial = new OperationResult<Object>();
// Act
var exception = Record.Exception(
() => initial.AddWarning(null)
);
// Assert
Assert.IsType<ArgumentNullException>(exception);
}
[Fact]
public void AddWarning_WhiteSpaceMessage_NonGeneric() {
// Arrange
var initial = OperationResult.Success;
// Act
var exception = Record.Exception(
() => initial.AddWarning(" ")
);
// Assert
Assert.IsType<ArgumentException>(exception);
}
[Fact]
public void AddWarning_WhiteSpaceMessage_Generic() {
// Arrange
var initial = new OperationResult<Object>();
// Act
var exception = Record.Exception(
() => initial.AddWarning(" ")
);
// Assert
Assert.IsType<ArgumentException>(exception);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
public void AddWarning_VaryingSets_NonGeneric(
int initialNumberOfValidationIssues) {
// Arrange
var initialValidationIssues =
this.GenerateValidationIssues(initialNumberOfValidationIssues)
.ToImmutableHashSet();
var message = "FooBar";
var initial = new OperationResult(initialValidationIssues);
// Act
var updated = initial.AddWarning(message);
// Assert
var issue = ValidationIssue.Warning(message);
Assert.Contains(issue, updated.ValidationIssues);
Assert.DoesNotContain(issue, initial.ValidationIssues);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
public void AddWarning_VaryingSets_Generic(
int initialNumberOfValidationIssues) {
// Arrange
var initialValidationIssues =
this.GenerateValidationIssues(initialNumberOfValidationIssues)
.ToImmutableHashSet();
var message = "FooBar";
var initial = new OperationResult<Object>(initialValidationIssues);
// Act
var updated = initial.AddWarning(message);
// Assert
var issue = ValidationIssue.Warning(message);
Assert.Contains(issue, updated.ValidationIssues);
Assert.DoesNotContain(issue, initial.ValidationIssues);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
public void AddWarning_VaryingSetsWithCodes_Generic(
int initialNumberOfValidationIssues) {
// Arrange
var initialValidationIssues =
this.GenerateValidationIssues(initialNumberOfValidationIssues)
.ToImmutableHashSet();
var message = "FooBar";
var code = Guid.NewGuid().ToString("N");
var initial = new OperationResult<Object>(initialValidationIssues);
// Act
var updated = initial.AddWarning(message, code);
// Assert
var issue = ValidationIssue.Warning(message, code);
Assert.Contains(issue, updated.ValidationIssues);
Assert.DoesNotContain(issue, initial.ValidationIssues);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
public void AddWarning_VaryingSetsWithMembers_NonGeneric(
int initialNumberOfValidationIssues) {
// Arrange
var initialValidationIssues =
this.GenerateValidationIssues(initialNumberOfValidationIssues)
.ToImmutableHashSet();
var message = "FooBar";
var memberNames = ImmutableHashSet.Create("Foo", "Bar");
var initial = new OperationResult(initialValidationIssues);
// Act
var updated = initial.AddWarning(message, memberNames: memberNames);
// Assert
var issue = ValidationIssue.Warning(message, memberNames: memberNames);
Assert.Contains(issue, updated.ValidationIssues);
Assert.DoesNotContain(issue, initial.ValidationIssues);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
public void AddWarning_VaryingSetsWithMembers_Generic(
int initialNumberOfValidationIssues) {
// Arrange
var initialValidationIssues =
this.GenerateValidationIssues(initialNumberOfValidationIssues)
.ToImmutableHashSet();
var message = "FooBar";
var memberNames = ImmutableHashSet.Create("Foo", "Bar");
var initial = new OperationResult<Object>(initialValidationIssues);
// Act
var updated = initial.AddWarning(message, memberNames);
// Assert
var issue = ValidationIssue.Warning(message, memberNames);
Assert.Contains(issue, updated.ValidationIssues);
Assert.DoesNotContain(issue, initial.ValidationIssues);
}
[Fact]
public void AddError_NullMessage_NonGeneric() {
// Arrange
var initial = OperationResult.Success;
// Act
var exception = Record.Exception(
() => initial.AddError(null)
);
// Assert
Assert.IsType<ArgumentNullException>(exception);
}
[Fact]
public void AddError_NullMessage_Generic() {
// Arrange
var initial = new OperationResult<Object>();
// Act
var exception = Record.Exception(
() => initial.AddError(null)
);
// Assert
Assert.IsType<ArgumentNullException>(exception);
}
[Fact]
public void AddError_WhiteSpaceMessage_NonGeneric() {
// Arrange
var initial = OperationResult.Success;
// Act
var exception = Record.Exception(
() => initial.AddError(" ")
);
// Assert
Assert.IsType<ArgumentException>(exception);
}
[Fact]
public void AddError_WhiteSpaceMessage_Generic() {
// Arrange
var initial = new OperationResult<Object>();
// Act
var exception = Record.Exception(
() => initial.AddError(" ")
);
// Assert
Assert.IsType<ArgumentException>(exception);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
public void AddError_VaryingSets_NonGeneric(
int initialNumberOfValidationIssues) {
// Arrange
var initialValidationIssues =
this.GenerateValidationIssues(initialNumberOfValidationIssues)
.ToImmutableHashSet();
var message = "FooBar";
var initial = new OperationResult(initialValidationIssues);
// Act
var updated = initial.AddError(message);
// Assert
var issue = ValidationIssue.Error(message);
Assert.Contains(issue, updated.ValidationIssues);
Assert.DoesNotContain(issue, initial.ValidationIssues);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
public void AddError_VaryingSets_Generic(
int initialNumberOfValidationIssues) {
// Arrange
var initialValidationIssues =
this.GenerateValidationIssues(initialNumberOfValidationIssues)
.ToImmutableHashSet();
var message = "FooBar";
var initial = new OperationResult<Object>(initialValidationIssues);
// Act
var updated = initial.AddError(message);
// Assert
var issue = ValidationIssue.Error(message);
Assert.Contains(issue, updated.ValidationIssues);
Assert.DoesNotContain(issue, initial.ValidationIssues);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
public void AddError_VaryingSetsWithCodes_Generic(
int initialNumberOfValidationIssues) {
// Arrange
var initialValidationIssues =
this.GenerateValidationIssues(initialNumberOfValidationIssues)
.ToImmutableHashSet();
var message = "FooBar";
var code = Guid.NewGuid().ToString("N");
var initial = new OperationResult<Object>(initialValidationIssues);
// Act
var updated = initial.AddError(message, code);
// Assert
var issue = ValidationIssue.Error(message, code);
Assert.Contains(issue, updated.ValidationIssues);
Assert.DoesNotContain(issue, initial.ValidationIssues);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
public void AddError_VaryingSetsWithMembers_NonGeneric(
int initialNumberOfValidationIssues) {
// Arrange
var initialValidationIssues =
this.GenerateValidationIssues(initialNumberOfValidationIssues)
.ToImmutableHashSet();
var message = "FooBar";
var memberNames = ImmutableHashSet.Create("Foo", "Bar");
var initial = new OperationResult(initialValidationIssues);
// Act
var updated = initial.AddError(message, memberNames: memberNames);
// Assert
var issue = ValidationIssue.Error(message, memberNames);
Assert.Contains(issue, updated.ValidationIssues);
Assert.DoesNotContain(issue, initial.ValidationIssues);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
public void AddError_VaryingSetsWithMembers_Generic(
int initialNumberOfValidationIssues) {
// Arrange
var initialValidationIssues =
this.GenerateValidationIssues(initialNumberOfValidationIssues)
.ToImmutableHashSet();
var message = "FooBar";
var memberNames = ImmutableHashSet.Create("Foo", "Bar");
var initial = new OperationResult<Object>(initialValidationIssues);
// Act
var updated = initial.AddError(message, memberNames);
// Assert
var issue = ValidationIssue.Error(message, memberNames);
Assert.Contains(issue, updated.ValidationIssues);
Assert.DoesNotContain(issue, initial.ValidationIssues);
}
private IEnumerable<ValidationIssue> GenerateValidationIssues(int numberOfIssues) {
foreach (var _ in Enumerable.Range(0, numberOfIssues)) {
yield return ValidationIssue.Error(Guid.NewGuid().ToString());
}
}
}
}
| |
using System.Data;
using Epi.Data.Services;
using Epi.Data;
namespace Epi.Fields
{
/// <summary>
/// Grid column
/// </summary>
public abstract class GridColumnBase : INamedObject
{
#region Fields Members
private int id;
private string name = string.Empty;
private string text = string.Empty;
private bool shouldRepeatLast;
private bool isRequired;
private bool isReadOnly;
private bool isUniqueField;
private int position;
private int width;
private MetaFieldType gridColumnType;
private GridField grid;
#endregion Fields
#region Protected Data
/// <summary>
/// Generic db column type used to translated to specific column type for the DB engine.
/// </summary>
protected GenericDbColumnType genericDbColumnType;
#endregion Protected Data
#region Constructors
/// <summary>
/// Private constructor - not used
/// </summary>
private GridColumnBase()
{
}
/// <summary>
/// Constructor for the class
/// </summary>
public GridColumnBase(GridField grid)
{
this.grid = grid;
}
/// <summary>
/// Constructor for the class
/// </summary>
/// <param name="gridRow">A DataRow containing the grid row's data</param>
/// <param name="grid">The GridField that the row belongs to</param>
public GridColumnBase(DataRow gridRow, GridField grid)
{
this.id = (int)gridRow[ColumnNames.GRID_COLUMN_ID];
this.name = gridRow[ColumnNames.NAME].ToString();
this.text = gridRow[ColumnNames.TEXT].ToString();
this.shouldRepeatLast = (bool)gridRow[ColumnNames.SHOULD_REPEAT_LAST];
this.isRequired = (bool)gridRow[ColumnNames.IS_REQUIRED];
this.isReadOnly = (bool)gridRow[ColumnNames.IS_READ_ONLY];
if (gridRow.Table.Columns.Contains(ColumnNames.IS_UNIQUE_FIELD) && gridRow[ColumnNames.IS_UNIQUE_FIELD] is bool)
{
this.isUniqueField = (bool)gridRow[ColumnNames.IS_UNIQUE_FIELD];
}
else
{
this.isUniqueField = false;
}
this.position = (short)gridRow[ColumnNames.POSITION];
this.width = int.Parse(gridRow["Width"].ToString());
this.grid = grid;
}
#endregion
#region Public Properties
///// <summary>
///// Gets the ansi-92 SQL data type of the grid column.
///// </summary>
//public abstract String DataTypes
//{
// get;
//}
/// <summary>
/// Gets/sets the parent grid
/// </summary>
public GridField Grid
{
get
{
return this.grid;
}
set
{
this.grid = value;
}
}
/// <summary>
/// Gets/sets the Id
/// </summary>
public int Id
{
get
{
return id;
}
set
{
id = value;
}
}
/// <summary>
/// Gets/sets the name
/// </summary>
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
/// <summary>
/// Gets/sets the display text
/// </summary>
public string Text
{
get
{
return text;
}
set
{
text = value;
}
}
/// <summary>
/// Gets/sets whether the column should repeat last
/// </summary>
public bool ShouldRepeatLast
{
get
{
return shouldRepeatLast;
}
set
{
shouldRepeatLast = value;
}
}
/// <summary>
/// Gets/sets whether the column is required
/// </summary>
public bool IsRequired
{
get
{
return isRequired;
}
set
{
isRequired = value;
}
}
/// <summary>
/// Gets/sets whether the column is read only
/// </summary>
public bool IsReadOnly
{
get
{
return isReadOnly;
}
set
{
isReadOnly = value;
}
}
/// <summary>
/// Gets/sets whether the column is...
/// </summary>
public bool IsUniqueField
{
get
{
return isUniqueField;
}
set
{
isUniqueField = value;
}
}
/// <summary>
/// Gets/sets the column's position
/// </summary>
public int Position
{
get
{
return position;
}
set
{
position = value;
}
}
/// <summary>
/// Gets/sets the column's width
/// </summary>
public int Width
{
get
{
return width;
}
set
{
width = value;
}
}
/// <summary>
/// Gets/sets the column's type
/// </summary>
public MetaFieldType GridColumnType
{
get
{
return gridColumnType;
}
set
{
gridColumnType = value;
}
}
#endregion
#region Protected Properties
#endregion Protected Properties
#region Protected Methods
/// <summary>
/// Event handler for On Column Inserted event.
/// </summary>
protected void OnColumnInserted()
{
this.Grid.GetView().MustRefreshFieldCollection = true;
}
/// <summary>
/// Insert new grid column to database.
/// </summary>
protected abstract void InsertColumn();
/// <summary>
/// Delete grid column from database.
/// </summary>
protected abstract void DeleteColumn();
/// <summary>
/// Update existing grid column to database.
/// </summary>
protected abstract void UpdateColumn();
#endregion Protected Methods
#region Public Methods
/// <summary>
/// Shortcut to get Metadata
/// </summary>
/// <returns></returns>
protected IMetadataProvider GetMetadata()
{
return Grid.GetMetadata();
}
/// <summary>
/// Saves the grid column to the database.
/// </summary>
public void SaveToDb()
{
if (Id == 0)
{
InsertColumn();
}
else
{
UpdateColumn();
}
}
/// <summary>
/// Deletes the grid column from the database.
/// </summary>
public void DeleteFromDb()
{
DeleteColumn();
}
/// <summary>
/// Releases all resources used by this GridColumnBase.
/// </summary>
public virtual void Dispose()
{
}
/// <summary>
/// Returns database sepecific column type
/// </summary>
/// <returns></returns>
///
public virtual string GetDbSpecificColumnType()
{
return Grid.GetProject().CollectedData.GetDatabase().GetDbSpecificColumnType(genericDbColumnType);
}
#endregion Public Methods
}
}
| |
// 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.Runtime.InteropServices;
namespace System.Data.OleDb
{
#if DEBUG
using Globalization;
using Text;
#endif
internal enum DBBindStatus
{
OK = 0,
BADORDINAL = 1,
UNSUPPORTEDCONVERSION = 2,
BADBINDINFO = 3,
BADSTORAGEFLAGS = 4,
NOINTERFACE = 5,
MULTIPLESTORAGE = 6
}
#if false
typedef struct tagDBPARAMBINDINFO {
LPOLESTR pwszDataSourceType;
LPOLESTR pwszName;
DBLENGTH ulParamSize;
DBPARAMFLAGS dwFlags;
BYTE bPrecision;
BYTE bScale;
}
#endif
#if (WIN32 && !ARCH_arm)
[StructLayoutAttribute(LayoutKind.Sequential, Pack = 2)]
#else
[StructLayout(LayoutKind.Sequential, Pack = 8)]
#endif
internal struct tagDBPARAMBINDINFO
{
internal IntPtr pwszDataSourceType;
internal IntPtr pwszName;
internal IntPtr ulParamSize;
internal Int32 dwFlags;
internal Byte bPrecision;
internal Byte bScale;
#if DEBUG
public override string ToString()
{
StringBuilder builder = new StringBuilder();
builder.Append("tagDBPARAMBINDINFO").Append(Environment.NewLine);
if (IntPtr.Zero != pwszDataSourceType)
{
builder.Append("pwszDataSourceType =").Append(Marshal.PtrToStringUni(pwszDataSourceType)).Append(Environment.NewLine);
}
builder.Append("\tulParamSize =" + ulParamSize.ToInt64().ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine);
builder.Append("\tdwFlags =0x" + dwFlags.ToString("X4", CultureInfo.InvariantCulture)).Append(Environment.NewLine);
builder.Append("\tPrecision =" + bPrecision.ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine);
builder.Append("\tScale =" + bScale.ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine);
return builder.ToString();
}
#endif
}
#if false
typedef struct tagDBBINDING {
DBORDINAL iOrdinal;
DBBYTEOFFSET obValue;
DBBYTEOFFSET obLength;
DBBYTEOFFSET obStatus;
ITypeInfo *pTypeInfo;
DBOBJECT *pObject;
DBBINDEXT *pBindExt;
DBPART dwPart;
DBMEMOWNER dwMemOwner;
DBPARAMIO eParamIO;
DBLENGTH cbMaxLen;
DWORD dwFlags;
DBTYPE wType;
BYTE bPrecision;
BYTE bScale;
}
#endif
#if (WIN32 && !ARCH_arm)
[StructLayoutAttribute(LayoutKind.Sequential, Pack = 2)]
#else
[StructLayout(LayoutKind.Sequential, Pack = 8)]
#endif
internal sealed class tagDBBINDING
{
internal IntPtr iOrdinal;
internal IntPtr obValue;
internal IntPtr obLength;
internal IntPtr obStatus;
internal IntPtr pTypeInfo;
internal IntPtr pObject;
internal IntPtr pBindExt;
internal Int32 dwPart;
internal Int32 dwMemOwner;
internal Int32 eParamIO;
internal IntPtr cbMaxLen;
internal Int32 dwFlags;
internal Int16 wType;
internal byte bPrecision;
internal byte bScale;
internal tagDBBINDING()
{
}
#if DEBUG
public override string ToString()
{
StringBuilder builder = new StringBuilder();
builder.Append("tagDBBINDING").Append(Environment.NewLine);
builder.Append("\tOrdinal =" + iOrdinal.ToInt64().ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine);
builder.Append("\tValueOffset =" + obValue.ToInt64().ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine);
builder.Append("\tLengthOffset=" + obLength.ToInt64().ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine);
builder.Append("\tStatusOffset=" + obStatus.ToInt64().ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine);
builder.Append("\tMaxLength =" + cbMaxLen.ToInt64().ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine);
builder.Append("\tDB_Type =" + ODB.WLookup(wType)).Append(Environment.NewLine);
builder.Append("\tPrecision =" + bPrecision.ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine);
builder.Append("\tScale =" + bScale.ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine);
return builder.ToString();
}
#endif
}
#if false
typedef struct tagDBCOLUMNACCESS {
void *pData;
DBID columnid;
DBLENGTH cbDataLen;
DBSTATUS dwStatus;
DBLENGTH cbMaxLen;
DB_DWRESERVE dwReserved;
DBTYPE wType;
BYTE bPrecision;
BYTE bScale;
}
#endif
#if (WIN32 && !ARCH_arm)
[StructLayoutAttribute(LayoutKind.Sequential, Pack = 2)]
#else
[StructLayout(LayoutKind.Sequential, Pack = 8)]
#endif
internal struct tagDBCOLUMNACCESS
{
internal IntPtr pData;
internal tagDBIDX columnid;
internal IntPtr cbDataLen;
internal Int32 dwStatus;
internal IntPtr cbMaxLen;
internal IntPtr dwReserved;
internal Int16 wType;
internal Byte bPrecision;
internal Byte bScale;
}
#if false
typedef struct tagDBID {
/* [switch_is][switch_type] */ union {
/* [case()] */ GUID guid;
/* [case()] */ GUID *pguid;
/* [default] */ /* Empty union arm */
} uGuid;
DBKIND eKind;
/* [switch_is][switch_type] */ union {
/* [case()] */ LPOLESTR pwszName;
/* [case()] */ ULONG ulPropid;
/* [default] */ /* Empty union arm */
} uName;
}
#endif
#if (WIN32 && !ARCH_arm)
[StructLayoutAttribute(LayoutKind.Sequential, Pack = 2)]
#else
[StructLayout(LayoutKind.Sequential, Pack = 8)]
#endif
internal struct tagDBIDX
{
internal Guid uGuid;
internal Int32 eKind;
internal IntPtr ulPropid;
}
#if (WIN32 && !ARCH_arm)
[StructLayoutAttribute(LayoutKind.Sequential, Pack = 2)]
#else
[StructLayout(LayoutKind.Sequential, Pack = 8)]
#endif
internal sealed class tagDBID
{
internal Guid uGuid;
internal Int32 eKind;
internal IntPtr ulPropid;
}
#if false
typedef struct tagDBLITERALINFO {
LPOLESTR pwszLiteralValue;
LPOLESTR pwszInvalidChars;
LPOLESTR pwszInvalidStartingChars;
DBLITERAL lt;
BOOL fSupported;
ULONG cchMaxLen;
}
#endif
#if (WIN32 && !ARCH_arm)
[StructLayoutAttribute(LayoutKind.Sequential, Pack = 2)]
#else
[StructLayout(LayoutKind.Sequential, Pack = 8)]
#endif
sealed internal class tagDBLITERALINFO
{
[MarshalAs(UnmanagedType.LPWStr)]
internal String pwszLiteralValue = null;
[MarshalAs(UnmanagedType.LPWStr)]
internal String pwszInvalidChars = null;
[MarshalAs(UnmanagedType.LPWStr)]
internal String pwszInvalidStartingChars = null;
internal Int32 it;
internal Int32 fSupported;
internal Int32 cchMaxLen;
internal tagDBLITERALINFO()
{
}
}
#if false
typedef struct tagDBPROPSET {
/* [size_is] */ DBPROP *rgProperties;
ULONG cProperties;
GUID guidPropertySet;
}
#endif
#if (WIN32 && !ARCH_arm)
[StructLayoutAttribute(LayoutKind.Sequential, Pack = 2)]
#else
[StructLayout(LayoutKind.Sequential, Pack = 8)]
#endif
sealed internal class tagDBPROPSET
{
internal IntPtr rgProperties;
internal Int32 cProperties;
internal Guid guidPropertySet;
internal tagDBPROPSET()
{
}
internal tagDBPROPSET(int propertyCount, Guid propertySet)
{
cProperties = propertyCount;
guidPropertySet = propertySet;
}
}
#if false
typedef struct tagDBPROP {
DBPROPID dwPropertyID;
DBPROPOPTIONS dwOptions;
DBPROPSTATUS dwStatus;
DBID colid;
VARIANT vValue;
}
#endif
#if (WIN32 && !ARCH_arm)
[StructLayoutAttribute(LayoutKind.Sequential, Pack = 2)]
#else
[StructLayout(LayoutKind.Sequential, Pack = 8)]
#endif
sealed internal class tagDBPROP
{
internal Int32 dwPropertyID;
internal Int32 dwOptions;
internal OleDbPropertyStatus dwStatus;
internal tagDBIDX columnid;
// Variant
[MarshalAs(UnmanagedType.Struct)] internal object vValue;
internal tagDBPROP()
{
}
internal tagDBPROP(int propertyID, bool required, object value)
{
dwPropertyID = propertyID;
dwOptions = ((required) ? ODB.DBPROPOPTIONS_REQUIRED : ODB.DBPROPOPTIONS_OPTIONAL);
vValue = value;
}
}
#if false
typedef struct tagDBPARAMS {
void *pData;
DB_UPARAMS cParamSets;
HACCESSOR hAccessor;
}
#endif
#if (WIN32 && !ARCH_arm)
[StructLayoutAttribute(LayoutKind.Sequential, Pack = 2)]
#else
[StructLayout(LayoutKind.Sequential, Pack = 8)]
#endif
sealed internal class tagDBPARAMS
{
internal IntPtr pData;
internal Int32 cParamSets;
internal IntPtr hAccessor;
internal tagDBPARAMS()
{
}
}
#if false
typedef struct tagDBCOLUMNINFO {
LPOLESTR pwszName;
ITypeInfo *pTypeInfo;
DBORDINAL iOrdinal;
DBCOLUMNFLAGS dwFlags;
DBLENGTH ulColumnSize;
DBTYPE wType;
BYTE bPrecision;
BYTE bScale;
DBID columnid;
}
#endif
#if (WIN32 && !ARCH_arm)
[StructLayoutAttribute(LayoutKind.Sequential, Pack = 2)]
#else
[StructLayout(LayoutKind.Sequential, Pack = 8)]
#endif
sealed internal class tagDBCOLUMNINFO
{
[MarshalAs(UnmanagedType.LPWStr)]
internal String pwszName = null;
//[MarshalAs(UnmanagedType.Interface)]
internal IntPtr pTypeInfo = (IntPtr)0;
internal IntPtr iOrdinal = (IntPtr)0;
internal Int32 dwFlags = 0;
internal IntPtr ulColumnSize = (IntPtr)0;
internal Int16 wType = 0;
internal Byte bPrecision = 0;
internal Byte bScale = 0;
internal tagDBIDX columnid;
internal tagDBCOLUMNINFO()
{
}
#if DEBUG
public override string ToString()
{
StringBuilder builder = new StringBuilder();
builder.Append("tagDBCOLUMNINFO: " + Convert.ToString(pwszName, CultureInfo.InvariantCulture)).Append(Environment.NewLine);
builder.Append("\t" + iOrdinal.ToInt64().ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine);
builder.Append("\t" + "0x" + dwFlags.ToString("X8", CultureInfo.InvariantCulture)).Append(Environment.NewLine);
builder.Append("\t" + ulColumnSize.ToInt64().ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine);
builder.Append("\t" + "0x" + wType.ToString("X2", CultureInfo.InvariantCulture)).Append(Environment.NewLine);
builder.Append("\t" + bPrecision.ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine);
builder.Append("\t" + bScale.ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine);
builder.Append("\t" + columnid.eKind.ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine);
return builder.ToString();
}
#endif
}
#if false
typedef struct tagDBPROPINFOSET {
/* [size_is] */ PDBPROPINFO rgPropertyInfos;
ULONG cPropertyInfos;
GUID guidPropertySet;
}
#endif
#if (WIN32 && !ARCH_arm)
[StructLayoutAttribute(LayoutKind.Sequential, Pack = 2)]
#else
[StructLayout(LayoutKind.Sequential, Pack = 8)]
#endif
sealed internal class tagDBPROPINFOSET
{
internal IntPtr rgPropertyInfos;
internal Int32 cPropertyInfos;
internal Guid guidPropertySet;
internal tagDBPROPINFOSET()
{
}
}
#if false
typedef struct tagDBPROPINFO {
LPOLESTR pwszDescription;
DBPROPID dwPropertyID;
DBPROPFLAGS dwFlags;
VARTYPE vtType;
VARIANT vValues;
}
#endif
#if (WIN32 && !ARCH_arm)
[StructLayoutAttribute(LayoutKind.Sequential, Pack = 2)]
#else
[StructLayout(LayoutKind.Sequential, Pack = 8)]
#endif
sealed internal class tagDBPROPINFO
{
[MarshalAs(UnmanagedType.LPWStr)] internal string pwszDescription;
internal Int32 dwPropertyID;
internal Int32 dwFlags;
internal Int16 vtType;
[MarshalAs(UnmanagedType.Struct)] internal object vValue;
internal tagDBPROPINFO()
{
}
}
#if false
typedef struct tagDBPROPIDSET {
/* [size_is] */ DBPROPID *rgPropertyIDs;
ULONG cPropertyIDs;
GUID guidPropertySet;
}
#endif
#if (WIN32 && !ARCH_arm)
[StructLayoutAttribute(LayoutKind.Sequential, Pack = 2)]
#else
[StructLayout(LayoutKind.Sequential, Pack = 8)]
#endif
internal struct tagDBPROPIDSET
{
internal IntPtr rgPropertyIDs;
internal Int32 cPropertyIDs;
internal Guid guidPropertySet;
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.Runtime.Serialization;
using System.Xml;
using System.ServiceModel.Diagnostics;
using System.Runtime;
namespace System.ServiceModel.Dispatcher
{
internal class PrimitiveOperationFormatter : IClientMessageFormatter, IDispatchMessageFormatter
{
private OperationDescription _operation;
private MessageDescription _responseMessage;
private MessageDescription _requestMessage;
private XmlDictionaryString _action;
private XmlDictionaryString _replyAction;
private ActionHeader _actionHeaderNone;
private ActionHeader _actionHeader10;
private ActionHeader _replyActionHeaderNone;
private ActionHeader _replyActionHeader10;
private XmlDictionaryString _requestWrapperName;
private XmlDictionaryString _requestWrapperNamespace;
private XmlDictionaryString _responseWrapperName;
private XmlDictionaryString _responseWrapperNamespace;
private PartInfo[] _requestParts;
private PartInfo[] _responseParts;
private PartInfo _returnPart;
private XmlDictionaryString _xsiNilLocalName;
private XmlDictionaryString _xsiNilNamespace;
public PrimitiveOperationFormatter(OperationDescription description, bool isRpc)
{
if (description == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("description");
OperationFormatter.Validate(description, isRpc, false/*isEncoded*/);
_operation = description;
_requestMessage = description.Messages[0];
if (description.Messages.Count == 2)
_responseMessage = description.Messages[1];
int stringCount = 3 + _requestMessage.Body.Parts.Count;
if (_responseMessage != null)
stringCount += 2 + _responseMessage.Body.Parts.Count;
XmlDictionary dictionary = new XmlDictionary(stringCount * 2);
_xsiNilLocalName = dictionary.Add("nil");
_xsiNilNamespace = dictionary.Add(EndpointAddressProcessor.XsiNs);
OperationFormatter.GetActions(description, dictionary, out _action, out _replyAction);
if (_requestMessage.Body.WrapperName != null)
{
_requestWrapperName = AddToDictionary(dictionary, _requestMessage.Body.WrapperName);
_requestWrapperNamespace = AddToDictionary(dictionary, _requestMessage.Body.WrapperNamespace);
}
_requestParts = AddToDictionary(dictionary, _requestMessage.Body.Parts, isRpc);
if (_responseMessage != null)
{
if (_responseMessage.Body.WrapperName != null)
{
_responseWrapperName = AddToDictionary(dictionary, _responseMessage.Body.WrapperName);
_responseWrapperNamespace = AddToDictionary(dictionary, _responseMessage.Body.WrapperNamespace);
}
_responseParts = AddToDictionary(dictionary, _responseMessage.Body.Parts, isRpc);
if (_responseMessage.Body.ReturnValue != null && _responseMessage.Body.ReturnValue.Type != typeof(void))
{
_returnPart = AddToDictionary(dictionary, _responseMessage.Body.ReturnValue, isRpc);
}
}
}
private ActionHeader ActionHeaderNone
{
get
{
if (_actionHeaderNone == null)
{
_actionHeaderNone =
ActionHeader.Create(_action, AddressingVersion.None);
}
return _actionHeaderNone;
}
}
private ActionHeader ActionHeader10
{
get
{
if (_actionHeader10 == null)
{
_actionHeader10 =
ActionHeader.Create(_action, AddressingVersion.WSAddressing10);
}
return _actionHeader10;
}
}
private ActionHeader ReplyActionHeaderNone
{
get
{
if (_replyActionHeaderNone == null)
{
_replyActionHeaderNone =
ActionHeader.Create(_replyAction, AddressingVersion.None);
}
return _replyActionHeaderNone;
}
}
private ActionHeader ReplyActionHeader10
{
get
{
if (_replyActionHeader10 == null)
{
_replyActionHeader10 =
ActionHeader.Create(_replyAction, AddressingVersion.WSAddressing10);
}
return _replyActionHeader10;
}
}
private static XmlDictionaryString AddToDictionary(XmlDictionary dictionary, string s)
{
XmlDictionaryString dictionaryString;
if (!dictionary.TryLookup(s, out dictionaryString))
{
dictionaryString = dictionary.Add(s);
}
return dictionaryString;
}
private static PartInfo[] AddToDictionary(XmlDictionary dictionary, MessagePartDescriptionCollection parts, bool isRpc)
{
PartInfo[] partInfos = new PartInfo[parts.Count];
for (int i = 0; i < parts.Count; i++)
{
partInfos[i] = AddToDictionary(dictionary, parts[i], isRpc);
}
return partInfos;
}
private ActionHeader GetActionHeader(AddressingVersion addressing)
{
if (_action == null)
{
return null;
}
if (addressing == AddressingVersion.WSAddressing10)
{
return ActionHeader10;
}
else if (addressing == AddressingVersion.None)
{
return ActionHeaderNone;
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InvalidOperationException(SR.Format(SR.AddressingVersionNotSupported, addressing)));
}
}
ActionHeader GetReplyActionHeader(AddressingVersion addressing)
{
if (_replyAction == null)
{
return null;
}
if (addressing == AddressingVersion.WSAddressing10)
{
return ReplyActionHeader10;
}
else if (addressing == AddressingVersion.None)
{
return ReplyActionHeaderNone;
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InvalidOperationException(SR.Format(SR.AddressingVersionNotSupported, addressing)));
}
}
private static string GetArrayItemName(Type type)
{
switch (type.GetTypeCode())
{
case TypeCode.Boolean:
return "boolean";
case TypeCode.DateTime:
return "dateTime";
case TypeCode.Decimal:
return "decimal";
case TypeCode.Int32:
return "int";
case TypeCode.Int64:
return "long";
case TypeCode.Single:
return "float";
case TypeCode.Double:
return "double";
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxInvalidUseOfPrimitiveOperationFormatter));
}
}
private static PartInfo AddToDictionary(XmlDictionary dictionary, MessagePartDescription part, bool isRpc)
{
Type type = part.Type;
XmlDictionaryString itemName = null;
XmlDictionaryString itemNamespace = null;
if (type.IsArray && type != typeof(byte[]))
{
const string ns = "http://schemas.microsoft.com/2003/10/Serialization/Arrays";
string name = GetArrayItemName(type.GetElementType());
itemName = AddToDictionary(dictionary, name);
itemNamespace = AddToDictionary(dictionary, ns);
}
return new PartInfo(part,
AddToDictionary(dictionary, part.Name),
AddToDictionary(dictionary, isRpc ? string.Empty : part.Namespace),
itemName, itemNamespace);
}
public static bool IsContractSupported(OperationDescription description)
{
if (description == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("description");
OperationDescription operation = description;
MessageDescription requestMessage = description.Messages[0];
MessageDescription responseMessage = null;
if (description.Messages.Count == 2)
responseMessage = description.Messages[1];
if (requestMessage.Headers.Count > 0)
return false;
if (requestMessage.Properties.Count > 0)
return false;
if (requestMessage.IsTypedMessage)
return false;
if (responseMessage != null)
{
if (responseMessage.Headers.Count > 0)
return false;
if (responseMessage.Properties.Count > 0)
return false;
if (responseMessage.IsTypedMessage)
return false;
}
if (!AreTypesSupported(requestMessage.Body.Parts))
return false;
if (responseMessage != null)
{
if (!AreTypesSupported(responseMessage.Body.Parts))
return false;
if (responseMessage.Body.ReturnValue != null && !IsTypeSupported(responseMessage.Body.ReturnValue))
return false;
}
return true;
}
private static bool AreTypesSupported(MessagePartDescriptionCollection bodyDescriptions)
{
for (int i = 0; i < bodyDescriptions.Count; i++)
if (!IsTypeSupported(bodyDescriptions[i]))
return false;
return true;
}
private static bool IsTypeSupported(MessagePartDescription bodyDescription)
{
Fx.Assert(bodyDescription != null, "");
Type type = bodyDescription.Type;
if (type == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxMessagePartDescriptionMissingType, bodyDescription.Name, bodyDescription.Namespace)));
if (bodyDescription.Multiple)
return false;
if (type == typeof(void))
return true;
if (type.IsEnum())
return false;
switch (type.GetTypeCode())
{
case TypeCode.Boolean:
case TypeCode.DateTime:
case TypeCode.Decimal:
case TypeCode.Double:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.String:
return true;
case TypeCode.Object:
if (type.IsArray && type.GetArrayRank() == 1 && IsArrayTypeSupported(type.GetElementType()))
return true;
break;
default:
break;
}
return false;
}
private static bool IsArrayTypeSupported(Type type)
{
if (type.IsEnum())
return false;
switch (type.GetTypeCode())
{
case TypeCode.Byte:
case TypeCode.Boolean:
case TypeCode.DateTime:
case TypeCode.Decimal:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
return true;
default:
return false;
}
}
public Message SerializeRequest(MessageVersion messageVersion, object[] parameters)
{
if (messageVersion == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("messageVersion");
if (parameters == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parameters");
return Message.CreateMessage(messageVersion, GetActionHeader(messageVersion.Addressing), new PrimitiveRequestBodyWriter(parameters, this));
}
public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result)
{
if (messageVersion == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("messageVersion");
if (parameters == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parameters");
return Message.CreateMessage(messageVersion, GetReplyActionHeader(messageVersion.Addressing), new PrimitiveResponseBodyWriter(parameters, result, this));
}
public object DeserializeReply(Message message, object[] parameters)
{
if (message == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("message"));
if (parameters == null)
throw TraceUtility.ThrowHelperError(new ArgumentNullException("parameters"), message);
try
{
if (message.IsEmpty)
{
if (_responseWrapperName == null)
return null;
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.SFxInvalidMessageBodyEmptyMessage));
}
XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents();
using (bodyReader)
{
object returnValue = DeserializeResponse(bodyReader, parameters);
message.ReadFromBodyContentsToEnd(bodyReader);
return returnValue;
}
}
catch (XmlException xe)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(
SR.Format(SR.SFxErrorDeserializingReplyBodyMore, _operation.Name, xe.Message), xe));
}
catch (FormatException fe)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(
SR.Format(SR.SFxErrorDeserializingReplyBodyMore, _operation.Name, fe.Message), fe));
}
catch (SerializationException se)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(
SR.Format(SR.SFxErrorDeserializingReplyBodyMore, _operation.Name, se.Message), se));
}
}
public void DeserializeRequest(Message message, object[] parameters)
{
if (message == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("message"));
if (parameters == null)
throw TraceUtility.ThrowHelperError(new ArgumentNullException("parameters"), message);
try
{
if (message.IsEmpty)
{
if (_requestWrapperName == null)
return;
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.SFxInvalidMessageBodyEmptyMessage));
}
XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents();
using (bodyReader)
{
DeserializeRequest(bodyReader, parameters);
message.ReadFromBodyContentsToEnd(bodyReader);
}
}
catch (XmlException xe)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
OperationFormatter.CreateDeserializationFailedFault(
SR.Format(SR.SFxErrorDeserializingRequestBodyMore, _operation.Name, xe.Message),
xe));
}
catch (FormatException fe)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
OperationFormatter.CreateDeserializationFailedFault(
SR.Format(SR.SFxErrorDeserializingRequestBodyMore, _operation.Name, fe.Message),
fe));
}
catch (SerializationException se)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(
SR.Format(SR.SFxErrorDeserializingRequestBodyMore, _operation.Name, se.Message),
se));
}
}
void DeserializeRequest(XmlDictionaryReader reader, object[] parameters)
{
if (_requestWrapperName != null)
{
if (!reader.IsStartElement(_requestWrapperName, _requestWrapperNamespace))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.Format(SR.SFxInvalidMessageBody, _requestWrapperName, _requestWrapperNamespace, reader.NodeType, reader.Name, reader.NamespaceURI)));
bool isEmptyElement = reader.IsEmptyElement;
reader.Read();
if (isEmptyElement)
{
return;
}
}
DeserializeParameters(reader, _requestParts, parameters);
if (_requestWrapperName != null)
{
reader.ReadEndElement();
}
}
private object DeserializeResponse(XmlDictionaryReader reader, object[] parameters)
{
if (_responseWrapperName != null)
{
if (!reader.IsStartElement(_responseWrapperName, _responseWrapperNamespace))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.Format(SR.SFxInvalidMessageBody, _responseWrapperName, _responseWrapperNamespace, reader.NodeType, reader.Name, reader.NamespaceURI)));
bool isEmptyElement = reader.IsEmptyElement;
reader.Read();
if (isEmptyElement)
{
return null;
}
}
object returnValue = null;
if (_returnPart != null)
{
while (true)
{
if (IsPartElement(reader, _returnPart))
{
returnValue = DeserializeParameter(reader, _returnPart);
break;
}
if (!reader.IsStartElement())
break;
if (IsPartElements(reader, _responseParts))
break;
OperationFormatter.TraceAndSkipElement(reader);
}
}
DeserializeParameters(reader, _responseParts, parameters);
if (_responseWrapperName != null)
{
reader.ReadEndElement();
}
return returnValue;
}
private void DeserializeParameters(XmlDictionaryReader reader, PartInfo[] parts, object[] parameters)
{
if (parts.Length != parameters.Length)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentException(SR.Format(SR.SFxParameterCountMismatch, "parts", parts.Length, "parameters", parameters.Length), "parameters"));
int nextPartIndex = 0;
while (reader.IsStartElement())
{
for (int i = nextPartIndex; i < parts.Length; i++)
{
PartInfo part = parts[i];
if (IsPartElement(reader, part))
{
parameters[part.Description.Index] = DeserializeParameter(reader, parts[i]);
nextPartIndex = i + 1;
}
else
parameters[part.Description.Index] = null;
}
if (reader.IsStartElement())
OperationFormatter.TraceAndSkipElement(reader);
}
}
private bool IsPartElements(XmlDictionaryReader reader, PartInfo[] parts)
{
foreach (PartInfo part in parts)
if (IsPartElement(reader, part))
return true;
return false;
}
private bool IsPartElement(XmlDictionaryReader reader, PartInfo part)
{
return reader.IsStartElement(part.DictionaryName, part.DictionaryNamespace);
}
private object DeserializeParameter(XmlDictionaryReader reader, PartInfo part)
{
if (reader.AttributeCount > 0 &&
reader.MoveToAttribute(_xsiNilLocalName.Value, _xsiNilNamespace.Value) &&
reader.ReadContentAsBoolean())
{
reader.Skip();
return null;
}
return part.ReadValue(reader);
}
private void SerializeParameter(XmlDictionaryWriter writer, PartInfo part, object graph)
{
writer.WriteStartElement(part.DictionaryName, part.DictionaryNamespace);
if (graph == null)
{
writer.WriteStartAttribute(_xsiNilLocalName, _xsiNilNamespace);
writer.WriteValue(true);
writer.WriteEndAttribute();
}
else
part.WriteValue(writer, graph);
writer.WriteEndElement();
}
private void SerializeParameters(XmlDictionaryWriter writer, PartInfo[] parts, object[] parameters)
{
if (parts.Length != parameters.Length)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentException(SR.Format(SR.SFxParameterCountMismatch, "parts", parts.Length, "parameters", parameters.Length), "parameters"));
for (int i = 0; i < parts.Length; i++)
{
PartInfo part = parts[i];
SerializeParameter(writer, part, parameters[part.Description.Index]);
}
}
private void SerializeRequest(XmlDictionaryWriter writer, object[] parameters)
{
if (_requestWrapperName != null)
writer.WriteStartElement(_requestWrapperName, _requestWrapperNamespace);
SerializeParameters(writer, _requestParts, parameters);
if (_requestWrapperName != null)
writer.WriteEndElement();
}
private void SerializeResponse(XmlDictionaryWriter writer, object returnValue, object[] parameters)
{
if (_responseWrapperName != null)
writer.WriteStartElement(_responseWrapperName, _responseWrapperNamespace);
if (_returnPart != null)
SerializeParameter(writer, _returnPart, returnValue);
SerializeParameters(writer, _responseParts, parameters);
if (_responseWrapperName != null)
writer.WriteEndElement();
}
internal class PartInfo
{
private XmlDictionaryString _dictionaryName;
private XmlDictionaryString _dictionaryNamespace;
private XmlDictionaryString _itemName;
private XmlDictionaryString _itemNamespace;
private MessagePartDescription _description;
private TypeCode _typeCode;
private bool _isArray;
public PartInfo(MessagePartDescription description, XmlDictionaryString dictionaryName, XmlDictionaryString dictionaryNamespace, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
{
_dictionaryName = dictionaryName;
_dictionaryNamespace = dictionaryNamespace;
_itemName = itemName;
_itemNamespace = itemNamespace;
_description = description;
if (description.Type.IsArray)
{
_isArray = true;
_typeCode = description.Type.GetElementType().GetTypeCode();
}
else
{
_isArray = false;
_typeCode = description.Type.GetTypeCode();
}
}
public MessagePartDescription Description
{
get { return _description; }
}
public XmlDictionaryString DictionaryName
{
get { return _dictionaryName; }
}
public XmlDictionaryString DictionaryNamespace
{
get { return _dictionaryNamespace; }
}
public object ReadValue(XmlDictionaryReader reader)
{
object value;
if (_isArray)
{
switch (_typeCode)
{
case TypeCode.Byte:
value = reader.ReadElementContentAsBase64();
break;
case TypeCode.Boolean:
if (!reader.IsEmptyElement)
{
reader.ReadStartElement();
value = reader.ReadBooleanArray(_itemName, _itemNamespace);
reader.ReadEndElement();
}
else
{
reader.Read();
value = Array.Empty<bool>();
}
break;
case TypeCode.DateTime:
if (!reader.IsEmptyElement)
{
reader.ReadStartElement();
value = reader.ReadDateTimeArray(_itemName, _itemNamespace);
reader.ReadEndElement();
}
else
{
reader.Read();
value = Array.Empty<DateTime>();
}
break;
case TypeCode.Decimal:
if (!reader.IsEmptyElement)
{
reader.ReadStartElement();
value = reader.ReadDecimalArray(_itemName, _itemNamespace);
reader.ReadEndElement();
}
else
{
reader.Read();
value = Array.Empty<Decimal>();
}
break;
case TypeCode.Int32:
if (!reader.IsEmptyElement)
{
reader.ReadStartElement();
value = reader.ReadInt32Array(_itemName, _itemNamespace);
reader.ReadEndElement();
}
else
{
reader.Read();
value = Array.Empty<Int32>();
}
break;
case TypeCode.Int64:
if (!reader.IsEmptyElement)
{
reader.ReadStartElement();
value = reader.ReadInt64Array(_itemName, _itemNamespace);
reader.ReadEndElement();
}
else
{
reader.Read();
value = Array.Empty<Int64>();
}
break;
case TypeCode.Single:
if (!reader.IsEmptyElement)
{
reader.ReadStartElement();
value = reader.ReadSingleArray(_itemName, _itemNamespace);
reader.ReadEndElement();
}
else
{
reader.Read();
value = Array.Empty<Single>();
}
break;
case TypeCode.Double:
if (!reader.IsEmptyElement)
{
reader.ReadStartElement();
value = reader.ReadDoubleArray(_itemName, _itemNamespace);
reader.ReadEndElement();
}
else
{
reader.Read();
value = Array.Empty<Double>();
}
break;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxInvalidUseOfPrimitiveOperationFormatter));
}
}
else
{
switch (_typeCode)
{
case TypeCode.Boolean:
value = reader.ReadElementContentAsBoolean();
break;
case TypeCode.DateTime:
value = reader.ReadElementContentAsDateTime();
break;
case TypeCode.Decimal:
value = reader.ReadElementContentAsDecimal();
break;
case TypeCode.Double:
value = reader.ReadElementContentAsDouble();
break;
case TypeCode.Int32:
value = reader.ReadElementContentAsInt();
break;
case TypeCode.Int64:
value = reader.ReadElementContentAsLong();
break;
case TypeCode.Single:
value = reader.ReadElementContentAsFloat();
break;
case TypeCode.String:
return reader.ReadElementContentAsString();
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxInvalidUseOfPrimitiveOperationFormatter));
}
}
return value;
}
public void WriteValue(XmlDictionaryWriter writer, object value)
{
if (_isArray)
{
switch (_typeCode)
{
case TypeCode.Byte:
{
byte[] arrayValue = (byte[])value;
writer.WriteBase64(arrayValue, 0, arrayValue.Length);
}
break;
case TypeCode.Boolean:
{
bool[] arrayValue = (bool[])value;
writer.WriteArray(null, _itemName, _itemNamespace, arrayValue, 0, arrayValue.Length);
}
break;
case TypeCode.DateTime:
{
DateTime[] arrayValue = (DateTime[])value;
writer.WriteArray(null, _itemName, _itemNamespace, arrayValue, 0, arrayValue.Length);
}
break;
case TypeCode.Decimal:
{
decimal[] arrayValue = (decimal[])value;
writer.WriteArray(null, _itemName, _itemNamespace, arrayValue, 0, arrayValue.Length);
}
break;
case TypeCode.Int32:
{
Int32[] arrayValue = (Int32[])value;
writer.WriteArray(null, _itemName, _itemNamespace, arrayValue, 0, arrayValue.Length);
}
break;
case TypeCode.Int64:
{
Int64[] arrayValue = (Int64[])value;
writer.WriteArray(null, _itemName, _itemNamespace, arrayValue, 0, arrayValue.Length);
}
break;
case TypeCode.Single:
{
float[] arrayValue = (float[])value;
writer.WriteArray(null, _itemName, _itemNamespace, arrayValue, 0, arrayValue.Length);
}
break;
case TypeCode.Double:
{
double[] arrayValue = (double[])value;
writer.WriteArray(null, _itemName, _itemNamespace, arrayValue, 0, arrayValue.Length);
}
break;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxInvalidUseOfPrimitiveOperationFormatter));
}
}
else
{
switch (_typeCode)
{
case TypeCode.Boolean:
writer.WriteValue((bool)value);
break;
case TypeCode.DateTime:
writer.WriteValue((DateTime)value);
break;
case TypeCode.Decimal:
writer.WriteValue((Decimal)value);
break;
case TypeCode.Double:
writer.WriteValue((double)value);
break;
case TypeCode.Int32:
writer.WriteValue((int)value);
break;
case TypeCode.Int64:
writer.WriteValue((long)value);
break;
case TypeCode.Single:
writer.WriteValue((float)value);
break;
case TypeCode.String:
writer.WriteString((string)value);
break;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxInvalidUseOfPrimitiveOperationFormatter));
}
}
}
}
internal class PrimitiveRequestBodyWriter : BodyWriter
{
private object[] _parameters;
private PrimitiveOperationFormatter _primitiveOperationFormatter;
public PrimitiveRequestBodyWriter(object[] parameters, PrimitiveOperationFormatter primitiveOperationFormatter)
: base(true)
{
_parameters = parameters;
_primitiveOperationFormatter = primitiveOperationFormatter;
}
protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
{
_primitiveOperationFormatter.SerializeRequest(writer, _parameters);
}
}
internal class PrimitiveResponseBodyWriter : BodyWriter
{
private object[] _parameters;
private object _returnValue;
private PrimitiveOperationFormatter _primitiveOperationFormatter;
public PrimitiveResponseBodyWriter(object[] parameters, object returnValue,
PrimitiveOperationFormatter primitiveOperationFormatter)
: base(true)
{
_parameters = parameters;
_returnValue = returnValue;
_primitiveOperationFormatter = primitiveOperationFormatter;
}
protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
{
_primitiveOperationFormatter.SerializeResponse(writer, _returnValue, _parameters);
}
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Compute.V1.Snippets
{
using Google.Api.Gax;
using System;
using System.Linq;
using System.Threading.Tasks;
using lro = Google.LongRunning;
/// <summary>Generated snippets.</summary>
public sealed class AllGeneratedImagesClientSnippets
{
/// <summary>Snippet for Delete</summary>
public void DeleteRequestObject()
{
// Snippet: Delete(DeleteImageRequest, CallSettings)
// Create client
ImagesClient imagesClient = ImagesClient.Create();
// Initialize request argument(s)
DeleteImageRequest request = new DeleteImageRequest
{
RequestId = "",
Image = "",
Project = "",
};
// Make the request
lro::Operation<Operation, Operation> response = imagesClient.Delete(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = imagesClient.PollOnceDelete(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteAsync</summary>
public async Task DeleteRequestObjectAsync()
{
// Snippet: DeleteAsync(DeleteImageRequest, CallSettings)
// Additional: DeleteAsync(DeleteImageRequest, CancellationToken)
// Create client
ImagesClient imagesClient = await ImagesClient.CreateAsync();
// Initialize request argument(s)
DeleteImageRequest request = new DeleteImageRequest
{
RequestId = "",
Image = "",
Project = "",
};
// Make the request
lro::Operation<Operation, Operation> response = await imagesClient.DeleteAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await imagesClient.PollOnceDeleteAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Delete</summary>
public void Delete()
{
// Snippet: Delete(string, string, CallSettings)
// Create client
ImagesClient imagesClient = ImagesClient.Create();
// Initialize request argument(s)
string project = "";
string image = "";
// Make the request
lro::Operation<Operation, Operation> response = imagesClient.Delete(project, image);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = imagesClient.PollOnceDelete(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteAsync</summary>
public async Task DeleteAsync()
{
// Snippet: DeleteAsync(string, string, CallSettings)
// Additional: DeleteAsync(string, string, CancellationToken)
// Create client
ImagesClient imagesClient = await ImagesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string image = "";
// Make the request
lro::Operation<Operation, Operation> response = await imagesClient.DeleteAsync(project, image);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await imagesClient.PollOnceDeleteAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Deprecate</summary>
public void DeprecateRequestObject()
{
// Snippet: Deprecate(DeprecateImageRequest, CallSettings)
// Create client
ImagesClient imagesClient = ImagesClient.Create();
// Initialize request argument(s)
DeprecateImageRequest request = new DeprecateImageRequest
{
RequestId = "",
Image = "",
Project = "",
DeprecationStatusResource = new DeprecationStatus(),
};
// Make the request
lro::Operation<Operation, Operation> response = imagesClient.Deprecate(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = imagesClient.PollOnceDeprecate(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeprecateAsync</summary>
public async Task DeprecateRequestObjectAsync()
{
// Snippet: DeprecateAsync(DeprecateImageRequest, CallSettings)
// Additional: DeprecateAsync(DeprecateImageRequest, CancellationToken)
// Create client
ImagesClient imagesClient = await ImagesClient.CreateAsync();
// Initialize request argument(s)
DeprecateImageRequest request = new DeprecateImageRequest
{
RequestId = "",
Image = "",
Project = "",
DeprecationStatusResource = new DeprecationStatus(),
};
// Make the request
lro::Operation<Operation, Operation> response = await imagesClient.DeprecateAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await imagesClient.PollOnceDeprecateAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Deprecate</summary>
public void Deprecate()
{
// Snippet: Deprecate(string, string, DeprecationStatus, CallSettings)
// Create client
ImagesClient imagesClient = ImagesClient.Create();
// Initialize request argument(s)
string project = "";
string image = "";
DeprecationStatus deprecationStatusResource = new DeprecationStatus();
// Make the request
lro::Operation<Operation, Operation> response = imagesClient.Deprecate(project, image, deprecationStatusResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = imagesClient.PollOnceDeprecate(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeprecateAsync</summary>
public async Task DeprecateAsync()
{
// Snippet: DeprecateAsync(string, string, DeprecationStatus, CallSettings)
// Additional: DeprecateAsync(string, string, DeprecationStatus, CancellationToken)
// Create client
ImagesClient imagesClient = await ImagesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string image = "";
DeprecationStatus deprecationStatusResource = new DeprecationStatus();
// Make the request
lro::Operation<Operation, Operation> response = await imagesClient.DeprecateAsync(project, image, deprecationStatusResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await imagesClient.PollOnceDeprecateAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Get</summary>
public void GetRequestObject()
{
// Snippet: Get(GetImageRequest, CallSettings)
// Create client
ImagesClient imagesClient = ImagesClient.Create();
// Initialize request argument(s)
GetImageRequest request = new GetImageRequest
{
Image = "",
Project = "",
};
// Make the request
Image response = imagesClient.Get(request);
// End snippet
}
/// <summary>Snippet for GetAsync</summary>
public async Task GetRequestObjectAsync()
{
// Snippet: GetAsync(GetImageRequest, CallSettings)
// Additional: GetAsync(GetImageRequest, CancellationToken)
// Create client
ImagesClient imagesClient = await ImagesClient.CreateAsync();
// Initialize request argument(s)
GetImageRequest request = new GetImageRequest
{
Image = "",
Project = "",
};
// Make the request
Image response = await imagesClient.GetAsync(request);
// End snippet
}
/// <summary>Snippet for Get</summary>
public void Get()
{
// Snippet: Get(string, string, CallSettings)
// Create client
ImagesClient imagesClient = ImagesClient.Create();
// Initialize request argument(s)
string project = "";
string image = "";
// Make the request
Image response = imagesClient.Get(project, image);
// End snippet
}
/// <summary>Snippet for GetAsync</summary>
public async Task GetAsync()
{
// Snippet: GetAsync(string, string, CallSettings)
// Additional: GetAsync(string, string, CancellationToken)
// Create client
ImagesClient imagesClient = await ImagesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string image = "";
// Make the request
Image response = await imagesClient.GetAsync(project, image);
// End snippet
}
/// <summary>Snippet for GetFromFamily</summary>
public void GetFromFamilyRequestObject()
{
// Snippet: GetFromFamily(GetFromFamilyImageRequest, CallSettings)
// Create client
ImagesClient imagesClient = ImagesClient.Create();
// Initialize request argument(s)
GetFromFamilyImageRequest request = new GetFromFamilyImageRequest
{
Project = "",
Family = "",
};
// Make the request
Image response = imagesClient.GetFromFamily(request);
// End snippet
}
/// <summary>Snippet for GetFromFamilyAsync</summary>
public async Task GetFromFamilyRequestObjectAsync()
{
// Snippet: GetFromFamilyAsync(GetFromFamilyImageRequest, CallSettings)
// Additional: GetFromFamilyAsync(GetFromFamilyImageRequest, CancellationToken)
// Create client
ImagesClient imagesClient = await ImagesClient.CreateAsync();
// Initialize request argument(s)
GetFromFamilyImageRequest request = new GetFromFamilyImageRequest
{
Project = "",
Family = "",
};
// Make the request
Image response = await imagesClient.GetFromFamilyAsync(request);
// End snippet
}
/// <summary>Snippet for GetFromFamily</summary>
public void GetFromFamily()
{
// Snippet: GetFromFamily(string, string, CallSettings)
// Create client
ImagesClient imagesClient = ImagesClient.Create();
// Initialize request argument(s)
string project = "";
string family = "";
// Make the request
Image response = imagesClient.GetFromFamily(project, family);
// End snippet
}
/// <summary>Snippet for GetFromFamilyAsync</summary>
public async Task GetFromFamilyAsync()
{
// Snippet: GetFromFamilyAsync(string, string, CallSettings)
// Additional: GetFromFamilyAsync(string, string, CancellationToken)
// Create client
ImagesClient imagesClient = await ImagesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string family = "";
// Make the request
Image response = await imagesClient.GetFromFamilyAsync(project, family);
// End snippet
}
/// <summary>Snippet for GetIamPolicy</summary>
public void GetIamPolicyRequestObject()
{
// Snippet: GetIamPolicy(GetIamPolicyImageRequest, CallSettings)
// Create client
ImagesClient imagesClient = ImagesClient.Create();
// Initialize request argument(s)
GetIamPolicyImageRequest request = new GetIamPolicyImageRequest
{
Resource = "",
Project = "",
OptionsRequestedPolicyVersion = 0,
};
// Make the request
Policy response = imagesClient.GetIamPolicy(request);
// End snippet
}
/// <summary>Snippet for GetIamPolicyAsync</summary>
public async Task GetIamPolicyRequestObjectAsync()
{
// Snippet: GetIamPolicyAsync(GetIamPolicyImageRequest, CallSettings)
// Additional: GetIamPolicyAsync(GetIamPolicyImageRequest, CancellationToken)
// Create client
ImagesClient imagesClient = await ImagesClient.CreateAsync();
// Initialize request argument(s)
GetIamPolicyImageRequest request = new GetIamPolicyImageRequest
{
Resource = "",
Project = "",
OptionsRequestedPolicyVersion = 0,
};
// Make the request
Policy response = await imagesClient.GetIamPolicyAsync(request);
// End snippet
}
/// <summary>Snippet for GetIamPolicy</summary>
public void GetIamPolicy()
{
// Snippet: GetIamPolicy(string, string, CallSettings)
// Create client
ImagesClient imagesClient = ImagesClient.Create();
// Initialize request argument(s)
string project = "";
string resource = "";
// Make the request
Policy response = imagesClient.GetIamPolicy(project, resource);
// End snippet
}
/// <summary>Snippet for GetIamPolicyAsync</summary>
public async Task GetIamPolicyAsync()
{
// Snippet: GetIamPolicyAsync(string, string, CallSettings)
// Additional: GetIamPolicyAsync(string, string, CancellationToken)
// Create client
ImagesClient imagesClient = await ImagesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string resource = "";
// Make the request
Policy response = await imagesClient.GetIamPolicyAsync(project, resource);
// End snippet
}
/// <summary>Snippet for Insert</summary>
public void InsertRequestObject()
{
// Snippet: Insert(InsertImageRequest, CallSettings)
// Create client
ImagesClient imagesClient = ImagesClient.Create();
// Initialize request argument(s)
InsertImageRequest request = new InsertImageRequest
{
RequestId = "",
ForceCreate = false,
Project = "",
ImageResource = new Image(),
};
// Make the request
lro::Operation<Operation, Operation> response = imagesClient.Insert(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = imagesClient.PollOnceInsert(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for InsertAsync</summary>
public async Task InsertRequestObjectAsync()
{
// Snippet: InsertAsync(InsertImageRequest, CallSettings)
// Additional: InsertAsync(InsertImageRequest, CancellationToken)
// Create client
ImagesClient imagesClient = await ImagesClient.CreateAsync();
// Initialize request argument(s)
InsertImageRequest request = new InsertImageRequest
{
RequestId = "",
ForceCreate = false,
Project = "",
ImageResource = new Image(),
};
// Make the request
lro::Operation<Operation, Operation> response = await imagesClient.InsertAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await imagesClient.PollOnceInsertAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Insert</summary>
public void Insert()
{
// Snippet: Insert(string, Image, CallSettings)
// Create client
ImagesClient imagesClient = ImagesClient.Create();
// Initialize request argument(s)
string project = "";
Image imageResource = new Image();
// Make the request
lro::Operation<Operation, Operation> response = imagesClient.Insert(project, imageResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = imagesClient.PollOnceInsert(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for InsertAsync</summary>
public async Task InsertAsync()
{
// Snippet: InsertAsync(string, Image, CallSettings)
// Additional: InsertAsync(string, Image, CancellationToken)
// Create client
ImagesClient imagesClient = await ImagesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
Image imageResource = new Image();
// Make the request
lro::Operation<Operation, Operation> response = await imagesClient.InsertAsync(project, imageResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await imagesClient.PollOnceInsertAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for List</summary>
public void ListRequestObject()
{
// Snippet: List(ListImagesRequest, CallSettings)
// Create client
ImagesClient imagesClient = ImagesClient.Create();
// Initialize request argument(s)
ListImagesRequest request = new ListImagesRequest
{
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedEnumerable<ImageList, Image> response = imagesClient.List(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Image item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ImageList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Image item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Image> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Image item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAsync</summary>
public async Task ListRequestObjectAsync()
{
// Snippet: ListAsync(ListImagesRequest, CallSettings)
// Create client
ImagesClient imagesClient = await ImagesClient.CreateAsync();
// Initialize request argument(s)
ListImagesRequest request = new ListImagesRequest
{
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedAsyncEnumerable<ImageList, Image> response = imagesClient.ListAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Image item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ImageList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Image item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Image> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Image item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for List</summary>
public void List()
{
// Snippet: List(string, string, int?, CallSettings)
// Create client
ImagesClient imagesClient = ImagesClient.Create();
// Initialize request argument(s)
string project = "";
// Make the request
PagedEnumerable<ImageList, Image> response = imagesClient.List(project);
// Iterate over all response items, lazily performing RPCs as required
foreach (Image item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ImageList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Image item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Image> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Image item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAsync</summary>
public async Task ListAsync()
{
// Snippet: ListAsync(string, string, int?, CallSettings)
// Create client
ImagesClient imagesClient = await ImagesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
// Make the request
PagedAsyncEnumerable<ImageList, Image> response = imagesClient.ListAsync(project);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Image item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ImageList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Image item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Image> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Image item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for Patch</summary>
public void PatchRequestObject()
{
// Snippet: Patch(PatchImageRequest, CallSettings)
// Create client
ImagesClient imagesClient = ImagesClient.Create();
// Initialize request argument(s)
PatchImageRequest request = new PatchImageRequest
{
RequestId = "",
Image = "",
Project = "",
ImageResource = new Image(),
};
// Make the request
lro::Operation<Operation, Operation> response = imagesClient.Patch(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = imagesClient.PollOncePatch(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for PatchAsync</summary>
public async Task PatchRequestObjectAsync()
{
// Snippet: PatchAsync(PatchImageRequest, CallSettings)
// Additional: PatchAsync(PatchImageRequest, CancellationToken)
// Create client
ImagesClient imagesClient = await ImagesClient.CreateAsync();
// Initialize request argument(s)
PatchImageRequest request = new PatchImageRequest
{
RequestId = "",
Image = "",
Project = "",
ImageResource = new Image(),
};
// Make the request
lro::Operation<Operation, Operation> response = await imagesClient.PatchAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await imagesClient.PollOncePatchAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Patch</summary>
public void Patch()
{
// Snippet: Patch(string, string, Image, CallSettings)
// Create client
ImagesClient imagesClient = ImagesClient.Create();
// Initialize request argument(s)
string project = "";
string image = "";
Image imageResource = new Image();
// Make the request
lro::Operation<Operation, Operation> response = imagesClient.Patch(project, image, imageResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = imagesClient.PollOncePatch(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for PatchAsync</summary>
public async Task PatchAsync()
{
// Snippet: PatchAsync(string, string, Image, CallSettings)
// Additional: PatchAsync(string, string, Image, CancellationToken)
// Create client
ImagesClient imagesClient = await ImagesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string image = "";
Image imageResource = new Image();
// Make the request
lro::Operation<Operation, Operation> response = await imagesClient.PatchAsync(project, image, imageResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await imagesClient.PollOncePatchAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for SetIamPolicy</summary>
public void SetIamPolicyRequestObject()
{
// Snippet: SetIamPolicy(SetIamPolicyImageRequest, CallSettings)
// Create client
ImagesClient imagesClient = ImagesClient.Create();
// Initialize request argument(s)
SetIamPolicyImageRequest request = new SetIamPolicyImageRequest
{
Resource = "",
Project = "",
GlobalSetPolicyRequestResource = new GlobalSetPolicyRequest(),
};
// Make the request
Policy response = imagesClient.SetIamPolicy(request);
// End snippet
}
/// <summary>Snippet for SetIamPolicyAsync</summary>
public async Task SetIamPolicyRequestObjectAsync()
{
// Snippet: SetIamPolicyAsync(SetIamPolicyImageRequest, CallSettings)
// Additional: SetIamPolicyAsync(SetIamPolicyImageRequest, CancellationToken)
// Create client
ImagesClient imagesClient = await ImagesClient.CreateAsync();
// Initialize request argument(s)
SetIamPolicyImageRequest request = new SetIamPolicyImageRequest
{
Resource = "",
Project = "",
GlobalSetPolicyRequestResource = new GlobalSetPolicyRequest(),
};
// Make the request
Policy response = await imagesClient.SetIamPolicyAsync(request);
// End snippet
}
/// <summary>Snippet for SetIamPolicy</summary>
public void SetIamPolicy()
{
// Snippet: SetIamPolicy(string, string, GlobalSetPolicyRequest, CallSettings)
// Create client
ImagesClient imagesClient = ImagesClient.Create();
// Initialize request argument(s)
string project = "";
string resource = "";
GlobalSetPolicyRequest globalSetPolicyRequestResource = new GlobalSetPolicyRequest();
// Make the request
Policy response = imagesClient.SetIamPolicy(project, resource, globalSetPolicyRequestResource);
// End snippet
}
/// <summary>Snippet for SetIamPolicyAsync</summary>
public async Task SetIamPolicyAsync()
{
// Snippet: SetIamPolicyAsync(string, string, GlobalSetPolicyRequest, CallSettings)
// Additional: SetIamPolicyAsync(string, string, GlobalSetPolicyRequest, CancellationToken)
// Create client
ImagesClient imagesClient = await ImagesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string resource = "";
GlobalSetPolicyRequest globalSetPolicyRequestResource = new GlobalSetPolicyRequest();
// Make the request
Policy response = await imagesClient.SetIamPolicyAsync(project, resource, globalSetPolicyRequestResource);
// End snippet
}
/// <summary>Snippet for SetLabels</summary>
public void SetLabelsRequestObject()
{
// Snippet: SetLabels(SetLabelsImageRequest, CallSettings)
// Create client
ImagesClient imagesClient = ImagesClient.Create();
// Initialize request argument(s)
SetLabelsImageRequest request = new SetLabelsImageRequest
{
Resource = "",
Project = "",
GlobalSetLabelsRequestResource = new GlobalSetLabelsRequest(),
};
// Make the request
lro::Operation<Operation, Operation> response = imagesClient.SetLabels(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = imagesClient.PollOnceSetLabels(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for SetLabelsAsync</summary>
public async Task SetLabelsRequestObjectAsync()
{
// Snippet: SetLabelsAsync(SetLabelsImageRequest, CallSettings)
// Additional: SetLabelsAsync(SetLabelsImageRequest, CancellationToken)
// Create client
ImagesClient imagesClient = await ImagesClient.CreateAsync();
// Initialize request argument(s)
SetLabelsImageRequest request = new SetLabelsImageRequest
{
Resource = "",
Project = "",
GlobalSetLabelsRequestResource = new GlobalSetLabelsRequest(),
};
// Make the request
lro::Operation<Operation, Operation> response = await imagesClient.SetLabelsAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await imagesClient.PollOnceSetLabelsAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for SetLabels</summary>
public void SetLabels()
{
// Snippet: SetLabels(string, string, GlobalSetLabelsRequest, CallSettings)
// Create client
ImagesClient imagesClient = ImagesClient.Create();
// Initialize request argument(s)
string project = "";
string resource = "";
GlobalSetLabelsRequest globalSetLabelsRequestResource = new GlobalSetLabelsRequest();
// Make the request
lro::Operation<Operation, Operation> response = imagesClient.SetLabels(project, resource, globalSetLabelsRequestResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = imagesClient.PollOnceSetLabels(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for SetLabelsAsync</summary>
public async Task SetLabelsAsync()
{
// Snippet: SetLabelsAsync(string, string, GlobalSetLabelsRequest, CallSettings)
// Additional: SetLabelsAsync(string, string, GlobalSetLabelsRequest, CancellationToken)
// Create client
ImagesClient imagesClient = await ImagesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string resource = "";
GlobalSetLabelsRequest globalSetLabelsRequestResource = new GlobalSetLabelsRequest();
// Make the request
lro::Operation<Operation, Operation> response = await imagesClient.SetLabelsAsync(project, resource, globalSetLabelsRequestResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await imagesClient.PollOnceSetLabelsAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for TestIamPermissions</summary>
public void TestIamPermissionsRequestObject()
{
// Snippet: TestIamPermissions(TestIamPermissionsImageRequest, CallSettings)
// Create client
ImagesClient imagesClient = ImagesClient.Create();
// Initialize request argument(s)
TestIamPermissionsImageRequest request = new TestIamPermissionsImageRequest
{
Resource = "",
Project = "",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
// Make the request
TestPermissionsResponse response = imagesClient.TestIamPermissions(request);
// End snippet
}
/// <summary>Snippet for TestIamPermissionsAsync</summary>
public async Task TestIamPermissionsRequestObjectAsync()
{
// Snippet: TestIamPermissionsAsync(TestIamPermissionsImageRequest, CallSettings)
// Additional: TestIamPermissionsAsync(TestIamPermissionsImageRequest, CancellationToken)
// Create client
ImagesClient imagesClient = await ImagesClient.CreateAsync();
// Initialize request argument(s)
TestIamPermissionsImageRequest request = new TestIamPermissionsImageRequest
{
Resource = "",
Project = "",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
// Make the request
TestPermissionsResponse response = await imagesClient.TestIamPermissionsAsync(request);
// End snippet
}
/// <summary>Snippet for TestIamPermissions</summary>
public void TestIamPermissions()
{
// Snippet: TestIamPermissions(string, string, TestPermissionsRequest, CallSettings)
// Create client
ImagesClient imagesClient = ImagesClient.Create();
// Initialize request argument(s)
string project = "";
string resource = "";
TestPermissionsRequest testPermissionsRequestResource = new TestPermissionsRequest();
// Make the request
TestPermissionsResponse response = imagesClient.TestIamPermissions(project, resource, testPermissionsRequestResource);
// End snippet
}
/// <summary>Snippet for TestIamPermissionsAsync</summary>
public async Task TestIamPermissionsAsync()
{
// Snippet: TestIamPermissionsAsync(string, string, TestPermissionsRequest, CallSettings)
// Additional: TestIamPermissionsAsync(string, string, TestPermissionsRequest, CancellationToken)
// Create client
ImagesClient imagesClient = await ImagesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string resource = "";
TestPermissionsRequest testPermissionsRequestResource = new TestPermissionsRequest();
// Make the request
TestPermissionsResponse response = await imagesClient.TestIamPermissionsAsync(project, resource, testPermissionsRequestResource);
// End snippet
}
}
}
| |
// 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.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Billing
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// InvoicesOperations operations.
/// </summary>
internal partial class InvoicesOperations : IServiceOperations<BillingManagementClient>, IInvoicesOperations
{
/// <summary>
/// Initializes a new instance of the InvoicesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal InvoicesOperations(BillingManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the BillingManagementClient
/// </summary>
public BillingManagementClient Client { get; private set; }
/// <summary>
/// Lists the available invoices for a subscription in reverse chronological
/// order beginning with the most recent invoice. In preview, invoices are
/// available via this API only for invoice periods which end December 1, 2016
/// or later.
/// <see href="https://go.microsoft.com/fwlink/?linkid=842057" />
/// </summary>
/// <param name='expand'>
/// May be used to expand the downloadUrl property within a list of invoices.
/// This enables download links to be generated for multiple invoices at once.
/// By default, downloadURLs are not included when listing invoices.
/// </param>
/// <param name='filter'>
/// May be used to filter invoices by invoicePeriodEndDate. The filter supports
/// 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support
/// 'ne', 'or', or 'not'.
/// </param>
/// <param name='skiptoken'>
/// Skiptoken is only used if a previous operation returned a partial result.
/// If a previous response contains a nextLink element, the value of the
/// nextLink element will include a skiptoken parameter that specifies a
/// starting point to use for subsequent calls.
/// </param>
/// <param name='top'>
/// May be used to limit the number of results to the most recent N invoices.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Invoice>>> ListWithHttpMessagesAsync(string expand = default(string), string filter = default(string), string skiptoken = default(string), int? top = default(int?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (top > 100)
{
throw new ValidationException(ValidationRules.InclusiveMaximum, "top", 100);
}
if (top < 1)
{
throw new ValidationException(ValidationRules.InclusiveMinimum, "top", 1);
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("expand", expand);
tracingParameters.Add("filter", filter);
tracingParameters.Add("skiptoken", skiptoken);
tracingParameters.Add("top", top);
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.Billing/invoices").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 (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand)));
}
if (filter != null)
{
_queryParameters.Add(string.Format("$filter={0}", System.Uri.EscapeDataString(filter)));
}
if (skiptoken != null)
{
_queryParameters.Add(string.Format("$skiptoken={0}", System.Uri.EscapeDataString(skiptoken)));
}
if (top != null)
{
_queryParameters.Add(string.Format("$top={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(top, Client.SerializationSettings).Trim('"'))));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Invoice>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Invoice>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a named invoice resource. When getting a single invoice, the
/// downloadUrl property is expanded automatically.
/// </summary>
/// <param name='invoiceName'>
/// The name of an invoice resource.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Invoice>> GetWithHttpMessagesAsync(string invoiceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (invoiceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "invoiceName");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("invoiceName", invoiceName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Billing/invoices/{invoiceName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{invoiceName}", System.Uri.EscapeDataString(invoiceName));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Invoice>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Invoice>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets the most recent invoice. When getting a single invoice, the
/// downloadUrl property is expanded automatically.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Invoice>> GetLatestWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetLatest", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Billing/invoices/latest").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 ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Invoice>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Invoice>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists the available invoices for a subscription in reverse chronological
/// order beginning with the most recent invoice. In preview, invoices are
/// available via this API only for invoice periods which end December 1, 2016
/// or later.
/// <see href="https://go.microsoft.com/fwlink/?linkid=842057" />
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Invoice>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Invoice>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Invoice>>(_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;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Globalization;
using System.Security.Cryptography.X509Certificates;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Net;
using System.Security.Principal;
using System.DirectoryServices;
namespace System.DirectoryServices.AccountManagement
{
internal partial class SAMStoreCtx : StoreCtx
{
//
// Native <--> Principal
//
// For modified object, pushes any changes (including IdentityClaim changes)
// into the underlying store-specific object (e.g., DirectoryEntry) and returns the underlying object.
// For unpersisted object, creates a underlying object if one doesn't already exist (in
// Principal.UnderlyingObject), then pushes any changes into the underlying object.
internal override object PushChangesToNative(Principal p)
{
try
{
DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject;
Type principalType = p.GetType();
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "Entering PushChangesToNative, type={0}", p.GetType());
if (de == null)
{
// Must be a newly-inserted Principal for which PushChangesToNative has not yet
// been called.
// Determine the objectClass of the SAM entry we'll be creating
string objectClass;
if (principalType == typeof(UserPrincipal) || principalType.IsSubclassOf(typeof(UserPrincipal)))
objectClass = "user";
else if (principalType == typeof(GroupPrincipal) || principalType.IsSubclassOf(typeof(GroupPrincipal)))
objectClass = "group";
else
{
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture, StringResources.StoreCtxUnsupportedPrincipalTypeForSave, principalType.ToString()));
}
// Determine the SAM account name for the entry we'll be creating. Use the name from the NT4 IdentityClaim.
string samAccountName = GetSamAccountName(p);
if (samAccountName == null)
{
// They didn't set a NT4 IdentityClaim.
throw new InvalidOperationException(StringResources.NameMustBeSetToPersistPrincipal);
}
lock (_ctxBaseLock)
{
de = _ctxBase.Children.Add(samAccountName, objectClass);
}
GlobalDebug.WriteLineIf(
GlobalDebug.Info, "SAMStoreCtx", "PushChangesToNative: created fresh DE, oc={0}, name={1}, path={2}",
objectClass, samAccountName, de.Path);
p.UnderlyingObject = de;
// set the default user account control bits for authenticable principals
if (principalType.IsSubclassOf(typeof(AuthenticablePrincipal)))
{
InitializeUserAccountControl((AuthenticablePrincipal)p);
}
}
// Determine the mapping table to use, based on the principal type
Hashtable propertyMappingTableByProperty;
if (principalType == typeof(UserPrincipal))
{
propertyMappingTableByProperty = s_userPropertyMappingTableByProperty;
}
else if (principalType == typeof(GroupPrincipal))
{
propertyMappingTableByProperty = s_groupPropertyMappingTableByProperty;
}
else
{
Debug.Assert(principalType == typeof(ComputerPrincipal));
propertyMappingTableByProperty = s_computerPropertyMappingTableByProperty;
}
// propertyMappingTableByProperty has entries for all writable properties,
// including writable properties which we don't support in SAM for some or
// all principal types.
// If we don't support the property, the PropertyMappingTableEntry will map
// it to a converter which will throw an appropriate exception.
foreach (DictionaryEntry dictEntry in propertyMappingTableByProperty)
{
ArrayList propertyEntries = (ArrayList)dictEntry.Value;
foreach (PropertyMappingTableEntry propertyEntry in propertyEntries)
{
if (null != propertyEntry.papiToWinNTConverter)
{
if (p.GetChangeStatusForProperty(propertyEntry.propertyName))
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "PushChangesToNative: pushing {0}", propertyEntry.propertyName);
// The property was set. Write it to the DirectoryEntry.
Debug.Assert(propertyEntry.propertyName == (string)dictEntry.Key);
propertyEntry.papiToWinNTConverter(
p,
propertyEntry.propertyName,
de,
propertyEntry.suggestedWinNTPropertyName,
this.IsLSAM
);
}
}
}
}
// Unlike AD, where password sets on newly-created principals must be handled after persisting the principal,
// in SAM they get set before persisting the principal, and ADSI's WinNT provider saves off the operation
// until the SetInfo() is performed.
if (p.GetChangeStatusForProperty(PropertyNames.PwdInfoPassword))
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "PushChangesToNative: setting password");
// Only AuthenticablePrincipals can have PasswordInfo
Debug.Assert(p is AuthenticablePrincipal);
string password = (string)p.GetValueForProperty(PropertyNames.PwdInfoPassword);
Debug.Assert(password != null); // if null, PasswordInfo should not have indicated it was changed
SDSUtils.SetPassword(de, password);
}
return de;
}
catch (System.Runtime.InteropServices.COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(e);
}
}
private string GetSamAccountName(Principal p)
{
// They didn't set any IdentityClaims, so they certainly didn't set a NT4 IdentityClaim
if (!p.GetChangeStatusForProperty(PropertyNames.PrincipalSamAccountName))
return null;
string Name = p.SamAccountName;
if (Name == null)
return null;
// Split the SAM account name out of the UrnValue
// We accept both "host\user" and "user"
int index = Name.IndexOf('\\');
if (index == Name.Length - 1)
return null;
return (index != -1) ? Name.Substring(index + 1) : // +1 to skip the '/'
Name;
}
// Given a underlying store object (e.g., DirectoryEntry), further narrowed down a discriminant
// (if applicable for the StoreCtx type), returns a fresh instance of a Principal
// object based on it. The WinFX Principal API follows ADSI-style semantics, where you get multiple
// in-memory objects all referring to the same store pricipal, rather than WinFS semantics, where
// multiple searches all return references to the same in-memory object.
// Used to implement the reverse wormhole. Also, used internally by FindResultEnumerator
// to construct Principals from the store objects returned by a store query.
//
// The Principal object produced by this method does not have all the properties
// loaded. The Principal object will call the Load method on demand to load its properties
// from its Principal.UnderlyingObject.
//
//
// This method works for native objects from the store corresponding to _this_ StoreCtx.
// Each StoreCtx will also have its own internal algorithms used for dealing with cross-store objects, e.g.,
// for use when iterating over group membership. These routines are exposed as
// ResolveCrossStoreRefToPrincipal, and will be called by the StoreCtx's associated ResultSet
// classes when iterating over a representation of a "foreign" principal.
internal override Principal GetAsPrincipal(object storeObject, object discriminant)
{
// SAM doesn't use discriminant, should always be null.
Debug.Assert(discriminant == null);
Debug.Assert(storeObject != null);
Debug.Assert(storeObject is DirectoryEntry);
DirectoryEntry de = (DirectoryEntry)storeObject;
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "GetAsPrincipal: using path={0}", de.Path);
// Construct a appropriate Principal object.
Principal p = SDSUtils.DirectoryEntryToPrincipal(de, this.OwningContext, null);
Debug.Assert(p != null);
// Assign a SAMStoreKey to the newly-constructed Principal.
// If it doesn't have an objectSid, it's not a principal and we shouldn't be here.
Debug.Assert((de.Properties["objectSid"] != null) && (de.Properties["objectSid"].Count == 1));
SAMStoreKey key = new SAMStoreKey(this.MachineFlatName, (byte[])de.Properties["objectSid"].Value);
p.Key = key;
return p;
}
internal override void Load(Principal p, string principalPropertyName)
{
Debug.Assert(p != null);
Debug.Assert(p.UnderlyingObject != null);
Debug.Assert(p.UnderlyingObject is DirectoryEntry);
DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject;
Type principalType = p.GetType();
Hashtable propertyMappingTableByProperty;
if (principalType == typeof(UserPrincipal))
{
propertyMappingTableByProperty = s_userPropertyMappingTableByProperty;
}
else if (principalType == typeof(GroupPrincipal))
{
propertyMappingTableByProperty = s_groupPropertyMappingTableByProperty;
}
else
{
Debug.Assert(principalType == typeof(ComputerPrincipal));
propertyMappingTableByProperty = s_computerPropertyMappingTableByProperty;
}
ArrayList entries = (ArrayList)propertyMappingTableByProperty[principalPropertyName];
// We don't support this property and cannot load it. To maintain backward compatibility with the old code just return.
if (entries == null)
return;
try
{
foreach (PropertyMappingTableEntry entry in entries)
{
if (null != entry.winNTToPapiConverter)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "Load_PropertyName: loading {0}", entry.propertyName);
entry.winNTToPapiConverter(de, entry.suggestedWinNTPropertyName, p, entry.propertyName);
}
}
}
catch (System.Runtime.InteropServices.COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(e);
}
}
// Loads the store values from p.UnderlyingObject into p, performing schema mapping as needed.
internal override void Load(Principal p)
{
try
{
Debug.Assert(p != null);
Debug.Assert(p.UnderlyingObject != null);
Debug.Assert(p.UnderlyingObject is DirectoryEntry);
DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject;
Debug.Assert(de != null);
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "Entering Load, type={0}, path={1}", p.GetType(), de.Path);
// The list of all the SAM attributes in the DirectoryEntry
ICollection samAttributes = de.Properties.PropertyNames;
// Determine the mapping table to use, based on the principal type
Type principalType = p.GetType();
Hashtable propertyMappingTableByWinNT;
if (principalType == typeof(UserPrincipal))
{
propertyMappingTableByWinNT = s_userPropertyMappingTableByWinNT;
}
else if (principalType == typeof(GroupPrincipal))
{
propertyMappingTableByWinNT = s_groupPropertyMappingTableByWinNT;
}
else
{
Debug.Assert(principalType == typeof(ComputerPrincipal));
propertyMappingTableByWinNT = s_computerPropertyMappingTableByWinNT;
}
// Map each SAM attribute into the Principal in turn
foreach (string samAttribute in samAttributes)
{
ArrayList entries = (ArrayList)propertyMappingTableByWinNT[samAttribute.ToLower(CultureInfo.InvariantCulture)];
// If it's not in the table, it's not an SAM attribute we care about
if (entries == null)
continue;
// Load it into the Principal. Some LDAP attributes (such as userAccountControl)
// map to more than one Principal property.
foreach (PropertyMappingTableEntry entry in entries)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "Load: loading {0}", entry.propertyName);
entry.winNTToPapiConverter(de, entry.suggestedWinNTPropertyName, p, entry.propertyName);
}
}
}
catch (System.Runtime.InteropServices.COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(e);
}
}
// Performs store-specific resolution of an IdentityReference to a Principal
// corresponding to the IdentityReference. Returns null if no matching object found.
// principalType can be used to scope the search to principals of a specified type, e.g., users or groups.
// Specify typeof(Principal) to search all principal types.
internal override Principal FindPrincipalByIdentRef(
Type principalType, string urnScheme, string urnValue, DateTime referenceDate)
{
// Perform the appropriate action based on the type of the UrnScheme
if (urnScheme == UrnScheme.SidScheme)
{
// Get the SID from the UrnValue
SecurityIdentifier sidObj = new SecurityIdentifier(urnValue);
byte[] sid = new byte[sidObj.BinaryLength];
sidObj.GetBinaryForm(sid, 0);
if (sid == null)
throw new ArgumentException(StringResources.StoreCtxSecurityIdentityClaimBadFormat);
// If they're searching by SID for a SID corresponding to a fake group, construct
// and return the fake group
IntPtr pSid = IntPtr.Zero;
try
{
pSid = Utils.ConvertByteArrayToIntPtr(sid);
if (UnsafeNativeMethods.IsValidSid(pSid) && (Utils.ClassifySID(pSid) == SidType.FakeObject))
{
GlobalDebug.WriteLineIf(GlobalDebug.Info,
"SAMStoreCtx",
"FindPrincipalByIdentRef: fake principal {0}",
sidObj.ToString());
return ConstructFakePrincipalFromSID(sid);
}
}
finally
{
if (pSid != IntPtr.Zero)
Marshal.FreeHGlobal(pSid);
}
// Not a fake group. Search for the real group.
object o = FindNativeBySIDIdentRef(principalType, sid);
return (o != null) ? GetAsPrincipal(o, null) : null;
}
else if (urnScheme == UrnScheme.SamAccountScheme || urnScheme == UrnScheme.NameScheme)
{
object o = FindNativeByNT4IdentRef(principalType, urnValue);
return (o != null) ? GetAsPrincipal(o, null) : null;
}
else if (urnScheme == null)
{
object sidPrincipal = null;
object nt4Principal = null;
//
// Try UrnValue as a SID IdentityClaim
//
// Get the SID from the UrnValue
byte[] sid = null;
try
{
SecurityIdentifier sidObj = new SecurityIdentifier(urnValue);
sid = new byte[sidObj.BinaryLength];
sidObj.GetBinaryForm(sid, 0);
}
catch (ArgumentException)
{
// must not have been a valid sid claim ignore it.
}
// If null, must have been a non-SID UrnValue. Ignore it, and
// continue on to try NT4 Account IdentityClaim.
if (sid != null)
{
// Are they perhaps searching for a fake group?
// If they passed in a valid SID for a fake group, construct and return the fake
// group.
if (principalType == typeof(Principal) || principalType == typeof(GroupPrincipal) || principalType.IsSubclassOf(typeof(GroupPrincipal)))
{
// They passed in a hex string, is it a valid SID, and if so, does it correspond to a fake
// principal?
IntPtr pSid = IntPtr.Zero;
try
{
pSid = Utils.ConvertByteArrayToIntPtr(sid);
if (UnsafeNativeMethods.IsValidSid(pSid) && (Utils.ClassifySID(pSid) == SidType.FakeObject))
{
GlobalDebug.WriteLineIf(GlobalDebug.Info,
"SAMStoreCtx",
"FindPrincipalByIdentRef: fake principal {0} (scheme==null)",
Utils.ByteArrayToString(sid));
return ConstructFakePrincipalFromSID(sid);
}
}
finally
{
if (pSid != IntPtr.Zero)
Marshal.FreeHGlobal(pSid);
}
}
sidPrincipal = FindNativeBySIDIdentRef(principalType, sid);
}
//
// Try UrnValue as a NT4 IdentityClaim
//
try
{
nt4Principal = FindNativeByNT4IdentRef(principalType, urnValue);
}
catch (ArgumentException)
{
// Must have been a non-NT4 Account UrnValue. Ignore it.
}
GlobalDebug.WriteLineIf(GlobalDebug.Info,
"SAMStoreCtx",
"FindPrincipalByIdentRef: scheme==null, found nt4={0}, found sid={1}",
(nt4Principal != null),
(sidPrincipal != null));
// If they both succeeded in finding a match, we have too many matches.
// Throw an exception.
if ((sidPrincipal != null) && (nt4Principal != null))
throw new MultipleMatchesException(StringResources.MultipleMatchingPrincipals);
// Return whichever one matched. If neither matched, this will return null.
return (sidPrincipal != null) ? GetAsPrincipal(sidPrincipal, null) :
((nt4Principal != null) ? GetAsPrincipal(nt4Principal, null) :
null);
}
else
{
// Unsupported type of IdentityClaim
throw new ArgumentException(StringResources.StoreCtxUnsupportedIdentityClaimForQuery);
}
}
private object FindNativeBySIDIdentRef(Type principalType, byte[] sid)
{
// We can't lookup directly by SID, so we transform the SID --> SAM account name,
// and do a lookup by that.
string samUrnValue;
string name;
string domainName;
int accountUsage;
// Map the SID to a machine and account name
// If this fails, there's no match
int err = Utils.LookupSid(this.MachineUserSuppliedName, _credentials, sid, out name, out domainName, out accountUsage);
if (err != 0)
{
GlobalDebug.WriteLineIf(GlobalDebug.Error,
"SAMStoreCtx",
"FindNativeBySIDIdentRef:LookupSid on {0} failed, err={1}",
this.MachineUserSuppliedName,
err);
return null;
}
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "FindNativeBySIDIdentRef: mapped to {0}\\{1}", domainName, name);
// Fixup the domainName for BUILTIN principals
if (Utils.ClassifySID(sid) == SidType.RealObjectFakeDomain)
{
// BUILTIN principal ---> Issuer is actually our machine, not "BUILTIN" domain.
domainName = this.MachineFlatName;
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "FindNativeBySIDIdentRef: using {0} for domainName", domainName);
}
// Valid SID, but not for our context (machine). No match.
if (String.Compare(domainName, this.MachineFlatName, StringComparison.OrdinalIgnoreCase) != 0)
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "FindNativeBySIDIdentRef: {0} != {1}, no match", domainName, this.MachineFlatName);
return null;
}
// Build the NT4 UrnValue
samUrnValue = domainName + "\\" + name;
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "FindNativeBySIDIdentRef: searching for {0}", samUrnValue);
return FindNativeByNT4IdentRef(principalType, samUrnValue);
}
private object FindNativeByNT4IdentRef(Type principalType, string urnValue)
{
// Extract the SAM account name from the UrnValue.
// We'll accept both "host\user" and "user".
int index = urnValue.IndexOf('\\');
if (index == urnValue.Length - 1)
throw new ArgumentException(StringResources.StoreCtxNT4IdentityClaimWrongForm);
string samAccountName = (index != -1) ? urnValue.Substring(index + 1) : // +1 to skip the '/'
urnValue;
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "FindNativeByNT4IdentRef: searching for {0}", samAccountName);
// If they specified a specific type of principal, use that as a hint to speed up
// the lookup.
string principalHint = "";
if (principalType == typeof(UserPrincipal) || principalType.IsSubclassOf(typeof(UserPrincipal)))
{
principalHint = ",user";
principalType = typeof(UserPrincipal);
}
else if (principalType == typeof(GroupPrincipal) || principalType.IsSubclassOf(typeof(GroupPrincipal)))
{
principalHint = ",group";
principalType = typeof(GroupPrincipal);
}
else if (principalType == typeof(ComputerPrincipal) || principalType.IsSubclassOf(typeof(ComputerPrincipal)))
{
principalHint = ",computer";
principalType = typeof(ComputerPrincipal);
}
// Retrieve the object from SAM
string adsPath = "WinNT://" + this.MachineUserSuppliedName + "/" + samAccountName + principalHint;
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "FindNativeByNT4IdentRef: adsPath={0}", adsPath);
DirectoryEntry de = SDSUtils.BuildDirectoryEntry(_credentials, _authTypes);
try
{
de.Path = adsPath;
// If it has no SID, it's not a security principal, and we're not interested in it.
// This also has the side effect of forcing the object to load, thereby testing
// whether or not it exists.
if (de.Properties["objectSid"] == null || de.Properties["objectSid"].Count == 0)
return false;
}
catch (System.Runtime.InteropServices.COMException e)
{
GlobalDebug.WriteLineIf(GlobalDebug.Error,
"SAMStoreCtx",
"FindNativeByNT4IdentRef: caught COMException, message={0}, code={1}",
e.Message,
e.ErrorCode);
// Failed to find it
if ((e.ErrorCode == unchecked((int)0x800708AB)) || // unknown user
(e.ErrorCode == unchecked((int)0x800708AC)) || // unknown group
(e.ErrorCode == unchecked((int)0x80070035)) || // bad net path
(e.ErrorCode == unchecked((int)0x800708AD)))
{
return null;
}
// Unknown error, don't suppress it
throw ExceptionHelper.GetExceptionFromCOMException(e);
}
// Make sure it's of the correct type
bool fMatch = false;
if ((principalType == typeof(UserPrincipal)) && SAMUtils.IsOfObjectClass(de, "User"))
fMatch = true;
else if ((principalType == typeof(GroupPrincipal)) && SAMUtils.IsOfObjectClass(de, "Group"))
fMatch = true;
else if ((principalType == typeof(ComputerPrincipal)) && SAMUtils.IsOfObjectClass(de, "Computer"))
fMatch = true;
else if ((principalType == typeof(AuthenticablePrincipal)) &&
(SAMUtils.IsOfObjectClass(de, "User") || SAMUtils.IsOfObjectClass(de, "Computer")))
fMatch = true;
else
{
Debug.Assert(principalType == typeof(Principal));
if (SAMUtils.IsOfObjectClass(de, "User") || SAMUtils.IsOfObjectClass(de, "Group") || SAMUtils.IsOfObjectClass(de, "Computer"))
fMatch = true;
}
if (fMatch)
return de;
return null;
}
// Returns a type indicating the type of object that would be returned as the wormhole for the specified
// Principal. For some StoreCtxs, this method may always return a constant (e.g., typeof(DirectoryEntry)
// for ADStoreCtx). For others, it may vary depending on the Principal passed in.
internal override Type NativeType(Principal p)
{
Debug.Assert(p != null);
return typeof(DirectoryEntry);
}
//
// Property mapping tables
//
// We only list properties we map in this table. At run-time, if we detect they set a
// property that's not listed here, or is listed here but not for the correct principal type,
// when writing to SAM, we throw an exception.
private static object[,] s_propertyMappingTableRaw =
{
// PropertyName Principal Type SAM property Converter(WinNT->PAPI) Converter(PAPI->WinNT)
{PropertyNames.PrincipalDisplayName, typeof(UserPrincipal), "FullName", new FromWinNTConverterDelegate(StringFromWinNTConverter), new ToWinNTConverterDelegate(StringToWinNTConverter)},
{PropertyNames.PrincipalDescription, typeof(UserPrincipal), "Description", new FromWinNTConverterDelegate(StringFromWinNTConverter), new ToWinNTConverterDelegate(StringToWinNTConverter)},
{PropertyNames.PrincipalDescription, typeof(GroupPrincipal), "Description", new FromWinNTConverterDelegate(StringFromWinNTConverter), new ToWinNTConverterDelegate(StringToWinNTConverter)},
{PropertyNames.PrincipalSamAccountName, typeof(Principal), "Name", new FromWinNTConverterDelegate(SamAccountNameFromWinNTConverter), null},
{PropertyNames.PrincipalSid, typeof(Principal), "objectSid", new FromWinNTConverterDelegate(SidFromWinNTConverter), null },
{PropertyNames.PrincipalDistinguishedName, typeof(UserPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.PrincipalGuid, typeof(UserPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.PrincipalUserPrincipalName, typeof(UserPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
// Name and SamAccountNAme properties are currently routed to the same underlying Name property.
{PropertyNames.PrincipalName, typeof(Principal), "Name", new FromWinNTConverterDelegate(SamAccountNameFromWinNTConverter), null},
//
{PropertyNames.AuthenticablePrincipalEnabled , typeof(UserPrincipal), "UserFlags", new FromWinNTConverterDelegate(UserFlagsFromWinNTConverter), new ToWinNTConverterDelegate(UserFlagsToWinNTConverter)},
{PropertyNames.AuthenticablePrincipalCertificates, typeof(UserPrincipal), "*******", new FromWinNTConverterDelegate(CertFromWinNTConverter), new ToWinNTConverterDelegate(CertToWinNT)},
//
{PropertyNames.GroupIsSecurityGroup, typeof(GroupPrincipal), "*******", new FromWinNTConverterDelegate(GroupTypeFromWinNTConverter), new ToWinNTConverterDelegate(GroupTypeToWinNTConverter)},
{PropertyNames.GroupGroupScope, typeof(GroupPrincipal), "groupType", new FromWinNTConverterDelegate(GroupTypeFromWinNTConverter), new ToWinNTConverterDelegate(GroupTypeToWinNTConverter)},
//
{PropertyNames.UserEmailAddress, typeof(UserPrincipal), "*******" , new FromWinNTConverterDelegate(EmailFromWinNTConverter), new ToWinNTConverterDelegate(EmailToWinNTConverter)},
//
{PropertyNames.AcctInfoLastLogon, typeof(UserPrincipal), "LastLogin", new FromWinNTConverterDelegate(DateFromWinNTConverter), null},
{PropertyNames.AcctInfoPermittedWorkstations, typeof(UserPrincipal), "LoginWorkstations", new FromWinNTConverterDelegate(MultiStringFromWinNTConverter), new ToWinNTConverterDelegate(MultiStringToWinNTConverter)},
{PropertyNames.AcctInfoPermittedLogonTimes, typeof(UserPrincipal), "LoginHours", new FromWinNTConverterDelegate(BinaryFromWinNTConverter), new ToWinNTConverterDelegate(LogonHoursToWinNTConverter)},
{PropertyNames.AcctInfoExpirationDate, typeof(UserPrincipal), "AccountExpirationDate", new FromWinNTConverterDelegate(DateFromWinNTConverter), new ToWinNTConverterDelegate(AcctExpirDateToNTConverter)},
{PropertyNames.AcctInfoSmartcardRequired, typeof(UserPrincipal), "UserFlags", new FromWinNTConverterDelegate(UserFlagsFromWinNTConverter), new ToWinNTConverterDelegate(UserFlagsToWinNTConverter)},
{PropertyNames.AcctInfoDelegationPermitted, typeof(UserPrincipal), "UserFlags", new FromWinNTConverterDelegate(UserFlagsFromWinNTConverter), new ToWinNTConverterDelegate(UserFlagsToWinNTConverter)},
{PropertyNames.AcctInfoBadLogonCount, typeof(UserPrincipal), "BadPasswordAttempts", new FromWinNTConverterDelegate(IntFromWinNTConverter), null},
{PropertyNames.AcctInfoHomeDirectory, typeof(UserPrincipal), "HomeDirectory", new FromWinNTConverterDelegate(StringFromWinNTConverter), new ToWinNTConverterDelegate(StringToWinNTConverter)},
{PropertyNames.AcctInfoHomeDrive, typeof(UserPrincipal), "HomeDirDrive", new FromWinNTConverterDelegate(StringFromWinNTConverter), new ToWinNTConverterDelegate(StringToWinNTConverter)},
{PropertyNames.AcctInfoScriptPath, typeof(UserPrincipal), "LoginScript", new FromWinNTConverterDelegate(StringFromWinNTConverter), new ToWinNTConverterDelegate(StringToWinNTConverter)},
//
{PropertyNames.PwdInfoLastPasswordSet, typeof(UserPrincipal), "PasswordAge", new FromWinNTConverterDelegate(ElapsedTimeFromWinNTConverter), null},
{PropertyNames.PwdInfoLastBadPasswordAttempt, typeof(UserPrincipal), "*******", new FromWinNTConverterDelegate(LastBadPwdAttemptFromWinNTConverter), null},
{PropertyNames.PwdInfoPasswordNotRequired, typeof(UserPrincipal), "UserFlags", new FromWinNTConverterDelegate(UserFlagsFromWinNTConverter), new ToWinNTConverterDelegate(UserFlagsToWinNTConverter)},
{PropertyNames.PwdInfoPasswordNeverExpires, typeof(UserPrincipal), "UserFlags", new FromWinNTConverterDelegate(UserFlagsFromWinNTConverter), new ToWinNTConverterDelegate(UserFlagsToWinNTConverter)},
{PropertyNames.PwdInfoCannotChangePassword, typeof(UserPrincipal), "UserFlags", new FromWinNTConverterDelegate(UserFlagsFromWinNTConverter), new ToWinNTConverterDelegate(UserFlagsToWinNTConverter)},
{PropertyNames.PwdInfoAllowReversiblePasswordEncryption, typeof(UserPrincipal), "UserFlags", new FromWinNTConverterDelegate(UserFlagsFromWinNTConverter), new ToWinNTConverterDelegate(UserFlagsToWinNTConverter)},
//
// Writable properties we don't support writing in SAM
//
{PropertyNames.UserGivenName, typeof(UserPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.UserMiddleName, typeof(UserPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.UserSurname, typeof(UserPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.UserVoiceTelephoneNumber, typeof(UserPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.UserEmployeeID, typeof(UserPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.PrincipalDisplayName, typeof(GroupPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.PrincipalDisplayName, typeof(ComputerPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.PrincipalDescription, typeof(ComputerPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.AuthenticablePrincipalEnabled, typeof(ComputerPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.AuthenticablePrincipalCertificates, typeof(ComputerPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.ComputerServicePrincipalNames, typeof(ComputerPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.AcctInfoPermittedWorkstations, typeof(ComputerPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.AcctInfoPermittedLogonTimes, typeof(ComputerPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.AcctInfoExpirationDate, typeof(ComputerPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.AcctInfoSmartcardRequired, typeof(ComputerPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.AcctInfoDelegationPermitted, typeof(ComputerPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.AcctInfoHomeDirectory, typeof(ComputerPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.AcctInfoHomeDrive, typeof(ComputerPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.AcctInfoScriptPath, typeof(ComputerPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.PwdInfoPasswordNotRequired, typeof(ComputerPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.PwdInfoPasswordNeverExpires, typeof(ComputerPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.PwdInfoCannotChangePassword, typeof(ComputerPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.PwdInfoAllowReversiblePasswordEncryption, typeof(ComputerPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)}
};
private static Hashtable s_userPropertyMappingTableByProperty = null;
private static Hashtable s_userPropertyMappingTableByWinNT = null;
private static Hashtable s_groupPropertyMappingTableByProperty = null;
private static Hashtable s_groupPropertyMappingTableByWinNT = null;
private static Hashtable s_computerPropertyMappingTableByProperty = null;
private static Hashtable s_computerPropertyMappingTableByWinNT = null;
private static Dictionary<string, ObjectMask> s_validPropertyMap = null;
private static Dictionary<Type, ObjectMask> s_maskMap = null;
[Flags]
private enum ObjectMask
{
None = 0,
User = 0x1,
Computer = 0x2,
Group = 0x4,
Principal = User | Computer | Group
}
private class PropertyMappingTableEntry
{
internal string propertyName; // PAPI name
internal string suggestedWinNTPropertyName; // WinNT attribute name
internal FromWinNTConverterDelegate winNTToPapiConverter;
internal ToWinNTConverterDelegate papiToWinNTConverter;
}
//
// Conversion routines
//
// Loads the specified attribute of the DirectoryEntry into the specified property of the Principal
private delegate void FromWinNTConverterDelegate(DirectoryEntry de, string suggestedWinNTProperty, Principal p, string propertyName);
// Loads the specified property of the Principal into the specified attribute of the DirectoryEntry.
// For multivalued attributes, must test to make sure the value hasn't already been loaded into the DirectoryEntry
// (to maintain idempotency when PushChangesToNative is called multiple times).
private delegate void ToWinNTConverterDelegate(Principal p, string propertyName, DirectoryEntry de, string suggestedWinNTProperty, bool isLSAM);
//
// WinNT --> PAPI
//
private static void StringFromWinNTConverter(DirectoryEntry de, string suggestedWinNTProperty, Principal p, string propertyName)
{
PropertyValueCollection values = de.Properties[suggestedWinNTProperty];
// The WinNT provider represents some string attributes that haven't been set as an empty string.
// Map them to null (not set), to maintain consistency with the LDAP context.
if ((values.Count > 0) && (((string)values[0]).Length == 0))
return;
SDSUtils.SingleScalarFromDirectoryEntry<string>(new dSPropertyCollection(de.Properties), suggestedWinNTProperty, p, propertyName);
}
private static void SidFromWinNTConverter(DirectoryEntry de, string suggestedWinNTProperty, Principal p, string propertyName)
{
byte[] sid = (byte[])de.Properties["objectSid"][0];
string stringizedSid = Utils.ByteArrayToString(sid);
string sddlSid = Utils.ConvertSidToSDDL(sid);
SecurityIdentifier SidObj = new SecurityIdentifier(sddlSid);
p.LoadValueIntoProperty(propertyName, (object)SidObj);
}
private static void SamAccountNameFromWinNTConverter(DirectoryEntry de, string suggestedWinNTProperty, Principal p, string propertyName)
{
Debug.Assert(de.Properties["Name"].Count == 1);
string samAccountName = (string)de.Properties["Name"][0];
// string urnValue = p.Context.ConnectedServer + @"\" + samAccountName;
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "SamAccountNameFromWinNTConverter: loading SAM{0}", samAccountName);
p.LoadValueIntoProperty(propertyName, (object)samAccountName);
}
private static void MultiStringFromWinNTConverter(DirectoryEntry de, string suggestedWinNTProperty, Principal p, string propertyName)
{
// ValueCollection<string> is Load'ed from a List<string>
SDSUtils.MultiScalarFromDirectoryEntry<string>(new dSPropertyCollection(de.Properties), suggestedWinNTProperty, p, propertyName);
}
private static void IntFromWinNTConverter(DirectoryEntry de, string suggestedWinNTProperty, Principal p, string propertyName)
{
SDSUtils.SingleScalarFromDirectoryEntry<int>(new dSPropertyCollection(de.Properties), suggestedWinNTProperty, p, propertyName);
}
private static void BinaryFromWinNTConverter(DirectoryEntry de, string suggestedWinNTProperty, Principal p, string propertyName)
{
SDSUtils.SingleScalarFromDirectoryEntry<byte[]>(new dSPropertyCollection(de.Properties), suggestedWinNTProperty, p, propertyName);
}
private static void CertFromWinNTConverter(DirectoryEntry de, string suggestedWinNTProperty, Principal p, string propertyName)
{
}
private static void GroupTypeFromWinNTConverter(DirectoryEntry de, string suggestedWinNTProperty, Principal p, string propertyName)
{
// Groups are always enabled in SAM. There is no such thing as a distribution group.
p.LoadValueIntoProperty(PropertyNames.GroupIsSecurityGroup, (object)true);
if (propertyName == PropertyNames.GroupIsSecurityGroup)
{
// Do nothing for this property.
}
else
{
Debug.Assert(propertyName == PropertyNames.GroupGroupScope);
// All local machine SAM groups are local
#if DEBUG
PropertyValueCollection values = de.Properties[suggestedWinNTProperty];
if (values.Count != 0)
Debug.Assert(((int)values[0]) == 4);
#endif
p.LoadValueIntoProperty(propertyName, GroupScope.Local);
}
}
private static void EmailFromWinNTConverter(DirectoryEntry de, string suggestedWinNTProperty, Principal p, string propertyName)
{
}
private static void LastBadPwdAttemptFromWinNTConverter(DirectoryEntry de, string suggestedWinNTProperty, Principal p, string propertyName)
{
}
private static void ElapsedTimeFromWinNTConverter(DirectoryEntry de, string suggestedWinNTProperty, Principal p, string propertyName)
{
// These properties are expressed as "seconds passed since the event of interest". So to convert
// to a DateTime, we substract them from DateTime.UtcNow.
PropertyValueCollection values = de.Properties[suggestedWinNTProperty];
if (values.Count != 0)
{
// We're intended to handle single-valued scalar properties
Debug.Assert(values.Count == 1);
Debug.Assert(values[0] is Int32);
int secondsLapsed = (int)values[0];
Nullable<DateTime> dt = DateTime.UtcNow - new TimeSpan(0, 0, secondsLapsed);
p.LoadValueIntoProperty(propertyName, dt);
}
}
private static void DateFromWinNTConverter(DirectoryEntry de, string suggestedWinNTProperty, Principal p, string propertyName)
{
PropertyValueCollection values = de.Properties[suggestedWinNTProperty];
if (values.Count != 0)
{
Debug.Assert(values.Count == 1);
// Unlike with the ADSI LDAP provider, these come back as a DateTime (expressed in UTC), instead
// of a IADsLargeInteger.
Nullable<DateTime> dt = (Nullable<DateTime>)values[0];
p.LoadValueIntoProperty(propertyName, dt);
}
}
private static void UserFlagsFromWinNTConverter(DirectoryEntry de, string suggestedWinNTProperty, Principal p, string propertyName)
{
Debug.Assert(String.Compare(suggestedWinNTProperty, "UserFlags", StringComparison.OrdinalIgnoreCase) == 0);
SDSUtils.AccountControlFromDirectoryEntry(new dSPropertyCollection(de.Properties), suggestedWinNTProperty, p, propertyName, true);
}
//
// PAPI --> WinNT
//
private static void ExceptionToWinNTConverter(Principal p, string propertyName, DirectoryEntry de, string suggestedWinNTProperty, bool isLSAM)
{
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
StringResources.PrincipalUnsupportPropertyForType,
p.GetType().ToString(),
PropertyNamesExternal.GetExternalForm(propertyName)));
}
private static void StringToWinNTConverter(Principal p, string propertyName, DirectoryEntry de, string suggestedWinNTProperty, bool isLSAM)
{
string value = (string)p.GetValueForProperty(propertyName);
if (p.unpersisted && value == null)
return;
if (value != null && value.Length > 0)
de.Properties[suggestedWinNTProperty].Value = value;
else
de.Properties[suggestedWinNTProperty].Value = "";
}
private static void MultiStringToWinNTConverter(Principal p, string propertyName, DirectoryEntry de, string suggestedWinNTProperty, bool isLSAM)
{
SDSUtils.MultiStringToDirectoryEntryConverter(p, propertyName, de, suggestedWinNTProperty);
}
private static void LogonHoursToWinNTConverter(Principal p, string propertyName, DirectoryEntry de, string suggestedWinNTProperty, bool isLSAM)
{
Debug.Assert(propertyName == PropertyNames.AcctInfoPermittedLogonTimes);
byte[] value = (byte[])p.GetValueForProperty(propertyName);
if (p.unpersisted && value == null)
return;
if (value != null && value.Length != 0)
{
de.Properties[suggestedWinNTProperty].Value = value;
}
else
{
byte[] allHours = new byte[]{0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff};
de.Properties[suggestedWinNTProperty].Value = allHours;
}
}
private static void CertToWinNT(Principal p, string propertyName, DirectoryEntry de, string suggestedWinNTProperty, bool isLSAM)
{
if (!isLSAM)
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
StringResources.PrincipalUnsupportPropertyForPlatform,
PropertyNamesExternal.GetExternalForm(propertyName)));
}
private static void GroupTypeToWinNTConverter(Principal p, string propertyName, DirectoryEntry de, string suggestedWinNTProperty, bool isLSAM)
{
if (propertyName == PropertyNames.GroupIsSecurityGroup)
{
if (!isLSAM)
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
StringResources.PrincipalUnsupportPropertyForPlatform,
PropertyNamesExternal.GetExternalForm(propertyName)));
}
else
{
Debug.Assert(propertyName == PropertyNames.GroupGroupScope);
// local machine SAM only supports local groups
GroupScope value = (GroupScope)p.GetValueForProperty(propertyName);
if (value != GroupScope.Local)
throw new InvalidOperationException(StringResources.SAMStoreCtxLocalGroupsOnly);
}
}
private static void EmailToWinNTConverter(Principal p, string propertyName, DirectoryEntry de, string suggestedWinNTProperty, bool isLSAM)
{
if (!isLSAM)
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
StringResources.PrincipalUnsupportPropertyForPlatform,
PropertyNamesExternal.GetExternalForm(propertyName)));
}
private static void AcctExpirDateToNTConverter(Principal p, string propertyName, DirectoryEntry de, string suggestedWinNTProperty, bool isLSAM)
{
Nullable<DateTime> value = (Nullable<DateTime>)p.GetValueForProperty(propertyName);
if (p.unpersisted && value == null)
return;
// ADSI's WinNT provider uses 1/1/1970 to represent "never expires" when setting the property
if (value.HasValue)
de.Properties[suggestedWinNTProperty].Value = (DateTime)value;
else
de.Properties[suggestedWinNTProperty].Value = new DateTime(1970, 1, 1);
}
private static void UserFlagsToWinNTConverter(Principal p, string propertyName, DirectoryEntry de, string suggestedWinNTProperty, bool isLSAM)
{
Debug.Assert(String.Compare(suggestedWinNTProperty, "UserFlags", StringComparison.OrdinalIgnoreCase) == 0);
SDSUtils.AccountControlToDirectoryEntry(p, propertyName, de, suggestedWinNTProperty, true, p.unpersisted);
}
private static void UpdateGroupMembership(Principal group, DirectoryEntry de, NetCred credentials, AuthenticationTypes authTypes)
{
Debug.Assert(group.fakePrincipal == false);
PrincipalCollection members = (PrincipalCollection)group.GetValueForProperty(PropertyNames.GroupMembers);
UnsafeNativeMethods.IADsGroup iADsGroup = (UnsafeNativeMethods.IADsGroup)de.NativeObject;
try
{
//
// Process clear
//
if (members.Cleared)
{
// Unfortunately, there's no quick way to clear a group's membership in SAM.
// So we remove each member in turn, by enumerating over the group membership
// and calling remove on each.
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "UpdateGroupMembership: clearing {0}", de.Path);
// Prepare the COM Interopt enumeration
UnsafeNativeMethods.IADsMembers iADsMembers = iADsGroup.Members();
IEnumVARIANT enumerator = (IEnumVARIANT)iADsMembers._NewEnum;
object[] nativeMembers = new object[1];
int hr;
do
{
hr = enumerator.Next(1, nativeMembers, IntPtr.Zero);
if (hr == 0) // S_OK
{
// Found a member, remove it.
UnsafeNativeMethods.IADs iADs = (UnsafeNativeMethods.IADs)nativeMembers[0];
iADsGroup.Remove(iADs.ADsPath);
}
}
while (hr == 0);
// Either hr == S_FALSE (1), which means we completed the enumerator,
// or we encountered an error
if (hr != 1)
{
// Error occurred.
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "UpdateGroupMembership: error while clearing, hr={0}", hr);
throw new PrincipalOperationException(
String.Format(
CultureInfo.CurrentCulture,
StringResources.SAMStoreCtxFailedToClearGroup,
hr.ToString(CultureInfo.InvariantCulture)));
}
}
//
// Process inserted members
//
List<Principal> insertedMembers = members.Inserted;
// First, validate the members to be added
foreach (Principal member in insertedMembers)
{
Type memberType = member.GetType();
if ((memberType != typeof(UserPrincipal)) && (!memberType.IsSubclassOf(typeof(UserPrincipal))) &&
(memberType != typeof(ComputerPrincipal)) && (!memberType.IsSubclassOf(typeof(ComputerPrincipal))) &&
(memberType != typeof(GroupPrincipal)) && (!memberType.IsSubclassOf(typeof(GroupPrincipal))))
{
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture, StringResources.StoreCtxUnsupportedPrincipalTypeForGroupInsert, memberType.ToString()));
}
// Can't inserted unpersisted principal
if (member.unpersisted)
throw new InvalidOperationException(StringResources.StoreCtxGroupHasUnpersistedInsertedPrincipal);
Debug.Assert(member.Context != null);
// There's no restriction on the type of principal to be inserted (AD/reg-SAM/MSAM), but it needs
// to have a SID IdentityClaim. We'll check that as we go.
}
// Now add each member to the group
foreach (Principal member in insertedMembers)
{
// We'll add the member via its SID. This works for both MSAM members and AD members.
// Build a SID ADsPath
string memberSidPath = GetSidADsPathFromPrincipal(member);
if (memberSidPath == null)
throw new InvalidOperationException(StringResources.SAMStoreCtxCouldntGetSIDForGroupMember);
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "UpdateGroupMembership: inserting {0}", memberSidPath);
// Add the member to the group
iADsGroup.Add(memberSidPath);
}
//
// Process removed members
//
List<Principal> removedMembers = members.Removed;
foreach (Principal member in removedMembers)
{
// Since we don't allow any of these to be inserted, none of them should ever
// show up in the removal list
Debug.Assert(member.unpersisted == false);
// If the collection was cleared, there should be no original members to remove
Debug.Assert(members.Cleared == false);
// Like insertion, we'll remove by SID.
// Build a SID ADsPath
string memberSidPath = GetSidADsPathFromPrincipal(member);
if (memberSidPath == null)
throw new InvalidOperationException(StringResources.SAMStoreCtxCouldntGetSIDForGroupMember);
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "UpdateGroupMembership: removing {0}", memberSidPath);
// Remove the member from the group
iADsGroup.Remove(memberSidPath);
}
}
catch (System.Runtime.InteropServices.COMException e)
{
GlobalDebug.WriteLineIf(GlobalDebug.Error,
"SAMStoreCtx",
"UpdateGroupMembership: caught COMException, message={0}, code={1}",
e.Message,
e.ErrorCode);
// ADSI threw an exception trying to update the group membership
throw ExceptionHelper.GetExceptionFromCOMException(e);
}
}
private static string GetSidADsPathFromPrincipal(Principal p)
{
Debug.Assert(p.unpersisted == false);
// Get the member's SID from its Security IdentityClaim
SecurityIdentifier Sid = p.Sid;
if (Sid == null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "GetSidADsPathFromPrincipal: no SID");
return null;
}
string sddlSid = Sid.ToString();
if (sddlSid == null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn,
"SAMStoreCtx",
"GetSidADsPathFromPrincipal: Couldn't convert to SDDL ({0})",
Sid.ToString());
return null;
}
// Build a SID ADsPath
return @"WinNT://" + sddlSid;
}
}
}
// #endif // PAPI_REGSAM
| |
using System;
using System.Linq;
using System.Collections.Generic;
#if __UNIFIED__
using UIKit;
using Foundation;
using CoreGraphics;
#else
using MonoTouch.UIKit;
using MonoTouch.Foundation;
using MonoTouch.CoreGraphics;
using System.Drawing;
using CGRect = global::System.Drawing.RectangleF;
using CGPoint = global::System.Drawing.PointF;
using CGSize = global::System.Drawing.SizeF;
using nfloat = global::System.Single;
using nint = global::System.Int32;
using nuint = global::System.UInt32;
#endif
namespace PatridgeDev {
public class RatingConfig {
public UIImage EmptyImage { get; set; }
/// <summary>
/// Image shown for the current average rating, when a rating is provided.
/// </summary>
public UIImage FilledImage { get; set; }
/// <summary>
/// Image shown when a user has chosen a rating.
/// </summary>
public UIImage ChosenImage { get; set; }
/// <summary>
/// Padding between the rendering of the items. The default is none (0f).
/// </summary>
public float ItemPadding { get; set; }
/// <summary>
/// Number of rating items in the scale (5 stars, 10 cows, whatever). The default is five.
/// </summary>
public int ScaleSize { get; set; }
public RatingConfig(UIImage emptyImage, UIImage filledImage, UIImage chosenImage) {
EmptyImage = emptyImage;
FilledImage = filledImage;
ChosenImage = chosenImage;
ScaleSize = 5;
ItemPadding = 0f;
}
}
class RatingItemView : UIButton {
UIImageView EmptyImageView;
UIView FilledImageViewObscuringWrapper;
UIView FilledImageViewSizingHolder;
UIImageView FilledImageView;
UIImageView SelectedImageView;
private float _PercentFilled = 0f;
public float PercentFilled {
get {
return _PercentFilled;
}
set {
_PercentFilled = value;
SetNeedsLayout();
}
}
private bool _Chosen = false;
public bool Chosen {
get {
return _Chosen;
}
set {
_Chosen = value;
SetNeedsLayout();
}
}
public RatingItemView(UIImage emptyImage, UIImage filledImage, UIImage chosenImage) {
AutoresizingMask = UIViewAutoresizing.FlexibleDimensions;
EmptyImageView = new UIImageView(emptyImage) {
AutoresizingMask = UIViewAutoresizing.FlexibleDimensions,
};
Add(EmptyImageView);
FilledImageView = new UIImageView(filledImage) {
AutoresizingMask = UIViewAutoresizing.FlexibleDimensions,
};
FilledImageViewSizingHolder = new UIView();
FilledImageViewSizingHolder.Add(FilledImageView);
FilledImageViewObscuringWrapper = new UIView() {
ClipsToBounds = true,
UserInteractionEnabled = false,
};
FilledImageViewObscuringWrapper.Add(FilledImageViewSizingHolder);
Add(FilledImageViewObscuringWrapper);
SelectedImageView = new UIImageView(chosenImage) {
AutoresizingMask = UIViewAutoresizing.FlexibleDimensions,
};
Add(SelectedImageView);
PercentFilled = 0;
}
public override void LayoutSubviews() {
base.LayoutSubviews();
// Layout everything to their appropriate sizes.
SelectedImageView.Frame = new CGRect(CGPoint.Empty, Bounds.Size);
EmptyImageView.Frame = new CGRect(CGPoint.Empty, Bounds.Size);
FilledImageViewObscuringWrapper.Frame = new CGRect(CGPoint.Empty, Bounds.Size);
FilledImageViewSizingHolder.Frame = new CGRect(CGPoint.Empty, FilledImageViewObscuringWrapper.Bounds.Size);
FilledImageView.Frame = new CGRect(CGPoint.Empty, FilledImageViewSizingHolder.Bounds.Size);
// Hide/Show things accordingly.
if (Chosen) {
// If selected, only show that view completely and hide the rest.
SelectedImageView.SetAspectFitAsNeeded(UIViewContentMode.Center);
EmptyImageView.Hidden = true;
FilledImageViewObscuringWrapper.Hidden = true;
SelectedImageView.Hidden = false;
}
else {
// If not selected, hide selected, show empty and portion of filled.
EmptyImageView.SetAspectFitAsNeeded(UIViewContentMode.Center);
if (PercentFilled > 0f) {
FilledImageView.SetAspectFitAsNeeded(UIViewContentMode.Center);
if (PercentFilled < 1f) {
// Obscure a portion of the filled image based on the percent.
nfloat revealWidth;
if (FilledImageView.Image.Size.Width < FilledImageView.Bounds.Width) {
revealWidth = ((FilledImageView.Bounds.Width - FilledImageView.Image.Size.Width) / 2f) + (FilledImageView.Image.Size.Width * PercentFilled);
}
else {
revealWidth = FilledImageView.Bounds.Width * PercentFilled;
}
FilledImageViewObscuringWrapper.Frame = new CGRect(FilledImageViewSizingHolder.Frame.Location, new CGSize(revealWidth, FilledImageViewSizingHolder.Frame.Height));
}
FilledImageViewObscuringWrapper.Hidden = false;
}
else {
FilledImageViewObscuringWrapper.Hidden = true;
}
SelectedImageView.Hidden = true;
EmptyImageView.Hidden = false;
}
}
}
public class RatingChosenEventArgs : EventArgs {
public int Rating { get; set; }
public RatingChosenEventArgs(int rating) {
Rating = rating;
}
}
public class PDRatingView : UIView {
public event EventHandler<RatingChosenEventArgs> RatingChosen = delegate { };
readonly RatingConfig StarRatingConfig;
private decimal _AverageRating = 0m;
public decimal AverageRating {
get {
return _AverageRating;
}
set {
_AverageRating = value;
SetNeedsLayout();
}
}
private int? _ChosenRating = null;
public int? ChosenRating {
get {
return _ChosenRating;
}
set {
_ChosenRating = value;
SetNeedsLayout();
}
}
List<RatingItemView> StarViews;
public PDRatingView(CGRect frame, RatingConfig config) : this(frame, config, 0m) {
}
public PDRatingView(CGRect frame, RatingConfig config, decimal averageRating) : this(config, averageRating) {
Frame = frame;
}
public PDRatingView(RatingConfig config, decimal averageRating) : this(config) {
AverageRating = averageRating;
}
public PDRatingView(RatingConfig config) {
StarRatingConfig = config;
StarViews = new List<RatingItemView>();
ButtonsAndHandlers = new Dictionary<UIButton, EventHandler>();
Enumerable.Range(0, StarRatingConfig.ScaleSize).ToList().ForEach(i => {
int starRating = i + 1;
RatingItemView starView = new RatingItemView(emptyImage: StarRatingConfig.EmptyImage,
filledImage: StarRatingConfig.FilledImage,
chosenImage: StarRatingConfig.ChosenImage);
StarViews.Add(starView);
EventHandler handler = (s, e) => {
ChosenRating = starRating;
RatingChosen(this, new RatingChosenEventArgs(ChosenRating.Value));
};
ButtonsAndHandlers.Add(starView, handler);
Add(starView);
});
AssignHandlers();
}
public override void LayoutSubviews() {
nfloat starAreaWidth = Bounds.Width / StarRatingConfig.ScaleSize;
nfloat starAreaHeight = Bounds.Height - (2 * StarRatingConfig.ItemPadding);
nfloat starImageMaxWidth = starAreaWidth - (2 * StarRatingConfig.ItemPadding);
nfloat starImageMaxHeight = starAreaHeight - (2 * StarRatingConfig.ItemPadding);
CGSize starAreaScaled = StarRatingConfig.EmptyImage.Size.ScaleProportional(starImageMaxWidth, starImageMaxHeight);
nfloat top = (Bounds.Height / 2f) - (starAreaScaled.Height / 2f);
int i = 0;
StarViews.ForEach(v => {
nfloat x = (i * starAreaWidth) + StarRatingConfig.ItemPadding;
v.Frame = new CGRect(new CGPoint(x, top), starAreaScaled);
// Choose between showing a chosen rating and the average rating.
if (ChosenRating != null) {
v.Chosen = ChosenRating.Value > i;
v.PercentFilled = 0f;
}
else {
v.Chosen = false;
float percentFilled = (AverageRating - 1) > i ? 1.0f : (float)(AverageRating - i);
v.PercentFilled = percentFilled;
}
i += 1;
});
base.LayoutSubviews();
}
Dictionary<UIButton, EventHandler> ButtonsAndHandlers { get; set; }
protected void AssignHandlers() {
ButtonsAndHandlers.ToList().ForEach(kvp => {
UIButton button = kvp.Key;
EventHandler handler = kvp.Value;
button.TouchUpInside += handler;
});
}
protected void RemoveHandlers() {
ButtonsAndHandlers.ToList().ForEach(kvp => {
UIButton button = kvp.Key;
if (button != null) {
EventHandler handler = kvp.Value;
button.TouchUpInside -= handler;
}
});
}
protected override void Dispose(bool disposing) {
if (disposing) {
RemoveHandlers();
}
base.Dispose(disposing);
}
}
}
| |
/*
* 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.IO;
using System.Reflection;
using System.Net;
using System.Text;
using OpenSim.Server.Base;
using OpenSim.Server.Handlers.Base;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Server.Handlers.Simulation;
using Utils = OpenSim.Server.Handlers.Simulation.Utils;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using Nini.Config;
using log4net;
namespace OpenSim.Server.Handlers.Hypergrid
{
public class HomeAgentHandler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IUserAgentService m_UserAgentService;
private string m_LoginServerIP;
private bool m_Proxy = false;
public HomeAgentHandler(IUserAgentService userAgentService, string loginServerIP, bool proxy)
{
m_UserAgentService = userAgentService;
m_LoginServerIP = loginServerIP;
m_Proxy = proxy;
}
public Hashtable Handler(Hashtable request)
{
// m_log.Debug("[CONNECTION DEBUGGING]: HomeAgentHandler Called");
//
// m_log.Debug("---------------------------");
// m_log.Debug(" >> uri=" + request["uri"]);
// m_log.Debug(" >> content-type=" + request["content-type"]);
// m_log.Debug(" >> http-method=" + request["http-method"]);
// m_log.Debug("---------------------------\n");
Hashtable responsedata = new Hashtable();
responsedata["content_type"] = "text/html";
responsedata["keepalive"] = false;
UUID agentID;
UUID regionID;
string action;
if (!Utils.GetParams((string)request["uri"], out agentID, out regionID, out action))
{
m_log.InfoFormat("[HOME AGENT HANDLER]: Invalid parameters for agent message {0}", request["uri"]);
responsedata["int_response_code"] = 404;
responsedata["str_response_string"] = "false";
return responsedata;
}
// Next, let's parse the verb
string method = (string)request["http-method"];
if (method.Equals("POST"))
{
DoAgentPost(request, responsedata, agentID);
return responsedata;
}
else
{
m_log.InfoFormat("[HOME AGENT HANDLER]: method {0} not supported in agent message", method);
responsedata["int_response_code"] = HttpStatusCode.MethodNotAllowed;
responsedata["str_response_string"] = "Method not allowed";
return responsedata;
}
}
protected void DoAgentPost(Hashtable request, Hashtable responsedata, UUID id)
{
OSDMap args = Utils.GetOSDMap((string)request["body"]);
if (args == null)
{
responsedata["int_response_code"] = HttpStatusCode.BadRequest;
responsedata["str_response_string"] = "Bad request";
return;
}
// retrieve the input arguments
int x = 0, y = 0;
UUID uuid = UUID.Zero;
string regionname = string.Empty;
string gatekeeper_host = string.Empty;
string gatekeeper_serveruri = string.Empty;
string destination_serveruri = string.Empty;
int gatekeeper_port = 0;
IPEndPoint client_ipaddress = null;
if (args.ContainsKey("gatekeeper_host") && args["gatekeeper_host"] != null)
gatekeeper_host = args["gatekeeper_host"].AsString();
if (args.ContainsKey("gatekeeper_port") && args["gatekeeper_port"] != null)
Int32.TryParse(args["gatekeeper_port"].AsString(), out gatekeeper_port);
if (args.ContainsKey("gatekeeper_serveruri") && args["gatekeeper_serveruri"] !=null)
gatekeeper_serveruri = args["gatekeeper_serveruri"];
if (args.ContainsKey("destination_serveruri") && args["destination_serveruri"] !=null)
destination_serveruri = args["destination_serveruri"];
GridRegion gatekeeper = new GridRegion();
gatekeeper.ServerURI = gatekeeper_serveruri;
gatekeeper.ExternalHostName = gatekeeper_host;
gatekeeper.HttpPort = (uint)gatekeeper_port;
gatekeeper.InternalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), 0);
if (args.ContainsKey("destination_x") && args["destination_x"] != null)
Int32.TryParse(args["destination_x"].AsString(), out x);
else
m_log.WarnFormat(" -- request didn't have destination_x");
if (args.ContainsKey("destination_y") && args["destination_y"] != null)
Int32.TryParse(args["destination_y"].AsString(), out y);
else
m_log.WarnFormat(" -- request didn't have destination_y");
if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null)
UUID.TryParse(args["destination_uuid"].AsString(), out uuid);
if (args.ContainsKey("destination_name") && args["destination_name"] != null)
regionname = args["destination_name"].ToString();
if (args.ContainsKey("client_ip") && args["client_ip"] != null)
{
string ip_str = args["client_ip"].ToString();
try
{
string callerIP = GetCallerIP(request);
// Verify if this caller has authority to send the client IP
if (callerIP == m_LoginServerIP)
client_ipaddress = new IPEndPoint(IPAddress.Parse(ip_str), 0);
else // leaving this for now, but this warning should be removed
m_log.WarnFormat("[HOME AGENT HANDLER]: Unauthorized machine {0} tried to set client ip to {1}", callerIP, ip_str);
}
catch
{
m_log.DebugFormat("[HOME AGENT HANDLER]: Exception parsing client ip address from {0}", ip_str);
}
}
GridRegion destination = new GridRegion();
destination.RegionID = uuid;
destination.RegionLocX = x;
destination.RegionLocY = y;
destination.RegionName = regionname;
destination.ServerURI = destination_serveruri;
AgentCircuitData aCircuit = new AgentCircuitData();
try
{
aCircuit.UnpackAgentCircuitData(args);
}
catch (Exception ex)
{
m_log.InfoFormat("[HOME AGENT HANDLER]: exception on unpacking ChildCreate message {0}", ex.Message);
responsedata["int_response_code"] = HttpStatusCode.BadRequest;
responsedata["str_response_string"] = "Bad request";
return;
}
OSDMap resp = new OSDMap(2);
string reason = String.Empty;
bool result = m_UserAgentService.LoginAgentToGrid(aCircuit, gatekeeper, destination, client_ipaddress, out reason);
resp["reason"] = OSD.FromString(reason);
resp["success"] = OSD.FromBoolean(result);
// TODO: add reason if not String.Empty?
responsedata["int_response_code"] = HttpStatusCode.OK;
responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp);
}
private string GetCallerIP(Hashtable request)
{
if (!m_Proxy)
return Util.GetCallerIP(request);
// We're behind a proxy
Hashtable headers = (Hashtable)request["headers"];
string xff = "X-Forwarded-For";
if (headers.ContainsKey(xff.ToLower()))
xff = xff.ToLower();
if (!headers.ContainsKey(xff) || headers[xff] == null)
{
m_log.WarnFormat("[AGENT HANDLER]: No XFF header");
return Util.GetCallerIP(request);
}
m_log.DebugFormat("[AGENT HANDLER]: XFF is {0}", headers[xff]);
IPEndPoint ep = Util.GetClientIPFromXFF((string)headers[xff]);
if (ep != null)
return ep.Address.ToString();
// Oops
return Util.GetCallerIP(request);
}
}
}
| |
using System;
using System.IO;
using System.Text;
using System.Globalization;
using System.Windows.Forms;
using SpyUO.Packets;
namespace SpyUO
{
public class LootFilterForm : System.Windows.Forms.Form
{
#region Windows Form Designer generated code
private CheckedListBox ItemFilter;
private Button ButtonOk;
private Button ButtonCancel;
private Button ButtonLoad;
private Button ButtonSave;
private SaveFileDialog FilterSave;
private OpenFileDialog FilterLoad;
private CheckBox ToggleArmor;
private CheckBox ToggleAos;
private CheckBox ToggleWeapon;
private CheckedListBox MobileFilter;
private Label LabelItemFilter;
private Label LabelMobileFilter;
private CheckBox ToggleAllMobiles;
private TextBox SavePath;
private Button ButtonSelectFile;
private CheckBox ToggleWearable;
private CheckBox ToggleOther;
private SaveFileDialog LootSave;
private TextBox PropertyFilter;
private RadioButton RadioInclude;
private RadioButton RadioExclude;
private System.ComponentModel.Container components = null;
protected override void Dispose( bool disposing )
{
if ( disposing )
{
if ( components != null )
{
components.Dispose();
}
}
base.Dispose( disposing );
}
/// <summary>
/// Metodo necessario per il supporto della finestra di progettazione. Non modificare
/// il contenuto del metodo con l'editor di codice.
/// </summary>
private void InitializeComponent()
{
this.ItemFilter = new System.Windows.Forms.CheckedListBox();
this.ButtonOk = new System.Windows.Forms.Button();
this.ButtonCancel = new System.Windows.Forms.Button();
this.ButtonLoad = new System.Windows.Forms.Button();
this.ButtonSave = new System.Windows.Forms.Button();
this.FilterSave = new System.Windows.Forms.SaveFileDialog();
this.FilterLoad = new System.Windows.Forms.OpenFileDialog();
this.ToggleArmor = new System.Windows.Forms.CheckBox();
this.ToggleAos = new System.Windows.Forms.CheckBox();
this.ToggleWeapon = new System.Windows.Forms.CheckBox();
this.MobileFilter = new System.Windows.Forms.CheckedListBox();
this.LabelItemFilter = new System.Windows.Forms.Label();
this.LabelMobileFilter = new System.Windows.Forms.Label();
this.ToggleAllMobiles = new System.Windows.Forms.CheckBox();
this.SavePath = new System.Windows.Forms.TextBox();
this.ButtonSelectFile = new System.Windows.Forms.Button();
this.ToggleWearable = new System.Windows.Forms.CheckBox();
this.ToggleOther = new System.Windows.Forms.CheckBox();
this.LootSave = new System.Windows.Forms.SaveFileDialog();
this.PropertyFilter = new System.Windows.Forms.TextBox();
this.RadioInclude = new System.Windows.Forms.RadioButton();
this.RadioExclude = new System.Windows.Forms.RadioButton();
this.SuspendLayout();
//
// ItemFilter
//
this.ItemFilter.Location = new System.Drawing.Point( 12, 71 );
this.ItemFilter.Name = "ItemFilter";
this.ItemFilter.Size = new System.Drawing.Size( 176, 259 );
this.ItemFilter.TabIndex = 0;
this.ItemFilter.SelectedIndexChanged += new System.EventHandler( this.ItemFilter_SelectedIndexChanged );
this.ItemFilter.ItemCheck += new System.Windows.Forms.ItemCheckEventHandler( this.FilterList_ItemCheck );
//
// ButtonOk
//
this.ButtonOk.DialogResult = System.Windows.Forms.DialogResult.OK;
this.ButtonOk.Location = new System.Drawing.Point( 295, 403 );
this.ButtonOk.Name = "ButtonOk";
this.ButtonOk.Size = new System.Drawing.Size( 75, 23 );
this.ButtonOk.TabIndex = 1;
this.ButtonOk.Text = "Ok";
//
// ButtonCancel
//
this.ButtonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.ButtonCancel.Location = new System.Drawing.Point( 214, 402 );
this.ButtonCancel.Name = "ButtonCancel";
this.ButtonCancel.Size = new System.Drawing.Size( 75, 23 );
this.ButtonCancel.TabIndex = 2;
this.ButtonCancel.Text = "Cancel";
//
// ButtonLoad
//
this.ButtonLoad.Location = new System.Drawing.Point( 113, 6 );
this.ButtonLoad.Name = "ButtonLoad";
this.ButtonLoad.Size = new System.Drawing.Size( 75, 23 );
this.ButtonLoad.TabIndex = 7;
this.ButtonLoad.Text = "Load";
this.ButtonLoad.Click += new System.EventHandler( this.ButtonLoad_Click );
//
// ButtonSave
//
this.ButtonSave.Location = new System.Drawing.Point( 194, 6 );
this.ButtonSave.Name = "ButtonSave";
this.ButtonSave.Size = new System.Drawing.Size( 75, 23 );
this.ButtonSave.TabIndex = 8;
this.ButtonSave.Text = "Save";
this.ButtonSave.Click += new System.EventHandler( this.ButtonSave_Click );
//
// FilterSave
//
this.FilterSave.FileName = "Filter.loot";
this.FilterSave.Filter = "Filter files (*.loot)|*.loot";
//
// FilterLoad
//
this.FilterLoad.FileName = "Filter.loot";
this.FilterLoad.Filter = "Filter files (*.loot)|*.loot";
//
// ToggleArmor
//
this.ToggleArmor.AutoSize = true;
this.ToggleArmor.Checked = true;
this.ToggleArmor.CheckState = System.Windows.Forms.CheckState.Indeterminate;
this.ToggleArmor.Location = new System.Drawing.Point( 12, 41 );
this.ToggleArmor.Name = "ToggleArmor";
this.ToggleArmor.Size = new System.Drawing.Size( 53, 17 );
this.ToggleArmor.TabIndex = 9;
this.ToggleArmor.Text = "Armor";
this.ToggleArmor.UseVisualStyleBackColor = true;
this.ToggleArmor.CheckStateChanged += new System.EventHandler( this.ToggleArmor_CheckStateChanged );
//
// ToggleAos
//
this.ToggleAos.AutoSize = true;
this.ToggleAos.Checked = true;
this.ToggleAos.CheckState = System.Windows.Forms.CheckState.Indeterminate;
this.ToggleAos.Location = new System.Drawing.Point( 71, 41 );
this.ToggleAos.Name = "ToggleAos";
this.ToggleAos.Size = new System.Drawing.Size( 44, 17 );
this.ToggleAos.TabIndex = 10;
this.ToggleAos.Text = "Aos";
this.ToggleAos.UseVisualStyleBackColor = true;
this.ToggleAos.CheckStateChanged += new System.EventHandler( this.ToggleAos_CheckStateChanged );
//
// ToggleWeapon
//
this.ToggleWeapon.AutoSize = true;
this.ToggleWeapon.Checked = true;
this.ToggleWeapon.CheckState = System.Windows.Forms.CheckState.Indeterminate;
this.ToggleWeapon.Location = new System.Drawing.Point( 121, 41 );
this.ToggleWeapon.Name = "ToggleWeapon";
this.ToggleWeapon.Size = new System.Drawing.Size( 67, 17 );
this.ToggleWeapon.TabIndex = 11;
this.ToggleWeapon.Text = "Weapon";
this.ToggleWeapon.UseVisualStyleBackColor = true;
this.ToggleWeapon.CheckStateChanged += new System.EventHandler( this.ToggleWeapon_CheckStateChanged );
//
// MobileFilter
//
this.MobileFilter.Location = new System.Drawing.Point( 194, 71 );
this.MobileFilter.Name = "MobileFilter";
this.MobileFilter.Size = new System.Drawing.Size( 176, 259 );
this.MobileFilter.TabIndex = 0;
this.MobileFilter.ItemCheck += new System.Windows.Forms.ItemCheckEventHandler( this.MobileFilter_ItemCheck );
//
// LabelItemFilter
//
this.LabelItemFilter.AutoSize = true;
this.LabelItemFilter.Font = new System.Drawing.Font( "Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ( (byte) ( 238 ) ) );
this.LabelItemFilter.Location = new System.Drawing.Point( 25, 9 );
this.LabelItemFilter.Name = "LabelItemFilter";
this.LabelItemFilter.Size = new System.Drawing.Size( 76, 16 );
this.LabelItemFilter.TabIndex = 13;
this.LabelItemFilter.Text = "Item Filter";
//
// LabelMobileFilter
//
this.LabelMobileFilter.AutoSize = true;
this.LabelMobileFilter.Font = new System.Drawing.Font( "Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ( (byte) ( 238 ) ) );
this.LabelMobileFilter.Location = new System.Drawing.Point( 276, 9 );
this.LabelMobileFilter.Name = "LabelMobileFilter";
this.LabelMobileFilter.Size = new System.Drawing.Size( 85, 16 );
this.LabelMobileFilter.TabIndex = 14;
this.LabelMobileFilter.Text = "Mobs Filter";
//
// ToggleAllMobiles
//
this.ToggleAllMobiles.AutoSize = true;
this.ToggleAllMobiles.Checked = true;
this.ToggleAllMobiles.CheckState = System.Windows.Forms.CheckState.Indeterminate;
this.ToggleAllMobiles.Location = new System.Drawing.Point( 242, 41 );
this.ToggleAllMobiles.Name = "ToggleAllMobiles";
this.ToggleAllMobiles.Size = new System.Drawing.Size( 76, 17 );
this.ToggleAllMobiles.TabIndex = 15;
this.ToggleAllMobiles.Text = "All Mobiles";
this.ToggleAllMobiles.UseVisualStyleBackColor = true;
this.ToggleAllMobiles.CheckedChanged += new System.EventHandler( this.ToggleAllMobiles_CheckedChanged );
//
// SavePath
//
this.SavePath.Location = new System.Drawing.Point( 12, 376 );
this.SavePath.Name = "SavePath";
this.SavePath.Size = new System.Drawing.Size( 329, 20 );
this.SavePath.TabIndex = 16;
//
// ButtonSelectFile
//
this.ButtonSelectFile.Location = new System.Drawing.Point( 347, 374 );
this.ButtonSelectFile.Name = "ButtonSelectFile";
this.ButtonSelectFile.Size = new System.Drawing.Size( 23, 23 );
this.ButtonSelectFile.TabIndex = 17;
this.ButtonSelectFile.Text = "...";
this.ButtonSelectFile.UseVisualStyleBackColor = true;
this.ButtonSelectFile.Click += new System.EventHandler( this.ButtonSelectFile_Click );
//
// ToggleWearable
//
this.ToggleWearable.AutoSize = true;
this.ToggleWearable.Checked = true;
this.ToggleWearable.CheckState = System.Windows.Forms.CheckState.Checked;
this.ToggleWearable.Location = new System.Drawing.Point( 12, 407 );
this.ToggleWearable.Name = "ToggleWearable";
this.ToggleWearable.Size = new System.Drawing.Size( 72, 17 );
this.ToggleWearable.TabIndex = 19;
this.ToggleWearable.Text = "Wearable";
this.ToggleWearable.UseVisualStyleBackColor = true;
this.ToggleWearable.CheckStateChanged += new System.EventHandler( this.ToggleWearable_CheckedStateChanged );
//
// ToggleOther
//
this.ToggleOther.AutoSize = true;
this.ToggleOther.Checked = true;
this.ToggleOther.CheckState = System.Windows.Forms.CheckState.Checked;
this.ToggleOther.Location = new System.Drawing.Point( 90, 407 );
this.ToggleOther.Name = "ToggleOther";
this.ToggleOther.Size = new System.Drawing.Size( 52, 17 );
this.ToggleOther.TabIndex = 20;
this.ToggleOther.Text = "Other";
this.ToggleOther.UseVisualStyleBackColor = true;
this.ToggleOther.CheckStateChanged += new System.EventHandler( this.ToggleOther_CheckedStateChanged );
//
// LootSave
//
this.LootSave.FileName = "Loot.txt";
this.LootSave.Filter = "txt files (*.txt)|*.txt";
//
// PropertyFilter
//
this.PropertyFilter.Enabled = false;
this.PropertyFilter.Location = new System.Drawing.Point( 113, 343 );
this.PropertyFilter.Name = "PropertyFilter";
this.PropertyFilter.Size = new System.Drawing.Size( 257, 20 );
this.PropertyFilter.TabIndex = 22;
this.PropertyFilter.Leave += new System.EventHandler( this.PropertyFilter_Leave );
//
// RadioInclude
//
this.RadioInclude.AutoSize = true;
this.RadioInclude.Checked = true;
this.RadioInclude.Enabled = false;
this.RadioInclude.Location = new System.Drawing.Point( 12, 336 );
this.RadioInclude.Margin = new System.Windows.Forms.Padding( 3, 3, 3, 0 );
this.RadioInclude.Name = "RadioInclude";
this.RadioInclude.Size = new System.Drawing.Size( 78, 17 );
this.RadioInclude.TabIndex = 24;
this.RadioInclude.TabStop = true;
this.RadioInclude.Text = "Must have:";
this.RadioInclude.UseVisualStyleBackColor = true;
//
// RadioExclude
//
this.RadioExclude.AutoSize = true;
this.RadioExclude.Enabled = false;
this.RadioExclude.Location = new System.Drawing.Point( 12, 353 );
this.RadioExclude.Margin = new System.Windows.Forms.Padding( 3, 0, 3, 3 );
this.RadioExclude.Name = "RadioExclude";
this.RadioExclude.Size = new System.Drawing.Size( 96, 17 );
this.RadioExclude.TabIndex = 25;
this.RadioExclude.Text = "Must not have:";
this.RadioExclude.UseVisualStyleBackColor = true;
this.RadioExclude.CheckedChanged += new System.EventHandler( this.RadioExclude_CheckedChanged );
//
// LootFilterForm
//
this.AcceptButton = this.ButtonOk;
this.AutoScaleBaseSize = new System.Drawing.Size( 5, 13 );
this.CancelButton = this.ButtonCancel;
this.ClientSize = new System.Drawing.Size( 382, 438 );
this.Controls.Add( this.RadioExclude );
this.Controls.Add( this.RadioInclude );
this.Controls.Add( this.PropertyFilter );
this.Controls.Add( this.ToggleOther );
this.Controls.Add( this.ToggleWearable );
this.Controls.Add( this.ButtonSelectFile );
this.Controls.Add( this.SavePath );
this.Controls.Add( this.ToggleAllMobiles );
this.Controls.Add( this.LabelMobileFilter );
this.Controls.Add( this.LabelItemFilter );
this.Controls.Add( this.MobileFilter );
this.Controls.Add( this.ToggleWeapon );
this.Controls.Add( this.ToggleAos );
this.Controls.Add( this.ToggleArmor );
this.Controls.Add( this.ButtonSave );
this.Controls.Add( this.ButtonLoad );
this.Controls.Add( this.ButtonCancel );
this.Controls.Add( this.ButtonOk );
this.Controls.Add( this.ItemFilter );
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "LootFilterForm";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Loot Filter";
this.Shown += new System.EventHandler( this.LootFilterForm_Shown );
this.ResumeLayout( false );
this.PerformLayout();
}
#endregion
#region Properties
private LootFilter m_Filter;
private bool m_Locked;
public string FileName
{
get { return SavePath.Text; }
}
#endregion
#region Constructors
public LootFilterForm( LootFilter filter )
{
m_Filter = filter;
InitializeComponent();
string[] names = Enum.GetNames( typeof( ItemProperty ) );
ItemFilter.Items.AddRange( names );
ItemFilter.Items.AddRange( Item.DefaultNames );
}
#endregion
#region Private Members
private void InvalidateItems()
{
m_Locked = true;
for ( int i = 0; i < ItemFilter.Items.Count; i++ )
ItemFilter.SetItemChecked( i, m_Filter.Filters( i ) );
m_Locked = false;
}
private void InvalidateMobiles()
{
m_Locked = true;
for ( int i = 0; i < MobileFilter.Items.Count; i++ )
MobileFilter.SetItemChecked( i, m_Filter.Filters( MobileFilter.Items[ i ].ToString() ) );
m_Locked = false;
}
#region Events
private void ButtonLoad_Click( object sender, EventArgs e )
{
if ( FilterLoad.ShowDialog() == DialogResult.OK )
{
m_Filter.Load( FilterLoad.FileName );
InvalidateItems();
}
}
private void ButtonSave_Click( object sender, EventArgs e )
{
if ( FilterSave.ShowDialog() == DialogResult.OK )
{
m_Filter.Save( FilterLoad.FileName );
}
}
private void FilterList_ItemCheck( object sender, ItemCheckEventArgs e )
{
if ( !m_Locked )
m_Filter.Toggle( e.Index );
}
private void MobileFilter_ItemCheck( object sender, ItemCheckEventArgs e )
{
if ( !m_Locked )
m_Filter.Toggle( MobileFilter.Items[ e.Index ].ToString() );
}
private void ToggleAllMobiles_CheckedChanged( object sender, EventArgs e )
{
m_Filter.ToggleMobiles( ToggleAllMobiles.Checked );
InvalidateMobiles();
}
private void ToggleArmor_CheckStateChanged( object sender, EventArgs e )
{
m_Filter.ToggleArmor( ToggleArmor.Checked );
InvalidateItems();
}
private void ToggleAos_CheckStateChanged( object sender, EventArgs e )
{
m_Filter.ToggleAos( ToggleAos.Checked );
InvalidateItems();
}
private void ToggleWeapon_CheckStateChanged( object sender, EventArgs e )
{
m_Filter.ToggleWeapon( ToggleWeapon.Checked );
InvalidateItems();
}
private void ToggleWearable_CheckedStateChanged( object sender, EventArgs e )
{
m_Filter.Wearable = ToggleWearable.Checked;
}
private void ToggleOther_CheckedStateChanged( object sender, EventArgs e )
{
m_Filter.Other = ToggleOther.Checked;
}
private void ButtonSelectFile_Click( object sender, EventArgs e )
{
if ( !String.IsNullOrEmpty( SavePath.Text ) )
LootSave.FileName = SavePath.Text;
if ( LootSave.ShowDialog() == DialogResult.OK )
SavePath.Text = LootSave.FileName;
}
private void LootFilterForm_Shown( object sender, EventArgs e )
{
MobileFilter.Items.Clear();
foreach ( string s in m_Filter.MobileFilter.Keys )
MobileFilter.Items.Add( s );
InvalidateItems();
InvalidateMobiles();
}
private void RadioExclude_CheckedChanged( object sender, EventArgs e )
{
int i = ItemFilter.SelectedIndex;
if ( i >= 0 )
{
PropertyFilter filter = m_Filter.PropertyFilter[ i ];
filter.Exclude = RadioExclude.Checked;
}
}
private void ItemFilter_SelectedIndexChanged( object sender, EventArgs e )
{
int i = ItemFilter.SelectedIndex;
if ( i >= 0 )
{
PropertyFilter filter = m_Filter.PropertyFilter[ i ];
StringBuilder builder = new StringBuilder();
foreach ( object o in filter.Values )
{
builder.Append( o.ToString() );
builder.Append( '|' );
}
RadioExclude.Enabled = true;
RadioInclude.Enabled = true;
PropertyFilter.Enabled = true;
PropertyFilter.Text = builder.ToString();
}
else
{
RadioExclude.Enabled = false;
RadioInclude.Enabled = false;
PropertyFilter.Enabled = false;
}
}
private void PropertyFilter_Leave( object sender, EventArgs e )
{
int i = ItemFilter.SelectedIndex;
if ( i >= 0 )
{
PropertyFilter filter = m_Filter.PropertyFilter[ i ];
string[] split = PropertyFilter.Text.Split( new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries );
int iValue;
double dValue;
filter.Values.Clear();
foreach ( string s in split )
{
if ( s.StartsWith( "0x" ) && Int32.TryParse( s.Substring( 2, s.Length - 2 ), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out iValue ) )
filter.Values.Add( iValue );
else if ( Int32.TryParse( s, out iValue ) )
filter.Values.Add( iValue );
else if ( Double.TryParse( s, out dValue ) )
filter.Values.Add( dValue );
else
filter.Values.Add( s );
}
}
}
#endregion
#endregion
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Text;
using System.Globalization;
using System.Windows.Forms;
using OpenLiveWriter.CoreServices.Layout;
using OpenLiveWriter.HtmlParser.Parser;
using OpenLiveWriter.ApplicationFramework;
using OpenLiveWriter.ApplicationFramework.Skinning;
using OpenLiveWriter.Controls;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.Extensibility.BlogClient;
using OpenLiveWriter.Interop.Windows;
using OpenLiveWriter.Localization;
using OpenLiveWriter.Localization.Bidi;
namespace OpenLiveWriter.PostEditor.PostPropertyEditing.CategoryControl
{
/// <summary>
/// Summary description for CategoryDisplayForm.
/// </summary>
internal class CategoryDisplayFormM1 : MiniForm
{
public CategoryDisplayFormM1(Control parentControl, CategoryContext categoryContext)
{
SuppressAutoRtlFixup = true;
// save references and signup for changed event
_parentControl = parentControl;
_categoryContext = categoryContext;
_categoryContext.Changed += new CategoryContext.CategoryChangedEventHandler(_categoryContext_Changed);
// standard designer stuff
InitializeComponent();
this.buttonAdd.Text = Res.Get(StringId.AddButton2);
// mini form behavior
DismissOnDeactivate = true;
// dynamic background colors based on theme
BackColor = ColorizedResources.Instance.FrameGradientLight ;
categoryRefreshControl.BackColor = ColorizedResources.Instance.FrameGradientLight ;
categoryContainerControl.BackColor = SystemColors.Window ;
// dynamic layout depending upon whether we support adding categories
if ( categoryContext.SupportsAddingCategories )
{
textBoxAddCategory.MaxLength = categoryContext.MaxCategoryNameLength ;
}
else
{
int gap = categoryContainerControl.Top - panelAddCategory.Top ;
panelAddCategory.Visible = false ;
categoryContainerControl.Top = panelAddCategory.Top + 2 ;
categoryContainerControl.Height += gap ;
}
// dynamic layout depending upon whether we support heirarchical categories
if ( !categoryContext.SupportsHierarchicalCategories )
{
textBoxAddCategory.Width += (comboBoxParent.Right - textBoxAddCategory.Right);
comboBoxParent.Visible = false ;
}
// initialize add textbox
ClearAddTextBox() ;
// initialize category control
categoryRefreshControl.Initialize(_categoryContext);
}
public int MaxDropDownWidth
{
get { return _maxDropDownWidth; }
set { _maxDropDownWidth = value; }
}
public int MinDropDownWidth
{
get { return _minDropDownWidth; }
set { _minDropDownWidth = value; }
}
private int _maxDropDownWidth = 260;
private int _minDropDownWidth = 104;
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
RefreshParentCombo();
if (panelAddCategory.Visible)
{
if (comboBoxParent.Visible)
{
DisplayHelper.AutoFitSystemButton(buttonAdd);
using (new AutoGrow(this, AnchorStyles.Bottom | AnchorStyles.Right, false))
{
textBoxAddCategory.Width = buttonAdd.Right - textBoxAddCategory.Left;
DisplayHelper.AutoFitSystemCombo(comboBoxParent, 0, int.MaxValue, true);
comboBoxParent.Left = textBoxAddCategory.Left;
comboBoxParent.Top = textBoxAddCategory.Bottom + ScaleY(3);
buttonAdd.Top = comboBoxParent.Top + (comboBoxParent.Height - buttonAdd.Height) / 2;
buttonAdd.Left = comboBoxParent.Right + ScaleX(3);
if (buttonAdd.Right > textBoxAddCategory.Right)
{
int deltaX = buttonAdd.Right - textBoxAddCategory.Right;
textBoxAddCategory.Width += deltaX;
using (LayoutHelper.SuspendAnchoring(textBoxAddCategory, buttonAdd, comboBoxParent))
panelAddCategory.Width += deltaX;
categoryContainerControl.Width += deltaX;
}
else
{
buttonAdd.Left = textBoxAddCategory.Right - buttonAdd.Width;
comboBoxParent.Width = buttonAdd.Left - comboBoxParent.Left - ScaleX(3);
}
int deltaY = comboBoxParent.Bottom - textBoxAddCategory.Bottom;
panelAddCategory.Height += deltaY;
categoryContainerControl.Top += deltaY;
categoryRefreshControl.Top += deltaY;
}
}
else
{
using (new AutoGrow(this, AnchorStyles.Right, false))
{
int deltaX = -buttonAdd.Width + DisplayHelper.AutoFitSystemButton(buttonAdd);
textBoxAddCategory.Width -= deltaX;
int desiredWidth = DisplayHelper.MeasureString(textBoxAddCategory, textBoxAddCategory.Text).Width + (int)DisplayHelper.ScaleX(10);
deltaX += desiredWidth - textBoxAddCategory.Width;
if (deltaX > 0)
{
panelAddCategory.Width += deltaX;
categoryContainerControl.Width += deltaX;
// textBoxAddCategory.Width += deltaX;
// buttonAdd.Left = textBoxAddCategory.Right + ScaleX(3);
// textBoxAddCategory.Width = Math.Max(desiredWidth, textBoxAddCategory.Width);
// textBoxAddCategory.Width = buttonAdd.Left - textBoxAddCategory.Left - ScaleX(3);
}
}
}
/*using (LayoutHelper.SuspendAnchoring(comboBoxParent, buttonAdd, textBoxAddCategory, panelAddCategory, categoryContainerControl))
{
if (comboBoxParent.Visible)
{
deltaW = -comboBoxParent.Width + DisplayHelper.AutoFitSystemCombo(comboBoxParent, 0, int.MaxValue, true);
buttonAdd.Left += deltaW;
}
int oldWidth = buttonAdd.Width;
DisplayHelper.AutoFitSystemButton(buttonAdd);
buttonAdd.Width += (int)DisplayHelper.ScaleX(6); // add some more "air" in the Add button
deltaW += buttonAdd.Width - oldWidth;
panelAddCategory.Width += deltaW;
categoryContainerControl.Width += deltaW;
Width += deltaW;
}*/
}
// use design time defaults to drive dynamic layout
_topMargin = categoryContainerControl.Top ;
_bottomMargin = Bottom - categoryContainerControl.Bottom ;
using (new AutoGrow(this, AnchorStyles.Right, false))
LayoutControls(_categoryContext, true, false);
UpdateSelectedCategories(_categoryContext.SelectedCategories);
BidiHelper.RtlLayoutFixup(this);
}
private System.Windows.Forms.Panel panelAddCategory;
private System.Windows.Forms.TextBox textBoxAddCategory;
private System.Windows.Forms.Button buttonAdd;
private OpenLiveWriter.PostEditor.PostPropertyEditing.CategoryControl.CategoryRefreshControl categoryRefreshControl;
private ParentCategoryComboBox comboBoxParent;
protected override CreateParams CreateParams
{
get
{
CreateParams createParams = base.CreateParams;
// Borderless windows show in the alt+tab window, so this fakes
// out windows into thinking its a tool window (which doesn't
// show up in the alt+tab window).
createParams.ExStyle |= 0x00000080; // WS_EX_TOOLWINDOW
return createParams;
}
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if ( keyData == Keys.Enter )
{
if ( textBoxAddCategory.ContainsFocus )
{
AddCategory() ;
return true ;
}
else if ( categoryContainerControl.ContainsFocus )
{
Close() ;
return true ;
}
else
{
return false ;
}
}
else if (keyData == Keys.Escape )
{
Close();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
protected override void OnPaintBackground(PaintEventArgs e)
{
base.OnPaintBackground(e);
// I don't know why this is necessary, but when RightToLeft and RightToLeftLayout
// are both true, the rightmost column or two of pixels get clipped unless we
// explicitly reset the clip.
e.Graphics.ResetClip();
// draw border around form
using ( Pen pen = new Pen(ColorizedResources.Instance.BorderDarkColor) )
e.Graphics.DrawRectangle(pen, 0, 0, ClientSize.Width - 1, ClientSize.Height - 1);
// draw border around category control
Color controlBorderColor = ColorHelper.GetThemeBorderColor(ColorizedResources.Instance.BorderDarkColor) ;
using ( Pen pen = new Pen( controlBorderColor, 1 ))
{
Rectangle categoryRect = categoryContainerControl.Bounds ;
categoryRect.Inflate(1,1);
e.Graphics.DrawRectangle(pen, categoryRect);
}
}
private int _topMargin ;
private int _bottomMargin ;
private Panel categoryContainerControl;
private void LayoutControls(CategoryContext categoryContext, bool sizeForm, bool performRtlLayoutFixup)
{
ClearForm();
SuspendLayout();
// calculate how much room there is above me on the parent form
int parentControlY = _parentControl.PointToScreen(_parentControl.Location).Y ;
Form parentForm = _parentControl.FindForm() ;
int parentFormY = parentForm.PointToScreen(parentForm.ClientRectangle.Location).Y ;
int maxHeight = parentControlY - parentFormY - ScaleY(_topMargin) - ScaleY(_bottomMargin);
// enforce additional constraint (or not, let freedom reign!)
//maxHeight = Math.Min(maxHeight, 400) ;
using (PositionManager positionManager = new PositionManager(ScaleX(X_MARGIN), ScaleY(Y_MARGIN + 2), ScaleY(4), ScaleX(MinDropDownWidth), categoryContainerControl.Width, maxHeight, scale))
{
// add 'none' if we're single selecting categories
if (categoryContext.SelectionMode != CategoryContext.SelectionModes.MultiSelect)
AddCategoryControl(new BlogPostCategoryListItem(new BlogPostCategoryNone(), 0), positionManager);
// add the other categories
BlogPostCategoryListItem[] categoryListItems = BlogPostCategoryListItem.BuildList(categoryContext.Categories, true) ;
foreach(BlogPostCategoryListItem categoryListItem in categoryListItems)
AddCategoryControl(categoryListItem, positionManager) ;
if ( sizeForm )
PositionAndSizeForm(positionManager);
}
if (performRtlLayoutFixup)
BidiHelper.RtlLayoutFixup(categoryContainerControl);
ResumeLayout();
}
private BlogPostCategory[] GetCategories(CategoryContext context)
{
ArrayList categories = new ArrayList(context.Categories);
categories.Sort();
return (BlogPostCategory[]) categories.ToArray(typeof (BlogPostCategory));
}
private void ClearForm()
{
if (_categoryControls.Count > 0)
{
categoryContainerControl.Controls.Clear();
_categoryControls.Clear();
}
}
private void AddCategoryControl(BlogPostCategoryListItem categoryListItem, PositionManager positionManager)
{
ICategorySelectorControl catSelector =
CategorySelectorControlFactory.Instance.GetControl(categoryListItem.Category,
(_categoryContext.SelectionMode ==
CategoryContext.SelectionModes.MultiSelect));
catSelector.SelectedChanged += new EventHandler(catSelector_SelectedChanged);
catSelector.Control.Scale(new SizeF(scale.X, scale.Y));
positionManager.PositionControl(catSelector.Control, categoryListItem.IndentLevel);
categoryContainerControl.Controls.Add(catSelector.Control);
_categoryControls.Add(catSelector.Control);
}
private void PositionAndSizeForm(PositionManager manager)
{
// determine height based on position manager calculations
categoryContainerControl.Height = manager.Height;
Height = manager.Height + ScaleY(_topMargin) + ScaleY(_bottomMargin) ;
Point bottomRightCorner =
_parentControl.PointToScreen(new Point(_parentControl.Width - Width, -Height));
Location = bottomRightCorner;
}
#region High DPI Scaling
protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
{
SaveScaleState(factor.Width, factor.Height);
base.ScaleControl(factor, specified);
}
protected override void ScaleCore(float dx, float dy)
{
SaveScaleState(dx, dy);
base.ScaleCore(dx, dy);
}
private void SaveScaleState(float dx, float dy)
{
scale = new PointF(scale.X*dx, scale.Y*dy);
//synchronize the comboBoxParent item height so it matches the scaled control height.
//Note: ScaleY(3) is padding to deal with mismatches in the way the ItemHeight scales versus its peer controls...
//comboBoxParent.ItemHeight = (int) (comboBoxParent.ItemHeight*dy) + ScaleY(3);
comboBoxParent.ItemHeight = (int) (comboBoxParent.ItemHeight*dy) + (scale.Y == 1f ? 0 : ScaleY(3));
}
private PointF scale = new PointF(1f, 1f);
protected int ScaleX(int x)
{
return (int) (x*scale.X);
}
protected int ScaleY(int y)
{
return (int) (y*scale.Y);
}
#endregion
private const int Y_MARGIN = 2;
private const int X_MARGIN = 4;
private void CommitSelection()
{
ArrayList selectedCategories = new ArrayList();
foreach (ICategorySelectorControl categoryControl in _categoryControls)
{
if (categoryControl.Selected)
{
if (BlogPostCategoryNone.IsCategoryNone(categoryControl.Category))
{
selectedCategories.Clear();
break;
}
else
{
selectedCategories.Add(categoryControl.Category);
}
}
}
_categoryContext.SelectedCategories = (BlogPostCategory[]) selectedCategories.ToArray(typeof (BlogPostCategory));
}
private BlogPostCategory[] GetCurrentlySelectedCategories()
{
ArrayList selectedCategories = new ArrayList();
foreach (ICategorySelectorControl sc in _categoryControls)
{
if (sc.Selected)
{
if (BlogPostCategoryNone.IsCategoryNone(sc.Category))
{
selectedCategories.Clear();
break;
}
else
{
selectedCategories.Add(sc.Category);
}
}
}
return (BlogPostCategory[]) selectedCategories.ToArray(typeof (BlogPostCategory));
}
private void UpdateSelectedCategories(BlogPostCategory[] selectedCategories)
{
bool focused = false;
foreach (ICategorySelectorControl sc in _categoryControls)
{
if (!focused)
{
sc.Control.Focus();
focused = true;
}
sc.Selected = false;
}
if (selectedCategories.Length > 0)
{
foreach (BlogPostCategory c in selectedCategories)
foreach (ICategorySelectorControl sc in _categoryControls)
{
if (c.Id.ToLower(CultureInfo.CurrentCulture) == sc.Category.Id.ToLower(CultureInfo.CurrentCulture) ||
c.Name.ToLower(CultureInfo.CurrentCulture) == sc.Category.Name.ToLower(CultureInfo.CurrentCulture) )
{
sc.Selected = true;
break;
}
}
}
else
{
// scan for special "None" category and select it
foreach (ICategorySelectorControl sc in _categoryControls)
{
if (BlogPostCategoryNone.IsCategoryNone((sc.Category)))
{
sc.Selected = true;
break;
}
}
}
}
private void textBoxAddCategory_Enter(object sender, System.EventArgs e)
{
if ( textBoxAddCategory.Text == Res.Get(StringId.CategoryAdd) )
ActivateAddTextBoxForEdit() ;
}
private void textBoxAddCategory_Leave(object sender, System.EventArgs e)
{
if ( textBoxAddCategory.Text.Trim() == String.Empty )
ClearAddTextBox() ;
}
private void ClearAddTextBox()
{
textBoxAddCategory.ForeColor = SystemColors.GrayText ;
textBoxAddCategory.Text = Res.Get(StringId.CategoryAdd);
}
private void ActivateAddTextBoxForEdit()
{
textBoxAddCategory.ForeColor = SystemColors.ControlText;
textBoxAddCategory.Text = String.Empty ;
}
private void buttonAdd_Click(object sender, System.EventArgs e)
{
AddCategory() ;
}
private void AddCategory()
{
// add the new category
BlogPostCategory newCategory = GetNewCategory() ;
// see if the "new" category is already in our list
if ( newCategory != null )
{
ICategorySelectorControl selectorControl = GetCategorySelectorControl(newCategory) ;
// if there is no existing selector control then add the category
if ( selectorControl == null )
_categoryContext.AddNewCategory(newCategory);
// now re-lookup the selector control and select it
selectorControl = GetCategorySelectorControl(newCategory) ;
selectorControl.Selected = true ;
// ensure the added category is scrolled into view
categoryContainerControl.ScrollControlIntoView(selectorControl.Control);
// clear the parent combo and update its ui
comboBoxParent.SelectedIndex = 0 ;
UpdateParentComboForeColor() ;
// setup the text box to add another category if we support multiple categories
if ( _categoryContext.SelectionMode == CategoryContext.SelectionModes.MultiSelect )
{
ActivateAddTextBoxForEdit() ;
textBoxAddCategory.Focus() ;
}
else
{
ClearAddTextBox() ;
selectorControl.Control.Focus() ;
}
}
}
private BlogPostCategory GetNewCategory()
{
if ( textBoxAddCategory.ForeColor == SystemColors.ControlText )
{
string categoryName = this.textBoxAddCategory.Text.Trim() ;
if ( categoryName != String.Empty )
{
// see if we have a parent
BlogPostCategory parentCategory = GetParentCategory() ;
if ( parentCategory != null )
return new BlogPostCategory(categoryName, categoryName, parentCategory.Id);
else
return new BlogPostCategory(categoryName);
}
else
{
return null ;
}
}
else
{
return null ;
}
}
private ICategorySelectorControl GetCategorySelectorControl(BlogPostCategory category)
{
// scan for control
foreach (ICategorySelectorControl selectorControl in _categoryControls)
{
if ( selectorControl.Category.Id.ToLower(CultureInfo.CurrentCulture) == category.Id.ToLower(CultureInfo.CurrentCulture) ||
selectorControl.Category.Name.ToLower(CultureInfo.CurrentCulture) == category.Name.ToLower(CultureInfo.CurrentCulture) )
{
return selectorControl ;
}
}
// didn't find it
return null ;
}
#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.categoryContainerControl = new System.Windows.Forms.Panel();
this.panelAddCategory = new System.Windows.Forms.Panel();
this.comboBoxParent = new OpenLiveWriter.PostEditor.PostPropertyEditing.CategoryControl.CategoryDisplayFormM1.ParentCategoryComboBox();
this.buttonAdd = new System.Windows.Forms.Button();
this.textBoxAddCategory = new System.Windows.Forms.TextBox();
this.categoryRefreshControl = new OpenLiveWriter.PostEditor.PostPropertyEditing.CategoryControl.CategoryRefreshControl();
this.panelAddCategory.SuspendLayout();
this.SuspendLayout();
//
// categoryContainerControl
//
this.categoryContainerControl.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.categoryContainerControl.AutoScroll = true;
this.categoryContainerControl.Location = new System.Drawing.Point(7, 33);
this.categoryContainerControl.Name = "categoryContainerControl";
this.categoryContainerControl.Size = new System.Drawing.Size(189, 72);
this.categoryContainerControl.TabIndex = 0;
//
// panelAddCategory
//
this.panelAddCategory.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.panelAddCategory.Controls.Add(this.comboBoxParent);
this.panelAddCategory.Controls.Add(this.buttonAdd);
this.panelAddCategory.Controls.Add(this.textBoxAddCategory);
this.panelAddCategory.Location = new System.Drawing.Point(6, 5);
this.panelAddCategory.Name = "panelAddCategory";
this.panelAddCategory.Size = new System.Drawing.Size(194, 25);
this.panelAddCategory.TabIndex = 1;
//
// comboBoxParent
//
this.comboBoxParent.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.comboBoxParent.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
this.comboBoxParent.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxParent.DropDownWidth = 200;
this.comboBoxParent.IntegralHeight = false;
this.comboBoxParent.ItemHeight = 15;
this.comboBoxParent.Location = new System.Drawing.Point(42, 1);
this.comboBoxParent.MaxDropDownItems = 20;
this.comboBoxParent.Name = "comboBoxParent";
this.comboBoxParent.Size = new System.Drawing.Size(88, 21);
this.comboBoxParent.TabIndex = 1;
this.comboBoxParent.Leave += new System.EventHandler(this.comboBoxParent_Leave);
this.comboBoxParent.Enter += new System.EventHandler(this.comboBoxParent_Enter);
//
// buttonAdd
//
this.buttonAdd.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.buttonAdd.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.buttonAdd.Location = new System.Drawing.Point(134, 0);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(59, 23);
this.buttonAdd.TabIndex = 2;
this.buttonAdd.Text = "&Add";
this.buttonAdd.Click += new System.EventHandler(this.buttonAdd_Click);
//
// textBoxAddCategory
//
this.textBoxAddCategory.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.textBoxAddCategory.AutoSize = false;
this.textBoxAddCategory.Location = new System.Drawing.Point(0, 1);
this.textBoxAddCategory.Name = "textBoxAddCategory";
this.textBoxAddCategory.Size = new System.Drawing.Size(38, 21);
this.textBoxAddCategory.TabIndex = 0;
this.textBoxAddCategory.Text = "";
this.textBoxAddCategory.Leave += new System.EventHandler(this.textBoxAddCategory_Leave);
this.textBoxAddCategory.Enter += new System.EventHandler(this.textBoxAddCategory_Enter);
//
// categoryRefreshControl
//
this.categoryRefreshControl.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.categoryRefreshControl.BackColor = System.Drawing.SystemColors.ControlLightLight;
this.categoryRefreshControl.Location = new System.Drawing.Point(6, 111);
this.categoryRefreshControl.Name = "categoryRefreshControl";
this.categoryRefreshControl.Size = new System.Drawing.Size(193, 23);
this.categoryRefreshControl.TabIndex = 2;
//
// CategoryDisplayFormM1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 14);
this.AutoScrollMargin = new System.Drawing.Size(2, 2);
this.BackColor = System.Drawing.SystemColors.ControlLightLight;
this.ClientSize = new System.Drawing.Size(205, 138);
this.ControlBox = false;
this.Controls.Add(this.categoryRefreshControl);
this.Controls.Add(this.panelAddCategory);
this.Controls.Add(this.categoryContainerControl);
this.DismissOnDeactivate = true;
this.DockPadding.All = 1;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "CategoryDisplayFormM1";
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.panelAddCategory.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
_categoryContext.Changed -= new CategoryContext.CategoryChangedEventHandler(_categoryContext_Changed);
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
private System.ComponentModel.IContainer components = new Container();
private ArrayList _categoryControls = new ArrayList();
private CategoryContext _categoryContext;
private Control _parentControl;
private void catSelector_SelectedChanged(object sender, EventArgs e)
{
CommitSelection();
}
private void _categoryContext_Changed(object sender, CategoryContext.CategoryChangedEventArgs e)
{
if (e.ChangeType == CategoryContext.ChangeType.Category || e.ChangeType == CategoryContext.ChangeType.SelectionMode)
{
BlogPostCategory[] selectedCategories = GetCurrentlySelectedCategories();
LayoutControls(_categoryContext, false, true);
UpdateSelectedCategories(selectedCategories);
RefreshParentCombo() ;
Invalidate() ;
}
}
private void RefreshParentCombo()
{
// populate "parent" combo
object selectedItem = comboBoxParent.SelectedItem ;
comboBoxParent.Items.Clear();
comboBoxParent.Items.Add(new ParentCategoryComboItemNone(comboBoxParent)) ;
BlogPostCategoryListItem[] categoryListItems = BlogPostCategoryListItem.BuildList(_categoryContext.BlogCategories, true) ;
foreach(BlogPostCategoryListItem categoryListItem in categoryListItems)
comboBoxParent.Items.Add(new ParentCategoryComboItem(comboBoxParent, categoryListItem.Category, categoryListItem.IndentLevel)) ;
UpdateParentComboForeColor() ;
if ( selectedItem != null && comboBoxParent.Items.Contains(selectedItem))
comboBoxParent.SelectedItem = selectedItem ;
else
comboBoxParent.SelectedIndex = 0 ;
}
private BlogPostCategory GetParentCategory()
{
ParentCategoryComboItem parentComboItem = comboBoxParent.SelectedItem as ParentCategoryComboItem ;
if ( parentComboItem != null )
{
if ( !BlogPostCategoryNone.IsCategoryNone(parentComboItem.Category) )
return parentComboItem.Category ;
else
return null ;
}
else
{
return null ;
}
}
private void comboBoxParent_Enter(object sender, System.EventArgs e)
{
comboBoxParent.ForeColor = SystemColors.ControlText;
}
private void comboBoxParent_Leave(object sender, System.EventArgs e)
{
UpdateParentComboForeColor() ;
}
private void UpdateParentComboForeColor()
{
if ( GetParentCategory() != null )
comboBoxParent.ForeColor = SystemColors.ControlText ;
else
comboBoxParent.ForeColor = SystemColors.GrayText ;
}
private class ParentCategoryComboItem
{
public ParentCategoryComboItem(ComboBox parentCombo, BlogPostCategory category, int indentLevel)
{
_parentCombo = parentCombo ;
_category = category ;
_indentLevel = indentLevel ;
}
public BlogPostCategory Category
{
get { return _category; }
}
private BlogPostCategory _category ;
public override bool Equals(object obj)
{
return (obj as ParentCategoryComboItem).Category.Equals(Category) ;
}
public override int GetHashCode()
{
return Category.GetHashCode() ;
}
public override string ToString()
{
// default padding
string padding = new String(' ', _indentLevel * 3) ;
// override if we are selected
if ( !_parentCombo.DroppedDown && (_parentCombo.SelectedItem != null) && this.Equals(_parentCombo.SelectedItem) )
padding = String.Empty ;
string categoryName = HtmlUtils.UnEscapeEntities(Category.Name, HtmlUtils.UnEscapeMode.Default) ;
string stringRepresentation = String.Format(CultureInfo.InvariantCulture, "{0}{1}", padding, categoryName) ;
return stringRepresentation ;
}
private int _indentLevel ;
private ComboBox _parentCombo ;
}
private class ParentCategoryComboBox : ComboBox
{
public ParentCategoryComboBox()
{
// prevent editing and showing of drop down
DropDownStyle = ComboBoxStyle.DropDownList ;
// fully cusotm painting
DrawMode = DrawMode.OwnerDrawFixed ;
IntegralHeight = false ;
}
protected override void OnDrawItem(DrawItemEventArgs e)
{
if (e.Index != -1)
{
ParentCategoryComboItem comboItem = Items[e.Index] as ParentCategoryComboItem ;
e.DrawBackground();
// don't indent for main display of category
string text = comboItem.ToString();
if (e.Bounds.Width < Width)
text = text.Trim() ;
using ( Brush brush = new SolidBrush(e.ForeColor) )
e.Graphics.DrawString(text, e.Font, brush, e.Bounds.X, e.Bounds.Y) ;
e.DrawFocusRectangle();
}
}
}
private class ParentCategoryComboItemNone : ParentCategoryComboItem
{
public ParentCategoryComboItemNone(ComboBox parentCombo)
: base(parentCombo, new BlogPostCategoryNone(), 0)
{
}
public override string ToString()
{
return Res.Get(StringId.CategoryNoParent) ;
}
}
private class PositionManager : IDisposable
{
private int _top;
private int _left;
private int _width;
private int _margin;
private ArrayList _controls = new ArrayList();
private int _maxWidth;
private int _minWidth;
private int _maxHeight ;
private int _enforcedMaxHeight = -1 ;
private PointF _autoScaleSize;
private StringFormat _format;
public PositionManager(int initialLeft, int initialTop, int scaledMargin, int minWidth, int maxWidth, int maxHeight, PointF autoScaleSize)
{
_left = initialLeft;
_top = initialTop;
_margin = scaledMargin;
_maxWidth = maxWidth;
_minWidth = _width = minWidth;
_maxHeight = maxHeight ;
_autoScaleSize = autoScaleSize;
_format = new StringFormat();
_format.Trimming = StringTrimming.EllipsisCharacter;
}
public void PositionControl(Control c, int indentLevel)
{
int INDENT_MARGIN = ScaleX(16) ;
c.Top = _top;
c.Left = _left + (INDENT_MARGIN * indentLevel);
Graphics g = c.CreateGraphics();
try
{
int maxWidth = _maxWidth - SystemInformation.VerticalScrollBarWidth - c.Left - _left;
c.Width = maxWidth;
if (c is CheckBox)
DisplayHelper.AutoFitSystemCheckBox((CheckBox)c, 0, maxWidth);
else if (c is RadioButton)
DisplayHelper.AutoFitSystemRadioButton((RadioButton)c, 0, maxWidth);
else
Debug.Fail("Being asked to position a control that isn't a radiobutton or checkbox");
LayoutHelper.NaturalizeHeight(c);
}
finally
{
g.Dispose();
}
_width = Math.Max(_width, c.Width);
_controls.Add(c);
_top = _top + c.Height + _margin;
// enforce max height if necessary
if ( _enforcedMaxHeight == -1 && _top > _maxHeight )
_enforcedMaxHeight = _top ;
}
public int Width
{
get { return _width; }
}
public int Height
{
get
{
if ( _enforcedMaxHeight != -1 )
return _enforcedMaxHeight ;
else
return _top + _margin;
}
}
protected int ScaleX(int x)
{
return (int) (x*_autoScaleSize.X);
}
protected int ScaleY(int y)
{
return (int) (y*_autoScaleSize.Y);
}
#region IDisposable Members
public void Dispose()
{
}
#endregion
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using log4net;
using Rhino.PersistentHashTable;
using Rhino.ServiceBus.DataStructures;
using Rhino.ServiceBus.Exceptions;
using Rhino.ServiceBus.Impl;
using Rhino.ServiceBus.Internal;
using Rhino.ServiceBus.MessageModules;
using Rhino.ServiceBus.Messages;
using Rhino.ServiceBus.Transport;
namespace Rhino.ServiceBus.RhinoQueues
{
public class PhtSubscriptionStorage : ISubscriptionStorage, IDisposable, IMessageModule
{
private const string SubscriptionsKey = "subscriptions";
private readonly Hashtable<string, List<WeakReference>> localInstanceSubscriptions =
new Hashtable<string, List<WeakReference>>();
private readonly ILog logger = LogManager.GetLogger(typeof (PhtSubscriptionStorage));
private readonly IMessageSerializer messageSerializer;
private readonly PersistentHashTable.PersistentHashTable pht;
private readonly IReflection reflection;
private readonly MultiValueIndexHashtable<Guid, string, Uri, int> remoteInstanceSubscriptions =
new MultiValueIndexHashtable<Guid, string, Uri, int>();
private readonly Hashtable<TypeAndUriKey, IList<int>> subscriptionMessageIds =
new Hashtable<TypeAndUriKey, IList<int>>();
private readonly string subscriptionPath;
private readonly Hashtable<string, HashSet<Uri>> subscriptions = new Hashtable<string, HashSet<Uri>>();
private bool currentlyLoadingPersistentData;
public PhtSubscriptionStorage(
string subscriptionPath,
IMessageSerializer messageSerializer,
IReflection reflection)
{
this.subscriptionPath = subscriptionPath;
this.messageSerializer = messageSerializer;
this.reflection = reflection;
pht = new PersistentHashTable.PersistentHashTable(subscriptionPath);
}
#region IDisposable Members
public void Dispose()
{
if (pht != null)
pht.Dispose();
}
#endregion
#region IMessageModule Members
void IMessageModule.Init(ITransport transport, IServiceBus bus)
{
transport.AdministrativeMessageArrived += HandleAdministrativeMessage;
}
void IMessageModule.Stop(ITransport transport, IServiceBus bus)
{
transport.AdministrativeMessageArrived -= HandleAdministrativeMessage;
}
#endregion
#region ISubscriptionStorage Members
public void Initialize()
{
logger.DebugFormat("Initializing msmq subscription storage on: {0}", subscriptionPath);
pht.Initialize();
pht.Batch(actions =>
{
var items = actions.GetItems(new GetItemsRequest
{
Key = SubscriptionsKey
});
foreach (var item in items)
{
object[] msgs;
try
{
msgs = messageSerializer.Deserialize(new MemoryStream(item.Value));
}
catch (Exception e)
{
throw new SubscriptionException("Could not deserialize message from subscription queue", e);
}
try
{
currentlyLoadingPersistentData = true;
foreach (var msg in msgs)
{
HandleAdministrativeMessage(new CurrentMessageInformation
{
AllMessages = msgs,
Message = msg,
});
}
}
catch (Exception e)
{
throw new SubscriptionException("Failed to process subscription records", e);
}
finally
{
currentlyLoadingPersistentData = false;
}
}
actions.Commit();
});
}
public IEnumerable<Uri> GetSubscriptionsFor(Type type)
{
HashSet<Uri> subscriptionForType = null;
subscriptions.Read(reader => reader.TryGetValue(type.FullName, out subscriptionForType));
var subscriptionsFor = subscriptionForType ?? new HashSet<Uri>();
List<Uri> instanceSubscriptions;
remoteInstanceSubscriptions.TryGet(type.FullName, out instanceSubscriptions);
subscriptionsFor.UnionWith(instanceSubscriptions);
return subscriptionsFor;
}
public void RemoveLocalInstanceSubscription(IMessageConsumer consumer)
{
var messagesConsumes = reflection.GetMessagesConsumed(consumer);
var changed = false;
var list = new List<WeakReference>();
localInstanceSubscriptions.Write(writer =>
{
foreach (var type in messagesConsumes)
{
List<WeakReference> value;
if (writer.TryGetValue(type.FullName, out value) == false)
continue;
writer.Remove(type.FullName);
list.AddRange(value);
}
});
foreach (var reference in list)
{
if (ReferenceEquals(reference.Target, consumer))
continue;
changed = true;
}
if (changed)
RaiseSubscriptionChanged();
}
public object[] GetInstanceSubscriptions(Type type)
{
List<WeakReference> value = null;
localInstanceSubscriptions.Read(reader => reader.TryGetValue(type.FullName, out value));
if (value == null)
return new object[0];
var liveInstances = value
.Select(x => x.Target)
.Where(x => x != null)
.ToArray();
if (liveInstances.Length != value.Count) //cleanup
{
localInstanceSubscriptions.Write(writer => value.RemoveAll(x => x.IsAlive == false));
}
return liveInstances;
}
public event Action SubscriptionChanged;
public bool AddSubscription(string type, string endpoint)
{
var added = false;
subscriptions.Write(writer =>
{
HashSet<Uri> subscriptionsForType;
if (writer.TryGetValue(type, out subscriptionsForType) == false)
{
subscriptionsForType = new HashSet<Uri>();
writer.Add(type, subscriptionsForType);
}
var uri = new Uri(endpoint);
added = subscriptionsForType.Add(uri);
logger.InfoFormat("Added subscription for {0} on {1}",
type, uri);
});
RaiseSubscriptionChanged();
return added;
}
public void RemoveSubscription(string type, string endpoint)
{
var uri = new Uri(endpoint);
RemoveSubscriptionMessageFromPht(type, uri);
subscriptions.Write(writer =>
{
HashSet<Uri> subscriptionsForType;
if (writer.TryGetValue(type, out subscriptionsForType) == false)
{
subscriptionsForType = new HashSet<Uri>();
writer.Add(type, subscriptionsForType);
}
subscriptionsForType.Remove(uri);
logger.InfoFormat("Removed subscription for {0} on {1}",
type, endpoint);
});
RaiseSubscriptionChanged();
}
public void AddLocalInstanceSubscription(IMessageConsumer consumer)
{
localInstanceSubscriptions.Write(writer =>
{
foreach (var type in reflection.GetMessagesConsumed(consumer))
{
List<WeakReference> value;
if (writer.TryGetValue(type.FullName, out value) == false)
{
value = new List<WeakReference>();
writer.Add(type.FullName, value);
}
value.Add(new WeakReference(consumer));
}
});
RaiseSubscriptionChanged();
}
#endregion
private void AddMessageIdentifierForTracking(int messageId, string messageType, Uri uri)
{
subscriptionMessageIds.Write(writer =>
{
var key = new TypeAndUriKey {TypeName = messageType, Uri = uri};
IList<int> value;
if (writer.TryGetValue(key, out value) == false)
{
value = new List<int>();
writer.Add(key, value);
}
value.Add(messageId);
});
}
private void RemoveSubscriptionMessageFromPht(string type, Uri uri)
{
subscriptionMessageIds.Write(writer =>
{
var key = new TypeAndUriKey
{
TypeName = type,
Uri = uri
};
IList<int> messageIds;
if (writer.TryGetValue(key, out messageIds) == false)
return;
pht.Batch(actions =>
{
foreach (var msgId in messageIds)
{
actions.RemoveItem(new RemoveItemRequest
{
Id = msgId,
Key = SubscriptionsKey
});
}
actions.Commit();
});
writer.Remove(key);
});
}
public bool HandleAdministrativeMessage(CurrentMessageInformation msgInfo)
{
var addSubscription = msgInfo.Message as AddSubscription;
if (addSubscription != null)
{
return ConsumeAddSubscription(addSubscription);
}
var removeSubscription = msgInfo.Message as RemoveSubscription;
if (removeSubscription != null)
{
return ConsumeRemoveSubscription(removeSubscription);
}
var addInstanceSubscription = msgInfo.Message as AddInstanceSubscription;
if (addInstanceSubscription != null)
{
return ConsumeAddInstanceSubscription(addInstanceSubscription);
}
var removeInstanceSubscription = msgInfo.Message as RemoveInstanceSubscription;
if (removeInstanceSubscription != null)
{
return ConsumeRemoveInstanceSubscription(removeInstanceSubscription);
}
return false;
}
public bool ConsumeRemoveInstanceSubscription(RemoveInstanceSubscription subscription)
{
int msgId;
if (remoteInstanceSubscriptions.TryRemove(subscription.InstanceSubscriptionKey, out msgId))
{
pht.Batch(actions =>
{
actions.RemoveItem(new RemoveItemRequest
{
Id = msgId,
Key = SubscriptionsKey
});
actions.Commit();
});
RaiseSubscriptionChanged();
}
return true;
}
public bool ConsumeAddInstanceSubscription(
AddInstanceSubscription subscription)
{
pht.Batch(actions =>
{
var message = new MemoryStream();
messageSerializer.Serialize(new[] {subscription}, message);
var itemId = actions.AddItem(new AddItemRequest
{
Key = SubscriptionsKey,
Data = message.ToArray()
});
remoteInstanceSubscriptions.Add(
subscription.InstanceSubscriptionKey,
subscription.Type,
new Uri(subscription.Endpoint),
itemId);
actions.Commit();
});
RaiseSubscriptionChanged();
return true;
}
public bool ConsumeRemoveSubscription(RemoveSubscription removeSubscription)
{
RemoveSubscription(removeSubscription.Type, removeSubscription.Endpoint.Uri.ToString());
return true;
}
public bool ConsumeAddSubscription(AddSubscription addSubscription)
{
var newSubscription = AddSubscription(addSubscription.Type, addSubscription.Endpoint.Uri.ToString());
if (newSubscription && currentlyLoadingPersistentData == false)
{
var itemId = 0;
pht.Batch(actions =>
{
var stream = new MemoryStream();
messageSerializer.Serialize(new[] {addSubscription}, stream);
itemId = actions.AddItem(new AddItemRequest
{
Key = SubscriptionsKey,
Data = stream.ToArray()
});
actions.Commit();
});
AddMessageIdentifierForTracking(
itemId,
addSubscription.Type,
addSubscription.Endpoint.Uri);
return true;
}
return false;
}
private void RaiseSubscriptionChanged()
{
var copy = SubscriptionChanged;
if (copy != null)
copy();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Xunit;
namespace System.IO.MemoryMappedFiles.Tests
{
/// <summary>
/// Tests for MemoryMappedViewAccessor.
/// </summary>
public class MemoryMappedViewAccessorTests : MemoryMappedFilesTestBase
{
/// <summary>
/// Test to validate the offset, size, and access parameters to MemoryMappedFile.CreateViewAccessor.
/// </summary>
[Fact]
public void InvalidArguments()
{
int mapLength = s_pageSize.Value;
foreach (MemoryMappedFile mmf in CreateSampleMaps(mapLength))
{
using (mmf)
{
// Offset
AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => mmf.CreateViewAccessor(-1, mapLength));
AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => mmf.CreateViewAccessor(-1, mapLength, MemoryMappedFileAccess.ReadWrite));
// Size
AssertExtensions.Throws<ArgumentOutOfRangeException>("size", () => mmf.CreateViewAccessor(0, -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("size", () => mmf.CreateViewAccessor(0, -1, MemoryMappedFileAccess.ReadWrite));
if (IntPtr.Size == 4)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("size", () => mmf.CreateViewAccessor(0, 1 + (long)uint.MaxValue));
AssertExtensions.Throws<ArgumentOutOfRangeException>("size", () => mmf.CreateViewAccessor(0, 1 + (long)uint.MaxValue, MemoryMappedFileAccess.ReadWrite));
}
else
{
Assert.Throws<IOException>(() => mmf.CreateViewAccessor(0, long.MaxValue));
Assert.Throws<IOException>(() => mmf.CreateViewAccessor(0, long.MaxValue, MemoryMappedFileAccess.ReadWrite));
}
// Offset + Size
Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor(0, mapLength + 1));
Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor(0, mapLength + 1, MemoryMappedFileAccess.ReadWrite));
Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor(mapLength, 1));
Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor(mapLength, 1, MemoryMappedFileAccess.ReadWrite));
// Access
AssertExtensions.Throws<ArgumentOutOfRangeException>("access", () => mmf.CreateViewAccessor(0, mapLength, (MemoryMappedFileAccess)(-1)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("access", () => mmf.CreateViewAccessor(0, mapLength, (MemoryMappedFileAccess)(42)));
}
}
}
[Theory]
[InlineData(MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.Write)]
[InlineData(MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.ReadWrite)]
[InlineData(MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.CopyOnWrite)]
[InlineData(MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.ReadExecute)]
[InlineData(MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.ReadWriteExecute)]
[InlineData(MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.CopyOnWrite)]
[InlineData(MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.ReadExecute)]
[InlineData(MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.CopyOnWrite)]
[InlineData(MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.Write)]
[InlineData(MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.ReadWrite)]
[InlineData(MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite)]
[InlineData(MemoryMappedFileAccess.Read, MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.Read, MemoryMappedFileAccess.CopyOnWrite)]
public void ValidAccessLevelCombinations(MemoryMappedFileAccess mapAccess, MemoryMappedFileAccess viewAccess)
{
const int Capacity = 4096;
AssertExtensions.ThrowsIf<UnauthorizedAccessException>(PlatformDetection.IsWinRT && (mapAccess == MemoryMappedFileAccess.ReadExecute ||
mapAccess == MemoryMappedFileAccess.ReadWriteExecute ||
viewAccess == MemoryMappedFileAccess.ReadExecute ||
viewAccess == MemoryMappedFileAccess.ReadWriteExecute), () =>
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, Capacity, mapAccess))
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(0, Capacity, viewAccess))
{
ValidateMemoryMappedViewAccessor(acc, Capacity, viewAccess);
}
});
}
[Theory]
[InlineData(MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.Write)]
[InlineData(MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.ReadWrite)]
[InlineData(MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.ReadWriteExecute)]
[InlineData(MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.Write)]
[InlineData(MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.ReadWrite)]
[InlineData(MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.ReadExecute)]
[InlineData(MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.ReadWriteExecute)]
[InlineData(MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.ReadExecute)]
[InlineData(MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.ReadWriteExecute)]
[InlineData(MemoryMappedFileAccess.Read, MemoryMappedFileAccess.Write)]
[InlineData(MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite)]
[InlineData(MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadExecute)]
[InlineData(MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWriteExecute)]
public void InvalidAccessLevelsCombinations(MemoryMappedFileAccess mapAccess, MemoryMappedFileAccess viewAccess)
{
const int Capacity = 4096;
AssertExtensions.ThrowsIf<UnauthorizedAccessException>(PlatformDetection.IsWinRT &&
(mapAccess == MemoryMappedFileAccess.ReadExecute ||
mapAccess == MemoryMappedFileAccess.ReadWriteExecute), () =>
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, Capacity, mapAccess))
{
Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor(0, Capacity, viewAccess));
}
});
}
/// <summary>
/// Test to verify the accessor's PointerOffset.
/// </summary>
[Fact]
public void PointerOffsetMatchesViewStart()
{
const int MapLength = 4096;
foreach (MemoryMappedFile mmf in CreateSampleMaps(MapLength))
{
using (mmf)
{
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor())
{
Assert.Equal(0, acc.PointerOffset);
}
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(0, MapLength))
{
Assert.Equal(0, acc.PointerOffset);
}
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(1, MapLength - 1))
{
Assert.Equal(1, acc.PointerOffset);
}
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(MapLength - 1, 1))
{
Assert.Equal(MapLength - 1, acc.PointerOffset);
}
// On Unix creating a view of size zero will result in an offset and capacity
// of 0 due to mmap behavior, whereas on Windows it's possible to create a
// zero-size view anywhere in the created file mapping.
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(MapLength, 0))
{
Assert.Equal(
RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? MapLength : 0,
acc.PointerOffset);
}
}
}
}
/// <summary>
/// Test all of the Read/Write accessor methods against a variety of maps and accessors.
/// </summary>
[Theory]
[InlineData(0, 8192)]
[InlineData(8100, 92)]
[InlineData(0, 20)]
[InlineData(1, 8191)]
[InlineData(17, 8175)]
[InlineData(17, 20)]
public void AllReadWriteMethods(long offset, long size)
{
foreach (MemoryMappedFile mmf in CreateSampleMaps(8192))
{
using (mmf)
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(offset, size))
{
AssertWritesReads(acc);
}
}
}
/// <summary>Performs many reads and writes of various data types against the accessor.</summary>
private static unsafe void AssertWritesReads(MemoryMappedViewAccessor acc) // TODO: unsafe can be removed once using C# 6 compiler
{
// Successful reads and writes at the beginning for each data type
AssertWriteRead<bool>(false, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadBoolean(pos));
AssertWriteRead<bool>(true, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadBoolean(pos));
AssertWriteRead<byte>(42, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadByte(pos));
AssertWriteRead<char>('c', 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadChar(pos));
AssertWriteRead<decimal>(9, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadDecimal(pos));
AssertWriteRead<double>(10, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadDouble(pos));
AssertWriteRead<short>(11, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadInt16(pos));
AssertWriteRead<int>(12, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadInt32(pos));
AssertWriteRead<long>(13, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadInt64(pos));
AssertWriteRead<sbyte>(14, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadSByte(pos));
AssertWriteRead<float>(15, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadSingle(pos));
AssertWriteRead<ushort>(16, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadUInt16(pos));
AssertWriteRead<uint>(17, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadUInt32(pos));
AssertWriteRead<ulong>(17, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadUInt64(pos));
// Successful reads and writes at the end for each data type
long end = acc.Capacity;
AssertWriteRead<bool>(false, end - sizeof(bool), (pos, value) => acc.Write(pos, value), pos => acc.ReadBoolean(pos));
AssertWriteRead<bool>(true, end - sizeof(bool), (pos, value) => acc.Write(pos, value), pos => acc.ReadBoolean(pos));
AssertWriteRead<byte>(42, end - sizeof(byte), (pos, value) => acc.Write(pos, value), pos => acc.ReadByte(pos));
AssertWriteRead<char>('c', end - sizeof(char), (pos, value) => acc.Write(pos, value), pos => acc.ReadChar(pos));
AssertWriteRead<decimal>(9, end - sizeof(decimal), (pos, value) => acc.Write(pos, value), pos => acc.ReadDecimal(pos));
AssertWriteRead<double>(10, end - sizeof(double), (pos, value) => acc.Write(pos, value), pos => acc.ReadDouble(pos));
AssertWriteRead<short>(11, end - sizeof(short), (pos, value) => acc.Write(pos, value), pos => acc.ReadInt16(pos));
AssertWriteRead<int>(12, end - sizeof(int), (pos, value) => acc.Write(pos, value), pos => acc.ReadInt32(pos));
AssertWriteRead<long>(13, end - sizeof(long), (pos, value) => acc.Write(pos, value), pos => acc.ReadInt64(pos));
AssertWriteRead<sbyte>(14, end - sizeof(sbyte), (pos, value) => acc.Write(pos, value), pos => acc.ReadSByte(pos));
AssertWriteRead<float>(15, end - sizeof(float), (pos, value) => acc.Write(pos, value), pos => acc.ReadSingle(pos));
AssertWriteRead<ushort>(16, end - sizeof(ushort), (pos, value) => acc.Write(pos, value), pos => acc.ReadUInt16(pos));
AssertWriteRead<uint>(17, end - sizeof(uint), (pos, value) => acc.Write(pos, value), pos => acc.ReadUInt32(pos));
AssertWriteRead<ulong>(17, end - sizeof(ulong), (pos, value) => acc.Write(pos, value), pos => acc.ReadUInt64(pos));
// Failed reads and writes just at the border of the end. This triggers different exception types
// for some types than when we're completely beyond the end.
long beyondEnd = acc.Capacity + 1;
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadBoolean(beyondEnd - sizeof(bool)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadByte(beyondEnd - sizeof(byte)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadSByte(beyondEnd - sizeof(sbyte)));
AssertExtensions.Throws<ArgumentException>("position", () => acc.ReadChar(beyondEnd - sizeof(char)));
AssertExtensions.Throws<ArgumentException>("position", () => acc.ReadDecimal(beyondEnd - sizeof(decimal)));
AssertExtensions.Throws<ArgumentException>("position", () => acc.ReadDouble(beyondEnd - sizeof(double)));
AssertExtensions.Throws<ArgumentException>("position", () => acc.ReadInt16(beyondEnd - sizeof(short)));
AssertExtensions.Throws<ArgumentException>("position", () => acc.ReadInt32(beyondEnd - sizeof(int)));
AssertExtensions.Throws<ArgumentException>("position", () => acc.ReadInt64(beyondEnd - sizeof(long)));
AssertExtensions.Throws<ArgumentException>("position", () => acc.ReadSingle(beyondEnd - sizeof(float)));
AssertExtensions.Throws<ArgumentException>("position", () => acc.ReadUInt16(beyondEnd - sizeof(ushort)));
AssertExtensions.Throws<ArgumentException>("position", () => acc.ReadUInt32(beyondEnd - sizeof(uint)));
AssertExtensions.Throws<ArgumentException>("position", () => acc.ReadUInt64(beyondEnd - sizeof(ulong)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(bool), false));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(byte), (byte)0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(sbyte), (sbyte)0));
AssertExtensions.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(char), 'c'));
AssertExtensions.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(decimal), (decimal)0));
AssertExtensions.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(double), (double)0));
AssertExtensions.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(short), (short)0));
AssertExtensions.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(int), (int)0));
AssertExtensions.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(long), (long)0));
AssertExtensions.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(float), (float)0));
AssertExtensions.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(ushort), (ushort)0));
AssertExtensions.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(uint), (uint)0));
AssertExtensions.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(ulong), (ulong)0));
// Failed reads and writes well past the end
beyondEnd = acc.Capacity + 20;
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadBoolean(beyondEnd - sizeof(bool)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadByte(beyondEnd - sizeof(byte)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadSByte(beyondEnd - sizeof(sbyte)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadChar(beyondEnd - sizeof(char)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadDecimal(beyondEnd - sizeof(decimal)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadDouble(beyondEnd - sizeof(double)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadInt16(beyondEnd - sizeof(short)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadInt32(beyondEnd - sizeof(int)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadInt64(beyondEnd - sizeof(long)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadSingle(beyondEnd - sizeof(float)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadUInt16(beyondEnd - sizeof(ushort)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadUInt32(beyondEnd - sizeof(uint)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadUInt64(beyondEnd - sizeof(ulong)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(bool), false));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(byte), (byte)0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(sbyte), (sbyte)0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(char), 'c'));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(decimal), (decimal)0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(double), (double)0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(short), (short)0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(int), (int)0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(long), (long)0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(float), (float)0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(ushort), (ushort)0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(uint), (uint)0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(ulong), (ulong)0));
}
/// <summary>Performs and verifies a read and write against an accessor.</summary>
/// <typeparam name="T">The type of data being read and written.</typeparam>
/// <param name="expected">The data expected to be read.</param>
/// <param name="position">The position of the read and write.</param>
/// <param name="write">The function to perform the write, handed the position at which to write and the value to write.</param>
/// <param name="read">The function to perform the read, handed the position from which to read and returning the read value.</param>
private static void AssertWriteRead<T>(T expected, long position, Action<long, T> write, Func<long, T> read)
{
write(position, expected);
Assert.Equal(expected, read(position));
}
/// <summary>
/// Test to verify that Flush is supported regardless of the accessor's access level
/// </summary>
[Theory]
[InlineData(MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.Write)]
[InlineData(MemoryMappedFileAccess.ReadWrite)]
[InlineData(MemoryMappedFileAccess.CopyOnWrite)]
public void FlushSupportedOnBothReadAndWriteAccessors(MemoryMappedFileAccess access)
{
const int Capacity = 256;
foreach (MemoryMappedFile mmf in CreateSampleMaps(Capacity))
{
using (mmf)
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(0, Capacity, access))
{
acc.Flush();
}
}
}
/// <summary>
/// Test to validate that multiple accessors over the same map share data appropriately.
/// </summary>
[Fact]
public void ViewsShareData()
{
const int MapLength = 256;
foreach (MemoryMappedFile mmf in CreateSampleMaps(MapLength))
{
using (mmf)
{
// Create two views over the same map, and verify that data
// written to one is readable by the other.
using (MemoryMappedViewAccessor acc1 = mmf.CreateViewAccessor())
using (MemoryMappedViewAccessor acc2 = mmf.CreateViewAccessor())
{
for (int i = 0; i < MapLength; i++)
{
acc1.Write(i, (byte)i);
}
acc1.Flush();
for (int i = 0; i < MapLength; i++)
{
Assert.Equal(i, acc2.ReadByte(i));
}
}
// Then verify that after those views have been disposed of,
// we can create another view and still read the same data.
using (MemoryMappedViewAccessor acc3 = mmf.CreateViewAccessor())
{
for (int i = 0; i < MapLength; i++)
{
Assert.Equal(i, acc3.ReadByte(i));
}
}
// Finally, make sure such data is also visible to a stream view
// created subsequently from the same map.
using (MemoryMappedViewStream stream4 = mmf.CreateViewStream())
{
for (int i = 0; i < MapLength; i++)
{
Assert.Equal(i, stream4.ReadByte());
}
}
}
}
}
/// <summary>
/// Test to verify copy-on-write behavior of accessors.
/// </summary>
[Fact]
public void CopyOnWrite()
{
const int MapLength = 256;
foreach (MemoryMappedFile mmf in CreateSampleMaps(MapLength))
{
using (mmf)
{
// Create a normal view, make sure the original data is there, then write some new data.
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(0, MapLength, MemoryMappedFileAccess.ReadWrite))
{
Assert.Equal(0, acc.ReadInt32(0));
acc.Write(0, 42);
}
// In a CopyOnWrite view, verify the previously written data is there, then write some new data
// and verify it's visible through this view.
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(0, MapLength, MemoryMappedFileAccess.CopyOnWrite))
{
Assert.Equal(42, acc.ReadInt32(0));
acc.Write(0, 84);
Assert.Equal(84, acc.ReadInt32(0));
}
// Finally, verify that the CopyOnWrite data is not visible to others using the map.
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(0, MapLength, MemoryMappedFileAccess.Read))
{
Assert.Equal(42, acc.ReadInt32(0));
}
}
}
}
/// <summary>
/// Test to verify that we can dispose of an accessor multiple times.
/// </summary>
[Fact]
public void DisposeMultipleTimes()
{
foreach (MemoryMappedFile mmf in CreateSampleMaps())
{
using (mmf)
{
MemoryMappedViewAccessor acc = mmf.CreateViewAccessor();
acc.Dispose();
acc.Dispose();
}
}
}
/// <summary>
/// Test to verify that a view becomes unusable after it's been disposed.
/// </summary>
[Fact]
public void InvalidAfterDisposal()
{
foreach (MemoryMappedFile mmf in CreateSampleMaps())
{
using (mmf)
{
MemoryMappedViewAccessor acc = mmf.CreateViewAccessor();
SafeMemoryMappedViewHandle handle = acc.SafeMemoryMappedViewHandle;
Assert.False(handle.IsClosed);
acc.Dispose();
Assert.True(handle.IsClosed);
Assert.Throws<ObjectDisposedException>(() => acc.ReadByte(0));
Assert.Throws<ObjectDisposedException>(() => acc.Write(0, (byte)0));
Assert.Throws<ObjectDisposedException>(() => acc.Flush());
}
}
}
/// <summary>
/// Test to verify that we can still use a view after the associated map has been disposed.
/// </summary>
[Fact]
public void UseAfterMMFDisposal()
{
foreach (MemoryMappedFile mmf in CreateSampleMaps(8192))
{
// Create the view, then dispose of the map
MemoryMappedViewAccessor acc;
using (mmf) acc = mmf.CreateViewAccessor();
// Validate we can still use the view
ValidateMemoryMappedViewAccessor(acc, 8192, MemoryMappedFileAccess.ReadWrite);
acc.Dispose();
}
}
/// <summary>
/// Test to allow a map and view to be finalized, just to ensure we don't crash.
/// </summary>
[Fact]
public void AllowFinalization()
{
// Explicitly do not dispose, to allow finalization to happen, just to try to verify
// that nothing fails/throws when it does.
WeakReference<MemoryMappedFile> mmfWeak;
WeakReference<MemoryMappedViewAccessor> mmvaWeak;
CreateWeakMmfAndMmva(out mmfWeak, out mmvaWeak);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
MemoryMappedFile mmf;
Assert.False(mmfWeak.TryGetTarget(out mmf));
MemoryMappedViewAccessor mmva;
Assert.False(mmvaWeak.TryGetTarget(out mmva));
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void CreateWeakMmfAndMmva(out WeakReference<MemoryMappedFile> mmfWeak, out WeakReference<MemoryMappedViewAccessor> mmvaWeak)
{
MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, 4096);
MemoryMappedViewAccessor acc = mmf.CreateViewAccessor();
mmfWeak = new WeakReference<MemoryMappedFile>(mmf);
mmvaWeak = new WeakReference<MemoryMappedViewAccessor>(acc);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.Build.ManagedReference.BuildOutputs
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using Newtonsoft.Json;
using YamlDotNet.Serialization;
using Microsoft.DocAsCode.Common;
using Microsoft.DocAsCode.DataContracts.Common;
using Microsoft.DocAsCode.DataContracts.ManagedReference;
using Microsoft.DocAsCode.YamlSerialization;
[Serializable]
public class ApiReferenceBuildOutput
{
[YamlMember(Alias = "uid")]
[JsonProperty("uid")]
public string Uid { get; set; }
[YamlMember(Alias = "isEii")]
[JsonProperty("isEii")]
public bool IsExplicitInterfaceImplementation { get; set; }
[YamlMember(Alias = "isExtensionMethod")]
[JsonProperty("isExtensionMethod")]
public bool IsExtensionMethod { get; set; }
[YamlMember(Alias = "parent")]
[JsonProperty("parent")]
public string Parent { get; set; }
[YamlMember(Alias = "definition")]
[JsonProperty("definition")]
public string Definition { get; set; }
[JsonProperty("isExternal")]
[YamlMember(Alias = "isExternal")]
public bool? IsExternal { get; set; }
[YamlMember(Alias = "href")]
[JsonProperty("href")]
public string Href { get; set; }
[YamlMember(Alias = "name")]
[JsonProperty("name")]
public List<ApiLanguageValuePair> Name { get; set; }
[YamlMember(Alias = "nameWithType")]
[JsonProperty("nameWithType")]
public List<ApiLanguageValuePair> NameWithType { get; set; }
[YamlMember(Alias = "fullName")]
[JsonProperty("fullName")]
public List<ApiLanguageValuePair> FullName { get; set; }
[YamlMember(Alias = "specName")]
[JsonProperty("specName")]
public List<ApiLanguageValuePair> Spec { get; set; }
[YamlMember(Alias = "syntax")]
[JsonProperty("syntax")]
public ApiSyntaxBuildOutput Syntax { get; set; }
[YamlMember(Alias = "source")]
[JsonProperty("source")]
public SourceDetail Source { get; set; }
[YamlMember(Alias = "documentation")]
[JsonProperty("documentation")]
public SourceDetail Documentation { get; set; }
[YamlMember(Alias = "assemblies")]
[JsonProperty("assemblies")]
public List<string> AssemblyNameList { get; set; }
[YamlMember(Alias = "namespace")]
[JsonProperty("namespace")]
public string NamespaceName { get; set; }
[YamlMember(Alias = "remarks")]
[JsonProperty("remarks")]
public string Remarks { get; set; }
[YamlMember(Alias = "example")]
[JsonProperty("example")]
public List<string> Examples { get; set; }
[YamlMember(Alias = "overridden")]
[JsonProperty("overridden")]
public ApiNames Overridden { get; set; }
[YamlMember(Alias = "overload")]
[JsonProperty("overload")]
public ApiNames Overload { get; set; }
[YamlMember(Alias = "exceptions")]
[JsonProperty("exceptions")]
public List<ApiExceptionInfoBuildOutput> Exceptions { get; set; }
[YamlMember(Alias = "seealso")]
[JsonProperty("seealso")]
public List<ApiLinkInfoBuildOutput> SeeAlsos { get; set; }
[YamlMember(Alias = "see")]
[JsonProperty("see")]
public List<ApiLinkInfoBuildOutput> Sees { get; set; }
[YamlMember(Alias = "inheritance")]
[JsonProperty("inheritance")]
public List<ApiReferenceBuildOutput> Inheritance { get; set; }
[YamlMember(Alias = "level")]
[JsonProperty("level")]
public int Level { get { return Inheritance != null ? Inheritance.Count : 0; } }
[YamlMember(Alias = "implements")]
[JsonProperty("implements")]
public List<ApiNames> Implements { get; set; }
[YamlMember(Alias = "inheritedMembers")]
[JsonProperty("inheritedMembers")]
public List<string> InheritedMembers { get; set; }
[YamlMember(Alias = "extensionMethods")]
[JsonProperty("extensionMethods")]
public List<string> ExtensionMethods { get; set; }
[ExtensibleMember(Constants.ExtensionMemberPrefix.Modifiers)]
[JsonIgnore]
public SortedList<string, List<string>> Modifiers { get; set; } = new SortedList<string, List<string>>();
[YamlMember(Alias = "conceptual")]
[JsonProperty("conceptual")]
public string Conceptual { get; set; }
[YamlMember(Alias = "attributes")]
[JsonProperty("attributes")]
public List<AttributeInfo> Attributes { get; set; }
[YamlMember(Alias = "index")]
[JsonProperty("index")]
public int? Index { get; set; }
[ExtensibleMember]
[JsonIgnore]
public Dictionary<string, object> Metadata { get; set; } = new Dictionary<string, object>();
[EditorBrowsable(EditorBrowsableState.Never)]
[YamlIgnore]
[JsonExtensionData]
public CompositeDictionary MetadataJson =>
CompositeDictionary
.CreateBuilder()
.Add(Constants.ExtensionMemberPrefix.Modifiers, Modifiers, JTokenConverter.Convert<List<string>>)
.Add(string.Empty, Metadata)
.Create();
private bool _needExpand = true;
public static ApiReferenceBuildOutput FromUid(string uid)
{
if (string.IsNullOrEmpty(uid)) return null;
return new ApiReferenceBuildOutput
{
Uid = uid,
};
}
public static ApiReferenceBuildOutput FromModel(ReferenceViewModel vm, string[] supportedLanguages)
{
if (vm == null) return null;
// TODO: may lead to potential problems with have vm.Additional["syntax"] as SyntaxDetailViewModel
// It is now working as syntax is set only in FillReferenceInformation and not from YAML deserialization
var result = new ApiReferenceBuildOutput
{
Uid = vm.Uid,
Parent = vm.Parent,
Definition = vm.Definition,
IsExternal = vm.IsExternal,
Href = vm.Href,
Name = ApiBuildOutputUtility.TransformToLanguagePairList(vm.Name, vm.NameInDevLangs, supportedLanguages),
NameWithType = ApiBuildOutputUtility.TransformToLanguagePairList(vm.NameWithType, vm.NameWithTypeInDevLangs, supportedLanguages),
FullName = ApiBuildOutputUtility.TransformToLanguagePairList(vm.FullName, vm.FullNameInDevLangs, supportedLanguages),
Spec = GetSpecNames(ApiBuildOutputUtility.GetXref(vm.Uid, vm.Name, vm.FullName), supportedLanguages, vm.Specs),
Metadata = vm.Additional,
};
object syntax;
if (result.Metadata.TryGetValue("syntax", out syntax))
{
result.Syntax = ApiSyntaxBuildOutput.FromModel(syntax as SyntaxDetailViewModel, supportedLanguages);
result.Metadata.Remove("syntax");
}
return result;
}
public static ApiReferenceBuildOutput FromModel(ItemViewModel vm)
{
if (vm == null) return null;
var output = new ApiReferenceBuildOutput
{
Uid = vm.Uid,
IsExplicitInterfaceImplementation = vm.IsExplicitInterfaceImplementation,
IsExtensionMethod = vm.IsExtensionMethod,
Parent = vm.Parent,
IsExternal = false,
Href = vm.Href,
Name = ApiBuildOutputUtility.TransformToLanguagePairList(vm.Name, vm.Names, vm.SupportedLanguages),
NameWithType = ApiBuildOutputUtility.TransformToLanguagePairList(vm.NameWithType, vm.NamesWithType, vm.SupportedLanguages),
FullName = ApiBuildOutputUtility.TransformToLanguagePairList(vm.FullName, vm.FullNames, vm.SupportedLanguages),
Spec = GetSpecNames(ApiBuildOutputUtility.GetXref(vm.Uid, vm.Name, vm.FullName), vm.SupportedLanguages),
Source = vm.Source,
Documentation = vm.Documentation,
AssemblyNameList = vm.AssemblyNameList,
NamespaceName = vm.NamespaceName,
Remarks = vm.Remarks,
Examples = vm.Examples,
Overridden = ApiNames.FromUid(vm.Overridden),
Overload = ApiNames.FromUid(vm.Overload),
SeeAlsos = vm.SeeAlsos?.Select(ApiLinkInfoBuildOutput.FromModel).ToList(),
Sees = vm.Sees?.Select(ApiLinkInfoBuildOutput.FromModel).ToList(),
Inheritance = vm.Inheritance?.Select(FromUid).ToList(),
Implements = vm.Implements?.Select(ApiNames.FromUid).ToList(),
InheritedMembers = vm.InheritedMembers,
ExtensionMethods = vm.ExtensionMethods,
Modifiers = vm.Modifiers,
Conceptual = vm.Conceptual,
Metadata = vm.Metadata,
Attributes = vm.Attributes,
Syntax = ApiSyntaxBuildOutput.FromModel(vm.Syntax, vm.SupportedLanguages),
Exceptions = vm.Exceptions?.Select(ApiExceptionInfoBuildOutput.FromModel).ToList(),
};
output.Metadata["type"] = vm.Type;
output.Metadata["summary"] = vm.Summary;
output.Metadata["platform"] = vm.Platform;
return output;
}
public void Expand(Dictionary<string, ApiReferenceBuildOutput> references, string[] supportedLanguages)
{
if (_needExpand)
{
_needExpand = false;
Inheritance = Inheritance?.Select(i => ApiBuildOutputUtility.GetReferenceViewModel(i.Uid, references, supportedLanguages)).ToList();
Implements = Implements?.Select(i => ApiBuildOutputUtility.GetApiNames(i.Uid, references, supportedLanguages)).ToList();
Syntax?.Expand(references, supportedLanguages);
Overridden = ApiBuildOutputUtility.GetApiNames(Overridden?.Uid, references, supportedLanguages);
SeeAlsos?.ForEach(e => e.Expand(references, supportedLanguages));
Sees?.ForEach(e => e.Expand(references, supportedLanguages));
Exceptions?.ForEach(e => e.Expand(references, supportedLanguages));
Overload = ApiBuildOutputUtility.GetApiNames(Overload?.Uid, references, supportedLanguages);
}
}
public static List<ApiLanguageValuePair> GetSpecNames(string xref, string[] supportedLanguages, SortedList<string, List<SpecViewModel>> specs = null)
{
if (specs != null && specs.Count > 0)
{
return specs.Where(kv => supportedLanguages.Contains(kv.Key)).Select(kv => new ApiLanguageValuePair() { Language = kv.Key, Value = GetSpecName(kv.Value) }).ToList();
}
if (!string.IsNullOrEmpty(xref))
{
return supportedLanguages.Select(s => new ApiLanguageValuePair() { Language = s, Value = xref }).ToList();
}
return null;
}
private static string GetSpecName(List<SpecViewModel> spec)
{
if (spec == null) return null;
return string.Concat(spec.Select(GetCompositeName));
}
private static string GetCompositeName(SpecViewModel svm)
{
// If href does not exists, return full name
if (string.IsNullOrEmpty(svm.Uid)) { return System.Web.HttpUtility.HtmlEncode(svm.FullName); }
// If href exists, return name with href
return ApiBuildOutputUtility.GetXref(svm.Uid, svm.Name, svm.FullName);
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Extensions.TypeExtensions;
using osu.Framework.Screens;
using osu.Framework.Utils;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Replays;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Types;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.Replays;
using osu.Game.Rulesets.Replays;
using osu.Game.Rulesets.Scoring;
using osu.Game.Scoring;
using osu.Game.Screens.Play;
using osu.Game.Tests.Visual;
using osuTK;
namespace osu.Game.Rulesets.Osu.Tests
{
public class TestSceneStartTimeOrderedHitPolicy : RateAdjustedBeatmapTestScene
{
private const double early_miss_window = 1000; // time after -1000 to -500 is considered a miss
private const double late_miss_window = 500; // time after +500 is considered a miss
/// <summary>
/// Tests clicking a future circle before the first circle's start time, while the first circle HAS NOT been judged.
/// </summary>
[Test]
public void TestClickSecondCircleBeforeFirstCircleTime()
{
const double time_first_circle = 1500;
const double time_second_circle = 1600;
Vector2 positionFirstCircle = Vector2.Zero;
Vector2 positionSecondCircle = new Vector2(80);
var hitObjects = new List<OsuHitObject>
{
new TestHitCircle
{
StartTime = time_first_circle,
Position = positionFirstCircle
},
new TestHitCircle
{
StartTime = time_second_circle,
Position = positionSecondCircle
}
};
performTest(hitObjects, new List<ReplayFrame>
{
new OsuReplayFrame { Time = time_first_circle - 100, Position = positionSecondCircle, Actions = { OsuAction.LeftButton } }
});
addJudgementAssert(hitObjects[0], HitResult.Miss);
addJudgementAssert(hitObjects[1], HitResult.Miss);
addJudgementOffsetAssert(hitObjects[0], late_miss_window);
}
/// <summary>
/// Tests clicking a future circle at the first circle's start time, while the first circle HAS NOT been judged.
/// </summary>
[Test]
public void TestClickSecondCircleAtFirstCircleTime()
{
const double time_first_circle = 1500;
const double time_second_circle = 1600;
Vector2 positionFirstCircle = Vector2.Zero;
Vector2 positionSecondCircle = new Vector2(80);
var hitObjects = new List<OsuHitObject>
{
new TestHitCircle
{
StartTime = time_first_circle,
Position = positionFirstCircle
},
new TestHitCircle
{
StartTime = time_second_circle,
Position = positionSecondCircle
}
};
performTest(hitObjects, new List<ReplayFrame>
{
new OsuReplayFrame { Time = time_first_circle, Position = positionSecondCircle, Actions = { OsuAction.LeftButton } }
});
addJudgementAssert(hitObjects[0], HitResult.Miss);
addJudgementAssert(hitObjects[1], HitResult.Great);
addJudgementOffsetAssert(hitObjects[0], 0);
}
/// <summary>
/// Tests clicking a future circle after the first circle's start time, while the first circle HAS NOT been judged.
/// </summary>
[Test]
public void TestClickSecondCircleAfterFirstCircleTime()
{
const double time_first_circle = 1500;
const double time_second_circle = 1600;
Vector2 positionFirstCircle = Vector2.Zero;
Vector2 positionSecondCircle = new Vector2(80);
var hitObjects = new List<OsuHitObject>
{
new TestHitCircle
{
StartTime = time_first_circle,
Position = positionFirstCircle
},
new TestHitCircle
{
StartTime = time_second_circle,
Position = positionSecondCircle
}
};
performTest(hitObjects, new List<ReplayFrame>
{
new OsuReplayFrame { Time = time_first_circle + 100, Position = positionSecondCircle, Actions = { OsuAction.LeftButton } }
});
addJudgementAssert(hitObjects[0], HitResult.Miss);
addJudgementAssert(hitObjects[1], HitResult.Great);
addJudgementOffsetAssert(hitObjects[0], 100);
}
/// <summary>
/// Tests clicking a future circle before the first circle's start time, while the first circle HAS been judged.
/// </summary>
[Test]
public void TestClickSecondCircleBeforeFirstCircleTimeWithFirstCircleJudged()
{
const double time_first_circle = 1500;
const double time_second_circle = 1600;
Vector2 positionFirstCircle = Vector2.Zero;
Vector2 positionSecondCircle = new Vector2(80);
var hitObjects = new List<OsuHitObject>
{
new TestHitCircle
{
StartTime = time_first_circle,
Position = positionFirstCircle
},
new TestHitCircle
{
StartTime = time_second_circle,
Position = positionSecondCircle
}
};
performTest(hitObjects, new List<ReplayFrame>
{
new OsuReplayFrame { Time = time_first_circle - 200, Position = positionFirstCircle, Actions = { OsuAction.LeftButton } },
new OsuReplayFrame { Time = time_first_circle - 100, Position = positionSecondCircle, Actions = { OsuAction.RightButton } }
});
addJudgementAssert(hitObjects[0], HitResult.Great);
addJudgementAssert(hitObjects[1], HitResult.Great);
addJudgementOffsetAssert(hitObjects[0], -200); // time_first_circle - 200
addJudgementOffsetAssert(hitObjects[1], -200); // time_second_circle - first_circle_time - 100
}
/// <summary>
/// Tests clicking a future circle after a slider's start time, but hitting all slider ticks.
/// </summary>
[Test]
public void TestMissSliderHeadAndHitAllSliderTicks()
{
const double time_slider = 1500;
const double time_circle = 1510;
Vector2 positionCircle = Vector2.Zero;
Vector2 positionSlider = new Vector2(80);
var hitObjects = new List<OsuHitObject>
{
new TestHitCircle
{
StartTime = time_circle,
Position = positionCircle
},
new TestSlider
{
StartTime = time_slider,
Position = positionSlider,
Path = new SliderPath(PathType.Linear, new[]
{
Vector2.Zero,
new Vector2(25, 0),
})
}
};
performTest(hitObjects, new List<ReplayFrame>
{
new OsuReplayFrame { Time = time_slider, Position = positionCircle, Actions = { OsuAction.LeftButton } },
new OsuReplayFrame { Time = time_slider + 10, Position = positionSlider, Actions = { OsuAction.RightButton } }
});
addJudgementAssert(hitObjects[0], HitResult.Great);
addJudgementAssert(hitObjects[1], HitResult.IgnoreHit);
addJudgementAssert("slider head", () => ((Slider)hitObjects[1]).HeadCircle, HitResult.Miss);
addJudgementAssert("slider tick", () => ((Slider)hitObjects[1]).NestedHitObjects[1] as SliderTick, HitResult.LargeTickHit);
}
/// <summary>
/// Tests clicking hitting future slider ticks before a circle.
/// </summary>
[Test]
public void TestHitSliderTicksBeforeCircle()
{
const double time_slider = 1500;
const double time_circle = 1510;
Vector2 positionCircle = Vector2.Zero;
Vector2 positionSlider = new Vector2(30);
var hitObjects = new List<OsuHitObject>
{
new TestHitCircle
{
StartTime = time_circle,
Position = positionCircle
},
new TestSlider
{
StartTime = time_slider,
Position = positionSlider,
Path = new SliderPath(PathType.Linear, new[]
{
Vector2.Zero,
new Vector2(25, 0),
})
}
};
performTest(hitObjects, new List<ReplayFrame>
{
new OsuReplayFrame { Time = time_slider, Position = positionSlider, Actions = { OsuAction.LeftButton } },
new OsuReplayFrame { Time = time_circle + late_miss_window - 100, Position = positionCircle, Actions = { OsuAction.RightButton } },
new OsuReplayFrame { Time = time_circle + late_miss_window - 90, Position = positionSlider, Actions = { OsuAction.LeftButton } },
});
addJudgementAssert(hitObjects[0], HitResult.Great);
addJudgementAssert(hitObjects[1], HitResult.IgnoreHit);
addJudgementAssert("slider head", () => ((Slider)hitObjects[1]).HeadCircle, HitResult.Great);
addJudgementAssert("slider tick", () => ((Slider)hitObjects[1]).NestedHitObjects[1] as SliderTick, HitResult.LargeTickHit);
}
/// <summary>
/// Tests clicking a future circle before a spinner.
/// </summary>
[Test]
public void TestHitCircleBeforeSpinner()
{
const double time_spinner = 1500;
const double time_circle = 1800;
Vector2 positionCircle = Vector2.Zero;
var hitObjects = new List<OsuHitObject>
{
new TestSpinner
{
StartTime = time_spinner,
Position = new Vector2(256, 192),
EndTime = time_spinner + 1000,
},
new TestHitCircle
{
StartTime = time_circle,
Position = positionCircle
},
};
performTest(hitObjects, new List<ReplayFrame>
{
new OsuReplayFrame { Time = time_spinner - 100, Position = positionCircle, Actions = { OsuAction.LeftButton } },
new OsuReplayFrame { Time = time_spinner + 10, Position = new Vector2(236, 192), Actions = { OsuAction.RightButton } },
new OsuReplayFrame { Time = time_spinner + 20, Position = new Vector2(256, 172), Actions = { OsuAction.RightButton } },
new OsuReplayFrame { Time = time_spinner + 30, Position = new Vector2(276, 192), Actions = { OsuAction.RightButton } },
new OsuReplayFrame { Time = time_spinner + 40, Position = new Vector2(256, 212), Actions = { OsuAction.RightButton } },
new OsuReplayFrame { Time = time_spinner + 50, Position = new Vector2(236, 192), Actions = { OsuAction.RightButton } },
});
addJudgementAssert(hitObjects[0], HitResult.Great);
addJudgementAssert(hitObjects[1], HitResult.Great);
}
[Test]
public void TestHitSliderHeadBeforeHitCircle()
{
const double time_circle = 1000;
const double time_slider = 1200;
Vector2 positionCircle = Vector2.Zero;
Vector2 positionSlider = new Vector2(80);
var hitObjects = new List<OsuHitObject>
{
new TestHitCircle
{
StartTime = time_circle,
Position = positionCircle
},
new TestSlider
{
StartTime = time_slider,
Position = positionSlider,
Path = new SliderPath(PathType.Linear, new[]
{
Vector2.Zero,
new Vector2(25, 0),
})
}
};
performTest(hitObjects, new List<ReplayFrame>
{
new OsuReplayFrame { Time = time_circle - 100, Position = positionSlider, Actions = { OsuAction.LeftButton } },
new OsuReplayFrame { Time = time_circle, Position = positionCircle, Actions = { OsuAction.RightButton } },
new OsuReplayFrame { Time = time_slider, Position = positionSlider, Actions = { OsuAction.LeftButton } },
});
addJudgementAssert(hitObjects[0], HitResult.Great);
addJudgementAssert(hitObjects[1], HitResult.IgnoreHit);
}
private void addJudgementAssert(OsuHitObject hitObject, HitResult result)
{
AddAssert($"({hitObject.GetType().ReadableName()} @ {hitObject.StartTime}) judgement is {result}",
() => judgementResults.Single(r => r.HitObject == hitObject).Type == result);
}
private void addJudgementAssert(string name, Func<OsuHitObject> hitObject, HitResult result)
{
AddAssert($"{name} judgement is {result}",
() => judgementResults.Single(r => r.HitObject == hitObject()).Type == result);
}
private void addJudgementOffsetAssert(OsuHitObject hitObject, double offset)
{
AddAssert($"({hitObject.GetType().ReadableName()} @ {hitObject.StartTime}) judged at {offset}",
() => Precision.AlmostEquals(judgementResults.Single(r => r.HitObject == hitObject).TimeOffset, offset, 100));
}
private ScoreAccessibleReplayPlayer currentPlayer;
private List<JudgementResult> judgementResults;
private void performTest(List<OsuHitObject> hitObjects, List<ReplayFrame> frames)
{
AddStep("load player", () =>
{
Beatmap.Value = CreateWorkingBeatmap(new Beatmap<OsuHitObject>
{
HitObjects = hitObjects,
BeatmapInfo =
{
BaseDifficulty = new BeatmapDifficulty { SliderTickRate = 3 },
Ruleset = new OsuRuleset().RulesetInfo
},
});
Beatmap.Value.Beatmap.ControlPointInfo.Add(0, new DifficultyControlPoint { SpeedMultiplier = 0.1f });
var p = new ScoreAccessibleReplayPlayer(new Score { Replay = new Replay { Frames = frames } });
p.OnLoadComplete += _ =>
{
p.ScoreProcessor.NewJudgement += result =>
{
if (currentPlayer == p) judgementResults.Add(result);
};
};
LoadScreen(currentPlayer = p);
judgementResults = new List<JudgementResult>();
});
AddUntilStep("Beatmap at 0", () => Beatmap.Value.Track.CurrentTime == 0);
AddUntilStep("Wait until player is loaded", () => currentPlayer.IsCurrentScreen());
AddUntilStep("Wait for completion", () => currentPlayer.ScoreProcessor.HasCompleted.Value);
}
private class TestHitCircle : HitCircle
{
protected override HitWindows CreateHitWindows() => new TestHitWindows();
}
private class TestSlider : Slider
{
public TestSlider()
{
DefaultsApplied += _ =>
{
HeadCircle.HitWindows = new TestHitWindows();
TailCircle.HitWindows = new TestHitWindows();
HeadCircle.HitWindows.SetDifficulty(0);
TailCircle.HitWindows.SetDifficulty(0);
};
}
}
private class TestSpinner : Spinner
{
protected override void ApplyDefaultsToSelf(ControlPointInfo controlPointInfo, BeatmapDifficulty difficulty)
{
base.ApplyDefaultsToSelf(controlPointInfo, difficulty);
SpinsRequired = 1;
}
}
private class TestHitWindows : HitWindows
{
private static readonly DifficultyRange[] ranges =
{
new DifficultyRange(HitResult.Great, 500, 500, 500),
new DifficultyRange(HitResult.Miss, early_miss_window, early_miss_window, early_miss_window),
};
public override bool IsHitResultAllowed(HitResult result) => result == HitResult.Great || result == HitResult.Miss;
protected override DifficultyRange[] GetRanges() => ranges;
}
private class ScoreAccessibleReplayPlayer : ReplayPlayer
{
public new ScoreProcessor ScoreProcessor => base.ScoreProcessor;
protected override bool PauseOnFocusLost => false;
public ScoreAccessibleReplayPlayer(Score score)
: base(score, new PlayerConfiguration
{
AllowPause = false,
ShowResults = false,
})
{
}
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace ApplicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
public partial class NetworkClient : ServiceClient<NetworkClient>, INetworkClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// The subscription credentials which uniquely identify the Microsoft Azure
/// subscription. The subscription ID forms part of the URI for every service
/// call.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IApplicationGatewaysOperations.
/// </summary>
public virtual IApplicationGatewaysOperations ApplicationGateways { get; private set; }
/// <summary>
/// Gets the IExpressRouteCircuitAuthorizationsOperations.
/// </summary>
public virtual IExpressRouteCircuitAuthorizationsOperations ExpressRouteCircuitAuthorizations { get; private set; }
/// <summary>
/// Gets the IExpressRouteCircuitPeeringsOperations.
/// </summary>
public virtual IExpressRouteCircuitPeeringsOperations ExpressRouteCircuitPeerings { get; private set; }
/// <summary>
/// Gets the IExpressRouteCircuitsOperations.
/// </summary>
public virtual IExpressRouteCircuitsOperations ExpressRouteCircuits { get; private set; }
/// <summary>
/// Gets the IExpressRouteServiceProvidersOperations.
/// </summary>
public virtual IExpressRouteServiceProvidersOperations ExpressRouteServiceProviders { get; private set; }
/// <summary>
/// Gets the ILoadBalancersOperations.
/// </summary>
public virtual ILoadBalancersOperations LoadBalancers { get; private set; }
/// <summary>
/// Gets the INetworkInterfacesOperations.
/// </summary>
public virtual INetworkInterfacesOperations NetworkInterfaces { get; private set; }
/// <summary>
/// Gets the INetworkSecurityGroupsOperations.
/// </summary>
public virtual INetworkSecurityGroupsOperations NetworkSecurityGroups { get; private set; }
/// <summary>
/// Gets the ISecurityRulesOperations.
/// </summary>
public virtual ISecurityRulesOperations SecurityRules { get; private set; }
/// <summary>
/// Gets the INetworkWatchersOperations.
/// </summary>
public virtual INetworkWatchersOperations NetworkWatchers { get; private set; }
/// <summary>
/// Gets the IPacketCapturesOperations.
/// </summary>
public virtual IPacketCapturesOperations PacketCaptures { get; private set; }
/// <summary>
/// Gets the IPublicIPAddressesOperations.
/// </summary>
public virtual IPublicIPAddressesOperations PublicIPAddresses { get; private set; }
/// <summary>
/// Gets the IRouteFiltersOperations.
/// </summary>
public virtual IRouteFiltersOperations RouteFilters { get; private set; }
/// <summary>
/// Gets the IRouteFilterRulesOperations.
/// </summary>
public virtual IRouteFilterRulesOperations RouteFilterRules { get; private set; }
/// <summary>
/// Gets the IRouteTablesOperations.
/// </summary>
public virtual IRouteTablesOperations RouteTables { get; private set; }
/// <summary>
/// Gets the IRoutesOperations.
/// </summary>
public virtual IRoutesOperations Routes { get; private set; }
/// <summary>
/// Gets the IBgpServiceCommunitiesOperations.
/// </summary>
public virtual IBgpServiceCommunitiesOperations BgpServiceCommunities { get; private set; }
/// <summary>
/// Gets the IUsagesOperations.
/// </summary>
public virtual IUsagesOperations Usages { get; private set; }
/// <summary>
/// Gets the IVirtualNetworksOperations.
/// </summary>
public virtual IVirtualNetworksOperations VirtualNetworks { get; private set; }
/// <summary>
/// Gets the ISubnetsOperations.
/// </summary>
public virtual ISubnetsOperations Subnets { get; private set; }
/// <summary>
/// Gets the IVirtualNetworkPeeringsOperations.
/// </summary>
public virtual IVirtualNetworkPeeringsOperations VirtualNetworkPeerings { get; private set; }
/// <summary>
/// Gets the IVirtualNetworkGatewaysOperations.
/// </summary>
public virtual IVirtualNetworkGatewaysOperations VirtualNetworkGateways { get; private set; }
/// <summary>
/// Gets the IVirtualNetworkGatewayConnectionsOperations.
/// </summary>
public virtual IVirtualNetworkGatewayConnectionsOperations VirtualNetworkGatewayConnections { get; private set; }
/// <summary>
/// Gets the ILocalNetworkGatewaysOperations.
/// </summary>
public virtual ILocalNetworkGatewaysOperations LocalNetworkGateways { get; private set; }
/// <summary>
/// Initializes a new instance of the NetworkClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected NetworkClient(params DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the NetworkClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected NetworkClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the NetworkClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected NetworkClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the NetworkClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected NetworkClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the NetworkClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public NetworkClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the NetworkClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public NetworkClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the NetworkClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public NetworkClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the NetworkClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public NetworkClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
ApplicationGateways = new ApplicationGatewaysOperations(this);
ExpressRouteCircuitAuthorizations = new ExpressRouteCircuitAuthorizationsOperations(this);
ExpressRouteCircuitPeerings = new ExpressRouteCircuitPeeringsOperations(this);
ExpressRouteCircuits = new ExpressRouteCircuitsOperations(this);
ExpressRouteServiceProviders = new ExpressRouteServiceProvidersOperations(this);
LoadBalancers = new LoadBalancersOperations(this);
NetworkInterfaces = new NetworkInterfacesOperations(this);
NetworkSecurityGroups = new NetworkSecurityGroupsOperations(this);
SecurityRules = new SecurityRulesOperations(this);
NetworkWatchers = new NetworkWatchersOperations(this);
PacketCaptures = new PacketCapturesOperations(this);
PublicIPAddresses = new PublicIPAddressesOperations(this);
RouteFilters = new RouteFiltersOperations(this);
RouteFilterRules = new RouteFilterRulesOperations(this);
RouteTables = new RouteTablesOperations(this);
Routes = new RoutesOperations(this);
BgpServiceCommunities = new BgpServiceCommunitiesOperations(this);
Usages = new UsagesOperations(this);
VirtualNetworks = new VirtualNetworksOperations(this);
Subnets = new SubnetsOperations(this);
VirtualNetworkPeerings = new VirtualNetworkPeeringsOperations(this);
VirtualNetworkGateways = new VirtualNetworkGatewaysOperations(this);
VirtualNetworkGatewayConnections = new VirtualNetworkGatewayConnectionsOperations(this);
LocalNetworkGateways = new LocalNetworkGatewaysOperations(this);
BaseUri = new System.Uri("https://management.azure.com");
AcceptLanguage = "en-US";
LongRunningOperationRetryTimeout = 30;
GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
/// <summary>
/// Checks whether a domain name in the cloudapp.net zone is available for use.
/// </summary>
/// <param name='location'>
/// The location of the domain name.
/// </param>
/// <param name='domainNameLabel'>
/// The domain name to be verified. It must conform to the following regular
/// expression: ^[a-z][a-z0-9-]{1,61}[a-z0-9]$.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<DnsNameAvailabilityResult>> CheckDnsNameAvailabilityWithHttpMessagesAsync(string location, string domainNameLabel = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (location == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "location");
}
if (SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("location", location);
tracingParameters.Add("domainNameLabel", domainNameLabel);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CheckDnsNameAvailability", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/CheckDnsNameAvailability").ToString();
_url = _url.Replace("{location}", System.Uri.EscapeDataString(location));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(SubscriptionId));
List<string> _queryParameters = new List<string>();
if (domainNameLabel != null)
{
_queryParameters.Add(string.Format("domainNameLabel={0}", System.Uri.EscapeDataString(domainNameLabel)));
}
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (GenerateClientRequestId != null && GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<DnsNameAvailabilityResult>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<DnsNameAvailabilityResult>(_responseContent, DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// BZip2InputStream.cs
// ------------------------------------------------------------------
//
// Copyright (c) 2011 Dino Chiesa.
// All rights reserved.
//
// This code module is part of DotNetZip, a zipfile class library.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.txt for the license details.
// More info on: http://dotnetzip.codeplex.com
//
// ------------------------------------------------------------------
//
// Last Saved: <2011-July-31 11:57:32>
//
// ------------------------------------------------------------------
//
// This module defines the BZip2InputStream class, which is a decompressing
// stream that handles BZIP2. This code is derived from Apache commons source code.
// The license below applies to the original Apache code.
//
// ------------------------------------------------------------------
/*
* 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.
*/
/*
* This package is based on the work done by Keiron Liddle, Aftex Software
* <keiron@aftexsw.com> to whom the Ant project is very grateful for his
* great code.
*/
// compile: msbuild
// not: csc.exe /t:library /debug+ /out:Ionic.BZip2.dll BZip2InputStream.cs BCRC32.cs Rand.cs
using System;
using System.IO;
namespace Ionic.BZip2
{
/// <summary>
/// A read-only decorator stream that performs BZip2 decompression on Read.
/// </summary>
public class BZip2InputStream : System.IO.Stream
{
private bool _disposed;
private bool _leaveOpen;
private Int64 totalBytesRead;
private int last;
/* for undoing the Burrows-Wheeler transform */
private int origPtr;
// blockSize100k: 0 .. 9.
//
// This var name is a misnomer. The actual block size is 100000
// * blockSize100k. (not 100k * blocksize100k)
private int blockSize100k;
private bool blockRandomised;
private int bsBuff;
private int bsLive;
private readonly Ionic.Crc.CRC32 crc = new Ionic.Crc.CRC32(true);
private int nInUse;
private Stream input;
private int currentChar = -1;
/// <summary>
/// Compressor State
/// </summary>
private enum CState
{
EOF = 0,
START_BLOCK = 1,
RAND_PART_A = 2,
RAND_PART_B = 3,
RAND_PART_C = 4,
NO_RAND_PART_A = 5,
NO_RAND_PART_B = 6,
NO_RAND_PART_C = 7,
}
private CState currentState = CState.START_BLOCK;
private uint storedBlockCRC, storedCombinedCRC;
private uint computedBlockCRC, computedCombinedCRC;
// Variables used by setup* methods exclusively
private int su_count;
private int su_ch2;
private int su_chPrev;
private int su_i2;
private int su_j2;
private int su_rNToGo;
private int su_rTPos;
private int su_tPos;
private char su_z;
private BZip2InputStream.DecompressionState data;
/// <summary>
/// Create a BZip2InputStream, wrapping it around the given input Stream.
/// </summary>
/// <remarks>
/// <para>
/// The input stream will be closed when the BZip2InputStream is closed.
/// </para>
/// </remarks>
/// <param name='input'>The stream from which to read compressed data</param>
public BZip2InputStream(Stream input)
: this(input, false)
{}
/// <summary>
/// Create a BZip2InputStream with the given stream, and
/// specifying whether to leave the wrapped stream open when
/// the BZip2InputStream is closed.
/// </summary>
/// <param name='input'>The stream from which to read compressed data</param>
/// <param name='leaveOpen'>
/// Whether to leave the input stream open, when the BZip2InputStream closes.
/// </param>
///
/// <example>
///
/// This example reads a bzip2-compressed file, decompresses it,
/// and writes the decompressed data into a newly created file.
///
/// <code>
/// var fname = "logfile.log.bz2";
/// using (var fs = File.OpenRead(fname))
/// {
/// using (var decompressor = new Ionic.BZip2.BZip2InputStream(fs))
/// {
/// var outFname = fname + ".decompressed";
/// using (var output = File.Create(outFname))
/// {
/// byte[] buffer = new byte[2048];
/// int n;
/// while ((n = decompressor.Read(buffer, 0, buffer.Length)) > 0)
/// {
/// output.Write(buffer, 0, n);
/// }
/// }
/// }
/// }
/// </code>
/// </example>
public BZip2InputStream(Stream input, bool leaveOpen)
: base()
{
this.input = input;
this._leaveOpen = leaveOpen;
init();
}
/// <summary>
/// Read data from the stream.
/// </summary>
///
/// <remarks>
/// <para>
/// To decompress a BZip2 data stream, create a <c>BZip2InputStream</c>,
/// providing a stream that reads compressed data. Then call Read() on
/// that <c>BZip2InputStream</c>, and the data read will be decompressed
/// as you read.
/// </para>
///
/// <para>
/// A <c>BZip2InputStream</c> can be used only for <c>Read()</c>, not for <c>Write()</c>.
/// </para>
/// </remarks>
///
/// <param name="buffer">The buffer into which the read data should be placed.</param>
/// <param name="offset">the offset within that data array to put the first byte read.</param>
/// <param name="count">the number of bytes to read.</param>
/// <returns>the number of bytes actually read</returns>
public override int Read(byte[] buffer, int offset, int count)
{
if (offset < 0)
throw new IndexOutOfRangeException(String.Format("offset ({0}) must be > 0", offset));
if (count < 0)
throw new IndexOutOfRangeException(String.Format("count ({0}) must be > 0", count));
if (offset + count > buffer.Length)
throw new IndexOutOfRangeException(String.Format("offset({0}) count({1}) bLength({2})",
offset, count, buffer.Length));
if (this.input == null)
throw new IOException("the stream is not open");
int hi = offset + count;
int destOffset = offset;
for (int b; (destOffset < hi) && ((b = ReadByte()) >= 0);)
{
buffer[destOffset++] = (byte) b;
}
return destOffset - offset;
}
private void MakeMaps()
{
bool[] inUse = this.data.inUse;
byte[] seqToUnseq = this.data.seqToUnseq;
int n = 0;
for (int i = 0; i < 256; i++)
{
if (inUse[i])
seqToUnseq[n++] = (byte) i;
}
this.nInUse = n;
}
/// <summary>
/// Read a single byte from the stream.
/// </summary>
/// <returns>the byte read from the stream, or -1 if EOF</returns>
public override int ReadByte()
{
int retChar = this.currentChar;
totalBytesRead++;
switch (this.currentState)
{
case CState.EOF:
return -1;
case CState.START_BLOCK:
throw new IOException("bad state");
case CState.RAND_PART_A:
throw new IOException("bad state");
case CState.RAND_PART_B:
SetupRandPartB();
break;
case CState.RAND_PART_C:
SetupRandPartC();
break;
case CState.NO_RAND_PART_A:
throw new IOException("bad state");
case CState.NO_RAND_PART_B:
SetupNoRandPartB();
break;
case CState.NO_RAND_PART_C:
SetupNoRandPartC();
break;
default:
throw new IOException("bad state");
}
return retChar;
}
/// <summary>
/// Indicates whether the stream can be read.
/// </summary>
/// <remarks>
/// The return value depends on whether the captive stream supports reading.
/// </remarks>
public override bool CanRead
{
get
{
if (_disposed) throw new ObjectDisposedException("BZip2Stream");
return this.input.CanRead;
}
}
/// <summary>
/// Indicates whether the stream supports Seek operations.
/// </summary>
/// <remarks>
/// Always returns false.
/// </remarks>
public override bool CanSeek
{
get { return false; }
}
/// <summary>
/// Indicates whether the stream can be written.
/// </summary>
/// <remarks>
/// The return value depends on whether the captive stream supports writing.
/// </remarks>
public override bool CanWrite
{
get
{
if (_disposed) throw new ObjectDisposedException("BZip2Stream");
return input.CanWrite;
}
}
/// <summary>
/// Flush the stream.
/// </summary>
public override void Flush()
{
if (_disposed) throw new ObjectDisposedException("BZip2Stream");
input.Flush();
}
/// <summary>
/// Reading this property always throws a <see cref="NotImplementedException"/>.
/// </summary>
public override long Length
{
get { throw new NotImplementedException(); }
}
/// <summary>
/// The position of the stream pointer.
/// </summary>
///
/// <remarks>
/// Setting this property always throws a <see
/// cref="NotImplementedException"/>. Reading will return the
/// total number of uncompressed bytes read in.
/// </remarks>
public override long Position
{
get
{
return this.totalBytesRead;
}
set { throw new NotImplementedException(); }
}
/// <summary>
/// Calling this method always throws a <see cref="NotImplementedException"/>.
/// </summary>
/// <param name="offset">this is irrelevant, since it will always throw!</param>
/// <param name="origin">this is irrelevant, since it will always throw!</param>
/// <returns>irrelevant!</returns>
public override long Seek(long offset, System.IO.SeekOrigin origin)
{
throw new NotImplementedException();
}
/// <summary>
/// Calling this method always throws a <see cref="NotImplementedException"/>.
/// </summary>
/// <param name="value">this is irrelevant, since it will always throw!</param>
public override void SetLength(long value)
{
throw new NotImplementedException();
}
/// <summary>
/// Calling this method always throws a <see cref="NotImplementedException"/>.
/// </summary>
/// <param name='buffer'>this parameter is never used</param>
/// <param name='offset'>this parameter is never used</param>
/// <param name='count'>this parameter is never used</param>
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
/// <summary>
/// Dispose the stream.
/// </summary>
/// <param name="disposing">
/// indicates whether the Dispose method was invoked by user code.
/// </param>
protected override void Dispose(bool disposing)
{
try
{
if (!_disposed)
{
if (disposing)
input?.Close();
_disposed = true;
}
}
finally
{
base.Dispose(disposing);
}
}
private void init()
{
if (null == this.input)
throw new IOException("No input Stream");
if (!this.input.CanRead)
throw new IOException("Unreadable input Stream");
CheckMagicChar('B', 0);
CheckMagicChar('Z', 1);
CheckMagicChar('h', 2);
int blockSize = this.input.ReadByte();
if ((blockSize < '1') || (blockSize > '9'))
throw new IOException("Stream is not BZip2 formatted: illegal "
+ "blocksize " + (char) blockSize);
this.blockSize100k = blockSize - '0';
InitBlock();
SetupBlock();
}
private void CheckMagicChar(char expected, int position)
{
int magic = this.input.ReadByte();
if (magic != (int)expected)
{
var msg = String.Format("Not a valid BZip2 stream. byte {0}, expected '{1}', got '{2}'",
position, (int)expected, magic);
throw new IOException(msg);
}
}
private void InitBlock()
{
char magic0 = bsGetUByte();
char magic1 = bsGetUByte();
char magic2 = bsGetUByte();
char magic3 = bsGetUByte();
char magic4 = bsGetUByte();
char magic5 = bsGetUByte();
if (magic0 == 0x17 && magic1 == 0x72 && magic2 == 0x45
&& magic3 == 0x38 && magic4 == 0x50 && magic5 == 0x90)
{
complete(); // end of file
}
else if (magic0 != 0x31 ||
magic1 != 0x41 ||
magic2 != 0x59 ||
magic3 != 0x26 ||
magic4 != 0x53 ||
magic5 != 0x59)
{
this.currentState = CState.EOF;
var msg = String.Format("bad block header at offset 0x{0:X}",
this.input.Position);
throw new IOException(msg);
}
else
{
this.storedBlockCRC = bsGetInt();
// Console.WriteLine(" stored block CRC : {0:X8}", this.storedBlockCRC);
this.blockRandomised = (GetBits(1) == 1);
// Lazily allocate data
if (this.data == null)
this.data = new DecompressionState(this.blockSize100k);
// currBlockNo++;
getAndMoveToFrontDecode();
this.crc.Reset();
this.currentState = CState.START_BLOCK;
}
}
private void EndBlock()
{
this.computedBlockCRC = (uint)this.crc.Crc32Result;
// A bad CRC is considered a fatal error.
if (this.storedBlockCRC != this.computedBlockCRC)
{
// make next blocks readable without error
// (repair feature, not yet documented, not tested)
// this.computedCombinedCRC = (this.storedCombinedCRC << 1)
// | (this.storedCombinedCRC >> 31);
// this.computedCombinedCRC ^= this.storedBlockCRC;
var msg = String.Format("BZip2 CRC error (expected {0:X8}, computed {1:X8})",
this.storedBlockCRC, this.computedBlockCRC);
throw new IOException(msg);
}
// Console.WriteLine(" combined CRC (before): {0:X8}", this.computedCombinedCRC);
this.computedCombinedCRC = (this.computedCombinedCRC << 1)
| (this.computedCombinedCRC >> 31);
this.computedCombinedCRC ^= this.computedBlockCRC;
// Console.WriteLine(" computed block CRC : {0:X8}", this.computedBlockCRC);
// Console.WriteLine(" combined CRC (after) : {0:X8}", this.computedCombinedCRC);
// Console.WriteLine();
}
private void complete()
{
this.storedCombinedCRC = bsGetInt();
this.currentState = CState.EOF;
this.data = null;
if (this.storedCombinedCRC != this.computedCombinedCRC)
{
var msg = String.Format("BZip2 CRC error (expected {0:X8}, computed {1:X8})",
this.storedCombinedCRC, this.computedCombinedCRC);
throw new IOException(msg);
}
}
/// <summary>
/// Close the stream.
/// </summary>
public override void Close()
{
Stream inShadow = this.input;
if (inShadow != null)
{
try
{
if (!this._leaveOpen)
inShadow.Close();
}
finally
{
this.data = null;
this.input = null;
}
}
}
/// <summary>
/// Read n bits from input, right justifying the result.
/// </summary>
/// <remarks>
/// <para>
/// For example, if you read 1 bit, the result is either 0
/// or 1.
/// </para>
/// </remarks>
/// <param name ="n">
/// The number of bits to read, always between 1 and 32.
/// </param>
private int GetBits(int n)
{
int bsLiveShadow = this.bsLive;
int bsBuffShadow = this.bsBuff;
if (bsLiveShadow < n)
{
do
{
int thech = this.input.ReadByte();
if (thech < 0)
throw new IOException("unexpected end of stream");
// Console.WriteLine("R {0:X2}", thech);
bsBuffShadow = (bsBuffShadow << 8) | thech;
bsLiveShadow += 8;
} while (bsLiveShadow < n);
this.bsBuff = bsBuffShadow;
}
this.bsLive = bsLiveShadow - n;
return (bsBuffShadow >> (bsLiveShadow - n)) & ((1 << n) - 1);
}
// private bool bsGetBit()
// {
// int bsLiveShadow = this.bsLive;
// int bsBuffShadow = this.bsBuff;
//
// if (bsLiveShadow < 1)
// {
// int thech = this.input.ReadByte();
//
// if (thech < 0)
// {
// throw new IOException("unexpected end of stream");
// }
//
// bsBuffShadow = (bsBuffShadow << 8) | thech;
// bsLiveShadow += 8;
// this.bsBuff = bsBuffShadow;
// }
//
// this.bsLive = bsLiveShadow - 1;
// return ((bsBuffShadow >> (bsLiveShadow - 1)) & 1) != 0;
// }
private bool bsGetBit()
{
int bit = GetBits(1);
return bit != 0;
}
private char bsGetUByte()
{
return (char) GetBits(8);
}
private uint bsGetInt()
{
return (uint)((((((GetBits(8) << 8) | GetBits(8)) << 8) | GetBits(8)) << 8) | GetBits(8));
}
/**
* Called by createHuffmanDecodingTables() exclusively.
*/
private static void hbCreateDecodeTables(int[] limit,
int[] bbase, int[] perm, char[] length,
int minLen, int maxLen, int alphaSize)
{
for (int i = minLen, pp = 0; i <= maxLen; i++)
{
for (int j = 0; j < alphaSize; j++)
{
if (length[j] == i)
{
perm[pp++] = j;
}
}
}
for (int i = BZip2.MaxCodeLength; --i > 0;)
{
bbase[i] = 0;
limit[i] = 0;
}
for (int i = 0; i < alphaSize; i++)
{
bbase[length[i] + 1]++;
}
for (int i = 1, b = bbase[0]; i < BZip2.MaxCodeLength; i++)
{
b += bbase[i];
bbase[i] = b;
}
for (int i = minLen, vec = 0, b = bbase[i]; i <= maxLen; i++)
{
int nb = bbase[i + 1];
vec += nb - b;
b = nb;
limit[i] = vec - 1;
vec <<= 1;
}
for (int i = minLen + 1; i <= maxLen; i++)
{
bbase[i] = ((limit[i - 1] + 1) << 1) - bbase[i];
}
}
private void recvDecodingTables()
{
var s = this.data;
bool[] inUse = s.inUse;
byte[] pos = s.recvDecodingTables_pos;
//byte[] selector = s.selector;
int inUse16 = 0;
/* Receive the mapping table */
for (int i = 0; i < 16; i++)
{
if (bsGetBit())
{
inUse16 |= 1 << i;
}
}
for (int i = 256; --i >= 0;)
{
inUse[i] = false;
}
for (int i = 0; i < 16; i++)
{
if ((inUse16 & (1 << i)) != 0)
{
int i16 = i << 4;
for (int j = 0; j < 16; j++)
{
if (bsGetBit())
{
inUse[i16 + j] = true;
}
}
}
}
MakeMaps();
int alphaSize = this.nInUse + 2;
/* Now the selectors */
int nGroups = GetBits(3);
int nSelectors = GetBits(15);
for (int i = 0; i < nSelectors; i++)
{
int j = 0;
while (bsGetBit())
{
j++;
}
s.selectorMtf[i] = (byte) j;
}
/* Undo the MTF values for the selectors. */
for (int v = nGroups; --v >= 0;)
{
pos[v] = (byte) v;
}
for (int i = 0; i < nSelectors; i++)
{
int v = s.selectorMtf[i];
byte tmp = pos[v];
while (v > 0)
{
// nearly all times v is zero, 4 in most other cases
pos[v] = pos[v - 1];
v--;
}
pos[0] = tmp;
s.selector[i] = tmp;
}
char[][] len = s.temp_charArray2d;
/* Now the coding tables */
for (int t = 0; t < nGroups; t++)
{
int curr = GetBits(5);
char[] len_t = len[t];
for (int i = 0; i < alphaSize; i++)
{
while (bsGetBit())
{
curr += bsGetBit() ? -1 : 1;
}
len_t[i] = (char) curr;
}
}
// finally create the Huffman tables
createHuffmanDecodingTables(alphaSize, nGroups);
}
/**
* Called by recvDecodingTables() exclusively.
*/
private void createHuffmanDecodingTables(int alphaSize,
int nGroups)
{
var s = this.data;
char[][] len = s.temp_charArray2d;
for (int t = 0; t < nGroups; t++)
{
int minLen = 32;
int maxLen = 0;
char[] len_t = len[t];
for (int i = alphaSize; --i >= 0;)
{
char lent = len_t[i];
if (lent > maxLen)
maxLen = lent;
if (lent < minLen)
minLen = lent;
}
hbCreateDecodeTables(s.gLimit[t], s.gBase[t], s.gPerm[t], len[t], minLen,
maxLen, alphaSize);
s.gMinlen[t] = minLen;
}
}
private void getAndMoveToFrontDecode()
{
var s = this.data;
this.origPtr = GetBits(24);
if (this.origPtr < 0)
throw new IOException("BZ_DATA_ERROR");
if (this.origPtr > 10 + BZip2.BlockSizeMultiple * this.blockSize100k)
throw new IOException("BZ_DATA_ERROR");
recvDecodingTables();
byte[] yy = s.getAndMoveToFrontDecode_yy;
int limitLast = this.blockSize100k * BZip2.BlockSizeMultiple;
/*
* Setting up the unzftab entries here is not strictly necessary, but it
* does save having to do it later in a separate pass, and so saves a
* block's worth of cache misses.
*/
for (int i = 256; --i >= 0;)
{
yy[i] = (byte) i;
s.unzftab[i] = 0;
}
int groupNo = 0;
int groupPos = BZip2.G_SIZE - 1;
int eob = this.nInUse + 1;
int nextSym = getAndMoveToFrontDecode0(0);
int bsBuffShadow = this.bsBuff;
int bsLiveShadow = this.bsLive;
int lastShadow = -1;
int zt = s.selector[groupNo] & 0xff;
int[] base_zt = s.gBase[zt];
int[] limit_zt = s.gLimit[zt];
int[] perm_zt = s.gPerm[zt];
int minLens_zt = s.gMinlen[zt];
while (nextSym != eob)
{
if ((nextSym == BZip2.RUNA) || (nextSym == BZip2.RUNB))
{
int es = -1;
for (int n = 1; true; n <<= 1)
{
if (nextSym == BZip2.RUNA)
{
es += n;
}
else if (nextSym == BZip2.RUNB)
{
es += n << 1;
}
else
{
break;
}
if (groupPos == 0)
{
groupPos = BZip2.G_SIZE - 1;
zt = s.selector[++groupNo] & 0xff;
base_zt = s.gBase[zt];
limit_zt = s.gLimit[zt];
perm_zt = s.gPerm[zt];
minLens_zt = s.gMinlen[zt];
}
else
{
groupPos--;
}
int zn = minLens_zt;
// Inlined:
// int zvec = GetBits(zn);
while (bsLiveShadow < zn)
{
int thech = this.input.ReadByte();
if (thech >= 0)
{
bsBuffShadow = (bsBuffShadow << 8) | thech;
bsLiveShadow += 8;
continue;
}
else
{
throw new IOException("unexpected end of stream");
}
}
int zvec = (bsBuffShadow >> (bsLiveShadow - zn))
& ((1 << zn) - 1);
bsLiveShadow -= zn;
while (zvec > limit_zt[zn])
{
zn++;
while (bsLiveShadow < 1)
{
int thech = this.input.ReadByte();
if (thech >= 0)
{
bsBuffShadow = (bsBuffShadow << 8) | thech;
bsLiveShadow += 8;
continue;
}
else
{
throw new IOException("unexpected end of stream");
}
}
bsLiveShadow--;
zvec = (zvec << 1)
| ((bsBuffShadow >> bsLiveShadow) & 1);
}
nextSym = perm_zt[zvec - base_zt[zn]];
}
byte ch = s.seqToUnseq[yy[0]];
s.unzftab[ch & 0xff] += es + 1;
while (es-- >= 0)
{
s.ll8[++lastShadow] = ch;
}
if (lastShadow >= limitLast)
throw new IOException("block overrun");
}
else
{
if (++lastShadow >= limitLast)
throw new IOException("block overrun");
byte tmp = yy[nextSym - 1];
s.unzftab[s.seqToUnseq[tmp] & 0xff]++;
s.ll8[lastShadow] = s.seqToUnseq[tmp];
/*
* This loop is hammered during decompression, hence avoid
* native method call overhead of System.Buffer.BlockCopy for very
* small ranges to copy.
*/
if (nextSym <= 16)
{
for (int j = nextSym - 1; j > 0;)
{
yy[j] = yy[--j];
}
}
else
{
System.Buffer.BlockCopy(yy, 0, yy, 1, nextSym - 1);
}
yy[0] = tmp;
if (groupPos == 0)
{
groupPos = BZip2.G_SIZE - 1;
zt = s.selector[++groupNo] & 0xff;
base_zt = s.gBase[zt];
limit_zt = s.gLimit[zt];
perm_zt = s.gPerm[zt];
minLens_zt = s.gMinlen[zt];
}
else
{
groupPos--;
}
int zn = minLens_zt;
// Inlined:
// int zvec = GetBits(zn);
while (bsLiveShadow < zn)
{
int thech = this.input.ReadByte();
if (thech >= 0)
{
bsBuffShadow = (bsBuffShadow << 8) | thech;
bsLiveShadow += 8;
continue;
}
else
{
throw new IOException("unexpected end of stream");
}
}
int zvec = (bsBuffShadow >> (bsLiveShadow - zn))
& ((1 << zn) - 1);
bsLiveShadow -= zn;
while (zvec > limit_zt[zn])
{
zn++;
while (bsLiveShadow < 1)
{
int thech = this.input.ReadByte();
if (thech >= 0)
{
bsBuffShadow = (bsBuffShadow << 8) | thech;
bsLiveShadow += 8;
continue;
}
else
{
throw new IOException("unexpected end of stream");
}
}
bsLiveShadow--;
zvec = (zvec << 1) | ((bsBuffShadow >> bsLiveShadow) & 1);
}
nextSym = perm_zt[zvec - base_zt[zn]];
}
}
this.last = lastShadow;
this.bsLive = bsLiveShadow;
this.bsBuff = bsBuffShadow;
}
private int getAndMoveToFrontDecode0(int groupNo)
{
var s = this.data;
int zt = s.selector[groupNo] & 0xff;
int[] limit_zt = s.gLimit[zt];
int zn = s.gMinlen[zt];
int zvec = GetBits(zn);
int bsLiveShadow = this.bsLive;
int bsBuffShadow = this.bsBuff;
while (zvec > limit_zt[zn])
{
zn++;
while (bsLiveShadow < 1)
{
int thech = this.input.ReadByte();
if (thech >= 0)
{
bsBuffShadow = (bsBuffShadow << 8) | thech;
bsLiveShadow += 8;
continue;
}
else
{
throw new IOException("unexpected end of stream");
}
}
bsLiveShadow--;
zvec = (zvec << 1) | ((bsBuffShadow >> bsLiveShadow) & 1);
}
this.bsLive = bsLiveShadow;
this.bsBuff = bsBuffShadow;
return s.gPerm[zt][zvec - s.gBase[zt][zn]];
}
private void SetupBlock()
{
if (this.data == null)
return;
int i;
var s = this.data;
int[] tt = s.initTT(this.last + 1);
// xxxx
/* Check: unzftab entries in range. */
for (i = 0; i <= 255; i++)
{
if (s.unzftab[i] < 0 || s.unzftab[i] > this.last)
throw new Exception("BZ_DATA_ERROR");
}
/* Actually generate cftab. */
s.cftab[0] = 0;
for (i = 1; i <= 256; i++) s.cftab[i] = s.unzftab[i-1];
for (i = 1; i <= 256; i++) s.cftab[i] += s.cftab[i-1];
/* Check: cftab entries in range. */
for (i = 0; i <= 256; i++)
{
if (s.cftab[i] < 0 || s.cftab[i] > this.last+1)
{
var msg = String.Format("BZ_DATA_ERROR: cftab[{0}]={1} last={2}",
i, s.cftab[i], this.last);
throw new Exception(msg);
}
}
/* Check: cftab entries non-descending. */
for (i = 1; i <= 256; i++)
{
if (s.cftab[i-1] > s.cftab[i])
throw new Exception("BZ_DATA_ERROR");
}
int lastShadow;
for (i = 0, lastShadow = this.last; i <= lastShadow; i++)
{
tt[s.cftab[s.ll8[i] & 0xff]++] = i;
}
if ((this.origPtr < 0) || (this.origPtr >= tt.Length))
throw new IOException("stream corrupted");
this.su_tPos = tt[this.origPtr];
this.su_count = 0;
this.su_i2 = 0;
this.su_ch2 = 256; /* not a valid 8-bit byte value?, and not EOF */
if (this.blockRandomised)
{
this.su_rNToGo = 0;
this.su_rTPos = 0;
SetupRandPartA();
}
else
{
SetupNoRandPartA();
}
}
private void SetupRandPartA()
{
if (this.su_i2 <= this.last)
{
this.su_chPrev = this.su_ch2;
int su_ch2Shadow = this.data.ll8[this.su_tPos] & 0xff;
this.su_tPos = this.data.tt[this.su_tPos];
if (this.su_rNToGo == 0)
{
this.su_rNToGo = Rand.Rnums(this.su_rTPos) - 1;
if (++this.su_rTPos == 512)
{
this.su_rTPos = 0;
}
}
else
{
this.su_rNToGo--;
}
this.su_ch2 = su_ch2Shadow ^= (this.su_rNToGo == 1) ? 1 : 0;
this.su_i2++;
this.currentChar = su_ch2Shadow;
this.currentState = CState.RAND_PART_B;
this.crc.UpdateCRC((byte)su_ch2Shadow);
}
else
{
EndBlock();
InitBlock();
SetupBlock();
}
}
private void SetupNoRandPartA()
{
if (this.su_i2 <= this.last)
{
this.su_chPrev = this.su_ch2;
int su_ch2Shadow = this.data.ll8[this.su_tPos] & 0xff;
this.su_ch2 = su_ch2Shadow;
this.su_tPos = this.data.tt[this.su_tPos];
this.su_i2++;
this.currentChar = su_ch2Shadow;
this.currentState = CState.NO_RAND_PART_B;
this.crc.UpdateCRC((byte)su_ch2Shadow);
}
else
{
this.currentState = CState.NO_RAND_PART_A;
EndBlock();
InitBlock();
SetupBlock();
}
}
private void SetupRandPartB()
{
if (this.su_ch2 != this.su_chPrev)
{
this.currentState = CState.RAND_PART_A;
this.su_count = 1;
SetupRandPartA();
}
else if (++this.su_count >= 4)
{
this.su_z = (char) (this.data.ll8[this.su_tPos] & 0xff);
this.su_tPos = this.data.tt[this.su_tPos];
if (this.su_rNToGo == 0)
{
this.su_rNToGo = Rand.Rnums(this.su_rTPos) - 1;
if (++this.su_rTPos == 512)
{
this.su_rTPos = 0;
}
}
else
{
this.su_rNToGo--;
}
this.su_j2 = 0;
this.currentState = CState.RAND_PART_C;
if (this.su_rNToGo == 1)
{
this.su_z ^= (char)1;
}
SetupRandPartC();
}
else
{
this.currentState = CState.RAND_PART_A;
SetupRandPartA();
}
}
private void SetupRandPartC()
{
if (this.su_j2 < this.su_z)
{
this.currentChar = this.su_ch2;
this.crc.UpdateCRC((byte)this.su_ch2);
this.su_j2++;
}
else
{
this.currentState = CState.RAND_PART_A;
this.su_i2++;
this.su_count = 0;
SetupRandPartA();
}
}
private void SetupNoRandPartB()
{
if (this.su_ch2 != this.su_chPrev)
{
this.su_count = 1;
SetupNoRandPartA();
}
else if (++this.su_count >= 4)
{
this.su_z = (char) (this.data.ll8[this.su_tPos] & 0xff);
this.su_tPos = this.data.tt[this.su_tPos];
this.su_j2 = 0;
SetupNoRandPartC();
}
else
{
SetupNoRandPartA();
}
}
private void SetupNoRandPartC()
{
if (this.su_j2 < this.su_z)
{
int su_ch2Shadow = this.su_ch2;
this.currentChar = su_ch2Shadow;
this.crc.UpdateCRC((byte)su_ch2Shadow);
this.su_j2++;
this.currentState = CState.NO_RAND_PART_C;
}
else
{
this.su_i2++;
this.su_count = 0;
SetupNoRandPartA();
}
}
private sealed class DecompressionState
{
// (with blockSize 900k)
public readonly bool[] inUse = new bool[256];
public readonly byte[] seqToUnseq = new byte[256]; // 256 byte
public readonly byte[] selector = new byte[BZip2.MaxSelectors]; // 18002 byte
public readonly byte[] selectorMtf = new byte[BZip2.MaxSelectors]; // 18002 byte
/**
* Freq table collected to save a pass over the data during
* decompression.
*/
public readonly int[] unzftab;
public readonly int[][] gLimit;
public readonly int[][] gBase;
public readonly int[][] gPerm;
public readonly int[] gMinlen;
public readonly int[] cftab;
public readonly byte[] getAndMoveToFrontDecode_yy;
public readonly char[][] temp_charArray2d;
public readonly byte[] recvDecodingTables_pos;
// ---------------
// 60798 byte
public int[] tt; // 3600000 byte
public byte[] ll8; // 900000 byte
// ---------------
// 4560782 byte
// ===============
public DecompressionState(int blockSize100k)
{
this.unzftab = new int[256]; // 1024 byte
this.gLimit = BZip2.InitRectangularArray<int>(BZip2.NGroups,BZip2.MaxAlphaSize);
this.gBase = BZip2.InitRectangularArray<int>(BZip2.NGroups,BZip2.MaxAlphaSize);
this.gPerm = BZip2.InitRectangularArray<int>(BZip2.NGroups,BZip2.MaxAlphaSize);
this.gMinlen = new int[BZip2.NGroups]; // 24 byte
this.cftab = new int[257]; // 1028 byte
this.getAndMoveToFrontDecode_yy = new byte[256]; // 512 byte
this.temp_charArray2d = BZip2.InitRectangularArray<char>(BZip2.NGroups,BZip2.MaxAlphaSize);
this.recvDecodingTables_pos = new byte[BZip2.NGroups]; // 6 byte
this.ll8 = new byte[blockSize100k * BZip2.BlockSizeMultiple];
}
/**
* Initializes the tt array.
*
* This method is called when the required length of the array is known.
* I don't initialize it at construction time to avoid unneccessary
* memory allocation when compressing small files.
*/
public int[] initTT(int length)
{
int[] ttShadow = this.tt;
// tt.length should always be >= length, but theoretically
// it can happen, if the compressor mixed small and large
// blocks. Normally only the last block will be smaller
// than others.
if ((ttShadow == null) || (ttShadow.Length < length))
{
this.tt = ttShadow = new int[length];
}
return ttShadow;
}
}
/// <summary>
/// Dump the current state of the decompressor, to restore it in case of an error.
/// This allows the decompressor to be essentially "rewound" and retried when more
/// data arrives.
///
/// This is only used by IronPython.
/// </summary>
/// <returns>The current state.</returns>
internal object DumpState() {
return new StateDump {
_disposed = _disposed,
totalBytesRead = this.totalBytesRead,
last = this.last,
origPtr = this.origPtr,
blockRandomised = this.blockRandomised,
bsBuff = this.bsBuff,
bsLive = this.bsLive,
nInUse = this.nInUse,
currentChar = this.currentChar,
currentState = this.currentState,
storedBlockCRC = this.storedBlockCRC,
storedCombinedCRC = this.storedCombinedCRC,
computedBlockCRC = this.computedBlockCRC,
computedCombinedCRC = this.computedCombinedCRC,
su_count = this.su_count,
su_ch2 = this.su_ch2,
su_chPrev = this.su_chPrev,
su_i2 = this.su_i2,
su_j2 = this.su_j2,
su_rNToGo = this.su_rNToGo,
su_rTPos = this.su_rTPos,
su_tPos = this.su_tPos,
su_z = this.su_z,
};
}
/// <summary>
/// Restore the internal compressor state if an error occurred.
/// </summary>
/// <param name="o">The old state.</param>
internal void RestoreState(object o) {
StateDump s = (StateDump)o;
this._disposed = s._disposed;
this.totalBytesRead = s.totalBytesRead;
this.last = s.last;
this.origPtr = s.origPtr;
this.bsBuff = s.bsBuff;
this.bsLive = s.bsLive;
this.nInUse = s.nInUse;
this.currentChar = s.currentChar;
this.currentState = s.currentState;
this.storedBlockCRC = s.storedBlockCRC;
this.storedCombinedCRC = s.storedCombinedCRC;
this.computedBlockCRC = s.computedBlockCRC;
this.computedCombinedCRC = s.computedCombinedCRC;
this.su_count = s.su_count;
this.su_ch2 = s.su_ch2;
this.su_chPrev = s.su_chPrev;
this.su_i2 = s.su_i2;
this.su_j2 = s.su_j2;
this.su_rNToGo = s.su_rNToGo;
this.su_rTPos = s.su_rTPos;
this.su_tPos = s.su_tPos;
this.su_z = s.su_z;
}
private struct StateDump {
public bool _disposed;
public Int64 totalBytesRead;
public int last;
/* for undoing the Burrows-Wheeler transform */
public int origPtr;
// blockSize100k: 0 .. 9.
//
// This var name is a misnomer. The actual block size is 100000
// * blockSize100k. (not 100k * blocksize100k)
public bool blockRandomised;
public int bsBuff;
public int bsLive;
public int nInUse;
public int currentChar;
public CState currentState;
public uint storedBlockCRC, storedCombinedCRC;
public uint computedBlockCRC, computedCombinedCRC;
// Variables used by setup* methods exclusively
public int su_count;
public int su_ch2;
public int su_chPrev;
public int su_i2;
public int su_j2;
public int su_rNToGo;
public int su_rTPos;
public int su_tPos;
public char su_z;
}
}
// /**
// * Checks if the signature matches what is expected for a bzip2 file.
// *
// * @param signature
// * the bytes to check
// * @param length
// * the number of bytes to check
// * @return true, if this stream is a bzip2 compressed stream, false otherwise
// *
// * @since Apache Commons Compress 1.1
// */
// public static boolean MatchesSig(byte[] signature)
// {
// if ((signature.Length < 3) ||
// (signature[0] != 'B') ||
// (signature[1] != 'Z') ||
// (signature[2] != 'h'))
// return false;
//
// return true;
// }
internal static class BZip2
{
internal static T[][] InitRectangularArray<T>(int d1, int d2)
{
var x = new T[d1][];
for (int i=0; i < d1; i++)
{
x[i] = new T[d2];
}
return x;
}
public static readonly int BlockSizeMultiple = 100000;
public static readonly int MinBlockSize = 1;
public static readonly int MaxBlockSize = 9;
public static readonly int MaxAlphaSize = 258;
public static readonly int MaxCodeLength = 23;
public static readonly char RUNA = (char) 0;
public static readonly char RUNB = (char) 1;
public static readonly int NGroups = 6;
public static readonly int G_SIZE = 50;
public static readonly int N_ITERS = 4;
public static readonly int MaxSelectors = (2 + (900000 / G_SIZE));
public static readonly int NUM_OVERSHOOT_BYTES = 20;
/*
* <p> If you are ever unlucky/improbable enough to get a stack
* overflow whilst sorting, increase the following constant and
* try again. In practice I have never seen the stack go above 27
* elems, so the following limit seems very generous. </p>
*/
internal static readonly int QSORT_STACK_SIZE = 1000;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.