context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Security;
namespace System
{
// 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.
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 Boolean 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)1 : (byte)0);
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 == sizeof(char));
byte[] bytes = new byte[sizeof(char)];
Unsafe.As<byte, char>(ref bytes[0]) = value;
return bytes;
}
// Converts a short into an array of bytes with length
// two.
public static byte[] GetBytes(short value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == sizeof(short));
byte[] bytes = new byte[sizeof(short)];
Unsafe.As<byte, short>(ref bytes[0]) = value;
return bytes;
}
// Converts an int into an array of bytes with length
// four.
public static byte[] GetBytes(int value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == sizeof(int));
byte[] bytes = new byte[sizeof(int)];
Unsafe.As<byte, int>(ref bytes[0]) = value;
return bytes;
}
// Converts a long into an array of bytes with length
// eight.
public static byte[] GetBytes(long value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == sizeof(long));
byte[] bytes = new byte[sizeof(long)];
Unsafe.As<byte, long>(ref bytes[0]) = 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 == sizeof(ushort));
byte[] bytes = new byte[sizeof(ushort)];
Unsafe.As<byte, ushort>(ref bytes[0]) = value;
return bytes;
}
// 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 == sizeof(uint));
byte[] bytes = new byte[sizeof(uint)];
Unsafe.As<byte, uint>(ref bytes[0]) = value;
return bytes;
}
// 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 == sizeof(ulong));
byte[] bytes = new byte[sizeof(ulong)];
Unsafe.As<byte, ulong>(ref bytes[0]) = value;
return bytes;
}
// Converts a float into an array of bytes with length
// four.
public static byte[] GetBytes(float value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == sizeof(float));
byte[] bytes = new byte[sizeof(float)];
Unsafe.As<byte, float>(ref bytes[0]) = value;
return bytes;
}
// Converts a double into an array of bytes with length
// eight.
public static byte[] GetBytes(double value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == sizeof(double));
byte[] bytes = new byte[sizeof(double)];
Unsafe.As<byte, double>(ref bytes[0]) = value;
return bytes;
}
// Converts an array of bytes into a char.
public static char ToChar(byte[] value, int startIndex) => unchecked((char)ReadInt16(value, startIndex));
private static short ReadInt16(byte[] value, int startIndex)
{
if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
if (unchecked((uint)startIndex) >= unchecked((uint)value.Length))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
if (startIndex > value.Length - sizeof(short))
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value);
Contract.EndContractBlock();
return Unsafe.ReadUnaligned<short>(ref value[startIndex]);
}
private static int ReadInt32(byte[] value, int startIndex)
{
if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
if (unchecked((uint)startIndex) >= unchecked((uint)value.Length))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
if (startIndex > value.Length - sizeof(int))
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value);
Contract.EndContractBlock();
return Unsafe.ReadUnaligned<int>(ref value[startIndex]);
}
private static long ReadInt64(byte[] value, int startIndex)
{
if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
if (unchecked((uint)startIndex) >= unchecked((uint)value.Length))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
if (startIndex > value.Length - sizeof(long))
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value);
Contract.EndContractBlock();
return Unsafe.ReadUnaligned<long>(ref value[startIndex]);
}
// Converts an array of bytes into a short.
public static short ToInt16(byte[] value, int startIndex) => ReadInt16(value, startIndex);
// Converts an array of bytes into an int.
public static int ToInt32(byte[] value, int startIndex) => ReadInt32(value, startIndex);
// Converts an array of bytes into a long.
public static long ToInt64(byte[] value, int startIndex) => ReadInt64(value, startIndex);
// Converts an array of bytes into an ushort.
//
[CLSCompliant(false)]
public static ushort ToUInt16(byte[] value, int startIndex) => unchecked((ushort)ReadInt16(value, startIndex));
// Converts an array of bytes into an uint.
//
[CLSCompliant(false)]
public static uint ToUInt32(byte[] value, int startIndex) => unchecked((uint)ReadInt32(value, startIndex));
// Converts an array of bytes into an unsigned long.
//
[CLSCompliant(false)]
public static ulong ToUInt64(byte[] value, int startIndex) => unchecked((ulong)ReadInt64(value, startIndex));
// Converts an array of bytes into a float.
public static unsafe float ToSingle(byte[] value, int startIndex)
{
int val = ReadInt32(value, startIndex);
return *(float*)&val;
}
// Converts an array of bytes into a double.
public static unsafe double ToDouble(byte[] value, int startIndex)
{
long val = ReadInt64(value, startIndex);
return *(double*)&val;
}
private static char GetHexValue(int i)
{
Debug.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)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
if (startIndex < 0 || startIndex >= value.Length && startIndex > 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);;
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_GenericPositive);
if (startIndex > value.Length - length)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value);
Contract.EndContractBlock();
if (length == 0)
{
return string.Empty;
}
if (length > (int.MaxValue / 3))
{
// (Int32.MaxValue / 3) == 715,827,882 Bytes == 699 MB
throw new ArgumentOutOfRangeException(nameof(length), SR.Format(SR.ArgumentOutOfRange_LengthTooLarge, (int.MaxValue / 3)));
}
int chArrayLength = length * 3;
const int StackLimit = 512; // arbitrary limit to switch from stack to heap allocation
unsafe
{
if (chArrayLength < StackLimit)
{
char* chArrayPtr = stackalloc char[chArrayLength];
return ToString(value, startIndex, length, chArrayPtr, chArrayLength);
}
else
{
char[] chArray = new char[chArrayLength];
fixed (char* chArrayPtr = &chArray[0])
return ToString(value, startIndex, length, chArrayPtr, chArrayLength);
}
}
}
private static unsafe string ToString(byte[] value, int startIndex, int length, char* chArray, int chArrayLength)
{
Debug.Assert(length > 0);
Debug.Assert(chArrayLength == length * 3);
char* p = chArray;
int endIndex = startIndex + length;
for (int i = startIndex; i < endIndex; i++)
{
byte b = value[i];
*p++ = GetHexValue(b >> 4);
*p++ = GetHexValue(b & 0xF);
*p++ = '-';
}
// We don't need the last '-' character
return new string(chArray, 0, chArrayLength - 1);
}
// Converts an array of bytes into a String.
public static string ToString(byte[] value)
{
if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.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)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.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)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
if (startIndex < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);;
if (startIndex > value.Length - 1)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);; // differs from other overloads, which throw base ArgumentException
Contract.EndContractBlock();
return value[startIndex] != 0;
}
public static unsafe long DoubleToInt64Bits(double value)
{
return *((long*)&value);
}
public static unsafe double Int64BitsToDouble(long value)
{
return *((double*)&value);
}
public static unsafe int SingleToInt32Bits(float value)
{
return *((int*)&value);
}
public static unsafe float Int32BitsToSingle(int value)
{
return *((float*)&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 Microsoft.Azure.Management.Automation
{
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>
/// AgentRegistrationInformationOperations operations.
/// </summary>
internal partial class AgentRegistrationInformationOperations : IServiceOperations<AutomationClient>, IAgentRegistrationInformationOperations
{
/// <summary>
/// Initializes a new instance of the AgentRegistrationInformationOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal AgentRegistrationInformationOperations(AutomationClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the AutomationClient
/// </summary>
public AutomationClient Client { get; private set; }
/// <summary>
/// Retrieve the automation agent registration information.
/// <see href="http://aka.ms/azureautomationsdk/agentregistrationoperations" />
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='automationAccountName'>
/// The automation account name.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<AgentRegistration>> GetWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$");
}
}
if (automationAccountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "automationAccountName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2015-10-31";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccountName", automationAccountName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/agentRegistrationInformation").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{automationAccountName}", System.Uri.EscapeDataString(automationAccountName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
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 (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);
}
System.Net.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<AgentRegistration>();
_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<AgentRegistration>(_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>
/// Regenerate a primary or secondary agent registration key
/// <see href="http://aka.ms/azureautomationsdk/agentregistrationoperations" />
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='automationAccountName'>
/// The automation account name.
/// </param>
/// <param name='parameters'>
/// The name of the agent registration key to be regenerated
/// </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<AgentRegistration>> RegenerateKeyWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, AgentRegistrationRegenerateKeyParameter parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$");
}
}
if (automationAccountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "automationAccountName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (parameters != null)
{
parameters.Validate();
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2015-10-31";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccountName", automationAccountName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "RegenerateKey", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/agentRegistrationInformation/regenerateKey").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{automationAccountName}", System.Uri.EscapeDataString(automationAccountName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
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("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.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<AgentRegistration>();
_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<AgentRegistration>(_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;
}
}
}
| |
using System;
using UnityEngine;
using DG.Tweening;
public class BluetoothEventListener : MonoBehaviour {
public static float JUMP_TIME_PER_ONE = 0.05f;
public bool isServer = false;
private bool isReady = false;
public bool Ready {
set {
if (!isServer) {
Bluetooth.Instance().Send(BluetoothMessageStrings.CLIENT_READY + "#" + value.ToString());
}
isReady = value;
CheckAllReady();
}
}
void Start() {
DontDestroyOnLoad(gameObject);
ScaneManager.OnScreenChange += ScreenChanged;
LoadResources();
bluetoothConnectionManager = FindObjectOfType<BluetoothConnectionManager>();
// Call the update function
if (isServer) InvokeRepeating("SendClientUpdateMsg", 0f, 0.2f);
}
private void ScreenChanged(string from, string to) {
// We changed to a non bluetooth scene
// We can only change to these from the connection screen
if (to != "ClientBluetoothGame" && to != "ServerBluetoothGame") {
ScaneManager.OnScreenChange -= ScreenChanged;
Bluetooth.Instance().DisableBluetooth();
Destroy(gameObject);
}
}
void OnApplicationPause(bool paused) {
if (!paused) {
LoadResources();
}
}
private void LoadResources() {
foundDevicePanel = Resources.Load("Prefabs/Bluetooth/FoundDevicePanel") as GameObject;
}
/// <summary>
/// What the latest border's bluetooth ID is that we displayed
/// </summary>
private int lastBorderID = 0;
/// <summary>
/// Whether the person is in game or not
/// </summary>
private bool isInGame = false;
private BluetoothConnectionManager bluetoothConnectionManager;
//----------------------------
// Client Stuff
//----------------------------
private ClientCellStorage clientCellStorage;
private ClientCellStorage ClientCellStrg {
get {
if (clientCellStorage == null) {
clientCellStorage = FindObjectOfType<ClientCellStorage>();
}
return clientCellStorage;
}
}
private BluetoothClientUIInScript clientUIInScript;
private BluetoothClientUIInScript ClientUIInScript {
get {
if (clientUIInScript == null) clientUIInScript = GameObject.Find("Canvas").GetComponent<BluetoothClientUIInScript>();
return clientUIInScript;
}
}
/// <summary>
/// Where the client thinks last sign was palced
/// </summary>
private int[] lastSignPlaced = new int[] { int.MaxValue, int.MaxValue };
private int[] secondToLastSignPlaced = new int[] { int.MaxValue, int.MaxValue };
private ScoringScript scoring;
private ScoringScript Scoring {
get {
if (scoring == null) scoring = GameObject.Find("Scoring").GetComponent<ScoringScript>();
return scoring;
}
}
//----------------------------
// Server Stuff
//----------------------------
private bool isClientReady = false;
private BluetoothTTTGameLogic gameLogic;
private BluetoothTTTGameLogic GameLogic {
get {
if (gameLogic == null) gameLogic = FindObjectOfType<BluetoothTTTGameLogic>();
return gameLogic;
}
}
//Prefabs
private GameObject foundDevicePanel;
// The panel in which we put the device names
private GameObject serverViewContent;
private GameObject ServerViewContent {
get {
// If we haven't found it or it has been destroyed
if (serverViewContent == null) serverViewContent = GameObject.Find("ServerViewContent");
return serverViewContent;
}
}
private BluetoothGrid grid;
private BluetoothGrid Grid {
get {
if (grid == null) grid = FindObjectOfType<BluetoothGrid>();
return grid;
}
}
/// <summary>
/// Last placed border's data
/// </summary>
private Border.BorderStorageLogic lastBorder;
/// <summary>
/// Should be called from BluetoothTTTGameLogic when a new border has been placed
/// </summary>
public void SetLastBorder(Border.BorderStorageLogic lastBorder) {
this.lastBorder = lastBorder;
lastBorderID++;
}
/// <summary>
/// All in all an update function for clientCalled every half a second or so
///
/// Sends client last sign's pos
/// Also send last border's id
/// Also send whose turn it is
/// </summary>
private void SendClientUpdateMsg() {
if (Bluetooth.Instance().IsConnected() && isInGame) {
// Most efficent way of concatting string
string sent = String.Join("", new string[] {
// last placed sign
BluetoothMessageStrings.WHERE_LAST_PLACED,
"#",
GameLogic.LastSignPlaced[0].ToString(),
"#",
GameLogic.LastSignPlaced[1].ToString(),
"#",
GameLogic.LastType.ToString(),
"|||",
// Last placed border
BluetoothMessageStrings.LAST_BORDER_ID.ToString(),
"#",
lastBorderID.ToString(),
"|||",
// Whose turn it is
BluetoothMessageStrings.TURN_OF,
"#",
GameLogic.WhoseTurn.ToString(),
"|||",
// The score
BluetoothMessageStrings.SEND_SCORE,
"#",
GameLogic.XScore.ToString(),
"#",
GameLogic.OScore.ToString()
});
Bluetooth.Instance().Send(sent);
}
}
/// <summary>
/// Start searching for potential clients
/// </summary>
public void StartSearching() {
// Only do it for servers
if (!isServer) return;
// Remove every shown device first
foreach (Transform t in ServerViewContent.transform) {
Destroy(t.gameObject);
}
Debug.Log("Is server discoverable " + Bluetooth.Instance().Discoverable());
Bluetooth.Instance().SearchDevice();
GameObject.Find("LoadImage").GetComponent<LoadImage>().StartLoading();
}
/// <summary>
/// Event for the end of the search devices and there is zero device
/// </summary>
void FoundZeroDeviceEvent() {
Debug.Log("Found zero device");
}
/// <summary>
/// Event for the end of the current search
/// </summary>
void ScanFinishEvent() {
Debug.Log("Scan finished");
GameObject.Find("LoadImage").GetComponent<LoadImage>().StopLoading();
}
/// <summary>
/// Event when the search find new device
/// </summary>
/// <param name="Device"></param>
void FoundDeviceEvent(string Device) {
// split up data
string[] data = Device.Split(new string[] { ",\n" }, StringSplitOptions.None);
if (data[0] == "null") return; // Bug in bluetooth plugin
Bluetooth.Instance().MacAddresses.Add(Device); // Add to list in bluetooth
// Create new GUI for device
GameObject newPanel = Instantiate(foundDevicePanel, ServerViewContent.transform, false);
newPanel.GetComponent<FoundDevicePanel>().SetNameAndMac(data[0], data[1], Device);
}
/// <summary>
/// Check whether everyone is ready
/// If all is ready start game
/// </summary>
private bool CheckAllReady() {
if (!isServer) return false;
if (isReady && isClientReady) {
StartGame();
return true;
}
return false;
}
// Starts game
private void StartGame() {
if (!isServer) return;
ScaneManager.Instance.GoToScene("ServerBluetoothGame");
Bluetooth.Instance().Send(BluetoothMessageStrings.START_GAME);
}
//----------------------------
// Server/Client Stuff
//----------------------------
void ConnectionStateEvent(string state) {
Debug.Log("Connection state " + state);
//Connection State event this is the result of the connection fire after you try to Connect
switch (state) {
case "STATE_CONNECTED":
// Go to lobby
bluetoothConnectionManager.GoToLobby(Bluetooth.Instance().GetDeviceConnectedName());
isInGame = true;
bluetoothConnectionManager.NotConnectingAnymore();
break;
case "STATE_CONNECTING":
break;
case "UNABLE TO CONNECT":
// We are not in game, so most likely in lobby
if (!isInGame) {
PopupManager.Instance.PopUp("Couldn't connect!", "OK");
bluetoothConnectionManager.NotConnectingAnymore();
} else {
// We are in game
PopupManager.Instance.PopUp(new PopUpOneButton("Lost connection!\n Going back to menu", "OK").SetButtonPressAction(() => {
ScaneManager.Instance.GoToSceneWithErase("Menu");
}));
}
break;
}
}
/// <summary>
/// Done sending the message event
/// </summary>
/// <param name="writeMessage"></param>
void DoneSendingEvent(string writeMessage) {
}
/// <summary>
/// Done reading the message event
/// </summary>
/// <param name="readMessage"></param>
void DoneReadingEvent(string readMessage) {
string[] differentMessages = readMessage.Split(new string[] { "|||" }, StringSplitOptions.None);
for (int i = 0; i < differentMessages.Length - 1; i++) {
string[] splitMessage = differentMessages[i].Split('#');
// SERVER SERVER SERVER SERVER SERVER SERVER SERVER SERVER SERVER SERVER
// SERVER SERVER SERVER SERVER SERVER SERVER SERVER SERVER SERVER SERVER
if (isServer) {
switch (splitMessage[0]) {
case "CLIENTREADY": // client sends he is ready
isClientReady = bool.Parse(splitMessage[1]);
CheckAllReady();
break;
case "TRYPLACEAT": // client is trying to place at pos
Vector2 pos = new Vector2(int.Parse(splitMessage[1]), int.Parse(splitMessage[2]));
// If it's not server's turn try placing at pos
if (!GameLogic.IsItServersTurn())
GameLogic.WantToPlaceAt(pos);
break;
case "WHOSETURN": // Client is asking for whose turn it is
Bluetooth.Instance().Send(BluetoothMessageStrings.TURN_OF + "#" + gameLogic.WhoseTurn.ToString());
break;
case "SMB": // Client is asking for latest border data
Bluetooth.Instance().Send(BluetoothMessageStrings.ADD_BORDER + "#" + lastBorder.ToString() + "#" + lastBorderID);
break;
}
// CLIENT CLIENT CLIENT CLIENT CLIENT CLIENT CLIENT CLIENT CLIENT
// CLIENT CLIENT CLIENT CLIENT CLIENT CLIENT CLIENT CLIENT CLIENT
} else {
switch (splitMessage[0]) {
case "STARTGAME": // Server sends that the game has been started
// Switch scenes
ScaneManager.Instance.GoToScene("ClientBluetoothGame");
break;
case "WLP": // Server sends where last sign has been placed
int[] lastPos = new int[] {
int.Parse(splitMessage[1]),
int.Parse(splitMessage[2])
};
if (!(lastPos[0] == lastSignPlaced[0] && lastPos[1] == lastSignPlaced[1])) {
secondToLastSignPlaced[0] = lastSignPlaced[0]; secondToLastSignPlaced[1] = lastSignPlaced[1];
lastSignPlaced[0] = lastPos[0]; lastSignPlaced[1] = lastPos[1]; // Store new sign pos as last sign
Cell.CellOcc lastType = (Cell.CellOcc) Enum.Parse(typeof(Cell.CellOcc), splitMessage[3]);
// Place sign locally
ClientCellStrg.PlaceCellAt(lastPos, lastType);
}
break;
case "LBI": // Server sends what the last border's bluetooth id is
// The server has a newer border placed
if (lastBorderID != int.Parse(splitMessage[1])) {
Bluetooth.Instance().Send(BluetoothMessageStrings.SEND_ME_BORDER);
}
break;
case "TURNOF": // Server sends whose turn it is
Cell.CellOcc whoseTurn = (Cell.CellOcc) Enum.Parse(typeof(Cell.CellOcc), splitMessage[1]);
ClientUIInScript.UpdateImage(whoseTurn);
break;
case "ADDBORDER": // Server sends border data
// set lates bluetooth border id
lastBorderID = int.Parse(splitMessage[splitMessage.Length - 1]);
// Get data and add a border locally
int countOfPoints = int.Parse(splitMessage[1]);
int[,] points = new int[countOfPoints, 2];
float[,] winLine = new float[2, 2];
for (int k = 0; k < countOfPoints; k++) {
points[k, 0] = int.Parse(splitMessage[2 * (k + 3)]);
points[k, 1] = int.Parse(splitMessage[2 * (k + 3) + 1]);
}
winLine[0, 0] = float.Parse(splitMessage[2]);
winLine[0, 1] = float.Parse(splitMessage[3]);
winLine[1, 0] = float.Parse(splitMessage[4]);
winLine[1, 1] = float.Parse(splitMessage[5]);
Cell.CellOcc winType = (Cell.CellOcc) Enum.Parse(typeof(Cell.CellOcc), splitMessage[6 + countOfPoints * 2]);
BluetoothClientBorder.AddBorderPoints(points, winLine, winType);
// Because a border was added someone won the game so call the event
ClientCellStrg.SomeoneWon(winType);
break;
case "JPT": // Server sends to jump to this pos because new game has been started
Vector3 jumpTo = new Vector3(int.Parse(splitMessage[1]), int.Parse(splitMessage[2]), Camera.main.transform.position.z);
Camera.main.transform.DOMove(jumpTo, Vector2.Distance(Camera.main.transform.position, jumpTo) * JUMP_TIME_PER_ONE);
break;
case "SSCR":
int xScore = int.Parse(splitMessage[1]);
int oScore = int.Parse(splitMessage[2]);
Scoring.SetScore(xScore, oScore);
break;
}
}
// BOTH BOTH BOTH BOTH BOTH BOTH BOTH BOTH BOTH BOTH BOTH BOTH BOTH BOTH BOTH BOTH BOTH BOTH BOTH BOTH BOTH BOTH BOTH BOTH
// BOTH BOTH BOTH BOTH BOTH BOTH BOTH BOTH BOTH BOTH BOTH BOTH BOTH BOTH BOTH BOTH BOTH BOTH BOTH BOTH BOTH BOTH BOTH BOTH
switch (splitMessage[0]) {
case "SMSG":
BluetoothMessageManager.ShowEmojiMessage(EmojiSprites.GetEmoji(splitMessage[1]));
break;
}
}
}
}
public static class BluetoothMessageStrings {
//_________________________________ S -> C || C -> S ___________________________
/// <summary>
/// Sent by both client and server and it simply sends a message then displays it
/// ID path
/// </summary>
public static readonly string SEND_MESSAGE = "SMSG";
//________________________________ S -> C __________________________________
/// <summary>
/// Sent by server to client to start game
/// ID
/// </summary>
public static readonly string START_GAME = "STARTGAME";
/// <summary>
/// Sent by server to client: whose turn is it
/// ID whoseTurn
/// </summary>
public static readonly string TURN_OF = "TURNOF";
/// <summary>
/// Sent by server to client to add a border
/// ID numberOfPoint win1X win1Y win2X win2Y point1X point1Y point2X point2Y.... winType bluetoothID
/// </summary>
public static readonly string ADD_BORDER = "ADDBORDER";
/// <summary>
/// Sent by server to client where last sign was placed
/// ID whereX whereY serverTypeSign
/// </summary>
public static readonly string WHERE_LAST_PLACED = "WLP";
/// <summary>
/// Sent by server to client what last border's bluetooth ID is
/// ID borderID
/// </summary>
public static readonly string LAST_BORDER_ID = "LBI";
/// <summary>
/// Sent by server to client to jump to a location with camera where sign has been placed
/// ID whereX whereY
/// </summary>
public static readonly string JUMP_TO = "JPT";
/// <summary>
/// Sent by server to client and it sends the current score
/// ID scoreX scoreO
/// </summary>
public static readonly string SEND_SCORE = "SSCR";
//___________________________ C -> S _________________________________
/// <summary>
/// Sent by client to server to set it's ready state
/// ID isReady
/// </summary>
public static readonly string CLIENT_READY = "CLIENTREADY";
/// <summary>
/// Sent by client to server to try place at pos
/// ID coordX coordY
/// </summary>
public static readonly string TRY_PLACE_AT = "TRYPLACEAT";
/// <summary>
/// Sent by client to server asks whether it's his turn
/// ID
/// </summary>
public static readonly string WHOSE_TURN = "WHOSETURN";
/// <summary>
/// Sent by client to server when it asks for the lates border
/// ID
/// </summary>
public static readonly string SEND_ME_BORDER = "SMB";
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Compute
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Impl.Common;
/// <summary>
/// Synchronous Compute facade.
/// </summary>
internal class Compute : ICompute
{
/** */
private readonly ComputeImpl _compute;
/// <summary>
/// Initializes a new instance of the <see cref="Compute"/> class.
/// </summary>
/// <param name="computeImpl">The compute implementation.</param>
public Compute(ComputeImpl computeImpl)
{
Debug.Assert(computeImpl != null);
_compute = computeImpl;
}
/** <inheritDoc /> */
public IClusterGroup ClusterGroup
{
get { return _compute.ClusterGroup; }
}
/** <inheritDoc /> */
public ICompute WithNoFailover()
{
_compute.WithNoFailover();
return this;
}
/** <inheritDoc /> */
public ICompute WithNoResultCache()
{
_compute.WithNoResultCache();
return this;
}
/** <inheritDoc /> */
public ICompute WithTimeout(long timeout)
{
_compute.WithTimeout(timeout);
return this;
}
/** <inheritDoc /> */
public ICompute WithKeepBinary()
{
_compute.WithKeepBinary();
return this;
}
/** <inheritDoc /> */
public ICompute WithExecutor(string executorName)
{
var computeImpl = _compute.WithExecutor(executorName);
return new Compute(computeImpl);
}
/** <inheritDoc /> */
public TReduceRes ExecuteJavaTask<TReduceRes>(string taskName, object taskArg)
{
return _compute.ExecuteJavaTask<TReduceRes>(taskName, taskArg);
}
/** <inheritDoc /> */
public Task<TRes> ExecuteJavaTaskAsync<TRes>(string taskName, object taskArg)
{
return _compute.ExecuteJavaTaskAsync<TRes>(taskName, taskArg).Task;
}
/** <inheritDoc /> */
public Task<TRes> ExecuteJavaTaskAsync<TRes>(string taskName, object taskArg,
CancellationToken cancellationToken)
{
return GetTaskIfAlreadyCancelled<TRes>(cancellationToken) ??
_compute.ExecuteJavaTaskAsync<TRes>(taskName, taskArg).GetTask(cancellationToken);
}
/** <inheritDoc /> */
public TReduceRes Execute<TArg, TJobRes, TReduceRes>(IComputeTask<TArg, TJobRes, TReduceRes> task, TArg taskArg)
{
return _compute.Execute(task, taskArg).Get();
}
/** <inheritDoc /> */
public Task<TRes> ExecuteAsync<TArg, TJobRes, TRes>(IComputeTask<TArg, TJobRes, TRes> task, TArg taskArg)
{
return _compute.Execute(task, taskArg).Task;
}
/** <inheritDoc /> */
public Task<TRes> ExecuteAsync<TArg, TJobRes, TRes>(IComputeTask<TArg, TJobRes, TRes> task, TArg taskArg,
CancellationToken cancellationToken)
{
return GetTaskIfAlreadyCancelled<TRes>(cancellationToken) ??
_compute.Execute(task, taskArg).GetTask(cancellationToken);
}
/** <inheritDoc /> */
public TJobRes Execute<TArg, TJobRes>(IComputeTask<TArg, TJobRes> task)
{
return _compute.Execute(task, null).Get();
}
/** <inheritDoc /> */
public Task<TRes> ExecuteAsync<TJobRes, TRes>(IComputeTask<TJobRes, TRes> task)
{
return _compute.Execute(task, null).Task;
}
/** <inheritDoc /> */
public Task<TRes> ExecuteAsync<TJobRes, TRes>(IComputeTask<TJobRes, TRes> task,
CancellationToken cancellationToken)
{
return GetTaskIfAlreadyCancelled<TRes>(cancellationToken) ??
_compute.Execute(task, null).GetTask(cancellationToken);
}
/** <inheritDoc /> */
public TReduceRes Execute<TArg, TJobRes, TReduceRes>(Type taskType, TArg taskArg)
{
return _compute.Execute<TArg, TJobRes, TReduceRes>(taskType, taskArg).Get();
}
/** <inheritDoc /> */
public Task<TReduceRes> ExecuteAsync<TArg, TJobRes, TReduceRes>(Type taskType, TArg taskArg)
{
return _compute.Execute<TArg, TJobRes, TReduceRes>(taskType, taskArg).Task;
}
/** <inheritDoc /> */
public Task<TReduceRes> ExecuteAsync<TArg, TJobRes, TReduceRes>(Type taskType, TArg taskArg,
CancellationToken cancellationToken)
{
return GetTaskIfAlreadyCancelled<TReduceRes>(cancellationToken) ??
_compute.Execute<TArg, TJobRes, TReduceRes>(taskType, taskArg).GetTask(cancellationToken);
}
/** <inheritDoc /> */
public TReduceRes Execute<TArg, TReduceRes>(Type taskType)
{
return _compute.Execute<object, TArg, TReduceRes>(taskType, null).Get();
}
/** <inheritDoc /> */
public Task<TReduceRes> ExecuteAsync<TArg, TReduceRes>(Type taskType)
{
return _compute.Execute<object, TArg, TReduceRes>(taskType, null).Task;
}
/** <inheritDoc /> */
public Task<TReduceRes> ExecuteAsync<TArg, TReduceRes>(Type taskType, CancellationToken cancellationToken)
{
return GetTaskIfAlreadyCancelled<TReduceRes>(cancellationToken) ??
_compute.Execute<object, TArg, TReduceRes>(taskType, null).GetTask(cancellationToken);
}
/** <inheritDoc /> */
public TJobRes Call<TJobRes>(IComputeFunc<TJobRes> clo)
{
return _compute.Execute(clo).Get();
}
/** <inheritDoc /> */
public Task<TRes> CallAsync<TRes>(IComputeFunc<TRes> clo)
{
return _compute.Execute(clo).Task;
}
/** <inheritDoc /> */
public Task<TRes> CallAsync<TRes>(IComputeFunc<TRes> clo, CancellationToken cancellationToken)
{
return GetTaskIfAlreadyCancelled<TRes>(cancellationToken) ??
_compute.Execute(clo).GetTask(cancellationToken);
}
/** <inheritDoc /> */
public TJobRes AffinityCall<TJobRes>(string cacheName, object affinityKey, IComputeFunc<TJobRes> clo)
{
IgniteArgumentCheck.NotNull(cacheName, "cacheName");
return _compute.AffinityCall(cacheName, affinityKey, clo).Get();
}
/** <inheritDoc /> */
public Task<TRes> AffinityCallAsync<TRes>(string cacheName, object affinityKey, IComputeFunc<TRes> clo)
{
IgniteArgumentCheck.NotNull(cacheName, "cacheName");
return _compute.AffinityCall(cacheName, affinityKey, clo).Task;
}
/** <inheritDoc /> */
public Task<TRes> AffinityCallAsync<TRes>(string cacheName, object affinityKey, IComputeFunc<TRes> clo,
CancellationToken cancellationToken)
{
IgniteArgumentCheck.NotNull(cacheName, "cacheName");
return GetTaskIfAlreadyCancelled<TRes>(cancellationToken) ??
_compute.AffinityCall(cacheName, affinityKey, clo).GetTask(cancellationToken);
}
/** <inheritDoc /> */
public TRes AffinityCall<TRes>(IEnumerable<string> cacheNames, int partition, IComputeFunc<TRes> func)
{
IgniteArgumentCheck.NotNull(cacheNames, "cacheNames");
IgniteArgumentCheck.NotNull(func, "func");
return _compute.AffinityCall(cacheNames, partition, func).Get();
}
/** <inheritDoc /> */
public Task<TRes> AffinityCallAsync<TRes>(IEnumerable<string> cacheNames, int partition,
IComputeFunc<TRes> func)
{
return _compute.AffinityCall(cacheNames, partition, func).Task;
}
/** <inheritDoc /> */
public Task<TRes> AffinityCallAsync<TRes>(IEnumerable<string> cacheNames, int partition,
IComputeFunc<TRes> func, CancellationToken cancellationToken)
{
return _compute.AffinityCall(cacheNames, partition, func).GetTask(cancellationToken);
}
/** <inheritDoc /> */
public Task<TRes> CallAsync<TFuncRes, TRes>(IEnumerable<IComputeFunc<TFuncRes>> clos,
IComputeReducer<TFuncRes, TRes> reducer)
{
return _compute.Execute(clos, reducer).Task;
}
/** <inheritDoc /> */
public Task<TRes> CallAsync<TFuncRes, TRes>(IEnumerable<IComputeFunc<TFuncRes>> clos,
IComputeReducer<TFuncRes, TRes> reducer, CancellationToken cancellationToken)
{
return GetTaskIfAlreadyCancelled<TRes>(cancellationToken) ??
_compute.Execute(clos, reducer).GetTask(cancellationToken);
}
/** <inheritDoc /> */
public ICollection<TJobRes> Call<TJobRes>(IEnumerable<IComputeFunc<TJobRes>> clos)
{
return _compute.Execute(clos).Get();
}
/** <inheritDoc /> */
public Task<ICollection<TRes>> CallAsync<TRes>(IEnumerable<IComputeFunc<TRes>> clos)
{
return _compute.Execute(clos).Task;
}
/** <inheritDoc /> */
public Task<ICollection<TRes>> CallAsync<TRes>(IEnumerable<IComputeFunc<TRes>> clos,
CancellationToken cancellationToken)
{
return GetTaskIfAlreadyCancelled<ICollection<TRes>>(cancellationToken) ??
_compute.Execute(clos).GetTask(cancellationToken);
}
/** <inheritDoc /> */
public TReduceRes Call<TJobRes, TReduceRes>(IEnumerable<IComputeFunc<TJobRes>> clos,
IComputeReducer<TJobRes, TReduceRes> reducer)
{
return _compute.Execute(clos, reducer).Get();
}
/** <inheritDoc /> */
public ICollection<TJobRes> Broadcast<TJobRes>(IComputeFunc<TJobRes> clo)
{
return _compute.Broadcast(clo).Get();
}
/** <inheritDoc /> */
public Task<ICollection<TRes>> BroadcastAsync<TRes>(IComputeFunc<TRes> clo)
{
return _compute.Broadcast(clo).Task;
}
/** <inheritDoc /> */
public Task<ICollection<TRes>> BroadcastAsync<TRes>(IComputeFunc<TRes> clo, CancellationToken cancellationToken)
{
return GetTaskIfAlreadyCancelled<ICollection<TRes>>(cancellationToken) ??
_compute.Broadcast(clo).GetTask(cancellationToken);
}
/** <inheritDoc /> */
public ICollection<TJobRes> Broadcast<T, TJobRes>(IComputeFunc<T, TJobRes> clo, T arg)
{
return _compute.Broadcast(clo, arg).Get();
}
/** <inheritDoc /> */
public Task<ICollection<TRes>> BroadcastAsync<TArg, TRes>(IComputeFunc<TArg, TRes> clo, TArg arg)
{
return _compute.Broadcast(clo, arg).Task;
}
/** <inheritDoc /> */
public Task<ICollection<TRes>> BroadcastAsync<TArg, TRes>(IComputeFunc<TArg, TRes> clo, TArg arg,
CancellationToken cancellationToken)
{
return GetTaskIfAlreadyCancelled<ICollection<TRes>>(cancellationToken) ??
_compute.Broadcast(clo, arg).GetTask(cancellationToken);
}
/** <inheritDoc /> */
public void Broadcast(IComputeAction action)
{
_compute.Broadcast(action).Get();
}
/** <inheritDoc /> */
public Task BroadcastAsync(IComputeAction action)
{
return _compute.Broadcast(action).Task;
}
/** <inheritDoc /> */
public Task BroadcastAsync(IComputeAction action, CancellationToken cancellationToken)
{
return GetTaskIfAlreadyCancelled<object>(cancellationToken) ??
_compute.Broadcast(action).GetTask(cancellationToken);
}
/** <inheritDoc /> */
public void Run(IComputeAction action)
{
_compute.Run(action).Get();
}
/** <inheritDoc /> */
public Task RunAsync(IComputeAction action)
{
return _compute.Run(action).Task;
}
/** <inheritDoc /> */
public Task RunAsync(IComputeAction action, CancellationToken cancellationToken)
{
return GetTaskIfAlreadyCancelled<object>(cancellationToken) ??
_compute.Run(action).GetTask(cancellationToken);
}
/** <inheritDoc /> */
public void AffinityRun(string cacheName, object affinityKey, IComputeAction action)
{
IgniteArgumentCheck.NotNull(cacheName, "cacheName");
_compute.AffinityRun(cacheName, affinityKey, action).Get();
}
/** <inheritDoc /> */
public Task AffinityRunAsync(string cacheName, object affinityKey, IComputeAction action)
{
IgniteArgumentCheck.NotNull(cacheName, "cacheName");
return _compute.AffinityRun(cacheName, affinityKey, action).Task;
}
/** <inheritDoc /> */
public Task AffinityRunAsync(string cacheName, object affinityKey, IComputeAction action,
CancellationToken cancellationToken)
{
IgniteArgumentCheck.NotNull(cacheName, "cacheName");
return GetTaskIfAlreadyCancelled<object>(cancellationToken) ??
_compute.AffinityRun(cacheName, affinityKey, action).GetTask(cancellationToken);
}
/** <inheritDoc /> */
public void AffinityRun(IEnumerable<string> cacheNames, int partition, IComputeAction action)
{
_compute.AffinityRun(cacheNames, partition, action).Get();
}
/** <inheritDoc /> */
public Task AffinityRunAsync(IEnumerable<string> cacheNames, int partition, IComputeAction action)
{
return _compute.AffinityRun(cacheNames, partition, action).Task;
}
/** <inheritDoc /> */
public Task AffinityRunAsync(IEnumerable<string> cacheNames, int partition, IComputeAction action,
CancellationToken cancellationToken)
{
return _compute.AffinityRun(cacheNames, partition, action).GetTask(cancellationToken);
}
/** <inheritDoc /> */
public void Run(IEnumerable<IComputeAction> actions)
{
_compute.Run(actions).Get();
}
/** <inheritDoc /> */
public Task RunAsync(IEnumerable<IComputeAction> actions)
{
return _compute.Run(actions).Task;
}
/** <inheritDoc /> */
public Task RunAsync(IEnumerable<IComputeAction> actions, CancellationToken cancellationToken)
{
return GetTaskIfAlreadyCancelled<object>(cancellationToken) ??
_compute.Run(actions).GetTask(cancellationToken);
}
/** <inheritDoc /> */
public TJobRes Apply<TArg, TJobRes>(IComputeFunc<TArg, TJobRes> clo, TArg arg)
{
return _compute.Apply(clo, arg).Get();
}
/** <inheritDoc /> */
public Task<TRes> ApplyAsync<TArg, TRes>(IComputeFunc<TArg, TRes> clo, TArg arg)
{
return _compute.Apply(clo, arg).Task;
}
/** <inheritDoc /> */
public Task<TRes> ApplyAsync<TArg, TRes>(IComputeFunc<TArg, TRes> clo, TArg arg,
CancellationToken cancellationToken)
{
return GetTaskIfAlreadyCancelled<TRes>(cancellationToken) ??
_compute.Apply(clo, arg).GetTask(cancellationToken);
}
/** <inheritDoc /> */
public ICollection<TJobRes> Apply<TArg, TJobRes>(IComputeFunc<TArg, TJobRes> clo, IEnumerable<TArg> args)
{
return _compute.Apply(clo, args).Get();
}
/** <inheritDoc /> */
public Task<ICollection<TRes>> ApplyAsync<TArg, TRes>(IComputeFunc<TArg, TRes> clo, IEnumerable<TArg> args)
{
return _compute.Apply(clo, args).Task;
}
/** <inheritDoc /> */
public Task<ICollection<TRes>> ApplyAsync<TArg, TRes>(IComputeFunc<TArg, TRes> clo, IEnumerable<TArg> args,
CancellationToken cancellationToken)
{
return GetTaskIfAlreadyCancelled<ICollection<TRes>>(cancellationToken) ??
_compute.Apply(clo, args).GetTask(cancellationToken);
}
/** <inheritDoc /> */
public TReduceRes Apply<TArg, TJobRes, TReduceRes>(IComputeFunc<TArg, TJobRes> clo,
IEnumerable<TArg> args, IComputeReducer<TJobRes, TReduceRes> rdc)
{
return _compute.Apply(clo, args, rdc).Get();
}
/** <inheritDoc /> */
public Task<TRes> ApplyAsync<TArg, TFuncRes, TRes>(IComputeFunc<TArg, TFuncRes> clo, IEnumerable<TArg> args,
IComputeReducer<TFuncRes, TRes> rdc)
{
return _compute.Apply(clo, args, rdc).Task;
}
/** <inheritDoc /> */
public Task<TRes> ApplyAsync<TArg, TFuncRes, TRes>(IComputeFunc<TArg, TFuncRes> clo, IEnumerable<TArg> args,
IComputeReducer<TFuncRes, TRes> rdc, CancellationToken cancellationToken)
{
return GetTaskIfAlreadyCancelled<TRes>(cancellationToken) ??
_compute.Apply(clo, args, rdc).GetTask(cancellationToken);
}
/// <summary>
/// Gets the cancelled task if specified token is cancelled.
/// </summary>
private static Task<T> GetTaskIfAlreadyCancelled<T>(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return CancelledTask<T>.Instance;
return null;
}
/// <summary>
/// Determines whether specified exception should result in a job failover.
/// </summary>
internal static bool IsFailoverException(Exception err)
{
while (err != null)
{
if (err is ComputeExecutionRejectedException || err is ClusterTopologyException ||
err is ComputeJobFailoverException)
return true;
err = err.InnerException;
}
return false;
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Windows.Input.Mouse.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Windows.Input
{
static public partial class Mouse
{
#region Methods and constructors
public static void AddGotMouseCaptureHandler(System.Windows.DependencyObject element, MouseEventHandler handler)
{
}
public static void AddLostMouseCaptureHandler(System.Windows.DependencyObject element, MouseEventHandler handler)
{
}
public static void AddMouseDownHandler(System.Windows.DependencyObject element, MouseButtonEventHandler handler)
{
}
public static void AddMouseEnterHandler(System.Windows.DependencyObject element, MouseEventHandler handler)
{
}
public static void AddMouseLeaveHandler(System.Windows.DependencyObject element, MouseEventHandler handler)
{
}
public static void AddMouseMoveHandler(System.Windows.DependencyObject element, MouseEventHandler handler)
{
}
public static void AddMouseUpHandler(System.Windows.DependencyObject element, MouseButtonEventHandler handler)
{
}
public static void AddMouseWheelHandler(System.Windows.DependencyObject element, MouseWheelEventHandler handler)
{
}
public static void AddPreviewMouseDownHandler(System.Windows.DependencyObject element, MouseButtonEventHandler handler)
{
}
public static void AddPreviewMouseDownOutsideCapturedElementHandler(System.Windows.DependencyObject element, MouseButtonEventHandler handler)
{
}
public static void AddPreviewMouseMoveHandler(System.Windows.DependencyObject element, MouseEventHandler handler)
{
}
public static void AddPreviewMouseUpHandler(System.Windows.DependencyObject element, MouseButtonEventHandler handler)
{
}
public static void AddPreviewMouseUpOutsideCapturedElementHandler(System.Windows.DependencyObject element, MouseButtonEventHandler handler)
{
}
public static void AddPreviewMouseWheelHandler(System.Windows.DependencyObject element, MouseWheelEventHandler handler)
{
}
public static void AddQueryCursorHandler(System.Windows.DependencyObject element, QueryCursorEventHandler handler)
{
}
public static bool Capture(System.Windows.IInputElement element)
{
return default(bool);
}
public static bool Capture(System.Windows.IInputElement element, CaptureMode captureMode)
{
return default(bool);
}
public static int GetIntermediatePoints(System.Windows.IInputElement relativeTo, System.Windows.Point[] points)
{
return default(int);
}
public static System.Windows.Point GetPosition(System.Windows.IInputElement relativeTo)
{
return default(System.Windows.Point);
}
public static void RemoveGotMouseCaptureHandler(System.Windows.DependencyObject element, MouseEventHandler handler)
{
}
public static void RemoveLostMouseCaptureHandler(System.Windows.DependencyObject element, MouseEventHandler handler)
{
}
public static void RemoveMouseDownHandler(System.Windows.DependencyObject element, MouseButtonEventHandler handler)
{
}
public static void RemoveMouseEnterHandler(System.Windows.DependencyObject element, MouseEventHandler handler)
{
}
public static void RemoveMouseLeaveHandler(System.Windows.DependencyObject element, MouseEventHandler handler)
{
}
public static void RemoveMouseMoveHandler(System.Windows.DependencyObject element, MouseEventHandler handler)
{
}
public static void RemoveMouseUpHandler(System.Windows.DependencyObject element, MouseButtonEventHandler handler)
{
}
public static void RemoveMouseWheelHandler(System.Windows.DependencyObject element, MouseWheelEventHandler handler)
{
}
public static void RemovePreviewMouseDownHandler(System.Windows.DependencyObject element, MouseButtonEventHandler handler)
{
}
public static void RemovePreviewMouseDownOutsideCapturedElementHandler(System.Windows.DependencyObject element, MouseButtonEventHandler handler)
{
}
public static void RemovePreviewMouseMoveHandler(System.Windows.DependencyObject element, MouseEventHandler handler)
{
}
public static void RemovePreviewMouseUpHandler(System.Windows.DependencyObject element, MouseButtonEventHandler handler)
{
}
public static void RemovePreviewMouseUpOutsideCapturedElementHandler(System.Windows.DependencyObject element, MouseButtonEventHandler handler)
{
}
public static void RemovePreviewMouseWheelHandler(System.Windows.DependencyObject element, MouseWheelEventHandler handler)
{
}
public static void RemoveQueryCursorHandler(System.Windows.DependencyObject element, QueryCursorEventHandler handler)
{
}
public static bool SetCursor(Cursor cursor)
{
return default(bool);
}
public static void Synchronize()
{
}
public static void UpdateCursor()
{
}
#endregion
#region Properties and indexers
public static System.Windows.IInputElement Captured
{
get
{
return default(System.Windows.IInputElement);
}
}
public static System.Windows.IInputElement DirectlyOver
{
get
{
return default(System.Windows.IInputElement);
}
}
public static MouseButtonState LeftButton
{
get
{
return default(MouseButtonState);
}
}
public static MouseButtonState MiddleButton
{
get
{
return default(MouseButtonState);
}
}
public static Cursor OverrideCursor
{
get
{
return default(Cursor);
}
set
{
}
}
public static MouseDevice PrimaryDevice
{
get
{
return default(MouseDevice);
}
}
public static MouseButtonState RightButton
{
get
{
return default(MouseButtonState);
}
}
public static MouseButtonState XButton1
{
get
{
return default(MouseButtonState);
}
}
public static MouseButtonState XButton2
{
get
{
return default(MouseButtonState);
}
}
#endregion
#region Fields
public readonly static System.Windows.RoutedEvent GotMouseCaptureEvent;
public readonly static System.Windows.RoutedEvent LostMouseCaptureEvent;
public readonly static System.Windows.RoutedEvent MouseDownEvent;
public readonly static System.Windows.RoutedEvent MouseEnterEvent;
public readonly static System.Windows.RoutedEvent MouseLeaveEvent;
public readonly static System.Windows.RoutedEvent MouseMoveEvent;
public readonly static System.Windows.RoutedEvent MouseUpEvent;
public readonly static System.Windows.RoutedEvent MouseWheelEvent;
public readonly static System.Windows.RoutedEvent PreviewMouseDownEvent;
public readonly static System.Windows.RoutedEvent PreviewMouseDownOutsideCapturedElementEvent;
public readonly static System.Windows.RoutedEvent PreviewMouseMoveEvent;
public readonly static System.Windows.RoutedEvent PreviewMouseUpEvent;
public readonly static System.Windows.RoutedEvent PreviewMouseUpOutsideCapturedElementEvent;
public readonly static System.Windows.RoutedEvent PreviewMouseWheelEvent;
public readonly static System.Windows.RoutedEvent QueryCursorEvent;
#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 UnpackLowSByte()
{
var test = new SimpleBinaryOpTest__UnpackLowSByte();
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();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// 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();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
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__UnpackLowSByte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(SByte[] inArray1, SByte[] inArray2, SByte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<SByte, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<SByte> _fld1;
public Vector128<SByte> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__UnpackLowSByte testClass)
{
var result = Sse2.UnpackLow(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__UnpackLowSByte testClass)
{
fixed (Vector128<SByte>* pFld1 = &_fld1)
fixed (Vector128<SByte>* pFld2 = &_fld2)
{
var result = Sse2.UnpackLow(
Sse2.LoadVector128((SByte*)(pFld1)),
Sse2.LoadVector128((SByte*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte);
private static SByte[] _data1 = new SByte[Op1ElementCount];
private static SByte[] _data2 = new SByte[Op2ElementCount];
private static Vector128<SByte> _clsVar1;
private static Vector128<SByte> _clsVar2;
private Vector128<SByte> _fld1;
private Vector128<SByte> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__UnpackLowSByte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
}
public SimpleBinaryOpTest__UnpackLowSByte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
_dataTable = new DataTable(_data1, _data2, new SByte[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.UnpackLow(
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.UnpackLow(
Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.UnpackLow(
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.UnpackLow), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.UnpackLow), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.UnpackLow), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.UnpackLow(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<SByte>* pClsVar1 = &_clsVar1)
fixed (Vector128<SByte>* pClsVar2 = &_clsVar2)
{
var result = Sse2.UnpackLow(
Sse2.LoadVector128((SByte*)(pClsVar1)),
Sse2.LoadVector128((SByte*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr);
var result = Sse2.UnpackLow(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr));
var result = Sse2.UnpackLow(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr));
var result = Sse2.UnpackLow(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__UnpackLowSByte();
var result = Sse2.UnpackLow(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__UnpackLowSByte();
fixed (Vector128<SByte>* pFld1 = &test._fld1)
fixed (Vector128<SByte>* pFld2 = &test._fld2)
{
var result = Sse2.UnpackLow(
Sse2.LoadVector128((SByte*)(pFld1)),
Sse2.LoadVector128((SByte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.UnpackLow(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<SByte>* pFld1 = &_fld1)
fixed (Vector128<SByte>* pFld2 = &_fld2)
{
var result = Sse2.UnpackLow(
Sse2.LoadVector128((SByte*)(pFld1)),
Sse2.LoadVector128((SByte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.UnpackLow(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse2.UnpackLow(
Sse2.LoadVector128((SByte*)(&test._fld1)),
Sse2.LoadVector128((SByte*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(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<SByte> op1, Vector128<SByte> op2, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != left[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((i % 2 == 0) ? result[i] != left[i/2] : result[i] != right[(i - 1)/2])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.UnpackLow)}<SByte>(Vector128<SByte>, Vector128<SByte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
#region Copyright
/*
Copyright 2014 Cluster Reply s.r.l.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#endregion
/// -----------------------------------------------------------------------------------------------------------
/// Module : AdoNetAdapterConnection.cs
/// Description : Defines the connection to the target system.
/// -----------------------------------------------------------------------------------------------------------
#region Using Directives
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using Microsoft.ServiceModel.Channels.Common;
using System.Data.Common;
using System.Data;
#endregion
namespace Reply.Cluster.Mercury.Adapters.AdoNet
{
public class AdoNetAdapterConnection : IConnection
{
#region Private Fields
private AdoNetAdapterConnectionFactory connectionFactory;
private string connectionId;
#endregion Private Fields
/// <summary>
/// Initializes a new instance of the AdoNetAdapterConnection class with the AdoNetAdapterConnectionFactory
/// </summary>
public AdoNetAdapterConnection(AdoNetAdapterConnectionFactory connectionFactory)
{
this.connectionFactory = connectionFactory;
this.connectionId = Guid.NewGuid().ToString();
}
#region Public Properties
/// <summary>
/// Gets the ConnectionFactory
/// </summary>
public AdoNetAdapterConnectionFactory ConnectionFactory
{
get
{
return this.connectionFactory;
}
}
#endregion Public Properties
#region Custom Internal Properties
internal string connectionString;
internal DbProviderFactory providerFactory;
#endregion Custom Private Fields
#region IConnection Members
/// <summary>
/// Closes the connection to the target system
/// </summary>
public void Close(TimeSpan timeout) { }
/// <summary>
/// Returns a value indicating whether the connection is still valid
/// </summary>
public bool IsValid(TimeSpan timeout)
{
return true;
}
/// <summary>
/// Opens the connection to the target system.
/// </summary>
public void Open(TimeSpan timeout)
{
var uri = ConnectionFactory.ConnectionUri;
string name = uri.ConnectionName;
string provider = uri.ProviderName;
string connectionString = uri.ConnectionString;
if (string.IsNullOrEmpty(provider) || string.IsNullOrEmpty(connectionString))
{
var csElement = System.Configuration.ConfigurationManager.ConnectionStrings[name];
if (string.IsNullOrEmpty(provider))
provider = csElement.ProviderName;
if (string.IsNullOrEmpty(connectionString))
connectionString = csElement.ConnectionString;
}
this.providerFactory = DbProviderFactories.GetFactory(provider);
this.connectionString = connectionString;
// TODO: gestione delle eccezioni
}
/// <summary>
/// Clears the context of the Connection. This method is called when the connection is set back to the connection pool
/// </summary>
public void ClearContext() { }
/// <summary>
/// Builds a new instance of the specified IConnectionHandler type
/// </summary>
public TConnectionHandler BuildHandler<TConnectionHandler>(MetadataLookup metadataLookup)
where TConnectionHandler : class, IConnectionHandler
{
if (typeof(IOutboundHandler).IsAssignableFrom(typeof(TConnectionHandler)))
{
return new AdoNetAdapterOutboundHandler(this, metadataLookup) as TConnectionHandler;
}
if (typeof(IInboundHandler).IsAssignableFrom(typeof(TConnectionHandler)))
{
return new AdoNetAdapterInboundHandler(this, metadataLookup) as TConnectionHandler;
}
if (typeof(IMetadataResolverHandler).IsAssignableFrom(typeof(TConnectionHandler)))
{
return new AdoNetAdapterMetadataResolverHandler(this, metadataLookup) as TConnectionHandler;
}
if (typeof(IMetadataBrowseHandler).IsAssignableFrom(typeof(TConnectionHandler)))
{
return new AdoNetAdapterMetadataBrowseHandler(this, metadataLookup) as TConnectionHandler;
}
if (typeof(IMetadataSearchHandler).IsAssignableFrom(typeof(TConnectionHandler)))
{
return new AdoNetAdapterMetadataSearchHandler(this, metadataLookup) as TConnectionHandler;
}
return default(TConnectionHandler);
}
/// <summary>
/// Aborts the connection to the target system
/// </summary>
public void Abort() { }
/// <summary>
/// Gets the Id of the Connection
/// </summary>
public String ConnectionId
{
get
{
return connectionId;
}
}
#endregion IConnection Members
#region Internal Members
internal DbConnection CreateDbConnection()
{
var connection = providerFactory.CreateConnection();
connection.ConnectionString = connectionString;
return connection;
}
internal DbCommandBuilder CreateDbCommandBuilder(string table, DbConnection connection)
{
var commandBuilder = providerFactory.CreateCommandBuilder();
commandBuilder.DataAdapter = providerFactory.CreateDataAdapter();
if (!string.IsNullOrWhiteSpace(table))
{
var selectCommand = connection.CreateCommand();
selectCommand.CommandText = string.Format("SELECT * FROM {0} WHERE 0=1", commandBuilder.QuoteIdentifier(table));
commandBuilder.DataAdapter.SelectCommand = selectCommand;
}
return commandBuilder;
}
#endregion Internal Members
}
}
| |
using System;
using System.Collections.Generic;
using FF9;
using Memoria;
using Memoria.Assets;
using UnityEngine;
using XInputDotNetPure;
namespace Assets.Sources.Scripts.UI.Common
{
public class FF9UIDataTool
{
public static void DisplayItem(Int32 itemId, UISprite itemIcon, UILabel itemName, Boolean isEnable)
{
if (itemId != 255)
{
FF9ITEM_DATA ff9ITEM_DATA = ff9item._FF9Item_Data[itemId];
Byte b = (Byte)((!isEnable) ? 15 : ff9ITEM_DATA.color);
if (itemIcon != (UnityEngine.Object)null)
{
itemIcon.spriteName = "item" + ff9ITEM_DATA.shape.ToString("0#") + "_" + b.ToString("0#");
itemIcon.alpha = ((!isEnable) ? 0.5f : 1f);
}
if (itemName != (UnityEngine.Object)null)
{
itemName.text = FF9TextTool.ItemName(itemId);
itemName.color = ((!isEnable) ? FF9TextTool.Gray : FF9TextTool.White);
}
}
else
{
if (itemIcon != (UnityEngine.Object)null)
{
itemIcon.spriteName = String.Empty;
}
if (itemName != (UnityEngine.Object)null)
{
itemName.text = String.Empty;
}
}
}
public static void DisplayCharacterDetail(PLAYER player, CharacterDetailHUD charHud)
{
charHud.Self.SetActive(true);
charHud.NameLabel.text = player.name;
charHud.LvLabel.text = player.level.ToString();
Color color = (player.cur.hp != 0) ? ((player.cur.hp > player.max.hp / 6) ? FF9TextTool.White : FF9TextTool.Yellow) : FF9TextTool.Red;
charHud.HPLabel.text = player.cur.hp.ToString();
charHud.HPMaxLabel.text = player.max.hp.ToString();
charHud.HPTextColor = color;
color = ((player.cur.mp > player.max.mp / 6) ? FF9TextTool.White : FF9TextTool.Yellow);
charHud.MPLabel.text = player.cur.mp.ToString();
charHud.MPMaxLabel.text = player.max.mp.ToString();
charHud.MPTextColor = color;
if (charHud.MagicStoneLabel != (UnityEngine.Object)null)
{
charHud.MagicStoneLabel.text = player.cur.capa.ToString();
charHud.MagicStoneMaxLabel.text = player.max.capa.ToString();
charHud.MagicStoneTextColor = ((player.cur.capa != 0) ? FF9TextTool.White : FF9TextTool.Yellow);
}
if (charHud.StatusesSpriteList != null)
{
Int32 num = 0;
UISprite[] statusesSpriteList = charHud.StatusesSpriteList;
for (Int32 i = 0; i < (Int32)statusesSpriteList.Length; i++)
{
UISprite uisprite = statusesSpriteList[i];
if (((Int32)player.status & 1 << num) != 0)
{
uisprite.spriteName = FF9UIDataTool.IconSpriteName[FF9UIDataTool.status_id[num]];
uisprite.alpha = 1f;
}
else
{
uisprite.alpha = 0f;
}
num++;
}
}
}
public static void DisplayCharacterAvatar(PLAYER player, Vector3 frontPos, Vector3 backPos, UISprite avatarSprite, Boolean rowUpdate)
{
avatarSprite.spriteName = FF9UIDataTool.AvatarSpriteName(player.info.serial_no);
avatarSprite.alpha = ((player.cur.hp != 0) ? 1f : 0.5f);
if (rowUpdate)
{
if (player.info.row == 1)
{
avatarSprite.transform.localPosition = frontPos;
}
else if (player.info.row == 0)
{
avatarSprite.transform.localPosition = backPos;
}
}
}
public static void DisplayCharacterAvatar(Int32 serialId, Vector3 frontPos, Vector3 backPos, UISprite avatarSprite, Boolean rowUpdate)
{
avatarSprite.spriteName = FF9UIDataTool.AvatarSpriteName((Byte)serialId);
}
public static void DisplayCard(QuadMistCard card, CardDetailHUD cardHud, Boolean subCard = false)
{
for (Int32 i = 0; i < 8; i++)
{
Boolean flag = ((Int32)card.arrow & (Int32)Mathf.Pow(2f, (Single)i)) != 0;
flag = (!subCard && flag);
cardHud.CardArrowList[i].SetActive(flag);
}
cardHud.CardImageSprite.spriteName = "card_" + card.id.ToString("0#");
if (!subCard)
{
cardHud.AtkParamSprite.gameObject.SetActive(true);
cardHud.PhysicDefParamSprite.gameObject.SetActive(true);
cardHud.MagicDefParamSprite.gameObject.SetActive(true);
cardHud.AtkTypeParamSprite.gameObject.SetActive(true);
cardHud.AtkParamSprite.spriteName = "card_point_" + (card.atk >> 4).ToString("x");
cardHud.PhysicDefParamSprite.spriteName = "card_point_" + (card.pdef >> 4).ToString("x");
cardHud.MagicDefParamSprite.spriteName = "card_point_" + (card.mdef >> 4).ToString("x");
switch (card.type)
{
case QuadMistCard.Type.PHYSICAL:
cardHud.AtkTypeParamSprite.spriteName = "card_point_p";
break;
case QuadMistCard.Type.MAGIC:
cardHud.AtkTypeParamSprite.spriteName = "card_point_m";
break;
case QuadMistCard.Type.FLEXIABLE:
cardHud.AtkTypeParamSprite.spriteName = "card_point_x";
break;
case QuadMistCard.Type.ASSAULT:
cardHud.AtkTypeParamSprite.spriteName = "card_point_a";
break;
}
}
else
{
cardHud.AtkParamSprite.gameObject.SetActive(false);
cardHud.PhysicDefParamSprite.gameObject.SetActive(false);
cardHud.MagicDefParamSprite.gameObject.SetActive(false);
cardHud.AtkTypeParamSprite.gameObject.SetActive(false);
}
}
public static void DisplayAPBar(PLAYER player, Int32 abilityId, Boolean isShowText, APBarHUD apBar)
{
Int32 num = ff9abil.FF9Abil_GetAp(player.Index, abilityId);
Int32 num2 = ff9abil.FF9Abil_GetMax(player.Index, abilityId);
if (num >= num2)
{
apBar.TextPanel.SetActive(false);
apBar.APLable.text = num.ToString();
apBar.APMaxLable.text = num2.ToString();
apBar.ForegroundSprite.spriteName = "ap_bar_complete";
apBar.MasterSprite.spriteName = "ap_bar_complete_star";
apBar.Slider.value = 1f;
}
else
{
apBar.TextPanel.SetActive(isShowText);
apBar.APLable.text = num.ToString();
apBar.APMaxLable.text = num2.ToString();
apBar.ForegroundSprite.spriteName = "ap_bar_progress";
apBar.MasterSprite.spriteName = String.Empty;
apBar.Slider.value = (Single)num / (Single)num2;
}
}
public static void DisplayTextLocalize(GameObject go, String key)
{
go.GetComponent<UILocalize>().key = key;
go.GetComponent<UILabel>().text = Localization.Get(key);
}
public static UIAtlas WindowAtlas
{
get
{
if (FF9StateSystem.Settings.cfg.win_type == 0UL)
{
if (FF9UIDataTool.grayAtlas == (UnityEngine.Object)null)
{
String[] grayAtlasInfo;
FF9UIDataTool.grayAtlas = AssetManager.Load<UIAtlas>("EmbeddedAsset/UI/Atlas/Gray Atlas", out grayAtlasInfo, false);
}
return FF9UIDataTool.grayAtlas;
}
if (FF9UIDataTool.blueAtlas == (UnityEngine.Object)null)
{
String[] blueAtlasInfo;
FF9UIDataTool.blueAtlas = AssetManager.Load<UIAtlas>("EmbeddedAsset/UI/Atlas/Blue Atlas", out blueAtlasInfo, false);
}
return FF9UIDataTool.blueAtlas;
}
}
public static UIAtlas GrayAtlas
{
get
{
if (FF9UIDataTool.grayAtlas == (UnityEngine.Object)null)
{
String[] atlasInfo;
FF9UIDataTool.grayAtlas = AssetManager.Load<UIAtlas>("EmbeddedAsset/UI/Atlas/Gray Atlas", out atlasInfo, false);
}
return FF9UIDataTool.grayAtlas;
}
}
public static UIAtlas BlueAtlas
{
get
{
if (FF9UIDataTool.blueAtlas == (UnityEngine.Object)null)
{
String[] atlasInfo;
FF9UIDataTool.blueAtlas = AssetManager.Load<UIAtlas>("EmbeddedAsset/UI/Atlas/Blue Atlas", out atlasInfo, false);
}
return FF9UIDataTool.blueAtlas;
}
}
public static UIAtlas IconAtlas
{
get
{
if (FF9UIDataTool.iconAtlas == (UnityEngine.Object)null)
{
String[] atlasInfo;
FF9UIDataTool.iconAtlas = AssetManager.Load<UIAtlas>("EmbeddedAsset/UI/Atlas/Icon Atlas", out atlasInfo, false);
}
return FF9UIDataTool.iconAtlas;
}
}
public static UIAtlas GeneralAtlas
{
get
{
if (FF9UIDataTool.generalAtlas == (UnityEngine.Object)null)
{
String[] atlasInfo;
FF9UIDataTool.generalAtlas = AssetManager.Load<UIAtlas>("EmbeddedAsset/UI/Atlas/General Atlas", out atlasInfo, false);
}
return FF9UIDataTool.generalAtlas;
}
}
public static UIAtlas ScreenButtonAtlas
{
get
{
if (FF9UIDataTool.screenButtonAtlas == (UnityEngine.Object)null)
{
String[] atlasInfo;
FF9UIDataTool.screenButtonAtlas = AssetManager.Load<UIAtlas>("EmbeddedAsset/UI/Atlas/Screen Button Atlas", out atlasInfo, false);
}
return FF9UIDataTool.screenButtonAtlas;
}
}
public static UIAtlas TutorialAtlas
{
get
{
if (FF9UIDataTool.tutorialAtlas == (UnityEngine.Object)null)
{
String[] atlasInfo;
FF9UIDataTool.tutorialAtlas = AssetManager.Load<UIAtlas>("EmbeddedAsset/UI/Atlas/TutorialUI Atlas", out atlasInfo, false);
}
return FF9UIDataTool.tutorialAtlas;
}
}
public static GameObject IconGameObject(Int32 id)
{
GameObject result = (GameObject)null;
String spriteName = String.Empty;
if (id == FF9UIDataTool.NewIconId)
{
result = FF9UIDataTool.DrawButton(BitmapIconType.New);
}
else if (FF9UIDataTool.TutorialIconSpriteName.ContainsKey(id))
{
spriteName = FF9UIDataTool.TutorialIconSpriteName[id];
result = FF9UIDataTool.DrawButton(BitmapIconType.Sprite, FF9UIDataTool.TutorialAtlas, spriteName);
}
else if (FF9UIDataTool.IconSpriteName.ContainsKey(id))
{
spriteName = FF9UIDataTool.IconSpriteName[id];
result = FF9UIDataTool.DrawButton(BitmapIconType.Sprite, FF9UIDataTool.IconAtlas, spriteName);
}
return result;
}
public static Vector2 GetIconSize(Int32 id)
{
String spriteName = String.Empty;
Vector2 spriteSize = new Vector2(0f, 0f);
if (id == FF9UIDataTool.NewIconId)
{
spriteSize = new Vector2(115f, 64f);
}
else if (FF9UIDataTool.IconSpriteName.ContainsKey(id))
{
spriteName = FF9UIDataTool.IconSpriteName[id];
spriteSize = FF9UIDataTool.GetSpriteSize(spriteName);
}
return spriteSize;
}
public static GameObject ButtonGameObject(Control key, Boolean checkFromConfig, String tag)
{
GameObject result = (GameObject)null;
if (tag == NGUIText.JoyStickButtonIcon)
{
result = FF9UIDataTool.DrawButton(BitmapIconType.Sprite, FF9UIDataTool.IconAtlas, FF9UIDataTool.DialogButtonSpriteName(key, checkFromConfig, tag));
}
else if (PersistenSingleton<HonoInputManager>.Instance.IsControllerConnect && tag != NGUIText.KeyboardButtonIcon)
{
result = FF9UIDataTool.DrawButton(BitmapIconType.Sprite, FF9UIDataTool.IconAtlas, FF9UIDataTool.DialogButtonSpriteName(key, checkFromConfig, tag));
}
else
{
switch (key)
{
case Control.Confirm:
case Control.Cancel:
case Control.Menu:
case Control.Special:
case Control.LeftBumper:
case Control.RightBumper:
case Control.LeftTrigger:
case Control.RightTrigger:
{
KeyCode keycode;
if (tag == NGUIText.KeyboardButtonIcon)
{
keycode = PersistenSingleton<HonoInputManager>.Instance.DefaultInputKeys[(Int32)key];
}
else if (checkFromConfig)
{
keycode = PersistenSingleton<HonoInputManager>.Instance.InputKeysPrimary[(Int32)key];
}
else
{
keycode = PersistenSingleton<HonoInputManager>.Instance.DefaultInputKeys[(Int32)key];
}
result = FF9UIDataTool.DrawButton(BitmapIconType.Keyboard, keycode);
break;
}
case Control.Pause:
result = FF9UIDataTool.DrawButton(BitmapIconType.Sprite, FF9UIDataTool.IconAtlas, "keyboard_button_backspace");
break;
case Control.Select:
result = FF9UIDataTool.DrawButton(BitmapIconType.Keyboard, KeyCode.Alpha1);
break;
case Control.Up:
result = FF9UIDataTool.DrawButton(BitmapIconType.Keyboard, KeyCode.W);
break;
case Control.Down:
result = FF9UIDataTool.DrawButton(BitmapIconType.Keyboard, KeyCode.S);
break;
case Control.Left:
result = FF9UIDataTool.DrawButton(BitmapIconType.Keyboard, KeyCode.A);
break;
case Control.Right:
result = FF9UIDataTool.DrawButton(BitmapIconType.Keyboard, KeyCode.D);
break;
case Control.DPad:
result = FF9UIDataTool.DrawButton(BitmapIconType.Sprite, FF9UIDataTool.IconAtlas, "ps_dpad");
break;
}
}
return result;
}
private static GameObject GetMobileButtonGameObject(Control key)
{
GameObject result = (GameObject)null;
Int32 key2 = 0;
Int32 num = EventEngineUtils.eventIDToMESID[(Int32)FF9StateSystem.Common.FF9.fldMapNo];
if (num != 2)
{
if (num != 3)
{
}
}
else if (key == Control.Up)
{
key2 = 268;
}
FF9UIDataTool.DrawButton(BitmapIconType.Sprite, FF9UIDataTool.IconAtlas, FF9UIDataTool.IconSpriteName[key2]);
return result;
}
public static Vector2 GetButtonSize(Control key, Boolean checkFromConfig, String tag)
{
String spriteName = String.Empty;
if (tag == NGUIText.JoyStickButtonIcon)
{
spriteName = FF9UIDataTool.DialogButtonSpriteName(key, checkFromConfig, tag);
}
else if (PersistenSingleton<HonoInputManager>.Instance.IsControllerConnect && tag != NGUIText.KeyboardButtonIcon)
{
spriteName = FF9UIDataTool.DialogButtonSpriteName(key, checkFromConfig, tag);
}
else
{
switch (key)
{
case Control.Confirm:
case Control.Cancel:
case Control.Menu:
case Control.Special:
case Control.LeftBumper:
case Control.RightBumper:
case Control.LeftTrigger:
case Control.RightTrigger:
case Control.Pause:
case Control.Select:
case Control.Up:
case Control.Down:
case Control.Left:
case Control.Right:
spriteName = "keyboard_button";
break;
case Control.DPad:
spriteName = "ps_dpad";
break;
}
}
if (!checkFromConfig && (FF9StateSystem.PCPlatform || FF9StateSystem.AndroidPlatform))
{
bool flag = !global::GamePad.GetState(PlayerIndex.One).IsConnected;
if (flag)
{
if (key == Control.Pause)
{
spriteName = "keyboard_button_backspace";
}
}
}
return FF9UIDataTool.GetSpriteSize(spriteName);
}
private static Vector2 GetSpriteSize(String spriteName)
{
UISpriteData sprite = FF9UIDataTool.IconAtlas.GetSprite(spriteName);
Vector2 result;
if (sprite == null)
{
result = new Vector2(64f, 64f);
}
else
{
Int32 num = sprite.width + sprite.paddingLeft + sprite.paddingRight;
Int32 num2 = sprite.height + sprite.paddingTop + sprite.paddingBottom;
result = new Vector2((Single)num, (Single)num2);
}
return result;
}
private static GameObject DrawButton(BitmapIconType bitmapIconType)
{
return FF9UIDataTool.GetControllerGameObject(bitmapIconType);
}
private static GameObject DrawButton(BitmapIconType bitmapIconType, UIAtlas atlas, String spriteName)
{
spriteName = FF9UIDataTool.CheckIconLocalize(spriteName);
GameObject controllerGameObject = FF9UIDataTool.GetControllerGameObject(bitmapIconType);
FF9UIDataTool.DrawSprite(controllerGameObject, atlas, spriteName);
return controllerGameObject;
}
private static GameObject DrawButton(BitmapIconType bitmapIconType, KeyCode keycode)
{
GameObject controllerGameObject = FF9UIDataTool.GetControllerGameObject(bitmapIconType);
FF9UIDataTool.DrawLabel(controllerGameObject.GetChild(0), keycode);
return controllerGameObject;
}
private static GameObject GetControllerGameObject(BitmapIconType bitmapIconType)
{
GameObject gameObject = (GameObject)null;
switch (bitmapIconType)
{
case BitmapIconType.Sprite:
gameObject = FF9UIDataTool.GetGameObjectFromPool(FF9UIDataTool.bitmapSpritePool);
if (gameObject == (UnityEngine.Object)null)
{
if (FF9UIDataTool.controllerSpritePrefab == (UnityEngine.Object)null)
{
FF9UIDataTool.controllerSpritePrefab = (Resources.Load("EmbeddedAsset/UI/Prefabs/Controller Sprite") as GameObject);
}
gameObject = UnityEngine.Object.Instantiate<GameObject>(FF9UIDataTool.controllerSpritePrefab);
gameObject.tag = "BitmapSprite";
}
gameObject.SetActive(false);
FF9UIDataTool.activeBitmapSpriteList.Push(gameObject);
break;
case BitmapIconType.Keyboard:
gameObject = FF9UIDataTool.GetGameObjectFromPool(FF9UIDataTool.bitmapKeyboardPool);
if (gameObject == (UnityEngine.Object)null)
{
if (FF9UIDataTool.controllerKeyboardPrefab == (UnityEngine.Object)null)
{
FF9UIDataTool.controllerKeyboardPrefab = (Resources.Load("EmbeddedAsset/UI/Prefabs/Controller Keyboard") as GameObject);
}
gameObject = UnityEngine.Object.Instantiate<GameObject>(FF9UIDataTool.controllerKeyboardPrefab);
gameObject.tag = "BitmapKeyboard";
}
gameObject.SetActive(false);
FF9UIDataTool.activeBitmapKeyboardList.Push(gameObject);
break;
case BitmapIconType.New:
gameObject = FF9UIDataTool.GetGameObjectFromPool(FF9UIDataTool.bitmapNewIconPool);
if (gameObject == (UnityEngine.Object)null)
{
if (FF9UIDataTool.newIconPrefab == (UnityEngine.Object)null)
{
FF9UIDataTool.newIconPrefab = (Resources.Load("EmbeddedAsset/UI/Prefabs/New Icon") as GameObject);
}
gameObject = UnityEngine.Object.Instantiate<GameObject>(FF9UIDataTool.newIconPrefab);
gameObject.tag = "BitmapNewIcon";
}
gameObject.SetActive(false);
FF9UIDataTool.activeBitmapNewIconList.Push(gameObject);
break;
}
return gameObject;
}
private static GameObject GetGameObjectFromPool(List<GameObject> currentPool)
{
GameObject gameObject = (GameObject)null;
if (currentPool.Count > 0)
{
gameObject = currentPool.Pop<GameObject>();
gameObject.SetActive(false);
}
return gameObject;
}
private static String CheckIconLocalize(String spriteName)
{
String key = spriteName + "#" + FF9StateSystem.Settings.CurrentLanguage;
if (FF9UIDataTool.iconLocalizeList.ContainsKey(key))
{
spriteName = FF9UIDataTool.iconLocalizeList[key];
}
return spriteName;
}
public static void ReleaseBitmapIconToPool(GameObject bitmap)
{
List<GameObject> theList;
List<GameObject> list;
FF9UIDataTool.GetCurrentPool(bitmap.tag, out theList, out list);
bitmap.transform.parent = PersistenSingleton<UIManager>.Instance.transform;
bitmap.SetActive(false);
list.Remove(bitmap);
theList.Push(bitmap);
}
private static void GetCurrentPool(String tag, out List<GameObject> currentPool, out List<GameObject> currentActivePool)
{
switch (tag)
{
case "BitmapKeyboard":
currentPool = FF9UIDataTool.bitmapKeyboardPool;
currentActivePool = FF9UIDataTool.activeBitmapKeyboardList;
return;
case "BitmapSprite":
currentPool = FF9UIDataTool.bitmapSpritePool;
currentActivePool = FF9UIDataTool.activeBitmapSpriteList;
return;
case "BitmapNewIcon":
currentPool = FF9UIDataTool.bitmapNewIconPool;
currentActivePool = FF9UIDataTool.activeBitmapNewIconList;
return;
}
currentPool = null;
currentActivePool = null;
}
private static void ReleaseAllBitmapIconsToPool(List<GameObject> currentPool, List<GameObject> currentActiveList)
{
foreach (GameObject gameObject in currentActiveList)
{
gameObject.transform.parent = PersistenSingleton<UIManager>.Instance.transform;
gameObject.SetActive(false);
}
currentPool.AddRange(currentActiveList);
currentActiveList.Clear();
}
public static void ReleaseAllTypeBitmapIconsToPool()
{
if (FF9UIDataTool.activeBitmapKeyboardList.Count != 0)
{
FF9UIDataTool.ReleaseAllBitmapIconsToPool(FF9UIDataTool.bitmapKeyboardPool, FF9UIDataTool.activeBitmapKeyboardList);
}
if (FF9UIDataTool.activeBitmapSpriteList.Count != 0)
{
FF9UIDataTool.ReleaseAllBitmapIconsToPool(FF9UIDataTool.bitmapSpritePool, FF9UIDataTool.activeBitmapSpriteList);
}
if (FF9UIDataTool.activeBitmapNewIconList.Count != 0)
{
FF9UIDataTool.ReleaseAllBitmapIconsToPool(FF9UIDataTool.bitmapNewIconPool, FF9UIDataTool.activeBitmapNewIconList);
}
}
public static void ClearAllPool()
{
FF9UIDataTool.bitmapKeyboardPool.Clear();
FF9UIDataTool.bitmapSpritePool.Clear();
FF9UIDataTool.bitmapNewIconPool.Clear();
}
public static void DrawSprite(GameObject go, UIAtlas atlas, String spriteName)
{
UISprite component = go.GetComponent<UISprite>();
component.atlas = atlas;
component.spriteName = spriteName;
component.MakePixelPerfect();
}
public static void DrawLabel(GameObject go, KeyCode keycode)
{
String text = String.Empty;
if (FF9UIDataTool.KeyboardIconLabel.ContainsKey(keycode))
{
text = FF9UIDataTool.KeyboardIconLabel[keycode];
}
UILabel component = go.GetComponent<UILabel>();
component.text = text;
if (keycode >= KeyCode.Keypad0 && keycode <= KeyCode.KeypadPlus)
{
go.transform.localPosition = new Vector3(go.transform.localPosition.x, -37f, go.transform.localPosition.z);
FF9UIDataTool.DrawSprite(go.GetParent(), FF9UIDataTool.IconAtlas, "keyboard_button_num");
}
else
{
go.transform.localPosition = new Vector3(go.transform.localPosition.x, -31f, go.transform.localPosition.z);
FF9UIDataTool.DrawSprite(go.GetParent(), FF9UIDataTool.IconAtlas, "keyboard_button");
}
}
public static String DialogButtonSpriteName(Control key, Boolean checkFromConfig, String tag)
{
String result = String.Empty;
if (PersistenSingleton<HonoInputManager>.Instance.IsControllerConnect || tag == NGUIText.JoyStickButtonIcon)
{
Dictionary<String, String> dictionary;
if (Application.platform == RuntimePlatform.Android)
{
dictionary = FF9UIDataTool.buttonSpriteNameAndroidJoystick;
}
else if (Application.platform == RuntimePlatform.IPhonePlayer)
{
dictionary = FF9UIDataTool.buttonSpriteNameiOSJoystick;
}
else
{
dictionary = FF9UIDataTool.buttonSpriteNameJoystick;
}
switch (key)
{
case Control.Confirm:
case Control.Cancel:
case Control.Menu:
case Control.Special:
case Control.LeftBumper:
case Control.RightBumper:
case Control.LeftTrigger:
case Control.RightTrigger:
{
String key2;
if (checkFromConfig)
{
key2 = PersistenSingleton<HonoInputManager>.Instance.JoystickKeysPrimary[(Int32)key];
}
else
{
key2 = PersistenSingleton<HonoInputManager>.Instance.DefaultJoystickInputKeys[(Int32)key];
}
if (dictionary.ContainsKey(key2))
{
result = dictionary[key2];
}
break;
}
case Control.Pause:
result = FF9UIDataTool.buttonSpriteNameJoystick["JoystickButton6"];
break;
case Control.Select:
result = FF9UIDataTool.buttonSpriteNameJoystick["JoystickButton7"];
break;
case Control.Up:
result = dictionary["Up"];
break;
case Control.Down:
result = dictionary["Down"];
break;
case Control.Left:
result = dictionary["Left"];
break;
case Control.Right:
result = dictionary["Right"];
break;
case Control.DPad:
result = dictionary["DPad"];
break;
}
}
return result;
}
public static String GetJoystickSpriteByName(String key)
{
String result = String.Empty;
if (Application.platform == RuntimePlatform.IPhonePlayer)
{
if (FF9UIDataTool.buttonSpriteNameiOSJoystick.ContainsKey(key))
{
result = FF9UIDataTool.buttonSpriteNameiOSJoystick[key];
}
}
else if (Application.platform == RuntimePlatform.Android)
{
if (FF9UIDataTool.buttonSpriteNameAndroidJoystick.ContainsKey(key))
{
result = FF9UIDataTool.buttonSpriteNameAndroidJoystick[key];
}
}
else if (FF9UIDataTool.buttonSpriteNameJoystick.ContainsKey(key))
{
result = FF9UIDataTool.buttonSpriteNameJoystick[key];
}
return result;
}
public static String AvatarSpriteName(Byte serialNo)
{
switch (serialNo)
{
case 0:
case 1:
return "face00";
case 2:
return "face01";
case 3:
case 4:
if (Configuration.Graphics.GarnetHair == 2)
return "face03";
return "face02";
case 5:
case 6:
if (Configuration.Graphics.GarnetHair == 1)
return "face02";
return "face03";
case 7:
case 8:
return "face04";
case 9:
return "face05";
case 10:
case 11:
return "face06";
case 12:
return "face07";
case 13:
return "face08";
case 14:
return "face09";
case 15:
return "face10";
case 16:
case 17:
return "face11";
case 18:
return "face12";
default:
return String.Empty;
}
}
public static Sprite LoadWorldTitle(SByte titleId, Boolean isShadow)
{
Sprite sprite = (Sprite)null;
String text;
if (FF9StateSystem.Settings.CurrentLanguage == "English(UK)")
{
text = "US";
}
else
{
text = Localization.GetSymbol();
}
String text2;
if ((Int32)titleId == (Int32)FF9UIDataTool.WorldTitleMistContinent)
{
text2 = "title_world_mist";
}
else if ((Int32)titleId == (Int32)FF9UIDataTool.WorldTitleOuterContinent)
{
text2 = "title_world_outer";
}
else if ((Int32)titleId == (Int32)FF9UIDataTool.WorldTitleForgottenContinent)
{
text2 = "title_world_forgotten";
}
else
{
if ((Int32)titleId != (Int32)FF9UIDataTool.WorldTitleLostContinent)
{
global::Debug.LogError("World Continent Title: Could not found resource from titleId:" + titleId);
return sprite;
}
text2 = "title_world_lost";
}
text2 += ((!isShadow) ? ("_" + text.ToLower()) : ("_shadow_" + text.ToLower()));
if (FF9UIDataTool.worldTitleSpriteList.ContainsKey(text2))
{
sprite = FF9UIDataTool.worldTitleSpriteList[text2];
}
else
{
String path = "EmbeddedAsset/UI/Sprites/" + text + "/" + text2;
String[] spriteInfo;
sprite = AssetManager.Load<Sprite>(path, out spriteInfo, false);
FF9UIDataTool.worldTitleSpriteList.Add(text2, sprite);
}
return sprite;
}
public static readonly Int32 NewIconId = 400;
private static UIAtlas generalAtlas;
private static UIAtlas iconAtlas;
private static UIAtlas grayAtlas;
private static UIAtlas blueAtlas;
private static UIAtlas screenButtonAtlas;
private static UIAtlas tutorialAtlas;
private static GameObject controllerSpritePrefab = (GameObject)null;
private static GameObject controllerKeyboardPrefab = (GameObject)null;
private static GameObject newIconPrefab = (GameObject)null;
private static List<GameObject> bitmapKeyboardPool = new List<GameObject>();
private static List<GameObject> bitmapSpritePool = new List<GameObject>();
private static List<GameObject> bitmapNewIconPool = new List<GameObject>();
private static List<GameObject> activeBitmapKeyboardList = new List<GameObject>();
private static List<GameObject> activeBitmapSpriteList = new List<GameObject>();
private static List<GameObject> activeBitmapNewIconList = new List<GameObject>();
public static Int32[] status_id = new Int32[]
{
154,
153,
152,
151,
150,
149,
148
};
private static Dictionary<String, String> buttonSpriteNameiOSJoystick = new Dictionary<String, String>
{
{
"JoystickButton14",
"joystick_button_a"
},
{
"JoystickButton13",
"joystick_button_b"
},
{
"JoystickButton15",
"joystick_button_x"
},
{
"JoystickButton12",
"joystick_button_y"
},
{
"JoystickButton8",
"joystick_l1"
},
{
"JoystickButton9",
"joystick_r1"
},
{
"JoystickButton10",
"joystick_l2"
},
{
"JoystickButton11",
"joystick_r2"
},
{
"JoystickButton0",
"joystick_start"
},
{
"Empty",
"joystick_analog_r"
},
{
"Up",
"ps_dpad_up"
},
{
"Down",
"ps_dpad_down"
},
{
"Left",
"ps_dpad_left"
},
{
"Right",
"ps_dpad_right"
},
{
"DPad",
"ps_dpad"
}
};
private static Dictionary<String, String> buttonSpriteNameAndroidJoystick = new Dictionary<String, String>
{
{
"JoystickButton0",
"joystick_button_a"
},
{
"JoystickButton1",
"joystick_button_b"
},
{
"JoystickButton2",
"joystick_button_x"
},
{
"JoystickButton3",
"joystick_button_y"
},
{
"JoystickButton4",
"joystick_l1"
},
{
"JoystickButton5",
"joystick_r1"
},
{
"LeftTrigger Android",
"joystick_l2"
},
{
"RightTrigger Android",
"joystick_r2"
},
{
"JoystickButton10",
"joystick_start"
},
{
"Empty",
"joystick_analog_r"
},
{
"Up",
"ps_dpad_up"
},
{
"Down",
"ps_dpad_down"
},
{
"Left",
"ps_dpad_left"
},
{
"Right",
"ps_dpad_right"
},
{
"DPad",
"ps_dpad"
}
};
private static Dictionary<String, String> buttonSpriteNameJoystick = new Dictionary<String, String>
{
{
"JoystickButton0",
"joystick_button_a"
},
{
"JoystickButton1",
"joystick_button_b"
},
{
"JoystickButton2",
"joystick_button_x"
},
{
"JoystickButton3",
"joystick_button_y"
},
{
"JoystickButton4",
"joystick_l1"
},
{
"JoystickButton5",
"joystick_r1"
},
{
"LeftTrigger",
"joystick_l2"
},
{
"RightTrigger",
"joystick_r2"
},
{
"JoystickButton6",
"joystick_start"
},
{
"JoystickButton7",
"joystick_select"
},
{
"Up",
"ps_dpad_up"
},
{
"Down",
"ps_dpad_down"
},
{
"Left",
"ps_dpad_left"
},
{
"Right",
"ps_dpad_right"
},
{
"DPad",
"ps_dpad"
}
};
public static readonly Dictionary<Int32, String> IconSpriteName = new Dictionary<Int32, String>
{
{
1,
"cursor_hand_choice"
},
{
19,
"arrow_up"
},
{
20,
"arrow_down"
},
{
27,
"help_mog_dialog"
},
{
28,
"help_mog_hand_1"
},
{
29,
"help_mog_hand_2"
},
{
92,
"item00_00"
},
{
93,
"item01_00"
},
{
94,
"item02_00"
},
{
95,
"item03_00"
},
{
96,
"item04_00"
},
{
97,
"item05_00"
},
{
98,
"item06_00"
},
{
99,
"item07_00"
},
{
100,
"item08_00"
},
{
101,
"item09_00"
},
{
102,
"item10_00"
},
{
103,
"item11_00"
},
{
104,
"item12_00"
},
{
105,
"item13_01"
},
{
106,
"item14_02"
},
{
107,
"item15_01"
},
{
108,
"item16_01"
},
{
109,
"item17_01"
},
{
110,
"item18_00"
},
{
111,
"item19_02"
},
{
112,
"item20_01"
},
{
113,
"item21_00"
},
{
114,
"item22_02"
},
{
115,
"item23_00"
},
{
116,
"item24_00"
},
{
117,
"item25_03"
},
{
118,
"item26_09"
},
{
119,
"item27_01"
},
{
120,
"item28_03"
},
{
121,
"item29_01"
},
{
122,
"item30_00"
},
{
123,
"item31_08"
},
{
124,
"item32_02"
},
{
125,
"item33_01"
},
{
126,
"item34_02"
},
{
127,
"item35_03"
},
{
131,
"icon_status_22"
},
{
132,
"icon_status_23"
},
{
133,
"icon_status_11"
},
{
134,
"icon_status_00"
},
{
135,
"icon_status_01"
},
{
136,
"icon_status_02"
},
{
137,
"icon_status_03"
},
{
138,
"icon_status_04"
},
{
139,
"icon_status_05"
},
{
140,
"icon_status_06"
},
{
141,
"icon_status_07"
},
{
142,
"icon_status_08"
},
{
143,
"icon_status_09"
},
{
144,
"icon_status_10"
},
{
145,
"icon_status_12"
},
{
146,
"icon_status_13"
},
{
147,
"icon_status_14"
},
{
148,
"icon_status_15"
},
{
149,
"icon_status_16"
},
{
150,
"icon_status_17"
},
{
151,
"icon_status_18"
},
{
152,
"icon_status_19"
},
{
153,
"icon_status_20"
},
{
154,
"icon_status_21"
},
{
180,
"text_lv_us_uk_jp_gr_it"
},
{
188,
"ability_stone"
},
{
189,
"skill_stone_on"
},
{
190,
"ability_stone_null"
},
{
191,
"skill_stone_null"
},
{
192,
"ap_bar_complete_star"
},
{
193,
"skill_stone_gem"
},
{
244,
"skill_stone_off"
},
{
254,
"ap_bar_full"
},
{
255,
"ap_bar_half"
},
{
257,
"balloon_exclamation"
},
{
258,
"balloon_question"
},
{
259,
"balloon_card"
},
{
260,
"icon_action"
},
{
261,
"icon_back"
},
{
262,
"icon_analog"
},
{
263,
"virtual_up"
},
{
264,
"virtual_down"
},
{
265,
"virtual_left"
},
{
266,
"virtual_right"
},
{
267,
"icon_left"
},
{
268,
"icon_up"
},
{
269,
"icon_right"
},
{
270,
"icon_down"
},
{
271,
"icon_x"
},
{
272,
"icon_y"
},
{
273,
"icon_b"
},
{
274,
"icon_a"
},
{
275,
"icon_minus"
},
{
276,
"icon_plus"
},
{
277,
"icon_racing_01"
},
{
278,
"icon_racing_02"
},
{
279,
"icon_help"
},
{
280,
"virtual_aside"
},
{
281,
"icon_world_map"
},
{
282,
"icon_world_mog"
},
{
283,
"icon_world_map"
},
{
284,
"icon_cam_rotate"
},
{
285,
"icon_cam_perspective"
},
{
286,
"icon_world_dismount"
},
{
287,
"icon_cam_align"
},
{
288,
"icon_menu_jp"
},
{
289,
"icon_menu_us"
},
{
290,
"icon_menu_fr"
},
{
291,
"icon_menu_es"
},
{
292,
"icon_menu_gr"
},
{
293,
"icon_menu_it"
},
{
294,
"icon_menu_uk"
},
{
295,
"icon_deck_jp"
},
{
296,
"icon_deck_us"
},
{
297,
"icon_deck_fr"
},
{
298,
"icon_deck_es"
},
{
299,
"icon_deck_gr"
},
{
300,
"icon_deck_it"
},
{
301,
"icon_deck_uk"
},
{
302,
"icon_battle_run"
},
{
303,
"icon_battle_all"
},
{
304,
"icon_pause"
},
{
305,
"icon_bubble_question"
},
{
306,
"text_touch_us_uk_fr_gr_it_es"
},
{
307,
"text_touchconfirm_us_uk_fr_gr_it_es"
},
{
308,
"text_touchscreen_us_uk_fr_gr_it_es"
},
{
309,
"text_characterpanel_us_uk_fr_gr_it_es"
},
{
310,
"icon_bubble_card"
},
{
311,
"icon_chocobo_dig"
},
{
312,
"icon_bubble_question"
},
{
313,
"icon_ate_us_uk_jp"
},
{
314,
"icon_ate_es_fr"
},
{
315,
"icon_ate_gr_it"
},
{
316,
"text_touch_jp"
},
{
317,
"text_touch_us_uk"
},
{
318,
"text_touch_fr"
},
{
319,
"text_touch_es"
},
{
320,
"text_touch_gr"
},
{
321,
"text_touch_it"
},
{
322,
"text_touchconfirm_jp"
},
{
323,
"text_touchconfirm_us_uk"
},
{
324,
"text_touchconfirm_fr"
},
{
325,
"text_touchconfirm_es"
},
{
326,
"text_touchconfirm_gr"
},
{
327,
"text_touchconfirm_it"
},
{
328,
"text_touchscreen_jp"
},
{
329,
"text_touchscreen_us_uk"
},
{
330,
"text_touchscreen_fr"
},
{
331,
"text_touchscreen_es"
},
{
332,
"text_touchscreen_gr"
},
{
333,
"text_touchscreen_it"
},
{
334,
"text_characterpanel_jp"
},
{
335,
"text_characterpanel_us_uk"
},
{
336,
"text_characterpanel_fr"
},
{
337,
"text_characterpanel_es"
},
{
338,
"text_characterpanel_gr"
},
{
339,
"text_characterpanel_it"
},
{
340,
"icon_ate_us_uk_jp"
},
{
341,
"icon_ate_es_fr"
},
{
342,
"icon_ate_gr_it"
},
{
343,
"icon_beach"
},
{
512,
"item01_06"
},
{
513,
"item01_12"
},
{
514,
"item03_03"
},
{
515,
"item03_05"
},
{
516,
"item03_09"
},
{
517,
"item03_11"
},
{
518,
"item03_13"
},
{
519,
"item04_03"
},
{
520,
"item05_03"
},
{
521,
"item05_05"
},
{
522,
"item05_06"
},
{
523,
"item05_12"
},
{
524,
"item06_03"
},
{
525,
"item06_06"
},
{
526,
"item06_13"
},
{
527,
"item08_03"
},
{
528,
"item08_04"
},
{
529,
"item08_12"
},
{
530,
"item09_02"
},
{
531,
"item09_03"
},
{
532,
"item09_07"
},
{
533,
"item10_02"
},
{
534,
"item10_05"
},
{
535,
"item10_09"
},
{
536,
"item10_11"
},
{
537,
"item11_02"
},
{
538,
"item11_04"
},
{
539,
"item13_02"
},
{
540,
"item13_03"
},
{
541,
"item13_07"
},
{
542,
"item13_14"
},
{
543,
"item14_08"
},
{
544,
"item14_09"
},
{
545,
"item14_11"
},
{
546,
"item15_02"
},
{
547,
"item15_04"
},
{
548,
"item15_07"
},
{
549,
"item15_08"
},
{
550,
"item15_09"
},
{
551,
"item15_12"
},
{
552,
"item16_03"
},
{
553,
"item16_08"
},
{
554,
"item16_09"
},
{
555,
"item16_12"
},
{
556,
"item17_02"
},
{
557,
"item17_03"
},
{
558,
"item17_08"
},
{
559,
"item17_14"
},
{
560,
"item18_06"
},
{
561,
"item18_08"
},
{
562,
"item18_09"
},
{
563,
"item18_10"
},
{
564,
"item18_11"
},
{
565,
"item18_14"
},
{
566,
"item19_03"
},
{
567,
"item19_06"
},
{
568,
"item19_08"
},
{
569,
"item19_11"
},
{
570,
"item19_12"
},
{
571,
"item20_02"
},
{
572,
"item20_03"
},
{
573,
"item20_06"
},
{
574,
"item20_10"
},
{
575,
"item20_11"
},
{
576,
"item20_14"
},
{
577,
"item21_01"
},
{
578,
"item21_02"
},
{
579,
"item21_03"
},
{
580,
"item21_04"
},
{
581,
"item21_05"
},
{
582,
"item21_06"
},
{
583,
"item21_07"
},
{
584,
"item21_08"
},
{
585,
"item21_10"
},
{
586,
"item21_12"
},
{
587,
"item21_13"
},
{
588,
"item21_14"
},
{
589,
"item22_06"
},
{
590,
"item22_08"
},
{
591,
"item22_09"
},
{
592,
"item23_03"
},
{
593,
"item23_05"
},
{
594,
"item23_06"
},
{
595,
"item23_07"
},
{
596,
"item23_09"
},
{
597,
"item23_10"
},
{
598,
"item24_02"
},
{
599,
"item24_03"
},
{
600,
"item24_04"
},
{
601,
"item24_06"
},
{
602,
"item24_08"
},
{
603,
"item24_10"
},
{
604,
"item24_11"
},
{
605,
"item25_09"
},
{
606,
"item27_09"
},
{
607,
"item28_08"
},
{
608,
"item29_02"
},
{
609,
"item29_03"
},
{
610,
"item29_04"
},
{
611,
"item29_08"
},
{
612,
"item29_10"
},
{
613,
"item29_12"
},
{
614,
"item29_14"
},
{
615,
"item31_09"
},
{
616,
"item31_14"
},
{
617,
"item32_03"
},
{
618,
"item33_02"
},
{
619,
"item33_03"
},
{
620,
"item33_04"
},
{
621,
"item33_05"
},
{
622,
"item33_11"
},
{
623,
"item33_14"
},
{
624,
"item35_12"
},
{
625,
"icon_equip_0"
},
{
626,
"icon_equip_1"
},
{
627,
"icon_equip_2"
},
{
628,
"icon_equip_3"
},
{
629,
"icon_equip_4"
},
{
630,
"keyboard_button_enter"
},
{
631,
"keyboard_button_esc"
},
{
632,
"keyboard_button_arrow_up"
},
{
633,
"keyboard_button_arrow_left"
},
{
634,
"keyboard_button_arrow_right"
},
{
635,
"keyboard_button_arrow_down"
},
{
636,
"text_lv_es"
},
{
637,
"text_lv_fr"
},
{
638,
"joystick_start"
},
{
639,
"joystick_l2"
},
{
640,
"joystick_r2"
},
{
641,
"joystick_button_y"
}
};
public static readonly Dictionary<Int32, String> TutorialIconSpriteName = new Dictionary<Int32, String>
{
{
769,
"tutorial_quadmist_2"
},
{
770,
"tutorial_quadmist_3"
}
};
public static readonly Dictionary<KeyCode, String> KeyboardIconLabel = new Dictionary<KeyCode, String>
{
{
KeyCode.Exclaim,
"!"
},
{
KeyCode.DoubleQuote,
"\""
},
{
KeyCode.Hash,
"#"
},
{
KeyCode.Dollar,
"$"
},
{
KeyCode.Ampersand,
"&"
},
{
KeyCode.Quote,
"'"
},
{
KeyCode.LeftParen,
"("
},
{
KeyCode.RightParen,
")"
},
{
KeyCode.Asterisk,
"*"
},
{
KeyCode.Plus,
"+"
},
{
KeyCode.Comma,
","
},
{
KeyCode.Minus,
"-"
},
{
KeyCode.Period,
"."
},
{
KeyCode.Slash,
"/"
},
{
KeyCode.Alpha0,
"0"
},
{
KeyCode.Alpha1,
"1"
},
{
KeyCode.Alpha2,
"2"
},
{
KeyCode.Alpha3,
"3"
},
{
KeyCode.Alpha4,
"4"
},
{
KeyCode.Alpha5,
"5"
},
{
KeyCode.Alpha6,
"6"
},
{
KeyCode.Alpha7,
"7"
},
{
KeyCode.Alpha8,
"8"
},
{
KeyCode.Alpha9,
"9"
},
{
KeyCode.Colon,
":"
},
{
KeyCode.Semicolon,
";"
},
{
KeyCode.Less,
"<"
},
{
KeyCode.Equals,
"="
},
{
KeyCode.Greater,
">"
},
{
KeyCode.Question,
"?"
},
{
KeyCode.At,
"@"
},
{
KeyCode.LeftBracket,
"["
},
{
KeyCode.Backslash,
"\\"
},
{
KeyCode.RightBracket,
"]"
},
{
KeyCode.Caret,
"^"
},
{
KeyCode.Underscore,
"_"
},
{
KeyCode.BackQuote,
"`"
},
{
KeyCode.A,
"A"
},
{
KeyCode.B,
"B"
},
{
KeyCode.C,
"C"
},
{
KeyCode.D,
"D"
},
{
KeyCode.E,
"E"
},
{
KeyCode.F,
"F"
},
{
KeyCode.G,
"G"
},
{
KeyCode.H,
"H"
},
{
KeyCode.I,
"I"
},
{
KeyCode.J,
"J"
},
{
KeyCode.K,
"K"
},
{
KeyCode.L,
"L"
},
{
KeyCode.M,
"M"
},
{
KeyCode.N,
"N"
},
{
KeyCode.O,
"O"
},
{
KeyCode.P,
"P"
},
{
KeyCode.Q,
"Q"
},
{
KeyCode.R,
"R"
},
{
KeyCode.S,
"S"
},
{
KeyCode.T,
"T"
},
{
KeyCode.U,
"U"
},
{
KeyCode.V,
"V"
},
{
KeyCode.W,
"W"
},
{
KeyCode.X,
"X"
},
{
KeyCode.Y,
"Y"
},
{
KeyCode.Z,
"Z"
},
{
KeyCode.Keypad0,
"0"
},
{
KeyCode.Keypad1,
"1"
},
{
KeyCode.Keypad2,
"2"
},
{
KeyCode.Keypad3,
"3"
},
{
KeyCode.Keypad4,
"4"
},
{
KeyCode.Keypad5,
"5"
},
{
KeyCode.Keypad6,
"6"
},
{
KeyCode.Keypad7,
"7"
},
{
KeyCode.Keypad8,
"8"
},
{
KeyCode.Keypad9,
"9"
},
{
KeyCode.KeypadDivide,
"/"
},
{
KeyCode.KeypadPeriod,
"."
},
{
KeyCode.KeypadMultiply,
"*"
},
{
KeyCode.KeypadPlus,
"+"
},
{
KeyCode.KeypadMinus,
"-"
},
{
KeyCode.F1,
"F1"
},
{
KeyCode.F2,
"F2"
},
{
KeyCode.F3,
"F3"
},
{
KeyCode.F4,
"F4"
},
{
KeyCode.F5,
"F5"
},
{
KeyCode.F6,
"F6"
},
{
KeyCode.F7,
"F7"
},
{
KeyCode.F8,
"F8"
},
{
KeyCode.F9,
"F9"
},
{
KeyCode.F10,
"F10"
},
{
KeyCode.F11,
"F11"
},
{
KeyCode.F12,
"F12"
}
};
private static readonly SByte WorldTitleMistContinent = 0;
private static readonly SByte WorldTitleOuterContinent = 1;
private static readonly SByte WorldTitleForgottenContinent = 2;
private static readonly SByte WorldTitleLostContinent = 3;
private static Dictionary<String, Sprite> worldTitleSpriteList = new Dictionary<String, Sprite>();
private static readonly Dictionary<String, String> iconLocalizeList = new Dictionary<String, String>
{
{
"keyboard_button_enter#French",
"keyboard_button_enter_fr_gr"
},
{
"keyboard_button_enter#German",
"keyboard_button_enter_fr_gr"
},
{
"keyboard_button_enter#Italian",
"keyboard_button_enter_it"
},
{
"keyboard_button_backspace#French",
"keyboard_button_backspace_fr_gr_it"
},
{
"keyboard_button_backspace#German",
"keyboard_button_backspace_fr_gr_it"
},
{
"keyboard_button_backspace#Italian",
"keyboard_button_backspace_fr_gr_it"
}
};
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.IO;
using Microsoft.Build.Shared;
using System.Reflection;
using Xunit;
using Microsoft.Build.Tasks;
using Microsoft.Build.Framework;
using Microsoft.Build.UnitTests.Shared;
namespace Microsoft.Build.UnitTests
{
public class TypeLoader_Tests
{
private static readonly string ProjectFileFolder = Path.Combine(BuildEnvironmentHelper.Instance.CurrentMSBuildToolsDirectory, "PortableTask");
private static readonly string ProjectFileName = "portableTaskTest.proj";
private static readonly string DLLFileName = "PortableTask.dll";
[Fact]
public void Basic()
{
Assert.True(TypeLoader.IsPartialTypeNameMatch("Csc", "csc")); // ==> exact match
Assert.True(TypeLoader.IsPartialTypeNameMatch("Microsoft.Build.Tasks.Csc", "Microsoft.Build.Tasks.Csc")); // ==> exact match
Assert.True(TypeLoader.IsPartialTypeNameMatch("Microsoft.Build.Tasks.Csc", "Csc")); // ==> partial match
Assert.True(TypeLoader.IsPartialTypeNameMatch("Microsoft.Build.Tasks.Csc", "Tasks.Csc")); // ==> partial match
Assert.True(TypeLoader.IsPartialTypeNameMatch("MyTasks.ATask+NestedTask", "NestedTask")); // ==> partial match
Assert.True(TypeLoader.IsPartialTypeNameMatch("MyTasks.ATask\\\\+NestedTask", "NestedTask")); // ==> partial match
Assert.False(TypeLoader.IsPartialTypeNameMatch("MyTasks.CscTask", "Csc")); // ==> no match
Assert.False(TypeLoader.IsPartialTypeNameMatch("MyTasks.MyCsc", "Csc")); // ==> no match
Assert.False(TypeLoader.IsPartialTypeNameMatch("MyTasks.ATask\\.Csc", "Csc")); // ==> no match
Assert.False(TypeLoader.IsPartialTypeNameMatch("MyTasks.ATask\\\\\\.Csc", "Csc")); // ==> no match
}
[Fact]
public void Regress_Mutation_TrailingPartMustMatch()
{
Assert.False(TypeLoader.IsPartialTypeNameMatch("Microsoft.Build.Tasks.Csc", "Vbc"));
}
[Fact]
public void Regress_Mutation_ParameterOrderDoesntMatter()
{
Assert.True(TypeLoader.IsPartialTypeNameMatch("Csc", "Microsoft.Build.Tasks.Csc"));
}
[Fact]
public void LoadNonExistingAssembly()
{
using (var dir = new FileUtilities.TempWorkingDirectory(ProjectFileFolder))
{
string projectFilePath = Path.Combine(dir.Path, ProjectFileName);
string dllName = "NonExistent.dll";
bool successfulExit;
string output = RunnerUtilities.ExecMSBuild(projectFilePath + " /v:diag /p:AssemblyPath=" + dllName, out successfulExit);
Assert.False(successfulExit);
string dllPath = Path.Combine(BuildEnvironmentHelper.Instance.CurrentMSBuildToolsDirectory, dllName);
CheckIfCorrectAssemblyLoaded(output, dllPath, false);
}
}
[Fact]
public void LoadInsideAsssembly()
{
using (var dir = new FileUtilities.TempWorkingDirectory(ProjectFileFolder))
{
string projectFilePath = Path.Combine(dir.Path, ProjectFileName);
bool successfulExit;
string output = RunnerUtilities.ExecMSBuild(projectFilePath + " /v:diag", out successfulExit);
Assert.True(successfulExit);
string dllPath = Path.Combine(dir.Path, DLLFileName);
CheckIfCorrectAssemblyLoaded(output, dllPath);
}
}
[Fact]
public void LoadOutsideAssembly()
{
using (var dir = new FileUtilities.TempWorkingDirectory(ProjectFileFolder))
{
string projectFilePath = Path.Combine(dir.Path, ProjectFileName);
string originalDLLPath = Path.Combine(dir.Path, DLLFileName);
string movedDLLPath = MoveOrCopyDllToTempDir(originalDLLPath, copy: false);
try
{
bool successfulExit;
string output = RunnerUtilities.ExecMSBuild(projectFilePath + " /v:diag /p:AssemblyPath=" + movedDLLPath, out successfulExit);
Assert.True(successfulExit);
CheckIfCorrectAssemblyLoaded(output, movedDLLPath);
}
finally
{
UndoDLLOperations(movedDLLPath);
}
}
}
[Fact (Skip = "https://github.com/Microsoft/msbuild/issues/325")]
public void LoadInsideAssemblyWhenGivenOutsideAssemblyWithSameName()
{
using (var dir = new FileUtilities.TempWorkingDirectory(ProjectFileFolder))
{
string projectFilePath = Path.Combine(dir.Path, ProjectFileName);
string originalDLLPath = Path.Combine(dir.Path, DLLFileName);
string copiedDllPath = MoveOrCopyDllToTempDir(originalDLLPath, copy: true);
try
{
bool successfulExit;
string output = RunnerUtilities.ExecMSBuild(projectFilePath + " /v:diag /p:AssemblyPath=" + copiedDllPath, out successfulExit);
Assert.True(successfulExit);
CheckIfCorrectAssemblyLoaded(output, originalDLLPath);
}
finally
{
UndoDLLOperations(copiedDllPath);
}
}
}
/// <summary>
/// </summary>
/// <param name="copy"></param>
/// <returns>Path to new DLL</returns>
private string MoveOrCopyDllToTempDir(string originalDllPath, bool copy)
{
var temporaryDirectory = FileUtilities.GetTemporaryDirectory();
var newDllPath = Path.Combine(temporaryDirectory, DLLFileName);
Assert.True(File.Exists(originalDllPath));
if (copy)
{
File.Copy(originalDllPath, newDllPath);
Assert.True(File.Exists(newDllPath));
}
else
{
File.Move(originalDllPath, newDllPath);
Assert.True(File.Exists(newDllPath));
Assert.False(File.Exists(originalDllPath));
}
return newDllPath;
}
/// <summary>
/// Delete newDllPath and delete temp directory
/// </summary>
/// <param name="newDllPath"></param>
/// <param name="moveBack">If true, move newDllPath back to bin. If false, delete it</param>
private void UndoDLLOperations(string newDllPath)
{
var tempDirectoryPath = Path.GetDirectoryName(newDllPath);
File.Delete(newDllPath);
Assert.False(File.Exists(newDllPath));
Assert.Empty(Directory.EnumerateFiles(tempDirectoryPath));
Directory.Delete(tempDirectoryPath);
Assert.False(Directory.Exists(tempDirectoryPath));
}
private void CheckIfCorrectAssemblyLoaded(string scriptOutput, string expectedAssemblyPath, bool expectedSuccess = true)
{
var successfulMessage = @"Using ""ShowItems"" task from assembly """ + expectedAssemblyPath + @""".";
if (expectedSuccess)
{
Assert.Contains(successfulMessage, scriptOutput, StringComparison.OrdinalIgnoreCase);
}
else
{
Assert.DoesNotContain(successfulMessage, scriptOutput, StringComparison.OrdinalIgnoreCase);
}
}
#if FEATURE_ASSEMBLY_LOCATION
/// <summary>
/// Make sure that when we load multiple types out of the same assembly with different type filters that both the fullyqualified name matching and the
/// partial name matching still work.
/// </summary>
[Fact]
public void Regress640476PartialName()
{
string forwardingLoggerLocation = typeof(Microsoft.Build.Logging.ConfigurableForwardingLogger).Assembly.Location;
TypeLoader loader = new TypeLoader(IsForwardingLoggerClass);
LoadedType loadedType = loader.Load("ConfigurableForwardingLogger", AssemblyLoadInfo.Create(null, forwardingLoggerLocation));
Assert.NotNull(loadedType);
Assert.Equal(forwardingLoggerLocation, loadedType.Assembly.AssemblyLocation);
string fileLoggerLocation = typeof(Microsoft.Build.Logging.FileLogger).Assembly.Location;
loader = new TypeLoader(IsLoggerClass);
loadedType = loader.Load("FileLogger", AssemblyLoadInfo.Create(null, fileLoggerLocation));
Assert.NotNull(loadedType);
Assert.Equal(fileLoggerLocation, loadedType.Assembly.AssemblyLocation);
}
/// <summary>
/// Make sure that when we load multiple types out of the same assembly with different type filters that both the fullyqualified name matching and the
/// partial name matching still work.
/// </summary>
[Fact]
public void Regress640476FullyQualifiedName()
{
Type forwardingLoggerType = typeof(Microsoft.Build.Logging.ConfigurableForwardingLogger);
string forwardingLoggerLocation = forwardingLoggerType.Assembly.Location;
TypeLoader loader = new TypeLoader(IsForwardingLoggerClass);
LoadedType loadedType = loader.Load(forwardingLoggerType.FullName, AssemblyLoadInfo.Create(null, forwardingLoggerLocation));
Assert.NotNull(loadedType);
Assert.Equal(forwardingLoggerLocation, loadedType.Assembly.AssemblyLocation);
Type fileLoggerType = typeof(Microsoft.Build.Logging.FileLogger);
string fileLoggerLocation = fileLoggerType.Assembly.Location;
loader = new TypeLoader(IsLoggerClass);
loadedType = loader.Load(fileLoggerType.FullName, AssemblyLoadInfo.Create(null, fileLoggerLocation));
Assert.NotNull(loadedType);
Assert.Equal(fileLoggerLocation, loadedType.Assembly.AssemblyLocation);
}
/// <summary>
/// Make sure if no typeName is passed in then pick the first type which matches the desired type filter.
/// This has been in since whidbey but there has been no test for it and it was broken in the last refactoring of TypeLoader.
/// This test is to prevent that from happening again.
/// </summary>
[Fact]
public void NoTypeNamePicksFirstType()
{
Type forwardingLoggerType = typeof(Microsoft.Build.Logging.ConfigurableForwardingLogger);
string forwardingLoggerAssemblyLocation = forwardingLoggerType.Assembly.Location;
Func<Type, object, bool> forwardingLoggerfilter = IsForwardingLoggerClass;
Type firstPublicType = FirstPublicDesiredType(forwardingLoggerfilter, forwardingLoggerAssemblyLocation);
TypeLoader loader = new TypeLoader(forwardingLoggerfilter);
LoadedType loadedType = loader.Load(String.Empty, AssemblyLoadInfo.Create(null, forwardingLoggerAssemblyLocation));
Assert.NotNull(loadedType);
Assert.Equal(forwardingLoggerAssemblyLocation, loadedType.Assembly.AssemblyLocation);
Assert.Equal(firstPublicType, loadedType.Type);
Type fileLoggerType = typeof(Microsoft.Build.Logging.FileLogger);
string fileLoggerAssemblyLocation = forwardingLoggerType.Assembly.Location;
Func<Type, object, bool> fileLoggerfilter = IsLoggerClass;
firstPublicType = FirstPublicDesiredType(fileLoggerfilter, fileLoggerAssemblyLocation);
loader = new TypeLoader(fileLoggerfilter);
loadedType = loader.Load(String.Empty, AssemblyLoadInfo.Create(null, fileLoggerAssemblyLocation));
Assert.NotNull(loadedType);
Assert.Equal(fileLoggerAssemblyLocation, loadedType.Assembly.AssemblyLocation);
Assert.Equal(firstPublicType, loadedType.Type);
}
private static Type FirstPublicDesiredType(Func<Type, object, bool> filter, string assemblyLocation)
{
Assembly loadedAssembly = Assembly.UnsafeLoadFrom(assemblyLocation);
// only look at public types
Type[] allPublicTypesInAssembly = loadedAssembly.GetExportedTypes();
foreach (Type publicType in allPublicTypesInAssembly)
{
if (filter(publicType, null))
{
return publicType;
}
}
return null;
}
private static bool IsLoggerClass(Type type, object unused)
{
return (type.IsClass &&
!type.IsAbstract &&
(type.GetInterface("ILogger") != null));
}
private static bool IsForwardingLoggerClass(Type type, object unused)
{
return (type.IsClass &&
!type.IsAbstract &&
(type.GetInterface("IForwardingLogger") != null));
}
#endif
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace Scalider.Text
{
/// <summary>
/// Represents an <see cref="ITextTransformer"/> that converts alphabetic, numeric, and symbolic Unicode characters
/// which are not in the first 127 ASCII characters (the "Basic Latin" Unicode block) into their ASCII equivalents,
/// if one exists.
/// <para />
/// Characters from the following Unicode blocks are converted; however, only those characters with reasonable
/// ASCII alternatives are converted:
/// <para />
/// <ul>
/// <item><description>C1 Controls and Latin-1 Supplement: <a href="http://www.unicode.org/charts/PDF/U0080.pdf">http://www.unicode.org/charts/PDF/U0080.pdf</a></description></item>
/// <item><description>Latin Extended-A: <a href="http://www.unicode.org/charts/PDF/U0100.pdf">http://www.unicode.org/charts/PDF/U0100.pdf</a></description></item>
/// <item><description>Latin Extended-B: <a href="http://www.unicode.org/charts/PDF/U0180.pdf">http://www.unicode.org/charts/PDF/U0180.pdf</a></description></item>
/// <item><description>Latin Extended Additional: <a href="http://www.unicode.org/charts/PDF/U1E00.pdf">http://www.unicode.org/charts/PDF/U1E00.pdf</a></description></item>
/// <item><description>Latin Extended-C: <a href="http://www.unicode.org/charts/PDF/U2C60.pdf">http://www.unicode.org/charts/PDF/U2C60.pdf</a></description></item>
/// <item><description>Latin Extended-D: <a href="http://www.unicode.org/charts/PDF/UA720.pdf">http://www.unicode.org/charts/PDF/UA720.pdf</a></description></item>
/// <item><description>IPA Extensions: <a href="http://www.unicode.org/charts/PDF/U0250.pdf">http://www.unicode.org/charts/PDF/U0250.pdf</a></description></item>
/// <item><description>Phonetic Extensions: <a href="http://www.unicode.org/charts/PDF/U1D00.pdf">http://www.unicode.org/charts/PDF/U1D00.pdf</a></description></item>
/// <item><description>Phonetic Extensions Supplement: <a href="http://www.unicode.org/charts/PDF/U1D80.pdf">http://www.unicode.org/charts/PDF/U1D80.pdf</a></description></item>
/// <item><description>General Punctuation: <a href="http://www.unicode.org/charts/PDF/U2000.pdf">http://www.unicode.org/charts/PDF/U2000.pdf</a></description></item>
/// <item><description>Superscripts and Subscripts: <a href="http://www.unicode.org/charts/PDF/U2070.pdf">http://www.unicode.org/charts/PDF/U2070.pdf</a></description></item>
/// <item><description>Enclosed Alphanumerics: <a href="http://www.unicode.org/charts/PDF/U2460.pdf">http://www.unicode.org/charts/PDF/U2460.pdf</a></description></item>
/// <item><description>Dingbats: <a href="http://www.unicode.org/charts/PDF/U2700.pdf">http://www.unicode.org/charts/PDF/U2700.pdf</a></description></item>
/// <item><description>Supplemental Punctuation: <a href="http://www.unicode.org/charts/PDF/U2E00.pdf">http://www.unicode.org/charts/PDF/U2E00.pdf</a></description></item>
/// <item><description>Alphabetic Presentation Forms: <a href="http://www.unicode.org/charts/PDF/UFB00.pdf">http://www.unicode.org/charts/PDF/UFB00.pdf</a></description></item>
/// <item><description>Halfwidth and Fullwidth Forms: <a href="http://www.unicode.org/charts/PDF/UFF00.pdf">http://www.unicode.org/charts/PDF/UFF00.pdf</a></description></item>
/// </ul>
/// <para/>
/// See: <a href="http://en.wikipedia.org/wiki/Latin_characters_in_Unicode">http://en.wikipedia.org/wiki/Latin_characters_in_Unicode</a>
/// <para/>
/// <![CDATA[For example, 'à' will be replaced by 'a'.]]>
/// </summary>
/// <remarks>
/// https://github.com/apache/lucenenet/blob/master/src/Lucene.Net.Analysis.Common/Analysis/Miscellaneous/ASCIIFoldingFilter.cs
/// </remarks>
public sealed class AsciiFoldingTextTransformer : TextTransformerBase
{
private static readonly object LockObj = new object();
private static ITextTransformer? _instance;
private static IDictionary<ushort, char[]>? _charAsciiFoldingTable;
private AsciiFoldingTextTransformer()
{
}
/// <summary>
/// Gets a singleton instance of the <see cref="AsciiFoldingTextTransformer"/>.
/// </summary>
public static ITextTransformer Instance
{
get
{
lock (LockObj)
{
return _instance ??= new AsciiFoldingTextTransformer();
}
}
}
/// <inheritdoc />
public override ReadOnlySpan<char> Transform(ReadOnlySpan<char> input)
{
var inputLength = input.Length;
if (inputLength <= 0)
return ReadOnlySpan<char>.Empty;
return input.IsWhiteSpace()
? input // The input only contains whitespace characters, we don't need to do any transformation
: base.Transform(input, inputLength, inputLength * 4);
}
/// <inheritdoc />
protected override void TransformCharacter(char chr, char[] output, ref int outputPosition,
bool isLastCharacter)
{
// Determine whether the current character is in the first 127 ASCII characters
if (chr < FirstNonAsciiCharacter)
output[outputPosition++] = chr;
else
{
// The current character is not in the first 127 ASCII characters
if (chr >= FirstSurrogateCharacter && chr <= LastSurrogateCharacter)
{
// Surrogate characters should be ignored
return;
}
FoldToAscii(chr, output, ref outputPosition);
}
}
private static void InitializeCharactersAsciiFoldingTableIfNeeded()
{
if (_charAsciiFoldingTable != null)
return;
// We need to initialize the character ASCII folding table
_charAsciiFoldingTable = new Dictionary<ushort, char[]>();
using var stream = typeof(AsciiFoldingTextTransformer).Assembly
.GetManifestResourceStream("Scalider.Text.data.ascii_folding.dat");
// Determine whether the character ASCII folding data is available
if (stream == null)
return;
// The character ASCII folding data is available, lets read it
using var reader = new BinaryReader(stream);
// First we need to retrieve all the indexed data
var totalConversions = reader.ReadByte();
var conversions = new List<char[]>();
for (var i = 0; i < totalConversions; i++)
{
var length = reader.ReadByte();
conversions.Add(reader.ReadChars(length));
}
// Then retrieve teh characters and map them to the actual conversion data
var totalDataCount = reader.ReadInt16();
for (var i = 0; i < totalDataCount; i++)
{
var charCode = reader.ReadUInt16();
var dataIndex = reader.ReadByte();
_charAsciiFoldingTable[charCode] = conversions[dataIndex];
}
}
private static void FoldToAscii(char chr, char[] output, ref int outputPos)
{
lock (LockObj)
{
InitializeCharactersAsciiFoldingTableIfNeeded();
if (_charAsciiFoldingTable!.TryGetValue(chr, out var conversion) && conversion != null)
{
// We can fold the ASCII character
foreach (var c in conversion)
output[outputPos++] = c;
}
else
output[outputPos++] = chr;
}
}
#region GenerateAsciiFoldingDataFileAsync
#if DEBUG
public static async Task GenerateAsciiFoldingDataFileAsync(string output,
CancellationToken cancellationToken = default)
{
using var httpClient = new HttpClient();
var response = await httpClient.SendAsync(
new HttpRequestMessage(
HttpMethod.Get,
"https://raw.githubusercontent.com/apache/lucenenet/master/src/Lucene.Net.Analysis.Common/Analysis/Miscellaneous/ASCIIFoldingFilter.cs"
),
HttpCompletionOption.ResponseHeadersRead,
cancellationToken
);
// Determine whether the response was successful
if (!response.IsSuccessStatusCode)
return;
// Read the content of the response
var content = await response.Content.ReadAsStringAsync();
if (string.IsNullOrWhiteSpace(content))
return;
//
var resultSet = new List<CharacterConversionHolder>();
{
var isInsideCaseStatement = false;
var charCodes = new List<ushort>();
var sb = new StringBuilder();
foreach (var l in content.Replace("\r", "").Split("\n"))
{
if (string.IsNullOrWhiteSpace(l))
continue;
var charCodeMatch = Regex.Match(l, @"case '\\u(?<Value>[a-zA-Z0-9]{4})':");
var outputMatch = Regex.Match(l, @"= '(?<Value>(.*){1})';");
if (charCodeMatch.Success)
{
//
isInsideCaseStatement = true;
var charCode = ushort.Parse(charCodeMatch.Groups["Value"].Value, NumberStyles.HexNumber);
charCodes.Add(charCode);
}
else if (isInsideCaseStatement && outputMatch.Success)
{
//
var value = outputMatch.Groups["Value"].Value;
if (value[0] == '\\' && value.Length == 2 && value[1] == '\'') value = "'";
if (value[0] == '\\' && value.Length == 2 && value[1] == '\\') value = @"\";
sb.Append(value[0]);
}
else if (isInsideCaseStatement && l.Trim().Equals("break;", StringComparison.OrdinalIgnoreCase))
{
//
resultSet.Add(new CharacterConversionHolder(charCodes.ToArray(), sb.ToString()));
isInsideCaseStatement = false;
charCodes.Clear();
sb.Clear();
}
}
}
// Initialize the binary writer
await using var writer = new BinaryWriter(File.OpenWrite(output));
// First, we need to write all the conversion values and keep track of the indices, that
// way we don't need to repeat the conversion for each character
var codesToIndicesMap = new Dictionary<byte, ushort[]>();
writer.Write((byte) resultSet.Count);
foreach (var item in resultSet)
{
codesToIndicesMap.Add((byte) codesToIndicesMap.Count, item.Characters);
writer.Write(item.ConversionLength);
writer.Write(item.ConversionCharacters);
}
// Write the character with the index where for the conversion
var totalDataCount = resultSet.Sum(t => t.Characters.Length);
writer.Write((short) totalDataCount);
foreach (var (index, codes) in codesToIndicesMap)
{
foreach (var c in codes)
{
writer.Write(c);
writer.Write(index);
}
}
// Flush the binary writer
writer.Flush();
}
private readonly struct CharacterConversionHolder
{
public CharacterConversionHolder(ushort[] characters, string conversion)
{
Characters = characters;
ConversionCharacters = conversion.ToCharArray();
}
public ushort[] Characters { get; }
public char[] ConversionCharacters { get; }
public byte ConversionLength => (byte) ConversionCharacters.Length;
}
#endif
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using Diagnostics.Tracing;
using Diagnostics.Tracing.Parsers;
using FastSerialization;
using Utilities;
using System.IO;
using System.Diagnostics.Tracing;
namespace Diagnostics.Tracing.Parsers
{
/// <summary>
/// A DynamicTraceEventParser is a parser that understands how to read the embedded manifests that occur in the
/// dataStream (System.Diagnostics.Tracing.EventSources do this).
///
/// See also code:TDHDynamicTraceEventParser which knows how to read the manifest that are registered globally with
/// the machine.
/// </summary>
public class DynamicTraceEventParser : TraceEventParser
{
public DynamicTraceEventParser(TraceEventSource source)
: base(source)
{
if (source == null) // Happens during deserialization.
return;
// Try to retieve persisted state
state = (DynamicTraceEventParserState)StateObject;
if (state == null)
{
StateObject = state = new DynamicTraceEventParserState();
dynamicManifests = new Dictionary<Guid, DynamicManifestInfo>();
this.source.RegisterUnhandledEvent(delegate(TraceEvent data)
{
if (data.ID != (TraceEventID)0xFFFE)
return data;
// Look up our information.
DynamicManifestInfo dynamicManifest;
if (!dynamicManifests.TryGetValue(data.ProviderGuid, out dynamicManifest))
{
dynamicManifest = new DynamicManifestInfo();
dynamicManifests.Add(data.ProviderGuid, dynamicManifest);
}
ProviderManifest provider = dynamicManifest.AddChunk(data);
// We have a completed manifest, add it to our list.
if (provider != null)
AddDynamicProvider(provider);
return data;
});
}
else if (allCallbackCalled)
{
foreach (ProviderManifest provider in state.providers.Values)
provider.AddProviderEvents(source, allCallback);
}
}
public override event Action<TraceEvent> All
{
add
{
if (state != null)
{
foreach (ProviderManifest provider in state.providers.Values)
provider.AddProviderEvents(source, value);
}
allCallback += value;
allCallbackCalled = true;
}
remove
{
throw new Exception("Not supported");
}
}
/// <summary>
/// Returns a list of providers (their manifest) that this TraceParser knows about.
/// </summary>
public IEnumerable<ProviderManifest> DynamicProviders
{
get
{
return state.providers.Values;
}
}
/// <summary>
/// Given a manifest describing the provider add its information to the parser.
/// </summary>
/// <param name="providerManifest"></param>
public void AddDynamicProvider(ProviderManifest providerManifest)
{
// Remember this serialized information.
state.providers[providerManifest.Guid] = providerManifest;
// If someone as asked for callbacks on every event, then include these too.
if (allCallbackCalled)
providerManifest.AddProviderEvents(source, allCallback);
}
/// <summary>
/// Utility method that stores all the manifests known to the DynamicTraceEventParser to the directory 'directoryPath'
/// </summary>
public void WriteAllManifests(string directoryPath)
{
Directory.CreateDirectory(directoryPath);
foreach (var providerManifest in DynamicProviders)
{
var filePath = Path.Combine(directoryPath, providerManifest.Name + ".manifest.xml");
providerManifest.WriteToFile(filePath);
}
}
/// <summary>
/// Utility method that read all the manifests the directory 'directoryPath' into the parser.
/// </summary>
public void ReadAllManifests(string directoryPath)
{
foreach (var fileName in Directory.GetFiles(directoryPath, "*.manifest.xml"))
{
AddDynamicProvider(new ProviderManifest(fileName));
}
foreach (var fileName in Directory.GetFiles(directoryPath, "*.man"))
{
AddDynamicProvider(new ProviderManifest(fileName));
}
}
#region private
// This allows protected members to avoid the normal initization.
protected DynamicTraceEventParser(TraceEventSource source, bool noInit) : base(source) { }
private class DynamicManifestInfo
{
internal DynamicManifestInfo() { }
byte[][] Chunks;
int ChunksLeft;
ProviderManifest provider;
byte majorVersion;
byte minorVersion;
ManifestEnvelope.ManifestFormats format;
internal unsafe ProviderManifest AddChunk(TraceEvent data)
{
if (provider != null)
return null;
// TODO
if (data.EventDataLength <= sizeof(ManifestEnvelope) || data.GetByteAt(3) != 0x5B) // magic number
return null;
ushort totalChunks = (ushort)data.GetInt16At(4);
ushort chunkNum = (ushort)data.GetInt16At(6);
if (chunkNum >= totalChunks || totalChunks == 0)
return null;
if (Chunks == null)
{
format = (ManifestEnvelope.ManifestFormats)data.GetByteAt(0);
majorVersion = (byte)data.GetByteAt(1);
minorVersion = (byte)data.GetByteAt(2);
ChunksLeft = totalChunks;
Chunks = new byte[ChunksLeft][];
}
else
{
// Chunks have to agree with the format and version information.
if (format != (ManifestEnvelope.ManifestFormats)data.GetByteAt(0) ||
majorVersion != data.GetByteAt(1) || minorVersion != data.GetByteAt(2))
return null;
}
if (Chunks[chunkNum] != null)
return null;
byte[] chunk = new byte[data.EventDataLength - 8];
Chunks[chunkNum] = data.EventData(chunk, 0, 8, chunk.Length);
--ChunksLeft;
if (ChunksLeft > 0)
return null;
// OK we have a complete set of chunks
byte[] serializedData = Chunks[0];
if (Chunks.Length > 1)
{
int totalLength = 0;
for (int i = 0; i < Chunks.Length; i++)
totalLength += Chunks[i].Length;
// Concatinate all the arrays.
serializedData = new byte[totalLength];
int pos = 0;
for (int i = 0; i < Chunks.Length; i++)
{
Array.Copy(Chunks[i], 0, serializedData, pos, Chunks[i].Length);
pos += Chunks[i].Length;
}
}
Chunks = null;
// string str = Encoding.UTF8.GetString(serializedData);
provider = new ProviderManifest(serializedData, format, majorVersion, minorVersion);
provider.ISDynamic = true;
return provider;
}
}
DynamicTraceEventParserState state;
private Dictionary<Guid, DynamicManifestInfo> dynamicManifests;
Action<TraceEvent> allCallback;
bool allCallbackCalled;
#endregion
}
/// <summary>
/// A ProviderManifest represents the XML manifest associated with teh provider.
/// </summary>
public class ProviderManifest : IFastSerializable
{
// create a manifest from a stream or a file
/// <summary>
/// Read a ProviderManifest from a stream
/// </summary>
public ProviderManifest(Stream manifestStream, int manifestLen = int.MaxValue)
{
format = ManifestEnvelope.ManifestFormats.SimpleXmlFormat;
int len = Math.Min((int)(manifestStream.Length - manifestStream.Position), manifestLen);
serializedManifest = new byte[len];
manifestStream.Read(serializedManifest, 0, len);
}
/// <summary>
/// Read a ProviderManifest from a file.
/// </summary>
public ProviderManifest(string manifestFilePath)
{
format = ManifestEnvelope.ManifestFormats.SimpleXmlFormat;
serializedManifest = File.ReadAllBytes(manifestFilePath);
}
// write a manifest to a stream or a file.
/// <summary>
/// Writes the manifest to 'outputStream' (as UTF8 XML text)
/// </summary>
public void WriteToStream(Stream outputStream)
{
outputStream.Write(serializedManifest, 0, serializedManifest.Length);
}
/// <summary>
/// Writes the manifest to a file 'filePath' (as a UTF8 XML)
/// </summary>
/// <param name="filePath"></param>
public void WriteToFile(string filePath)
{
using (var stream = File.Create(filePath))
WriteToStream(stream);
}
/// <summary>
/// Set if this manifest came from the ETL data stream file.
/// </summary>
public bool ISDynamic { get; internal set; }
// Get at the data in the manifest.
public string Name { get { if (!inited) Init(); return name; } }
public Guid Guid { get { if (!inited) Init(); return guid; } }
/// <summary>
/// Retrieve manifest as one big string.
/// </summary>
public string Manifest { get { if (!inited) Init(); return Encoding.UTF8.GetString(serializedManifest); } }
/// <summary>
/// Retrieve the manifest as XML
/// </summary>
public XmlReader ManifestReader
{
get
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreComments = true;
settings.IgnoreWhitespace = true;
// TODO FIX NOW remove
// var manifest = System.Text.Encoding.UTF8.GetString(serializedManifest);
// Trace.WriteLine(manifest);
System.IO.MemoryStream stream = new System.IO.MemoryStream(serializedManifest);
return XmlReader.Create(stream, settings);
}
}
#region private
internal ProviderManifest(byte[] serializedManifest, ManifestEnvelope.ManifestFormats format, byte majorVersion, byte minorVersion)
{
this.serializedManifest = serializedManifest;
this.majorVersion = majorVersion;
this.minorVersion = minorVersion;
this.format = format;
}
internal void AddProviderEvents(ITraceParserServices source, Action<TraceEvent> callback)
{
if (error != null)
return;
if (!inited)
Init();
try
{
Dictionary<string, int> opcodes = new Dictionary<string, int>();
opcodes.Add("win:Info", 0);
opcodes.Add("win:Start", 1);
opcodes.Add("win:Stop", 2);
opcodes.Add("win:DC_Start", 3);
opcodes.Add("win:DC_Stop", 4);
opcodes.Add("win:Extension", 5);
opcodes.Add("win:Reply", 6);
opcodes.Add("win:Resume", 7);
opcodes.Add("win:Suspend", 8);
opcodes.Add("win:Send", 9);
opcodes.Add("win:Receive", 240);
Dictionary<string, TaskInfo> tasks = new Dictionary<string, TaskInfo>();
Dictionary<string, TemplateInfo> templates = new Dictionary<string, TemplateInfo>();
Dictionary<string, IDictionary<long, string>> maps = null;
Dictionary<string, string> strings = new Dictionary<string, string>();
IDictionary<long, string> map = null;
List<EventInfo> events = new List<EventInfo>();
bool alreadyReadMyCulture = false; // I read my culture some time in the past (I can igore things)
string cultureBeingRead = null;
while (reader.Read())
{
// TODO I currently require opcodes,and tasks BEFORE events BEFORE templates.
// Can be fixed by going multi-pass.
switch (reader.Name)
{
case "event":
{
int taskNum = 0;
Guid taskGuid = Guid;
string taskName = reader.GetAttribute("task");
if (taskName != null)
{
TaskInfo taskInfo;
if (tasks.TryGetValue(taskName, out taskInfo))
{
taskNum = taskInfo.id;
taskGuid = taskInfo.guid;
}
}
else
taskName = "";
int eventID = int.Parse(reader.GetAttribute("value"));
int opcode = 0;
string opcodeName = reader.GetAttribute("opcode");
if (opcodeName != null)
{
opcodes.TryGetValue(opcodeName, out opcode);
// Strip off any namespace prefix. TODO is this a good idea?
int colon = opcodeName.IndexOf(':');
if (colon >= 0)
opcodeName = opcodeName.Substring(colon + 1);
}
else
{
opcodeName = "";
// opcodeName = "UnknownEvent" + eventID.ToString();
}
DynamicTraceEventData eventTemplate = new DynamicTraceEventData(
callback, eventID, taskNum, taskName, taskGuid, opcode, opcodeName, Guid, Name);
events.Add(new EventInfo(eventTemplate, reader.GetAttribute("template")));
// This will be looked up in the string table in a second pass.
eventTemplate.MessageFormat = reader.GetAttribute("message");
} break;
case "template":
{
string templateName = reader.GetAttribute("tid");
Debug.Assert(templateName != null);
#if DEBUG
try
{
#endif
templates.Add(templateName, ComputeFieldInfo(reader.ReadSubtree(), maps));
#if DEBUG
}
catch (Exception e)
{
Console.WriteLine("Error: Exception during processing template {0}: {1}", templateName, e.ToString());
throw;
}
#endif
} break;
case "opcode":
// TODO use message for opcode if it is available so it is localized.
opcodes.Add(reader.GetAttribute("name"), int.Parse(reader.GetAttribute("value")));
break;
case "task":
{
TaskInfo info = new TaskInfo();
info.id = int.Parse(reader.GetAttribute("value"));
string guidString = reader.GetAttribute("eventGUID");
if (guidString != null)
info.guid = new Guid(guidString);
tasks.Add(reader.GetAttribute("name"), info);
} break;
case "valueMap":
map = new Dictionary<long, string>(); // value maps use dictionaries
goto DoMap;
case "bitMap":
map = new SortedList<long, string>(); // Bitmaps stored as sorted lists
goto DoMap;
DoMap:
string name = reader.GetAttribute("name");
var mapValues = reader.ReadSubtree();
while (mapValues.Read())
{
if (mapValues.Name == "map")
{
string keyStr = reader.GetAttribute("value");
long key;
if (keyStr.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
key = long.Parse(keyStr.Substring(2), System.Globalization.NumberStyles.AllowHexSpecifier);
else
key = long.Parse(keyStr);
string value = reader.GetAttribute("message");
map[key] = value;
}
}
if (maps == null)
maps = new Dictionary<string, IDictionary<long, string>>();
maps[name] = map;
break;
case "resources":
{
if (!alreadyReadMyCulture)
{
string desiredCulture = System.Globalization.CultureInfo.CurrentCulture.Name;
if (cultureBeingRead != null && string.Compare(cultureBeingRead, desiredCulture, StringComparison.OrdinalIgnoreCase) == 0)
alreadyReadMyCulture = true;
cultureBeingRead = reader.GetAttribute("culture");
}
} break;
case "string":
if (!alreadyReadMyCulture)
strings[reader.GetAttribute("id")] = reader.GetAttribute("value");
break;
}
}
// localize strings for maps.
if (maps != null)
{
foreach (IDictionary<long, string> amap in maps.Values)
{
foreach (var keyValue in new List<KeyValuePair<long, string>>(amap))
{
Match m = Regex.Match(keyValue.Value, @"^\$\(string\.(.*)\)$");
if (m.Success)
{
string newValue;
if (strings.TryGetValue(m.Groups[1].Value, out newValue))
amap[keyValue.Key] = newValue;
}
}
}
}
// Register all the events
foreach (var eventInfo in events)
{
var event_ = eventInfo.eventTemplate;
// Set the template if there is any.
if (eventInfo.templateName != null)
{
var templateInfo = templates[eventInfo.templateName];
event_.payloadNames = templateInfo.payloadNames.ToArray();
event_.payloadFetches = templateInfo.payloadFetches.ToArray();
}
else
{
event_.payloadNames = new string[0];
event_.payloadFetches = new DynamicTraceEventData.PayloadFetch[0];
}
// before registering, localize any message format strings.
string message = event_.MessageFormat;
if (message != null)
{
// Expect $(STRINGNAME) where STRINGNAME needs to be looked up in the string table
// TODO currently we just ignore messages without a valid string name. Is that OK?
event_.MessageFormat = null;
Match m = Regex.Match(message, @"^\$\(string\.(.*)\)$");
if (m.Success)
strings.TryGetValue(m.Groups[1].Value, out event_.MessageFormat);
}
source.RegisterEventTemplate(event_);
}
// Create an event for the manifest event itself so it looks pretty in dumps.
source.RegisterEventTemplate(new DynamicManifestTraceEventData(callback, this));
}
catch (Exception e)
{
// TODO FIX NOW, log this!
Debug.Assert(false, "Exception during manifest parsing");
#if DEBUG
Console.WriteLine("Error: Exception during processing of in-log manifest for provider {0}. Symbolic information may not be complete.", Name);
#endif
error = e;
}
inited = false; // If we call it again, start over from the begining.
}
private class EventInfo
{
public EventInfo(DynamicTraceEventData eventTemplate, string templateName)
{
this.eventTemplate = eventTemplate;
this.templateName = templateName;
}
public DynamicTraceEventData eventTemplate;
public string templateName;
};
private class TaskInfo
{
public int id;
public Guid guid;
};
private class TemplateInfo
{
public List<string> payloadNames;
public List<DynamicTraceEventData.PayloadFetch> payloadFetches;
};
private TemplateInfo ComputeFieldInfo(XmlReader reader, Dictionary<string, IDictionary<long, string>> maps)
{
var ret = new TemplateInfo();
ret.payloadNames = new List<string>();
ret.payloadFetches = new List<DynamicTraceEventData.PayloadFetch>();
ushort offset = 0;
while (reader.Read())
{
if (reader.Name == "data")
{
string inType = reader.GetAttribute("inType");
Type type = GetTypeForManifestTypeName(inType);
ushort size = DynamicTraceEventData.SizeOfType(type);
// Strings are weird in that they are encoded multiple ways.
if (type == typeof(string) && inType == "win:AnsiString")
size = DynamicTraceEventData.NULL_TERMINATED | DynamicTraceEventData.IS_ANSI;
ret.payloadNames.Add(reader.GetAttribute("name"));
IDictionary<long, string> map = null;
string mapName = reader.GetAttribute("map");
if (mapName != null && maps != null)
maps.TryGetValue(mapName, out map);
ret.payloadFetches.Add(new DynamicTraceEventData.PayloadFetch(offset, size, type, map));
if (offset != ushort.MaxValue)
{
Debug.Assert(size != 0);
if (size < DynamicTraceEventData.SPECIAL_SIZES)
offset += size;
else
offset = ushort.MaxValue;
}
}
}
return ret;
}
private static Type GetTypeForManifestTypeName(string manifestTypeName)
{
switch (manifestTypeName)
{
// TODO do we want to support unsigned?
case "win:Pointer":
case "trace:SizeT":
return typeof(IntPtr);
case "win:Boolean":
return typeof(bool);
case "win:UInt8":
case "win:Int8":
return typeof(byte);
case "win:UInt16":
case "win:Int16":
case "trace:Port":
return typeof(short);
case "win:UInt32":
case "win:Int32":
case "trace:IPAddr":
case "trace:IPAddrV4":
return typeof(int);
case "trace:WmiTime":
case "win:UInt64":
case "win:Int64":
return typeof(long);
case "win:Double":
return typeof(double);
case "win:Float":
return typeof(float);
case "win:AnsiString":
case "win:UnicodeString":
return typeof(string);
case "win:GUID":
return typeof(Guid);
case "win:FILETIME":
return typeof(DateTime);
default:
throw new Exception("Unsupported type " + manifestTypeName);
}
}
#region IFastSerializable Members
void IFastSerializable.ToStream(Serializer serializer)
{
serializer.Write(majorVersion);
serializer.Write(minorVersion);
serializer.Write((int)format);
int count = 0;
if (serializedManifest != null)
count = serializedManifest.Length;
serializer.Write(count);
for (int i = 0; i < count; i++)
serializer.Write(serializedManifest[i]);
}
void IFastSerializable.FromStream(Deserializer deserializer)
{
deserializer.Read(out majorVersion);
deserializer.Read(out minorVersion);
format = (ManifestEnvelope.ManifestFormats)deserializer.ReadInt();
int count = deserializer.ReadInt();
serializedManifest = new byte[count];
for (int i = 0; i < count; i++)
serializedManifest[i] = deserializer.ReadByte();
Init();
}
private void Init()
{
try
{
reader = ManifestReader;
while (reader.Read())
{
if (reader.Name == "provider")
{
guid = new Guid(reader.GetAttribute("guid"));
name = reader.GetAttribute("name");
fileName = reader.GetAttribute("resourceFileName");
break;
}
}
if (name == null)
throw new Exception("No provider element found in manifest");
}
catch (Exception e)
{
Debug.Assert(false, "Exception during manifest parsing");
name = "";
error = e;
}
inited = true;
}
#endregion
private XmlReader reader;
private byte[] serializedManifest;
private byte majorVersion;
private byte minorVersion;
ManifestEnvelope.ManifestFormats format;
private Guid guid;
private string name;
private string fileName;
private bool inited;
private Exception error;
#endregion
}
#region internal classes
/// <summary>
/// DynamicTraceEventData is an event that knows how to take runtime information to parse event fields (and payload)
///
/// This meta-data is distilled down to a array of field names and an array of PayloadFetches which contain enough
/// information to find the field data in the payload blob. This meta-data is used in the
/// code:DynamicTraceEventData.PayloadNames and code:DynamicTraceEventData.PayloadValue methods.
/// </summary>
public class DynamicTraceEventData : TraceEvent, IFastSerializable
{
internal DynamicTraceEventData(Action<TraceEvent> action, int eventID, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName)
: base(eventID, task, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName)
{
Action = action;
}
internal protected event Action<TraceEvent> Action;
protected internal override void Dispatch()
{
if (Action != null)
{
Action(this);
}
}
public override string[] PayloadNames
{
get { Debug.Assert(payloadNames != null); return payloadNames; }
}
public override object PayloadValue(int index)
{
Type type = payloadFetches[index].type;
if (type == null)
return "[CANT PARSE]";
int offset = payloadFetches[index].offset;
if (offset == ushort.MaxValue)
offset = SkipToField(index);
if ((uint)offset >= 0x10000)
return "[CANT PARSE OFFSET]";
switch (Type.GetTypeCode(type))
{
case TypeCode.String:
{
var size = payloadFetches[index].size;
var isAnsi = false;
if (size >= SPECIAL_SIZES)
{
isAnsi = ((size & IS_ANSI) != 0);
var format = (size & ~IS_ANSI);
if (format == NULL_TERMINATED)
{
if ((size & IS_ANSI) != 0)
return GetUTF8StringAt(offset);
else
return GetUnicodeStringAt(offset);
}
else if (format == DynamicTraceEventData.COUNT32_PRECEEDS)
size = (ushort)GetInt32At(offset - 4);
else if (format == DynamicTraceEventData.COUNT16_PRECEEDS)
size = (ushort)GetInt16At(offset - 2);
else
return "[CANT PARSE STRING]";
}
else if (size > 0x8000)
{
size -= 0x8000;
isAnsi = true;
}
if (isAnsi)
return GetFixedAnsiStringAt(size, offset);
else
return GetFixedUnicodeStringAt(size / 2, offset);
}
case TypeCode.Boolean:
return GetByteAt(offset) != 0;
case TypeCode.Byte:
return (byte)GetByteAt(offset);
case TypeCode.SByte:
return (SByte)GetByteAt(offset);
case TypeCode.Int16:
return GetInt16At(offset);
case TypeCode.UInt16:
return (UInt16)GetInt16At(offset);
case TypeCode.Int32:
return GetInt32At(offset);
case TypeCode.UInt32:
return (UInt32)GetInt32At(offset);
case TypeCode.Int64:
return GetInt64At(offset);
case TypeCode.UInt64:
return (UInt64)GetInt64At(offset);
case TypeCode.Single:
return GetSingleAt(offset);
case TypeCode.Double:
return GetDoubleAt(offset);
default:
if (type == typeof(IntPtr))
{
if (PointerSize == 4)
return (UInt32)GetInt32At(offset);
else
return (UInt64)GetInt64At(offset);
}
else if (type == typeof(Guid))
return GetGuidAt(offset);
else if (type == typeof(DateTime))
return DateTime.FromFileTime(GetInt64At(offset));
else if (type == typeof(byte[]))
{
int size = payloadFetches[index].size;
if (size >= DynamicTraceEventData.SPECIAL_SIZES)
{
if (payloadFetches[index].size == DynamicTraceEventData.COUNT32_PRECEEDS)
size = GetInt32At(offset - 4);
else if (payloadFetches[index].size == DynamicTraceEventData.COUNT16_PRECEEDS)
size = (ushort)GetInt16At(offset - 2);
else
return "[CANT PARSE]";
}
var ret = new byte[size];
EventData(ret, 0, offset, ret.Length);
return ret;
}
return "[UNSUPPORTED TYPE]";
}
}
public override string PayloadString(int index)
{
object value = PayloadValue(index);
var map = payloadFetches[index].map;
string ret = null;
long asLong;
if (map != null)
{
asLong = (long)((IConvertible)value).ToInt64(null);
if (map is SortedList<long, string>)
{
StringBuilder sb = new StringBuilder();
// It is a bitmap, compute the bits from the bitmap.
foreach (var keyValue in map)
{
if (asLong == 0)
break;
if ((keyValue.Key & asLong) != 0)
{
if (sb.Length != 0)
sb.Append('|');
sb.Append(keyValue.Value);
asLong &= ~keyValue.Key;
}
}
if (asLong != 0)
{
if (sb.Length != 0)
sb.Append('|');
sb.Append(asLong);
}
else if (sb.Length == 0)
sb.Append('0');
ret = sb.ToString();
}
else
{
// It is a value map, just look up the value
map.TryGetValue(asLong, out ret);
}
}
if (ret != null)
return ret;
// Print large long values as hex by default.
if (value is long)
{
asLong = (long)value;
goto PrintLongAsHex;
}
else if (value is ulong)
{
asLong = (long)(ulong)value;
goto PrintLongAsHex;
}
var asByteArray = value as byte[];
if (asByteArray != null)
{
StringBuilder sb = new StringBuilder();
var limit = Math.Min(asByteArray.Length, 16);
for (int i = 0; i < limit; i++)
{
var b = asByteArray[i];
sb.Append(HexDigit((b / 16)));
sb.Append(HexDigit((b % 16)));
}
if (limit < asByteArray.Length)
sb.Append("...");
return sb.ToString();
}
return value.ToString();
PrintLongAsHex:
if ((int)asLong != asLong)
return "0x" + asLong.ToString("x");
return asLong.ToString();
}
private static char HexDigit(int digit)
{
if (digit < 10)
return (char)('0' + digit);
else
return (char)('A' - 10 + digit);
}
public override string FormattedMessage
{
get
{
if (MessageFormat == null)
return null;
// TODO is this error handling OK?
// Replace all %N with the string value for that parameter.
return Regex.Replace(MessageFormat, @"%(\d+)", delegate(Match m)
{
int index = int.Parse(m.Groups[1].Value) - 1;
if ((uint)index < (uint)PayloadNames.Length)
return PayloadString(index);
else
return "<<Out Of Range>>";
});
}
}
#region private
private int SkipToField(int index)
{
// Find the first field that has a fixed offset.
int offset = 0;
int cur = index;
while (0 < cur)
{
--cur;
offset = payloadFetches[cur].offset;
if (offset != ushort.MaxValue)
break;
}
// TODO it probably does pay to remember the offsets in a particular instance, since otherwise the
// algorithm is N*N
while (cur < index)
{
ushort size = payloadFetches[cur].size;
if (size >= SPECIAL_SIZES)
{
if (size == NULL_TERMINATED)
offset = SkipUnicodeString(offset);
else if (size == (NULL_TERMINATED | IS_ANSI))
offset = SkipUTF8String(offset);
else if (size == POINTER_SIZE)
offset += PointerSize;
else if ((size & ~IS_ANSI) == COUNT32_PRECEEDS)
offset += GetInt32At(offset - 4);
else if ((size & ~IS_ANSI) == COUNT16_PRECEEDS)
offset += (ushort)GetInt16At(offset - 2);
else
return -1;
}
else
offset += size;
cur++;
}
return offset;
}
internal static ushort SizeOfType(Type type)
{
switch (Type.GetTypeCode(type))
{
case TypeCode.String:
return NULL_TERMINATED;
case TypeCode.SByte:
case TypeCode.Byte:
return 1;
case TypeCode.UInt16:
case TypeCode.Int16:
return 2;
case TypeCode.UInt32:
case TypeCode.Int32:
case TypeCode.Boolean: // We follow windows conventions and use 4 bytes for bool.
case TypeCode.Single:
return 4;
case TypeCode.UInt64:
case TypeCode.Int64:
case TypeCode.Double:
case TypeCode.DateTime:
return 8;
default:
if (type == typeof(Guid))
return 16;
if (type == typeof(IntPtr))
return POINTER_SIZE;
throw new Exception("Unsupported type " + type.Name); // TODO
}
}
internal const ushort IS_ANSI = 1; // A bit mask that represents the string is ASCII
// NULL_TERMINATD | IS_ANSI == MaxValue
internal const ushort NULL_TERMINATED = ushort.MaxValue - 1;
// COUNT32_PRECEEDS | IS_ANSI == MaxValue - 2
internal const ushort COUNT32_PRECEEDS = ushort.MaxValue - 3; // Count is a 32 bit int directly before
// COUNT16_PRECEEDS | IS_ANSI == MaxValue -4
internal const ushort COUNT16_PRECEEDS = ushort.MaxValue - 5; // Count is a 16 bit uint directly before
internal const ushort POINTER_SIZE = ushort.MaxValue - 14; // It is the pointer size of the target machine.
internal const ushort UNKNOWN_SIZE = ushort.MaxValue - 15; // Generic unknown.
internal const ushort SPECIAL_SIZES = ushort.MaxValue - 15; // Some room for growth.
internal struct PayloadFetch
{
public PayloadFetch(ushort offset, ushort size, Type type, IDictionary<long, string> map = null)
{
this.offset = offset;
this.size = size;
this.type = type;
this.map = map;
}
public ushort offset; // offset == MaxValue means variable size.
// TODO come up with a real encoding for variable sized things
public ushort size; // See special encodeings above (also size > 0x8000 means fixed lenght ANSI).
public IDictionary<long, string> map;
public Type type;
};
void IFastSerializable.ToStream(Serializer serializer)
{
serializer.Write((int)eventID);
serializer.Write((int)task);
serializer.Write(taskName);
serializer.Write(taskGuid);
serializer.Write((int)opcode);
serializer.Write(opcodeName);
serializer.Write(providerGuid);
serializer.Write(providerName);
serializer.Write(MessageFormat);
serializer.Write(lookupAsWPP);
serializer.Write(payloadNames.Length);
foreach (var payloadName in payloadNames)
serializer.Write(payloadName);
serializer.Write(payloadFetches.Length);
foreach (var payloadFetch in payloadFetches)
{
serializer.Write((short)payloadFetch.offset);
serializer.Write((short)payloadFetch.size);
if (payloadFetch.type == null)
serializer.Write((string)null);
else
serializer.Write(payloadFetch.type.FullName);
serializer.Write((IFastSerializable)null); // This is for the map (eventually)
}
}
void IFastSerializable.FromStream(Deserializer deserializer)
{
eventID = (TraceEventID)deserializer.ReadInt();
task = (TraceEventTask)deserializer.ReadInt();
deserializer.Read(out taskName);
deserializer.Read(out taskGuid);
opcode = (TraceEventOpcode)deserializer.ReadInt();
deserializer.Read(out opcodeName);
deserializer.Read(out providerGuid);
deserializer.Read(out providerName);
deserializer.Read(out MessageFormat);
deserializer.Read(out lookupAsWPP);
int count;
deserializer.Read(out count);
payloadNames = new string[count];
for (int i = 0; i < count; i++)
deserializer.Read(out payloadNames[i]);
deserializer.Read(out count);
payloadFetches = new PayloadFetch[count];
for (int i = 0; i < count; i++)
{
payloadFetches[i].offset = (ushort)deserializer.ReadInt16();
payloadFetches[i].size = (ushort)deserializer.ReadInt16();
var typeName = deserializer.ReadString();
if (typeName != null)
payloadFetches[i].type = Type.GetType(typeName);
IFastSerializable dummy;
deserializer.Read(out dummy); // For map when we use it.
}
}
// Fields
internal PayloadFetch[] payloadFetches;
internal string MessageFormat; // This is in ETW conventions (%N)
#endregion
}
/// <summary>
/// This class is only used to pretty-print the manifest event itself. It is pretty special purpose
/// </summary>
class DynamicManifestTraceEventData : DynamicTraceEventData
{
internal DynamicManifestTraceEventData(Action<TraceEvent> action, ProviderManifest manifest)
: base(action, 0xFFFE, 0, "ManifestData", Guid.Empty, 0, null, manifest.Guid, manifest.Name)
{
this.manifest = manifest;
payloadNames = new string[] { "Format", "MajorVersion", "MinorVersion", "Magic", "TotalChunks", "ChunkNumber" };
payloadFetches = new PayloadFetch[] {
new PayloadFetch(0, 1, typeof(byte)),
new PayloadFetch(1, 1, typeof(byte)),
new PayloadFetch(2, 1, typeof(byte)),
new PayloadFetch(3, 1, typeof(byte)),
new PayloadFetch(4, 2, typeof(ushort)),
new PayloadFetch(6, 2, typeof(ushort)),
};
Action += action;
}
public override StringBuilder ToXml(StringBuilder sb)
{
int totalChunks = GetInt16At(4);
int chunkNumber = GetInt16At(6);
if (chunkNumber + 1 == totalChunks)
{
StringBuilder baseSb = new StringBuilder();
base.ToXml(baseSb);
sb.AppendLine(XmlUtilities.OpenXmlElement(baseSb.ToString()));
sb.Append(manifest.Manifest);
sb.Append("</Event>");
return sb;
}
else
return base.ToXml(sb);
}
#region private
ProviderManifest manifest;
#endregion
}
/// <summary>
/// DynamicTraceEventParserState represents the state of a DynamicTraceEventParser that needs to be
/// serialied to a log file. It does NOT include information about what events are chosen but DOES contain
/// any other necessary information that came from the ETL data file.
/// </summary>
class DynamicTraceEventParserState : IFastSerializable
{
public DynamicTraceEventParserState() { providers = new Dictionary<Guid, ProviderManifest>(); }
internal Dictionary<Guid, ProviderManifest> providers;
#region IFastSerializable Members
void IFastSerializable.ToStream(Serializer serializer)
{
serializer.Write(providers.Count);
foreach (ProviderManifest provider in providers.Values)
serializer.Write(provider);
}
void IFastSerializable.FromStream(Deserializer deserializer)
{
int count;
deserializer.Read(out count);
for (int i = 0; i < count; i++)
{
ProviderManifest provider;
deserializer.Read(out provider);
providers.Add(provider.Guid, provider);
}
}
#endregion
}
}
#endregion
| |
namespace android.app
{
[global::MonoJavaBridge.JavaClass()]
public partial class ProgressDialog : android.app.AlertDialog
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected ProgressDialog(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
protected override void onCreate(android.os.Bundle arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.ProgressDialog.staticClass, "onCreate", "(Landroid/os/Bundle;)V", ref global::android.app.ProgressDialog._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m1;
public virtual void onStart()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.ProgressDialog.staticClass, "onStart", "()V", ref global::android.app.ProgressDialog._m1);
}
private static global::MonoJavaBridge.MethodId _m2;
protected override void onStop()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.ProgressDialog.staticClass, "onStop", "()V", ref global::android.app.ProgressDialog._m2);
}
private static global::MonoJavaBridge.MethodId _m3;
public virtual void setProgress(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.ProgressDialog.staticClass, "setProgress", "(I)V", ref global::android.app.ProgressDialog._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m4;
public virtual void setSecondaryProgress(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.ProgressDialog.staticClass, "setSecondaryProgress", "(I)V", ref global::android.app.ProgressDialog._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m5;
public static global::android.app.ProgressDialog show(android.content.Context arg0, java.lang.CharSequence arg1, java.lang.CharSequence arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.app.ProgressDialog._m5.native == global::System.IntPtr.Zero)
global::android.app.ProgressDialog._m5 = @__env.GetStaticMethodIDNoThrow(global::android.app.ProgressDialog.staticClass, "show", "(Landroid/content/Context;Ljava/lang/CharSequence;Ljava/lang/CharSequence;)Landroid/app/ProgressDialog;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.app.ProgressDialog.staticClass, global::android.app.ProgressDialog._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as android.app.ProgressDialog;
}
public static android.app.ProgressDialog show(android.content.Context arg0, string arg1, string arg2)
{
return show(arg0, (global::java.lang.CharSequence)(global::java.lang.String)arg1, (global::java.lang.CharSequence)(global::java.lang.String)arg2);
}
private static global::MonoJavaBridge.MethodId _m6;
public static global::android.app.ProgressDialog show(android.content.Context arg0, java.lang.CharSequence arg1, java.lang.CharSequence arg2, bool arg3, bool arg4)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.app.ProgressDialog._m6.native == global::System.IntPtr.Zero)
global::android.app.ProgressDialog._m6 = @__env.GetStaticMethodIDNoThrow(global::android.app.ProgressDialog.staticClass, "show", "(Landroid/content/Context;Ljava/lang/CharSequence;Ljava/lang/CharSequence;ZZ)Landroid/app/ProgressDialog;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.app.ProgressDialog.staticClass, global::android.app.ProgressDialog._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4))) as android.app.ProgressDialog;
}
public static android.app.ProgressDialog show(android.content.Context arg0, string arg1, string arg2, bool arg3, bool arg4)
{
return show(arg0, (global::java.lang.CharSequence)(global::java.lang.String)arg1, (global::java.lang.CharSequence)(global::java.lang.String)arg2, arg3, arg4);
}
private static global::MonoJavaBridge.MethodId _m7;
public static global::android.app.ProgressDialog show(android.content.Context arg0, java.lang.CharSequence arg1, java.lang.CharSequence arg2, bool arg3, bool arg4, android.content.DialogInterface_OnCancelListener arg5)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.app.ProgressDialog._m7.native == global::System.IntPtr.Zero)
global::android.app.ProgressDialog._m7 = @__env.GetStaticMethodIDNoThrow(global::android.app.ProgressDialog.staticClass, "show", "(Landroid/content/Context;Ljava/lang/CharSequence;Ljava/lang/CharSequence;ZZLandroid/content/DialogInterface$OnCancelListener;)Landroid/app/ProgressDialog;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.app.ProgressDialog.staticClass, global::android.app.ProgressDialog._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5))) as android.app.ProgressDialog;
}
public static android.app.ProgressDialog show(android.content.Context arg0, string arg1, string arg2, bool arg3, bool arg4, global::android.content.DialogInterface_OnCancelListenerDelegate arg5)
{
return show(arg0, (global::java.lang.CharSequence)(global::java.lang.String)arg1, (global::java.lang.CharSequence)(global::java.lang.String)arg2, arg3, arg4, (global::android.content.DialogInterface_OnCancelListenerDelegateWrapper)arg5);
}
private static global::MonoJavaBridge.MethodId _m8;
public static global::android.app.ProgressDialog show(android.content.Context arg0, java.lang.CharSequence arg1, java.lang.CharSequence arg2, bool arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.app.ProgressDialog._m8.native == global::System.IntPtr.Zero)
global::android.app.ProgressDialog._m8 = @__env.GetStaticMethodIDNoThrow(global::android.app.ProgressDialog.staticClass, "show", "(Landroid/content/Context;Ljava/lang/CharSequence;Ljava/lang/CharSequence;Z)Landroid/app/ProgressDialog;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.app.ProgressDialog.staticClass, global::android.app.ProgressDialog._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as android.app.ProgressDialog;
}
public static android.app.ProgressDialog show(android.content.Context arg0, string arg1, string arg2, bool arg3)
{
return show(arg0, (global::java.lang.CharSequence)(global::java.lang.String)arg1, (global::java.lang.CharSequence)(global::java.lang.String)arg2, arg3);
}
public new global::java.lang.CharSequence Message
{
set
{
setMessage(value);
}
}
private static global::MonoJavaBridge.MethodId _m9;
public override void setMessage(java.lang.CharSequence arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.ProgressDialog.staticClass, "setMessage", "(Ljava/lang/CharSequence;)V", ref global::android.app.ProgressDialog._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public void setMessage(string arg0)
{
setMessage((global::java.lang.CharSequence)(global::java.lang.String)arg0);
}
public new int Progress
{
get
{
return getProgress();
}
set
{
setProgress(value);
}
}
private static global::MonoJavaBridge.MethodId _m10;
public virtual int getProgress()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.app.ProgressDialog.staticClass, "getProgress", "()I", ref global::android.app.ProgressDialog._m10);
}
public new int SecondaryProgress
{
get
{
return getSecondaryProgress();
}
set
{
setSecondaryProgress(value);
}
}
private static global::MonoJavaBridge.MethodId _m11;
public virtual int getSecondaryProgress()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.app.ProgressDialog.staticClass, "getSecondaryProgress", "()I", ref global::android.app.ProgressDialog._m11);
}
public new int Max
{
get
{
return getMax();
}
set
{
setMax(value);
}
}
private static global::MonoJavaBridge.MethodId _m12;
public virtual int getMax()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.app.ProgressDialog.staticClass, "getMax", "()I", ref global::android.app.ProgressDialog._m12);
}
private static global::MonoJavaBridge.MethodId _m13;
public virtual void setMax(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.ProgressDialog.staticClass, "setMax", "(I)V", ref global::android.app.ProgressDialog._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m14;
public virtual void incrementProgressBy(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.ProgressDialog.staticClass, "incrementProgressBy", "(I)V", ref global::android.app.ProgressDialog._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m15;
public virtual void incrementSecondaryProgressBy(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.ProgressDialog.staticClass, "incrementSecondaryProgressBy", "(I)V", ref global::android.app.ProgressDialog._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new global::android.graphics.drawable.Drawable ProgressDrawable
{
set
{
setProgressDrawable(value);
}
}
private static global::MonoJavaBridge.MethodId _m16;
public virtual void setProgressDrawable(android.graphics.drawable.Drawable arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.ProgressDialog.staticClass, "setProgressDrawable", "(Landroid/graphics/drawable/Drawable;)V", ref global::android.app.ProgressDialog._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new global::android.graphics.drawable.Drawable IndeterminateDrawable
{
set
{
setIndeterminateDrawable(value);
}
}
private static global::MonoJavaBridge.MethodId _m17;
public virtual void setIndeterminateDrawable(android.graphics.drawable.Drawable arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.ProgressDialog.staticClass, "setIndeterminateDrawable", "(Landroid/graphics/drawable/Drawable;)V", ref global::android.app.ProgressDialog._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new bool Indeterminate
{
set
{
setIndeterminate(value);
}
}
private static global::MonoJavaBridge.MethodId _m18;
public virtual void setIndeterminate(bool arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.ProgressDialog.staticClass, "setIndeterminate", "(Z)V", ref global::android.app.ProgressDialog._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m19;
public virtual bool isIndeterminate()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.app.ProgressDialog.staticClass, "isIndeterminate", "()Z", ref global::android.app.ProgressDialog._m19);
}
public new int ProgressStyle
{
set
{
setProgressStyle(value);
}
}
private static global::MonoJavaBridge.MethodId _m20;
public virtual void setProgressStyle(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.ProgressDialog.staticClass, "setProgressStyle", "(I)V", ref global::android.app.ProgressDialog._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m21;
public ProgressDialog(android.content.Context arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.app.ProgressDialog._m21.native == global::System.IntPtr.Zero)
global::android.app.ProgressDialog._m21 = @__env.GetMethodIDNoThrow(global::android.app.ProgressDialog.staticClass, "<init>", "(Landroid/content/Context;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.app.ProgressDialog.staticClass, global::android.app.ProgressDialog._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m22;
public ProgressDialog(android.content.Context arg0, int arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.app.ProgressDialog._m22.native == global::System.IntPtr.Zero)
global::android.app.ProgressDialog._m22 = @__env.GetMethodIDNoThrow(global::android.app.ProgressDialog.staticClass, "<init>", "(Landroid/content/Context;I)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.app.ProgressDialog.staticClass, global::android.app.ProgressDialog._m22, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
public static int STYLE_SPINNER
{
get
{
return 0;
}
}
public static int STYLE_HORIZONTAL
{
get
{
return 1;
}
}
static ProgressDialog()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.app.ProgressDialog.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/app/ProgressDialog"));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Cirrious.FluentLayouts.Touch;
using Foundation;
using UIKit;
using Toggl.Phoebe.Analytics;
using Toggl.Phoebe.Data;
using Toggl.Phoebe.Data.DataObjects;
using Toggl.Phoebe.Data.Models;
using XPlatUtils;
using Toggl.Ross.Theme;
using Toggl.Ross.Views;
namespace Toggl.Ross.ViewControllers
{
public class NewProjectViewController : UIViewController
{
private readonly ProjectModel model;
private TextField nameTextField;
private UIButton clientButton;
private bool shouldRebindOnAppear;
private bool isSaving;
public NewProjectViewController (WorkspaceModel workspace, int color)
{
model = new ProjectModel {
Workspace = workspace,
Color = color,
IsActive = true,
IsPrivate = true
};
Title = "NewProjectTitle".Tr ();
}
public Action<ProjectModel> ProjectCreated { get; set; }
private void BindNameField (TextField v)
{
if (v.Text != model.Name) {
v.Text = model.Name;
}
}
private void BindClientButton (UIButton v)
{
if (model.Client == null) {
v.Apply (Style.NewProject.NoClient);
v.SetTitle ("NewProjectClientHint".Tr (), UIControlState.Normal);
} else {
var text = model.Client.Name;
if (String.IsNullOrEmpty (text)) {
text = "NewProjectNoNameClient".Tr ();
}
v.Apply (Style.NewProject.WithClient);
v.SetTitle (text, UIControlState.Normal);
}
}
private void Rebind ()
{
nameTextField.Apply (BindNameField);
clientButton.Apply (BindClientButton);
}
public override void LoadView ()
{
var view = new UIView ().Apply (Style.Screen);
view.Add (nameTextField = new TextField () {
TranslatesAutoresizingMaskIntoConstraints = false,
AttributedPlaceholder = new NSAttributedString (
"NewProjectNameHint".Tr (),
foregroundColor: Color.Gray
),
ShouldReturn = (tf) => tf.ResignFirstResponder (),
} .Apply (Style.NewProject.NameField).Apply (BindNameField));
nameTextField.EditingChanged += OnNameFieldEditingChanged;
view.Add (clientButton = new UIButton () {
TranslatesAutoresizingMaskIntoConstraints = false,
} .Apply (Style.NewProject.ClientButton).Apply (BindClientButton));
clientButton.TouchUpInside += OnClientButtonTouchUpInside;
view.AddConstraints (VerticalLinearLayout (view));
EdgesForExtendedLayout = UIRectEdge.None;
View = view;
NavigationItem.RightBarButtonItem = new UIBarButtonItem (
"NewProjectAdd".Tr (), UIBarButtonItemStyle.Plain, OnNavigationBarAddClicked)
.Apply (Style.NavLabelButton);
}
private void OnNameFieldEditingChanged (object sender, EventArgs e)
{
model.Name = nameTextField.Text;
}
private void OnClientButtonTouchUpInside (object sender, EventArgs e)
{
var controller = new ClientSelectionViewController (model.Workspace) {
ClientSelected = (client) => {
model.Client = client;
NavigationController.PopToViewController (this, true);
}
};
NavigationController.PushViewController (controller, true);
}
private async void OnNavigationBarAddClicked (object sender, EventArgs e)
{
if (String.IsNullOrWhiteSpace (model.Name)) {
// TODO: Show error dialog?
return;
}
if (isSaving) {
return;
}
isSaving = true;
try {
// Check for existing name
var dataStore = ServiceContainer.Resolve<IDataStore> ();
Guid clientId = (model.Client == null) ? Guid.Empty : model.Client.Id;
var existWithName = await dataStore.Table<ProjectData>().ExistWithNameAsync (model.Name, clientId);
if (existWithName) {
var alert = new UIAlertView (
"NewProjectNameExistTitle".Tr (),
"NewProjectNameExistMessage".Tr (),
null,
"NewProjectNameExistOk".Tr (),
null);
alert.Clicked += async (s, ev) => {
if (ev.ButtonIndex == 0) {
nameTextField.BecomeFirstResponder ();
}
};
alert.Show ();
} else {
// Create new project:
await model.SaveAsync ();
// Invoke callback hook
var cb = ProjectCreated;
if (cb != null) {
cb (model);
} else {
NavigationController.PopViewController (true);
}
}
} finally {
isSaving = false;
}
}
private IEnumerable<FluentLayout> VerticalLinearLayout (UIView container)
{
UIView prev = null;
var subviews = container.Subviews.Where (v => !v.Hidden).ToList ();
foreach (var v in subviews) {
if (prev == null) {
yield return v.AtTopOf (container, 10f);
} else {
yield return v.Below (prev, 5f);
}
yield return v.Height ().EqualTo (60f).SetPriority (UILayoutPriority.DefaultLow);
yield return v.Height ().GreaterThanOrEqualTo (60f);
yield return v.AtLeftOf (container);
yield return v.AtRightOf (container);
prev = v;
}
}
public override void ViewWillAppear (bool animated)
{
base.ViewWillAppear (animated);
if (shouldRebindOnAppear) {
Rebind ();
} else {
shouldRebindOnAppear = true;
}
}
public override void ViewDidAppear (bool animated)
{
base.ViewDidAppear (animated);
nameTextField.BecomeFirstResponder ();
ServiceContainer.Resolve<ITracker> ().CurrentScreen = "New Project";
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using sc = System.Collections;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.AppEngine.V1
{
/// <summary>Settings for <see cref="AuthorizedDomainsClient"/> instances.</summary>
public sealed partial class AuthorizedDomainsSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="AuthorizedDomainsSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="AuthorizedDomainsSettings"/>.</returns>
public static AuthorizedDomainsSettings GetDefault() => new AuthorizedDomainsSettings();
/// <summary>Constructs a new <see cref="AuthorizedDomainsSettings"/> object with default settings.</summary>
public AuthorizedDomainsSettings()
{
}
private AuthorizedDomainsSettings(AuthorizedDomainsSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
ListAuthorizedDomainsSettings = existing.ListAuthorizedDomainsSettings;
OnCopy(existing);
}
partial void OnCopy(AuthorizedDomainsSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>AuthorizedDomainsClient.ListAuthorizedDomains</c> and
/// <c>AuthorizedDomainsClient.ListAuthorizedDomainsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings ListAuthorizedDomainsSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="AuthorizedDomainsSettings"/> object.</returns>
public AuthorizedDomainsSettings Clone() => new AuthorizedDomainsSettings(this);
}
/// <summary>
/// Builder class for <see cref="AuthorizedDomainsClient"/> to provide simple configuration of credentials, endpoint
/// etc.
/// </summary>
public sealed partial class AuthorizedDomainsClientBuilder : gaxgrpc::ClientBuilderBase<AuthorizedDomainsClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public AuthorizedDomainsSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public AuthorizedDomainsClientBuilder()
{
UseJwtAccessWithScopes = AuthorizedDomainsClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref AuthorizedDomainsClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<AuthorizedDomainsClient> task);
/// <summary>Builds the resulting client.</summary>
public override AuthorizedDomainsClient Build()
{
AuthorizedDomainsClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<AuthorizedDomainsClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<AuthorizedDomainsClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private AuthorizedDomainsClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return AuthorizedDomainsClient.Create(callInvoker, Settings);
}
private async stt::Task<AuthorizedDomainsClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return AuthorizedDomainsClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => AuthorizedDomainsClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => AuthorizedDomainsClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => AuthorizedDomainsClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>AuthorizedDomains client wrapper, for convenient use.</summary>
/// <remarks>
/// Manages domains a user is authorized to administer. To authorize use of a
/// domain, verify ownership via
/// [Webmaster Central](https://www.google.com/webmasters/verification/home).
/// </remarks>
public abstract partial class AuthorizedDomainsClient
{
/// <summary>
/// The default endpoint for the AuthorizedDomains service, which is a host of "appengine.googleapis.com" and a
/// port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "appengine.googleapis.com:443";
/// <summary>The default AuthorizedDomains scopes.</summary>
/// <remarks>
/// The default AuthorizedDomains scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/appengine.admin</description></item>
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// <item><description>https://www.googleapis.com/auth/cloud-platform.read-only</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/appengine.admin",
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="AuthorizedDomainsClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="AuthorizedDomainsClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="AuthorizedDomainsClient"/>.</returns>
public static stt::Task<AuthorizedDomainsClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new AuthorizedDomainsClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="AuthorizedDomainsClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="AuthorizedDomainsClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="AuthorizedDomainsClient"/>.</returns>
public static AuthorizedDomainsClient Create() => new AuthorizedDomainsClientBuilder().Build();
/// <summary>
/// Creates a <see cref="AuthorizedDomainsClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="AuthorizedDomainsSettings"/>.</param>
/// <returns>The created <see cref="AuthorizedDomainsClient"/>.</returns>
internal static AuthorizedDomainsClient Create(grpccore::CallInvoker callInvoker, AuthorizedDomainsSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
AuthorizedDomains.AuthorizedDomainsClient grpcClient = new AuthorizedDomains.AuthorizedDomainsClient(callInvoker);
return new AuthorizedDomainsClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC AuthorizedDomains client</summary>
public virtual AuthorizedDomains.AuthorizedDomainsClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Lists all domains the user is authorized to administer.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="AuthorizedDomain"/> resources.</returns>
public virtual gax::PagedEnumerable<ListAuthorizedDomainsResponse, AuthorizedDomain> ListAuthorizedDomains(ListAuthorizedDomainsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Lists all domains the user is authorized to administer.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="AuthorizedDomain"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ListAuthorizedDomainsResponse, AuthorizedDomain> ListAuthorizedDomainsAsync(ListAuthorizedDomainsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
}
/// <summary>AuthorizedDomains client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Manages domains a user is authorized to administer. To authorize use of a
/// domain, verify ownership via
/// [Webmaster Central](https://www.google.com/webmasters/verification/home).
/// </remarks>
public sealed partial class AuthorizedDomainsClientImpl : AuthorizedDomainsClient
{
private readonly gaxgrpc::ApiCall<ListAuthorizedDomainsRequest, ListAuthorizedDomainsResponse> _callListAuthorizedDomains;
/// <summary>
/// Constructs a client wrapper for the AuthorizedDomains service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="AuthorizedDomainsSettings"/> used within this client.</param>
public AuthorizedDomainsClientImpl(AuthorizedDomains.AuthorizedDomainsClient grpcClient, AuthorizedDomainsSettings settings)
{
GrpcClient = grpcClient;
AuthorizedDomainsSettings effectiveSettings = settings ?? AuthorizedDomainsSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callListAuthorizedDomains = clientHelper.BuildApiCall<ListAuthorizedDomainsRequest, ListAuthorizedDomainsResponse>(grpcClient.ListAuthorizedDomainsAsync, grpcClient.ListAuthorizedDomains, effectiveSettings.ListAuthorizedDomainsSettings).WithGoogleRequestParam("parent", request => request.Parent);
Modify_ApiCall(ref _callListAuthorizedDomains);
Modify_ListAuthorizedDomainsApiCall(ref _callListAuthorizedDomains);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_ListAuthorizedDomainsApiCall(ref gaxgrpc::ApiCall<ListAuthorizedDomainsRequest, ListAuthorizedDomainsResponse> call);
partial void OnConstruction(AuthorizedDomains.AuthorizedDomainsClient grpcClient, AuthorizedDomainsSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC AuthorizedDomains client</summary>
public override AuthorizedDomains.AuthorizedDomainsClient GrpcClient { get; }
partial void Modify_ListAuthorizedDomainsRequest(ref ListAuthorizedDomainsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Lists all domains the user is authorized to administer.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="AuthorizedDomain"/> resources.</returns>
public override gax::PagedEnumerable<ListAuthorizedDomainsResponse, AuthorizedDomain> ListAuthorizedDomains(ListAuthorizedDomainsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListAuthorizedDomainsRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedEnumerable<ListAuthorizedDomainsRequest, ListAuthorizedDomainsResponse, AuthorizedDomain>(_callListAuthorizedDomains, request, callSettings);
}
/// <summary>
/// Lists all domains the user is authorized to administer.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="AuthorizedDomain"/> resources.</returns>
public override gax::PagedAsyncEnumerable<ListAuthorizedDomainsResponse, AuthorizedDomain> ListAuthorizedDomainsAsync(ListAuthorizedDomainsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListAuthorizedDomainsRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedAsyncEnumerable<ListAuthorizedDomainsRequest, ListAuthorizedDomainsResponse, AuthorizedDomain>(_callListAuthorizedDomains, request, callSettings);
}
}
public partial class ListAuthorizedDomainsRequest : gaxgrpc::IPageRequest
{
}
public partial class ListAuthorizedDomainsResponse : gaxgrpc::IPageResponse<AuthorizedDomain>
{
/// <summary>Returns an enumerator that iterates through the resources in this response.</summary>
public scg::IEnumerator<AuthorizedDomain> GetEnumerator() => Domains.GetEnumerator();
sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator();
}
}
| |
// ***********************************************************************
// Copyright (c) 2011 Charlie Poole
//
// 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.IO;
using System.Reflection;
using NUnit.Common;
using NUnit.Options;
namespace NUnit.ConsoleRunner.Tests
{
using System.Collections.Generic;
using Framework;
[TestFixture]
public class CommandLineTests
{
#region General Tests
[Test]
public void NoInputFiles()
{
ConsoleOptions options = new ConsoleOptions();
Assert.True(options.Validate());
Assert.AreEqual(0, options.InputFiles.Count);
}
[TestCase("ShowHelp", "help|h")]
[TestCase("ShowVersion", "version|V")]
[TestCase("StopOnError", "stoponerror")]
[TestCase("WaitBeforeExit", "wait")]
[TestCase("NoHeader", "noheader|noh")]
[TestCase("RunAsX86", "x86")]
[TestCase("DisposeRunners", "dispose-runners")]
[TestCase("ShadowCopyFiles", "shadowcopy")]
[TestCase("TeamCity", "teamcity")]
[TestCase("DebugTests", "debug")]
[TestCase("PauseBeforeRun", "pause")]
#if DEBUG
[TestCase("DebugAgent", "debug-agent")]
#endif
public void CanRecognizeBooleanOptions(string propertyName, string pattern)
{
string[] prototypes = pattern.Split('|');
PropertyInfo property = GetPropertyInfo(propertyName);
Assert.AreEqual(typeof(bool), property.PropertyType, "Property '{0}' is wrong type", propertyName);
foreach (string option in prototypes)
{
ConsoleOptions options;
if (option.Length == 1)
{
options = new ConsoleOptions("-" + option);
Assert.AreEqual(true, (bool)property.GetValue(options, null), "Didn't recognize -" + option);
options = new ConsoleOptions("-" + option + "+");
Assert.AreEqual(true, (bool)property.GetValue(options, null), "Didn't recognize -" + option + "+");
options = new ConsoleOptions("-" + option + "-");
Assert.AreEqual(false, (bool)property.GetValue(options, null), "Didn't recognize -" + option + "-");
}
else
{
options = new ConsoleOptions("--" + option);
Assert.AreEqual(true, (bool)property.GetValue(options, null), "Didn't recognize --" + option);
}
options = new ConsoleOptions("/" + option);
Assert.AreEqual(true, (bool)property.GetValue(options, null), "Didn't recognize /" + option);
}
}
[TestCase("WhereClause", "where", new string[] { "cat==Fast" }, new string[0])]
[TestCase("ActiveConfig", "config", new string[] { "Debug" }, new string[0])]
[TestCase("ProcessModel", "process", new string[] { "InProcess", "Separate", "Multiple" }, new string[] { "JUNK" })]
[TestCase("DomainUsage", "domain", new string[] { "None", "Single", "Multiple" }, new string[] { "JUNK" })]
[TestCase("Framework", "framework", new string[] { "net-4.0" }, new string[0])]
[TestCase("OutFile", "output|out", new string[] { "output.txt" }, new string[0])]
[TestCase("ErrFile", "err", new string[] { "error.txt" }, new string[0])]
[TestCase("WorkDirectory", "work", new string[] { "results" }, new string[0])]
[TestCase("DisplayTestLabels", "labels", new string[] { "Off", "On", "All" }, new string[] { "JUNK" })]
[TestCase("InternalTraceLevel", "trace", new string[] { "Off", "Error", "Warning", "Info", "Debug", "Verbose" }, new string[] { "JUNK" })]
public void CanRecognizeStringOptions(string propertyName, string pattern, string[] goodValues, string[] badValues)
{
string[] prototypes = pattern.Split('|');
PropertyInfo property = GetPropertyInfo(propertyName);
Assert.AreEqual(typeof(string), property.PropertyType);
foreach (string option in prototypes)
{
foreach (string value in goodValues)
{
string optionPlusValue = string.Format("--{0}:{1}", option, value);
ConsoleOptions options = new ConsoleOptions(optionPlusValue);
Assert.True(options.Validate(), "Should be valid: " + optionPlusValue);
Assert.AreEqual(value, (string)property.GetValue(options, null), "Didn't recognize " + optionPlusValue);
}
foreach (string value in badValues)
{
string optionPlusValue = string.Format("--{0}:{1}", option, value);
ConsoleOptions options = new ConsoleOptions(optionPlusValue);
Assert.False(options.Validate(), "Should not be valid: " + optionPlusValue);
}
}
}
[Test]
public void CanRegognizeInProcessOption()
{
ConsoleOptions options = new ConsoleOptions("--inprocess");
Assert.True(options.Validate(), "Should be valid: --inprocess");
Assert.AreEqual("InProcess", options.ProcessModel, "Didn't recognize --inprocess");
}
[TestCase("ProcessModel", "process", new string[] { "InProcess", "Separate", "Multiple" })]
[TestCase("DomainUsage", "domain", new string[] { "None", "Single", "Multiple" })]
[TestCase("DisplayTestLabels", "labels", new string[] { "Off", "On", "All" })]
[TestCase("InternalTraceLevel", "trace", new string[] { "Off", "Error", "Warning", "Info", "Debug", "Verbose" })]
public void CanRecognizeLowerCaseOptionValues(string propertyName, string optionName, string[] canonicalValues)
{
PropertyInfo property = GetPropertyInfo(propertyName);
Assert.AreEqual(typeof(string), property.PropertyType);
foreach (string canonicalValue in canonicalValues)
{
string lowercaseValue = canonicalValue.ToLowerInvariant();
string optionPlusValue = string.Format("--{0}:{1}", optionName, lowercaseValue);
ConsoleOptions options = new ConsoleOptions(optionPlusValue);
Assert.True(options.Validate(), "Should be valid: " + optionPlusValue);
Assert.AreEqual(canonicalValue, (string)property.GetValue(options, null), "Didn't recognize " + optionPlusValue);
}
}
[TestCase("DefaultTimeout", "timeout")]
[TestCase("RandomSeed", "seed")]
[TestCase("NumberOfTestWorkers", "workers")]
[TestCase("MaxAgents", "agents")]
public void CanRecognizeIntOptions(string propertyName, string pattern)
{
string[] prototypes = pattern.Split('|');
PropertyInfo property = GetPropertyInfo(propertyName);
Assert.AreEqual(typeof(int), property.PropertyType);
foreach (string option in prototypes)
{
ConsoleOptions options = new ConsoleOptions("--" + option + ":42");
Assert.AreEqual(42, (int)property.GetValue(options, null), "Didn't recognize --" + option + ":42");
}
}
//[TestCase("InternalTraceLevel", "trace", typeof(InternalTraceLevel))]
//public void CanRecognizeEnumOptions(string propertyName, string pattern, Type enumType)
//{
// string[] prototypes = pattern.Split('|');
// PropertyInfo property = GetPropertyInfo(propertyName);
// Assert.IsNotNull(property, "Property {0} not found", propertyName);
// Assert.IsTrue(property.PropertyType.IsEnum, "Property {0} is not an enum", propertyName);
// Assert.AreEqual(enumType, property.PropertyType);
// foreach (string option in prototypes)
// {
// foreach (string name in Enum.GetNames(enumType))
// {
// {
// ConsoleOptions options = new ConsoleOptions("--" + option + ":" + name);
// Assert.AreEqual(name, property.GetValue(options, null).ToString(), "Didn't recognize -" + option + ":" + name);
// }
// }
// }
//}
[TestCase("--where")]
[TestCase("--config")]
[TestCase("--process")]
[TestCase("--domain")]
[TestCase("--framework")]
[TestCase("--timeout")]
[TestCase("--output")]
[TestCase("--err")]
[TestCase("--work")]
[TestCase("--trace")]
public void MissingValuesAreReported(string option)
{
ConsoleOptions options = new ConsoleOptions(option + "=");
Assert.False(options.Validate(), "Missing value should not be valid");
Assert.AreEqual("Missing required value for option '" + option + "'.", options.ErrorMessages[0]);
}
[Test]
public void AssemblyName()
{
ConsoleOptions options = new ConsoleOptions("nunit.tests.dll");
Assert.True(options.Validate());
Assert.AreEqual(1, options.InputFiles.Count);
Assert.AreEqual("nunit.tests.dll", options.InputFiles[0]);
}
//[Test]
//public void FixtureNamePlusAssemblyIsValid()
//{
// ConsoleOptions options = new ConsoleOptions( "-fixture:NUnit.Tests.AllTests", "nunit.tests.dll" );
// Assert.AreEqual("nunit.tests.dll", options.Parameters[0]);
// Assert.AreEqual("NUnit.Tests.AllTests", options.fixture);
// Assert.IsTrue(options.Validate());
//}
[Test]
public void AssemblyAloneIsValid()
{
ConsoleOptions options = new ConsoleOptions("nunit.tests.dll");
Assert.True(options.Validate());
Assert.AreEqual(0, options.ErrorMessages.Count, "command line should be valid");
}
[Test]
public void X86AndInProcessAreNotCompatible()
{
ConsoleOptions options = new ConsoleOptions("nunit.tests.dll", "--x86", "--inprocess");
Assert.False(options.Validate(), "Should be invalid");
Assert.AreEqual("The --x86 and --inprocess options are incompatible.", options.ErrorMessages[0]);
}
[Test]
public void InvalidOption()
{
ConsoleOptions options = new ConsoleOptions("-assembly:nunit.tests.dll");
Assert.False(options.Validate());
Assert.AreEqual(1, options.ErrorMessages.Count);
Assert.AreEqual("Invalid argument: -assembly:nunit.tests.dll", options.ErrorMessages[0]);
}
//[Test]
//public void NoFixtureNameProvided()
//{
// ConsoleOptions options = new ConsoleOptions( "-fixture:", "nunit.tests.dll" );
// Assert.IsFalse(options.Validate());
//}
[Test]
public void InvalidCommandLineParms()
{
ConsoleOptions options = new ConsoleOptions("-garbage:TestFixture", "-assembly:Tests.dll");
Assert.False(options.Validate());
Assert.AreEqual(2, options.ErrorMessages.Count);
Assert.AreEqual("Invalid argument: -garbage:TestFixture", options.ErrorMessages[0]);
Assert.AreEqual("Invalid argument: -assembly:Tests.dll", options.ErrorMessages[1]);
}
#endregion
#region Timeout Option
[Test]
public void TimeoutIsMinusOneIfNoOptionIsProvided()
{
ConsoleOptions options = new ConsoleOptions("tests.dll");
Assert.True(options.Validate());
Assert.AreEqual(-1, options.DefaultTimeout);
}
[Test]
public void TimeoutThrowsExceptionIfOptionHasNoValue()
{
Assert.Throws<OptionException>(() => new ConsoleOptions("tests.dll", "-timeout"));
}
[Test]
public void TimeoutParsesIntValueCorrectly()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "-timeout:5000");
Assert.True(options.Validate());
Assert.AreEqual(5000, options.DefaultTimeout);
}
[Test]
public void TimeoutCausesErrorIfValueIsNotInteger()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "-timeout:abc");
Assert.False(options.Validate());
Assert.AreEqual(-1, options.DefaultTimeout);
}
#endregion
#region EngineResult Option
[Test]
public void ResultOptionWithFilePath()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "-result:results.xml");
Assert.True(options.Validate());
Assert.AreEqual(1, options.InputFiles.Count, "assembly should be set");
Assert.AreEqual("tests.dll", options.InputFiles[0]);
OutputSpecification spec = options.ResultOutputSpecifications[0];
Assert.AreEqual("results.xml", spec.OutputPath);
Assert.AreEqual("nunit3", spec.Format);
Assert.Null(spec.Transform);
}
[Test]
public void ResultOptionWithFilePathAndFormat()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "-result:results.xml;format=nunit2");
Assert.True(options.Validate());
Assert.AreEqual(1, options.InputFiles.Count, "assembly should be set");
Assert.AreEqual("tests.dll", options.InputFiles[0]);
OutputSpecification spec = options.ResultOutputSpecifications[0];
Assert.AreEqual("results.xml", spec.OutputPath);
Assert.AreEqual("nunit2", spec.Format);
Assert.Null(spec.Transform);
}
[Test]
public void ResultOptionWithFilePathAndTransform()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "-result:results.xml;transform=transform.xslt");
Assert.True(options.Validate());
Assert.AreEqual(1, options.InputFiles.Count, "assembly should be set");
Assert.AreEqual("tests.dll", options.InputFiles[0]);
OutputSpecification spec = options.ResultOutputSpecifications[0];
Assert.AreEqual("results.xml", spec.OutputPath);
Assert.AreEqual("user", spec.Format);
Assert.AreEqual("transform.xslt", spec.Transform);
}
[Test]
public void FileNameWithoutResultOptionLooksLikeParameter()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "results.xml");
Assert.True(options.Validate());
Assert.AreEqual(0, options.ErrorMessages.Count);
Assert.AreEqual(2, options.InputFiles.Count);
}
[Test]
public void ResultOptionWithoutFileNameIsInvalid()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "-result:");
Assert.False(options.Validate(), "Should not be valid");
Assert.AreEqual(1, options.ErrorMessages.Count, "An error was expected");
}
[Test]
public void ResultOptionMayBeRepeated()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "-result:results.xml", "-result:nunit2results.xml;format=nunit2", "-result:myresult.xml;transform=mytransform.xslt");
Assert.True(options.Validate(), "Should be valid");
var specs = options.ResultOutputSpecifications;
Assert.AreEqual(3, specs.Count);
var spec1 = specs[0];
Assert.AreEqual("results.xml", spec1.OutputPath);
Assert.AreEqual("nunit3", spec1.Format);
Assert.Null(spec1.Transform);
var spec2 = specs[1];
Assert.AreEqual("nunit2results.xml", spec2.OutputPath);
Assert.AreEqual("nunit2", spec2.Format);
Assert.Null(spec2.Transform);
var spec3 = specs[2];
Assert.AreEqual("myresult.xml", spec3.OutputPath);
Assert.AreEqual("user", spec3.Format);
Assert.AreEqual("mytransform.xslt", spec3.Transform);
}
[Test]
public void DefaultResultSpecification()
{
var options = new ConsoleOptions("test.dll");
Assert.AreEqual(1, options.ResultOutputSpecifications.Count);
var spec = options.ResultOutputSpecifications[0];
Assert.AreEqual("TestResult.xml", spec.OutputPath);
Assert.AreEqual("nunit3", spec.Format);
Assert.Null(spec.Transform);
}
[Test]
public void NoResultSuppressesDefaultResultSpecification()
{
var options = new ConsoleOptions("test.dll", "-noresult");
Assert.AreEqual(0, options.ResultOutputSpecifications.Count);
}
[Test]
public void NoResultSuppressesAllResultSpecifications()
{
var options = new ConsoleOptions("test.dll", "-result:results.xml", "-noresult", "-result:nunit2results.xml;format=nunit2");
Assert.AreEqual(0, options.ResultOutputSpecifications.Count);
}
#endregion
#region Explore Option
[Test]
public void ExploreOptionWithoutPath()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "-explore");
Assert.True(options.Validate());
Assert.True(options.Explore);
}
[Test]
public void ExploreOptionWithFilePath()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "-explore:results.xml");
Assert.True(options.Validate());
Assert.AreEqual(1, options.InputFiles.Count, "assembly should be set");
Assert.AreEqual("tests.dll", options.InputFiles[0]);
Assert.True(options.Explore);
OutputSpecification spec = options.ExploreOutputSpecifications[0];
Assert.AreEqual("results.xml", spec.OutputPath);
Assert.AreEqual("nunit3", spec.Format);
Assert.Null(spec.Transform);
}
[Test]
public void ExploreOptionWithFilePathAndFormat()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "-explore:results.xml;format=cases");
Assert.True(options.Validate());
Assert.AreEqual(1, options.InputFiles.Count, "assembly should be set");
Assert.AreEqual("tests.dll", options.InputFiles[0]);
Assert.True(options.Explore);
OutputSpecification spec = options.ExploreOutputSpecifications[0];
Assert.AreEqual("results.xml", spec.OutputPath);
Assert.AreEqual("cases", spec.Format);
Assert.Null(spec.Transform);
}
[Test]
public void ExploreOptionWithFilePathAndTransform()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "-explore:results.xml;transform=myreport.xslt");
Assert.True(options.Validate());
Assert.AreEqual(1, options.InputFiles.Count, "assembly should be set");
Assert.AreEqual("tests.dll", options.InputFiles[0]);
Assert.True(options.Explore);
OutputSpecification spec = options.ExploreOutputSpecifications[0];
Assert.AreEqual("results.xml", spec.OutputPath);
Assert.AreEqual("user", spec.Format);
Assert.AreEqual("myreport.xslt", spec.Transform);
}
[Test]
public void ExploreOptionWithFilePathUsingEqualSign()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "-explore=C:/nunit/tests/bin/Debug/console-test.xml");
Assert.True(options.Validate());
Assert.True(options.Explore);
Assert.AreEqual(1, options.InputFiles.Count, "assembly should be set");
Assert.AreEqual("tests.dll", options.InputFiles[0]);
Assert.AreEqual("C:/nunit/tests/bin/Debug/console-test.xml", options.ExploreOutputSpecifications[0].OutputPath);
}
[Test]
[TestCase(true, null, true)]
[TestCase(false, null, false)]
[TestCase(true, false, true)]
[TestCase(false, false, false)]
[TestCase(true, true, true)]
[TestCase(false, true, true)]
public void ShouldSetTeamCityFlagAccordingToArgsAndDefauls(bool hasTeamcityInCmd, bool? defaultTeamcity, bool expectedTeamCity)
{
// Given
List<string> args = new List<string> { "tests.dll" };
if (hasTeamcityInCmd)
{
args.Add("--teamcity");
}
ConsoleOptions options;
if (defaultTeamcity.HasValue)
{
options = new ConsoleOptions(new DefaultOptionsProviderStub(defaultTeamcity.Value), args.ToArray());
}
else
{
options = new ConsoleOptions(args.ToArray());
}
// When
var actualTeamCity = options.TeamCity;
// Then
Assert.AreEqual(actualTeamCity, expectedTeamCity);
}
#endregion
#region Testlist Option
[Test]
public void ShouldNotFailOnEmptyLine()
{
var testListPath = Path.Combine(TestContext.CurrentContext.TestDirectory, "TestListWithEmptyLine.tst");
// Not copying this test file into releases
Assume.That(testListPath, Does.Exist);
var options = new ConsoleOptions("--testlist=" + testListPath);
Assert.That(options.errorMessages, Is.Empty);
Assert.That(options.TestList, Is.EqualTo(new[] {"AmazingTest"}));
}
#endregion
#region Helper Methods
private static FieldInfo GetFieldInfo(string fieldName)
{
FieldInfo field = typeof(ConsoleOptions).GetField(fieldName);
Assert.IsNotNull(field, "The field '{0}' is not defined", fieldName);
return field;
}
private static PropertyInfo GetPropertyInfo(string propertyName)
{
PropertyInfo property = typeof(ConsoleOptions).GetProperty(propertyName);
Assert.IsNotNull(property, "The property '{0}' is not defined", propertyName);
return property;
}
#endregion
internal sealed class DefaultOptionsProviderStub : IDefaultOptionsProvider
{
public DefaultOptionsProviderStub(bool teamCity)
{
TeamCity = teamCity;
}
public bool TeamCity { get; private set; }
}
}
}
| |
/*
Copyright (c) 2003-2006 Niels Kokholm and Peter Sestoft
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 C5;
using NUnit.Framework;
namespace C5UnitTests.hashtable.bag
{
using CollectionOfInt = HashBag<int>;
[TestFixture]
public class GenericTesters
{
[Test]
public void TestEvents()
{
Func<CollectionOfInt> factory = delegate() { return new CollectionOfInt(TenEqualityComparer.Default); };
new C5UnitTests.Templates.Events.CollectionTester<CollectionOfInt>().Test(factory);
}
[Test]
public void Extensible()
{
C5UnitTests.Templates.Extensible.Clone.Tester<CollectionOfInt>();
C5UnitTests.Templates.Extensible.Serialization.Tester<CollectionOfInt>();
}
}
static class Factory
{
public static ICollection<T> New<T>() { return new HashBag<T>(); }
}
[TestFixture]
public class Formatting
{
ICollection<int> coll;
IFormatProvider rad16;
[SetUp]
public void Init()
{
Debug.UseDeterministicHashing = true;
coll = Factory.New<int>(); rad16 = new RadixFormatProvider(16);
}
[TearDown]
public void Dispose()
{
Debug.UseDeterministicHashing = false;
coll = null; rad16 = null;
}
[Test]
public void Format()
{
Assert.AreEqual("{{ }}", coll.ToString());
coll.AddAll(new int[] { -4, 28, 129, 65530, -4, 28 });
Assert.AreEqual("{{ 65530(*1), -4(*2), 28(*2), 129(*1) }}", coll.ToString());
Assert.AreEqual("{{ FFFA(*1), -4(*2), 1C(*2), 81(*1) }}", coll.ToString(null, rad16));
Assert.AreEqual("{{ 65530(*1), -4(*2)... }}", coll.ToString("L18", null));
Assert.AreEqual("{{ FFFA(*1), -4(*2)... }}", coll.ToString("L18", rad16));
}
}
[TestFixture]
public class Combined
{
private ICollection<KeyValuePair<int, int>> lst;
[SetUp]
public void Init()
{
lst = new HashBag<KeyValuePair<int, int>>(new KeyValuePairEqualityComparer<int, int>());
for (int i = 0; i < 10; i++)
lst.Add(new KeyValuePair<int, int>(i, i + 30));
}
[TearDown]
public void Dispose() { lst = null; }
[Test]
public void Find()
{
KeyValuePair<int, int> p = new KeyValuePair<int, int>(3, 78);
Assert.IsTrue(lst.Find(ref p));
Assert.AreEqual(3, p.Key);
Assert.AreEqual(33, p.Value);
p = new KeyValuePair<int, int>(13, 78);
Assert.IsFalse(lst.Find(ref p));
}
[Test]
public void FindOrAdd()
{
KeyValuePair<int, int> p = new KeyValuePair<int, int>(3, 78);
KeyValuePair<int, int> q = new KeyValuePair<int, int>();
Assert.IsTrue(lst.FindOrAdd(ref p));
Assert.AreEqual(3, p.Key);
Assert.AreEqual(33, p.Value);
p = new KeyValuePair<int, int>(13, 79);
Assert.IsFalse(lst.FindOrAdd(ref p));
q.Key = 13;
Assert.IsTrue(lst.Find(ref q));
Assert.AreEqual(13, q.Key);
Assert.AreEqual(79, q.Value);
}
[Test]
public void Update()
{
KeyValuePair<int, int> p = new KeyValuePair<int, int>(3, 78);
KeyValuePair<int, int> q = new KeyValuePair<int, int>();
Assert.IsTrue(lst.Update(p));
q.Key = 3;
Assert.IsTrue(lst.Find(ref q));
Assert.AreEqual(3, q.Key);
Assert.AreEqual(78, q.Value);
p = new KeyValuePair<int, int>(13, 78);
Assert.IsFalse(lst.Update(p));
}
[Test]
public void UpdateOrAdd1()
{
KeyValuePair<int, int> p = new KeyValuePair<int, int>(3, 78);
KeyValuePair<int, int> q = new KeyValuePair<int, int>();
Assert.IsTrue(lst.UpdateOrAdd(p));
q.Key = 3;
Assert.IsTrue(lst.Find(ref q));
Assert.AreEqual(3, q.Key);
Assert.AreEqual(78, q.Value);
p = new KeyValuePair<int, int>(13, 79);
Assert.IsFalse(lst.UpdateOrAdd(p));
q.Key = 13;
Assert.IsTrue(lst.Find(ref q));
Assert.AreEqual(13, q.Key);
Assert.AreEqual(79, q.Value);
}
[Test]
public void UpdateOrAdd2()
{
ICollection<String> coll = new HashBag<String>();
// s1 and s2 are distinct objects but contain the same text:
String old, s1 = "abc", s2 = ("def" + s1).Substring(3);
Assert.IsFalse(coll.UpdateOrAdd(s1, out old));
Assert.AreEqual(null, old);
Assert.IsTrue(coll.UpdateOrAdd(s2, out old));
Assert.IsTrue(Object.ReferenceEquals(s1, old));
Assert.IsFalse(Object.ReferenceEquals(s2, old));
}
[Test]
public void RemoveWithReturn()
{
KeyValuePair<int, int> p = new KeyValuePair<int, int>(3, 78);
//KeyValuePair<int, int> q = new KeyValuePair<int, int>();
Assert.IsTrue(lst.Remove(p, out p));
Assert.AreEqual(3, p.Key);
Assert.AreEqual(33, p.Value);
p = new KeyValuePair<int, int>(13, 78);
Assert.IsFalse(lst.Remove(p, out p));
}
}
[TestFixture]
public class CollectionOrSink
{
private HashBag<int> hashbag;
[SetUp]
public void Init()
{
Debug.UseDeterministicHashing = true;
hashbag = new HashBag<int>();
}
[Test]
[ExpectedException(typeof(NullReferenceException))]
public void NullEqualityComparerinConstructor1()
{
new HashBag<int>(null);
}
[Test]
[ExpectedException(typeof(NullReferenceException))]
public void NullEqualityComparerinConstructor2()
{
new HashBag<int>(5, null);
}
[Test]
[ExpectedException(typeof(NullReferenceException))]
public void NullEqualityComparerinConstructor3()
{
new HashBag<int>(5, 0.5, null);
}
[Test]
public void Choose()
{
hashbag.Add(7);
Assert.AreEqual(7, hashbag.Choose());
}
[Test]
[ExpectedException(typeof(NoSuchItemException))]
public void BadChoose()
{
hashbag.Choose();
}
[Test]
public void CountEtAl()
{
Assert.IsFalse(hashbag.IsReadOnly);
// Assert.IsFalse(hashbag.SyncRoot == null);
Assert.AreEqual(0, hashbag.Count);
Assert.IsTrue(hashbag.IsEmpty);
Assert.IsTrue(hashbag.AllowsDuplicates);
Assert.IsTrue(hashbag.Add(0));
Assert.AreEqual(1, hashbag.Count);
Assert.IsFalse(hashbag.IsEmpty);
Assert.IsTrue(hashbag.Add(5));
Assert.AreEqual(2, hashbag.Count);
Assert.IsTrue(hashbag.Add(5));
Assert.AreEqual(3, hashbag.Count);
Assert.IsFalse(hashbag.IsEmpty);
Assert.IsTrue(hashbag.Add(8));
Assert.AreEqual(4, hashbag.Count);
Assert.AreEqual(2, hashbag.ContainsCount(5));
Assert.AreEqual(1, hashbag.ContainsCount(8));
Assert.AreEqual(1, hashbag.ContainsCount(0));
}
[Test]
public void AddAll()
{
hashbag.Add(3); hashbag.Add(4); hashbag.Add(4); hashbag.Add(5); hashbag.Add(4);
HashBag<int> hashbag2 = new HashBag<int>();
hashbag2.AddAll(hashbag);
Assert.IsTrue(IC.seteq(hashbag2, 3, 4, 4, 4, 5));
hashbag.Add(9);
hashbag.AddAll(hashbag2);
Assert.IsTrue(IC.seteq(hashbag2, 3, 4, 4, 4, 5));
Assert.IsTrue(IC.seteq(hashbag, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 9));
}
[Test]
public void ContainsCount()
{
Assert.AreEqual(0, hashbag.ContainsCount(5));
hashbag.Add(5);
Assert.AreEqual(1, hashbag.ContainsCount(5));
Assert.AreEqual(0, hashbag.ContainsCount(7));
hashbag.Add(8);
Assert.AreEqual(1, hashbag.ContainsCount(5));
Assert.AreEqual(0, hashbag.ContainsCount(7));
Assert.AreEqual(1, hashbag.ContainsCount(8));
hashbag.Add(5);
Assert.AreEqual(2, hashbag.ContainsCount(5));
Assert.AreEqual(0, hashbag.ContainsCount(7));
Assert.AreEqual(1, hashbag.ContainsCount(8));
}
[Test]
public void RemoveAllCopies()
{
hashbag.Add(5); hashbag.Add(7); hashbag.Add(5);
Assert.AreEqual(2, hashbag.ContainsCount(5));
Assert.AreEqual(1, hashbag.ContainsCount(7));
hashbag.RemoveAllCopies(5);
Assert.AreEqual(0, hashbag.ContainsCount(5));
Assert.AreEqual(1, hashbag.ContainsCount(7));
hashbag.Add(5); hashbag.Add(8); hashbag.Add(5);
hashbag.RemoveAllCopies(8);
Assert.IsTrue(IC.eq(hashbag, 7, 5, 5));
}
[Test]
public void ContainsAll()
{
HashBag<int> list2 = new HashBag<int>();
Assert.IsTrue(hashbag.ContainsAll(list2));
list2.Add(4);
Assert.IsFalse(hashbag.ContainsAll(list2));
hashbag.Add(4);
Assert.IsTrue(hashbag.ContainsAll(list2));
hashbag.Add(5);
Assert.IsTrue(hashbag.ContainsAll(list2));
list2.Add(20);
Assert.IsFalse(hashbag.ContainsAll(list2));
hashbag.Add(20);
Assert.IsTrue(hashbag.ContainsAll(list2));
list2.Add(4);
Assert.IsFalse(hashbag.ContainsAll(list2));
hashbag.Add(4);
Assert.IsTrue(hashbag.ContainsAll(list2));
}
[Test]
public void RetainAll()
{
HashBag<int> list2 = new HashBag<int>();
hashbag.Add(4); hashbag.Add(5); hashbag.Add(4); hashbag.Add(6); hashbag.Add(4);
list2.Add(5); list2.Add(4); list2.Add(7); list2.Add(4);
hashbag.RetainAll(list2);
Assert.IsTrue(IC.seteq(hashbag, 4, 4, 5));
hashbag.Add(6);
list2.Clear();
list2.Add(7); list2.Add(8); list2.Add(9);
hashbag.RetainAll(list2);
Assert.IsTrue(IC.eq(hashbag));
}
[Test]
public void RemoveAll()
{
HashBag<int> list2 = new HashBag<int>();
hashbag.Add(4); hashbag.Add(5); hashbag.Add(6); hashbag.Add(4); hashbag.Add(5);
list2.Add(5); list2.Add(4); list2.Add(7); list2.Add(4);
hashbag.RemoveAll(list2);
Assert.IsTrue(IC.seteq(hashbag, 5, 6));
hashbag.Add(5); hashbag.Add(4);
list2.Clear();
list2.Add(6); list2.Add(5);
hashbag.RemoveAll(list2);
Assert.IsTrue(IC.seteq(hashbag, 4, 5));
list2.Clear();
list2.Add(7); list2.Add(8); list2.Add(9);
hashbag.RemoveAll(list2);
Assert.IsTrue(IC.seteq(hashbag, 4, 5));
}
[Test]
public void Remove()
{
hashbag.Add(4); hashbag.Add(4); hashbag.Add(5); hashbag.Add(4); hashbag.Add(6);
Assert.IsFalse(hashbag.Remove(2));
Assert.IsTrue(hashbag.Remove(4));
Assert.IsTrue(IC.seteq(hashbag, 4, 4, 5, 6));
hashbag.Add(7);
hashbag.Add(21); hashbag.Add(37); hashbag.Add(53); hashbag.Add(69); hashbag.Add(53); hashbag.Add(85);
Assert.IsTrue(hashbag.Remove(5));
Assert.IsTrue(IC.seteq(hashbag, 4, 4, 6, 7, 21, 37, 53, 53, 69, 85));
Assert.IsFalse(hashbag.Remove(165));
Assert.IsTrue(hashbag.Check());
Assert.IsTrue(IC.seteq(hashbag, 4, 4, 6, 7, 21, 37, 53, 53, 69, 85));
Assert.IsTrue(hashbag.Remove(53));
Assert.IsTrue(IC.seteq(hashbag, 4, 4, 6, 7, 21, 37, 53, 69, 85));
Assert.IsTrue(hashbag.Remove(37));
Assert.IsTrue(IC.seteq(hashbag, 4, 4, 6, 7, 21, 53, 69, 85));
Assert.IsTrue(hashbag.Remove(85));
Assert.IsTrue(IC.seteq(hashbag, 4, 4, 6, 7, 21, 53, 69));
}
[TearDown]
public void Dispose()
{
Debug.UseDeterministicHashing = false;
hashbag = null;
}
}
[TestFixture]
public class FindPredicate
{
private HashBag<int> list;
Func<int, bool> pred;
[SetUp]
public void Init()
{
Debug.UseDeterministicHashing = true;
list = new HashBag<int>(TenEqualityComparer.Default);
pred = delegate(int i) { return i % 5 == 0; };
}
[TearDown]
public void Dispose()
{
Debug.UseDeterministicHashing = false;
list = null;
}
[Test]
public void Find()
{
int i;
Assert.IsFalse(list.Find(pred, out i));
list.AddAll(new int[] { 4, 22, 67, 37 });
Assert.IsFalse(list.Find(pred, out i));
list.AddAll(new int[] { 45, 122, 675, 137 });
Assert.IsTrue(list.Find(pred, out i));
Assert.AreEqual(45, i);
}
}
[TestFixture]
public class UniqueItems
{
private HashBag<int> list;
[SetUp]
public void Init() { list = new HashBag<int>(); }
[TearDown]
public void Dispose() { list = null; }
[Test]
public void Test()
{
Assert.IsTrue(IC.seteq(list.UniqueItems()));
Assert.IsTrue(IC.seteq(list.ItemMultiplicities()));
list.AddAll(new int[] { 7, 9, 7 });
Assert.IsTrue(IC.seteq(list.UniqueItems(), 7, 9));
Assert.IsTrue(IC.seteq(list.ItemMultiplicities(), 7, 2, 9, 1));
}
}
[TestFixture]
public class ArrayTest
{
private HashBag<int> hashbag;
int[] a;
[SetUp]
public void Init()
{
Debug.UseDeterministicHashing = true;
hashbag = new HashBag<int>();
a = new int[10];
for (int i = 0; i < 10; i++)
a[i] = 1000 + i;
}
[TearDown]
public void Dispose()
{
Debug.UseDeterministicHashing = false;
hashbag = null;
}
private string aeq(int[] a, params int[] b)
{
if (a.Length != b.Length)
return "Lengths differ: " + a.Length + " != " + b.Length;
for (int i = 0; i < a.Length; i++)
if (a[i] != b[i])
return string.Format("{0}'th elements differ: {1} != {2}", i, a[i], b[i]);
return "Alles klar";
}
[Test]
public void ToArray()
{
Assert.AreEqual("Alles klar", aeq(hashbag.ToArray()));
hashbag.Add(7);
hashbag.Add(3);
hashbag.Add(10);
hashbag.Add(3);
int[] r = hashbag.ToArray();
Array.Sort(r);
Assert.AreEqual("Alles klar", aeq(r, 3, 3, 7, 10));
}
[Test]
public void CopyTo()
{
//Note: for small ints the itemequalityComparer is the identity!
hashbag.CopyTo(a, 1);
Assert.AreEqual("Alles klar", aeq(a, 1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009));
hashbag.Add(6);
hashbag.CopyTo(a, 2);
Assert.AreEqual("Alles klar", aeq(a, 1000, 1001, 6, 1003, 1004, 1005, 1006, 1007, 1008, 1009));
hashbag.Add(4);
hashbag.Add(6);
hashbag.Add(9);
hashbag.CopyTo(a, 4);
//TODO: make independent of interequalityComparer
Assert.AreEqual("Alles klar", aeq(a, 1000, 1001, 6, 1003, 6, 6, 9, 4, 1008, 1009));
hashbag.Clear();
hashbag.Add(7);
hashbag.CopyTo(a, 9);
Assert.AreEqual("Alles klar", aeq(a, 1000, 1001, 6, 1003, 6, 6, 9, 4, 1008, 7));
}
[Test]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void CopyToBad()
{
hashbag.CopyTo(a, 11);
}
[Test]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void CopyToBad2()
{
hashbag.CopyTo(a, -1);
}
[Test]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void CopyToTooFar()
{
hashbag.Add(3);
hashbag.Add(8);
hashbag.CopyTo(a, 9);
}
}
[TestFixture]
public class HashingEquals
{
private ICollection<int> h1, h2;
[SetUp]
public void Init()
{
h1 = new HashBag<int>();
h2 = new LinkedList<int>();
}
[TearDown]
public void Dispose()
{
h1 = h2 = null;
}
[Test]
public void Hashing()
{
Assert.AreEqual(h1.GetUnsequencedHashCode(), h2.GetUnsequencedHashCode());
h1.Add(7);
h2.Add(9);
Assert.IsTrue(h1.GetUnsequencedHashCode() != h2.GetUnsequencedHashCode());
h2.Add(7);
h1.Add(9);
Assert.IsTrue(h1.GetUnsequencedHashCode() == h2.GetUnsequencedHashCode());
}
[Test]
public void Equals()
{
Assert.IsTrue(h1.UnsequencedEquals(h2));
// Code 1550734257, Pair (3 x 1602896434, 2 x 1186320090) number 169185 matched oth
//er pair (3 x -1615223932, 2 x 1019546595)
h1.Add(1602896434);
h1.Add(1186320090);
h1.Add(1602896434);
h1.Add(1186320090);
h1.Add(1602896434);
h2.Add(-1615223932);
h2.Add(1019546595);
h2.Add(-1615223932);
h2.Add(1019546595);
h2.Add(-1615223932);
Assert.IsTrue(h1.GetUnsequencedHashCode() == h2.GetUnsequencedHashCode());
Assert.IsTrue(!h1.UnsequencedEquals(h2));
h1.Clear();
h2.Clear();
h1.Add(1);
h1.Add(2);
h2.Add(2);
h2.Add(1);
Assert.IsTrue(h1.GetUnsequencedHashCode() == h2.GetUnsequencedHashCode());
Assert.IsTrue(h1.UnsequencedEquals(h2));
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="Transform.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.KnownBoxes;
using MS.Internal.Collections;
using MS.Internal.PresentationCore;
using MS.Utility;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.ComponentModel.Design.Serialization;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Effects;
using System.Windows.Media.Media3D;
using System.Windows.Media.Animation;
using System.Windows.Media.Composition;
using System.Windows.Media.Imaging;
using System.Windows.Markup;
using System.Windows.Media.Converters;
using System.Security;
using System.Security.Permissions;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
// These types are aliased to match the unamanaged names used in interop
using BOOL = System.UInt32;
using WORD = System.UInt16;
using Float = System.Single;
namespace System.Windows.Media
{
[TypeConverter(typeof(TransformConverter))]
[ValueSerializer(typeof(TransformValueSerializer))] // Used by MarkupWriter
abstract partial class Transform : GeneralTransform, DUCE.IResource
{
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Shadows inherited Clone() with a strongly typed
/// version for convenience.
/// </summary>
public new Transform Clone()
{
return (Transform)base.Clone();
}
/// <summary>
/// Shadows inherited CloneCurrentValue() with a strongly typed
/// version for convenience.
/// </summary>
public new Transform CloneCurrentValue()
{
return (Transform)base.CloneCurrentValue();
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
#region Public Properties
#endregion Public Properties
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
#region Protected Methods
#endregion ProtectedMethods
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
internal abstract DUCE.ResourceHandle AddRefOnChannelCore(DUCE.Channel channel);
/// <summary>
/// AddRefOnChannel
/// </summary>
DUCE.ResourceHandle DUCE.IResource.AddRefOnChannel(DUCE.Channel channel)
{
// Reconsider the need for this lock when removing the MultiChannelResource.
using (CompositionEngineLock.Acquire())
{
return AddRefOnChannelCore(channel);
}
}
internal abstract void ReleaseOnChannelCore(DUCE.Channel channel);
/// <summary>
/// ReleaseOnChannel
/// </summary>
void DUCE.IResource.ReleaseOnChannel(DUCE.Channel channel)
{
// Reconsider the need for this lock when removing the MultiChannelResource.
using (CompositionEngineLock.Acquire())
{
ReleaseOnChannelCore(channel);
}
}
internal abstract DUCE.ResourceHandle GetHandleCore(DUCE.Channel channel);
/// <summary>
/// GetHandle
/// </summary>
DUCE.ResourceHandle DUCE.IResource.GetHandle(DUCE.Channel channel)
{
DUCE.ResourceHandle handle;
using (CompositionEngineLock.Acquire())
{
handle = GetHandleCore(channel);
}
return handle;
}
internal abstract int GetChannelCountCore();
/// <summary>
/// GetChannelCount
/// </summary>
int DUCE.IResource.GetChannelCount()
{
// must already be in composition lock here
return GetChannelCountCore();
}
internal abstract DUCE.Channel GetChannelCore(int index);
/// <summary>
/// GetChannel
/// </summary>
DUCE.Channel DUCE.IResource.GetChannel(int index)
{
// must already be in composition lock here
return GetChannelCore(index);
}
#endregion Internal Methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
/// <summary>
/// Parse - returns an instance converted from the provided string
/// using the current culture
/// <param name="source"> string with Transform data </param>
/// </summary>
public static Transform Parse(string source)
{
IFormatProvider formatProvider = System.Windows.Markup.TypeConverterHelper.InvariantEnglishUS;
return MS.Internal.Parsers.ParseTransform(source, formatProvider);
}
#endregion Internal Properties
//------------------------------------------------------
//
// Dependency Properties
//
//------------------------------------------------------
#region Dependency Properties
#endregion Dependency Properties
//------------------------------------------------------
//
// Internal Fields
//
//------------------------------------------------------
#region Internal Fields
#endregion Internal Fields
#region Constructors
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#endregion Constructors
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.IdentityModel.Claims
{
using System.Collections.Generic;
using System.IdentityModel.Policy;
using System.Net.Mail;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
public class X509CertificateClaimSet : ClaimSet, IIdentityInfo, IDisposable
{
X509Certificate2 certificate;
DateTime expirationTime = SecurityUtils.MinUtcDateTime;
ClaimSet issuer;
X509Identity identity;
X509ChainElementCollection elements;
IList<Claim> claims;
int index;
bool disposed = false;
public X509CertificateClaimSet(X509Certificate2 certificate)
: this(certificate, true)
{
}
internal X509CertificateClaimSet(X509Certificate2 certificate, bool clone)
{
if (certificate == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("certificate");
this.certificate = clone ? new X509Certificate2(certificate) : certificate;
}
X509CertificateClaimSet(X509CertificateClaimSet from)
: this(from.X509Certificate, true)
{
}
X509CertificateClaimSet(X509ChainElementCollection elements, int index)
{
this.elements = elements;
this.index = index;
this.certificate = elements[index].Certificate;
}
public override Claim this[int index]
{
get
{
ThrowIfDisposed();
EnsureClaims();
return this.claims[index];
}
}
public override int Count
{
get
{
ThrowIfDisposed();
EnsureClaims();
return this.claims.Count;
}
}
IIdentity IIdentityInfo.Identity
{
get
{
ThrowIfDisposed();
if (this.identity == null)
this.identity = new X509Identity(this.certificate, false, false);
return this.identity;
}
}
public DateTime ExpirationTime
{
get
{
ThrowIfDisposed();
if (this.expirationTime == SecurityUtils.MinUtcDateTime)
this.expirationTime = this.certificate.NotAfter.ToUniversalTime();
return this.expirationTime;
}
}
public override ClaimSet Issuer
{
get
{
ThrowIfDisposed();
if (this.issuer == null)
{
if (this.elements == null)
{
X509Chain chain = new X509Chain();
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.Build(certificate);
this.index = 0;
this.elements = chain.ChainElements;
}
if (this.index + 1 < this.elements.Count)
{
this.issuer = new X509CertificateClaimSet(this.elements, this.index + 1);
this.elements = null;
}
// SelfSigned?
else if (StringComparer.OrdinalIgnoreCase.Equals(this.certificate.SubjectName.Name, this.certificate.IssuerName.Name))
this.issuer = this;
else
this.issuer = new X500DistinguishedNameClaimSet(this.certificate.IssuerName);
}
return this.issuer;
}
}
public X509Certificate2 X509Certificate
{
get
{
ThrowIfDisposed();
return this.certificate;
}
}
internal X509CertificateClaimSet Clone()
{
ThrowIfDisposed();
return new X509CertificateClaimSet(this);
}
public void Dispose()
{
if (!this.disposed)
{
this.disposed = true;
SecurityUtils.DisposeIfNecessary(this.identity);
if (this.issuer != null)
{
if (this.issuer != this)
{
SecurityUtils.DisposeIfNecessary(this.issuer as IDisposable);
}
}
if (this.elements != null)
{
for (int i = this.index + 1; i < this.elements.Count; ++i)
{
SecurityUtils.ResetCertificate(this.elements[i].Certificate);
}
}
SecurityUtils.ResetCertificate(this.certificate);
}
}
IList<Claim> InitializeClaimsCore()
{
List<Claim> claims = new List<Claim>();
byte[] thumbprint = this.certificate.GetCertHash();
claims.Add(new Claim(ClaimTypes.Thumbprint, thumbprint, Rights.Identity));
claims.Add(new Claim(ClaimTypes.Thumbprint, thumbprint, Rights.PossessProperty));
// Ordering SubjectName, Dns, SimpleName, Email, Upn
string value = this.certificate.SubjectName.Name;
if (!string.IsNullOrEmpty(value))
claims.Add(Claim.CreateX500DistinguishedNameClaim(this.certificate.SubjectName));
value = this.certificate.GetNameInfo(X509NameType.DnsName, false);
if (!string.IsNullOrEmpty(value))
claims.Add(Claim.CreateDnsClaim(value));
value = this.certificate.GetNameInfo(X509NameType.SimpleName, false);
if (!string.IsNullOrEmpty(value))
claims.Add(Claim.CreateNameClaim(value));
value = this.certificate.GetNameInfo(X509NameType.EmailName, false);
if (!string.IsNullOrEmpty(value))
claims.Add(Claim.CreateMailAddressClaim(new MailAddress(value)));
value = this.certificate.GetNameInfo(X509NameType.UpnName, false);
if (!string.IsNullOrEmpty(value))
claims.Add(Claim.CreateUpnClaim(value));
value = this.certificate.GetNameInfo(X509NameType.UrlName, false);
if (!string.IsNullOrEmpty(value))
claims.Add(Claim.CreateUriClaim(new Uri(value)));
RSA rsa = this.certificate.PublicKey.Key as RSA;
if (rsa != null)
claims.Add(Claim.CreateRsaClaim(rsa));
return claims;
}
void EnsureClaims()
{
if (this.claims != null)
return;
this.claims = InitializeClaimsCore();
}
static bool SupportedClaimType(string claimType)
{
return claimType == null ||
ClaimTypes.Thumbprint.Equals(claimType) ||
ClaimTypes.X500DistinguishedName.Equals(claimType) ||
ClaimTypes.Dns.Equals(claimType) ||
ClaimTypes.Name.Equals(claimType) ||
ClaimTypes.Email.Equals(claimType) ||
ClaimTypes.Upn.Equals(claimType) ||
ClaimTypes.Uri.Equals(claimType) ||
ClaimTypes.Rsa.Equals(claimType);
}
// Note: null string represents any.
public override IEnumerable<Claim> FindClaims(string claimType, string right)
{
ThrowIfDisposed();
if (!SupportedClaimType(claimType) || !ClaimSet.SupportedRight(right))
{
yield break;
}
else if (this.claims == null && ClaimTypes.Thumbprint.Equals(claimType))
{
if (right == null || Rights.Identity.Equals(right))
{
yield return new Claim(ClaimTypes.Thumbprint, this.certificate.GetCertHash(), Rights.Identity);
}
if (right == null || Rights.PossessProperty.Equals(right))
{
yield return new Claim(ClaimTypes.Thumbprint, this.certificate.GetCertHash(), Rights.PossessProperty);
}
}
else if (this.claims == null && ClaimTypes.Dns.Equals(claimType))
{
if (right == null || Rights.PossessProperty.Equals(right))
{
string value = this.certificate.GetNameInfo(X509NameType.DnsName, false);
if (!string.IsNullOrEmpty(value))
{
yield return Claim.CreateDnsClaim(value);
}
}
}
else
{
EnsureClaims();
bool anyClaimType = (claimType == null);
bool anyRight = (right == null);
for (int i = 0; i < this.claims.Count; ++i)
{
Claim claim = this.claims[i];
if ((claim != null) &&
(anyClaimType || claimType.Equals(claim.ClaimType)) &&
(anyRight || right.Equals(claim.Right)))
{
yield return claim;
}
}
}
}
public override IEnumerator<Claim> GetEnumerator()
{
ThrowIfDisposed();
EnsureClaims();
return this.claims.GetEnumerator();
}
public override string ToString()
{
return this.disposed ? base.ToString() : SecurityUtils.ClaimSetToString(this);
}
void ThrowIfDisposed()
{
if (this.disposed)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(this.GetType().FullName));
}
}
class X500DistinguishedNameClaimSet : DefaultClaimSet, IIdentityInfo
{
IIdentity identity;
public X500DistinguishedNameClaimSet(X500DistinguishedName x500DistinguishedName)
{
if (x500DistinguishedName == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("x500DistinguishedName");
this.identity = new X509Identity(x500DistinguishedName);
List<Claim> claims = new List<Claim>(2);
claims.Add(new Claim(ClaimTypes.X500DistinguishedName, x500DistinguishedName, Rights.Identity));
claims.Add(Claim.CreateX500DistinguishedNameClaim(x500DistinguishedName));
Initialize(ClaimSet.Anonymous, claims);
}
public IIdentity Identity
{
get { return this.identity; }
}
}
}
class X509Identity : GenericIdentity, IDisposable
{
const string X509 = "X509";
const string Thumbprint = "; ";
X500DistinguishedName x500DistinguishedName;
X509Certificate2 certificate;
string name;
bool disposed = false;
bool disposable = true;
public X509Identity(X509Certificate2 certificate)
: this(certificate, true, true)
{
}
public X509Identity(X500DistinguishedName x500DistinguishedName)
: base(X509, X509)
{
this.x500DistinguishedName = x500DistinguishedName;
}
internal X509Identity(X509Certificate2 certificate, bool clone, bool disposable)
: base(X509, X509)
{
this.certificate = clone ? new X509Certificate2(certificate) : certificate;
this.disposable = clone || disposable;
}
public override string Name
{
get
{
ThrowIfDisposed();
if (this.name == null)
{
//
// DCR 48092: PrincipalPermission authorization using certificates could cause Elevation of Privilege.
// because there could be duplicate subject name. In order to be more unique, we use SubjectName + Thumbprint
// instead
//
this.name = GetName() + Thumbprint + this.certificate.Thumbprint;
}
return this.name;
}
}
string GetName()
{
if (this.x500DistinguishedName != null)
return this.x500DistinguishedName.Name;
string value = this.certificate.SubjectName.Name;
if (!string.IsNullOrEmpty(value))
return value;
value = this.certificate.GetNameInfo(X509NameType.DnsName, false);
if (!string.IsNullOrEmpty(value))
return value;
value = this.certificate.GetNameInfo(X509NameType.SimpleName, false);
if (!string.IsNullOrEmpty(value))
return value;
value = this.certificate.GetNameInfo(X509NameType.EmailName, false);
if (!string.IsNullOrEmpty(value))
return value;
value = this.certificate.GetNameInfo(X509NameType.UpnName, false);
if (!string.IsNullOrEmpty(value))
return value;
return String.Empty;
}
public override ClaimsIdentity Clone()
{
return this.certificate != null ? new X509Identity(this.certificate) : new X509Identity(this.x500DistinguishedName);
}
public void Dispose()
{
if (this.disposable && !this.disposed)
{
this.disposed = true;
if (this.certificate != null)
{
this.certificate.Reset();
}
}
}
void ThrowIfDisposed()
{
if (this.disposed)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(this.GetType().FullName));
}
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="YamlResourceCache.cs" company="Itransition">
// Itransition (c) Copyright. All right reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
using Castle.Core.Logging;
using Microsoft.Practices.ServiceLocation;
using Yaml.Grammar;
using Environment = Framework.Core.Configuration.Environment;
namespace Framework.Mvc.Resources
{
/// <summary>
/// Parses resources from yaml-files. Monitors resource files changes for development environment.
/// </summary>
/// <remarks>
/// <see cref="YamlResourceCache"/> is thread safe.
/// </remarks>
public class YamlResourceCache : IResourceCache, IDisposable
{
#region Fields
/// <summary>
/// Scope separator.
/// </summary>
public static readonly String ScopeSeparator = ".";
private const String YamlFilesPattern = "*.yml";
private static readonly Object syncRoot = new Object();
private readonly String resourcesPath;
private readonly FileSystemWatcher fileMonitor;
private readonly TimeSpan maximumRetryPeriod = new TimeSpan(0, 0, 30);
private readonly TimeSpan retryDelay = new TimeSpan(0, 0, 5);
private IDictionary<String, String> resources;
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="YamlResourceCache"/> class.
/// </summary>
/// <param name="environment">The environment.</param>
/// <param name="resourcesPath">The resources path.</param>
public YamlResourceCache(Environment environment, String resourcesPath)
{
this.resourcesPath = resourcesPath;
ReadResources();
if (Environment.Development.Equals(environment))
{
fileMonitor = new FileSystemWatcher(resourcesPath, YamlFilesPattern);
fileMonitor.IncludeSubdirectories = true;
fileMonitor.Changed += ResourcesChangedHandler;
fileMonitor.EnableRaisingEvents = true;
}
}
#endregion
#region IResourceCache members
/// <summary>
/// Updates resources cache.
/// </summary>
public void Update()
{
ReadResources();
}
/// <summary>
/// Gets the resource by key.
/// </summary>
/// <param name="key">The resource key.</param>
/// <returns>value associated with <paramref name="key"/> specified or <c>null</c>.</returns>
public String GetResource(String key)
{
lock (syncRoot)
{
String value;
resources.TryGetValue(key.ToLowerInvariant(), out value);
return value;
}
}
/// <summary>
/// Gets resources enumerator.
/// </summary>
/// <returns>resources enumerator.</returns>
public IEnumerator<KeyValuePair<String, String>> GetEnumerator()
{
lock (syncRoot)
{
return resources.GetEnumerator();
}
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
/// <filterpriority>2</filterpriority>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
#region IDisposable members
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
fileMonitor.Dispose();
}
#endregion
#region Helper members
private static String Combine(String key, String prefix)
{
if (String.IsNullOrEmpty(prefix))
{
return key.ToLowerInvariant();
}
return prefix + ScopeSeparator + key.ToLowerInvariant();
}
/// <summary>
/// Check if the file is accesible.
/// </summary>
/// <param name="filename">The name of file to check.</param>
/// <returns>
/// <c>true</c> if the specified file is accessible; <c>false</c> otherwise.
/// </returns>
private static bool IsFileAccessible(String filename)
{
bool success;
// If the file can be opened for exclusive access it means that the file
// is no longer locked by another process.
try
{
using (File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None))
{
success = true;
}
}
catch (IOException)
{
success = false;
}
return success;
}
private void ResourcesChangedHandler(Object sender, FileSystemEventArgs e)
{
ReadResources();
}
private void ReadResources()
{
lock (syncRoot)
{
resources = new Dictionary<String, String>();
foreach (var file in Directory.GetFiles(resourcesPath, YamlFilesPattern, SearchOption.AllDirectories))
{
ThreadPool.QueueUserWorkItem(ProcessFile, file);
}
}
}
private void ProcessFile(Object state)
{
var logger = ServiceLocator.Current.GetInstance<ILogger>();
var file = state as String;
if (!String.IsNullOrEmpty(file) && File.Exists(file))
{
Stopwatch startTime = Stopwatch.StartNew();
while (true)
{
if (IsFileAccessible(file))
{
try
{
var yaml = YamlParser.Load(file).Documents;
foreach (var document in yaml)
{
AddNode(document.Root, String.Empty);
}
break;
}
catch (Exception e)
{
logger.ErrorFormat("Some erro was occured during \"{0}\" processing ({1}).", file, e.Message);
}
}
// Calculate the elapsed time and stop if the maximum retry
// period has been reached.
TimeSpan timeElapsed = startTime.Elapsed;
if (timeElapsed > maximumRetryPeriod)
{
logger.ErrorFormat("The file \"{0}\" could not be processed.", file);
break;
}
Thread.Sleep(retryDelay);
}
}
}
private void AddNode(DataItem node, String path)
{
var mapping = node as Mapping;
if (mapping != null)
{
foreach (var record in mapping.Enties)
{
var key = record.Key as Scalar;
if (key != null)
{
AddNode(record.Value, Combine(key.Text, path));
}
}
}
var scalar = node as Scalar;
if (scalar != null)
{
resources[path] = scalar.Text;
}
}
#endregion
}
}
| |
// INFORM request message type.
// Copyright (C) 2008-2010 Malcolm Crowe, Lex Li, and other contributors.
//
// 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.
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/8/3
* Time: 15:37
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using Lextm.SharpSnmpLib.Security;
namespace Lextm.SharpSnmpLib.Messaging
{
/// <summary>
/// INFORM request message.
/// </summary>
public sealed class InformRequestMessage : ISnmpMessage
{
private readonly byte[] _bytes;
/// <summary>
/// Creates a <see cref="InformRequestMessage"/> with all contents.
/// </summary>
/// <param name="requestId">The request id.</param>
/// <param name="version">Protocol version.</param>
/// <param name="community">Community name.</param>
/// <param name="enterprise">Enterprise.</param>
/// <param name="time">Time ticks.</param>
/// <param name="variables">Variables.</param>
[CLSCompliant(false)]
public InformRequestMessage(int requestId, VersionCode version, OctetString community, ObjectIdentifier enterprise, uint time, IList<Variable> variables)
{
if (variables == null)
{
throw new ArgumentNullException("variables");
}
if (enterprise == null)
{
throw new ArgumentNullException("enterprise");
}
if (community == null)
{
throw new ArgumentNullException("community");
}
if (version == VersionCode.V3)
{
throw new ArgumentException("only v1 and v2c are supported", "version");
}
Version = version;
Enterprise = enterprise;
TimeStamp = time;
Header = Header.Empty;
Parameters = SecurityParameters.Create(community);
var pdu = new InformRequestPdu(
requestId,
enterprise,
time,
variables);
Scope = new Scope(pdu);
Privacy = DefaultPrivacyProvider.DefaultPair;
_bytes = this.PackMessage(null).ToBytes();
}
/// <summary>
/// Initializes a new instance of the <see cref="InformRequestMessage"/> class.
/// </summary>
/// <param name="version">The version.</param>
/// <param name="messageId">The message id.</param>
/// <param name="requestId">The request id.</param>
/// <param name="userName">Name of the user.</param>
/// <param name="enterprise">The enterprise.</param>
/// <param name="time">The time.</param>
/// <param name="variables">The variables.</param>
/// <param name="privacy">The privacy provider.</param>
/// <param name="report">The report.</param>
[CLSCompliant(false)]
[Obsolete("Please use other overloading ones.")]
public InformRequestMessage(VersionCode version, int messageId, int requestId, OctetString userName, ObjectIdentifier enterprise, uint time, IList<Variable> variables, IPrivacyProvider privacy, ISnmpMessage report)
: this(version, messageId, requestId, userName, enterprise, time, variables, privacy, 0xFFE3, report)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="InformRequestMessage"/> class.
/// </summary>
/// <param name="version">The version.</param>
/// <param name="messageId">The message id.</param>
/// <param name="requestId">The request id.</param>
/// <param name="userName">Name of the user.</param>
/// <param name="enterprise">The enterprise.</param>
/// <param name="time">The time.</param>
/// <param name="variables">The variables.</param>
/// <param name="privacy">The privacy provider.</param>
/// <param name="maxMessageSize">Size of the max message.</param>
/// <param name="report">The report.</param>
[CLSCompliant(false)]
public InformRequestMessage(VersionCode version, int messageId, int requestId, OctetString userName, ObjectIdentifier enterprise, uint time, IList<Variable> variables, IPrivacyProvider privacy, int maxMessageSize, ISnmpMessage report)
{
if (userName == null)
{
throw new ArgumentNullException("userName");
}
if (variables == null)
{
throw new ArgumentNullException("variables");
}
if (version != VersionCode.V3)
{
throw new ArgumentException("only v3 is supported", "version");
}
if (enterprise == null)
{
throw new ArgumentNullException("enterprise");
}
if (report == null)
{
throw new ArgumentNullException("report");
}
if (privacy == null)
{
throw new ArgumentNullException("privacy");
}
Version = version;
Privacy = privacy;
Enterprise = enterprise;
TimeStamp = time;
Header = new Header(new Integer32(messageId), new Integer32(maxMessageSize), privacy.ToSecurityLevel() | Levels.Reportable);
var parameters = report.Parameters;
var authenticationProvider = Privacy.AuthenticationProvider;
Parameters = new SecurityParameters(
parameters.EngineId,
parameters.EngineBoots,
parameters.EngineTime,
userName,
authenticationProvider.CleanDigest,
Privacy.Salt);
var pdu = new InformRequestPdu(
requestId,
enterprise,
time,
variables);
var scope = report.Scope;
var contextEngineId = scope.ContextEngineId == OctetString.Empty ? parameters.EngineId : scope.ContextEngineId;
Scope = new Scope(contextEngineId, scope.ContextName, pdu);
authenticationProvider.ComputeHash(Version, Header, Parameters, Scope, Privacy);
_bytes = this.PackMessage(null).ToBytes();
}
internal InformRequestMessage(VersionCode version, Header header, SecurityParameters parameters, Scope scope, IPrivacyProvider privacy, byte[] length)
{
if (scope == null)
{
throw new ArgumentNullException("scope");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (header == null)
{
throw new ArgumentNullException("header");
}
if (privacy == null)
{
throw new ArgumentNullException("privacy");
}
Version = version;
Header = header;
Parameters = parameters;
Scope = scope;
Privacy = privacy;
var pdu = (InformRequestPdu)scope.Pdu;
Enterprise = pdu.Enterprise;
TimeStamp = pdu.TimeStamp;
_bytes = this.PackMessage(length).ToBytes();
}
/// <summary>
/// Gets the privacy provider.
/// </summary>
/// <value>The privacy provider.</value>
public IPrivacyProvider Privacy { get; private set; }
/// <summary>
/// Gets the version.
/// </summary>
/// <value>The version.</value>
public VersionCode Version { get; private set; }
/// <summary>
/// Gets the time stamp.
/// </summary>
/// <value>The time stamp.</value>
[CLSCompliant(false), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "TimeStamp")]
public uint TimeStamp { get; private set; }
/// <summary>
/// Enterprise.
/// </summary>
public ObjectIdentifier Enterprise { get; private set; }
/// <summary>
/// Gets the header.
/// </summary>
public Header Header { get; private set; }
/// <summary>
/// Converts to byte format.
/// </summary>
/// <returns></returns>
public byte[] ToBytes()
{
return _bytes;
}
/// <summary>
/// Gets the parameters.
/// </summary>
/// <value>The parameters.</value>
public SecurityParameters Parameters { get; private set; }
/// <summary>
/// Gets the scope.
/// </summary>
/// <value>The scope.</value>
public Scope Scope { get; private set; }
/// <summary>
/// Returns a <see cref="string"/> that represents this <see cref="InformRequestMessage"/>.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return ToString(null);
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <param name="objects">The objects.</param>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
[CLSCompliant(false)]
public string ToString(IObjectRegistry objects)
{
return string.Format(
CultureInfo.InvariantCulture,
"INFORM request message: time stamp: {0}; community: {1}; enterprise: {2}; varbind count: {3}",
TimeStamp.ToString(CultureInfo.InvariantCulture),
this.Community(),
Enterprise.ToString(objects),
this.Variables().Count.ToString(CultureInfo.InvariantCulture));
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="HttpRequestWrapper.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web {
using System;
using System.Collections.Specialized;
using System.IO;
using System.Runtime.CompilerServices;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Web.Routing;
[TypeForwardedFrom("System.Web.Abstractions, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=31bf3856ad364e35")]
public class HttpRequestWrapper : HttpRequestBase {
private HttpRequest _httpRequest;
public HttpRequestWrapper(HttpRequest httpRequest) {
if (httpRequest == null) {
throw new ArgumentNullException("httpRequest");
}
_httpRequest = httpRequest;
}
public override HttpBrowserCapabilitiesBase Browser {
get {
return new HttpBrowserCapabilitiesWrapper(_httpRequest.Browser);
}
}
public override NameValueCollection Params {
get {
return _httpRequest.Params;
}
}
public override string Path {
get {
return _httpRequest.Path;
}
}
public override string FilePath {
get {
return _httpRequest.FilePath;
}
}
public override NameValueCollection Headers {
get {
return _httpRequest.Headers;
}
}
public override NameValueCollection QueryString {
get {
return _httpRequest.QueryString;
}
}
public override string[] AcceptTypes {
get {
return _httpRequest.AcceptTypes;
}
}
public override string ApplicationPath {
get {
return _httpRequest.ApplicationPath;
}
}
public override string AnonymousID {
get {
return _httpRequest.AnonymousID;
}
}
public override string AppRelativeCurrentExecutionFilePath {
get {
return _httpRequest.AppRelativeCurrentExecutionFilePath;
}
}
public override ChannelBinding HttpChannelBinding {
get {
return _httpRequest.HttpChannelBinding;
}
}
public override HttpClientCertificate ClientCertificate {
get {
return _httpRequest.ClientCertificate;
}
}
public override Encoding ContentEncoding {
get {
return _httpRequest.ContentEncoding;
}
set {
_httpRequest.ContentEncoding = value;
}
}
public override int ContentLength {
get {
return _httpRequest.ContentLength;
}
}
public override string ContentType {
get {
return _httpRequest.ContentType;
}
set {
_httpRequest.ContentType = value;
}
}
public override HttpCookieCollection Cookies {
get {
return _httpRequest.Cookies;
}
}
public override string CurrentExecutionFilePath {
get {
return _httpRequest.CurrentExecutionFilePath;
}
}
public override string CurrentExecutionFilePathExtension {
get {
return _httpRequest.CurrentExecutionFilePathExtension;
}
}
public override HttpFileCollectionBase Files {
get {
// method returns an empty collection rather than null
return new HttpFileCollectionWrapper(_httpRequest.Files);
}
}
public override Stream Filter {
get {
return _httpRequest.Filter;
}
set {
_httpRequest.Filter = value;
}
}
public override NameValueCollection Form {
get {
return _httpRequest.Form;
}
}
public override string HttpMethod {
get {
return _httpRequest.HttpMethod;
}
}
public override Stream InputStream {
get {
return _httpRequest.InputStream;
}
}
public override bool IsAuthenticated {
get {
return _httpRequest.IsAuthenticated;
}
}
public override bool IsLocal {
get {
return _httpRequest.IsLocal;
}
}
public override bool IsSecureConnection {
get {
return _httpRequest.IsSecureConnection;
}
}
public override WindowsIdentity LogonUserIdentity {
get {
return _httpRequest.LogonUserIdentity;
}
}
public override string PathInfo {
get {
return _httpRequest.PathInfo;
}
}
public override string PhysicalApplicationPath {
get {
return _httpRequest.PhysicalApplicationPath;
}
}
public override string PhysicalPath {
get {
return _httpRequest.PhysicalPath;
}
}
public override string RawUrl {
get {
return _httpRequest.RawUrl;
}
}
public override ReadEntityBodyMode ReadEntityBodyMode {
get {
return _httpRequest.ReadEntityBodyMode;
}
}
public override RequestContext RequestContext {
get {
return _httpRequest.RequestContext;
}
set {
_httpRequest.RequestContext = value;
}
}
public override string RequestType {
get {
return _httpRequest.RequestType;
}
set {
_httpRequest.RequestType = value;
}
}
public override NameValueCollection ServerVariables {
get {
return _httpRequest.ServerVariables;
}
}
public override CancellationToken TimedOutToken {
get {
return _httpRequest.TimedOutToken;
}
}
public override ITlsTokenBindingInfo TlsTokenBindingInfo {
get {
return _httpRequest.TlsTokenBindingInfo;
}
}
public override int TotalBytes {
get {
return _httpRequest.TotalBytes;
}
}
public override UnvalidatedRequestValuesBase Unvalidated {
get {
return new UnvalidatedRequestValuesWrapper(_httpRequest.Unvalidated);
}
}
public override Uri Url {
get {
return _httpRequest.Url;
}
}
public override Uri UrlReferrer {
get {
return _httpRequest.UrlReferrer;
}
}
public override string UserAgent {
get {
return _httpRequest.UserAgent;
}
}
public override string[] UserLanguages {
get {
return _httpRequest.UserLanguages;
}
}
public override string UserHostAddress {
get {
return _httpRequest.UserHostAddress;
}
}
public override string UserHostName {
get {
return _httpRequest.UserHostName;
}
}
public override string this[string key] {
get {
return _httpRequest[key];
}
}
public override void Abort() {
_httpRequest.Abort();
}
public override byte[] BinaryRead(int count) {
return _httpRequest.BinaryRead(count);
}
public override Stream GetBufferedInputStream() {
return _httpRequest.GetBufferedInputStream();
}
public override Stream GetBufferlessInputStream() {
return _httpRequest.GetBufferlessInputStream();
}
public override Stream GetBufferlessInputStream(bool disableMaxRequestLength) {
return _httpRequest.GetBufferlessInputStream(disableMaxRequestLength);
}
public override void InsertEntityBody() {
_httpRequest.InsertEntityBody();
}
public override void InsertEntityBody(byte[] buffer, int offset, int count) {
_httpRequest.InsertEntityBody(buffer, offset, count);
}
public override int[] MapImageCoordinates(string imageFieldName) {
return _httpRequest.MapImageCoordinates(imageFieldName);
}
public override double[] MapRawImageCoordinates(string imageFieldName) {
return _httpRequest.MapRawImageCoordinates(imageFieldName);
}
public override string MapPath(string virtualPath) {
return _httpRequest.MapPath(virtualPath);
}
public override string MapPath(string virtualPath, string baseVirtualDir, bool allowCrossAppMapping) {
return _httpRequest.MapPath(virtualPath, baseVirtualDir, allowCrossAppMapping);
}
public override void ValidateInput() {
_httpRequest.ValidateInput();
}
public override void SaveAs(string filename, bool includeHeaders) {
_httpRequest.SaveAs(filename, includeHeaders);
}
}
}
| |
// Graph Engine
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Trinity.Storage;
namespace FanoutSearch
{
internal static class ExpressionBuilder
{
#region Method info objects
private static readonly MemberInfo s_icell_accessor_cell_id_member = typeof(ICell).GetMember("CellID").First();
private static readonly MethodInfo s_long_ienumerable_contains = typeof(Enumerable).GetMethods(BindingFlags.Public | BindingFlags.Static).First(_ => _.Name == "Contains" && _.GetParameters().Count() == 2).MakeGenericMethod(typeof(long));
private static readonly MethodInfo s_string_contains = typeof(string).GetMethod("Contains");
private static readonly MethodInfo s_icell_has = typeof(Verbs).GetMethod("has", new Type[] { typeof(ICell), typeof(string) });
private static readonly MethodInfo s_icell_has_value = typeof(Verbs).GetMethod("has", new Type[] { typeof(ICell), typeof(string), typeof(string) });
private static readonly MethodInfo s_icell_get = typeof(Verbs).GetMethod("get", new Type[] { typeof(ICell), typeof(string) });
private static readonly MethodInfo s_icell_type = typeof(Verbs).GetMethod("type");
private static readonly MethodInfo s_icell_count = typeof(Verbs).GetMethod("count");
#region numerical
private static readonly MethodInfo s_icell_gt_int = typeof(Verbs).GetMethod("greater_than", new Type[] {typeof(ICell), typeof(string), typeof(int) });
private static readonly MethodInfo s_icell_gt_double = typeof(Verbs).GetMethod("greater_than", new Type[] {typeof(ICell), typeof(string), typeof(double) });
private static readonly MethodInfo s_icell_geq_int = typeof(Verbs).GetMethod("greater_than_or_equal", new Type[] {typeof(ICell), typeof(string), typeof(int) });
private static readonly MethodInfo s_icell_geq_double = typeof(Verbs).GetMethod("greater_than_or_equal", new Type[] {typeof(ICell), typeof(string), typeof(double) });
private static readonly MethodInfo s_icell_lt_int = typeof(Verbs).GetMethod("less_than", new Type[] {typeof(ICell), typeof(string), typeof(int) });
private static readonly MethodInfo s_icell_lt_double = typeof(Verbs).GetMethod("less_than", new Type[] {typeof(ICell), typeof(string), typeof(double) });
private static readonly MethodInfo s_icell_leq_int = typeof(Verbs).GetMethod("less_than_or_equal", new Type[] {typeof(ICell), typeof(string), typeof(int) });
private static readonly MethodInfo s_icell_leq_double = typeof(Verbs).GetMethod("less_than_or_equal", new Type[] {typeof(ICell), typeof(string), typeof(double) });
#endregion
#endregion
internal static Expression CompositeEnumConstantToConvertExpression(Type type, object value)
{
int action_int_val = (int)value;
ConstantExpression action_const = Expression.Constant(action_int_val);
Expression action_converted = Expression.Convert(action_const, type);
return action_converted;
}
internal static Expression<Func<ICellAccessor, Action>> WrapAction(Action action)
{
return Expression.Lambda<Func<ICellAccessor, Action>>(
Expression.Constant(action),
Expression.Parameter(typeof(ICellAccessor)));
}
internal static Expression<Func<ICellAccessor, Action>> GenerateTraverseActionFromCellIds(Action action, List<long> cellIds)
{
/***********************************************
* The target expression:
*
* icell_accessor =>
* [cell_id_predicate] ?
* [given action] : ~0
*
* cell_id_predicate:
* single cell id:
* input_icell_param.CellID == cell_id_const
* multiple cell ids:
* cell_id_const.Contains(input_icell_param.CellID)
*
***********************************************/
/* 1. input params */
ParameterExpression input_icell_param = Expression.Parameter(typeof(ICellAccessor), "icell_accessor");
bool single_cell_id = cellIds.Count == 1;
ConstantExpression cell_id_const = single_cell_id ? Expression.Constant(cellIds[0]) : Expression.Constant(cellIds.ToArray());
ConstantExpression action_const = Expression.Constant(action);
ConstantExpression abort_const = Expression.Constant(~(Action)0);
MemberExpression cell_id_expr = Expression.MakeMemberAccess(input_icell_param, s_icell_accessor_cell_id_member);
/* 2. cell_id_predicate */
Expression cell_id_predicate = single_cell_id ? Expression.Equal(cell_id_expr, cell_id_const) : Expression.Call(s_long_ienumerable_contains, cell_id_const, cell_id_expr) as Expression;
/* 3. conditional tenary operator */
ConditionalExpression cond_expr = Expression.Condition(cell_id_predicate, action_const, abort_const);
/* Final lambda expression */
return Expression.Lambda<Func<ICellAccessor, Action>>(cond_expr, input_icell_param);
}
internal static Expression GenerateFieldOperatorExpression(string fieldname, string op, JToken op_obj, ParameterExpression icell)
{
ConstantExpression fieldname_expr = Expression.Constant(fieldname);
switch (op)
{
case JsonDSL.Count:
return GenerateFieldOperatorCountExpression(fieldname_expr, op_obj, icell);
case JsonDSL.Substring:
return GenerateFieldOperatorSubstringExpression(fieldname_expr, op_obj, icell);
case JsonDSL.gt:
case JsonDSL.sym_gt:
return GenerateFieldOperatorGreaterThanExpression(fieldname_expr, op_obj, icell);
case JsonDSL.lt:
case JsonDSL.sym_lt:
return GenerateFieldOperatorLessThanExpression(fieldname_expr, op_obj, icell);
case JsonDSL.geq:
case JsonDSL.sym_geq:
return GenerateFieldOperatorGreaterEqualExpression(fieldname_expr, op_obj, icell);
case JsonDSL.leq:
case JsonDSL.sym_leq:
return GenerateFieldOperatorLessEqualExpression(fieldname_expr, op_obj, icell);
default:
//TODO ignore unrecognized opcode or throw error?
throw new FanoutSearchQueryException("Unrecognized operator " + op);
}
}
#region Field operators
#region Numerical
internal static Expression GenerateFieldOperatorLessEqualExpression(Expression field, JToken op_obj, ParameterExpression icell)
{
if (op_obj.Type == JTokenType.Integer)
{
return Expression.Call(s_icell_leq_int, icell, field, Expression.Constant((int)op_obj));
}
else /* Assume Double */
{
return Expression.Call(s_icell_leq_double, icell, field, Expression.Constant((double)op_obj));
}
}
internal static Expression GenerateFieldOperatorGreaterEqualExpression(Expression field, JToken op_obj, ParameterExpression icell)
{
if (op_obj.Type == JTokenType.Integer)
{
return Expression.Call(s_icell_geq_int, icell, field, Expression.Constant((int)op_obj));
}
else /* Assume Double */
{
return Expression.Call(s_icell_geq_double, icell, field, Expression.Constant((double)op_obj));
}
}
internal static Expression GenerateFieldOperatorLessThanExpression(Expression field, JToken op_obj, ParameterExpression icell)
{
if (op_obj.Type == JTokenType.Integer)
{
return Expression.Call(s_icell_lt_int, icell, field, Expression.Constant((int)op_obj));
}
else /* Assume Double */
{
return Expression.Call(s_icell_lt_double, icell, field, Expression.Constant((double)op_obj));
}
}
internal static Expression GenerateFieldOperatorGreaterThanExpression(Expression field, JToken op_obj, ParameterExpression icell)
{
try
{
if (op_obj.Type == JTokenType.Integer)
{
return Expression.Call(s_icell_gt_int, icell, field, Expression.Constant((int)op_obj));
}
else /* Assume Double */
{
return Expression.Call(s_icell_gt_double, icell, field, Expression.Constant((double)op_obj));
}
}
catch (ArgumentException) { throw new FanoutSearchQueryException("Invalid comparand"); }
catch (FormatException) { throw new FanoutSearchQueryException("Invalid comparand"); }
}
#endregion
internal static Expression GenerateFieldOperatorSubstringExpression(Expression field, JToken op_obj, ParameterExpression icell)
{
ConstantExpression str_expr = Expression.Constant((string)op_obj);
MethodCallExpression get_call = Expression.Call(s_icell_get, icell, field);
return Expression.Call(get_call, s_string_contains, str_expr);
}
internal static Expression GenerateFieldOperatorCountExpression(Expression field, JToken op_obj, ParameterExpression icell)
{
MethodCallExpression count_call = Expression.Call(s_icell_count, icell, field);
if (op_obj.Type == JTokenType.Integer)
{
return Expression.Equal(count_call, Expression.Constant((int)op_obj));
}
else /* Assume Json struct, extract 1st child */
{
IEnumerable<KeyValuePair<string, JToken>> dict = op_obj as JObject;
if (dict == null) { throw new FanoutSearchQueryException("Invalid count operand"); }
var key = dict.First().Key;
var val = dict.First().Value;
if(val.Type != JTokenType.Integer) { throw new FanoutSearchQueryException("Invalid count value"); }
var count_cnt_expr = Expression.Constant((int)val);
switch (key)
{
case JsonDSL.gt:
case JsonDSL.sym_gt:
return Expression.GreaterThan(count_call, count_cnt_expr);
case JsonDSL.lt:
case JsonDSL.sym_lt:
return Expression.LessThan(count_call, count_cnt_expr);
case JsonDSL.geq:
case JsonDSL.sym_geq:
return Expression.GreaterThanOrEqual(count_call, count_cnt_expr);
case JsonDSL.leq:
case JsonDSL.sym_leq:
return Expression.LessThanOrEqual(count_call, count_cnt_expr);
default:
throw new FanoutSearchQueryException("Unrecognized comparator " + key);
}
}
}
#endregion
/// <summary>
/// When the field key is a DSL keyword, it may also represents a predicate of:
/// - type query
/// - cell id query
/// - has query
/// </summary>
internal static Expression GenerateFieldPredicateExpression(string pred_key, JToken pred_obj, ParameterExpression icell)
{
ConstantExpression key_expr = Expression.Constant(pred_key);
Lazy<ConstantExpression> pred_str_expr = new Lazy<ConstantExpression>(() => Expression.Constant((string)pred_obj));
switch (pred_key)
{
case JsonDSL.Id:
{
ConstantExpression id_list = Expression.Constant((pred_obj as JArray).Select(_ => (long)_).ToArray());
MemberExpression icell_id = Expression.MakeMemberAccess(icell, s_icell_accessor_cell_id_member);
return Expression.Call(s_long_ienumerable_contains, id_list, icell_id);
}
case JsonDSL.Type:
{
return Expression.Call(s_icell_type, icell, pred_str_expr.Value);
}
case JsonDSL.Has:
{
if(pred_obj.Type != JTokenType.String) { throw new FanoutSearchQueryException("Invalid has operand"); }
return Expression.Call(s_icell_has, icell, pred_str_expr.Value);
}
}
switch (pred_obj.Type)
{
case JTokenType.String:
return Expression.IsTrue(Expression.Call(s_icell_has_value, icell, key_expr, pred_str_expr.Value));
case JTokenType.Object:
{
IEnumerable<KeyValuePair<string, JToken>> child_tokens = pred_obj as JObject;
if (child_tokens == null || child_tokens.Count() == 0)
{
/* If no conditions are specified, return true */
return Expression.Constant(true);
}
Expression field_pred_exp = GenerateFieldOperatorExpression(pred_key, child_tokens.First().Key, child_tokens.First().Value, icell);
foreach (var kvp in child_tokens.Skip(1))
{
field_pred_exp = Expression.AndAlso(field_pred_exp, GenerateFieldOperatorExpression(pred_key, kvp.Key, kvp.Value, icell));
}
return field_pred_exp;
}
default:
throw new FanoutSearchQueryException("Invalid property value");
}
}
/// <summary>
/// Generates boolean expressions from the Json DSL predicate object.
/// </summary>
/// <param name="pred_object">Caller guarantees that pred_object is not null</param>
/// <param name="icell"></param>
/// <returns></returns>
internal static Expression GenerateBooleanPredicateExpression(JObject pred_object, ParameterExpression icell)
{
JToken or_token = null;
JToken not_token = null;
JObject or_obj = null;
JObject not_obj = null;
if(pred_object.TryGetValue(JsonDSL.or, out or_token))
{
or_obj = or_token as JObject;
}
if(pred_object.TryGetValue(JsonDSL.not, out not_token))
{
not_obj = not_token as JObject;
}
if (or_obj != null && not_obj != null)
{
throw new FanoutSearchQueryException("Cannot specify not/or conditions together.");
}
if (or_obj != null)
{
if (or_obj.Count == 0)
{
throw new FanoutSearchQueryException("No predicates found in OR expression.");
}
IEnumerable<KeyValuePair<string, JToken>> enumerable = or_obj;
Expression or_pred = GenerateFieldPredicateExpression(enumerable.First().Key, enumerable.First().Value, icell);
foreach (var or_other_conditions in enumerable.Skip(1))
{
or_pred = Expression.OrElse(or_pred, GenerateFieldPredicateExpression(or_other_conditions.Key, or_other_conditions.Value, icell));
}
return or_pred;
}
else if (not_obj != null)
{
return Expression.IsFalse(GenerateBooleanPredicateExpression(not_obj, icell));
}
else /* and also expr */
{
IEnumerable<KeyValuePair<string, JToken>> enumerable = pred_object;
if (pred_object.Count == 0)
{
throw new FanoutSearchQueryException("No predicates found.");
}
Expression and_pred = GenerateFieldPredicateExpression(enumerable.First().Key, enumerable.First().Value, icell);
foreach (var and_other_conditions in enumerable.Skip(1))
{
and_pred = Expression.AndAlso(and_pred, GenerateFieldPredicateExpression(and_other_conditions.Key, and_other_conditions.Value, icell));
}
return and_pred;
}
}
/// <summary>
/// Generates conditional expressions of form (pred) ? action: noaction
/// When pred is empty, or always evaluates to true, generate Action.pred_action.
/// When pred is false, generate NOACTION
/// When pred is null, return null.
/// </summary>
internal static Expression GenerateConditionalPredicateExpression(JObject pred_object, Action pred_action, ParameterExpression icell)
{
ConstantExpression action_const = Expression.Constant(pred_action);
Expression noaction_const = Expression.Convert(Expression.Constant(~(int)0), typeof(FanoutSearch.Action));
if (pred_object == null)
return null;
if ((pred_object.Type == JTokenType.Boolean && ((bool)pred_object) == true) || pred_object.Count == 0)
return action_const;
if (pred_object.Type == JTokenType.Boolean && (bool)pred_object == false)
return noaction_const;
return Expression.Condition(GenerateBooleanPredicateExpression(pred_object, icell), action_const, noaction_const);
}
/// <summary>
/// If both return & continue predicates are not given, the action_object itself will be parsed
/// as a conditional predicate expression, defaulting to default_action.
/// If action_object is null, returns a pass-through default action (_ => default_action).
///
/// Valid action_object examples:
///
/// 1.
/// {
/// return: { ... }
/// }
///
/// 2.
/// {
/// continue: { ... }
/// }
///
/// 3.
/// {
/// return: { ... }
/// continue: { ... }
/// }
///
/// 4.
/// {
/// /* no return, no continue, but can be directly parsed as traverse conditions */
/// }
///
/// </summary>
internal static Expression<Func<ICellAccessor, Action>> GenerateTraverseActionFromQueryObject(JObject action_object, Action default_action)
{
ParameterExpression icell_param = Expression.Parameter(typeof(ICellAccessor), "icell_accessor");
if (action_object == null)
{
return WrapAction(default_action);
}
JToken continue_obj = action_object[JsonDSL.Continue];
JToken return_obj = action_object[JsonDSL.Return];
Expression continue_pred = GenerateConditionalPredicateExpression(continue_obj as JObject, Action.Continue, icell_param);
Expression return_pred = GenerateConditionalPredicateExpression(return_obj as JObject, Action.Return, icell_param);
Expression lambda_body;
if(continue_pred == null && continue_obj != null) { throw new FanoutSearchQueryException("Invalid continue expression"); }
if(return_pred == null && return_obj != null) { throw new FanoutSearchQueryException("Invalid return expression"); }
if (continue_pred != null && return_pred != null)
{
// Bitwise 'AND' operator does not work with flag enums.
// According to system-generated expression trees, they
// are translated to integers, bitwise-and, and then
// converted back.
lambda_body =
Expression.Convert(
Expression.And(
Expression.Convert(continue_pred, typeof(Int32)),
Expression.Convert(return_pred, typeof(Int32))),
typeof(FanoutSearch.Action));
}
else if (continue_pred != null || return_pred != null)
{
lambda_body = continue_pred ?? return_pred;
}
else /* continue_pred == null && return_pred == null */
{
lambda_body = GenerateConditionalPredicateExpression(action_object, default_action, icell_param);
}
return Expression.Lambda<Func<ICellAccessor, Action>>(lambda_body, icell_param);
}
internal static Expression<Func<ICellAccessor, Action>> GenerateStronglyTypedTraverseAction<T>(Expression<Func<T, Action>> action) where T : ICellAccessor
{
/***********************************************
* The target expression:
*
* icell_accessor =>
* icell_accessor.let(
* icell.Cast<T>(),
* (_, strongly_typed_accessor) =>
* action(strongly_typed_accessor));
***********************************************/
/***********************************************
Example:
Func<T, TraverseAction> action_func = t => TraverseAction.Stop;
Func<ICellAccessor, TraverseAction> target_func =
icell_accessor =>
icell_accessor.let(
icell_accessor.Cast<T>(),
(_, strongly_typed_accessor) =>
action_func(strongly_typed_accessor));
************************************************/
/* 1. input params */
ParameterExpression input_icell_param = Expression.Parameter(typeof(ICellAccessor), "icell_accessor");
ParameterExpression _param = Expression.Parameter(typeof(ICellAccessor), "_");
ParameterExpression s_typed_param = Expression.Parameter(typeof(T), "strongly_typed_accessor");
/* 2. The invocation of the strongly-typed action */
InvocationExpression action_invoke = Expression.Invoke(action, s_typed_param);
/* 3. inner lambda expression */
LambdaExpression inner_lambda = Expression.Lambda<Func<ICellAccessor, T, Action>>(action_invoke, _param, s_typed_param);
/* 4. let call */
MethodCallExpression cast_call = Expression.Call(typeof(Verbs), "Cast", new Type[] { typeof(T) }, new Expression[] { input_icell_param });
MethodCallExpression let_call = Expression.Call(typeof(Verbs), "let", new Type[] { typeof(T) }, new Expression[] { input_icell_param, cast_call, inner_lambda });
/* 5. final lambda expression */
Expression<Func<ICellAccessor, Action>> wrapped_action = Expression.Lambda<Func<ICellAccessor, Action>>(let_call, input_icell_param);
return wrapped_action;
}
}
}
| |
using System;
using System.Collections;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Reflection;
using Mono.Cecil;
using MonoDevelop.MicroFramework;
using Mono.Cecil.Cil;
namespace Microsoft.SPOT.Debugger
{
public class CorDebugFunction
{
CorDebugClass m_class;
Pdbx.Method m_pdbxMethod;
CorDebugCode m_codeNative;
CorDebugCode m_codeIL;
uint m_tkSymbolless;
public CorDebugFunction (CorDebugClass cls, Pdbx.Method method)
{
m_class = cls;
m_pdbxMethod = method;
}
public CorDebugFunction (CorDebugClass cls, uint tkSymbolless) : this (cls, null)
{
m_tkSymbolless = tkSymbolless;
}
public CorDebugClass Class {
[System.Diagnostics.DebuggerHidden]
get { return m_class; }
}
public CorDebugAppDomain AppDomain {
[System.Diagnostics.DebuggerHidden]
get { return this.Class.AppDomain; }
}
public CorDebugProcess Process {
[System.Diagnostics.DebuggerHidden]
get { return this.Class.Process; }
}
public CorDebugAssembly Assembly {
[System.Diagnostics.DebuggerHidden]
get { return this.Class.Assembly; }
}
private Engine Engine {
[System.Diagnostics.DebuggerHidden]
get { return this.Class.Engine; }
}
[System.Diagnostics.DebuggerStepThrough]
private CorDebugCode GetCode (ref CorDebugCode code)
{
if (code == null)
code = new CorDebugCode (this);
return code;
}
public bool HasSymbols {
get { return m_pdbxMethod != null; }
}
public uint MethodDef_Index {
get {
uint tk = HasSymbols ? m_pdbxMethod.Token.TinyCLR : m_tkSymbolless;
return TinyCLR_TypeSystem.ClassMemberIndexFromTinyCLRToken (tk, this.m_class.Assembly);
}
}
public Pdbx.Method PdbxMethod {
[System.Diagnostics.DebuggerHidden]
get { return m_pdbxMethod; }
}
public bool IsInternal {
get { return (Class.Assembly.MetaData.LookupToken ((int)this.m_pdbxMethod.Token.CLR) as MethodDefinition).IsInternalCall; }
}
public bool IsInstance {
get { return !(Class.Assembly.MetaData.LookupToken ((int)this.m_pdbxMethod.Token.CLR) as MethodDefinition).IsStatic; }
}
public bool IsVirtual {
get { return (Class.Assembly.MetaData.LookupToken ((int)this.m_pdbxMethod.Token.CLR) as MethodDefinition).IsVirtual; }
}
public uint GetILCLRFromILTinyCLR (uint ilTinyCLR)
{
uint ilCLR;
//Special case for CatchHandlerFound and AppDomain transitions; possibly used elsewhere.
if (ilTinyCLR == uint.MaxValue)
return uint.MaxValue;
ilCLR = ILComparer.Map (false, m_pdbxMethod.ILMap, ilTinyCLR);
Debug.Assert (ilTinyCLR <= ilCLR);
return ilCLR;
}
public uint GetILTinyCLRFromILCLR (uint ilCLR)
{
//Special case for when CPDE wants to step to the end of the function?
if (ilCLR == uint.MaxValue)
return uint.MaxValue;
uint ilTinyCLR = ILComparer.Map (true, m_pdbxMethod.ILMap, ilCLR);
Debug.Assert (ilTinyCLR <= ilCLR);
return ilTinyCLR;
}
private class ILComparer : IComparer
{
bool m_fCLR;
private ILComparer (bool fCLR)
{
m_fCLR = fCLR;
}
private static uint GetIL (bool fCLR, Pdbx.IL il)
{
return fCLR ? il.CLR : il.TinyCLR;
}
private uint GetIL (Pdbx.IL il)
{
return GetIL (m_fCLR, il);
}
private static void SetIL (bool fCLR, Pdbx.IL il, uint offset)
{
if (fCLR)
il.CLR = offset;
else
il.TinyCLR = offset;
}
private void SetIL (Pdbx.IL il, uint offset)
{
SetIL (m_fCLR, il, offset);
}
public int Compare (object o1, object o2)
{
return GetIL (o1 as Pdbx.IL).CompareTo (GetIL (o2 as Pdbx.IL));
}
public static uint Map (bool fCLR, Pdbx.IL[] ilMap, uint offset)
{
ILComparer ilComparer = new ILComparer (fCLR);
Pdbx.IL il = new Pdbx.IL ();
ilComparer.SetIL (il, offset);
int i = Array.BinarySearch (ilMap, il, ilComparer);
uint ret = 0;
if (i >= 0) {
//Exact match
ret = GetIL (!fCLR, ilMap [i]);
} else {
i = ~i;
if (i == 0) {
//Before the IL diverges
ret = offset;
} else {
//Somewhere in between
i--;
il = ilMap [i];
ret = offset - GetIL (fCLR, il) + GetIL (!fCLR, il);
}
}
Debug.Assert (ret >= 0);
return ret;
}
}
public uint Token {
get {
return HasSymbols ? m_pdbxMethod.Token.CLR : m_tkSymbolless;
}
}
public CorDebugCode ILCode {
get {
return GetCode (ref m_codeIL);
}
}
public MethodDefinition GetMethodInfo (MicroFrameworkDebuggerSession session)
{
return Assembly.MetaData != null ? Assembly.MetaData.LookupToken ((int)Token) as MethodDefinition : null;
}
public MethodSymbols GetMethodSymbols (MicroFrameworkDebuggerSession session)
{
if (Assembly.DebugData == null)
return null;
var methodSymols = new MethodSymbols (new MetadataToken (PdbxMethod.Token.CLR));
//Ugliest hack ever
if(Assembly.DebugData is Mono.Cecil.Mdb.MdbReader) {
for(int i = 0; i < 100; i++)
methodSymols.Variables.Add(new VariableDefinition(null));
}
Assembly.DebugData.Read (methodSymols);
return methodSymols;
}
}
}
| |
// 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.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
//using OpenLiveWriter.CoreServices;
//using OpenLiveWriter.Localization;
namespace Platform.Presentation.Forms.Controls
{
[ToolboxBitmap(typeof(System.Windows.Forms.PictureBox))]
[ToolboxItem(true)]
public partial class ImageCropControl : UserControl
{
private const AnchorStyles ANCHOR_ALL = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Bottom | AnchorStyles.Right;
private Bitmap bitmap;
private DualRects crop;
private CachedResizedBitmap crbNormal;
private CachedResizedBitmap crbGrayed;
private bool gridLines;
private CropStrategy cropStrategy = new FreeCropStrategy();
private bool fireCropChangedOnKeyUp = false;
public ImageCropControl()
{
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.ResizeRedraw, true);
InitializeComponent();
//AccessibleName = Res.Get(StringId.CropPane);
AccessibleRole = AccessibleRole.Pane;
TabStop = true;
}
public bool GridLines
{
get { return gridLines; }
set
{
if (gridLines != value)
{
gridLines = value;
Invalidate();
}
}
}
public event EventHandler CropRectangleChanged;
private void OnCropRectangleChanged()
{
if (CropRectangleChanged != null)
CropRectangleChanged(this, EventArgs.Empty);
}
public event EventHandler AspectRatioChanged;
private void OnAspectRatioChanged()
{
if (AspectRatioChanged != null)
AspectRatioChanged(this, EventArgs.Empty);
}
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Rectangle CropRectangle
{
get { return crop.Real; }
set { crop.Real = value; }
}
public void Crop()
{
Bitmap newBitmap = new Bitmap(bitmap, crop.Real.Size.Width, crop.Real.Size.Height);
using (Graphics g = Graphics.FromImage(newBitmap))
{
g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;
g.DrawImage(bitmap, new Rectangle(0, 0, newBitmap.Width, newBitmap.Height), crop.Real, GraphicsUnit.Pixel);
}
Bitmap = newBitmap;
}
public double? AspectRatio
{
get
{
return cropStrategy.AspectRatio;
}
set
{
if (value == null)
{
cropStrategy = new FreeCropStrategy();
OnAspectRatioChanged();
Invalidate();
}
else
{
cropStrategy = new FixedAspectRatioCropStrategy(value.Value);
OnAspectRatioChanged();
Rectangle containerRect = crop.VirtualizeRect(0, 0, bitmap.Width, bitmap.Height);
Rectangle cropped = ((FixedAspectRatioCropStrategy)cropStrategy).ConformCropRectangle(containerRect, crop.Virtual);
if (cropped.Right > containerRect.Right)
cropped.X -= cropped.Right - containerRect.Right;
if (cropped.Bottom > containerRect.Bottom)
cropped.Y -= cropped.Bottom - containerRect.Bottom;
if (cropped.Left < containerRect.Left)
cropped.X += containerRect.Left - cropped.Left;
if (cropped.Top < containerRect.Top)
cropped.Y += containerRect.Top - cropped.Top;
crop.Virtual = cropped;
if (!cropStrategy.IsDragging)
{
cropStrategy.BeginDrag(
crop.Virtual,
new Point(crop.Virtual.Right, crop.Virtual.Bottom),
AnchorStyles.Bottom | AnchorStyles.Right,
crop.VirtualizeRect(0, 0, bitmap.Width, bitmap.Height));
crop.Virtual = cropStrategy.GetNewBounds(new Point(crop.Virtual.Right, crop.Virtual.Bottom));
Invalidate();
Update();
OnCropRectangleChanged();
cropStrategy.EndDrag();
}
}
}
}
private void NullAndDispose<T>(ref T disposable) where T : IDisposable
{
IDisposable tmp = disposable;
disposable = default(T);
if (tmp != null)
tmp.Dispose();
}
public Bitmap Bitmap
{
get { return bitmap; }
set
{
if (value != null)
{
NullAndDispose(ref crbNormal);
NullAndDispose(ref crbGrayed);
}
bitmap = value;
if (bitmap != null)
{
crbNormal = new CachedResizedBitmap(value, false);
crbGrayed = new CachedResizedBitmap(MakeGray(value), true);
crop = new DualRects(PointF.Empty, bitmap.Size);
crop.Real = new Rectangle(
bitmap.Width / 4,
bitmap.Height / 4,
Math.Max(1, bitmap.Width / 2),
Math.Max(1, bitmap.Height / 2));
OnCropRectangleChanged();
}
PerformLayout();
Invalidate();
}
}
private Bitmap MakeGray(Bitmap orig)
{
Bitmap grayed = new Bitmap(orig);
using (Graphics g = Graphics.FromImage(grayed))
{
using (Brush b = new SolidBrush(Color.FromArgb(128, Color.Gray)))
g.FillRectangle(b, 0, 0, grayed.Width, grayed.Height);
}
return grayed;
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
if (e.Button == MouseButtons.Left)
{
AnchorStyles anchor = cropStrategy.HitTest(crop.Virtual, e.Location);
if (anchor != AnchorStyles.None)
{
cropStrategy.BeginDrag(
crop.Virtual,
e.Location,
anchor,
crop.VirtualizeRect(0, 0, bitmap.Width, bitmap.Height));
Capture = true;
}
}
}
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
if (cropStrategy.IsDragging && e.Button == MouseButtons.Left)
{
cropStrategy.EndDrag();
Capture = false;
OnCropRectangleChanged();
}
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
if (cropStrategy.IsDragging)
{
Rectangle originalRect = crop.Virtual;
crop.Virtual = cropStrategy.GetNewBounds(PointToClient(MousePosition));
InvalidateForRectChange(originalRect, crop.Virtual);
}
else if (e.Button == MouseButtons.None)
{
Cursor = ChooseCursor(crop.Virtual, e.Location);
}
}
private void InvalidateForRectChange(Rectangle oldRect, Rectangle newRect)
{
int borderWidth = BoundsWithHandles.HANDLE_SIZE * 2;
InvalidateBorder(oldRect, borderWidth);
InvalidateBorder(newRect, borderWidth);
if (gridLines)
{
InvalidateGridlines(oldRect);
InvalidateGridlines(newRect);
}
using (Region region = new Region(oldRect))
{
region.Xor(newRect);
Invalidate(region);
}
}
private void InvalidateBorder(Rectangle rect, int width)
{
rect.Inflate(width / 2, width / 2);
using (Region region = new Region(rect))
{
rect.Inflate(-width, -width);
region.Exclude(rect);
Invalidate(region);
}
}
private void InvalidateGridlines(Rectangle rect)
{
int x1, x2, y1, y2;
CalculateGridlines(rect, out x1, out x2, out y1, out y2);
using (Region gridRegion = new Region())
{
gridRegion.MakeEmpty();
gridRegion.Union(new Rectangle(x1, rect.Top, 1, rect.Height));
gridRegion.Union(new Rectangle(x2, rect.Top, 1, rect.Height));
gridRegion.Union(new Rectangle(rect.Left, y1, rect.Width, 1));
gridRegion.Union(new Rectangle(rect.Left, y2, rect.Width, 1));
Invalidate(gridRegion);
}
}
private Cursor ChooseCursor(Rectangle sizeRect, Point point)
{
AnchorStyles anchor = cropStrategy.HitTest(sizeRect, point);
switch (anchor)
{
case AnchorStyles.Left:
case AnchorStyles.Right:
return Cursors.SizeWE;
case AnchorStyles.Top:
case AnchorStyles.Bottom:
return Cursors.SizeNS;
case AnchorStyles.Top | AnchorStyles.Left:
case AnchorStyles.Bottom | AnchorStyles.Right:
return Cursors.SizeNWSE;
case AnchorStyles.Top | AnchorStyles.Right:
case AnchorStyles.Bottom | AnchorStyles.Left:
return Cursors.SizeNESW;
case AnchorStyles.None:
return Cursors.Default;
case ANCHOR_ALL:
return Cursors.SizeAll;
default:
Debug.Fail("Unexpected anchor: " + anchor);
return Cursors.Default;
}
}
protected override void OnGotFocus(EventArgs e)
{
base.OnGotFocus(e);
Invalidate();
}
protected override void OnLostFocus(EventArgs e)
{
base.OnLostFocus(e);
Invalidate();
}
public bool ProcessCommandKey(ref Message msg, Keys keyData)
{
return ProcessCmdKey(ref msg, keyData);
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
switch (keyData)
{
case Keys.Up | Keys.Control:
case Keys.Up:
return AdjustCropRectangle(0, -1, 0, 0);
case Keys.Down | Keys.Control:
case Keys.Down:
return AdjustCropRectangle(0, 1, 0, 0);
case Keys.Left | Keys.Control:
case Keys.Left:
return AdjustCropRectangle(-1, 0, 0, 0);
case Keys.Right | Keys.Control:
case Keys.Right:
return AdjustCropRectangle(1, 0, 0, 0);
case Keys.Left | Keys.Shift:
return AdjustCropRectangle(0, 0, -1, 0);
case Keys.Right | Keys.Shift:
return AdjustCropRectangle(0, 0, 1, 0);
case Keys.Up | Keys.Shift:
return AdjustCropRectangle(0, 0, 0, -1);
case Keys.Down | Keys.Shift:
return AdjustCropRectangle(0, 0, 0, 1);
}
return base.ProcessCmdKey(ref msg, keyData);
}
private bool AdjustCropRectangle(int xOffset, int yOffset, int xGrow, int yGrow)
{
Rectangle orig = crop.Virtual;
Rectangle result = cropStrategy.AdjustRectangle(
crop.VirtualizeRect(0, 0, bitmap.Width, bitmap.Height),
orig,
xOffset, yOffset, xGrow, yGrow);
if (orig != result)
{
crop.Virtual = result;
fireCropChangedOnKeyUp = true;
InvalidateForRectChange(orig, result);
}
else
{
// annoying
// SystemSounds.Beep.Play();
}
return true;
}
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
if (fireCropChangedOnKeyUp)
{
fireCropChangedOnKeyUp = false;
OnCropRectangleChanged();
}
}
protected override void OnLayout(LayoutEventArgs e)
{
if (bitmap == null)
return;
float scaleFactor = Math.Min(
(float)Width / bitmap.Width,
(float)Height / bitmap.Height);
Rectangle realRect = crop.Real;
SizeF scale;
PointF offset;
if (scaleFactor > 1.0f)
{
scale = new SizeF(1, 1);
offset = new PointF((Width - bitmap.Width) / 2, (Height - bitmap.Height) / 2);
}
else
{
offset = Point.Empty;
scale = new SizeF(scaleFactor, scaleFactor);
offset.X = (Width - (bitmap.Width * scale.Width)) / 2;
offset.Y = (Height - (bitmap.Height * scale.Height)) / 2;
}
crop = new DualRects(offset, scale);
crop.Real = realRect;
Size virtualBitmapSize = crop.VirtualizeRect(0, 0, bitmap.Width, bitmap.Height).Size;
crbNormal.Resize(virtualBitmapSize);
crbGrayed.Resize(virtualBitmapSize);
}
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.InterpolationMode = InterpolationMode.Default;
e.Graphics.SmoothingMode = SmoothingMode.HighSpeed;
e.Graphics.CompositingMode = CompositingMode.SourceCopy;
e.Graphics.CompositingQuality = CompositingQuality.HighSpeed;
using (Brush b = new SolidBrush(BackColor))
e.Graphics.FillRectangle(b, ClientRectangle);
if (bitmap == null)
return;
Rectangle bitmapRect = crop.VirtualizeRect(0, 0, bitmap.Width, bitmap.Height);
e.Graphics.DrawImage(crbGrayed.ResizedBitmap, bitmapRect);
Rectangle normalSrcRect = crop.Virtual;
normalSrcRect.Offset(-bitmapRect.X, -bitmapRect.Y);
e.Graphics.DrawImage(crbNormal.ResizedBitmap, crop.Virtual, normalSrcRect, GraphicsUnit.Pixel);
e.Graphics.CompositingMode = CompositingMode.SourceOver;
Rectangle cropDrawRect = crop.Virtual;
cropDrawRect.Width -= 1;
cropDrawRect.Height -= 1;
using (Brush b = new SolidBrush(Color.FromArgb(200, Color.White)))
using (Pen p = new Pen(b, 1))
{
e.Graphics.DrawRectangle(p, cropDrawRect);
}
if (gridLines)
{
int x1, x2, y1, y2;
CalculateGridlines(crop.Virtual, out x1, out x2, out y1, out y2);
using (Brush b = new SolidBrush(Color.FromArgb(128, Color.Gray)))
using (Pen p = new Pen(b, 1))
{
e.Graphics.DrawLine(p, cropDrawRect.Left, y1, cropDrawRect.Right, y1);
e.Graphics.DrawLine(p, cropDrawRect.Left, y2, cropDrawRect.Right, y2);
e.Graphics.DrawLine(p, x1, cropDrawRect.Top, x1, cropDrawRect.Bottom);
e.Graphics.DrawLine(p, x2, cropDrawRect.Top, x2, cropDrawRect.Bottom);
}
}
if (Focused)
{
Rectangle focusRect = cropDrawRect;
focusRect.Inflate(2, 2);
ControlPaint.DrawFocusRectangle(e.Graphics, focusRect);
}
BoundsWithHandles boundsWithHandles = new BoundsWithHandles(cropStrategy.AspectRatio == null ? true : false);
boundsWithHandles.Bounds = cropDrawRect;
using (Pen p = new Pen(SystemColors.ControlDarkDark, 1f))
{
foreach (Rectangle rect in boundsWithHandles.GetHandles())
{
e.Graphics.FillRectangle(SystemBrushes.Window, rect);
e.Graphics.DrawRectangle(p, rect);
}
}
}
private static void CalculateGridlines(Rectangle cropDrawRect, out int x1, out int x2, out int y1, out int y2)
{
int yThird = cropDrawRect.Height / 3;
y1 = cropDrawRect.Top + yThird;
y2 = cropDrawRect.Top + yThird * 2;
int xThird = cropDrawRect.Width / 3;
x1 = cropDrawRect.Left + xThird;
x2 = cropDrawRect.Left + xThird * 2;
}
private class CachedResizedBitmap : IDisposable
{
private readonly Bitmap original;
private bool originalIsOwned;
private Bitmap resized;
private Size? currentSize;
public CachedResizedBitmap(Bitmap original, bool takeOwnership)
{
this.original = original;
this.originalIsOwned = takeOwnership;
}
public void Dispose()
{
Reset();
if (originalIsOwned)
{
originalIsOwned = false; // allows safe multiple disposal
original.Dispose();
}
}
public void Reset()
{
Bitmap tmp = resized;
resized = null;
currentSize = null;
if (tmp != null)
tmp.Dispose();
}
public void Resize(Size size)
{
size = new Size(Math.Max(size.Width, 1), Math.Max(size.Height, 1));
Reset();
Bitmap newBitmap = new Bitmap(original, size);
using (Graphics g = Graphics.FromImage(newBitmap))
{
g.DrawImage(original, 0, 0, newBitmap.Width, newBitmap.Height);
}
resized = newBitmap;
currentSize = size;
}
public Size CurrentSize
{
get { return currentSize ?? original.Size; }
}
public Bitmap ResizedBitmap
{
get { return resized ?? original; }
}
}
public abstract class CropStrategy
{
protected const int MIN_WIDTH = 5;
protected const int MIN_HEIGHT = 5;
private bool dragging = false;
protected Rectangle initialBounds;
protected Point initialLoc;
protected AnchorStyles anchor;
protected Rectangle? container;
public virtual void BeginDrag(Rectangle initialBounds, Point initalLoc, AnchorStyles anchor, Rectangle? container)
{
dragging = true;
this.initialBounds = initialBounds;
this.initialLoc = initalLoc;
this.anchor = anchor;
this.container = container;
}
public virtual double? AspectRatio
{
get { return null; }
}
public virtual void EndDrag()
{
dragging = false;
}
public bool IsDragging
{
get { return dragging; }
}
public virtual Rectangle GetNewBounds(Point newLoc)
{
Rectangle newRect = initialBounds;
if (anchor == ANCHOR_ALL) // move
{
newRect = DoMove(newLoc);
}
else // resize
{
newRect = DoResize(newLoc);
}
if (container != null)
newRect.Intersect(container.Value);
return newRect;
}
public abstract Rectangle AdjustRectangle(Rectangle cont, Rectangle rect, int xOffset, int yOffset, int xGrow, int yGrow);
protected static int Round(double dblVal)
{
return (int)Math.Round(dblVal);
}
protected static int Round(float fltVal)
{
return (int)Math.Round(fltVal);
}
protected virtual Rectangle DoMove(Point newLoc)
{
Rectangle newRect = initialBounds;
int deltaX = newLoc.X - initialLoc.X;
int deltaY = newLoc.Y - initialLoc.Y;
newRect.Offset(deltaX, deltaY);
if (container != null)
{
Rectangle cont = container.Value;
if (cont.Left > newRect.Left)
newRect.Offset(cont.Left - newRect.Left, 0);
else if (cont.Right < newRect.Right)
newRect.Offset(cont.Right - newRect.Right, 0);
if (cont.Top > newRect.Top)
newRect.Offset(0, cont.Top - newRect.Top);
else if (cont.Bottom < newRect.Bottom)
newRect.Offset(0, cont.Bottom - newRect.Bottom);
}
return newRect;
}
protected abstract Rectangle DoResize(Point newLoc);
[Flags]
private enum HT
{
None = 0,
Left = 1,
Top = 2,
Right = 4,
Bottom = 8,
AlmostLeft = 16,
AlmostTop = 32,
AlmostRight = 64,
AlmostBottom = 128,
Mask_Horizontal = Left | AlmostLeft | Right | AlmostRight,
Mask_Vertical = Top | AlmostTop | Bottom | AlmostBottom,
}
public virtual AnchorStyles HitTest(Rectangle sizeRect, Point point)
{
sizeRect.Inflate(1, 1);
if (!sizeRect.Contains(point))
return AnchorStyles.None;
HT hitTest = HT.None;
Test(sizeRect.Right - point.X,
HT.Right,
HT.AlmostRight,
ref hitTest);
Test(sizeRect.Bottom - point.Y,
HT.Bottom,
HT.AlmostBottom,
ref hitTest);
Test(point.X - sizeRect.Left,
HT.Left,
HT.AlmostLeft,
ref hitTest);
Test(point.Y - sizeRect.Top,
HT.Top,
HT.AlmostTop,
ref hitTest);
RemoveConflicts(ref hitTest);
switch (hitTest)
{
case HT.Left:
return AnchorStyles.Left;
case HT.Top:
return AnchorStyles.Top;
case HT.Right:
return AnchorStyles.Right;
case HT.Bottom:
return AnchorStyles.Bottom;
case HT.Left | HT.Top:
case HT.Left | HT.AlmostTop:
case HT.Top | HT.AlmostLeft:
return AnchorStyles.Top | AnchorStyles.Left;
case HT.Right | HT.Top:
case HT.Right | HT.AlmostTop:
case HT.Top | HT.AlmostRight:
return AnchorStyles.Top | AnchorStyles.Right;
case HT.Right | HT.Bottom:
case HT.Right | HT.AlmostBottom:
case HT.Bottom | HT.AlmostRight:
return AnchorStyles.Bottom | AnchorStyles.Right;
case HT.Left | HT.Bottom:
case HT.Left | HT.AlmostBottom:
case HT.Bottom | HT.AlmostLeft:
return AnchorStyles.Bottom | AnchorStyles.Left;
default:
return ANCHOR_ALL;
}
}
private static void RemoveConflicts(ref HT hitTest)
{
TestClearAndSet(ref hitTest, HT.Right, HT.Mask_Horizontal);
TestClearAndSet(ref hitTest, HT.Left, HT.Mask_Horizontal);
TestClearAndSet(ref hitTest, HT.AlmostRight, HT.Mask_Horizontal);
TestClearAndSet(ref hitTest, HT.AlmostLeft, HT.Mask_Horizontal);
TestClearAndSet(ref hitTest, HT.Bottom, HT.Mask_Vertical);
TestClearAndSet(ref hitTest, HT.Top, HT.Mask_Vertical);
TestClearAndSet(ref hitTest, HT.AlmostBottom, HT.Mask_Vertical);
TestClearAndSet(ref hitTest, HT.AlmostTop, HT.Mask_Vertical);
}
private static void TestClearAndSet(ref HT val, HT test, HT clearMask)
{
if (test == (test & val))
{
val &= ~clearMask;
val |= test;
}
}
private static void Test(int distance, HT exactResult, HT fuzzyResult, ref HT hitTest)
{
hitTest |=
distance < 0 ? 0 :
distance < 5 ? exactResult :
distance < 10 ? fuzzyResult :
0;
}
}
public class FixedAspectRatioCropStrategy : FreeCropStrategy
{
private double aspectRatio;
public FixedAspectRatioCropStrategy(double aspectRatio)
{
this.aspectRatio = aspectRatio;
}
public override double? AspectRatio
{
get { return aspectRatio; }
}
public override Rectangle AdjustRectangle(Rectangle cont, Rectangle rect, int xOffset, int yOffset, int xGrow, int yGrow)
{
Rectangle result = base.AdjustRectangle(cont, rect, xOffset, yOffset, xGrow, yGrow);
if (xGrow != 0)
{
result.Height = Math.Max(MIN_HEIGHT, Round(result.Width / aspectRatio));
}
else if (yGrow != 0)
{
result.Width = Math.Max(MIN_WIDTH, Round(result.Height * aspectRatio));
}
// too far--revert!
if (result.Bottom > cont.Bottom || result.Right > cont.Right)
result = rect;
return result;
}
public Rectangle ConformCropRectangle(Rectangle containerRect, Rectangle cropRect)
{
// try to preserve the same number of pixels
int numOfPixels = cropRect.Width * cropRect.Height;
PointF center = new PointF(cropRect.Left + cropRect.Width / 2f, cropRect.Top + cropRect.Height / 2f);
double height = Math.Sqrt(numOfPixels / aspectRatio);
double width = aspectRatio * height;
PointF newLoc = new PointF(center.X - (float)width / 2f, center.Y - (float)height / 2f);
return new Rectangle(
Convert.ToInt32(newLoc.X),
Convert.ToInt32(newLoc.Y),
Convert.ToInt32(width),
Convert.ToInt32(height));
}
public override AnchorStyles HitTest(Rectangle sizeRect, Point point)
{
AnchorStyles hitTest = base.HitTest(sizeRect, point);
if (AnchorStyles.None == (hitTest & (AnchorStyles.Left | AnchorStyles.Right)))
{
return AnchorStyles.None;
}
if (AnchorStyles.None == (hitTest & (AnchorStyles.Top | AnchorStyles.Bottom)))
{
return AnchorStyles.None;
}
return hitTest;
}
protected override Rectangle DoResize(Point newLoc)
{
bool up = AnchorStyles.Top == (anchor & AnchorStyles.Top);
bool left = AnchorStyles.Left == (anchor & AnchorStyles.Left);
PointF origin = new PointF(
initialBounds.Left + (left ? initialBounds.Width : 0),
initialBounds.Top + (up ? initialBounds.Height : 0));
double desiredAngle = Math.Atan2(
1d * (up ? -1 : 1),
1d * aspectRatio * (left ? -1 : 1));
double actualAngle = Math.Atan2(
newLoc.Y - origin.Y,
newLoc.X - origin.X);
double angleDiff = Math.Abs(actualAngle - desiredAngle);
if (angleDiff >= Math.PI / 2) // >=90 degrees--too much angle!
return base.DoResize(new Point((int)origin.X, (int)origin.Y));
double distance = Distance(origin, newLoc);
double resizeMagnitude = Math.Cos(angleDiff) * distance;
double xMagnitude = resizeMagnitude * Math.Cos(desiredAngle);
double yMagnitude = resizeMagnitude * Math.Sin(desiredAngle);
newLoc.X = Round(origin.X + xMagnitude);
newLoc.Y = Round(origin.Y + yMagnitude);
Rectangle newRect = base.DoResize(newLoc);
if (container != null)
{
Rectangle newRectConstrained = newRect;
newRectConstrained.Intersect(container.Value);
if (!newRectConstrained.Equals(newRect))
{
int newWidth = Round(Math.Min(newRectConstrained.Width, newRectConstrained.Height * aspectRatio));
int newHeight = Round(Math.Min(newRectConstrained.Height, newRectConstrained.Width / aspectRatio));
newRect.Width = newWidth;
newRect.Height = newHeight;
if (left)
newRect.Location = new Point(initialBounds.Right - newRect.Width, newRect.Top);
if (up)
newRect.Location = new Point(newRect.Left, initialBounds.Bottom - newRect.Height);
}
}
return newRect;
}
private double Distance(PointF pFrom, PointF pTo)
{
double deltaX = Math.Abs((double)(pTo.X - pFrom.X));
double deltaY = Math.Abs((double)(pTo.Y - pFrom.Y));
return Math.Sqrt(
deltaX * deltaX + deltaY * deltaY
);
}
private PointF Rotate(PointF origin, double angleRadians, PointF point)
{
float x, y;
x = point.X - origin.X;
y = point.Y - origin.Y;
point.X = (float)(x * Math.Cos(angleRadians) - y * Math.Sin(angleRadians));
point.Y = (float)(y * Math.Cos(angleRadians) - x * Math.Sin(angleRadians));
point.X += origin.X;
point.Y += origin.Y;
return point;
}
}
public class FreeCropStrategy : CropStrategy
{
protected override Rectangle DoResize(Point newLoc)
{
Rectangle newRect = initialBounds;
int deltaX = newLoc.X - initialLoc.X;
int deltaY = newLoc.Y - initialLoc.Y;
switch (anchor & (AnchorStyles.Left | AnchorStyles.Right))
{
case AnchorStyles.Left:
if (MIN_WIDTH >= initialBounds.Width - deltaX)
deltaX = initialBounds.Width - MIN_WIDTH;
newRect.Width -= deltaX;
newRect.Offset(deltaX, 0);
break;
case AnchorStyles.Right:
if (MIN_WIDTH >= initialBounds.Width + deltaX)
deltaX = -initialBounds.Width + MIN_WIDTH;
newRect.Width += deltaX;
break;
}
switch (anchor & (AnchorStyles.Top | AnchorStyles.Bottom))
{
case AnchorStyles.Top:
if (MIN_HEIGHT >= initialBounds.Height - deltaY)
deltaY = initialBounds.Height - MIN_HEIGHT;
newRect.Height -= deltaY;
newRect.Offset(0, deltaY);
break;
case AnchorStyles.Bottom:
if (MIN_HEIGHT >= initialBounds.Height + deltaY)
deltaY = -initialBounds.Height + MIN_HEIGHT;
newRect.Height += deltaY;
break;
}
return newRect;
}
public override Rectangle AdjustRectangle(Rectangle cont, Rectangle rect, int xOffset, int yOffset, int xGrow, int yGrow)
{
Debug.Assert(MathHelper.Max(xOffset, yOffset, xGrow, yGrow) <= 1,
"AdjustRectangle doesn't work well with values larger than 1--edge cases in FixedAspectRatioCropStrategy");
Debug.Assert(MathHelper.Min(xOffset, yOffset, xGrow, yGrow) >= -1,
"AdjustRectangle doesn't work well with values larger than 1--edge cases in FixedAspectRatioCropStrategy");
Debug.Assert((xOffset == 0 && yOffset == 0) || (xGrow == 0 && yGrow == 0),
"Beware of changing offset and size with the same call--weird things may happen as you approach the edges of the container");
rect.X = Math.Max(cont.X, Math.Min(cont.Right - rect.Width, rect.X + xOffset));
rect.Y = Math.Max(cont.Y, Math.Min(cont.Bottom - rect.Height, rect.Y + yOffset));
rect.Width = Math.Max(MIN_WIDTH, Math.Min(cont.Right - rect.Left, rect.Width + xGrow));
rect.Height = Math.Max(MIN_HEIGHT, Math.Min(cont.Bottom - rect.Top, rect.Height + yGrow));
return rect;
}
}
private class DualRects
{
private Rectangle r;
private Rectangle v;
private readonly PointF offset;
private readonly SizeF scale;
public DualRects(PointF offset, SizeF scale)
{
this.offset = offset;
this.scale = scale;
}
public Rectangle Real
{
get { return r; }
set
{
r = value;
v = VirtualizeRect(r.X, r.Y, r.Width, r.Height);
}
}
public Rectangle Virtual
{
get { return v; }
set
{
v = value;
r = RealizeRect(v.X, v.Y, v.Width, v.Height);
}
}
public Rectangle RealizeRect(int x, int y, int width, int height)
{
return new Rectangle(
(int)Math.Round((x - offset.X) / scale.Width),
(int)Math.Round((y - offset.Y) / scale.Height),
(int)Math.Round(width / scale.Width),
(int)Math.Round(height / scale.Height)
);
}
public Rectangle VirtualizeRect(int x, int y, int width, int height)
{
return new Rectangle(
(int)Math.Round(x * scale.Width + offset.X),
(int)Math.Round(y * scale.Height + offset.Y),
(int)Math.Round(width * scale.Width),
(int)Math.Round(height * scale.Height)
);
}
}
private class BoundsWithHandles
{
public const int HANDLE_SIZE = 5;
private readonly bool includeSideHandles;
private Rectangle bounds;
public BoundsWithHandles(bool includeSideHandles)
{
this.includeSideHandles = includeSideHandles;
}
public Rectangle Bounds
{
get { return bounds; }
set { bounds = value; }
}
public Rectangle[] GetHandles()
{
List<Rectangle> handles = new List<Rectangle>(includeSideHandles ? 8 : 4);
// top left
handles.Add(MakeRect(bounds.Left, bounds.Top));
if (includeSideHandles)
handles.Add(MakeRect((bounds.Left + bounds.Right) / 2, bounds.Top));
handles.Add(MakeRect(bounds.Right, bounds.Top));
if (includeSideHandles)
{
handles.Add(MakeRect(bounds.Left, (bounds.Top + bounds.Bottom) / 2));
handles.Add(MakeRect(bounds.Right, (bounds.Top + bounds.Bottom) / 2));
}
handles.Add(MakeRect(bounds.Left, bounds.Bottom));
if (includeSideHandles)
handles.Add(MakeRect((bounds.Left + bounds.Right) / 2, bounds.Bottom));
handles.Add(MakeRect(bounds.Right, bounds.Bottom));
return handles.ToArray();
}
private static Rectangle MakeRect(int x, int y)
{
return new Rectangle(x - (HANDLE_SIZE / 2), y - (HANDLE_SIZE / 2), HANDLE_SIZE, HANDLE_SIZE);
}
}
}
internal class MathHelper
{
public static int Max(params int[] values)
{
if (values.Length == 0)
throw new ArgumentException("At least one value is required", "values");
int max = values[0];
for (int i = 1; i < values.Length; i++)
max = Math.Max(max, values[i]);
return max;
}
public static int Min(params int[] values)
{
if (values.Length == 0)
throw new ArgumentException("At least one value is required", "values");
int min = values[0];
for (int i = 1; i < values.Length; i++)
min = Math.Min(min, values[i]);
return min;
}
}
}
| |
//------------------------------------------------------------------------------
// Symbooglix
//
//
// Copyright 2014-2017 Daniel Liew
//
// This file is licensed under the MIT license.
// See LICENSE.txt for details.
//------------------------------------------------------------------------------
using NUnit.Framework;
using System;
using Symbooglix;
using Microsoft.Boogie;
namespace ExprBuilderTests
{
[TestFixture()]
public class EqualityAndLogicalOperatorsSimpleBuilder : SimpleExprBuilderTestBase
{
[Test()]
public void EqBool()
{
var builder = GetSimpleBuilder();
var constant0 = builder.True;
var constant1 = builder.False;
var result = builder.Eq(constant0, constant1);
Assert.AreEqual("true == false", result.ToString());
CheckIsBoolType(result);
}
[Test()]
public void EqBv()
{
var builder = GetSimpleBuilder();
var constant0 = builder.ConstantBV(5, 4);
var constant1 = builder.ConstantBV(2, 4);
var result = builder.Eq(constant0, constant1);
Assert.AreEqual("5bv4 == 2bv4", result.ToString());
CheckIsBoolType(result);
}
[Test()]
public void EqInt()
{
var builder = GetSimpleBuilder();
var constant0 = builder.ConstantInt(5);
var constant1 = builder.ConstantInt(2);
var result = builder.Eq(constant0, constant1);
Assert.AreEqual("5 == 2", result.ToString());
CheckIsBoolType(result);
}
[Test()]
public void EqReal()
{
var builder = GetSimpleBuilder();
var constant0 = builder.ConstantReal("5.0");
var constant1 = builder.ConstantReal("2.0");
var result = builder.Eq(constant0, constant1);
Assert.AreEqual("5e0 == 2e0", result.ToString());
CheckIsBoolType(result);
}
[Test(),ExpectedException(typeof(ExprTypeCheckException))]
public void EqTypeMismatch()
{
var builder = GetSimpleBuilder();
var constant0 = builder.ConstantReal("5.0");
var constant1 = builder.True;
builder.Eq(constant0, constant1);
}
[Test()]
public void NotEqBool()
{
var builder = GetSimpleBuilder();
var constant0 = builder.True;
var constant1 = builder.False;
var result = builder.NotEq(constant0, constant1);
Assert.AreEqual("true != false", result.ToString());
CheckIsBoolType(result);
}
[Test()]
public void NotEqBv()
{
var builder = GetSimpleBuilder();
var constant0 = builder.ConstantBV(5, 4);
var constant1 = builder.ConstantBV(2, 4);
var result = builder.NotEq(constant0, constant1);
Assert.AreEqual("5bv4 != 2bv4", result.ToString());
CheckIsBoolType(result);
}
[Test()]
public void NotEqInt()
{
var builder = GetSimpleBuilder();
var constant0 = builder.ConstantInt(5);
var constant1 = builder.ConstantInt(2);
var result = builder.NotEq(constant0, constant1);
Assert.AreEqual("5 != 2", result.ToString());
CheckIsBoolType(result);
}
[Test()]
public void NotEqReal()
{
var builder = GetSimpleBuilder();
var constant0 = builder.ConstantReal("5.0");
var constant1 = builder.ConstantReal("2.0");
var result = builder.NotEq(constant0, constant1);
Assert.AreEqual("5e0 != 2e0", result.ToString());
CheckIsBoolType(result);
}
[Test(),ExpectedException(typeof(ExprTypeCheckException))]
public void NotEqTypeMismatch()
{
var builder = GetSimpleBuilder();
var constant0 = builder.ConstantReal("5.0");
var constant1 = builder.True;
builder.NotEq(constant0, constant1);
}
[Test()]
public void IfThenElseSimple()
{
var builder = GetSimpleBuilder();
var condition = builder.False;
var constant0 = builder.ConstantInt(5);
var constant1 = builder.ConstantInt(2);
var result = builder.IfThenElse(condition, constant0, constant1);
Assert.AreEqual("(if false then 5 else 2)", result.ToString());
Assert.IsNotNull(result.Type);
Assert.IsTrue(result.Type.IsInt);
Assert.IsTrue(result.ShallowType.IsInt);
var TC = new TypecheckingContext(this);
result.Typecheck(TC);
}
[Test(), ExpectedException(typeof(ExprTypeCheckException))]
public void IfThenElseTypeMistmatchCondition()
{
var builder = GetSimpleBuilder();
var condition = builder.ConstantInt(0);
var constant0 = builder.ConstantInt(5);
var constant1 = builder.ConstantInt(2);
builder.IfThenElse(condition, constant0, constant1);
}
[Test(), ExpectedException(typeof(ExprTypeCheckException))]
public void IfThenElseTypeMistmatchThenElse()
{
var builder = GetSimpleBuilder();
var condition = builder.False;
var constant0 = builder.ConstantInt(5);
var constant1 = builder.ConstantBV(5, 4);
builder.IfThenElse(condition, constant0, constant1);
}
[Test()]
public void Not()
{
var builder = GetSimpleBuilder();
var condition = builder.False;
var result = builder.Not(condition);
Assert.AreEqual("!false", result.ToString());
CheckIsBoolType(result);
}
[Test(),ExpectedException(typeof(ExprTypeCheckException))]
public void NotWrongType()
{
var builder = GetSimpleBuilder();
var condition = builder.ConstantBV(2, 5);
builder.Not(condition);
}
[Test()]
public void And()
{
var builder = GetSimpleBuilder();
var constant0 = builder.True;
var constant1 = builder.False;
var result = builder.And(constant0, constant1);
Assert.AreEqual("true && false", result.ToString());
CheckIsBoolType(result);
}
[Test(), ExpectedException(typeof(ExprTypeCheckException))]
public void AndWrongLhsType()
{
var builder = GetSimpleBuilder();
var constant0 = builder.True;
var constant1 = builder.ConstantInt(8);
builder.And(constant0, constant1);
}
[Test(), ExpectedException(typeof(ExprTypeCheckException))]
public void AndWrongRhsType()
{
var builder = GetSimpleBuilder();
var constant1 = builder.True;
var constant0 = builder.ConstantInt(8);
builder.And(constant0, constant1);
}
[Test()]
public void Or()
{
var builder = GetSimpleBuilder();
var constant0 = builder.True;
var constant1 = builder.False;
var result = builder.Or(constant0, constant1);
Assert.AreEqual("true || false", result.ToString());
CheckIsBoolType(result);
}
[Test(), ExpectedException(typeof(ExprTypeCheckException))]
public void OrWrongLhsType()
{
var builder = GetSimpleBuilder();
var constant0 = builder.True;
var constant1 = builder.ConstantInt(8);
builder.Or(constant0, constant1);
}
[Test(), ExpectedException(typeof(ExprTypeCheckException))]
public void OrWrongRhsType()
{
var builder = GetSimpleBuilder();
var constant1 = builder.True;
var constant0 = builder.ConstantInt(8);
builder.Or(constant0, constant1);
}
[Test()]
public void Iff()
{
var builder = GetSimpleBuilder();
var constant0 = builder.True;
var constant1 = builder.False;
var result = builder.Iff(constant0, constant1);
Assert.AreEqual("true <==> false", result.ToString());
CheckIsBoolType(result);
}
[Test(), ExpectedException(typeof(ExprTypeCheckException))]
public void IffWrongLhsType()
{
var builder = GetSimpleBuilder();
var constant0 = builder.True;
var constant1 = builder.ConstantInt(8);
builder.Iff(constant0, constant1);
}
[Test(), ExpectedException(typeof(ExprTypeCheckException))]
public void IffWrongRhsType()
{
var builder = GetSimpleBuilder();
var constant1 = builder.True;
var constant0 = builder.ConstantInt(8);
builder.Iff(constant0, constant1);
}
[Test()]
public void Imp()
{
var builder = GetSimpleBuilder();
var constant0 = builder.True;
var constant1 = builder.False;
var result = builder.Imp(constant0, constant1);
Assert.AreEqual("true ==> false", result.ToString());
CheckIsBoolType(result);
}
[Test(), ExpectedException(typeof(ExprTypeCheckException))]
public void ImpWrongLhsType()
{
var builder = GetSimpleBuilder();
var constant0 = builder.True;
var constant1 = builder.ConstantInt(8);
builder.Imp(constant0, constant1);
}
[Test(), ExpectedException(typeof(ExprTypeCheckException))]
public void ImpWrongRhsType()
{
var builder = GetSimpleBuilder();
var constant1 = builder.True;
var constant0 = builder.ConstantInt(8);
builder.Imp(constant0, constant1);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Collections;
using System.Text;
using gov.va.medora.utils;
using gov.va.medora.mdo.exceptions;
using gov.va.medora.mdo.src.mdo;
namespace gov.va.medora.mdo.dao.vista
{
public class DdrLister : DdrQuery
{
string file = "";
string iens = "";
string _requestedFieldString;
string[] _requestedFields; // Holds user's requested order
//Hashtable requestedFieldsTbl; // Needed to fetch by FileMan field #, and to hold if External or not
Dictionary<String, String> _requestedFieldsTbl;
//ArrayList ienLst; // Needed to hold record IENs across methods.
IList<String> _ienLst;
string flags = "";
string max = "";
string from = "";
string part = "";
string xref = "";
string screen = "";
string id = "";
string options = "";
string moreFrom = "";
string moreIens = "";
public bool more = false;
public DdrLister(AbstractConnection cxn) : base(cxn) { }
internal MdoQuery buildRequest()
{
if (File == "")
{
throw new ArgumentNullException("Must have a file!");
}
VistaQuery vq = new VistaQuery("DDR LISTER");
DictionaryHashList paramLst = new DictionaryHashList();
paramLst.Add("\"FILE\"", File);
if (Iens != "")
{
paramLst.Add("\"IENS\"", Iens);
}
if (_requestedFields.Length > 0)
{
paramLst.Add("\"FIELDS\"", getFieldsArg());
}
if (Flags != "")
{
paramLst.Add("\"FLAGS\"", Flags);
}
if (Max != "")
{
paramLst.Add("\"MAX\"", Max);
}
if (From != "")
{
paramLst.Add("\"FROM\"", From);
}
if (Part != "")
{
paramLst.Add("\"PART\"", Part);
}
if (Xref != "")
{
paramLst.Add("\"XREF\"", Xref);
}
if (Screen != "")
{
paramLst.Add("\"SCREEN\"", Screen);
}
if (Id != "")
{
paramLst.Add("\"ID\"", Id);
}
if (Options != "")
{
paramLst.Add("\"OPTIONS\"", Options);
}
if (moreFrom != "")
{
paramLst.Add("\"FROM\"", moreFrom);
}
if (moreIens != "")
{
paramLst.Add("\"IENS\"", moreIens);
}
vq.addParameter(vq.LIST, paramLst);
return vq;
}
public string[] execute()
{
MdoQuery request = buildRequest();
string response = this.execute(request);
return buildResult(response.Replace('|', '^'));
}
//public VistaRpcQuery executePlus()
//{
// MdoQuery request = buildRequest();
// VistaRpcQuery result = this.executePlus(request);
// result.ParsedResult = buildResult(result.ResponseString.Replace('|', '^'));
// return result;
//}
private String getFieldsArg()
{
StringBuilder result = new StringBuilder();
result.Append("@");
for (int i = 0; i < _requestedFields.Length; i++)
{
if (String.Equals(_requestedFields[i], "@"))
{
continue;
}
result.Append(';');
result.Append(_requestedFields[i]);
}
return result.ToString();
}
private void setMoreParams(string line)
{
string[] flds = StringUtils.split(line, StringUtils.CARET);
if (flds[0] != "MORE")
{
throw new UnexpectedDataException("Invalid return data: expected 'MORE', got " + flds[0]);
}
moreFrom = flds[1];
moreIens = flds[2];
more = true;
}
public string[] buildResult(string rtn)
{
if (String.IsNullOrEmpty(rtn))
{
return null;
}
if (this.flags.IndexOf("P") < 0) // DdrListerUtils now takes care of unpacked results so let's check if query had P flag before we split the lines unnecessarily
{
return DdrListerUtils.parseUnpackedResult(rtn, this.Fields, this.Id);
}
String[] lines = StringUtils.split(rtn, StringUtils.CRLF);
lines = StringUtils.trimArray(lines);
int i = 0;
if (lines[i] == VistaConstants.MISC)
{
if (!lines[++i].StartsWith("MORE"))
{
throw new UnexpectedDataException("Error packing LISTER return; expected 'MORE...', got " + lines[i]);
}
setMoreParams(lines[i]);
}
return parsePackedResult(lines);
//if (this.flags.IndexOf("P") != -1)
//{
// return parsePackedResult(lines);
//}
//else
//{
// return DdrListerUtils.parseUnpackedResult(rtn, this.Fields, this.Id);
// //return packResult(lines);
//}
}
private string[] parsePackedResult(string[] lines)
{
int idx = StringUtils.getIdx(lines, VistaConstants.BEGIN_ERRS, 0);
if (idx != -1)
{
throw new ConnectionException(getErrMsg(lines, idx));
}
idx = StringUtils.getIdx(lines, VistaConstants.BEGIN_DATA, 0);
if (idx == -1)
{
throw new UnexpectedDataException("Error parsing packed result: expected " + VistaConstants.BEGIN_DATA + ", found none.");
}
ArrayList lst = new ArrayList();
idx++;
while (idx < lines.Length && lines[idx] != VistaConstants.END_DATA)
{
lst.Add(lines[idx++]);
}
return (string[])lst.ToArray(typeof(string));
}
internal string[] packResult(string[] lines)
{
int idx = 0;
if (lines[idx] == VistaConstants.UNPACKED_NO_RESULTS)
{
return new string[] { };
}
Dictionary<String, Dictionary<String, DdrField>> rs = new Dictionary<string, Dictionary<string, DdrField>>();
Dictionary<String, String> identifierVals = new Dictionary<String, String>();
if ((idx = StringUtils.getIdx(lines, VistaConstants.BEGIN_ERRS, 0)) != -1)
{
throw new ConnectionException(getErrMsg(lines, idx));
}
if ((idx = StringUtils.getIdx(lines, VistaConstants.BEGIN_DATA, 0)) != -1)
{
_ienLst = new List<String>(); // new ArrayList();
if (lines[++idx] != VistaConstants.BEGIN_IENS)
{
throw new UnexpectedDataException("Incorrectly formatted return data");
}
idx++;
while (lines[idx] != VistaConstants.END_IENS)
{
_ienLst.Add(lines[idx++]);
}
idx++;
if (lines[idx] != VistaConstants.BEGIN_IDVALS)
{
throw new UnexpectedDataException("Incorrectly formatted return data");
}
//String[] flds = StringUtils.split(lines[++idx], StringUtils.SEMICOLON); -- this line was wrong! see check for [MAP] index above to obtain field names
IList<String> adjustedFields = new List<String>();
foreach (String s in _requestedFields)
{
if (!String.Equals("WID", s))
{
adjustedFields.Add(s);
}
}
int recIdx = 0;
idx++;
while (lines[idx] != VistaConstants.END_IDVALS)
{
// the last field in flds is the field count, not a field <--- I don't think this is a valid comment...
Dictionary<String, DdrField> rec = new Dictionary<string, DdrField>();
//Hashtable rec = new Hashtable();
for (int fldIdx = 0; fldIdx < adjustedFields.Count; fldIdx++) // <--- changing this due to thinking the comment above is invalid
{
DdrField f = new DdrField();
f.FmNumber = _requestedFields[fldIdx];
String requestedOptions = (String)_requestedFieldsTbl[f.FmNumber];
f.HasExternal = requestedOptions.IndexOf('E') != -1;
if (f.HasExternal)
{
f.ExternalValue = lines[idx++];
}
if (requestedOptions.IndexOf('I') != -1)
{
f.Value = lines[idx++];
}
rec.Add(f.FmNumber, f);
}
rs.Add((String)_ienLst[recIdx++], rec);
}
// any identifier params? if so, turn them in to a Dictionary<String, String> where key is IEN and all lines are separated by tilde just like packed results
if (lines.Length > (idx + 1) && String.Equals(lines[++idx], VistaConstants.BEGIN_WIDVALS))
{
idx++;
while (!String.Equals(lines[idx], VistaConstants.END_WIDVALS))
{
String[] pieces = StringUtils.split(lines[idx], StringUtils.CARET);
StringBuilder sb = new StringBuilder();
while (!lines[++idx].StartsWith("WID") && !String.Equals(lines[idx], VistaConstants.END_WIDVALS))
{
sb.Append(lines[idx]);
sb.Append(StringUtils.TILDE);
}
sb.Remove(sb.Length - 1, 1);
identifierVals.Add(pieces[1], sb.ToString());
}
}
// at this point line should be VistaConstants.END_DATA
// unless more functionality is added.
}
return toStringArray(rs, identifierVals);
}
private string getErrMsg(string[] lines, int idx)
{
string msg = lines[idx + 3];
int endIdx = StringUtils.getIdx(lines, VistaConstants.END_ERRS, 0);
for (int i = idx + 4; i < endIdx; i++)
{
if (msg[msg.Length - 1] != '.')
{
msg += ". ";
}
msg += lines[i];
}
return msg;
}
internal String[] toStringArray(Dictionary<String, Dictionary<String, DdrField>> records, Dictionary<String, String> identifierVals)
{
//ArrayList lst = new ArrayList();
IList<String> results = new List<String>();
for (int recnum = 0; recnum < _ienLst.Count; recnum++)
{
StringBuilder sb = new StringBuilder();
sb.Append(_ienLst[recnum]);
Dictionary<String, DdrField> flds = records[_ienLst[recnum]];
//Hashtable hashedFlds = (Hashtable)records[_ienLst[recnum]];
for (int fldnum = 0; fldnum < _requestedFields.Length; fldnum++)
{
if (String.Equals(_requestedFields[fldnum], "WID"))
{
continue;
}
String fmNum = _requestedFields[fldnum];
bool external = false;
if (fmNum.IndexOf('E') != -1)
{
fmNum = fmNum.Substring(0, fmNum.Length - 1);
external = true;
}
DdrField fld = (DdrField)flds[fmNum];
if (external)
{
sb.Append('^');
sb.Append(fld.ExternalValue);
}
else
{
sb.Append('^');
sb.Append(fld.Value);
}
}
if (identifierVals != null && identifierVals.Count > 0 && identifierVals.ContainsKey(_ienLst[recnum]))
{
sb.Append("^"); // packed results have this string before start of ID values
sb.Append(identifierVals[_ienLst[recnum]]);
}
results.Add(sb.ToString());
}
String[] final = new String[results.Count];
results.CopyTo(final, 0);
return final;
}
public String File
{
get { return file; }
set { file = value; }
}
public String Iens
{
get { return iens; }
set { iens = value; }
}
public String Fields
{
get { return _requestedFieldString; }
set
{
_requestedFieldString = value;
String s = value;
_requestedFields = StringUtils.split(s, StringUtils.SEMICOLON);
_requestedFieldsTbl = new Dictionary<string, string>(); // new Hashtable(_requestedFields.Length);
for (int i = 0; i < _requestedFields.Length; i++)
{
if (String.IsNullOrEmpty(_requestedFields[i]))
{
continue;
}
String fldnum = _requestedFields[i];
String option = "I";
if (fldnum.IndexOf('E') != -1)
{
fldnum = fldnum.Substring(0, fldnum.Length - 1);
option = "E";
}
if (!_requestedFieldsTbl.ContainsKey(fldnum))
{
_requestedFieldsTbl.Add(fldnum, option);
}
else
{
_requestedFieldsTbl[fldnum] += option;
}
}
}
}
public String Flags
{
get { return flags; }
set { flags = value; }
}
public string Max
{
get { return max; }
set { max = value; }
}
public String From
{
get { return from; }
set { from = value; }
}
public String Part
{
get { return part; }
set { part = value; }
}
public String Xref
{
get { return xref; }
set { xref = value; }
}
public String Screen
{
get { return screen; }
set { screen = value; }
}
public String Id
{
get { return id; }
set { id = value; }
}
public String Options
{
get { return options; }
set { options = value; }
}
public string MoreFrom
{
get { return moreFrom; }
set { moreFrom = value; }
}
public string MoreIens
{
get { return moreIens; }
set { moreIens = value; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Text;
using System.Collections;
using System.Globalization;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace System.DirectoryServices.ActiveDirectory
{
public enum DomainMode : int
{
Unknown = -1,
Windows2000MixedDomain = 0, // win2000, win2003, NT
Windows2000NativeDomain = 1, // win2000, win2003
Windows2003InterimDomain = 2, // win2003, NT
Windows2003Domain = 3, // win2003
Windows2008Domain = 4, // win2008
Windows2008R2Domain = 5, // win2008 R2
Windows8Domain = 6, //Windows Server 2012
Windows2012R2Domain = 7, //Windows Server 2012 R2
}
public class Domain : ActiveDirectoryPartition
{
/// Private Variables
private string _crossRefDN = null;
private string _trustParent = null;
// internal variables corresponding to public properties
private DomainControllerCollection _cachedDomainControllers = null;
private DomainCollection _cachedChildren = null;
private DomainMode _currentDomainMode = (DomainMode)(-1);
private int _domainModeLevel = -1;
private DomainController _cachedPdcRoleOwner = null;
private DomainController _cachedRidRoleOwner = null;
private DomainController _cachedInfrastructureRoleOwner = null;
private Domain _cachedParent = null;
private Forest _cachedForest = null;
// this is needed because null value for parent is valid
private bool _isParentInitialized = false;
#region constructors
// internal constructors
internal Domain(DirectoryContext context, string domainName, DirectoryEntryManager directoryEntryMgr)
: base(context, domainName)
{
this.directoryEntryMgr = directoryEntryMgr;
}
internal Domain(DirectoryContext context, string domainName)
: this(context, domainName, new DirectoryEntryManager(context))
{
}
#endregion constructors
#region public methods
public static Domain GetDomain(DirectoryContext context)
{
// check that the argument is not null
if (context == null)
throw new ArgumentNullException(nameof(context));
// contexttype should be Domain or DirectoryServer
if ((context.ContextType != DirectoryContextType.Domain) &&
(context.ContextType != DirectoryContextType.DirectoryServer))
{
throw new ArgumentException(SR.TargetShouldBeServerORDomain, nameof(context));
}
if ((context.Name == null) && (!context.isDomain()))
{
throw new ActiveDirectoryObjectNotFoundException(SR.ContextNotAssociatedWithDomain, typeof(Domain), null);
}
if (context.Name != null)
{
// the target should be a valid domain name or a server
if (!((context.isDomain()) || (context.isServer())))
{
if (context.ContextType == DirectoryContextType.Domain)
{
throw new ActiveDirectoryObjectNotFoundException(SR.DomainNotFound, typeof(Domain), context.Name);
}
else
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DCNotFound, context.Name), typeof(Domain), null);
}
}
}
// work with copy of the context
context = new DirectoryContext(context);
// bind to the rootDSE of the domain specified in the context
// and get the dns name
DirectoryEntryManager directoryEntryMgr = new DirectoryEntryManager(context);
DirectoryEntry rootDSE = null;
string defaultDomainNC = null;
try
{
rootDSE = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE);
if ((context.isServer()) && (!Utils.CheckCapability(rootDSE, Capability.ActiveDirectory)))
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DCNotFound, context.Name), typeof(Domain), null);
}
defaultDomainNC = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.DefaultNamingContext);
}
catch (COMException e)
{
int errorCode = e.ErrorCode;
if (errorCode == unchecked((int)0x8007203a))
{
if (context.ContextType == DirectoryContextType.Domain)
{
throw new ActiveDirectoryObjectNotFoundException(SR.DomainNotFound, typeof(Domain), context.Name);
}
else
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DCNotFound, context.Name), typeof(Domain), null);
}
}
else
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
// return domain object
return new Domain(context, Utils.GetDnsNameFromDN(defaultDomainNC), directoryEntryMgr);
}
public static Domain GetComputerDomain()
{
string computerDomainName = DirectoryContext.GetDnsDomainName(null);
if (computerDomainName == null)
{
throw new ActiveDirectoryObjectNotFoundException(SR.ComputerNotJoinedToDomain, typeof(Domain), null);
}
return Domain.GetDomain(new DirectoryContext(DirectoryContextType.Domain, computerDomainName));
}
public void RaiseDomainFunctionalityLevel(int domainMode)
{
int existingDomainModeLevel;
CheckIfDisposed();
// check if domainMode is within the valid range
if (domainMode < 0)
{
throw new ArgumentException(SR.InvalidMode, nameof(domainMode));
}
// get the current domain mode
existingDomainModeLevel = DomainModeLevel;
if (existingDomainModeLevel >= domainMode)
{
throw new ArgumentException(SR.InvalidMode, nameof(domainMode));
}
DomainMode existingDomainMode = DomainMode;
// set the forest mode on AD
DirectoryEntry domainEntry = null;
// CurrentDomain Valid domainMode Action
// -----------------
// Windows2000Mixed 0 ntMixedDomain = 0 msDS-Behavior-Version = 0
// Windows2000Mixed 1 msDS-Behavior-Version = 1
// Windows2000Mixed 2 ntMixedDomain = 0, msDS-Behavior-Version = 2
//
// Windows2003Interim 2 ntMixedDomain = 0, msDS-Behavior-Version = 2
//
// Rest 2 or above msDS-Behavior-Version = domainMode
try
{
domainEntry = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.DefaultNamingContext));
// set the new functional level
domainEntry.Properties[PropertyManager.MsDSBehaviorVersion].Value = domainMode;
switch (existingDomainMode)
{
case DomainMode.Windows2000MixedDomain:
{
if (domainMode == 2 || domainMode == 0)
{
domainEntry.Properties[PropertyManager.NTMixedDomain].Value = 0;
}
else if (domainMode > 2) // new level should be less than or equal to Windows2003
{
throw new ArgumentException(SR.InvalidMode, nameof(domainMode));
}
break;
}
case DomainMode.Windows2003InterimDomain:
{
if (domainMode == 2) // only Windows2003 allowed
{
domainEntry.Properties[PropertyManager.NTMixedDomain].Value = 0;
}
else
{
throw new ArgumentException(SR.InvalidMode, nameof(domainMode));
}
break;
}
default:
break;
}
// NOTE:
// If the domain controller we are talking to is W2K
// (more specifically the schema is a W2K schema) then the
// msDS-Behavior-Version attribute will not be present.
// If that is the case, the domain functionality cannot be raised
// to Windows2003InterimDomain or Windows2003Domain (which is when we would set this attribute)
// since there are only W2K domain controllers
// So, we catch that exception and throw a more meaningful one.
domainEntry.CommitChanges();
}
catch (System.Runtime.InteropServices.COMException e)
{
if (e.ErrorCode == unchecked((int)0x8007200A))
{
// attribute does not exist which means this is not a W2K3 DC
// cannot raise domain functionality
throw new ArgumentException(SR.NoW2K3DCs, nameof(domainMode));
}
else
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
finally
{
if (domainEntry != null)
{
domainEntry.Dispose();
}
}
// at this point the raise domain function has succeeded
// invalidate the domain mode so that we get it from the server the next time
_currentDomainMode = (DomainMode)(-1);
_domainModeLevel = -1;
}
public void RaiseDomainFunctionality(DomainMode domainMode)
{
DomainMode existingDomainMode;
CheckIfDisposed();
// check if domain mode is within the valid range
if (domainMode < DomainMode.Windows2000MixedDomain || domainMode > DomainMode.Windows2012R2Domain)
{
throw new InvalidEnumArgumentException(nameof(domainMode), (int)domainMode, typeof(DomainMode));
}
// get the current domain mode
existingDomainMode = GetDomainMode();
// set the forest mode on AD
DirectoryEntry domainEntry = null;
// CurrentDomain Valid RequestedDomain Action
// -----------------
// Windows2000Mixed Windows2000Native ntMixedDomain = 0
// Windows2000Mixed Windows2003Interim msDS-Behavior-Version = 1
// Windows2000Mixed Windows2003 ntMixedDomain = 0, msDS-Behavior-Version = 2
//
// Windows2003Interim Windows2003 ntMixedDomain = 0, msDS-Behavior-Version = 2
//
// Windows2000Native Windows2003 or above
// Windows2003 Windows2008 or above
// Windows2008 Windows2008R2 or above
// Windows2008R2 Windows2012 or above
// Windows2012 Windows2012R2 or above
// Windows2012R2 ERROR
try
{
domainEntry = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.DefaultNamingContext));
switch (existingDomainMode)
{
case DomainMode.Windows2000MixedDomain:
{
if (domainMode == DomainMode.Windows2000NativeDomain)
{
domainEntry.Properties[PropertyManager.NTMixedDomain].Value = 0;
}
else if (domainMode == DomainMode.Windows2003InterimDomain)
{
domainEntry.Properties[PropertyManager.MsDSBehaviorVersion].Value = 1;
}
else if (domainMode == DomainMode.Windows2003Domain)
{
domainEntry.Properties[PropertyManager.NTMixedDomain].Value = 0;
domainEntry.Properties[PropertyManager.MsDSBehaviorVersion].Value = 2;
}
else
{
throw new ArgumentException(SR.InvalidMode, nameof(domainMode));
}
break;
}
case DomainMode.Windows2003InterimDomain:
{
if (domainMode == DomainMode.Windows2003Domain)
{
domainEntry.Properties[PropertyManager.NTMixedDomain].Value = 0;
domainEntry.Properties[PropertyManager.MsDSBehaviorVersion].Value = 2;
}
else
{
throw new ArgumentException(SR.InvalidMode, nameof(domainMode));
}
break;
}
case DomainMode.Windows2000NativeDomain:
case DomainMode.Windows2003Domain:
case DomainMode.Windows2008Domain:
case DomainMode.Windows2008R2Domain:
case DomainMode.Windows8Domain:
case DomainMode.Windows2012R2Domain:
{
if (existingDomainMode >= domainMode)
{
throw new ArgumentException(SR.InvalidMode, nameof(domainMode));
}
if (domainMode == DomainMode.Windows2003Domain)
{
domainEntry.Properties[PropertyManager.MsDSBehaviorVersion].Value = 2;
}
else if (domainMode == DomainMode.Windows2008Domain)
{
domainEntry.Properties[PropertyManager.MsDSBehaviorVersion].Value = 3;
}
else if (domainMode == DomainMode.Windows2008R2Domain)
{
domainEntry.Properties[PropertyManager.MsDSBehaviorVersion].Value = 4;
}
else if (domainMode == DomainMode.Windows8Domain)
{
domainEntry.Properties[PropertyManager.MsDSBehaviorVersion].Value = 5;
}
else if (domainMode == DomainMode.Windows2012R2Domain)
{
domainEntry.Properties[PropertyManager.MsDSBehaviorVersion].Value = 6;
}
else
{
throw new ArgumentException(SR.InvalidMode, nameof(domainMode));
}
}
break;
default:
{
// should not happen
throw new ActiveDirectoryOperationException();
}
}
// NOTE:
// If the domain controller we are talking to is W2K
// (more specifically the schema is a W2K schema) then the
// msDS-Behavior-Version attribute will not be present.
// If that is the case, the domain functionality cannot be raised
// to Windows2003InterimDomain or Windows2003Domain (which is when we would set this attribute)
// since there are only W2K domain controllers
// So, we catch that exception and throw a more meaningful one.
domainEntry.CommitChanges();
}
catch (System.Runtime.InteropServices.COMException e)
{
if (e.ErrorCode == unchecked((int)0x8007200A))
{
// attribute does not exist which means this is not a W2K3 DC
// cannot raise domain functionality
throw new ArgumentException(SR.NoW2K3DCs, nameof(domainMode));
}
else
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
finally
{
if (domainEntry != null)
{
domainEntry.Dispose();
}
}
// at this point the raise domain function has succeeded
// invalidate the domain mode so that we get it from the server the next time
_currentDomainMode = (DomainMode)(-1);
_domainModeLevel = -1;
}
public DomainController FindDomainController()
{
CheckIfDisposed();
return DomainController.FindOneInternal(context, Name, null, 0);
}
public DomainController FindDomainController(string siteName)
{
CheckIfDisposed();
if (siteName == null)
{
throw new ArgumentNullException(nameof(siteName));
}
return DomainController.FindOneInternal(context, Name, siteName, 0);
}
public DomainController FindDomainController(LocatorOptions flag)
{
CheckIfDisposed();
return DomainController.FindOneInternal(context, Name, null, flag);
}
public DomainController FindDomainController(string siteName, LocatorOptions flag)
{
CheckIfDisposed();
if (siteName == null)
{
throw new ArgumentNullException(nameof(siteName));
}
return DomainController.FindOneInternal(context, Name, siteName, flag);
}
public DomainControllerCollection FindAllDomainControllers()
{
CheckIfDisposed();
return DomainController.FindAllInternal(context, Name, true /*isDnsDomainName */, null);
}
public DomainControllerCollection FindAllDomainControllers(string siteName)
{
CheckIfDisposed();
if (siteName == null)
{
throw new ArgumentNullException(nameof(siteName));
}
return DomainController.FindAllInternal(context, Name, true /*isDnsDomainName */, siteName);
}
public DomainControllerCollection FindAllDiscoverableDomainControllers()
{
long flag = (long)PrivateLocatorFlags.DSWriteableRequired;
CheckIfDisposed();
return new DomainControllerCollection(Locator.EnumerateDomainControllers(context, Name, null, (long)flag));
}
public DomainControllerCollection FindAllDiscoverableDomainControllers(string siteName)
{
long flag = (long)PrivateLocatorFlags.DSWriteableRequired;
CheckIfDisposed();
if (siteName == null)
{
throw new ArgumentNullException(nameof(siteName));
}
if (siteName.Length == 0)
{
throw new ArgumentException(SR.EmptyStringParameter, nameof(siteName));
}
return new DomainControllerCollection(Locator.EnumerateDomainControllers(context, Name, siteName, (long)flag));
}
public override DirectoryEntry GetDirectoryEntry()
{
CheckIfDisposed();
return DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.DefaultNamingContext));
}
public TrustRelationshipInformationCollection GetAllTrustRelationships()
{
CheckIfDisposed();
ArrayList trusts = GetTrustsHelper(null);
TrustRelationshipInformationCollection collection = new TrustRelationshipInformationCollection(context, Name, trusts);
return collection;
}
public TrustRelationshipInformation GetTrustRelationship(string targetDomainName)
{
CheckIfDisposed();
if (targetDomainName == null)
throw new ArgumentNullException(nameof(targetDomainName));
if (targetDomainName.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(targetDomainName));
ArrayList trusts = GetTrustsHelper(targetDomainName);
TrustRelationshipInformationCollection collection = new TrustRelationshipInformationCollection(context, Name, trusts);
if (collection.Count == 0)
{
// trust relationship does not exist
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DomainTrustDoesNotExist, Name, targetDomainName), typeof(TrustRelationshipInformation), null);
}
else
{
Debug.Assert(collection.Count == 1);
return collection[0];
}
}
public bool GetSelectiveAuthenticationStatus(string targetDomainName)
{
CheckIfDisposed();
if (targetDomainName == null)
throw new ArgumentNullException(nameof(targetDomainName));
if (targetDomainName.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(targetDomainName));
return TrustHelper.GetTrustedDomainInfoStatus(context, Name, targetDomainName, TRUST_ATTRIBUTE.TRUST_ATTRIBUTE_CROSS_ORGANIZATION, false);
}
public void SetSelectiveAuthenticationStatus(string targetDomainName, bool enable)
{
CheckIfDisposed();
if (targetDomainName == null)
throw new ArgumentNullException(nameof(targetDomainName));
if (targetDomainName.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(targetDomainName));
TrustHelper.SetTrustedDomainInfoStatus(context, Name, targetDomainName, TRUST_ATTRIBUTE.TRUST_ATTRIBUTE_CROSS_ORGANIZATION, enable, false);
}
public bool GetSidFilteringStatus(string targetDomainName)
{
CheckIfDisposed();
if (targetDomainName == null)
throw new ArgumentNullException(nameof(targetDomainName));
if (targetDomainName.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(targetDomainName));
return TrustHelper.GetTrustedDomainInfoStatus(context, Name, targetDomainName, TRUST_ATTRIBUTE.TRUST_ATTRIBUTE_QUARANTINED_DOMAIN, false);
}
public void SetSidFilteringStatus(string targetDomainName, bool enable)
{
CheckIfDisposed();
if (targetDomainName == null)
throw new ArgumentNullException(nameof(targetDomainName));
if (targetDomainName.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(targetDomainName));
TrustHelper.SetTrustedDomainInfoStatus(context, Name, targetDomainName, TRUST_ATTRIBUTE.TRUST_ATTRIBUTE_QUARANTINED_DOMAIN, enable, false);
}
public void DeleteLocalSideOfTrustRelationship(string targetDomainName)
{
CheckIfDisposed();
if (targetDomainName == null)
throw new ArgumentNullException(nameof(targetDomainName));
if (targetDomainName.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(targetDomainName));
// delete local side of trust only
TrustHelper.DeleteTrust(context, Name, targetDomainName, false);
}
public void DeleteTrustRelationship(Domain targetDomain)
{
CheckIfDisposed();
if (targetDomain == null)
throw new ArgumentNullException(nameof(targetDomain));
// first delete the trust on the remote side
TrustHelper.DeleteTrust(targetDomain.GetDirectoryContext(), targetDomain.Name, Name, false);
// then delete the local side trust
TrustHelper.DeleteTrust(context, Name, targetDomain.Name, false);
}
public void VerifyOutboundTrustRelationship(string targetDomainName)
{
CheckIfDisposed();
if (targetDomainName == null)
throw new ArgumentNullException(nameof(targetDomainName));
if (targetDomainName.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(targetDomainName));
TrustHelper.VerifyTrust(context, Name, targetDomainName, false/*not forest*/, TrustDirection.Outbound, false/*just TC verification*/, null /* no need to go to specific server*/);
}
public void VerifyTrustRelationship(Domain targetDomain, TrustDirection direction)
{
CheckIfDisposed();
if (targetDomain == null)
throw new ArgumentNullException(nameof(targetDomain));
if (direction < TrustDirection.Inbound || direction > TrustDirection.Bidirectional)
throw new InvalidEnumArgumentException(nameof(direction), (int)direction, typeof(TrustDirection));
// verify outbound trust first
if ((direction & TrustDirection.Outbound) != 0)
{
try
{
TrustHelper.VerifyTrust(context, Name, targetDomain.Name, false/*not forest*/, TrustDirection.Outbound, false/*just TC verification*/, null /* no need to go to specific server*/);
}
catch (ActiveDirectoryObjectNotFoundException)
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.WrongTrustDirection, Name, targetDomain.Name, direction), typeof(TrustRelationshipInformation), null);
}
}
// verify inbound trust
if ((direction & TrustDirection.Inbound) != 0)
{
try
{
TrustHelper.VerifyTrust(targetDomain.GetDirectoryContext(), targetDomain.Name, Name, false/*not forest*/, TrustDirection.Outbound, false/*just TC verification*/, null /* no need to go to specific server*/);
}
catch (ActiveDirectoryObjectNotFoundException)
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.WrongTrustDirection, Name, targetDomain.Name, direction), typeof(TrustRelationshipInformation), null);
}
}
}
public void CreateLocalSideOfTrustRelationship(string targetDomainName, TrustDirection direction, string trustPassword)
{
CheckIfDisposed();
if (targetDomainName == null)
throw new ArgumentNullException(nameof(targetDomainName));
if (targetDomainName.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(targetDomainName));
if (direction < TrustDirection.Inbound || direction > TrustDirection.Bidirectional)
throw new InvalidEnumArgumentException(nameof(direction), (int)direction, typeof(TrustDirection));
if (trustPassword == null)
throw new ArgumentNullException(nameof(trustPassword));
if (trustPassword.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(trustPassword));
// verify first that the target domain name is valid
Locator.GetDomainControllerInfo(null, targetDomainName, null, (long)PrivateLocatorFlags.DirectoryServicesRequired);
DirectoryContext targetContext = Utils.GetNewDirectoryContext(targetDomainName, DirectoryContextType.Domain, context);
TrustHelper.CreateTrust(context, Name, targetContext, targetDomainName, false, direction, trustPassword);
}
public void CreateTrustRelationship(Domain targetDomain, TrustDirection direction)
{
CheckIfDisposed();
if (targetDomain == null)
throw new ArgumentNullException(nameof(targetDomain));
if (direction < TrustDirection.Inbound || direction > TrustDirection.Bidirectional)
throw new InvalidEnumArgumentException(nameof(direction), (int)direction, typeof(TrustDirection));
string password = TrustHelper.CreateTrustPassword();
// first create trust on local side
TrustHelper.CreateTrust(context, Name, targetDomain.GetDirectoryContext(), targetDomain.Name, false, direction, password);
// then create trust on remote side
int reverseDirection = 0;
if ((direction & TrustDirection.Inbound) != 0)
reverseDirection |= (int)TrustDirection.Outbound;
if ((direction & TrustDirection.Outbound) != 0)
reverseDirection |= (int)TrustDirection.Inbound;
TrustHelper.CreateTrust(targetDomain.GetDirectoryContext(), targetDomain.Name, context, Name, false, (TrustDirection)reverseDirection, password);
}
public void UpdateLocalSideOfTrustRelationship(string targetDomainName, string newTrustPassword)
{
CheckIfDisposed();
if (targetDomainName == null)
throw new ArgumentNullException(nameof(targetDomainName));
if (targetDomainName.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(targetDomainName));
if (newTrustPassword == null)
throw new ArgumentNullException(nameof(newTrustPassword));
if (newTrustPassword.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(newTrustPassword));
TrustHelper.UpdateTrust(context, Name, targetDomainName, newTrustPassword, false);
}
public void UpdateLocalSideOfTrustRelationship(string targetDomainName, TrustDirection newTrustDirection, string newTrustPassword)
{
CheckIfDisposed();
if (targetDomainName == null)
throw new ArgumentNullException(nameof(targetDomainName));
if (targetDomainName.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(targetDomainName));
if (newTrustDirection < TrustDirection.Inbound || newTrustDirection > TrustDirection.Bidirectional)
throw new InvalidEnumArgumentException(nameof(newTrustDirection), (int)newTrustDirection, typeof(TrustDirection));
if (newTrustPassword == null)
throw new ArgumentNullException(nameof(newTrustPassword));
if (newTrustPassword.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(newTrustPassword));
TrustHelper.UpdateTrustDirection(context, Name, targetDomainName, newTrustPassword, false /*not a forest*/, newTrustDirection);
}
public void UpdateTrustRelationship(Domain targetDomain, TrustDirection newTrustDirection)
{
CheckIfDisposed();
if (targetDomain == null)
throw new ArgumentNullException(nameof(targetDomain));
if (newTrustDirection < TrustDirection.Inbound || newTrustDirection > TrustDirection.Bidirectional)
throw new InvalidEnumArgumentException(nameof(newTrustDirection), (int)newTrustDirection, typeof(TrustDirection));
// no we generate trust password
string password = TrustHelper.CreateTrustPassword();
TrustHelper.UpdateTrustDirection(context, Name, targetDomain.Name, password, false /* not a forest */, newTrustDirection);
// then create trust on remote side
TrustDirection reverseDirection = 0;
if ((newTrustDirection & TrustDirection.Inbound) != 0)
reverseDirection |= TrustDirection.Outbound;
if ((newTrustDirection & TrustDirection.Outbound) != 0)
reverseDirection |= TrustDirection.Inbound;
TrustHelper.UpdateTrustDirection(targetDomain.GetDirectoryContext(), targetDomain.Name, Name, password, false /* not a forest */, reverseDirection);
}
public void RepairTrustRelationship(Domain targetDomain)
{
TrustDirection direction = TrustDirection.Bidirectional;
CheckIfDisposed();
if (targetDomain == null)
throw new ArgumentNullException(nameof(targetDomain));
// first try to reset the secure channel
try
{
direction = GetTrustRelationship(targetDomain.Name).TrustDirection;
// verify outbound trust first
if ((direction & TrustDirection.Outbound) != 0)
{
TrustHelper.VerifyTrust(context, Name, targetDomain.Name, false /*not forest*/, TrustDirection.Outbound, true /*reset secure channel*/, null /* no need to go to specific server*/);
}
// verify inbound trust
if ((direction & TrustDirection.Inbound) != 0)
{
TrustHelper.VerifyTrust(targetDomain.GetDirectoryContext(), targetDomain.Name, Name, false /*not forest*/, TrustDirection.Outbound, true/*reset secure channel*/, null /* no need to go to specific server*/);
}
}
catch (ActiveDirectoryOperationException)
{
// secure channel setup fails
RepairTrustHelper(targetDomain, direction);
}
catch (UnauthorizedAccessException)
{
// trust password does not match
RepairTrustHelper(targetDomain, direction);
}
catch (ActiveDirectoryObjectNotFoundException)
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.WrongTrustDirection, Name, targetDomain.Name, direction), typeof(TrustRelationshipInformation), null);
}
}
public static Domain GetCurrentDomain()
{
return Domain.GetDomain(new DirectoryContext(DirectoryContextType.Domain));
}
#endregion public methods
#region public properties
public Forest Forest
{
get
{
CheckIfDisposed();
if (_cachedForest == null)
{
// get the name of rootDomainNamingContext
DirectoryEntry rootDSE = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE);
string rootDomainNC = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.RootDomainNamingContext);
string forestName = Utils.GetDnsNameFromDN(rootDomainNC);
DirectoryContext forestContext = Utils.GetNewDirectoryContext(forestName, DirectoryContextType.Forest, context);
_cachedForest = new Forest(forestContext, forestName);
}
return _cachedForest;
}
}
public DomainControllerCollection DomainControllers
{
get
{
CheckIfDisposed();
if (_cachedDomainControllers == null)
{
_cachedDomainControllers = FindAllDomainControllers();
}
return _cachedDomainControllers;
}
}
public DomainCollection Children
{
get
{
CheckIfDisposed();
if (_cachedChildren == null)
{
_cachedChildren = new DomainCollection(GetChildDomains());
}
return _cachedChildren;
}
}
public DomainMode DomainMode
{
get
{
CheckIfDisposed();
if ((int)_currentDomainMode == -1)
{
_currentDomainMode = GetDomainMode();
}
return _currentDomainMode;
}
}
public int DomainModeLevel
{
get
{
CheckIfDisposed();
if (_domainModeLevel == -1)
{
_domainModeLevel = GetDomainModeLevel();
}
return _domainModeLevel;
}
}
public Domain Parent
{
get
{
CheckIfDisposed();
if (!_isParentInitialized)
{
_cachedParent = GetParent();
_isParentInitialized = true;
}
return _cachedParent;
}
}
public DomainController PdcRoleOwner
{
get
{
CheckIfDisposed();
if (_cachedPdcRoleOwner == null)
{
_cachedPdcRoleOwner = GetRoleOwner(ActiveDirectoryRole.PdcRole);
}
return _cachedPdcRoleOwner;
}
}
public DomainController RidRoleOwner
{
get
{
CheckIfDisposed();
if (_cachedRidRoleOwner == null)
{
_cachedRidRoleOwner = GetRoleOwner(ActiveDirectoryRole.RidRole);
}
return _cachedRidRoleOwner;
}
}
public DomainController InfrastructureRoleOwner
{
get
{
CheckIfDisposed();
if (_cachedInfrastructureRoleOwner == null)
{
_cachedInfrastructureRoleOwner = GetRoleOwner(ActiveDirectoryRole.InfrastructureRole);
}
return _cachedInfrastructureRoleOwner;
}
}
#endregion public properties
#region private methods
internal DirectoryContext GetDirectoryContext() => context;
private int GetDomainModeLevel()
{
DirectoryEntry domainEntry = null;
DirectoryEntry rootDSE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
int domainFunctionality = 0;
try
{
if (rootDSE.Properties.Contains(PropertyManager.DomainFunctionality))
{
domainFunctionality = int.Parse((string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.DomainFunctionality), NumberFormatInfo.InvariantInfo);
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
finally
{
rootDSE.Dispose();
if (domainEntry != null)
{
domainEntry.Dispose();
}
}
return domainFunctionality;
}
private DomainMode GetDomainMode()
{
// logic to check the domain mode
// if domainFunctionality is 0,
// then check ntMixedDomain to differentiate between
// Windows2000Native and Windows2000Mixed
// if domainFunctionality is 1 ==> Windows2003Interim
// if domainFunctionality is 2 ==> Windows2003
// if domainFunctionality is 3 ==> Windows2008
// if domainFunctionality is 4 ==> Windows2008R2
// if domainFunctionality is 5 ==> Windows2012
// if domainFunctionality is 6 ==> Windows2012R2
DomainMode domainMode;
DirectoryEntry domainEntry = null;
int domainFunctionality = DomainModeLevel;
try
{
// If the "domainFunctionality" attribute is not set on the rootdse, then
// this is a W2K domain (with W2K schema) so just check for mixed or native
switch (domainFunctionality)
{
case 0:
{
domainEntry = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.DefaultNamingContext));
int ntMixedDomain = (int)PropertyManager.GetPropertyValue(context, domainEntry, PropertyManager.NTMixedDomain);
if (ntMixedDomain == 0)
{
domainMode = DomainMode.Windows2000NativeDomain;
}
else
{
domainMode = DomainMode.Windows2000MixedDomain;
}
break;
}
case 1:
domainMode = DomainMode.Windows2003InterimDomain;
break;
case 2:
domainMode = DomainMode.Windows2003Domain;
break;
case 3:
domainMode = DomainMode.Windows2008Domain;
break;
case 4:
domainMode = DomainMode.Windows2008R2Domain;
break;
case 5:
domainMode = DomainMode.Windows8Domain;
break;
case 6:
domainMode = DomainMode.Windows2012R2Domain;
break;
default:
// unrecognized domain mode
domainMode = DomainMode.Unknown;
break;
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
finally
{
if (domainEntry != null)
{
domainEntry.Dispose();
}
}
return domainMode;
}
/// <returns>Returns a DomainController object for the DC that holds the specified FSMO role</returns>
private DomainController GetRoleOwner(ActiveDirectoryRole role)
{
DirectoryEntry entry = null;
string dcName = null;
try
{
switch (role)
{
case ActiveDirectoryRole.PdcRole:
{
entry = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.DefaultNamingContext));
break;
}
case ActiveDirectoryRole.RidRole:
{
entry = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.RidManager));
break;
}
case ActiveDirectoryRole.InfrastructureRole:
{
entry = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.Infrastructure));
break;
}
default:
// should not happen since we are calling this only internally
Debug.Fail("Domain.GetRoleOwner: Invalid role type.");
break;
}
dcName = Utils.GetDnsHostNameFromNTDSA(context, (string)PropertyManager.GetPropertyValue(context, entry, PropertyManager.FsmoRoleOwner));
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
finally
{
if (entry != null)
{
entry.Dispose();
}
}
// create a new context object for the domain controller passing on the
// credentials from the domain context
DirectoryContext dcContext = Utils.GetNewDirectoryContext(dcName, DirectoryContextType.DirectoryServer, context);
return new DomainController(dcContext, dcName);
}
private void LoadCrossRefAttributes()
{
DirectoryEntry partitionsEntry = null;
try
{
partitionsEntry = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.PartitionsContainer));
// now within the partitions container search for the
// crossRef object that has it's "dnsRoot" attribute equal to the
// dns name of the current domain
// build the filter
StringBuilder str = new StringBuilder(15);
str.Append("(&(");
str.Append(PropertyManager.ObjectCategory);
str.Append("=crossRef)(");
str.Append(PropertyManager.SystemFlags);
str.Append(":1.2.840.113556.1.4.804:=");
str.Append((int)SystemFlag.SystemFlagNtdsNC);
str.Append(")(");
str.Append(PropertyManager.SystemFlags);
str.Append(":1.2.840.113556.1.4.804:=");
str.Append((int)SystemFlag.SystemFlagNtdsDomain);
str.Append(")(");
str.Append(PropertyManager.DnsRoot);
str.Append("=");
str.Append(Utils.GetEscapedFilterValue(partitionName));
str.Append("))");
string filter = str.ToString();
string[] propertiesToLoad = new string[2];
propertiesToLoad[0] = PropertyManager.DistinguishedName;
propertiesToLoad[1] = PropertyManager.TrustParent;
ADSearcher searcher = new ADSearcher(partitionsEntry, filter, propertiesToLoad, SearchScope.OneLevel, false /*not paged search*/, false /*no cached results*/);
SearchResult res = searcher.FindOne();
_crossRefDN = (string)PropertyManager.GetSearchResultPropertyValue(res, PropertyManager.DistinguishedName);
// "trustParent" attribute may not be set
if (res.Properties[PropertyManager.TrustParent].Count > 0)
{
_trustParent = (string)res.Properties[PropertyManager.TrustParent][0];
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
finally
{
if (partitionsEntry != null)
{
partitionsEntry.Dispose();
}
}
}
private Domain GetParent()
{
if (_crossRefDN == null)
{
LoadCrossRefAttributes();
}
if (_trustParent != null)
{
DirectoryEntry parentCrossRef = DirectoryEntryManager.GetDirectoryEntry(context, _trustParent);
string parentDomainName = null;
DirectoryContext domainContext = null;
try
{
// create a new directory context for the parent domain
parentDomainName = (string)PropertyManager.GetPropertyValue(context, parentCrossRef, PropertyManager.DnsRoot);
domainContext = Utils.GetNewDirectoryContext(parentDomainName, DirectoryContextType.Domain, context);
}
finally
{
parentCrossRef.Dispose();
}
return new Domain(domainContext, parentDomainName);
}
// does not have a parent so just return null
return null;
}
private ArrayList GetChildDomains()
{
ArrayList childDomains = new ArrayList();
if (_crossRefDN == null)
{
LoadCrossRefAttributes();
}
DirectoryEntry partitionsEntry = null;
SearchResultCollection resCol = null;
try
{
partitionsEntry = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.PartitionsContainer));
// search for all the "crossRef" objects that have the
// ADS_SYSTEMFLAG_CR_NTDS_NC and SYSTEMFLAG_CR_NTDS_DOMAIN flags set
// (one-level search is good enough)
// setup the directory searcher object
// build the filter
StringBuilder str = new StringBuilder(15);
str.Append("(&(");
str.Append(PropertyManager.ObjectCategory);
str.Append("=crossRef)(");
str.Append(PropertyManager.SystemFlags);
str.Append(":1.2.840.113556.1.4.804:=");
str.Append((int)SystemFlag.SystemFlagNtdsNC);
str.Append(")(");
str.Append(PropertyManager.SystemFlags);
str.Append(":1.2.840.113556.1.4.804:=");
str.Append((int)SystemFlag.SystemFlagNtdsDomain);
str.Append(")(");
str.Append(PropertyManager.TrustParent);
str.Append("=");
str.Append(Utils.GetEscapedFilterValue(_crossRefDN));
str.Append("))");
string filter = str.ToString();
string[] propertiesToLoad = new string[1];
propertiesToLoad[0] = PropertyManager.DnsRoot;
ADSearcher searcher = new ADSearcher(partitionsEntry, filter, propertiesToLoad, SearchScope.OneLevel);
resCol = searcher.FindAll();
foreach (SearchResult res in resCol)
{
string childDomainName = (string)PropertyManager.GetSearchResultPropertyValue(res, PropertyManager.DnsRoot);
DirectoryContext childContext = Utils.GetNewDirectoryContext(childDomainName, DirectoryContextType.Domain, context);
childDomains.Add(new Domain(childContext, childDomainName));
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
finally
{
if (resCol != null)
{
resCol.Dispose();
}
if (partitionsEntry != null)
{
partitionsEntry.Dispose();
}
}
return childDomains;
}
private ArrayList GetTrustsHelper(string targetDomainName)
{
string serverName = null;
IntPtr domains = (IntPtr)0;
int count = 0;
ArrayList unmanagedTrustList = new ArrayList();
ArrayList tmpTrustList = new ArrayList();
int localDomainIndex = 0;
string localDomainParent = null;
int error = 0;
bool impersonated = false;
// first decide which server to go to
if (context.isServer())
{
serverName = context.Name;
}
else
{
serverName = DomainController.FindOne(context).Name;
}
// impersonate appropriately
impersonated = Utils.Impersonate(context);
// call the DS API to get trust domain information
try
{
try
{
error = UnsafeNativeMethods.DsEnumerateDomainTrustsW(serverName, (int)DS_DOMAINTRUST_FLAG.DS_DOMAIN_IN_FOREST | (int)DS_DOMAINTRUST_FLAG.DS_DOMAIN_DIRECT_OUTBOUND | (int)DS_DOMAINTRUST_FLAG.DS_DOMAIN_DIRECT_INBOUND, out domains, out count);
}
finally
{
if (impersonated)
Utils.Revert();
}
}
catch { throw; }
// check the result
if (error != 0)
throw ExceptionHelper.GetExceptionFromErrorCode(error, serverName);
try
{
// now enumerate through the collection
if (domains != (IntPtr)0 && count != 0)
{
IntPtr addr = (IntPtr)0;
int j = 0;
for (int i = 0; i < count; i++)
{
// get the unmanaged trust object
addr = IntPtr.Add(domains, +i * Marshal.SizeOf(typeof(DS_DOMAIN_TRUSTS)));
DS_DOMAIN_TRUSTS unmanagedTrust = new DS_DOMAIN_TRUSTS();
Marshal.PtrToStructure(addr, unmanagedTrust);
unmanagedTrustList.Add(unmanagedTrust);
}
for (int i = 0; i < unmanagedTrustList.Count; i++)
{
DS_DOMAIN_TRUSTS unmanagedTrust = (DS_DOMAIN_TRUSTS)unmanagedTrustList[i];
// make sure this is the trust object that we want
if ((unmanagedTrust.Flags & (int)(DS_DOMAINTRUST_FLAG.DS_DOMAIN_PRIMARY | DS_DOMAINTRUST_FLAG.DS_DOMAIN_DIRECT_OUTBOUND | DS_DOMAINTRUST_FLAG.DS_DOMAIN_DIRECT_INBOUND)) == 0)
{
// Not interested in indirectly trusted domains.
continue;
}
// we don't want to have the NT4 trust to be returned
if (unmanagedTrust.TrustType == TrustHelper.TRUST_TYPE_DOWNLEVEL)
continue;
TrustObject obj = new TrustObject();
obj.TrustType = TrustType.Unknown;
if (unmanagedTrust.DnsDomainName != (IntPtr)0)
obj.DnsDomainName = Marshal.PtrToStringUni(unmanagedTrust.DnsDomainName);
if (unmanagedTrust.NetbiosDomainName != (IntPtr)0)
obj.NetbiosDomainName = Marshal.PtrToStringUni(unmanagedTrust.NetbiosDomainName);
obj.Flags = unmanagedTrust.Flags;
obj.TrustAttributes = unmanagedTrust.TrustAttributes;
obj.OriginalIndex = i;
obj.ParentIndex = unmanagedTrust.ParentIndex;
// check whether it is the case that we are only interested in the trust with target as specified
if (targetDomainName != null)
{
bool sameTarget = false;
// check whether it is the same target
if (obj.DnsDomainName != null && Utils.Compare(targetDomainName, obj.DnsDomainName) == 0)
sameTarget = true;
else if (obj.NetbiosDomainName != null && Utils.Compare(targetDomainName, obj.NetbiosDomainName) == 0)
sameTarget = true;
// we only want to need local domain and specified target domain trusts
if (!sameTarget && (obj.Flags & (int)DS_DOMAINTRUST_FLAG.DS_DOMAIN_PRIMARY) == 0)
continue;
}
// local domain case
if ((obj.Flags & (int)DS_DOMAINTRUST_FLAG.DS_DOMAIN_PRIMARY) != 0)
{
localDomainIndex = j;
// verify whether this is already the root
if ((obj.Flags & (int)DS_DOMAINTRUST_FLAG.DS_DOMAIN_TREE_ROOT) == 0)
{
// get the parent domain name
DS_DOMAIN_TRUSTS parentTrust = (DS_DOMAIN_TRUSTS)unmanagedTrustList[obj.ParentIndex];
if (parentTrust.DnsDomainName != (IntPtr)0)
localDomainParent = Marshal.PtrToStringUni(parentTrust.DnsDomainName);
}
// this is the trust type SELF
obj.TrustType = (TrustType)7;
}
// this is the case of MIT kerberos trust
else if (unmanagedTrust.TrustType == 3)
{
obj.TrustType = TrustType.Kerberos;
}
j++;
tmpTrustList.Add(obj);
}
// now determine the trust type
for (int i = 0; i < tmpTrustList.Count; i++)
{
TrustObject tmpObject = (TrustObject)tmpTrustList[i];
// local domain case, trust type has been determined
if (i == localDomainIndex)
continue;
if (tmpObject.TrustType == TrustType.Kerberos)
continue;
// parent domain
if (localDomainParent != null && Utils.Compare(localDomainParent, tmpObject.DnsDomainName) == 0)
{
tmpObject.TrustType = TrustType.ParentChild;
continue;
}
if ((tmpObject.Flags & (int)DS_DOMAINTRUST_FLAG.DS_DOMAIN_IN_FOREST) != 0)
{
// child domain
if (tmpObject.ParentIndex == ((TrustObject)tmpTrustList[localDomainIndex]).OriginalIndex)
{
tmpObject.TrustType = TrustType.ParentChild;
}
// tree root
else if ((tmpObject.Flags & (int)DS_DOMAINTRUST_FLAG.DS_DOMAIN_TREE_ROOT) != 0 &&
(((TrustObject)tmpTrustList[localDomainIndex]).Flags & (int)DS_DOMAINTRUST_FLAG.DS_DOMAIN_TREE_ROOT) != 0)
{
string tmpForestName = null;
string rootDomainNC = directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.RootDomainNamingContext);
tmpForestName = Utils.GetDnsNameFromDN(rootDomainNC);
// only if either the local domain or tmpObject is the tree root, will this trust relationship be a Root, otherwise it is cross link
DirectoryContext tmpContext = Utils.GetNewDirectoryContext(context.Name, DirectoryContextType.Forest, context);
if (tmpContext.isRootDomain() || Utils.Compare(tmpObject.DnsDomainName, tmpForestName) == 0)
{
tmpObject.TrustType = TrustType.TreeRoot;
}
else
{
tmpObject.TrustType = TrustType.CrossLink;
}
}
else
{
tmpObject.TrustType = TrustType.CrossLink;
}
continue;
}
// external trust or forest trust
if ((tmpObject.TrustAttributes & (int)TRUST_ATTRIBUTE.TRUST_ATTRIBUTE_FOREST_TRANSITIVE) != 0)
{
// should not happen as we specify DS_DOMAIN_IN_FOREST when enumerating the trust, so forest trust will not be returned
tmpObject.TrustType = TrustType.Forest;
}
else
{
tmpObject.TrustType = TrustType.External;
}
}
}
return tmpTrustList;
}
finally
{
if (domains != (IntPtr)0)
UnsafeNativeMethods.NetApiBufferFree(domains);
}
}
private void RepairTrustHelper(Domain targetDomain, TrustDirection direction)
{
// now we try changing trust password on both sides
string password = TrustHelper.CreateTrustPassword();
// first reset trust password on remote side
string targetServerName = TrustHelper.UpdateTrust(targetDomain.GetDirectoryContext(), targetDomain.Name, Name, password, false);
// then reset trust password on local side
string sourceServerName = TrustHelper.UpdateTrust(context, Name, targetDomain.Name, password, false);
// last we reset the secure channel again to make sure info is replicated and trust is indeed ready now
// verify outbound trust first
if ((direction & TrustDirection.Outbound) != 0)
{
try
{
TrustHelper.VerifyTrust(context, Name, targetDomain.Name, false /*not forest*/, TrustDirection.Outbound, true /*reset secure channel*/, targetServerName /* need to specify which target server */);
}
catch (ActiveDirectoryObjectNotFoundException)
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.WrongTrustDirection, Name, targetDomain.Name, direction), typeof(TrustRelationshipInformation), null);
}
}
// verify inbound trust
if ((direction & TrustDirection.Inbound) != 0)
{
try
{
TrustHelper.VerifyTrust(targetDomain.GetDirectoryContext(), targetDomain.Name, Name, false /*not forest*/, TrustDirection.Outbound, true/*reset secure channel*/, sourceServerName /* need to specify which target server */);
}
catch (ActiveDirectoryObjectNotFoundException)
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.WrongTrustDirection, Name, targetDomain.Name, direction), typeof(TrustRelationshipInformation), null);
}
}
}
#endregion private methods
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Common
{
using System;
using System.Globalization;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Event;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Datastream;
using Apache.Ignite.Core.Events;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Cache;
using Apache.Ignite.Core.Impl.Cache.Query.Continuous;
using Apache.Ignite.Core.Impl.Datastream;
using Apache.Ignite.Core.Impl.Unmanaged;
using Apache.Ignite.Core.Messaging;
/// <summary>
/// Type descriptor with precompiled delegates for known methods.
/// </summary>
internal class DelegateTypeDescriptor
{
/** Cached descriptors. */
private static readonly CopyOnWriteConcurrentDictionary<Type, DelegateTypeDescriptor> Descriptors
= new CopyOnWriteConcurrentDictionary<Type, DelegateTypeDescriptor>();
/** */
private readonly Func<object, object> _computeOutFunc;
/** */
private readonly Func<object, object, object> _computeFunc;
/** */
private readonly Func<object, object, bool> _eventFilter;
/** */
private readonly Func<object, object, object, bool> _cacheEntryFilter;
/** */
private readonly Tuple<Func<object, IMutableCacheEntryInternal, object, object>, Tuple<Type, Type>>
_cacheEntryProcessor;
/** */
private readonly Func<object, Guid, object, bool> _messageLsnr;
/** */
private readonly Func<object, object> _computeJobExecute;
/** */
private readonly Action<object> _computeJobCancel;
/** */
private readonly Action<object, Ignite, IUnmanagedTarget, IBinaryStream, bool> _streamReceiver;
/** */
private readonly Func<object, object> _streamTransformerCtor;
/** */
private readonly Func<object, object, object> _continuousQueryFilterCtor;
/// <summary>
/// Gets the <see cref="IComputeFunc{T}" /> invocator.
/// </summary>
/// <param name="type">Type.</param>
/// <returns>Precompiled invocator delegate.</returns>
public static Func<object, object> GetComputeOutFunc(Type type)
{
return Get(type)._computeOutFunc;
}
/// <summary>
/// Gets the <see cref="IComputeFunc{T, R}" /> invocator.
/// </summary>
/// <param name="type">Type.</param>
/// <returns>Precompiled invocator delegate.</returns>
public static Func<object, object, object> GetComputeFunc(Type type)
{
return Get(type)._computeFunc;
}
/// <summary>
/// Gets the <see cref="IEventFilter{T}" /> invocator.
/// </summary>
/// <param name="type">Type.</param>
/// <returns>Precompiled invocator delegate.</returns>
public static Func<object, object, bool> GetEventFilter(Type type)
{
return Get(type)._eventFilter;
}
/// <summary>
/// Gets the <see cref="ICacheEntryFilter{TK,TV}" /> invocator.
/// </summary>
/// <param name="type">Type.</param>
/// <returns>Precompiled invocator delegate.</returns>
public static Func<object, object, object, bool> GetCacheEntryFilter(Type type)
{
return Get(type)._cacheEntryFilter;
}
/// <summary>
/// Gets the <see cref="ICacheEntryProcessor{K, V, A, R}" /> invocator.
/// </summary>
/// <param name="type">Type.</param>
/// <returns>Precompiled invocator delegate.</returns>
public static Func<object, IMutableCacheEntryInternal, object, object> GetCacheEntryProcessor(Type type)
{
return Get(type)._cacheEntryProcessor.Item1;
}
/// <summary>
/// Gets key and value types for the <see cref="ICacheEntryProcessor{K, V, A, R}" />.
/// </summary>
/// <param name="type">Type.</param>
/// <returns>Key and value types.</returns>
public static Tuple<Type, Type> GetCacheEntryProcessorTypes(Type type)
{
return Get(type)._cacheEntryProcessor.Item2;
}
/// <summary>
/// Gets the <see cref="IMessageListener{T}" /> invocator.
/// </summary>
/// <param name="type">Type.</param>
/// <returns>Precompiled invocator delegate.</returns>
public static Func<object, Guid, object, bool> GetMessageListener(Type type)
{
return Get(type)._messageLsnr;
}
/// <summary>
/// Gets the <see cref="IComputeJob{T}.Execute" /> and <see cref="IComputeJob{T}.Cancel" /> invocators.
/// </summary>
/// <param name="type">Type.</param>
/// <param name="execute">Execute invocator.</param>
/// <param name="cancel">Cancel invocator.</param>
public static void GetComputeJob(Type type, out Func<object, object> execute, out Action<object> cancel)
{
var desc = Get(type);
execute = desc._computeJobExecute;
cancel = desc._computeJobCancel;
}
/// <summary>
/// Gets the <see cref="IStreamReceiver{TK,TV}"/> invocator.
/// </summary>
/// <param name="type">Type.</param>
/// <returns>Precompiled invocator delegate.</returns>
public static Action<object, Ignite, IUnmanagedTarget, IBinaryStream, bool> GetStreamReceiver(Type type)
{
return Get(type)._streamReceiver;
}
/// <summary>
/// Gets the <see cref="StreamTransformer{K, V, A, R}"/>> ctor invocator.
/// </summary>
/// <param name="type">Type.</param>
/// <returns>Precompiled invocator delegate.</returns>
public static Func<object, object> GetStreamTransformerCtor(Type type)
{
return Get(type)._streamTransformerCtor;
}
/// <summary>
/// Gets the <see cref="ContinuousQueryFilter{TK,TV}"/>> ctor invocator.
/// </summary>
/// <param name="type">Type.</param>
/// <returns>Precompiled invocator delegate.</returns>
public static Func<object, object, object> GetContinuousQueryFilterCtor(Type type)
{
return Get(type)._continuousQueryFilterCtor;
}
/// <summary>
/// Gets the <see cref="DelegateTypeDescriptor" /> by type.
/// </summary>
private static DelegateTypeDescriptor Get(Type type)
{
DelegateTypeDescriptor result;
return Descriptors.TryGetValue(type, out result)
? result
: Descriptors.GetOrAdd(type, t => new DelegateTypeDescriptor(t));
}
/// <summary>
/// Throws an exception if first argument is not null.
/// </summary>
// ReSharper disable once UnusedParameter.Local
private static void ThrowIfMultipleInterfaces(object check, Type userType, Type interfaceType)
{
if (check != null)
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture,
"Not Supported: Type {0} implements interface {1} multiple times.", userType, interfaceType));
}
/// <summary>
/// Initializes a new instance of the <see cref="DelegateTypeDescriptor"/> class.
/// </summary>
/// <param name="type">The type.</param>
private DelegateTypeDescriptor(Type type)
{
foreach (var iface in type.GetInterfaces())
{
if (!iface.IsGenericType)
continue;
var genericTypeDefinition = iface.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof (IComputeFunc<>))
{
ThrowIfMultipleInterfaces(_computeOutFunc, type, typeof(IComputeFunc<>));
_computeOutFunc = DelegateConverter.CompileFunc(iface);
}
else if (genericTypeDefinition == typeof (IComputeFunc<,>))
{
ThrowIfMultipleInterfaces(_computeFunc, type, typeof(IComputeFunc<,>));
var args = iface.GetGenericArguments();
_computeFunc = DelegateConverter.CompileFunc<Func<object, object, object>>(iface, new[] {args[0]});
}
else if (genericTypeDefinition == typeof (IEventFilter<>))
{
ThrowIfMultipleInterfaces(_eventFilter, type, typeof(IEventFilter<>));
var args = iface.GetGenericArguments();
_eventFilter = DelegateConverter.CompileFunc<Func<object, object, bool>>(iface,
new[] {args[0]}, new[] {true, false});
}
else if (genericTypeDefinition == typeof (ICacheEntryFilter<,>))
{
ThrowIfMultipleInterfaces(_cacheEntryFilter, type, typeof(ICacheEntryFilter<,>));
var args = iface.GetGenericArguments();
var entryType = typeof (ICacheEntry<,>).MakeGenericType(args);
var invokeFunc = DelegateConverter.CompileFunc<Func<object, object, bool>>(iface,
new[] { entryType }, new[] { true, false });
var ctor = DelegateConverter.CompileCtor<Func<object, object, object>>(
typeof (CacheEntry<,>).MakeGenericType(args), args);
// Resulting func constructs CacheEntry and passes it to user implementation
_cacheEntryFilter = (obj, k, v) => invokeFunc(obj, ctor(k, v));
}
else if (genericTypeDefinition == typeof (ICacheEntryProcessor<,,,>))
{
ThrowIfMultipleInterfaces(_cacheEntryProcessor, type, typeof(ICacheEntryProcessor<,,,>));
var args = iface.GetGenericArguments();
var entryType = typeof (IMutableCacheEntry<,>).MakeGenericType(args[0], args[1]);
var func = DelegateConverter.CompileFunc<Func<object, object, object, object>>(iface,
new[] { entryType, args[2] }, null, "Process");
var types = new Tuple<Type, Type>(args[0], args[1]);
_cacheEntryProcessor = new Tuple<Func<object, IMutableCacheEntryInternal, object, object>, Tuple<Type, Type>>
(func, types);
var transformerType = typeof (StreamTransformer<,,,>).MakeGenericType(args);
_streamTransformerCtor = DelegateConverter.CompileCtor<Func<object, object>>(transformerType,
new[] {iface});
}
else if (genericTypeDefinition == typeof (IMessageListener<>))
{
ThrowIfMultipleInterfaces(_messageLsnr, type, typeof(IMessageListener<>));
var arg = iface.GetGenericArguments()[0];
_messageLsnr = DelegateConverter.CompileFunc<Func<object, Guid, object, bool>>(iface,
new[] { typeof(Guid), arg }, new[] { false, true, false });
}
else if (genericTypeDefinition == typeof (IComputeJob<>))
{
ThrowIfMultipleInterfaces(_messageLsnr, type, typeof(IComputeJob<>));
_computeJobExecute = DelegateConverter.CompileFunc<Func<object, object>>(iface, new Type[0],
methodName: "Execute");
_computeJobCancel = DelegateConverter.CompileFunc<Action<object>>(iface, new Type[0],
new[] {false}, "Cancel");
}
else if (genericTypeDefinition == typeof (IStreamReceiver<,>))
{
ThrowIfMultipleInterfaces(_streamReceiver, type, typeof (IStreamReceiver<,>));
var method =
typeof (StreamReceiverHolder).GetMethod("InvokeReceiver")
.MakeGenericMethod(iface.GetGenericArguments());
_streamReceiver = DelegateConverter
.CompileFunc<Action<object, Ignite, IUnmanagedTarget, IBinaryStream, bool>>(
typeof (StreamReceiverHolder),
method,
new[]
{
iface, typeof (Ignite), typeof (IUnmanagedTarget), typeof (IBinaryStream),
typeof (bool)
},
new[] {true, false, false, false, false, false});
}
else if (genericTypeDefinition == typeof (ICacheEntryEventFilter<,>))
{
ThrowIfMultipleInterfaces(_streamReceiver, type, typeof(ICacheEntryEventFilter<,>));
var args = iface.GetGenericArguments();
_continuousQueryFilterCtor =
DelegateConverter.CompileCtor<Func<object, object, object>>(
typeof(ContinuousQueryFilter<,>).MakeGenericType(args), new[] { iface, typeof(bool) });
}
}
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email [email protected] or visit
the website www.fyiReporting.com.
*/
using System;
using System.Collections;
using System.IO;
using System.Reflection;
using System.Text;
using fyiReporting.RDL;
namespace fyiReporting.RDL
{
/// <summary>
/// The VBFunctions class holds a number of static functions for support VB functions.
/// </summary>
sealed public class VBFunctions
{
/// <summary>
/// Obtains the year
/// </summary>
/// <param name="dt"></param>
/// <returns>int year</returns>
static public int Year(DateTime dt)
{
return dt.Year;
}
/// <summary>
/// Returns the integer day of week: 1=Sunday, 2=Monday, ..., 7=Saturday
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
static public int Weekday(DateTime dt)
{
int dow;
switch (dt.DayOfWeek)
{
case DayOfWeek.Sunday:
dow=1;
break;
case DayOfWeek.Monday:
dow=2;
break;
case DayOfWeek.Tuesday:
dow=3;
break;
case DayOfWeek.Wednesday:
dow=4;
break;
case DayOfWeek.Thursday:
dow=5;
break;
case DayOfWeek.Friday:
dow=6;
break;
case DayOfWeek.Saturday:
dow=7;
break;
default: // should never happen
dow=1;
break;
}
return dow;
}
/// <summary>
/// Returns the name of the day of week
/// </summary>
/// <param name="d"></param>
/// <returns></returns>
static public string WeekdayName(int d)
{
return WeekdayName(d, false);
}
/// <summary>
/// Returns the name of the day of week
/// </summary>
/// <param name="d"></param>
/// <param name="bAbbreviation">true for abbreviated name</param>
/// <returns></returns>
static public string WeekdayName(int d, bool bAbbreviation)
{
DateTime dt = new DateTime(2005, 5, d); // May 1, 2005 is a Sunday
string wdn = bAbbreviation? string.Format("{0:ddd}", dt):string.Format("{0:dddd}", dt);
return wdn;
}
/// <summary>
/// Get the day of the month.
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
static public int Day(DateTime dt)
{
return dt.Day;
}
/// <summary>
/// Gets the integer month
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
static public int Month(DateTime dt)
{
return dt.Month;
}
/// <summary>
/// Get the month name
/// </summary>
/// <param name="m"></param>
/// <returns></returns>
static public string MonthName(int m)
{
return MonthName(m, false);
}
/// <summary>
/// Gets the month name; optionally abbreviated
/// </summary>
/// <param name="m"></param>
/// <param name="bAbbreviation"></param>
/// <returns></returns>
static public string MonthName(int m, bool bAbbreviation)
{
DateTime dt = new DateTime(2005, m, 1);
string mdn = bAbbreviation? string.Format("{0:MMM}", dt):string.Format("{0:MMMM}", dt);
return mdn;
}
/// <summary>
/// Gets the hour
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
static public int Hour(DateTime dt)
{
return dt.Hour;
}
/// <summary>
/// Get the minute
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
static public int Minute(DateTime dt)
{
return dt.Minute;
}
/// <summary>
/// Get the second
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
static public int Second(DateTime dt)
{
return dt.Second;
}
/// <summary>
/// Gets the current local date on this computer
/// </summary>
/// <returns></returns>
static public DateTime Today()
{
DateTime dt = DateTime.Now;
return new DateTime(dt.Year, dt.Month, dt.Day, 0, 0, 0, 0);
}
/// <summary>
/// Converts the first letter in a string to ANSI code
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
static public int Asc(string o)
{
if (o == null || o.Length == 0)
return 0;
return Convert.ToInt32(o[0]);
}
/// <summary>
/// Converts an expression to Boolean
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
static public bool CBool(object o)
{
return Convert.ToBoolean(o);
}
/// <summary>
/// Converts an expression to type Byte
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
static public Byte CByte(string o)
{
return Convert.ToByte(o);
}
/// <summary>
/// Converts an expression to type Currency - really Decimal
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
static public decimal CCur(string o)
{
return Convert.ToDecimal(o);
}
/// <summary>
/// Converts an expression to type Date
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
static public DateTime CDate(string o)
{
return Convert.ToDateTime(o);
}
/// <summary>
/// Converts the specified ANSI code to a character
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
static public char Chr(int o)
{
return Convert.ToChar(o);
}
/// <summary>
/// Converts the expression to integer
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
static public int CInt(object o)
{
return Convert.ToInt32(o);
}
/// <summary>
/// Converts the expression to long
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
static public long CLng(object o)
{
return Convert.ToInt64(o);
}
/// <summary>
/// Converts the expression to Single
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
static public Single CSng(object o)
{
return Convert.ToSingle(o);
}
/// <summary>
/// Converts the expression to String
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
static public string CStr(object o)
{
return Convert.ToString(o);
}
/// <summary>
/// Returns the hexadecimal value of a specified number
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
static public string Hex(long o)
{
return Convert.ToString(o, 16);
}
/// <summary>
/// Returns the octal value of a specified number
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
static public string Oct(long o)
{
return Convert.ToString(o, 8);
}
/// <summary>
/// Converts the passed parameter to double
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
static public double CDbl(Object o)
{
return Convert.ToDouble(o);
}
static public DateTime DateAdd(string interval, double number, string date)
{
return DateAdd(interval, number, DateTime.Parse(date));
}
/// <summary>
/// Returns a date to which a specified time interval has been added.
/// </summary>
/// <param name="interval">String expression that is the interval you want to add.</param>
/// <param name="number">Numeric expression that is the number of interval you want to add. The numeric expression can either be positive, for dates in the future, or negative, for dates in the past.</param>
/// <param name="date">The date to which interval is added.</param>
/// <returns></returns>
static public DateTime DateAdd(string interval, double number, DateTime date)
{
switch (interval)
{
case "yyyy": // year
date = date.AddYears((int) Math.Round(number, 0));
break;
case "m": // month
date = date.AddMonths((int)Math.Round(number, 0));
break;
case "d": // day
date = date.AddDays(number);
break;
case "h": // hour
date = date.AddHours(number);
break;
case "n": // minute
date = date.AddMinutes(number);
break;
case "s": // second
date = date.AddSeconds(number);
break;
case "y": // day of year
date = date.AddDays(number);
break;
case "q": // quarter
date = date.AddMonths((int)Math.Round(number, 0) * 3);
break;
case "w": // weekday
date = date.AddDays(number);
break;
case "ww": // week of year
date = date.AddDays((int)Math.Round(number, 0) * 7);
break;
default:
throw new ArgumentException(string.Format("Interval '{0}' is invalid or unsupported.", interval));
}
return date;
}
/// <summary>
/// 1 based offset of string2 in string1
/// </summary>
/// <param name="string1"></param>
/// <param name="string2"></param>
/// <returns></returns>
static public int InStr(string string1, string string2)
{
return InStr(1, string1, string2, 0);
}
/// <summary>
/// 1 based offset of string2 in string1
/// </summary>
/// <param name="start"></param>
/// <param name="string1"></param>
/// <param name="string2"></param>
/// <returns></returns>
static public int InStr(int start, string string1, string string2)
{
return InStr(start, string1, string2, 0);
}
/// <summary>
/// 1 based offset of string2 in string1; optionally case insensitive
/// </summary>
/// <param name="string1"></param>
/// <param name="string2"></param>
/// <param name="compare">1 if you want case insensitive compare</param>
/// <returns></returns>
static public int InStr(string string1, string string2, int compare)
{
return InStr(1, string1, string2, compare);
}
/// <summary>
/// 1 based offset of string2 in string1; optionally case insensitive
/// </summary>
/// <param name="start"></param>
/// <param name="string1"></param>
/// <param name="string2"></param>
/// <param name="compare"></param>
/// <returns></returns>
static public int InStr(int start, string string1, string string2, int compare)
{
if (string1 == null || string2 == null ||
string1.Length == 0 || start > string1.Length ||
start < 1)
return 0;
if (string2.Length == 0)
return start;
// Make start zero based
start--;
if (start < 0)
start=0;
if (compare == 1) // Make case insensitive comparison?
{ // yes; just make both strings lower case
string1 = string1.ToLower();
string2 = string2.ToLower();
}
int i = string1.IndexOf(string2, start);
return i+1; // result is 1 based
}
/// <summary>
/// 1 based offset of string2 in string1 starting from end of string
/// </summary>
/// <param name="string1"></param>
/// <param name="string2"></param>
/// <returns></returns>
static public int InStrRev(string string1, string string2)
{
return InStrRev(string1, string2, -1, 0);
}
/// <summary>
/// 1 based offset of string2 in string1 starting from end of string - start
/// </summary>
/// <param name="string1"></param>
/// <param name="string2"></param>
/// <param name="start"></param>
/// <returns></returns>
static public int InStrRev(string string1, string string2, int start)
{
return InStrRev(string1, string2, start, 0);
}
/// <summary>
/// 1 based offset of string2 in string1 starting from end of string - start optionally case insensitive
/// </summary>
/// <param name="string1"></param>
/// <param name="string2"></param>
/// <param name="start"></param>
/// <param name="compare">1 for case insensitive comparison</param>
/// <returns></returns>
static public int InStrRev(string string1, string string2, int start, int compare)
{
if (string1 == null || string2 == null ||
string1.Length == 0 || string2.Length > string1.Length)
return 0;
// TODO this is the brute force method of searching; should use better algorithm
bool bCaseSensitive = compare == 1;
int inc= start == -1? string1.Length: start;
if (inc > string1.Length)
inc = string1.Length;
while (inc >= string2.Length) // go thru the string backwards; but string still needs to long enough to hold find string
{
int i=string2.Length-1;
for ( ; i >= 0; i--) // match the find string backwards as well
{
if (bCaseSensitive)
{
if (Char.ToLower(string1[inc-string2.Length+i]) != string2[i])
break;
}
else
{
if (string1[inc-string2.Length+i] != string2[i])
break;
}
}
if (i < 0) // We got a match
return inc+1-string2.Length;
inc--; // No match try next character
}
return 0;
}
/// <summary>
/// IsNumeric returns True if the data type of Expression is Boolean, Byte, Decimal, Double, Integer, Long,
/// SByte, Short, Single, UInteger, ULong, or UShort.
/// It also returns True if Expression is a Char, String, or Object that can be successfully converted to a number.
///
/// IsNumeric returns False if Expression is of data type Date. It returns False if Expression is a
/// Char, String, or Object that cannot be successfully converted to a number.
/// </summary>
/// <param name="v"></param>
/// <returns></returns>
static public bool IsNumeric(object expression)
{
if (expression == null)
return false;
if (expression is string || expression is char)
{
}
else if (expression is bool || expression is byte || expression is sbyte ||
expression is decimal ||
expression is double || expression is float ||
expression is Int16 || expression is Int32 || expression is Int64 ||
expression is UInt16 || expression is UInt32 || expression is UInt64)
return true;
try
{
Convert.ToDouble(expression);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Returns the lower case of the passed string
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
static public string LCase(string str)
{
return str == null? null: str.ToLower();
}
/// <summary>
/// Returns the left n characters from the string
/// </summary>
/// <param name="str"></param>
/// <param name="count"></param>
/// <returns></returns>
static public string Left(string str, int count)
{
if (str == null || count >= str.Length)
return str;
else
return str.Substring(0, count);
}
/// <summary>
/// Returns the length of the string
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
static public int Len(string str)
{
return str == null? 0: str.Length;
}
/// <summary>
/// Removes leading blanks from string
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
static public string LTrim(string str)
{
if (str == null || str.Length == 0)
return str;
return str.TrimStart(' ');
}
/// <summary>
/// Returns the portion of the string denoted by the start.
/// </summary>
/// <param name="str"></param>
/// <param name="start">1 based starting position</param>
/// <returns></returns>
static public string Mid(string str, int start)
{
if (str == null)
return null;
if (start > str.Length)
return "";
return str.Substring(start - 1);
}
/// <summary>
/// Returns the portion of the string denoted by the start and length.
/// </summary>
/// <param name="str"></param>
/// <param name="start">1 based starting position</param>
/// <param name="length">length to extract</param>
/// <returns></returns>
static public string Mid(string str, int start, int length)
{
if (str == null)
return null;
if (start > str.Length)
return "";
if (str.Length < start - 1 + length)
return str.Substring(start - 1); // Length specified is too large
return str.Substring(start-1, length);
}
//Replace(string,find,replacewith[,start[,count[,compare]]])
/// <summary>
/// Returns string replacing all instances of the searched for text with the replace text.
/// </summary>
/// <param name="str"></param>
/// <param name="find"></param>
/// <param name="replacewith"></param>
/// <returns></returns>
static public string Replace(string str, string find, string replacewith)
{
return Replace(str, find, replacewith, 1, -1, 0);
}
/// <summary>
/// Returns string replacing all instances of the searched for text starting at position
/// start with the replace text.
/// </summary>
/// <param name="str"></param>
/// <param name="find"></param>
/// <param name="replacewith"></param>
/// <param name="start"></param>
/// <returns></returns>
static public string Replace(string str, string find, string replacewith, int start)
{
return Replace(str, find, replacewith, start, -1, 0);
}
/// <summary>
/// Returns string replacing 'count' instances of the searched for text starting at position
/// start with the replace text.
/// </summary>
/// <param name="str"></param>
/// <param name="find"></param>
/// <param name="replacewith"></param>
/// <param name="start"></param>
/// <param name="count"></param>
/// <returns></returns>
static public string Replace(string str, string find, string replacewith, int start, int count)
{
return Replace(str, find, replacewith, start, count, 0);
}
/// <summary>
/// Returns string replacing 'count' instances of the searched for text (optionally
/// case insensitive) starting at position start with the replace text.
/// </summary>
/// <param name="str"></param>
/// <param name="find"></param>
/// <param name="replacewith"></param>
/// <param name="start"></param>
/// <param name="count"></param>
/// <param name="compare">1 for case insensitive search</param>
/// <returns></returns>
static public string Replace(string str, string find, string replacewith, int start, int count, int compare)
{
if (str == null || find == null || find.Length == 0 || count == 0)
return str;
if (count == -1) // user want all changed?
count = int.MaxValue;
StringBuilder sb = new StringBuilder(str);
bool bCaseSensitive = compare != 0; // determine if case sensitive; compare = 0 for case sensitive
if (bCaseSensitive)
find = find.ToLower();
int inc=0;
bool bReplace = (replacewith != null && replacewith.Length > 0);
// TODO this is the brute force method of searching; should use better algorithm
while (inc <= sb.Length - find.Length)
{
int i=0;
for ( ; i < find.Length; i++)
{
if (bCaseSensitive)
{
if (Char.ToLower(sb[inc+i]) != find[i])
break;
}
else
{
if (sb[inc+i] != find[i])
break;
}
}
if (i == find.Length) // We got a match
{
// replace the found string with the replacement string
sb.Remove(inc, find.Length);
if (bReplace)
{
sb.Insert(inc, replacewith);
inc += (replacewith.Length + 1);
}
count--;
if (count == 0) // have we done as many replaces as requested?
return sb.ToString(); // yes, return
}
else
inc++; // No match try next character
}
return sb.ToString();
}
/// <summary>
/// Returns the rightmost length of string.
/// </summary>
/// <param name="str"></param>
/// <param name="length"></param>
/// <returns></returns>
static public string Right(string str, int length)
{
if (str == null || str.Length <= length)
return str;
if (length <= 0)
return "";
return str.Substring(str.Length - length);
}
/// <summary>
/// Removes trailing blanks from string.
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
static public string RTrim(string str)
{
if (str == null || str.Length == 0)
return str;
return str.TrimEnd(' ');
}
/// <summary>
/// Returns blank string of the specified length
/// </summary>
/// <param name="length"></param>
/// <returns></returns>
static public string Space(int length)
{
return String(length, ' ');
}
//StrComp(string1,string2[,compare])
/// <summary>
/// Compares the strings. When string1 < string2: -1, string1 = string2: 0, string1 > string2: 1
/// </summary>
/// <param name="string1"></param>
/// <param name="string2"></param>
/// <returns></returns>
static public int StrComp(string string1, string string2)
{
return StrComp(string1, string2, 0);
}
/// <summary>
/// Compares the strings; optionally with case insensitivity. When string1 < string2: -1, string1 = string2: 0, string1 > string2: 1
/// </summary>
/// <param name="string1"></param>
/// <param name="string2"></param>
/// <param name="compare">1 for case insensitive comparison</param>
/// <returns></returns>
static public int StrComp(string string1, string string2, int compare)
{
if (string1 == null || string2 == null)
return 0; // not technically correct; should return null
return compare == 0?
string1.CompareTo(string2):
string1.ToLower().CompareTo(string2.ToLower());
}
/// <summary>
/// Return string with the character repeated for the length
/// </summary>
/// <param name="length"></param>
/// <param name="c"></param>
/// <returns></returns>
static public string String(int length, string c)
{
if (length <= 0 || c == null || c.Length == 0)
return "";
return String(length, c[0]);
}
/// <summary>
/// Return string with the character repeated for the length
/// </summary>
/// <param name="length"></param>
/// <param name="c"></param>
/// <returns></returns>
static public string String(int length, char c)
{
if (length <= 0)
return "";
StringBuilder sb = new StringBuilder(length, length);
for (int i = 0; i < length; i++)
sb.Append(c);
return sb.ToString();
}
/// <summary>
/// Returns a string with the characters reversed.
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
static public string StrReverse(string str)
{
if (str == null || str.Length < 2)
return str;
StringBuilder sb = new StringBuilder(str, str.Length);
int i = str.Length-1;
foreach (char c in str)
{
sb[i--] = c;
}
return sb.ToString();
}
/// <summary>
/// Removes whitespace from beginning and end of string.
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
static public string Trim(string str)
{
if (str == null || str.Length == 0)
return str;
return str.Trim(' ');
}
/// <summary>
/// Returns the uppercase version of the string
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
static public string UCase(string str)
{
return str == null? null: str.ToUpper();
}
/// <summary>
/// Rounds a number to zero decimal places
/// </summary>
/// <param name="n">Number to round</param>
/// <returns></returns>
static public double Round(double n)
{
return Math.Round(n);
}
/// <summary>
/// Rounds a number to the specified decimal places
/// </summary>
/// <param name="n">Number to round</param>
/// <param name="decimals">Number of decimal places</param>
/// <returns></returns>
static public double Round(double n, int decimals)
{
return Math.Round(n, decimals);
}
/// <summary>
/// Rounds a number to zero decimal places
/// </summary>
/// <param name="n">Number to round</param>
/// <returns></returns>
static public decimal Round(decimal n)
{
return Math.Round(n);
}
/// <summary>
/// Rounds a number to the specified decimal places
/// </summary>
/// <param name="n">Number to round</param>
/// <param name="decimals">Number of decimal places</param>
/// <returns></returns>
static public decimal Round(decimal n, int decimals)
{
return Math.Round(n, decimals);
}
}
}
| |
using System;
using System.Collections.Generic;
using GraphQL.Language.AST;
using GraphQL.Types;
namespace GraphQL.Validation
{
/// <summary>
/// Provides information pertaining to the current state of the AST tree while being walked.
/// Thus, validation rules checking is designed for sequential execution.
/// </summary>
public class TypeInfo : INodeVisitor
{
private readonly ISchema _schema;
private readonly Stack<IGraphType?> _typeStack = new Stack<IGraphType?>();
private readonly Stack<IGraphType?> _inputTypeStack = new Stack<IGraphType?>();
private readonly Stack<IGraphType> _parentTypeStack = new Stack<IGraphType>();
private readonly Stack<FieldType?> _fieldDefStack = new Stack<FieldType?>();
private readonly Stack<INode> _ancestorStack = new Stack<INode>();
private DirectiveGraphType? _directive;
private QueryArgument? _argument;
/// <summary>
/// Initializes a new instance for the specified schema.
/// </summary>
/// <param name="schema"></param>
public TypeInfo(ISchema schema)
{
_schema = schema;
}
private static T? PeekElement<T>(Stack<T> from, int index)
{
if (index == 0)
{
return from.Count > 0 ? from.Peek() : default;
}
else
{
if (index >= from.Count)
throw new InvalidOperationException($"Stack contains only {from.Count} items");
var e = from.GetEnumerator();
int i = index;
do
{
_ = e.MoveNext();
}
while (i-- > 0);
return e.Current;
}
}
/// <summary>
/// Returns an ancestor of the current node.
/// </summary>
/// <param name="index">Index of the ancestor; 0 for the node itself, 1 for the direct ancestor and so on.</param>
public INode? GetAncestor(int index) => PeekElement(_ancestorStack, index);
/// <summary>
/// Returns the last graph type matched, or <see langword="null"/> if none.
/// </summary>
/// <param name="index">Index of the type; 0 for the top-most type, 1 for the direct ancestor and so on.</param>
public IGraphType? GetLastType(int index = 0) => PeekElement(_typeStack, index);
/// <summary>
/// Returns the last input graph type matched, or <see langword="null"/> if none.
/// </summary>
/// <param name="index">Index of the type; 0 for the top-most type, 1 for the direct ancestor and so on.</param>
public IGraphType? GetInputType(int index = 0) => PeekElement(_inputTypeStack, index);
/// <summary>
/// Returns the parent graph type of the current node, or <see langword="null"/> if none.
/// </summary>
/// <param name="index">Index of the type; 0 for the top-most type, 1 for the direct ancestor and so on.</param>
public IGraphType? GetParentType(int index = 0) => PeekElement(_parentTypeStack, index);
/// <summary>
/// Returns the last field type matched, or <see langword="null"/> if none.
/// </summary>
/// <param name="index">Index of the field; 0 for the top-most field, 1 for the direct ancestor and so on.</param>
public FieldType? GetFieldDef(int index = 0) => PeekElement(_fieldDefStack, index);
/// <summary>
/// Returns the last directive specified, or <see langword="null"/> if none.
/// </summary>
public DirectiveGraphType? GetDirective() => _directive;
/// <summary>
/// Returns the last query argument matched, or <see langword="null"/> if none.
/// </summary>
public QueryArgument? GetArgument() => _argument;
/// <inheritdoc/>
public void Enter(INode node, ValidationContext context)
{
_ancestorStack.Push(node);
if (node is SelectionSet)
{
_parentTypeStack.Push(GetLastType()!);
return;
}
if (node is Field field)
{
var parentType = _parentTypeStack.Peek().GetNamedType();
var fieldType = GetFieldDef(_schema, parentType, field);
_fieldDefStack.Push(fieldType);
var targetType = fieldType?.ResolvedType;
_typeStack.Push(targetType);
return;
}
if (node is Directive directive)
{
_directive = _schema.Directives.Find(directive.Name);
}
if (node is Operation op)
{
IGraphType? type = null;
if (op.OperationType == OperationType.Query)
{
type = _schema.Query;
}
else if (op.OperationType == OperationType.Mutation)
{
type = _schema.Mutation;
}
else if (op.OperationType == OperationType.Subscription)
{
type = _schema.Subscription;
}
_typeStack.Push(type);
return;
}
if (node is FragmentDefinition def1)
{
var type = _schema.AllTypes[def1.Type.Name];
_typeStack.Push(type);
return;
}
if (node is InlineFragment def)
{
var type = def.Type != null ? _schema.AllTypes[def.Type.Name] : GetLastType();
_typeStack.Push(type);
return;
}
if (node is VariableDefinition varDef)
{
var inputType = varDef.Type.GraphTypeFromType(_schema);
_inputTypeStack.Push(inputType);
return;
}
if (node is Argument argAst)
{
QueryArgument? argDef = null;
IGraphType? argType = null;
var args = GetDirective() != null ? GetDirective()?.Arguments : GetFieldDef()?.Arguments;
if (args != null)
{
argDef = args.Find(argAst.Name);
argType = argDef?.ResolvedType;
}
_argument = argDef;
_inputTypeStack.Push(argType);
}
if (node is ListValue)
{
var type = GetInputType()?.GetNamedType();
_inputTypeStack.Push(type);
}
if (node is ObjectField objectField)
{
var objectType = GetInputType()?.GetNamedType();
IGraphType? fieldType = null;
if (objectType is IInputObjectGraphType complexType)
{
var inputField = complexType.GetField(objectField.Name);
fieldType = inputField?.ResolvedType;
}
_inputTypeStack.Push(fieldType);
}
}
/// <inheritdoc/>
public void Leave(INode node, ValidationContext context)
{
_ancestorStack.Pop();
if (node is SelectionSet)
{
_parentTypeStack.Pop();
}
else if (node is Field)
{
_fieldDefStack.Pop();
_typeStack.Pop();
}
else if (node is Directive)
{
_directive = null;
}
else if (node is Operation || node is FragmentDefinition || node is InlineFragment)
{
_typeStack.Pop();
}
else if (node is VariableDefinition)
{
_inputTypeStack.Pop();
}
else if (node is Argument)
{
_argument = null;
_inputTypeStack.Pop();
}
else if (node is ListValue || node is ObjectField)
{
_inputTypeStack.Pop();
}
}
private FieldType? GetFieldDef(ISchema schema, IGraphType parentType, Field field)
{
var name = field.Name;
if (name == schema.SchemaMetaFieldType.Name && Equals(schema.Query, parentType))
{
return schema.SchemaMetaFieldType;
}
if (name == schema.TypeMetaFieldType.Name && Equals(schema.Query, parentType))
{
return schema.TypeMetaFieldType;
}
if (name == schema.TypeNameMetaFieldType.Name && parentType.IsCompositeType())
{
return schema.TypeNameMetaFieldType;
}
if (parentType is IObjectGraphType || parentType is IInterfaceGraphType)
{
var complexType = (IComplexGraphType)parentType;
return complexType.GetField(field.Name);
}
return null;
}
/// <summary>
/// Tracks already visited fragments to maintain O(N) and to ensure that cycles
/// are not redundantly reported.
/// </summary>
internal HashSet<string>? NoFragmentCycles_VisitedFrags;
/// <summary>
/// Array of AST nodes used to produce meaningful errors
/// </summary>
internal Stack<FragmentSpread>? NoFragmentCycles_SpreadPath;
/// <summary>
/// Position in the spread path
/// </summary>
internal Dictionary<string, int>? NoFragmentCycles_SpreadPathIndexByName;
internal HashSet<string>? NoUndefinedVariables_VariableNameDefined;
internal List<Operation>? NoUnusedFragments_OperationDefs;
internal List<FragmentDefinition>? NoUnusedFragments_FragmentDefs;
internal List<VariableDefinition>? NoUnusedVariables_VariableDefs;
internal Dictionary<string, Argument>? UniqueArgumentNames_KnownArgs;
internal Dictionary<string, FragmentDefinition>? UniqueFragmentNames_KnownFragments;
internal Stack<Dictionary<string, IValue>>? UniqueInputFieldNames_KnownNameStack;
internal Dictionary<string, IValue>? UniqueInputFieldNames_KnownNames;
internal HashSet<string>? UniqueOperationNames_Frequency;
internal Dictionary<string, VariableDefinition>? UniqueVariableNames_KnownVariables;
internal Dictionary<string, VariableDefinition>? VariablesInAllowedPosition_VarDefMap;
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Orleans.Metadata;
using Orleans.Runtime;
namespace Orleans.Streams
{
internal class ImplicitStreamSubscriberTable
{
private readonly object _lockObj = new object();
private readonly GrainBindingsResolver _bindings;
private readonly IStreamNamespacePredicateProvider[] _providers;
private readonly IServiceProvider _serviceProvider;
private Cache _cache;
public ImplicitStreamSubscriberTable(
GrainBindingsResolver bindings,
IEnumerable<IStreamNamespacePredicateProvider> providers,
IServiceProvider serviceProvider)
{
_bindings = bindings;
var initialBindings = bindings.GetAllBindings();
_providers = providers.ToArray();
_serviceProvider = serviceProvider;
_cache = BuildCache(initialBindings.Version, initialBindings.Bindings);
}
private Cache GetCache()
{
var cache = _cache;
var bindings = _bindings.GetAllBindings();
if (bindings.Version == cache.Version)
{
return cache;
}
lock (_lockObj)
{
bindings = _bindings.GetAllBindings();
if (bindings.Version == cache.Version)
{
return cache;
}
return _cache = BuildCache(bindings.Version, bindings.Bindings);
}
}
private Cache BuildCache(MajorMinorVersion version, ImmutableDictionary<GrainType, GrainBindings> bindings)
{
var newPredicates = new List<StreamSubscriberPredicate>();
foreach (var binding in bindings.Values)
{
foreach (var grainBinding in binding.Bindings)
{
if (!grainBinding.TryGetValue(WellKnownGrainTypeProperties.BindingTypeKey, out var type)
|| !string.Equals(type, WellKnownGrainTypeProperties.StreamBindingTypeValue, StringComparison.Ordinal))
{
continue;
}
if (!grainBinding.TryGetValue(WellKnownGrainTypeProperties.StreamBindingPatternKey, out var pattern))
{
throw new KeyNotFoundException(
$"Stream binding for grain type {binding.GrainType} is missing a \"{WellKnownGrainTypeProperties.StreamBindingPatternKey}\" value");
}
IStreamNamespacePredicate predicate = null;
foreach (var provider in _providers)
{
if (provider.TryGetPredicate(pattern, out predicate)) break;
}
if (predicate is null)
{
throw new KeyNotFoundException(
$"Could not find an {nameof(IStreamNamespacePredicate)} for the pattern \"{pattern}\"."
+ $" Ensure that a corresponding {nameof(IStreamNamespacePredicateProvider)} is registered");
}
if (!grainBinding.TryGetValue(WellKnownGrainTypeProperties.StreamIdMapperKey, out var mapperName))
{
throw new KeyNotFoundException(
$"Stream binding for grain type {binding.GrainType} is missing a \"{WellKnownGrainTypeProperties.StreamIdMapperKey}\" value");
}
var streamIdMapper = _serviceProvider.GetServiceByName<IStreamIdMapper>(string.IsNullOrWhiteSpace(mapperName) ? DefaultStreamIdMapper.Name : mapperName);
var subscriber = new StreamSubscriber(binding, streamIdMapper);
newPredicates.Add(new StreamSubscriberPredicate(subscriber, predicate));
}
}
return new Cache(version, newPredicates);
}
/// <summary>
/// Retrieve a map of implicit subscriptionsIds to implicit subscribers, given a stream ID. This method throws an exception if there's no namespace associated with the stream ID.
/// </summary>
/// <param name="streamId">A stream ID.</param>
/// <param name="grainFactory">The grain factory used to get consumer references.</param>
/// <returns>A set of references to implicitly subscribed grains. They are expected to support the streaming consumer extension.</returns>
/// <exception cref="System.ArgumentException">The stream ID doesn't have an associated namespace.</exception>
/// <exception cref="System.InvalidOperationException">Internal invariant violation.</exception>
internal IDictionary<Guid, IStreamConsumerExtension> GetImplicitSubscribers(InternalStreamId streamId, IInternalGrainFactory grainFactory)
{
if (!IsImplicitSubscribeEligibleNameSpace(streamId.GetNamespace()))
{
throw new ArgumentException("The stream ID doesn't have an associated namespace.", nameof(streamId));
}
var entries = GetOrAddImplicitSubscribers(streamId.GetNamespace());
var result = new Dictionary<Guid, IStreamConsumerExtension>();
foreach (var entry in entries)
{
var consumer = MakeConsumerReference(grainFactory, streamId, entry);
Guid subscriptionGuid = MakeSubscriptionGuid(entry.GrainType, streamId);
if (result.ContainsKey(subscriptionGuid))
{
throw new InvalidOperationException(
$"Internal invariant violation: generated duplicate subscriber reference: {consumer}, subscriptionId: {subscriptionGuid}");
}
result.Add(subscriptionGuid, consumer);
}
return result;
}
private HashSet<StreamSubscriber> GetOrAddImplicitSubscribers(string streamNamespace)
{
var cache = GetCache();
if (cache.Namespaces.TryGetValue(streamNamespace, out var result))
{
return result;
}
return cache.Namespaces[streamNamespace] = FindImplicitSubscribers(streamNamespace, cache.Predicates);
}
/// <summary>
/// Determines whether the specified grain is an implicit subscriber of a given stream.
/// </summary>
/// <param name="grainId">The grain identifier.</param>
/// <param name="streamId">The stream identifier.</param>
/// <returns>true if the grain id describes an implicit subscriber of the stream described by the stream id.</returns>
internal bool IsImplicitSubscriber(GrainId grainId, InternalStreamId streamId)
{
return HasImplicitSubscription(streamId.GetNamespace(), grainId.Type);
}
/// <summary>
/// Try to get the implicit subscriptionId.
/// If an implicit subscription exists, return a subscription Id that is unique per grain type, grainId, namespace combination.
/// </summary>
/// <param name="grainId"></param>
/// <param name="streamId"></param>
/// <param name="subscriptionId"></param>
/// <returns></returns>
internal bool TryGetImplicitSubscriptionGuid(GrainId grainId, InternalStreamId streamId, out Guid subscriptionId)
{
subscriptionId = Guid.Empty;
if (!IsImplicitSubscriber(grainId, streamId))
{
return false;
}
// make subscriptionId
subscriptionId = MakeSubscriptionGuid(grainId.Type, streamId);
return true;
}
/// <summary>
/// Create a subscriptionId that is unique per grainId, grainType, namespace combination.
/// </summary>
private Guid MakeSubscriptionGuid(GrainType grainType, InternalStreamId streamId)
{
// next 2 shorts inc guid are from namespace hash
uint namespaceHash = JenkinsHash.ComputeHash(streamId.GetNamespace());
byte[] namespaceHashByes = BitConverter.GetBytes(namespaceHash);
short s1 = BitConverter.ToInt16(namespaceHashByes, 0);
short s2 = BitConverter.ToInt16(namespaceHashByes, 2);
// Tailing 8 bytes of the guid are from the hash of the streamId Guid and a hash of the provider name.
// get streamId guid hash code
uint streamIdGuidHash = JenkinsHash.ComputeHash(streamId.StreamId.Key.Span);
// get provider name hash code
uint providerHash = JenkinsHash.ComputeHash(streamId.ProviderName);
// build guid tailing 8 bytes from grainIdHash and the hash of the provider name.
var tail = new List<byte>();
tail.AddRange(BitConverter.GetBytes(streamIdGuidHash));
tail.AddRange(BitConverter.GetBytes(providerHash));
// make guid.
// - First int is grain type
// - Two shorts from namespace hash
// - 8 byte tail from streamId Guid and provider name hash.
var id = new Guid((int)JenkinsHash.ComputeHash(grainType.ToString()), s1, s2, tail.ToArray());
var result = SubscriptionMarker.MarkAsImplictSubscriptionId(id);
return result;
}
internal static bool IsImplicitSubscribeEligibleNameSpace(string streamNameSpace)
{
return !string.IsNullOrWhiteSpace(streamNameSpace);
}
private bool HasImplicitSubscription(string streamNamespace, GrainType grainType)
{
if (!IsImplicitSubscribeEligibleNameSpace(streamNamespace))
{
return false;
}
var entry = GetOrAddImplicitSubscribers(streamNamespace);
return entry.Any(e => e.GrainType == grainType);
}
/// <summary>
/// Finds all implicit subscribers for the given stream namespace.
/// </summary>
private static HashSet<StreamSubscriber> FindImplicitSubscribers(string streamNamespace, List<StreamSubscriberPredicate> predicates)
{
var result = new HashSet<StreamSubscriber>();
foreach (var predicate in predicates)
{
if (predicate.Predicate.IsMatch(streamNamespace))
{
result.Add(predicate.Subscriber);
}
}
return result;
}
/// <summary>
/// Create a reference to a grain that we expect to support the stream consumer extension.
/// </summary>
/// <param name="grainFactory">The grain factory used to get consumer references.</param>
/// <param name="streamId">The stream ID to use for the grain ID construction.</param>
/// <param name="streamSubscriber">The GrainBindings for the grain to create</param>
/// <returns></returns>
private IStreamConsumerExtension MakeConsumerReference(
IInternalGrainFactory grainFactory,
InternalStreamId streamId,
StreamSubscriber streamSubscriber)
{
var grainId = streamSubscriber.GetGrainId(streamId);
return grainFactory.GetGrain<IStreamConsumerExtension>(grainId);
}
private class StreamSubscriberPredicate
{
public StreamSubscriberPredicate(StreamSubscriber subscriber, IStreamNamespacePredicate predicate)
{
this.Subscriber = subscriber;
this.Predicate = predicate;
}
public StreamSubscriber Subscriber { get; }
public IStreamNamespacePredicate Predicate { get; }
}
private class StreamSubscriber
{
public StreamSubscriber(GrainBindings grainBindings, IStreamIdMapper streamIdMapper)
{
this.grainBindings = grainBindings;
this.streamIdMapper = streamIdMapper;
}
public GrainType GrainType => this.grainBindings.GrainType;
private GrainBindings grainBindings { get; }
private IStreamIdMapper streamIdMapper { get; }
public override bool Equals(object obj)
{
return obj is StreamSubscriber subscriber &&
this.GrainType.Equals(subscriber.GrainType);
}
public override int GetHashCode() => GrainType.GetHashCode();
internal GrainId GetGrainId(InternalStreamId streamId)
{
var grainKeyId = this.streamIdMapper.GetGrainKeyId(this.grainBindings, streamId);
return GrainId.Create(this.GrainType, grainKeyId);
}
}
private class Cache
{
public Cache(MajorMinorVersion version, List<StreamSubscriberPredicate> predicates)
{
this.Version = version;
this.Predicates = predicates;
this.Namespaces = new ConcurrentDictionary<string, HashSet<StreamSubscriber>>();
}
public MajorMinorVersion Version { get; }
public ConcurrentDictionary<string, HashSet<StreamSubscriber>> Namespaces { get; }
public List<StreamSubscriberPredicate> Predicates { get; }
}
}
}
| |
using System.Data;
using System.Collections;
using PCSComUtils.Framework.TableFrame.DS;
using PCSComUtils.PCSExc;
namespace PCSComUtils.Framework.TableFrame.BO
{
public class TableConfigDetailBO
{
public TableConfigDetailBO()
{
//
// TODO: Add constructor logic here
//
}
//**************************************************************************
/// <Description>
/// This method uses to add a record into sys_TableField
/// </Description>
/// <Inputs>
/// sysTableFieldVO
/// </Inputs>
/// <Outputs>
/// newly inserted primarkey value
/// </Outputs>
/// <Returns>
/// TableID
/// </Returns>
/// <Authors>
/// Hoang Trung Son - iSphere software
/// </Authors>
/// <History>
/// 14-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Add(object pobjObjectVO)
{
try
{
sys_TableFieldDS ds = new sys_TableFieldDS();
ds.Add(pobjObjectVO);
}
catch(PCSDBException ex)
{
throw ex;
}
}
//**************************************************************************
/// <Description>
/// This method uses to update data to sys_TableField
/// </Description>
/// <Inputs>
/// sysTableFieldVO
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// Hoang Trung Son - iSphere software
/// </Authors>
/// <History>
/// 14-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Update(object pobjObjectVO)
{
try
{
sys_TableFieldDS ds = new sys_TableFieldDS();
ds.Update(pobjObjectVO);
}
catch(PCSDBException ex)
{
throw ex;
}
}
//**************************************************************************
/// <Description>
/// This method uses to get data from sys_TableField
/// </Description>
/// <Inputs>
/// TableID
/// </Inputs>
/// <Outputs>
/// sysTableFieldVO
/// </Outputs>
/// <Returns>
/// sysTableFieldVO
/// </Returns>
/// <Authors>
/// Hoang Trung Son - iSphere software
/// </Authors>
/// <History>
/// 14-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public object GetObjectVO(int pintTableFieldID)
{
try
{
sys_TableFieldDS ds = new sys_TableFieldDS();
return ds.GetObjectVO(pintTableFieldID);
}
catch(PCSDBException ex)
{
throw ex;
}
}
//**************************************************************************
/// <Description>
/// This method uses to delete data from sys_TableField
/// </Description>
/// <Inputs>
/// pintTableID
/// </Inputs>
/// <Outputs>
/// void
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// Hoang Trung Son - iSphere software
/// </Authors>
/// <History>
/// 14-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Delete(int pintTableFieldID)
{
try
{
sys_TableFieldDS ds = new sys_TableFieldDS();
ds.Delete(pintTableFieldID);
}
catch(PCSDBException ex)
{
throw ex;
}
}
//**************************************************************************
/// <Description>
/// This method uses to get all data from sys_TableGroup
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// Hoang Trung Son - iSphere software
/// </Authors>
/// <History>
/// 14-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataSet List(int pintTableID)
{
try
{
sys_TableFieldDS ds = new sys_TableFieldDS();
return ds.List(pintTableID);
}
catch(PCSDBException ex)
{
throw ex;
}
}
public DataSet List(string pstrTableName)
{
try
{
sys_TableFieldDS ds = new sys_TableFieldDS();
return ds.List(pstrTableName);
}
catch(PCSDBException ex)
{
throw ex;
}
}
//**************************************************************************
/// <Description>
/// List field name
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// Hoang Trung Son - iSphere software
/// </Authors>
/// <History>
/// 14-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataSet ListFieldName(string pstrTableName)
{
try
{
sys_TableFieldDS ds = new sys_TableFieldDS();
return ds.ListFieldName(pstrTableName);
}
catch(PCSDBException ex)
{
throw ex;
}
}
/// <summary>
/// GetInformationSchema
/// </summary>
/// <param name="pstrTableName"></param>
/// <returns></returns>
/// <author>Trada</author>
/// <date>Friday, April 14 2006</date>
public DataSet GetInformationSchema(string pstrTableName)
{
DataSet dstReturn = new DataSet();
sys_TableFieldDS dsTableField = new sys_TableFieldDS();
dstReturn = dsTableField.GetInformationSchema(pstrTableName);
return dstReturn;
}
//**************************************************************************
/// <Description>
/// List field name
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// Hoang Trung Son - iSphere software
/// </Authors>
/// <History>
/// 14-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public ArrayList GetColumnProperty(string pstrTableName,string pstrFieldName)
{
try
{
sys_TableFieldDS ds = new sys_TableFieldDS();
return ds.GetColumnProperty(pstrTableName,pstrFieldName);
}
catch(PCSDBException ex)
{
throw ex;
}
}
public void UpdateDataSet(DataSet dstData)
{
// TODO: Add TableConfigDetailBO.UpdateDataSet implementation
}
/// <summary>
/// UpdateDataSetByTableID
/// </summary>
/// <param name="dstData"></param>
/// <param name="pintTableID"></param>
/// <author>Trada</author>
/// <date>Thursday, Dec 1 2005</date>
public void UpdateDataSetByTableID(DataSet dstData, int pintTableID)
{
sys_TableFieldDS dsSys_TableField = new sys_TableFieldDS();
dsSys_TableField.UpdateDataSetByTableID(dstData, pintTableID);
}
public object GetObjectVO(int pintID, string VOclass)
{
// TODO: Add TableConfigDetailBO.GetObjectVO implementation
return null;
}
public void Delete(object pObjectVO)
{
// TODO: Add TableConfigDetailBO.Delete implementation
}
}
}
| |
/* skybox.cs Skybox Script
* author: SoulofDeity
*
* Features:
* - animation via rotation on y axis, speed adjustable
* - skybox tinting (requires skybox shader)
* - smooth fading color transitioning over a specified
* period of time
* - multiple skyboxes
* - smooth fading skybox transitioning over a specified
* period of time (works in conjunction with color
* fading as well)
*
* Technical Details:
* - uses user layer 8 for the skybox layer, which is
* rendered at a depth of -1
* - gSkybox is the global declaration of the skybox
* transform
* - tSkybox is the global declaration of the target
* skybox transform used when transitioning
* - skyboxColorTrans tells whether or not the skybox
* is transitioning from one color to another. you
* cannot transition to another color while this is
* happening.
* - skyboxTexTrans tells whether or not the skybox
* is transitioning from one set of textures to
* another. you cannot transition to another set of
* textures while this is happening.
* - skybox texture arrays are stored in the order:
* front, back, left, right, top, bottom
***************************************************************/
using UnityEngine;
using System.Collections;
public class skybox : MonoBehaviour {
enum SkyboxType {
DAY = 0,
NIGHT = 1
};
static Transform gSkybox;
static Transform tSkybox = null;
static bool skyboxColorTrans = false;
static bool skyboxTexTrans = false;
public float rotationSpeed = 5.0f;
public Shader shader;
public Color hue = new Color(1.0f, 1.0f, 1.0f, 1.0f);
public Texture[] daySkybox = new Texture[6];
public Texture[] nightSkybox = new Texture[6];
private Mesh cubeMesh;
private float turnVal = 0f;
private Transform skyboxCam;
void Start() {
initCubeMesh();
Camera camera = (Camera)transform.GetComponent("Camera");
camera.clearFlags = CameraClearFlags.Depth;
camera.cullingMask = ~(1 << 8);
camera.depth = 0;
skyboxCam = (new GameObject("skyboxCam")).transform;
Camera cam = (Camera)skyboxCam.gameObject.AddComponent<Camera>();
cam.enabled = true;
cam.clearFlags = CameraClearFlags.SolidColor;
cam.cullingMask = 1 << 8;
cam.depth = -1;
gSkybox = createSkybox("skybox", daySkybox);
gSkybox.parent = skyboxCam;
}
void Update() {
gSkybox.Rotate(new Vector3(0, rotationSpeed * Time.deltaTime, 0));
if (tSkybox) tSkybox.rotation = gSkybox.rotation;
if (Input.GetKeyDown(KeyCode.Z)) {
Transition(SkyboxType.DAY, Color.white, 3.0f);
} else if (Input.GetKeyDown(KeyCode.X)) {
Transition(SkyboxType.DAY, new Color(0.75f, 0.15f, 0.0f, 1.0f), 3.0f);
} else if (Input.GetKeyDown(KeyCode.C)) {
Transition(SkyboxType.NIGHT, new Color(0.75f, 0.75f, 1.0f, 1.0f), 3.0f);
}
}
void LateUpdate()
{
turnVal = Time.deltaTime;
Vector3 rotationValue = new Vector3(Camera.main.transform.rotation.eulerAngles.x, Camera.main.transform.rotation.eulerAngles.y + turnVal, Camera.main.transform.rotation.eulerAngles.z);
skyboxCam.rotation = Quaternion.Euler(rotationValue);
}
IEnumerator crTransition(Color color, float time) {
if (skyboxColorTrans) yield break;
float i = 0.0f;
MeshRenderer gmr = (MeshRenderer)gSkybox.GetComponent("MeshRenderer");
Color start = gmr.materials[0].color;
skyboxColorTrans = true;
while (i <= 1.0f) {
Color tc = Color.Lerp(start, color, i);
gmr.materials[0].color = new Color(tc.r, tc.g, tc.b, gmr.materials[0].color.a);
for (int j = 1; j < 6; j++)
gmr.materials[j].color = gmr.materials[0].color;
i += Time.deltaTime / time;
yield return null;
}
skyboxColorTrans = false;
}
IEnumerator crTransition(SkyboxType type, float time) {
if (skyboxTexTrans) yield break;
Texture[] textures;
switch (type) {
case SkyboxType.NIGHT: {
textures = nightSkybox;
break;
}
default: {
textures = daySkybox;
break;
}
}
tSkybox = createSkybox("skybox", textures);
tSkybox.parent = gSkybox.parent;
MeshRenderer gmr = (MeshRenderer)gSkybox.GetComponent("MeshRenderer");
MeshRenderer tmr = (MeshRenderer)tSkybox.GetComponent("MeshRenderer");
Color color = new Color(
gmr.materials[0].color.r,
gmr.materials[0].color.g,
gmr.materials[0].color.b,
0.0f);
for (int i = 0; i < 6; i++)
tmr.materials[i].color = color;
skyboxTexTrans = true;
float j = 0.0f;
while (j <= 1.0f) {
gmr.materials[0].color = new Color(
gmr.materials[0].color.r,
gmr.materials[0].color.g,
gmr.materials[0].color.b,
1.0f - j);
tmr.materials[0].color = new Color(
gmr.materials[0].color.r,
gmr.materials[0].color.g,
gmr.materials[0].color.b,
j);
for (int i = 1; i < 6; i++) {
gmr.materials[i].color = gmr.materials[0].color;
tmr.materials[i].color = tmr.materials[0].color;
}
j += Time.deltaTime / time;
yield return null;
}
tmr.materials[0].color = new Color(
gmr.materials[0].color.r,
gmr.materials[0].color.g,
gmr.materials[0].color.b,
1.0f);
for (int i = 1; i < 6; i++)
tmr.materials[i].color = tmr.materials[0].color;
GameObject.Destroy(gSkybox.gameObject);
gSkybox = tSkybox;
tSkybox = null;
skyboxTexTrans = false;
}
void Transition(Color color, float time) {
StartCoroutine(crTransition(color, time));
}
void Transition(SkyboxType type, float time) {
StartCoroutine(crTransition(type, time));
}
void Transition(SkyboxType type, Color color, float time) {
StartCoroutine(crTransition(color, time));
StartCoroutine(crTransition(type, time));
}
Transform createSkybox(string name, Texture[] textures) {
Transform sb = (new GameObject(name)).transform;
sb.gameObject.layer = 8;
MeshFilter mf = (MeshFilter)sb.gameObject.AddComponent<MeshFilter>();
mf.mesh = cubeMesh;
MeshRenderer mr = (MeshRenderer)sb.gameObject.AddComponent<MeshRenderer>();
mr.enabled = true;
mr.castShadows = false;
mr.receiveShadows = false;
mr.materials = new Material[6];
for (int i = 0; i < 6; i++) {
mr.materials[i] = new Material(shader);
mr.materials[i].shader = shader;
mr.materials[i].color = hue;
mr.materials[i].mainTexture = textures[i];
}
return sb;
}
void initCubeMesh() {
cubeMesh = new Mesh();
cubeMesh.vertices = new Vector3[] {
new Vector3(-1,-1, 1), // front
new Vector3(-1, 1, 1),
new Vector3( 1, 1, 1),
new Vector3( 1,-1, 1),
new Vector3(-1,-1,-1), // back
new Vector3(-1, 1,-1),
new Vector3( 1, 1,-1),
new Vector3( 1,-1,-1),
new Vector3(-1,-1,-1), // left
new Vector3(-1, 1,-1),
new Vector3(-1, 1, 1),
new Vector3(-1,-1, 1),
new Vector3( 1,-1,-1), // right
new Vector3( 1, 1,-1),
new Vector3( 1, 1, 1),
new Vector3( 1,-1, 1),
new Vector3(-1, 1,-1), // top
new Vector3(-1, 1, 1),
new Vector3( 1, 1, 1),
new Vector3( 1, 1,-1),
new Vector3(-1,-1,-1), // bottom
new Vector3(-1,-1, 1),
new Vector3( 1,-1, 1),
new Vector3( 1,-1,-1)
};
cubeMesh.uv = new Vector2[] {
new Vector2(0, 0), // front
new Vector2(0, 1),
new Vector2(1, 1),
new Vector2(1, 0),
new Vector2(1, 0), // back
new Vector2(1, 1),
new Vector2(0, 1),
new Vector2(0, 0),
new Vector2(0, 0), // left
new Vector2(0, 1),
new Vector2(1, 1),
new Vector2(1, 0),
new Vector2(1, 0), // right
new Vector2(1, 1),
new Vector2(0, 1),
new Vector2(0, 0),
new Vector2(1, 0), // top
new Vector2(1, 1),
new Vector2(0, 1),
new Vector2(0, 0),
new Vector2(1, 1), // bottom
new Vector2(1, 0),
new Vector2(0, 0),
new Vector2(0, 1)
};
cubeMesh.subMeshCount = 6;
cubeMesh.SetTriangles(new int[] { 0, 1, 2, 2, 3, 0}, 0); // front
cubeMesh.SetTriangles(new int[] { 6, 5, 4, 4, 7, 6}, 1); // back
cubeMesh.SetTriangles(new int[] { 8, 9,10,10,11, 8}, 2); // left
cubeMesh.SetTriangles(new int[] {14,13,12,12,15,14}, 3); // right
cubeMesh.SetTriangles(new int[] {18,17,16,16,19,18}, 4); // top
cubeMesh.SetTriangles(new int[] {20,21,22,22,23,20}, 5); // bottom
cubeMesh.RecalculateNormals();
cubeMesh.Optimize();
}
}
| |
using Lucene.Net.Store;
using Lucene.Net.Support.Threading;
using Lucene.Net.Util;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Threading;
using JCG = J2N.Collections.Generic;
using Directory = Lucene.Net.Store.Directory;
using Lucene.Net.Diagnostics;
namespace Lucene.Net.Replicator
{
/*
* 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 client which monitors and obtains new revisions from a <see cref="IReplicator"/>.
/// It can be used to either periodically check for updates by invoking
/// <see cref="StartUpdateThread"/>, or manually by calling <see cref="UpdateNow()"/>.
/// <para/>
/// Whenever a new revision is available, the <see cref="RequiredFiles"/> are
/// copied to the <see cref="Directory"/> specified by <see cref="PerSessionDirectoryFactory"/> and
/// a handler is notified.
/// </summary>
/// <remarks>
/// @lucene.experimental
/// </remarks>
public class ReplicationClient : IDisposable
{
//Note: LUCENENET specific, .NET does not work with Threads in the same way as Java does, so we mimic the same behavior using the ThreadPool instead.
private class ReplicationThread
{
private readonly Action doUpdate;
private readonly Action<Exception> handleException;
private readonly ReentrantLock @lock;
private readonly object controlLock = new object();
private readonly long interval;
private readonly AutoResetEvent handle = new AutoResetEvent(false);
private AutoResetEvent stopHandle;
/// <summary>
/// Gets or sets the name
/// </summary>
public string Name { get; private set; }
/// <summary>
///
/// </summary>
/// <param name="intervalMillis">The interval in milliseconds.</param>
/// <param name="threadName">The thread name.</param>
/// <param name="doUpdate">A delegate to call to perform the update.</param>
/// <param name="handleException">A delegate to call to handle an exception.</param>
/// <param name="lock"></param>
public ReplicationThread(long intervalMillis, string threadName, Action doUpdate, Action<Exception> handleException, ReentrantLock @lock)
{
this.doUpdate = doUpdate;
this.handleException = handleException;
this.@lock = @lock;
Name = threadName;
this.interval = intervalMillis;
}
/// <summary>
///
/// </summary>
public bool IsAlive { get; private set; }
/// <summary>
///
/// </summary>
public void Start()
{
lock (controlLock)
{
if (IsAlive)
return;
IsAlive = true;
}
RegisterWait(interval);
}
/// <summary>
///
/// </summary>
public void Stop()
{
lock (controlLock)
{
if (!IsAlive)
return;
IsAlive = false;
}
stopHandle = new AutoResetEvent(false);
//NOTE: Execute any outstanding, this execution will terminate almost instantaniously if it's not already running.
ExecuteImmediately();
stopHandle.WaitOne();
stopHandle = null;
}
/// <summary>
/// Executes the next cycle of work immediately
/// </summary>
public void ExecuteImmediately()
{
handle.Set();
}
private void RegisterWait(long timeout)
{
//NOTE: We don't care about timedout as it can either be because we was requested to run immidiately or stop.
if (IsAlive)
ThreadPool.RegisterWaitForSingleObject(handle, (state, timedout) => Run(), null, timeout, true);
else
SignalStop();
}
private void SignalStop()
{
if (stopHandle != null)
stopHandle.Set();
}
private void Run()
{
if (!IsAlive)
{
SignalStop();
return;
}
Stopwatch timer = Stopwatch.StartNew();
@lock.Lock();
try
{
doUpdate();
}
catch (Exception exception)
{
handleException(exception);
}
finally
{
@lock.Unlock();
timer.Stop();
long driftAdjusted = Math.Max(interval - timer.ElapsedMilliseconds, 0);
if (IsAlive)
RegisterWait(driftAdjusted);
else
SignalStop();
}
}
}
// LUCENENET specific - de-nested the IReplicationHandler and
// ISourceDirectoryFactory interfaces.
/// <summary>
/// The component name to use with <see cref="Util.InfoStream.IsEnabled"/>
/// </summary>
public const string INFO_STREAM_COMPONENT = "ReplicationThread";
private readonly IReplicator replicator;
private readonly IReplicationHandler handler;
private readonly ISourceDirectoryFactory factory;
private readonly byte[] copyBuffer = new byte[16384];
private readonly ReentrantLock updateLock = new ReentrantLock();
private ReplicationThread updateThread;
private bool disposed = false;
private InfoStream infoStream = InfoStream.Default;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="replicator">The <see cref="IReplicator"/> used for checking for updates</param>
/// <param name="handler">The <see cref="IReplicationHandler"/> notified when new revisions are ready</param>
/// <param name="factory">The <see cref="ISourceDirectoryFactory"/> for returning a <see cref="Directory"/> for a given source and session</param>
public ReplicationClient(IReplicator replicator, IReplicationHandler handler, ISourceDirectoryFactory factory)
{
this.replicator = replicator;
this.handler = handler;
this.factory = factory;
}
/// <exception cref="IOException"></exception>
private void CopyBytes(IndexOutput output, Stream input)
{
int numBytes;
while ((numBytes = input.Read(copyBuffer, 0, copyBuffer.Length)) > 0)
{
output.WriteBytes(copyBuffer, 0, numBytes);
}
}
/// <exception cref="IOException"></exception>
private void DoUpdate()
{
SessionToken session = null;
Dictionary<string, Directory> sourceDirectory = new Dictionary<string, Directory>();
Dictionary<string, IList<string>> copiedFiles = new Dictionary<string, IList<string>>();
bool notify = false;
try
{
string version = handler.CurrentVersion;
session = replicator.CheckForUpdate(version);
WriteToInfoStream(string.Format("doUpdate(): handlerVersion={0} session={1}", version, session));
if (session == null)
return;
IDictionary<string, IList<RevisionFile>> requiredFiles = RequiredFiles(session.SourceFiles);
WriteToInfoStream(string.Format("doUpdate(): handlerVersion={0} session={1}", version, session));
foreach (KeyValuePair<string, IList<RevisionFile>> pair in requiredFiles)
{
string source = pair.Key;
Directory directory = factory.GetDirectory(session.Id, source);
sourceDirectory.Add(source, directory);
List<string> cpFiles = new List<string>();
copiedFiles.Add(source, cpFiles);
foreach (RevisionFile file in pair.Value)
{
if (disposed)
{
// if we're closed, abort file copy
WriteToInfoStream("doUpdate(): detected client was closed); abort file copy");
return;
}
Stream input = null;
IndexOutput output = null;
try
{
input = replicator.ObtainFile(session.Id, source, file.FileName);
output = directory.CreateOutput(file.FileName, IOContext.DEFAULT);
CopyBytes(output, input);
cpFiles.Add(file.FileName);
// TODO add some validation, on size / checksum
}
finally
{
IOUtils.Dispose(input, output);
}
}
// only notify if all required files were successfully obtained.
notify = true;
}
}
finally
{
if (session != null)
{
try
{
replicator.Release(session.Id);
}
finally
{
if (!notify)
{
// cleanup after ourselves
IOUtils.Dispose(sourceDirectory.Values);
factory.CleanupSession(session.Id);
}
}
}
}
// notify outside the try-finally above, so the session is released sooner.
// the handler may take time to finish acting on the copied files, but the
// session itself is no longer needed.
try
{
if (notify && !disposed)
{ // no use to notify if we are closed already
handler.RevisionReady(session.Version, session.SourceFiles, new ReadOnlyDictionary<string, IList<string>>(copiedFiles), sourceDirectory);
}
}
finally
{
IOUtils.Dispose(sourceDirectory.Values);
//TODO: Resharper Message, Expression is always true -> Verify and if so then we can remove the null check.
if (session != null)
{
factory.CleanupSession(session.Id);
}
}
}
/// <summary>Throws <see cref="ObjectDisposedException"/> if the client has already been disposed.</summary>
protected void EnsureOpen()
{
if (!disposed)
return;
throw new ObjectDisposedException("this update client has already been closed");
}
// LUCENENET specific Utility Method
private void WriteToInfoStream(string message)
{
if (infoStream.IsEnabled(INFO_STREAM_COMPONENT))
infoStream.Message(INFO_STREAM_COMPONENT, message);
}
/// <summary>
/// Called when an exception is hit by the replication thread. The default
/// implementation prints the full stacktrace to the <see cref="Util.InfoStream"/> set in
/// <see cref="InfoStream"/>, or the <see cref="Util.InfoStream.Default"/>
/// one. You can override to log the exception elsewhere.
/// </summary>
/// <remarks>
/// <b>NOTE:</b> If you override this method to throw the exception further,
/// the replication thread will be terminated. The only way to restart it is to
/// call <see cref="StopUpdateThread"/> followed by
/// <see cref="StartUpdateThread"/>.
/// </remarks>
protected virtual void HandleUpdateException(Exception exception)
{
WriteToInfoStream(string.Format("an error occurred during revision update: {0}", exception));
}
/// <summary>
/// Returns the files required for replication. By default, this method returns
/// all files that exist in the new revision, but not in the handler.
/// </summary>
protected virtual IDictionary<string, IList<RevisionFile>> RequiredFiles(IDictionary<string, IList<RevisionFile>> newRevisionFiles)
{
IDictionary<string, IList<RevisionFile>> handlerRevisionFiles = handler.CurrentRevisionFiles;
if (handlerRevisionFiles == null)
return newRevisionFiles;
Dictionary<string, IList<RevisionFile>> requiredFiles = new Dictionary<string, IList<RevisionFile>>();
foreach (var e in handlerRevisionFiles)
{
// put the handler files in a Set, for faster contains() checks later
ISet<string> handlerFiles = new JCG.HashSet<string>();
foreach (RevisionFile file in e.Value)
{
handlerFiles.Add(file.FileName);
}
// make sure to preserve revisionFiles order
List<RevisionFile> res = new List<RevisionFile>();
string source = e.Key;
if (Debugging.AssertsEnabled) Debugging.Assert(newRevisionFiles.ContainsKey(source), () => string.Format("source not found in newRevisionFiles: {0}", newRevisionFiles));
foreach (RevisionFile file in newRevisionFiles[source])
{
if (!handlerFiles.Contains(file.FileName))
{
res.Add(file);
}
}
requiredFiles[source] = res;
}
return requiredFiles;
}
protected virtual void Dispose(bool disposing)
{
if (disposed || !disposing)
return;
StopUpdateThread();
disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Start the update thread with the specified interval in milliseconds. For
/// debugging purposes, you can optionally set the name to set on
/// <see cref="ReplicationThread.Name"/>. If you pass <c>null</c>, a default name
/// will be set.
/// </summary>
/// <exception cref="InvalidOperationException"> if the thread has already been started </exception>
public virtual void StartUpdateThread(long intervalMillis, string threadName)
{
EnsureOpen();
if (updateThread != null && updateThread.IsAlive)
throw new InvalidOperationException("cannot start an update thread when one is running, must first call 'stopUpdateThread()'");
threadName = threadName == null ? INFO_STREAM_COMPONENT : "ReplicationThread-" + threadName;
updateThread = new ReplicationThread(intervalMillis, threadName, DoUpdate, HandleUpdateException, updateLock);
updateThread.Start();
// we rely on isAlive to return true in isUpdateThreadAlive, assert to be on the safe side
if (Debugging.AssertsEnabled) Debugging.Assert(updateThread.IsAlive, "updateThread started but not alive?");
}
/// <summary>
/// Stop the update thread. If the update thread is not running, silently does
/// nothing. This method returns after the update thread has stopped.
/// </summary>
public virtual void StopUpdateThread()
{
// this will trigger the thread to terminate if it awaits the lock.
// otherwise, if it's in the middle of replication, we wait for it to
// stop.
if (updateThread != null)
updateThread.Stop();
updateThread = null;
}
/// <summary>
/// Returns true if the update thread is alive. The update thread is alive if
/// it has been <see cref="StartUpdateThread"/> and not
/// <see cref="StopUpdateThread"/>, as well as didn't hit an error which
/// caused it to terminate (i.e. <see cref="HandleUpdateException"/>
/// threw the exception further).
/// </summary>
public virtual bool IsUpdateThreadAlive => updateThread != null && updateThread.IsAlive;
public override string ToString()
{
if (updateThread == null)
return "ReplicationClient";
return string.Format("ReplicationClient ({0})", updateThread.Name);
}
/// <summary>
/// Executes the update operation immediately, regardless if an update thread
/// is running or not.
/// </summary>
/// <exception cref="IOException"></exception>
public virtual void UpdateNow()
{
EnsureOpen();
if (updateThread != null)
{
//NOTE: We have a worker running, we use that to perform the work instead by requesting it to run
// it's cycle immidiately.
updateThread.ExecuteImmediately();
return;
}
//NOTE: We don't have a worker running, so we just do the work.
updateLock.Lock();
try
{
DoUpdate();
}
finally
{
updateLock.Unlock();
}
}
/// <summary>
/// Gets or sets the <see cref="Util.InfoStream"/> to use for logging messages.
/// </summary>
public virtual InfoStream InfoStream
{
get => infoStream;
set => infoStream = value ?? InfoStream.NO_OUTPUT;
}
}
/// <summary>Handler for revisions obtained by the client.</summary>
//Note: LUCENENET specific denesting of interface
public interface IReplicationHandler
{
/// <summary>Returns the current revision files held by the handler.</summary>
string CurrentVersion { get; }
/// <summary>Returns the current revision version held by the handler.</summary>
IDictionary<string, IList<RevisionFile>> CurrentRevisionFiles { get; }
/// <summary>
/// Called when a new revision was obtained and is available (i.e. all needed files were successfully copied).
/// </summary>
/// <param name="version">The version of the <see cref="IRevision"/> that was copied</param>
/// <param name="revisionFiles"> The files contained by this <see cref="IRevision"/></param>
/// <param name="copiedFiles">The files that were actually copied</param>
/// <param name="sourceDirectory">A mapping from a source of files to the <see cref="Directory"/> they were copied into</param>
/// <exception cref="IOException"/>
void RevisionReady(string version,
IDictionary<string, IList<RevisionFile>> revisionFiles,
IDictionary<string, IList<string>> copiedFiles,
IDictionary<string, Directory> sourceDirectory);
}
/// <summary>
/// Resolves a session and source into a <see cref="Directory"/> to use for copying
/// the session files to.
/// </summary>
//Note: LUCENENET specific denesting of interface
public interface ISourceDirectoryFactory
{
/// <summary>
/// Returns the <see cref="Directory"/> to use for the given session and source.
/// Implementations may e.g. return different directories for different
/// sessions, or the same directory for all sessions. In that case, it is
/// advised to clean the directory before it is used for a new session.
/// </summary>
/// <exception cref="IOException"></exception>
/// <seealso cref="CleanupSession(string)"/>
Directory GetDirectory(string sessionId, string source); //throws IOException;
/// <summary>
/// Called to denote that the replication actions for this session were finished and the directory is no longer needed.
/// </summary>
/// <exception cref="IOException"></exception>
void CleanupSession(string sessionId);
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Shared.Preview;
using Microsoft.CodeAnalysis.Editor.Shared.Tagging;
using Microsoft.CodeAnalysis.Editor.UnitTests.Squiggles;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Differencing;
using Microsoft.VisualStudio.Text.Tagging;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Preview
{
public class PreviewWorkspaceTests
{
[Fact, Trait(Traits.Editor, Traits.Editors.Preview)]
public void TestPreviewCreationDefault()
{
using (var previewWorkspace = new PreviewWorkspace())
{
Assert.NotNull(previewWorkspace.CurrentSolution);
}
}
[Fact, Trait(Traits.Editor, Traits.Editors.Preview)]
public void TestPreviewCreationWithExplicitHostServices()
{
var assembly = typeof(ISolutionCrawlerRegistrationService).Assembly;
using (var previewWorkspace = new PreviewWorkspace(MefHostServices.Create(MefHostServices.DefaultAssemblies.Concat(assembly))))
{
Assert.NotNull(previewWorkspace.CurrentSolution);
}
}
[Fact, Trait(Traits.Editor, Traits.Editors.Preview)]
public void TestPreviewCreationWithSolution()
{
using (var custom = new AdhocWorkspace())
using (var previewWorkspace = new PreviewWorkspace(custom.CurrentSolution))
{
Assert.NotNull(previewWorkspace.CurrentSolution);
}
}
[Fact, Trait(Traits.Editor, Traits.Editors.Preview)]
public void TestPreviewAddRemoveProject()
{
using (var previewWorkspace = new PreviewWorkspace())
{
var solution = previewWorkspace.CurrentSolution;
var project = solution.AddProject("project", "project.dll", LanguageNames.CSharp);
Assert.True(previewWorkspace.TryApplyChanges(project.Solution));
var newSolution = previewWorkspace.CurrentSolution.RemoveProject(project.Id);
Assert.True(previewWorkspace.TryApplyChanges(newSolution));
Assert.Equal(0, previewWorkspace.CurrentSolution.ProjectIds.Count);
}
}
[Fact, Trait(Traits.Editor, Traits.Editors.Preview)]
public void TestPreviewProjectChanges()
{
using (var previewWorkspace = new PreviewWorkspace())
{
var solution = previewWorkspace.CurrentSolution;
var project = solution.AddProject("project", "project.dll", LanguageNames.CSharp);
Assert.True(previewWorkspace.TryApplyChanges(project.Solution));
var addedSolution = previewWorkspace.CurrentSolution.Projects.First()
.AddMetadataReference(TestReferences.NetFx.v4_0_30319.mscorlib)
.AddDocument("document", "").Project.Solution;
Assert.True(previewWorkspace.TryApplyChanges(addedSolution));
Assert.Equal(1, previewWorkspace.CurrentSolution.Projects.First().MetadataReferences.Count);
Assert.Equal(1, previewWorkspace.CurrentSolution.Projects.First().DocumentIds.Count);
var text = "class C {}";
var changedSolution = previewWorkspace.CurrentSolution.Projects.First().Documents.First().WithText(SourceText.From(text)).Project.Solution;
Assert.True(previewWorkspace.TryApplyChanges(changedSolution));
Assert.Equal(previewWorkspace.CurrentSolution.Projects.First().Documents.First().GetTextAsync().Result.ToString(), text);
var removedSolution = previewWorkspace.CurrentSolution.Projects.First()
.RemoveMetadataReference(previewWorkspace.CurrentSolution.Projects.First().MetadataReferences[0])
.RemoveDocument(previewWorkspace.CurrentSolution.Projects.First().DocumentIds[0]).Solution;
Assert.True(previewWorkspace.TryApplyChanges(removedSolution));
Assert.Equal(0, previewWorkspace.CurrentSolution.Projects.First().MetadataReferences.Count);
Assert.Equal(0, previewWorkspace.CurrentSolution.Projects.First().DocumentIds.Count);
}
}
[WorkItem(923121)]
[Fact, Trait(Traits.Editor, Traits.Editors.Preview)]
public void TestPreviewOpenCloseFile()
{
using (var previewWorkspace = new PreviewWorkspace())
{
var solution = previewWorkspace.CurrentSolution;
var project = solution.AddProject("project", "project.dll", LanguageNames.CSharp);
var document = project.AddDocument("document", "");
Assert.True(previewWorkspace.TryApplyChanges(document.Project.Solution));
previewWorkspace.OpenDocument(document.Id);
Assert.Equal(1, previewWorkspace.GetOpenDocumentIds().Count());
Assert.True(previewWorkspace.IsDocumentOpen(document.Id));
previewWorkspace.CloseDocument(document.Id);
Assert.Equal(0, previewWorkspace.GetOpenDocumentIds().Count());
Assert.False(previewWorkspace.IsDocumentOpen(document.Id));
}
}
[Fact, Trait(Traits.Editor, Traits.Editors.Preview)]
public void TestPreviewServices()
{
using (var previewWorkspace = new PreviewWorkspace(MefV1HostServices.Create(TestExportProvider.ExportProviderWithCSharpAndVisualBasic.AsExportProvider())))
{
var service = previewWorkspace.Services.GetService<ISolutionCrawlerRegistrationService>();
Assert.True(service is PreviewSolutionCrawlerRegistrationService);
var persistentService = previewWorkspace.Services.GetService<IPersistentStorageService>();
Assert.NotNull(persistentService);
var storage = persistentService.GetStorage(previewWorkspace.CurrentSolution);
Assert.True(storage is NoOpPersistentStorage);
}
}
[WorkItem(923196)]
[Fact, Trait(Traits.Editor, Traits.Editors.Preview)]
public void TestPreviewDiagnostic()
{
var diagnosticService = TestExportProvider.ExportProviderWithCSharpAndVisualBasic.GetExportedValue<IDiagnosticAnalyzerService>() as IDiagnosticUpdateSource;
var taskSource = new TaskCompletionSource<DiagnosticsUpdatedArgs>();
diagnosticService.DiagnosticsUpdated += (s, a) => taskSource.TrySetResult(a);
using (var previewWorkspace = new PreviewWorkspace(MefV1HostServices.Create(TestExportProvider.ExportProviderWithCSharpAndVisualBasic.AsExportProvider())))
{
var solution = previewWorkspace.CurrentSolution
.AddProject("project", "project.dll", LanguageNames.CSharp)
.AddDocument("document", "class { }")
.Project
.Solution;
Assert.True(previewWorkspace.TryApplyChanges(solution));
previewWorkspace.OpenDocument(previewWorkspace.CurrentSolution.Projects.First().DocumentIds[0]);
previewWorkspace.EnableDiagnostic();
// wait 20 seconds
taskSource.Task.Wait(20000);
if (!taskSource.Task.IsCompleted)
{
// something is wrong
FatalError.Report(new System.Exception("not finished after 20 seconds"));
}
var args = taskSource.Task.Result;
Assert.True(args.Diagnostics.Length > 0);
}
}
[Fact]
public void TestPreviewDiagnosticTagger()
{
using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines("class { }"))
using (var previewWorkspace = new PreviewWorkspace(workspace.CurrentSolution))
{
//// preview workspace and owner of the solution now share solution and its underlying text buffer
var hostDocument = workspace.Projects.First().Documents.First();
//// enable preview diagnostics
previewWorkspace.EnableDiagnostic();
var spans = SquiggleUtilities.GetErrorSpans(workspace);
Assert.Equal(1, spans.Count);
}
}
[Fact]
public void TestPreviewDiagnosticTaggerInPreviewPane()
{
using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines("class { }"))
{
// set up listener to wait until diagnostic finish running
var diagnosticService = workspace.ExportProvider.GetExportedValue<IDiagnosticService>() as DiagnosticService;
// no easy way to setup waiter. kind of hacky way to setup waiter
var source = new CancellationTokenSource();
var taskSource = new TaskCompletionSource<DiagnosticsUpdatedArgs>();
diagnosticService.DiagnosticsUpdated += (s, a) =>
{
source.Cancel();
source = new CancellationTokenSource();
var cancellationToken = source.Token;
Task.Delay(2000, cancellationToken).ContinueWith(t => taskSource.TrySetResult(a), CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Current);
};
var hostDocument = workspace.Projects.First().Documents.First();
// make a change to remove squiggle
var oldDocument = workspace.CurrentSolution.GetDocument(hostDocument.Id);
var oldText = oldDocument.GetTextAsync().Result;
var newDocument = oldDocument.WithText(oldText.WithChanges(new TextChange(new TextSpan(0, oldText.Length), "class C { }")));
// create a diff view
var previewFactoryService = workspace.ExportProvider.GetExportedValue<IPreviewFactoryService>();
var diffView = (IWpfDifferenceViewer)previewFactoryService.CreateChangedDocumentPreviewViewAsync(oldDocument, newDocument, CancellationToken.None).PumpingWaitResult();
var foregroundService = workspace.GetService<IForegroundNotificationService>();
var optionsService = workspace.Services.GetService<IOptionService>();
var waiter = new ErrorSquiggleWaiter();
var listeners = AsynchronousOperationListener.CreateListeners(FeatureAttribute.ErrorSquiggles, waiter);
// set up tagger for both buffers
var leftBuffer = diffView.LeftView.BufferGraph.GetTextBuffers(t => t.ContentType.IsOfType(ContentTypeNames.CSharpContentType)).First();
var leftProvider = new DiagnosticsSquiggleTaggerProvider(optionsService, diagnosticService, foregroundService, listeners);
var leftTagger = leftProvider.CreateTagger<IErrorTag>(leftBuffer);
using (var leftDisposable = leftTagger as IDisposable)
{
var rightBuffer = diffView.RightView.BufferGraph.GetTextBuffers(t => t.ContentType.IsOfType(ContentTypeNames.CSharpContentType)).First();
var rightProvider = new DiagnosticsSquiggleTaggerProvider(optionsService, diagnosticService, foregroundService, listeners);
var rightTagger = rightProvider.CreateTagger<IErrorTag>(rightBuffer);
using (var rightDisposable = rightTagger as IDisposable)
{
// wait up to 20 seconds for diagnostics
taskSource.Task.Wait(20000);
if (!taskSource.Task.IsCompleted)
{
// something is wrong
FatalError.Report(new System.Exception("not finished after 20 seconds"));
}
// wait taggers
waiter.CreateWaitTask().PumpingWait();
// check left buffer
var leftSnapshot = leftBuffer.CurrentSnapshot;
var leftSpans = leftTagger.GetTags(new NormalizedSnapshotSpanCollection(new SnapshotSpan(leftSnapshot, 0, leftSnapshot.Length))).ToList();
Assert.Equal(1, leftSpans.Count);
// check right buffer
var rightSnapshot = rightBuffer.CurrentSnapshot;
var rightSpans = rightTagger.GetTags(new NormalizedSnapshotSpanCollection(new SnapshotSpan(rightSnapshot, 0, rightSnapshot.Length))).ToList();
Assert.Equal(0, rightSpans.Count);
}
}
}
}
private class ErrorSquiggleWaiter : AsynchronousOperationListener { }
}
}
| |
/*
Copyright (c) 2013 Mitch Thompson
Extended by Harald Lurger (2013) (Process to Sprites)
Standard MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
public static class TexturePackerExtensions{
public static Rect TPHashtableToRect(this Hashtable table){
return new Rect((float)table["x"], (float)table["y"], (float)table["w"], (float)table["h"]);
}
public static Vector2 TPHashtableToVector2(this Hashtable table){
if(table.ContainsKey("x") && table.ContainsKey("y")){
return new Vector2((float)table["x"], (float)table["y"]);
}
else{
return new Vector2((float)table["w"], (float)table["h"]);
}
}
public static Vector2 TPVector3toVector2(this Vector3 vec){
return new Vector2(vec.x, vec.y);
}
public static bool IsTexturePackerTable(this Hashtable table){
if(table == null) return false;
if(table.ContainsKey("meta")){
Hashtable metaTable = (Hashtable)table["meta"];
if(metaTable.ContainsKey("app")){
return true;
// if((string)metaTable["app"] == "http://www.texturepacker.com"){
// return true;
// }
}
}
return false;
}
}
public class TexturePacker{
public class PackedFrame{
public string name;
public Rect frame;
public Rect spriteSourceSize;
public Vector2 sourceSize;
public bool rotated;
public bool trimmed;
Vector2 atlasSize;
public PackedFrame(string name, Vector2 atlasSize, Hashtable table){
this.name = name;
this.atlasSize = atlasSize;
frame = ((Hashtable)table["frame"]).TPHashtableToRect();
spriteSourceSize = ((Hashtable)table["spriteSourceSize"]).TPHashtableToRect();
sourceSize = ((Hashtable)table["sourceSize"]).TPHashtableToVector2();
rotated = (bool)table["rotated"];
trimmed = (bool)table["trimmed"];
}
public Mesh BuildBasicMesh(float scale, Color32 defaultColor){
return BuildBasicMesh(scale, defaultColor, Quaternion.identity);
}
public Mesh BuildBasicMesh(float scale, Color32 defaultColor, Quaternion rotation){
Mesh m = new Mesh();
Vector3[] verts = new Vector3[4];
Vector2[] uvs = new Vector2[4];
Color32[] colors = new Color32[4];
if(!rotated){
verts[0] = new Vector3(frame.x,frame.y,0);
verts[1] = new Vector3(frame.x,frame.y+frame.height,0);
verts[2] = new Vector3(frame.x+frame.width,frame.y+frame.height,0);
verts[3] = new Vector3(frame.x+frame.width,frame.y,0);
}
else{
verts[0] = new Vector3(frame.x,frame.y,0);
verts[1] = new Vector3(frame.x,frame.y+frame.width,0);
verts[2] = new Vector3(frame.x+frame.height,frame.y+frame.width,0);
verts[3] = new Vector3(frame.x+frame.height,frame.y,0);
}
uvs[0] = verts[0].TPVector3toVector2();
uvs[1] = verts[1].TPVector3toVector2();
uvs[2] = verts[2].TPVector3toVector2();
uvs[3] = verts[3].TPVector3toVector2();
for(int i = 0; i < uvs.Length; i++){
uvs[i].x /= atlasSize.x;
uvs[i].y /= atlasSize.y;
uvs[i].y = 1.0f - uvs[i].y;
}
if(rotated){
verts[3] = new Vector3(frame.x,frame.y,0);
verts[0] = new Vector3(frame.x,frame.y+frame.height,0);
verts[1] = new Vector3(frame.x+frame.width,frame.y+frame.height,0);
verts[2] = new Vector3(frame.x+frame.width,frame.y,0);
}
//v-flip
for(int i = 0; i < verts.Length; i++){
verts[i].y = atlasSize.y - verts[i].y;
}
//original origin
for(int i = 0; i < verts.Length; i++){
verts[i].x -= frame.x - spriteSourceSize.x + (sourceSize.x/2.0f);
verts[i].y -= (atlasSize.y - frame.y) - (sourceSize.y - spriteSourceSize.y) + (sourceSize.y/2.0f);
}
//scaler
for(int i = 0; i < verts.Length; i++){
verts[i] *= scale;
}
//rotator
if(rotation != Quaternion.identity){
for(int i = 0; i < verts.Length; i++){
verts[i] = rotation * verts[i];
}
}
for(int i = 0; i < colors.Length; i++){
colors[i] = defaultColor;
}
m.vertices = verts;
m.uv = uvs;
m.colors32 = colors;
m.triangles = new int[6]{0,3,1,1,3,2};
m.RecalculateNormals();
m.RecalculateBounds();
m.name = name;
return m;
}
public SpriteMetaData BuildBasicSprite(float scale, Color32 defaultColor){
SpriteMetaData smd = new SpriteMetaData();
Rect rect;
if(!rotated){
rect = this.frame;
}
else
{
rect = new Rect(frame.x,frame.y,frame.height,frame.width);
}
/* Look if frame is outside from texture */
if( (frame.x + frame.width) > atlasSize.x || (frame.y + frame.height) > atlasSize.y ||
(frame.x < 0 || frame.y < 0))
{
Debug.Log(this.name + " is outside from texture! Sprite is ignored!");
smd.name = "IGNORE_SPRITE";
return smd;
}
//calculate Height
/* Example: Texture: 1000 Width x 500 height
* Sprite.Recht(0,0,100,100) --> Sprite is on the bottom left
*/
rect.y = atlasSize.y - frame.y - rect.height;
smd.rect = rect;
smd.alignment = (int)SpriteAlignment.Center;
smd.name = name;
smd.pivot = new Vector2(frame.width/2, frame.height/2);
return smd;
}
}
public class MetaData{
public string image;
public string format;
public Vector2 size;
public float scale;
public string smartUpdate;
public MetaData(Hashtable table){
image = (string)table["image"];
format = (string)table["format"];
size = ((Hashtable)table["size"]).TPHashtableToVector2();
scale = float.Parse(table["scale"].ToString());
smartUpdate = (string)table["smartUpdate"];
}
}
public static List<SpriteMetaData> ProcessToSprites(string text) {
Hashtable table = text.hashtableFromJson();
MetaData meta = new MetaData((Hashtable)table["meta"]);
Hashtable frameTable = (Hashtable)table["frames"];
List<PackedFrame> frames = new List<PackedFrame>();
foreach(DictionaryEntry entry in frameTable) {
frames.Add(new PackedFrame((string)entry.Key, meta.size, (Hashtable)entry.Value));
}
alphabatizeFramesByName( frames );
List<SpriteMetaData> sprites = new List<SpriteMetaData>();
for(int i = 0; i < frames.Count; i++){
SpriteMetaData smd = frames[i].BuildBasicSprite( 0.01f, new Color32(128,128,128,128));
if(smd.name.Equals("IGNORE_SPRITE")) {
continue;
}
sprites.Add(smd);
}
return sprites;
}
static void alphabatizeFramesByName(List<PackedFrame> frames)
{
frames.Sort(delegate(PackedFrame a, PackedFrame b) {
if (a.name == null && b.name == null) {
return 0;
}else if (a.name == null) {
return -1;
}else if (b.name == null) {
return 1;
}else {
return a.name.CompareTo(b.name);
}
});
}
public static Mesh[] ProcessToMeshes(string text){
return ProcessToMeshes(text, Quaternion.identity);
}
public static Mesh[] ProcessToMeshes(string text, Quaternion rotation){
Hashtable table = text.hashtableFromJson();
MetaData meta = new MetaData((Hashtable)table["meta"]);
List<PackedFrame> frames = new List<PackedFrame>();
Hashtable frameTable = (Hashtable)table["frames"];
foreach(DictionaryEntry entry in frameTable){
frames.Add(new PackedFrame((string)entry.Key, meta.size, (Hashtable)entry.Value));
}
List<Mesh> meshes = new List<Mesh>();
for(int i = 0; i < frames.Count; i++){
meshes.Add(frames[i].BuildBasicMesh(0.01f, new Color32(128,128,128,128), rotation));
}
return meshes.ToArray();
}
public static MetaData GetMetaData(string text){
Hashtable table = text.hashtableFromJson();
MetaData meta = new MetaData((Hashtable)table["meta"]);
return meta;
}
}
#endif
| |
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using XmasHell.Controls;
using XmasHell.Entities.Bosses;
using XmasHell.GUI;
using XmasHell.Rendering;
using XmasHell.Spriter;
namespace XmasHell.Screens.Menu
{
public class BossSelectionScreen : MenuScreen
{
#region Fields
private BossType _selectedBoss;
private Dictionary<string, SpriterSubstituteEntity> _bossGarlands = new Dictionary<string, SpriterSubstituteEntity>();
private List<SpriterSubstituteEntity> _ballHooks = new List<SpriterSubstituteEntity>();
private readonly List<string> _bossNames = new List<string>()
{
"ball", "bell", "snowflake", "candy", "gift", "log", "tree", "reindeer", "snowman", "santa"
};
private readonly Dictionary<string, Tuple<string, string>> _bossRelations = new Dictionary<string, Tuple<string, string>>
{
{ "santa", new Tuple<string, string>("reindeer", "snowman") },
{ "reindeer", new Tuple<string, string>("gift", "log") },
{ "snowman", new Tuple<string, string>("log", "tree") },
{ "gift", new Tuple<string, string>("bell", "candy") },
{ "log", new Tuple<string, string>("candy", "ball") },
{ "tree", new Tuple<string, string>("ball", "snowflake") }
};
// GUI
private Dictionary<BossType, SpriterGuiButton> _bossButtons = new Dictionary<BossType, SpriterGuiButton>();
private List<SpriterGuiButton> _bossPanelButtons = new List<SpriterGuiButton>();
// Labels
private List<SpriterGuiLabel> _bossPanelLabels = new List<SpriterGuiLabel>();
private SpriterGuiLabel _bossNameLabel;
private SpriterGuiLabel _bestTimeLabel;
private SpriterGuiLabel _playTimeLabel;
private SpriterGuiLabel _playerDeathLabel;
private SpriterGuiLabel _bossDeathLabel;
#endregion
public BossSelectionScreen(XmasHell game) : base(game)
{
}
public override void Initialize()
{
base.Initialize();
}
public override void LoadContent()
{
base.LoadContent();
SpriterFile = Assets.GetSpriterAnimators("Graphics/GUI/boss-selection");
InitializeSpriterGui();
}
private void InitializeSpriterGui()
{
SpriterFile["Main"].AnimationFinished += BossSelectionScreen_AnimationFinished;
SpriterFile["BossPanel"].AnimationFinished += BossPanel_AnimationFinished;
SpriterFile["Garland"].ZIndex(5);
SpriterFile["BallHook"].ZIndex(6);
SpriterFile["Ball"].ZIndex(9);
SpriterFile["BossPanel"].ZIndex(10);
// Christmas tree's balls
foreach (var bossName in _bossNames)
{
var ballAnimator = SpriterFile["Ball"].Clone();
var hasRelation = _bossRelations.ContainsKey(bossName);
for (int i = 0; i < 10; i++)
_ballHooks.Add(new SpriterSubstituteEntity("garland-forbidden-ball.png", SpriterFile["Main"], SpriterFile["BallHook"].Clone(), "garland-forbidden-ball_00" + i));
if (hasRelation)
{
var garlandAnimator1 = SpriterFile["Garland"].Clone();
var garlandAnimator2 = SpriterFile["Garland"].Clone();
garlandAnimator1.Play("FlashForbidden");
garlandAnimator2.Play("FlashForbidden");
garlandAnimator1.Speed = 0.5f + (float)Game.GameManager.Random.NextDouble() / 2f;
garlandAnimator2.Speed = 0.5f + (float)Game.GameManager.Random.NextDouble() / 2f;
garlandAnimator1.Progress = (float)Game.GameManager.Random.NextDouble();
garlandAnimator2.Progress = (float)Game.GameManager.Random.NextDouble();
_bossGarlands.Add(
_bossRelations[bossName].Item1 + "-" + bossName,
new SpriterSubstituteEntity(
"xmas-" + _bossRelations[bossName].Item1 + "-" + bossName + "-garland.png",
SpriterFile["Main"], garlandAnimator1
)
);
_bossGarlands.Add(
_bossRelations[bossName].Item2 + "-" + bossName,
new SpriterSubstituteEntity(
"xmas-" + _bossRelations[bossName].Item2 + "-" + bossName + "-garland.png",
SpriterFile["Main"], garlandAnimator2
)
);
}
var bossButton = new SpriterGuiButton(
Game.ViewportAdapter, bossName, "Graphics/GUI/BossSelection/xmas-" + bossName + "-available-button.png",
ballAnimator, SpriterFile["Main"], "Balance", null, "Audio/SE/select1"
);
bossButton.SubstituteEntity.SubstituteAnimator.Progress = (float)Game.GameManager.Random.NextDouble();
bossButton.SubstituteEntity.SubstituteAnimator.Speed = 0.5f + (float)Game.GameManager.Random.NextDouble();
bossButton.Action += OnBossButtonAction;
_bossButtons.Add(BossFactory.StringToBossType(bossName), bossButton);
}
// Boss panel buttons
var closeBossPanelButton = new SpriterGuiButton(
Game.ViewportAdapter, "CloseBossPanel", "Graphics/GUI/BossSelection/boss-panel-close-button.png",
SpriterFile["CloseButton"], SpriterFile["BossPanel"], "Idle", null, "Audio/SE/select4"
);
var startBattleBossPanelButton = new SpriterGuiButton(
Game.ViewportAdapter, "StartBattleBossPanel", "Graphics/GUI/BossSelection/boss-panel-battle-button.png",
SpriterFile["BattleButton"], SpriterFile["BossPanel"], "Idle", null, "Audio/SE/select2"
);
closeBossPanelButton.Action += BossPanelCloseButtonAction;
startBattleBossPanelButton.Action += BossPanelStartBattleButtonAction;
closeBossPanelButton.Animator().ZIndex(11);
startBattleBossPanelButton.Animator().ZIndex(11);
_bossPanelButtons.Add(closeBossPanelButton);
_bossPanelButtons.Add(startBattleBossPanelButton);
// Labels
_bossNameLabel = new SpriterGuiLabel("Unknown", Assets.GetFont("Graphics/Fonts/ui-title"), "boss-panel-title-label.png", SpriterFile["BossPanel"], Vector2.Zero, true);
_bestTimeLabel = new SpriterGuiLabel("", Assets.GetFont("Graphics/Fonts/ui"), "boss-panel-best-time-label.png", SpriterFile["BossPanel"], Vector2.Zero);
_playTimeLabel = new SpriterGuiLabel("", Assets.GetFont("Graphics/Fonts/ui"), "boss-panel-play-time-label.png", SpriterFile["BossPanel"], Vector2.Zero);
_playerDeathLabel = new SpriterGuiLabel("", Assets.GetFont("Graphics/Fonts/ui"), "boss-panel-player-deaths-label.png", SpriterFile["BossPanel"], Vector2.Zero);
_bossDeathLabel = new SpriterGuiLabel("", Assets.GetFont("Graphics/Fonts/ui"), "boss-panel-boss-deaths-label.png", SpriterFile["BossPanel"], Vector2.Zero);
_bossPanelLabels.Add(_bossNameLabel);
_bossPanelLabels.Add(_bestTimeLabel);
_bossPanelLabels.Add(_playTimeLabel);
_bossPanelLabels.Add(_playerDeathLabel);
_bossPanelLabels.Add(_bossDeathLabel);
ResetUI();
}
#region Button actions
private void OnBossButtonAction(object button, Point position)
{
var spriterGuiButton = button as SpriterGuiButton;
// Make sure the ball is entirely visible
spriterGuiButton.SubstituteEntity.SubstituteAnimator.Color =
new Color(spriterGuiButton.SubstituteEntity.SubstituteAnimator.Color, 1f);
var bossType = BossFactory.StringToBossType(spriterGuiButton.Name);
if (bossType != BossType.Unknown)
OpenBossPanel(bossType);
}
private void BossPanelCloseButtonAction(object button, Point e)
{
CloseBossPanel();
}
private void BossPanelStartBattleButtonAction(object button, Point e)
{
Game.GameManager.LoadBoss(_selectedBoss);
Game.ScreenManager.GoTo<GameScreen>();
Game.CloudManager.Dispose();
}
#endregion
#region Animations finished
private void BossSelectionScreen_AnimationFinished(string animationName)
{
if (animationName == "Intro")
{
SpriterFile["Main"].Play("Idle");
}
}
private void BossPanel_AnimationFinished(string animationName)
{
if (animationName == "Show")
SpriterFile["BossPanel"].Play("Idle");
else if (animationName == "Hide")
DoCloseBossPanel();
}
#endregion
private void OpenBossPanel(BossType bossType)
{
_selectedBoss = bossType;
var spriterGuiButton = _bossButtons[bossType];
spriterGuiButton.SubstituteEntity.EnableSynchronization(false);
var ballPosition = Game.ViewportAdapter.Center.ToVector2();
ballPosition.Y -= 575;
spriterGuiButton.Animator().Position = ballPosition;
spriterGuiButton.Animator().Scale = new Vector2(2f);
spriterGuiButton.Animator().ZIndex(11);
foreach (var bossPanelButton in _bossPanelButtons)
Game.GuiManager.AddButton(bossPanelButton);
foreach (var bossPanelLabel in _bossPanelLabels)
Game.GuiManager.AddLabel(bossPanelLabel);
Game.SpriteBatchManager.AddSpriterAnimator(SpriterFile["BossPanel"], Layer.UI);
SpriterFile["BossPanel"].Play("Show");
// Update labels
var bossDeath = Game.PlayerData.BossBeatenCounter(bossType);
_bossNameLabel.Text = "Xmas " + bossType.ToString().Substring(4);
_bestTimeLabel.Text = "Best time: ";
_bestTimeLabel.Text += (bossDeath > 0) ? Game.PlayerData.BossBestTime(bossType).ToString("mm\\:ss") : "--:--";
_playTimeLabel.Text = "Play time: " + Game.PlayerData.BossPlayTime(bossType).ToString("mm\\:ss");
_playerDeathLabel.Text = "Attempts: " + (Game.PlayerData.DeathCounter(bossType) + Game.PlayerData.BossBeatenCounter(bossType)).ToString("000");
_bossDeathLabel.Text = "Boss deaths: " + bossDeath;
DoOpenBossPanel();
}
// Performed when animation is finished
private void DoOpenBossPanel()
{
DisableBossButtons();
}
// Performed when animation is finished
private void DoCloseBossPanel()
{
foreach (var bossPanelButton in _bossPanelButtons)
Game.GuiManager.RemoveButton(bossPanelButton);
foreach (var bossPanelLabel in _bossPanelLabels)
Game.GuiManager.RemoveLabel(bossPanelLabel);
Game.SpriteBatchManager.RemoveSpriterAnimator(SpriterFile["BossPanel"], Layer.UI);
EnableBossButtons();
}
private void CloseBossPanel(bool hardClose = false)
{
if (_bossButtons.ContainsKey(_selectedBoss))
{
_bossButtons[_selectedBoss].SubstituteEntity.EnableSynchronization(true);
_bossButtons[_selectedBoss].Animator().ZIndex(9);
}
if (hardClose)
{
DoCloseBossPanel();
}
else
{
SpriterFile["BossPanel"].Play("Hide");
SpriterFile["BossPanel"].CurrentAnimation.Looping = false;
}
}
public override void Show(bool reset = false)
{
base.Show(reset);
ResetUI();
}
private void ShowBossButtons()
{
foreach (var bossButtonPair in _bossButtons)
{
var bossButton = bossButtonPair.Value;
var bossType = BossFactory.StringToBossType(bossButton.Name);
bossButton.SubstituteEntity.EnableSynchronization(true);
var hasRelation = _bossRelations.ContainsKey(bossButton.Name);
var available = !hasRelation ||
(Game.PlayerData.BossBeatenCounter(BossFactory.StringToBossType(_bossRelations[bossButton.Name].Item1)) > 0 &&
Game.PlayerData.BossBeatenCounter(BossFactory.StringToBossType(_bossRelations[bossButton.Name].Item2)) > 0);
if (Array.IndexOf(GameConfig.EnabledBosses, bossType) == -1)
available = false;
if (available)
{
var beaten = Game.PlayerData.BossBeatenCounter(bossType) > 0;
var hidden = Game.PlayerData.DeathCounter(bossType) == 0 && Game.PlayerData.BossBeatenCounter(bossType) == 0;
var buttonTextureSwapName = "xmas-" + bossButton.Name + "-" + ((beaten) ? "beaten" : "available") + "-button";
if (hasRelation && hidden)
buttonTextureSwapName = "hidden-boss-button";
if (hasRelation)
{
var relation1 = _bossRelations[bossButton.Name].Item1;
var relation2 = _bossRelations[bossButton.Name].Item2;
var animationName = (beaten) ? "FlashBeaten" : "FlashAvailable";
_bossGarlands[relation1 + "-" + bossButton.Name].SubstituteAnimator.Play(animationName);
_bossGarlands[relation2 + "-" + bossButton.Name].SubstituteAnimator.Play(animationName);
_bossGarlands[relation1 + "-" + bossButton.Name].SubstituteAnimator.Speed = 0.5f + (float)Game.GameManager.Random.NextDouble() / 2f;
_bossGarlands[relation2 + "-" + bossButton.Name].SubstituteAnimator.Speed = 0.5f + (float)Game.GameManager.Random.NextDouble() / 2f;
_bossGarlands[relation1 + "-" + bossButton.Name].SubstituteAnimator.Progress = (float)Game.GameManager.Random.NextDouble();
_bossGarlands[relation2 + "-" + bossButton.Name].SubstituteAnimator.Progress = (float)Game.GameManager.Random.NextDouble();
}
bossButton.Animator().AddTextureSwap(
"Graphics/GUI/BossSelection/unknown-boss-button",
Assets.GetTexture2D("Graphics/GUI/BossSelection/" + buttonTextureSwapName)
);
}
else
{
bossButton.Name = "Unknown";
}
Game.GuiManager.AddButton(bossButton);
}
EnableBossButtons();
}
protected override void ResetUI()
{
base.ResetUI();
if (UIReseted)
return;
if (SpriterFile["Main"] != null)
{
if (Game.ScreenManager.GetPreviousScreen().Name == "MainMenuScreen")
SpriterFile["Main"].Play("Intro");
else if (Game.ScreenManager.GetPreviousScreen().Name == "GameScreen")
SpriterFile["Main"].Play("Idle");
Game.SpriteBatchManager.AddSpriterAnimator(SpriterFile["Main"], Layer.BACKGROUND);
SpriterFile["Main"].CurrentAnimation.Looping = false;
}
foreach (var ballHook in _ballHooks)
{
ballHook.Reset();
Game.SpriteBatchManager.AddSpriterAnimator(ballHook.SubstituteAnimator, Layer.UI);
}
foreach (var garland in _bossGarlands)
{
garland.Value.Reset();
Game.SpriteBatchManager.AddSpriterAnimator(garland.Value.SubstituteAnimator, Layer.UI);
}
ShowBossButtons();
UIReseted = true;
}
private void EnableBossButtons()
{
foreach (var bossButtonPair in _bossButtons)
{
var bossButton = bossButtonPair.Value;
bossButton.Enable(true);
}
}
private void DisableBossButtons()
{
foreach (var bossButtonPair in _bossButtons)
{
var bossButton = bossButtonPair.Value;
bossButton.Enable(false);
}
}
private void HideBossButtons()
{
foreach (var bossButtonPair in _bossButtons)
{
var bossButton = bossButtonPair.Value;
Game.GuiManager.RemoveButton(bossButton);
}
DisableBossButtons();
}
public override void Hide()
{
base.Hide();
foreach (var ballHook in _ballHooks)
Game.SpriteBatchManager.RemoveSpriterAnimator(ballHook.SubstituteAnimator, Layer.UI);
foreach (var garland in _bossGarlands)
Game.SpriteBatchManager.RemoveSpriterAnimator(garland.Value.SubstituteAnimator, Layer.UI);
HideBossButtons();
SpriterFile["Main"].Play("Idle");
Game.SpriteBatchManager.RemoveSpriterAnimator(SpriterFile["Main"], Layer.BACKGROUND);
CloseBossPanel(true);
}
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
if (InputManager.PressedCancel())
Game.ScreenManager.GoTo<MainMenuScreen>();
foreach (var ballHook in _ballHooks)
ballHook.Update(gameTime);
foreach (var garland in _bossGarlands)
garland.Value.Update(gameTime);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace MyMicroService.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// Copyright 2021 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
// language governing permissions and limitations under the License.
using Android;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Runtime;
using Android.Support.V4.App;
using Android.Support.V4.Content;
using Android.Widget;
using AndroidX.AppCompat.App;
using ArcGISRuntime.Helpers;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.Tasks.NetworkAnalysis;
using Esri.ArcGISRuntime.UI;
using Esri.ArcGISRuntime.UI.Controls;
using System;
using System.Linq;
namespace ArcGISRuntimeXamarin.Samples.NavigateAR
{
[Activity(ConfigurationChanges =
ConfigChanges.Orientation | ConfigChanges.ScreenSize)]
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Navigate in AR",
category: "Augmented reality",
description: "Use a route displayed in the real world to navigate.",
instructions: "The sample opens with a map centered on the current location. Tap the map to add an origin and a destination; the route will be shown as a line. When ready, click 'Confirm' to start the AR navigation. Calibrate the heading before starting to navigate. When you start, route instructions will be displayed and spoken. As you proceed through the route, new directions will be provided until you arrive.",
tags: new[] { "augmented reality", "directions", "full-scale", "guidance", "mixed reality", "navigate", "navigation", "real-scale", "route", "routing", "world-scale" })]
[ArcGISRuntime.Samples.Shared.Attributes.OfflineData("628e8e3521cf45e9a28a12fe10c02c4d")]
public class NavigateARRoutePlanner : AppCompatActivity
{
// Hold references to the UI controls.
private MapView _mapView;
private TextView _helpLabel;
private Button _navigateButton;
// Overlays for showing the stops and calculated route.
private GraphicsOverlay _routeOverlay;
private GraphicsOverlay _stopsOverlay;
// Start and end point for the route.
private MapPoint _startPoint;
private MapPoint _endPoint;
// Objects for route calculation.
private RouteTask _routeTask;
private Route _route;
private RouteResult _routeResult;
private RouteParameters _routeParameters;
// URL to the routing service; requires login.
private readonly Uri _routingUri =
new Uri("https://route.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World");
// Permissions and permission request.
private readonly string[] _requestedPermissions = { Manifest.Permission.AccessFineLocation };
private const int RequestCode = 35;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
Title = "Navigate in AR";
CreateLayout();
RequestPermissions();
}
private void CreateLayout()
{
// Create and show the layout.
SetContentView(ArcGISRuntime.Resource.Layout.NavigateARRoutePlanner);
// Set up control references.
_helpLabel = FindViewById<TextView>(ArcGISRuntime.Resource.Id.helpLabel);
_mapView = FindViewById<MapView>(ArcGISRuntime.Resource.Id.mapView);
_navigateButton = FindViewById<Button>(ArcGISRuntime.Resource.Id.navigateButton);
}
private async void Initialize()
{
// Create and show a map.
_mapView.Map = new Map(BasemapStyle.ArcGISImageryStandard);
try
{
// Enable location display.
_mapView.LocationDisplay.AutoPanMode = LocationDisplayAutoPanMode.Recenter;
await _mapView.LocationDisplay.DataSource.StartAsync();
_mapView.LocationDisplay.IsEnabled = true;
// Configure authentication.
ArcGISLoginPrompt.SetChallengeHandler();
// Create the route task.
_routeTask = await RouteTask.CreateAsync(_routingUri);
// Create route display overlay and symbology.
_routeOverlay = new GraphicsOverlay();
SimpleLineSymbol routeSymbol =
new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Yellow, 1);
_routeOverlay.Renderer = new SimpleRenderer(routeSymbol);
// Create stop display overlay.
_stopsOverlay = new GraphicsOverlay();
// Add the overlays to the map.
_mapView.GraphicsOverlays.Add(_routeOverlay);
_mapView.GraphicsOverlays.Add(_stopsOverlay);
// Enable tap-to-place stops.
_mapView.GeoViewTapped += MapView_GeoViewTapped;
// Update the UI.
_helpLabel.Text = "Tap to set a start point";
}
catch (Exception ex)
{
new AndroidX.AppCompat.App.AlertDialog.Builder(this).SetMessage(ex.Message).SetTitle(ex.GetType().Name).Show();
System.Diagnostics.Debug.WriteLine(ex);
}
}
private void MapView_GeoViewTapped(object sender, GeoViewInputEventArgs e)
{
if (_startPoint == null)
{
// Place the start point.
_startPoint = e.Location;
Graphic startGraphic = new Graphic(_startPoint,
new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Cross, System.Drawing.Color.Green, 25));
_stopsOverlay.Graphics.Add(startGraphic);
// Update help text.
_helpLabel.Text = "Tap to set an end point";
}
else if (_endPoint == null)
{
// Place the end point.
_endPoint = e.Location;
Graphic endGraphic = new Graphic(_endPoint,
new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.X, System.Drawing.Color.Red, 25));
_stopsOverlay.Graphics.Add(endGraphic);
// Update help text.
_helpLabel.Text = "Solving route";
// Solve the route.
SolveRoute();
}
}
private void EnableNavigation()
{
// Pass the route result to the route viewer.
RouteViewerAR.PassedRouteResult = _routeResult;
// Configure the UI.
_navigateButton.Click += NavigateButton_Click;
_navigateButton.Visibility = Android.Views.ViewStates.Visible;
_helpLabel.Text = "You're ready to start navigating!";
}
private void NavigateButton_Click(object sender, EventArgs e)
{
// Start the AR navigation activity.
Intent myIntent = new Intent(this, typeof(RouteViewerAR));
StartActivity(myIntent);
}
private async void SolveRoute()
{
try
{
// Create route parameters and configure them to enable navigation.
_routeParameters = await _routeTask.CreateDefaultParametersAsync();
_routeParameters.ReturnStops = true;
_routeParameters.ReturnDirections = true;
_routeParameters.ReturnRoutes = true;
// Prefer walking directions if available.
TravelMode walkingMode =
_routeTask.RouteTaskInfo.TravelModes.FirstOrDefault(mode => mode.Name.Contains("Walk")) ??
_routeTask.RouteTaskInfo.TravelModes.First();
_routeParameters.TravelMode = walkingMode;
// Set the stops for the route.
Stop stop1 = new Stop(_startPoint);
Stop stop2 = new Stop(_endPoint);
_routeParameters.SetStops(new[] { stop1, stop2 });
// Calculate the route.
_routeResult = await _routeTask.SolveRouteAsync(_routeParameters);
// Get the first result.
_route = _routeResult.Routes.First();
// Create and show a graphic for the route.
Graphic routeGraphic = new Graphic(_route.RouteGeometry);
_routeOverlay.Graphics.Add(routeGraphic);
// Allow the user to start navigating.
EnableNavigation();
}
catch (Exception ex)
{
new AndroidX.AppCompat.App.AlertDialog.Builder(this).SetMessage(ex.Message).SetTitle(ex.GetType().Name).Show();
System.Diagnostics.Debug.WriteLine(ex);
}
}
private void RequestPermissions()
{
if (ContextCompat.CheckSelfPermission(this, _requestedPermissions[0]) == Permission.Granted)
{
Initialize();
}
else
{
ActivityCompat.RequestPermissions(this, _requestedPermissions, NavigateARRoutePlanner.RequestCode);
}
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions,
[GeneratedEnum] Permission[] grantResults)
{
if (requestCode == NavigateARRoutePlanner.RequestCode && grantResults[0] == Permission.Granted)
{
Initialize();
}
else
{
Toast.MakeText(this, "Location permissions needed for this sample", ToastLength.Short).Show();
}
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
| |
// 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 System.Globalization;
using System.Text;
using NodaTime.Annotations;
using NodaTime.Globalization;
using NodaTime.Text.Patterns;
using NodaTime.Utility;
using JetBrains.Annotations;
namespace NodaTime.Text
{
/// <summary>
/// Represents a pattern for parsing and formatting <see cref="OffsetDateTime"/> 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 OffsetDateTimePattern : IPattern<OffsetDateTime>
{
internal static readonly OffsetDateTime DefaultTemplateValue = new LocalDateTime(2000, 1, 1, 0, 0).WithOffset(Offset.Zero);
/// <summary>
/// Gets an invariant offset date/time pattern based on ISO-8601 (down to the second), including offset from UTC.
/// </summary>
/// <remarks>
/// The calendar system is not parsed or formatted as part of this pattern. It corresponds to a custom pattern of
/// "uuuu'-'MM'-'dd'T'HH':'mm':'sso<G>". This pattern is available as the "G"
/// standard pattern (even though it is invariant).
/// </remarks>
/// <value>An invariant offset date/time pattern based on ISO-8601 (down to the second), including offset from UTC.</value>
public static OffsetDateTimePattern GeneralIsoPattern => Patterns.GeneralIsoPatternImpl;
/// <summary>
/// Gets an invariant offset date/time pattern based on ISO-8601 (down to the nanosecond), including offset from UTC.
/// </summary>
/// <remarks>
/// The calendar system is not parsed or formatted as part of this pattern. It corresponds to a custom pattern of
/// "uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFFo<G>". This will round-trip any values
/// in the ISO calendar, and is available as the "o" standard pattern.
/// </remarks>
/// <value>An invariant offset date/time pattern based on ISO-8601 (down to the nanosecond), including offset from UTC.</value>
public static OffsetDateTimePattern ExtendedIsoPattern => Patterns.ExtendedIsoPatternImpl;
/// <summary>
/// Gets an invariant offset date/time pattern based on RFC 3339 (down to the nanosecond), including offset from UTC
/// as hours and minutes only.
/// </summary>
/// <remarks>
/// The minutes part of the offset is always included, but any sub-minute component
/// of the offset is lost. An offset of zero is formatted as 'Z', but all of 'Z', '+00:00' and '-00:00' are parsed
/// the same way. The RFC 3339 meaning of '-00:00' is not supported by Noda Time.
/// Note that parsing is case-sensitive (so 'T' and 'Z' must be upper case).
/// The calendar system is not parsed or formatted as part of this pattern. It corresponds to a custom pattern of
/// "uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFFo<Z+HH:mm>".
/// </remarks>
/// <value>An invariant offset date/time pattern based on RFC 3339 (down to the nanosecond), including offset from UTC
/// as hours and minutes only.</value>
public static OffsetDateTimePattern Rfc3339Pattern => Patterns.Rfc3339PatternImpl;
/// <summary>
/// Gets an invariant offset date/time pattern based on ISO-8601 (down to the nanosecond)
/// including offset from UTC and calendar ID.
/// </summary>
/// <remarks>
/// The returned pattern corresponds to a custom pattern of
/// "uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFFo<G> '('c')'". This will round-trip any value in any calendar,
/// and is available as the "r" standard pattern.
/// </remarks>
/// <value>An invariant offset date/time pattern based on ISO-8601 (down to the nanosecond)
/// including offset from UTC and calendar ID.</value>
public static OffsetDateTimePattern FullRoundtripPattern => Patterns.FullRoundtripPatternImpl;
/// <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 OffsetDateTimePattern GeneralIsoPatternImpl = Create("uuuu'-'MM'-'dd'T'HH':'mm':'sso<G>", NodaFormatInfo.InvariantInfo, DefaultTemplateValue);
internal static readonly OffsetDateTimePattern ExtendedIsoPatternImpl = Create("uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFFo<G>", NodaFormatInfo.InvariantInfo, DefaultTemplateValue);
internal static readonly OffsetDateTimePattern Rfc3339PatternImpl = Create("uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFFo<Z+HH:mm>", NodaFormatInfo.InvariantInfo, DefaultTemplateValue);
internal static readonly OffsetDateTimePattern FullRoundtripPatternImpl = Create("uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFFo<G> '('c')'", NodaFormatInfo.InvariantInfo, DefaultTemplateValue);
internal static readonly PatternBclSupport<OffsetDateTime> BclSupport = new PatternBclSupport<OffsetDateTime>("G", fi => fi.OffsetDateTimePatternParser);
}
private readonly IPattern<OffsetDateTime> pattern;
/// <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>
internal 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 OffsetDateTime TemplateValue { get; }
private OffsetDateTimePattern(string patternText, NodaFormatInfo formatInfo, OffsetDateTime templateValue,
IPattern<OffsetDateTime> pattern)
{
this.PatternText = patternText;
this.FormatInfo = formatInfo;
this.TemplateValue = templateValue;
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<OffsetDateTime> Parse(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(OffsetDateTime 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(OffsetDateTime value, [NotNull] StringBuilder builder) => pattern.AppendFormat(value, builder);
/// <summary>
/// Creates a pattern for the given pattern text, format info, and template value.
/// </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>
/// <returns>A pattern for parsing and formatting zoned date/times.</returns>
/// <exception cref="InvalidPatternException">The pattern text was invalid.</exception>
private static OffsetDateTimePattern Create([NotNull] string patternText, [NotNull] NodaFormatInfo formatInfo,
OffsetDateTime templateValue)
{
Preconditions.CheckNotNull(patternText, nameof(patternText));
Preconditions.CheckNotNull(formatInfo, nameof(formatInfo));
var pattern = new OffsetDateTimePatternParser(templateValue).ParsePattern(patternText, formatInfo);
return new OffsetDateTimePattern(patternText, formatInfo, templateValue, pattern);
}
/// <summary>
/// Creates a pattern for the given pattern text, culture, and template value.
/// </summary>
/// <remarks>
/// See the user guide for the available pattern text options.
/// </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="templateValue">Template value to use for unspecified fields</param>
/// <returns>A pattern for parsing and formatting local date/times.</returns>
/// <exception cref="InvalidPatternException">The pattern text was invalid.</exception>
public static OffsetDateTimePattern Create([NotNull] string patternText, [NotNull] CultureInfo cultureInfo, OffsetDateTime templateValue) =>
Create(patternText, NodaFormatInfo.GetFormatInfo(cultureInfo), templateValue);
/// <summary>
/// Creates a pattern for the given pattern text in the invariant culture, using the default
/// template value of midnight January 1st 2000 at an offset of 0.
/// </summary>
/// <remarks>
/// See the user guide for the available pattern text options.
/// </remarks>
/// <param name="patternText">Pattern text to create the pattern for</param>
/// <returns>A pattern for parsing and formatting local date/times.</returns>
/// <exception cref="InvalidPatternException">The pattern text was invalid.</exception>
public static OffsetDateTimePattern CreateWithInvariantCulture([NotNull] string patternText) =>
Create(patternText, NodaFormatInfo.InvariantInfo, DefaultTemplateValue);
/// <summary>
/// Creates a pattern for the given pattern text in the current culture, using the default
/// template value of midnight January 1st 2000 at an offset of 0.
/// </summary>
/// <remarks>
/// See the user guide for the available pattern text options. 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>
/// <returns>A pattern for parsing and formatting local date/times.</returns>
/// <exception cref="InvalidPatternException">The pattern text was invalid.</exception>
public static OffsetDateTimePattern CreateWithCurrentCulture([NotNull] string patternText) =>
Create(patternText, NodaFormatInfo.CurrentInfo, 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 OffsetDateTimePattern WithPatternText([NotNull] string patternText) =>
Create(patternText, FormatInfo, 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 OffsetDateTimePattern WithFormatInfo([NotNull] NodaFormatInfo formatInfo) =>
Create(PatternText, formatInfo, 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 OffsetDateTimePattern WithCulture([NotNull] CultureInfo cultureInfo) =>
WithFormatInfo(NodaFormatInfo.GetFormatInfo(cultureInfo));
/// <summary>
/// Creates a pattern for the same original pattern text and culture as this pattern, but with
/// the specified template value.
/// </summary>
/// <param name="newTemplateValue">The template value to use in the new pattern.</param>
/// <returns>A new pattern with the given template value.</returns>
public OffsetDateTimePattern WithTemplateValue(OffsetDateTime newTemplateValue) =>
Create(PatternText, FormatInfo, 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 OffsetDateTimePattern WithCalendar([NotNull] CalendarSystem calendar) =>
WithTemplateValue(TemplateValue.WithCalendar(calendar));
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using EmpleoDotNet.WebApi.Areas.HelpPage.ModelDescriptions;
using EmpleoDotNet.WebApi.Areas.HelpPage.Models;
namespace EmpleoDotNet.WebApi.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
using System;
using System.Text;
using System.Collections.Generic;
using Adaptive.Agrona;
namespace Adaptive.Cluster.Codecs {
public class VoteEncoder
{
public const ushort BLOCK_LENGTH = 36;
public const ushort TEMPLATE_ID = 52;
public const ushort SCHEMA_ID = 111;
public const ushort SCHEMA_VERSION = 7;
private VoteEncoder _parentMessage;
private IMutableDirectBuffer _buffer;
protected int _offset;
protected int _limit;
public VoteEncoder()
{
_parentMessage = this;
}
public ushort SbeBlockLength()
{
return BLOCK_LENGTH;
}
public ushort SbeTemplateId()
{
return TEMPLATE_ID;
}
public ushort SbeSchemaId()
{
return SCHEMA_ID;
}
public ushort SbeSchemaVersion()
{
return SCHEMA_VERSION;
}
public string SbeSemanticType()
{
return "";
}
public IMutableDirectBuffer Buffer()
{
return _buffer;
}
public int Offset()
{
return _offset;
}
public VoteEncoder Wrap(IMutableDirectBuffer buffer, int offset)
{
this._buffer = buffer;
this._offset = offset;
Limit(offset + BLOCK_LENGTH);
return this;
}
public VoteEncoder WrapAndApplyHeader(
IMutableDirectBuffer buffer, int offset, MessageHeaderEncoder headerEncoder)
{
headerEncoder
.Wrap(buffer, offset)
.BlockLength(BLOCK_LENGTH)
.TemplateId(TEMPLATE_ID)
.SchemaId(SCHEMA_ID)
.Version(SCHEMA_VERSION);
return Wrap(buffer, offset + MessageHeaderEncoder.ENCODED_LENGTH);
}
public int EncodedLength()
{
return _limit - _offset;
}
public int Limit()
{
return _limit;
}
public void Limit(int limit)
{
this._limit = limit;
}
public static int CandidateTermIdEncodingOffset()
{
return 0;
}
public static int CandidateTermIdEncodingLength()
{
return 8;
}
public static long CandidateTermIdNullValue()
{
return -9223372036854775808L;
}
public static long CandidateTermIdMinValue()
{
return -9223372036854775807L;
}
public static long CandidateTermIdMaxValue()
{
return 9223372036854775807L;
}
public VoteEncoder CandidateTermId(long value)
{
_buffer.PutLong(_offset + 0, value, ByteOrder.LittleEndian);
return this;
}
public static int LogLeadershipTermIdEncodingOffset()
{
return 8;
}
public static int LogLeadershipTermIdEncodingLength()
{
return 8;
}
public static long LogLeadershipTermIdNullValue()
{
return -9223372036854775808L;
}
public static long LogLeadershipTermIdMinValue()
{
return -9223372036854775807L;
}
public static long LogLeadershipTermIdMaxValue()
{
return 9223372036854775807L;
}
public VoteEncoder LogLeadershipTermId(long value)
{
_buffer.PutLong(_offset + 8, value, ByteOrder.LittleEndian);
return this;
}
public static int LogPositionEncodingOffset()
{
return 16;
}
public static int LogPositionEncodingLength()
{
return 8;
}
public static long LogPositionNullValue()
{
return -9223372036854775808L;
}
public static long LogPositionMinValue()
{
return -9223372036854775807L;
}
public static long LogPositionMaxValue()
{
return 9223372036854775807L;
}
public VoteEncoder LogPosition(long value)
{
_buffer.PutLong(_offset + 16, value, ByteOrder.LittleEndian);
return this;
}
public static int CandidateMemberIdEncodingOffset()
{
return 24;
}
public static int CandidateMemberIdEncodingLength()
{
return 4;
}
public static int CandidateMemberIdNullValue()
{
return -2147483648;
}
public static int CandidateMemberIdMinValue()
{
return -2147483647;
}
public static int CandidateMemberIdMaxValue()
{
return 2147483647;
}
public VoteEncoder CandidateMemberId(int value)
{
_buffer.PutInt(_offset + 24, value, ByteOrder.LittleEndian);
return this;
}
public static int FollowerMemberIdEncodingOffset()
{
return 28;
}
public static int FollowerMemberIdEncodingLength()
{
return 4;
}
public static int FollowerMemberIdNullValue()
{
return -2147483648;
}
public static int FollowerMemberIdMinValue()
{
return -2147483647;
}
public static int FollowerMemberIdMaxValue()
{
return 2147483647;
}
public VoteEncoder FollowerMemberId(int value)
{
_buffer.PutInt(_offset + 28, value, ByteOrder.LittleEndian);
return this;
}
public static int VoteEncodingOffset()
{
return 32;
}
public static int VoteEncodingLength()
{
return 4;
}
public VoteEncoder Vote(BooleanType value)
{
_buffer.PutInt(_offset + 32, (int)value, ByteOrder.LittleEndian);
return this;
}
public override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
VoteDecoder writer = new VoteDecoder();
writer.Wrap(_buffer, _offset, BLOCK_LENGTH, SCHEMA_VERSION);
return writer.AppendTo(builder);
}
}
}
| |
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Linq.Expressions;
using Eto.Forms;
namespace Eto.Forms
{
/// <summary>
/// Direct delegate binding.
/// </summary>
/// <remarks>
/// This is a direct binding, in that the get/set delegates can get/set the value directly without any associated object
/// instance.
/// This is used when binding directly to a property or when an object instance isn't needed to get/set a value.
/// </remarks>
public class DelegateBinding<TValue> : DirectBinding<TValue>
{
/// <summary>
/// Gets or sets the delegate to get the value for this binding.
/// </summary>
/// <value>The get value delegate.</value>
public Func<TValue> GetValue { get; set; }
/// <summary>
/// Gets or sets the delegate to set the value for this binding.
/// </summary>
/// <value>The set value delegate.</value>
public Action<TValue> SetValue { get; set; }
/// <summary>
/// Gets or sets the delegate to register the change event, when needed by the consumer of this binding.
/// </summary>
/// <value>The add change event delegate.</value>
public Action<EventHandler<EventArgs>> AddChangeEvent { get; set; }
/// <summary>
/// Gets or sets the delegate to remove the change event.
/// </summary>
/// <value>The remove change event delegate.</value>
public Action<EventHandler<EventArgs>> RemoveChangeEvent { get; set; }
/// <summary>
/// Gets or sets the value of this binding
/// </summary>
/// <value>The data value.</value>
public override TValue DataValue
{
get { return GetValue != null ? GetValue() : default(TValue); }
set { if (SetValue != null) SetValue(value); }
}
void HandleChangedEvent(object sender, EventArgs e)
{
OnDataValueChanged(e);
}
/// <summary>
/// Initializes a new instance of the <see cref="DelegateBinding{TValue}"/> class.
/// </summary>
public DelegateBinding()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DelegateBinding{TValue}"/> class with the specified delegates.
/// </summary>
/// <param name="getValue">Delegate to get the value for the binding.</param>
/// <param name="setValue">Delegate to set the value for the binding.</param>
/// <param name="addChangeEvent">Delegate to register the change event, when needed by the consumer of this binding.</param>
/// <param name="removeChangeEvent">Delegate to remove the change event.</param>
public DelegateBinding(Func<TValue> getValue = null, Action<TValue> setValue = null, Action<EventHandler<EventArgs>> addChangeEvent = null, Action<EventHandler<EventArgs>> removeChangeEvent = null)
{
GetValue = getValue;
SetValue = setValue;
AddChangeEvent = addChangeEvent;
RemoveChangeEvent = removeChangeEvent;
}
/// <summary>
/// Hooks up the late bound events for this object
/// </summary>
protected override void HandleEvent(string id)
{
switch (id)
{
case DataValueChangedEvent:
if (AddChangeEvent != null)
AddChangeEvent(new EventHandler<EventArgs>(HandleChangedEvent));
break;
default:
base.HandleEvent(id);
break;
}
}
/// <summary>
/// Removes the late bound events for this object
/// </summary>
protected override void RemoveEvent(string id)
{
switch (id)
{
case DataValueChangedEvent:
if (RemoveChangeEvent != null)
RemoveChangeEvent(new EventHandler<EventArgs>(HandleChangedEvent));
break;
default:
base.RemoveEvent(id);
break;
}
}
}
/// <summary>
/// Indirect binding using delegate methods
/// </summary>
/// <remarks>
/// This is an indirect binding, in that the object to get/set the values from/to is passed to each of the delegates
/// to get/set the value.
/// This is used for things like columns in a <see cref="Forms.Grid"/> control to bind to specific values of each item
/// in the grid.
/// </remarks>
/// <typeparam name="T">Type of the object this binding will get/set the values from/to</typeparam>
/// <typeparam name="TValue">Type of the value this binding will get/set</typeparam>
/// <copyright>(c) 2014 by Curtis Wensley</copyright>
/// <license type="BSD-3">See LICENSE for full terms</license>
public class DelegateBinding<T, TValue> : IndirectBinding<TValue>
{
/// <summary>
/// Gets or sets the delegate to get the value for this binding.
/// </summary>
/// <value>The get value delegate.</value>
public new Func<T, TValue> GetValue { get; set; }
/// <summary>
/// Gets or sets the delegate to set the value for this binding.
/// </summary>
/// <value>The set value delegate.</value>
public new Action<T, TValue> SetValue { get; set; }
/// <summary>
/// Gets or sets the delegate to register the change event, when needed by the consumer of this binding.
/// </summary>
/// <value>The add change event delegate.</value>
public Action<T, EventHandler<EventArgs>> AddChangeEvent { get; set; }
/// <summary>
/// Gets or sets the delegate to remove the change event.
/// </summary>
/// <value>The remove change event delegate.</value>
public Action<T, EventHandler<EventArgs>> RemoveChangeEvent { get; set; }
/// <summary>
/// Gets or sets the default get value, when the object instance is null.
/// </summary>
/// <value>The default get value.</value>
public TValue DefaultGetValue { get; set; }
/// <summary>
/// Gets or sets the default set value, when the incoming value is null.
/// </summary>
/// <value>The default set value.</value>
public TValue DefaultSetValue { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="DelegateBinding{T,TValue}"/> class.
/// </summary>
/// <param name="getValue">Delegate to get the value for the binding.</param>
/// <param name="setValue">Delegate to set the value for the binding.</param>
/// <param name="addChangeEvent">Delegate to register the change event, when needed by the consumer of this binding.</param>
/// <param name="removeChangeEvent">Delegate to remove the change event.</param>
/// <param name="defaultGetValue">Default get value, when the object instance is null.</param>
/// <param name="defaultSetValue">Default set value, when the incoming value is null.</param>
public DelegateBinding(Func<T, TValue> getValue = null, Action<T, TValue> setValue = null, Action<T, EventHandler<EventArgs>> addChangeEvent = null, Action<T, EventHandler<EventArgs>> removeChangeEvent = null, TValue defaultGetValue = default(TValue), TValue defaultSetValue = default(TValue))
{
GetValue = getValue;
DefaultGetValue = defaultGetValue;
SetValue = setValue;
DefaultSetValue = defaultSetValue;
if (addChangeEvent != null && removeChangeEvent != null)
{
AddChangeEvent = addChangeEvent;
RemoveChangeEvent = removeChangeEvent;
}
else if (addChangeEvent != null || removeChangeEvent != null)
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "You must either specify both the add and remove change event delegates, or pass null for both"));
}
/// <summary>
/// Initializes a new instance of the <see cref="DelegateBinding{T,TValue}"/> class.
/// </summary>
/// <param name="getValue">Delegate to get the value for the binding.</param>
/// <param name="setValue">Delegate to set the value for the binding.</param>
/// <param name="notifyProperty">Name of the property to listen for change events of this binding.</param>
/// <param name="defaultGetValue">Default get value, when the object instance is null.</param>
/// <param name="defaultSetValue">Default set value, when the incoming value is null.</param>
public DelegateBinding(Func<T, TValue> getValue, Action<T, TValue> setValue, string notifyProperty, TValue defaultGetValue = default(TValue), TValue defaultSetValue = default(TValue))
{
GetValue = getValue;
DefaultGetValue = defaultGetValue;
SetValue = setValue;
DefaultSetValue = defaultSetValue;
if (!string.IsNullOrEmpty(notifyProperty))
{
AddChangeEvent = (obj, eh) => AddPropertyEvent(obj, notifyProperty, eh);
RemoveChangeEvent = (obj, eh) => RemovePropertyEvent(obj, eh);
}
}
/// <summary>
/// Implements the logic to get the value from the specified object
/// </summary>
/// <remarks>Implementors of this binding must implement this method to get the value from the specified object</remarks>
/// <param name="dataItem">object to get the value from</param>
/// <returns>value from this binding of the specified object</returns>
protected override TValue InternalGetValue(object dataItem)
{
if (GetValue != null && dataItem is T)
{
return GetValue((T)dataItem);
}
return DefaultGetValue;
}
/// <summary>
/// Implements the logic to set the value to the specified object
/// </summary>
/// <param name="dataItem">object to set the value to</param>
/// <param name="value">value to set on the dataItem for this binding</param>
protected override void InternalSetValue(object dataItem, TValue value)
{
if (SetValue != null && dataItem is T)
SetValue((T)dataItem, value);
}
/// <summary>
/// Wires an event handler to fire when the property of the dataItem is changed
/// </summary>
/// <param name="dataItem">object to detect changes on</param>
/// <param name="handler">handler to fire when the property changes on the specified dataItem</param>
/// <returns>binding reference used to track the event hookup, to pass to <see cref="RemoveValueChangedHandler"/> when removing the handler</returns>
public override object AddValueChangedHandler(object dataItem, EventHandler<EventArgs> handler)
{
if (AddChangeEvent != null && dataItem is T)
{
AddChangeEvent((T)dataItem, handler);
return dataItem;
}
return false;
}
/// <summary>
/// Removes the handler for the specified reference from <see cref="AddValueChangedHandler"/>
/// </summary>
/// <param name="bindingReference">Reference from the call to <see cref="AddValueChangedHandler"/></param>
/// <param name="handler">Same handler that was set up during the <see cref="AddValueChangedHandler"/> call</param>
public override void RemoveValueChangedHandler(object bindingReference, EventHandler<EventArgs> handler)
{
if (RemoveChangeEvent != null && bindingReference is T)
{
var dataItem = bindingReference;
RemoveChangeEvent((T)dataItem, handler);
}
}
}
}
| |
using UnityEngine;
using System;
using System.Collections.Generic;
using Random = System.Random;
public class Steelguard : AIBase
{
#region Variables / Properties
public float SwordDistance = 2f;
public float DecisionRate = 1.5f;
public float StrikeUnguardedRate = 25;
public float MinimumHomingDistance = 0.05f;
public string IdleLeft;
public string IdleRight;
public string HitLeft;
public string HitRight;
public string WalkLeft;
public string WalkRight;
public string AttackLeft;
public string AttackRight;
public string CrouchLeft;
public string CrouchRight;
public string CrouchAttackLeft;
public string CrouchAttackRight;
private bool _isFacingLeft = true;
private string _currentAnimation;
private float _nextAttack;
private float _nextDecision;
private AnimationMode _animationType = AnimationMode.Loop;
private Vector3 _originalPosition;
private StateMachine _states;
private HitboxController _hitboxes;
private SidescrollingMovement _movement;
private bool _lockAnimation = false;
#endregion Variables / Properties
#region Engine Hooks
// Use this for initialization
public override void Start()
{
_originalPosition = transform.position;
base.Start();
_movement = GetComponent<SidescrollingMovement>();
_hitboxes = GetComponentInChildren<HitboxController>();
_states = new StateMachine(new List<State> {
new State {Condition = DefaultCondition, Behavior = GuardOriginalPosition},
new State {Condition = SeesPlayer, Behavior = MoveTowardPlayer},
new State {Condition = InRange, Behavior = FenceWithPlayer},
new State {Condition = PlayerIsJumping, Behavior = MoveTowardPlayer},
new State {Condition = IsHit, Behavior = BeHit}
});
}
// Update is called once per frame
public void Update()
{
if(_isPaused)
return;
_states.EvaluateState();
_movement.PerformMovement();
PlayAnimations();
}
#endregion Engine Hooks
#region Conditions
public bool DefaultCondition()
{
return true;
}
public bool SeesPlayer()
{
return _sense.DetectedPlayer;
}
public bool InRange()
{
if(_sense.PlayerLocation == null)
{
if(DebugMode)
Debug.LogWarning("Did not detect any nearby players.");
return false;
}
bool result = Vector3.Distance(transform.position, _sense.PlayerLocation.position) <= SwordDistance;
if(DebugMode)
Debug.Log("The enemy " + (result ? "is" : "is not") + " in range for me to attack!");
return result;
}
public bool PlayerIsJumping()
{
if(_sense.PlayerState == null)
return false;
bool result = _sense.PlayerState.isJumping;
if(DebugMode)
Debug.Log("The enemy " + (result ? "is" : "is not") + " jumping.");
return result;
}
public bool IsHit()
{
return _movement.MovementType == SidescrollingMovementType.Hit;
}
#endregion Conditions
#region Behaviors
public void GuardOriginalPosition()
{
if(Vector3.Distance(transform.position, _originalPosition) < MinimumHomingDistance)
{
BeIdle();
return;
}
_lockAnimation = false;
MoveTowardLocation(_originalPosition);
}
public void MoveTowardPlayer()
{
Vector3 target = _originalPosition;
if(_sense.PlayerLocation != null)
{
if(DebugMode)
Debug.Log("Found a player!");
target = _sense.PlayerLocation.position;
}
else
{
if(DebugMode)
Debug.LogWarning("Could not find a player! Moving to original position instead.");
}
MoveTowardLocation(target);
}
public void FenceWithPlayer()
{
if(Time.time < _nextDecision)
return;
Random generator = new Random();
int roll = generator.Next(0, 100);
if(DebugMode)
Debug.Log("Rolled " + roll + "; need " + StrikeUnguardedRate + " to attack the enemy's unguarded spot!");
if(roll < StrikeUnguardedRate)
{
StrikeUnguardedArea();
}
else
{
StrikeGuardedArea();
}
_nextDecision = Time.time + DecisionRate;
if(DebugMode)
Debug.Log("Next decision at: " + _nextDecision);
}
#endregion Behaviors
#region Methods
public override void PlayAnimations()
{
_sprite.PlaySingleFrame(_currentAnimation, _lockAnimation, _animationType);
_hitboxes.PlaySingleFrame(_currentAnimation, _lockAnimation, _animationType);
}
private void StrikeUnguardedArea()
{
if(!_sense.DetectedPlayer)
return;
bool shouldCrouch = ! _sense.PlayerState.isCrouching;
if(DebugMode)
Debug.Log((shouldCrouch ? "Crouching" : "Standing") + " to strike the player where they're not guarding!");
_movement.ClearHorizontalMovement();
PerformAttack(shouldCrouch);
}
private void StrikeGuardedArea()
{
if(!_sense.DetectedPlayer)
return;
bool shouldCrouch = _sense.PlayerState.isCrouching;
if(DebugMode)
Debug.Log((shouldCrouch ? "Crouching" : "Standing") + " to strike the player where they are guarding!");
_movement.ClearHorizontalMovement();
PerformAttack(shouldCrouch);
}
private void BeHit()
{
_lockAnimation = true;
_animationType = AnimationMode.OneShot;
_currentAnimation = _isFacingLeft ? HitLeft : HitRight;
}
private void PerformAttack(bool shouldCrouch)
{
_lockAnimation = true;
_animationType = AnimationMode.OneShot;
_currentAnimation = shouldCrouch
? _isFacingLeft
? CrouchAttackLeft
: CrouchAttackRight
: _isFacingLeft
? AttackLeft
: AttackRight;
}
private void MoveTowardLocation(Vector3 location)
{
_animationType = AnimationMode.Loop;
if(Mathf.Abs(location.x - transform.position.x) < MinimumHomingDistance)
{
if(DebugMode)
Debug.Log("Close enough, not moving.");
return;
}
if(DebugMode)
Debug.Log("Moving towards " + location);
if(location.x < transform.position.x)
{
if(DebugMode)
Debug.Log("Moving left...");
_currentAnimation = WalkLeft;
_isFacingLeft = true;
_movement.MoveHorizontally(false);
return;
}
else if(location.x > transform.position.x)
{
if(DebugMode)
Debug.Log("Moving right...");
_currentAnimation = WalkRight;
_isFacingLeft = false;
_movement.MoveHorizontally(true);
return;
}
}
private void BeIdle()
{
if(DebugMode)
Debug.Log("I am being idle...");
_lockAnimation = false;
_movement.ClearHorizontalMovement();
_currentAnimation = _isFacingLeft ? IdleLeft : IdleRight;
}
#endregion Methods
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Text;
namespace AE.Net.Mail {
public enum MailPriority {
Normal = 3,
High = 5,
Low = 1
}
[System.Flags]
public enum Flags {
None = 0,
Seen = 1,
Answered = 2,
Flagged = 4,
Deleted = 8,
Draft = 16
}
public class MailMessage : ObjectWHeaders {
public static implicit operator System.Net.Mail.MailMessage(MailMessage msg) {
var ret = new System.Net.Mail.MailMessage();
ret.Subject = msg.Subject;
ret.Sender = msg.Sender;
foreach (var a in msg.Bcc)
ret.Bcc.Add(a);
ret.Body = msg.Body;
ret.IsBodyHtml = msg.ContentType.Contains("html");
ret.From = msg.From;
ret.Priority = (System.Net.Mail.MailPriority)msg.Importance;
foreach (var a in msg.ReplyTo)
ret.ReplyToList.Add(a);
foreach (var a in msg.To)
ret.To.Add(a);
foreach (var a in msg.Attachments)
ret.Attachments.Add(new System.Net.Mail.Attachment(new System.IO.MemoryStream(a.GetData()), a.Filename, a.ContentType));
foreach (var a in msg.AlternateViews)
ret.AlternateViews.Add(new System.Net.Mail.AlternateView(new System.IO.MemoryStream(a.GetData()), a.ContentType));
return ret;
}
private bool _HeadersOnly; // set to true if only headers have been fetched.
public MailMessage() {
RawFlags = new string[0];
To = new Collection<MailAddress>();
Cc = new Collection<MailAddress>();
Bcc = new Collection<MailAddress>();
ReplyTo = new Collection<MailAddress>();
Attachments = new Collection<Attachment>();
AlternateViews = new AlternateViewCollection();
}
public virtual DateTime Date { get; set; }
public virtual string[] RawFlags { get; set; }
public virtual Flags Flags { get; set; }
public virtual int Size { get; internal set; }
public virtual string Subject { get; set; }
public virtual ICollection<MailAddress> To { get; private set; }
public virtual ICollection<MailAddress> Cc { get; private set; }
public virtual ICollection<MailAddress> Bcc { get; private set; }
public virtual ICollection<MailAddress> ReplyTo { get; private set; }
public virtual ICollection<Attachment> Attachments { get; set; }
public virtual AlternateViewCollection AlternateViews { get; set; }
public virtual MailAddress From { get; set; }
public virtual MailAddress Sender { get; set; }
public virtual string MessageID { get; set; }
public virtual string Uid { get; internal set; }
public virtual MailPriority Importance { get; set; }
public virtual void Load(string message, bool headersOnly = false) {
if (string.IsNullOrEmpty(message)) return;
using (var mem = new MemoryStream(_DefaultEncoding.GetBytes(message))) {
Load(mem, headersOnly, message.Length);
}
}
public virtual void Load(Stream reader, bool headersOnly = false, int maxLength = 0, char? termChar = null) {
_HeadersOnly = headersOnly;
Headers = null;
Body = null;
var headers = new StringBuilder();
string line;
while ((line = reader.ReadLine(ref maxLength, _DefaultEncoding, termChar)) != null) {
if (line.Trim().Length == 0)
if (headers.Length == 0)
continue;
else
break;
headers.AppendLine(line);
}
RawHeaders = headers.ToString();
if (!headersOnly) {
string boundary = Headers.GetBoundary();
if (!string.IsNullOrEmpty(boundary)) {
var atts = new List<Attachment>();
var body = ParseMime(reader, boundary, ref maxLength, atts, Encoding, termChar);
if (!string.IsNullOrEmpty(body))
SetBody(body);
foreach (var att in atts)
(att.IsAttachment ? Attachments : AlternateViews).Add(att);
if (maxLength > 0)
reader.ReadToEnd(maxLength, Encoding);
} else {
// sometimes when email doesn't have a body, we get here with maxLength == 0 and we shouldn't read any further
string body = String.Empty;
if (maxLength > 0)
body = reader.ReadToEnd(maxLength, Encoding);
SetBody(body);
}
}
if ((string.IsNullOrWhiteSpace(Body) || ContentType.StartsWith("multipart/")) && AlternateViews.Count > 0) {
var att = AlternateViews.GetTextView() ?? AlternateViews.GetHtmlView();
if (att != null) {
Body = att.Body;
ContentTransferEncoding = att.Headers["Content-Transfer-Encoding"].RawValue;
ContentType = att.Headers["Content-Type"].RawValue;
}
}
Date = Headers.GetDate();
To = Headers.GetMailAddresses("To").ToList();
Cc = Headers.GetMailAddresses("Cc").ToList();
Bcc = Headers.GetMailAddresses("Bcc").ToList();
Sender = Headers.GetMailAddresses("Sender").FirstOrDefault();
ReplyTo = Headers.GetMailAddresses("Reply-To").ToList();
From = Headers.GetMailAddresses("From").FirstOrDefault();
MessageID = Headers["Message-ID"].RawValue;
Importance = Headers.GetEnum<MailPriority>("Importance");
Subject = Headers["Subject"].RawValue;
}
private static string ParseMime(Stream reader, string boundary, ref int maxLength, ICollection<Attachment> attachments, Encoding encoding, char? termChar) {
var maxLengthSpecified = maxLength > 0;
string data = null,
bounderInner = "--" + boundary,
bounderOuter = bounderInner + "--";
var n = 0;
var body = new System.Text.StringBuilder();
do {
if (maxLengthSpecified && maxLength <= 0)
return body.ToString();
if (data != null) {
body.Append(data);
}
data = reader.ReadLine(ref maxLength, encoding, termChar);
n++;
} while (data != null && !data.StartsWith(bounderInner));
while (data != null && !data.StartsWith(bounderOuter) && !(maxLengthSpecified && maxLength == 0)) {
data = reader.ReadLine(ref maxLength, encoding, termChar);
if (data == null) break;
var a = new Attachment { Encoding = encoding };
var part = new StringBuilder();
// read part header
while (!data.StartsWith(bounderInner) && data != string.Empty && !(maxLengthSpecified && maxLength == 0)) {
part.AppendLine(data);
data = reader.ReadLine(ref maxLength, encoding, termChar);
if (data == null) break;
}
a.RawHeaders = part.ToString();
// header body
// check for nested part
var nestedboundary = a.Headers.GetBoundary();
if (!string.IsNullOrEmpty(nestedboundary)) {
ParseMime(reader, nestedboundary, ref maxLength, attachments, encoding, termChar);
while (!data.StartsWith(bounderInner))
data = reader.ReadLine(ref maxLength, encoding, termChar);
} else {
data = reader.ReadLine(ref maxLength, a.Encoding, termChar);
if (data == null) break;
var nestedBody = new StringBuilder();
while (!data.StartsWith(bounderInner) && !(maxLengthSpecified && maxLength == 0)) {
nestedBody.AppendLine(data);
data = reader.ReadLine(ref maxLength, a.Encoding, termChar);
}
a.SetBody(nestedBody.ToString());
attachments.Add(a);
}
}
return body.ToString();
}
private static Dictionary<string, int> _FlagCache = System.Enum.GetValues(typeof(Flags)).Cast<Flags>().ToDictionary(x => x.ToString(), x => (int)x, StringComparer.OrdinalIgnoreCase);
internal void SetFlags(string flags) {
RawFlags = flags.Split(' ').Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
Flags = (Flags)RawFlags.Select(x => {
int flag = 0;
if (_FlagCache.TryGetValue(x.TrimStart('\\'), out flag))
return flag;
else
return 0;
}).Sum();
}
public virtual void Save(System.IO.Stream stream, Encoding encoding = null) {
using (var str = new System.IO.StreamWriter(stream, encoding ?? System.Text.Encoding.Default))
Save(str);
}
private static readonly string[] SpecialHeaders = "Date,To,Cc,Reply-To,Bcc,Sender,From,Message-ID,Importance,Subject".Split(',');
public virtual void Save(System.IO.TextWriter txt) {
txt.WriteLine("Date: {0}", Date.GetRFC2060Date());
txt.WriteLine("To: {0}", string.Join("; ", To.Select(x => x.ToString())));
txt.WriteLine("Cc: {0}", string.Join("; ", Cc.Select(x => x.ToString())));
txt.WriteLine("Reply-To: {0}", string.Join("; ", ReplyTo.Select(x => x.ToString())));
txt.WriteLine("Bcc: {0}", string.Join("; ", Bcc.Select(x => x.ToString())));
if (Sender != null)
txt.WriteLine("Sender: {0}", Sender);
if (From != null)
txt.WriteLine("From: {0}", From);
if (!string.IsNullOrEmpty(MessageID))
txt.WriteLine("Message-ID: {0}", MessageID);
var otherHeaders = Headers.Where(x => !SpecialHeaders.Contains(x.Key, StringComparer.InvariantCultureIgnoreCase));
foreach (var header in otherHeaders) {
txt.WriteLine("{0}: {1}", header.Key, header.Value);
}
if (Importance != MailPriority.Normal)
txt.WriteLine("Importance: {0}", (int)Importance);
txt.WriteLine("Subject: {0}", Subject);
string boundary = null;
if (this.Attachments.Any()) {
boundary = string.Format("--boundary_{0}", Guid.NewGuid());
txt.WriteLine("Content-Type: multipart/mixed; boundary={0}", boundary);
}
// signal end of headers
txt.WriteLine();
if (boundary != null) {
txt.WriteLine("--" + boundary);
txt.WriteLine();
}
txt.Write(Body);
this.Attachments.ToList().ForEach(att => {
txt.WriteLine();
txt.WriteLine("--" + boundary);
txt.WriteLine(string.Join("\n", att.Headers.Select(h => string.Format("{0}: {1}", h.Key, h.Value))));
txt.WriteLine();
txt.WriteLine(att.Body);
});
if (boundary != null) {
txt.WriteLine("--" + boundary + "--");
}
}
}
}
| |
//
// RecommendationPane.cs
//
// Authors:
// Fredrik Hedberg
// Aaron Bockover <[email protected]>
// Lukas Lipka
// Gabriel Burt <[email protected]>
//
// Copyright (C) 2005-2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Linq;
using System.IO;
using System.Net;
using System.Text;
using System.Security.Cryptography;
using Gtk;
using Mono.Unix;
using Hyena;
using Hyena.Gui;
using Hyena.Widgets;
using Lastfm;
using Lastfm.Data;
using Lastfm.Gui;
using Banshee.MediaEngine;
using Banshee.Base;
using Banshee.Configuration;
using Banshee.ServiceStack;
using Banshee.Gui;
using Banshee.Gui.Widgets;
using Banshee.Networking;
using Banshee.Collection;
using Banshee.Widgets;
using Browser = Lastfm.Browser;
namespace Banshee.Lastfm.Recommendations
{
public class RecommendationPane : HBox
{
private ContextPage context_page;
private HBox main_box;
private MessagePane no_artists_pane;
private TitledList artist_box;
private TitledList album_box;
private TitledList track_box;
private Gtk.ScrolledWindow similar_artists_view_sw;
private TileView similar_artists_view;
private VBox album_list;
private VBox track_list;
private static string album_title_format = Catalog.GetString ("Top Albums by {0}");
private static string track_title_format = Catalog.GetString ("Top Tracks by {0}");
private static string[] special_artists = new string[] {
"Unknown",
"Unknown Artists",
"Unknown Artist",
"Various Artists",
"[unknown]",
"[no artist]",
Catalog.GetString ("Unknown Artist"),
Catalog.GetString ("Various Artists")
};
private bool ready = false;
private bool refreshing = false;
private bool show_when_ready = true;
private bool ShowWhenReady {
get { return show_when_ready; }
set {
show_when_ready = value;
ShowIfReady ();
if (!show_when_ready) {
CancelTasks ();
} else if (!ready && !refreshing) {
RefreshRecommendations ();
}
}
}
private void ShowIfReady ()
{
if (ShowWhenReady && ready) {
ShowAll ();
}
}
private string artist;
public string Artist {
get { return artist; }
set {
if (artist == value) {
return;
}
ready = false;
artist = value;
foreach (string special_artist in special_artists) {
if (String.Compare (artist, special_artist, true) == 0) {
artist = null;
break;
}
}
if (!String.IsNullOrEmpty (artist)) {
RefreshRecommendations ();
}
}
}
private void RefreshRecommendations ()
{
CancelTasks ();
if (show_when_ready && !String.IsNullOrEmpty (Artist)) {
refreshing = true;
context_page.SetState (Banshee.ContextPane.ContextState.Loading);
Banshee.Kernel.Scheduler.Schedule (new RefreshRecommendationsJob (this, Artist));
}
}
private void CancelTasks ()
{
Banshee.Kernel.Scheduler.Unschedule (typeof (RefreshRecommendationsJob));
refreshing = false;
}
public void HideWithTimeout ()
{
GLib.Timeout.Add (200, OnHideTimeout);
}
private bool OnHideTimeout ()
{
if (!ShowWhenReady || !ready) {
Hide ();
}
return false;
}
public RecommendationPane (ContextPage contextPage) : base ()
{
this.context_page = contextPage;
main_box = this;
main_box.BorderWidth = 5;
artist_box = new TitledList (Catalog.GetString ("Recommended Artists"));
artist_box.ShowAll ();
similar_artists_view = new TileView (2);
similar_artists_view_sw = new Gtk.ScrolledWindow ();
similar_artists_view_sw.SetPolicy (PolicyType.Never, PolicyType.Automatic);
similar_artists_view_sw.Add (similar_artists_view);
similar_artists_view_sw.ShowAll ();
artist_box.PackStart (similar_artists_view_sw, true, true, 0);
album_box = new TitledList (null);
album_box.TitleWidthChars = 25;
album_box.SizeAllocated += OnSideSizeAllocated;
album_list = new VBox ();
album_box.PackStart (album_list, false, false, 0);
track_box = new TitledList (null);
track_box.SizeAllocated += OnSideSizeAllocated;
track_box.TitleWidthChars = 25;
track_list = new VBox ();
track_box.PackStart (track_list, true, true, 0);
no_artists_pane = new MessagePane ();
no_artists_pane.NoShowAll = true;
no_artists_pane.Visible = false;
string no_results_message;
if (!ApplicationContext.Debugging) {
no_artists_pane.HeaderIcon = IconThemeUtils.LoadIcon (48, "face-sad", Stock.DialogError);
no_results_message = Catalog.GetString("No similar artists found");
} else {
no_artists_pane.HeaderIcon = Gdk.Pixbuf.LoadFromResource ("no-results.png");
no_results_message = "No one likes your music, fool!";
}
no_artists_pane.HeaderMarkup = String.Format ("<big><b>{0}</b></big>", GLib.Markup.EscapeText (no_results_message));
artist_box.PackEnd (no_artists_pane, true, true, 0);
main_box.PackStart (artist_box, true, true, 5);
main_box.PackStart (new VSeparator (), false, false, 0);
main_box.PackStart (album_box, false, false, 5);
main_box.PackStart (new VSeparator (), false, false, 0);
main_box.PackStart (track_box, false, false, 5);
no_artists_pane.Hide ();
}
private void OnSideSizeAllocated (object o, SizeAllocatedArgs args)
{
SetSizeRequest (-1, args.Allocation.Height + (Allocation.Height - args.Allocation.Height));
}
protected override void OnStyleUpdated ()
{
base.OnStyleUpdated ();
similar_artists_view.OverrideBackgroundColor (StateFlags.Normal,
StyleContext.GetBackgroundColor (StateFlags.Normal));
}
private class RefreshRecommendationsJob : Banshee.Kernel.Job
{
private RecommendationPane pane;
private string artist;
public RefreshRecommendationsJob (RecommendationPane pane, string artist)
{
this.pane = pane;
this.artist = artist;
}
protected override void RunJob ()
{
pane.UpdateForArtist (artist);
}
}
private void UpdateForArtist (string artist)
{
try {
LastfmArtistData artist_data = new LastfmArtistData (artist);
// Make sure all the album art is downloaded
foreach (SimilarArtist similar in artist_data.SimilarArtists) {
DataCore.DownloadContent (similar.SmallImageUrl);
}
UpdateForArtist (artist, artist_data.SimilarArtists, artist_data.TopAlbums, artist_data.TopTracks);
} catch (Exception e) {
Log.Error (e);
}
}
private void UpdateForArtist (string artist_name, LastfmData<SimilarArtist> similar_artists,
LastfmData<ArtistTopAlbum> top_albums, LastfmData<ArtistTopTrack> top_tracks)
{
ThreadAssist.ProxyToMain (delegate {
album_box.Title = String.Format (album_title_format, artist);
track_box.Title = String.Format (track_title_format, artist);
similar_artists_view.ClearWidgets ();
ClearBox (album_list);
ClearBox (track_list);
// Similar Artists
var artists = similar_artists.Take (20);
if (artists.Any ()) {
int artist_name_max_len = 2 * (int) artists.Select (a => a.Name.Length).Average ();
foreach (var similar_artist in artists) {
SimilarArtistTile tile = new SimilarArtistTile (similar_artist);
tile.PrimaryLabel.WidthChars = artist_name_max_len;
tile.PrimaryLabel.Ellipsize = Pango.EllipsizeMode.End;
tile.ShowAll ();
similar_artists_view.AddWidget (tile);
}
no_artists_pane.Hide ();
similar_artists_view_sw.ShowAll ();
} else {
similar_artists_view_sw.Hide ();
no_artists_pane.ShowAll ();
}
for (int i = 0; i < Math.Min (5, top_albums.Count); i++) {
ArtistTopAlbum album = top_albums[i];
Button album_button = new Button ();
album_button.Relief = ReliefStyle.None;
Label label = new Label ();
label.OverrideColor (StateFlags.Normal, StyleContext.GetColor (StateFlags.Normal));
label.Ellipsize = Pango.EllipsizeMode.End;
label.Xalign = 0;
label.Markup = String.Format ("{0}. {1}", i+1, GLib.Markup.EscapeText (album.Name));
album_button.Add (label);
album_button.Clicked += delegate {
Banshee.Web.Browser.Open (album.Url);
};
album_list.PackStart (album_button, false, true, 0);
}
album_box.ShowAll ();
for (int i = 0; i < Math.Min (5, top_tracks.Count); i++) {
ArtistTopTrack track = top_tracks[i];
Button track_button = new Button ();
track_button.Relief = ReliefStyle.None;
HBox box = new HBox ();
Label label = new Label ();
label.OverrideColor (StateFlags.Normal, StyleContext.GetColor (StateFlags.Normal));
label.Ellipsize = Pango.EllipsizeMode.End;
label.Xalign = 0;
label.Markup = String.Format ("{0}. {1}", i+1, GLib.Markup.EscapeText (track.Name));
/*if(node.SelectSingleNode("track_id") != null) {
box.PackEnd(new Image(now_playing_arrow), false, false, 0);
track_button.Clicked += delegate {
//PlayerEngineCore.OpenPlay(Globals.Library.GetTrack(
//Convert.ToInt32(node.SelectSingleNode("track_id").InnerText)));
};
} else {*/
track_button.Clicked += delegate {
Banshee.Web.Browser.Open (track.Url);
};
//}
box.PackStart (label, true, true, 0);
track_button.Add (box);
track_list.PackStart (track_button, false, true, 0);
}
track_box.ShowAll ();
ready = true;
refreshing = false;
context_page.SetState (Banshee.ContextPane.ContextState.Loaded);
});
}
private static void ClearBox (Box box)
{
while (box.Children.Length > 0) {
box.Remove (box.Children[0]);
}
}
}
}
| |
namespace CocosSharp
{
internal class CCParticleSystemQuadLoader : CCNodeLoader
{
private const string PROPERTY_EMITERMODE = "emitterMode";
private const string PROPERTY_POSVAR = "posVar";
private const string PROPERTY_EMISSIONRATE = "emissionRate";
private const string PROPERTY_DURATION = "duration";
private const string PROPERTY_TOTALPARTICLES = "totalParticles";
private const string PROPERTY_LIFE = "life";
private const string PROPERTY_STARTSIZE = "startSize";
private const string PROPERTY_ENDSIZE = "endSize";
private const string PROPERTY_STARTSPIN = "startSpin";
private const string PROPERTY_ENDSPIN = "endSpin";
private const string PROPERTY_ANGLE = "angle";
private const string PROPERTY_STARTCOLOR = "startColor";
private const string PROPERTY_ENDCOLOR = "endColor";
private const string PROPERTY_BLENDFUNC = "blendFunc";
private const string PROPERTY_GRAVITY = "gravity";
private const string PROPERTY_SPEED = "speed";
private const string PROPERTY_TANGENTIALACCEL = "tangentialAccel";
private const string PROPERTY_RADIALACCEL = "radialAccel";
private const string PROPERTY_TEXTURE = "texture";
private const string PROPERTY_STARTRADIUS = "startRadius";
private const string PROPERTY_ENDRADIUS = "endRadius";
private const string PROPERTY_ROTATEPERSECOND = "rotatePerSecond";
public override CCNode CreateCCNode()
{
return new CCParticleSystemQuad(new CCParticleSystemConfig());
}
protected override void OnHandlePropTypeIntegerLabeled(CCNode node, CCNode parent, string propertyName, int pIntegerLabeled,
CCBReader reader)
{
if (propertyName == PROPERTY_EMITERMODE)
{
// FIX ME: We want to set EmitterMode only during construction of particle System
// For now we will comment this out
// ((CCParticleSystemQuad) node).EmitterMode = (CCEmitterMode) pIntegerLabeled;
}
else
{
base.OnHandlePropTypeIntegerLabeled(node, parent, propertyName, pIntegerLabeled, reader);
}
}
protected override void OnHandlePropTypePoint(CCNode node, CCNode parent, string propertyName, CCPoint point, CCBReader reader)
{
if (propertyName == PROPERTY_POSVAR)
{
((CCParticleSystemQuad) node).PositionVar = point;
}
else if (propertyName == PROPERTY_GRAVITY)
{
((CCParticleSystemQuad) node).Gravity = point;
}
else
{
base.OnHandlePropTypePoint(node, parent, propertyName, point, reader);
}
}
protected override void OnHandlePropTypeFloat(CCNode node, CCNode parent, string propertyName, float pFloat, CCBReader reader)
{
if (propertyName == PROPERTY_EMISSIONRATE)
{
((CCParticleSystemQuad) node).EmissionRate = pFloat;
}
else if (propertyName == PROPERTY_DURATION)
{
((CCParticleSystemQuad) node).Duration = pFloat;
}
else
{
base.OnHandlePropTypeFloat(node, parent, propertyName, pFloat, reader);
}
}
protected override void OnHandlePropTypeInteger(CCNode node, CCNode parent, string propertyName, int pInteger, CCBReader reader)
{
if (propertyName == PROPERTY_TOTALPARTICLES)
{
((CCParticleSystemQuad) node).TotalParticles = pInteger;
}
else
{
base.OnHandlePropTypeInteger(node, parent, propertyName, pInteger, reader);
}
}
protected override void OnHandlePropTypeFloatVar(CCNode node, CCNode parent, string propertyName, float[] pFloatVar, CCBReader reader)
{
if (propertyName == PROPERTY_LIFE)
{
((CCParticleSystemQuad) node).Life = pFloatVar[0];
((CCParticleSystemQuad) node).LifeVar = pFloatVar[1];
}
else if (propertyName == PROPERTY_STARTSIZE)
{
((CCParticleSystemQuad) node).StartSize = pFloatVar[0];
((CCParticleSystemQuad) node).StartSizeVar = pFloatVar[1];
}
else if (propertyName == PROPERTY_ENDSIZE)
{
((CCParticleSystemQuad) node).EndSize = pFloatVar[0];
((CCParticleSystemQuad) node).EndSizeVar = pFloatVar[1];
}
else if (propertyName == PROPERTY_STARTSPIN)
{
((CCParticleSystemQuad) node).StartSpin = (pFloatVar[0]);
((CCParticleSystemQuad) node).StartSpinVar = (pFloatVar[1]);
}
else if (propertyName == PROPERTY_ENDSPIN)
{
((CCParticleSystemQuad) node).EndSpin = (pFloatVar[0]);
((CCParticleSystemQuad) node).EndSpinVar = (pFloatVar[1]);
}
else if (propertyName == PROPERTY_ANGLE)
{
((CCParticleSystemQuad) node).Angle = (pFloatVar[0]);
((CCParticleSystemQuad) node).AngleVar = (pFloatVar[1]);
}
else if (propertyName == PROPERTY_SPEED)
{
((CCParticleSystemQuad) node).Speed = (pFloatVar[0]);
((CCParticleSystemQuad) node).SpeedVar = (pFloatVar[1]);
}
else if (propertyName == PROPERTY_TANGENTIALACCEL)
{
((CCParticleSystemQuad) node).TangentialAccel = (pFloatVar[0]);
((CCParticleSystemQuad) node).TangentialAccelVar = (pFloatVar[1]);
}
else if (propertyName == PROPERTY_RADIALACCEL)
{
((CCParticleSystemQuad) node).RadialAccel = (pFloatVar[0]);
((CCParticleSystemQuad) node).RadialAccelVar = (pFloatVar[1]);
}
else if (propertyName == PROPERTY_STARTRADIUS)
{
((CCParticleSystemQuad) node).StartRadius = (pFloatVar[0]);
((CCParticleSystemQuad) node).StartRadiusVar = (pFloatVar[1]);
}
else if (propertyName == PROPERTY_ENDRADIUS)
{
((CCParticleSystemQuad) node).EndRadius = (pFloatVar[0]);
((CCParticleSystemQuad) node).EndRadiusVar = (pFloatVar[1]);
}
else if (propertyName == PROPERTY_ROTATEPERSECOND)
{
((CCParticleSystemQuad) node).RotatePerSecond = (pFloatVar[0]);
((CCParticleSystemQuad) node).RotatePerSecondVar = (pFloatVar[1]);
}
else
{
base.OnHandlePropTypeFloatVar(node, parent, propertyName, pFloatVar, reader);
}
}
protected override void OnHandlePropTypeColor4FVar(CCNode node, CCNode parent, string propertyName, CCColor4F[] colorVar,
CCBReader reader)
{
if (propertyName == PROPERTY_STARTCOLOR)
{
((CCParticleSystemQuad) node).StartColor = (colorVar[0]);
((CCParticleSystemQuad) node).StartColorVar = (colorVar[1]);
}
else if (propertyName == PROPERTY_ENDCOLOR)
{
((CCParticleSystemQuad) node).EndColor = (colorVar[0]);
((CCParticleSystemQuad) node).EndColorVar = (colorVar[1]);
}
else
{
base.OnHandlePropTypeColor4FVar(node, parent, propertyName, colorVar, reader);
}
}
protected override void OnHandlePropTypeBlendFunc(CCNode node, CCNode parent, string propertyName, CCBlendFunc blendFunc,
CCBReader reader)
{
if (propertyName == PROPERTY_BLENDFUNC)
{
((CCParticleSystemQuad) node).BlendFunc = blendFunc;
}
else
{
base.OnHandlePropTypeBlendFunc(node, parent, propertyName, blendFunc, reader);
}
}
protected override void OnHandlePropTypeTexture(CCNode node, CCNode parent, string propertyName, CCTexture2D texture,
CCBReader reader)
{
if (propertyName == PROPERTY_TEXTURE)
{
((CCParticleSystemQuad) node).Texture = texture;
}
else
{
base.OnHandlePropTypeTexture(node, parent, propertyName, texture, reader);
}
}
}
}
| |
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 Travelopedia_API.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
namespace Microsoft.Internal
{
internal static class GenerationServices
{
// Type.GetTypeFromHandle
private static readonly MethodInfo _typeGetTypeFromHandleMethod = typeof(Type).GetMethod("GetTypeFromHandle");
// typeofs are pretty expensive, so we cache them statically
private static readonly Type TypeType = typeof(System.Type);
private static readonly Type StringType = typeof(string);
private static readonly Type CharType = typeof(char);
private static readonly Type BooleanType = typeof(bool);
private static readonly Type ByteType = typeof(byte);
private static readonly Type SByteType = typeof(sbyte);
private static readonly Type Int16Type = typeof(short);
private static readonly Type UInt16Type = typeof(ushort);
private static readonly Type Int32Type = typeof(int);
private static readonly Type UInt32Type = typeof(uint);
private static readonly Type Int64Type = typeof(long);
private static readonly Type UInt64Type = typeof(ulong);
private static readonly Type DoubleType = typeof(double);
private static readonly Type SingleType = typeof(float);
private static readonly Type IEnumerableTypeofT = typeof(System.Collections.Generic.IEnumerable<>);
private static readonly Type IEnumerableType = typeof(System.Collections.IEnumerable);
private static readonly MethodInfo ExceptionGetData = typeof(Exception).GetProperty("Data").GetGetMethod();
private static readonly MethodInfo DictionaryAdd = typeof(IDictionary).GetMethod("Add");
private static readonly ConstructorInfo ObjectCtor = typeof(object).GetConstructor(Type.EmptyTypes);
public static ILGenerator CreateGeneratorForPublicConstructor(this TypeBuilder typeBuilder, Type[] ctrArgumentTypes)
{
ConstructorBuilder ctorBuilder = typeBuilder.DefineConstructor(
MethodAttributes.Public,
CallingConventions.Standard,
ctrArgumentTypes);
ILGenerator ctorIL = ctorBuilder.GetILGenerator();
ctorIL.Emit(OpCodes.Ldarg_0);
ctorIL.Emit(OpCodes.Call, ObjectCtor);
return ctorIL;
}
/// Generates the code that loads the supplied value on the stack
/// This is not as simple as it seems, as different instructions need to be generated depending
/// on its type.
/// We support:
/// 1. All primitive types
/// 2. Strings
/// 3. Enums
/// 4. typeofs
/// 5. nulls
/// 6. Enumerables
/// 7. Delegates on static functions or any of the above
/// Everything else cannot be represented as literals
/// <param name="ilGenerator"></param>
/// <param name="value"></param>
public static void LoadValue(this ILGenerator ilGenerator, object value)
{
Debug.Assert(ilGenerator != null);
//
// Get nulls out of the way - they are basically typeless, so we just load null
//
if (value == null)
{
ilGenerator.LoadNull();
return;
}
//
// Prepare for literal loading - decide whether we should box, and handle enums properly
//
Type valueType = value.GetType();
object rawValue = value;
if (valueType.IsEnum)
{
// enums are special - we need to load the underlying constant on the stack
rawValue = Convert.ChangeType(value, Enum.GetUnderlyingType(valueType), null);
valueType = rawValue.GetType();
}
//
// Generate IL depending on the valueType - this is messier than it should ever be, but sadly necessary
//
if (valueType == GenerationServices.StringType)
{
// we need to check for strings before enumerables, because strings are IEnumerable<char>
ilGenerator.LoadString((string)rawValue);
}
else if (GenerationServices.TypeType.IsAssignableFrom(valueType))
{
ilGenerator.LoadTypeOf((Type)rawValue);
}
else if (GenerationServices.IEnumerableType.IsAssignableFrom(valueType))
{
// NOTE : strings and dictionaries are also enumerables, but we have already handled those
ilGenerator.LoadEnumerable((IEnumerable)rawValue);
}
else if (
(valueType == GenerationServices.CharType) ||
(valueType == GenerationServices.BooleanType) ||
(valueType == GenerationServices.ByteType) ||
(valueType == GenerationServices.SByteType) ||
(valueType == GenerationServices.Int16Type) ||
(valueType == GenerationServices.UInt16Type) ||
(valueType == GenerationServices.Int32Type)
)
{
// NOTE : Everything that is 32 bit or less uses ldc.i4. We need to pass int32, even if the actual types is shorter - this is IL memory model
// direct casting to (int) won't work, because the value is boxed, thus we need to use Convert.
// Sadly, this will not work for all cases - namely large uint32 - because they can't semantically fit into 32 signed bits
// We have a special case for that next
ilGenerator.LoadInt((int)Convert.ChangeType(rawValue, typeof(int), CultureInfo.InvariantCulture));
}
else if (valueType == GenerationServices.UInt32Type)
{
// NOTE : This one is a bit tricky. Ldc.I4 takes an Int32 as an argument, although it really treats it as a 32bit number
// That said, some UInt32 values are larger that Int32.MaxValue, so the Convert call above will fail, which is why
// we need to treat this case individually and cast to uint, and then - unchecked - to int.
ilGenerator.LoadInt(unchecked((int)((uint)rawValue)));
}
else if (valueType == GenerationServices.Int64Type)
{
ilGenerator.LoadLong((long)rawValue);
}
else if (valueType == GenerationServices.UInt64Type)
{
// NOTE : This one is a bit tricky. Ldc.I8 takes an Int64 as an argument, although it really treats it as a 64bit number
// That said, some UInt64 values are larger that Int64.MaxValue, so the direct case we use above (or Convert, for that matter)will fail, which is why
// we need to treat this case individually and cast to ulong, and then - unchecked - to long.
ilGenerator.LoadLong(unchecked((long)((ulong)rawValue)));
}
else if (valueType == GenerationServices.SingleType)
{
ilGenerator.LoadFloat((float)rawValue);
}
else if (valueType == GenerationServices.DoubleType)
{
ilGenerator.LoadDouble((double)rawValue);
}
else
{
throw new InvalidOperationException(
SR.Format(SR.InvalidMetadataValue, value.GetType().FullName));
}
}
/// Generates the code that adds an object to a dictionary stored in a local variable
/// <param name="ilGenerator"></param>
/// <param name="dictionary"></param>
/// <param name="key"></param>
/// <param name="value"></param>
public static void AddItemToLocalDictionary(this ILGenerator ilGenerator, LocalBuilder dictionary, object key, object value)
{
Debug.Assert(ilGenerator != null);
if (dictionary == null)
{
throw new ArgumentNullException(nameof(dictionary));
}
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
ilGenerator.Emit(OpCodes.Ldloc, dictionary);
ilGenerator.LoadValue(key);
ilGenerator.LoadValue(value);
ilGenerator.Emit(OpCodes.Callvirt, DictionaryAdd);
}
/// Generates the code that adds an object from a local variable to a dictionary also stored in a local
/// <param name="ilGenerator"></param>
/// <param name="dictionary"></param>
/// <param name="key"></param>
/// <param name="value"></param>
public static void AddLocalToLocalDictionary(this ILGenerator ilGenerator, LocalBuilder dictionary, object key, LocalBuilder value)
{
Debug.Assert(ilGenerator != null);
if (dictionary == null)
{
throw new ArgumentNullException(nameof(dictionary));
}
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
ilGenerator.Emit(OpCodes.Ldloc, dictionary);
ilGenerator.LoadValue(key);
ilGenerator.Emit(OpCodes.Ldloc, value);
ilGenerator.Emit(OpCodes.Callvirt, DictionaryAdd);
}
/// Generates the code to get the type of an object and store it in a local
/// <param name="ilGenerator"></param>
/// <param name="exception"></param>
/// <param name="dataStore"></param>
public static void GetExceptionDataAndStoreInLocal(this ILGenerator ilGenerator, LocalBuilder exception, LocalBuilder dataStore)
{
Debug.Assert(ilGenerator != null);
if (exception == null)
{
throw new ArgumentNullException(nameof(exception));
}
if (dataStore == null)
{
throw new ArgumentNullException(nameof(dataStore));
}
ilGenerator.Emit(OpCodes.Ldloc, exception);
ilGenerator.Emit(OpCodes.Callvirt, ExceptionGetData);
ilGenerator.Emit(OpCodes.Stloc, dataStore);
}
private static void LoadEnumerable(this ILGenerator ilGenerator, IEnumerable enumerable)
{
Debug.Assert(ilGenerator != null);
if (enumerable == null)
{
throw new ArgumentNullException(nameof(enumerable));
}
// We load enumerable as an array - this is the most compact and efficient way of representing it
Type elementType = null;
Type closedType = null;
if (ReflectionServices.TryGetGenericInterfaceType(enumerable.GetType(), GenerationServices.IEnumerableTypeofT, out closedType))
{
elementType = closedType.GetGenericArguments()[0];
}
else
{
elementType = typeof(object);
}
//
// elem[] array = new elem[<enumerable.Count()>]
//
Type generatedArrayType = elementType.MakeArrayType();
LocalBuilder generatedArrayLocal = ilGenerator.DeclareLocal(generatedArrayType);
ilGenerator.LoadInt(enumerable.Cast<object>().Count());
ilGenerator.Emit(OpCodes.Newarr, elementType);
ilGenerator.Emit(OpCodes.Stloc, generatedArrayLocal);
int index = 0;
foreach (object value in enumerable)
{
//
//array[<index>] = value;
//
ilGenerator.Emit(OpCodes.Ldloc, generatedArrayLocal);
ilGenerator.LoadInt(index);
ilGenerator.LoadValue(value);
if (GenerationServices.IsBoxingRequiredForValue(value) && !elementType.IsValueType)
{
ilGenerator.Emit(OpCodes.Box, value.GetType());
}
ilGenerator.Emit(OpCodes.Stelem, elementType);
index++;
}
ilGenerator.Emit(OpCodes.Ldloc, generatedArrayLocal);
}
private static bool IsBoxingRequiredForValue(object value)
{
if (value == null)
{
return false;
}
else
{
return value.GetType().IsValueType;
}
}
private static void LoadNull(this ILGenerator ilGenerator)
{
ilGenerator.Emit(OpCodes.Ldnull);
}
private static void LoadString(this ILGenerator ilGenerator, string s)
{
Debug.Assert(ilGenerator != null);
if (s == null)
{
ilGenerator.LoadNull();
}
else
{
ilGenerator.Emit(OpCodes.Ldstr, s);
}
}
private static void LoadInt(this ILGenerator ilGenerator, int value)
{
Debug.Assert(ilGenerator != null);
ilGenerator.Emit(OpCodes.Ldc_I4, value);
}
private static void LoadLong(this ILGenerator ilGenerator, long value)
{
Debug.Assert(ilGenerator != null);
ilGenerator.Emit(OpCodes.Ldc_I8, value);
}
private static void LoadFloat(this ILGenerator ilGenerator, float value)
{
Debug.Assert(ilGenerator != null);
ilGenerator.Emit(OpCodes.Ldc_R4, value);
}
private static void LoadDouble(this ILGenerator ilGenerator, double value)
{
Debug.Assert(ilGenerator != null);
ilGenerator.Emit(OpCodes.Ldc_R8, value);
}
private static void LoadTypeOf(this ILGenerator ilGenerator, Type type)
{
Debug.Assert(ilGenerator != null);
//typeofs() translate into ldtoken and Type::GetTypeFromHandle call
ilGenerator.Emit(OpCodes.Ldtoken, type);
ilGenerator.EmitCall(OpCodes.Call, GenerationServices._typeGetTypeFromHandleMethod, null);
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using gagr = Google.Api.Gax.ResourceNames;
using lro = Google.LongRunning;
using wkt = Google.Protobuf.WellKnownTypes;
using gr = Google.Rpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.AIPlatform.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedPipelineServiceClientTest
{
[xunit::FactAttribute]
public void CreateTrainingPipelineRequestObject()
{
moq::Mock<PipelineService.PipelineServiceClient> mockGrpcClient = new moq::Mock<PipelineService.PipelineServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateTrainingPipelineRequest request = new CreateTrainingPipelineRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
TrainingPipeline = new TrainingPipeline(),
};
TrainingPipeline expectedResponse = new TrainingPipeline
{
TrainingPipelineName = TrainingPipelineName.FromProjectLocationTrainingPipeline("[PROJECT]", "[LOCATION]", "[TRAINING_PIPELINE]"),
DisplayName = "display_name137f65c2",
InputDataConfig = new InputDataConfig(),
TrainingTaskDefinition = "training_task_definition3e3456be",
TrainingTaskInputs = new wkt::Value(),
TrainingTaskMetadata = new wkt::Value(),
ModelToUpload = new Model(),
State = PipelineState.Running,
Error = new gr::Status(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
EncryptionSpec = new EncryptionSpec(),
};
mockGrpcClient.Setup(x => x.CreateTrainingPipeline(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
PipelineServiceClient client = new PipelineServiceClientImpl(mockGrpcClient.Object, null);
TrainingPipeline response = client.CreateTrainingPipeline(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateTrainingPipelineRequestObjectAsync()
{
moq::Mock<PipelineService.PipelineServiceClient> mockGrpcClient = new moq::Mock<PipelineService.PipelineServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateTrainingPipelineRequest request = new CreateTrainingPipelineRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
TrainingPipeline = new TrainingPipeline(),
};
TrainingPipeline expectedResponse = new TrainingPipeline
{
TrainingPipelineName = TrainingPipelineName.FromProjectLocationTrainingPipeline("[PROJECT]", "[LOCATION]", "[TRAINING_PIPELINE]"),
DisplayName = "display_name137f65c2",
InputDataConfig = new InputDataConfig(),
TrainingTaskDefinition = "training_task_definition3e3456be",
TrainingTaskInputs = new wkt::Value(),
TrainingTaskMetadata = new wkt::Value(),
ModelToUpload = new Model(),
State = PipelineState.Running,
Error = new gr::Status(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
EncryptionSpec = new EncryptionSpec(),
};
mockGrpcClient.Setup(x => x.CreateTrainingPipelineAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TrainingPipeline>(stt::Task.FromResult(expectedResponse), null, null, null, null));
PipelineServiceClient client = new PipelineServiceClientImpl(mockGrpcClient.Object, null);
TrainingPipeline responseCallSettings = await client.CreateTrainingPipelineAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TrainingPipeline responseCancellationToken = await client.CreateTrainingPipelineAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateTrainingPipeline()
{
moq::Mock<PipelineService.PipelineServiceClient> mockGrpcClient = new moq::Mock<PipelineService.PipelineServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateTrainingPipelineRequest request = new CreateTrainingPipelineRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
TrainingPipeline = new TrainingPipeline(),
};
TrainingPipeline expectedResponse = new TrainingPipeline
{
TrainingPipelineName = TrainingPipelineName.FromProjectLocationTrainingPipeline("[PROJECT]", "[LOCATION]", "[TRAINING_PIPELINE]"),
DisplayName = "display_name137f65c2",
InputDataConfig = new InputDataConfig(),
TrainingTaskDefinition = "training_task_definition3e3456be",
TrainingTaskInputs = new wkt::Value(),
TrainingTaskMetadata = new wkt::Value(),
ModelToUpload = new Model(),
State = PipelineState.Running,
Error = new gr::Status(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
EncryptionSpec = new EncryptionSpec(),
};
mockGrpcClient.Setup(x => x.CreateTrainingPipeline(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
PipelineServiceClient client = new PipelineServiceClientImpl(mockGrpcClient.Object, null);
TrainingPipeline response = client.CreateTrainingPipeline(request.Parent, request.TrainingPipeline);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateTrainingPipelineAsync()
{
moq::Mock<PipelineService.PipelineServiceClient> mockGrpcClient = new moq::Mock<PipelineService.PipelineServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateTrainingPipelineRequest request = new CreateTrainingPipelineRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
TrainingPipeline = new TrainingPipeline(),
};
TrainingPipeline expectedResponse = new TrainingPipeline
{
TrainingPipelineName = TrainingPipelineName.FromProjectLocationTrainingPipeline("[PROJECT]", "[LOCATION]", "[TRAINING_PIPELINE]"),
DisplayName = "display_name137f65c2",
InputDataConfig = new InputDataConfig(),
TrainingTaskDefinition = "training_task_definition3e3456be",
TrainingTaskInputs = new wkt::Value(),
TrainingTaskMetadata = new wkt::Value(),
ModelToUpload = new Model(),
State = PipelineState.Running,
Error = new gr::Status(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
EncryptionSpec = new EncryptionSpec(),
};
mockGrpcClient.Setup(x => x.CreateTrainingPipelineAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TrainingPipeline>(stt::Task.FromResult(expectedResponse), null, null, null, null));
PipelineServiceClient client = new PipelineServiceClientImpl(mockGrpcClient.Object, null);
TrainingPipeline responseCallSettings = await client.CreateTrainingPipelineAsync(request.Parent, request.TrainingPipeline, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TrainingPipeline responseCancellationToken = await client.CreateTrainingPipelineAsync(request.Parent, request.TrainingPipeline, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateTrainingPipelineResourceNames()
{
moq::Mock<PipelineService.PipelineServiceClient> mockGrpcClient = new moq::Mock<PipelineService.PipelineServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateTrainingPipelineRequest request = new CreateTrainingPipelineRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
TrainingPipeline = new TrainingPipeline(),
};
TrainingPipeline expectedResponse = new TrainingPipeline
{
TrainingPipelineName = TrainingPipelineName.FromProjectLocationTrainingPipeline("[PROJECT]", "[LOCATION]", "[TRAINING_PIPELINE]"),
DisplayName = "display_name137f65c2",
InputDataConfig = new InputDataConfig(),
TrainingTaskDefinition = "training_task_definition3e3456be",
TrainingTaskInputs = new wkt::Value(),
TrainingTaskMetadata = new wkt::Value(),
ModelToUpload = new Model(),
State = PipelineState.Running,
Error = new gr::Status(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
EncryptionSpec = new EncryptionSpec(),
};
mockGrpcClient.Setup(x => x.CreateTrainingPipeline(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
PipelineServiceClient client = new PipelineServiceClientImpl(mockGrpcClient.Object, null);
TrainingPipeline response = client.CreateTrainingPipeline(request.ParentAsLocationName, request.TrainingPipeline);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateTrainingPipelineResourceNamesAsync()
{
moq::Mock<PipelineService.PipelineServiceClient> mockGrpcClient = new moq::Mock<PipelineService.PipelineServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateTrainingPipelineRequest request = new CreateTrainingPipelineRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
TrainingPipeline = new TrainingPipeline(),
};
TrainingPipeline expectedResponse = new TrainingPipeline
{
TrainingPipelineName = TrainingPipelineName.FromProjectLocationTrainingPipeline("[PROJECT]", "[LOCATION]", "[TRAINING_PIPELINE]"),
DisplayName = "display_name137f65c2",
InputDataConfig = new InputDataConfig(),
TrainingTaskDefinition = "training_task_definition3e3456be",
TrainingTaskInputs = new wkt::Value(),
TrainingTaskMetadata = new wkt::Value(),
ModelToUpload = new Model(),
State = PipelineState.Running,
Error = new gr::Status(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
EncryptionSpec = new EncryptionSpec(),
};
mockGrpcClient.Setup(x => x.CreateTrainingPipelineAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TrainingPipeline>(stt::Task.FromResult(expectedResponse), null, null, null, null));
PipelineServiceClient client = new PipelineServiceClientImpl(mockGrpcClient.Object, null);
TrainingPipeline responseCallSettings = await client.CreateTrainingPipelineAsync(request.ParentAsLocationName, request.TrainingPipeline, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TrainingPipeline responseCancellationToken = await client.CreateTrainingPipelineAsync(request.ParentAsLocationName, request.TrainingPipeline, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetTrainingPipelineRequestObject()
{
moq::Mock<PipelineService.PipelineServiceClient> mockGrpcClient = new moq::Mock<PipelineService.PipelineServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetTrainingPipelineRequest request = new GetTrainingPipelineRequest
{
TrainingPipelineName = TrainingPipelineName.FromProjectLocationTrainingPipeline("[PROJECT]", "[LOCATION]", "[TRAINING_PIPELINE]"),
};
TrainingPipeline expectedResponse = new TrainingPipeline
{
TrainingPipelineName = TrainingPipelineName.FromProjectLocationTrainingPipeline("[PROJECT]", "[LOCATION]", "[TRAINING_PIPELINE]"),
DisplayName = "display_name137f65c2",
InputDataConfig = new InputDataConfig(),
TrainingTaskDefinition = "training_task_definition3e3456be",
TrainingTaskInputs = new wkt::Value(),
TrainingTaskMetadata = new wkt::Value(),
ModelToUpload = new Model(),
State = PipelineState.Running,
Error = new gr::Status(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
EncryptionSpec = new EncryptionSpec(),
};
mockGrpcClient.Setup(x => x.GetTrainingPipeline(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
PipelineServiceClient client = new PipelineServiceClientImpl(mockGrpcClient.Object, null);
TrainingPipeline response = client.GetTrainingPipeline(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetTrainingPipelineRequestObjectAsync()
{
moq::Mock<PipelineService.PipelineServiceClient> mockGrpcClient = new moq::Mock<PipelineService.PipelineServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetTrainingPipelineRequest request = new GetTrainingPipelineRequest
{
TrainingPipelineName = TrainingPipelineName.FromProjectLocationTrainingPipeline("[PROJECT]", "[LOCATION]", "[TRAINING_PIPELINE]"),
};
TrainingPipeline expectedResponse = new TrainingPipeline
{
TrainingPipelineName = TrainingPipelineName.FromProjectLocationTrainingPipeline("[PROJECT]", "[LOCATION]", "[TRAINING_PIPELINE]"),
DisplayName = "display_name137f65c2",
InputDataConfig = new InputDataConfig(),
TrainingTaskDefinition = "training_task_definition3e3456be",
TrainingTaskInputs = new wkt::Value(),
TrainingTaskMetadata = new wkt::Value(),
ModelToUpload = new Model(),
State = PipelineState.Running,
Error = new gr::Status(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
EncryptionSpec = new EncryptionSpec(),
};
mockGrpcClient.Setup(x => x.GetTrainingPipelineAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TrainingPipeline>(stt::Task.FromResult(expectedResponse), null, null, null, null));
PipelineServiceClient client = new PipelineServiceClientImpl(mockGrpcClient.Object, null);
TrainingPipeline responseCallSettings = await client.GetTrainingPipelineAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TrainingPipeline responseCancellationToken = await client.GetTrainingPipelineAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetTrainingPipeline()
{
moq::Mock<PipelineService.PipelineServiceClient> mockGrpcClient = new moq::Mock<PipelineService.PipelineServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetTrainingPipelineRequest request = new GetTrainingPipelineRequest
{
TrainingPipelineName = TrainingPipelineName.FromProjectLocationTrainingPipeline("[PROJECT]", "[LOCATION]", "[TRAINING_PIPELINE]"),
};
TrainingPipeline expectedResponse = new TrainingPipeline
{
TrainingPipelineName = TrainingPipelineName.FromProjectLocationTrainingPipeline("[PROJECT]", "[LOCATION]", "[TRAINING_PIPELINE]"),
DisplayName = "display_name137f65c2",
InputDataConfig = new InputDataConfig(),
TrainingTaskDefinition = "training_task_definition3e3456be",
TrainingTaskInputs = new wkt::Value(),
TrainingTaskMetadata = new wkt::Value(),
ModelToUpload = new Model(),
State = PipelineState.Running,
Error = new gr::Status(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
EncryptionSpec = new EncryptionSpec(),
};
mockGrpcClient.Setup(x => x.GetTrainingPipeline(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
PipelineServiceClient client = new PipelineServiceClientImpl(mockGrpcClient.Object, null);
TrainingPipeline response = client.GetTrainingPipeline(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetTrainingPipelineAsync()
{
moq::Mock<PipelineService.PipelineServiceClient> mockGrpcClient = new moq::Mock<PipelineService.PipelineServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetTrainingPipelineRequest request = new GetTrainingPipelineRequest
{
TrainingPipelineName = TrainingPipelineName.FromProjectLocationTrainingPipeline("[PROJECT]", "[LOCATION]", "[TRAINING_PIPELINE]"),
};
TrainingPipeline expectedResponse = new TrainingPipeline
{
TrainingPipelineName = TrainingPipelineName.FromProjectLocationTrainingPipeline("[PROJECT]", "[LOCATION]", "[TRAINING_PIPELINE]"),
DisplayName = "display_name137f65c2",
InputDataConfig = new InputDataConfig(),
TrainingTaskDefinition = "training_task_definition3e3456be",
TrainingTaskInputs = new wkt::Value(),
TrainingTaskMetadata = new wkt::Value(),
ModelToUpload = new Model(),
State = PipelineState.Running,
Error = new gr::Status(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
EncryptionSpec = new EncryptionSpec(),
};
mockGrpcClient.Setup(x => x.GetTrainingPipelineAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TrainingPipeline>(stt::Task.FromResult(expectedResponse), null, null, null, null));
PipelineServiceClient client = new PipelineServiceClientImpl(mockGrpcClient.Object, null);
TrainingPipeline responseCallSettings = await client.GetTrainingPipelineAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TrainingPipeline responseCancellationToken = await client.GetTrainingPipelineAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetTrainingPipelineResourceNames()
{
moq::Mock<PipelineService.PipelineServiceClient> mockGrpcClient = new moq::Mock<PipelineService.PipelineServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetTrainingPipelineRequest request = new GetTrainingPipelineRequest
{
TrainingPipelineName = TrainingPipelineName.FromProjectLocationTrainingPipeline("[PROJECT]", "[LOCATION]", "[TRAINING_PIPELINE]"),
};
TrainingPipeline expectedResponse = new TrainingPipeline
{
TrainingPipelineName = TrainingPipelineName.FromProjectLocationTrainingPipeline("[PROJECT]", "[LOCATION]", "[TRAINING_PIPELINE]"),
DisplayName = "display_name137f65c2",
InputDataConfig = new InputDataConfig(),
TrainingTaskDefinition = "training_task_definition3e3456be",
TrainingTaskInputs = new wkt::Value(),
TrainingTaskMetadata = new wkt::Value(),
ModelToUpload = new Model(),
State = PipelineState.Running,
Error = new gr::Status(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
EncryptionSpec = new EncryptionSpec(),
};
mockGrpcClient.Setup(x => x.GetTrainingPipeline(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
PipelineServiceClient client = new PipelineServiceClientImpl(mockGrpcClient.Object, null);
TrainingPipeline response = client.GetTrainingPipeline(request.TrainingPipelineName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetTrainingPipelineResourceNamesAsync()
{
moq::Mock<PipelineService.PipelineServiceClient> mockGrpcClient = new moq::Mock<PipelineService.PipelineServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetTrainingPipelineRequest request = new GetTrainingPipelineRequest
{
TrainingPipelineName = TrainingPipelineName.FromProjectLocationTrainingPipeline("[PROJECT]", "[LOCATION]", "[TRAINING_PIPELINE]"),
};
TrainingPipeline expectedResponse = new TrainingPipeline
{
TrainingPipelineName = TrainingPipelineName.FromProjectLocationTrainingPipeline("[PROJECT]", "[LOCATION]", "[TRAINING_PIPELINE]"),
DisplayName = "display_name137f65c2",
InputDataConfig = new InputDataConfig(),
TrainingTaskDefinition = "training_task_definition3e3456be",
TrainingTaskInputs = new wkt::Value(),
TrainingTaskMetadata = new wkt::Value(),
ModelToUpload = new Model(),
State = PipelineState.Running,
Error = new gr::Status(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
EncryptionSpec = new EncryptionSpec(),
};
mockGrpcClient.Setup(x => x.GetTrainingPipelineAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TrainingPipeline>(stt::Task.FromResult(expectedResponse), null, null, null, null));
PipelineServiceClient client = new PipelineServiceClientImpl(mockGrpcClient.Object, null);
TrainingPipeline responseCallSettings = await client.GetTrainingPipelineAsync(request.TrainingPipelineName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TrainingPipeline responseCancellationToken = await client.GetTrainingPipelineAsync(request.TrainingPipelineName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CancelTrainingPipelineRequestObject()
{
moq::Mock<PipelineService.PipelineServiceClient> mockGrpcClient = new moq::Mock<PipelineService.PipelineServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CancelTrainingPipelineRequest request = new CancelTrainingPipelineRequest
{
TrainingPipelineName = TrainingPipelineName.FromProjectLocationTrainingPipeline("[PROJECT]", "[LOCATION]", "[TRAINING_PIPELINE]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.CancelTrainingPipeline(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
PipelineServiceClient client = new PipelineServiceClientImpl(mockGrpcClient.Object, null);
client.CancelTrainingPipeline(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CancelTrainingPipelineRequestObjectAsync()
{
moq::Mock<PipelineService.PipelineServiceClient> mockGrpcClient = new moq::Mock<PipelineService.PipelineServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CancelTrainingPipelineRequest request = new CancelTrainingPipelineRequest
{
TrainingPipelineName = TrainingPipelineName.FromProjectLocationTrainingPipeline("[PROJECT]", "[LOCATION]", "[TRAINING_PIPELINE]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.CancelTrainingPipelineAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
PipelineServiceClient client = new PipelineServiceClientImpl(mockGrpcClient.Object, null);
await client.CancelTrainingPipelineAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.CancelTrainingPipelineAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CancelTrainingPipeline()
{
moq::Mock<PipelineService.PipelineServiceClient> mockGrpcClient = new moq::Mock<PipelineService.PipelineServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CancelTrainingPipelineRequest request = new CancelTrainingPipelineRequest
{
TrainingPipelineName = TrainingPipelineName.FromProjectLocationTrainingPipeline("[PROJECT]", "[LOCATION]", "[TRAINING_PIPELINE]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.CancelTrainingPipeline(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
PipelineServiceClient client = new PipelineServiceClientImpl(mockGrpcClient.Object, null);
client.CancelTrainingPipeline(request.Name);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CancelTrainingPipelineAsync()
{
moq::Mock<PipelineService.PipelineServiceClient> mockGrpcClient = new moq::Mock<PipelineService.PipelineServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CancelTrainingPipelineRequest request = new CancelTrainingPipelineRequest
{
TrainingPipelineName = TrainingPipelineName.FromProjectLocationTrainingPipeline("[PROJECT]", "[LOCATION]", "[TRAINING_PIPELINE]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.CancelTrainingPipelineAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
PipelineServiceClient client = new PipelineServiceClientImpl(mockGrpcClient.Object, null);
await client.CancelTrainingPipelineAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.CancelTrainingPipelineAsync(request.Name, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CancelTrainingPipelineResourceNames()
{
moq::Mock<PipelineService.PipelineServiceClient> mockGrpcClient = new moq::Mock<PipelineService.PipelineServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CancelTrainingPipelineRequest request = new CancelTrainingPipelineRequest
{
TrainingPipelineName = TrainingPipelineName.FromProjectLocationTrainingPipeline("[PROJECT]", "[LOCATION]", "[TRAINING_PIPELINE]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.CancelTrainingPipeline(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
PipelineServiceClient client = new PipelineServiceClientImpl(mockGrpcClient.Object, null);
client.CancelTrainingPipeline(request.TrainingPipelineName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CancelTrainingPipelineResourceNamesAsync()
{
moq::Mock<PipelineService.PipelineServiceClient> mockGrpcClient = new moq::Mock<PipelineService.PipelineServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CancelTrainingPipelineRequest request = new CancelTrainingPipelineRequest
{
TrainingPipelineName = TrainingPipelineName.FromProjectLocationTrainingPipeline("[PROJECT]", "[LOCATION]", "[TRAINING_PIPELINE]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.CancelTrainingPipelineAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
PipelineServiceClient client = new PipelineServiceClientImpl(mockGrpcClient.Object, null);
await client.CancelTrainingPipelineAsync(request.TrainingPipelineName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.CancelTrainingPipelineAsync(request.TrainingPipelineName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreatePipelineJobRequestObject()
{
moq::Mock<PipelineService.PipelineServiceClient> mockGrpcClient = new moq::Mock<PipelineService.PipelineServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreatePipelineJobRequest request = new CreatePipelineJobRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
PipelineJob = new PipelineJob(),
PipelineJobId = "pipeline_job_id54c2a3dd",
};
PipelineJob expectedResponse = new PipelineJob
{
PipelineJobName = PipelineJobName.FromProjectLocationPipelineJob("[PROJECT]", "[LOCATION]", "[PIPELINE_JOB]"),
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
PipelineSpec = new wkt::Struct(),
State = PipelineState.Running,
JobDetail = new PipelineJobDetail(),
Error = new gr::Status(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
RuntimeConfig = new PipelineJob.Types.RuntimeConfig(),
EncryptionSpec = new EncryptionSpec(),
ServiceAccount = "service_accounta3c1b923",
NetworkAsNetworkName = NetworkName.FromProjectNetwork("[PROJECT]", "[NETWORK]"),
};
mockGrpcClient.Setup(x => x.CreatePipelineJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
PipelineServiceClient client = new PipelineServiceClientImpl(mockGrpcClient.Object, null);
PipelineJob response = client.CreatePipelineJob(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreatePipelineJobRequestObjectAsync()
{
moq::Mock<PipelineService.PipelineServiceClient> mockGrpcClient = new moq::Mock<PipelineService.PipelineServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreatePipelineJobRequest request = new CreatePipelineJobRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
PipelineJob = new PipelineJob(),
PipelineJobId = "pipeline_job_id54c2a3dd",
};
PipelineJob expectedResponse = new PipelineJob
{
PipelineJobName = PipelineJobName.FromProjectLocationPipelineJob("[PROJECT]", "[LOCATION]", "[PIPELINE_JOB]"),
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
PipelineSpec = new wkt::Struct(),
State = PipelineState.Running,
JobDetail = new PipelineJobDetail(),
Error = new gr::Status(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
RuntimeConfig = new PipelineJob.Types.RuntimeConfig(),
EncryptionSpec = new EncryptionSpec(),
ServiceAccount = "service_accounta3c1b923",
NetworkAsNetworkName = NetworkName.FromProjectNetwork("[PROJECT]", "[NETWORK]"),
};
mockGrpcClient.Setup(x => x.CreatePipelineJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PipelineJob>(stt::Task.FromResult(expectedResponse), null, null, null, null));
PipelineServiceClient client = new PipelineServiceClientImpl(mockGrpcClient.Object, null);
PipelineJob responseCallSettings = await client.CreatePipelineJobAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
PipelineJob responseCancellationToken = await client.CreatePipelineJobAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreatePipelineJob()
{
moq::Mock<PipelineService.PipelineServiceClient> mockGrpcClient = new moq::Mock<PipelineService.PipelineServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreatePipelineJobRequest request = new CreatePipelineJobRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
PipelineJob = new PipelineJob(),
PipelineJobId = "pipeline_job_id54c2a3dd",
};
PipelineJob expectedResponse = new PipelineJob
{
PipelineJobName = PipelineJobName.FromProjectLocationPipelineJob("[PROJECT]", "[LOCATION]", "[PIPELINE_JOB]"),
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
PipelineSpec = new wkt::Struct(),
State = PipelineState.Running,
JobDetail = new PipelineJobDetail(),
Error = new gr::Status(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
RuntimeConfig = new PipelineJob.Types.RuntimeConfig(),
EncryptionSpec = new EncryptionSpec(),
ServiceAccount = "service_accounta3c1b923",
NetworkAsNetworkName = NetworkName.FromProjectNetwork("[PROJECT]", "[NETWORK]"),
};
mockGrpcClient.Setup(x => x.CreatePipelineJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
PipelineServiceClient client = new PipelineServiceClientImpl(mockGrpcClient.Object, null);
PipelineJob response = client.CreatePipelineJob(request.Parent, request.PipelineJob, request.PipelineJobId);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreatePipelineJobAsync()
{
moq::Mock<PipelineService.PipelineServiceClient> mockGrpcClient = new moq::Mock<PipelineService.PipelineServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreatePipelineJobRequest request = new CreatePipelineJobRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
PipelineJob = new PipelineJob(),
PipelineJobId = "pipeline_job_id54c2a3dd",
};
PipelineJob expectedResponse = new PipelineJob
{
PipelineJobName = PipelineJobName.FromProjectLocationPipelineJob("[PROJECT]", "[LOCATION]", "[PIPELINE_JOB]"),
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
PipelineSpec = new wkt::Struct(),
State = PipelineState.Running,
JobDetail = new PipelineJobDetail(),
Error = new gr::Status(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
RuntimeConfig = new PipelineJob.Types.RuntimeConfig(),
EncryptionSpec = new EncryptionSpec(),
ServiceAccount = "service_accounta3c1b923",
NetworkAsNetworkName = NetworkName.FromProjectNetwork("[PROJECT]", "[NETWORK]"),
};
mockGrpcClient.Setup(x => x.CreatePipelineJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PipelineJob>(stt::Task.FromResult(expectedResponse), null, null, null, null));
PipelineServiceClient client = new PipelineServiceClientImpl(mockGrpcClient.Object, null);
PipelineJob responseCallSettings = await client.CreatePipelineJobAsync(request.Parent, request.PipelineJob, request.PipelineJobId, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
PipelineJob responseCancellationToken = await client.CreatePipelineJobAsync(request.Parent, request.PipelineJob, request.PipelineJobId, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreatePipelineJobResourceNames()
{
moq::Mock<PipelineService.PipelineServiceClient> mockGrpcClient = new moq::Mock<PipelineService.PipelineServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreatePipelineJobRequest request = new CreatePipelineJobRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
PipelineJob = new PipelineJob(),
PipelineJobId = "pipeline_job_id54c2a3dd",
};
PipelineJob expectedResponse = new PipelineJob
{
PipelineJobName = PipelineJobName.FromProjectLocationPipelineJob("[PROJECT]", "[LOCATION]", "[PIPELINE_JOB]"),
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
PipelineSpec = new wkt::Struct(),
State = PipelineState.Running,
JobDetail = new PipelineJobDetail(),
Error = new gr::Status(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
RuntimeConfig = new PipelineJob.Types.RuntimeConfig(),
EncryptionSpec = new EncryptionSpec(),
ServiceAccount = "service_accounta3c1b923",
NetworkAsNetworkName = NetworkName.FromProjectNetwork("[PROJECT]", "[NETWORK]"),
};
mockGrpcClient.Setup(x => x.CreatePipelineJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
PipelineServiceClient client = new PipelineServiceClientImpl(mockGrpcClient.Object, null);
PipelineJob response = client.CreatePipelineJob(request.ParentAsLocationName, request.PipelineJob, request.PipelineJobId);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreatePipelineJobResourceNamesAsync()
{
moq::Mock<PipelineService.PipelineServiceClient> mockGrpcClient = new moq::Mock<PipelineService.PipelineServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreatePipelineJobRequest request = new CreatePipelineJobRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
PipelineJob = new PipelineJob(),
PipelineJobId = "pipeline_job_id54c2a3dd",
};
PipelineJob expectedResponse = new PipelineJob
{
PipelineJobName = PipelineJobName.FromProjectLocationPipelineJob("[PROJECT]", "[LOCATION]", "[PIPELINE_JOB]"),
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
PipelineSpec = new wkt::Struct(),
State = PipelineState.Running,
JobDetail = new PipelineJobDetail(),
Error = new gr::Status(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
RuntimeConfig = new PipelineJob.Types.RuntimeConfig(),
EncryptionSpec = new EncryptionSpec(),
ServiceAccount = "service_accounta3c1b923",
NetworkAsNetworkName = NetworkName.FromProjectNetwork("[PROJECT]", "[NETWORK]"),
};
mockGrpcClient.Setup(x => x.CreatePipelineJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PipelineJob>(stt::Task.FromResult(expectedResponse), null, null, null, null));
PipelineServiceClient client = new PipelineServiceClientImpl(mockGrpcClient.Object, null);
PipelineJob responseCallSettings = await client.CreatePipelineJobAsync(request.ParentAsLocationName, request.PipelineJob, request.PipelineJobId, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
PipelineJob responseCancellationToken = await client.CreatePipelineJobAsync(request.ParentAsLocationName, request.PipelineJob, request.PipelineJobId, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetPipelineJobRequestObject()
{
moq::Mock<PipelineService.PipelineServiceClient> mockGrpcClient = new moq::Mock<PipelineService.PipelineServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetPipelineJobRequest request = new GetPipelineJobRequest
{
PipelineJobName = PipelineJobName.FromProjectLocationPipelineJob("[PROJECT]", "[LOCATION]", "[PIPELINE_JOB]"),
};
PipelineJob expectedResponse = new PipelineJob
{
PipelineJobName = PipelineJobName.FromProjectLocationPipelineJob("[PROJECT]", "[LOCATION]", "[PIPELINE_JOB]"),
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
PipelineSpec = new wkt::Struct(),
State = PipelineState.Running,
JobDetail = new PipelineJobDetail(),
Error = new gr::Status(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
RuntimeConfig = new PipelineJob.Types.RuntimeConfig(),
EncryptionSpec = new EncryptionSpec(),
ServiceAccount = "service_accounta3c1b923",
NetworkAsNetworkName = NetworkName.FromProjectNetwork("[PROJECT]", "[NETWORK]"),
};
mockGrpcClient.Setup(x => x.GetPipelineJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
PipelineServiceClient client = new PipelineServiceClientImpl(mockGrpcClient.Object, null);
PipelineJob response = client.GetPipelineJob(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetPipelineJobRequestObjectAsync()
{
moq::Mock<PipelineService.PipelineServiceClient> mockGrpcClient = new moq::Mock<PipelineService.PipelineServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetPipelineJobRequest request = new GetPipelineJobRequest
{
PipelineJobName = PipelineJobName.FromProjectLocationPipelineJob("[PROJECT]", "[LOCATION]", "[PIPELINE_JOB]"),
};
PipelineJob expectedResponse = new PipelineJob
{
PipelineJobName = PipelineJobName.FromProjectLocationPipelineJob("[PROJECT]", "[LOCATION]", "[PIPELINE_JOB]"),
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
PipelineSpec = new wkt::Struct(),
State = PipelineState.Running,
JobDetail = new PipelineJobDetail(),
Error = new gr::Status(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
RuntimeConfig = new PipelineJob.Types.RuntimeConfig(),
EncryptionSpec = new EncryptionSpec(),
ServiceAccount = "service_accounta3c1b923",
NetworkAsNetworkName = NetworkName.FromProjectNetwork("[PROJECT]", "[NETWORK]"),
};
mockGrpcClient.Setup(x => x.GetPipelineJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PipelineJob>(stt::Task.FromResult(expectedResponse), null, null, null, null));
PipelineServiceClient client = new PipelineServiceClientImpl(mockGrpcClient.Object, null);
PipelineJob responseCallSettings = await client.GetPipelineJobAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
PipelineJob responseCancellationToken = await client.GetPipelineJobAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetPipelineJob()
{
moq::Mock<PipelineService.PipelineServiceClient> mockGrpcClient = new moq::Mock<PipelineService.PipelineServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetPipelineJobRequest request = new GetPipelineJobRequest
{
PipelineJobName = PipelineJobName.FromProjectLocationPipelineJob("[PROJECT]", "[LOCATION]", "[PIPELINE_JOB]"),
};
PipelineJob expectedResponse = new PipelineJob
{
PipelineJobName = PipelineJobName.FromProjectLocationPipelineJob("[PROJECT]", "[LOCATION]", "[PIPELINE_JOB]"),
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
PipelineSpec = new wkt::Struct(),
State = PipelineState.Running,
JobDetail = new PipelineJobDetail(),
Error = new gr::Status(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
RuntimeConfig = new PipelineJob.Types.RuntimeConfig(),
EncryptionSpec = new EncryptionSpec(),
ServiceAccount = "service_accounta3c1b923",
NetworkAsNetworkName = NetworkName.FromProjectNetwork("[PROJECT]", "[NETWORK]"),
};
mockGrpcClient.Setup(x => x.GetPipelineJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
PipelineServiceClient client = new PipelineServiceClientImpl(mockGrpcClient.Object, null);
PipelineJob response = client.GetPipelineJob(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetPipelineJobAsync()
{
moq::Mock<PipelineService.PipelineServiceClient> mockGrpcClient = new moq::Mock<PipelineService.PipelineServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetPipelineJobRequest request = new GetPipelineJobRequest
{
PipelineJobName = PipelineJobName.FromProjectLocationPipelineJob("[PROJECT]", "[LOCATION]", "[PIPELINE_JOB]"),
};
PipelineJob expectedResponse = new PipelineJob
{
PipelineJobName = PipelineJobName.FromProjectLocationPipelineJob("[PROJECT]", "[LOCATION]", "[PIPELINE_JOB]"),
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
PipelineSpec = new wkt::Struct(),
State = PipelineState.Running,
JobDetail = new PipelineJobDetail(),
Error = new gr::Status(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
RuntimeConfig = new PipelineJob.Types.RuntimeConfig(),
EncryptionSpec = new EncryptionSpec(),
ServiceAccount = "service_accounta3c1b923",
NetworkAsNetworkName = NetworkName.FromProjectNetwork("[PROJECT]", "[NETWORK]"),
};
mockGrpcClient.Setup(x => x.GetPipelineJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PipelineJob>(stt::Task.FromResult(expectedResponse), null, null, null, null));
PipelineServiceClient client = new PipelineServiceClientImpl(mockGrpcClient.Object, null);
PipelineJob responseCallSettings = await client.GetPipelineJobAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
PipelineJob responseCancellationToken = await client.GetPipelineJobAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetPipelineJobResourceNames()
{
moq::Mock<PipelineService.PipelineServiceClient> mockGrpcClient = new moq::Mock<PipelineService.PipelineServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetPipelineJobRequest request = new GetPipelineJobRequest
{
PipelineJobName = PipelineJobName.FromProjectLocationPipelineJob("[PROJECT]", "[LOCATION]", "[PIPELINE_JOB]"),
};
PipelineJob expectedResponse = new PipelineJob
{
PipelineJobName = PipelineJobName.FromProjectLocationPipelineJob("[PROJECT]", "[LOCATION]", "[PIPELINE_JOB]"),
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
PipelineSpec = new wkt::Struct(),
State = PipelineState.Running,
JobDetail = new PipelineJobDetail(),
Error = new gr::Status(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
RuntimeConfig = new PipelineJob.Types.RuntimeConfig(),
EncryptionSpec = new EncryptionSpec(),
ServiceAccount = "service_accounta3c1b923",
NetworkAsNetworkName = NetworkName.FromProjectNetwork("[PROJECT]", "[NETWORK]"),
};
mockGrpcClient.Setup(x => x.GetPipelineJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
PipelineServiceClient client = new PipelineServiceClientImpl(mockGrpcClient.Object, null);
PipelineJob response = client.GetPipelineJob(request.PipelineJobName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetPipelineJobResourceNamesAsync()
{
moq::Mock<PipelineService.PipelineServiceClient> mockGrpcClient = new moq::Mock<PipelineService.PipelineServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetPipelineJobRequest request = new GetPipelineJobRequest
{
PipelineJobName = PipelineJobName.FromProjectLocationPipelineJob("[PROJECT]", "[LOCATION]", "[PIPELINE_JOB]"),
};
PipelineJob expectedResponse = new PipelineJob
{
PipelineJobName = PipelineJobName.FromProjectLocationPipelineJob("[PROJECT]", "[LOCATION]", "[PIPELINE_JOB]"),
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
PipelineSpec = new wkt::Struct(),
State = PipelineState.Running,
JobDetail = new PipelineJobDetail(),
Error = new gr::Status(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
RuntimeConfig = new PipelineJob.Types.RuntimeConfig(),
EncryptionSpec = new EncryptionSpec(),
ServiceAccount = "service_accounta3c1b923",
NetworkAsNetworkName = NetworkName.FromProjectNetwork("[PROJECT]", "[NETWORK]"),
};
mockGrpcClient.Setup(x => x.GetPipelineJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PipelineJob>(stt::Task.FromResult(expectedResponse), null, null, null, null));
PipelineServiceClient client = new PipelineServiceClientImpl(mockGrpcClient.Object, null);
PipelineJob responseCallSettings = await client.GetPipelineJobAsync(request.PipelineJobName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
PipelineJob responseCancellationToken = await client.GetPipelineJobAsync(request.PipelineJobName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CancelPipelineJobRequestObject()
{
moq::Mock<PipelineService.PipelineServiceClient> mockGrpcClient = new moq::Mock<PipelineService.PipelineServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CancelPipelineJobRequest request = new CancelPipelineJobRequest
{
PipelineJobName = PipelineJobName.FromProjectLocationPipelineJob("[PROJECT]", "[LOCATION]", "[PIPELINE_JOB]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.CancelPipelineJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
PipelineServiceClient client = new PipelineServiceClientImpl(mockGrpcClient.Object, null);
client.CancelPipelineJob(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CancelPipelineJobRequestObjectAsync()
{
moq::Mock<PipelineService.PipelineServiceClient> mockGrpcClient = new moq::Mock<PipelineService.PipelineServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CancelPipelineJobRequest request = new CancelPipelineJobRequest
{
PipelineJobName = PipelineJobName.FromProjectLocationPipelineJob("[PROJECT]", "[LOCATION]", "[PIPELINE_JOB]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.CancelPipelineJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
PipelineServiceClient client = new PipelineServiceClientImpl(mockGrpcClient.Object, null);
await client.CancelPipelineJobAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.CancelPipelineJobAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CancelPipelineJob()
{
moq::Mock<PipelineService.PipelineServiceClient> mockGrpcClient = new moq::Mock<PipelineService.PipelineServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CancelPipelineJobRequest request = new CancelPipelineJobRequest
{
PipelineJobName = PipelineJobName.FromProjectLocationPipelineJob("[PROJECT]", "[LOCATION]", "[PIPELINE_JOB]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.CancelPipelineJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
PipelineServiceClient client = new PipelineServiceClientImpl(mockGrpcClient.Object, null);
client.CancelPipelineJob(request.Name);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CancelPipelineJobAsync()
{
moq::Mock<PipelineService.PipelineServiceClient> mockGrpcClient = new moq::Mock<PipelineService.PipelineServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CancelPipelineJobRequest request = new CancelPipelineJobRequest
{
PipelineJobName = PipelineJobName.FromProjectLocationPipelineJob("[PROJECT]", "[LOCATION]", "[PIPELINE_JOB]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.CancelPipelineJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
PipelineServiceClient client = new PipelineServiceClientImpl(mockGrpcClient.Object, null);
await client.CancelPipelineJobAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.CancelPipelineJobAsync(request.Name, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CancelPipelineJobResourceNames()
{
moq::Mock<PipelineService.PipelineServiceClient> mockGrpcClient = new moq::Mock<PipelineService.PipelineServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CancelPipelineJobRequest request = new CancelPipelineJobRequest
{
PipelineJobName = PipelineJobName.FromProjectLocationPipelineJob("[PROJECT]", "[LOCATION]", "[PIPELINE_JOB]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.CancelPipelineJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
PipelineServiceClient client = new PipelineServiceClientImpl(mockGrpcClient.Object, null);
client.CancelPipelineJob(request.PipelineJobName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CancelPipelineJobResourceNamesAsync()
{
moq::Mock<PipelineService.PipelineServiceClient> mockGrpcClient = new moq::Mock<PipelineService.PipelineServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CancelPipelineJobRequest request = new CancelPipelineJobRequest
{
PipelineJobName = PipelineJobName.FromProjectLocationPipelineJob("[PROJECT]", "[LOCATION]", "[PIPELINE_JOB]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.CancelPipelineJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
PipelineServiceClient client = new PipelineServiceClientImpl(mockGrpcClient.Object, null);
await client.CancelPipelineJobAsync(request.PipelineJobName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.CancelPipelineJobAsync(request.PipelineJobName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: Some floating-point math operations
**
**
===========================================================*/
//This class contains only static members and doesn't require serialization.
using System;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
namespace System
{
public static class Math
{
private static double doubleRoundLimit = 1e16d;
private const int maxRoundingDigits = 15;
// This table is required for the Round function which can specify the number of digits to round to
private static double[] roundPower10Double = new double[] {
1E0, 1E1, 1E2, 1E3, 1E4, 1E5, 1E6, 1E7, 1E8,
1E9, 1E10, 1E11, 1E12, 1E13, 1E14, 1E15
};
public const double PI = 3.14159265358979323846;
public const double E = 2.7182818284590452354;
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Acos(double d);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Asin(double d);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Atan(double d);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Atan2(double y, double x);
public static Decimal Ceiling(Decimal d)
{
return Decimal.Ceiling(d);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Ceiling(double a);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Cos(double d);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Cosh(double value);
public static Decimal Floor(Decimal d)
{
return Decimal.Floor(d);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Floor(double d);
private static unsafe double InternalRound(double value, int digits, MidpointRounding mode)
{
if (Abs(value) < doubleRoundLimit)
{
Double power10 = roundPower10Double[digits];
value *= power10;
if (mode == MidpointRounding.AwayFromZero)
{
double fraction = SplitFractionDouble(&value);
if (Abs(fraction) >= 0.5d)
{
value += Sign(fraction);
}
}
else
{
// On X86 this can be inlined to just a few instructions
value = Round(value);
}
value /= power10;
}
return value;
}
private unsafe static double InternalTruncate(double d)
{
SplitFractionDouble(&d);
return d;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Sin(double a);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Tan(double a);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Sinh(double value);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Tanh(double value);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Round(double a);
public static double Round(double value, int digits)
{
if ((digits < 0) || (digits > maxRoundingDigits))
throw new ArgumentOutOfRangeException(nameof(digits), SR.ArgumentOutOfRange_RoundingDigits);
Contract.EndContractBlock();
return InternalRound(value, digits, MidpointRounding.ToEven);
}
public static double Round(double value, MidpointRounding mode)
{
return Round(value, 0, mode);
}
public static double Round(double value, int digits, MidpointRounding mode)
{
if ((digits < 0) || (digits > maxRoundingDigits))
throw new ArgumentOutOfRangeException(nameof(digits), SR.ArgumentOutOfRange_RoundingDigits);
if (mode < MidpointRounding.ToEven || mode > MidpointRounding.AwayFromZero)
{
throw new ArgumentException(SR.Format(SR.Argument_InvalidEnumValue, mode, nameof(MidpointRounding)), nameof(mode));
}
Contract.EndContractBlock();
return InternalRound(value, digits, mode);
}
public static Decimal Round(Decimal d)
{
return Decimal.Round(d, 0);
}
public static Decimal Round(Decimal d, int decimals)
{
return Decimal.Round(d, decimals);
}
public static Decimal Round(Decimal d, MidpointRounding mode)
{
return Decimal.Round(d, 0, mode);
}
public static Decimal Round(Decimal d, int decimals, MidpointRounding mode)
{
return Decimal.Round(d, decimals, mode);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static unsafe extern double SplitFractionDouble(double* value);
public static Decimal Truncate(Decimal d)
{
return Decimal.Truncate(d);
}
public static double Truncate(double d)
{
return InternalTruncate(d);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Sqrt(double d);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Log(double d);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Log10(double d);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Exp(double d);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Pow(double x, double y);
public static double IEEERemainder(double x, double y)
{
if (Double.IsNaN(x))
{
return x; // IEEE 754-2008: NaN payload must be preserved
}
if (Double.IsNaN(y))
{
return y; // IEEE 754-2008: NaN payload must be preserved
}
double regularMod = x % y;
if (Double.IsNaN(regularMod))
{
return Double.NaN;
}
if (regularMod == 0)
{
if (Double.IsNegative(x))
{
return Double.NegativeZero;
}
}
double alternativeResult;
alternativeResult = regularMod - (Math.Abs(y) * Math.Sign(x));
if (Math.Abs(alternativeResult) == Math.Abs(regularMod))
{
double divisionResult = x / y;
double roundedResult = Math.Round(divisionResult);
if (Math.Abs(roundedResult) > Math.Abs(divisionResult))
{
return alternativeResult;
}
else
{
return regularMod;
}
}
if (Math.Abs(alternativeResult) < Math.Abs(regularMod))
{
return alternativeResult;
}
else
{
return regularMod;
}
}
/*================================Abs=========================================
**Returns the absolute value of it's argument.
============================================================================*/
[CLSCompliant(false)]
public static sbyte Abs(sbyte value)
{
if (value >= 0)
return value;
else
return AbsHelper(value);
}
private static sbyte AbsHelper(sbyte value)
{
Contract.Requires(value < 0, "AbsHelper should only be called for negative values! (workaround for JIT inlining)");
if (value == SByte.MinValue)
throw new OverflowException(SR.Overflow_NegateTwosCompNum);
Contract.EndContractBlock();
return ((sbyte)(-value));
}
public static short Abs(short value)
{
if (value >= 0)
return value;
else
return AbsHelper(value);
}
private static short AbsHelper(short value)
{
Contract.Requires(value < 0, "AbsHelper should only be called for negative values! (workaround for JIT inlining)");
if (value == Int16.MinValue)
throw new OverflowException(SR.Overflow_NegateTwosCompNum);
Contract.EndContractBlock();
return (short)-value;
}
public static int Abs(int value)
{
if (value >= 0)
return value;
else
return AbsHelper(value);
}
private static int AbsHelper(int value)
{
Contract.Requires(value < 0, "AbsHelper should only be called for negative values! (workaround for JIT inlining)");
if (value == Int32.MinValue)
throw new OverflowException(SR.Overflow_NegateTwosCompNum);
Contract.EndContractBlock();
return -value;
}
public static long Abs(long value)
{
if (value >= 0)
return value;
else
return AbsHelper(value);
}
private static long AbsHelper(long value)
{
Contract.Requires(value < 0, "AbsHelper should only be called for negative values! (workaround for JIT inlining)");
if (value == Int64.MinValue)
throw new OverflowException(SR.Overflow_NegateTwosCompNum);
Contract.EndContractBlock();
return -value;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern public static float Abs(float value);
// This is special code to handle NaN (We need to make sure NaN's aren't
// negated). In CSharp, the else clause here should always be taken if
// value is NaN, since the normal case is taken if and only if value < 0.
// To illustrate this completely, a compiler has translated this into:
// "load value; load 0; bge; ret -value ; ret value".
// The bge command branches for comparisons with the unordered NaN. So
// it runs the else case, which returns +value instead of negating it.
// return (value < 0) ? -value : value;
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern public static double Abs(double value);
// This is special code to handle NaN (We need to make sure NaN's aren't
// negated). In CSharp, the else clause here should always be taken if
// value is NaN, since the normal case is taken if and only if value < 0.
// To illustrate this completely, a compiler has translated this into:
// "load value; load 0; bge; ret -value ; ret value".
// The bge command branches for comparisons with the unordered NaN. So
// it runs the else case, which returns +value instead of negating it.
// return (value < 0) ? -value : value;
public static Decimal Abs(Decimal value)
{
return Decimal.Abs(value);
}
/*================================MAX=========================================
**Returns the larger of val1 and val2
============================================================================*/
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public static sbyte Max(sbyte val1, sbyte val2)
{
return (val1 >= val2) ? val1 : val2;
}
[System.Runtime.Versioning.NonVersionable]
public static byte Max(byte val1, byte val2)
{
return (val1 >= val2) ? val1 : val2;
}
[System.Runtime.Versioning.NonVersionable]
public static short Max(short val1, short val2)
{
return (val1 >= val2) ? val1 : val2;
}
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public static ushort Max(ushort val1, ushort val2)
{
return (val1 >= val2) ? val1 : val2;
}
[System.Runtime.Versioning.NonVersionable]
public static int Max(int val1, int val2)
{
return (val1 >= val2) ? val1 : val2;
}
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public static uint Max(uint val1, uint val2)
{
return (val1 >= val2) ? val1 : val2;
}
[System.Runtime.Versioning.NonVersionable]
public static long Max(long val1, long val2)
{
return (val1 >= val2) ? val1 : val2;
}
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public static ulong Max(ulong val1, ulong val2)
{
return (val1 >= val2) ? val1 : val2;
}
public static float Max(float val1, float val2)
{
if (val1 > val2)
return val1;
if (Single.IsNaN(val1))
return val1;
return val2;
}
public static double Max(double val1, double val2)
{
if (val1 > val2)
return val1;
if (Double.IsNaN(val1))
return val1;
return val2;
}
public static Decimal Max(Decimal val1, Decimal val2)
{
return Decimal.Max(val1, val2);
}
/*================================MIN=========================================
**Returns the smaller of val1 and val2.
============================================================================*/
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public static sbyte Min(sbyte val1, sbyte val2)
{
return (val1 <= val2) ? val1 : val2;
}
[System.Runtime.Versioning.NonVersionable]
public static byte Min(byte val1, byte val2)
{
return (val1 <= val2) ? val1 : val2;
}
[System.Runtime.Versioning.NonVersionable]
public static short Min(short val1, short val2)
{
return (val1 <= val2) ? val1 : val2;
}
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public static ushort Min(ushort val1, ushort val2)
{
return (val1 <= val2) ? val1 : val2;
}
[System.Runtime.Versioning.NonVersionable]
public static int Min(int val1, int val2)
{
return (val1 <= val2) ? val1 : val2;
}
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public static uint Min(uint val1, uint val2)
{
return (val1 <= val2) ? val1 : val2;
}
[System.Runtime.Versioning.NonVersionable]
public static long Min(long val1, long val2)
{
return (val1 <= val2) ? val1 : val2;
}
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public static ulong Min(ulong val1, ulong val2)
{
return (val1 <= val2) ? val1 : val2;
}
public static float Min(float val1, float val2)
{
if (val1 < val2)
return val1;
if (Single.IsNaN(val1))
return val1;
return val2;
}
public static double Min(double val1, double val2)
{
if (val1 < val2)
return val1;
if (Double.IsNaN(val1))
return val1;
return val2;
}
public static Decimal Min(Decimal val1, Decimal val2)
{
return Decimal.Min(val1, val2);
}
/*=====================================Clamp====================================
**
==============================================================================*/
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Byte Clamp(Byte value, Byte min, Byte max)
{
if (min > max)
ThrowMinMaxException(min, max);
if (value < min)
return min;
else if (value > max)
return max;
return value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Decimal Clamp(Decimal value, Decimal min, Decimal max)
{
if (min > max)
ThrowMinMaxException(min, max);
if (value < min)
return min;
else if (value > max)
return max;
return value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Double Clamp(Double value, Double min, Double max)
{
if (min > max)
ThrowMinMaxException(min, max);
if (value < min)
return min;
else if (value > max)
return max;
return value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Int16 Clamp(Int16 value, Int16 min, Int16 max)
{
if (min > max)
ThrowMinMaxException(min, max);
if (value < min)
return min;
else if (value > max)
return max;
return value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Int32 Clamp(Int32 value, Int32 min, Int32 max)
{
if (min > max)
ThrowMinMaxException(min, max);
if (value < min)
return min;
else if (value > max)
return max;
return value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Int64 Clamp(Int64 value, Int64 min, Int64 max)
{
if (min > max)
ThrowMinMaxException(min, max);
if (value < min)
return min;
else if (value > max)
return max;
return value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[CLSCompliant(false)]
public static SByte Clamp(SByte value, SByte min, SByte max)
{
if (min > max)
ThrowMinMaxException(min, max);
if (value < min)
return min;
else if (value > max)
return max;
return value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Single Clamp(Single value, Single min, Single max)
{
if (min > max)
ThrowMinMaxException(min, max);
if (value < min)
return min;
else if (value > max)
return max;
return value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[CLSCompliant(false)]
public static UInt16 Clamp(UInt16 value, UInt16 min, UInt16 max)
{
if (min > max)
ThrowMinMaxException(min, max);
if (value < min)
return min;
else if (value > max)
return max;
return value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[CLSCompliant(false)]
public static UInt32 Clamp(UInt32 value, UInt32 min, UInt32 max)
{
if (min > max)
ThrowMinMaxException(min, max);
if (value < min)
return min;
else if (value > max)
return max;
return value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[CLSCompliant(false)]
public static UInt64 Clamp(UInt64 value, UInt64 min, UInt64 max)
{
if (min > max)
ThrowMinMaxException(min, max);
if (value < min)
return min;
else if (value > max)
return max;
return value;
}
private static void ThrowMinMaxException<T>(T min, T max)
{
throw new ArgumentException(SR.Format(SR.Argument_MinMaxValue, min, max));
}
/*=====================================Log======================================
**
==============================================================================*/
public static double Log(double a, double newBase)
{
if (Double.IsNaN(a))
{
return a; // IEEE 754-2008: NaN payload must be preserved
}
if (Double.IsNaN(newBase))
{
return newBase; // IEEE 754-2008: NaN payload must be preserved
}
if (newBase == 1)
return Double.NaN;
if (a != 1 && (newBase == 0 || Double.IsPositiveInfinity(newBase)))
return Double.NaN;
return (Log(a) / Log(newBase));
}
// Sign function for VB. Returns -1, 0, or 1 if the sign of the number
// is negative, 0, or positive. Throws for floating point NaN's.
[CLSCompliant(false)]
public static int Sign(sbyte value)
{
if (value < 0)
return -1;
else if (value > 0)
return 1;
else
return 0;
}
// Sign function for VB. Returns -1, 0, or 1 if the sign of the number
// is negative, 0, or positive. Throws for floating point NaN's.
public static int Sign(short value)
{
if (value < 0)
return -1;
else if (value > 0)
return 1;
else
return 0;
}
// Sign function for VB. Returns -1, 0, or 1 if the sign of the number
// is negative, 0, or positive. Throws for floating point NaN's.
public static int Sign(int value)
{
if (value < 0)
return -1;
else if (value > 0)
return 1;
else
return 0;
}
public static int Sign(long value)
{
if (value < 0)
return -1;
else if (value > 0)
return 1;
else
return 0;
}
public static int Sign(float value)
{
if (value < 0)
return -1;
else if (value > 0)
return 1;
else if (value == 0)
return 0;
throw new ArithmeticException(SR.Arithmetic_NaN);
}
public static int Sign(double value)
{
if (value < 0)
return -1;
else if (value > 0)
return 1;
else if (value == 0)
return 0;
throw new ArithmeticException(SR.Arithmetic_NaN);
}
public static int Sign(Decimal value)
{
if (value < 0)
return -1;
else if (value > 0)
return 1;
else
return 0;
}
public static long BigMul(int a, int b)
{
return ((long)a) * b;
}
public static int DivRem(int a, int b, out int result)
{
// TODO https://github.com/dotnet/coreclr/issues/3439:
// Restore to using % and / when the JIT is able to eliminate one of the idivs.
// In the meantime, a * and - is measurably faster than an extra /.
int div = a / b;
result = a - (div * b);
return div;
}
public static long DivRem(long a, long b, out long result)
{
// TODO https://github.com/dotnet/coreclr/issues/3439:
// Restore to using % and / when the JIT is able to eliminate one of the idivs.
// In the meantime, a * and - is measurably faster than an extra /.
long div = a / b;
result = a - (div * b);
return div;
}
}
}
| |
//#define USE_SharpZipLib
#if !UNITY_WEBPLAYER
#define USE_FileIO
#endif
/* * * * *
* A simple JSON Parser / builder
* ------------------------------
*
* It mainly has been written as a simple JSON parser. It can build a JSON string
* from the node-tree, or generate a node tree from any valid JSON string.
*
* If you want to use compression when saving to file / stream / B64 you have to include
* SharpZipLib ( http://www.icsharpcode.net/opensource/sharpziplib/ ) in your project and
* define "USE_SharpZipLib" at the top of the file
*
* Written by Bunny83
* 2012-06-09
*
* Features / attributes:
* - provides strongly typed node classes and lists / dictionaries
* - provides easy access to class members / array items / data values
* - the parser ignores data types. Each value is a string.
* - only double quotes (") are used for quoting strings.
* - values and names are not restricted to quoted strings. They simply add up and are trimmed.
* - There are only 3 types: arrays(JSONArray), objects(JSONClass) and values(JSONData)
* - provides "casting" properties to easily convert to / from those types:
* int / float / double / bool
* - provides a common interface for each node so no explicit casting is required.
* - the parser try to avoid errors, but if malformed JSON is parsed the result is undefined
*
*
* 2012-12-17 Update:
* - Added internal JSONLazyCreator class which simplifies the construction of a JSON tree
* Now you can simple reference any item that doesn't exist yet and it will return a JSONLazyCreator
* The class determines the required type by it's further use, creates the type and removes itself.
* - Added binary serialization / deserialization.
* - Added support for BZip2 zipped binary format. Requires the SharpZipLib ( http://www.icsharpcode.net/opensource/sharpziplib/ )
* The usage of the SharpZipLib library can be disabled by removing or commenting out the USE_SharpZipLib define at the top
* - The serializer uses different types when it comes to store the values. Since my data values
* are all of type string, the serializer will "try" which format fits best. The order is: int, float, double, bool, string.
* It's not the most efficient way but for a moderate amount of data it should work on all platforms.
*
* * * * */
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace SimpleJSON
{
public enum JSONBinaryTag
{
Array = 1,
Class = 2,
Value = 3,
IntValue = 4,
DoubleValue = 5,
BoolValue = 6,
FloatValue = 7,
}
public class JSONNode
{
#region common interface
public virtual void Add(string aKey, JSONNode aItem){ }
public virtual JSONNode this[int aIndex] { get { return null; } set { } }
public virtual JSONNode this[string aKey] { get { return null; } set { } }
public virtual string Value { get { return ""; } set { } }
public virtual int Count { get { return 0; } }
public virtual void Add(JSONNode aItem)
{
Add("", aItem);
}
public virtual JSONNode Remove(string aKey) { return null; }
public virtual JSONNode Remove(int aIndex) { return null; }
public virtual JSONNode Remove(JSONNode aNode) { return aNode; }
public virtual IEnumerable<JSONNode> Childs { get { yield break;} }
public IEnumerable<JSONNode> DeepChilds
{
get
{
foreach (var C in Childs)
foreach (var D in C.DeepChilds)
yield return D;
}
}
public override string ToString()
{
return "JSONNode";
}
public virtual string ToString(string aPrefix)
{
return "JSONNode";
}
#endregion common interface
#region typecasting properties
public virtual int AsInt
{
get
{
int v = 0;
if (int.TryParse(Value,out v))
return v;
return 0;
}
set
{
Value = value.ToString();
}
}
public virtual float AsFloat
{
get
{
float v = 0.0f;
if (float.TryParse(Value,out v))
return v;
return 0.0f;
}
set
{
Value = value.ToString();
}
}
public virtual double AsDouble
{
get
{
double v = 0.0;
if (double.TryParse(Value,out v))
return v;
return 0.0;
}
set
{
Value = value.ToString();
}
}
public virtual decimal AsDecimal
{
get
{
decimal v = 0;
if (decimal.TryParse(Value, out v))
return v;
return 0;
}
set
{
Value = value.ToString();
}
}
public virtual long AsLong
{
get
{
long v = 0;
if (long.TryParse(Value, out v))
return v;
return 0;
}
}
public virtual bool AsBool
{
get
{
bool v = false;
if (bool.TryParse(Value,out v))
return v;
return !string.IsNullOrEmpty(Value);
}
set
{
Value = (value)?"true":"false";
}
}
public virtual JSONArray AsArray
{
get
{
return this as JSONArray;
}
}
public virtual JSONClass AsObject
{
get
{
return this as JSONClass;
}
}
#endregion typecasting properties
#region operators
public static implicit operator JSONNode(string s)
{
return new JSONData(s);
}
public static implicit operator string(JSONNode d)
{
return (d == null)?null:d.Value;
}
public static bool operator ==(JSONNode a, object b)
{
if (b == null && a is JSONLazyCreator)
return true;
return System.Object.ReferenceEquals(a,b);
}
public static bool operator !=(JSONNode a, object b)
{
return !(a == b);
}
public override bool Equals (object obj)
{
return System.Object.ReferenceEquals(this, obj);
}
public override int GetHashCode ()
{
return base.GetHashCode();
}
#endregion operators
internal static string Escape(string aText)
{
string result = "";
foreach(char c in aText)
{
switch(c)
{
case '\\' : result += "\\\\"; break;
case '\"' : result += "\\\""; break;
case '\n' : result += "\\n" ; break;
case '\r' : result += "\\r" ; break;
case '\t' : result += "\\t" ; break;
case '\b' : result += "\\b" ; break;
case '\f' : result += "\\f" ; break;
default : result += c ; break;
}
}
return result;
}
public static JSONNode Parse(string aJSON)
{
Stack<JSONNode> stack = new Stack<JSONNode>();
JSONNode ctx = null;
int i = 0;
string Token = "";
string TokenName = "";
bool QuoteMode = false;
while (i < aJSON.Length)
{
switch (aJSON[i])
{
case '{':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
stack.Push(new JSONClass());
if (ctx != null)
{
TokenName = TokenName.Trim();
if (ctx is JSONArray)
ctx.Add(stack.Peek());
else if (TokenName != "")
ctx.Add(TokenName,stack.Peek());
}
TokenName = "";
Token = "";
ctx = stack.Peek();
break;
case '[':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
stack.Push(new JSONArray());
if (ctx != null)
{
TokenName = TokenName.Trim();
if (ctx is JSONArray)
ctx.Add(stack.Peek());
else if (TokenName != "")
ctx.Add(TokenName,stack.Peek());
}
TokenName = "";
Token = "";
ctx = stack.Peek();
break;
case '}':
case ']':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
if (stack.Count == 0)
throw new Exception("JSON Parse: Too many closing brackets");
stack.Pop();
if (Token != "")
{
TokenName = TokenName.Trim();
if (ctx is JSONArray)
ctx.Add(Token);
else if (TokenName != "")
ctx.Add(TokenName,Token);
}
TokenName = "";
Token = "";
if (stack.Count>0)
ctx = stack.Peek();
break;
case ':':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
TokenName = Token;
Token = "";
break;
case '"':
QuoteMode ^= true;
break;
case ',':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
if (Token != "")
{
if (ctx is JSONArray)
ctx.Add(Token);
else if (TokenName != "")
ctx.Add(TokenName, Token);
}
TokenName = "";
Token = "";
break;
case '\r':
case '\n':
break;
case ' ':
case '\t':
if (QuoteMode)
Token += aJSON[i];
break;
case '\\':
++i;
if (QuoteMode)
{
char C = aJSON[i];
switch (C)
{
case 't' : Token += '\t'; break;
case 'r' : Token += '\r'; break;
case 'n' : Token += '\n'; break;
case 'b' : Token += '\b'; break;
case 'f' : Token += '\f'; break;
case 'u':
{
string s = aJSON.Substring(i+1,4);
Token += (char)int.Parse(s, System.Globalization.NumberStyles.AllowHexSpecifier);
i += 4;
break;
}
default : Token += C; break;
}
}
break;
default:
Token += aJSON[i];
break;
}
++i;
}
if (QuoteMode)
{
throw new Exception("JSON Parse: Quotation marks seems to be messed up.");
}
return ctx;
}
public virtual void Serialize(System.IO.BinaryWriter aWriter) {}
public void SaveToStream(System.IO.Stream aData)
{
var W = new System.IO.BinaryWriter(aData);
Serialize(W);
}
#if USE_SharpZipLib
public void SaveToCompressedStream(System.IO.Stream aData)
{
using (var gzipOut = new ICSharpCode.SharpZipLib.BZip2.BZip2OutputStream(aData))
{
gzipOut.IsStreamOwner = false;
SaveToStream(gzipOut);
gzipOut.Close();
}
}
public void SaveToCompressedFile(string aFileName)
{
#if USE_FileIO
System.IO.Directory.CreateDirectory((new System.IO.FileInfo(aFileName)).Directory.FullName);
using(var F = System.IO.File.OpenWrite(aFileName))
{
SaveToCompressedStream(F);
}
#else
throw new Exception("Can't use File IO stuff in webplayer");
#endif
}
public string SaveToCompressedBase64()
{
using (var stream = new System.IO.MemoryStream())
{
SaveToCompressedStream(stream);
stream.Position = 0;
return System.Convert.ToBase64String(stream.ToArray());
}
}
#else
public void SaveToCompressedStream(System.IO.Stream aData)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public void SaveToCompressedFile(string aFileName)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public string SaveToCompressedBase64()
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
#endif
public void SaveToFile(string aFileName)
{
#if USE_FileIO
System.IO.Directory.CreateDirectory((new System.IO.FileInfo(aFileName)).Directory.FullName);
using(var F = System.IO.File.OpenWrite(aFileName))
{
SaveToStream(F);
}
#else
throw new Exception("Can't use File IO stuff in webplayer");
#endif
}
public string SaveToBase64()
{
using (var stream = new System.IO.MemoryStream())
{
SaveToStream(stream);
stream.Position = 0;
return System.Convert.ToBase64String(stream.ToArray());
}
}
public static JSONNode Deserialize(System.IO.BinaryReader aReader)
{
JSONBinaryTag type = (JSONBinaryTag)aReader.ReadByte();
switch(type)
{
case JSONBinaryTag.Array:
{
int count = aReader.ReadInt32();
JSONArray tmp = new JSONArray();
for(int i = 0; i < count; i++)
tmp.Add(Deserialize(aReader));
return tmp;
}
case JSONBinaryTag.Class:
{
int count = aReader.ReadInt32();
JSONClass tmp = new JSONClass();
for(int i = 0; i < count; i++)
{
string key = aReader.ReadString();
var val = Deserialize(aReader);
tmp.Add(key, val);
}
return tmp;
}
case JSONBinaryTag.Value:
{
return new JSONData(aReader.ReadString());
}
case JSONBinaryTag.IntValue:
{
return new JSONData(aReader.ReadInt32());
}
case JSONBinaryTag.DoubleValue:
{
return new JSONData(aReader.ReadDouble());
}
case JSONBinaryTag.BoolValue:
{
return new JSONData(aReader.ReadBoolean());
}
case JSONBinaryTag.FloatValue:
{
return new JSONData(aReader.ReadSingle());
}
default:
{
throw new Exception("Error deserializing JSON. Unknown tag: " + type);
}
}
}
#if USE_SharpZipLib
public static JSONNode LoadFromCompressedStream(System.IO.Stream aData)
{
var zin = new ICSharpCode.SharpZipLib.BZip2.BZip2InputStream(aData);
return LoadFromStream(zin);
}
public static JSONNode LoadFromCompressedFile(string aFileName)
{
#if USE_FileIO
using(var F = System.IO.File.OpenRead(aFileName))
{
return LoadFromCompressedStream(F);
}
#else
throw new Exception("Can't use File IO stuff in webplayer");
#endif
}
public static JSONNode LoadFromCompressedBase64(string aBase64)
{
var tmp = System.Convert.FromBase64String(aBase64);
var stream = new System.IO.MemoryStream(tmp);
stream.Position = 0;
return LoadFromCompressedStream(stream);
}
#else
public static JSONNode LoadFromCompressedFile(string aFileName)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public static JSONNode LoadFromCompressedStream(System.IO.Stream aData)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public static JSONNode LoadFromCompressedBase64(string aBase64)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
#endif
public static JSONNode LoadFromStream(System.IO.Stream aData)
{
using(var R = new System.IO.BinaryReader(aData))
{
return Deserialize(R);
}
}
public static JSONNode LoadFromFile(string aFileName)
{
#if USE_FileIO
using(var F = System.IO.File.OpenRead(aFileName))
{
return LoadFromStream(F);
}
#else
throw new Exception("Can't use File IO stuff in webplayer");
#endif
}
public static JSONNode LoadFromBase64(string aBase64)
{
var tmp = System.Convert.FromBase64String(aBase64);
var stream = new System.IO.MemoryStream(tmp);
stream.Position = 0;
return LoadFromStream(stream);
}
} // End of JSONNode
public class JSONArray : JSONNode, IEnumerable
{
private List<JSONNode> m_List = new List<JSONNode>();
public override JSONNode this[int aIndex]
{
get
{
if (aIndex<0 || aIndex >= m_List.Count)
return new JSONLazyCreator(this);
return m_List[aIndex];
}
set
{
if (aIndex<0 || aIndex >= m_List.Count)
m_List.Add(value);
else
m_List[aIndex] = value;
}
}
public override JSONNode this[string aKey]
{
get{ return new JSONLazyCreator(this);}
set{ m_List.Add(value); }
}
public override int Count
{
get { return m_List.Count; }
}
public override void Add(string aKey, JSONNode aItem)
{
m_List.Add(aItem);
}
public override JSONNode Remove(int aIndex)
{
if (aIndex < 0 || aIndex >= m_List.Count)
return null;
JSONNode tmp = m_List[aIndex];
m_List.RemoveAt(aIndex);
return tmp;
}
public override JSONNode Remove(JSONNode aNode)
{
m_List.Remove(aNode);
return aNode;
}
public override IEnumerable<JSONNode> Childs
{
get
{
foreach(JSONNode N in m_List)
yield return N;
}
}
public IEnumerator GetEnumerator()
{
foreach(JSONNode N in m_List)
yield return N;
}
public override string ToString()
{
string result = "[ ";
foreach (JSONNode N in m_List)
{
if (result.Length > 2)
result += ", ";
result += N.ToString();
}
result += " ]";
return result;
}
public override string ToString(string aPrefix)
{
string result = "[ ";
foreach (JSONNode N in m_List)
{
if (result.Length > 3)
result += ", ";
result += "\n" + aPrefix + " ";
result += N.ToString(aPrefix+" ");
}
result += "\n" + aPrefix + "]";
return result;
}
public override void Serialize (System.IO.BinaryWriter aWriter)
{
aWriter.Write((byte)JSONBinaryTag.Array);
aWriter.Write(m_List.Count);
for(int i = 0; i < m_List.Count; i++)
{
m_List[i].Serialize(aWriter);
}
}
} // End of JSONArray
public class JSONClass : JSONNode, IEnumerable
{
private Dictionary<string,JSONNode> m_Dict = new Dictionary<string,JSONNode>();
public override JSONNode this[string aKey]
{
get
{
if (m_Dict.ContainsKey(aKey))
return m_Dict[aKey];
else
return new JSONLazyCreator(this, aKey);
}
set
{
if (m_Dict.ContainsKey(aKey))
m_Dict[aKey] = value;
else
m_Dict.Add(aKey,value);
}
}
public override JSONNode this[int aIndex]
{
get
{
if (aIndex < 0 || aIndex >= m_Dict.Count)
return null;
return m_Dict.ElementAt(aIndex).Value;
}
set
{
if (aIndex < 0 || aIndex >= m_Dict.Count)
return;
string key = m_Dict.ElementAt(aIndex).Key;
m_Dict[key] = value;
}
}
public override int Count
{
get { return m_Dict.Count; }
}
public override void Add(string aKey, JSONNode aItem)
{
if (!string.IsNullOrEmpty(aKey))
{
if (m_Dict.ContainsKey(aKey))
m_Dict[aKey] = aItem;
else
m_Dict.Add(aKey, aItem);
}
else
m_Dict.Add(Guid.NewGuid().ToString(), aItem);
}
public override JSONNode Remove(string aKey)
{
if (!m_Dict.ContainsKey(aKey))
return null;
JSONNode tmp = m_Dict[aKey];
m_Dict.Remove(aKey);
return tmp;
}
public override JSONNode Remove(int aIndex)
{
if (aIndex < 0 || aIndex >= m_Dict.Count)
return null;
var item = m_Dict.ElementAt(aIndex);
m_Dict.Remove(item.Key);
return item.Value;
}
public override JSONNode Remove(JSONNode aNode)
{
try
{
var item = m_Dict.Where(k => k.Value == aNode).First();
m_Dict.Remove(item.Key);
return aNode;
}
catch
{
return null;
}
}
public override IEnumerable<JSONNode> Childs
{
get
{
foreach(KeyValuePair<string,JSONNode> N in m_Dict)
yield return N.Value;
}
}
public IEnumerator GetEnumerator()
{
foreach(KeyValuePair<string, JSONNode> N in m_Dict)
yield return N;
}
public bool ContainsKey(string s)
{
return m_Dict.ContainsKey (s);
}
public ArrayList GetKeys() // The method is named "GetKeys()"
{
ArrayList arrayOfStrings = new ArrayList(); // declares new array
foreach (KeyValuePair<string, JSONNode> N in m_Dict) // for each key/values
arrayOfStrings.Add(N.Key); // I add only the keys
return arrayOfStrings; // And then I get them all :D
}
public Dictionary<string, JSONNode> GetKeyValueDict()
{
return m_Dict;
}
public override string ToString()
{
string result = "{";
foreach (KeyValuePair<string, JSONNode> N in m_Dict)
{
if (result.Length > 2)
result += ", ";
result += "\"" + Escape(N.Key) + "\":" + N.Value.ToString();
}
result += "}";
return result;
}
public override string ToString(string aPrefix)
{
string result = "{ ";
foreach (KeyValuePair<string, JSONNode> N in m_Dict)
{
if (result.Length > 3)
result += ", ";
result += "\n" + aPrefix + " ";
result += "\"" + Escape(N.Key) + "\" : " + N.Value.ToString(aPrefix+" ");
}
result += "\n" + aPrefix + "}";
return result;
}
public override void Serialize (System.IO.BinaryWriter aWriter)
{
aWriter.Write((byte)JSONBinaryTag.Class);
aWriter.Write(m_Dict.Count);
foreach(string K in m_Dict.Keys)
{
aWriter.Write(K);
m_Dict[K].Serialize(aWriter);
}
}
} // End of JSONClass
public class JSONData : JSONNode
{
private string m_Data;
public override string Value
{
get { return m_Data; }
set { m_Data = value; }
}
public JSONData(string aData)
{
m_Data = aData;
}
public JSONData(float aData)
{
AsFloat = aData;
}
public JSONData(double aData)
{
AsDouble = aData;
}
public JSONData(bool aData)
{
AsBool = aData;
}
public JSONData(int aData)
{
AsInt = aData;
}
public override string ToString()
{
return "\"" + Escape(m_Data) + "\"";
}
public override string ToString(string aPrefix)
{
return "\"" + Escape(m_Data) + "\"";
}
public override void Serialize (System.IO.BinaryWriter aWriter)
{
var tmp = new JSONData("");
tmp.AsInt = AsInt;
if (tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.IntValue);
aWriter.Write(AsInt);
return;
}
tmp.AsFloat = AsFloat;
if (tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.FloatValue);
aWriter.Write(AsFloat);
return;
}
tmp.AsDouble = AsDouble;
if (tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.DoubleValue);
aWriter.Write(AsDouble);
return;
}
tmp.AsBool = AsBool;
if (tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.BoolValue);
aWriter.Write(AsBool);
return;
}
aWriter.Write((byte)JSONBinaryTag.Value);
aWriter.Write(m_Data);
}
} // End of JSONData
internal class JSONLazyCreator : JSONNode
{
private JSONNode m_Node = null;
private string m_Key = null;
public JSONLazyCreator(JSONNode aNode)
{
m_Node = aNode;
m_Key = null;
}
public JSONLazyCreator(JSONNode aNode, string aKey)
{
m_Node = aNode;
m_Key = aKey;
}
private void Set(JSONNode aVal)
{
if (m_Key == null)
{
m_Node.Add(aVal);
}
else
{
m_Node.Add(m_Key, aVal);
}
m_Node = null; // Be GC friendly.
}
public override JSONNode this[int aIndex]
{
get
{
return new JSONLazyCreator(this);
}
set
{
var tmp = new JSONArray();
tmp.Add(value);
Set(tmp);
}
}
public override JSONNode this[string aKey]
{
get
{
return new JSONLazyCreator(this, aKey);
}
set
{
var tmp = new JSONClass();
tmp.Add(aKey, value);
Set(tmp);
}
}
public override void Add (JSONNode aItem)
{
var tmp = new JSONArray();
tmp.Add(aItem);
Set(tmp);
}
public override void Add (string aKey, JSONNode aItem)
{
var tmp = new JSONClass();
tmp.Add(aKey, aItem);
Set(tmp);
}
public static bool operator ==(JSONLazyCreator a, object b)
{
if (b == null)
return true;
return System.Object.ReferenceEquals(a,b);
}
public static bool operator !=(JSONLazyCreator a, object b)
{
return !(a == b);
}
public override bool Equals (object obj)
{
if (obj == null)
return true;
return System.Object.ReferenceEquals(this, obj);
}
public override int GetHashCode ()
{
return base.GetHashCode();
}
public override string ToString()
{
return "";
}
public override string ToString(string aPrefix)
{
return "";
}
public override int AsInt
{
get
{
JSONData tmp = new JSONData(0);
Set(tmp);
return 0;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override float AsFloat
{
get
{
JSONData tmp = new JSONData(0.0f);
Set(tmp);
return 0.0f;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override double AsDouble
{
get
{
JSONData tmp = new JSONData(0.0);
Set(tmp);
return 0.0;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override bool AsBool
{
get
{
JSONData tmp = new JSONData(false);
Set(tmp);
return false;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override JSONArray AsArray
{
get
{
JSONArray tmp = new JSONArray();
Set(tmp);
return tmp;
}
}
public override JSONClass AsObject
{
get
{
JSONClass tmp = new JSONClass();
Set(tmp);
return tmp;
}
}
} // End of JSONLazyCreator
public static class JSON
{
public static JSONNode Parse(string aJSON)
{
return JSONNode.Parse(aJSON);
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using NuGet.Resources;
namespace NuGet
{
public class LocalPackageRepository : PackageRepositoryBase, IPackageLookup
{
private readonly ConcurrentDictionary<string, PackageCacheEntry> _packageCache = new ConcurrentDictionary<string, PackageCacheEntry>(StringComparer.OrdinalIgnoreCase);
private readonly ConcurrentDictionary<PackageName, string> _packagePathLookup = new ConcurrentDictionary<PackageName, string>();
private readonly bool _enableCaching;
public LocalPackageRepository(string physicalPath)
: this(physicalPath, enableCaching: true)
{
}
public LocalPackageRepository(string physicalPath, bool enableCaching)
: this(new DefaultPackagePathResolver(physicalPath),
new PhysicalFileSystem(physicalPath),
enableCaching)
{
}
public LocalPackageRepository(IPackagePathResolver pathResolver, IFileSystem fileSystem)
: this(pathResolver, fileSystem, enableCaching: true)
{
}
public LocalPackageRepository(IPackagePathResolver pathResolver, IFileSystem fileSystem, bool enableCaching)
{
if (pathResolver == null)
{
throw new ArgumentNullException("pathResolver");
}
if (fileSystem == null)
{
throw new ArgumentNullException("fileSystem");
}
FileSystem = fileSystem;
PathResolver = pathResolver;
_enableCaching = enableCaching;
}
public override string Source
{
get
{
return FileSystem.Root;
}
}
public IPackagePathResolver PathResolver
{
get;
set;
}
public override bool SupportsPrereleasePackages
{
get { return true; }
}
protected IFileSystem FileSystem
{
get;
private set;
}
public override IQueryable<IPackage> GetPackages()
{
return GetPackages(OpenPackage).AsQueryable();
}
public override void AddPackage(IPackage package)
{
string packageFilePath = GetPackageFilePath(package);
FileSystem.AddFileWithCheck(packageFilePath, package.GetStream);
}
public override void RemovePackage(IPackage package)
{
// Delete the package file
string packageFilePath = GetPackageFilePath(package);
FileSystem.DeleteFileSafe(packageFilePath);
// Delete the package directory if any
FileSystem.DeleteDirectorySafe(PathResolver.GetPackageDirectory(package), recursive: false);
// If this is the last package delete the package directory
if (!FileSystem.GetFilesSafe(String.Empty).Any() &&
!FileSystem.GetDirectoriesSafe(String.Empty).Any())
{
FileSystem.DeleteDirectorySafe(String.Empty, recursive: false);
}
}
public virtual IPackage FindPackage(string packageId, SemanticVersion version)
{
if (String.IsNullOrEmpty(packageId))
{
throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "packageId");
}
if (version == null)
{
throw new ArgumentNullException("version");
}
return FindPackage(OpenPackage, packageId, version);
}
public virtual IEnumerable<IPackage> FindPackagesById(string packageId)
{
if (String.IsNullOrEmpty(packageId))
{
throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "packageId");
}
return FindPackagesById(OpenPackage, packageId);
}
public virtual bool Exists(string packageId, SemanticVersion version)
{
return FindPackage(packageId, version) != null;
}
public virtual IEnumerable<string> GetPackageLookupPaths(string packageId, SemanticVersion version)
{
// Files created by the path resolver. This would take into account the non-side-by-side scenario
// and we do not need to match this for id and version.
var packageFileName = PathResolver.GetPackageFileName(packageId, version);
var filesMatchingFullName = GetPackageFiles(packageFileName);
if (version != null && version.Version.Revision < 1)
{
// If the build or revision number is not set, we need to look for combinations of the format
// * Foo.1.2.nupkg
// * Foo.1.2.3.nupkg
// * Foo.1.2.0.nupkg
// * Foo.1.2.0.0.nupkg
// To achieve this, we would look for files named 1.2*.nupkg if both build and revision are 0 and
// 1.2.3*.nupkg if only the revision is set to 0.
string partialName = version.Version.Build < 1 ?
String.Join(".", packageId, version.Version.Major, version.Version.Minor) :
String.Join(".", packageId, version.Version.Major, version.Version.Minor, version.Version.Build);
partialName += "*" + Constants.PackageExtension;
// Partial names would result is gathering package with matching major and minor but different build and revision.
// Attempt to match the version in the path to the version we're interested in.
var partialNameMatches = GetPackageFiles(partialName).Where(path => FileNameMatchesPattern(packageId, version, path));
return Enumerable.Concat(filesMatchingFullName, partialNameMatches);
}
return filesMatchingFullName;
}
internal IPackage FindPackage(Func<string, IPackage> openPackage, string packageId, SemanticVersion version)
{
var lookupPackageName = new PackageName(packageId, version);
string packagePath;
// If caching is enabled, check if we have a cached path. Additionally, verify that the file actually exists on disk since it might have moved.
if (_enableCaching &&
_packagePathLookup.TryGetValue(lookupPackageName, out packagePath) &&
FileSystem.FileExists(packagePath))
{
// When depending on the cached path, verify the file exists on disk.
return GetPackage(openPackage, packagePath);
}
// Lookup files which start with the name "<Id>." and attempt to match it with all possible version string combinations (e.g. 1.2.0, 1.2.0.0)
// before opening the package. To avoid creating file name strings, we attempt to specifically match everything after the last path separator
// which would be the file name and extension.
return (from path in GetPackageLookupPaths(packageId, version)
let package = GetPackage(openPackage, path)
where lookupPackageName.Equals(new PackageName(package.Id, package.Version))
select package).FirstOrDefault();
}
internal IEnumerable<IPackage> FindPackagesById(Func<string, IPackage> openPackage, string packageId)
{
Debug.Assert(!String.IsNullOrEmpty(packageId), "The caller has to ensure packageId is never null.");
var packagePaths = GetPackageFiles(packageId + "*" + Constants.PackageExtension);
return from path in packagePaths
let package = GetPackage(openPackage, path)
where package.Id.Equals(packageId, StringComparison.OrdinalIgnoreCase)
select package;
}
internal IEnumerable<IPackage> GetPackages(Func<string, IPackage> openPackage)
{
return from path in GetPackageFiles()
select GetPackage(openPackage, path);
}
private IPackage GetPackage(Func<string, IPackage> openPackage, string path)
{
PackageCacheEntry cacheEntry;
DateTimeOffset lastModified = FileSystem.GetLastModified(path);
// If we never cached this file or we did and it's current last modified time is newer
// create a new entry
if (!_packageCache.TryGetValue(path, out cacheEntry) ||
(cacheEntry != null && lastModified > cacheEntry.LastModifiedTime))
{
// We need to do this so we capture the correct loop variable
string packagePath = path;
// Create the package
IPackage package = openPackage(packagePath);
// create a cache entry with the last modified time
cacheEntry = new PackageCacheEntry(package, lastModified);
if (_enableCaching)
{
// Store the entry
_packageCache[packagePath] = cacheEntry;
_packagePathLookup[new PackageName(package.Id, package.Version)] = path;
}
}
return cacheEntry.Package;
}
internal IEnumerable<string> GetPackageFiles(string filter = null)
{
filter = filter ?? "*" + Constants.PackageExtension;
Debug.Assert(filter.EndsWith(Constants.PackageExtension, StringComparison.OrdinalIgnoreCase));
// Check for package files one level deep. We use this at package install time
// to determine the set of installed packages. Installed packages are copied to
// {id}.{version}\{packagefile}.{extension}.
foreach (var dir in FileSystem.GetDirectories(String.Empty))
{
foreach (var path in FileSystem.GetFiles(dir, filter))
{
yield return path;
}
}
// Check top level directory
foreach (var path in FileSystem.GetFiles(String.Empty, filter))
{
yield return path;
}
}
protected virtual IPackage OpenPackage(string path)
{
if (FileSystem.FileExists(path))
{
OptimizedZipPackage package;
try
{
package = new OptimizedZipPackage(FileSystem, path);
}
catch (FileFormatException ex)
{
throw new InvalidDataException(String.Format(CultureInfo.CurrentCulture, NuGetResources.ErrorReadingPackage, path), ex);
}
// Set the last modified date on the package
package.Published = FileSystem.GetLastModified(path);
return package;
}
else
{
// if the .nupkg file doesn't exist, fall back to searching for the .nuspec file
var nuspecPath = Path.ChangeExtension(path, Constants.ManifestExtension);
if (FileSystem.FileExists(nuspecPath))
{
return new UnzippedPackage(FileSystem, Path.GetFileNameWithoutExtension(nuspecPath));
}
}
return null;
}
protected virtual string GetPackageFilePath(IPackage package)
{
return Path.Combine(PathResolver.GetPackageDirectory(package),
PathResolver.GetPackageFileName(package));
}
protected virtual string GetPackageFilePath(string id, SemanticVersion version)
{
return Path.Combine(PathResolver.GetPackageDirectory(id, version),
PathResolver.GetPackageFileName(id, version));
}
private static bool FileNameMatchesPattern(string packageId, SemanticVersion version, string path)
{
var name = Path.GetFileNameWithoutExtension(path);
SemanticVersion parsedVersion;
// When matching by pattern, we will always have a version token. Packages without versions would be matched early on by the version-less path resolver
// when doing an exact match.
return name.Length > packageId.Length &&
SemanticVersion.TryParse(name.Substring(packageId.Length + 1), out parsedVersion) &&
parsedVersion == version;
}
private class PackageCacheEntry
{
public PackageCacheEntry(IPackage package, DateTimeOffset lastModifiedTime)
{
Package = package;
LastModifiedTime = lastModifiedTime;
}
public IPackage Package { get; private set; }
public DateTimeOffset LastModifiedTime { get; private set; }
}
}
}
| |
// This file has been generated by the GUI designer. Do not modify.
namespace MonoDevelop.PackageManagement
{
public partial class PackageManagementOptionsWidget
{
private global::Gtk.VBox mainVBox;
private global::Gtk.HBox recentPackagesLabelHBox;
private global::Gtk.Label recentPackagesFrameLabel;
private global::Gtk.Label recentPackagesPaddingLabel;
private global::Gtk.HButtonBox recentPackagesButtonBox;
private global::Gtk.Button clearRecentPackagesButton;
private global::Gtk.HBox packagesCacheLabelHBox;
private global::Gtk.Label packagesCacheLabel;
private global::Gtk.Label packagesCachePaddingLabel;
private global::Gtk.HBox packagesCacheHBox;
private global::Gtk.HButtonBox packagesCacheButtonBox;
private global::Gtk.Button clearPackagesCacheButton;
private global::Gtk.HBox browseButtonHBox;
private global::Gtk.Button browseButton;
private global::Gtk.HBox restorePackagesLabelHBox;
private global::Gtk.Label restorePackagesLabel;
private global::Gtk.Label restorePackagesPaddingLabel;
private global::Gtk.CheckButton restorePackagesCheckBox;
private global::Gtk.Label bottomLabel;
protected virtual void Build ()
{
global::Stetic.Gui.Initialize (this);
// Widget MonoDevelop.PackageManagement.PackageManagementOptionsWidget
global::Stetic.BinContainer.Attach (this);
this.Name = "MonoDevelop.PackageManagement.PackageManagementOptionsWidget";
// Container child MonoDevelop.PackageManagement.PackageManagementOptionsWidget.Gtk.Container+ContainerChild
this.mainVBox = new global::Gtk.VBox ();
this.mainVBox.Name = "mainVBox";
this.mainVBox.Spacing = 6;
// Container child mainVBox.Gtk.Box+BoxChild
this.recentPackagesLabelHBox = new global::Gtk.HBox ();
this.recentPackagesLabelHBox.Name = "recentPackagesLabelHBox";
this.recentPackagesLabelHBox.Spacing = 6;
// Container child recentPackagesLabelHBox.Gtk.Box+BoxChild
this.recentPackagesFrameLabel = new global::Gtk.Label ();
this.recentPackagesFrameLabel.Name = "recentPackagesFrameLabel";
this.recentPackagesFrameLabel.LabelProp = global::Mono.Unix.Catalog.GetString ("<b>Recent Packages</b>");
this.recentPackagesFrameLabel.UseMarkup = true;
this.recentPackagesLabelHBox.Add (this.recentPackagesFrameLabel);
global::Gtk.Box.BoxChild w1 = ((global::Gtk.Box.BoxChild)(this.recentPackagesLabelHBox [this.recentPackagesFrameLabel]));
w1.Position = 0;
w1.Expand = false;
w1.Fill = false;
// Container child recentPackagesLabelHBox.Gtk.Box+BoxChild
this.recentPackagesPaddingLabel = new global::Gtk.Label ();
this.recentPackagesPaddingLabel.Name = "recentPackagesPaddingLabel";
this.recentPackagesLabelHBox.Add (this.recentPackagesPaddingLabel);
global::Gtk.Box.BoxChild w2 = ((global::Gtk.Box.BoxChild)(this.recentPackagesLabelHBox [this.recentPackagesPaddingLabel]));
w2.Position = 1;
this.mainVBox.Add (this.recentPackagesLabelHBox);
global::Gtk.Box.BoxChild w3 = ((global::Gtk.Box.BoxChild)(this.mainVBox [this.recentPackagesLabelHBox]));
w3.Position = 0;
w3.Expand = false;
w3.Fill = false;
// Container child mainVBox.Gtk.Box+BoxChild
this.recentPackagesButtonBox = new global::Gtk.HButtonBox ();
this.recentPackagesButtonBox.Name = "recentPackagesButtonBox";
this.recentPackagesButtonBox.BorderWidth = ((uint)(8));
this.recentPackagesButtonBox.LayoutStyle = ((global::Gtk.ButtonBoxStyle)(3));
// Container child recentPackagesButtonBox.Gtk.ButtonBox+ButtonBoxChild
this.clearRecentPackagesButton = new global::Gtk.Button ();
this.clearRecentPackagesButton.CanFocus = true;
this.clearRecentPackagesButton.Name = "clearRecentPackagesButton";
this.clearRecentPackagesButton.UseUnderline = true;
this.clearRecentPackagesButton.Label = global::Mono.Unix.Catalog.GetString ("Clear _Recent Packages");
this.recentPackagesButtonBox.Add (this.clearRecentPackagesButton);
global::Gtk.ButtonBox.ButtonBoxChild w4 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.recentPackagesButtonBox [this.clearRecentPackagesButton]));
w4.Expand = false;
w4.Fill = false;
this.mainVBox.Add (this.recentPackagesButtonBox);
global::Gtk.Box.BoxChild w5 = ((global::Gtk.Box.BoxChild)(this.mainVBox [this.recentPackagesButtonBox]));
w5.Position = 1;
w5.Expand = false;
w5.Fill = false;
// Container child mainVBox.Gtk.Box+BoxChild
this.packagesCacheLabelHBox = new global::Gtk.HBox ();
this.packagesCacheLabelHBox.Name = "packagesCacheLabelHBox";
this.packagesCacheLabelHBox.Spacing = 6;
// Container child packagesCacheLabelHBox.Gtk.Box+BoxChild
this.packagesCacheLabel = new global::Gtk.Label ();
this.packagesCacheLabel.Name = "packagesCacheLabel";
this.packagesCacheLabel.LabelProp = global::Mono.Unix.Catalog.GetString ("<b>Packages Cache</b>");
this.packagesCacheLabel.UseMarkup = true;
this.packagesCacheLabelHBox.Add (this.packagesCacheLabel);
global::Gtk.Box.BoxChild w6 = ((global::Gtk.Box.BoxChild)(this.packagesCacheLabelHBox [this.packagesCacheLabel]));
w6.Position = 0;
w6.Expand = false;
w6.Fill = false;
// Container child packagesCacheLabelHBox.Gtk.Box+BoxChild
this.packagesCachePaddingLabel = new global::Gtk.Label ();
this.packagesCachePaddingLabel.Name = "packagesCachePaddingLabel";
this.packagesCacheLabelHBox.Add (this.packagesCachePaddingLabel);
global::Gtk.Box.BoxChild w7 = ((global::Gtk.Box.BoxChild)(this.packagesCacheLabelHBox [this.packagesCachePaddingLabel]));
w7.Position = 1;
this.mainVBox.Add (this.packagesCacheLabelHBox);
global::Gtk.Box.BoxChild w8 = ((global::Gtk.Box.BoxChild)(this.mainVBox [this.packagesCacheLabelHBox]));
w8.Position = 2;
w8.Expand = false;
w8.Fill = false;
// Container child mainVBox.Gtk.Box+BoxChild
this.packagesCacheHBox = new global::Gtk.HBox ();
this.packagesCacheHBox.Name = "packagesCacheHBox";
this.packagesCacheHBox.Spacing = 6;
// Container child packagesCacheHBox.Gtk.Box+BoxChild
this.packagesCacheButtonBox = new global::Gtk.HButtonBox ();
this.packagesCacheButtonBox.Name = "packagesCacheButtonBox";
this.packagesCacheButtonBox.BorderWidth = ((uint)(8));
this.packagesCacheButtonBox.LayoutStyle = ((global::Gtk.ButtonBoxStyle)(3));
// Container child packagesCacheButtonBox.Gtk.ButtonBox+ButtonBoxChild
this.clearPackagesCacheButton = new global::Gtk.Button ();
this.clearPackagesCacheButton.CanFocus = true;
this.clearPackagesCacheButton.Name = "clearPackagesCacheButton";
this.clearPackagesCacheButton.UseUnderline = true;
this.clearPackagesCacheButton.Label = global::Mono.Unix.Catalog.GetString ("Clear Package _Cache");
this.packagesCacheButtonBox.Add (this.clearPackagesCacheButton);
global::Gtk.ButtonBox.ButtonBoxChild w9 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.packagesCacheButtonBox [this.clearPackagesCacheButton]));
w9.Expand = false;
w9.Fill = false;
this.packagesCacheHBox.Add (this.packagesCacheButtonBox);
global::Gtk.Box.BoxChild w10 = ((global::Gtk.Box.BoxChild)(this.packagesCacheHBox [this.packagesCacheButtonBox]));
w10.Position = 0;
w10.Expand = false;
// Container child packagesCacheHBox.Gtk.Box+BoxChild
this.browseButtonHBox = new global::Gtk.HBox ();
this.browseButtonHBox.Name = "browseButtonHBox";
this.browseButtonHBox.Spacing = 6;
// Container child browseButtonHBox.Gtk.Box+BoxChild
this.browseButton = new global::Gtk.Button ();
this.browseButton.CanFocus = true;
this.browseButton.Name = "browseButton";
this.browseButton.UseUnderline = true;
this.browseButton.BorderWidth = ((uint)(8));
this.browseButton.Label = global::Mono.Unix.Catalog.GetString ("_Browse...");
this.browseButtonHBox.Add (this.browseButton);
global::Gtk.Box.BoxChild w11 = ((global::Gtk.Box.BoxChild)(this.browseButtonHBox [this.browseButton]));
w11.Position = 0;
w11.Expand = false;
w11.Fill = false;
this.packagesCacheHBox.Add (this.browseButtonHBox);
global::Gtk.Box.BoxChild w12 = ((global::Gtk.Box.BoxChild)(this.packagesCacheHBox [this.browseButtonHBox]));
w12.Position = 1;
w12.Expand = false;
w12.Fill = false;
this.mainVBox.Add (this.packagesCacheHBox);
global::Gtk.Box.BoxChild w13 = ((global::Gtk.Box.BoxChild)(this.mainVBox [this.packagesCacheHBox]));
w13.Position = 3;
w13.Expand = false;
w13.Fill = false;
// Container child mainVBox.Gtk.Box+BoxChild
this.restorePackagesLabelHBox = new global::Gtk.HBox ();
this.restorePackagesLabelHBox.Name = "restorePackagesLabelHBox";
this.restorePackagesLabelHBox.Spacing = 6;
// Container child restorePackagesLabelHBox.Gtk.Box+BoxChild
this.restorePackagesLabel = new global::Gtk.Label ();
this.restorePackagesLabel.Name = "restorePackagesLabel";
this.restorePackagesLabel.LabelProp = global::Mono.Unix.Catalog.GetString ("<b>Restore Packages</b>");
this.restorePackagesLabel.UseMarkup = true;
this.restorePackagesLabelHBox.Add (this.restorePackagesLabel);
global::Gtk.Box.BoxChild w14 = ((global::Gtk.Box.BoxChild)(this.restorePackagesLabelHBox [this.restorePackagesLabel]));
w14.Position = 0;
w14.Expand = false;
w14.Fill = false;
// Container child restorePackagesLabelHBox.Gtk.Box+BoxChild
this.restorePackagesPaddingLabel = new global::Gtk.Label ();
this.restorePackagesPaddingLabel.Name = "restorePackagesPaddingLabel";
this.restorePackagesLabelHBox.Add (this.restorePackagesPaddingLabel);
global::Gtk.Box.BoxChild w15 = ((global::Gtk.Box.BoxChild)(this.restorePackagesLabelHBox [this.restorePackagesPaddingLabel]));
w15.Position = 1;
this.mainVBox.Add (this.restorePackagesLabelHBox);
global::Gtk.Box.BoxChild w16 = ((global::Gtk.Box.BoxChild)(this.mainVBox [this.restorePackagesLabelHBox]));
w16.Position = 4;
w16.Expand = false;
w16.Fill = false;
// Container child mainVBox.Gtk.Box+BoxChild
this.restorePackagesCheckBox = new global::Gtk.CheckButton ();
this.restorePackagesCheckBox.CanFocus = true;
this.restorePackagesCheckBox.Name = "restorePackagesCheckBox";
this.restorePackagesCheckBox.Label = global::Mono.Unix.Catalog.GetString ("_Enable package restore");
this.restorePackagesCheckBox.DrawIndicator = true;
this.restorePackagesCheckBox.UseUnderline = true;
this.restorePackagesCheckBox.BorderWidth = ((uint)(10));
this.mainVBox.Add (this.restorePackagesCheckBox);
global::Gtk.Box.BoxChild w17 = ((global::Gtk.Box.BoxChild)(this.mainVBox [this.restorePackagesCheckBox]));
w17.Position = 5;
w17.Expand = false;
w17.Fill = false;
// Container child mainVBox.Gtk.Box+BoxChild
this.bottomLabel = new global::Gtk.Label ();
this.bottomLabel.Name = "bottomLabel";
this.mainVBox.Add (this.bottomLabel);
global::Gtk.Box.BoxChild w18 = ((global::Gtk.Box.BoxChild)(this.mainVBox [this.bottomLabel]));
w18.Position = 6;
this.Add (this.mainVBox);
if ((this.Child != null)) {
this.Child.ShowAll ();
}
this.Hide ();
this.clearRecentPackagesButton.Clicked += new global::System.EventHandler (this.ClearRecentPackagesButtonClicked);
this.clearPackagesCacheButton.Clicked += new global::System.EventHandler (this.ClearPackagesCacheButtonClicked);
this.browseButton.Clicked += new global::System.EventHandler (this.BrowseButtonClicked);
this.restorePackagesCheckBox.Toggled += new global::System.EventHandler (this.RestorePackagesCheckBoxToggled);
}
}
}
| |
using System;
using System.Globalization;
using Eto.Drawing;
using Eto.Forms;
using Eto.WinForms.Drawing;
using sd = System.Drawing;
using sdp = System.Drawing.Printing;
using sd2 = System.Drawing.Drawing2D;
using swf = System.Windows.Forms;
using sdi = System.Drawing.Imaging;
using Eto.WinForms.Forms.Printing;
namespace Eto.WinForms
{
public static partial class WinConversions
{
public const float WheelDelta = 120f;
public static Padding ToEto(this swf.Padding padding)
{
return new Padding(padding.Left, padding.Top, padding.Right, padding.Bottom);
}
public static swf.Padding ToSWF(this Padding padding)
{
return new swf.Padding(padding.Left, padding.Top, padding.Right, padding.Bottom);
}
public static Color ToEto(this sd.Color color)
{
return new Color(color.R / 255f, color.G / 255f, color.B / 255f, color.A / 255f);
}
public static sd.Color ToSD(this Color color)
{
return sd.Color.FromArgb((byte)(color.A * 255), (byte)(color.R * 255), (byte)(color.G * 255), (byte)(color.B * 255));
}
public static DialogResult ToEto(this swf.DialogResult result)
{
switch (result)
{
case swf.DialogResult.OK:
return DialogResult.Ok;
case swf.DialogResult.Cancel:
return DialogResult.Cancel;
case swf.DialogResult.Yes:
return DialogResult.Yes;
case swf.DialogResult.No:
return DialogResult.No;
case swf.DialogResult.Abort:
return DialogResult.Cancel;
case swf.DialogResult.Ignore:
return DialogResult.Ignore;
case swf.DialogResult.Retry:
return DialogResult.Retry;
case swf.DialogResult.None:
return DialogResult.None;
default:
return DialogResult.None;
}
}
public static sd.Imaging.ImageFormat ToSD(this ImageFormat format)
{
switch (format)
{
case ImageFormat.Jpeg:
return sd.Imaging.ImageFormat.Jpeg;
case ImageFormat.Bitmap:
return sd.Imaging.ImageFormat.Bmp;
case ImageFormat.Gif:
return sd.Imaging.ImageFormat.Gif;
case ImageFormat.Tiff:
return sd.Imaging.ImageFormat.Tiff;
case ImageFormat.Png:
return sd.Imaging.ImageFormat.Png;
default:
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid format specified"));
}
}
public static ImageInterpolation ToEto(this sd2.InterpolationMode value)
{
switch (value)
{
case sd2.InterpolationMode.NearestNeighbor:
return ImageInterpolation.None;
case sd2.InterpolationMode.Low:
return ImageInterpolation.Low;
case sd2.InterpolationMode.High:
return ImageInterpolation.Medium;
case sd2.InterpolationMode.HighQualityBilinear:
return ImageInterpolation.High;
case sd2.InterpolationMode.Default:
return ImageInterpolation.Default;
default:
throw new NotSupportedException();
}
}
public static sd2.InterpolationMode ToSD(this ImageInterpolation value)
{
switch (value)
{
case ImageInterpolation.Default:
return sd2.InterpolationMode.High;
case ImageInterpolation.None:
return sd2.InterpolationMode.NearestNeighbor;
case ImageInterpolation.Low:
return sd2.InterpolationMode.Low;
case ImageInterpolation.Medium:
return sd2.InterpolationMode.High;
case ImageInterpolation.High:
return sd2.InterpolationMode.HighQualityBilinear;
default:
throw new NotSupportedException();
}
}
public static sd.FontStyle ToSD(this FontStyle style)
{
sd.FontStyle ret = sd.FontStyle.Regular;
if (style.HasFlag(FontStyle.Bold))
ret |= sd.FontStyle.Bold;
if (style.HasFlag(FontStyle.Italic))
ret |= sd.FontStyle.Italic;
return ret;
}
public static sd.FontStyle ToSD(this FontDecoration decoration)
{
sd.FontStyle ret = sd.FontStyle.Regular;
if (decoration.HasFlag(FontDecoration.Underline))
ret |= sd.FontStyle.Underline;
if (decoration.HasFlag(FontDecoration.Strikethrough))
ret |= sd.FontStyle.Strikeout;
return ret;
}
public static sdp.PrintRange ToSDP(this PrintSelection value)
{
switch (value)
{
case PrintSelection.AllPages:
return sdp.PrintRange.AllPages;
case PrintSelection.SelectedPages:
return sdp.PrintRange.SomePages;
case PrintSelection.Selection:
return sdp.PrintRange.Selection;
default:
throw new NotSupportedException();
}
}
public static PrintSelection ToEto(this sdp.PrintRange value)
{
switch (value)
{
case sdp.PrintRange.AllPages:
return PrintSelection.AllPages;
case sdp.PrintRange.SomePages:
return PrintSelection.SelectedPages;
case sdp.PrintRange.Selection:
return PrintSelection.Selection;
default:
throw new NotSupportedException();
}
}
public static FontStyle ToEtoStyle(this sd.FontStyle style)
{
var ret = FontStyle.None;
if (style.HasFlag(sd.FontStyle.Bold))
ret |= FontStyle.Bold;
if (style.HasFlag(sd.FontStyle.Italic))
ret |= FontStyle.Italic;
return ret;
}
public static FontDecoration ToEtoDecoration(this sd.FontStyle style)
{
var ret = FontDecoration.None;
if (style.HasFlag(sd.FontStyle.Underline))
ret |= FontDecoration.Underline;
if (style.HasFlag(sd.FontStyle.Strikeout))
ret |= FontDecoration.Strikethrough;
return ret;
}
public static Point ToEto(this sd.Point point)
{
return new Point(point.X, point.Y);
}
public static PointF ToEto(this sd.PointF point)
{
return new PointF(point.X, point.Y);
}
public static sd.PointF ToSD(this PointF point)
{
return new sd.PointF(point.X, point.Y);
}
public static sd.Point ToSDPoint(this PointF point)
{
return new sd.Point((int)point.X, (int)point.Y);
}
public static Size ToEto(this sd.Size size)
{
return new Size(size.Width, size.Height);
}
public static sd.Size ToSD(this Size size)
{
return new sd.Size(size.Width, size.Height);
}
public static Size ToEtoF(this sd.SizeF size)
{
return new Size((int)size.Width, (int)size.Height);
}
public static SizeF ToEto(this sd.SizeF size)
{
return new SizeF(size.Width, size.Height);
}
public static sd.SizeF ToSD(this SizeF size)
{
return new sd.SizeF(size.Width, size.Height);
}
public static Rectangle ToEto(this sd.Rectangle rect)
{
return new Rectangle(rect.X, rect.Y, rect.Width, rect.Height);
}
public static RectangleF ToEto(this sd.RectangleF rect)
{
return new RectangleF(rect.X, rect.Y, rect.Width, rect.Height);
}
public static sd.Rectangle ToSD(this Rectangle rect)
{
return new sd.Rectangle(rect.X, rect.Y, rect.Width, rect.Height);
}
public static sd.RectangleF ToSD(this RectangleF rect)
{
return new sd.RectangleF(rect.X, rect.Y, rect.Width, rect.Height);
}
public static sd.Rectangle ToSDRectangle(this RectangleF rect)
{
return new sd.Rectangle((int)rect.X, (int)rect.Y, (int)rect.Width, (int)rect.Height);
}
internal static sd.Point[] ToSD(this Point[] points)
{
var result =
new sd.Point[points.Length];
for (var i = 0;
i < points.Length;
++i)
{
var p = points[i];
result[i] =
new sd.Point(p.X, p.Y);
}
return result;
}
internal static sd.PointF[] ToSD(this PointF[] points)
{
var result =
new sd.PointF[points.Length];
for (var i = 0;
i < points.Length;
++i)
{
var p = points[i];
result[i] =
new sd.PointF(p.X, p.Y);
}
return result;
}
internal static PointF[] ToEto(this sd.PointF[] points)
{
var result =
new PointF[points.Length];
for (var i = 0;
i < points.Length;
++i)
{
var p = points[i];
result[i] =
new PointF(p.X, p.Y);
}
return result;
}
public static sd.Graphics ToSD(this Graphics graphics)
{
var h = (GraphicsHandler)graphics.Handler;
return h.Control;
}
public static sd.Image ToSD(this Image image, int? size = null)
{
if (image == null)
return null;
var h = (IWindowsImageSource)image.Handler;
return h.GetImageWithSize(size);
}
public static sd.Font ToSD(this Font font)
{
if (font == null)
return null;
return ((IWindowsFontSource)font.Handler).GetFont();
}
public static sd.FontFamily ToSD(this FontFamily family)
{
if (family == null)
return null;
return ((FontFamilyHandler)family.Handler).Control;
}
public static sd.Font ToSD(this SystemFont systemFont)
{
switch (systemFont)
{
case SystemFont.Default:
return sd.SystemFonts.DefaultFont;
case SystemFont.Bold:
return new sd.Font(sd.SystemFonts.DefaultFont, sd.FontStyle.Bold);
case SystemFont.TitleBar:
return sd.SystemFonts.CaptionFont;
case SystemFont.ToolTip:
return sd.SystemFonts.DefaultFont;
case SystemFont.Label:
return sd.SystemFonts.DialogFont;
case SystemFont.MenuBar:
return sd.SystemFonts.MenuFont;
case SystemFont.Menu:
return sd.SystemFonts.MenuFont;
case SystemFont.Message:
return sd.SystemFonts.MessageBoxFont;
case SystemFont.Palette:
return sd.SystemFonts.DialogFont;
case SystemFont.StatusBar:
return sd.SystemFonts.StatusFont;
default:
throw new NotSupportedException();
}
}
public static Font ToEto(this sd.Font font)
{
return font == null ? null : new Font(new FontHandler(font));
}
public static FontFamily ToEto(this sd.FontFamily family)
{
return family == null ? null : new FontFamily(new FontFamilyHandler(family));
}
public static MouseEventArgs ToEto(this swf.MouseEventArgs e, swf.Control control)
{
var point = control.PointToClient(swf.Control.MousePosition).ToEto();
var buttons = ToEto(e.Button);
var modifiers = swf.Control.ModifierKeys.ToEto();
return new MouseEventArgs(buttons, modifiers, point, new SizeF(0, (float)e.Delta / WheelDelta));
}
public static MouseButtons ToEto(this swf.MouseButtons button)
{
MouseButtons buttons = MouseButtons.None;
if ((button & swf.MouseButtons.Left) != 0)
buttons |= MouseButtons.Primary;
if ((button & swf.MouseButtons.Right) != 0)
buttons |= MouseButtons.Alternate;
if ((button & swf.MouseButtons.Middle) != 0)
buttons |= MouseButtons.Middle;
return buttons;
}
public static Graphics ToEto(this sd.Graphics g)
{
return new Graphics(new GraphicsHandler(g));
}
public static PaintEventArgs ToEto(this swf.PaintEventArgs e)
{
return new PaintEventArgs(ToEto(e.Graphics), e.ClipRectangle.ToEto());
}
public static sd2.PixelOffsetMode ToSD(this PixelOffsetMode mode)
{
switch (mode)
{
case PixelOffsetMode.None:
return sd2.PixelOffsetMode.None;
case PixelOffsetMode.Half:
return sd2.PixelOffsetMode.Half;
default:
throw new NotSupportedException();
}
}
public static PixelOffsetMode ToEto(this sd2.PixelOffsetMode mode)
{
switch (mode)
{
case sd2.PixelOffsetMode.None:
return PixelOffsetMode.None;
case sd2.PixelOffsetMode.Half:
return PixelOffsetMode.Half;
default:
throw new NotSupportedException();
}
}
public static sd2.Matrix ToSD(this IMatrix m)
{
return (sd2.Matrix)m.ControlObject;
}
public static IMatrix ToEto(this sd2.Matrix matrix)
{
return new MatrixHandler(matrix);
}
public static ITreeItem ToEto(this swf.TreeNode treeNode)
{
return
treeNode != null
? treeNode.Tag as ITreeItem
: null;
}
public static sd.Pen ToSD(this Pen pen)
{
return (sd.Pen)pen.ControlObject;
}
public static sd.Brush ToSD(this Brush brush, RectangleF bounds)
{
return ((BrushHandler)brush.Handler).GetBrush(brush, bounds);
}
public static sd2.LineJoin ToSD(this PenLineJoin value)
{
switch (value)
{
case PenLineJoin.Miter:
return sd2.LineJoin.MiterClipped;
case PenLineJoin.Bevel:
return sd2.LineJoin.Bevel;
case PenLineJoin.Round:
return sd2.LineJoin.Round;
default:
throw new NotSupportedException();
}
}
public static PenLineJoin ToEto(this sd2.LineJoin value)
{
switch (value)
{
case sd2.LineJoin.Bevel:
return PenLineJoin.Bevel;
case sd2.LineJoin.Miter:
return PenLineJoin.Miter;
case sd2.LineJoin.Round:
return PenLineJoin.Round;
default:
throw new NotSupportedException();
}
}
public static sd2.LineCap ToSD(this PenLineCap value)
{
switch (value)
{
case PenLineCap.Butt:
return sd2.LineCap.Flat;
case PenLineCap.Round:
return sd2.LineCap.Round;
case PenLineCap.Square:
return sd2.LineCap.Square;
default:
throw new NotSupportedException();
}
}
public static PenLineCap ToEto(this sd2.LineCap value)
{
switch (value)
{
case sd2.LineCap.Flat:
return PenLineCap.Butt;
case sd2.LineCap.Round:
return PenLineCap.Round;
case sd2.LineCap.Square:
return PenLineCap.Square;
default:
throw new NotSupportedException();
}
}
public static sd2.GraphicsPath ToSD(this IGraphicsPath path)
{
return (sd2.GraphicsPath)path.ControlObject;
}
public static sd2.WrapMode ToSD(this GradientWrapMode wrap)
{
switch (wrap)
{
case GradientWrapMode.Reflect:
return sd2.WrapMode.TileFlipXY;
case GradientWrapMode.Repeat:
return sd2.WrapMode.Tile;
case GradientWrapMode.Pad:
return sd2.WrapMode.Clamp;
default:
throw new NotSupportedException();
}
}
public static GradientWrapMode ToEto(this sd2.WrapMode wrapMode)
{
switch (wrapMode)
{
case sd2.WrapMode.TileFlipXY:
return GradientWrapMode.Reflect;
case sd2.WrapMode.Tile:
return GradientWrapMode.Repeat;
case sd2.WrapMode.Clamp:
return GradientWrapMode.Pad;
default:
throw new NotSupportedException();
}
}
public static int BitsPerPixel(this sdi.PixelFormat format)
{
switch (format)
{
case sdi.PixelFormat.Format1bppIndexed:
return 1;
case sdi.PixelFormat.Format4bppIndexed:
return 4;
case sdi.PixelFormat.Format8bppIndexed:
return 8;
case sdi.PixelFormat.Format24bppRgb:
return 24;
case sdi.PixelFormat.Format32bppArgb:
case sdi.PixelFormat.Format32bppPArgb:
case sdi.PixelFormat.Format32bppRgb:
return 32;
default:
throw new NotSupportedException();
}
}
public static swf.TextImageRelation ToSD(this ButtonImagePosition value)
{
switch (value)
{
case ButtonImagePosition.Left:
return swf.TextImageRelation.ImageBeforeText;
case ButtonImagePosition.Right:
return swf.TextImageRelation.TextBeforeImage;
case ButtonImagePosition.Above:
return swf.TextImageRelation.ImageAboveText;
case ButtonImagePosition.Below:
return swf.TextImageRelation.TextAboveImage;
case ButtonImagePosition.Overlay:
return swf.TextImageRelation.Overlay;
default:
throw new NotSupportedException();
}
}
public static ButtonImagePosition ToEto(this swf.TextImageRelation value)
{
switch (value)
{
case swf.TextImageRelation.ImageAboveText:
return ButtonImagePosition.Above;
case swf.TextImageRelation.ImageBeforeText:
return ButtonImagePosition.Left;
case swf.TextImageRelation.Overlay:
return ButtonImagePosition.Overlay;
case swf.TextImageRelation.TextAboveImage:
return ButtonImagePosition.Below;
case swf.TextImageRelation.TextBeforeImage:
return ButtonImagePosition.Left;
default:
throw new NotSupportedException();
}
}
public static bool IsResizable(this swf.FormBorderStyle style)
{
switch (style)
{
case swf.FormBorderStyle.Fixed3D:
case swf.FormBorderStyle.FixedDialog:
case swf.FormBorderStyle.FixedSingle:
case swf.FormBorderStyle.FixedToolWindow:
case swf.FormBorderStyle.None:
return false;
case swf.FormBorderStyle.Sizable:
case swf.FormBorderStyle.SizableToolWindow:
return true;
default:
throw new NotSupportedException();
}
}
public static WindowStyle ToEto(this swf.FormBorderStyle style)
{
switch (style)
{
case swf.FormBorderStyle.Fixed3D:
case swf.FormBorderStyle.Sizable:
case swf.FormBorderStyle.SizableToolWindow:
case swf.FormBorderStyle.FixedDialog:
return WindowStyle.Default;
case swf.FormBorderStyle.None:
return WindowStyle.None;
default:
throw new NotSupportedException();
}
}
public static swf.FormBorderStyle ToSWF(this WindowStyle style, bool resizable, swf.FormBorderStyle defaultStyle)
{
switch (style)
{
case WindowStyle.Default:
return resizable ? swf.FormBorderStyle.Sizable : defaultStyle;
case WindowStyle.None:
return swf.FormBorderStyle.None;
default:
throw new NotSupportedException();
}
}
public static DrawableCellStates ToEto(this swf.DataGridViewElementStates state)
{
if (state.HasFlag(swf.DataGridViewElementStates.Selected))
return DrawableCellStates.Selected;
return DrawableCellStates.None;
}
public static PrintSettings ToEto(this sdp.PrinterSettings settings)
{
return settings == null ? null : new PrintSettings(new PrintSettingsHandler(settings));
}
public static sdp.PrinterSettings ToSD(this PrintSettings settings)
{
if (settings == null)
return PrintSettingsHandler.DefaultSettings();
return ((PrintSettingsHandler)settings.Handler).Control;
}
public static sdp.PrintDocument ToSD(this PrintDocument document)
{
return document == null ? null : ((PrintDocumentHandler)document.Handler).Control;
}
public static Range<DateTime> ToEto(this swf.SelectionRange range)
{
return new Range<DateTime>(range.Start, range.End);
}
public static swf.SelectionRange ToSWF(this Range<DateTime> range)
{
return new swf.SelectionRange(range.Start, range.End);
}
public static swf.HorizontalAlignment ToSWF(this TextAlignment align)
{
switch (align)
{
case TextAlignment.Left:
return swf.HorizontalAlignment.Left;
case TextAlignment.Center:
return swf.HorizontalAlignment.Center;
case TextAlignment.Right:
return swf.HorizontalAlignment.Right;
default:
throw new NotSupportedException();
}
}
public static TextAlignment ToEto(this swf.HorizontalAlignment align)
{
switch (align)
{
case swf.HorizontalAlignment.Center:
return TextAlignment.Center;
case swf.HorizontalAlignment.Left:
return TextAlignment.Left;
case swf.HorizontalAlignment.Right:
return TextAlignment.Right;
default:
throw new NotSupportedException();
}
}
public static swf.Form ToSWF(this Window window)
{
if (window == null)
return null;
var handler = window.Handler as Forms.IWindowHandler;
if (handler != null)
return handler.Win32Window as swf.Form;
return null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Schema;
namespace System.Xml.Xsl.Runtime
{
/// <summary>
/// External XmlWriter Cached Sequence
/// ===================================================================================================
/// Multiple Trees Merged into Entity Multiple Trees
///
/// Attributes Error Floating
/// at top-level Attribute
///
/// Namespace Error Floating
/// at top-level Namespace
///
/// Elements, Text, PI Implicit Root Floating
/// Comments at top-level Nodes
///
/// Root at top-level Ignored Root
///
/// Atomic Values Whitespace-Separated Atomic Values
/// at top-level Text Node
///
/// Nodes By Reference Copied Preserve Identity
/// </summary>
internal abstract class XmlSequenceWriter
{
/// <summary>
/// Start construction of a new Xml tree (document or fragment).
/// </summary>
public abstract XmlRawWriter StartTree(XPathNodeType rootType, IXmlNamespaceResolver nsResolver, XmlNameTable nameTable);
/// <summary>
/// End construction of a new Xml tree (document or fragment).
/// </summary>
public abstract void EndTree();
/// <summary>
/// Write a top-level item by reference.
/// </summary>
public abstract void WriteItem(XPathItem item);
}
/// <summary>
/// An implementation of XmlSequenceWriter that builds a cached XPath/XQuery sequence.
/// </summary>
internal class XmlCachedSequenceWriter : XmlSequenceWriter
{
private XmlQueryItemSequence _seqTyped;
private XPathDocument _doc;
private XmlRawWriter _writer;
/// <summary>
/// Constructor.
/// </summary>
public XmlCachedSequenceWriter()
{
_seqTyped = new XmlQueryItemSequence();
}
/// <summary>
/// Return the sequence after it has been fully constructed.
/// </summary>
public XmlQueryItemSequence ResultSequence
{
get { return _seqTyped; }
}
/// <summary>
/// Start construction of a new Xml tree (document or fragment).
/// </summary>
public override XmlRawWriter StartTree(XPathNodeType rootType, IXmlNamespaceResolver nsResolver, XmlNameTable nameTable)
{
// Build XPathDocument
// If rootType != XPathNodeType.Root, then build an XQuery fragment
_doc = new XPathDocument(nameTable);
_writer = _doc.LoadFromWriter(XPathDocument.LoadFlags.AtomizeNames | (rootType == XPathNodeType.Root ? XPathDocument.LoadFlags.None : XPathDocument.LoadFlags.Fragment), string.Empty);
_writer.NamespaceResolver = nsResolver;
return _writer;
}
/// <summary>
/// End construction of a new Xml tree (document or fragment).
/// </summary>
public override void EndTree()
{
// Add newly constructed document to sequence
_writer.Close();
_seqTyped.Add(_doc.CreateNavigator());
}
/// <summary>
/// Write a top-level item by reference.
/// </summary>
public override void WriteItem(XPathItem item)
{
// Preserve identity
_seqTyped.AddClone(item);
}
}
/// <summary>
/// An implementation of XmlSequenceWriter that converts an instance of the XQuery data model into a series
/// of calls to XmlRawWriter. The algorithm to do this is designed to be compatible with the rules in the
/// "XSLT 2.0 and XQuery 1.0 Serialization" spec. Here are the rules we use:
/// 1. An exception is thrown if the top-level sequence contains attribute or namespace nodes
/// 2. Each atomic value in the top-level sequence is converted to text, and XmlWriter.WriteString is called
/// 3. A call to XmlRawWriter.WriteWhitespace(" ") is made between adjacent atomic values at the top-level
/// 4. All items in the top-level sequence are merged together into a single result document.
/// </summary>
internal class XmlMergeSequenceWriter : XmlSequenceWriter
{
private XmlRawWriter _xwrt;
private bool _lastItemWasAtomic;
/// <summary>
/// Constructor.
/// </summary>
public XmlMergeSequenceWriter(XmlRawWriter xwrt)
{
_xwrt = xwrt;
_lastItemWasAtomic = false;
}
/// <summary>
/// Start construction of a new Xml tree (document or fragment).
/// </summary>
public override XmlRawWriter StartTree(XPathNodeType rootType, IXmlNamespaceResolver nsResolver, XmlNameTable nameTable)
{
if (rootType == XPathNodeType.Attribute || rootType == XPathNodeType.Namespace)
throw new XslTransformException(SR.XmlIl_TopLevelAttrNmsp, string.Empty);
// Provide a namespace resolver to the writer
_xwrt.NamespaceResolver = nsResolver;
return _xwrt;
}
/// <summary>
/// End construction of a new Xml tree (document or fragment).
/// </summary>
public override void EndTree()
{
_lastItemWasAtomic = false;
}
/// <summary>
/// Write a top-level item by reference.
/// </summary>
public override void WriteItem(XPathItem item)
{
if (item.IsNode)
{
XPathNavigator nav = item as XPathNavigator;
if (nav.NodeType == XPathNodeType.Attribute || nav.NodeType == XPathNodeType.Namespace)
throw new XslTransformException(SR.XmlIl_TopLevelAttrNmsp, string.Empty);
// Copy navigator to raw writer
CopyNode(nav);
_lastItemWasAtomic = false;
}
else
{
WriteString(item.Value);
}
}
/// <summary>
/// Write the string value of a top-level atomic value.
/// </summary>
private void WriteString(string value)
{
if (_lastItemWasAtomic)
{
// Insert space character between adjacent atomic values
_xwrt.WriteWhitespace(" ");
}
else
{
_lastItemWasAtomic = true;
}
_xwrt.WriteString(value);
}
/// <summary>
/// Copy the navigator subtree to the raw writer.
/// </summary>
private void CopyNode(XPathNavigator nav)
{
XPathNodeType nodeType;
int iLevel = 0;
while (true)
{
if (CopyShallowNode(nav))
{
nodeType = nav.NodeType;
if (nodeType == XPathNodeType.Element)
{
// Copy attributes
if (nav.MoveToFirstAttribute())
{
do
{
CopyShallowNode(nav);
}
while (nav.MoveToNextAttribute());
nav.MoveToParent();
}
// Copy namespaces in document order (navigator returns them in reverse document order)
XPathNamespaceScope nsScope = (iLevel == 0) ? XPathNamespaceScope.ExcludeXml : XPathNamespaceScope.Local;
if (nav.MoveToFirstNamespace(nsScope))
{
CopyNamespaces(nav, nsScope);
nav.MoveToParent();
}
_xwrt.StartElementContent();
}
// If children exist, move down to next level
if (nav.MoveToFirstChild())
{
iLevel++;
continue;
}
else
{
// EndElement
if (nav.NodeType == XPathNodeType.Element)
_xwrt.WriteEndElement(nav.Prefix, nav.LocalName, nav.NamespaceURI);
}
}
// No children
while (true)
{
if (iLevel == 0)
{
// The entire subtree has been copied
return;
}
if (nav.MoveToNext())
{
// Found a sibling, so break to outer loop
break;
}
// No siblings, so move up to previous level
iLevel--;
nav.MoveToParent();
// EndElement
if (nav.NodeType == XPathNodeType.Element)
_xwrt.WriteFullEndElement(nav.Prefix, nav.LocalName, nav.NamespaceURI);
}
}
}
/// <summary>
/// Begin shallow copy of the specified node to the writer. Returns true if the node might have content.
/// </summary>
private bool CopyShallowNode(XPathNavigator nav)
{
bool mayHaveChildren = false;
switch (nav.NodeType)
{
case XPathNodeType.Element:
_xwrt.WriteStartElement(nav.Prefix, nav.LocalName, nav.NamespaceURI);
mayHaveChildren = true;
break;
case XPathNodeType.Attribute:
_xwrt.WriteStartAttribute(nav.Prefix, nav.LocalName, nav.NamespaceURI);
_xwrt.WriteString(nav.Value);
_xwrt.WriteEndAttribute();
break;
case XPathNodeType.Text:
_xwrt.WriteString(nav.Value);
break;
case XPathNodeType.SignificantWhitespace:
case XPathNodeType.Whitespace:
_xwrt.WriteWhitespace(nav.Value);
break;
case XPathNodeType.Root:
mayHaveChildren = true;
break;
case XPathNodeType.Comment:
_xwrt.WriteComment(nav.Value);
break;
case XPathNodeType.ProcessingInstruction:
_xwrt.WriteProcessingInstruction(nav.LocalName, nav.Value);
break;
case XPathNodeType.Namespace:
_xwrt.WriteNamespaceDeclaration(nav.LocalName, nav.Value);
break;
default:
Debug.Fail($"Unexpected node type {nav.NodeType}");
break;
}
return mayHaveChildren;
}
/// <summary>
/// Copy all or some (which depends on nsScope) of the namespaces on the navigator's current node to the
/// raw writer.
/// </summary>
private void CopyNamespaces(XPathNavigator nav, XPathNamespaceScope nsScope)
{
string prefix = nav.LocalName;
string ns = nav.Value;
if (nav.MoveToNextNamespace(nsScope))
{
CopyNamespaces(nav, nsScope);
}
_xwrt.WriteNamespaceDeclaration(prefix, ns);
}
}
}
| |
using Xunit;
using Nsar.Nodes.CafEcTower.LoggerNet.Extract;
using System.Collections.Generic;
using Nsar.Nodes.Models.LoggerNet.TOA5;
using System;
using Nsar.Nodes.Models.LoggerNet.TOA5.DataTables;
using System.Linq;
namespace Nsar.Nodes.CafEcTower.LoggerNet.Tests
{
public class TOA5ExtractorTests_Meteorology
{
private readonly string pathToFileWithValidContent;
private readonly string pathToFileToTestTimeZone;
public TOA5ExtractorTests_Meteorology()
{
pathToFileWithValidContent = @"Assets/CookEastEcTower_Met_Raw_2017_06_20_1115.dat";
pathToFileToTestTimeZone = @"Assets/CookEastEcTower_Met_Raw_TestTimeZone.dat";
}
[Fact]
public void FilePathConstructor_ValidContent_SetsData()
{
//# Arrange
string expectedFileName = "CookEastEcTower_Met_Raw_2017_06_20_1115.dat";
int expectedContentLength = 710;
//# Act
TOA5Extractor sut = new TOA5Extractor(pathToFileWithValidContent);
//# Assert
Assert.Equal(expectedFileName, sut.FileName);
Assert.Equal(expectedContentLength, sut.FileContent.Length);
}
[Fact]
public void GetObservations_ValidContent_ReturnsCorrectObservations()
{
//# Arrange
List<IObservation> actualObservations = new List<IObservation>();
Meteorology expectedRecord = new Meteorology()
{
TIMESTAMP = new System.DateTime(2017, 6, 20, 11, 30, 00),
RECORD = 15,
amb_tmpr_Avg = 23.13316,
rslt_wnd_spd = 4.940109,
wnd_dir_compass = 259.7,
RH_Avg = 56.22676,
Precipitation_Tot = 0,
amb_press_Avg = 93.25672,
PAR_density_Avg = 1956.598,
batt_volt_Avg = 13.63667,
panel_tmpr_Avg = 25.22728,
std_wnd_dir = 14.26,
VPD_air = 1.244421,
Rn_meas_Avg = 643.2509
};
//# Act
TOA5Extractor sut = new TOA5Extractor(pathToFileWithValidContent);
actualObservations = sut.GetObservations<Meteorology>().Cast<IObservation>().ToList();
//# Assert
// TODO: Override obj.Equals for better test
Assert.Equal(expectedRecord.amb_tmpr_Avg, actualObservations[1]
.GetType()
.GetProperty("amb_tmpr_Avg")
.GetValue(actualObservations[1], null));
Assert.Equal(expectedRecord.RECORD, actualObservations[1].RECORD);
Assert.Equal(expectedRecord.Rn_meas_Avg, actualObservations[1]
.GetType()
.GetProperty("Rn_meas_Avg")
.GetValue(actualObservations[1], null));
}
[Fact]
public void GetMetadata_ValidContent_ReturnsCorrectMetadata()
{
//# Arrange
Metadata actualMetadata = new Metadata();
Metadata expectedMetadata = new Metadata()
{
FileFormat = "TOA5",
StationName = "LTAR_CookEast",
DataLoggerType = "CR3000",
SerialNumber = 6503,
OperatingSystemVersion = "CR3000.Std.31",
DataloggerProgramName = "CPU:DEFAULT.CR3",
DataloggerProgramSignature = 13636,
TableName = "LTAR_Met",
Variables = new List<Variable>()
{
new Variable()
{
FieldName = "TIMESTAMP",
Units = "TS",
Processing = ""
},
new Variable()
{
FieldName = "RECORD",
Units = "",
Processing = ""
},
new Variable()
{
FieldName = "amb_tmpr_Avg",
Units = "C",
Processing = "Avg"
},
new Variable()
{
FieldName = "rslt_wnd_spd",
Units = "m/s",
Processing = "Smp"
},
new Variable()
{
FieldName = "wnd_dir_compass",
Units = "degrees",
Processing = "Smp"
},
new Variable()
{
FieldName = "RH_Avg",
Units = "%",
Processing = "Avg"
},
new Variable()
{
FieldName = "Precipitation_Tot",
Units = "mm",
Processing = "Tot"
},
new Variable()
{
FieldName = "amb_press_Avg",
Units = "kPa",
Processing = "Avg"
},
new Variable()
{
FieldName = "PAR_density_Avg",
Units = "umol/(s m^2)",
Processing = "Avg"
},
new Variable()
{
FieldName = "batt_volt_Avg",
Units = "V",
Processing = "Avg"
},
new Variable()
{
FieldName = "panel_tmpr_Avg",
Units = "C",
Processing = "Avg"
},
new Variable()
{
FieldName = "std_wnd_dir",
Units = "degrees",
Processing = "Smp"
},
new Variable()
{
FieldName = "VPD_air",
Units = "kpa",
Processing = "Smp"
},
new Variable()
{
FieldName = "Rn_meas_Avg",
Units = "W/m^2",
Processing = "Avg"
}
}
};
//# Act
TOA5Extractor sut = new TOA5Extractor(pathToFileWithValidContent);
actualMetadata = sut.GetMetadata();
//# Assert
// TODO: Override obj.Equals for better testing
Assert.Equal(expectedMetadata.FileFormat, actualMetadata.FileFormat);
Assert.Equal(expectedMetadata.TableName, actualMetadata.TableName);
Assert.Equal(expectedMetadata.SerialNumber, actualMetadata.SerialNumber);
Assert.Equal(
expectedMetadata.Variables.Find(mv => mv.FieldName == "TIMESTAMP").Processing,
actualMetadata.Variables.Find(mv => mv.FieldName == "TIMESTAMP").Processing);
Assert.Equal(
expectedMetadata.Variables.Find(mv => mv.FieldName == "amb_tmpr_Avg").Units,
actualMetadata.Variables.Find(mv => mv.FieldName == "amb_tmpr_Avg").Units);
Assert.Equal(
expectedMetadata.Variables.Find(mv => mv.FieldName == "Rn_meas_Avg").Units,
actualMetadata.Variables.Find(mv => mv.FieldName == "Rn_meas_Avg").Units);
}
[Fact]
public void GetObservations_AdjustedTimezone_ReturnsCorrectTimes()
{
//# Arrange
List<IObservation> actualObservations = new List<IObservation>();
//# Act
TOA5Extractor sut = new TOA5Extractor(pathToFileToTestTimeZone, -8);
actualObservations = sut.GetObservations<Meteorology>().Cast<IObservation>().ToList();
//# Assert
Assert.Equal(actualObservations[0].TIMESTAMP, new DateTime(2017, 06, 20, 8, 30, 0));
Assert.Equal(actualObservations[1].TIMESTAMP, new DateTime(2017, 06, 20, 19, 30, 0));
Assert.Equal(actualObservations[2].TIMESTAMP, new DateTime(2017, 06, 21, 7, 15, 0));
}
[Fact]
public void GetObservations_ContentWithNAN_DoesNotErrorSetsNull()
{
// Arrange
string dataPath = @"Assets/CookEastEcTower_Met_Raw_2017_10_24_0615.dat";
TOA5Extractor sut = new TOA5Extractor(dataPath);
// Act
List<IObservation> actualObs = sut.GetObservations<Meteorology>()
.Cast<IObservation>()
.ToList();
// Assert
// //observation.GetType().GetProperty(variable.FieldName).GetValue(observation, null)
Assert.Null(actualObs[0]
.GetType()
.GetProperty("VPD_air")
.GetValue(actualObs[0], null));
Assert.Null(actualObs[0]
.GetType()
.GetProperty("RH_Avg")
.GetValue(actualObs[0], null));
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.DeviceModels.Chipset.LPC3180.Drivers
{
using System;
using System.Runtime.CompilerServices;
using RT = Microsoft.Zelig.Runtime;
[Flags]
public enum InterruptSettings
{
Normal = 0x00000000,
Fast = 0x00000001,
LevelSensitive = 0x00000000,
EdgeSensitive = 0x00000002,
ActiveLowOrFalling = 0x00000000,
ActiveHighOrRising = 0x00000004,
ActiveLow = LevelSensitive | ActiveLowOrFalling,
ActiveHigh = LevelSensitive | ActiveHighOrRising,
FallingEdge = EdgeSensitive | ActiveLowOrFalling,
RisingEdge = EdgeSensitive | ActiveHighOrRising,
}
public abstract class InterruptController
{
public delegate void Callback( Handler handler );
public class Handler
{
//
// State
//
private int m_index;
private int m_section;
private InterruptSettings m_settings;
private Callback m_callback;
internal RT.KernelNode< Handler > m_node;
//
// Constructor Methods
//
private Handler( int index ,
InterruptSettings settings ,
Callback callback )
{
m_index = index % 32;
m_section = index / 32;
m_settings = settings;
m_callback = callback;
}
//
// Helper Methods
//
public static Handler Create( int index ,
InterruptSettings settings ,
Callback callback )
{
Handler hnd = new Handler( index, settings, callback );
hnd.m_node = new RT.KernelNode< Handler >( hnd );
return hnd;
}
public void Enable()
{
LPC3180.INTC.Section ctrl = LPC3180.INTC.Instance.Sections[m_section];
uint mask = this.Mask;
if(this.IsEdgeSensitive)
{
ctrl.ATR |= mask;
}
else
{
ctrl.ATR &= ~mask;
}
if(this.IsActiveHighOrRising)
{
ctrl.APR |= mask;
}
else
{
ctrl.APR &= ~mask;
}
if(this.IsFastHandler)
{
ctrl.ITR |= mask;
}
else
{
ctrl.ITR &= ~mask;
}
ctrl.ER |= mask;
}
public void Disable()
{
LPC3180.INTC.Section ctrl = LPC3180.INTC.Instance.Sections[m_section];
uint mask = this.Mask;
ctrl.ER &= ~mask;
}
public void Invoke()
{
m_callback( this );
}
//
// Access Methods
//
public uint Mask
{
[RT.Inline]
get
{
return 1U << m_index;
}
}
public int Index
{
get
{
return m_index;
}
}
public int Section
{
get
{
return m_section;
}
}
public bool IsFastHandler
{
[RT.Inline]
get
{
return (m_settings & InterruptSettings.Fast) != 0;
}
}
public bool IsEdgeSensitive
{
[RT.Inline]
get
{
return (m_settings & InterruptSettings.EdgeSensitive) != 0;;
}
}
public bool IsActiveHighOrRising
{
[RT.Inline]
get
{
return (m_settings & InterruptSettings.ActiveHighOrRising) != 0;;
}
}
}
//
// State
//
private RT.KernelList< Handler > m_handlers;
private Handler m_sub1Interrupt_IRQ;
private Handler m_sub1Interrupt_FIQ;
private Handler m_sub2Interrupt_IRQ;
private Handler m_sub2Interrupt_FIQ;
private Handler m_softInterrupt;
private RT.Peripherals.Continuation m_softCallback;
//
// Helper Methods
//
public void Initialize()
{
m_handlers = new RT.KernelList< Handler >();
LPC3180.INTC.Instance.Sections[0].ER = 0;
LPC3180.INTC.Instance.Sections[1].ER = 0;
LPC3180.INTC.Instance.Sections[2].ER = 0;
//--//
m_sub1Interrupt_IRQ = InterruptController.Handler.Create( LPC3180.INTC.IRQ_INDEX_Sub1IRQn, InterruptSettings.ActiveLow , ProcessSub1Interrupt );
m_sub1Interrupt_FIQ = InterruptController.Handler.Create( LPC3180.INTC.IRQ_INDEX_Sub1FIQn, InterruptSettings.ActiveLow , ProcessSub1Interrupt );
m_sub2Interrupt_IRQ = InterruptController.Handler.Create( LPC3180.INTC.IRQ_INDEX_Sub2IRQn, InterruptSettings.ActiveLow , ProcessSub2Interrupt );
m_sub2Interrupt_FIQ = InterruptController.Handler.Create( LPC3180.INTC.IRQ_INDEX_Sub2FIQn, InterruptSettings.ActiveLow , ProcessSub2Interrupt );
m_softInterrupt = InterruptController.Handler.Create( LPC3180.INTC.IRQ_INDEX_SW_INT , InterruptSettings.ActiveHigh, ProcessSoftInterrupt );
RegisterAndEnable( m_sub1Interrupt_IRQ );
RegisterAndEnable( m_sub1Interrupt_FIQ );
RegisterAndEnable( m_sub2Interrupt_IRQ );
RegisterAndEnable( m_sub2Interrupt_FIQ );
RegisterAndEnable( m_softInterrupt );
}
//--//
public void RegisterAndEnable( Handler hnd )
{
Register( hnd );
hnd.Enable();
}
public void Register( Handler hnd )
{
RT.BugCheck.AssertInterruptsOff();
m_handlers.InsertAtTail( hnd.m_node );
}
//--//
public void DeregisterAndDisable( Handler hnd )
{
RT.BugCheck.AssertInterruptsOff();
hnd.Disable();
Deregister( hnd );
}
public void Deregister( Handler hnd )
{
RT.BugCheck.AssertInterruptsOff();
hnd.m_node.RemoveFromList();
}
//--//
public void ProcessInterrupt()
{
ProcessSection( LPC3180.INTC.Instance.Sections[0], 0 );
}
private void ProcessSection( LPC3180.INTC.Section ctrl ,
int section )
{
while(true)
{
uint status = ctrl.SR;
if(status == 0)
{
break;
}
do
{
RT.KernelNode< Handler > node = m_handlers.StartOfForwardWalk;
while(true)
{
if(node.IsValidForForwardMove == false)
{
//
// BUGBUG: Unhandled interrupts. We should crash. For now we just disable them.
//
ctrl.ER &= ~status;
break;
}
Handler hnd = node.Target;
if(hnd.Section == section)
{
uint mask = hnd.Mask;
if((status & mask) != 0)
{
status &= ~mask;
hnd.Invoke();
break;
}
}
node = node.Next;
}
}
while(status != 0);
}
}
//// [RT.MemoryRequirements( RT.MemoryAttributes.Unpaged )]
public void ProcessFastInterrupt()
{
ProcessInterrupt();
}
public void CauseInterrupt()
{
var val = new SystemControl.SW_INT_bitfield();
val.Raise = true;
LPC3180.SystemControl.Instance.SW_INT = val;
}
public void ContinueUnderNormalInterrupt( RT.Peripherals.Continuation dlg )
{
m_softCallback = dlg;
CauseInterrupt();
}
private void ProcessSub1Interrupt( InterruptController.Handler handler )
{
ProcessSection( LPC3180.INTC.Instance.Sections[1], 1 );
}
private void ProcessSub2Interrupt( InterruptController.Handler handler )
{
ProcessSection( LPC3180.INTC.Instance.Sections[2], 2 );
}
private void ProcessSoftInterrupt( InterruptController.Handler handler )
{
var val = new SystemControl.SW_INT_bitfield();
val.Raise = false;
LPC3180.SystemControl.Instance.SW_INT = val;
RT.Peripherals.Continuation dlg = System.Threading.Interlocked.Exchange( ref m_softCallback, null );
if(dlg != null)
{
dlg();
}
}
//
// Access Methods
//
public static extern InterruptController Instance
{
[RT.SingletonFactory()]
[MethodImpl( MethodImplOptions.InternalCall )]
get;
}
}
}
| |
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
using Microsoft.AspNetCore.Routing;
using Moq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using NetEscapades.AspNetCore.SecurityHeaders.Infrastructure;
using Xunit;
namespace NetEscapades.AspNetCore.SecurityHeaders.TagHelpers.Test
{
public class HashTagHelperTests
{
const string shortSnippet = @"var msg = document.getElementById('message');";
const string scriptSnippet = @"
var msg = document.getElementById('message');
msg.innerText = ""My JavaScript is running!"";
";
const string styleSnippet = @" #message {
color: red;
} ";
[Fact]
public async Task ProcessAsync_Script_GeneratesExpectedOutput()
{
// Arrange
var id = Guid.NewGuid().ToString();
var tagName = "script";
var tagHelperContext = GetTagHelperContext(id, tagName);
var tagHelper = new HashTagHelper()
{
CSPHashType = CSPHashType.SHA256,
ViewContext = GetViewContext(),
};
var output = new TagHelperOutput(
tagName,
attributes: new TagHelperAttributeList(),
getChildContentAsync: (useCachedResult, encoder) =>
{
var tagHelperContent = new DefaultTagHelperContent();
tagHelperContent.SetHtmlContent(scriptSnippet);
return Task.FromResult<TagHelperContent>(tagHelperContent);
});
output.Content.SetHtmlContent(shortSnippet);
// Act
await tagHelper.ProcessAsync(tagHelperContext, output);
// Assert
Assert.Equal(tagName, output.TagName);
Assert.Empty(output.Attributes);
Assert.Equal(shortSnippet, output.Content.GetContent());
}
[Fact]
public async Task ProcessAsync_Script_AddsHashToHttpContextForOneLineSnippets()
{
// Arrange
var id = Guid.NewGuid().ToString();
var tagName = "script";
var tagHelperContext = GetTagHelperContext(id, tagName);
var tagHelper = new HashTagHelper()
{
CSPHashType = CSPHashType.SHA256,
ViewContext = GetViewContext(),
};
var output = new TagHelperOutput(
tagName,
attributes: new TagHelperAttributeList(),
getChildContentAsync: (useCachedResult, encoder) =>
{
var tagHelperContent = new DefaultTagHelperContent();
tagHelperContent.SetHtmlContent(shortSnippet);
return Task.FromResult<TagHelperContent>(tagHelperContent);
});
// Act
await tagHelper.ProcessAsync(tagHelperContext, output);
// Assert
var hash = Assert.Single(tagHelper.ViewContext.HttpContext.GetScriptCSPHashes());
var expected = "'sha256-1yLcYHZUiV92moZ6snTrg6e0yBO8emEEpUSB2wlMFz8='";
Assert.Equal(expected, hash);
}
[Fact]
public async Task ProcessAsync_Script_AddsHashToHttpContextForMultiLineSnippets()
{
// Arrange
var id = Guid.NewGuid().ToString();
var tagName = "script";
var tagHelperContext = GetTagHelperContext(id, tagName);
var tagHelper = new HashTagHelper()
{
CSPHashType = CSPHashType.SHA256,
ViewContext = GetViewContext(),
};
var output = new TagHelperOutput(
tagName,
attributes: new TagHelperAttributeList(),
getChildContentAsync: (useCachedResult, encoder) =>
{
var tagHelperContent = new DefaultTagHelperContent();
tagHelperContent.SetHtmlContent(scriptSnippet);
return Task.FromResult<TagHelperContent>(tagHelperContent);
});
// Act
await tagHelper.ProcessAsync(tagHelperContext, output);
// Assert
var hash = Assert.Single(tagHelper.ViewContext.HttpContext.GetScriptCSPHashes());
var expected = "'sha256-Oro8tit8euyKzxqyJteBRTdQBlipvXGQWfS5epMHmUU='";
Assert.Equal(expected, hash);
}
[Fact]
public async Task ProcessAsync_Style_GeneratesExpectedOutput()
{
// Arrange
var id = Guid.NewGuid().ToString();
var tagName = "style";
var tagHelperContext = GetTagHelperContext(id, tagName);
var tagHelper = new HashTagHelper()
{
CSPHashType = CSPHashType.SHA256,
ViewContext = GetViewContext(),
};
var output = new TagHelperOutput(
tagName,
attributes: new TagHelperAttributeList(),
getChildContentAsync: (useCachedResult, encoder) =>
{
var tagHelperContent = new DefaultTagHelperContent();
tagHelperContent.SetHtmlContent(scriptSnippet);
return Task.FromResult<TagHelperContent>(tagHelperContent);
});
output.Content.SetHtmlContent(styleSnippet);
// Act
await tagHelper.ProcessAsync(tagHelperContext, output);
// Assert
Assert.Equal(tagName, output.TagName);
Assert.Empty(output.Attributes);
Assert.Equal(styleSnippet, output.Content.GetContent());
}
[Fact]
public async Task ProcessAsync_Style_AddsHashToHttpContextForOneLineSnippets()
{
// Arrange
var id = Guid.NewGuid().ToString();
var tagName = "style";
var tagHelperContext = GetTagHelperContext(id, tagName);
var tagHelper = new HashTagHelper()
{
CSPHashType = CSPHashType.SHA256,
ViewContext = GetViewContext(),
};
var output = new TagHelperOutput(
tagName,
attributes: new TagHelperAttributeList(),
getChildContentAsync: (useCachedResult, encoder) =>
{
var tagHelperContent = new DefaultTagHelperContent();
tagHelperContent.SetHtmlContent(styleSnippet);
return Task.FromResult<TagHelperContent>(tagHelperContent);
});
// Act
await tagHelper.ProcessAsync(tagHelperContext, output);
// Assert
var hash = Assert.Single(tagHelper.ViewContext.HttpContext.GetStyleCSPHashes());
var expected = "'sha256-Wz9o8J/ijdXtAzs95rmQ8OtBacYk6JfYTXQlM8yxIjg='";
Assert.Equal(expected, hash);
}
private static ViewContext GetViewContext()
{
var actionContext = new ActionContext(new DefaultHttpContext(), new RouteData(), new ActionDescriptor());
return new ViewContext(actionContext,
Mock.Of<IView>(),
new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()),
Mock.Of<ITempDataDictionary>(),
TextWriter.Null,
new HtmlHelperOptions());
}
private static TagHelperContext GetTagHelperContext(string id = "testid", string tagName = "script")
{
return new TagHelperContext(
tagName: tagName,
allAttributes: new TagHelperAttributeList(),
items: new Dictionary<object, object>(),
uniqueId: id);
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="StorageProgress.cs" company="Microsoft">
// Copyright 2017 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-----------------------------------------------------------------------
#if !WINDOWS_RT
namespace Microsoft.Azure.Storage.Core.Util
{
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Holds information about the progress data transfers for both request and response streams in a single operation.
/// </summary>
/// <remarks>
/// ## Examples
/// [!code-csharp[StorageProgress](~/azure-storage-net/Test/WindowsRuntime/Blob/BlobUploadDownloadTest.cs#sample_StorageProgress_NetCore "StorageProgress Sample")]
/// </remarks>
public sealed class StorageProgress
{
/// <summary>
/// Progress in bytes of the request data transfer.
/// </summary>
public long BytesTransferred { get; private set; }
/// <summary>
/// Creates a <see cref="StorageProgress"/> object.
/// </summary>
/// <param name="bytesTransferred">The progress value being reported.</param>
public StorageProgress(long bytesTransferred)
{
this.BytesTransferred = bytesTransferred;
}
}
/// <summary>
/// An accumulator for request and response data transfers.
/// </summary>
internal sealed class AggregatingProgressIncrementer : IProgress<long>
{
long currentValue;
bool currentValueHasValue;
IProgress<StorageProgress> innerHandler;
public Stream CreateProgressIncrementingStream(Stream stream)
{
return innerHandler != null ? new ProgressIncrementingStream(stream, this) : stream;
}
public AggregatingProgressIncrementer(IProgress<StorageProgress> innerHandler)
{
this.innerHandler = innerHandler;
}
/// <summary>
/// Increments the current value and reports it to the progress handler
/// </summary>
/// <param name="bytes"></param>
public void Report(long bytes)
{
Interlocked.Add(ref this.currentValue, bytes);
Volatile.Write(ref this.currentValueHasValue, true);
if (this.innerHandler != null)
{
StorageProgress current = this.Current;
if (current != null)
{
this.innerHandler.Report(current);
}
}
}
/// <summary>
/// Zeroes out the current accumulation, and reports it to the progress handler
/// </summary>
public void Reset()
{
long currentActual = Volatile.Read(ref this.currentValue);
this.Report(-currentActual);
}
static readonly AggregatingProgressIncrementer nullHandler = new AggregatingProgressIncrementer(default(IProgress<StorageProgress>));
/// <summary>
/// Returns an instance that no-ops accumulation.
/// </summary>
public static AggregatingProgressIncrementer None
{
get
{
return nullHandler;
}
}
/// <summary>
/// Returns a StorageProgress instance representing the current progress value.
/// </summary>
public StorageProgress Current
{
get
{
StorageProgress result = default(StorageProgress);
if (this.currentValueHasValue)
{
long currentActual = Volatile.Read(ref this.currentValue);
result = new StorageProgress(currentActual);
}
return result;
}
}
}
/// <summary>
/// Wraps a stream, and reports position updates to a progress incrementer
/// </summary>
internal class ProgressIncrementingStream : Stream
{
Stream innerStream;
AggregatingProgressIncrementer incrementer;
public ProgressIncrementingStream(Stream stream, AggregatingProgressIncrementer incrementer)
{
if (stream == null)
{
throw new ArgumentNullException("stream");
}
if (incrementer == null)
{
throw new ArgumentNullException("incrementer");
}
this.innerStream = stream;
this.incrementer = incrementer;
}
public override bool CanRead
{
get
{
return this.innerStream.CanRead;
}
}
public override bool CanSeek
{
get
{
return this.innerStream.CanSeek;
}
}
public override bool CanTimeout
{
get
{
return this.innerStream.CanTimeout;
}
}
public override bool CanWrite
{
get
{
return this.innerStream.CanWrite;
}
}
public override async Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
long oldPosition = this.innerStream.Position;
await this.innerStream.CopyToAsync(destination, bufferSize, cancellationToken).ConfigureAwait(false);
long newPosition = this.innerStream.Position;
this.incrementer.Report(newPosition - oldPosition);
}
protected override void Dispose(bool disposing)
{
this.innerStream.Dispose();
}
public override async Task FlushAsync(CancellationToken cancellationToken)
{
long oldPosition = this.innerStream.Position;
await this.innerStream.FlushAsync(cancellationToken).ConfigureAwait(false);
long newPosition = this.innerStream.Position;
this.incrementer.Report(newPosition - oldPosition);
}
public override void Flush()
{
long oldPosition = this.innerStream.Position;
this.innerStream.Flush();
long newPosition = this.innerStream.Position;
this.incrementer.Report(newPosition - oldPosition);
}
public override long Length
{
get
{
return this.innerStream.Length;
}
}
public override long Position
{
get
{
return this.innerStream.Position;
}
set
{
long delta = value - this.innerStream.Position;
this.innerStream.Position = value;
this.incrementer.Report(delta);
}
}
public override int Read(byte[] buffer, int offset, int count)
{
int n = this.innerStream.Read(buffer, offset, count);
this.incrementer.Report(n);
return n;
}
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
int n = await this.innerStream.ReadAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false);
this.incrementer.Report(n);
return n;
}
public override int ReadByte()
{
int b = this.innerStream.ReadByte();
if (b != -1) // -1 = end of stream sentinel
{
this.incrementer.Report(1);
}
return b;
}
public override int ReadTimeout
{
get
{
return this.innerStream.ReadTimeout;
}
set
{
this.innerStream.ReadTimeout = value;
}
}
public override long Seek(long offset, SeekOrigin origin)
{
long oldPosition = this.innerStream.Position;
long newPosition = this.innerStream.Seek(offset, origin);
this.incrementer.Report(newPosition - oldPosition);
return newPosition;
}
public override void SetLength(long value)
{
this.innerStream.SetLength(value);
}
public override void Write(byte[] buffer, int offset, int count)
{
this.innerStream.Write(buffer, offset, count);
this.incrementer.Report(count);
}
public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
await this.innerStream.WriteAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false);
this.incrementer.Report(count);
}
public override void WriteByte(byte value)
{
this.innerStream.WriteByte(value);
this.incrementer.Report(1);
}
public override int WriteTimeout
{
get
{
return this.innerStream.WriteTimeout;
}
set
{
this.innerStream.WriteTimeout = value;
}
}
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
using System;
using System.Security;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
namespace System.Runtime.InteropServices.WindowsRuntime
{
// This is a set of stub methods implementing the support for the IReadOnlyDictionary`2 interface on WinRT
// objects that support IMapView`2. Used by the interop mashaling infrastructure.
//
// The methods on this class must be written VERY carefully to avoid introducing security holes.
// That's because they are invoked with special "this"! The "this" object
// for all of these methods are not IMapViewToIReadOnlyDictionaryAdapter objects. Rather, they are of type
// IMapView<K, V>. No actual IMapViewToIReadOnlyDictionaryAdapter object is ever instantiated. Thus, you will see
// a lot of expressions that cast "this" to "IMapView<K, V>".
[DebuggerDisplay("Count = {Count}")]
internal sealed class IMapViewToIReadOnlyDictionaryAdapter
{
private IMapViewToIReadOnlyDictionaryAdapter()
{
Debug.Assert(false, "This class is never instantiated");
}
// V this[K key] { get }
internal V Indexer_Get<K, V>(K key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
Contract.EndContractBlock();
IMapView<K, V> _this = JitHelpers.UnsafeCast<IMapView<K, V>>(this);
return Lookup(_this, key);
}
// IEnumerable<K> Keys { get }
internal IEnumerable<K> Keys<K, V>()
{
IMapView<K, V> _this = JitHelpers.UnsafeCast<IMapView<K, V>>(this);
IReadOnlyDictionary<K, V> roDictionary = (IReadOnlyDictionary<K, V>)_this;
return new ReadOnlyDictionaryKeyCollection<K, V>(roDictionary);
}
// IEnumerable<V> Values { get }
internal IEnumerable<V> Values<K, V>()
{
IMapView<K, V> _this = JitHelpers.UnsafeCast<IMapView<K, V>>(this);
IReadOnlyDictionary<K, V> roDictionary = (IReadOnlyDictionary<K, V>)_this;
return new ReadOnlyDictionaryValueCollection<K, V>(roDictionary);
}
// bool ContainsKey(K key)
[Pure]
internal bool ContainsKey<K, V>(K key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
IMapView<K, V> _this = JitHelpers.UnsafeCast<IMapView<K, V>>(this);
return _this.HasKey(key);
}
// bool TryGetValue(TKey key, out TValue value)
internal bool TryGetValue<K, V>(K key, out V value)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
IMapView<K, V> _this = JitHelpers.UnsafeCast<IMapView<K, V>>(this);
// It may be faster to call HasKey then Lookup. On failure, we would otherwise
// throw an exception from Lookup.
if (!_this.HasKey(key))
{
value = default(V);
return false;
}
try
{
value = _this.Lookup(key);
return true;
}
catch (Exception ex) // Still may hit this case due to a race condition
{
if (__HResults.E_BOUNDS == ex._HResult)
{
value = default(V);
return false;
}
throw;
}
}
#region Helpers
private static V Lookup<K, V>(IMapView<K, V> _this, K key)
{
Contract.Requires(null != key);
try
{
return _this.Lookup(key);
}
catch (Exception ex)
{
if (__HResults.E_BOUNDS == ex._HResult)
throw new KeyNotFoundException(SR.Arg_KeyNotFound);
throw;
}
}
#endregion Helpers
}
// Note: One day we may make these return IReadOnlyCollection<T>
[DebuggerDisplay("Count = {Count}")]
internal sealed class ReadOnlyDictionaryKeyCollection<TKey, TValue> : IEnumerable<TKey>
{
private readonly IReadOnlyDictionary<TKey, TValue> dictionary;
public ReadOnlyDictionaryKeyCollection(IReadOnlyDictionary<TKey, TValue> dictionary)
{
if (dictionary == null)
throw new ArgumentNullException(nameof(dictionary));
this.dictionary = dictionary;
}
/*
public void CopyTo(TKey[] array, int index)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index));
if (array.Length <= index && this.Count > 0)
throw new ArgumentException(SR.Arg_IndexOutOfRangeException);
if (array.Length - index < dictionary.Count)
throw new ArgumentException(SR.Argument_InsufficientSpaceToCopyCollection);
int i = index;
foreach (KeyValuePair<TKey, TValue> mapping in dictionary)
{
array[i++] = mapping.Key;
}
}
public int Count {
get { return dictionary.Count; }
}
public bool Contains(TKey item)
{
return dictionary.ContainsKey(item);
}
*/
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<TKey>)this).GetEnumerator();
}
public IEnumerator<TKey> GetEnumerator()
{
return new ReadOnlyDictionaryKeyEnumerator<TKey, TValue>(dictionary);
}
} // public class ReadOnlyDictionaryKeyCollection<TKey, TValue>
internal sealed class ReadOnlyDictionaryKeyEnumerator<TKey, TValue> : IEnumerator<TKey>
{
private readonly IReadOnlyDictionary<TKey, TValue> dictionary;
private IEnumerator<KeyValuePair<TKey, TValue>> enumeration;
public ReadOnlyDictionaryKeyEnumerator(IReadOnlyDictionary<TKey, TValue> dictionary)
{
if (dictionary == null)
throw new ArgumentNullException(nameof(dictionary));
this.dictionary = dictionary;
enumeration = dictionary.GetEnumerator();
}
void IDisposable.Dispose()
{
enumeration.Dispose();
}
public bool MoveNext()
{
return enumeration.MoveNext();
}
Object IEnumerator.Current
{
get { return ((IEnumerator<TKey>)this).Current; }
}
public TKey Current
{
get { return enumeration.Current.Key; }
}
public void Reset()
{
enumeration = dictionary.GetEnumerator();
}
} // class ReadOnlyDictionaryKeyEnumerator<TKey, TValue>
[DebuggerDisplay("Count = {Count}")]
internal sealed class ReadOnlyDictionaryValueCollection<TKey, TValue> : IEnumerable<TValue>
{
private readonly IReadOnlyDictionary<TKey, TValue> dictionary;
public ReadOnlyDictionaryValueCollection(IReadOnlyDictionary<TKey, TValue> dictionary)
{
if (dictionary == null)
throw new ArgumentNullException(nameof(dictionary));
this.dictionary = dictionary;
}
/*
public void CopyTo(TValue[] array, int index)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index));
if (array.Length <= index && this.Count > 0)
throw new ArgumentException(SR.Arg_IndexOutOfRangeException);
if (array.Length - index < dictionary.Count)
throw new ArgumentException(SR.Argument_InsufficientSpaceToCopyCollection);
int i = index;
foreach (KeyValuePair<TKey, TValue> mapping in dictionary)
{
array[i++] = mapping.Value;
}
}
public int Count {
get { return dictionary.Count; }
}
public bool Contains(TValue item)
{
EqualityComparer<TValue> comparer = EqualityComparer<TValue>.Default;
foreach (TValue value in this)
if (comparer.Equals(item, value))
return true;
return false;
}
*/
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<TValue>)this).GetEnumerator();
}
public IEnumerator<TValue> GetEnumerator()
{
return new ReadOnlyDictionaryValueEnumerator<TKey, TValue>(dictionary);
}
} // public class ReadOnlyDictionaryValueCollection<TKey, TValue>
internal sealed class ReadOnlyDictionaryValueEnumerator<TKey, TValue> : IEnumerator<TValue>
{
private readonly IReadOnlyDictionary<TKey, TValue> dictionary;
private IEnumerator<KeyValuePair<TKey, TValue>> enumeration;
public ReadOnlyDictionaryValueEnumerator(IReadOnlyDictionary<TKey, TValue> dictionary)
{
if (dictionary == null)
throw new ArgumentNullException(nameof(dictionary));
this.dictionary = dictionary;
enumeration = dictionary.GetEnumerator();
}
void IDisposable.Dispose()
{
enumeration.Dispose();
}
public bool MoveNext()
{
return enumeration.MoveNext();
}
Object IEnumerator.Current
{
get { return ((IEnumerator<TValue>)this).Current; }
}
public TValue Current
{
get { return enumeration.Current.Value; }
}
public void Reset()
{
enumeration = dictionary.GetEnumerator();
}
} // class ReadOnlyDictionaryValueEnumerator<TKey, TValue>
}
| |
// 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 is used internally to create best fit behavior as per the original windows best fit behavior.
//
using System;
using System.Text;
using System.Threading;
using System.Diagnostics;
namespace System.Text
{
internal sealed class InternalDecoderBestFitFallback : DecoderFallback
{
// Our variables
internal BaseCodePageEncoding encoding = null;
internal char[] arrayBestFit = null;
internal char cReplacement = '?';
internal InternalDecoderBestFitFallback(BaseCodePageEncoding _encoding)
{
// Need to load our replacement characters table.
encoding = _encoding;
}
public override DecoderFallbackBuffer CreateFallbackBuffer()
{
return new InternalDecoderBestFitFallbackBuffer(this);
}
// Maximum number of characters that this instance of this fallback could return
public override int MaxCharCount
{
get
{
return 1;
}
}
public override bool Equals(object value)
{
InternalDecoderBestFitFallback that = value as InternalDecoderBestFitFallback;
if (that != null)
{
return (encoding.CodePage == that.encoding.CodePage);
}
return (false);
}
public override int GetHashCode()
{
return encoding.CodePage;
}
}
internal sealed class InternalDecoderBestFitFallbackBuffer : DecoderFallbackBuffer
{
// Our variables
internal char cBestFit = '\0';
internal int iCount = -1;
internal int iSize;
private InternalDecoderBestFitFallback _oFallback;
// Private object for locking instead of locking on a public type for SQL reliability work.
private static object s_InternalSyncObject;
private static object InternalSyncObject
{
get
{
if (s_InternalSyncObject == null)
{
object o = new object();
Interlocked.CompareExchange<Object>(ref s_InternalSyncObject, o, null);
}
return s_InternalSyncObject;
}
}
// Constructor
public InternalDecoderBestFitFallbackBuffer(InternalDecoderBestFitFallback fallback)
{
_oFallback = fallback;
if (_oFallback.arrayBestFit == null)
{
// Lock so we don't confuse ourselves.
lock (InternalSyncObject)
{
// Double check before we do it again.
if (_oFallback.arrayBestFit == null)
_oFallback.arrayBestFit = fallback.encoding.GetBestFitBytesToUnicodeData();
}
}
}
// Fallback methods
public override bool Fallback(byte[] bytesUnknown, int index)
{
// We expect no previous fallback in our buffer
Debug.Assert(iCount < 1, "[DecoderReplacementFallbackBuffer.Fallback] Calling fallback without a previously empty buffer");
cBestFit = TryBestFit(bytesUnknown);
if (cBestFit == '\0')
cBestFit = _oFallback.cReplacement;
iCount = iSize = 1;
return true;
}
// Default version is overridden in DecoderReplacementFallback.cs
public override char GetNextChar()
{
// We want it to get < 0 because == 0 means that the current/last character is a fallback
// and we need to detect recursion. We could have a flag but we already have this counter.
iCount--;
// Do we have anything left? 0 is now last fallback char, negative is nothing left
if (iCount < 0)
return '\0';
// Need to get it out of the buffer.
// Make sure it didn't wrap from the fast count-- path
if (iCount == int.MaxValue)
{
iCount = -1;
return '\0';
}
// Return the best fit character
return cBestFit;
}
public override bool MovePrevious()
{
// Exception fallback doesn't have anywhere to back up to.
if (iCount >= 0)
iCount++;
// Return true if we could do it.
return (iCount >= 0 && iCount <= iSize);
}
// How many characters left to output?
public override int Remaining
{
get
{
return (iCount > 0) ? iCount : 0;
}
}
// Clear the buffer
public override unsafe void Reset()
{
iCount = -1;
}
// This version just counts the fallback and doesn't actually copy anything.
internal unsafe int InternalFallback(byte[] bytes, byte* pBytes)
// Right now this has both bytes and bytes[], since we might have extra bytes, hence the
// array, and we might need the index, hence the byte*
{
// return our replacement string Length (always 1 for InternalDecoderBestFitFallback, either
// a best fit char or ?
return 1;
}
// private helper methods
private char TryBestFit(byte[] bytesCheck)
{
// Need to figure out our best fit character, low is beginning of array, high is 1 AFTER end of array
int lowBound = 0;
int highBound = _oFallback.arrayBestFit.Length;
int index;
char cCheck;
// Check trivial case first (no best fit)
if (highBound == 0)
return '\0';
// If our array is too small or too big we can't check
if (bytesCheck.Length == 0 || bytesCheck.Length > 2)
return '\0';
if (bytesCheck.Length == 1)
cCheck = unchecked((char)bytesCheck[0]);
else
cCheck = unchecked((char)((bytesCheck[0] << 8) + bytesCheck[1]));
// Check trivial out of range case
if (cCheck < _oFallback.arrayBestFit[0] || cCheck > _oFallback.arrayBestFit[highBound - 2])
return '\0';
// Binary search the array
int iDiff;
while ((iDiff = (highBound - lowBound)) > 6)
{
// Look in the middle, which is complicated by the fact that we have 2 #s for each pair,
// so we don't want index to be odd because it must be word aligned.
// Also note that index can never == highBound (because diff is rounded down)
index = ((iDiff / 2) + lowBound) & 0xFFFE;
char cTest = _oFallback.arrayBestFit[index];
if (cTest == cCheck)
{
// We found it
Debug.Assert(index + 1 < _oFallback.arrayBestFit.Length,
"[InternalDecoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array");
return _oFallback.arrayBestFit[index + 1];
}
else if (cTest < cCheck)
{
// We weren't high enough
lowBound = index;
}
else
{
// We weren't low enough
highBound = index;
}
}
for (index = lowBound; index < highBound; index += 2)
{
if (_oFallback.arrayBestFit[index] == cCheck)
{
// We found it
Debug.Assert(index + 1 < _oFallback.arrayBestFit.Length,
"[InternalDecoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array");
return _oFallback.arrayBestFit[index + 1];
}
}
// Char wasn't in our table
return '\0';
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
namespace Windows7.DesktopIntegration.Interop
{
internal enum KNOWNDESTCATEGORY
{
KDC_FREQUENT = 1,
KDC_RECENT
}
internal enum APPDOCLISTTYPE
{
ADLT_RECENT = 0,
ADLT_FREQUENT
}
[StructLayout(LayoutKind.Sequential)]
internal struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
public RECT(int left, int top, int right, int bottom)
{
this.left = left;
this.top = top;
this.right = right;
this.bottom = bottom;
}
}
internal enum TBPFLAG
{
TBPF_NOPROGRESS = 0,
TBPF_INDETERMINATE = 0x1,
TBPF_NORMAL = 0x2,
TBPF_ERROR = 0x4,
TBPF_PAUSED = 0x8
}
internal enum TBATFLAG
{
TBATF_USEMDITHUMBNAIL = 0x1,
TBATF_USEMDILIVEPREVIEW = 0x2
}
internal enum THBMASK
{
THB_BITMAP = 0x1,
THB_ICON = 0x2,
THB_TOOLTIP = 0x4,
THB_FLAGS = 0x8
}
internal enum THBFLAGS
{
THBF_ENABLED = 0,
THBF_DISABLED = 0x1,
THBF_DISMISSONCLICK = 0x2,
THBF_NOBACKGROUND = 0x4,
THBF_HIDDEN = 0x8
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
internal struct THUMBBUTTON
{
[MarshalAs(UnmanagedType.U4)]
public THBMASK dwMask;
public uint iId;
public uint iBitmap;
public IntPtr hIcon;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szTip;
[MarshalAs(UnmanagedType.U4)]
public THBFLAGS dwFlags;
}
[StructLayout(LayoutKind.Sequential, Pack = 4)]
internal struct PropertyKey
{
public Guid fmtid;
public uint pid;
public PropertyKey(Guid fmtid, uint pid)
{
this.fmtid = fmtid;
this.pid = pid;
}
public static PropertyKey PKEY_Title = new PropertyKey(new Guid("F29F85E0-4FF9-1068-AB91-08002B27B3D9"), 2);
public static PropertyKey PKEY_AppUserModel_ID = new PropertyKey(new Guid("9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3"), 5);
public static PropertyKey PKEY_AppUserModel_IsDestListSeparator = new PropertyKey(new Guid("9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3"), 6);
public static PropertyKey PKEY_AppUserModel_RelaunchCommand = new PropertyKey(new Guid("9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3"), 2);
public static PropertyKey PKEY_AppUserModel_RelaunchDisplayNameResource = new PropertyKey(new Guid("9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3"), 4);
public static PropertyKey PKEY_AppUserModel_RelaunchIconResource = new PropertyKey(new Guid("9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3"), 3);
}
[StructLayout(LayoutKind.Explicit)]
internal struct CALPWSTR
{
[FieldOffset(0)]
internal uint cElems;
[FieldOffset(4)]
internal IntPtr pElems;
}
[StructLayout(LayoutKind.Explicit)]
internal struct PropVariant
{
[FieldOffset(0)]
private ushort vt;
[FieldOffset(8)]
private IntPtr pointerValue;
[FieldOffset(8)]
private byte byteValue;
[FieldOffset(8)]
private long longValue;
[FieldOffset(8)]
private short boolValue;
[MarshalAs(UnmanagedType.Struct)]
[FieldOffset(8)]
private CALPWSTR calpwstr;
[DllImport("ole32.dll")]
private static extern int PropVariantClear(ref PropVariant pvar);
public VarEnum VarType
{
get { return (VarEnum)vt; }
}
public void SetValue(String val)
{
this.Clear();
this.vt = (ushort)VarEnum.VT_LPWSTR;
this.pointerValue = Marshal.StringToCoTaskMemUni(val);
}
public void SetValue(bool val)
{
this.Clear();
this.vt = (ushort)VarEnum.VT_BOOL;
this.boolValue = val ? (short)-1 : (short)0;
}
public string GetValue()
{
return Marshal.PtrToStringUni(this.pointerValue);
}
public void Clear()
{
PropVariantClear(ref this);
}
}
internal enum SHARD
{
SHARD_PIDL = 0x1,
SHARD_PATHA = 0x2,
SHARD_PATHW = 0x3,
SHARD_APPIDINFO = 0x4, // indicates the data type is a pointer to a SHARDAPPIDINFO structure
SHARD_APPIDINFOIDLIST = 0x5, // indicates the data type is a pointer to a SHARDAPPIDINFOIDLIST structure
SHARD_LINK = 0x6, // indicates the data type is a pointer to an IShellLink instance
SHARD_APPIDINFOLINK = 0x7, // indicates the data type is a pointer to a SHARDAPPIDINFOLINK structure
}
/*
[StructLayout(LayoutKind.Sequential, Pack = 4)]
internal struct SHARDAPPIDINFO
{
//[MarshalAs(UnmanagedType.Interface)]
//public object psi; // The namespace location of the the item that should be added to the recent docs folder.
//public IntPtr psi;
public Microsoft.SDK.Samples.VistaBridge.Interop.IShellItem psi;
[MarshalAs(UnmanagedType.LPWStr)]
public string pszAppID; // The id of the application that should be associated with this recent doc.
}
*/
//TODO: Test this as well, currently not tested
[StructLayout(LayoutKind.Sequential, Pack = 4)]
internal struct SHARDAPPIDINFOIDLIST
{
public IntPtr pidl; // The idlist for the shell item that should be added to the recent docs folder.
[MarshalAs(UnmanagedType.LPWStr)]
public string pszAppID; // The id of the application that should be associated with this recent doc.
}
[StructLayout(LayoutKind.Sequential, Pack = 4)]
internal struct SHARDAPPIDINFOLINK
{
//public IntPtr psl; // An IShellLink instance that when launched opens a recently used item in the specified
//// application. This link is not added to the recent docs folder, but will be added to the
//// specified application's destination list.
public IShellLinkW psl;
[MarshalAs(UnmanagedType.LPWStr)]
public string pszAppID; // The id of the application that should be associated with this recent doc.
}
/*
[SuppressUnmanagedCodeSecurity]
internal static class SafeNativeMethods
{
//Obviously, these GUIDs shouldn't be modified. The reason they
//are not readonly is that they are passed with 'ref' to various
//native methods.
public static Guid IID_IObjectArray = new Guid("92CA9DCD-5622-4BBA-A805-5E9F541BD8C9");
public static Guid IID_IObjectCollection = new Guid("5632B1A4-E38A-400A-928A-D4CD63230295");
public static Guid IID_IPropertyStore = new Guid(VistaBridgeInterop.IIDGuid.IPropertyStore);
public static Guid IID_IUnknown = new Guid("00000000-0000-0000-C000-000000000046");
public const int DWM_SIT_DISPLAYFRAME = 0x00000001;
public const int DWMWA_FORCE_ICONIC_REPRESENTATION = 7;
public const int DWMWA_HAS_ICONIC_BITMAP = 10;
//TODO: DISALLOW_PEEK and FLIP3D_POLICY etc. sound interesting too
public const int WM_COMMAND = 0x111;
public const int WM_SYSCOMMAND = 0x112;
public const int WM_DWMSENDICONICTHUMBNAIL = 0x0323;
public const int WM_DWMSENDICONICLIVEPREVIEWBITMAP = 0x0326;
public const int WM_CLOSE = 0x0010;
public const int WM_ACTIVATE = 0x0006;
public const int WA_ACTIVE = 1;
public const int WA_CLICKACTIVE = 2;
public const int SC_CLOSE = 0xF060;
public const int MSGFLT_ADD = 1;
public const int MSGFLT_REMOVE = 2;
// Thumbbutton WM_COMMAND notification
public const uint THBN_CLICKED = 0x1800;
#region Shell Library
internal enum LIBRARYFOLDERFILTER
{
LFF_FORCEFILESYSTEM = 1,
LFF_STORAGEITEMS = 2,
LFF_ALLITEMS = 3
};
internal enum LIBRARYOPTIONFLAGS
{
LOF_DEFAULT = 0,
LOF_PINNEDTONAVPANE = 0x1,
LOF_MASK_ALL = 0x1
};
internal enum DEFAULTSAVEFOLDERTYPE
{
DSFT_DETECT = 1,
DSFT_PRIVATE = (DSFT_DETECT + 1),
DSFT_PUBLIC = (DSFT_PRIVATE + 1)
};
internal enum LIBRARYSAVEFLAGS
{
LSF_FAILIFTHERE = 0,
LSF_OVERRIDEEXISTING = 0x1,
LSF_MAKEUNIQUENAME = 0x2
};
internal enum LIBRARYMANAGEDIALOGOPTIONS
{
LMD_DEFAULT = 0,
LMD_NOUNINDEXABLELOCATIONWARNING = 0x1
};
internal enum StorageInstantiationModes
{
STGM_DIRECT = 0x00000000,
STGM_TRANSACTED = 0x00010000,
STGM_SIMPLE = 0x08000000,
STGM_READ = 0x00000000,
STGM_WRITE = 0x00000001,
STGM_READWRITE = 0x00000002,
STGM_SHARE_DENY_NONE = 0x00000040,
STGM_SHARE_DENY_READ = 0x00000030,
STGM_SHARE_DENY_WRITE = 0x00000020,
STGM_SHARE_EXCLUSIVE = 0x00000010,
STGM_PRIORITY = 0x00040000,
STGM_DELETEONRELEASE = 0x04000000,
STGM_NOSCRATCH = 0x00100000,
STGM_CREATE = 0x00001000,
STGM_CONVERT = 0x00020000,
STGM_FAILIFTHERE = 0x00000000,
STGM_NOSNAPSHOT = 0x00200000,
STGM_DIRECT_SWMR = 0x00400000
};
#endregion
}*/
[SuppressUnmanagedCodeSecurity]
internal static class UnsafeNativeMethods
{
[DllImport("shell32.dll")]
public static extern int SHGetPropertyStoreForWindow(
IntPtr hwnd,
ref Guid iid /*IID_IPropertyStore*/,
[Out(), MarshalAs(UnmanagedType.Interface)]
out IPropertyStore propertyStore);
[DllImport("dwmapi.dll")]
public static extern int DwmSetIconicThumbnail(
IntPtr hwnd, IntPtr hbitmap, uint flags);
/*
[DllImport("dwmapi.dll")]
public static extern int DwmSetIconicLivePreviewBitmap(
IntPtr hwnd,
IntPtr hbitmap,
ref VistaBridgeInterop.SafeNativeMethods.POINT ptClient,
uint flags);*/
[DllImport("dwmapi.dll")]
public static extern int DwmSetIconicLivePreviewBitmap(
IntPtr hwnd, IntPtr hbitmap, IntPtr ptClient, uint flags);
[DllImport("dwmapi.dll")]
public static extern int DwmInvalidateIconicBitmaps(IntPtr hwnd);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ChangeWindowMessageFilter(uint message, uint flags);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
internal static extern uint RegisterWindowMessage(string lpString);
public static uint WM_TaskbarButtonCreated
{
get
{
if (_uTBBCMsg == 0)
{
_uTBBCMsg = RegisterWindowMessage("TaskbarButtonCreated");
}
return _uTBBCMsg;
}
}
private static uint _uTBBCMsg;
[DllImport("shell32.dll")]
public static extern void SetCurrentProcessExplicitAppUserModelID(
[MarshalAs(UnmanagedType.LPWStr)] string AppID);
[DllImport("shell32.dll")]
public static extern void GetCurrentProcessExplicitAppUserModelID(
[Out(), MarshalAs(UnmanagedType.LPWStr)] out string AppID);
[DllImport("shell32.dll")]
public static extern void SHAddToRecentDocs(SHARD flags, IntPtr pv);
[DllImport("shell32.dll")]
public static extern void SHAddToRecentDocs(
SHARD flags,
[MarshalAs(UnmanagedType.LPWStr)] string path);
public static void SHAddToRecentDocs(string path)
{
UnsafeNativeMethods.SHAddToRecentDocs(SHARD.SHARD_PATHW, path);
}
/*
[DllImport("shell32.dll")]
public static extern void SHAddToRecentDocs(
SHARD flags,
ref SHARDAPPIDINFO appIDInfo);
public static void SHAddToRecentDocs(ref SHARDAPPIDINFO appIDInfo)
{
UnsafeNativeMethods.SHAddToRecentDocs(SHARD.SHARD_APPIDINFO, ref appIDInfo);
}*/
[DllImport("shell32.dll")]
public static extern void SHAddToRecentDocs(
SHARD flags,
[MarshalAs(UnmanagedType.LPStruct)] ref SHARDAPPIDINFOIDLIST appIDInfoIDList);
public static void SHAddToRecentDocs(ref SHARDAPPIDINFOIDLIST appIDInfoIDList)
{
UnsafeNativeMethods.SHAddToRecentDocs(SHARD.SHARD_APPIDINFOIDLIST, ref appIDInfoIDList);
}
[DllImport("shell32.dll")]
public static extern void SHAddToRecentDocs(
SHARD flags,
ref SHARDAPPIDINFOLINK appIDInfoLink);
public static void SHAddToRecentDocs(ref SHARDAPPIDINFOLINK appIDInfoLink)
{
UnsafeNativeMethods.SHAddToRecentDocs(SHARD.SHARD_APPIDINFOLINK, ref appIDInfoLink);
}
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetWindowRect(IntPtr hwnd, ref RECT rect);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetClientRect(IntPtr hwnd, ref RECT rect);
public static bool GetClientSize(IntPtr hwnd, out System.Drawing.Size size)
{
RECT rect = new RECT();
if (!GetClientRect(hwnd, ref rect))
{
size = new System.Drawing.Size(-1, -1);
return false;
}
size = new System.Drawing.Size(rect.right, rect.bottom);
return true;
}
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ShowWindow(IntPtr hwnd, int cmd);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetWindowPos(IntPtr hwnd, IntPtr hwndInsertAfter, int X, int Y, int cx, int cy, uint flags);
/*
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ClientToScreen(
IntPtr hwnd,
ref VistaBridgeInterop.SafeNativeMethods.POINT point);
*/
[DllImport("user32.dll")]
public static extern int GetWindowText(
IntPtr hwnd, StringBuilder str, int maxCount);
[DllImport("gdi32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool BitBlt (
IntPtr hDestDC, int destX, int destY, int width, int height,
IntPtr hSrcDC, int srcX, int srcY,
uint operation);
[DllImport("gdi32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool StretchBlt(
IntPtr hDestDC, int destX, int destY, int destWidth, int destHeight,
IntPtr hSrcDC, int srcX, int srcY, int srcWidth, int srcHeight,
uint operation);
[DllImport("user32.dll")]
public static extern IntPtr GetWindowDC(IntPtr hwnd);
[DllImport("user32.dll")]
public static extern int ReleaseDC(IntPtr hwnd, IntPtr hdc);
}
/*
internal static class NativeLibraryMethods
{
[DllImport("Shell32", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
internal static extern int SHShowManageLibraryUI(
[In, MarshalAs(UnmanagedType.Interface)] Microsoft.SDK.Samples.VistaBridge.Interop.IShellItem library,
[In] IntPtr hwndOwner,
[In] string title,
[In] string instruction,
[In] SafeNativeMethods.LIBRARYMANAGEDIALOGOPTIONS lmdOptions);
}*/
}
| |
// 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.12.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsAzureReport
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Test Infrastructure for AutoRest
/// </summary>
public partial class AutoRestReportServiceForAzure : ServiceClient<AutoRestReportServiceForAzure>, IAutoRestReportServiceForAzure, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public 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>
/// The management credentials for Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// The retry timeout for Long Running Operations.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// Initializes a new instance of the AutoRestReportServiceForAzure class.
/// </summary>
public AutoRestReportServiceForAzure() : base()
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestReportServiceForAzure class.
/// </summary>
/// <param name='handlers'>
/// Optional. The set of delegating handlers to insert in the http
/// client pipeline.
/// </param>
public AutoRestReportServiceForAzure(params DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestReportServiceForAzure class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The set of delegating handlers to insert in the http
/// client pipeline.
/// </param>
public AutoRestReportServiceForAzure(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestReportServiceForAzure class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The set of delegating handlers to insert in the http
/// client pipeline.
/// </param>
public AutoRestReportServiceForAzure(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestReportServiceForAzure class.
/// </summary>
/// <param name='credentials'>
/// Required. The management credentials for Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The set of delegating handlers to insert in the http
/// client pipeline.
/// </param>
public AutoRestReportServiceForAzure(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestReportServiceForAzure class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. The management credentials for Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The set of delegating handlers to insert in the http
/// client pipeline.
/// </param>
public AutoRestReportServiceForAzure(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.BaseUri = new Uri("http://localhost");
this.AcceptLanguage = "en-US";
SerializationSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new ResourceJsonConverter());
DeserializationSettings = new JsonSerializerSettings{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings.Converters.Add(new ResourceJsonConverter());
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
/// <summary>
/// Get test coverage report
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<IDictionary<string, int?>>> GetReportWithHttpMessagesAsync(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, "GetReport", tracingParameters);
}
// Construct URL
var baseUrl = this.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "report/azure").ToString();
List<string> queryParameters = new List<string>();
if (queryParameters.Count > 0)
{
url += "?" + string.Join("&", queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
if (this.AcceptLanguage != null)
{
if (httpRequest.Headers.Contains("accept-language"))
{
httpRequest.Headers.Remove("accept-language");
}
httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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);
}
}
// Set Credentials
if (this.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new AzureOperationResponse<IDictionary<string, int?>>();
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 (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<IDictionary<string, int?>>(responseContent, this.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
}
}
| |
#region using declarations
using System;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using System.Xml.Serialization;
using DigitallyImported.Components;
using DigitallyImported.Configuration.Properties;
#endregion
namespace DigitallyImported.Controls.Windows
{
/// <summary>
/// Summary description for ChannelSection.
/// </summary>
[Serializable]
[XmlRoot("RegularChannel")]
public partial class Channel : UserControl, IChannel
{
internal static EventHandler<EventArgs> _elementMouseHover;
private static readonly object _elementHoverLock = new object();
internal static EventHandler<ChannelChangedEventArgs<IChannel>> _channelChanged;
private static readonly object _channelChangedLock = new object();
private readonly object _channelRefreshedLock = new object();
private readonly object _historyClickedLock = new object();
private readonly object _trackChangedLock = new object();
internal EventHandler<TrackChangedEventArgs<ITrack>> _channelRefreshed;
internal EventHandler<EventArgs> _historyClicked;
internal EventHandler<TrackChangedEventArgs<ITrack>> _trackChanged;
private Uri channelInfoUrl;
private string channelName = string.Empty;
private ITrack currentTrack;
private bool isAlternating;
private bool isSelected;
private Uri playListHistoryUrl;
private IPlaylist playlist;
private StationType playlistType;
private Icon siteIcon;
private string siteName = string.Empty;
private StreamType streamType;
private StreamCollection<IStream> streams;
private SubscriptionLevel subscriptionLevel;
private TrackCollection<ITrack> tracks;
/// <summary>
/// </summary>
public Channel()
: this(StationType.Custom)
{
}
/// <summary>
/// </summary>
/// <param name="PlaylistTypes"> </param>
public Channel(StationType PlaylistTypes)
// : base(PlaylistTypes)
{
InitializeComponent();
PlaylistType = PlaylistTypes;
LoadImages();
// events
Settings.Default.SettingChanging += ChannelSection_SettingChanging;
}
/// <summary>
/// </summary>
/// <param name="track"> </param>
/// <returns> </returns>
public virtual IChannel this[ITrack track]
{
get { return tracks[track.Name].ParentChannel; }
}
/// <summary>
/// </summary>
/// <param name="index"> </param>
/// <returns> </returns>
public virtual IChannel this[int index]
{
get { return tracks[index].ParentChannel; }
}
#region IChannel Members
/// <summary>
/// Property to get/set the channel name
/// </summary>
[XmlAttribute("ChannelName")]
public virtual string ChannelName
{
get { return channelName; }
set
{
base.Name = value.Replace(" ", "").ToLower(); // unique key for control
channelName = value;
if (InvokeRequired)
{
Invoke((Action) delegate
{
foreach (Control c in Controls)
{
c.Name += value.Replace(" ", "").ToLower();
}
toolTipLinks.SetToolTip(lblChannelName, value);
lblChannelName.Text = value;
});
}
else
{
foreach (Control c in Controls)
{
c.Name += value.Replace(" ", "").ToLower();
}
toolTipLinks.SetToolTip(lblChannelName, value);
lblChannelName.Text = value;
}
}
}
/// <summary>
/// </summary>
[XmlElement("ChannelInfoUrl")]
public virtual Uri ChannelInfoUrl
{
get { return channelInfoUrl; }
set
{
channelInfoUrl = value;
if (InvokeRequired)
{
Invoke((Action) delegate
{
toolTipLinks.SetToolTip(lnkChannelInfo, value.AbsoluteUri);
lnkChannelInfo.Links[0].LinkData = value.AbsoluteUri;
});
}
else
{
toolTipLinks.SetToolTip(lnkChannelInfo, value.AbsoluteUri);
lnkChannelInfo.Links[0].LinkData = value.AbsoluteUri;
}
}
}
/// <summary>
/// </summary>
[XmlElement("SiteName")]
public virtual string SiteName
{
get { return siteName; }
set { siteName = value; }
}
/// <summary>
/// </summary>
[XmlElement("PlaylistHistoryUrl")]
public virtual Uri PlaylistHistoryUrl
{
get { return playListHistoryUrl; }
set
{
playListHistoryUrl = value;
if (InvokeRequired)
{
Invoke((Action) delegate
{
lnkPlaylistHistory.Links[0].LinkData = value.AbsoluteUri;
toolTipLinks.SetToolTip(lnkPlaylistHistory, value.AbsoluteUri);
});
}
else
{
lnkPlaylistHistory.Links[0].LinkData = value.AbsoluteUri;
toolTipLinks.SetToolTip(lnkPlaylistHistory, value.AbsoluteUri);
}
}
}
/// <summary>
/// </summary>
[XmlElement("SiteIcon")]
public virtual Icon SiteIcon
{
get { return siteIcon; }
set
{
if (InvokeRequired)
{
Invoke((Action) delegate { picSiteIcon.Image = value.ToBitmap(); });
}
else
{
picSiteIcon.Image = value.ToBitmap();
}
siteIcon = value;
}
}
/// <summary>
/// </summary>
[XmlElement("PlaylistType")]
public virtual StationType PlaylistType
{
get { return playlistType; }
set { playlistType = value; }
}
/// <summary>
/// </summary>
[XmlElement("SubscriptionLevel")]
public virtual SubscriptionLevel SubscriptionLevel
{
get { return subscriptionLevel; }
set { subscriptionLevel = value; }
}
/// <summary>
/// </summary>
[XmlElement("StreamType")]
public virtual StreamType StreamType
{
get { return streamType; }
set { streamType = value; }
}
/// <summary>
/// </summary>
[XmlArray("Streams")]
public virtual StreamCollection<IStream> Streams
{
get { return streams; }
set { streams = value; }
}
/// <summary>
/// </summary>
[XmlElement("Playlist")]
public virtual IPlaylist Playlist
{
get { return playlist; }
set { playlist = value; }
}
/// <summary>
/// </summary>
[XmlArray("Tracks")]
public virtual TrackCollection<ITrack> Tracks
{
get { return tracks; }
set
{
if (tracks != null)
{
if (!currentTrack.TrackTitle.Equals(value[0].TrackTitle))
{
Trace.WriteLine(string.Format("Track changed on channel {0}", ChannelName),
TraceCategory.ContentChangedEvents.ToString());
OnTrackChanged(this, new TrackChangedEventArgs<ITrack>(value[0]));
}
}
tracks = value;
currentTrack = tracks[0];
// update GUI...not very expensive
if (InvokeRequired)
{
Invoke((Action) SetValues);
}
else
{
SetValues();
}
}
}
/// <summary>
/// </summary>
[XmlIgnore]
public virtual ITrack CurrentTrack
{
get { return currentTrack; // CHANGE THIS PLEASE! should be the track marked as IsPlaying!
}
}
/// <summary>
/// </summary>
[XmlIgnore]
public virtual bool IsAlternating
{
get { return isAlternating; }
set
{
isAlternating = value;
if (InvokeRequired)
{
Invoke(
(Action)
delegate
{
BackColor = value
? Settings.Default.AlternatingChannelBackground
: Settings.Default.ChannelBackground;
});
}
else
{
BackColor = value
? Settings.Default.AlternatingChannelBackground
: Settings.Default.ChannelBackground;
}
}
}
/// <summary>
/// </summary>
[XmlElement("SelectedChannel")]
public virtual bool IsSelected
{
get { return isSelected; }
set
{
isSelected = value;
if (InvokeRequired)
{
Invoke((Action) delegate
{
if (value)
{
BackColor = Settings.Default.SelectedChannelBackground;
Focus();
}
else
{
BackColor = isAlternating
? Settings.Default.AlternatingChannelBackground
: Settings.Default.ChannelBackground;
}
});
}
else
{
if (value)
{
BackColor = Settings.Default.SelectedChannelBackground;
Focus();
}
else
{
BackColor = isAlternating
? Settings.Default.AlternatingChannelBackground
: Settings.Default.ChannelBackground;
}
}
}
}
/// <summary>
/// </summary>
[Browsable(true)]
public event EventHandler<TrackChangedEventArgs<ITrack>> TrackChanged
{
add
{
lock (_trackChangedLock)
{
{
_trackChanged += value;
}
}
}
remove
{
lock (_trackChangedLock)
{
_trackChanged -= value;
}
}
}
/// <summary>
/// </summary>
/// <param name="other"> </param>
/// <returns> </returns>
public bool Equals(IContent other)
{
return Name.Equals(other.Name, StringComparison.CurrentCultureIgnoreCase);
}
#endregion
/// <summary>
/// Method to initialize the image controls.
/// </summary>
protected internal virtual void LoadImages()
{
pic24k.Image = Resources.Properties.Resources.blue_24k;
pic32k.Image = Resources.Properties.Resources.blue_32k;
pic96k.Image = Resources.Properties.Resources.blue_96k;
picAacPlus.Image = Resources.Properties.Resources.icon_trans_aacplus;
picMp3.Image = Resources.Properties.Resources.icon_mp3;
picWmp.Image = Resources.Properties.Resources.icon_wm;
}
/// <summary>
/// Event to set the mouse cursor to hand upon entering a picture box
/// </summary>
/// <param name="sender"> sender </param>
/// <param name="e"> EventArgs </param>
protected internal virtual void PictureBox_MouseEnter(object sender, EventArgs e)
{
Cursor = Cursors.Hand;
var c = (Control) sender;
string name = c.Name.ToLower();
//switch (c.Name.ToLower().Substring(0, c.Name.Length - this.channelName.Replace(" ", "").Length))
//{
if (name.Contains("picmp3"))
{
toolTipLinks.SetToolTip(c, string.Format(siteName, Resources.Properties.Resources.MediaTypeMp3About));
//break;
}
if (name.Contains("picwmp"))
{
toolTipLinks.SetToolTip(c, string.Format(siteName, Resources.Properties.Resources.MediaTypeWmaAbout));
//break;
}
if (name.Contains("picaacplus"))
{
toolTipLinks.SetToolTip(c, string.Format(siteName, Resources.Properties.Resources.MediaTypeAacPlusAbout));
//break;
}
// testing, delete and refactor
if (name.Contains("pic24k"))
{
toolTipLinks.SetToolTip(c, Components.Utilities.GetChannelUri(StreamType.AacPlus,
siteName, channelName).AbsoluteUri);
//break;
}
if (name.Contains("pic32k"))
{
toolTipLinks.SetToolTip(c, Components.Utilities.GetChannelUri(StreamType.Wma,
siteName, channelName).AbsoluteUri);
//break;
}
if (name.Contains("pic96k"))
{
toolTipLinks.SetToolTip(c, Components.Utilities.GetChannelUri(StreamType.Mp3,
siteName, channelName).AbsoluteUri);
//break;
}
// end testing
//}
}
/// <summary>
/// Event to set the mouse cursor to arrow upon leaving a picture box
/// </summary>
/// <param name="sender"> sender </param>
/// <param name="e"> EventArgs </param>
protected internal virtual void PictureBox_MouseLeave(object sender, EventArgs e)
{
Cursor = Cursors.Arrow;
}
/// <summary>
/// </summary>
/// <param name="sender"> </param>
/// <param name="e"> </param>
protected internal virtual void LinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
var link = sender as LinkLabel;
if (link != null)
{
link.Tag = e.Link.LinkData ?? link.Text;
if (e.Button == MouseButtons.Left)
{
if (link.Name.Contains("lnkPlaylistHistory"))
{
OnPlaylistHistoryClicked(this, EventArgs.Empty);
}
else
{
Components.Utilities.StartProcess(e.Link.LinkData as string);
}
}
}
}
/// <summary>
/// </summary>
/// <param name="sender"> </param>
/// <param name="e"> </param>
protected internal virtual void ChannelSection_SettingChanging(object sender, SettingChangingEventArgs e)
{
switch (e.SettingName)
{
case ("AlternatingChannelBackground"):
{
// this.IsAlternating = true;
break;
}
case ("SelectedChannelBackground"):
{
// this.IsSelected = true;
break;
}
}
}
/// <summary>
/// </summary>
/// <param name="sender"> </param>
/// <param name="e"> </param>
protected internal virtual void OnChannelChanged(object sender, ChannelChangedEventArgs<IChannel> e)
{
if (_channelChanged != null)
{
_channelChanged(sender, e);
}
}
/// <summary>
/// Event to refresh the main page's playlist
/// </summary>
/// <param name="sender"> sender </param>
/// <param name="e"> EventArgs </param>
protected internal virtual void OnChannelRefreshed(object sender, TrackChangedEventArgs<ITrack> e)
{
if (_channelRefreshed != null)
{
_channelRefreshed(this, e);
}
}
/// <summary>
/// </summary>
/// <param name="sender"> sender </param>
/// <param name="e"> EventArgs </param>
protected internal virtual void OnTrackChanged(object sender, TrackChangedEventArgs<ITrack> e)
{
if (_trackChanged != null)
{
_trackChanged(this, e);
}
}
/// <summary>
/// </summary>
/// <param name="sender"> </param>
/// <param name="e"> </param>
protected internal virtual void OnPlaylistHistoryClicked(object sender, EventArgs e)
{
if (_historyClicked != null)
{
_historyClicked(this, e);
}
}
///// <summary>
/////
///// </summary>
///// <param name="sender"></param>
///// <param name="e"></param>
//protected internal virtual void Onee(object sender, CommentCountChangedEventArgs<IChannel> e)
//{
// if (_ee != null)
// {
// _ee(this, e);
// }
//}
/// <summary>
/// </summary>
/// <param name="sender"> </param>
/// <param name="e"> </param>
protected internal virtual void OnElementHover(object sender, PopupEventArgs e)
{
// TODO omplement
}
/// <summary>
/// </summary>
/// <returns> </returns>
public override string ToString()
{
return channelName;
}
/// <summary>
/// </summary>
/// <param name="sender"> </param>
/// <param name="e"> </param>
protected internal virtual void StreamType_MouseClick(object sender, MouseEventArgs e)
{
base.OnMouseDown(e);
// refactor into property -- TODO, break all inks into Uri's and use Uri methods to extract/build string
Uri linkUri = null;
// MediaType mediaType = MediaType.None;
var c = (Control) sender;
string name = c.Name.ToLower();
//switch (c.Name.ToLower().Substring(0, c.Name.Length - this.channelName.Replace(" ", "").Length))
//{
if (name.Contains("pic24k"))
{
linkUri = Components.Utilities.GetChannelUri(StreamType.AacPlus, siteName, channelName);
streamType = StreamType.AacPlus;
//break;
}
if (name.Contains("pic32k"))
{
linkUri = Components.Utilities.GetChannelUri(StreamType.Wma, siteName, channelName);
streamType = StreamType.Wma;
//break;
}
if (name.Contains("pic96k"))
{
linkUri = Components.Utilities.GetChannelUri(StreamType.Mp3, siteName, channelName);
streamType = StreamType.Mp3;
//break;
}
if (name.Contains("picmp3"))
{
Components.Utilities.StartProcess(string.Format(siteName,
Resources.Properties.Resources.MediaTypeMp3About));
//break;
}
if (name.Contains("picwmp"))
{
Components.Utilities.StartProcess(string.Format(siteName,
Resources.Properties.Resources.MediaTypeWmaAbout));
//break;
}
if (name.Contains("picaac"))
{
Components.Utilities.StartProcess(string.Format(siteName,
Resources.Properties.Resources.MediaTypeAacPlusAbout));
//break;
}
//}
// testing
currentTrack.TrackUrl = linkUri; // NEED TO SET THIS VALUE EARLIER
c.Tag = linkUri != null ? linkUri.AbsoluteUri : string.Empty;
if (e.Button == MouseButtons.Left)
OnChannelChanged(this, new ChannelChangedEventArgs<IChannel>(this));
}
/// <summary>
/// </summary>
[Browsable(true)]
public event EventHandler<TrackChangedEventArgs<ITrack>> ChannelRefreshed
{
add
{
lock (_channelRefreshedLock)
{
{
_channelRefreshed += value;
}
}
}
remove
{
lock (_channelRefreshedLock)
{
_channelRefreshed -= value;
}
}
}
/// <summary>
/// </summary>
// todo refactor this out into it's own EventArgs class, pass link as e.Message
[Browsable(true)]
public static event EventHandler<EventArgs> ElementMouseHover
{
add
{
lock (_elementHoverLock)
{
_elementMouseHover += value;
}
}
remove
{
lock (_elementHoverLock)
{
_elementMouseHover -= value;
}
}
}
/// <summary>
/// </summary>
[Browsable(true)]
public static event EventHandler<ChannelChangedEventArgs<IChannel>> ChannelChanged
{
add
{
lock (_channelChangedLock)
{
_channelChanged += value;
}
}
remove
{
lock (_channelChangedLock)
{
_channelChanged -= value;
}
}
}
/// <summary>
/// </summary>
[Browsable(true)]
public event EventHandler<EventArgs> PlaylistHistoryClicked
{
add
{
lock (_historyClickedLock)
{
_historyClicked += value;
}
}
remove
{
lock (_historyClickedLock)
{
_historyClicked -= value;
}
}
}
/// <summary>
/// </summary>
public virtual void LoadUI()
{
if (currentTrack == null)
throw new InvalidOperationException("Channel control must have a valid Track collection");
if (currentTrack != null)
{
if (InvokeRequired)
{
Invoke((Action) SetValues);
}
else
{
SetValues();
}
}
// base.OnLoad(e);
}
private void SetValues()
{
ITrack track = CurrentTrack;
// track title
toolTipLinks.SetToolTip(lnkTrackTitle, track.TrackTitle);
lnkTrackTitle.Text = track.TrackTitle;
// comment count
lnkPostComments.Text = string.Format("Read and Post Comments {0}{1} {2}{3}", "(", track.CommentCount,
"comments", ")");
// forum url
if (track.ForumUrl != null)
{
lnkPostComments.Links[0].LinkData = track.ForumUrl.AbsoluteUri;
toolTipLinks.SetToolTip(lnkPostComments, track.ForumUrl.AbsoluteUri);
}
// artist homepage link
if (track.ArtistUri != null)
{
lnkTrackTitle.Links[0].LinkData = track.ArtistUri.AbsoluteUri;
lnkTrackTitle.LinkBehavior = LinkBehavior.AlwaysUnderline;
lnkTrackTitle.LinkColor = Color.RoyalBlue;
toolTipLinks.SetToolTip(lnkTrackTitle, track.ArtistUri.AbsoluteUri);
}
// record label
if (track.RecordLabel != null)
lblRecordLabel.Text = track.RecordLabel;
// the url to the track (what is this?)
Uri trackUrl;
if (track.TrackUrl != null)
trackUrl = track.TrackUrl;
// time the track started
DateTime startTime = track.StartTime.AddMinutes(Settings.Default.TrackStartTimeOffset);
StartTimeLabel.Text = string.Format("{0} {1}", "Started at", startTime.ToShortTimeString());
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.AspNetCore.Authentication.OAuth;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.TestHost;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging.Abstractions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Xunit;
namespace Microsoft.AspNetCore.Authentication.Google
{
public class GoogleTests : RemoteAuthenticationTests<GoogleOptions>
{
protected override string DefaultScheme => GoogleDefaults.AuthenticationScheme;
protected override Type HandlerType => typeof(GoogleHandler);
protected override bool SupportsSignIn { get => false; }
protected override bool SupportsSignOut { get => false; }
protected override void RegisterAuth(AuthenticationBuilder services, Action<GoogleOptions> configure)
{
services.AddGoogle(o =>
{
ConfigureDefaults(o);
configure.Invoke(o);
});
}
protected override void ConfigureDefaults(GoogleOptions o)
{
o.ClientId = "whatever";
o.ClientSecret = "whatever";
o.SignInScheme = "auth1";
}
[Fact]
public async Task ChallengeWillTriggerRedirection()
{
using var host = await CreateHost(o =>
{
o.ClientId = "Test Id";
o.ClientSecret = "Test Secret";
});
using var server = host.GetTestServer();
var transaction = await server.SendAsync("https://example.com/challenge");
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
var location = transaction.Response.Headers.Location.ToString();
Assert.Contains("https://accounts.google.com/o/oauth2/v2/auth?response_type=code", location);
Assert.Contains("&client_id=", location);
Assert.Contains("&redirect_uri=", location);
Assert.Contains("&scope=", location);
Assert.Contains("&state=", location);
Assert.DoesNotContain("access_type=", location);
Assert.DoesNotContain("prompt=", location);
Assert.DoesNotContain("approval_prompt=", location);
Assert.DoesNotContain("login_hint=", location);
Assert.DoesNotContain("include_granted_scopes=", location);
}
[Fact]
public async Task SignInThrows()
{
using var host = await CreateHost(o =>
{
o.ClientId = "Test Id";
o.ClientSecret = "Test Secret";
});
using var server = host.GetTestServer();
var transaction = await server.SendAsync("https://example.com/signIn");
Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
}
[Fact]
public async Task SignOutThrows()
{
using var host = await CreateHost(o =>
{
o.ClientId = "Test Id";
o.ClientSecret = "Test Secret";
});
using var server = host.GetTestServer();
var transaction = await server.SendAsync("https://example.com/signOut");
Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
}
[Fact]
public async Task ForbidThrows()
{
using var host = await CreateHost(o =>
{
o.ClientId = "Test Id";
o.ClientSecret = "Test Secret";
});
using var server = host.GetTestServer();
var transaction = await server.SendAsync("https://example.com/signOut");
Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
}
[Fact]
public async Task Challenge401WillNotTriggerRedirection()
{
using var host = await CreateHost(o =>
{
o.ClientId = "Test Id";
o.ClientSecret = "Test Secret";
});
using var server = host.GetTestServer();
var transaction = await server.SendAsync("https://example.com/401");
Assert.Equal(HttpStatusCode.Unauthorized, transaction.Response.StatusCode);
}
[Fact]
public async Task ChallengeWillSetCorrelationCookie()
{
using var host = await CreateHost(o =>
{
o.ClientId = "Test Id";
o.ClientSecret = "Test Secret";
});
using var server = host.GetTestServer();
var transaction = await server.SendAsync("https://example.com/challenge");
Assert.Contains(transaction.SetCookie, cookie => cookie.StartsWith(".AspNetCore.Correlation.", StringComparison.Ordinal));
}
[Fact]
public async Task ChallengeWillSetDefaultScope()
{
using var host = await CreateHost(o =>
{
o.ClientId = "Test Id";
o.ClientSecret = "Test Secret";
});
using var server = host.GetTestServer();
var transaction = await server.SendAsync("https://example.com/challenge");
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
var query = transaction.Response.Headers.Location.Query;
Assert.Contains("&scope=" + UrlEncoder.Default.Encode("openid profile email"), query);
}
[Fact]
public async Task ChallengeWillUseAuthenticationPropertiesParametersAsQueryArguments()
{
var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider(NullLoggerFactory.Instance).CreateProtector("GoogleTest"));
using var host = await CreateHost(o =>
{
o.ClientId = "Test Id";
o.ClientSecret = "Test Secret";
o.StateDataFormat = stateFormat;
},
context =>
{
var req = context.Request;
var res = context.Response;
if (req.Path == new PathString("/challenge2"))
{
return context.ChallengeAsync("Google", new GoogleChallengeProperties
{
Scope = new string[] { "openid", "https://www.googleapis.com/auth/plus.login" },
AccessType = "offline",
ApprovalPrompt = "force",
Prompt = "consent",
LoginHint = "[email protected]",
IncludeGrantedScopes = false,
});
}
return Task.FromResult<object>(null);
});
using var server = host.GetTestServer();
var transaction = await server.SendAsync("https://example.com/challenge2");
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
// verify query arguments
var query = QueryHelpers.ParseQuery(transaction.Response.Headers.Location.Query);
Assert.Equal("openid https://www.googleapis.com/auth/plus.login", query["scope"]);
Assert.Equal("offline", query["access_type"]);
Assert.Equal("force", query["approval_prompt"]);
Assert.Equal("consent", query["prompt"]);
Assert.Equal("false", query["include_granted_scopes"]);
Assert.Equal("[email protected]", query["login_hint"]);
// verify that the passed items were not serialized
var stateProperties = stateFormat.Unprotect(query["state"]);
Assert.DoesNotContain("scope", stateProperties.Items.Keys);
Assert.DoesNotContain("access_type", stateProperties.Items.Keys);
Assert.DoesNotContain("include_granted_scopes", stateProperties.Items.Keys);
Assert.DoesNotContain("approval_prompt", stateProperties.Items.Keys);
Assert.DoesNotContain("prompt", stateProperties.Items.Keys);
Assert.DoesNotContain("login_hint", stateProperties.Items.Keys);
}
[Fact]
public async Task ChallengeWillUseAuthenticationPropertiesItemsAsParameters()
{
var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider(NullLoggerFactory.Instance).CreateProtector("GoogleTest"));
using var host = await CreateHost(o =>
{
o.ClientId = "Test Id";
o.ClientSecret = "Test Secret";
o.StateDataFormat = stateFormat;
},
context =>
{
var req = context.Request;
var res = context.Response;
if (req.Path == new PathString("/challenge2"))
{
return context.ChallengeAsync("Google", new AuthenticationProperties(new Dictionary<string, string>()
{
{ "scope", "https://www.googleapis.com/auth/plus.login" },
{ "access_type", "offline" },
{ "approval_prompt", "force" },
{ "prompt", "consent" },
{ "login_hint", "[email protected]" },
{ "include_granted_scopes", "false" }
}));
}
return Task.FromResult<object>(null);
});
using var server = host.GetTestServer();
var transaction = await server.SendAsync("https://example.com/challenge2");
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
// verify query arguments
var query = QueryHelpers.ParseQuery(transaction.Response.Headers.Location.Query);
Assert.Equal("https://www.googleapis.com/auth/plus.login", query["scope"]);
Assert.Equal("offline", query["access_type"]);
Assert.Equal("force", query["approval_prompt"]);
Assert.Equal("consent", query["prompt"]);
Assert.Equal("false", query["include_granted_scopes"]);
Assert.Equal("[email protected]", query["login_hint"]);
// verify that the passed items were not serialized
var stateProperties = stateFormat.Unprotect(query["state"]);
Assert.DoesNotContain("scope", stateProperties.Items.Keys);
Assert.DoesNotContain("access_type", stateProperties.Items.Keys);
Assert.DoesNotContain("include_granted_scopes", stateProperties.Items.Keys);
Assert.DoesNotContain("approval_prompt", stateProperties.Items.Keys);
Assert.DoesNotContain("prompt", stateProperties.Items.Keys);
Assert.DoesNotContain("login_hint", stateProperties.Items.Keys);
}
[Fact]
public async Task ChallengeWillUseAuthenticationPropertiesItemsAsQueryArgumentsButParametersWillOverwrite()
{
var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider(NullLoggerFactory.Instance).CreateProtector("GoogleTest"));
using var host = await CreateHost(o =>
{
o.ClientId = "Test Id";
o.ClientSecret = "Test Secret";
o.StateDataFormat = stateFormat;
},
context =>
{
var req = context.Request;
var res = context.Response;
if (req.Path == new PathString("/challenge2"))
{
return context.ChallengeAsync("Google", new GoogleChallengeProperties(new Dictionary<string, string>
{
["scope"] = "https://www.googleapis.com/auth/plus.login",
["access_type"] = "offline",
["include_granted_scopes"] = "false",
["approval_prompt"] = "force",
["prompt"] = "login",
["login_hint"] = "[email protected]",
})
{
Prompt = "consent",
LoginHint = "[email protected]",
});
}
return Task.FromResult<object>(null);
});
using var server = host.GetTestServer();
var transaction = await server.SendAsync("https://example.com/challenge2");
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
// verify query arguments
var query = QueryHelpers.ParseQuery(transaction.Response.Headers.Location.Query);
Assert.Equal("https://www.googleapis.com/auth/plus.login", query["scope"]);
Assert.Equal("offline", query["access_type"]);
Assert.Equal("force", query["approval_prompt"]);
Assert.Equal("consent", query["prompt"]);
Assert.Equal("false", query["include_granted_scopes"]);
Assert.Equal("[email protected]", query["login_hint"]);
// verify that the passed items were not serialized
var stateProperties = stateFormat.Unprotect(query["state"]);
Assert.DoesNotContain("scope", stateProperties.Items.Keys);
Assert.DoesNotContain("access_type", stateProperties.Items.Keys);
Assert.DoesNotContain("include_granted_scopes", stateProperties.Items.Keys);
Assert.DoesNotContain("approval_prompt", stateProperties.Items.Keys);
Assert.DoesNotContain("prompt", stateProperties.Items.Keys);
Assert.DoesNotContain("login_hint", stateProperties.Items.Keys);
}
[Fact]
public async Task ChallengeWillTriggerApplyRedirectEvent()
{
using var host = await CreateHost(o =>
{
o.ClientId = "Test Id";
o.ClientSecret = "Test Secret";
o.Events = new OAuthEvents
{
OnRedirectToAuthorizationEndpoint = context =>
{
context.Response.Redirect(context.RedirectUri + "&custom=test");
return Task.FromResult(0);
}
};
});
using var server = host.GetTestServer();
var transaction = await server.SendAsync("https://example.com/challenge");
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
var query = transaction.Response.Headers.Location.Query;
Assert.Contains("custom=test", query);
}
[Fact]
public async Task AuthenticateWithoutCookieWillFail()
{
using var host = await CreateHost(o =>
{
o.ClientId = "Test Id";
o.ClientSecret = "Test Secret";
},
async context =>
{
var req = context.Request;
var res = context.Response;
if (req.Path == new PathString("/auth"))
{
var result = await context.AuthenticateAsync("Google");
Assert.NotNull(result.Failure);
}
});
using var server = host.GetTestServer();
var transaction = await server.SendAsync("https://example.com/auth");
Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
}
[Fact]
public async Task ReplyPathWithoutStateQueryStringWillBeRejected()
{
using var host = await CreateHost(o =>
{
o.ClientId = "Test Id";
o.ClientSecret = "Test Secret";
});
using var server = host.GetTestServer();
var error = await Assert.ThrowsAnyAsync<Exception>(() => server.SendAsync("https://example.com/signin-google?code=TestCode"));
Assert.Equal("The oauth state was missing or invalid.", error.GetBaseException().Message);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task ReplyPathWithAccessDeniedErrorFails(bool redirect)
{
using var host = await CreateHost(o =>
{
o.ClientId = "Test Id";
o.ClientSecret = "Test Secret";
o.StateDataFormat = new TestStateDataFormat();
o.Events = redirect ? new OAuthEvents()
{
OnAccessDenied = ctx =>
{
ctx.Response.Redirect("/error?FailureMessage=AccessDenied");
ctx.HandleResponse();
return Task.FromResult(0);
}
} : new OAuthEvents();
});
using var server = host.GetTestServer();
var sendTask = server.SendAsync("https://example.com/signin-google?error=access_denied&error_description=SoBad&error_uri=foobar&state=protected_state",
".AspNetCore.Correlation.correlationId=N");
if (redirect)
{
var transaction = await sendTask;
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
Assert.Equal("/error?FailureMessage=AccessDenied", transaction.Response.Headers.GetValues("Location").First());
}
else
{
var error = await Assert.ThrowsAnyAsync<Exception>(() => sendTask);
Assert.Equal("Access was denied by the resource owner or by the remote server.", error.GetBaseException().Message);
}
}
[Fact]
public async Task ReplyPathWithAccessDeniedError_AllowsCustomizingPath()
{
using var host = await CreateHost(o =>
{
o.ClientId = "Test Id";
o.ClientSecret = "Test Secret";
o.StateDataFormat = new TestStateDataFormat();
o.AccessDeniedPath = "/access-denied";
o.Events = new OAuthEvents()
{
OnAccessDenied = ctx =>
{
Assert.Equal("/access-denied", ctx.AccessDeniedPath.Value);
Assert.Equal("http://testhost/redirect", ctx.ReturnUrl);
Assert.Equal("ReturnUrl", ctx.ReturnUrlParameter);
ctx.AccessDeniedPath = "/custom-denied-page";
ctx.ReturnUrl = "http://www.google.com/";
ctx.ReturnUrlParameter = "rurl";
return Task.FromResult(0);
}
};
});
using var server = host.GetTestServer();
var transaction = await server.SendAsync("https://example.com/signin-google?error=access_denied&error_description=SoBad&error_uri=foobar&state=protected_state",
".AspNetCore.Correlation.correlationId=N");
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
Assert.Equal("https://example.com/custom-denied-page?rurl=http%3A%2F%2Fwww.google.com%2F", transaction.Response.Headers.GetValues("Location").First());
}
[Fact]
public async Task ReplyPathWithAccessDeniedErrorAndNoAccessDeniedPath_FallsBackToRemoteError()
{
var accessDeniedCalled = false;
var remoteFailureCalled = false;
using var host = await CreateHost(o =>
{
o.ClientId = "Test Id";
o.ClientSecret = "Test Secret";
o.StateDataFormat = new TestStateDataFormat();
o.Events = new OAuthEvents()
{
OnAccessDenied = ctx =>
{
Assert.Null(ctx.AccessDeniedPath.Value);
Assert.Equal("http://testhost/redirect", ctx.ReturnUrl);
Assert.Equal("ReturnUrl", ctx.ReturnUrlParameter);
accessDeniedCalled = true;
return Task.FromResult(0);
},
OnRemoteFailure = ctx =>
{
var ex = ctx.Failure;
Assert.True(ex.Data.Contains("error"), "error");
Assert.True(ex.Data.Contains("error_description"), "error_description");
Assert.True(ex.Data.Contains("error_uri"), "error_uri");
Assert.Equal("access_denied", ex.Data["error"]);
Assert.Equal("whyitfailed", ex.Data["error_description"]);
Assert.Equal("https://example.com/fail", ex.Data["error_uri"]);
remoteFailureCalled = true;
ctx.Response.Redirect("/error?FailureMessage=" + UrlEncoder.Default.Encode(ctx.Failure.Message));
ctx.HandleResponse();
return Task.FromResult(0);
}
};
});
using var server = host.GetTestServer();
var transaction = await server.SendAsync("https://example.com/signin-google?error=access_denied&error_description=whyitfailed&error_uri=https://example.com/fail&state=protected_state",
".AspNetCore.Correlation.correlationId=N");
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
Assert.StartsWith("/error?FailureMessage=", transaction.Response.Headers.GetValues("Location").First());
Assert.True(accessDeniedCalled);
Assert.True(remoteFailureCalled);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task ReplyPathWithErrorFails(bool redirect)
{
using var host = await CreateHost(o =>
{
o.ClientId = "Test Id";
o.ClientSecret = "Test Secret";
o.StateDataFormat = new TestStateDataFormat();
o.Events = redirect ? new OAuthEvents()
{
OnRemoteFailure = ctx =>
{
var ex = ctx.Failure;
Assert.True(ex.Data.Contains("error"), "error");
Assert.True(ex.Data.Contains("error_description"), "error_description");
Assert.True(ex.Data.Contains("error_uri"), "error_uri");
Assert.Equal("itfailed", ex.Data["error"]);
Assert.Equal("whyitfailed", ex.Data["error_description"]);
Assert.Equal("https://example.com/fail", ex.Data["error_uri"]);
ctx.Response.Redirect("/error?FailureMessage=" + UrlEncoder.Default.Encode(ctx.Failure.Message));
ctx.HandleResponse();
return Task.FromResult(0);
}
} : new OAuthEvents();
});
using var server = host.GetTestServer();
var sendTask = server.SendAsync("https://example.com/signin-google?error=itfailed&error_description=whyitfailed&error_uri=https://example.com/fail&state=protected_state",
".AspNetCore.Correlation.correlationId=N");
if (redirect)
{
var transaction = await sendTask;
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
Assert.Equal("/error?FailureMessage=itfailed" + UrlEncoder.Default.Encode(";Description=whyitfailed;Uri=https://example.com/fail"), transaction.Response.Headers.GetValues("Location").First());
}
else
{
var error = await Assert.ThrowsAnyAsync<Exception>(() => sendTask);
Assert.Equal("itfailed;Description=whyitfailed;Uri=https://example.com/fail", error.GetBaseException().Message);
}
}
[Theory]
[InlineData(null)]
[InlineData("CustomIssuer")]
public async Task ReplyPathWillAuthenticateValidAuthorizeCodeAndState(string claimsIssuer)
{
var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider(NullLoggerFactory.Instance).CreateProtector("GoogleTest"));
using var host = await CreateHost(o =>
{
o.ClientId = "Test Id";
o.ClientSecret = "Test Secret";
o.SaveTokens = true;
o.StateDataFormat = stateFormat;
if (claimsIssuer != null)
{
o.ClaimsIssuer = claimsIssuer;
}
o.BackchannelHttpHandler = CreateBackchannel();
});
var properties = new AuthenticationProperties();
var correlationKey = ".xsrf";
var correlationValue = "TestCorrelationId";
properties.Items.Add(correlationKey, correlationValue);
properties.RedirectUri = "/me";
var state = stateFormat.Protect(properties);
using var server = host.GetTestServer();
var transaction = await server.SendAsync(
"https://example.com/signin-google?code=TestCode&state=" + UrlEncoder.Default.Encode(state),
$".AspNetCore.Correlation.{correlationValue}=N");
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
Assert.Equal("/me", transaction.Response.Headers.GetValues("Location").First());
Assert.Equal(2, transaction.SetCookie.Count);
Assert.Contains($".AspNetCore.Correlation.{correlationValue}", transaction.SetCookie[0]);
Assert.Contains(".AspNetCore." + TestExtensions.CookieAuthenticationScheme, transaction.SetCookie[1]);
var authCookie = transaction.AuthenticationCookieValue;
transaction = await server.SendAsync("https://example.com/me", authCookie);
Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
var expectedIssuer = claimsIssuer ?? GoogleDefaults.AuthenticationScheme;
Assert.Equal("Test Name", transaction.FindClaimValue(ClaimTypes.Name, expectedIssuer));
Assert.Equal("Test User ID", transaction.FindClaimValue(ClaimTypes.NameIdentifier, expectedIssuer));
Assert.Equal("Test Given Name", transaction.FindClaimValue(ClaimTypes.GivenName, expectedIssuer));
Assert.Equal("Test Family Name", transaction.FindClaimValue(ClaimTypes.Surname, expectedIssuer));
Assert.Equal("Test email", transaction.FindClaimValue(ClaimTypes.Email, expectedIssuer));
// Ensure claims transformation
Assert.Equal("yup", transaction.FindClaimValue("xform"));
transaction = await server.SendAsync("https://example.com/tokens", authCookie);
Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
Assert.Equal("Test Access Token", transaction.FindTokenValue("access_token"));
Assert.Equal("Bearer", transaction.FindTokenValue("token_type"));
Assert.NotNull(transaction.FindTokenValue("expires_at"));
}
// REVIEW: Fix this once we revisit error handling to not blow up
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task ReplyPathWillThrowIfCodeIsInvalid(bool redirect)
{
var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider(NullLoggerFactory.Instance).CreateProtector("GoogleTest"));
using var host = await CreateHost(o =>
{
o.ClientId = "Test Id";
o.ClientSecret = "Test Secret";
o.StateDataFormat = stateFormat;
o.BackchannelHttpHandler = new TestHttpMessageHandler
{
Sender = req =>
{
return ReturnJsonResponse(new { Error = "Error" },
HttpStatusCode.BadRequest);
}
};
o.Events = redirect ? new OAuthEvents()
{
OnRemoteFailure = ctx =>
{
ctx.Response.Redirect("/error?FailureMessage=" + UrlEncoder.Default.Encode(ctx.Failure.Message));
ctx.HandleResponse();
return Task.FromResult(0);
}
} : new OAuthEvents();
});
var properties = new AuthenticationProperties();
var correlationKey = ".xsrf";
var correlationValue = "TestCorrelationId";
properties.Items.Add(correlationKey, correlationValue);
properties.RedirectUri = "/me";
var state = stateFormat.Protect(properties);
using var server = host.GetTestServer();
var sendTask = server.SendAsync(
"https://example.com/signin-google?code=TestCode&state=" + UrlEncoder.Default.Encode(state),
$".AspNetCore.Correlation.{correlationValue}=N");
if (redirect)
{
var transaction = await sendTask;
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
Assert.Equal("/error?FailureMessage=" + UrlEncoder.Default.Encode("OAuth token endpoint failure: Status: BadRequest;Headers: ;Body: {\"Error\":\"Error\"};"),
transaction.Response.Headers.GetValues("Location").First());
}
else
{
var error = await Assert.ThrowsAnyAsync<Exception>(() => sendTask);
Assert.Equal("OAuth token endpoint failure: Status: BadRequest;Headers: ;Body: {\"Error\":\"Error\"};", error.GetBaseException().Message);
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task ReplyPathWillRejectIfAccessTokenIsMissing(bool redirect)
{
var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider(NullLoggerFactory.Instance).CreateProtector("GoogleTest"));
using var host = await CreateHost(o =>
{
o.ClientId = "Test Id";
o.ClientSecret = "Test Secret";
o.StateDataFormat = stateFormat;
o.BackchannelHttpHandler = new TestHttpMessageHandler
{
Sender = req =>
{
return ReturnJsonResponse(new object());
}
};
o.Events = redirect ? new OAuthEvents()
{
OnRemoteFailure = ctx =>
{
ctx.Response.Redirect("/error?FailureMessage=" + UrlEncoder.Default.Encode(ctx.Failure.Message));
ctx.HandleResponse();
return Task.FromResult(0);
}
} : new OAuthEvents();
});
var properties = new AuthenticationProperties();
var correlationKey = ".xsrf";
var correlationValue = "TestCorrelationId";
properties.Items.Add(correlationKey, correlationValue);
properties.RedirectUri = "/me";
var state = stateFormat.Protect(properties);
using var server = host.GetTestServer();
var sendTask = server.SendAsync(
"https://example.com/signin-google?code=TestCode&state=" + UrlEncoder.Default.Encode(state),
$".AspNetCore.Correlation.{correlationValue}=N");
if (redirect)
{
var transaction = await sendTask;
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
Assert.Equal("/error?FailureMessage=" + UrlEncoder.Default.Encode("Failed to retrieve access token."),
transaction.Response.Headers.GetValues("Location").First());
}
else
{
var error = await Assert.ThrowsAnyAsync<Exception>(() => sendTask);
Assert.Equal("Failed to retrieve access token.", error.GetBaseException().Message);
}
}
[Fact]
public async Task AuthenticatedEventCanGetRefreshToken()
{
var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider(NullLoggerFactory.Instance).CreateProtector("GoogleTest"));
using var host = await CreateHost(o =>
{
o.ClientId = "Test Id";
o.ClientSecret = "Test Secret";
o.StateDataFormat = stateFormat;
o.BackchannelHttpHandler = CreateBackchannel();
o.Events = new OAuthEvents
{
OnCreatingTicket = context =>
{
var refreshToken = context.RefreshToken;
context.Principal.AddIdentity(new ClaimsIdentity(new Claim[] { new Claim("RefreshToken", refreshToken, ClaimValueTypes.String, "Google") }, "Google"));
return Task.FromResult(0);
}
};
});
var properties = new AuthenticationProperties();
var correlationKey = ".xsrf";
var correlationValue = "TestCorrelationId";
properties.Items.Add(correlationKey, correlationValue);
properties.RedirectUri = "/me";
var state = stateFormat.Protect(properties);
using var server = host.GetTestServer();
var transaction = await server.SendAsync(
"https://example.com/signin-google?code=TestCode&state=" + UrlEncoder.Default.Encode(state),
$".AspNetCore.Correlation.{correlationValue}=N");
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
Assert.Equal("/me", transaction.Response.Headers.GetValues("Location").First());
Assert.Equal(2, transaction.SetCookie.Count);
Assert.Contains($".AspNetCore.Correlation.{correlationValue}", transaction.SetCookie[0]);
Assert.Contains(".AspNetCore." + TestExtensions.CookieAuthenticationScheme, transaction.SetCookie[1]);
var authCookie = transaction.AuthenticationCookieValue;
transaction = await server.SendAsync("https://example.com/me", authCookie);
Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
Assert.Equal("Test Refresh Token", transaction.FindClaimValue("RefreshToken"));
}
[Fact]
public async Task NullRedirectUriWillRedirectToSlash()
{
var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider(NullLoggerFactory.Instance).CreateProtector("GoogleTest"));
using var host = await CreateHost(o =>
{
o.ClientId = "Test Id";
o.ClientSecret = "Test Secret";
o.StateDataFormat = stateFormat;
o.BackchannelHttpHandler = CreateBackchannel();
o.Events = new OAuthEvents
{
OnTicketReceived = context =>
{
context.Properties.RedirectUri = null;
return Task.FromResult(0);
}
};
});
var properties = new AuthenticationProperties();
var correlationKey = ".xsrf";
var correlationValue = "TestCorrelationId";
properties.Items.Add(correlationKey, correlationValue);
var state = stateFormat.Protect(properties);
using var server = host.GetTestServer();
var transaction = await server.SendAsync(
"https://example.com/signin-google?code=TestCode&state=" + UrlEncoder.Default.Encode(state),
$".AspNetCore.Correlation.{correlationValue}=N");
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
Assert.Equal("/", transaction.Response.Headers.GetValues("Location").First());
Assert.Equal(2, transaction.SetCookie.Count);
Assert.Contains($".AspNetCore.Correlation.{correlationValue}", transaction.SetCookie[0]);
Assert.Contains(".AspNetCore." + TestExtensions.CookieAuthenticationScheme, transaction.SetCookie[1]);
}
[Fact]
public async Task ValidateAuthenticatedContext()
{
var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider(NullLoggerFactory.Instance).CreateProtector("GoogleTest"));
using var host = await CreateHost(o =>
{
o.ClientId = "Test Id";
o.ClientSecret = "Test Secret";
o.StateDataFormat = stateFormat;
o.AccessType = "offline";
o.Events = new OAuthEvents()
{
OnCreatingTicket = context =>
{
Assert.Equal("Test Access Token", context.AccessToken);
Assert.Equal("Test Refresh Token", context.RefreshToken);
Assert.Equal(TimeSpan.FromSeconds(3600), context.ExpiresIn);
Assert.Equal("Test email", context.Identity.FindFirst(ClaimTypes.Email)?.Value);
Assert.Equal("Test User ID", context.Identity.FindFirst(ClaimTypes.NameIdentifier)?.Value);
Assert.Equal("Test Name", context.Identity.FindFirst(ClaimTypes.Name)?.Value);
Assert.Equal("Test Family Name", context.Identity.FindFirst(ClaimTypes.Surname)?.Value);
Assert.Equal("Test Given Name", context.Identity.FindFirst(ClaimTypes.GivenName)?.Value);
return Task.FromResult(0);
}
};
o.BackchannelHttpHandler = CreateBackchannel();
});
var properties = new AuthenticationProperties();
var correlationKey = ".xsrf";
var correlationValue = "TestCorrelationId";
properties.Items.Add(correlationKey, correlationValue);
properties.RedirectUri = "/foo";
var state = stateFormat.Protect(properties);
//Post a message to the Google middleware
using var server = host.GetTestServer();
var transaction = await server.SendAsync(
"https://example.com/signin-google?code=TestCode&state=" + UrlEncoder.Default.Encode(state),
$".AspNetCore.Correlation.{correlationValue}=N");
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
Assert.Equal("/foo", transaction.Response.Headers.GetValues("Location").First());
}
[Fact]
public async Task NoStateCausesException()
{
using var host = await CreateHost(o =>
{
o.ClientId = "Test Id";
o.ClientSecret = "Test Secret";
});
//Post a message to the Google middleware
using var server = host.GetTestServer();
var error = await Assert.ThrowsAnyAsync<Exception>(() => server.SendAsync("https://example.com/signin-google?code=TestCode"));
Assert.Equal("The oauth state was missing or invalid.", error.GetBaseException().Message);
}
[Fact]
public async Task CanRedirectOnError()
{
var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider(NullLoggerFactory.Instance).CreateProtector("GoogleTest"));
using var host = await CreateHost(o =>
{
o.ClientId = "Test Id";
o.ClientSecret = "Test Secret";
o.Events = new OAuthEvents()
{
OnRemoteFailure = ctx =>
{
ctx.Response.Redirect("/error?FailureMessage=" + UrlEncoder.Default.Encode(ctx.Failure.Message));
ctx.HandleResponse();
return Task.FromResult(0);
}
};
});
//Post a message to the Google middleware
using var server = host.GetTestServer();
var transaction = await server.SendAsync(
"https://example.com/signin-google?code=TestCode");
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
Assert.Equal("/error?FailureMessage=" + UrlEncoder.Default.Encode("The oauth state was missing or invalid."),
transaction.Response.Headers.GetValues("Location").First());
}
[Fact]
public async Task AuthenticateAutomaticWhenAlreadySignedInSucceeds()
{
var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider(NullLoggerFactory.Instance).CreateProtector("GoogleTest"));
using var host = await CreateHost(o =>
{
o.ClientId = "Test Id";
o.ClientSecret = "Test Secret";
o.StateDataFormat = stateFormat;
o.SaveTokens = true;
o.BackchannelHttpHandler = CreateBackchannel();
});
// Skip the challenge step, go directly to the callback path
var properties = new AuthenticationProperties();
var correlationKey = ".xsrf";
var correlationValue = "TestCorrelationId";
properties.Items.Add(correlationKey, correlationValue);
properties.RedirectUri = "/me";
var state = stateFormat.Protect(properties);
using var server = host.GetTestServer();
var transaction = await server.SendAsync(
"https://example.com/signin-google?code=TestCode&state=" + UrlEncoder.Default.Encode(state),
$".AspNetCore.Correlation.{correlationValue}=N");
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
Assert.Equal("/me", transaction.Response.Headers.GetValues("Location").First());
Assert.Equal(2, transaction.SetCookie.Count);
Assert.Contains($".AspNetCore.Correlation.{correlationValue}", transaction.SetCookie[0]); // Delete
Assert.Contains(".AspNetCore." + TestExtensions.CookieAuthenticationScheme, transaction.SetCookie[1]);
var authCookie = transaction.AuthenticationCookieValue;
transaction = await server.SendAsync("https://example.com/authenticate", authCookie);
Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
Assert.Equal("Test Name", transaction.FindClaimValue(ClaimTypes.Name));
Assert.Equal("Test User ID", transaction.FindClaimValue(ClaimTypes.NameIdentifier));
Assert.Equal("Test Given Name", transaction.FindClaimValue(ClaimTypes.GivenName));
Assert.Equal("Test Family Name", transaction.FindClaimValue(ClaimTypes.Surname));
Assert.Equal("Test email", transaction.FindClaimValue(ClaimTypes.Email));
// Ensure claims transformation
Assert.Equal("yup", transaction.FindClaimValue("xform"));
}
[Fact]
public async Task AuthenticateGoogleWhenAlreadySignedInSucceeds()
{
var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider(NullLoggerFactory.Instance).CreateProtector("GoogleTest"));
using var host = await CreateHost(o =>
{
o.ClientId = "Test Id";
o.ClientSecret = "Test Secret";
o.StateDataFormat = stateFormat;
o.SaveTokens = true;
o.BackchannelHttpHandler = CreateBackchannel();
});
// Skip the challenge step, go directly to the callback path
var properties = new AuthenticationProperties();
var correlationKey = ".xsrf";
var correlationValue = "TestCorrelationId";
properties.Items.Add(correlationKey, correlationValue);
properties.RedirectUri = "/me";
var state = stateFormat.Protect(properties);
using var server = host.GetTestServer();
var transaction = await server.SendAsync(
"https://example.com/signin-google?code=TestCode&state=" + UrlEncoder.Default.Encode(state),
$".AspNetCore.Correlation.{correlationValue}=N");
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
Assert.Equal("/me", transaction.Response.Headers.GetValues("Location").First());
Assert.Equal(2, transaction.SetCookie.Count);
Assert.Contains($".AspNetCore.Correlation.{correlationValue}", transaction.SetCookie[0]); // Delete
Assert.Contains(".AspNetCore." + TestExtensions.CookieAuthenticationScheme, transaction.SetCookie[1]);
var authCookie = transaction.AuthenticationCookieValue;
transaction = await server.SendAsync("https://example.com/authenticateGoogle", authCookie);
Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
Assert.Equal("Test Name", transaction.FindClaimValue(ClaimTypes.Name));
Assert.Equal("Test User ID", transaction.FindClaimValue(ClaimTypes.NameIdentifier));
Assert.Equal("Test Given Name", transaction.FindClaimValue(ClaimTypes.GivenName));
Assert.Equal("Test Family Name", transaction.FindClaimValue(ClaimTypes.Surname));
Assert.Equal("Test email", transaction.FindClaimValue(ClaimTypes.Email));
// Ensure claims transformation
Assert.Equal("yup", transaction.FindClaimValue("xform"));
}
[Fact]
public async Task AuthenticateGoogleWhenAlreadySignedWithGoogleReturnsNull()
{
var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider(NullLoggerFactory.Instance).CreateProtector("GoogleTest"));
using var host = await CreateHost(o =>
{
o.ClientId = "Test Id";
o.ClientSecret = "Test Secret";
o.StateDataFormat = stateFormat;
o.SaveTokens = true;
o.BackchannelHttpHandler = CreateBackchannel();
});
// Skip the challenge step, go directly to the callback path
var properties = new AuthenticationProperties();
var correlationKey = ".xsrf";
var correlationValue = "TestCorrelationId";
properties.Items.Add(correlationKey, correlationValue);
properties.RedirectUri = "/me";
var state = stateFormat.Protect(properties);
using var server = host.GetTestServer();
var transaction = await server.SendAsync(
"https://example.com/signin-google?code=TestCode&state=" + UrlEncoder.Default.Encode(state),
$".AspNetCore.Correlation.{correlationValue}=N");
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
Assert.Equal("/me", transaction.Response.Headers.GetValues("Location").First());
Assert.Equal(2, transaction.SetCookie.Count);
Assert.Contains($".AspNetCore.Correlation.{correlationValue}", transaction.SetCookie[0]); // Delete
Assert.Contains(".AspNetCore." + TestExtensions.CookieAuthenticationScheme, transaction.SetCookie[1]);
var authCookie = transaction.AuthenticationCookieValue;
transaction = await server.SendAsync("https://example.com/authenticateFacebook", authCookie);
Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
Assert.Null(transaction.FindClaimValue(ClaimTypes.Name));
}
[Fact]
public async Task ChallengeGoogleWhenAlreadySignedWithGoogleSucceeds()
{
var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider(NullLoggerFactory.Instance).CreateProtector("GoogleTest"));
using var host = await CreateHost(o =>
{
o.ClientId = "Test Id";
o.ClientSecret = "Test Secret";
o.StateDataFormat = stateFormat;
o.SaveTokens = true;
o.BackchannelHttpHandler = CreateBackchannel();
});
// Skip the challenge step, go directly to the callback path
var properties = new AuthenticationProperties();
var correlationKey = ".xsrf";
var correlationValue = "TestCorrelationId";
properties.Items.Add(correlationKey, correlationValue);
properties.RedirectUri = "/me";
var state = stateFormat.Protect(properties);
using var server = host.GetTestServer();
var transaction = await server.SendAsync(
"https://example.com/signin-google?code=TestCode&state=" + UrlEncoder.Default.Encode(state),
$".AspNetCore.Correlation.{correlationValue}=N");
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
Assert.Equal("/me", transaction.Response.Headers.GetValues("Location").First());
Assert.Equal(2, transaction.SetCookie.Count);
Assert.Contains($".AspNetCore.Correlation.{correlationValue}", transaction.SetCookie[0]); // Delete
Assert.Contains(".AspNetCore." + TestExtensions.CookieAuthenticationScheme, transaction.SetCookie[1]);
var authCookie = transaction.AuthenticationCookieValue;
transaction = await server.SendAsync("https://example.com/challengeFacebook", authCookie);
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
Assert.StartsWith("https://www.facebook.com/", transaction.Response.Headers.Location.OriginalString);
}
private HttpMessageHandler CreateBackchannel()
{
return new TestHttpMessageHandler()
{
Sender = req =>
{
if (req.RequestUri.AbsoluteUri == "https://oauth2.googleapis.com/token")
{
return ReturnJsonResponse(new
{
access_token = "Test Access Token",
expires_in = 3600,
token_type = "Bearer",
refresh_token = "Test Refresh Token"
});
}
else if (req.RequestUri.GetComponents(UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.UriEscaped) == "https://www.googleapis.com/oauth2/v2/userinfo")
{
return ReturnJsonResponse(new
{
id = "Test User ID",
name = "Test Name",
given_name = "Test Given Name",
family_name = "Test Family Name",
link = "Profile link",
email = "Test email",
});
}
throw new NotImplementedException(req.RequestUri.AbsoluteUri);
}
};
}
private static HttpResponseMessage ReturnJsonResponse(object content, HttpStatusCode code = HttpStatusCode.OK)
{
var res = new HttpResponseMessage(code);
var text = Newtonsoft.Json.JsonConvert.SerializeObject(content);
res.Content = new StringContent(text, Encoding.UTF8, "application/json");
return res;
}
private class ClaimsTransformer : IClaimsTransformation
{
public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal p)
{
if (!p.Identities.Any(i => i.AuthenticationType == "xform"))
{
var id = new ClaimsIdentity("xform");
id.AddClaim(new Claim("xform", "yup"));
p.AddIdentity(id);
}
return Task.FromResult(p);
}
}
private static async Task<IHost> CreateHost(Action<GoogleOptions> configureOptions, Func<HttpContext, Task> testpath = null)
{
var host = new HostBuilder()
.ConfigureWebHost(builder =>
builder.UseTestServer()
.Configure(app =>
{
app.UseAuthentication();
app.Use(async (context, next) =>
{
var req = context.Request;
var res = context.Response;
if (req.Path == new PathString("/challenge"))
{
await context.ChallengeAsync();
}
else if (req.Path == new PathString("/challengeFacebook"))
{
await context.ChallengeAsync("Facebook");
}
else if (req.Path == new PathString("/tokens"))
{
var result = await context.AuthenticateAsync(TestExtensions.CookieAuthenticationScheme);
var tokens = result.Properties.GetTokens();
await res.DescribeAsync(tokens);
}
else if (req.Path == new PathString("/me"))
{
await res.DescribeAsync(context.User);
}
else if (req.Path == new PathString("/authenticate"))
{
var result = await context.AuthenticateAsync(TestExtensions.CookieAuthenticationScheme);
await res.DescribeAsync(result.Principal);
}
else if (req.Path == new PathString("/authenticateGoogle"))
{
var result = await context.AuthenticateAsync("Google");
await res.DescribeAsync(result?.Principal);
}
else if (req.Path == new PathString("/authenticateFacebook"))
{
var result = await context.AuthenticateAsync("Facebook");
await res.DescribeAsync(result?.Principal);
}
else if (req.Path == new PathString("/unauthorized"))
{
// Simulate Authorization failure
var result = await context.AuthenticateAsync("Google");
await context.ChallengeAsync("Google");
}
else if (req.Path == new PathString("/unauthorizedAuto"))
{
var result = await context.AuthenticateAsync("Google");
await context.ChallengeAsync("Google");
}
else if (req.Path == new PathString("/401"))
{
res.StatusCode = 401;
}
else if (req.Path == new PathString("/signIn"))
{
await Assert.ThrowsAsync<InvalidOperationException>(() => context.SignInAsync("Google", new ClaimsPrincipal()));
}
else if (req.Path == new PathString("/signOut"))
{
await Assert.ThrowsAsync<InvalidOperationException>(() => context.SignOutAsync("Google"));
}
else if (req.Path == new PathString("/forbid"))
{
await Assert.ThrowsAsync<InvalidOperationException>(() => context.ForbidAsync("Google"));
}
else if (testpath != null)
{
await testpath(context);
}
else
{
await next(context);
}
});
})
.ConfigureServices(services =>
{
services.AddTransient<IClaimsTransformation, ClaimsTransformer>();
services.AddAuthentication(TestExtensions.CookieAuthenticationScheme)
.AddCookie(TestExtensions.CookieAuthenticationScheme, o => o.ForwardChallenge = GoogleDefaults.AuthenticationScheme)
.AddGoogle(configureOptions)
.AddFacebook(o =>
{
o.ClientId = "Test ClientId";
o.ClientSecret = "Test AppSecrent";
});
}))
.Build();
await host.StartAsync();
return host;
}
private class TestStateDataFormat : ISecureDataFormat<AuthenticationProperties>
{
private AuthenticationProperties Data { get; set; }
public string Protect(AuthenticationProperties data)
{
return "protected_state";
}
public string Protect(AuthenticationProperties data, string purpose)
{
throw new NotImplementedException();
}
public AuthenticationProperties Unprotect(string protectedText)
{
Assert.Equal("protected_state", protectedText);
var properties = new AuthenticationProperties(new Dictionary<string, string>()
{
{ ".xsrf", "correlationId" },
{ "testkey", "testvalue" }
});
properties.RedirectUri = "http://testhost/redirect";
return properties;
}
public AuthenticationProperties Unprotect(string protectedText, string purpose)
{
throw new NotImplementedException();
}
}
}
}
| |
using Signum.Engine.Basics;
using Signum.Engine.Translation;
using Signum.Entities;
using Signum.Entities.DynamicQuery;
using Signum.Entities.Mailing;
using Signum.Entities.Reflection;
using Signum.Entities.UserAssets;
using Signum.Utilities;
using Signum.Utilities.DataStructures;
using Signum.Utilities.ExpressionTrees;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
namespace Signum.Engine.Templating
{
public interface ITemplateParser
{
Type? ModelType { get; }
QueryDescription QueryDescription { get; }
ScopedDictionary<string, ValueProviderBase> Variables { get; }
void AddError(bool fatal, string error);
}
public abstract class ValueProviderBase
{
public string? Variable { get; set; }
public bool IsForeach { get; set; }
public abstract object? GetValue(TemplateParameters p);
public abstract string? Format { get; }
public abstract Type? Type { get; }
public abstract override bool Equals(object? obj);
public abstract override int GetHashCode();
public abstract void FillQueryTokens(List<QueryToken> list);
public abstract void ToStringInternal(StringBuilder sb, ScopedDictionary<string, ValueProviderBase> variables);
public string ToString(ScopedDictionary<string, ValueProviderBase> variables, string? format)
{
StringBuilder sb = new StringBuilder();
ToStringBrackets(sb, variables, format);
return sb.ToString();
}
public void ToStringBrackets(StringBuilder sb, ScopedDictionary<string, ValueProviderBase> variables, string? format)
{
sb.Append("[");
this.ToStringInternal(sb, variables);
if (format.HasItems())
sb.Append(format);
sb.Append("]");
if (Variable.HasItems())
sb.Append(" as " + Variable);
}
public override string ToString() => ToString(new ScopedDictionary<string, ValueProviderBase>(null), null);
public abstract void Synchronize(SynchronizationContext sc, string remainingText);
public virtual void Declare(ScopedDictionary<string, ValueProviderBase> variables)
{
if (Variable.HasText())
{
if (variables.TryGetValue(Variable, out var value))
{
if (value != null && value.Equals(this))
return;
else throw new InvalidOperationException("Redeclaring variable " + Variable + " with another value");
}
variables.Add(Variable, this);
}
}
public virtual void Foreach(TemplateParameters p, Action forEachElement)
{
var collection = (IEnumerable)this.GetValue(p)!;
foreach (var item in collection)
{
using (p.Scope())
{
if (this.Variable != null)
p.RuntimeVariables.Add(this.Variable, item!);
forEachElement();
}
}
}
public static ValueProviderBase? TryParse(string typeToken, string variable, ITemplateParser tp)
{
var type = typeToken.TryBefore(":") ?? "";
var token = typeToken.TryAfter(":") ?? typeToken;
switch (type)
{
case "":
{
if(token.StartsWith("$"))
{
string v = token.TryBefore('.') ?? token;
if (!tp.Variables.TryGetValue(v, out ValueProviderBase? vp))
{
tp.AddError(false, "Variable '{0}' is not defined at this scope".FormatWith(v));
return null;
}
if (!(vp is TokenValueProvider))
return new ContinueValueProvider(token.TryAfter('.'), vp, tp.AddError);
}
ParsedToken result = ParsedToken.TryParseToken(token, SubTokensOptions.CanElement, tp.QueryDescription, tp.Variables, tp.AddError);
if (result.QueryToken != null && TranslateInstanceValueProvider.IsTranslateInstanceCanditate(result.QueryToken))
return new TranslateInstanceValueProvider(result, false, tp.AddError) { Variable = variable };
else
return new TokenValueProvider(result, false) { Variable = variable };
}
case "q":
{
ParsedToken result = ParsedToken.TryParseToken(token, SubTokensOptions.CanElement, tp.QueryDescription, tp.Variables, tp.AddError);
return new TokenValueProvider(result, true) { Variable = variable };
}
case "t":
{
ParsedToken result = ParsedToken.TryParseToken(token, SubTokensOptions.CanElement, tp.QueryDescription, tp.Variables, tp.AddError);
return new TranslateInstanceValueProvider(result, true, tp.AddError) { Variable = variable };
}
case "m":
return new ModelValueProvider(token, tp.ModelType, tp.AddError) { Variable = variable };
case "g":
return new GlobalValueProvider(token, tp.AddError) { Variable = variable };
case "d":
return new DateValueProvider(token, tp.AddError) { Variable = variable };
default:
tp.AddError(false, "{0} is not a recognized value provider (q:Query, t:Translate, m:Model, g:Global or just blank)");
return null;
}
}
public void ValidateConditionValue(string valueString, FilterOperation? Operation, Action<bool, string> addError)
{
if (Type == null)
return;
var result = FilterValueConverter.TryParse(valueString, Type, Operation!.Value.IsList());
if (result is Result<object>.Error e)
addError(false, "Impossible to convert '{0}' to {1}: {2}".FormatWith(valueString, Type.TypeName(), e.ErrorText));
}
}
public abstract class TemplateParameters
{
public TemplateParameters(IEntity? entity, CultureInfo culture, Dictionary<QueryToken, ResultColumn> columns, IEnumerable<ResultRow> rows)
{
this.Entity = entity;
this.Culture = culture;
this.Columns = columns;
this.Rows = rows;
}
public readonly IEntity? Entity;
public readonly CultureInfo Culture;
public readonly Dictionary<QueryToken, ResultColumn> Columns;
public IEnumerable<ResultRow> Rows { get; private set; }
public ScopedDictionary<string, object> RuntimeVariables = new ScopedDictionary<string, object>(null);
public abstract object GetModel();
public IDisposable OverrideRows(IEnumerable<ResultRow> rows)
{
var old = this.Rows;
this.Rows = rows;
return new Disposable(() => this.Rows = old);
}
internal IDisposable Scope()
{
var old = RuntimeVariables;
RuntimeVariables = new ScopedDictionary<string, object>(RuntimeVariables);
return new Disposable(() => RuntimeVariables = old);
}
}
public class TokenValueProvider : ValueProviderBase
{
public readonly ParsedToken ParsedToken;
public readonly bool IsExplicit;
public override int GetHashCode() => ParsedToken.GetHashCode();
public override bool Equals(object? obj) => obj is TokenValueProvider tvp && tvp.ParsedToken.Equals(ParsedToken);
public TokenValueProvider (ParsedToken token, bool isExplicit)
{
this.ParsedToken = token;
this.IsExplicit = isExplicit;
}
public override object? GetValue(TemplateParameters p)
{
if (p.Rows.IsEmpty())
return null;
return p.Rows.DistinctSingle(p.Columns[ParsedToken.QueryToken!]);
}
public override void Foreach(TemplateParameters p, Action forEachElement)
{
var col = p.Columns[ParsedToken.QueryToken!];
foreach (var group in p.Rows.GroupByColumn(col))
{
using (p.OverrideRows(group))
forEachElement();
}
}
public override string? Format
{
get { return ParsedToken.QueryToken!.Format; }
}
public override void FillQueryTokens(List<QueryToken> list)
{
list.Add(ParsedToken.QueryToken!);
}
public override void ToStringInternal(StringBuilder sb, ScopedDictionary<string, ValueProviderBase> variables)
{
if (this.IsExplicit)
sb.Append("q:");
sb.Append(this.ParsedToken.ToString(variables));
}
public override void Synchronize(SynchronizationContext sc, string remainingText)
{
sc.SynchronizeToken(ParsedToken, remainingText);
Declare(sc.Variables);
}
public override Type? Type
{
get { return ParsedToken.QueryToken?.Type; }
}
}
public class TranslateInstanceValueProvider : ValueProviderBase
{
public readonly ParsedToken ParsedToken;
public readonly QueryToken? EntityToken;
public readonly PropertyRoute? Route;
public readonly bool IsExplicit;
public TranslateInstanceValueProvider(ParsedToken token, bool isExplicit, Action<bool, string> addError)
{
this.ParsedToken = token;
this.IsExplicit = isExplicit;
if (token.QueryToken != null)
{
this.Route = token.QueryToken.GetPropertyRoute();
this.EntityToken = DeterminEntityToken(token.QueryToken, addError);
}
}
public override object? GetValue(TemplateParameters p)
{
var entity = (Lite<Entity>)p.Rows.DistinctSingle(p.Columns[EntityToken!])!;
var fallback = (string)p.Rows.DistinctSingle(p.Columns[ParsedToken.QueryToken!])!;
return entity == null ? null : TranslatedInstanceLogic.TranslatedField(entity, Route!, fallback);
}
public override void Foreach(TemplateParameters parameters, Action forEachElement)
{
throw new NotImplementedException("{0} can not be used to foreach".FormatWith(typeof(TranslateInstanceValueProvider).Name));
}
QueryToken DeterminEntityToken(QueryToken token, Action<bool, string> addError)
{
var entityToken = token.Follow(a => a.Parent).FirstOrDefault(a => a.Type.IsLite() || a.Type.IsIEntity());
if (entityToken == null)
entityToken = QueryUtils.Parse("Entity", QueryLogic.Queries.QueryDescription(token.QueryName), 0);
if (!entityToken.Type.CleanType().IsAssignableFrom(Route!.RootType))
addError(false, "The entity of {0} ({1}) is not compatible with the property route {2}".FormatWith(token.FullKey(), entityToken.FullKey(), Route.RootType.NiceName()));
return entityToken;
}
public static bool IsTranslateInstanceCanditate(QueryToken token)
{
if (token.Type != typeof(string))
return false;
var pr = token.GetPropertyRoute();
if (pr == null)
return false;
if (TranslatedInstanceLogic.RouteType(pr) == null)
return false;
return true;
}
public override string? Format
{
get { return null; }
}
public override void FillQueryTokens(List<QueryToken> list)
{
list.Add(ParsedToken.QueryToken!);
list.Add(EntityToken!);
}
public override void ToStringInternal(StringBuilder sb, ScopedDictionary<string, ValueProviderBase> variables)
{
if (this.IsExplicit)
sb.Append("t:");
sb.Append(this.ParsedToken.ToString(variables));
}
public override void Synchronize(SynchronizationContext sc, string remainingText)
{
sc.SynchronizeToken(ParsedToken, remainingText);
Declare(sc.Variables);
}
public override Type ?Type
{
get { return typeof(string); }
}
public override int GetHashCode() => ParsedToken.GetHashCode();
public override bool Equals(object? obj) => obj is TranslateInstanceValueProvider tivp &&
Equals(tivp.ParsedToken, ParsedToken) &&
Equals(tivp.EntityToken, EntityToken) &&
Equals(tivp.Route, Route) &&
Equals(tivp.IsExplicit, IsExplicit);
}
public class ParsedToken
{
public string String;
public QueryToken? QueryToken { get; set; }
public ParsedToken(string @string)
{
String = @string;
}
public static ParsedToken TryParseToken(string tokenString, SubTokensOptions options, QueryDescription qd, ScopedDictionary<string, ValueProviderBase> variables, Action<bool, string> addError)
{
ParsedToken result = new ParsedToken(tokenString);
if (tokenString.StartsWith("$"))
{
string v = tokenString.TryBefore('.') ?? tokenString;
if (!variables.TryGetValue(v, out ValueProviderBase? vp))
{
addError(false, "Variable '{0}' is not defined at this scope".FormatWith(v));
return result;
}
var tvp = vp as TokenValueProvider;
if(tvp == null)
{
addError(false, "Variable '{0}' is not a token".FormatWith(v));
return result;
}
if (tvp.ParsedToken.QueryToken == null)
{
addError(false, "Variable '{0}' is not a correctly parsed".FormatWith(v));
return result;
}
var after = tokenString.TryAfter('.');
tokenString = tvp.ParsedToken.QueryToken.FullKey() + (after == null ? null : ("." + after));
}
try
{
result.QueryToken = QueryUtils.Parse(tokenString, qd, options);
}
catch (Exception ex)
{
addError(false, ex.Message);
}
return result;
}
public string SimplifyToken(ScopedDictionary<string, ValueProviderBase> variables, string token)
{
var pair = (from kvp in variables
let tp = kvp.Value as TokenValueProvider
where tp != null
let fullKey = tp.ParsedToken.QueryToken!.FullKey()
where token == fullKey || token.StartsWith(fullKey + ".")
orderby fullKey.Length descending
select new { kvp.Key, fullKey }).FirstOrDefault();
if (pair != null)
{
return pair.Key + token.RemoveStart(pair.fullKey!.Length); /*CSBUG*/
}
return token;
}
internal string ToString(ScopedDictionary<string, ValueProviderBase> variables)
{
if(QueryToken == null)
return String;
return SimplifyToken(variables, QueryToken.FullKey());
}
public override int GetHashCode() => (this.QueryToken?.FullKey() ?? this.String).GetHashCode();
public override bool Equals(object? obj) => obj is ParsedToken pt && Equals(pt.String, String) && Equals(pt.QueryToken, QueryToken);
}
public class ModelValueProvider : ValueProviderBase
{
string? fieldOrPropertyChain;
List<MemberInfo>? Members;
public ModelValueProvider(string fieldOrPropertyChain, Type? modelType, Action<bool, string> addError)
{
this.fieldOrPropertyChain = fieldOrPropertyChain;
if (modelType == null)
{
addError(false, EmailTemplateMessage.ImpossibleToAccess0BecauseTheTemplateHAsNo1.NiceToString(fieldOrPropertyChain, "Model"));
return;
}
this.Members = ParsedModel.GetMembers(modelType, fieldOrPropertyChain, addError);
}
public override object? GetValue(TemplateParameters p)
{
object? value = p.GetModel();
foreach (var m in Members!)
{
value = Getter(m, value, p);
if (value == null)
break;
}
return value;
}
internal static object? Getter(MemberInfo member, object model, TemplateParameters p)
{
try
{
if (member is PropertyInfo pi)
return pi.GetValue(model, null);
if (member is MethodInfo mi)
return mi.Invoke(model, new object[] { p });
return ((FieldInfo)member).GetValue(model);
}
catch (TargetInvocationException e)
{
e.InnerException!.PreserveStackTrace();
throw e.InnerException!;
}
}
public override string? Format
{
get { return Reflector.FormatString(this.Type!); }
}
public override Type? Type
{
get { return Members?.Let(ms => ms.Last().ReturningType().Nullify()); }
}
public override void FillQueryTokens(List<QueryToken> list)
{
}
public override void ToStringInternal(StringBuilder sb, ScopedDictionary<string, ValueProviderBase> variables)
{
sb.Append("m:");
sb.Append(Members == null ? fieldOrPropertyChain : Members.ToString(a => a.Name, "."));
}
public override void Synchronize(SynchronizationContext sc, string remainingText)
{
if (Members == null)
{
Members = sc.GetMembers(fieldOrPropertyChain!, sc.ModelType!);
if (Members != null)
fieldOrPropertyChain = Members.ToString(a => a.Name, ".");
}
Declare(sc.Variables);
}
public override int GetHashCode() => fieldOrPropertyChain?.GetHashCode() ?? 0;
public override bool Equals(object? obj) => obj is ModelValueProvider mvp && Equals(mvp.fieldOrPropertyChain, fieldOrPropertyChain);
}
public class GlobalValueProvider : ValueProviderBase
{
public class GlobalVariable
{
public Func<TemplateParameters, object?> GetValue;
public Type Type;
public string? Format;
public GlobalVariable(Func<TemplateParameters, object?> getValue, Type type, string? format)
{
GetValue = getValue;
Type = type;
Format = format;
}
}
public static Dictionary<string, GlobalVariable> GlobalVariables = new Dictionary<string, GlobalVariable>();
public static void RegisterGlobalVariable<T>(string key, Func<TemplateParameters, T> globalVariable, string? format = null)
{
GlobalVariables.Add(key, new GlobalVariable(a => globalVariable(a), typeof(T), format));
}
string globalKey;
string? remainingFieldsOrProperties;
List<MemberInfo>? Members;
public GlobalValueProvider(string fieldOrPropertyChain, Action<bool, string> addError)
{
globalKey = fieldOrPropertyChain.TryBefore('.') ?? fieldOrPropertyChain;
remainingFieldsOrProperties = fieldOrPropertyChain.TryAfter('.');
var gv = GlobalVariables.TryGetC(globalKey);
if (gv == null)
addError(false, "The global key {0} was not found".FormatWith(globalKey));
if (remainingFieldsOrProperties != null && gv != null)
this.Members = ParsedModel.GetMembers(gv.Type, remainingFieldsOrProperties, addError);
}
public override object? GetValue(TemplateParameters p)
{
object? value = GlobalVariables[globalKey].GetValue(p);
if (value == null)
return null;
if (Members != null)
{
foreach (var m in Members)
{
value = ModelValueProvider.Getter(m, value, p);
if (value == null)
break;
}
}
return value;
}
public override string? Format
{
get
{
return Members == null ?
GlobalVariables.TryGetC(globalKey)?.Format ?? Reflector.FormatString(Type!) :
Reflector.FormatString(Type!);
}
}
public override Type? Type
{
get
{
if (remainingFieldsOrProperties.HasText())
return Members?.Let(ms => ms.Last().ReturningType().Nullify());
else
return GlobalVariables.TryGetC(globalKey)?.Type;
}
}
public override void FillQueryTokens(List<QueryToken> list)
{
}
public override void ToStringInternal(StringBuilder sb, ScopedDictionary<string, ValueProviderBase> variables)
{
sb.Append("g:");
sb.Append(globalKey);
if (remainingFieldsOrProperties.HasText())
{
sb.Append(".");
sb.Append(Members == null ? remainingFieldsOrProperties : Members.ToString(a => a.Name, "."));
}
}
public override void Synchronize(SynchronizationContext sc, string remainingText)
{
globalKey = sc.Replacements.SelectInteractive(globalKey, GlobalVariables.Keys, "Globals", sc.StringDistance) ?? globalKey;
if(remainingFieldsOrProperties.HasText() && Members == null)
{
Members = sc.GetMembers(remainingFieldsOrProperties, GlobalVariables[globalKey].Type);
if (Members != null)
remainingFieldsOrProperties = Members.ToString(a => a.Name, ".");
}
Declare(sc.Variables);
}
public override int GetHashCode() => globalKey.GetHashCode() + (remainingFieldsOrProperties?.GetHashCode() ?? 0);
public override bool Equals(object? obj) => obj is GlobalValueProvider gvp
&& Equals(gvp.globalKey, globalKey)
&& Equals(gvp.remainingFieldsOrProperties, remainingFieldsOrProperties);
}
public class DateValueProvider : ValueProviderBase
{
string? dateTimeExpression;
public DateValueProvider(string dateTimeExpression, Action<bool, string> addError)
{
try
{
var obj = dateTimeExpression == null ? DateTime.Now: FilterValueConverter.Parse(dateTimeExpression, typeof(DateTime?), isList: false);
this.dateTimeExpression = dateTimeExpression;
}
catch (Exception e)
{
addError(false, $"Invalid expression {dateTimeExpression}: {e.Message}");
}
}
public override Type? Type => typeof(DateTime?);
public override object? GetValue(TemplateParameters p)
{
return dateTimeExpression == null ? DateTime.Now : FilterValueConverter.Parse(this.dateTimeExpression, typeof(DateTime?), isList: false);
}
public override void FillQueryTokens(List<QueryToken> list)
{
}
public override void ToStringInternal(StringBuilder sb, ScopedDictionary<string, ValueProviderBase> variables)
{
sb.Append("d:");
sb.Append(TemplateUtils.ScapeColon(this.dateTimeExpression!));
}
public override void Synchronize(SynchronizationContext sc, string remainingText)
{
}
public override string? Format => "G";
public override int GetHashCode() => dateTimeExpression?.GetHashCode() ?? 0;
public override bool Equals(object? obj) => obj is DateValueProvider gvp
&& Equals(gvp.dateTimeExpression, dateTimeExpression);
}
public class ContinueValueProvider : ValueProviderBase
{
string? fieldOrPropertyChain;
List<MemberInfo>? Members;
ValueProviderBase Parent;
public ContinueValueProvider(string? fieldOrPropertyChain, ValueProviderBase parent, Action<bool, string> addError)
{
this.Parent = parent;
var pt = ParentType();
if (pt == null)
addError(false, $"Impossible to continue with {fieldOrPropertyChain} (parentType is null)");
else
this.Members = ParsedModel.GetMembers(pt, fieldOrPropertyChain, addError);
}
private Type? ParentType()
{
if (Parent.IsForeach)
return Parent.Type?.ElementType();
return Parent.Type;
}
public override object? GetValue(TemplateParameters p)
{
if (!p.RuntimeVariables.TryGetValue(Parent.Variable!, out object? value))
throw new InvalidOperationException("Variable {0} not found".FormatWith(Parent.Variable));
foreach (var m in Members!)
{
value = Getter(m, value, p);
if (value == null)
break;
}
return value;
}
internal static object? Getter(MemberInfo member, object value, TemplateParameters p)
{
try
{
if (member is PropertyInfo pi)
return pi.GetValue(value, null);
if (member is MethodInfo mi)
return mi.Invoke(value, new object[] { p });
return ((FieldInfo)member).GetValue(value);
}
catch (TargetInvocationException e)
{
e.InnerException!.PreserveStackTrace();
throw e.InnerException!;
}
}
public override string? Format
{
get { return Reflector.FormatString(this.Type!); }
}
public override Type? Type
{
get { return Members?.Let(ms => ms.Last().ReturningType().Nullify()); }
}
public override void FillQueryTokens(List<QueryToken> list)
{
}
public override void ToStringInternal(StringBuilder sb, ScopedDictionary<string, ValueProviderBase> variables)
{
sb.Append(Parent.Variable);
sb.Append(".");
sb.Append(Members == null ? fieldOrPropertyChain : Members.ToString(a => a.Name, "."));
}
public override void Synchronize(SynchronizationContext sc, string remainingText)
{
if (Members == null)
{
Members = sc.GetMembers(fieldOrPropertyChain!, ParentType()!);
if (Members != null)
fieldOrPropertyChain = Members.ToString(a => a.Name, ".");
}
Declare(sc.Variables);
}
public override int GetHashCode() => (fieldOrPropertyChain?.GetHashCode() ?? 0) ^ this.Parent.GetHashCode();
public override bool Equals(object? obj) => obj is ContinueValueProvider gvp
&& Equals(gvp.fieldOrPropertyChain, fieldOrPropertyChain)
&& Equals(gvp.Parent, Parent);
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace ZipCodeFinal.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Xml.XPath;
namespace MS.Internal.Xml.XPath
{
internal class XPathParser
{
private XPathScanner _scanner;
private XPathParser(XPathScanner scanner)
{
_scanner = scanner;
}
public static AstNode ParseXPathExpresion(string xpathExpresion)
{
XPathScanner scanner = new XPathScanner(xpathExpresion);
XPathParser parser = new XPathParser(scanner);
AstNode result = parser.ParseExpresion(null);
if (scanner.Kind != XPathScanner.LexKind.Eof)
{
throw XPathException.Create(SR.Xp_InvalidToken, scanner.SourceText);
}
return result;
}
public static AstNode ParseXPathPattern(string xpathPattern)
{
XPathScanner scanner = new XPathScanner(xpathPattern);
XPathParser parser = new XPathParser(scanner);
AstNode result = parser.ParsePattern();
if (scanner.Kind != XPathScanner.LexKind.Eof)
{
throw XPathException.Create(SR.Xp_InvalidToken, scanner.SourceText);
}
return result;
}
// --------------- Expresion Parsing ----------------------
//The recursive is like
//ParseOrExpr->ParseAndExpr->ParseEqualityExpr->ParseRelationalExpr...->ParseFilterExpr->ParsePredicate->ParseExpresion
//So put 200 limitation here will max cause about 2000~3000 depth stack.
private int _parseDepth = 0;
private const int MaxParseDepth = 200;
private AstNode ParseExpresion(AstNode qyInput)
{
if (++_parseDepth > MaxParseDepth)
{
throw XPathException.Create(SR.Xp_QueryTooComplex);
}
AstNode result = ParseOrExpr(qyInput);
--_parseDepth;
return result;
}
//>> OrExpr ::= ( OrExpr 'or' )? AndExpr
private AstNode ParseOrExpr(AstNode qyInput)
{
AstNode opnd = ParseAndExpr(qyInput);
do
{
if (!TestOp("or"))
{
return opnd;
}
NextLex();
opnd = new Operator(Operator.Op.OR, opnd, ParseAndExpr(qyInput));
} while (true);
}
//>> AndExpr ::= ( AndExpr 'and' )? EqualityExpr
private AstNode ParseAndExpr(AstNode qyInput)
{
AstNode opnd = ParseEqualityExpr(qyInput);
do
{
if (!TestOp("and"))
{
return opnd;
}
NextLex();
opnd = new Operator(Operator.Op.AND, opnd, ParseEqualityExpr(qyInput));
} while (true);
}
//>> EqualityOp ::= '=' | '!='
//>> EqualityExpr ::= ( EqualityExpr EqualityOp )? RelationalExpr
private AstNode ParseEqualityExpr(AstNode qyInput)
{
AstNode opnd = ParseRelationalExpr(qyInput);
do
{
Operator.Op op = (
_scanner.Kind == XPathScanner.LexKind.Eq ? Operator.Op.EQ :
_scanner.Kind == XPathScanner.LexKind.Ne ? Operator.Op.NE :
/*default :*/ Operator.Op.INVALID
);
if (op == Operator.Op.INVALID)
{
return opnd;
}
NextLex();
opnd = new Operator(op, opnd, ParseRelationalExpr(qyInput));
} while (true);
}
//>> RelationalOp ::= '<' | '>' | '<=' | '>='
//>> RelationalExpr ::= ( RelationalExpr RelationalOp )? AdditiveExpr
private AstNode ParseRelationalExpr(AstNode qyInput)
{
AstNode opnd = ParseAdditiveExpr(qyInput);
do
{
Operator.Op op = (
_scanner.Kind == XPathScanner.LexKind.Lt ? Operator.Op.LT :
_scanner.Kind == XPathScanner.LexKind.Le ? Operator.Op.LE :
_scanner.Kind == XPathScanner.LexKind.Gt ? Operator.Op.GT :
_scanner.Kind == XPathScanner.LexKind.Ge ? Operator.Op.GE :
/*default :*/ Operator.Op.INVALID
);
if (op == Operator.Op.INVALID)
{
return opnd;
}
NextLex();
opnd = new Operator(op, opnd, ParseAdditiveExpr(qyInput));
} while (true);
}
//>> AdditiveOp ::= '+' | '-'
//>> AdditiveExpr ::= ( AdditiveExpr AdditiveOp )? MultiplicativeExpr
private AstNode ParseAdditiveExpr(AstNode qyInput)
{
AstNode opnd = ParseMultiplicativeExpr(qyInput);
do
{
Operator.Op op = (
_scanner.Kind == XPathScanner.LexKind.Plus ? Operator.Op.PLUS :
_scanner.Kind == XPathScanner.LexKind.Minus ? Operator.Op.MINUS :
/*default :*/ Operator.Op.INVALID
);
if (op == Operator.Op.INVALID)
{
return opnd;
}
NextLex();
opnd = new Operator(op, opnd, ParseMultiplicativeExpr(qyInput));
} while (true);
}
//>> MultiplicativeOp ::= '*' | 'div' | 'mod'
//>> MultiplicativeExpr ::= ( MultiplicativeExpr MultiplicativeOp )? UnaryExpr
private AstNode ParseMultiplicativeExpr(AstNode qyInput)
{
AstNode opnd = ParseUnaryExpr(qyInput);
do
{
Operator.Op op = (
_scanner.Kind == XPathScanner.LexKind.Star ? Operator.Op.MUL :
TestOp("div") ? Operator.Op.DIV :
TestOp("mod") ? Operator.Op.MOD :
/*default :*/ Operator.Op.INVALID
);
if (op == Operator.Op.INVALID)
{
return opnd;
}
NextLex();
opnd = new Operator(op, opnd, ParseUnaryExpr(qyInput));
} while (true);
}
//>> UnaryExpr ::= UnionExpr | '-' UnaryExpr
private AstNode ParseUnaryExpr(AstNode qyInput)
{
bool minus = false;
while (_scanner.Kind == XPathScanner.LexKind.Minus)
{
NextLex();
minus = !minus;
}
if (minus)
{
return new Operator(Operator.Op.MUL, ParseUnionExpr(qyInput), new Operand(-1));
}
else
{
return ParseUnionExpr(qyInput);
}
}
//>> UnionExpr ::= ( UnionExpr '|' )? PathExpr
private AstNode ParseUnionExpr(AstNode qyInput)
{
AstNode opnd = ParsePathExpr(qyInput);
do
{
if (_scanner.Kind != XPathScanner.LexKind.Union)
{
return opnd;
}
NextLex();
AstNode opnd2 = ParsePathExpr(qyInput);
CheckNodeSet(opnd.ReturnType);
CheckNodeSet(opnd2.ReturnType);
opnd = new Operator(Operator.Op.UNION, opnd, opnd2);
} while (true);
}
private static bool IsNodeType(XPathScanner scaner)
{
return (
scaner.Prefix.Length == 0 && (
scaner.Name == "node" ||
scaner.Name == "text" ||
scaner.Name == "processing-instruction" ||
scaner.Name == "comment"
)
);
}
//>> PathOp ::= '/' | '//'
//>> PathExpr ::= LocationPath |
//>> FilterExpr ( PathOp RelativeLocationPath )?
private AstNode ParsePathExpr(AstNode qyInput)
{
AstNode opnd;
if (IsPrimaryExpr(_scanner))
{ // in this moment we shoud distinct LocationPas vs FilterExpr (which starts from is PrimaryExpr)
opnd = ParseFilterExpr(qyInput);
if (_scanner.Kind == XPathScanner.LexKind.Slash)
{
NextLex();
opnd = ParseRelativeLocationPath(opnd);
}
else if (_scanner.Kind == XPathScanner.LexKind.SlashSlash)
{
NextLex();
opnd = ParseRelativeLocationPath(new Axis(Axis.AxisType.DescendantOrSelf, opnd));
}
}
else
{
opnd = ParseLocationPath(null);
}
return opnd;
}
//>> FilterExpr ::= PrimaryExpr | FilterExpr Predicate
private AstNode ParseFilterExpr(AstNode qyInput)
{
AstNode opnd = ParsePrimaryExpr(qyInput);
while (_scanner.Kind == XPathScanner.LexKind.LBracket)
{
// opnd must be a query
opnd = new Filter(opnd, ParsePredicate(opnd));
}
return opnd;
}
//>> Predicate ::= '[' Expr ']'
private AstNode ParsePredicate(AstNode qyInput)
{
AstNode opnd;
// we have predicates. Check that input type is NodeSet
CheckNodeSet(qyInput.ReturnType);
PassToken(XPathScanner.LexKind.LBracket);
opnd = ParseExpresion(qyInput);
PassToken(XPathScanner.LexKind.RBracket);
return opnd;
}
//>> LocationPath ::= RelativeLocationPath | AbsoluteLocationPath
private AstNode ParseLocationPath(AstNode qyInput)
{
if (_scanner.Kind == XPathScanner.LexKind.Slash)
{
NextLex();
AstNode opnd = new Root();
if (IsStep(_scanner.Kind))
{
opnd = ParseRelativeLocationPath(opnd);
}
return opnd;
}
else if (_scanner.Kind == XPathScanner.LexKind.SlashSlash)
{
NextLex();
return ParseRelativeLocationPath(new Axis(Axis.AxisType.DescendantOrSelf, new Root()));
}
else
{
return ParseRelativeLocationPath(qyInput);
}
} // ParseLocationPath
//>> PathOp ::= '/' | '//'
//>> RelativeLocationPath ::= ( RelativeLocationPath PathOp )? Step
private AstNode ParseRelativeLocationPath(AstNode qyInput)
{
AstNode opnd = qyInput;
do
{
opnd = ParseStep(opnd);
if (XPathScanner.LexKind.SlashSlash == _scanner.Kind)
{
NextLex();
opnd = new Axis(Axis.AxisType.DescendantOrSelf, opnd);
}
else if (XPathScanner.LexKind.Slash == _scanner.Kind)
{
NextLex();
}
else
{
break;
}
}
while (true);
return opnd;
}
private static bool IsStep(XPathScanner.LexKind lexKind)
{
return (
lexKind == XPathScanner.LexKind.Dot ||
lexKind == XPathScanner.LexKind.DotDot ||
lexKind == XPathScanner.LexKind.At ||
lexKind == XPathScanner.LexKind.Axe ||
lexKind == XPathScanner.LexKind.Star ||
lexKind == XPathScanner.LexKind.Name // NodeTest is also Name
);
}
//>> Step ::= '.' | '..' | ( AxisName '::' | '@' )? NodeTest Predicate*
private AstNode ParseStep(AstNode qyInput)
{
AstNode opnd;
if (XPathScanner.LexKind.Dot == _scanner.Kind)
{ //>> '.'
NextLex();
opnd = new Axis(Axis.AxisType.Self, qyInput);
}
else if (XPathScanner.LexKind.DotDot == _scanner.Kind)
{ //>> '..'
NextLex();
opnd = new Axis(Axis.AxisType.Parent, qyInput);
}
else
{ //>> ( AxisName '::' | '@' )? NodeTest Predicate*
Axis.AxisType axisType = Axis.AxisType.Child;
switch (_scanner.Kind)
{
case XPathScanner.LexKind.At: //>> '@'
axisType = Axis.AxisType.Attribute;
NextLex();
break;
case XPathScanner.LexKind.Axe: //>> AxisName '::'
axisType = GetAxis();
NextLex();
break;
}
XPathNodeType nodeType = (
axisType == Axis.AxisType.Attribute ? XPathNodeType.Attribute :
// axisType == Axis.AxisType.Namespace ? XPathNodeType.Namespace : // No Idea why it's this way but othervise Axes doesn't work
/* default: */ XPathNodeType.Element
);
opnd = ParseNodeTest(qyInput, axisType, nodeType);
while (XPathScanner.LexKind.LBracket == _scanner.Kind)
{
opnd = new Filter(opnd, ParsePredicate(opnd));
}
}
return opnd;
}
//>> NodeTest ::= NameTest | 'comment ()' | 'text ()' | 'node ()' | 'processing-instruction (' Literal ? ')'
private AstNode ParseNodeTest(AstNode qyInput, Axis.AxisType axisType, XPathNodeType nodeType)
{
string nodeName, nodePrefix;
switch (_scanner.Kind)
{
case XPathScanner.LexKind.Name:
if (_scanner.CanBeFunction && IsNodeType(_scanner))
{
nodePrefix = string.Empty;
nodeName = string.Empty;
nodeType = (
_scanner.Name == "comment" ? XPathNodeType.Comment :
_scanner.Name == "text" ? XPathNodeType.Text :
_scanner.Name == "node" ? XPathNodeType.All :
_scanner.Name == "processing-instruction" ? XPathNodeType.ProcessingInstruction :
/* default: */ XPathNodeType.Root
);
Debug.Assert(nodeType != XPathNodeType.Root);
NextLex();
PassToken(XPathScanner.LexKind.LParens);
if (nodeType == XPathNodeType.ProcessingInstruction)
{
if (_scanner.Kind != XPathScanner.LexKind.RParens)
{ //>> 'processing-instruction (' Literal ')'
CheckToken(XPathScanner.LexKind.String);
nodeName = _scanner.StringValue;
NextLex();
}
}
PassToken(XPathScanner.LexKind.RParens);
}
else
{
nodePrefix = _scanner.Prefix;
nodeName = _scanner.Name;
NextLex();
if (nodeName == "*")
{
nodeName = string.Empty;
}
}
break;
case XPathScanner.LexKind.Star:
nodePrefix = string.Empty;
nodeName = string.Empty;
NextLex();
break;
default:
throw XPathException.Create(SR.Xp_NodeSetExpected, _scanner.SourceText);
}
return new Axis(axisType, qyInput, nodePrefix, nodeName, nodeType);
}
private static bool IsPrimaryExpr(XPathScanner scanner)
{
return (
scanner.Kind == XPathScanner.LexKind.String ||
scanner.Kind == XPathScanner.LexKind.Number ||
scanner.Kind == XPathScanner.LexKind.Dollar ||
scanner.Kind == XPathScanner.LexKind.LParens ||
scanner.Kind == XPathScanner.LexKind.Name && scanner.CanBeFunction && !IsNodeType(scanner)
);
}
//>> PrimaryExpr ::= Literal | Number | VariableReference | '(' Expr ')' | FunctionCall
private AstNode ParsePrimaryExpr(AstNode qyInput)
{
Debug.Assert(IsPrimaryExpr(_scanner));
AstNode opnd = null;
switch (_scanner.Kind)
{
case XPathScanner.LexKind.String:
opnd = new Operand(_scanner.StringValue);
NextLex();
break;
case XPathScanner.LexKind.Number:
opnd = new Operand(_scanner.NumberValue);
NextLex();
break;
case XPathScanner.LexKind.Dollar:
NextLex();
CheckToken(XPathScanner.LexKind.Name);
opnd = new Variable(_scanner.Name, _scanner.Prefix);
NextLex();
break;
case XPathScanner.LexKind.LParens:
NextLex();
opnd = ParseExpresion(qyInput);
if (opnd.Type != AstNode.AstType.ConstantOperand)
{
opnd = new Group(opnd);
}
PassToken(XPathScanner.LexKind.RParens);
break;
case XPathScanner.LexKind.Name:
if (_scanner.CanBeFunction && !IsNodeType(_scanner))
{
opnd = ParseMethod(null);
}
break;
}
Debug.Assert(opnd != null, "IsPrimaryExpr() was true. We should recognize this lex.");
return opnd;
}
private AstNode ParseMethod(AstNode qyInput)
{
List<AstNode> argList = new List<AstNode>();
string name = _scanner.Name;
string prefix = _scanner.Prefix;
PassToken(XPathScanner.LexKind.Name);
PassToken(XPathScanner.LexKind.LParens);
if (_scanner.Kind != XPathScanner.LexKind.RParens)
{
do
{
argList.Add(ParseExpresion(qyInput));
if (_scanner.Kind == XPathScanner.LexKind.RParens)
{
break;
}
PassToken(XPathScanner.LexKind.Comma);
} while (true);
}
PassToken(XPathScanner.LexKind.RParens);
if (prefix.Length == 0)
{
ParamInfo pi;
if (s_functionTable.TryGetValue(name, out pi))
{
int argCount = argList.Count;
if (argCount < pi.Minargs)
{
throw XPathException.Create(SR.Xp_InvalidNumArgs, name, _scanner.SourceText);
}
if (pi.FType == Function.FunctionType.FuncConcat)
{
for (int i = 0; i < argCount; i++)
{
AstNode arg = (AstNode)argList[i];
if (arg.ReturnType != XPathResultType.String)
{
arg = new Function(Function.FunctionType.FuncString, arg);
}
argList[i] = arg;
}
}
else
{
if (pi.Maxargs < argCount)
{
throw XPathException.Create(SR.Xp_InvalidNumArgs, name, _scanner.SourceText);
}
if (pi.ArgTypes.Length < argCount)
{
argCount = pi.ArgTypes.Length; // argument we have the type specified (can be < pi.Minargs)
}
for (int i = 0; i < argCount; i++)
{
AstNode arg = (AstNode)argList[i];
if (
pi.ArgTypes[i] != XPathResultType.Any &&
pi.ArgTypes[i] != arg.ReturnType
)
{
switch (pi.ArgTypes[i])
{
case XPathResultType.NodeSet:
if (!(arg is Variable) && !(arg is Function && arg.ReturnType == XPathResultType.Any))
{
throw XPathException.Create(SR.Xp_InvalidArgumentType, name, _scanner.SourceText);
}
break;
case XPathResultType.String:
arg = new Function(Function.FunctionType.FuncString, arg);
break;
case XPathResultType.Number:
arg = new Function(Function.FunctionType.FuncNumber, arg);
break;
case XPathResultType.Boolean:
arg = new Function(Function.FunctionType.FuncBoolean, arg);
break;
}
argList[i] = arg;
}
}
}
return new Function(pi.FType, argList);
}
}
return new Function(prefix, name, argList);
}
// --------------- Pattern Parsing ----------------------
//>> Pattern ::= ( Pattern '|' )? LocationPathPattern
private AstNode ParsePattern()
{
AstNode opnd = ParseLocationPathPattern();
do
{
if (_scanner.Kind != XPathScanner.LexKind.Union)
{
return opnd;
}
NextLex();
opnd = new Operator(Operator.Op.UNION, opnd, ParseLocationPathPattern());
} while (true);
}
//>> LocationPathPattern ::= '/' | RelativePathPattern | '//' RelativePathPattern | '/' RelativePathPattern
//>> | IdKeyPattern (('/' | '//') RelativePathPattern)?
private AstNode ParseLocationPathPattern()
{
AstNode opnd = null;
switch (_scanner.Kind)
{
case XPathScanner.LexKind.Slash:
NextLex();
opnd = new Root();
if (_scanner.Kind == XPathScanner.LexKind.Eof || _scanner.Kind == XPathScanner.LexKind.Union)
{
return opnd;
}
break;
case XPathScanner.LexKind.SlashSlash:
NextLex();
opnd = new Axis(Axis.AxisType.DescendantOrSelf, new Root());
break;
case XPathScanner.LexKind.Name:
if (_scanner.CanBeFunction)
{
opnd = ParseIdKeyPattern();
if (opnd != null)
{
switch (_scanner.Kind)
{
case XPathScanner.LexKind.Slash:
NextLex();
break;
case XPathScanner.LexKind.SlashSlash:
NextLex();
opnd = new Axis(Axis.AxisType.DescendantOrSelf, opnd);
break;
default:
return opnd;
}
}
}
break;
}
return ParseRelativePathPattern(opnd);
}
//>> IdKeyPattern ::= 'id' '(' Literal ')' | 'key' '(' Literal ',' Literal ')'
private AstNode ParseIdKeyPattern()
{
Debug.Assert(_scanner.CanBeFunction);
List<AstNode> argList = new List<AstNode>();
if (_scanner.Prefix.Length == 0)
{
if (_scanner.Name == "id")
{
ParamInfo pi = (ParamInfo)s_functionTable["id"];
NextLex();
PassToken(XPathScanner.LexKind.LParens);
CheckToken(XPathScanner.LexKind.String);
argList.Add(new Operand(_scanner.StringValue));
NextLex();
PassToken(XPathScanner.LexKind.RParens);
return new Function(pi.FType, argList);
}
if (_scanner.Name == "key")
{
NextLex();
PassToken(XPathScanner.LexKind.LParens);
CheckToken(XPathScanner.LexKind.String);
argList.Add(new Operand(_scanner.StringValue));
NextLex();
PassToken(XPathScanner.LexKind.Comma);
CheckToken(XPathScanner.LexKind.String);
argList.Add(new Operand(_scanner.StringValue));
NextLex();
PassToken(XPathScanner.LexKind.RParens);
return new Function("", "key", argList);
}
}
return null;
}
//>> PathOp ::= '/' | '//'
//>> RelativePathPattern ::= ( RelativePathPattern PathOp )? StepPattern
private AstNode ParseRelativePathPattern(AstNode qyInput)
{
AstNode opnd = ParseStepPattern(qyInput);
if (XPathScanner.LexKind.SlashSlash == _scanner.Kind)
{
NextLex();
opnd = ParseRelativePathPattern(new Axis(Axis.AxisType.DescendantOrSelf, opnd));
}
else if (XPathScanner.LexKind.Slash == _scanner.Kind)
{
NextLex();
opnd = ParseRelativePathPattern(opnd);
}
return opnd;
}
//>> StepPattern ::= ChildOrAttributeAxisSpecifier NodeTest Predicate*
//>> ChildOrAttributeAxisSpecifier ::= @ ? | ('child' | 'attribute') '::'
private AstNode ParseStepPattern(AstNode qyInput)
{
AstNode opnd;
Axis.AxisType axisType = Axis.AxisType.Child;
switch (_scanner.Kind)
{
case XPathScanner.LexKind.At: //>> '@'
axisType = Axis.AxisType.Attribute;
NextLex();
break;
case XPathScanner.LexKind.Axe: //>> AxisName '::'
axisType = GetAxis();
if (axisType != Axis.AxisType.Child && axisType != Axis.AxisType.Attribute)
{
throw XPathException.Create(SR.Xp_InvalidToken, _scanner.SourceText);
}
NextLex();
break;
}
XPathNodeType nodeType = (
axisType == Axis.AxisType.Attribute ? XPathNodeType.Attribute :
/* default: */ XPathNodeType.Element
);
opnd = ParseNodeTest(qyInput, axisType, nodeType);
while (XPathScanner.LexKind.LBracket == _scanner.Kind)
{
opnd = new Filter(opnd, ParsePredicate(opnd));
}
return opnd;
}
// --------------- Helper methods ----------------------
void CheckToken(XPathScanner.LexKind t)
{
if (_scanner.Kind != t)
{
throw XPathException.Create(SR.Xp_InvalidToken, _scanner.SourceText);
}
}
void PassToken(XPathScanner.LexKind t)
{
CheckToken(t);
NextLex();
}
void NextLex()
{
_scanner.NextLex();
}
private bool TestOp(string op)
{
return (
_scanner.Kind == XPathScanner.LexKind.Name &&
_scanner.Prefix.Length == 0 &&
_scanner.Name.Equals(op)
);
}
void CheckNodeSet(XPathResultType t)
{
if (t != XPathResultType.NodeSet && t != XPathResultType.Any)
{
throw XPathException.Create(SR.Xp_NodeSetExpected, _scanner.SourceText);
}
}
// ----------------------------------------------------------------
private static readonly XPathResultType[] s_temparray1 = { };
private static readonly XPathResultType[] s_temparray2 = { XPathResultType.NodeSet };
private static readonly XPathResultType[] s_temparray3 = { XPathResultType.Any };
private static readonly XPathResultType[] s_temparray4 = { XPathResultType.String };
private static readonly XPathResultType[] s_temparray5 = { XPathResultType.String, XPathResultType.String };
private static readonly XPathResultType[] s_temparray6 = { XPathResultType.String, XPathResultType.Number, XPathResultType.Number };
private static readonly XPathResultType[] s_temparray7 = { XPathResultType.String, XPathResultType.String, XPathResultType.String };
private static readonly XPathResultType[] s_temparray8 = { XPathResultType.Boolean };
private static readonly XPathResultType[] s_temparray9 = { XPathResultType.Number };
private class ParamInfo
{
private Function.FunctionType _ftype;
private int _minargs;
private int _maxargs;
private XPathResultType[] _argTypes;
public Function.FunctionType FType { get { return _ftype; } }
public int Minargs { get { return _minargs; } }
public int Maxargs { get { return _maxargs; } }
public XPathResultType[] ArgTypes { get { return _argTypes; } }
internal ParamInfo(Function.FunctionType ftype, int minargs, int maxargs, XPathResultType[] argTypes)
{
_ftype = ftype;
_minargs = minargs;
_maxargs = maxargs;
_argTypes = argTypes;
}
} //ParamInfo
private static Dictionary<string, ParamInfo> s_functionTable = CreateFunctionTable();
private static Dictionary<string, ParamInfo> CreateFunctionTable()
{
Dictionary<string, ParamInfo> table = new Dictionary<string, ParamInfo>(36);
table.Add("last", new ParamInfo(Function.FunctionType.FuncLast, 0, 0, s_temparray1));
table.Add("position", new ParamInfo(Function.FunctionType.FuncPosition, 0, 0, s_temparray1));
table.Add("name", new ParamInfo(Function.FunctionType.FuncName, 0, 1, s_temparray2));
table.Add("namespace-uri", new ParamInfo(Function.FunctionType.FuncNameSpaceUri, 0, 1, s_temparray2));
table.Add("local-name", new ParamInfo(Function.FunctionType.FuncLocalName, 0, 1, s_temparray2));
table.Add("count", new ParamInfo(Function.FunctionType.FuncCount, 1, 1, s_temparray2));
table.Add("id", new ParamInfo(Function.FunctionType.FuncID, 1, 1, s_temparray3));
table.Add("string", new ParamInfo(Function.FunctionType.FuncString, 0, 1, s_temparray3));
table.Add("concat", new ParamInfo(Function.FunctionType.FuncConcat, 2, 100, s_temparray4));
table.Add("starts-with", new ParamInfo(Function.FunctionType.FuncStartsWith, 2, 2, s_temparray5));
table.Add("contains", new ParamInfo(Function.FunctionType.FuncContains, 2, 2, s_temparray5));
table.Add("substring-before", new ParamInfo(Function.FunctionType.FuncSubstringBefore, 2, 2, s_temparray5));
table.Add("substring-after", new ParamInfo(Function.FunctionType.FuncSubstringAfter, 2, 2, s_temparray5));
table.Add("substring", new ParamInfo(Function.FunctionType.FuncSubstring, 2, 3, s_temparray6));
table.Add("string-length", new ParamInfo(Function.FunctionType.FuncStringLength, 0, 1, s_temparray4));
table.Add("normalize-space", new ParamInfo(Function.FunctionType.FuncNormalize, 0, 1, s_temparray4));
table.Add("translate", new ParamInfo(Function.FunctionType.FuncTranslate, 3, 3, s_temparray7));
table.Add("boolean", new ParamInfo(Function.FunctionType.FuncBoolean, 1, 1, s_temparray3));
table.Add("not", new ParamInfo(Function.FunctionType.FuncNot, 1, 1, s_temparray8));
table.Add("true", new ParamInfo(Function.FunctionType.FuncTrue, 0, 0, s_temparray8));
table.Add("false", new ParamInfo(Function.FunctionType.FuncFalse, 0, 0, s_temparray8));
table.Add("lang", new ParamInfo(Function.FunctionType.FuncLang, 1, 1, s_temparray4));
table.Add("number", new ParamInfo(Function.FunctionType.FuncNumber, 0, 1, s_temparray3));
table.Add("sum", new ParamInfo(Function.FunctionType.FuncSum, 1, 1, s_temparray2));
table.Add("floor", new ParamInfo(Function.FunctionType.FuncFloor, 1, 1, s_temparray9));
table.Add("ceiling", new ParamInfo(Function.FunctionType.FuncCeiling, 1, 1, s_temparray9));
table.Add("round", new ParamInfo(Function.FunctionType.FuncRound, 1, 1, s_temparray9));
return table;
}
private static Dictionary<string, Axis.AxisType> s_AxesTable = CreateAxesTable();
private static Dictionary<string, Axis.AxisType> CreateAxesTable()
{
Dictionary<string, Axis.AxisType> table = new Dictionary<string, Axis.AxisType>(13);
table.Add("ancestor", Axis.AxisType.Ancestor);
table.Add("ancestor-or-self", Axis.AxisType.AncestorOrSelf);
table.Add("attribute", Axis.AxisType.Attribute);
table.Add("child", Axis.AxisType.Child);
table.Add("descendant", Axis.AxisType.Descendant);
table.Add("descendant-or-self", Axis.AxisType.DescendantOrSelf);
table.Add("following", Axis.AxisType.Following);
table.Add("following-sibling", Axis.AxisType.FollowingSibling);
table.Add("namespace", Axis.AxisType.Namespace);
table.Add("parent", Axis.AxisType.Parent);
table.Add("preceding", Axis.AxisType.Preceding);
table.Add("preceding-sibling", Axis.AxisType.PrecedingSibling);
table.Add("self", Axis.AxisType.Self);
return table;
}
private Axis.AxisType GetAxis()
{
Debug.Assert(_scanner.Kind == XPathScanner.LexKind.Axe);
Axis.AxisType axis;
if (!s_AxesTable.TryGetValue(_scanner.Name, out axis))
{
throw XPathException.Create(SR.Xp_InvalidToken, _scanner.SourceText);
}
return axis;
}
}
}
| |
#region MigraDoc - Creating Documents on the Fly
//
// Authors:
// Stefan Lange (mailto:[email protected])
// Klaus Potzesny (mailto:[email protected])
// David Stephensen (mailto:[email protected])
//
// Copyright (c) 2001-2009 empira Software GmbH, Cologne (Germany)
//
// http://www.pdfsharp.com
// http://www.migradoc.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Diagnostics;
using System.Reflection;
using MigraDoc.DocumentObjectModel.Internals;
using MigraDoc.DocumentObjectModel.Visitors;
using MigraDoc.DocumentObjectModel.Tables;
using MigraDoc.DocumentObjectModel.Shapes;
using MigraDoc.DocumentObjectModel.IO;
namespace MigraDoc.DocumentObjectModel
{
/// <summary>
/// Represents a footnote in a paragraph.
/// </summary>
public class Footnote : DocumentObject, IVisitable
{
/// <summary>
/// Initializes a new instance of the Footnote class.
/// </summary>
public Footnote()
{
//NYI: Nested footnote check!
}
/// <summary>
/// Initializes a new instance of the Footnote class with the specified parent.
/// </summary>
internal Footnote(DocumentObject parent) : base(parent) { }
/// <summary>
/// Initializes a new instance of the Footnote class with a text the Footnote shall content.
/// </summary>
internal Footnote(string content)
: this()
{
this.Elements.AddParagraph(content);
}
#region Methods
/// <summary>
/// Creates a deep copy of this object.
/// </summary>
public new Footnote Clone()
{
return (Footnote)DeepCopy();
}
/// <summary>
/// Implements the deep copy of the object.
/// </summary>
protected override object DeepCopy()
{
Footnote footnote = (Footnote)base.DeepCopy();
if (footnote.elements != null)
{
footnote.elements = footnote.elements.Clone();
footnote.elements.parent = footnote;
}
if (footnote.format != null)
{
footnote.format = footnote.format.Clone();
footnote.format.parent = footnote;
}
return footnote;
}
/// <summary>
/// Adds a new paragraph to the footnote.
/// </summary>
public Paragraph AddParagraph()
{
return this.Elements.AddParagraph();
}
/// <summary>
/// Adds a new paragraph with the specified text to the footnote.
/// </summary>
public Paragraph AddParagraph(string text)
{
return this.Elements.AddParagraph(text);
}
/// <summary>
/// Adds a new table to the footnote.
/// </summary>
public Table AddTable()
{
return this.Elements.AddTable();
}
/// <summary>
/// Adds a new image to the footnote.
/// </summary>
public Image AddImage(string name)
{
return this.Elements.AddImage(name);
}
/// <summary>
/// Adds a new paragraph to the footnote.
/// </summary>
public void Add(Paragraph paragraph)
{
this.Elements.Add(paragraph);
}
/// <summary>
/// Adds a new table to the footnote.
/// </summary>
public void Add(Table table)
{
this.Elements.Add(table);
}
/// <summary>
/// Adds a new image to the footnote.
/// </summary>
public void Add(Image image)
{
this.Elements.Add(image);
}
#endregion
#region Properties
/// <summary>
/// Gets the collection of paragraph elements that defines the footnote.
/// </summary>
public DocumentElements Elements
{
get
{
if (this.elements == null)
this.elements = new DocumentElements(this);
return this.elements;
}
set
{
SetParent(value);
this.elements = value;
}
}
[DV(ItemType = typeof(DocumentObject))]
internal DocumentElements elements;
/// <summary>
/// Gets or sets the character to be used to mark the footnote.
/// </summary>
public string Reference
{
get { return this.reference.Value; }
set { this.reference.Value = value; }
}
[DV]
internal NString reference = NString.NullValue;
/// <summary>
/// Gets or sets the style name of the footnote.
/// </summary>
public string Style
{
get { return this.style.Value; }
set { this.style.Value = value; }
}
[DV]
internal NString style = NString.NullValue;
/// <summary>
/// Gets the format of the footnote.
/// </summary>
public ParagraphFormat Format
{
get
{
if (this.format == null)
this.format = new ParagraphFormat(this);
return this.format;
}
set
{
SetParent(value);
this.format = value;
}
}
[DV]
internal ParagraphFormat format;
#endregion
#region Internal
/// <summary>
/// Converts Footnote into DDL.
/// </summary>
internal override void Serialize(Serializer serializer)
{
serializer.WriteLine("\\footnote");
int pos = serializer.BeginAttributes();
if (this.reference.Value != string.Empty)
serializer.WriteSimpleAttribute("Reference", this.Reference);
if (this.style.Value != string.Empty)
serializer.WriteSimpleAttribute("Style", this.Style);
if (!this.IsNull("Format"))
this.format.Serialize(serializer, "Format", null);
serializer.EndAttributes(pos);
pos = serializer.BeginContent();
if (!this.IsNull("Elements"))
this.elements.Serialize(serializer);
serializer.EndContent(pos);
}
/// <summary>
/// Allows the visitor object to visit the document object and it's child objects.
/// </summary>
void IVisitable.AcceptVisitor(DocumentObjectVisitor visitor, bool visitChildren)
{
visitor.VisitFootnote(this);
if (visitChildren && this.elements != null)
((IVisitable)this.elements).AcceptVisitor(visitor, visitChildren);
}
/// <summary>
/// Returns the meta object of this instance.
/// </summary>
internal override Meta Meta
{
get
{
if (meta == null)
meta = new Meta(typeof(Footnote));
return meta;
}
}
static Meta meta;
#endregion
}
}
| |
using Newtonsoft.Json.Linq;
using ReactNative.Bridge;
using ReactNative.UIManager;
using ReactNative.UIManager.Events;
using System;
using System.Collections.Generic;
using static System.FormattableString;
namespace ReactNative.Animated
{
/// <summary>
/// This is the main class that coordinates how native animated JS
/// implementation drives UI changes.
///
/// It implements a management interface for animated nodes graph as well
/// as implements a graph traversal algorithm that is run for each
/// animation frame.
///
/// For each animation frame we visit animated nodes that might've been
/// updated as well as their children that may use parent's values to
/// update themselves. At the end of the traversal algorithm we expect to
/// reach a special type of the node: PropsAnimatedNode that is then
/// responsible for calculating property map which can be sent to native
/// view hierarchy to update the view.
/// </summary>
/// <remarks>
/// This class should be accessed only from the dispatcher thread.
/// </remarks>
class NativeAnimatedNodesManager : IEventDispatcherListener
{
private readonly IDictionary<int, AnimatedNode> _animatedNodes = new Dictionary<int, AnimatedNode>();
private readonly IDictionary<int, AnimationDriver> _activeAnimations = new Dictionary<int, AnimationDriver>();
private readonly IDictionary<int, AnimatedNode> _updatedNodes = new Dictionary<int, AnimatedNode>();
// Mapping of a view tag and an event name to a list of event animation drivers. 99% of the time
// there will be only one driver per mapping so all code should be optimized around that.
private readonly IDictionary<Tuple<int, string>, IList<EventAnimationDriver>> _eventDrivers =
new Dictionary<Tuple<int, string>, IList<EventAnimationDriver>>();
private readonly Func<string, string> _customEventNamesResolver;
private readonly UIImplementation _uiImplementation;
// Used to avoid allocating a new array on every frame in `RunUpdates` and `OnEventDispatch`
private readonly List<AnimatedNode> _runUpdateNodeList = new List<AnimatedNode>();
// Used to avoid allocating a new array on every frame in `RunUpdates` and `StopAnimationsForNode`
private int[] _activeAnimationIds;
private int _animatedGraphBFSColor = 0;
public NativeAnimatedNodesManager(UIManagerModule uiManager)
{
_uiImplementation = uiManager.UIImplementation;
uiManager.EventDispatcher.AddListener(this);
_customEventNamesResolver = uiManager.ResolveCustomEventName;
}
public bool HasActiveAnimations
{
get
{
return _activeAnimations.Count > 0 || _updatedNodes.Count > 0;
}
}
public void CreateAnimatedNode(int tag, JObject config)
{
if (_animatedNodes.ContainsKey(tag))
{
throw new InvalidOperationException(
Invariant($"Animated node with tag '{tag}' already exists."));
}
var type = config.Value<string>("type");
var node = default(AnimatedNode);
switch (type)
{
case "style":
node = new StyleAnimatedNode(tag, config, this);
break;
case "value":
node = new ValueAnimatedNode(tag, config);
break;
case "props":
node = new PropsAnimatedNode(tag, config, this, _uiImplementation);
break;
case "interpolation":
node = new InterpolationAnimatedNode(tag, config);
break;
case "addition":
node = new AdditionAnimatedNode(tag, config, this);
break;
case "division":
node = new DivisionAnimatedNode(tag, config, this);
break;
case "multiplication":
node = new MultiplicationAnimatedNode(tag, config, this);
break;
case "modulus":
node = new ModulusAnimatedNode(tag, config, this);
break;
case "diffclamp":
node = new DiffClampAnimatedNode(tag, config, this);
break;
case "transform":
node = new TransformAnimatedNode(tag, config, this);
break;
default:
throw new InvalidOperationException(Invariant($"Unsupported node type: '{type}'"));
}
_animatedNodes.Add(tag, node);
_updatedNodes[tag] = node;
}
public void DropAnimatedNode(int tag)
{
_animatedNodes.Remove(tag);
_updatedNodes.Remove(tag);
}
public void StartListeningToAnimatedNodeValue(int tag, Action<double> callback)
{
var node = default(AnimatedNode);
if (!_animatedNodes.TryGetValue(tag, out node))
{
throw new InvalidOperationException(
Invariant($"Animated node with tag '{tag}' does not exist."));
}
var valueNode = node as ValueAnimatedNode;
if (valueNode == null)
{
throw new InvalidOperationException(
Invariant($"Animated node with tag '{tag}' is not a value node."));
}
valueNode.SetValueListener(callback);
}
public void StopListeningToAnimatedNodeValue(int tag)
{
var node = GetNode(tag);
var valueNode = node as ValueAnimatedNode;
if (valueNode == null)
{
throw new InvalidOperationException(
Invariant($"Animated node with tag '{tag}' is not a value node."));
}
valueNode.SetValueListener(null);
}
public void SetAnimatedNodeValue(int tag, double value)
{
var node = GetNode(tag);
var valueNode = node as ValueAnimatedNode;
if (valueNode == null)
{
throw new InvalidOperationException(
Invariant($"Animated node with tag '{tag}' is not a value node."));
}
valueNode.RawValue = value;
StopAnimationsForNode(node);
_updatedNodes[tag] = node;
}
public void SetAnimatedNodeOffset(int tag, double offset)
{
var node = GetNode(tag);
var valueNode = node as ValueAnimatedNode;
if (valueNode == null)
{
throw new InvalidOperationException(
Invariant($"Animated node with tag '{tag}' is not a value node"));
}
valueNode.Offset = offset;
_updatedNodes[tag] = node;
}
public void FlattenAnimatedNodeOffset(int tag)
{
var node = GetNode(tag);
var valueNode = node as ValueAnimatedNode;
if (valueNode == null)
{
throw new InvalidOperationException(
Invariant($"Animated node with tag '{tag}' is not a value node"));
}
valueNode.FlattenOffset();
}
public void ExtractAnimatedNodeOffset(int tag)
{
var node = GetNode(tag);
var valueNode = node as ValueAnimatedNode;
if (valueNode == null)
{
throw new InvalidOperationException(
Invariant($"Animated node with tag '{tag}' is not a value node"));
}
valueNode.ExtractOffset();
}
public void StartAnimatingNode(int animationId, int animatedNodeTag, JObject animationConfig, ICallback endCallback)
{
var node = GetNode(animatedNodeTag);
var valueNode = node as ValueAnimatedNode;
if (valueNode == null)
{
throw new InvalidOperationException(
Invariant($"Animated node with tag '{animatedNodeTag}' is not a value node."));
}
var type = animationConfig.Value<string>("type");
var animation = default(AnimationDriver);
switch (type)
{
case "decay":
animation = new DecayAnimationDriver(animationId, valueNode, endCallback, animationConfig);
break;
case "frames":
animation = new FrameBasedAnimationDriver(animationId, valueNode, endCallback, animationConfig);
break;
case "spring":
animation = new SpringAnimationDriver(animationId, valueNode, endCallback, animationConfig);
break;
default:
throw new InvalidOperationException(Invariant($"Unsupported animation type: '{type}'"));
}
_activeAnimations[animationId] = animation;
}
public void StopAnimation(int animationId)
{
AnimationDriver animation;
if (_activeAnimations.TryGetValue(animationId, out animation))
{
animation.EndCallback.Invoke(new JObject
{
{ "finished", false },
});
_activeAnimations.Remove(animationId);
}
// Do not throw an error in the case the animation was not found.
// We only keep active animations in the registry and there is a
// chance that Animated.js will enqueue a stopAnimation call after
// the animation has ended or the call will reach the native thread
// only when the animation is already over.
}
public void ConnectAnimatedNodes(int parentNodeTag, int childNodeTag)
{
var parentNode = GetNode(parentNodeTag);
var childNode = GetNode(childNodeTag);
parentNode.AddChild(childNode);
_updatedNodes[childNodeTag] = childNode;
}
public void DisconnectAnimatedNodes(int parentNodeTag, int childNodeTag)
{
var parentNode = GetNode(parentNodeTag);
var childNode = GetNode(childNodeTag);
parentNode.RemoveChild(childNode);
_updatedNodes[childNodeTag] = childNode;
}
public void ConnectAnimatedNodeToView(int animatedNodeTag, int viewTag)
{
var node = GetNode(animatedNodeTag);
var propsAnimatedNode = node as PropsAnimatedNode;
if (propsAnimatedNode == null)
{
throw new InvalidOperationException("Animated node connected to view should be props node.");
}
propsAnimatedNode.ConnectToView(viewTag);
_updatedNodes[animatedNodeTag] = node;
}
public void DisconnectAnimatedNodeFromView(int animatedNodeTag, int viewTag)
{
var node = GetNode(animatedNodeTag);
var propsAnimatedNode = node as PropsAnimatedNode;
if (propsAnimatedNode == null)
{
throw new InvalidOperationException("Animated node connected to view should be props node.");
}
propsAnimatedNode.DisconnectFromView(viewTag);
}
public void RestoreDefaultValues(int animatedNodeTag, int viewTag)
{
var node = default(AnimatedNode);
if (!_animatedNodes.TryGetValue(animatedNodeTag, out node))
{
// Restoring default values needs to happen before UIManager
// operations so it is possible the node hasn't been created yet if
// it is being connected and disconnected in the same batch. In
// that case we don't need to restore default values since it will
// never actually update the view.
return;
}
var propsAnimatedNode = node as PropsAnimatedNode;
if (propsAnimatedNode == null)
{
throw new InvalidOperationException("Animated node connected to view should be props node.");
}
propsAnimatedNode.RestoreDefaultValues();
}
public void AddAnimatedEventToView(int viewTag, string eventName, JObject eventMapping)
{
var nodeTag = eventMapping.Value<int>("animatedValueTag");
var node = default(AnimatedNode);
if (!_animatedNodes.TryGetValue(nodeTag, out node))
{
throw new InvalidOperationException(
Invariant($"Animated node with tag '{nodeTag}' does not exist."));
}
var valueNode = node as ValueAnimatedNode;
if (valueNode == null)
{
throw new InvalidOperationException(
Invariant($"Animated node connected to event should be of type '{nameof(ValueAnimatedNode)}'."));
}
var pathList = eventMapping["nativeEventPath"].ToObject<string[]>();
var @event = new EventAnimationDriver(pathList, valueNode);
var key = Tuple.Create(viewTag, eventName);
if (_eventDrivers.ContainsKey(key))
{
_eventDrivers[key].Add(@event);
}
else
{
var drivers = new List<EventAnimationDriver>(1);
drivers.Add(@event);
_eventDrivers.Add(key, drivers);
}
}
public void RemoveAnimatedEventFromView(int viewTag, string eventName, int animatedValueTag)
{
var key = Tuple.Create(viewTag, eventName);
if (_eventDrivers.ContainsKey(key))
{
var driversForKey = _eventDrivers[key];
if (driversForKey.Count == 1)
{
_eventDrivers.Remove(key);
}
else
{
for (var i = 0; i < driversForKey.Count; ++i)
{
var driver = driversForKey[i];
if (driver.ValueNode.Tag == animatedValueTag)
{
driversForKey.RemoveAt(i);
break;
}
}
}
}
}
public void OnEventDispatch(Event @event)
{
if (DispatcherHelpers.IsOnDispatcher())
{
HandleEvent(@event);
}
else
{
DispatcherHelpers.RunOnDispatcher(() =>
{
HandleEvent(@event);
});
}
}
private void HandleEvent(Event @event)
{
if (_eventDrivers.Count > 0)
{
var eventName = _customEventNamesResolver(@event.EventName);
var driversForKey = default(IList<EventAnimationDriver>);
if (_eventDrivers.TryGetValue(Tuple.Create(@event.ViewTag, eventName), out driversForKey))
{
foreach (var driver in driversForKey)
{
StopAnimationsForNode(driver.ValueNode);
@event.Dispatch(driver);
_runUpdateNodeList.Add(driver.ValueNode);
}
UpdateNodes(_runUpdateNodeList);
_runUpdateNodeList.Clear();
}
}
}
/// <summary>
/// Animation loop performs BFS over the graph of animated nodes.
/// </summary>
/// <remarks>
/// We use incremented <see cref="_animatedGraphBFSColor"/> to mark
/// nodes as visited in each of the BFS passes, which saves additional
/// loops for clearing "visited" states.
///
/// First BFS starts with nodes that are in <see cref="_updatedNodes" />
/// (this is, their value has been modified from JS in the last batch
/// of JS operations) or directly attached to an active animation
/// (thus linked to objects from <see cref="_activeAnimations"/>). In
/// that step we calculate an attribute <see cref="AnimatedNode.ActiveIncomingNodes"/>.
/// The second BFS runs in topological order over the sub-graph of
/// *active* nodes. This is done by adding nodes to the BFS queue only
/// if all its "predecessors" have already been visited.
/// </remarks>
/// <param name="renderingTime">Frame rendering time.</param>
public void RunUpdates(TimeSpan renderingTime)
{
DispatcherHelpers.AssertOnDispatcher();
var hasFinishedAnimations = false;
_runUpdateNodeList.AddRange(_updatedNodes.Values);
// Clean _updatedNodes queue
_updatedNodes.Clear();
var length = _activeAnimations.Count;
UpdateActiveAnimationIds();
for (var i = 0; i < length; ++i)
{
var animationId = _activeAnimationIds[i];
var animation = _activeAnimations[animationId];
animation.RunAnimationStep(renderingTime);
var valueNode = animation.AnimatedValue;
_runUpdateNodeList.Add(valueNode);
if (animation.HasFinished)
{
hasFinishedAnimations = true;
}
}
UpdateNodes(_runUpdateNodeList);
_runUpdateNodeList.Clear();
// Cleanup finished animations.
if (hasFinishedAnimations)
{
for (var i = 0; i < length; ++i)
{
var animationId = _activeAnimationIds[i];
var animation = _activeAnimations[animationId];
if (animation.HasFinished)
{
animation.EndCallback.Invoke(new JObject
{
{ "finished", true },
});
_activeAnimations.Remove(animationId);
}
}
}
}
private void StopAnimationsForNode(AnimatedNode animatedNode)
{
var length = _activeAnimations.Count;
UpdateActiveAnimationIds();
for (var i = 0; i < length; ++i)
{
var animationId = _activeAnimationIds[i];
var animation = _activeAnimations[animationId];
if (animatedNode == animation.AnimatedValue)
{
// Invoke animation end callback with {finished: false}
animation.EndCallback.Invoke(new JObject
{
{ "finished", false },
});
_activeAnimations.Remove(animationId);
}
}
}
private void UpdateNodes(IList<AnimatedNode> nodes)
{
var activeNodesCount = 0;
var updatedNodesCount = 0;
// STEP 1.
// BFS over graph of nodes starting from ones from `_updatedNodes` and ones that are attached to
// active animations (from `mActiveAnimations)`. Update `ActiveIncomingNodes` property for each node
// during that BFS. Store number of visited nodes in `activeNodesCount`. We "execute" active
// animations as a part of this step.
_animatedGraphBFSColor++; /* use new color */
if (_animatedGraphBFSColor == AnimatedNode.InitialBfsColor)
{
// value "0" is used as an initial color for a new node, using it in BFS may cause some nodes to be skipped.
_animatedGraphBFSColor++;
}
var nodesQueue = new Queue<AnimatedNode>();
foreach (var node in nodes)
{
if (node.BfsColor != _animatedGraphBFSColor)
{
node.BfsColor = _animatedGraphBFSColor;
activeNodesCount++;
nodesQueue.Enqueue(node);
}
}
while (nodesQueue.Count > 0)
{
var nextNode = nodesQueue.Dequeue();
if (nextNode.Children != null)
{
foreach (var child in nextNode.Children)
{
child.ActiveIncomingNodes++;
if (child.BfsColor != _animatedGraphBFSColor)
{
child.BfsColor = _animatedGraphBFSColor;
activeNodesCount++;
nodesQueue.Enqueue(child);
}
}
}
}
// STEP 2
// BFS over the graph of active nodes in topological order -> visit node only when all its
// "predecessors" in the graph have already been visited. It is important to visit nodes in that
// order as they may often use values of their predecessors in order to calculate "next state"
// of their own. We start by determining the starting set of nodes by looking for nodes with
// `ActiveIncomingNodes = 0` (those can only be the ones that we start BFS in the previous
// step). We store number of visited nodes in this step in `updatedNodesCount`
_animatedGraphBFSColor++;
if (_animatedGraphBFSColor == AnimatedNode.InitialBfsColor)
{
// see reasoning for this check a few lines above
_animatedGraphBFSColor++;
}
// find nodes with zero "incoming nodes", those can be either nodes from `mUpdatedNodes` or
// ones connected to active animations
foreach (var node in nodes)
{
if (node.ActiveIncomingNodes == 0 && node.BfsColor != _animatedGraphBFSColor)
{
node.BfsColor = _animatedGraphBFSColor;
updatedNodesCount++;
nodesQueue.Enqueue(node);
}
}
// Run main "update" loop
while (nodesQueue.Count > 0)
{
var nextNode = nodesQueue.Dequeue();
nextNode.Update();
var propsNode = nextNode as PropsAnimatedNode;
var valueNode = default(ValueAnimatedNode);
if (propsNode != null)
{
propsNode.UpdateView();
}
else if ((valueNode = nextNode as ValueAnimatedNode) != null)
{
// Potentially send events to JS when the node's value is updated
valueNode.OnValueUpdate();
}
if (nextNode.Children != null)
{
foreach (var child in nextNode.Children)
{
child.ActiveIncomingNodes--;
if (child.BfsColor != _animatedGraphBFSColor && child.ActiveIncomingNodes == 0)
{
child.BfsColor = _animatedGraphBFSColor;
updatedNodesCount++;
nodesQueue.Enqueue(child);
}
}
}
}
// Verify that we've visited *all* active nodes. Throw otherwise as this would mean there is a
// cycle in animated node graph. We also take advantage of the fact that all active nodes are
// visited in the step above so that all the nodes properties `mActiveIncomingNodes` are set to
// zero
if (activeNodesCount != updatedNodesCount)
{
throw new InvalidOperationException(
Invariant($"Looks like animated nodes graph has cycles, there are {activeNodesCount} but visited only {updatedNodesCount}."));
}
}
internal AnimatedNode GetNodeById(int tag)
{
return GetNode(tag);
}
private AnimatedNode GetNode(int tag)
{
var node = default(AnimatedNode);
if (!_animatedNodes.TryGetValue(tag, out node))
{
throw new InvalidOperationException(
Invariant($"Animated node with tag '{tag}' does not exist."));
}
return node;
}
private void UpdateActiveAnimationIds()
{
if (_activeAnimationIds == null || _activeAnimationIds.Length < _activeAnimations.Count)
{
_activeAnimationIds = new int[_activeAnimations.Count];
}
_activeAnimations.Keys.CopyTo(_activeAnimationIds, 0);
}
private static IReadOnlyDictionary<string, object> GetEventTypes(UIManagerModule uiManager)
{
return (IReadOnlyDictionary<string, object>)uiManager.Constants["customDirectEventTypes"];
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
namespace Elasticsearch.Net
{
public interface IRequestConfiguration
{
/// <summary>
/// The timeout for this specific request, takes precedence over the global timeout settings
/// </summary>
TimeSpan? RequestTimeout { get; set; }
/// <summary>
/// The ping timeout for this specific request
/// </summary>
TimeSpan? PingTimeout { get; set; }
/// <summary>
/// Force a different Content-Type header on the request
/// </summary>
string ContentType { get; set; }
/// <summary>
/// Force a different Accept header on the request
/// </summary>
string Accept { get; set; }
/// <summary>
/// This will override whatever is set on the connection configuration or whatever default the connectionpool has.
/// </summary>
int? MaxRetries { get; set; }
/// <summary>
/// This will force the operation on the specified node, this will bypass any configured connection pool and will no retry.
/// </summary>
Uri ForceNode { get; set; }
/// <summary>
/// Forces no sniffing to occur on the request no matter what configuration is in place
/// globally
/// </summary>
bool? DisableSniff { get; set; }
/// <summary>
/// Under no circumstance do a ping before the actual call. If a node was previously dead a small ping with
/// low connect timeout will be tried first in normal circumstances
/// </summary>
bool? DisablePing { get; set; }
/// <summary>
/// Whether to buffer the request and response bytes for the call
/// </summary>
bool? DisableDirectStreaming { get; set; }
/// <summary>
/// Treat the following statuses (on top of the 200 range) NOT as error.
/// </summary>
IEnumerable<int> AllowedStatusCodes { get; set; }
/// <summary>
/// Basic access authorization credentials to specify with this request.
/// Overrides any credentials that are set at the global IConnectionSettings level.
/// </summary>
BasicAuthenticationCredentials BasicAuthenticationCredentials { get; set; }
/// <summary>
/// Whether or not this request should be pipelined. http://en.wikipedia.org/wiki/HTTP_pipelining defaults to true
/// </summary>
bool EnableHttpPipelining { get; set; }
/// <summary>
/// Submit the request on behalf in the context of a different shield user
/// <pre/>https://www.elastic.co/guide/en/shield/current/submitting-requests-for-other-users.html
/// </summary>
string RunAs { get; set; }
/// <summary>
/// Use the following client certificates to authenticate this single request
/// </summary>
X509CertificateCollection ClientCertificates { get; set; }
}
public class RequestConfiguration : IRequestConfiguration
{
public TimeSpan? RequestTimeout { get; set; }
public TimeSpan? PingTimeout { get; set; }
public string ContentType { get; set; }
public string Accept { get; set; }
public int? MaxRetries { get; set; }
public Uri ForceNode { get; set; }
public bool? DisableSniff { get; set; }
public bool? DisablePing { get; set; }
public bool? DisableDirectStreaming { get; set; }
public IEnumerable<int> AllowedStatusCodes { get; set; }
public BasicAuthenticationCredentials BasicAuthenticationCredentials { get; set; }
public bool EnableHttpPipelining { get; set; } = true;
public CancellationToken CancellationToken { get; set; }
/// <summary>
/// Submit the request on behalf in the context of a different user
/// https://www.elastic.co/guide/en/shield/current/submitting-requests-for-other-users.html
/// </summary>
public string RunAs { get; set; }
public X509CertificateCollection ClientCertificates { get; set; }
}
public class RequestConfigurationDescriptor : IRequestConfiguration
{
private IRequestConfiguration Self => this;
TimeSpan? IRequestConfiguration.RequestTimeout { get; set; }
TimeSpan? IRequestConfiguration.PingTimeout { get; set; }
string IRequestConfiguration.ContentType { get; set; }
string IRequestConfiguration.Accept { get; set; }
int? IRequestConfiguration.MaxRetries { get; set; }
Uri IRequestConfiguration.ForceNode { get; set; }
bool? IRequestConfiguration.DisableSniff { get; set; }
bool? IRequestConfiguration.DisablePing { get; set; }
bool? IRequestConfiguration.DisableDirectStreaming { get; set; }
IEnumerable<int> IRequestConfiguration.AllowedStatusCodes { get; set; }
BasicAuthenticationCredentials IRequestConfiguration.BasicAuthenticationCredentials { get; set; }
bool IRequestConfiguration.EnableHttpPipelining { get; set; } = true;
string IRequestConfiguration.RunAs { get; set; }
X509CertificateCollection IRequestConfiguration.ClientCertificates { get; set; }
public RequestConfigurationDescriptor(IRequestConfiguration config)
{
Self.RequestTimeout = config?.RequestTimeout;
Self.PingTimeout = config?.PingTimeout;
Self.ContentType = config?.ContentType;
Self.Accept = config?.Accept;
Self.MaxRetries = config?.MaxRetries;
Self.ForceNode = config?.ForceNode;
Self.DisableSniff = config?.DisableSniff;
Self.DisablePing = config?.DisablePing;
Self.DisableDirectStreaming = config?.DisableDirectStreaming;
Self.AllowedStatusCodes = config?.AllowedStatusCodes;
Self.BasicAuthenticationCredentials = config?.BasicAuthenticationCredentials;
Self.EnableHttpPipelining = config?.EnableHttpPipelining ?? true;
Self.RunAs = config?.RunAs;
Self.ClientCertificates = config?.ClientCertificates;
}
/// <summary>
/// Submit the request on behalf in the context of a different shield user
/// <pre/>https://www.elastic.co/guide/en/shield/current/submitting-requests-for-other-users.html
/// </summary>
public RequestConfigurationDescriptor RunAs(string username)
{
Self.RunAs = username;
return this;
}
public RequestConfigurationDescriptor RequestTimeout(TimeSpan requestTimeout)
{
Self.RequestTimeout = requestTimeout;
return this;
}
public RequestConfigurationDescriptor PingTimeout(TimeSpan pingTimeout)
{
Self.PingTimeout = pingTimeout;
return this;
}
public RequestConfigurationDescriptor ContentType(string contentTypeHeader)
{
Self.ContentType = contentTypeHeader;
return this;
}
public RequestConfigurationDescriptor Accept(string acceptHeader)
{
Self.Accept = acceptHeader;
return this;
}
public RequestConfigurationDescriptor AllowedStatusCodes(IEnumerable<int> codes)
{
Self.AllowedStatusCodes = codes;
return this;
}
public RequestConfigurationDescriptor AllowedStatusCodes(params int[] codes)
{
Self.AllowedStatusCodes = codes;
return this;
}
public RequestConfigurationDescriptor DisableSniffing(bool? disable = true)
{
Self.DisableSniff = disable;
return this;
}
public RequestConfigurationDescriptor DisablePing(bool? disable = true)
{
Self.DisablePing = disable;
return this;
}
public RequestConfigurationDescriptor DisableDirectStreaming(bool? disable = true)
{
Self.DisableDirectStreaming = disable;
return this;
}
public RequestConfigurationDescriptor ForceNode(Uri uri)
{
Self.ForceNode = uri;
return this;
}
public RequestConfigurationDescriptor MaxRetries(int retry)
{
Self.MaxRetries = retry;
return this;
}
public RequestConfigurationDescriptor BasicAuthentication(string userName, string password)
{
if (Self.BasicAuthenticationCredentials == null)
Self.BasicAuthenticationCredentials = new BasicAuthenticationCredentials();
Self.BasicAuthenticationCredentials.Username = userName;
Self.BasicAuthenticationCredentials.Password = password;
return this;
}
public RequestConfigurationDescriptor EnableHttpPipelining(bool enable = true)
{
Self.EnableHttpPipelining = enable;
return this;
}
/// <summary> Use the following client certificates to authenticate this request to Elasticsearch </summary>
public RequestConfigurationDescriptor ClientCertificates(X509CertificateCollection certificates)
{
Self.ClientCertificates = certificates;
return this;
}
/// <summary> Use the following client certificate to authenticate this request to Elasticsearch </summary>
public RequestConfigurationDescriptor ClientCertificate(X509Certificate certificate) =>
this.ClientCertificates(new X509Certificate2Collection { certificate });
/// <summary> Use the following client certificate to authenticate this request to Elasticsearch </summary>
public RequestConfigurationDescriptor ClientCertificate(string certificatePath) =>
this.ClientCertificates(new X509Certificate2Collection {new X509Certificate(certificatePath)});
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
namespace System.DirectoryServices.ActiveDirectory
{
public enum HourOfDay
{
Zero,
One,
Two,
Three,
Four,
Five,
Six,
Seven,
Eight,
Nine,
Ten,
Eleven,
Twelve,
Thirteen,
Fourteen,
Fifteen,
Sixteen,
Seventeen,
Eighteen,
Nineteen,
Twenty,
TwentyOne,
TwentyTwo,
TwentyThree
}
public enum MinuteOfHour
{
Zero = 0,
Fifteen = 15,
Thirty = 30,
FortyFive = 45
}
public class ActiveDirectorySchedule
{
// 24*7*4 = 672
private readonly bool[] _scheduleArray = new bool[672];
private readonly long _utcOffSet = 0;
public ActiveDirectorySchedule()
{
// need to get the offset between local time and UTC time
#pragma warning disable 612, 618
_utcOffSet = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).Ticks / TimeSpan.TicksPerHour;
#pragma warning restore 612, 618
}
public ActiveDirectorySchedule(ActiveDirectorySchedule schedule) : this()
{
if (schedule == null)
throw new ArgumentNullException();
bool[] tmpSchedule = schedule._scheduleArray;
for (int i = 0; i < 672; i++)
_scheduleArray[i] = tmpSchedule[i];
}
internal ActiveDirectorySchedule(bool[] schedule) : this()
{
for (int i = 0; i < 672; i++)
_scheduleArray[i] = schedule[i];
}
public bool[,,] RawSchedule
{
get
{
bool[,,] tmp = new bool[7, 24, 4];
for (int i = 0; i < 7; i++)
for (int j = 0; j < 24; j++)
for (int k = 0; k < 4; k++)
tmp[i, j, k] = _scheduleArray[i * 24 * 4 + j * 4 + k];
return tmp;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
ValidateRawArray(value);
for (int i = 0; i < 7; i++)
for (int j = 0; j < 24; j++)
for (int k = 0; k < 4; k++)
_scheduleArray[i * 24 * 4 + j * 4 + k] = value[i, j, k];
}
}
public void SetSchedule(DayOfWeek day, HourOfDay fromHour, MinuteOfHour fromMinute, HourOfDay toHour, MinuteOfHour toMinute)
{
if (day < DayOfWeek.Sunday || day > DayOfWeek.Saturday)
throw new InvalidEnumArgumentException(nameof(day), (int)day, typeof(DayOfWeek));
if (fromHour < HourOfDay.Zero || fromHour > HourOfDay.TwentyThree)
throw new InvalidEnumArgumentException(nameof(fromHour), (int)fromHour, typeof(HourOfDay));
if (fromMinute != MinuteOfHour.Zero && fromMinute != MinuteOfHour.Fifteen && fromMinute != MinuteOfHour.Thirty && fromMinute != MinuteOfHour.FortyFive)
throw new InvalidEnumArgumentException(nameof(fromMinute), (int)fromMinute, typeof(MinuteOfHour));
if (toHour < HourOfDay.Zero || toHour > HourOfDay.TwentyThree)
throw new InvalidEnumArgumentException(nameof(toHour), (int)toHour, typeof(HourOfDay));
if (toMinute != MinuteOfHour.Zero && toMinute != MinuteOfHour.Fifteen && toMinute != MinuteOfHour.Thirty && toMinute != MinuteOfHour.FortyFive)
throw new InvalidEnumArgumentException(nameof(toMinute), (int)toMinute, typeof(MinuteOfHour));
// end time should be later than the start time
if ((int)fromHour * 60 + (int)fromMinute > (int)toHour * 60 + (int)toMinute)
throw new ArgumentException(SR.InvalidTime);
// set the availability
int startPoint = (int)day * 24 * 4 + (int)fromHour * 4 + (int)fromMinute / 15;
int endPoint = (int)day * 24 * 4 + (int)toHour * 4 + (int)toMinute / 15;
for (int i = startPoint; i <= endPoint; i++)
_scheduleArray[i] = true;
}
public void SetSchedule(DayOfWeek[] days, HourOfDay fromHour, MinuteOfHour fromMinute, HourOfDay toHour, MinuteOfHour toMinute)
{
if (days == null)
throw new ArgumentNullException(nameof(days));
for (int i = 0; i < days.Length; i++)
{
if (days[i] < DayOfWeek.Sunday || days[i] > DayOfWeek.Saturday)
throw new InvalidEnumArgumentException(nameof(days), (int)days[i], typeof(DayOfWeek));
}
for (int i = 0; i < days.Length; i++)
SetSchedule(days[i], fromHour, fromMinute, toHour, toMinute);
}
public void SetDailySchedule(HourOfDay fromHour, MinuteOfHour fromMinute, HourOfDay toHour, MinuteOfHour toMinute)
{
for (int i = 0; i < 7; i++)
{
SetSchedule((DayOfWeek)i, fromHour, fromMinute, toHour, toMinute);
}
}
public void ResetSchedule()
{
for (int i = 0; i < 672; i++)
_scheduleArray[i] = false;
}
private void ValidateRawArray(bool[,,] array)
{
if (array.Length != 672)
throw new ArgumentException("value");
int len1 = array.GetLength(0);
int len2 = array.GetLength(1);
int len3 = array.GetLength(2);
if (len1 != 7 || len2 != 24 || len3 != 4)
throw new ArgumentException("value");
}
internal byte[] GetUnmanagedSchedule()
{
byte val = 0;
int index = 0;
byte[] unmanagedSchedule = new byte[188];
int unmanagedScheduleIndex = 0;
// set size
unmanagedSchedule[0] = 188;
// set number of schedule
unmanagedSchedule[8] = 1;
// set offset
unmanagedSchedule[16] = 20;
// 20 is the offset in the unmanaged structure where the actual schedule begins
for (int i = 20; i < 188; i++)
{
val = 0;
index = (i - 20) * 4;
if (_scheduleArray[index])
val |= 1;
if (_scheduleArray[index + 1])
val |= 2;
if (_scheduleArray[index + 2])
val |= 4;
if (_scheduleArray[index + 3])
val |= 8;
//recalculate index position taking utc offset into account
//ensure circular array in both directions (with index from 20 to 187)
unmanagedScheduleIndex = i - (int)_utcOffSet;
if (unmanagedScheduleIndex >= 188)
{
// falling off higher end (move back)
unmanagedScheduleIndex = unmanagedScheduleIndex - 188 + 20;
}
else if (unmanagedScheduleIndex < 20)
{
// falling off lower end (move forward)
unmanagedScheduleIndex = 188 - (20 - unmanagedScheduleIndex);
}
unmanagedSchedule[unmanagedScheduleIndex] = val;
}
return unmanagedSchedule;
}
internal void SetUnmanagedSchedule(byte[] unmanagedSchedule)
{
int val = 0;
int index = 0;
int unmanagedScheduleIndex = 0;
// 20 is the offset in the unmanaged structure where the actual schedule begins
for (int i = 20; i < 188; i++)
{
val = 0;
index = (i - 20) * 4;
//recalculate index position taking utc offset into account
//ensure circular array in both directions (with index from 20 to 187)
unmanagedScheduleIndex = i - (int)_utcOffSet;
if (unmanagedScheduleIndex >= 188)
{
// falling off higher end (move back)
unmanagedScheduleIndex = unmanagedScheduleIndex - 188 + 20;
}
else if (unmanagedScheduleIndex < 20)
{
// falling off lower end (move forward)
unmanagedScheduleIndex = 188 - (20 - unmanagedScheduleIndex);
}
val = unmanagedSchedule[unmanagedScheduleIndex];
if ((val & 1) != 0)
_scheduleArray[index] = true;
if ((val & 2) != 0)
_scheduleArray[index + 1] = true;
if ((val & 4) != 0)
_scheduleArray[index + 2] = true;
if ((val & 8) != 0)
_scheduleArray[index + 3] = true;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using VersionOne.SDK.APIClient;
using VersionOne.SDK.ObjectModel.Filters;
using VersionOne.SDK.ObjectModel.List;
namespace VersionOne.SDK.ObjectModel {
public partial class V1Instance {
/// <summary>
/// Get various assets in the system
/// </summary>
public GetMethods Get {
get { return get ?? (get = new GetMethods(this)); }
}
private GetMethods get;
/// <summary>
/// Methods to get things
/// </summary>
public class GetMethods {
private readonly V1Instance instance;
internal GetMethods(V1Instance instance) {
this.instance = instance;
}
#region Get By Filter
private IAssetType ResolveAssetType(Type type) {
return instance.MetaModel.GetAssetType(GetAssetTypeToken(type));
}
internal ICollection<T> Get<T>(EntityFilter filter) where T : Entity {
// The returned entity type is determined by
// 1) the filter passed in or 2) the type of T if there is no filter.
var targetEntityType = filter != null ? filter.EntityType : typeof (T);
var type = ResolveAssetType(targetEntityType);
var query = new Query(type);
if (filter != null) {
var defaultToken = GetDefaultOrderByToken(targetEntityType);
IAttributeDefinition defaultOrderBy = null;
if(defaultToken != null) {
defaultOrderBy = instance.MetaModel.GetAttributeDefinition(defaultToken);
}
query.Filter = filter.BuildFilter(type, instance);
query.Find = filter.BuildFind(type);
query.OrderBy = filter.BuildOrderBy(type, defaultOrderBy);
query.Selection = filter.BuildSelection(type);
}
return instance.QueryToEntityEnum<T>(query);
}
/// <summary>
/// Get attachments filtered by the criteria specified in the passed in filter.
/// </summary>
/// <param name="filter">Limit the items returned. If null, then all items returned.</param>
/// <returns>ICollection of items as specified in the filter.</returns>
public ICollection<Attachment> Attachments(AttachmentFilter filter) {
return Get<Attachment>(filter ?? new AttachmentFilter());
}
/// <summary>
/// Get notes filtered by the criteria specified in the passed in filter.
/// </summary>
/// <param name="filter">Limit the items returned. If null, then all items returned.</param>
/// <returns>ICollection of items as specified in the filter.</returns>
public ICollection<Note> Notes(NoteFilter filter) {
return Get<Note>(filter ?? new NoteFilter());
}
/// <summary>
/// Get links filtered by the criteria specified in the passed in filter.
/// </summary>
/// <param name="filter">Limit the items returned. If null, then all items returned.</param>
/// <returns>ICollection of items as specified in the filter.</returns>
public ICollection<Link> Links(LinkFilter filter) {
return Get<Link>(filter ?? new LinkFilter());
}
/// <summary>
/// Get effort records filtered by the criteria specified in the passed in filter.
/// </summary>
/// <param name="filter">Limit the items returned. If null, then all items returned.</param>
/// <returns>ICollection of items as specified in the filter.</returns>
public ICollection<Effort> EffortRecords(EffortFilter filter) {
return Get<Effort>(filter ?? new EffortFilter());
}
/// <summary>
/// Get assets filtered by the criteria specified in the passed in filter.
/// </summary>
/// <param name="filter">Limit the items returned. If null, then all items returned.</param>
/// <returns>ICollection of items as specified in the filter.</returns>
public ICollection<BaseAsset> BaseAssets(BaseAssetFilter filter) {
return Get<BaseAsset>(filter ?? new BaseAssetFilter());
}
/// <summary>
/// Get stories filtered by the criteria specified in the passed in filter.
/// </summary>
/// <param name="filter">Limit the items returned. If null, then all items returned.</param>
/// <returns>ICollection of items as specified in the filter.</returns>
public ICollection<Story> Stories(StoryFilter filter) {
return Get<Story>(filter ?? new StoryFilter());
}
/// <summary>
/// Get Epics filtered by the criteria specified in the passed in filter.
/// </summary>
/// <param name="filter">Limit the items returned. If null, then all items returned.</param>
/// <returns>ICollection of items as specified in the filter.</returns>
public ICollection<Epic> Epics(EpicFilter filter) {
return Get<Epic>(filter ?? new EpicFilter());
}
/// <summary>
/// Get defects filtered by the criteria specified in the passed in filter.
/// </summary>
/// <param name="filter">Limit the items returned. If null, then all items returned.</param>
/// <returns>ICollection of items as specified in the filter.</returns>
public ICollection<Defect> Defects(DefectFilter filter) {
return Get<Defect>(filter ?? new DefectFilter());
}
/// <summary>
/// Get primary workitems (stories and defects) filtered by the criteria specified in the passed in filter.
/// </summary>
/// <param name="filter">Limit the items returned. If null, then all items returned.</param>
/// <returns>ICollection of items as specified in the filter.</returns>
public ICollection<PrimaryWorkitem> PrimaryWorkitems(PrimaryWorkitemFilter filter) {
return Get<PrimaryWorkitem>(filter ?? new PrimaryWorkitemFilter());
}
/// <summary>
/// Get workitems (stories, defects, tasks, and tests) filtered by the criteria specified in the passed in filter.
/// </summary>
/// <param name="filter">Limit the items returned. If null, then all items returned.</param>
/// <returns>ICollection of items as specified in the filter.</returns>
public ICollection<Workitem> Workitems(WorkitemFilter filter) {
return Get<Workitem>(filter ?? new WorkitemFilter());
}
/// <summary>
/// Get secondary workitems (tasks and tests) filtered by the criteria specified in the passed in filter.
/// </summary>
/// <param name="filter">Limit the items returned. If null, then all items returned.</param>
/// <returns>ICollection of items as specified in the filter.</returns>
public ICollection<SecondaryWorkitem> SecondaryWorkitems(SecondaryWorkitemFilter filter) {
return Get<SecondaryWorkitem>(filter ?? new SecondaryWorkitemFilter());
}
/// <summary>
/// Get tasks filtered by the criteria specified in the passed in filter.
/// </summary>
/// <param name="filter">Limit the items returned. If null, then all items returned.</param>
/// <returns>ICollection of items as specified in the filter.</returns>
public ICollection<Task> Tasks(TaskFilter filter) {
return Get<Task>(filter ?? new TaskFilter());
}
/// <summary>
/// Get Tests filtered by the criteria specified in the passed in filter.
/// </summary>
/// <param name="filter">Limit the items returned. If null, then all items returned.</param>
/// <returns>ICollection of items as specified in the filter.</returns>
public ICollection<Test> Tests(TestFilter filter) {
return Get<Test>(filter ?? new TestFilter());
}
/// <summary>
/// Get iterations filtered by the criteria specified in the passed in filter.
/// </summary>
/// <param name="filter">Limit the items returned. If null, then all items returned.</param>
/// <returns>ICollection of items as specified in the filter.</returns>
public ICollection<Iteration> Iterations(IterationFilter filter) {
return Get<Iteration>(filter ?? new IterationFilter());
}
/// <summary>
/// Get projects filtered by the criteria specified in the passed in filter.
/// </summary>
/// <param name="filter">Limit the items returned. If null, then all items returned.</param>
/// <returns>ICollection of items as specified in the filter.</returns>
public ICollection<Project> Projects(ProjectFilter filter) {
return Get<Project>(filter ?? new ProjectFilter());
}
/// <summary>
/// Get regression plans filtered by the criteria specified in the passed in filter.
/// </summary>
/// <param name="filter">Limit the items returned. If null, then all items are returned.</param>
/// <returns>ICollection of items as specified in the filter.</returns>
public ICollection<RegressionPlan> RegressionPlans(RegressionPlanFilter filter) {
return Get<RegressionPlan>(filter ?? new RegressionPlanFilter());
}
/// <summary>
/// Get Regression Suite filtered by the criteria specified in the passed in filter.
/// </summary>
/// <param name="filter">Limit the items returned. If null, then all items are returned.</param>
/// <returns>ICollection of items as specified in the filter.</returns>
public ICollection<RegressionSuite> RegressionSuites(RegressionSuiteFilter filter) {
return Get<RegressionSuite>(filter ?? new RegressionSuiteFilter());
}
/// <summary>
/// Get Regression Tests filtered by the criteria specified in the passed in filter.
/// </summary>
/// <param name="filter">Limit the items returned. If null, then all items are returned.</param>
/// <returns>ICollection of items as specified in the filter.</returns>
public ICollection<RegressionTest> RegressionTests(RegressionTestFilter filter) {
return Get<RegressionTest>(filter ?? new RegressionTestFilter());
}
/// <summary>
/// Get Test Sets filtered by the criteria specified in the passed in filter.
/// </summary>
/// <param name="filter">Limit the items returned. If null, then all items are returned.</param>
/// <returns>ICollection of items as specified in the filter.</returns>
public ICollection<TestSet> TestSets(TestSetFilter filter) {
return Get<TestSet>(filter ?? new TestSetFilter());
}
/// <summary>
/// Get Environment filtered by the criteria specified in the passed in filter.
/// </summary>
/// <param name="filter"></param>
/// <returns></returns>
public ICollection<Environment> Environments(EnvironmentFilter filter) {
return Get<Environment>(filter ?? new EnvironmentFilter());
}
/// <summary>
/// Get schedules filtered by the criteria specified in the passed in filter.
/// </summary>
/// <param name="filter">Limit the items returned. If null, then all items returned.</param>
/// <returns>ICollection of items as specified in the filter.</returns>
public ICollection<Schedule> Schedules(ScheduleFilter filter) {
return Get<Schedule>(filter ?? new ScheduleFilter());
}
/// <summary>
/// Get teams filtered by the criteria specified in the passed in filter.
/// </summary>
/// <param name="filter">Limit the items returned. If null, then all items returned.</param>
/// <returns>ICollection of items as specified in the filter.</returns>
public ICollection<Team> Teams(TeamFilter filter) {
return Get<Team>(filter ?? new TeamFilter());
}
/// <summary>
/// Get themes filtered by the criteria specified in the passed in filter.
/// </summary>
/// <param name="filter">Limit the items returned. If null, then all items returned.</param>
/// <returns>ICollection of items as specified in the filter.</returns>
public ICollection<Theme> Themes(ThemeFilter filter) {
return Get<Theme>(filter ?? new ThemeFilter());
}
/// <summary>
/// Get Members filtered by the criteria specified in the passed in filter.
/// </summary>
/// <param name="filter">Limit the items returned. If null, then all items returned.</param>
/// <returns>ICollection of items as specified in the filter.</returns>
public ICollection<Member> Members(MemberFilter filter) {
return Get<Member>(filter ?? new MemberFilter());
}
/// <summary>
/// Get Requests filtered by the criteria specified in the passed in filter.
/// </summary>
/// <param name="filter">Limit the items returned. If null, then all items returned.</param>
/// <returns>ICollection of items as specified in the filter.</returns>
public ICollection<Request> Requests(RequestFilter filter) {
return Get<Request>(filter ?? new RequestFilter());
}
/// <summary>
/// Get Goals filtered by the criteria specified in the passed in filter.
/// </summary>
/// <param name="filter">Limit the items returned. If null, then all items returned.</param>
/// <returns>ICollection of items as specified in the filter.</returns>
public ICollection<Goal> Goals(GoalFilter filter) {
return Get<Goal>(filter ?? new GoalFilter());
}
/// <summary>
/// Get Issues filtered by the criteria specified in the passed in filter.
/// </summary>
/// <param name="filter">Limit the items returned. If null, then all items returned.</param>
/// <returns>ICollection of items as specified in the filter.</returns>
public ICollection<Issue> Issues(IssueFilter filter) {
return Get<Issue>(filter ?? new IssueFilter());
}
/// <summary>
/// Get Retrospective filtered by the criteria specified in the passed in filter.
/// </summary>
/// <param name="filter">Limit the items returned. If null, then all items returned.</param>
/// <returns>ICollection of items as specified in the filter.</returns>
public ICollection<Retrospective> Retrospectives(RetrospectiveFilter filter) {
return Get<Retrospective>(filter ?? new RetrospectiveFilter());
}
/// <summary>
/// Get Build Runs filtered by the criteria specified in the passed in filter.
/// </summary>
/// <param name="filter">Limit the items returned. If null, then all items returned.</param>
/// <returns>ICollection of items as specified in the filter.</returns>
public ICollection<BuildRun> BuildRuns(BuildRunFilter filter) {
return Get<BuildRun>(filter ?? new BuildRunFilter());
}
/// <summary>
/// Get Build Projects filtered by the criteria specified in the passed in filter.
/// </summary>
/// <param name="filter">Limit the items returned. If null, then all items returned.</param>
/// <returns>ICollection of items as specified in the filter.</returns>
public ICollection<BuildProject> BuildProjects(BuildProjectFilter filter) {
return Get<BuildProject>(filter ?? new BuildProjectFilter());
}
/// <summary>
/// Get ChangeSets filtered by the criteria specified in the passed in filter.
/// </summary>
/// <param name="filter">Limit the items returned. If null, then all items returned.</param>
/// <returns>ICollection of items as specified in the filter.</returns>
public ICollection<ChangeSet> ChangeSets(ChangeSetFilter filter) {
return Get<ChangeSet>(filter ?? new ChangeSetFilter());
}
/// <summary>
/// Get Messages filtered by the criteria specified in the passed in filter.
/// </summary>
/// <param name="filter">Limit the items returned. If null, then all items returned.</param>
/// <returns>ICollection of items as specified in the filter.</returns>
public ICollection<Message> Messages(MessageFilter filter) {
return Get<Message>(filter ?? new MessageFilter());
}
/// <summary>
/// Get Conversation filtered by the criteria specified in the passed filter.
/// </summary>
/// <param name="filter">Limit the items returned. If null, then all items returned.</param>
/// <returns>ICollection of the items as specified in the filter.</returns>
public ICollection<Conversation> Conversations(ConversationFilter filter) {
return Get<Conversation>(filter ?? new ConversationFilter());
}
/// <summary>
/// Get Expression filtered by the criteria specified in the passed filter.
/// </summary>
/// <param name="filter">Limit the items returned. If null, then all items returned.</param>
/// <returns>ICollection of the items as specified in the filter.</returns>
public ICollection<Expression> Expressions(ExpressionFilter filter)
{
return Get<Expression>(filter ?? new ExpressionFilter());
}
internal ICollection<MessageReceipt> MessageReceipts(MessageReceiptFilter filter) {
return Get<MessageReceipt>(filter ?? new MessageReceiptFilter());
}
/// <summary>
/// Get tracked Epics for enlisted Projects.
/// </summary>
public ICollection<Epic> TrackedEpics(ICollection<Project> projects) {
return Get<Epic>(new TrackedEpicFilter(projects));
}
#endregion
#region Get By ID Methods
/// <summary>
/// Returns a project with the given ID or null if the ID is invalid
/// </summary>
/// <param name="id">ID of the project to retrieve</param>
/// <returns>an instance of a Project or null if ID is invalid</returns>
public Project ProjectByID(AssetID id) {
return GetByID<Project>(id);
}
/// <summary>
/// Returns a schedule with the given ID or null if the ID is invalid
/// </summary>
/// <param name="id">ID of the schedule to retrieve</param>
/// <returns>an instance of a Schedule or null if ID is invalid</returns>
public Schedule ScheduleByID(AssetID id) {
return GetByID<Schedule>(id);
}
/// <summary>
/// Returns an iteration with the given ID or null if the ID is invalid
/// </summary>
/// <param name="id">ID of the iteration to retrieve</param>
/// <returns>an instance of an Iteration or null if ID is invalid</returns>
public Iteration IterationByID(AssetID id) {
return GetByID<Iteration>(id);
}
/// <summary>
/// Returns a retrospective with the given ID or null if the ID is invalid
/// </summary>
/// <param name="id">ID of the iteration to retrieve</param>
/// <returns>an instance of a retrospective or null if ID is invalid</returns>
public Retrospective RetrospectiveByID(AssetID id) {
return GetByID<Retrospective>(id);
}
/// <summary>
/// Returns a Member with the given ID or null if the ID is invalid
/// </summary>
/// <param name="id">ID of the Member to retrieve</param>
/// <returns>an instance of a Member or null if ID is invalid</returns>
public Member MemberByID(AssetID id) {
return GetByID<Member>(id);
}
/// <summary>
/// Returns a Team with the given ID or null if the ID is invalid
/// </summary>
/// <param name="id">ID of the Team to retrieve</param>
/// <returns>an instance of a Team or null if ID is invalid</returns>
public Team TeamByID(AssetID id) {
return GetByID<Team>(id);
}
/// <summary>
/// Returns a Story with the given ID or null if the ID is invalid
/// </summary>
/// <param name="id">ID of the Story to retrieve</param>
/// <returns>an instance of a story or null if ID is invalid</returns>
public Story StoryByID(AssetID id) {
return GetByID<Story>(id);
}
/// <summary>
/// Returns a Defect with the given ID or null if the ID is invalid
/// </summary>
/// <param name="id">ID of the Defect to retrieve</param>
/// <returns>an instance of a Defect or null if ID is invalid</returns>
public Defect DefectByID(AssetID id) {
return GetByID<Defect>(id);
}
/// <summary>
/// Returns an Issue with the given ID or null if the ID is invalid
/// </summary>
/// <param name="id">ID of the Issue to retrieve</param>
/// <returns>an instance of a Issue or null if ID is invalid</returns>
public Issue IssueByID(AssetID id) {
return GetByID<Issue>(id);
}
/// <summary>
/// Returns a Request with the given ID or null if the ID is invalid
/// </summary>
/// <param name="id">ID of the Request to retrieve</param>
/// <returns>an instance of a Request or null if ID is invalid</returns>
public Request RequestByID(AssetID id) {
return GetByID<Request>(id);
}
/// <summary>
/// Returns a Theme with the given ID or null if the ID is invalid
/// </summary>
/// <param name="id">ID of the Theme to retrieve</param>
/// <returns>an instance of a Theme or null if ID is invalid</returns>
public Theme ThemeByID(AssetID id) {
return GetByID<Theme>(id);
}
/// <summary>
/// Returns a Goal with the given ID or null if the ID is invalid
/// </summary>
/// <param name="id">ID of the Goal to retrieve</param>
/// <returns>an instance of a Goal or null if ID is invalid</returns>
public Goal GoalByID(AssetID id) {
return GetByID<Goal>(id);
}
/// <summary>
/// Returns a Epic with the given ID or null if the ID is invalid
/// </summary>
/// <param name="id">ID of the Epic to retrieve</param>
/// <returns>an instance of a Epic or null if ID is invalid</returns>
public Epic EpicByID(AssetID id) {
return GetByID<Epic>(id);
}
/// <summary>
/// Returns a StoryTemplate with the given ID or null if the ID is invalid
/// </summary>
/// <param name="id">ID of the StoryTemplate to retrieve</param>
/// <returns>an instance of a StoryTemplate or null if ID is invalid</returns>
public StoryTemplate StoryTemplateByID(AssetID id) {
return GetByID<StoryTemplate>(id);
}
/// <summary>
/// Returns a DefectTemplate with the given ID or null if the ID is invalid
/// </summary>
/// <param name="id">ID of the DefectTemplate to retrieve</param>
/// <returns>an instance of a DefectTemplate or null if ID is invalid</returns>
public DefectTemplate DefectTemplateByID(AssetID id) {
return GetByID<DefectTemplate>(id);
}
/// <summary>
/// Returns a Note with the given ID or null if the ID is invalid
/// </summary>
/// <param name="id">ID of the Note to retrieve</param>
/// <returns>an instance of a Note or null if ID is invalid</returns>
public Note NoteByID(AssetID id) {
return GetByID<Note>(id);
}
/// <summary>
/// Returns a Link with the given ID or null if the ID is invalid
/// </summary>
/// <param name="id">ID of the Link to retrieve</param>
/// <returns>an instance of a Link or null if ID is invalid</returns>
public Link LinkByID(AssetID id) {
return GetByID<Link>(id);
}
/// <summary>
/// Returns an Attachment with the given ID or null if the ID is invalid
/// </summary>
/// <param name="id">ID of the Attachment to retrieve</param>
/// <returns>an instance of an Attachment or null if ID is invalid</returns>
public Attachment AttachmentByID(AssetID id) {
return GetByID<Attachment>(id);
}
/// <summary>
/// Returns a TestSuite with the given ID or null if the ID is invalid
/// </summary>
/// <param name="id">ID of the TestSuite to retrieve</param>
/// <returns>an instance of a TestSuite or null if ID is invalid</returns>
public TestSuite TestSuiteByID(AssetID id) {
return GetByID<TestSuite>(id);
}
/// <summary>
/// Returns an Effort Record with the given ID or null if the ID is invalid
/// </summary>
/// <param name="id">ID of the Effort Record to retrieve</param>
/// <returns>an instance of an Effort Record or null if ID is invalid</returns>
public Effort EffortByID(AssetID id) {
return GetByID<Effort>(id);
}
/// <summary>
/// Returns a Primary Workitem with the given ID or null if the ID is invalid
/// </summary>
/// <param name="id">ID of the Primary Workitem to retrieve</param>
/// <returns>an instance of a Primary Workitem or null if ID is invalid</returns>
public PrimaryWorkitem PrimaryWorkitemByID(AssetID id) {
return GetByID<PrimaryWorkitem>(id);
}
/// <summary>
/// Returns a Secondary Workitem with the given ID or null if the ID is invalid
/// </summary>
/// <param name="id">ID of the Secondary Workitem to retrieve</param>
/// <returns>an instance of a Secondary Workitem or null if ID is invalid</returns>
public SecondaryWorkitem SecondaryWorkitemByID(AssetID id) {
return GetByID<SecondaryWorkitem>(id);
}
/// <summary>
/// Returns a Workitem with the given ID or null if the ID is invalid
/// </summary>
/// <param name="id">ID of the Workitem to retrieve</param>
/// <returns>an instance of a Workitem or null if ID is invalid</returns>
public Workitem WorkitemByID(AssetID id) {
return GetByID<Workitem>(id);
}
/// <summary>
/// Returns a BaseAsset with the given ID or null if the ID is invalid
/// </summary>
/// <param name="id">ID of the BaseAsset to retrieve</param>
/// <returns>an instance of a BaseAsset or null if ID is invalid</returns>
public BaseAsset BaseAssetByID(AssetID id) {
return GetByID<BaseAsset>(id);
}
/// <summary>
/// Returns a Build Run with the given ID or null if the ID is invalid
/// </summary>
/// <param name="id">ID of the Build Run to retrieve</param>
/// <returns>an instance of a Build Run or null if ID is invalid</returns>
public BuildRun BuildRunByID(AssetID id) {
return GetByID<BuildRun>(id);
}
/// <summary>
/// Returns a Build Project with the given ID or null if the ID is invalid
/// </summary>
/// <param name="id">ID of the Build Project to retrieve</param>
/// <returns>an instance of a Build Project or null if ID is invalid</returns>
public BuildProject BuildProjectByID(AssetID id) {
return GetByID<BuildProject>(id);
}
/// <summary>
/// Returns a ChangeSet with the given ID or null if the ID is invalid
/// </summary>
/// <param name="id">ID of the ChangeSet to retrieve</param>
/// <returns>an instance of a ChangeSet or null if ID is invalid</returns>
public ChangeSet ChangeSetByID(AssetID id) {
return GetByID<ChangeSet>(id);
}
/// <summary>
/// Returns a RegressionPlan with the given ID or null if the ID is invalid
/// </summary>
/// <param name="id">ID of the RegressionPlan to retrieve</param>
/// <returns>an instance of a RegressionPlan or null if ID is invalid</returns>
public RegressionPlan RegressionPlanByID(AssetID id) {
return GetByID<RegressionPlan>(id);
}
/// <summary>
/// Returns a Regression Suite with the given ID or null if the ID is invalid
/// </summary>
/// <param name="id">ID of the Regression Suite to retrieve</param>
/// <returns>an instance of a Regression Suite or null if ID is invalid</returns>
public RegressionSuite RegressionSuiteByID(AssetID id) {
return GetByID<RegressionSuite>(id);
}
/// <summary>
/// Returns a Regression Test with the given ID or null if the ID is invalid
/// </summary>
/// <param name="id">ID of the Regression Test to retrieve</param>
/// <returns>an instance of a Regression Test or null if ID is invalid</returns>
public RegressionTest RegressionTestByID(AssetID id) {
return GetByID<RegressionTest>(id);
}
/// <summary>
/// Returns a Test Set with the given ID or null if the ID is invalid
/// </summary>
/// <param name="id">ID of the Test Set to retrieve</param>
/// <returns>an instance of a Test Set or null if ID is invalid</returns>
public TestSet TestSetByID(AssetID id) {
return GetByID<TestSet>(id);
}
/// <summary>
/// Returns a Environment with the given ID or null if the ID is invalid
/// </summary>
/// <param name="id">ID of the Environment to retrieve</param>
/// <returns>an instance of a Environment or null if ID is invalid</returns>
public Environment EnvironmentByID(AssetID id) {
return GetByID<Environment>(id);
}
/// <summary>
/// Returns a Conversation with the given ID or null if the ID is invalid.
/// </summary>
/// <param name="id">ID of the Conversation to retrieve.</param>
/// <returns>an instance of an Conversation or null if ID is invalid.</returns>
public Conversation ConversationByID(AssetID id) {
return GetByID<Conversation>(id);
}
/// <summary>
/// Returns a Expression with the given ID or null if the ID is invalid.
/// </summary>
/// <param name="id">ID of the Expression to retrieve.</param>
/// <returns>an instance of an Expression or null if ID is invalid.</returns>
public Expression ExpressionByID(AssetID id)
{
return GetByID<Expression>(id);
}
/// <summary>
/// Returns an Entity of Type T with the given ID or null if the ID is invalid
/// </summary>
/// <typeparam name="T">Entity Type to retrieve</typeparam>
/// <param name="id">ID of the Entity to retrieve</param>
/// <returns>an instance of an Entity of Type T or null if ID is invalid</returns>
public T GetByID<T>(AssetID id) where T : Entity {
return instance.wrapperManager.Create<T>(id, true);
}
#endregion
#region GetByDisplayID
/// <summary>
/// Returns an Entity of Type T with the given ID or null if the ID is invalid
/// </summary>
/// <typeparam name="T">Entity Type to retrieve</typeparam>
/// <param name="displayID">DisplayID of the Entity to retrieve</param>
/// <returns>an instance of an Entity of Type T or null if ID is invalid</returns>
public T GetByDisplayID<T>(string displayID) where T : ProjectAsset {
var assetTypeToken = GetAssetTypeToken(typeof (T));
var projectAssetType = instance.MetaModel.GetAssetType(assetTypeToken);
var idDef = projectAssetType.GetAttributeDefinition("Number");
var query = new Query(projectAssetType);
var idTerm = new FilterTerm(idDef);
idTerm.Equal(displayID);
query.Filter = idTerm;
var result = instance.Services.Retrieve(query);
if(result.Assets.Count == 0) {
return null;
}
var asset = result.Assets[0];
// need to validate here to make sure the DisplayID is for the proper type
// This is a problem with Epics and Stories.
return instance.wrapperManager.Create<T>(asset.Oid.Token, true);
}
/// <summary>
/// Returns a Story with the given ID or null if the ID is invalid
/// </summary>
/// <param name="displayID">DisplayID of the Story to retrieve</param>
/// <returns>an instance of a story or null if ID is invalid</returns>
public Story StoryByDisplayID(string displayID) {
return GetByDisplayID<Story>(displayID);
}
/// <summary>
/// Returns a Defect with the given ID or null if the ID is invalid
/// </summary>
/// <param name="displayID">DisplayID of the Defect to retrieve</param>
/// <returns>an instance of a Defect or null if ID is invalid</returns>
public Defect DefectByDisplayID(string displayID) {
return GetByDisplayID<Defect>(displayID);
}
/// <summary>
/// Returns a TestSet with the given ID or null if the ID is invalid
/// </summary>
/// <param name="displayID">DisplayID of the TestSet to retrieve</param>
/// <returns>an instance of a TestSet or null if ID is invalid</returns>
public TestSet TestSetByDisplayID(string displayID) {
return GetByDisplayID<TestSet>(displayID);
}
/// <summary>
/// Returns an Issue with the given ID or null if the ID is invalid
/// </summary>
/// <param name="displayID">DisplayID of the Issue to retrieve</param>
/// <returns>an instance of a Issue or null if ID is invalid</returns>
public Issue IssueByDisplayID(string displayID) {
return GetByDisplayID<Issue>(displayID);
}
/// <summary>
/// Returns a Request with the given ID or null if the ID is invalid
/// </summary>
/// <param name="displayID">DisplayID of the Request to retrieve</param>
/// <returns>an instance of a Request or null if ID is invalid</returns>
public Request RequestByDisplayID(string displayID) {
return GetByDisplayID<Request>(displayID);
}
/// <summary>
/// Returns a Theme with the given ID or null if the ID is invalid
/// </summary>
/// <param name="displayID">DisplayID of the Theme to retrieve</param>
/// <returns>an instance of a Theme or null if ID is invalid</returns>
public Theme ThemeByDisplayID(string displayID) {
return GetByDisplayID<Theme>(displayID);
}
/// <summary>
/// Returns a Goal with the given ID or null if the ID is invalid
/// </summary>
/// <param name="displayID">DisplayID of the Goal to retrieve</param>
/// <returns>an instance of a Goal or null if ID is invalid</returns>
public Goal GoalByDisplayID(string displayID) {
return GetByDisplayID<Goal>(displayID);
}
/// <summary>
/// Returns a Epic with the given ID or null if the ID is invalid
/// </summary>
/// <param name="displayID">DisplayID of the Epic to retrieve</param>
/// <returns>an instance of a Epic or null if ID is invalid</returns>
public Epic EpicByDisplayID(string displayID) {
return GetByDisplayID<Epic>(displayID);
}
/// <summary>
/// Returns a Primary Workitem with the given ID or null if the ID is invalid
/// </summary>
/// <param name="displayID">DisplayID of the Primary Workitem to retrieve</param>
/// <returns>an instance of a Primary Workitem or null if ID is invalid</returns>
public PrimaryWorkitem PrimaryWorkitemByDisplayID(string displayID) {
return GetByDisplayID<PrimaryWorkitem>(displayID);
}
/// <summary>
/// Returns a Secondary Workitem with the given ID or null if the ID is invalid
/// </summary>
/// <param name="displayID">DisplayID of the Secondary Workitem to retrieve</param>
/// <returns>an instance of a Secondary Workitem or null if ID is invalid</returns>
public SecondaryWorkitem SecondaryWorkitemByDisplayID(string displayID) {
return GetByDisplayID<SecondaryWorkitem>(displayID);
}
/// <summary>
/// Returns a Workitem with the given ID or null if the ID is invalid
/// </summary>
/// <param name="displayID">DisplayID of the Workitem to retrieve</param>
/// <returns>an instance of a Workitem or null if ID is invalid</returns>
public Workitem WorkitemByDisplayID(string displayID) {
return GetByDisplayID<Workitem>(displayID);
}
#endregion
#region GetByName, Etc.
/// <summary>
/// Retrieves the first schedule with the given name or null
/// </summary>
/// <param name="name">name of the schedule to retrieve</param>
/// <returns>the first instance of a Schedule that matches name or null</returns>
public Schedule ScheduleByName(string name) {
var scheduleAssetType = instance.MetaModel.GetAssetType("Schedule");
var nameDef = scheduleAssetType.GetAttributeDefinition("Name");
var query = new Query(scheduleAssetType);
var nameTerm = new FilterTerm(nameDef);
nameTerm.Equal(name);
query.Filter = nameTerm;
query.OrderBy.MajorSort(nameDef, OrderBy.Order.Ascending);
var result = instance.Services.Retrieve(query);
if(result.Assets.Count == 0) {
return null;
}
var asset = result.Assets[0];
return new Schedule(new AssetID(asset.Oid.Token), instance);
}
/// <summary>
/// Retrieves the first project with the given name or null
/// </summary>
/// <param name="name">name of the project to retrieve</param>
/// <returns>the first instance of a Project that matches name or null</returns>
public Project ProjectByName(string name) {
var projectAssetType = instance.MetaModel.GetAssetType("Scope");
var nameDef = projectAssetType.GetAttributeDefinition("Name");
var query = new Query(projectAssetType);
var nameTerm = new FilterTerm(nameDef);
nameTerm.Equal(name);
query.Filter = nameTerm;
query.OrderBy.MajorSort(nameDef, OrderBy.Order.Ascending);
var result = instance.Services.Retrieve(query);
if(result.Assets.Count == 0) {
return null;
}
var asset = result.Assets[0];
return new Project(new AssetID(asset.Oid.Token), instance);
}
/// <summary>
/// Retrieves the first Member with the given username
/// </summary>
/// <param name="userName">The username the user or member uses to login to the VersionOne system</param>
/// <returns>The first Member with the given username, or null if none found</returns>
public Member MemberByUserName(string userName) {
var memberAssetType = instance.MetaModel.GetAssetType("Member");
var nameDef = memberAssetType.GetAttributeDefinition("Username");
var query = new Query(memberAssetType);
var usernameTerm = new FilterTerm(nameDef);
usernameTerm.Equal(userName);
query.Filter = usernameTerm;
query.OrderBy.MajorSort(nameDef, OrderBy.Order.Ascending);
var result = instance.Services.Retrieve(query);
if(result.Assets.Count == 0) {
return null;
}
var asset = result.Assets[0];
return new Member(new AssetID(asset.Oid.Token), instance);
}
#endregion
/// <summary>
/// Gets the active values of a standard list type.
/// </summary>
/// <typeparam name="T">The type of Entity that represents the V1 List Type.</typeparam>
/// <returns>A list of active values for this list type.</returns>
public IEnumerable<T> ListTypeValues<T>() where T : ListValue {
var typeToGet = instance.MetaModel.GetAssetType(GetAssetTypeToken(typeof (T)));
var query = new Query(typeToGet);
var assetStateTerm = new FilterTerm(typeToGet.GetAttributeDefinition("AssetState"));
assetStateTerm.NotEqual(AssetState.Closed);
query.Filter = new AndFilterTerm(assetStateTerm);
return instance.QueryToEntityEnum<T>(query);
}
}
}
}
| |
// The MIT License (MIT)
//
// Copyright (c) Microsoft Corporation
//
// 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 Microsoft.Deployment.WindowsInstaller;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Management.Automation;
namespace Microsoft.Tools.WindowsInstaller.PowerShell.Commands
{
/// <summary>
/// The Get-MSIPatchInfo cmdlet.
/// </summary>
[Cmdlet(VerbsCommon.Get, "MSIPatchInfo", DefaultParameterSetName = ParameterSet.Patch)]
[OutputType(typeof(PatchInstallation))]
public sealed class GetPatchCommand : PSCmdlet
{
private List<Parameters> allParameters = new List<Parameters>();
private PatchStates filter = PatchStates.Applied;
private UserContexts context = UserContexts.All;
// Parameter positions below are to maintain backward call-compatibility.
/// <summary>
/// Gets or sets the ProductCodes for which patches are enumerated.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
[Parameter(ParameterSetName = ParameterSet.Patch, Position = 0, ValueFromPipelineByPropertyName = true)]
[ValidateGuid]
public string[] ProductCode { get; set; }
/// <summary>
/// Gets or sets patch codes for which information is retrieved.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
[Parameter(ParameterSetName = ParameterSet.Patch, Position = 1, ValueFromPipelineByPropertyName = true)]
[ValidateGuid]
public string[] PatchCode { get; set; }
/// <summary>
/// Gets or sets the patch states filter for enumeration.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
public PatchStates Filter
{
get { return this.filter; }
set
{
if (value == PatchStates.None)
{
throw new ArgumentException(Properties.Resources.Error_InvalidFilter);
}
this.filter = value;
}
}
/// <summary>
/// Gets or sets the user context for products to enumerate.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("Context", "InstallContext")] // Backward compatibility.
public UserContexts UserContext
{
get { return this.context; }
set
{
if (value == UserContexts.None)
{
var message = string.Format(CultureInfo.CurrentCulture, Properties.Resources.Error_InvalidContext, UserContexts.None);
throw new ArgumentException(message, "UserContext");
}
this.context = value;
}
}
/// <summary>
/// Gets or sets the user security identifier for products to enumerate.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("User")]
[Sid]
public string UserSid { get; set; }
/// <summary>
/// Gets or sets whether products for everyone should be enumerated.
/// </summary>
[Parameter]
public SwitchParameter Everyone
{
get { return string.Compare(this.UserSid, NativeMethods.World, StringComparison.OrdinalIgnoreCase) == 0; }
set { this.UserSid = value ? NativeMethods.World : null; }
}
/// <summary>
/// Collects input ProductCodes and PatchCodes for future processing.
/// </summary>
protected override void ProcessRecord()
{
this.allParameters.Add(new Parameters
{
ProductCode = this.ProductCode != null && this.ProductCode.Length > 0 ? this.ProductCode : new string[] { null},
PatchCode = this.PatchCode != null && this.PatchCode.Length > 0 ? this.PatchCode : new string[] { null},
Filter = this.Filter,
UserContext = this.UserContext,
UserSid = this.UserSid,
});
}
/// <summary>
/// Processes the ProductCodes or PatchCodes and writes a patch to the pipeline.
/// </summary>
protected override void EndProcessing()
{
this.allParameters.ForEach((param) =>
{
foreach (string productCode in param.ProductCode)
{
foreach (string patchCode in param.PatchCode)
{
this.WritePatches(patchCode, productCode, param.UserSid, param.UserContext, param.Filter);
}
}
});
}
/// <summary>
/// Enumerates patches for the given patch codes and ProductCodes and writes them to the pipeline.
/// </summary>
/// <param name="patchCode">The patch code to enumerate.</param>
/// <param name="productCode">The ProductCode having patches to enumerate.</param>
/// <param name="userSid">The user's SID for patches to enumerate.</param>
/// <param name="context">The installation context for patches to enumerate.</param>
/// <param name="filter">The patch installation state for patches to enumerate.</param>
private void WritePatches(string patchCode, string productCode, string userSid, UserContexts context, PatchStates filter)
{
foreach (PatchInstallation patch in PatchInstallation.GetPatches(patchCode, productCode, userSid, context, filter))
{
this.WritePatch(patch);
}
}
/// <summary>
/// Adds properties to the <see cref="PatchInstallation"/> object and writes it to the pipeline.
/// </summary>
/// <param name="patch">The <see cref="PatchInstallation"/> to write to the pipeline.</param>
private void WritePatch(PatchInstallation patch)
{
var obj = patch.ToPSObject(this.SessionState.Path);
this.WriteObject(obj);
}
/// <summary>
/// Collects parameters for processing.
/// </summary>
private sealed class Parameters
{
/// <summary>
/// Gets or sets the ProductCodes.
/// </summary>
internal string[] ProductCode;
/// <summary>
/// Gets or sets the patch codes.
/// </summary>
internal string[] PatchCode;
/// <summary>
/// Gets or sets the filter.
/// </summary>
internal PatchStates Filter;
/// <summary>
/// Gets or sets the installation context.
/// </summary>
internal UserContexts UserContext;
/// <summary>
/// Gets or sets the user's SID.
/// </summary>
internal string UserSid;
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
#if FRB_MDX
#elif SILVERLIGHT
using SilverArcade.SilverSprite;
#elif !FRB_RAW
using Microsoft.Xna.Framework;
#endif
namespace FlatRedBall.Utilities
{
#region XML Docs
/// <summary>
/// A class containing common string maniuplation methods.
/// </summary>
#endregion
public static class StringFunctions
{
#region Fields
static char[] sValidNumericalChars = { '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', ',' };
#endregion
public static bool IsAscii(string stringToCheck)
{
bool isAscii = true;
for (int i = 0; i < stringToCheck.Length; i++)
{
if (stringToCheck[i] > 255)
{
isAscii = false;
break;
}
}
return isAscii;
}
public static int CountOf(this string instanceToSearchIn, char characterToSearchFor)
{
return instanceToSearchIn.CountOf(characterToSearchFor, 0, instanceToSearchIn.Length);
}
public static int CountOf(this string instanceToSearchIn, char characterToSearchFor, int startIndex, int searchLength)
{
int count = 0;
for (int i = startIndex; i < searchLength; i++)
{
char characterAtIndex = instanceToSearchIn[i];
if (characterAtIndex == characterToSearchFor)
{
count++;
}
}
return count;
}
/// <summary>
/// Returns the number of times that the argument whatToFind is found in the calling string.
/// </summary>
/// <param name="instanceToSearchIn">The string to search within.</param>
/// <param name="whatToFind">The string to search for.</param>
/// <returns>The number of instances found</returns>
public static int CountOf(this string instanceToSearchIn, string whatToFind)
{
int count = 0;
int index = 0;
while (true)
{
int foundIndex = instanceToSearchIn.IndexOf(whatToFind, index);
if (foundIndex != -1)
{
count++;
index = foundIndex + 1;
}
else
{
break;
}
}
return count;
}
public static bool Contains(this string[] listToInvestigate, string whatToSearchFor)
{
for (int i = 0; i < listToInvestigate.Length; i++)
{
if (listToInvestigate[i] == whatToSearchFor)
{
return true;
}
}
return false;
}
#region XML Docs
/// <summary>
/// Returns the number of non-whitespace characters in the argument stringInQuestion.
/// </summary>
/// <remarks>
/// This method is used internally by the TextManager to determine the number of vertices needed to
/// draw a Text object.
/// </remarks>
/// <param name="stringInQuestion">The string to have its non-witespace counted.</param>
/// <returns>The number of non-whitespace characters counted.</returns>
#endregion
public static int CharacterCountWithoutWhitespace(string stringInQuestion)
{
int characterCount = 0;
for (int i = 0; i < stringInQuestion.Length; i++)
{
if (stringInQuestion[i] != ' ' && stringInQuestion[i] != '\t' && stringInQuestion[i] != '\n')
characterCount++;
}
return characterCount;
}
#region XML Docs
/// <summary>
/// Returns a string of the float with the argument decimalsAfterPoint digits of resolution after the point.
/// </summary>
/// <param name="floatToConvert">The float to convert.</param>
/// <param name="decimalsAfterPoint">The number of decimals after the point. For example, 3.14159 becomes "3.14" if the
/// decimalsAfterPoint is 2. This method will not append extra decimals to reach the argument decimalsAfterPoint.</param>
/// <returns>The string representation of the argument float.</returns>
#endregion
public static string FloatToString(float floatToConvert, int decimalsAfterPoint)
{
if (decimalsAfterPoint == 0)
return ((int)floatToConvert).ToString();
else
{
int lengthAsInt = ((int)floatToConvert).ToString().Length;
return floatToConvert.ToString().Substring(
0, System.Math.Min(floatToConvert.ToString().Length, lengthAsInt + 1 + decimalsAfterPoint));
}
}
#region XML Docs
/// <summary>
/// Returns the character that can be found after a particular sequence of characters.
/// </summary>
/// <remarks>
/// This will return the first character following a particular sequence of characters. For example,
/// GetCharAfter("bcd", "abcdef") would return 'e'.
/// </remarks>
/// <param name="stringToSearchFor">The string to search for.</param>
/// <param name="whereToSearch">The string to search in.</param>
/// <returns>Returns the character found or the null character '\0' if the string is not found.</returns>
#endregion
public static char GetCharAfter(string stringToSearchFor, string whereToSearch)
{
int indexOf = whereToSearch.IndexOf(stringToSearchFor);
if (indexOf != -1)
{
return whereToSearch[indexOf + stringToSearchFor.Length];
}
return '\0';
}
public static int GetClosingCharacter(string fullString, int startIndex, char openingCharacter, char closingCharacter)
{
int numberofParens = 1;
for (int i = startIndex; i < fullString.Length; i++)
{
if (fullString[i] == openingCharacter)
{
numberofParens++;
}
if (fullString[i] == closingCharacter)
{
numberofParens--;
}
if (numberofParens == 0)
{
return i;
}
}
return -1;
}
public static int GetDigitCount(double x)
{
// Written by Kao Martin 12/6/2008
int count = 1;
double diff = x - System.Math.Floor(x);
while ((x /= 10.0d) > 1.0d)
{
count++;
}
if (diff > 0)
{
count++;
while ((diff *= 10.0d) > 1.0d)
{
count++;
diff -= System.Math.Floor(diff);
}
}
return count;
}
#region XML Docs
/// <summary>
/// Returns the float that can be found after a particular sequence of characters.
/// </summary>
/// <remarks>
/// This will return the float following a particular sequence of characters. For example,
/// GetCharAfter("height = 6; width = 3; depth = 7;", "width = ") would return 3.0f.
/// </remarks>
/// <param name="stringToSearchFor">The string to search for.</param>
/// <param name="whereToSearch">The string to search in.</param>
/// <returns>Returns the float value found or float.NaN if the string is not found.</returns>
#endregion
public static float GetFloatAfter(string stringToSearchFor, string whereToSearch)
{
return GetFloatAfter(stringToSearchFor, whereToSearch, 0);
}
public static float GetFloatAfter(string stringToSearchFor, string whereToSearch, int startIndex)
{
int startOfNumber = -1;
int endOfNumber = -1;
int enterAt = -1;
string substring = "uninitialized";
try
{
int indexOf = whereToSearch.IndexOf(stringToSearchFor, startIndex);
if (indexOf != -1)
{
startOfNumber = indexOf + stringToSearchFor.Length;
endOfNumber = whereToSearch.IndexOf(' ', startOfNumber);
enterAt = whereToSearch.IndexOf('\n', startOfNumber);
if (whereToSearch.IndexOf('\r', startOfNumber) < enterAt)
enterAt = whereToSearch.IndexOf('\r', startOfNumber);
for (int i = startOfNumber; i < endOfNumber; i++)
{
bool found = false;
for (int indexInArray = 0; indexInArray < sValidNumericalChars.Length; indexInArray++)
{
if (whereToSearch[i] == sValidNumericalChars[indexInArray])
{
found = true;
break;
}
}
if (!found)
{
// if we got here, then the character is not valid, so end the string
endOfNumber = i;
break;
}
}
if (endOfNumber == -1 || (enterAt != -1 && enterAt < endOfNumber))
endOfNumber = enterAt;
if (endOfNumber == -1)
endOfNumber = whereToSearch.Length;
substring = whereToSearch.Substring(startOfNumber,
endOfNumber - startOfNumber);
// this method is called when reading from a file.
// usually, files use the . rather than other numerical formats, so if this fails, just use the regular . format
float toReturn = float.Parse(substring);
// Let's see if this is using exponential notation, like 5.21029e-007
if (endOfNumber < whereToSearch.Length - 1)
{
// Is there an "e" there?
if (whereToSearch[endOfNumber] == 'e')
{
int exponent = GetIntAfter("e", whereToSearch, endOfNumber);
float multiplyValue = (float)System.Math.Pow(10, exponent);
toReturn *= multiplyValue;
}
}
return toReturn;
}
}
catch (System.FormatException)
{
return float.Parse(substring, System.Globalization.NumberFormatInfo.InvariantInfo);
}
return float.NaN;
}
#region XML Docs
/// <summary>
/// Returns the first integer found after the argument stringToSearchFor in whereToSearch.
/// </summary>
/// <remarks>
/// This method is used to help simplify parsing of text files and data strings.
/// If stringToSearchFor is "Y:" and whereToSearch is "X: 30, Y:32", then the value
/// of 32 will be returned.
/// </remarks>
/// <param name="stringToSearchFor">The string pattern to search for.</param>
/// <param name="whereToSearch">The string that will be searched.</param>
/// <returns>The integer value found after the argument stringToSearchFor.</returns>
#endregion
public static int GetIntAfter(string stringToSearchFor, string whereToSearch)
{
return GetIntAfter(stringToSearchFor, whereToSearch, 0);
}
#region XML Docs
/// <summary>
/// Returns the first integer found after the argument stringToSearchFor. The search begins
/// at the argument startIndex.
/// </summary>
/// <param name="stringToSearchFor">The string pattern to search for.</param>
/// <param name="whereToSearch">The string that will be searched.</param>
/// <param name="startIndex">The index to begin searching at. This method
/// will ignore any instances of stringToSearchFor which begin at an index smaller
/// than the argument startIndex.</param>
/// <returns></returns>
#endregion
public static int GetIntAfter(string stringToSearchFor, string whereToSearch, int startIndex)
{
int startOfNumber = -1;
int endOfNumber = -1;
int enterAt = -1;
int carriageReturn = -1;
string substring = "uninitialized";
try
{
int indexOf = whereToSearch.IndexOf(stringToSearchFor, startIndex);
if (indexOf != -1)
{
startOfNumber = indexOf + stringToSearchFor.Length;
endOfNumber = whereToSearch.IndexOf(' ', startOfNumber);
enterAt = whereToSearch.IndexOf('\n', startOfNumber);
carriageReturn = whereToSearch.IndexOf('\r', startOfNumber);
if ( carriageReturn != -1 && carriageReturn < enterAt)
enterAt = whereToSearch.IndexOf('\r', startOfNumber);
if (endOfNumber == -1)
endOfNumber = whereToSearch.Length;
for (int i = startOfNumber; i < endOfNumber; i++)
{
bool found = false;
for (int indexInArray = 0; indexInArray < sValidNumericalChars.Length; indexInArray++)
{
if (whereToSearch[i] == sValidNumericalChars[indexInArray])
{
found = true;
break;
}
}
if (!found)
{
// if we got here, then the character is not valid, so end the string
endOfNumber = i;
break;
}
}
if (endOfNumber == -1 || (enterAt != -1 && enterAt < endOfNumber))
endOfNumber = enterAt;
if (endOfNumber == -1)
endOfNumber = whereToSearch.Length;
substring = whereToSearch.Substring(startOfNumber,
endOfNumber - startOfNumber);
// this method is called when reading from a file.
// usually, files use the . rather than other numerical formats, so if this fails, just use the regular . format
int toReturn = int.Parse(substring);
return toReturn;
}
}
catch (System.FormatException)
{
return int.Parse(substring, System.Globalization.NumberFormatInfo.InvariantInfo);
}
return 0;
}
static char[] WhitespaceChars = new char[] { ' ', '\n', '\t', '\r' };
public static string GetWordAfter(string stringToStartAfter, string entireString)
{
return GetWordAfter(stringToStartAfter, entireString, 0);
}
public static string GetWordAfter(string stringToStartAfter, string entireString, int indexToStartAt)
{
return GetWordAfter(stringToStartAfter, entireString, indexToStartAt, StringComparison.Ordinal);
}
public static string GetWordAfter(string stringToStartAfter, string entireString, int indexToStartAt, StringComparison comparison)
{
int indexOf = entireString.IndexOf(stringToStartAfter, indexToStartAt, StringComparison.OrdinalIgnoreCase);
if (indexOf != -1)
{
int startOfWord = indexOf + stringToStartAfter.Length;
// Let's not count the start of the word if it's a newline
while ( entireString[startOfWord] == WhitespaceChars[0] ||
entireString[startOfWord] == WhitespaceChars[1] ||
entireString[startOfWord] == WhitespaceChars[2] ||
entireString[startOfWord] == WhitespaceChars[3])
{
startOfWord++;
}
int endOfWord = entireString.IndexOfAny(WhitespaceChars, startOfWord);
if (endOfWord == -1)
{
endOfWord = entireString.Length;
}
return entireString.Substring(startOfWord, endOfWord - startOfWord);
}
else
{
return null;
}
}
public static string GetWordAfter(string stringToStartAfter, StringBuilder entireString)
{
return GetWordAfter(stringToStartAfter, entireString, 0);
}
public static string GetWordAfter(string stringToStartAfter, StringBuilder entireString, int indexToStartAt)
{
return GetWordAfter(stringToStartAfter, entireString, indexToStartAt, StringComparison.Ordinal);
}
public static string GetWordAfter(string stringToStartAfter, StringBuilder entireString, int indexToStartAt, StringComparison comparison)
{
int indexOf = entireString.IndexOf(stringToStartAfter, indexToStartAt, true);
if (indexOf != -1)
{
int startOfWord = indexOf + stringToStartAfter.Length;
// Let's not count the start of the word if it's a newline
while (entireString[startOfWord] == WhitespaceChars[0] ||
entireString[startOfWord] == WhitespaceChars[1] ||
entireString[startOfWord] == WhitespaceChars[2] ||
entireString[startOfWord] == WhitespaceChars[3])
{
startOfWord++;
}
int endOfWord = entireString.IndexOfAny(WhitespaceChars, startOfWord);
if (endOfWord == -1)
{
endOfWord = entireString.Length;
}
return entireString.Substring(startOfWord, endOfWord - startOfWord);
}
else
{
return null;
}
}
#region XML Docs
/// <summary>
/// Returns the number of lines in a given string. Newlines '\n' increase the
/// line count.
/// </summary>
/// <param name="stringInQuestion">The string that will have its lines counted.</param>
/// <returns>The number of lines in the argument. "Hello" will return a value of 1, "Hello\nthere" will return a value of 2.</returns>
#endregion
public static int GetLineCount(string stringInQuestion)
{
if (string.IsNullOrEmpty(stringInQuestion))
{
return 0;
}
int lines = 1;
foreach (char character in stringInQuestion)
{
if (character == '\n')
{
lines++;
}
}
return lines;
}
#region XML Docs
/// <summary>
/// Returns the number found at the end of the argument stringToGetNumberFrom or throws an
/// ArgumentException if no number is found.
/// </summary>
/// <remarks>
/// A stringToGetNumberFrom of "sprite41" will result in the value of 41 returned. A
/// stringToGetNumberFrom of "sprite" will result in an ArgumentException being thrown.
/// </remarks>
/// <exception cref="System.ArgumentException">Throws ArgumentException if no number is found at the end of the argument string.</exception>
/// <param name="stringToGetNumberFrom">The number found at the end.</param>
/// <returns>The integer value found at the end of the stringToGetNumberFrom.</returns>
#endregion
public static int GetNumberAtEnd(string stringToGetNumberFrom)
{
int letterChecking = stringToGetNumberFrom.Length;
do
{
letterChecking--;
} while (letterChecking > -1 && Char.IsDigit(stringToGetNumberFrom[letterChecking]));
if (letterChecking == stringToGetNumberFrom.Length - 1 && !Char.IsDigit(stringToGetNumberFrom[letterChecking]))
{
throw new ArgumentException("The argument string has no number at the end.");
}
return System.Convert.ToInt32(
stringToGetNumberFrom.Substring(letterChecking + 1, stringToGetNumberFrom.Length - letterChecking - 1));
}
public static void GetStartAndEndOfLineContaining(string contents, string whatToSearchFor, out int start, out int end)
{
int indexOfWhatToSearchFor = contents.IndexOf(whatToSearchFor);
start = -1;
end = -1;
if (indexOfWhatToSearchFor != -1)
{
start = contents.LastIndexOfAny(new char[] { '\n', '\r' }, indexOfWhatToSearchFor) + 1;
end = contents.IndexOfAny(new char[] { '\n', '\r' }, indexOfWhatToSearchFor);
}
}
public static bool HasNumberAtEnd(string stringToGetNumberFrom)
{
int letterChecking = stringToGetNumberFrom.Length;
do
{
letterChecking--;
} while (letterChecking > -1 && Char.IsDigit(stringToGetNumberFrom[letterChecking]));
if (letterChecking == stringToGetNumberFrom.Length - 1 && !Char.IsDigit(stringToGetNumberFrom[letterChecking]))
{
return false;
}
return true;
}
#region XML Docs
/// <summary>
/// Increments the number at the end of a string or adds a number if none exists.
/// </summary>
/// <remarks>
/// This method begins looking at the end of a string for numbers and moves towards the beginning of the string
/// until it encounters a character which is not a numerical digit or the beginning of the string. "Sprite123" would return
/// "Sprite124", and "MyString" would return "MyString1".
/// </remarks>
/// <param name="originalString">The string to "increment".</param>
/// <returns>Returns a string with the number at the end incremented, or with a number added on the end if none existed before.</returns>
#endregion
public static string IncrementNumberAtEnd(string originalString)
{
if(string.IsNullOrEmpty(originalString))
{
return "1";
}
// first we get the number at the end of the string
// start at the end of the string and move backwards until reacing a non-Digit.
int letterChecking = originalString.Length;
do
{
letterChecking--;
} while (letterChecking > -1 && Char.IsDigit(originalString[letterChecking]));
if (letterChecking == originalString.Length - 1 && !Char.IsDigit(originalString[letterChecking]))
{
// we don't have a number there, so let's add one
originalString = originalString + ((int)1).ToString();
return originalString;
}
string numAtEnd = originalString.Substring(letterChecking + 1, originalString.Length - letterChecking - 1);
string baseString = originalString.Remove(letterChecking + 1, originalString.Length - letterChecking - 1);
int numAtEndAsInt = System.Convert.ToInt32(numAtEnd);
numAtEndAsInt++;
return baseString + numAtEndAsInt.ToString();
}
#region XML Docs
/// <summary>
/// Inserts spaces before every capital letter in a camel-case
/// string. Ignores the first letter.
/// </summary>
/// <remarks>
/// For example "HelloThereIAmCamelCase" becomes
/// "Hello There I Am Camel Case".
/// </remarks>
/// <param name="originalString">The string in which to insert spaces.</param>
/// <returns>The string with spaces inserted.</returns>
#endregion
public static string InsertSpacesInCamelCaseString(string originalString)
{
// Normally in reverse loops you go til i > -1, but
// we don't want the character at index 0 to be tested.
for (int i = originalString.Length - 1; i > 0; i--)
{
if (char.IsUpper(originalString[i]) && i != 0)
{
originalString = originalString.Insert(i, " ");
}
}
return originalString;
}
public static bool IsNameUnique<T>(INameable nameable, IList<T> listToCheckAgainst) where T : INameable
{
for (int i = 0; i < listToCheckAgainst.Count; i++)
{
INameable nameableToCheckAgainst = listToCheckAgainst[i];
if (nameable != nameableToCheckAgainst && nameable.Name == nameableToCheckAgainst.Name)
{
return false;
}
}
return true;
}
public static bool IsNumber(string stringToCheck)
{
double throwaway;
return double.TryParse(stringToCheck, out throwaway);
}
public static string MakeCamelCase(string originalString)
{
if (string.IsNullOrEmpty(originalString))
{
return originalString;
}
char[] characterArray = originalString.ToCharArray();
for (int i = 0; i < originalString.Length; i++)
{
if (i == 0 &&
characterArray[i] >= 'a' && characterArray[i] <= 'z')
{
characterArray[i] -= (char)32;
}
if (characterArray[i] == ' ' &&
i < originalString.Length - 1 &&
characterArray[i + 1] >= 'a' && characterArray[i + 1] <= 'z')
{
characterArray[i + 1] -= (char)32;
}
}
return RemoveWhitespace(new string(characterArray));
}
#region XML Docs
/// <summary>
/// Renames the argument INameable to prevent duplicate names. This method is extremely inefficent for large lists.
/// </summary>
/// <typeparam name="T">The type of INameable contained int he list.</typeparam>
/// <param name="nameable">The INameable to rename if necessary.</param>
/// <param name="list">The list containing the INameables to compare against.</param>
#endregion
public static void MakeNameUnique<T>(T nameable, IList<T> list)
where T : INameable
{
for (int i = 0; i < list.Count; i++)
{
if (((object)nameable) != ((object)list[i]) &&
(nameable.Name == list[i].Name ||
(string.IsNullOrEmpty(nameable.Name) && string.IsNullOrEmpty(list[i].Name)))
)
{
// the name matches an item in the list that isn't the same reference, so increment the number.
nameable.Name = IncrementNumberAtEnd(nameable.Name);
// restart the loop:
i = -1;
}
}
}
public static void MakeNameUnique<T>(T nameable, IEnumerable<T> list)
where T : INameable
{
var count = list.Count();
for (int i = 0; i < list.Count(); i++)
{
var atI = list.ElementAt(i);
if (((object)nameable) != ((object)atI) &&
(nameable.Name == atI.Name ||
(string.IsNullOrEmpty(nameable.Name) && string.IsNullOrEmpty(atI.Name)))
)
{
// the name matches an item in the list that isn't the same reference, so increment the number.
nameable.Name = IncrementNumberAtEnd(nameable.Name);
// restart the loop:
i = -1;
}
}
}
/// <summary>
/// Makes an INameable's name unique given a list of existing INameables.
/// </summary>
/// <typeparam name="T">The type of nameable.</typeparam>
/// <typeparam name="U">The type of IList, where the type is an INameable</typeparam>
/// <param name="nameable">The instance to modify if necessary.</param>
/// <param name="list">The list of INameables</param>
public static void MakeNameUnique<T, U>(T nameable, IList<U> list) where T : INameable where U : INameable
{
for (int i = 0; i < list.Count; i++)
{
if (((object)nameable) != ((object)list[i]) &&
(nameable.Name == list[i].Name ||
(string.IsNullOrEmpty(nameable.Name) && string.IsNullOrEmpty(list[i].Name)))
)
{
// the name matches an item in the list that isn't the same reference, so increment the number.
nameable.Name = IncrementNumberAtEnd(nameable.Name);
// restart the loop:
i = -1;
}
}
}
public static string MakeStringUnique(string stringToMakeUnique, List<string> stringList)
{
return MakeStringUnique(stringToMakeUnique, stringList, 1);
}
public static string MakeStringUnique(string stringToMakeUnique, List<string> stringList, int numberToStartAt)
{
for (int i = 0; i < stringList.Count; i++)
{
if (stringToMakeUnique == stringList[i])
{
// the name matches an item in the list that isn't the same reference, so increment the number.
stringToMakeUnique = IncrementNumberAtEnd(stringToMakeUnique);
// Inefficient? Maybe if we have large numbers, but we're just using it to start at #2
// I may revisit this if this causes problems
while (GetNumberAtEnd(stringToMakeUnique) < numberToStartAt)
{
stringToMakeUnique = IncrementNumberAtEnd(stringToMakeUnique);
}
// restart the loop:
i = -1;
}
}
return stringToMakeUnique;
}
public static string MakeStringUnique<T>(string stringToMakeUnique, IEnumerable<T> nameableList) where T : INameable
{
int numberToStartAt = 1;
bool repeat = true;
while (repeat)
{
bool restart = false;
foreach(T nameable in nameableList)
{
if (stringToMakeUnique == nameable.Name)
{
// the name matches an item in the list that isn't the same reference, so increment the number.
stringToMakeUnique = IncrementNumberAtEnd(stringToMakeUnique);
// Inefficient? Maybe if we have large numbers, but we're just using it to start at #2
// I may revisit this if this causes problems
while (GetNumberAtEnd(stringToMakeUnique) < numberToStartAt)
{
stringToMakeUnique = IncrementNumberAtEnd(stringToMakeUnique);
}
// restart the loop:
restart = true ;
break;
}
}
repeat = restart;
}
return stringToMakeUnique;
}
public static void RemoveDuplicates(List<string> strings)
{
bool ignoreCase = false;
RemoveDuplicates(strings, ignoreCase);
}
public static void RemoveDuplicates(List<string> strings, bool ignoreCase)
{
Dictionary<string, int> uniqueStore = new Dictionary<string, int>();
List<string> finalList = new List<string>();
foreach (string currValueUncasted in strings)
{
string currValue;
if (ignoreCase)
{
currValue = currValueUncasted.ToLowerInvariant();
}
else
{
currValue = currValueUncasted;
}
if (!uniqueStore.ContainsKey(currValue))
{
uniqueStore.Add(currValue, 0);
finalList.Add(currValueUncasted);
}
}
strings.Clear();
strings.AddRange(finalList);
}
#region XML Docs
/// <summary>
/// Removes the number found at the end of the argument originalString and returns the resulting
/// string, or returns the original string if no number is found.
/// </summary>
/// <param name="originalString">The string that will have the number at its end removed.</param>
/// <returns>The string after the number has been removed.</returns>
#endregion
public static string RemoveNumberAtEnd(string originalString)
{
// start at the end of the string and move backwards until reacing a non-Digit.
int letterChecking = originalString.Length;
do
{
letterChecking--;
} while (letterChecking > -1 && Char.IsDigit(originalString[letterChecking]));
if (letterChecking == originalString.Length - 1 && !Char.IsDigit(originalString[letterChecking]))
{
// we don't have a number there, so return the original
return originalString;
}
return originalString.Remove(letterChecking + 1, originalString.Length - letterChecking - 1);
}
#region XML Docs
/// <summary>
/// Removes all whitespace found in the argument stringToRemoveWhitespaceFrom.
/// </summary>
/// <param name="stringToRemoveWhitespaceFrom">The string that will have its whitespace removed.</param>
/// <returns>The string resulting from removing whitespace from the argument string.</returns>
#endregion
public static string RemoveWhitespace(string stringToRemoveWhitespaceFrom)
{
return stringToRemoveWhitespaceFrom.Replace(" ", "").Replace("\t", "").Replace("\n", "").Replace("\r", "");
}
public static void ReplaceLine(ref string contents, string contentsOfLineToReplace, string whatToReplaceWith)
{
int startOfLine;
int endOfLine;
GetStartAndEndOfLineContaining(contents, contentsOfLineToReplace, out startOfLine, out endOfLine);
if (startOfLine != -1)
{
contents = contents.Remove(startOfLine, endOfLine - startOfLine);
contents = contents.Insert(startOfLine, whatToReplaceWith);
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.PopulateSwitch;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.PopulateSwitch
{
public partial class PopulateSwitchTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override Tuple<DiagnosticAnalyzer, CodeFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace)
{
return new Tuple<DiagnosticAnalyzer, CodeFixProvider>(
new PopulateSwitchDiagnosticAnalyzer(), new PopulateSwitchCodeFixProvider());
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)]
public async Task OnlyOnFirstToken()
{
await TestMissingAsync(
@"namespace ConsoleApplication1
{
enum MyEnum
{
Fizz,
Buzz,
FizzBuzz
}
class MyClass
{
void Method()
{
var e = MyEnum.Fizz;
switch ([||]e)
{
case MyEnum.Fizz:
case MyEnum.Buzz:
default:
break;
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)]
public async Task AllMembersAndDefaultExist()
{
await TestMissingAsync(
@"namespace ConsoleApplication1
{
enum MyEnum
{
Fizz,
Buzz,
FizzBuzz
}
class MyClass
{
void Method()
{
var e = MyEnum.Fizz;
[||]switch (e)
{
case MyEnum.Fizz:
case MyEnum.Buzz:
case MyEnum.FizzBuzz:
default:
break;
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)]
public async Task AllMembersExist_NotDefault()
{
await TestAsync(
@"namespace ConsoleApplication1
{
enum MyEnum
{
Fizz,
Buzz,
FizzBuzz
}
class MyClass
{
void Method()
{
var e = MyEnum.Fizz;
[||]switch (e)
{
case MyEnum.Fizz:
case MyEnum.Buzz:
case MyEnum.FizzBuzz:
break;
}
}
}
}",
@"namespace ConsoleApplication1
{
enum MyEnum
{
Fizz,
Buzz,
FizzBuzz
}
class MyClass
{
void Method()
{
var e = MyEnum.Fizz;
switch (e)
{
case MyEnum.Fizz:
case MyEnum.Buzz:
case MyEnum.FizzBuzz:
break;
default:
break;
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)]
public async Task NotAllMembersExist_NotDefault()
{
await TestAsync(
@"namespace ConsoleApplication1
{
enum MyEnum
{
Fizz,
Buzz,
FizzBuzz
}
class MyClass
{
void Method()
{
var e = MyEnum.Fizz;
[||]switch (e)
{
case MyEnum.Fizz:
case MyEnum.Buzz:
break;
}
}
}
}",
@"namespace ConsoleApplication1
{
enum MyEnum
{
Fizz,
Buzz,
FizzBuzz
}
class MyClass
{
void Method()
{
var e = MyEnum.Fizz;
switch (e)
{
case MyEnum.Fizz:
case MyEnum.Buzz:
break;
case MyEnum.FizzBuzz:
break;
default:
break;
}
}
}
}", index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)]
public async Task NotAllMembersExist_WithDefault()
{
await TestAsync(
@"namespace ConsoleApplication1
{
enum MyEnum
{
Fizz,
Buzz,
FizzBuzz
}
class MyClass
{
void Method()
{
var e = MyEnum.Fizz;
[||]switch (e)
{
case MyEnum.Fizz:
case MyEnum.Buzz:
break;
default:
break;
}
}
}
}",
@"namespace ConsoleApplication1
{
enum MyEnum
{
Fizz,
Buzz,
FizzBuzz
}
class MyClass
{
void Method()
{
var e = MyEnum.Fizz;
switch (e)
{
case MyEnum.Fizz:
case MyEnum.Buzz:
break;
case MyEnum.FizzBuzz:
break;
default:
break;
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)]
public async Task NotAllMembersExist_NotDefault_EnumHasExplicitType()
{
await TestAsync(
@"namespace ConsoleApplication1
{
enum MyEnum : long
{
Fizz,
Buzz,
FizzBuzz
}
class MyClass
{
void Method()
{
var e = MyEnum.Fizz;
[||]switch (e)
{
case MyEnum.Fizz:
case MyEnum.Buzz:
break;
}
}
}
}",
@"namespace ConsoleApplication1
{
enum MyEnum : long
{
Fizz,
Buzz,
FizzBuzz
}
class MyClass
{
void Method()
{
var e = MyEnum.Fizz;
switch (e)
{
case MyEnum.Fizz:
case MyEnum.Buzz:
break;
case MyEnum.FizzBuzz:
break;
default:
break;
}
}
}
}", index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)]
public async Task NotAllMembersExist_WithMembersAndDefaultInSection_NewValuesAboveDefaultSection()
{
await TestAsync(
@"namespace ConsoleApplication1
{
enum MyEnum
{
Fizz,
Buzz,
FizzBuzz
}
class MyClass
{
void Method()
{
var e = MyEnum.Fizz;
[||]switch (e)
{
case MyEnum.Fizz:
case MyEnum.Buzz:
default:
break;
}
}
}
}",
@"namespace ConsoleApplication1
{
enum MyEnum
{
Fizz,
Buzz,
FizzBuzz
}
class MyClass
{
void Method()
{
var e = MyEnum.Fizz;
switch (e)
{
case MyEnum.FizzBuzz:
break;
case MyEnum.Fizz:
case MyEnum.Buzz:
default:
break;
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)]
public async Task NotAllMembersExist_WithMembersAndDefaultInSection_AssumesDefaultIsInLastSection()
{
await TestAsync(
@"namespace ConsoleApplication1
{
enum MyEnum
{
Fizz,
Buzz,
FizzBuzz
}
class MyClass
{
void Method()
{
var e = MyEnum.Fizz;
[||]switch (e)
{
default:
break;
case MyEnum.Fizz:
case MyEnum.Buzz:
break;
}
}
}
}",
@"namespace ConsoleApplication1
{
enum MyEnum
{
Fizz,
Buzz,
FizzBuzz
}
class MyClass
{
void Method()
{
var e = MyEnum.Fizz;
switch (e)
{
default:
break;
case MyEnum.Fizz:
case MyEnum.Buzz:
break;
case MyEnum.FizzBuzz:
break;
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)]
public async Task NoMembersExist0()
{
await TestAsync(
@"namespace ConsoleApplication1
{
enum MyEnum
{
Fizz,
Buzz,
FizzBuzz
}
class MyClass
{
void Method()
{
var e = MyEnum.Fizz;
[||]switch (e)
{
}
}
}
}",
@"namespace ConsoleApplication1
{
enum MyEnum
{
Fizz,
Buzz,
FizzBuzz
}
class MyClass
{
void Method()
{
var e = MyEnum.Fizz;
switch (e)
{
case MyEnum.Fizz:
break;
case MyEnum.Buzz:
break;
case MyEnum.FizzBuzz:
break;
}
}
}
}", index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)]
public async Task NoMembersExist1()
{
await TestAsync(
@"namespace ConsoleApplication1
{
enum MyEnum
{
Fizz,
Buzz,
FizzBuzz
}
class MyClass
{
void Method()
{
var e = MyEnum.Fizz;
[||]switch (e)
{
}
}
}
}",
@"namespace ConsoleApplication1
{
enum MyEnum
{
Fizz,
Buzz,
FizzBuzz
}
class MyClass
{
void Method()
{
var e = MyEnum.Fizz;
switch (e)
{
default:
break;
}
}
}
}", index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)]
public async Task NoMembersExist2()
{
await TestAsync(
@"namespace ConsoleApplication1
{
enum MyEnum
{
Fizz,
Buzz,
FizzBuzz
}
class MyClass
{
void Method()
{
var e = MyEnum.Fizz;
[||]switch (e)
{
}
}
}
}",
@"namespace ConsoleApplication1
{
enum MyEnum
{
Fizz,
Buzz,
FizzBuzz
}
class MyClass
{
void Method()
{
var e = MyEnum.Fizz;
switch (e)
{
case MyEnum.Fizz:
break;
case MyEnum.Buzz:
break;
case MyEnum.FizzBuzz:
break;
default:
break;
}
}
}
}", index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)]
public async Task UsingStaticEnum_AllMembersExist()
{
await TestMissingAsync(
@"using static System.IO.FileMode;
namespace ConsoleApplication1
{
class MyClass
{
void Method()
{
var e = Append;
[||]switch (e)
{
case CreateNew:
break;
case Create:
break;
case Open:
break;
case OpenOrCreate:
break;
case Truncate:
break;
case Append:
break;
default:
break;
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)]
public async Task UsingStaticEnum_AllMembersExist_OutOfDefaultOrder()
{
await TestMissingAsync(
@"using static System.IO.FileMode;
namespace ConsoleApplication1
{
class MyClass
{
void Method()
{
var e = Append;
[||]switch (e)
{
case CreateNew:
break;
case OpenOrCreate:
break;
case Truncate:
break;
case Open:
break;
case Append:
break;
case Create:
break;
default:
break;
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)]
public async Task UsingStaticEnum_MembersExist()
{
await TestAsync(
@"using static System.IO.FileMode;
namespace ConsoleApplication1
{
class MyClass
{
void Method()
{
var e = Append;
[||]switch (e)
{
case CreateNew:
break;
case Create:
break;
case Open:
break;
case OpenOrCreate:
break;
default:
break;
}
}
}
}",
@"using static System.IO.FileMode;
namespace ConsoleApplication1
{
class MyClass
{
void Method()
{
var e = Append;
switch (e)
{
case CreateNew:
break;
case Create:
break;
case Open:
break;
case OpenOrCreate:
break;
case Truncate:
break;
case Append:
break;
default:
break;
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)]
public async Task UsingStaticEnum_NoMembersExist()
{
await TestAsync(
@"using static System.IO.FileMode;
namespace ConsoleApplication1
{
class MyClass
{
void Method()
{
var e = Append;
[||]switch (e)
{
}
}
}
}",
@"using static System.IO.FileMode;
namespace ConsoleApplication1
{
class MyClass
{
void Method()
{
var e = Append;
switch (e)
{
case CreateNew:
break;
case Create:
break;
case Open:
break;
case OpenOrCreate:
break;
case Truncate:
break;
case Append:
break;
default:
break;
}
}
}
}", index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)]
public async Task NotAllMembersExist_NotDefault_EnumHasNonFlagsAttribute()
{
await TestAsync(
@"namespace ConsoleApplication1
{
[System.Obsolete]
enum MyEnum
{
Fizz,
Buzz,
FizzBuzz
}
class MyClass
{
void Method()
{
var e = MyEnum.Fizz;
[||]switch (e)
{
case MyEnum.Fizz:
case MyEnum.Buzz:
break;
}
}
}
}",
@"namespace ConsoleApplication1
{
[System.Obsolete]
enum MyEnum
{
Fizz,
Buzz,
FizzBuzz
}
class MyClass
{
void Method()
{
var e = MyEnum.Fizz;
switch (e)
{
case MyEnum.Fizz:
case MyEnum.Buzz:
break;
case MyEnum.FizzBuzz:
break;
default:
break;
}
}
}
}", index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)]
public async Task NotAllMembersExist_NotDefault_EnumIsNested()
{
await TestAsync(
@"namespace ConsoleApplication1
{
class MyClass
{
enum MyEnum
{
Fizz,
Buzz,
FizzBuzz
}
void Method()
{
var e = MyEnum.Fizz;
[||]switch (e)
{
case MyEnum.Fizz:
case MyEnum.Buzz:
break;
}
}
}
}",
@"namespace ConsoleApplication1
{
class MyClass
{
enum MyEnum
{
Fizz,
Buzz,
FizzBuzz
}
void Method()
{
var e = MyEnum.Fizz;
switch (e)
{
case MyEnum.Fizz:
case MyEnum.Buzz:
break;
case MyEnum.FizzBuzz:
break;
default:
break;
}
}
}
}", index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)]
public async Task NotAllMembersExist_SwitchIsNotEnum()
{
await TestMissingAsync(
@"using System;
namespace ConsoleApplication1
{
class MyClass
{
void Method()
{
var e = ""test"";
[||]switch (e)
{
case ""test1"":
case ""test1"":
default:
break;
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)]
public async Task NotAllMembersExist_NotDefault_UsingConstants()
{
await TestAsync(
@"enum MyEnum
{
Fizz,
Buzz,
FizzBuzz
}
class MyClass
{
void Method()
{
var e = MyEnum.Fizz;
[||]switch (e)
{
case (MyEnum)0:
case (MyEnum)1:
break;
}
}
}",
@"enum MyEnum
{
Fizz,
Buzz,
FizzBuzz
}
class MyClass
{
void Method()
{
var e = MyEnum.Fizz;
switch (e)
{
case (MyEnum)0:
case (MyEnum)1:
break;
case MyEnum.FizzBuzz:
break;
default:
break;
}
}
}", index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)]
[WorkItem(13455, "https://github.com/dotnet/roslyn/issues/13455")]
public async Task AllMissingTokens()
{
await TestAsync(
@"
enum MyEnum
{
Fizz
}
class MyClass
{
void Method()
{
var e = MyEnum.Fizz;
[||]switch (e)
}
}
",
@"
enum MyEnum
{
Fizz
}
class MyClass
{
void Method()
{
var e = MyEnum.Fizz;
switch (e)
{
case MyEnum.Fizz:
break;
}
}
}", compareTokens: false);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace System.Threading.Channels.Tests
{
public abstract class ChannelTestBase : TestBase
{
protected abstract Channel<int> CreateChannel();
protected abstract Channel<int> CreateFullChannel();
protected virtual bool RequiresSingleReader => false;
protected virtual bool RequiresSingleWriter => false;
protected virtual bool BuffersItems => true;
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Requires internal reflection on framework types.")]
[Fact]
public void ValidateDebuggerAttributes()
{
Channel<int> c = CreateChannel();
for (int i = 1; i <= 10; i++)
{
c.Writer.WriteAsync(i);
}
DebuggerAttributes.ValidateDebuggerDisplayReferences(c);
DebuggerAttributes.InvokeDebuggerTypeProxyProperties(c);
}
[Fact]
public void Cast_MatchesInOut()
{
Channel<int> c = CreateChannel();
ChannelReader<int> rc = c;
ChannelWriter<int> wc = c;
Assert.Same(rc, c.Reader);
Assert.Same(wc, c.Writer);
}
[Fact]
public void Completion_Idempotent()
{
Channel<int> c = CreateChannel();
Task completion = c.Reader.Completion;
Assert.Equal(TaskStatus.WaitingForActivation, completion.Status);
Assert.Same(completion, c.Reader.Completion);
c.Writer.Complete();
Assert.Same(completion, c.Reader.Completion);
Assert.Equal(TaskStatus.RanToCompletion, completion.Status);
}
[Fact]
public async Task Complete_AfterEmpty_NoWaiters_TriggersCompletion()
{
Channel<int> c = CreateChannel();
c.Writer.Complete();
await c.Reader.Completion;
}
[Fact]
public async Task Complete_AfterEmpty_WaitingReader_TriggersCompletion()
{
Channel<int> c = CreateChannel();
Task<int> r = c.Reader.ReadAsync().AsTask();
c.Writer.Complete();
await c.Reader.Completion;
await Assert.ThrowsAnyAsync<InvalidOperationException>(() => r);
}
[Fact]
public async Task Complete_BeforeEmpty_WaitingReaders_TriggersCompletion()
{
Channel<int> c = CreateChannel();
Task<int> read = c.Reader.ReadAsync().AsTask();
c.Writer.Complete();
await c.Reader.Completion;
await Assert.ThrowsAnyAsync<InvalidOperationException>(() => read);
}
[Fact]
public void Complete_Twice_ThrowsInvalidOperationException()
{
Channel<int> c = CreateChannel();
c.Writer.Complete();
Assert.ThrowsAny<InvalidOperationException>(() => c.Writer.Complete());
}
[Fact]
public void TryComplete_Twice_ReturnsTrueThenFalse()
{
Channel<int> c = CreateChannel();
Assert.True(c.Writer.TryComplete());
Assert.False(c.Writer.TryComplete());
Assert.False(c.Writer.TryComplete());
}
[Fact]
public async Task TryComplete_ErrorsPropage()
{
Channel<int> c;
// Success
c = CreateChannel();
Assert.True(c.Writer.TryComplete());
await c.Reader.Completion;
// Error
c = CreateChannel();
Assert.True(c.Writer.TryComplete(new FormatException()));
await Assert.ThrowsAsync<FormatException>(() => c.Reader.Completion);
// Canceled
c = CreateChannel();
var cts = new CancellationTokenSource();
cts.Cancel();
Assert.True(c.Writer.TryComplete(new OperationCanceledException(cts.Token)));
await AssertCanceled(c.Reader.Completion, cts.Token);
}
[Fact]
public void SingleProducerConsumer_ConcurrentReadWrite_Success()
{
Channel<int> c = CreateChannel();
const int NumItems = 100000;
Task.WaitAll(
Task.Run(async () =>
{
for (int i = 0; i < NumItems; i++)
{
await c.Writer.WriteAsync(i);
}
}),
Task.Run(async () =>
{
for (int i = 0; i < NumItems; i++)
{
Assert.Equal(i, await c.Reader.ReadAsync());
}
}));
}
[Fact]
public void SingleProducerConsumer_PingPong_Success()
{
Channel<int> c1 = CreateChannel();
Channel<int> c2 = CreateChannel();
const int NumItems = 100000;
Task.WaitAll(
Task.Run(async () =>
{
for (int i = 0; i < NumItems; i++)
{
Assert.Equal(i, await c1.Reader.ReadAsync());
await c2.Writer.WriteAsync(i);
}
}),
Task.Run(async () =>
{
for (int i = 0; i < NumItems; i++)
{
await c1.Writer.WriteAsync(i);
Assert.Equal(i, await c2.Reader.ReadAsync());
}
}));
}
[Theory]
[InlineData(1, 1)]
[InlineData(1, 10)]
[InlineData(10, 1)]
[InlineData(10, 10)]
public void ManyProducerConsumer_ConcurrentReadWrite_Success(int numReaders, int numWriters)
{
if (RequiresSingleReader && numReaders > 1)
{
return;
}
if (RequiresSingleWriter && numWriters > 1)
{
return;
}
Channel<int> c = CreateChannel();
const int NumItems = 10000;
long readTotal = 0;
int remainingWriters = numWriters;
int remainingItems = NumItems;
Task[] tasks = new Task[numWriters + numReaders];
for (int i = 0; i < numReaders; i++)
{
tasks[i] = Task.Run(async () =>
{
try
{
while (await c.Reader.WaitToReadAsync())
{
if (c.Reader.TryRead(out int value))
{
Interlocked.Add(ref readTotal, value);
}
}
}
catch (ChannelClosedException) { }
});
}
for (int i = 0; i < numWriters; i++)
{
tasks[numReaders + i] = Task.Run(async () =>
{
while (true)
{
int value = Interlocked.Decrement(ref remainingItems);
if (value < 0)
{
break;
}
await c.Writer.WriteAsync(value + 1);
}
if (Interlocked.Decrement(ref remainingWriters) == 0)
{
c.Writer.Complete();
}
});
}
Task.WaitAll(tasks);
Assert.Equal((NumItems * (NumItems + 1L)) / 2, readTotal);
}
[Fact]
public void WaitToReadAsync_DataAvailableBefore_CompletesSynchronously()
{
Channel<int> c = CreateChannel();
Task write = c.Writer.WriteAsync(42);
Task<bool> read = c.Reader.WaitToReadAsync();
Assert.Equal(TaskStatus.RanToCompletion, read.Status);
}
[Fact]
public void WaitToReadAsync_DataAvailableAfter_CompletesAsynchronously()
{
Channel<int> c = CreateChannel();
Task<bool> read = c.Reader.WaitToReadAsync();
Assert.False(read.IsCompleted);
Task write = c.Writer.WriteAsync(42);
Assert.True(read.Result);
}
[Fact]
public void WaitToReadAsync_AfterComplete_SynchronouslyCompletes()
{
Channel<int> c = CreateChannel();
c.Writer.Complete();
Task<bool> read = c.Reader.WaitToReadAsync();
Assert.Equal(TaskStatus.RanToCompletion, read.Status);
Assert.False(read.Result);
}
[Fact]
public void WaitToReadAsync_BeforeComplete_AsynchronouslyCompletes()
{
Channel<int> c = CreateChannel();
Task<bool> read = c.Reader.WaitToReadAsync();
Assert.False(read.IsCompleted);
c.Writer.Complete();
Assert.False(read.Result);
}
[Fact]
public void WaitToWriteAsync_AfterComplete_SynchronouslyCompletes()
{
Channel<int> c = CreateChannel();
c.Writer.Complete();
Task<bool> write = c.Writer.WaitToWriteAsync();
Assert.Equal(TaskStatus.RanToCompletion, write.Status);
Assert.False(write.Result);
}
[Fact]
public void WaitToWriteAsync_EmptyChannel_SynchronouslyCompletes()
{
if (!BuffersItems)
{
return;
}
Channel<int> c = CreateChannel();
Task<bool> write = c.Writer.WaitToWriteAsync();
Assert.Equal(TaskStatus.RanToCompletion, write.Status);
Assert.True(write.Result);
}
[Fact]
public async Task WaitToWriteAsync_ManyConcurrent_SatisifedByReaders()
{
if (RequiresSingleReader || RequiresSingleWriter)
{
return;
}
Channel<int> c = CreateChannel();
Task[] writers = Enumerable.Range(0, 100).Select(_ => c.Writer.WaitToWriteAsync()).ToArray();
Task[] readers = Enumerable.Range(0, 100).Select(_ => c.Reader.ReadAsync().AsTask()).ToArray();
await Task.WhenAll(writers);
}
[Fact]
public void WaitToWriteAsync_BlockedReader_ReturnsTrue()
{
Channel<int> c = CreateChannel();
ValueTask<int> reader = c.Reader.ReadAsync();
AssertSynchronousSuccess(c.Writer.WaitToWriteAsync());
}
[Fact]
public void TryRead_DataAvailable_Success()
{
Channel<int> c = CreateChannel();
Task write = c.Writer.WriteAsync(42);
Assert.True(c.Reader.TryRead(out int result));
Assert.Equal(42, result);
}
[Fact]
public void TryRead_AfterComplete_ReturnsFalse()
{
Channel<int> c = CreateChannel();
c.Writer.Complete();
Assert.False(c.Reader.TryRead(out int result));
}
[Fact]
public void TryWrite_AfterComplete_ReturnsFalse()
{
Channel<int> c = CreateChannel();
c.Writer.Complete();
Assert.False(c.Writer.TryWrite(42));
}
[Fact]
public async Task WriteAsync_AfterComplete_ThrowsException()
{
Channel<int> c = CreateChannel();
c.Writer.Complete();
await Assert.ThrowsAnyAsync<InvalidOperationException>(() => c.Writer.WriteAsync(42));
}
[Fact]
public async Task Complete_WithException_PropagatesToCompletion()
{
Channel<int> c = CreateChannel();
var exc = new FormatException();
c.Writer.Complete(exc);
Assert.Same(exc, await Assert.ThrowsAsync<FormatException>(() => c.Reader.Completion));
}
[Fact]
public async Task Complete_WithCancellationException_PropagatesToCompletion()
{
Channel<int> c = CreateChannel();
var cts = new CancellationTokenSource();
cts.Cancel();
Exception exc = null;
try { cts.Token.ThrowIfCancellationRequested(); }
catch (Exception e) { exc = e; }
c.Writer.Complete(exc);
await AssertCanceled(c.Reader.Completion, cts.Token);
}
[Fact]
public async Task Complete_WithException_PropagatesToExistingWriter()
{
Channel<int> c = CreateFullChannel();
if (c != null)
{
Task write = c.Writer.WriteAsync(42);
var exc = new FormatException();
c.Writer.Complete(exc);
Assert.Same(exc, (await Assert.ThrowsAsync<ChannelClosedException>(() => write)).InnerException);
}
}
[Fact]
public async Task Complete_WithException_PropagatesToNewWriter()
{
Channel<int> c = CreateChannel();
var exc = new FormatException();
c.Writer.Complete(exc);
Task write = c.Writer.WriteAsync(42);
Assert.Same(exc, (await Assert.ThrowsAsync<ChannelClosedException>(() => write)).InnerException);
}
[Fact]
public async Task Complete_WithException_PropagatesToExistingWaitingReader()
{
Channel<int> c = CreateChannel();
Task<bool> read = c.Reader.WaitToReadAsync();
var exc = new FormatException();
c.Writer.Complete(exc);
await Assert.ThrowsAsync<FormatException>(() => read);
}
[Fact]
public async Task Complete_WithException_PropagatesToNewWaitingReader()
{
Channel<int> c = CreateChannel();
var exc = new FormatException();
c.Writer.Complete(exc);
Task<bool> read = c.Reader.WaitToReadAsync();
await Assert.ThrowsAsync<FormatException>(() => read);
}
[Fact]
public async Task Complete_WithException_PropagatesToNewWaitingWriter()
{
Channel<int> c = CreateChannel();
var exc = new FormatException();
c.Writer.Complete(exc);
Task<bool> write = c.Writer.WaitToWriteAsync();
await Assert.ThrowsAsync<FormatException>(() => write);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
public void ManyWriteAsync_ThenManyTryRead_Success(int readMode)
{
if (RequiresSingleReader || RequiresSingleWriter)
{
return;
}
Channel<int> c = CreateChannel();
const int NumItems = 2000;
Task[] writers = new Task[NumItems];
for (int i = 0; i < writers.Length; i++)
{
writers[i] = c.Writer.WriteAsync(i);
}
Task<int>[] readers = new Task<int>[NumItems];
for (int i = 0; i < readers.Length; i++)
{
int result;
Assert.True(c.Reader.TryRead(out result));
Assert.Equal(i, result);
}
Assert.All(writers, w => Assert.True(w.IsCompleted));
}
[Fact]
public void Precancellation_Writing_ReturnsImmediately()
{
Channel<int> c = CreateChannel();
Task writeTask = c.Writer.WriteAsync(42, new CancellationToken(true));
Assert.Equal(TaskStatus.Canceled, writeTask.Status);
Task<bool> waitTask = c.Writer.WaitToWriteAsync(new CancellationToken(true));
Assert.Equal(TaskStatus.Canceled, waitTask.Status);
}
[Fact]
public void Write_WaitToReadAsync_CompletesSynchronously()
{
Channel<int> c = CreateChannel();
c.Writer.WriteAsync(42);
AssertSynchronousTrue(c.Reader.WaitToReadAsync());
}
[Fact]
public void Precancellation_WaitToReadAsync_ReturnsImmediately()
{
Channel<int> c = CreateChannel();
Task writeTask = c.Reader.WaitToReadAsync(new CancellationToken(true));
Assert.Equal(TaskStatus.Canceled, writeTask.Status);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task WaitToReadAsync_DataWritten_CompletesSuccessfully(bool cancelable)
{
Channel<int> c = CreateChannel();
CancellationToken token = cancelable ? new CancellationTokenSource().Token : default;
Task<bool> read = c.Reader.WaitToReadAsync(token);
Assert.False(read.IsCompleted);
Task write = c.Writer.WriteAsync(42, token);
Assert.True(await read);
}
[Fact]
public async Task WaitToReadAsync_NoDataWritten_Canceled_CompletesAsCanceled()
{
Channel<int> c = CreateChannel();
var cts = new CancellationTokenSource();
Task<bool> read = c.Reader.WaitToReadAsync(cts.Token);
Assert.False(read.IsCompleted);
cts.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => read);
}
[Fact]
public async Task ReadAsync_ThenWriteAsync_Succeeds()
{
Channel<int> c = CreateChannel();
ValueTask<int> r = c.Reader.ReadAsync();
Assert.False(r.IsCompleted);
Task w = c.Writer.WriteAsync(42);
AssertSynchronousSuccess(w);
Assert.Equal(42, await r);
}
[Fact]
public async Task WriteAsync_ReadAsync_Succeeds()
{
Channel<int> c = CreateChannel();
Task w = c.Writer.WriteAsync(42);
ValueTask<int> r = c.Reader.ReadAsync();
await Task.WhenAll(w, r.AsTask());
Assert.Equal(42, await r);
}
[Fact]
public void ReadAsync_Precanceled_CanceledSynchronously()
{
Channel<int> c = CreateChannel();
var cts = new CancellationTokenSource();
cts.Cancel();
AssertSynchronouslyCanceled(c.Reader.ReadAsync(cts.Token).AsTask(), cts.Token);
}
[Fact]
public async Task ReadAsync_Canceled_CanceledAsynchronously()
{
Channel<int> c = CreateChannel();
var cts = new CancellationTokenSource();
ValueTask<int> r = c.Reader.ReadAsync(cts.Token);
Assert.False(r.IsCompleted);
cts.Cancel();
await AssertCanceled(r.AsTask(), cts.Token);
if (c.Writer.TryWrite(42))
{
Assert.Equal(42, await c.Reader.ReadAsync());
}
}
[Fact]
public async Task ReadAsync_WriteAsync_ManyConcurrentReaders_SerializedWriters_Success()
{
if (RequiresSingleReader)
{
return;
}
Channel<int> c = CreateChannel();
const int Items = 100;
ValueTask<int>[] readers = (from i in Enumerable.Range(0, Items) select c.Reader.ReadAsync()).ToArray();
for (int i = 0; i < Items; i++)
{
await c.Writer.WriteAsync(i);
}
Assert.Equal((Items * (Items - 1)) / 2, Enumerable.Sum(await Task.WhenAll(readers.Select(r => r.AsTask()))));
}
[Fact]
public async Task ReadAsync_TryWrite_ManyConcurrentReaders_SerializedWriters_Success()
{
if (RequiresSingleReader)
{
return;
}
Channel<int> c = CreateChannel();
const int Items = 100;
ValueTask<int>[] readers = (from i in Enumerable.Range(0, Items) select c.Reader.ReadAsync()).ToArray();
var remainingReaders = new List<Task<int>>(readers.Select(r => r.AsTask()));
for (int i = 0; i < Items; i++)
{
Assert.True(c.Writer.TryWrite(i), $"Failed to write at {i}");
Task<int> r = await Task.WhenAny(remainingReaders);
await r;
remainingReaders.Remove(r);
}
Assert.Equal((Items * (Items - 1)) / 2, Enumerable.Sum(await Task.WhenAll(readers.Select(r => r.AsTask()))));
}
[Fact]
public async Task ReadAsync_AlreadyCompleted_Throws()
{
Channel<int> c = CreateChannel();
c.Writer.Complete();
await Assert.ThrowsAsync<ChannelClosedException>(() => c.Reader.ReadAsync().AsTask());
}
[Fact]
public async Task ReadAsync_SubsequentlyCompleted_Throws()
{
Channel<int> c = CreateChannel();
Task<int> r = c.Reader.ReadAsync().AsTask();
Assert.False(r.IsCompleted);
c.Writer.Complete();
await Assert.ThrowsAsync<ChannelClosedException>(() => r);
}
[Fact]
public async Task ReadAsync_AfterFaultedChannel_Throws()
{
Channel<int> c = CreateChannel();
var e = new FormatException();
c.Writer.Complete(e);
Assert.True(c.Reader.Completion.IsFaulted);
ChannelClosedException cce = await Assert.ThrowsAsync<ChannelClosedException>(() => c.Reader.ReadAsync().AsTask());
Assert.Same(e, cce.InnerException);
}
[Fact]
public async Task ReadAsync_AfterCanceledChannel_Throws()
{
Channel<int> c = CreateChannel();
var e = new OperationCanceledException();
c.Writer.Complete(e);
Assert.True(c.Reader.Completion.IsCanceled);
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => c.Reader.ReadAsync().AsTask());
}
[Fact]
public async Task ReadAsync_Canceled_WriteAsyncCompletesNextReader()
{
Channel<int> c = CreateChannel();
for (int i = 0; i < 5; i++)
{
var cts = new CancellationTokenSource();
ValueTask<int> r = c.Reader.ReadAsync(cts.Token);
cts.Cancel();
await AssertCanceled(r.AsTask(), cts.Token);
}
for (int i = 0; i < 7; i++)
{
ValueTask<int> r = c.Reader.ReadAsync();
await c.Writer.WriteAsync(i);
Assert.Equal(i, await r);
}
}
}
}
| |
//
// ContentObject.cs
//
// Author: Jeffrey Stedfast <[email protected]>
//
// Copyright (c) 2013-2016 Xamarin Inc. (www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.IO;
using System.Threading;
using MimeKit.IO;
using MimeKit.IO.Filters;
namespace MimeKit {
/// <summary>
/// Encapsulates a content stream used by <see cref="MimeKit.MimePart"/>.
/// </summary>
/// <remarks>
/// A <see cref="ContentObject"/> represents the content of a <see cref="MimePart"/>.
/// The content has both a stream and an encoding (typically <see cref="ContentEncoding.Default"/>).
/// </remarks>
public class ContentObject : IContentObject
{
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.ContentObject"/> class.
/// </summary>
/// <remarks>
/// When creating new <see cref="MimeKit.MimePart"/>s, the <paramref name="encoding"/>
/// should typically be <see cref="MimeKit.ContentEncoding.Default"/> unless the
/// <paramref name="stream"/> has already been encoded.
/// </remarks>
/// <param name="stream">The content stream.</param>
/// <param name="encoding">The stream encoding.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="stream"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentException">
/// <para><paramref name="stream"/> does not support reading.</para>
/// <para>-or-</para>
/// <para><paramref name="stream"/> does not support seeking.</para>
/// </exception>
public ContentObject (Stream stream, ContentEncoding encoding = ContentEncoding.Default)
{
if (stream == null)
throw new ArgumentNullException ("stream");
if (!stream.CanRead)
throw new ArgumentException ("The stream does not support reading.", "stream");
if (!stream.CanSeek)
throw new ArgumentException ("The stream does not support seeking.", "stream");
Encoding = encoding;
Stream = stream;
}
#region IContentObject implementation
/// <summary>
/// Gets or sets the content encoding.
/// </summary>
/// <remarks>
/// If the <see cref="MimePart"/> was parsed from an existing stream, the
/// encoding will be identical to the <see cref="MimePart.ContentTransferEncoding"/>,
/// otherwise it will typically be <see cref="ContentEncoding.Default"/>.
/// </remarks>
/// <value>The content encoding.</value>
public ContentEncoding Encoding {
get; private set;
}
/// <summary>
/// Gets the content stream.
/// </summary>
/// <remarks>
/// Gets the content stream.
/// </remarks>
/// <value>The stream.</value>
public Stream Stream {
get; private set;
}
/// <summary>
/// Opens the decoded content stream.
/// </summary>
/// <remarks>
/// Provides a means of reading the decoded content without having to first write it to another
/// stream using <see cref="DecodeTo(System.IO.Stream,System.Threading.CancellationToken)"/>.
/// </remarks>
/// <returns>The decoded content stream.</returns>
public Stream Open ()
{
Stream.Seek (0, SeekOrigin.Begin);
var filtered = new FilteredStream (Stream);
filtered.Add (DecoderFilter.Create (Encoding));
return filtered;
}
/// <summary>
/// Copies the content stream to the specified output stream.
/// </summary>
/// <remarks>
/// This is equivalent to simply using <see cref="System.IO.Stream.CopyTo(System.IO.Stream)"/> to
/// copy the content stream to the output stream except that this method is
/// cancellable.
/// </remarks>
/// <param name="stream">The output stream.</param>
/// <param name="cancellationToken">A cancellation token.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="stream"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.OperationCanceledException">
/// The operation was canceled via the cancellation token.
/// </exception>
/// <exception cref="System.IO.IOException">
/// An I/O error occurred.
/// </exception>
public void WriteTo (Stream stream, CancellationToken cancellationToken = default (CancellationToken))
{
if (stream == null)
throw new ArgumentNullException ("stream");
var readable = Stream as ICancellableStream;
var writable = stream as ICancellableStream;
var buf = new byte[4096];
int nread;
Stream.Seek (0, SeekOrigin.Begin);
try {
do {
if (readable != null) {
if ((nread = readable.Read (buf, 0, buf.Length, cancellationToken)) <= 0)
break;
} else {
cancellationToken.ThrowIfCancellationRequested ();
if ((nread = Stream.Read (buf, 0, buf.Length)) <= 0)
break;
}
if (writable != null) {
writable.Write (buf, 0, nread, cancellationToken);
} else {
cancellationToken.ThrowIfCancellationRequested ();
stream.Write (buf, 0, nread);
}
} while (true);
Stream.Seek (0, SeekOrigin.Begin);
} catch (OperationCanceledException) {
// try and reset the stream
try {
Stream.Seek (0, SeekOrigin.Begin);
} catch (IOException) {
}
throw;
}
}
/// <summary>
/// Decodes the content stream into another stream.
/// </summary>
/// <remarks>
/// Uses the <see cref="Encoding"/> to decode the content stream to the output stream.
/// </remarks>
/// <param name="stream">The output stream.</param>
/// <param name="cancellationToken">A cancellation token.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="stream"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.OperationCanceledException">
/// The operation was canceled via the cancellation token.
/// </exception>
/// <exception cref="System.IO.IOException">
/// An I/O error occurred.
/// </exception>
public void DecodeTo (Stream stream, CancellationToken cancellationToken = default (CancellationToken))
{
if (stream == null)
throw new ArgumentNullException ("stream");
using (var filtered = new FilteredStream (stream)) {
filtered.Add (DecoderFilter.Create (Encoding));
WriteTo (filtered, cancellationToken);
filtered.Flush (cancellationToken);
}
}
#endregion
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Windows.Devices.Usb;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using SDKTemplate;
using CustomUsbDeviceAccess;
namespace CustomUsbDeviceAccess
{
/// <summary>
/// This page demonstrates how to use control transfers to communicate with the device.
/// </summary>
public sealed partial class Scenario2_ControlTransfer : Page
{
// A pointer back to the main page. This is needed if you want to call methods in MainPage such
// as NotifyUser()
private MainPage rootPage = MainPage.Current;
public Scenario2_ControlTransfer()
{
this.InitializeComponent();
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
///
/// We will enable/disable parts of the UI if the device doesn't support it.
/// </summary>
/// <param name="eventArgs">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs eventArgs)
{
// We will disable the scenario that is not supported by the device.
// If no devices are connected, none of the scenarios will be shown and an error will be displayed
Dictionary<DeviceType, UIElement> deviceScenarios = new Dictionary<DeviceType, UIElement>();
deviceScenarios.Add(DeviceType.OsrFx2, OsrFx2Scenario);
deviceScenarios.Add(DeviceType.SuperMutt, SuperMuttScenario);
Utilities.SetUpDeviceScenarios(deviceScenarios, DeviceScenarioContainer);
}
private async void GetOsrFx2SevenSegmentSetting_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
if (EventHandlerForDevice.Current.IsDeviceConnected)
{
ButtonGetOsrFx2SevenSegment.IsEnabled = false;
await GetOsrFx2SevenSegmentAsync();
ButtonGetOsrFx2SevenSegment.IsEnabled = true;
}
else
{
Utilities.NotifyDeviceNotConnected();
}
}
async void SetOsrFx2SevenSegmentSetting_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
if (EventHandlerForDevice.Current.IsDeviceConnected)
{
ButtonSetOsrFx2SevenSegment.IsEnabled = false;
Byte numericValue = (Byte)OsrFx2SevenSegmentSettingInput.SelectedIndex;
await SetOsrFx2SevenSegmentAsync(numericValue);
ButtonSetOsrFx2SevenSegment.IsEnabled = true;
}
else
{
Utilities.NotifyDeviceNotConnected();
}
}
async void GetSuperMuttLedBlinkPattern_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
if (EventHandlerForDevice.Current.IsDeviceConnected)
{
ButtonGetSuperMuttLedBlinkPattern.IsEnabled = false;
await GetSuperMuttLedBlinkPatternAsync();
ButtonGetSuperMuttLedBlinkPattern.IsEnabled = true;
}
else
{
Utilities.NotifyDeviceNotConnected();
}
}
async void SetSuperMuttLedBlinkPattern_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
if (EventHandlerForDevice.Current.IsDeviceConnected)
{
ButtonSetSuperMuttLedBlinkPattern.IsEnabled = false;
Byte pattern = (Byte)SuperMuttLedBlinkPatternInput.SelectedIndex;
await SetSuperMuttLedBlinkPatternAsync(pattern);
ButtonSetSuperMuttLedBlinkPattern.IsEnabled = true;
}
else
{
Utilities.NotifyDeviceNotConnected();
}
}
/// <summary>
/// Sets the seven segment display on the OSRFX2 device via control transfer
///
/// Before sending the data through the control transfer, the numeric value is converted into a hex value that is
/// bit masked. Different sections of the bit mask will turn on a different LEDs. Please refer to the OSRFX2 spec
/// to see the hex values per LED.
///
/// Any errors in async function will be passed down the task chain and will not be caught here because errors should be
/// handled at the end of the task chain.
///
/// Setting Seven Segment LED require setup packet:
/// bmRequestType: type: VENDOR
/// recipient: DEVICE
/// bRequest: 0xDB
/// wLength: 1
///
/// The Buffer is used to hold data that is meant to be sent over during the data phase.
/// The easiest way to write data to an IBuffer is to use a DataWriter. The DataWriter, when instantiated,
/// creates a buffer internally. The buffer is of type IBuffer and can be detached from the writer, which gives us
/// the internal IBuffer.
/// </summary>
/// <param name="numericValue"></param>
/// <returns>A task that can be used to chain more methods after completing the scenario</returns>
async Task SetOsrFx2SevenSegmentAsync(Byte numericValue)
{
DataWriter writer = new DataWriter();
// Convert the numeric value into a 7 segment LED hex value and write it to a buffer.
writer.WriteByte(OsrFx2.SevenLedSegmentMask[numericValue]);
// The buffer with the data
var bufferToSend = writer.DetachBuffer();
UsbSetupPacket setupPacket = new UsbSetupPacket
{
RequestType = new UsbControlRequestType
{
Direction = UsbTransferDirection.Out,
Recipient = UsbControlRecipient.Device,
ControlTransferType = UsbControlTransferType.Vendor
},
Request = OsrFx2.VendorCommand.SetSevenSegment,
Value = 0,
Length = bufferToSend.Length
};
UInt32 bytesTransferred = await EventHandlerForDevice.Current.Device.SendControlOutTransferAsync(setupPacket, bufferToSend);
// Make sure we sent the correct number of bytes
if (bytesTransferred == bufferToSend.Length)
{
MainPage.Current.NotifyUser("The segment display value is set to " + numericValue.ToString(), NotifyType.StatusMessage);
}
else
{
MainPage.Current.NotifyUser(
"Error sending data. Sent bytes: " + bytesTransferred.ToString() + "; Tried to send : " + bufferToSend.Length,
NotifyType.ErrorMessage);
}
}
/// <summary>
/// Gets the current value of the seven segment display on the OSRFX2 device via control transfer.
///
/// Any errors in async function will be passed down the task chain and will not be caught here because errors should be handled at the
/// end of the task chain.
///
/// When the seven segment hex value is received, we attempt to match it with a known (has a numerical value 0-9) hex value.
///
/// Getting Seven Segment LED require setup packet:
/// bmRequestType: type: VENDOR
/// recipient: DEVICE
/// bRequest: 0xD4
/// wLength: 1
/// </summary>
/// <returns>A task that can be used to chain more methods after completing the scenario</returns>
async Task GetOsrFx2SevenSegmentAsync()
{
// We expect to receive 1 byte of data with our control transfer, which is the state of the seven segment
uint receiveDataSize = 1;
// The Seven Segment display value is only 1 byte
IBuffer dataBuffer = await SendVendorControlTransferInToDeviceRecipientAsync(OsrFx2.VendorCommand.GetSevenSegment, receiveDataSize);
if (dataBuffer.Length == receiveDataSize)
{
DataReader reader = DataReader.FromBuffer(dataBuffer);
// The raw hex value representing the seven segment display
Byte rawValue = reader.ReadByte();
// The LED can't display the value of 255, so if the value
// we receive is not a number, we'll know by seeing if this value changed
Byte readableValue = 255;
// Find which numeric value has the segment hex value
for (int i = 0; i < OsrFx2.SevenLedSegmentMask.Length; i += 1)
{
if (rawValue == OsrFx2.SevenLedSegmentMask[i])
{
readableValue = (Byte)i;
break;
}
}
// Seven Segment cannot display value 255, the value we received isn't a number
if (readableValue == 255)
{
MainPage.Current.NotifyUser("The segment display is not yet initialized", NotifyType.ErrorMessage);
}
else
{
MainPage.Current.NotifyUser("The segment display value is " + readableValue.ToString(), NotifyType.StatusMessage);
}
}
else
{
MainPage.Current.NotifyUser(
"Expected to read " + receiveDataSize.ToString() + " bytes, but got " + dataBuffer.Length.ToString(),
NotifyType.ErrorMessage);
}
}
/// <summary>
/// Initiates a control transfer to set the blink pattern on the SuperMutt's LED.
///
/// Any errors in async function will be passed down the task chain and will not be caught here because errors should be handled
/// at the end of the task chain.
///
/// Setting LED blink pattern require setup packet:
/// bmRequestType: type: VENDOR
/// recipient: DEVICE
/// bRequest: 0x03
/// wValue: 0-7 (any number in that range, inclusive)
/// wLength: 0
///
/// The SuperMutt has the following patterns:
/// 0 - LED always on
/// 1 - LED flash 2 seconds on, 2 off, repeat
/// 2 - LED flash 2 seconds on, 1 off, 2 on, 4 off, repeat
/// ...
/// 7 - 7 iterations of 2 on, 1 off, followed by 4 off, repeat
/// </summary>
/// <param name="pattern">A number from 0-7. Each number represents a different blinking pattern</param>
/// <returns>A task that can be used to chain more methods after completing the scenario</returns>
async Task SetSuperMuttLedBlinkPatternAsync(Byte pattern)
{
UsbSetupPacket setupPacket = new UsbSetupPacket
{
RequestType = new UsbControlRequestType
{
Direction = UsbTransferDirection.Out,
Recipient = UsbControlRecipient.Device,
ControlTransferType = UsbControlTransferType.Vendor
},
Request = SuperMutt.VendorCommand.SetLedBlinkPattern,
Value = pattern,
Length = 0
};
UInt32 bytesTransferred = await EventHandlerForDevice.Current.Device.SendControlOutTransferAsync(setupPacket);
MainPage.Current.NotifyUser("The Led blink pattern is set to " + pattern.ToString(), NotifyType.StatusMessage);
}
/// <summary>
/// Sets up a UsbSetupPacket that will let the device know that we are trying to get the Led blink pattern on the SuperMutt via
/// control transfer.
///
/// Any errors in async function will be passed down the task chain and will not be caught here because errors should
/// be handled at the end of the task chain.
///
/// The simplest way to obtain a byte from the buffer is by using a DataReader. DataReader provides a simple way
/// to read from buffers (e.g. can return bytes, strings, ints).
///
/// Do note the method that is used to send a control transfer. There are two methods to send a control transfer.
/// One is to send data and the other is to get data.
/// </summary>
/// <returns>A task that can be used to chain more methods after completing the scenario</returns>
async Task GetSuperMuttLedBlinkPatternAsync()
{
// The blink pattern is 1 byte long, so we only need to retrieve 1 byte of data
IBuffer buffer = await SendVendorControlTransferInToDeviceRecipientAsync(SuperMutt.VendorCommand.GetLedBlinkPattern, 1);
if (buffer.Length > 0)
{
// Easiest way to read from a buffer
DataReader dataReader = DataReader.FromBuffer(buffer);
Byte pattern = dataReader.ReadByte();
MainPage.Current.NotifyUser("The Led blink pattern is " + pattern.ToString(), NotifyType.StatusMessage);
}
else
{
MainPage.Current.NotifyUser("ControlInTransfer returned 0 bytes", NotifyType.ErrorMessage);
}
}
/// <summary>
/// Sets up a UsbSetupPacket and sends control transfer that will let the device know that we are trying to retrieve data from the device.
/// This method only supports vendor commands because the scenario only uses vendor commands.
///
/// Do note the method that is used to send a control transfer. There are two methods to send a control transfer.
/// One involves receiving buffer data in the Data stage of the control transfer, and the other involves transmiting the buffer data.
///
/// The simplest way to obtain a byte from the buffer is by using a DataReader. DataReader provides a simple way
/// to read from buffers (e.g. can return bytes, strings, ints).
/// </summary>
/// <param name="vendorCommand">Command to put into SetupPacket's Request property</param>
/// <param name="dataPacketLength">Number of bytes in the data packet that is sent in the Data Stage</param>
/// <returns>A task that can be used to chain more methods after completing the scenario</returns>
async Task<IBuffer> SendVendorControlTransferInToDeviceRecipientAsync(Byte vendorCommand, UInt32 dataPacketLength)
{
// Data will be written to this buffer when we receive it
var buffer = new Windows.Storage.Streams.Buffer(dataPacketLength);
UsbSetupPacket setupPacket = new UsbSetupPacket
{
RequestType = new UsbControlRequestType
{
Direction = UsbTransferDirection.In,
Recipient = UsbControlRecipient.Device,
ControlTransferType = UsbControlTransferType.Vendor,
},
Request = vendorCommand,
Length = dataPacketLength
};
return await EventHandlerForDevice.Current.Device.SendControlInTransferAsync(setupPacket, buffer);
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Augurk.Api;
using Augurk.Api.Indeces;
using Augurk.Api.Managers;
using Augurk.Entities;
using Microsoft.Extensions.Logging;
using NSubstitute;
using Raven.Client.Documents;
using Raven.Client.Documents.Session;
using Raven.Client;
using Shouldly;
using Xunit;
using Augurk.Entities.Test;
using System;
namespace Augurk.Test.Managers
{
/// <summary>
/// Contains tests for the <see cref="FeatureManager" /> class.
/// </summary>
public class FeatureManagerTests : RavenTestBase
{
private readonly ILogger<FeatureManager> logger = Substitute.For<ILogger<FeatureManager>>();
/// <summary>
/// Tests that the <see cref="FeatureManager" /> can get the available versions of a particular feature.
/// </summary>
[Fact]
public async Task GetsAvailableVersionsForFeature()
{
// Arrange
var documentStoreProvider = DocumentStoreProvider;
await documentStoreProvider.StoreDbFeatureAsync("MyProduct", "MyGroup", "MyFirstFeature", "1.0.0");
await documentStoreProvider.StoreDbFeatureAsync("MyProduct", "MyGroup", "MyFirstFeature", "2.0.0");
WaitForIndexing(documentStoreProvider.Store);
// Act
var sut = new FeatureManager(documentStoreProvider, logger);
var result = await sut.GetFeatureAvailableVersions("MyProduct", "MyGroup", "MyFirstFeature");
// Assert
result.ShouldNotBeNull();
result.SequenceEqual(new[] { "2.0.0", "1.0.0" }).ShouldBeTrue();
}
/// <summary>
/// Tests that the <see cref="ProductManager" /> class can retrieve a previously stored feature.
/// </summary>
[Fact]
public async Task GetsPreviouslyStoredVersion()
{
// Arrange
var documentStoreProvider = DocumentStoreProvider;
await documentStoreProvider.StoreDbFeatureAsync("MyProduct", "MyGroup", "MyFirstFeature", "0.0.0");
WaitForIndexing(documentStoreProvider.Store);
// Act
var sut = new FeatureManager(documentStoreProvider, logger);
var actualFeature = await sut.GetFeatureAsync("MyProduct", "MyGroup", "MyFirstFeature", "0.0.0");
// Assert
actualFeature.ShouldNotBeNull();
}
/// <summary>
/// Tests that the <see cref="FeatureManager" /> class can get a list of groups containing the features.
/// </summary>
[Fact]
public async Task CanGetGroupedFeatureDescriptions()
{
// Arrange
var documentStoreProvider = DocumentStoreProvider;
await documentStoreProvider.StoreDbFeatureAsync("MyProduct", "Group1", "MyFirstFeature", "0.0.0");
await documentStoreProvider.StoreDbFeatureAsync("MyProduct", "Group1", "MySecondFeature", "0.0.0");
await documentStoreProvider.StoreDbFeatureAsync("MyProduct", "Group2", "MyOtherFeature", "0.0.0");
WaitForIndexing(documentStoreProvider.Store);
// Act
var sut = new FeatureManager(documentStoreProvider, logger);
var result = await sut.GetGroupedFeatureDescriptionsAsync("MyProduct");
// Assert
result.ShouldNotBeNull();
result.Count().ShouldBe(2);
var firstGroup = result.FirstOrDefault();
firstGroup.ShouldNotBeNull();
firstGroup.Features.Count().ShouldBe(2);
firstGroup.Features.FirstOrDefault()?.Title.ShouldBe("MyFirstFeature");
firstGroup.Features.LastOrDefault()?.Title.ShouldBe("MySecondFeature");
var secondGroup = result.LastOrDefault();
secondGroup.ShouldNotBeNull();
secondGroup.Features.Count().ShouldBe(1);
secondGroup.Features.FirstOrDefault()?.Title.ShouldBe("MyOtherFeature");
}
/// <summary>
/// Tests that the <see cref="FeatureManager" /> class can get both groups when there's a single feature
/// under multiple groups.
/// </summary>
[Fact]
public async Task CanGetGroupedFeatureDescriptions_WithSameFeatureUnderMultipleGroups()
{
// Arrange
var documentStoreProvider = DocumentStoreProvider;
await documentStoreProvider.StoreDbFeatureAsync("MyProduct", "Group1", "MyFirstFeature", "0.0.0");
await documentStoreProvider.StoreDbFeatureAsync("MyProduct", "Group2", "MyFirstFeature", "0.0.0");
WaitForIndexing(documentStoreProvider.Store);
// Act
var sut = new FeatureManager(documentStoreProvider, logger);
var result = await sut.GetGroupedFeatureDescriptionsAsync("MyProduct");
// Assert
result.ShouldNotBeNull();
result.Count().ShouldBe(2);
var firstGroup = result.FirstOrDefault();
firstGroup.ShouldNotBeNull();
firstGroup.Features.Count().ShouldBe(1);
firstGroup.Features.FirstOrDefault()?.Title.ShouldBe("MyFirstFeature");
var secondGroup = result.LastOrDefault();
secondGroup.ShouldNotBeNull();
secondGroup.Features.Count().ShouldBe(1);
secondGroup.Features.FirstOrDefault()?.Title.ShouldBe("MyFirstFeature");
}
/// <summary>
/// Tests that the <see cref="FeatureManager" /> class does not duplicate features if multiple versions
/// of the same feature exist.
/// </summary>
[Fact]
public async Task CanGetGroupedFeatureDescriptions_DoesNotReturnSameFeatureIfMultipleVersionsExist()
{
// Arrange
var documentStoreProvider = DocumentStoreProvider;
await documentStoreProvider.StoreDbFeatureAsync("MyProduct", "Group1", "MyFirstFeature", "0.0.0");
await documentStoreProvider.StoreDbFeatureAsync("MyProduct", "Group1", "MyFirstFeature", "1.0.0");
WaitForIndexing(documentStoreProvider.Store);
// Act
var sut = new FeatureManager(documentStoreProvider, logger);
var result = await sut.GetGroupedFeatureDescriptionsAsync("MyProduct");
// Assert
result.ShouldNotBeNull();
result.Count().ShouldBe(1);
var firstGroup = result.FirstOrDefault();
firstGroup.ShouldNotBeNull();
firstGroup.Features.Count().ShouldBe(1);
firstGroup.Features.FirstOrDefault()?.Title.ShouldBe("MyFirstFeature");
}
/// <summary>
/// Tests that the <see cref="FeatureManager" /> class can get feature descriptions based on a branch and a tag.
/// </summary>
[Fact]
public async Task CanGetFeatureDescriptionsByBranchAndTagAsync()
{
// Arrange
var documentStoreProvider = DocumentStoreProvider;
await documentStoreProvider.StoreDbFeatureAsync("MyProduct", "Group1", "MyFirstFeature", "0.0.0", "tag1");
await documentStoreProvider.StoreDbFeatureAsync("MyProduct", "Group1", "MySecondFeature", "0.0.0", "tag1", "tag2");
await documentStoreProvider.StoreDbFeatureAsync("MyProduct", "Group2", "MyOtherFeature", "0.0.0", "tag3");
WaitForIndexing(documentStoreProvider.Store);
// Act
var sut = new FeatureManager(documentStoreProvider, logger);
var result = await sut.GetFeatureDescriptionsByBranchAndTagAsync("MyProduct", "tag1");
// Assert
result.ShouldNotBeNull();
result.Count().ShouldBe(2);
result.FirstOrDefault()?.Title.ShouldBe("MyFirstFeature");
result.LastOrDefault()?.Title.ShouldBe("MySecondFeature");
}
/// <summary>
/// Tests that the <see cref="FeatureManager" /> class can get feature descriptions based on a product and group.
/// </summary>
[Fact]
public async Task CanGetFeatureDescriptionsByProductAndGroupAsync()
{
// Arrange
var documentStoreProvider = DocumentStoreProvider;
await documentStoreProvider.StoreDbFeatureAsync("MyProduct", "Group1", "MyFirstFeature", "0.0.0");
await documentStoreProvider.StoreDbFeatureAsync("MyProduct", "Group2", "MySecondFeature", "0.0.0");
await documentStoreProvider.StoreDbFeatureAsync("MyOtherProduct", "Group1", "MyThirdFeature", "0.0.0");
WaitForIndexing(documentStoreProvider.Store);
// Act
var sut = new FeatureManager(documentStoreProvider, logger);
var result = await sut.GetFeatureDescriptionsByProductAndGroupAsync("MyProduct", "Group1");
// Assert
result.ShouldNotBeNull();
result.Count().ShouldBe(1);
result.FirstOrDefault()?.Title.ShouldBe("MyFirstFeature");
}
/// <summary>
/// Tests that the <see cref="FeatureManager" /> class can get features based on a product and version.
/// </summary>
[Fact]
public async Task CanGetDbFeaturesByProductAndVersionAsync()
{
// Arrange
var documentStoreProvider = DocumentStoreProvider;
await documentStoreProvider.Store.ExecuteIndexAsync(new Features_ByTitleProductAndGroup());
await documentStoreProvider.StoreDbFeatureAsync("MyProduct", "MyGroup", "MyFirstFeature", "0.0.0");
await documentStoreProvider.StoreDbFeatureAsync("MyProduct", "MyGroup", "MyFirstFeature", "1.0.0");
await documentStoreProvider.StoreDbFeatureAsync("MyProduct", "MyGroup", "MySecondFeature", "1.0.0");
await documentStoreProvider.StoreDbFeatureAsync("MyProduct", "MyGroup", "MyThirdFeature", "0.0.0");
WaitForIndexing(documentStoreProvider.Store);
// Act
var sut = new FeatureManager(documentStoreProvider, logger);
var result = await sut.GetDbFeaturesByProductAndVersionAsync("MyProduct", "1.0.0");
// Assert
result.ShouldNotBeNull();
result.Count().ShouldBe(2);
result.First().Title.ShouldBe("MyFirstFeature");
result.First().Versions.ShouldNotBeNull();
result.First().Versions.Length.ShouldBe(2);
result.First().Versions.ShouldContain("0.0.0");
result.First().Versions.ShouldContain("1.0.0");
result.Last().Title.ShouldBe("MySecondFeature");
result.Last().Versions.ShouldNotBeNull();
result.Last().Versions.Length.ShouldBe(1);
result.Last().Versions.ShouldContain("1.0.0");
}
/// <summary>
/// Tests that the <see cref="FeatureManager" /> class can get all features from the database.
/// </summary>
[Fact]
public async Task CanGetAllDbFeatures()
{
// Arrange
var documentStoreProvider = DocumentStoreProvider;
await documentStoreProvider.StoreDbFeatureAsync("MyProduct", "MyGroup", "MyFirstFeature", "0.0.0");
await documentStoreProvider.StoreDbFeatureAsync("MyOtherProduct", "MyOtherGroup", "MySecondFeature", "0.0.0");
WaitForIndexing(documentStoreProvider.Store);
// Act
var sut = new FeatureManager(documentStoreProvider, logger);
var result = await sut.GetAllDbFeatures();
// Assert
result.ShouldNotBeNull();
result.FirstOrDefault().Title.ShouldBe("MyFirstFeature");
result.LastOrDefault().Title.ShouldBe("MySecondFeature");
}
/// <summary>
/// Tests that the <see cref="FeatureManager" /> class can persist a range of <see cref="DbFeature" /> instances.
/// </summary>
[Fact]
public async Task CanPersistDbFeatures()
{
// Arrange
var documentStoreProvider = DocumentStoreProvider;
var expectedFeature1 = new DbFeature(){
Title="MyFirstFeature",
Product = "MyProduct",
Group = "MyGroup",
Versions= new [] {"0.0.0", "0.1.0"}
};
var expectedFeature2 = new DbFeature(){
Title="MySecondFeature",
Product = "MyProduct",
Group = "MyGroup",
Versions= new [] {"0.0.0"}
};
// Act
var sut = new FeatureManager(documentStoreProvider, logger);
await sut.PersistDbFeatures(new[] { expectedFeature1, expectedFeature2 });
// Assert
using (var session = documentStoreProvider.Store.OpenAsyncSession())
{
var actualFeatures = await session.Query<DbFeature>().ToListAsync();
actualFeatures.ShouldNotBeNull();
actualFeatures.Count.ShouldBe(2);
var actualFeature1 = actualFeatures.FirstOrDefault();
actualFeature1.ShouldNotBeNull();
actualFeature1.GetIdentifier().ShouldBe(expectedFeature1.GetIdentifier());
var actualFeature2 = actualFeatures.LastOrDefault();
actualFeature2.ShouldNotBeNull();
actualFeature2.GetIdentifier().ShouldBe(expectedFeature2.GetIdentifier());
}
}
/// <summary>
/// Tests that the <see cref="FeatureManager" /> class can insert a new feature.
/// </summary>
[Fact]
public async Task CanInsertNewFeature()
{
// Arrange
var documentStoreProvider = DocumentStoreProvider;
var feature = new Feature
{
Title = "My Feature",
Description = "As a math idiot",
};
// Act
var sut = new FeatureManager(documentStoreProvider, logger);
var result = await sut.InsertOrUpdateFeatureAsync(feature, "MyProduct", "MyGroup", "0.0.0");
// Assert
result.Product.ShouldBe("MyProduct");
result.Group.ShouldBe("MyGroup");
result.Title.ShouldBe("My Feature");
result.Versions.ShouldBe(new []{"0.0.0"});
using (var session = documentStoreProvider.Store.OpenAsyncSession())
{
var dbFeature = await session.LoadAsync<DbFeature>(result.GetIdentifier());
dbFeature.ShouldNotBeNull();
}
}
/// <summary>
/// Tests that the <see cref="FeatureManager" /> class can update an existing feature.
/// </summary>
[Fact]
public async Task CanUpdateExistingFeature()
{
// Arrange
var documentStoreProvider = DocumentStoreProvider;
var feature = new Feature
{
Title = "My Feature",
Description = "As a math idiot",
Tags = new List<string> { "tag1", "tag2" }
};
await documentStoreProvider.StoreDbFeatureAsync("MyProduct", "MyGroup", "My Feature", "0.0.0", "tag1");
WaitForIndexing(documentStoreProvider.Store);
// Act
var sut = new FeatureManager(documentStoreProvider, logger);
var result = await sut.InsertOrUpdateFeatureAsync(feature, "MyProduct", "MyGroup", "0.0.0");
// Assert
result.Product.ShouldBe("MyProduct");
result.Group.ShouldBe("MyGroup");
result.Title.ShouldBe("My Feature");
result.Versions.ShouldBe(new []{"0.0.0"});
result.Tags.ShouldBe(new string[] { "tag1", "tag2" });
using (var session = documentStoreProvider.Store.OpenAsyncSession())
{
var dbFeature = await session.LoadAsync<DbFeature>(result.GetIdentifier());
dbFeature.ShouldNotBeNull();
}
}
/// <summary>
/// Tests that the <see cref="FeatureManager" /> class can persist test results.
/// </summary>
[Fact]
public async Task CanPersistTestResults()
{
// Arrange
var documentStoreProvider = DocumentStoreProvider;
var expectedTestResults = new FeatureTestResult
{
FeatureTitle = "My Feature",
Result = TestResult.Passed,
TestExecutionDate = DateTime.Now
};
await documentStoreProvider.StoreDbFeatureAsync("MyProduct", "MyGroup", "My Feature", "0.0.0");
WaitForIndexing(documentStoreProvider.Store);
// Act
var sut = new FeatureManager(documentStoreProvider, logger);
await sut.PersistFeatureTestResultAsync(expectedTestResults, "MyProduct", "MyGroup", "0.0.0");
// Assert
using (var session = documentStoreProvider.Store.OpenAsyncSession())
{
var dbFeature = (await sut.GetDbFeaturesByProductAndVersionAsync("MyProduct", "0.0.0")).Single();
dbFeature.TestResult.ShouldNotBeNull();
dbFeature.TestResult.Result.ShouldBe(TestResult.Passed);
dbFeature.TestResult.TestExecutionDate.ShouldBe(expectedTestResults.TestExecutionDate);
}
}
/// <summary>
/// Tests that the <see cref="FeatureManager" /> class throws an exception when attempting to store test results
/// for a feature that hasn't been previously stored.
/// </summary>
[Fact]
public async Task ThrowsWhenStoringTestResultsForNonExistingFeature()
{
// Arrange
var documentStoreProvider = DocumentStoreProvider;
var expectedTestResults = new FeatureTestResult
{
FeatureTitle = "My Feature",
Result = TestResult.Passed,
TestExecutionDate = DateTime.Now
};
// Act
var sut = new FeatureManager(documentStoreProvider, logger);
var exception = await Should.ThrowAsync<Exception>(sut.PersistFeatureTestResultAsync(expectedTestResults, "MyProduct", "MyGroup", "0.0.0"));
// Assert
exception.Message.ShouldContain(expectedTestResults.FeatureTitle);
exception.Message.ShouldContain("MyProduct");
exception.Message.ShouldContain("MyGroup");
}
/// <summary>
/// Tests that the <see cref="FeatureManager" /> class can delete features based on a product and group.
/// </summary>
[Fact]
public async Task CanDeleteFeaturesByProductAndGroup()
{
// Arrange
var documentStoreProvider = DocumentStoreProvider;
await documentStoreProvider.StoreDbFeatureAsync("MyProduct", "MyGroup", "My First Feature", "0.0.0");
await documentStoreProvider.StoreDbFeatureAsync("MyProduct", "MyOtherGroup", "My Second Feature", "0.0.0");
WaitForIndexing(documentStoreProvider.Store);
// Act
var sut = new FeatureManager(documentStoreProvider, logger);
await sut.DeleteFeaturesAsync("MyProduct", "MyGroup");
WaitForIndexing(documentStoreProvider.Store);
// Assert
using (var session = documentStoreProvider.Store.OpenAsyncSession())
{
var features = await session.Query<DbFeature>().ToListAsync();
features.ShouldNotBeNull();
features.Count.ShouldBe(1);
var remainingFeature = features.FirstOrDefault();
remainingFeature.ShouldNotBeNull();
remainingFeature.Title.ShouldBe("My Second Feature");
}
}
/// <summary>
/// Tests that the <see cref="FeatureManager" /> class can delete features based on a product, group and version.
/// </summary>
[Fact]
public async Task CanDeleteFeaturesByProductGroupAndVersion()
{
// Arrange
var documentStoreProvider = DocumentStoreProvider;
await documentStoreProvider.StoreDbFeatureAsync("MyProduct", "MyGroup", "My First Feature", "0.0.0");
await documentStoreProvider.StoreDbFeatureAsync("MyProduct", "MyGroup", "My First Feature", "1.0.0");
WaitForIndexing(documentStoreProvider.Store);
// Act
var sut = new FeatureManager(documentStoreProvider, logger);
await sut.DeleteFeaturesAsync("MyProduct", "MyGroup", "0.0.0");
// Assert
using (var session = documentStoreProvider.Store.OpenAsyncSession())
{
var features = await session.Query<DbFeature>().ToListAsync();
features.ShouldNotBeNull();
features.Count.ShouldBe(1);
var remainingFeature = features.FirstOrDefault();
remainingFeature.ShouldNotBeNull();
remainingFeature.Versions.ShouldBe(new [] {"1.0.0"});
}
}
/// <summary>
/// Tests that the <see cref="FeatureManager" /> class can delete a feature based on a product, group and title.
/// </summary>
[Fact]
public async Task CanDeleteFeatureByProductGroupAndTitle()
{
// Arrange
var documentStoreProvider = DocumentStoreProvider;
await documentStoreProvider.StoreDbFeatureAsync("MyProduct", "MyGroup", "My First Feature", "0.0.0");
await documentStoreProvider.StoreDbFeatureAsync("MyProduct", "MyGroup", "My First Feature", "1.0.0");
await documentStoreProvider.StoreDbFeatureAsync("MyProduct", "MyGroup", "My Second Feature", "0.0.0");
WaitForIndexing(documentStoreProvider.Store);
// Act
var sut = new FeatureManager(documentStoreProvider, logger);
await sut.DeleteFeatureAsync("MyProduct", "MyGroup", "My First Feature");
WaitForIndexing(documentStoreProvider.Store);
// Assert
using (var session = documentStoreProvider.Store.OpenAsyncSession())
{
var features = await session.Query<DbFeature>().ToListAsync();
features.ShouldNotBeNull();
features.Count.ShouldBe(1);
var remainingFeature = features.FirstOrDefault();
remainingFeature.ShouldNotBeNull();
remainingFeature.Title.ShouldBe("My Second Feature");
}
}
/// <summary>
/// Tests that the <see cref="FeatureManager" /> class can delete a feature based on a product, group, title and version.
/// </summary>
[Fact]
public async Task CanDeleteFeatureByProductGroupTitleAndVersion()
{
// Arrange
var documentStoreProvider = DocumentStoreProvider;
await documentStoreProvider.StoreDbFeatureAsync("MyProduct", "MyGroup", "My First Feature", "0.0.0");
await documentStoreProvider.StoreDbFeatureAsync("MyProduct", "MyGroup", "My First Feature", "1.0.0");
await documentStoreProvider.StoreDbFeatureAsync("MyProduct", "MyGroup", "My Second Feature", "0.0.0");
WaitForIndexing(documentStoreProvider.Store);
// Act
var sut = new FeatureManager(documentStoreProvider, logger);
await sut.DeleteFeatureAsync("MyProduct", "MyGroup", "My First Feature", "0.0.0");
WaitForIndexing(documentStoreProvider.Store);
// Assert
using (var session = documentStoreProvider.Store.OpenAsyncSession())
{
var features = await session.Query<DbFeature>().OrderBy(f => f.Title).ToListAsync();
features.ShouldNotBeNull();
features.Count.ShouldBe(2);
var remainingFeature1 = features.FirstOrDefault();
remainingFeature1.ShouldNotBeNull();
remainingFeature1.Title.ShouldBe("My First Feature");
remainingFeature1.Versions.ShouldBe(new [] {"1.0.0"});
var remainingFeature2 = features.LastOrDefault();
remainingFeature2.ShouldNotBeNull();
remainingFeature2.Title.ShouldBe("My Second Feature");
remainingFeature2.Versions.ShouldBe(new [] {"0.0.0"});
}
}
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System.Linq;
using NLog.Conditions;
using NLog.Config;
using NLog.Internal;
using NLog.LayoutRenderers;
using NLog.Layouts;
using NLog.Targets.Wrappers;
using NLog.UnitTests.Targets.Wrappers;
namespace NLog.UnitTests.Targets
{
using System;
using System.Collections.Generic;
using System.Threading;
using NLog.Common;
using NLog.Targets;
using Xunit;
public class TargetTests : NLogTestBase
{
/// <summary>
/// Test the following things:
/// - Target has default ctor
/// - Target has ctor with name (string) arg.
/// - Both ctors are creating the same instances
/// </summary>
[Fact]
public void TargetContructorWithNameTest()
{
var targetTypes = typeof(Target).Assembly.GetTypes().Where(t => !t.IsAbstract && t.IsSubclassOf(typeof(Target))).ToList();
int neededCheckCount = targetTypes.Count;
int checkCount = 0;
Target fileTarget = new FileTarget();
Target memoryTarget = new MemoryTarget();
foreach (Type targetType in targetTypes)
{
string lastPropertyName = null;
try
{
// Check if the Target can be created using a default constructor
var name = targetType + "_name";
var isWrapped = targetType.IsSubclassOf(typeof(WrapperTargetBase));
var isCompound = targetType.IsSubclassOf(typeof(CompoundTargetBase));
if (isWrapped)
{
neededCheckCount++;
var args = new List<object> { fileTarget };
//default ctor
var defaultConstructedTarget = (WrapperTargetBase)Activator.CreateInstance(targetType);
defaultConstructedTarget.Name = name;
defaultConstructedTarget.WrappedTarget = fileTarget;
//specials cases
if (targetType == typeof(FilteringTargetWrapper))
{
var cond = new ConditionLoggerNameExpression();
args.Add(cond);
var target = (FilteringTargetWrapper) defaultConstructedTarget;
target.Condition = cond;
}
else if (targetType == typeof(RepeatingTargetWrapper))
{
var repeatCount = 5;
args.Add(repeatCount);
var target = (RepeatingTargetWrapper)defaultConstructedTarget;
target.RepeatCount = repeatCount;
}
else if (targetType == typeof(RetryingTargetWrapper))
{
var retryCount = 10;
var retryDelayMilliseconds = 100;
args.Add(retryCount);
args.Add(retryDelayMilliseconds);
var target = (RetryingTargetWrapper)defaultConstructedTarget;
target.RetryCount = retryCount;
target.RetryDelayMilliseconds = retryDelayMilliseconds;
}
//ctor: target
var targetConstructedTarget = (WrapperTargetBase)Activator.CreateInstance(targetType, args.ToArray());
targetConstructedTarget.Name = name;
args.Insert(0, name);
//ctor: target+name
var namedConstructedTarget = (WrapperTargetBase)Activator.CreateInstance(targetType, args.ToArray());
CheckEquals(targetType, targetConstructedTarget, namedConstructedTarget, ref lastPropertyName, ref checkCount);
CheckEquals(targetType, defaultConstructedTarget, namedConstructedTarget, ref lastPropertyName, ref checkCount);
}
else if (isCompound)
{
neededCheckCount++;
//multiple targets
var args = new List<object> { fileTarget, memoryTarget };
//specials cases
//default ctor
var defaultConstructedTarget = (CompoundTargetBase)Activator.CreateInstance(targetType);
defaultConstructedTarget.Name = name;
defaultConstructedTarget.Targets.Add(fileTarget);
defaultConstructedTarget.Targets.Add(memoryTarget);
//ctor: target
var targetConstructedTarget = (CompoundTargetBase)Activator.CreateInstance(targetType, args.ToArray());
targetConstructedTarget.Name = name;
args.Insert(0, name);
//ctor: target+name
var namedConstructedTarget = (CompoundTargetBase)Activator.CreateInstance(targetType, args.ToArray());
CheckEquals(targetType, targetConstructedTarget, namedConstructedTarget, ref lastPropertyName, ref checkCount);
CheckEquals(targetType, defaultConstructedTarget, namedConstructedTarget, ref lastPropertyName, ref checkCount);
}
else
{
//default ctor
var targetConstructedTarget = (Target)Activator.CreateInstance(targetType);
targetConstructedTarget.Name = name;
// ctor: name
var namedConstructedTarget = (Target)Activator.CreateInstance(targetType, name);
CheckEquals(targetType, targetConstructedTarget, namedConstructedTarget, ref lastPropertyName, ref checkCount);
}
}
catch (Exception ex)
{
var constructionFailed = true;
string failureMessage = String.Format("Error testing constructors for '{0}.{1}`\n{2}", targetType, lastPropertyName, ex.ToString());
Assert.False(constructionFailed, failureMessage);
}
}
Assert.Equal(neededCheckCount, checkCount);
}
private static void CheckEquals(Type targetType, Target defaultConstructedTarget, Target namedConstructedTarget,
ref string lastPropertyName, ref int @checked)
{
var checkedAtLeastOneProperty = false;
var properties = targetType.GetProperties(
System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Public |
System.Reflection.BindingFlags.FlattenHierarchy |
System.Reflection.BindingFlags.Default |
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.Static);
foreach (System.Reflection.PropertyInfo pi in properties)
{
lastPropertyName = pi.Name;
if (pi.CanRead && !pi.Name.Equals("SyncRoot"))
{
var value1 = pi.GetValue(defaultConstructedTarget, null);
var value2 = pi.GetValue(namedConstructedTarget, null);
if (value1 != null && value2 != null)
{
if (value1 is IRenderable)
{
Assert.Equal((IRenderable) value1, (IRenderable) value2, new RenderableEq());
}
else if (value1 is AsyncRequestQueue)
{
Assert.Equal((AsyncRequestQueue) value1, (AsyncRequestQueue) value2, new AsyncRequestQueueEq());
}
else
{
Assert.Equal(value1, value2);
}
}
else
{
Assert.Null(value1);
Assert.Null(value2);
}
checkedAtLeastOneProperty = true;
}
}
if (checkedAtLeastOneProperty)
{
@checked++;
}
}
private class RenderableEq : EqualityComparer<IRenderable>
{
/// <summary>
/// Determines whether the specified objects are equal.
/// </summary>
/// <returns>
/// true if the specified objects are equal; otherwise, false.
/// </returns>
/// <param name="x">The first object of type <paramref name="T"/> to compare.</param><param name="y">The second object of type <paramref name="T"/> to compare.</param>
public override bool Equals(IRenderable x, IRenderable y)
{
if (x == null) return y == null;
var nullEvent = LogEventInfo.CreateNullEvent();
return x.Render(nullEvent) == y.Render(nullEvent);
}
/// <summary>
/// Returns a hash code for the specified object.
/// </summary>
/// <returns>
/// A hash code for the specified object.
/// </returns>
/// <param name="obj">The <see cref="T:System.Object"/> for which a hash code is to be returned.</param><exception cref="T:System.ArgumentNullException">The type of <paramref name="obj"/> is a reference type and <paramref name="obj"/> is null.</exception>
public override int GetHashCode(IRenderable obj)
{
return obj.ToString().GetHashCode();
}
}
private class AsyncRequestQueueEq : EqualityComparer<AsyncRequestQueue>
{
/// <summary>
/// Determines whether the specified objects are equal.
/// </summary>
/// <returns>
/// true if the specified objects are equal; otherwise, false.
/// </returns>
/// <param name="x">The first object of type <paramref name="T"/> to compare.</param><param name="y">The second object of type <paramref name="T"/> to compare.</param>
public override bool Equals(AsyncRequestQueue x, AsyncRequestQueue y)
{
if (x == null) return y == null;
return x.RequestLimit == y.RequestLimit && x.OnOverflow == y.OnOverflow;
}
/// <summary>
/// Returns a hash code for the specified object.
/// </summary>
/// <returns>
/// A hash code for the specified object.
/// </returns>
/// <param name="obj">The <see cref="T:System.Object"/> for which a hash code is to be returned.</param><exception cref="T:System.ArgumentNullException">The type of <paramref name="obj"/> is a reference type and <paramref name="obj"/> is null.</exception>
public override int GetHashCode(AsyncRequestQueue obj)
{
unchecked
{
return (obj.RequestLimit * 397) ^ (int)obj.OnOverflow;
}
}
}
[Fact]
public void InitializeTest()
{
var target = new MyTarget();
target.Initialize(null);
// initialize was called once
Assert.Equal(1, target.InitializeCount);
Assert.Equal(1, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
}
[Fact]
public void InitializeFailedTest()
{
var target = new MyTarget();
target.ThrowOnInitialize = true;
LogManager.ThrowExceptions = true;
Assert.Throws<InvalidOperationException>(() => target.Initialize(null));
// after exception in Initialize(), the target becomes non-functional and all Write() operations
var exceptions = new List<Exception>();
target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
Assert.Equal(0, target.WriteCount);
Assert.Equal(1, exceptions.Count);
Assert.NotNull(exceptions[0]);
Assert.Equal("Target " + target + " failed to initialize.", exceptions[0].Message);
Assert.Equal("Init error.", exceptions[0].InnerException.Message);
}
[Fact]
public void DoubleInitializeTest()
{
var target = new MyTarget();
target.Initialize(null);
target.Initialize(null);
// initialize was called once
Assert.Equal(1, target.InitializeCount);
Assert.Equal(1, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
}
[Fact]
public void DoubleCloseTest()
{
var target = new MyTarget();
target.Initialize(null);
target.Close();
target.Close();
// initialize and close were called once each
Assert.Equal(1, target.InitializeCount);
Assert.Equal(1, target.CloseCount);
Assert.Equal(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
}
[Fact]
public void CloseWithoutInitializeTest()
{
var target = new MyTarget();
target.Close();
// nothing was called
Assert.Equal(0, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
}
[Fact]
public void WriteWithoutInitializeTest()
{
var target = new MyTarget();
List<Exception> exceptions = new List<Exception>();
target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
target.WriteAsyncLogEvents(new[]
{
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
});
// write was not called
Assert.Equal(0, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
Assert.Equal(4, exceptions.Count);
exceptions.ForEach(Assert.Null);
}
[Fact]
public void WriteOnClosedTargetTest()
{
var target = new MyTarget();
target.Initialize(null);
target.Close();
var exceptions = new List<Exception>();
target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
target.WriteAsyncLogEvents(
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
Assert.Equal(1, target.InitializeCount);
Assert.Equal(1, target.CloseCount);
// write was not called
Assert.Equal(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
// but all callbacks were invoked with null values
Assert.Equal(4, exceptions.Count);
exceptions.ForEach(Assert.Null);
}
[Fact]
public void FlushTest()
{
var target = new MyTarget();
List<Exception> exceptions = new List<Exception>();
target.Initialize(null);
target.Flush(exceptions.Add);
// flush was called
Assert.Equal(1, target.FlushCount);
Assert.Equal(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
Assert.Equal(1, exceptions.Count);
exceptions.ForEach(Assert.Null);
}
[Fact]
public void FlushWithoutInitializeTest()
{
var target = new MyTarget();
List<Exception> exceptions = new List<Exception>();
target.Flush(exceptions.Add);
Assert.Equal(1, exceptions.Count);
exceptions.ForEach(Assert.Null);
// flush was not called
Assert.Equal(0, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
}
[Fact]
public void FlushOnClosedTargetTest()
{
var target = new MyTarget();
target.Initialize(null);
target.Close();
Assert.Equal(1, target.InitializeCount);
Assert.Equal(1, target.CloseCount);
List<Exception> exceptions = new List<Exception>();
target.Flush(exceptions.Add);
Assert.Equal(1, exceptions.Count);
exceptions.ForEach(Assert.Null);
// flush was not called
Assert.Equal(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
}
[Fact]
public void LockingTest()
{
var target = new MyTarget();
target.Initialize(null);
var mre = new ManualResetEvent(false);
Exception backgroundThreadException = null;
Thread t = new Thread(() =>
{
try
{
target.BlockingOperation(1000);
}
catch (Exception ex)
{
backgroundThreadException = ex;
}
finally
{
mre.Set();
}
});
target.Initialize(null);
t.Start();
Thread.Sleep(50);
List<Exception> exceptions = new List<Exception>();
target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
target.WriteAsyncLogEvents(new[]
{
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
});
target.Flush(exceptions.Add);
target.Close();
exceptions.ForEach(Assert.Null);
mre.WaitOne();
if (backgroundThreadException != null)
{
Assert.True(false, backgroundThreadException.ToString());
}
}
[Fact]
public void GivenNullEvents_WhenWriteAsyncLogEvents_ThenNoExceptionAreThrown()
{
var target = new MyTarget();
try
{
target.WriteAsyncLogEvents((AsyncLogEventInfo[])null);
}
catch (Exception e)
{
Assert.True(false, "Exception thrown: " + e);
}
}
[Fact]
public void WriteFormattedStringEvent_WithNullArgument()
{
var target = new MyTarget();
SimpleConfigurator.ConfigureForTargetLogging(target);
var logger = LogManager.GetLogger("WriteFormattedStringEvent_EventWithNullArguments");
string t = null;
logger.Info("Testing null:{0}", t);
Assert.Equal(1, target.WriteCount);
}
public class MyTarget : Target
{
private int inBlockingOperation;
public int InitializeCount { get; set; }
public int CloseCount { get; set; }
public int FlushCount { get; set; }
public int WriteCount { get; set; }
public int WriteCount2 { get; set; }
public bool ThrowOnInitialize { get; set; }
public int WriteCount3 { get; set; }
public MyTarget() : base()
{
}
public MyTarget(string name) : this()
{
this.Name = name;
}
protected override void InitializeTarget()
{
if (this.ThrowOnInitialize)
{
throw new InvalidOperationException("Init error.");
}
Assert.Equal(0, this.inBlockingOperation);
this.InitializeCount++;
base.InitializeTarget();
}
protected override void CloseTarget()
{
Assert.Equal(0, this.inBlockingOperation);
this.CloseCount++;
base.CloseTarget();
}
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
Assert.Equal(0, this.inBlockingOperation);
this.FlushCount++;
base.FlushAsync(asyncContinuation);
}
protected override void Write(LogEventInfo logEvent)
{
Assert.Equal(0, this.inBlockingOperation);
this.WriteCount++;
}
protected override void Write(AsyncLogEventInfo logEvent)
{
Assert.Equal(0, this.inBlockingOperation);
this.WriteCount2++;
base.Write(logEvent);
}
protected override void Write(ArraySegment<AsyncLogEventInfo> logEvents)
{
Assert.Equal(0, this.inBlockingOperation);
this.WriteCount3++;
base.Write(logEvents);
}
public void BlockingOperation(int millisecondsTimeout)
{
lock (this.SyncRoot)
{
this.inBlockingOperation++;
Thread.Sleep(millisecondsTimeout);
this.inBlockingOperation--;
}
}
}
[Fact]
public void WrongMyTargetShouldNotThrowExceptionWhenThrowExceptionsIsFalse()
{
var target = new WrongMyTarget();
LogManager.ThrowExceptions = false;
SimpleConfigurator.ConfigureForTargetLogging(target);
var logger = LogManager.GetLogger("WrongMyTargetShouldThrowException");
logger.Info("Testing");
var layouts = target.GetAllLayouts();
Assert.NotNull(layouts);
}
public class WrongMyTarget : Target
{
public WrongMyTarget() : base()
{
}
public WrongMyTarget(string name) : this()
{
this.Name = name;
}
/// <summary>
/// Initializes the target. Can be used by inheriting classes
/// to initialize logging.
/// </summary>
protected override void InitializeTarget()
{
//base.InitializeTarget() should be called
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//-----------------------------------------------------------------------
// <copyright file="AddNewImport_Tests.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>
// Baseline Regression Tests for v9 OM Public Interface Compatibility:
// Common Tests for Project.AddNewImport and ImportCollection.AddNewImport
// </summary>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Principal;
using System.Security.AccessControl;
using NUnit.Framework;
using Microsoft.Build;
using Microsoft.Build.BuildEngine;
using Microsoft.Build.Framework;
using Microsoft.Build.UnitTests;
namespace Microsoft.Build.UnitTests.OM.OrcasCompatibility
{
/// <summary>
/// Indirection delegate type for AddNewImport Method invocation
/// </summary>
public delegate void AddNewImportDelegate(Project p, string path, string condition);
/// <summary>
/// indirection for tests of Project.AddNewImport and ImportCollection.AddNewImport
/// </summary>
public abstract class AddNewImportTests
{
#region Indirection Delegates
/// <summary>
/// Indirection delegate for AddNewImport Method invocation
/// </summary>
protected AddNewImportDelegate InvokeAddNewImportMethod
{
get;
set;
}
#endregion
/// <summary>
/// AddNewImport Test, Empty
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void AddNewImportFileName_Empty()
{
Project p = new Project(new Engine());
InvokeAddNewImportMethod(p, String.Empty, null);
}
/// <summary>
/// AddNewImport Test, Null
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void AddNewImportFileName_Null()
{
Project p = new Project(new Engine());
InvokeAddNewImportMethod(p, null, null);
}
/// <summary>
/// AddNewImport Test, Where imported file does not exist
/// </summary>
[Test]
public void AddNewImportFile_DoesNotExist()
{
Project p = new Project(new Engine());
InvokeAddNewImportMethod(p, @"c:\doesnotexist.proj", null);
}
/// <summary>
/// AddNewImport Test, Import a File, where file is not permitted to be read.
/// </summary>
[Test]
public void AddNewImportFile_NoReadPermissions()
{
string importPath = String.Empty;
try
{
importPath = ObjectModelHelpers.CreateTempFileOnDisk(TestData.ContentSimpleTools35InitialTargets);
Project p = new Project(new Engine());
CompatibilityTestHelpers.SetFileAccessPermissions(importPath, FileSystemRights.Read, AccessControlType.Deny);
InvokeAddNewImportMethod(p, importPath, null);
}
finally
{
CompatibilityTestHelpers.RemoveFile(importPath);
}
}
/// <summary>
/// AddNewImport Test, Import a file with an empty condition.
/// </summary>
[Test]
public void AddNewImportFile_EmptyCondition()
{
string importPath = String.Empty;
try
{
Project p = new Project(new Engine());
importPath = ObjectModelHelpers.CreateTempFileOnDisk(TestData.ContentSimpleTools35InitialTargets);
InvokeAddNewImportMethod(p, importPath, String.Empty);
}
finally
{
CompatibilityTestHelpers.RemoveFile(importPath);
}
}
/// <summary>
/// AddNewImport Test, import file with condiction that is true.
/// </summary>
[Test]
public void AddNewImportFileCondition_True()
{
string importPath = String.Empty;
try
{
Project p = new Project(new Engine());
importPath = ObjectModelHelpers.CreateTempFileOnDisk(TestData.ContentSimpleTools35InitialTargets);
InvokeAddNewImportMethod(p, importPath, "true");
Assertion.AssertEquals(0, p.Imports.Count);
object o = p.EvaluatedItems; // force evaluation of imported projects.
Assertion.AssertEquals(1, p.Imports.Count);
}
finally
{
CompatibilityTestHelpers.RemoveFile(importPath);
}
}
/// <summary>
/// AddNewImport Test, import file with condiction that evaluates to true.
/// </summary>
[Test]
public void AddNewImportFileCondition_EqualIsTrue()
{
string importPath = String.Empty;
try
{
Project p = new Project(new Engine());
importPath = ObjectModelHelpers.CreateTempFileOnDisk(TestData.ContentSimpleTools35InitialTargets);
InvokeAddNewImportMethod(p, importPath, "1 == 1");
Assertion.AssertEquals(0, p.Imports.Count);
object o = p.EvaluatedItems; // force evaluation of imported projects.
Assertion.AssertEquals(1, p.Imports.Count);
}
finally
{
CompatibilityTestHelpers.RemoveFile(importPath);
}
}
/// <summary>
/// AddNewImport Test, import file with Condition that is false
/// </summary>
[Test]
public void AddNewImportFileCondition_False()
{
string importPath = String.Empty;
try
{
importPath = ObjectModelHelpers.CreateTempFileOnDisk(TestData.ContentSimpleTools35InitialTargets);
Project p = new Project(new Engine());
InvokeAddNewImportMethod(p, importPath, "false");
Assertion.AssertEquals(0, p.Imports.Count);
object o = p.EvaluatedItems; // force evaluation of imported projects.
Assertion.AssertEquals(0, p.Imports.Count);
}
finally
{
CompatibilityTestHelpers.RemoveFile(importPath);
}
}
/// <summary>
/// AddNewImport Test, check project flagged as dirty after import
/// </summary>
[Test]
public void AddNewImportsIsDirtyAfterImport()
{
Project p = new Project(new Engine());
string importPath = ObjectModelHelpers.CreateTempFileOnDisk(TestData.ContentSimpleTools35InitialTargets);
Assertion.AssertEquals(false, p.IsDirty);
InvokeAddNewImportMethod(p, importPath, null);
Assertion.AssertEquals(true, p.IsDirty);
}
/// <summary>
/// AddNewImport Test, Check precedence and import of InitialTargets
/// </summary>
[Test]
public void AddNewImportAttributeprecedence_InitialTargets()
{
Project p = new Project(new Engine());
p.InitialTargets = "localTargetFirst";
string importPath = ObjectModelHelpers.CreateTempFileOnDisk(TestData.ContentSimpleTools35InitialTargets); // InitialTarget
InvokeAddNewImportMethod(p, importPath, null);
Assertion.AssertEquals("localTargetFirst", p.InitialTargets); // Assert non automatic evaluation.
object o = p.EvaluatedItems; // force evaluation of imported projects.
Assertion.AssertEquals("localTargetFirst; InitialTarget", p.InitialTargets); // Assert the concat
}
/// <summary>
/// AddNewImport Test, Check precedence and import of DefaultTargets
/// </summary>
[Test]
public void AddNewImportAttributeprecedence_DefaultTarget()
{
string importPath = String.Empty;
try
{
Project p = new Project(new Engine());
p.DefaultTargets = "localTargetDefault";
importPath = ObjectModelHelpers.CreateTempFileOnDisk(TestData.Content3SimpleTargetsDefaultSpecified); // TestTargetDefault
InvokeAddNewImportMethod(p, importPath, null);
Assertion.AssertEquals("localTargetDefault", p.DefaultTargets); // Assert non automatic evaluation.
object o = p.EvaluatedItems; // force evaluation of imported projects.
Assertion.AssertEquals("localTargetDefault", p.DefaultTargets);
}
finally
{
CompatibilityTestHelpers.RemoveFile(importPath);
}
}
/// <summary>
/// AddNewImport Test, Import p1 into p2
/// </summary>
[Test]
public void AddNewImportStandard()
{
string projectPath = String.Empty;
string projectPathImport = String.Empty;
try
{
Project p = new Project(new Engine());
projectPath = ObjectModelHelpers.CreateTempFileOnDisk(TestData.Content3SimpleTargetsDefaultSpecified);
projectPathImport = ObjectModelHelpers.CreateTempFileOnDisk(TestData.Content3SimpleTargetsDefaultSpecified);
p.Load(projectPath);
InvokeAddNewImportMethod(p, projectPathImport, "true");
Assertion.AssertEquals(0, p.Imports.Count);
object o = p.EvaluatedItems; // force evaluation of imported projects.
Assertion.AssertEquals(1, CompatibilityTestHelpers.CountNodesWithName(p.Xml, "Import"));
Assertion.AssertEquals(1, p.Imports.Count);
}
finally
{
CompatibilityTestHelpers.RemoveFile(projectPath);
CompatibilityTestHelpers.RemoveFile(projectPathImport);
}
}
/// <summary>
/// AddNewImport Test, Import p1 into p twice
/// </summary>
[Test]
public void AddNewImportStandardTwice()
{
string projectPath = String.Empty;
string projectPathImport = String.Empty;
try
{
Project p = new Project(new Engine());
projectPath = ObjectModelHelpers.CreateTempFileOnDisk(TestData.Content3SimpleTargetsDefaultSpecified);
projectPathImport = ObjectModelHelpers.CreateTempFileOnDisk(TestData.Content3SimpleTargetsDefaultSpecified);
p.Load(projectPath);
InvokeAddNewImportMethod(p, projectPathImport, "true");
InvokeAddNewImportMethod(p, projectPathImport, "true");
Assertion.AssertEquals(0, p.Imports.Count);
object o = p.EvaluatedItems; // force evaluation of imported projects.
Assertion.AssertEquals(2, CompatibilityTestHelpers.CountNodesWithName(p.Xml, "Import")); // 2 in xml
Assertion.AssertEquals(1, p.Imports.Count); // 1 in OM.
}
finally
{
CompatibilityTestHelpers.RemoveFile(projectPath);
CompatibilityTestHelpers.RemoveFile(projectPathImport);
}
}
/// <summary>
/// AddNewImport Test, Import p1 and p2 into p
/// </summary>
[Test]
public void AddTwoNewImportStandard()
{
string projectPath = String.Empty;
string projectPathImport1 = String.Empty;
string projectPathImport2 = String.Empty;
try
{
Project p = new Project(new Engine());
projectPath = ObjectModelHelpers.CreateTempFileOnDisk(TestData.Content3SimpleTargetsDefaultSpecified);
projectPathImport1 = ObjectModelHelpers.CreateTempFileOnDisk(TestData.Content3SimpleTargetsDefaultSpecified);
projectPathImport2 = ObjectModelHelpers.CreateTempFileOnDisk(TestData.Content3SimpleTargetsDefaultSpecified);
p.Load(projectPath);
InvokeAddNewImportMethod(p, projectPathImport1, "true");
InvokeAddNewImportMethod(p, projectPathImport2, "true");
Assertion.AssertEquals(0, p.Imports.Count);
object o = p.EvaluatedItems; // force evaluation of imported projects.
Assertion.AssertEquals(2, CompatibilityTestHelpers.CountNodesWithName(p.Xml, "Import")); // 2 in the XML
Assertion.AssertEquals(2, p.Imports.Count); // 2 in OM
}
finally
{
CompatibilityTestHelpers.RemoveFile(projectPath);
CompatibilityTestHelpers.RemoveFile(projectPathImport1);
CompatibilityTestHelpers.RemoveFile(projectPathImport2);
}
}
/// <summary>
/// AddNewImport Test, Import a project into itself
/// </summary>
[Test]
public void AddNewImportToBecomeSelfReferential()
{
string projectPath = String.Empty;
try
{
Project p = new Project(new Engine());
projectPath = ObjectModelHelpers.CreateTempFileOnDisk(TestData.Content3SimpleTargetsDefaultSpecified);
p.Load(projectPath);
InvokeAddNewImportMethod(p, projectPath, "true");
Assertion.AssertEquals(0, p.Imports.Count);
object o = p.EvaluatedItems; // force evaluation of imported projects.
Assertion.AssertEquals(0, p.Imports.Count); // This is bonkers, should be 1 because the XML DOES contain the import node.
}
finally
{
CompatibilityTestHelpers.RemoveFile(projectPath);
}
}
/// <summary>
/// AddNewImport Test, Import a project into itself twice
/// </summary>
[Test]
public void AddNewImportToBecomeSelfReferentialTwice()
{
string projectPath = String.Empty;
try
{
Project p = new Project(new Engine());
projectPath = ObjectModelHelpers.CreateTempFileOnDisk(TestData.Content3SimpleTargetsDefaultSpecified);
InvokeAddNewImportMethod(p, projectPath, null);
InvokeAddNewImportMethod(p, projectPath, null);
object o = p.EvaluatedItems; // force evaluation of imported projects.
Assertion.AssertEquals(1, p.Imports.Count);
Assertion.AssertEquals(2, CompatibilityTestHelpers.CountNodesWithName(p.Xml, "Import")); // 2 in the XML
}
finally
{
CompatibilityTestHelpers.RemoveFile(projectPath);
}
}
}
}
| |
// 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.Linq;
using Avalonia.Interactivity;
using Avalonia.VisualTree;
namespace Avalonia.Input
{
/// <summary>
/// Implements input-related functionality for a control.
/// </summary>
public class InputElement : Interactive, IInputElement
{
/// <summary>
/// Defines the <see cref="Focusable"/> property.
/// </summary>
public static readonly StyledProperty<bool> FocusableProperty =
AvaloniaProperty.Register<InputElement, bool>(nameof(Focusable));
/// <summary>
/// Defines the <see cref="IsEnabled"/> property.
/// </summary>
public static readonly StyledProperty<bool> IsEnabledProperty =
AvaloniaProperty.Register<InputElement, bool>(nameof(IsEnabled), true);
/// <summary>
/// Defines the <see cref="IsEnabledCore"/> property.
/// </summary>
public static readonly StyledProperty<bool> IsEnabledCoreProperty =
AvaloniaProperty.Register<InputElement, bool>(nameof(IsEnabledCore), true);
/// <summary>
/// Gets or sets associated mouse cursor.
/// </summary>
public static readonly StyledProperty<Cursor> CursorProperty =
AvaloniaProperty.Register<InputElement, Cursor>(nameof(Cursor), null, true);
/// <summary>
/// Defines the <see cref="IsFocused"/> property.
/// </summary>
public static readonly DirectProperty<InputElement, bool> IsFocusedProperty =
AvaloniaProperty.RegisterDirect<InputElement, bool>(nameof(IsFocused), o => o.IsFocused);
/// <summary>
/// Defines the <see cref="IsHitTestVisible"/> property.
/// </summary>
public static readonly StyledProperty<bool> IsHitTestVisibleProperty =
AvaloniaProperty.Register<InputElement, bool>(nameof(IsHitTestVisible), true);
/// <summary>
/// Defines the <see cref="IsPointerOver"/> property.
/// </summary>
public static readonly DirectProperty<InputElement, bool> IsPointerOverProperty =
AvaloniaProperty.RegisterDirect<InputElement, bool>(nameof(IsPointerOver), o => o.IsPointerOver);
/// <summary>
/// Defines the <see cref="GotFocus"/> event.
/// </summary>
public static readonly RoutedEvent<GotFocusEventArgs> GotFocusEvent =
RoutedEvent.Register<InputElement, GotFocusEventArgs>(nameof(GotFocus), RoutingStrategies.Bubble);
/// <summary>
/// Defines the <see cref="LostFocus"/> event.
/// </summary>
public static readonly RoutedEvent<RoutedEventArgs> LostFocusEvent =
RoutedEvent.Register<InputElement, RoutedEventArgs>(nameof(LostFocus), RoutingStrategies.Bubble);
/// <summary>
/// Defines the <see cref="KeyDown"/> event.
/// </summary>
public static readonly RoutedEvent<KeyEventArgs> KeyDownEvent =
RoutedEvent.Register<InputElement, KeyEventArgs>(
"KeyDown",
RoutingStrategies.Tunnel | RoutingStrategies.Bubble);
/// <summary>
/// Defines the <see cref="KeyUp"/> event.
/// </summary>
public static readonly RoutedEvent<KeyEventArgs> KeyUpEvent =
RoutedEvent.Register<InputElement, KeyEventArgs>(
"KeyUp",
RoutingStrategies.Tunnel | RoutingStrategies.Bubble);
/// <summary>
/// Defines the <see cref="TextInput"/> event.
/// </summary>
public static readonly RoutedEvent<TextInputEventArgs> TextInputEvent =
RoutedEvent.Register<InputElement, TextInputEventArgs>(
"TextInput",
RoutingStrategies.Tunnel | RoutingStrategies.Bubble);
/// <summary>
/// Defines the <see cref="PointerEnter"/> event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerEnterEvent =
RoutedEvent.Register<InputElement, PointerEventArgs>(nameof(PointerEnter), RoutingStrategies.Direct);
/// <summary>
/// Defines the <see cref="PointerLeave"/> event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerLeaveEvent =
RoutedEvent.Register<InputElement, PointerEventArgs>(nameof(PointerLeave), RoutingStrategies.Direct);
/// <summary>
/// Defines the <see cref="PointerMoved"/> event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerMovedEvent =
RoutedEvent.Register<InputElement, PointerEventArgs>(
"PointerMove",
RoutingStrategies.Tunnel | RoutingStrategies.Bubble);
/// <summary>
/// Defines the <see cref="PointerPressed"/> event.
/// </summary>
public static readonly RoutedEvent<PointerPressedEventArgs> PointerPressedEvent =
RoutedEvent.Register<InputElement, PointerPressedEventArgs>(
"PointerPressed",
RoutingStrategies.Tunnel | RoutingStrategies.Bubble);
/// <summary>
/// Defines the <see cref="PointerReleased"/> event.
/// </summary>
public static readonly RoutedEvent<PointerReleasedEventArgs> PointerReleasedEvent =
RoutedEvent.Register<InputElement, PointerReleasedEventArgs>(
"PointerReleased",
RoutingStrategies.Tunnel | RoutingStrategies.Bubble);
/// <summary>
/// Defines the <see cref="PointerWheelChanged"/> event.
/// </summary>
public static readonly RoutedEvent<PointerWheelEventArgs> PointerWheelChangedEvent =
RoutedEvent.Register<InputElement, PointerWheelEventArgs>(
"PointerWheelChanged",
RoutingStrategies.Tunnel | RoutingStrategies.Bubble);
/// <summary>
/// Defines the <see cref="Tapped"/> event.
/// </summary>
public static readonly RoutedEvent<RoutedEventArgs> TappedEvent = Gestures.TappedEvent;
/// <summary>
/// Defines the <see cref="DoubleTapped"/> event.
/// </summary>
public static readonly RoutedEvent<RoutedEventArgs> DoubleTappedEvent = Gestures.DoubleTappedEvent;
private bool _isFocused;
private bool _isPointerOver;
/// <summary>
/// Initializes static members of the <see cref="InputElement"/> class.
/// </summary>
static InputElement()
{
IsEnabledProperty.Changed.Subscribe(IsEnabledChanged);
GotFocusEvent.AddClassHandler<InputElement>(x => x.OnGotFocus);
LostFocusEvent.AddClassHandler<InputElement>(x => x.OnLostFocus);
KeyDownEvent.AddClassHandler<InputElement>(x => x.OnKeyDown);
KeyUpEvent.AddClassHandler<InputElement>(x => x.OnKeyUp);
TextInputEvent.AddClassHandler<InputElement>(x => x.OnTextInput);
PointerEnterEvent.AddClassHandler<InputElement>(x => x.OnPointerEnterCore);
PointerLeaveEvent.AddClassHandler<InputElement>(x => x.OnPointerLeaveCore);
PointerMovedEvent.AddClassHandler<InputElement>(x => x.OnPointerMoved);
PointerPressedEvent.AddClassHandler<InputElement>(x => x.OnPointerPressed);
PointerReleasedEvent.AddClassHandler<InputElement>(x => x.OnPointerReleased);
PointerWheelChangedEvent.AddClassHandler<InputElement>(x => x.OnPointerWheelChanged);
PseudoClass<InputElement, bool>(IsEnabledCoreProperty, x => !x, ":disabled");
PseudoClass<InputElement>(IsFocusedProperty, ":focus");
PseudoClass<InputElement>(IsPointerOverProperty, ":pointerover");
}
/// <summary>
/// Occurs when the control receives focus.
/// </summary>
public event EventHandler<GotFocusEventArgs> GotFocus
{
add { AddHandler(GotFocusEvent, value); }
remove { RemoveHandler(GotFocusEvent, value); }
}
/// <summary>
/// Occurs when the control loses focus.
/// </summary>
public event EventHandler<RoutedEventArgs> LostFocus
{
add { AddHandler(LostFocusEvent, value); }
remove { RemoveHandler(LostFocusEvent, value); }
}
/// <summary>
/// Occurs when a key is pressed while the control has focus.
/// </summary>
public event EventHandler<KeyEventArgs> KeyDown
{
add { AddHandler(KeyDownEvent, value); }
remove { RemoveHandler(KeyDownEvent, value); }
}
/// <summary>
/// Occurs when a key is released while the control has focus.
/// </summary>
public event EventHandler<KeyEventArgs> KeyUp
{
add { AddHandler(KeyUpEvent, value); }
remove { RemoveHandler(KeyUpEvent, value); }
}
/// <summary>
/// Occurs when a user typed some text while the control has focus.
/// </summary>
public event EventHandler<TextInputEventArgs> TextInput
{
add { AddHandler(TextInputEvent, value); }
remove { RemoveHandler(TextInputEvent, value); }
}
/// <summary>
/// Occurs when the pointer enters the control.
/// </summary>
public event EventHandler<PointerEventArgs> PointerEnter
{
add { AddHandler(PointerEnterEvent, value); }
remove { RemoveHandler(PointerEnterEvent, value); }
}
/// <summary>
/// Occurs when the pointer leaves the control.
/// </summary>
public event EventHandler<PointerEventArgs> PointerLeave
{
add { AddHandler(PointerLeaveEvent, value); }
remove { RemoveHandler(PointerLeaveEvent, value); }
}
/// <summary>
/// Occurs when the pointer moves over the control.
/// </summary>
public event EventHandler<PointerEventArgs> PointerMoved
{
add { AddHandler(PointerMovedEvent, value); }
remove { RemoveHandler(PointerMovedEvent, value); }
}
/// <summary>
/// Occurs when the pointer is pressed over the control.
/// </summary>
public event EventHandler<PointerPressedEventArgs> PointerPressed
{
add { AddHandler(PointerPressedEvent, value); }
remove { RemoveHandler(PointerPressedEvent, value); }
}
/// <summary>
/// Occurs when the pointer is released over the control.
/// </summary>
public event EventHandler<PointerReleasedEventArgs> PointerReleased
{
add { AddHandler(PointerReleasedEvent, value); }
remove { RemoveHandler(PointerReleasedEvent, value); }
}
/// <summary>
/// Occurs when the mouse wheen is scrolled over the control.
/// </summary>
public event EventHandler<PointerWheelEventArgs> PointerWheelChanged
{
add { AddHandler(PointerWheelChangedEvent, value); }
remove { RemoveHandler(PointerWheelChangedEvent, value); }
}
/// <summary>
/// Occurs when a tap gesture occurs on the control.
/// </summary>
public event EventHandler<RoutedEventArgs> Tapped
{
add { AddHandler(TappedEvent, value); }
remove { RemoveHandler(TappedEvent, value); }
}
/// <summary>
/// Occurs when a double-tap gesture occurs on the control.
/// </summary>
public event EventHandler<RoutedEventArgs> DoubleTapped
{
add { AddHandler(DoubleTappedEvent, value); }
remove { RemoveHandler(DoubleTappedEvent, value); }
}
/// <summary>
/// Gets or sets a value indicating whether the control can receive focus.
/// </summary>
public bool Focusable
{
get { return GetValue(FocusableProperty); }
set { SetValue(FocusableProperty, value); }
}
/// <summary>
/// Gets or sets a value indicating whether the control is enabled for user interaction.
/// </summary>
public bool IsEnabled
{
get { return GetValue(IsEnabledProperty); }
set { SetValue(IsEnabledProperty, value); }
}
/// <summary>
/// Gets or sets associated mouse cursor.
/// </summary>
public Cursor Cursor
{
get { return GetValue(CursorProperty); }
set { SetValue(CursorProperty, value); }
}
/// <summary>
/// Gets or sets a value indicating whether the control is focused.
/// </summary>
public bool IsFocused
{
get { return _isFocused; }
private set { SetAndRaise(IsFocusedProperty, ref _isFocused, value); }
}
/// <summary>
/// Gets or sets a value indicating whether the control is considered for hit testing.
/// </summary>
public bool IsHitTestVisible
{
get { return GetValue(IsHitTestVisibleProperty); }
set { SetValue(IsHitTestVisibleProperty, value); }
}
/// <summary>
/// Gets or sets a value indicating whether the pointer is currently over the control.
/// </summary>
public bool IsPointerOver
{
get { return _isPointerOver; }
internal set { SetAndRaise(IsPointerOverProperty, ref _isPointerOver, value); }
}
/// <summary>
/// Gets a value indicating whether the control is effectively enabled for user interaction.
/// </summary>
/// <remarks>
/// The <see cref="IsEnabled"/> property is used to toggle the enabled state for individual
/// controls. The <see cref="IsEnabledCore"/> property takes into account the
/// <see cref="IsEnabled"/> value of this control and its parent controls.
/// </remarks>
bool IInputElement.IsEnabledCore => IsEnabledCore;
/// <summary>
/// Gets a value indicating whether the control is effectively enabled for user interaction.
/// </summary>
/// <remarks>
/// The <see cref="IsEnabled"/> property is used to toggle the enabled state for individual
/// controls. The <see cref="IsEnabledCore"/> property takes into account the
/// <see cref="IsEnabled"/> value of this control and its parent controls.
/// </remarks>
protected bool IsEnabledCore
{
get { return GetValue(IsEnabledCoreProperty); }
set { SetValue(IsEnabledCoreProperty, value); }
}
public List<KeyBinding> KeyBindings { get; } = new List<KeyBinding>();
/// <summary>
/// Focuses the control.
/// </summary>
public void Focus()
{
FocusManager.Instance.Focus(this);
}
/// <inheritdoc/>
protected override void OnDetachedFromVisualTreeCore(VisualTreeAttachmentEventArgs e)
{
base.OnDetachedFromVisualTreeCore(e);
if (IsFocused)
{
FocusManager.Instance.Focus(null);
}
}
/// <inheritdoc/>
protected override void OnAttachedToVisualTreeCore(VisualTreeAttachmentEventArgs e)
{
base.OnAttachedToVisualTreeCore(e);
UpdateIsEnabledCore();
}
/// <summary>
/// Called before the <see cref="GotFocus"/> event occurs.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnGotFocus(GotFocusEventArgs e)
{
IsFocused = e.Source == this;
}
/// <summary>
/// Called before the <see cref="LostFocus"/> event occurs.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnLostFocus(RoutedEventArgs e)
{
IsFocused = false;
}
/// <summary>
/// Called before the <see cref="KeyDown"/> event occurs.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnKeyDown(KeyEventArgs e)
{
}
/// <summary>
/// Called before the <see cref="KeyUp"/> event occurs.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnKeyUp(KeyEventArgs e)
{
}
/// <summary>
/// Called before the <see cref="TextInput"/> event occurs.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnTextInput(TextInputEventArgs e)
{
}
/// <summary>
/// Called before the <see cref="PointerEnter"/> event occurs.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnPointerEnter(PointerEventArgs e)
{
}
/// <summary>
/// Called before the <see cref="PointerLeave"/> event occurs.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnPointerLeave(PointerEventArgs e)
{
}
/// <summary>
/// Called before the <see cref="PointerMoved"/> event occurs.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnPointerMoved(PointerEventArgs e)
{
}
/// <summary>
/// Called before the <see cref="PointerPressed"/> event occurs.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnPointerPressed(PointerPressedEventArgs e)
{
}
/// <summary>
/// Called before the <see cref="PointerReleased"/> event occurs.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnPointerReleased(PointerReleasedEventArgs e)
{
}
/// <summary>
/// Called before the <see cref="PointerWheelChanged"/> event occurs.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnPointerWheelChanged(PointerWheelEventArgs e)
{
}
private static void IsEnabledChanged(AvaloniaPropertyChangedEventArgs e)
{
((InputElement)e.Sender).UpdateIsEnabledCore();
}
/// <summary>
/// Called before the <see cref="PointerEnter"/> event occurs.
/// </summary>
/// <param name="e">The event args.</param>
private void OnPointerEnterCore(PointerEventArgs e)
{
IsPointerOver = true;
OnPointerEnter(e);
}
/// <summary>
/// Called before the <see cref="PointerLeave"/> event occurs.
/// </summary>
/// <param name="e">The event args.</param>
private void OnPointerLeaveCore(PointerEventArgs e)
{
IsPointerOver = false;
OnPointerLeave(e);
}
/// <summary>
/// Updates the <see cref="IsEnabledCore"/> property value.
/// </summary>
private void UpdateIsEnabledCore()
{
UpdateIsEnabledCore(this.GetVisualParent<InputElement>());
}
/// <summary>
/// Updates the <see cref="IsEnabledCore"/> property based on the parent's
/// <see cref="IsEnabledCore"/>.
/// </summary>
/// <param name="parent">The parent control.</param>
private void UpdateIsEnabledCore(InputElement parent)
{
if (parent != null)
{
IsEnabledCore = IsEnabled && parent.IsEnabledCore;
}
else
{
IsEnabledCore = IsEnabled;
}
foreach (var child in this.GetVisualChildren().OfType<InputElement>())
{
child.UpdateIsEnabledCore(this);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using FarseerGames.FarseerPhysics.Dynamics;
using FarseerGames.FarseerPhysics.Interfaces;
#if (XNA)
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
#else
using FarseerGames.FarseerPhysics.Mathematics;
#endif
namespace FarseerGames.FarseerPhysics.Collisions
{
/// <summary>
/// This delegate is called when a collision between 2 geometries occurs
/// </summary>
public delegate bool CollisionEventHandler(Geom geometry1, Geom geometry2, ContactList contactList);
/// <summary>
/// This delegate is called when a separation between 2 geometries occurs
/// </summary>
public delegate void SeparationEventHandler(Geom geometry1, Geom geometry2);
/// <summary>
/// The geometry class is the heart of collision detection.
/// A Geom need a body and a set of vertices. The vertices should define the edge of the shape.
/// </summary>
public class Geom : IEquatable<Geom>, IIsDisposable
{
private bool _isSensor;
private Matrix _matrix = Matrix.Identity;
private Matrix _matrixInverse = Matrix.Identity;
private Vector2 _position = Vector2.Zero;
private Vector2 _positionOffset = Vector2.Zero;
private float _rotation;
private float _rotationOffset;
private bool _isDisposed;
internal Body body;
internal Vertices localVertices;
internal Vertices worldVertices;
internal int id;
public int Id { get { return id; } }
/// <summary>
/// Returns true if the geometry is added to the simulation.
/// Returns false if the geometriy is not.
/// </summary>
public bool InSimulation = true;
/// <summary>
/// Gets or sets the collision categories that this geom collides with.
/// </summary>
/// <Value>The collides with.</Value>
public CollisionCategory CollidesWith = CollisionCategory.All;
/// <summary>
/// Gets or sets the collision categories.
/// Member off all categories by default
/// </summary>
/// <Value>The collision categories.</Value>
public CollisionCategory CollisionCategories = CollisionCategory.All;
/// <summary>
/// Gets or sets a value indicating whether collision response is enabled.
/// If 2 geoms collide and CollisionResponseEnabled is false, then impulses will not be calculated
/// for the 2 colliding geoms. They will pass through each other, but will still be able to fire the
/// <see cref="OnCollision"/> event.
/// </summary>
/// <Value>
/// <c>true</c> if collision response enabled; otherwise, <c>false</c>.
/// </Value>
public bool CollisionResponseEnabled = true;
/// <summary>
/// Controls the amount of friction a geometry has when in contact with another geometry. A Value of zero implies
/// no friction. When two geometries collide, (by default) the average friction coefficient between the two bodies is used.
/// This is controlled using the PhysicsSimulator.FrictionType
/// </summary>
public float FrictionCoefficient;
#if(XNA)
[ContentSerializerIgnore]
#endif
[XmlIgnore]
/// <summary>
/// Fires when a collision occurs with the geom
/// </summary>
public CollisionEventHandler OnCollision;
#if(XNA)
[ContentSerializerIgnore]
#endif
[XmlIgnore]
/// <summary>
/// Fires when a separation between this and another geom occurs
/// </summary>
public SeparationEventHandler OnSeparation;
/// <summary>
/// The coefficient of restitution of the geometry.
/// <para>This parameter controls how bouncy an object is when it collides with other
/// geometries. Valid values range from 0 to 1 inclusive. 1 implies 100% restitution (perfect bounce)
/// 0 implies no restitution (think a ball of clay)</para>
/// </summary>
public float RestitutionCoefficient;
/// <summary>
/// Gets or sets the collision group.
/// If 2 geoms are in the same collision group, they will not collide.
/// </summary>
/// <Value>The collision group.</Value>
public int CollisionGroup;
#if(XNA)
[ContentSerializerIgnore]
#endif
[XmlIgnore]
/// <summary>
/// Gets or sets the Axis Aligned Bounding Box of the geom.
/// </summary>
/// <Value>The AABB.</Value>
public AABB AABB = new AABB();
/// <summary>
/// Gets or sets a Value indicating whether collision is enabled.
/// </summary>
/// <Value><c>true</c> if collision is enabled; otherwise, <c>false</c>.</Value>
public bool CollisionEnabled = true;
#if(XNA)
[ContentSerializerIgnore]
#endif
[XmlIgnore]
/// <summary>
/// Gets or sets the tag. A tag is used to attach a custom object to the Geom.
/// </summary>
/// <Value>The custom object.</Value>
public Object Tag;
/// <summary>
/// Initializes a new instance of the <see cref="Geom"/> class.
/// </summary>
public Geom()
{
id = GetNextId();
}
/// <summary>
/// Initializes a new instance of the <see cref="Geom"/> class.
/// </summary>
/// <param name="body">The body.</param>
/// <param name="vertices">The vertices.</param>
/// <param name="collisionGridSize">Size of the collision grid.</param>
public Geom(Body body, Vertices vertices, float collisionGridSize)
{
Construct(body, vertices, Vector2.Zero, 0, collisionGridSize);
}
/// <summary>
/// Initializes a new instance of the <see cref="Geom"/> class.
/// </summary>
/// <param name="body">The body.</param>
/// <param name="vertices">The vertices.</param>
/// <param name="offset">The offset.</param>
/// <param name="rotationOffset">The rotation offset.</param>
/// <param name="collisionGridSize">Size of the collision grid.</param>
public Geom(Body body, Vertices vertices, Vector2 offset, float rotationOffset, float collisionGridSize)
{
Construct(body, vertices, offset, rotationOffset, collisionGridSize);
}
/// <summary>
/// Creates a clone of an already existing geometry
/// </summary>
/// <param name="body">The body</param>
/// <param name="geometry">The geometry to clone</param>
public Geom(Body body, Geom geometry)
{
ConstructClone(body, geometry, geometry._positionOffset, geometry._rotationOffset);
}
/// <summary>
/// Creates a clone of an already existing geometry
/// </summary>
/// <param name="body">The body</param>
/// <param name="geometry">The geometry to clone</param>
/// <param name="offset">The offset.</param>
/// <param name="rotationOffset">The rotation offset.</param>
public Geom(Body body, Geom geometry, Vector2 offset, float rotationOffset)
{
ConstructClone(body, geometry, offset, rotationOffset);
}
/// <summary>
/// Gets the position. Compared to Body.Position, this property takes position offset of the geometry into account.
/// </summary>
/// <Value>The position.</Value>
public Vector2 Position
{
get { return _position; }
}
/// <summary>
/// Gets the rotation. Compared to Body.Rotation, this property takes rotation offset of the geometry into account.
/// </summary>
/// <Value>The rotation.</Value>
public float Rotation
{
get { return _rotation; }
}
#if(XNA)
[ContentSerializerIgnore]
#endif
[XmlIgnore]
/// <summary>
/// Gets the local vertices of the geom. Local vertices are relative to the center of the vertices.
/// </summary>
/// <Value>The local vertices.</Value>
public Vertices LocalVertices
{
get { return localVertices; }
}
#if(XNA)
[ContentSerializerIgnore]
#endif
[XmlIgnore]
/// <summary>
/// Gets the world vertices. World vertices are the vertices relative to the center of the geometry, plus the position in world space.
/// </summary>
/// <Value>The world vertices.</Value>
public Vertices WorldVertices
{
get { return worldVertices; }
}
#if(XNA)
[ContentSerializerIgnore]
#endif
[XmlIgnore]
/// <summary>
/// Gets or sets the matrix.
/// </summary>
/// <Value>The matrix.</Value>
public Matrix Matrix
{
get { return _matrix; }
set
{
_matrix = value;
Update();
}
}
/// <summary>
/// Gets the inverse matrix.
/// </summary>
/// <Value>The matrix inverse.</Value>
public Matrix MatrixInverse
{
get
{
Matrix.Invert(ref _matrix, out _matrixInverse);
return _matrixInverse;
}
}
/// <summary>
/// Gets or sets a Value indicating whether this instance is a sensor.
/// A sensor does not calculate impulses and does not change position (it's static)
/// it does however detect collisions. Sensors can be used to sense other geoms.
/// </summary>
/// <Value><c>true</c> if this instance is sensor; otherwise, <c>false</c>.</Value>
public bool IsSensor
{
get { return _isSensor; }
set
{
_isSensor = value;
if (_isSensor)
{
body.IsStatic = true;
CollisionResponseEnabled = false;
}
else
{
body.IsStatic = false;
CollisionResponseEnabled = true;
}
}
}
#if(XNA)
[ContentSerializerIgnore]
#endif
[XmlIgnore]
/// <summary>
/// Gets the body attached to the geom.
/// </summary>
/// <Value>The body.</Value>
public Body Body
{
get { return body; }
}
/// <summary>
/// The size of the grid cells used in the distance grid narrow phase collider.
/// </summary>
public float GridCellSize { get; internal set; }
private void Construct(Body bodyToSet, Vertices vertices, Vector2 positionOffset, float rotationOffset,
float collisionGridSize)
{
GridCellSize = collisionGridSize;
id = GetNextId();
_positionOffset = positionOffset;
_rotationOffset = rotationOffset;
SetVertices(vertices);
SetBody(bodyToSet);
//Distancegrid needs to be precomputed
if (PhysicsSimulator.NarrowPhaseCollider == NarrowPhaseCollider.DistanceGrid)
DistanceGrid.Instance.CreateDistanceGrid(this);
}
private void ConstructClone(Body bodyToSet, Geom geometry, Vector2 positionOffset, float rotationOffset)
{
id = GetNextId();
_positionOffset = positionOffset;
_rotationOffset = rotationOffset;
RestitutionCoefficient = geometry.RestitutionCoefficient;
FrictionCoefficient = geometry.FrictionCoefficient;
GridCellSize = geometry.GridCellSize;
//IsSensor = geometry.IsSensor;
CollisionGroup = geometry.CollisionGroup;
CollisionEnabled = geometry.CollisionEnabled;
CollisionResponseEnabled = geometry.CollisionResponseEnabled;
CollisionCategories = geometry.CollisionCategories;
CollidesWith = geometry.CollidesWith;
SetVertices(geometry.localVertices);
SetBody(bodyToSet);
//Make sure that the clone also gets the associated distance grid
if (PhysicsSimulator.NarrowPhaseCollider == NarrowPhaseCollider.DistanceGrid)
DistanceGrid.Instance.Copy(geometry.id, id);
}
/// <summary>
/// Sets the vertices of the geom.
/// </summary>
/// <param name="vertices">The vertices.</param>
public void SetVertices(Vertices vertices)
{
vertices.ForceCounterClockWiseOrder();
localVertices = new Vertices(vertices);
worldVertices = new Vertices(vertices);
AABB.Update(ref vertices);
}
/// <summary>
/// Sets the body.
/// </summary>
/// <param name="bodyToSet">The body.</param>
public void SetBody(Body bodyToSet)
{
body = bodyToSet;
bodyToSet.Updated += Update;
bodyToSet.Disposed += BodyOnDisposed;
Update(ref bodyToSet.position, ref bodyToSet.rotation);
}
/// <summary>
/// Gets the world position.
/// </summary>
/// <param name="localPosition">The local position.</param>
/// <returns></returns>
public Vector2 GetWorldPosition(Vector2 localPosition)
{
Vector2 retVector = Vector2.Transform(localPosition, _matrix);
return retVector;
}
/// <summary>
/// Gets the nearest distance relative to the point given.
/// </summary>
/// <param name="point">The point that should be calculated against.</param>
/// <returns>The distance</returns>
public float GetNearestDistance(ref Vector2 point)
{
float distance = float.MaxValue;
int nearestIndex = 0;
for (int i = 0; i < localVertices.Count; i++)
{
float pointDistance = GetDistanceToEdge(ref point, i);
if (pointDistance < distance)
{
distance = pointDistance;
nearestIndex = i;
}
}
Feature nearestFeature = GetNearestFeature(ref point, nearestIndex);
//Determine if inside or outside of geometry.
Vector2 diff = Vector2.Subtract(point, nearestFeature.Position);
float dot = Vector2.Dot(diff, nearestFeature.Normal);
if (dot < 0)
{
distance = -nearestFeature.Distance;
}
else
{
distance = nearestFeature.Distance;
}
return distance;
}
/// <summary>
/// Gets the distance to edge.
/// </summary>
/// <param name="point">The point.</param>
/// <param name="index">The index.</param>
/// <returns></returns>
private float GetDistanceToEdge(ref Vector2 point, int index)
{
Vector2 edge = localVertices.GetEdge(index);
Vector2 diff = Vector2.Subtract(point, localVertices[index]);
float c1 = Vector2.Dot(diff, edge);
if (c1 < 0)
{
return Math.Abs(diff.Length());
}
float c2 = Vector2.Dot(edge, edge);
if (c2 <= c1)
{
return Vector2.Distance(point, localVertices[localVertices.NextIndex(index)]);
}
float b = c1 / c2;
edge = Vector2.Multiply(edge, b);
Vector2 pb = Vector2.Add(localVertices[index], edge);
return Vector2.Distance(point, pb);
}
/// <summary>
/// Gets the nearest feature relative to a point.
/// </summary>
/// <param name="point">The point.</param>
/// <param name="index">The index of a vector in the vertices.</param>
/// <returns></returns>
public Feature GetNearestFeature(ref Vector2 point, int index)
{
Feature feature = new Feature();
Vector2 edge = localVertices.GetEdge(index);
Vector2 diff = Vector2.Subtract(point, localVertices[index]);
float c1 = Vector2.Dot(diff, edge);
if (c1 < 0)
{
feature.Position = localVertices[index];
feature.Normal = localVertices.GetVertexNormal(index);
feature.Distance = Math.Abs(diff.Length());
return feature;
}
float c2 = Vector2.Dot(edge, edge);
if (c2 <= c1)
{
Vector2 d1 = Vector2.Subtract(point, localVertices[localVertices.NextIndex(index)]);
feature.Position = localVertices[localVertices.NextIndex(index)];
feature.Normal = localVertices.GetVertexNormal(localVertices.NextIndex(index));
feature.Distance = Math.Abs(d1.Length());
return feature;
}
float b = c1 / c2;
edge = Vector2.Multiply(edge, b);
Vector2 pb = Vector2.Add(localVertices[index], edge);
Vector2 d2 = Vector2.Subtract(point, pb);
feature.Position = pb;
feature.Normal = localVertices.GetEdgeNormal(index); // GetEdgeNormal(index);
feature.Distance = d2.Length();
return feature;
}
/// <summary>
/// Checks to see if the geom collides with the specified point.
/// </summary>
/// <param name="position">The point.</param>
/// <returns>true if colliding</returns>
public bool Collide(Vector2 position)
{
return Collide(ref position);
}
/// <summary>
/// Checks to see if the geom collides with the specified point.
/// </summary>
/// <param name="position">The point.</param>
/// <returns>true if colliding</returns>
public bool Collide(ref Vector2 position)
{
//Check first if the AABB contains the point
if (AABB.Contains(ref position))
{
//Make sure the point is relative to the local vertices. (convert world point to local point)
Matrix matrixInverse = MatrixInverse;
Vector2.Transform(ref position, ref matrixInverse, out position);
if (PhysicsSimulator.NarrowPhaseCollider == NarrowPhaseCollider.DistanceGrid)
return DistanceGrid.Instance.Intersect(this, ref position);
if (PhysicsSimulator.NarrowPhaseCollider == NarrowPhaseCollider.SAT)
return SAT.Instance.Intersect(this, ref position);
}
return false;
}
/// <summary>
/// Exactly the same as Collide(), but does not do the AABB check because it was done elsewhere.
/// </summary>
/// <param name="point"></param>
/// <returns></returns>
private bool FastCollide(ref Vector2 position)
{
Matrix matrixInverse = MatrixInverse;
Vector2.Transform(ref position, ref matrixInverse, out position);
if (PhysicsSimulator.NarrowPhaseCollider == NarrowPhaseCollider.DistanceGrid)
return DistanceGrid.Instance.Intersect(this, ref position);
if (PhysicsSimulator.NarrowPhaseCollider == NarrowPhaseCollider.SAT)
return SAT.Instance.Intersect(this, ref position);
return false;
}
/// <summary>
/// Checks to see if the geom collides with the specified geom.
/// </summary>
/// <param name="geometry">The geometry.</param>
/// <returns></returns>
public bool Collide(Geom geometry)
{
//Check first if the AABB intersects the other geometry's AABB. If they
//do not intersect, there can be no collision.
if (AABB.Intersect(AABB, geometry.AABB))
{
//Check each vertice (of self) against the provided geometry
int count = worldVertices.Count;
for (int i = 0; i < count; i++)
{
_tempVector = worldVertices[i];
if (geometry.FastCollide(ref _tempVector))
return true;
}
//Check each vertice of the provided geometry, against itself
count = geometry.worldVertices.Count;
for (int i = 0; i < count; i++)
{
_tempVector = geometry.worldVertices[i];
if (FastCollide(ref _tempVector))
return true;
}
}
return false;
}
/// <summary>
/// Transforms a world vertex to local vertex.
/// </summary>
/// <param name="worldVertex">The world vertex.</param>
/// <param name="localVertex">The local vertex.</param>
public void TransformToLocalCoordinates(ref Vector2 worldVertex, out Vector2 localVertex)
{
_matrixInverseTemp = MatrixInverse;
Vector2.Transform(ref worldVertex, ref _matrixInverseTemp, out localVertex);
}
/// <summary>
/// Transforms a local normal to a world normal.
/// </summary>
/// <param name="localNormal">The local normal.</param>
/// <param name="worldNormal">The world normal.</param>
public void TransformNormalToWorld(ref Vector2 localNormal, out Vector2 worldNormal)
{
Vector2.TransformNormal(ref localNormal, ref _matrix, out worldNormal);
}
private void Update(ref Vector2 position, ref float rotation)
{
//Create rotation matrix with the rotation offset applied.
Matrix.CreateRotationZ(rotation + _rotationOffset, out _matrix);
#region INLINE: Vector2.Transform(ref _offset, ref _matrix, out _newPos);
//Transform the matrix with the position offset
float num2 = ((_positionOffset.X * _matrix.M11) + (_positionOffset.Y * _matrix.M21)) + _matrix.M41;
float num = ((_positionOffset.X * _matrix.M12) + (_positionOffset.Y * _matrix.M22)) + _matrix.M42;
#endregion
// Save the position (with offset) into the matrix
_matrix.M41 = position.X + num2;
_matrix.M42 = position.Y + num;
_matrix.M44 = 1;
//Update position
_position.X = _matrix.M41;
_position.Y = _matrix.M42;
//Update rotation
_rotation = body.rotation + _rotationOffset;
//Convert all the local vertices to world vertices (using the new matrix)
Update();
}
/// <summary>
/// Transform the local vertices to world vertices.
/// Also updates the AABB of the geometry to the new values.
/// </summary>
private void Update()
{
for (int i = 0; i < localVertices.Count; i++)
{
#region INLINE: worldVertices[i] = Vector2.Transform(localVertices[i], _matrix);
_localVertice = localVertices[i];
float num2 = ((_localVertice.X * _matrix.M11) + (_localVertice.Y * _matrix.M21)) + _matrix.M41;
float num = ((_localVertice.X * _matrix.M12) + (_localVertice.Y * _matrix.M22)) + _matrix.M42;
_vertice.X = num2;
_vertice.Y = num;
worldVertices[i] = _vertice;
#endregion
}
AABB.Update(ref worldVertices);
}
private List<Geom> _collisionIgnores = new List<Geom>();
public void IgnoreCollisionWith(Geom geometry)
{
_collisionIgnores.Add(geometry);
}
public bool FindDNC(Geom geometry)
{
foreach (Geom geom in _collisionIgnores)
{
if (geometry.Equals(geom))
{
return true;
}
}
return false;
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="T:System.Object"/>.
/// </returns>
/// <filterpriority>2</filterpriority>
public override int GetHashCode()
{
return base.GetHashCode();
}
/// <summary>
/// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>.
/// </summary>
/// <returns>
/// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false.
/// </returns>
/// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.
/// </param><exception cref="T:System.NullReferenceException">The <paramref name="obj"/> parameter is null.
/// </exception><filterpriority>2</filterpriority>
public override bool Equals(object obj)
{
Geom g = obj as Geom;
if ((object)g == null)
{
return false;
}
return Equals(g);
}
public static bool operator ==(Geom geometry1, Geom geometry2)
{
// If both are null, or both are same instance, return true.
if (ReferenceEquals(geometry1, geometry2))
{
return true;
}
// If one is null, but not both, return false.
if (((object)geometry1 == null) || ((object)geometry2 == null))
{
return false;
}
return geometry1.Equals(geometry2);
}
public static bool operator !=(Geom geometry1, Geom geometry2)
{
return !(geometry1 == geometry2);
}
public static bool operator <(Geom geometry1, Geom geometry2)
{
return geometry1.id < geometry2.id;
}
public static bool operator >(Geom geometry1, Geom geometry2)
{
return geometry1.id > geometry2.id;
}
private static int GetNextId()
{
_newId += 1;
return _newId;
}
private void BodyOnDisposed(object sender, EventArgs e)
{
Dispose();
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources
/// Subclasses can override incase they need to dispose of resources otherwise do nothing.
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (!IsDisposed)
{
if (disposing)
{
//Make sure to remove the distancegrid when removing this geometry
if (PhysicsSimulator.NarrowPhaseCollider == NarrowPhaseCollider.DistanceGrid)
DistanceGrid.Instance.RemoveDistanceGrid(this);
//dispose managed resources
if (body != null)
{
//Release event subscriptions
body.Updated -= Update;
body.Disposed -= BodyOnDisposed;
}
}
}
IsDisposed = true;
}
#region IDisposable Members
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
#region IEquatable<Geom> Members
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <returns>
/// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
/// </returns>
/// <param name="other">An object to compare with this object.
/// </param>
public bool Equals(Geom other)
{
if ((object)other == null)
{
return false;
}
return id == other.id;
}
#endregion
#region IIsDisposable Members
#if(XNA)
[ContentSerializerIgnore]
#endif
[XmlIgnore]
public bool IsDisposed
{
get { return _isDisposed; }
set { _isDisposed = value; }
}
#endregion
#region GetNextId variables
private static int _newId = -1;
#endregion
#region Update variables
private Vector2 _localVertice;
private Vector2 _vertice = Vector2.Zero;
#endregion
#region Collide variables
private Vector2 _tempVector;
#endregion
#region TransformToLocalCoordinates variables
private Matrix _matrixInverseTemp;
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using Internal.Win32;
namespace System
{
public static partial class Environment
{
internal static bool IsWindows8OrAbove => WindowsVersion.IsWindows8OrAbove;
private static string? GetEnvironmentVariableFromRegistry(string variable, bool fromMachine)
{
Debug.Assert(variable != null);
#if FEATURE_APPX
if (ApplicationModel.IsUap)
return null; // Systems without the Windows registry pretend that it's always empty.
#endif
using (RegistryKey? environmentKey = OpenEnvironmentKeyIfExists(fromMachine, writable: false))
{
return environmentKey?.GetValue(variable) as string;
}
}
private static void SetEnvironmentVariableFromRegistry(string variable, string? value, bool fromMachine)
{
Debug.Assert(variable != null);
#if FEATURE_APPX
if (ApplicationModel.IsUap)
return; // Systems without the Windows registry pretend that it's always empty.
#endif
const int MaxUserEnvVariableLength = 255; // User-wide env vars stored in the registry have names limited to 255 chars
if (!fromMachine && variable.Length >= MaxUserEnvVariableLength)
{
throw new ArgumentException(SR.Argument_LongEnvVarValue, nameof(variable));
}
using (RegistryKey? environmentKey = OpenEnvironmentKeyIfExists(fromMachine, writable: true))
{
if (environmentKey != null)
{
if (value == null)
{
environmentKey.DeleteValue(variable, throwOnMissingValue: false);
}
else
{
environmentKey.SetValue(variable, value);
}
}
}
// send a WM_SETTINGCHANGE message to all windows
IntPtr r = Interop.User32.SendMessageTimeout(new IntPtr(Interop.User32.HWND_BROADCAST), Interop.User32.WM_SETTINGCHANGE, IntPtr.Zero, "Environment", 0, 1000, IntPtr.Zero);
Debug.Assert(r != IntPtr.Zero, "SetEnvironmentVariable failed: " + Marshal.GetLastWin32Error());
}
private static IDictionary GetEnvironmentVariablesFromRegistry(bool fromMachine)
{
var results = new Hashtable();
#if FEATURE_APPX
if (ApplicationModel.IsUap) // Systems without the Windows registry pretend that it's always empty.
return results;
#endif
using (RegistryKey? environmentKey = OpenEnvironmentKeyIfExists(fromMachine, writable: false))
{
if (environmentKey != null)
{
foreach (string name in environmentKey.GetValueNames())
{
string? value = environmentKey.GetValue(name, "").ToString();
try
{
results.Add(name, value);
}
catch (ArgumentException)
{
// Throw and catch intentionally to provide non-fatal notification about corrupted environment block
}
}
}
}
return results;
}
private static RegistryKey? OpenEnvironmentKeyIfExists(bool fromMachine, bool writable)
{
RegistryKey baseKey;
string keyName;
if (fromMachine)
{
baseKey = Registry.LocalMachine;
keyName = @"System\CurrentControlSet\Control\Session Manager\Environment";
}
else
{
baseKey = Registry.CurrentUser;
keyName = "Environment";
}
return baseKey.OpenSubKey(keyName, writable: writable);
}
public static string UserName
{
get
{
#if FEATURE_APPX
if (ApplicationModel.IsUap)
return "Windows User";
#endif
// 40 should be enough as we're asking for the SAM compatible name (DOMAIN\User).
// The max length should be 15 (domain) + 1 (separator) + 20 (name) + null. If for
// some reason it isn't, we'll grow the buffer.
// https://support.microsoft.com/en-us/help/909264/naming-conventions-in-active-directory-for-computers-domains-sites-and
// https://msdn.microsoft.com/en-us/library/ms679635.aspx
Span<char> initialBuffer = stackalloc char[40];
var builder = new ValueStringBuilder(initialBuffer);
GetUserName(ref builder);
ReadOnlySpan<char> name = builder.AsSpan();
int index = name.IndexOf('\\');
if (index != -1)
{
// In the form of DOMAIN\User, cut off DOMAIN\
name = name.Slice(index + 1);
}
string result = name.ToString();
builder.Dispose();
return result;
}
}
private static void GetUserName(ref ValueStringBuilder builder)
{
uint size = 0;
while (Interop.Secur32.GetUserNameExW(Interop.Secur32.NameSamCompatible, ref builder.GetPinnableReference(), ref size) == Interop.BOOLEAN.FALSE)
{
if (Marshal.GetLastWin32Error() == Interop.Errors.ERROR_MORE_DATA)
{
builder.EnsureCapacity(checked((int)size));
}
else
{
builder.Length = 0;
return;
}
}
builder.Length = (int)size;
}
public static string UserDomainName
{
get
{
#if FEATURE_APPX
if (ApplicationModel.IsUap)
return "Windows Domain";
#endif
// See the comment in UserName
Span<char> initialBuffer = stackalloc char[40];
var builder = new ValueStringBuilder(initialBuffer);
GetUserName(ref builder);
ReadOnlySpan<char> name = builder.AsSpan();
int index = name.IndexOf('\\');
if (index != -1)
{
// In the form of DOMAIN\User, cut off \User and return
builder.Length = index;
return builder.ToString();
}
// In theory we should never get use out of LookupAccountNameW as the above API should
// always return what we need. Can't find any clues in the historical sources, however.
// Domain names aren't typically long.
// https://support.microsoft.com/en-us/help/909264/naming-conventions-in-active-directory-for-computers-domains-sites-and
Span<char> initialDomainNameBuffer = stackalloc char[64];
var domainBuilder = new ValueStringBuilder(initialDomainNameBuffer);
uint length = (uint)domainBuilder.Capacity;
// This API will fail to return the domain name without a buffer for the SID.
// SIDs are never over 68 bytes long.
Span<byte> sid = stackalloc byte[68];
uint sidLength = 68;
while (!Interop.Advapi32.LookupAccountNameW(null, ref builder.GetPinnableReference(), ref MemoryMarshal.GetReference(sid),
ref sidLength, ref domainBuilder.GetPinnableReference(), ref length, out _))
{
int error = Marshal.GetLastWin32Error();
// The docs don't call this out clearly, but experimenting shows that the error returned is the following.
if (error != Interop.Errors.ERROR_INSUFFICIENT_BUFFER)
{
throw new InvalidOperationException(Win32Marshal.GetMessage(error));
}
domainBuilder.EnsureCapacity((int)length);
}
builder.Dispose();
domainBuilder.Length = (int)length;
return domainBuilder.ToString();
}
}
private static string GetFolderPathCore(SpecialFolder folder, SpecialFolderOption option)
{
#if FEATURE_APPX
if (ApplicationModel.IsUap)
return WinRTFolderPaths.GetFolderPath(folder, option);
#endif
// We're using SHGetKnownFolderPath instead of SHGetFolderPath as SHGetFolderPath is
// capped at MAX_PATH.
//
// Because we validate both of the input enums we shouldn't have to care about CSIDL and flag
// definitions we haven't mapped. If we remove or loosen the checks we'd have to account
// for mapping here (this includes tweaking as SHGetFolderPath would do).
//
// The only SpecialFolderOption defines we have are equivalent to KnownFolderFlags.
string folderGuid;
switch (folder)
{
case SpecialFolder.ApplicationData:
folderGuid = Interop.Shell32.KnownFolders.RoamingAppData;
break;
case SpecialFolder.CommonApplicationData:
folderGuid = Interop.Shell32.KnownFolders.ProgramData;
break;
case SpecialFolder.LocalApplicationData:
folderGuid = Interop.Shell32.KnownFolders.LocalAppData;
break;
case SpecialFolder.Cookies:
folderGuid = Interop.Shell32.KnownFolders.Cookies;
break;
case SpecialFolder.Desktop:
folderGuid = Interop.Shell32.KnownFolders.Desktop;
break;
case SpecialFolder.Favorites:
folderGuid = Interop.Shell32.KnownFolders.Favorites;
break;
case SpecialFolder.History:
folderGuid = Interop.Shell32.KnownFolders.History;
break;
case SpecialFolder.InternetCache:
folderGuid = Interop.Shell32.KnownFolders.InternetCache;
break;
case SpecialFolder.Programs:
folderGuid = Interop.Shell32.KnownFolders.Programs;
break;
case SpecialFolder.MyComputer:
folderGuid = Interop.Shell32.KnownFolders.ComputerFolder;
break;
case SpecialFolder.MyMusic:
folderGuid = Interop.Shell32.KnownFolders.Music;
break;
case SpecialFolder.MyPictures:
folderGuid = Interop.Shell32.KnownFolders.Pictures;
break;
case SpecialFolder.MyVideos:
folderGuid = Interop.Shell32.KnownFolders.Videos;
break;
case SpecialFolder.Recent:
folderGuid = Interop.Shell32.KnownFolders.Recent;
break;
case SpecialFolder.SendTo:
folderGuid = Interop.Shell32.KnownFolders.SendTo;
break;
case SpecialFolder.StartMenu:
folderGuid = Interop.Shell32.KnownFolders.StartMenu;
break;
case SpecialFolder.Startup:
folderGuid = Interop.Shell32.KnownFolders.Startup;
break;
case SpecialFolder.System:
folderGuid = Interop.Shell32.KnownFolders.System;
break;
case SpecialFolder.Templates:
folderGuid = Interop.Shell32.KnownFolders.Templates;
break;
case SpecialFolder.DesktopDirectory:
folderGuid = Interop.Shell32.KnownFolders.Desktop;
break;
case SpecialFolder.Personal:
// Same as Personal
// case SpecialFolder.MyDocuments:
folderGuid = Interop.Shell32.KnownFolders.Documents;
break;
case SpecialFolder.ProgramFiles:
folderGuid = Interop.Shell32.KnownFolders.ProgramFiles;
break;
case SpecialFolder.CommonProgramFiles:
folderGuid = Interop.Shell32.KnownFolders.ProgramFilesCommon;
break;
case SpecialFolder.AdminTools:
folderGuid = Interop.Shell32.KnownFolders.AdminTools;
break;
case SpecialFolder.CDBurning:
folderGuid = Interop.Shell32.KnownFolders.CDBurning;
break;
case SpecialFolder.CommonAdminTools:
folderGuid = Interop.Shell32.KnownFolders.CommonAdminTools;
break;
case SpecialFolder.CommonDocuments:
folderGuid = Interop.Shell32.KnownFolders.PublicDocuments;
break;
case SpecialFolder.CommonMusic:
folderGuid = Interop.Shell32.KnownFolders.PublicMusic;
break;
case SpecialFolder.CommonOemLinks:
folderGuid = Interop.Shell32.KnownFolders.CommonOEMLinks;
break;
case SpecialFolder.CommonPictures:
folderGuid = Interop.Shell32.KnownFolders.PublicPictures;
break;
case SpecialFolder.CommonStartMenu:
folderGuid = Interop.Shell32.KnownFolders.CommonStartMenu;
break;
case SpecialFolder.CommonPrograms:
folderGuid = Interop.Shell32.KnownFolders.CommonPrograms;
break;
case SpecialFolder.CommonStartup:
folderGuid = Interop.Shell32.KnownFolders.CommonStartup;
break;
case SpecialFolder.CommonDesktopDirectory:
folderGuid = Interop.Shell32.KnownFolders.PublicDesktop;
break;
case SpecialFolder.CommonTemplates:
folderGuid = Interop.Shell32.KnownFolders.CommonTemplates;
break;
case SpecialFolder.CommonVideos:
folderGuid = Interop.Shell32.KnownFolders.PublicVideos;
break;
case SpecialFolder.Fonts:
folderGuid = Interop.Shell32.KnownFolders.Fonts;
break;
case SpecialFolder.NetworkShortcuts:
folderGuid = Interop.Shell32.KnownFolders.NetHood;
break;
case SpecialFolder.PrinterShortcuts:
folderGuid = Interop.Shell32.KnownFolders.PrintersFolder;
break;
case SpecialFolder.UserProfile:
folderGuid = Interop.Shell32.KnownFolders.Profile;
break;
case SpecialFolder.CommonProgramFilesX86:
folderGuid = Interop.Shell32.KnownFolders.ProgramFilesCommonX86;
break;
case SpecialFolder.ProgramFilesX86:
folderGuid = Interop.Shell32.KnownFolders.ProgramFilesX86;
break;
case SpecialFolder.Resources:
folderGuid = Interop.Shell32.KnownFolders.ResourceDir;
break;
case SpecialFolder.LocalizedResources:
folderGuid = Interop.Shell32.KnownFolders.LocalizedResourcesDir;
break;
case SpecialFolder.SystemX86:
folderGuid = Interop.Shell32.KnownFolders.SystemX86;
break;
case SpecialFolder.Windows:
folderGuid = Interop.Shell32.KnownFolders.Windows;
break;
default:
return string.Empty;
}
return GetKnownFolderPath(folderGuid, option);
}
private static string GetKnownFolderPath(string folderGuid, SpecialFolderOption option)
{
Guid folderId = new Guid(folderGuid);
int hr = Interop.Shell32.SHGetKnownFolderPath(folderId, (uint)option, IntPtr.Zero, out string path);
if (hr != 0) // Not S_OK
{
return string.Empty;
}
return path;
}
#if FEATURE_APPX
private static class WinRTFolderPaths
{
private static Func<SpecialFolder, SpecialFolderOption, string>? s_winRTFolderPathsGetFolderPath;
public static string GetFolderPath(SpecialFolder folder, SpecialFolderOption option)
{
if (s_winRTFolderPathsGetFolderPath == null)
{
Type? winRtFolderPathsType = Type.GetType("System.WinRTFolderPaths, System.Runtime.WindowsRuntime, Version=4.0.14.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", throwOnError: false);
MethodInfo? getFolderPathsMethod = winRtFolderPathsType?.GetMethod("GetFolderPath", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { typeof(SpecialFolder), typeof(SpecialFolderOption) }, null);
var d = (Func<SpecialFolder, SpecialFolderOption, string>?)getFolderPathsMethod?.CreateDelegate(typeof(Func<SpecialFolder, SpecialFolderOption, string>));
s_winRTFolderPathsGetFolderPath = d ?? delegate { return string.Empty; };
}
return s_winRTFolderPathsGetFolderPath(folder, option);
}
}
#endif
// Seperate type so a .cctor is not created for Enviroment which then would be triggered during startup
private static class WindowsVersion
{
// Cache the value in static readonly that can be optimized out by the JIT
internal static readonly bool IsWindows8OrAbove = GetIsWindows8OrAbove();
private static bool GetIsWindows8OrAbove()
{
ulong conditionMask = Interop.Kernel32.VerSetConditionMask(0, Interop.Kernel32.VER_MAJORVERSION, Interop.Kernel32.VER_GREATER_EQUAL);
conditionMask = Interop.Kernel32.VerSetConditionMask(conditionMask, Interop.Kernel32.VER_MINORVERSION, Interop.Kernel32.VER_GREATER_EQUAL);
conditionMask = Interop.Kernel32.VerSetConditionMask(conditionMask, Interop.Kernel32.VER_SERVICEPACKMAJOR, Interop.Kernel32.VER_GREATER_EQUAL);
conditionMask = Interop.Kernel32.VerSetConditionMask(conditionMask, Interop.Kernel32.VER_SERVICEPACKMINOR, Interop.Kernel32.VER_GREATER_EQUAL);
// Windows 8 version is 6.2
Interop.Kernel32.OSVERSIONINFOEX version = default;
unsafe
{
version.dwOSVersionInfoSize = sizeof(Interop.Kernel32.OSVERSIONINFOEX);
}
version.dwMajorVersion = 6;
version.dwMinorVersion = 2;
version.wServicePackMajor = 0;
version.wServicePackMinor = 0;
return Interop.Kernel32.VerifyVersionInfoW(ref version,
Interop.Kernel32.VER_MAJORVERSION | Interop.Kernel32.VER_MINORVERSION | Interop.Kernel32.VER_SERVICEPACKMAJOR | Interop.Kernel32.VER_SERVICEPACKMINOR,
conditionMask);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
** Purpose: A wrapper for establishing a WeakReference to an Object.
**
===========================================================*/
using System;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Threading;
using System.Diagnostics;
using Internal.Runtime.Augments;
namespace System
{
public class WeakReference
{
// If you fix bugs here, please fix them in WeakReference<T> at the same time.
// Most methods using m_handle should use GC.KeepAlive(this) to avoid potential handle recycling
// attacks (i.e. if the WeakReference instance is finalized away underneath you when you're still
// handling a cached value of the handle then the handle could be freed and reused).
internal volatile IntPtr m_handle;
internal bool m_IsLongReference;
// Creates a new WeakReference that keeps track of target.
// Assumes a Short Weak Reference (ie TrackResurrection is false.)
//
public WeakReference(Object target)
: this(target, false)
{
}
//Creates a new WeakReference that keeps track of target.
//
public WeakReference(Object target, bool trackResurrection)
{
m_IsLongReference = trackResurrection;
m_handle = GCHandle.ToIntPtr(GCHandle.Alloc(target, trackResurrection ? GCHandleType.WeakTrackResurrection : GCHandleType.Weak));
// Set the conditional weak table if the target is a __ComObject.
TrySetComTarget(target);
}
//Determines whether or not this instance of WeakReference still refers to an object
//that has not been collected.
//
public virtual bool IsAlive
{
get
{
IntPtr h = m_handle;
// In determining whether it is valid to use this object, we need to at least expose this
// without throwing an exception.
if (default(IntPtr) == h)
return false;
bool result = (RuntimeImports.RhHandleGet(h) != null || TryGetComTarget() != null);
// We want to ensure that if the target is live, then we will
// return it to the user. We need to keep this WeakReference object
// live so m_handle doesn't get set to 0 or reused.
// Since m_handle is volatile, the following statement will
// guarantee the weakref object is live till the following
// statement.
return (m_handle == default(IntPtr)) ? false : result;
}
}
//Returns a boolean indicating whether or not we're tracking objects until they're collected (true)
//or just until they're finalized (false).
//
public virtual bool TrackResurrection
{
get { return m_IsLongReference; }
}
//Gets the Object stored in the handle if it's accessible.
// Or sets it.
//
public virtual Object Target
{
get
{
IntPtr h = m_handle;
// Should only happen when used illegally, like using a
// WeakReference from a finalizer.
if (default(IntPtr) == h)
return null;
Object o = RuntimeImports.RhHandleGet(h);
if (o == null)
{
o = TryGetComTarget();
}
// We want to ensure that if the target is live, then we will
// return it to the user. We need to keep this WeakReference object
// live so m_handle doesn't get set to 0 or reused.
// Since m_handle is volatile, the following statement will
// guarantee the weakref object is live till the following
// statement.
return (m_handle == default(IntPtr)) ? null : o;
}
set
{
IntPtr h = m_handle;
if (h == default(IntPtr))
throw new InvalidOperationException(SR.InvalidOperation_HandleIsNotInitialized);
#if false
// There is a race w/ finalization where m_handle gets set to
// NULL and the WeakReference becomes invalid. Here we have to
// do the following in order:
//
// 1. Get the old object value
// 2. Get m_handle
// 3. HndInterlockedCompareExchange(m_handle, newValue, oldValue);
//
// If the interlocked-cmp-exchange fails, then either we lost a race
// with another updater, or we lost a race w/ the finalizer. In
// either case, we can just let the other guy win.
Object oldValue = RuntimeImports.RhHandleGet(h);
h = m_handle;
if (h == default(IntPtr))
throw new InvalidOperationException(SR.InvalidOperation_HandleIsNotInitialized);
GCHandle.InternalCompareExchange(h, value, oldValue, false /* isPinned */);
#else
// The above logic seems somewhat paranoid and even wrong.
//
// 1. It's the GC rather than any finalizer that clears weak handles (indeed there's no guarantee any finalizer is involved
// at all).
// 2. Retrieving the object from the handle atomically creates a strong reference to it, so
// as soon as we get the handle contents above (before it's even assigned into oldValue)
// the only race we can be in is with another setter.
// 3. We don't really care who wins in a race between two setters: last update wins is just
// as good as first update wins. If there was a race with the "finalizer" though, we'd
// probably want the setter to win (otherwise we could nullify a set just because it raced
// with the old object becoming unreferenced).
//
// The upshot of all of this is that we can just go ahead and set the handle. I suspect that
// with further review I could prove that this class doesn't need to mess around with raw
// IntPtrs at all and can simply use GCHandle directly, avoiding all these internal calls.
// Check whether the new value is __COMObject. If so, add the new entry to conditional weak table.
TrySetComTarget(value);
RuntimeImports.RhHandleSet(h, value);
#endif
// Ensure we don't have any handle recycling attacks in this
// method where the finalizer frees the handle.
GC.KeepAlive(this);
}
}
/// <summary>
/// This method checks whether the target to the weakreference is a native COMObject in which case the native object might still be alive although the RuntimeHandle could be null.
/// Hence we check in the conditionalweaktable maintained by the System.private.Interop.dll that maps weakreferenceInstance->nativeComObject to check whether the native COMObject is alive or not.
/// and gets\create a new RCW in case it is alive.
/// </summary>
/// <returns></returns>
private Object TryGetComTarget()
{
#if ENABLE_WINRT
WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks;
if (callbacks != null)
{
return callbacks.GetCOMWeakReferenceTarget(this);
}
else
{
Debug.Assert(false, "WinRTInteropCallback is null");
}
#endif // ENABLE_WINRT
return null;
}
/// <summary>
/// This method notifies the System.private.Interop.dll to update the conditionalweaktable for weakreferenceInstance->target in case the target is __ComObject. This ensures that we have a means to
/// go from the managed weak reference to the actual native object even though the managed counterpart might have been collected.
/// </summary>
/// <param name="target"></param>
private void TrySetComTarget(object target)
{
#if ENABLE_WINRT
WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks;
if (callbacks != null)
{
callbacks.SetCOMWeakReferenceTarget(this, target);
}
else
{
Debug.Assert(false, "WinRTInteropCallback is null");
}
#endif // ENABLE_WINRT
}
// Free all system resources associated with this reference.
~WeakReference()
{
#pragma warning disable 420 // FYI - ref m_handle causes this. I asked the C# team to add in "ref volatile T" as a parameter type in a future version.
IntPtr handle = Interlocked.Exchange(ref m_handle, default(IntPtr));
#pragma warning restore 420
if (handle != default(IntPtr))
((GCHandle)handle).Free();
}
}
}
| |
using System;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using FeedBuilder.Properties;
namespace FeedBuilder
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
#region " Private constants/variables"
private const string DialogFilter = "Feed configuration files (*.config)|*.config|All files (*.*)|*.*";
private const string DefaultFileName = "FeedBuilder.config";
private OpenFileDialog _openDialog;
#endregion
private ArgumentsParser _argParser;
#region " Properties"
public string FileName { get; set; }
public bool ShowGui { get; set; }
#endregion
#region " Loading/Initialization/Lifetime"
private void frmMain_Load(Object sender, EventArgs e)
{
Visible = false;
InitializeFormSettings();
string[] args = Environment.GetCommandLineArgs();
// The first arg is the path to ourself
//If args.Count >= 2 Then
// If File.Exists(args(1)) Then
// Dim p As New FeedBuilderSettingsProvider()
// p.LoadFrom(args(1))
// Me.FileName = args(1)
// End If
//End If
// The first arg is the path to ourself
_argParser = new ArgumentsParser(args);
if (!_argParser.HasArgs)
{
FreeConsole();
return;
}
FileName = _argParser.FileName;
if (!string.IsNullOrEmpty(FileName))
{
if (File.Exists(FileName))
{
FeedBuilderSettingsProvider p = new FeedBuilderSettingsProvider();
p.LoadFrom(FileName);
InitializeFormSettings();
}
else
{
_argParser.ShowGui = true;
_argParser.Build = false;
UpdateTitle();
}
}
if (_argParser.ShowGui) Show();
if (_argParser.Build) Build();
if (!_argParser.ShowGui) Close();
}
private void InitializeFormSettings()
{
if (string.IsNullOrEmpty(Settings.Default.OutputFolder))
{
txtOutputFolder.Text = string.Empty;
}
else
{
string path = GetFullDirectoryPath(Settings.Default.OutputFolder);
txtOutputFolder.Text = Directory.Exists(path) ? Settings.Default.OutputFolder : string.Empty;
}
txtFeedXML.Text = string.IsNullOrEmpty(Settings.Default.FeedXML) ? string.Empty : Settings.Default.FeedXML;
txtBaseURL.Text = string.IsNullOrEmpty(Settings.Default.BaseURL) ? string.Empty : Settings.Default.BaseURL;
chkVersion.Checked = Settings.Default.CompareVersion;
chkSize.Checked = Settings.Default.CompareSize;
chkDate.Checked = Settings.Default.CompareDate;
chkHash.Checked = Settings.Default.CompareHash;
chkSign.Checked = Settings.Default.Sign;
txtSignFile.Text = Settings.Default.SignFile;
chkIgnoreSymbols.Checked = Settings.Default.IgnoreDebugSymbols;
chkIgnoreVsHost.Checked = Settings.Default.IgnoreVsHosting;
chkCopyFiles.Checked = Settings.Default.CopyFiles;
chkCleanUp.Checked = Settings.Default.CleanUp;
txtAddExtension.Text = Settings.Default.AddExtension;
if (Settings.Default.IgnoreFiles == null) Settings.Default.IgnoreFiles = new StringCollection();
ReadFiles();
UpdateTitle();
}
private void UpdateTitle()
{
if (string.IsNullOrEmpty(FileName)) Text = "Feed Builder";
else Text = "Feed Builder - " + FileName;
}
private void SaveFormSettings()
{
if (!string.IsNullOrEmpty(txtOutputFolder.Text.Trim()) && Directory.Exists(txtOutputFolder.Text.Trim()))
Settings.Default.OutputFolder = txtOutputFolder.Text.Trim();
// ReSharper disable AssignNullToNotNullAttribute
if (!string.IsNullOrEmpty(txtFeedXML.Text.Trim()) && Directory.Exists(Path.GetDirectoryName(txtFeedXML.Text.Trim())))
Settings.Default.FeedXML = txtFeedXML.Text.Trim();
// ReSharper restore AssignNullToNotNullAttribute
if (!string.IsNullOrEmpty(txtBaseURL.Text.Trim())) Settings.Default.BaseURL = txtBaseURL.Text.Trim();
if (!string.IsNullOrEmpty(txtAddExtension.Text.Trim())) Settings.Default.AddExtension = txtAddExtension.Text.Trim();
Settings.Default.CompareVersion = chkVersion.Checked;
Settings.Default.CompareSize = chkSize.Checked;
Settings.Default.CompareDate = chkDate.Checked;
Settings.Default.CompareHash = chkHash.Checked;
Settings.Default.Sign = chkSign.Checked;
Settings.Default.SignFile = txtSignFile.Text;
Settings.Default.IgnoreDebugSymbols = chkIgnoreSymbols.Checked;
Settings.Default.IgnoreVsHosting = chkIgnoreVsHost.Checked;
Settings.Default.CopyFiles = chkCopyFiles.Checked;
Settings.Default.CleanUp = chkCleanUp.Checked;
if (Settings.Default.IgnoreFiles == null) Settings.Default.IgnoreFiles = new StringCollection();
Settings.Default.IgnoreFiles.Clear();
foreach (ListViewItem thisItem in lstFiles.Items)
{
if (!thisItem.Checked) Settings.Default.IgnoreFiles.Add(thisItem.Text);
}
}
private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
{
SaveFormSettings();
Settings.Default.Save();
}
#endregion
#region " Commands Events"
private void cmdBuild_Click(Object sender, EventArgs e)
{
Build();
}
private void btnOpenOutputs_Click(object sender, EventArgs e)
{
OpenOutputsFolder();
}
private void btnNew_Click(Object sender, EventArgs e)
{
Settings.Default.Reset();
InitializeFormSettings();
}
private void btnOpen_Click(Object sender, EventArgs e)
{
OpenFileDialog dlg;
if (_openDialog == null)
{
dlg = new OpenFileDialog
{
CheckFileExists = true,
FileName = string.IsNullOrEmpty(FileName) ? DefaultFileName : FileName
};
_openDialog = dlg;
}
else dlg = _openDialog;
dlg.Filter = DialogFilter;
if (dlg.ShowDialog() != DialogResult.OK) return;
FeedBuilderSettingsProvider p = new FeedBuilderSettingsProvider();
p.LoadFrom(dlg.FileName);
FileName = dlg.FileName;
InitializeFormSettings();
}
private void btnSave_Click(Object sender, EventArgs e)
{
Save(false);
}
private void btnSaveAs_Click(Object sender, EventArgs e)
{
Save(true);
}
private void btnRefresh_Click(Object sender, EventArgs e)
{
ReadFiles();
}
#endregion
#region " Options Events"
private void cmdOutputFolder_Click(Object sender, EventArgs e)
{
fbdOutputFolder.SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (fbdOutputFolder.ShowDialog(this) != DialogResult.OK) return;
txtOutputFolder.Text = fbdOutputFolder.SelectedPath;
ReadFiles();
}
private void cmdFeedXML_Click(Object sender, EventArgs e)
{
sfdFeedXML.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (sfdFeedXML.ShowDialog(this) == DialogResult.OK) txtFeedXML.Text = sfdFeedXML.FileName;
}
private void chkIgnoreSymbols_CheckedChanged(object sender, EventArgs e)
{
ReadFiles();
}
private void chkCopyFiles_CheckedChanged(Object sender, EventArgs e)
{
chkCleanUp.Enabled = chkCopyFiles.Checked;
if (!chkCopyFiles.Checked) chkCleanUp.Checked = false;
}
#endregion
#region " Helper Methods "
private void Build()
{
AttachConsole(ATTACH_PARENT_PROCESS);
Console.WriteLine("Building NAppUpdater feed '{0}'", txtBaseURL.Text.Trim());
if (string.IsNullOrEmpty(txtFeedXML.Text))
{
const string msg = "The feed file location needs to be defined.\n" +
"The outputs cannot be generated without this.";
if (_argParser.ShowGui) MessageBox.Show(msg);
Console.WriteLine(msg);
return;
}
// If the target folder doesn't exist, create a path to it
string dest = txtFeedXML.Text.Trim();
var destDir = Directory.GetParent(GetFullDirectoryPath(Path.GetDirectoryName(dest)));
if (!Directory.Exists(destDir.FullName)) Directory.CreateDirectory(destDir.FullName);
XmlDocument doc = new XmlDocument();
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
doc.AppendChild(dec);
XmlElement feed = doc.CreateElement("Feed");
if (!string.IsNullOrEmpty(txtBaseURL.Text.Trim())) feed.SetAttribute("BaseUrl", txtBaseURL.Text.Trim());
doc.AppendChild(feed);
XmlElement tasks = doc.CreateElement("Tasks");
Console.WriteLine("Processing feed items");
int itemsCopied = 0;
int itemsCleaned = 0;
int itemsSkipped = 0;
int itemsFailed = 0;
int itemsMissingConditions = 0;
foreach (ListViewItem thisItem in lstFiles.Items)
{
string destFile = "";
string filename = "";
try
{
filename = thisItem.Text;
destFile = Path.Combine(destDir.FullName, filename);
}
catch
{
}
if (destFile == "" || filename == "")
{
string msg = string.Format("The file could not be pathed:\nFolder:'{0}'\nFile:{1}", destDir.FullName, filename);
if (_argParser.ShowGui) MessageBox.Show(msg);
Console.WriteLine(msg);
continue;
}
if (thisItem.Checked)
{
var fileInfoEx = (FileInfoEx) thisItem.Tag;
XmlElement task = doc.CreateElement("FileUpdateTask");
task.SetAttribute("localPath", fileInfoEx.RelativeName);
// generate FileUpdateTask metadata items
task.SetAttribute("lastModified",
fileInfoEx.FileInfo.LastWriteTime.ToFileTime().ToString(CultureInfo.InvariantCulture));
if (!string.IsNullOrEmpty(txtAddExtension.Text))
{
task.SetAttribute("updateTo", AddExtensionToPath(fileInfoEx.RelativeName, txtAddExtension.Text));
}
task.SetAttribute("fileSize", fileInfoEx.FileInfo.Length.ToString(CultureInfo.InvariantCulture));
if (!string.IsNullOrEmpty(fileInfoEx.FileVersion)) task.SetAttribute("version", fileInfoEx.FileVersion);
XmlElement conds = doc.CreateElement("Conditions");
XmlElement cond;
//File Exists
cond = doc.CreateElement("FileExistsCondition");
cond.SetAttribute("type", "or-not");
conds.AppendChild(cond);
//Version
if (chkVersion.Checked && !string.IsNullOrEmpty(fileInfoEx.FileVersion))
{
cond = doc.CreateElement("FileVersionCondition");
cond.SetAttribute("type", "or");
cond.SetAttribute("what", "below");
cond.SetAttribute("version", fileInfoEx.FileVersion);
conds.AppendChild(cond);
}
//Size
if (chkSize.Checked)
{
cond = doc.CreateElement("FileSizeCondition");
cond.SetAttribute("type", "or-not");
cond.SetAttribute("what", "is");
cond.SetAttribute("size", fileInfoEx.FileInfo.Length.ToString(CultureInfo.InvariantCulture));
conds.AppendChild(cond);
}
//Date
if (chkDate.Checked)
{
cond = doc.CreateElement("FileDateCondition");
cond.SetAttribute("type", "or");
cond.SetAttribute("what", "older");
// local timestamp, not UTC
cond.SetAttribute("timestamp",
fileInfoEx.FileInfo.LastWriteTime.ToFileTime().ToString(CultureInfo.InvariantCulture));
conds.AppendChild(cond);
}
//Hash
if (chkHash.Checked)
{
cond = doc.CreateElement("FileChecksumCondition");
cond.SetAttribute("type", "or-not");
cond.SetAttribute("checksumType", "sha256");
cond.SetAttribute("checksum", fileInfoEx.Hash);
conds.AppendChild(cond);
}
if (conds.ChildNodes.Count == 0) itemsMissingConditions++;
task.AppendChild(conds);
tasks.AppendChild(task);
if (chkCopyFiles.Checked)
{
if (CopyFile(fileInfoEx.FileInfo.FullName, destFile)) itemsCopied++;
else itemsFailed++;
}
}
else
{
try
{
if (chkCleanUp.Checked & File.Exists(destFile))
{
File.Delete(destFile);
itemsCleaned += 1;
}
else itemsSkipped += 1;
}
catch (IOException)
{
itemsFailed += 1;
}
}
}
feed.AppendChild(tasks);
if (chkSign.Checked)
{
try
{
string signature = SignUpdate(doc, txtSignFile.Text);
feed.SetAttribute("RSASignature", signature);
}
catch (Exception)
{
Console.WriteLine("Could not sign the file. Probably the private key file is invalid");
return;
}
}
string xmlDest = Path.Combine(destDir.FullName, Path.GetFileName(dest));
doc.Save(xmlDest);
// open the outputs folder if we're running from the GUI or
// we have an explicit command line option to do so
if (!_argParser.HasArgs || _argParser.OpenOutputsFolder) OpenOutputsFolder();
Console.WriteLine("Done building feed.");
if (itemsCopied > 0) Console.WriteLine("{0,5} items copied", itemsCopied);
if (itemsCleaned > 0) Console.WriteLine("{0,5} items cleaned", itemsCleaned);
if (itemsSkipped > 0) Console.WriteLine("{0,5} items skipped", itemsSkipped);
if (itemsFailed > 0) Console.WriteLine("{0,5} items failed", itemsFailed);
if (itemsMissingConditions > 0) Console.WriteLine("{0,5} items without any conditions", itemsMissingConditions);
}
private string SignUpdate(XmlDocument doc, string pathToSignFile)
{
string keyFileContent = null;
if (string.IsNullOrEmpty(pathToSignFile))
{
throw new Exception("signature file not specified");
}
try
{
using (var file = File.Open(pathToSignFile, FileMode.Open))
{
StreamReader sr = new StreamReader(file);
keyFileContent = sr.ReadToEnd();
}
}
catch (Exception)
{
throw new Exception("Could not open or read file: " + keyFileContent);
}
if (string.IsNullOrEmpty(keyFileContent))
{
throw new Exception("key file was empty");
}
RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
provider.PersistKeyInCsp = false;
try
{
provider.FromXmlString(keyFileContent);
if (provider.PublicOnly)
{
throw new Exception();
}
}
catch (Exception)
{
throw new Exception(
"Could not read signing key. It needs to have an xml format, as required by RSACryptoServiceProvider, and it needs to contain both private and public parts");
}
SHA512Managed sha = new SHA512Managed();
var hash = sha.ComputeHash(Encoding.UTF8.GetBytes(doc.InnerXml));
string signature = Convert.ToBase64String(provider.SignHash(hash, "sha512"));
return signature;
}
private bool CopyFile(string sourceFile, string destFile)
{
// If the target folder doesn't exist, create the path to it
var fi = new FileInfo(destFile);
var d = Directory.GetParent(fi.FullName);
if (!Directory.Exists(d.FullName)) CreateDirectoryPath(d.FullName);
if (!string.IsNullOrEmpty(txtAddExtension.Text))
{
destFile = AddExtensionToPath(destFile, txtAddExtension.Text);
}
// Copy with delayed retry
int retries = 3;
while (retries > 0)
{
try
{
if (File.Exists(destFile)) File.Delete(destFile);
File.Copy(sourceFile, destFile);
retries = 0; // success
return true;
}
catch (IOException)
{
// Failed... let's try sleeping a bit (slow disk maybe)
if (retries-- > 0) Thread.Sleep(200);
}
catch (UnauthorizedAccessException)
{
// same handling as IOException
if (retries-- > 0) Thread.Sleep(200);
}
}
return false;
}
private void CreateDirectoryPath(string directoryPath)
{
// Create the folder/path if it doesn't exist, with delayed retry
int retries = 3;
while (retries > 0 && !Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
if (retries-- < 3) Thread.Sleep(200);
}
}
private void OpenOutputsFolder()
{
string path = txtOutputFolder.Text.Trim();
if (string.IsNullOrEmpty(path))
{
return;
}
string dir = GetFullDirectoryPath(path);
CreateDirectoryPath(dir);
Process process = new Process
{
StartInfo =
{
UseShellExecute = true,
FileName = dir
}
};
process.Start();
}
private int GetImageIndex(string ext)
{
switch (ext.Trim('.'))
{
case "bmp":
return 1;
case "dll":
return 2;
case "doc":
case "docx":
return 3;
case "exe":
return 4;
case "htm":
case "html":
return 5;
case "jpg":
case "jpeg":
return 6;
case "pdf":
return 7;
case "png":
return 8;
case "txt":
return 9;
case "wav":
case "mp3":
return 10;
case "wmv":
return 11;
case "xls":
case "xlsx":
return 12;
case "zip":
return 13;
default:
return 0;
}
}
private void ReadFiles()
{
string outputDir = GetFullDirectoryPath(txtOutputFolder.Text.Trim());
if (string.IsNullOrEmpty(outputDir) || !Directory.Exists(outputDir))
{
return;
}
outputDir = GetFullDirectoryPath(outputDir);
lstFiles.BeginUpdate();
lstFiles.Items.Clear();
FileSystemEnumerator enumerator = new FileSystemEnumerator(outputDir, "*.*", true);
foreach (FileInfo fi in enumerator.Matches())
{
string filePath = fi.FullName;
if ((IsIgnorable(filePath)))
{
continue;
}
FileInfoEx fileInfo = new FileInfoEx(filePath, outputDir.Length);
ListViewItem item = new ListViewItem(fileInfo.RelativeName, GetImageIndex(fileInfo.FileInfo.Extension));
item.SubItems.Add(fileInfo.FileVersion);
item.SubItems.Add(fileInfo.FileInfo.Length.ToString(CultureInfo.InvariantCulture));
item.SubItems.Add(fileInfo.FileInfo.LastWriteTime.ToString(CultureInfo.InvariantCulture));
item.SubItems.Add(fileInfo.Hash);
item.Checked = (!Settings.Default.IgnoreFiles.Contains(fileInfo.RelativeName));
item.Tag = fileInfo;
lstFiles.Items.Add(item);
}
lstFiles.EndUpdate();
}
private string GetFullDirectoryPath(string path)
{
string absolutePath = path;
if (!Path.IsPathRooted(absolutePath))
{
absolutePath = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), path);
}
if (!absolutePath.EndsWith("\\"))
{
absolutePath += "\\";
}
return Path.GetFullPath(absolutePath);
}
private bool IsIgnorable(string filename)
{
string ext = Path.GetExtension(filename);
if ((chkIgnoreSymbols.Checked && ext == ".pdb")) return true;
return (chkIgnoreVsHost.Checked && filename.ToLower().Contains("vshost.exe"));
}
private string AddExtensionToPath(string filePath, string extension)
{
string sanitizedExtension = (extension.Trim().StartsWith(".") ? String.Empty : ".") + extension.Trim();
return filePath + sanitizedExtension;
}
private void Save(bool forceDialog)
{
SaveFormSettings();
if (forceDialog || string.IsNullOrEmpty(FileName))
{
SaveFileDialog dlg = new SaveFileDialog
{
Filter = DialogFilter,
FileName = DefaultFileName
};
DialogResult result = dlg.ShowDialog();
if (result == DialogResult.OK)
{
FeedBuilderSettingsProvider p = new FeedBuilderSettingsProvider();
p.SaveAs(dlg.FileName);
FileName = dlg.FileName;
}
}
else
{
FeedBuilderSettingsProvider p = new FeedBuilderSettingsProvider();
p.SaveAs(FileName);
}
UpdateTitle();
}
#endregion
private void frmMain_DragEnter(object sender, DragEventArgs e)
{
string[] files = (string[]) e.Data.GetData(DataFormats.FileDrop);
if (files.Length == 0) return;
e.Effect = files[0].EndsWith(".config") ? DragDropEffects.Move : DragDropEffects.None;
}
private void frmMain_DragDrop(object sender, DragEventArgs e)
{
string[] files = (string[]) e.Data.GetData(DataFormats.FileDrop);
if (files.Length == 0) return;
try
{
string fileName = files[0];
FeedBuilderSettingsProvider p = new FeedBuilderSettingsProvider();
p.LoadFrom(fileName);
FileName = fileName;
InitializeFormSettings();
}
catch (Exception ex)
{
MessageBox.Show("The file could not be opened: \n" + ex.Message);
}
}
private void helpfulTextBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (openFileDialog1.ShowDialog(this) != DialogResult.OK) return;
txtSignFile.Text = openFileDialog1.FileName;
}
private void chkSign_CheckedChanged(object sender, EventArgs e)
{
lblSignFile.Enabled = chkSign.Checked;
cmdSignFile.Enabled = chkSign.Checked;
txtSignFile.Enabled = chkSign.Checked;
cmdCreateSigFile.Enabled = chkSign.Checked;
if (!chkHash.Checked && chkSign.Checked)
{
chkHash.Checked = true;
}
chkHash.Enabled = !chkSign.Checked;
}
private void cmdCreateSigFile_Click(object sender, EventArgs e)
{
var win = new frmCreateNewSignatureFile();
win.Show();
win.FormClosing += (a, b) => { txtSignFile.Text = win.SelectedPublicKeyPath; };
}
private static readonly int ATTACH_PARENT_PROCESS = -1;
[DllImport("kernel32.dll")]
private static extern bool AttachConsole(int dwProcessId);
[DllImport("kernel32.dll")]
private static extern bool FreeConsole();
}
}
| |
// 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.
using System;
using System.Data;
using System.Configuration;
using System.Xml;
using System.Diagnostics;
using System.Collections.Generic;
using System.Text;
using System.Web;
using WSE = Microsoft.Web.Services3.Security;
using Microsoft.Web.Services3;
using Microsoft.Web.Services3.Design;
using Microsoft.Web.Services3.Security;
using Microsoft.Web.Services3.Security.Tokens;
namespace WebsitePanel.EnterpriseServer
{
public class UsernameAssertion : SecurityPolicyAssertion
{
#region Public properties
private bool signRequest = true;
public bool SignRequest
{
get { return signRequest; }
set { signRequest = value; }
}
private bool encryptRequest = true;
public bool EncryptRequest
{
get { return encryptRequest; }
set { encryptRequest = value; }
}
private int serverId = 0;
public int ServerId
{
get { return serverId; }
set { serverId = value; }
}
private string password;
public string Password
{
get { return password; }
set { password = value; }
}
#endregion
public UsernameAssertion()
{
}
public UsernameAssertion(int serverId, string password)
{
this.serverId = serverId;
this.password = password;
}
public override SoapFilter CreateServiceInputFilter(FilterCreationContext context)
{
return new ServiceInputFilter(this, context);
}
public override SoapFilter CreateServiceOutputFilter(FilterCreationContext context)
{
return null;
}
public override SoapFilter CreateClientInputFilter(FilterCreationContext context)
{
return null;
}
public override SoapFilter CreateClientOutputFilter(FilterCreationContext context)
{
return new ClientOutputFilter(this, context);
}
public override void ReadXml(XmlReader reader, IDictionary<string, Type> extensions)
{
if (reader == null)
throw new ArgumentNullException("reader");
if (extensions == null)
throw new ArgumentNullException("extensions");
// find the current extension
string tagName = null;
foreach (string extName in extensions.Keys)
{
if (extensions[extName] == typeof(UsernameAssertion))
{
tagName = extName;
break;
}
}
// read the first element (maybe empty)
reader.ReadStartElement(tagName);
}
public override void WriteXml(XmlWriter writer)
{
// Typically this is not needed for custom policies
}
#region ServiceInputFilter
public class ServiceInputFilter : ReceiveSecurityFilter
{
UsernameAssertion parentAssertion;
FilterCreationContext filterContext;
public ServiceInputFilter(UsernameAssertion parentAssertion, FilterCreationContext filterContext)
: base(parentAssertion.ServiceActor, false, parentAssertion.ClientActor)
{
this.parentAssertion = parentAssertion;
this.filterContext = filterContext;
}
public override void ValidateMessageSecurity(SoapEnvelope envelope, WSE.Security security)
{
if (security != null)
ProcessWSERequest(envelope, security);
//else if (envelope.Header != null)
// ProcessSoapRequest(envelope);
else// if (HttpContext.Current.Request.Headers["Authorization"] != null)
ProcessBasicAuthRequest();
}
private void ProcessBasicAuthRequest()
{
string authStr = HttpContext.Current.Request.Headers["Authorization"];
if (authStr == null || authStr.Length == 0)
{
// No credentials; anonymous request
DenyAccess();
return;
}
authStr = authStr.Trim();
if (authStr.IndexOf("Basic", 0) != 0)
{
// Don't understand this header...we'll pass it along and
// assume someone else will handle it
DenyAccess();
return;
}
string encodedCredentials = authStr.Substring(6);
byte[] decodedBytes = Convert.FromBase64String(encodedCredentials);
string s = new ASCIIEncoding().GetString(decodedBytes);
string[] userPass = s.Split(new char[] { ':' });
string username = userPass[0];
string password = userPass[1];
UserInfo user = UserController.GetUserByUsernamePassword(
username, password, System.Web.HttpContext.Current.Request.UserHostAddress);
if (user == null)
{
// Invalid credentials; deny access
DenyAccess();
return;
//throw new Exception("Wrong BASIC credentials have been supplied");
}
SecurityContext.SetThreadPrincipal(user);
}
private void DenyAccess()
{
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.StatusCode = 401;
response.StatusDescription = "Access Denied";
response.Write("401 Access Denied");
string realm = "WebsitePanel Enterprise Server";
string val = String.Format("Basic Realm=\"{0}\"", realm);
response.AppendHeader("WWW-Authenticate", val);
response.End();
}
private void ProcessSoapRequest(SoapEnvelope envelope)
{
XmlNode authNode = envelope.Header.SelectSingleNode("Authentication");
if (authNode == null)
throw new Exception("Couldn't find authentication token specified");
XmlNode userNode = authNode.SelectSingleNode("Username");
XmlNode passwordNode = authNode.SelectSingleNode("Password");
if (userNode == null || passwordNode == null)
throw new Exception("Authentication token is invalid or broken");
UserInfo user = UserController.GetUserByUsernamePassword(
userNode.InnerText,
passwordNode.InnerText,
System.Web.HttpContext.Current.Request.UserHostAddress
);
if (user == null)
throw new Exception("Authentication token is invalid or broken");
SecurityContext.SetThreadPrincipal(user);
}
private void ProcessWSERequest(SoapEnvelope envelope, WSE.Security security)
{
// by default we consider that SOAP messages is not signed
bool IsSigned = false;
// if security element is null
// the call is made not from WSE-enabled client
if (security != null)
{
foreach (ISecurityElement element in security.Elements)
{
if (element is MessageSignature)
{
// The given context contains a Signature element.
MessageSignature sign = element as MessageSignature;
if (CheckSignature(envelope, security, sign))
{
// The SOAP message is signed.
if (sign.SigningToken is UsernameToken)
{
UsernameToken token = sign.SigningToken as UsernameToken;
// The SOAP message is signed
// with a UsernameToken.
IsSigned = true;
}
}
}
}
}
// throw an exception if the message did not pass all the tests
if (!IsSigned)
throw new SecurityFault("SOAP response should be signed.");
// check encryption
bool IsEncrypted = false;
foreach (ISecurityElement element in security.Elements)
{
if (element is EncryptedData)
{
EncryptedData encryptedData = element as EncryptedData;
System.Xml.XmlElement targetElement = encryptedData.TargetElement;
if (SoapHelper.IsBodyElement(targetElement))
{
// The given SOAP message has the Body element Encrypted.
IsEncrypted = true;
}
}
}
if (!IsEncrypted)
throw new SecurityFault("SOAP response should be encrypted.");
}
private bool CheckSignature(SoapEnvelope envelope, WSE.Security security, MessageSignature signature)
{
//
// Now verify which parts of the message were actually signed.
//
SignatureOptions actualOptions = signature.SignatureOptions;
SignatureOptions expectedOptions = SignatureOptions.IncludeSoapBody;
if (security != null && security.Timestamp != null)
expectedOptions |= SignatureOptions.IncludeTimestamp;
//
// The <Action> and <To> are required addressing elements.
//
expectedOptions |= SignatureOptions.IncludeAction;
expectedOptions |= SignatureOptions.IncludeTo;
if (envelope.Context.Addressing.FaultTo != null && envelope.Context.Addressing.FaultTo.TargetElement != null)
expectedOptions |= SignatureOptions.IncludeFaultTo;
if (envelope.Context.Addressing.From != null && envelope.Context.Addressing.From.TargetElement != null)
expectedOptions |= SignatureOptions.IncludeFrom;
if (envelope.Context.Addressing.MessageID != null && envelope.Context.Addressing.MessageID.TargetElement != null)
expectedOptions |= SignatureOptions.IncludeMessageId;
if (envelope.Context.Addressing.RelatesTo != null && envelope.Context.Addressing.RelatesTo.TargetElement != null)
expectedOptions |= SignatureOptions.IncludeRelatesTo;
if (envelope.Context.Addressing.ReplyTo != null && envelope.Context.Addressing.ReplyTo.TargetElement != null)
expectedOptions |= SignatureOptions.IncludeReplyTo;
//
// Check if the all the expected options are the present.
//
return ((expectedOptions & actualOptions) == expectedOptions);
}
}
#endregion
#region ClientOutputFilter
public class ClientOutputFilter : SendSecurityFilter
{
UsernameAssertion parentAssertion;
FilterCreationContext filterContext;
public ClientOutputFilter(UsernameAssertion parentAssertion, FilterCreationContext filterContext)
: base(parentAssertion.ServiceActor, false, parentAssertion.ClientActor)
{
this.parentAssertion = parentAssertion;
this.filterContext = filterContext;
}
public override void SecureMessage(SoapEnvelope envelope, WSE.Security security)
{
// get server password from database
string password = parentAssertion.Password;
if (password == null)
return;
// hash password
password = CryptoUtils.SHA1(password);
// create username token
UsernameToken userToken = new UsernameToken(parentAssertion.ServerId.ToString(), password,
PasswordOption.SendNone);
if (parentAssertion.signRequest || parentAssertion.encryptRequest)
{
// Add the token to the SOAP header.
security.Tokens.Add(userToken);
}
if (parentAssertion.signRequest)
{
// Sign the SOAP message by using the UsernameToken.
MessageSignature sig = new MessageSignature(userToken);
security.Elements.Add(sig);
}
if (parentAssertion.encryptRequest)
{
// we don't return any custom SOAP headers
// so, just encrypt a message Body
EncryptedData data = new EncryptedData(userToken);
// encrypt custom headers
for (int index = 0; index < envelope.Header.ChildNodes.Count; index++)
{
XmlElement child = envelope.Header.ChildNodes[index] as XmlElement;
// find all SecureSoapHeader headers marked with a special attribute
if (child != null && child.NamespaceURI == "http://com/websitepanel/server/")
{
// create ID attribute for referencing purposes
string id = Guid.NewGuid().ToString();
child.SetAttribute("Id", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", id);
// Create an encryption reference for the custom SOAP header.
data.AddReference(new EncryptionReference("#" + id));
}
}
security.Elements.Add(data);
}
}
}
#endregion
}
}
| |
using UnityEngine;
using UnityEngine.Rendering;
namespace UnityStandardAssets.CinematicEffects
{
[ExecuteInEditMode]
[RequireComponent(typeof(Camera))]
[AddComponentMenu("Image Effects/Cinematic/Ambient Occlusion")]
#if UNITY_5_4_OR_NEWER
[ImageEffectAllowedInSceneView]
#endif
public partial class AmbientOcclusion : MonoBehaviour
{
#region Public Properties
/// Effect settings.
[SerializeField]
public Settings settings = Settings.defaultSettings;
/// Checks if the ambient-only mode is supported under the current settings.
public bool isAmbientOnlySupported
{
get { return targetCamera.hdr && occlusionSource == OcclusionSource.GBuffer; }
}
/// Checks if the G-buffer is available
public bool isGBufferAvailable
{
get { return targetCamera.actualRenderingPath == RenderingPath.DeferredShading; }
}
#endregion
#region Private Properties
// Properties referring to the current settings
float intensity
{
get { return settings.intensity; }
}
float radius
{
get { return Mathf.Max(settings.radius, 1e-4f); }
}
SampleCount sampleCount
{
get { return settings.sampleCount; }
}
int sampleCountValue
{
get
{
switch (settings.sampleCount)
{
case SampleCount.Lowest: return 3;
case SampleCount.Low: return 6;
case SampleCount.Medium: return 12;
case SampleCount.High: return 20;
}
return Mathf.Clamp(settings.sampleCountValue, 1, 256);
}
}
OcclusionSource occlusionSource
{
get
{
if (settings.occlusionSource == OcclusionSource.GBuffer && !isGBufferAvailable)
// An unavailable source was chosen: fallback to DepthNormalsTexture.
return OcclusionSource.DepthNormalsTexture;
else
return settings.occlusionSource;
}
}
bool downsampling
{
get { return settings.downsampling; }
}
bool ambientOnly
{
get { return settings.ambientOnly && !settings.debug && isAmbientOnlySupported; }
}
// Texture format used for storing AO
RenderTextureFormat aoTextureFormat
{
get
{
if (SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.R8))
return RenderTextureFormat.R8;
else
return RenderTextureFormat.Default;
}
}
// AO shader
Shader aoShader
{
get
{
if (_aoShader == null)
_aoShader = Shader.Find("Hidden/Image Effects/Cinematic/AmbientOcclusion");
return _aoShader;
}
}
[SerializeField] Shader _aoShader;
// Temporary aterial for the AO shader
Material aoMaterial
{
get
{
if (_aoMaterial == null)
_aoMaterial = ImageEffectHelper.CheckShaderAndCreateMaterial(aoShader);
return _aoMaterial;
}
}
Material _aoMaterial;
// Command buffer for the AO pass
CommandBuffer aoCommands
{
get
{
if (_aoCommands == null)
{
_aoCommands = new CommandBuffer();
_aoCommands.name = "AmbientOcclusion";
}
return _aoCommands;
}
}
CommandBuffer _aoCommands;
// Target camera
Camera targetCamera
{
get { return GetComponent<Camera>(); }
}
// Property observer
PropertyObserver propertyObserver { get; set; }
// Reference to the quad mesh in the built-in assets
// (used in MRT blitting)
Mesh quadMesh
{
get { return _quadMesh; }
}
[SerializeField] Mesh _quadMesh;
#endregion
#region Effect Passes
// Build commands for the AO pass (used in the ambient-only mode).
void BuildAOCommands()
{
var cb = aoCommands;
var tw = targetCamera.pixelWidth;
var th = targetCamera.pixelHeight;
var ts = downsampling ? 2 : 1;
var format = aoTextureFormat;
var rwMode = RenderTextureReadWrite.Linear;
var filter = FilterMode.Bilinear;
// AO buffer
var m = aoMaterial;
var rtMask = Shader.PropertyToID("_OcclusionTexture");
cb.GetTemporaryRT(rtMask, tw / ts, th / ts, 0, filter, format, rwMode);
// AO estimation
cb.Blit((Texture)null, rtMask, m, 2);
// Blur buffer
var rtBlur = Shader.PropertyToID("_OcclusionBlurTexture");
// Primary blur filter (large kernel)
cb.GetTemporaryRT(rtBlur, tw, th, 0, filter, format, rwMode);
cb.SetGlobalVector("_BlurVector", Vector2.right * 2);
cb.Blit(rtMask, rtBlur, m, 4);
cb.ReleaseTemporaryRT(rtMask);
cb.GetTemporaryRT(rtMask, tw, th, 0, filter, format, rwMode);
cb.SetGlobalVector("_BlurVector", Vector2.up * 2 * ts);
cb.Blit(rtBlur, rtMask, m, 4);
cb.ReleaseTemporaryRT(rtBlur);
// Secondary blur filter (small kernel)
cb.GetTemporaryRT(rtBlur, tw, th, 0, filter, format, rwMode);
cb.SetGlobalVector("_BlurVector", Vector2.right * ts);
cb.Blit(rtMask, rtBlur, m, 6);
cb.ReleaseTemporaryRT(rtMask);
cb.GetTemporaryRT(rtMask, tw, th, 0, filter, format, rwMode);
cb.SetGlobalVector("_BlurVector", Vector2.up * ts);
cb.Blit(rtBlur, rtMask, m, 6);
cb.ReleaseTemporaryRT(rtBlur);
// Combine AO to the G-buffer.
var mrt = new RenderTargetIdentifier[] {
BuiltinRenderTextureType.GBuffer0, // Albedo, Occ
BuiltinRenderTextureType.CameraTarget // Ambient
};
cb.SetRenderTarget(mrt, BuiltinRenderTextureType.CameraTarget);
cb.SetGlobalTexture("_OcclusionTexture", rtMask);
cb.DrawMesh(quadMesh, Matrix4x4.identity, m, 0, 8);
cb.ReleaseTemporaryRT(rtMask);
}
// Execute the AO pass immediately (used in the forward mode).
void ExecuteAOPass(RenderTexture source, RenderTexture destination)
{
var tw = source.width;
var th = source.height;
var ts = downsampling ? 2 : 1;
var format = aoTextureFormat;
var rwMode = RenderTextureReadWrite.Linear;
var useGBuffer = settings.occlusionSource == OcclusionSource.GBuffer;
// AO buffer
var m = aoMaterial;
var rtMask = RenderTexture.GetTemporary(tw / ts, th / ts, 0, format, rwMode);
// AO estimation
Graphics.Blit(source, rtMask, m, (int)occlusionSource);
// Primary blur filter (large kernel)
var rtBlur = RenderTexture.GetTemporary(tw, th, 0, format, rwMode);
m.SetVector("_BlurVector", Vector2.right * 2);
Graphics.Blit(rtMask, rtBlur, m, useGBuffer ? 4 : 3);
RenderTexture.ReleaseTemporary(rtMask);
rtMask = RenderTexture.GetTemporary(tw, th, 0, format, rwMode);
m.SetVector("_BlurVector", Vector2.up * 2 * ts);
Graphics.Blit(rtBlur, rtMask, m, useGBuffer ? 4 : 3);
RenderTexture.ReleaseTemporary(rtBlur);
// Secondary blur filter (small kernel)
rtBlur = RenderTexture.GetTemporary(tw, th, 0, format, rwMode);
m.SetVector("_BlurVector", Vector2.right * ts);
Graphics.Blit(rtMask, rtBlur, m, useGBuffer ? 6 : 5);
RenderTexture.ReleaseTemporary(rtMask);
rtMask = RenderTexture.GetTemporary(tw, th, 0, format, rwMode);
m.SetVector("_BlurVector", Vector2.up * ts);
Graphics.Blit(rtBlur, rtMask, m, useGBuffer ? 6 : 5);
RenderTexture.ReleaseTemporary(rtBlur);
// Combine AO with the source.
m.SetTexture("_OcclusionTexture", rtMask);
if (!settings.debug)
Graphics.Blit(source, destination, m, 7);
else
Graphics.Blit(source, destination, m, 9);
RenderTexture.ReleaseTemporary(rtMask);
}
// Update the common material properties.
void UpdateMaterialProperties()
{
var m = aoMaterial;
m.SetFloat("_Intensity", intensity);
m.SetFloat("_Radius", radius);
m.SetFloat("_TargetScale", downsampling ? 0.5f : 1);
m.SetInt("_SampleCount", sampleCountValue);
}
#endregion
#region MonoBehaviour Functions
void OnEnable()
{
// Check if the shader is supported in the current platform.
if (!ImageEffectHelper.IsSupported(aoShader, true, false, this))
{
enabled = false;
return;
}
// Register the command buffer if in the ambient-only mode.
if (ambientOnly)
targetCamera.AddCommandBuffer(CameraEvent.BeforeReflections, aoCommands);
// Enable depth textures which the occlusion source requires.
if (occlusionSource == OcclusionSource.DepthTexture)
targetCamera.depthTextureMode |= DepthTextureMode.Depth;
if (occlusionSource != OcclusionSource.GBuffer)
targetCamera.depthTextureMode |= DepthTextureMode.DepthNormals;
}
void OnDisable()
{
// Destroy all the temporary resources.
if (_aoMaterial != null) DestroyImmediate(_aoMaterial);
_aoMaterial = null;
if (_aoCommands != null)
targetCamera.RemoveCommandBuffer(CameraEvent.BeforeReflections, _aoCommands);
_aoCommands = null;
}
void Update()
{
if (propertyObserver.CheckNeedsReset(settings, targetCamera))
{
// Reinitialize all the resources by disabling/enabling itself.
// This is not very efficient way but just works...
OnDisable();
OnEnable();
// Build the command buffer if in the ambient-only mode.
if (ambientOnly)
{
aoCommands.Clear();
BuildAOCommands();
}
propertyObserver.Update(settings, targetCamera);
}
// Update the material properties (later used in the AO commands).
if (ambientOnly) UpdateMaterialProperties();
}
[ImageEffectOpaque]
void OnRenderImage(RenderTexture source, RenderTexture destination)
{
if (ambientOnly)
{
// Do nothing in the ambient-only mode.
Graphics.Blit(source, destination);
}
else
{
// Execute the AO pass.
UpdateMaterialProperties();
ExecuteAOPass(source, destination);
}
}
#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.
/*
** Copyright (c) Microsoft. All rights reserved.
** Licensed under the MIT license.
** See LICENSE file in the project root for full license information.
**
** This program was translated to C# and adapted for xunit-performance.
** New variants of several tests were added to compare class versus
** struct and to compare jagged arrays vs multi-dimensional arrays.
*/
/*
** BYTEmark (tm)
** BYTE Magazine's Native Mode benchmarks
** Rick Grehan, BYTE Magazine
**
** Create:
** Revision: 3/95
**
** DISCLAIMER
** The source, executable, and documentation files that comprise
** the BYTEmark benchmarks are made available on an "as is" basis.
** This means that we at BYTE Magazine have made every reasonable
** effort to verify that the there are no errors in the source and
** executable code. We cannot, however, guarantee that the programs
** are error-free. Consequently, McGraw-HIll and BYTE Magazine make
** no claims in regard to the fitness of the source code, executable
** code, and documentation of the BYTEmark.
**
** Furthermore, BYTE Magazine, McGraw-Hill, and all employees
** of McGraw-Hill cannot be held responsible for any damages resulting
** from the use of this code or the results obtained from using
** this code.
**
*/
using System;
using System.Text;
/********************
** STRING HEAPSORT **
********************/
/*****************
** DoStringSort **
******************
** This routine performs the CPU string sort test.
** Arguments:
** requested_secs = # of seconds to execute test
** stringspersec = # of strings per second sorted (RETURNED)
*/
internal static class StringOrdinalComparer
{
public static int Compare(String left, String right)
{
return String.CompareOrdinal(left, right);
}
}
public class StringSort : StringSortStruct
{
public override string Name()
{
return "STRING SORT";
}
public override double Run()
{
string[][] arraybase; /* Base pointers of array */
long accumtime; /* Accumulated time */
double iterations; /* Iteration counter */
/*
** See if we need to do self adjustment code.
*/
if (this.adjust == 0)
{
/*
** Self-adjustment code. The system begins by sorting 1
** array. If it does that in no time, then two arrays
** are built and sorted. This process continues until
** enough arrays are built to handle the tolerance.
*/
this.numarrays = 1;
while (true)
{
/*
** Allocate space for arrays
*/
arraybase = new string[this.numarrays][];
for (int i = 0; i < this.numarrays; i++)
arraybase[i] = new string[this.arraysize];
/*
** Do an iteration of the string sort. If the
** elapsed time is less than or equal to the permitted
** minimum, then allocate for more arrays and
** try again.
*/
if (DoStringSortIteration(arraybase,
this.numarrays,
this.arraysize) > global.min_ticks)
break; /* We're ok...exit */
if (this.numarrays++ > global.NUMSTRARRAYS)
{
throw new Exception("CPU:SSORT -- NUMSTRARRAYS hit.");
}
}
}
else
{
/*
** Allocate space for arrays
*/
arraybase = new string[this.numarrays][];
for (int i = 0; i < this.numarrays; i++)
arraybase[i] = new string[this.arraysize];
}
/*
** All's well if we get here. Repeatedly perform sorts until the
** accumulated elapsed time is greater than # of seconds requested.
*/
accumtime = 0L;
iterations = (double)0.0;
do
{
accumtime += DoStringSortIteration(arraybase,
this.numarrays,
this.arraysize);
iterations += (double)this.numarrays;
} while (ByteMark.TicksToSecs(accumtime) < this.request_secs);
if (this.adjust == 0)
this.adjust = 1;
/*
** Clean up, calculate results, and go home.
** Set flag to show we don't need to rerun adjustment code.
*/
return (iterations * (double)this.numarrays / ByteMark.TicksToFracSecs(accumtime));
}
/**************************
** DoStringSortIteration **
***************************
** This routine executes one iteration of the string
** sort benchmark. It returns the number of ticks
** Note that this routine also builds the offset pointer
** array.
*/
private static int DoStringSortIteration(string[][] arraybase, int numarrays, int arraysize)
{
long elapsed; /* Elapsed ticks */
int i;
/*
** Load up the array(s) with random numbers
*/
LoadStringArray(arraybase, arraysize, numarrays);
/*
** Start the stopwatch
*/
elapsed = ByteMark.StartStopwatch();
/*
** Execute heapsorts
*/
for (i = 0; i < numarrays; i++)
{
// StrHeapSort(tempobase,tempsbase,nstrings,0L,nstrings-1);
StrHeapSort(arraybase[i], 0, arraysize - 1);
}
/*
** Record elapsed time
*/
elapsed = ByteMark.StopStopwatch(elapsed);
#if DEBUG
for (i = 0; i < arraysize - 1; i++)
{
/*
** Compare strings to check for proper
** sort.
*/
if (StringOrdinalComparer.Compare(arraybase[0][i + 1], arraybase[0][i]) < 0)
{
Console.Write("Error in StringSort! arraybase[0][{0}]='{1}', arraybase[0][{2}]='{3}\n", i, arraybase[0][i], i + 1, arraybase[0][i + 1]);
break;
}
}
#endif
return ((int)elapsed);
}
/********************
** LoadStringArray **
*********************
** Initialize the string array with random strings of
** varying sizes.
** Returns the pointer to the offset pointer array.
** Note that since we're creating a number of arrays, this
** routine builds one array, then copies it into the others.
*/
private static void LoadStringArray(string[][] array, /* String array */
int arraysize, /* Size of array */
int numarrays) /* # of arrays */
{
/*
** Initialize random number generator.
*/
ByteMark.randnum(13);
/*
** Load up the first array with randoms
*/
int i;
for (i = 0; i < arraysize; i++)
{
int length;
length = 4 + ByteMark.abs_randwc(76);
array[0][i] = "";
/*
** Fill up the string with random bytes.
*/
StringBuilder builder = new StringBuilder(length);
int add;
for (add = 0; add < length; add++)
{
char myChar = (char)(ByteMark.abs_randwc(96) + 32);
builder.Append(myChar);
}
array[0][i] = builder.ToString();
}
/*
** We now have initialized a single full array. If there
** is more than one array, copy the original into the
** others.
*/
int k;
for (k = 1; k < numarrays; k++)
{
for (i = 0; i < arraysize; i++)
{
array[k][i] = array[0][i];
}
}
}
/****************
** strheapsort **
*****************
** Pass this routine a pointer to an array of unsigned char.
** The array is presumed to hold strings occupying at most
** 80 bytes (counts a byte count).
** This routine also needs a pointer to an array of offsets
** which represent string locations in the array, and
** an unsigned long indicating the number of strings
** in the array.
*/
private static void StrHeapSort(string[] array,
int bottom, /* lower bound */
int top) /* upper bound */
{
int i;
string temp;
/*
** Build a heap in the array
*/
for (i = (top / 2); i > 0; --i)
strsift(array, i, top);
/*
** Repeatedly extract maximum from heap and place it at the
** end of the array. When we get done, we'll have a sorted
** array.
*/
for (i = top; i > 0; --i)
{
strsift(array, bottom, i);
temp = array[0];
array[0] = array[i]; /* perform exchange */
array[i] = temp;
}
return;
}
/************
** strsift **
*************
** Pass this function:
** 1) A pointer to an array of offset pointers
** 2) A pointer to a string array
** 3) The number of elements in the string array
** 4) Offset within which to sort.
** Sift the array within the bounds of those offsets (thus
** building a heap).
*/
private static void strsift(string[] array,
int i,
int j)
{
int k;
string temp;
while ((i + i) <= j)
{
k = i + i;
if (k < j)
{
//array[k].CompareTo(array[k+1]);
if (StringOrdinalComparer.Compare(array[k], array[k + 1]) < 0)
++k;
}
//if(array[i]<array[k])
if (StringOrdinalComparer.Compare(array[i], array[k]) < 0)
{
temp = array[k];
array[k] = array[i];
array[i] = temp;
i = k;
}
else
i = j + 1;
}
return;
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the lambda-2014-11-11.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Lambda.Model
{
/// <summary>
/// Describes mapping between an Amazon Kinesis stream and a Lambda function.
/// </summary>
public partial class EventSourceConfiguration
{
private int? _batchSize;
private string _eventSource;
private string _functionName;
private bool? _isActive;
private string _lastModified;
private Dictionary<string, string> _parameters = new Dictionary<string, string>();
private string _role;
private string _status;
private string _uuid;
/// <summary>
/// Gets and sets the property BatchSize.
/// <para>
/// The largest number of records that AWS Lambda will POST in the invocation request
/// to your function.
/// </para>
/// </summary>
public int BatchSize
{
get { return this._batchSize.GetValueOrDefault(); }
set { this._batchSize = value; }
}
// Check to see if BatchSize property is set
internal bool IsSetBatchSize()
{
return this._batchSize.HasValue;
}
/// <summary>
/// Gets and sets the property EventSource.
/// <para>
/// The Amazon Resource Name (ARN) of the Amazon Kinesis stream that is the source of
/// events.
/// </para>
/// </summary>
public string EventSource
{
get { return this._eventSource; }
set { this._eventSource = value; }
}
// Check to see if EventSource property is set
internal bool IsSetEventSource()
{
return this._eventSource != null;
}
/// <summary>
/// Gets and sets the property FunctionName.
/// <para>
/// The Lambda function to invoke when AWS Lambda detects an event on the stream.
/// </para>
/// </summary>
public string FunctionName
{
get { return this._functionName; }
set { this._functionName = value; }
}
// Check to see if FunctionName property is set
internal bool IsSetFunctionName()
{
return this._functionName != null;
}
/// <summary>
/// Gets and sets the property IsActive.
/// <para>
/// Indicates whether the event source mapping is currently honored. Events are only processes
/// if IsActive is true.
/// </para>
/// </summary>
public bool IsActive
{
get { return this._isActive.GetValueOrDefault(); }
set { this._isActive = value; }
}
// Check to see if IsActive property is set
internal bool IsSetIsActive()
{
return this._isActive.HasValue;
}
/// <summary>
/// Gets and sets the property LastModified.
/// <para>
/// The UTC time string indicating the last time the event mapping was updated.
/// </para>
/// </summary>
public string LastModified
{
get { return this._lastModified; }
set { this._lastModified = value; }
}
// Check to see if LastModified property is set
internal bool IsSetLastModified()
{
return this._lastModified != null;
}
/// <summary>
/// Gets and sets the property Parameters.
/// <para>
/// The map (key-value pairs) defining the configuration for AWS Lambda to use when reading
/// the event source.
/// </para>
/// </summary>
public Dictionary<string, string> Parameters
{
get { return this._parameters; }
set { this._parameters = value; }
}
// Check to see if Parameters property is set
internal bool IsSetParameters()
{
return this._parameters != null && this._parameters.Count > 0;
}
/// <summary>
/// Gets and sets the property Role.
/// <para>
/// The ARN of the IAM role (invocation role) that AWS Lambda can assume to read from
/// the stream and invoke the function.
/// </para>
/// </summary>
public string Role
{
get { return this._role; }
set { this._role = value; }
}
// Check to see if Role property is set
internal bool IsSetRole()
{
return this._role != null;
}
/// <summary>
/// Gets and sets the property Status.
/// <para>
/// The description of the health of the event source mapping. Valid values are: "PENDING",
/// "OK", and "PROBLEM:<i>message</i>". Initially this staus is "PENDING". When AWS Lambda
/// begins processing events, it changes the status to "OK".
/// </para>
/// </summary>
public string Status
{
get { return this._status; }
set { this._status = value; }
}
// Check to see if Status property is set
internal bool IsSetStatus()
{
return this._status != null;
}
/// <summary>
/// Gets and sets the property UUID.
/// <para>
/// The AWS Lambda assigned opaque identifier for the mapping.
/// </para>
/// </summary>
public string UUID
{
get { return this._uuid; }
set { this._uuid = value; }
}
// Check to see if UUID property is set
internal bool IsSetUUID()
{
return this._uuid != null;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Examples
{
using System;
using System.Linq;
using Apache.Ignite.Core;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Affinity;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.Linq;
/// <summary>
/// This example populates cache with sample data and runs several LINQ queries over this data.
/// </summary>
public class LinqExample
{
/// <summary>Organization cache name.</summary>
private const string OrganizationCacheName = "dotnet_cache_query_organization";
/// <summary>Employee cache name.</summary>
private const string EmployeeCacheName = "dotnet_cache_query_employee";
/// <summary>Colocated employee cache name.</summary>
private const string EmployeeCacheNameColocated = "dotnet_cache_query_employee_colocated";
[STAThread]
public static void Run()
{
var ignite = Ignition.TryGetIgnite() ?? Ignition.StartFromApplicationConfiguration();
Console.WriteLine();
Console.WriteLine(">>> Cache LINQ example started.");
var employeeCache = ignite.GetOrCreateCache<int, Employee>(
new CacheConfiguration(EmployeeCacheName, typeof(Employee)));
var employeeCacheColocated = ignite.GetOrCreateCache<AffinityKey, Employee>(
new CacheConfiguration(EmployeeCacheNameColocated, typeof(Employee)));
var organizationCache = ignite.GetOrCreateCache<int, Organization>(
new CacheConfiguration(OrganizationCacheName, new QueryEntity(typeof(int), typeof(Organization))));
// Populate cache with sample data entries.
PopulateCache(employeeCache);
PopulateCache(employeeCacheColocated);
PopulateCache(organizationCache);
// Run SQL query example.
QueryExample(employeeCache);
// Run compiled SQL query example.
CompiledQueryExample(employeeCache);
// Run SQL query with join example.
JoinQueryExample(employeeCacheColocated, organizationCache);
// Run SQL query with distributed join example.
DistributedJoinQueryExample(employeeCache, organizationCache);
// Run SQL fields query example.
FieldsQueryExample(employeeCache);
}
/// <summary>
/// Queries employees that have specific salary.
/// </summary>
/// <param name="cache">Cache.</param>
private static void QueryExample(ICache<int, Employee> cache)
{
const int minSalary = 10000;
var qry = cache.AsCacheQueryable().Where(emp => emp.Value.Salary > minSalary);
Console.WriteLine();
Console.WriteLine($">>> Employees with salary > {minSalary}:");
foreach (var entry in qry)
Console.WriteLine(">>> " + entry.Value);
Console.WriteLine();
Console.WriteLine(">>> Generated SQL: " + qry.ToCacheQueryable().GetFieldsQuery().Sql);
}
/// <summary>
/// Queries employees that have specific salary with a compiled query.
/// </summary>
/// <param name="cache">Cache.</param>
private static void CompiledQueryExample(ICache<int, Employee> cache)
{
const int minSalary = 10000;
var cache0 = cache.AsCacheQueryable();
// Compile cache query to eliminate LINQ overhead on multiple runs.
Func<int, IQueryCursor<ICacheEntry<int, Employee>>> qry =
CompiledQuery.Compile((int ms) => cache0.Where(emp => emp.Value.Salary > ms));
Console.WriteLine();
Console.WriteLine($">>> Employees with salary > {minSalary} using compiled query:");
foreach (var entry in qry(minSalary))
Console.WriteLine(">>> " + entry.Value);
}
/// <summary>
/// Queries employees that work for organization with provided name.
/// </summary>
/// <param name="employeeCache">Employee cache.</param>
/// <param name="organizationCache">Organization cache.</param>
private static void JoinQueryExample(ICache<AffinityKey, Employee> employeeCache,
ICache<int, Organization> organizationCache)
{
const string orgName = "Apache";
var employees = employeeCache.AsCacheQueryable();
var organizations = organizationCache.AsCacheQueryable();
var qry =
from employee in employees
from organization in organizations
where employee.Value.OrganizationId == organization.Key && organization.Value.Name == orgName
select employee;
Console.WriteLine();
Console.WriteLine(">>> Employees working for " + orgName + ":");
foreach (var entry in qry)
Console.WriteLine(">>> " + entry.Value);
Console.WriteLine();
Console.WriteLine(">>> Generated SQL: " + qry.ToCacheQueryable().GetFieldsQuery().Sql);
}
/// <summary>
/// Queries employees that work for organization with provided name.
/// </summary>
/// <param name="employeeCache">Employee cache.</param>
/// <param name="organizationCache">Organization cache.</param>
private static void DistributedJoinQueryExample(ICache<int, Employee> employeeCache,
ICache<int, Organization> organizationCache)
{
const string orgName = "Apache";
var queryOptions = new QueryOptions {EnableDistributedJoins = true};
var employees = employeeCache.AsCacheQueryable(queryOptions);
var organizations = organizationCache.AsCacheQueryable(queryOptions);
var qry =
from employee in employees
from organization in organizations
where employee.Value.OrganizationId == organization.Key && organization.Value.Name == orgName
select employee;
Console.WriteLine();
Console.WriteLine(">>> Employees working for " + orgName + " (distributed joins):");
foreach (var entry in qry)
Console.WriteLine(">>> " + entry.Value);
}
/// <summary>
/// Queries names and salaries for all employees.
/// </summary>
/// <param name="cache">Cache.</param>
private static void FieldsQueryExample(ICache<int, Employee> cache)
{
var qry = cache.AsCacheQueryable().Select(entry => new {entry.Value.Name, entry.Value.Salary});
Console.WriteLine();
Console.WriteLine(">>> Employee names and their salaries:");
foreach (var row in qry)
Console.WriteLine(">>> [Name=" + row.Name + ", salary=" + row.Salary + ']');
Console.WriteLine();
Console.WriteLine(">>> Generated SQL: " + qry.ToCacheQueryable().GetFieldsQuery().Sql);
}
/// <summary>
/// Populate cache with data for this example.
/// </summary>
/// <param name="cache">Cache.</param>
private static void PopulateCache(ICache<int, Organization> cache)
{
cache.Put(1, new Organization("Apache"));
cache.Put(2, new Organization("Microsoft"));
}
/// <summary>
/// Populate cache with data for this example.
/// </summary>
/// <param name="cache">Cache.</param>
private static void PopulateCache(ICache<AffinityKey, Employee> cache)
{
cache.Put(new AffinityKey(1, 1), new Employee("James Wilson", 12500, 1));
cache.Put(new AffinityKey(2, 1), new Employee("Daniel Adams", 11000, 1));
cache.Put(new AffinityKey(3, 1), new Employee("Cristian Moss", 12500, 1));
cache.Put(new AffinityKey(4, 2), new Employee("Allison Mathis", 25300, 2));
cache.Put(new AffinityKey(5, 2), new Employee("Breana Robbin", 6500, 2));
cache.Put(new AffinityKey(6, 2), new Employee("Philip Horsley", 19800, 2));
cache.Put(new AffinityKey(7, 2), new Employee("Brian Peters", 10600, 2));
}
/// <summary>
/// Populate cache with data for this example.
/// </summary>
/// <param name="cache">Cache.</param>
private static void PopulateCache(ICache<int, Employee> cache)
{
cache.Put(1, new Employee("James Wilson", 12500, 1));
cache.Put(2, new Employee("Daniel Adams", 11000, 1));
cache.Put(3, new Employee("Cristian Moss", 12500, 1));
cache.Put(4, new Employee("Allison Mathis", 25300, 2));
cache.Put(5, new Employee("Breana Robbin", 6500, 2));
cache.Put(6, new Employee("Philip Horsley", 19800, 2));
cache.Put(7, new Employee("Brian Peters", 10600, 2));
}
}
}
| |
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Numerics;
using Nethereum.Hex.HexTypes;
using Nethereum.ABI.FunctionEncoding.Attributes;
using Nethereum.Web3;
using Nethereum.RPC.Eth.DTOs;
using Nethereum.Contracts.CQS;
using Nethereum.Contracts.ContractHandlers;
using Nethereum.Contracts;
using System.Threading;
using Nethereum.ENS.EthRegistrarSubdomainRegistrar.ContractDefinition;
namespace Nethereum.ENS
{
public partial class EthRegistrarSubdomainRegistrarService
{
public static Task<TransactionReceipt> DeployContractAndWaitForReceiptAsync(Nethereum.Web3.Web3 web3, EthRegistrarSubdomainRegistrarDeployment ethRegistrarSubdomainRegistrarDeployment, CancellationTokenSource cancellationTokenSource = null)
{
return web3.Eth.GetContractDeploymentHandler<EthRegistrarSubdomainRegistrarDeployment>().SendRequestAndWaitForReceiptAsync(ethRegistrarSubdomainRegistrarDeployment, cancellationTokenSource);
}
public static Task<string> DeployContractAsync(Nethereum.Web3.Web3 web3, EthRegistrarSubdomainRegistrarDeployment ethRegistrarSubdomainRegistrarDeployment)
{
return web3.Eth.GetContractDeploymentHandler<EthRegistrarSubdomainRegistrarDeployment>().SendRequestAsync(ethRegistrarSubdomainRegistrarDeployment);
}
public static async Task<EthRegistrarSubdomainRegistrarService> DeployContractAndGetServiceAsync(Nethereum.Web3.Web3 web3, EthRegistrarSubdomainRegistrarDeployment ethRegistrarSubdomainRegistrarDeployment, CancellationTokenSource cancellationTokenSource = null)
{
var receipt = await DeployContractAndWaitForReceiptAsync(web3, ethRegistrarSubdomainRegistrarDeployment, cancellationTokenSource);
return new EthRegistrarSubdomainRegistrarService(web3, receipt.ContractAddress);
}
protected Nethereum.Web3.Web3 Web3{ get; }
public ContractHandler ContractHandler { get; }
public EthRegistrarSubdomainRegistrarService(Nethereum.Web3.Web3 web3, string contractAddress)
{
Web3 = web3;
ContractHandler = web3.Eth.GetContractHandler(contractAddress);
}
public Task<bool> SupportsInterfaceQueryAsync(SupportsInterfaceFunction supportsInterfaceFunction, BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<SupportsInterfaceFunction, bool>(supportsInterfaceFunction, blockParameter);
}
public Task<bool> SupportsInterfaceQueryAsync(byte[] interfaceID, BlockParameter blockParameter = null)
{
var supportsInterfaceFunction = new SupportsInterfaceFunction();
supportsInterfaceFunction.InterfaceID = interfaceID;
return ContractHandler.QueryAsync<SupportsInterfaceFunction, bool>(supportsInterfaceFunction, blockParameter);
}
public Task<string> OwnerQueryAsync(OwnerFunction ownerFunction, BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<OwnerFunction, string>(ownerFunction, blockParameter);
}
public Task<string> OwnerQueryAsync(byte[] label, BlockParameter blockParameter = null)
{
var ownerFunction = new OwnerFunction();
ownerFunction.Label = label;
return ContractHandler.QueryAsync<OwnerFunction, string>(ownerFunction, blockParameter);
}
public Task<string> StopRequestAsync(StopFunction stopFunction)
{
return ContractHandler.SendRequestAsync(stopFunction);
}
public Task<string> StopRequestAsync()
{
return ContractHandler.SendRequestAsync<StopFunction>();
}
public Task<TransactionReceipt> StopRequestAndWaitForReceiptAsync(StopFunction stopFunction, CancellationTokenSource cancellationToken = null)
{
return ContractHandler.SendRequestAndWaitForReceiptAsync(stopFunction, cancellationToken);
}
public Task<TransactionReceipt> StopRequestAndWaitForReceiptAsync(CancellationTokenSource cancellationToken = null)
{
return ContractHandler.SendRequestAndWaitForReceiptAsync<StopFunction>(null, cancellationToken);
}
public Task<string> MigrationQueryAsync(MigrationFunction migrationFunction, BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<MigrationFunction, string>(migrationFunction, blockParameter);
}
public Task<string> MigrationQueryAsync(BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<MigrationFunction, string>(null, blockParameter);
}
public Task<string> RegistrarOwnerQueryAsync(RegistrarOwnerFunction registrarOwnerFunction, BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<RegistrarOwnerFunction, string>(registrarOwnerFunction, blockParameter);
}
public Task<string> RegistrarOwnerQueryAsync(BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<RegistrarOwnerFunction, string>(null, blockParameter);
}
public Task<string> RegistrarQueryAsync(RegistrarFunction registrarFunction, BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<RegistrarFunction, string>(registrarFunction, blockParameter);
}
public Task<string> RegistrarQueryAsync(BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<RegistrarFunction, string>(null, blockParameter);
}
public Task<QueryOutputDTO> QueryQueryAsync(QueryFunction queryFunction, BlockParameter blockParameter = null)
{
return ContractHandler.QueryDeserializingToObjectAsync<QueryFunction, QueryOutputDTO>(queryFunction, blockParameter);
}
public Task<QueryOutputDTO> QueryQueryAsync(byte[] label, string subdomain, BlockParameter blockParameter = null)
{
var queryFunction = new QueryFunction();
queryFunction.Label = label;
queryFunction.Subdomain = subdomain;
return ContractHandler.QueryDeserializingToObjectAsync<QueryFunction, QueryOutputDTO>(queryFunction, blockParameter);
}
public Task<string> EnsQueryAsync(EnsFunction ensFunction, BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<EnsFunction, string>(ensFunction, blockParameter);
}
public Task<string> EnsQueryAsync(BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<EnsFunction, string>(null, blockParameter);
}
public Task<string> RegisterRequestAsync(RegisterFunction registerFunction)
{
return ContractHandler.SendRequestAsync(registerFunction);
}
public Task<TransactionReceipt> RegisterRequestAndWaitForReceiptAsync(RegisterFunction registerFunction, CancellationTokenSource cancellationToken = null)
{
return ContractHandler.SendRequestAndWaitForReceiptAsync(registerFunction, cancellationToken);
}
public Task<string> RegisterRequestAsync(byte[] label, string subdomain, string subdomainOwner, string referrer, string resolver)
{
var registerFunction = new RegisterFunction();
registerFunction.Label = label;
registerFunction.Subdomain = subdomain;
registerFunction.SubdomainOwner = subdomainOwner;
registerFunction.Referrer = referrer;
registerFunction.Resolver = resolver;
return ContractHandler.SendRequestAsync(registerFunction);
}
public Task<TransactionReceipt> RegisterRequestAndWaitForReceiptAsync(byte[] label, string subdomain, string subdomainOwner, string referrer, string resolver, CancellationTokenSource cancellationToken = null)
{
var registerFunction = new RegisterFunction();
registerFunction.Label = label;
registerFunction.Subdomain = subdomain;
registerFunction.SubdomainOwner = subdomainOwner;
registerFunction.Referrer = referrer;
registerFunction.Resolver = resolver;
return ContractHandler.SendRequestAndWaitForReceiptAsync(registerFunction, cancellationToken);
}
public Task<string> SetMigrationAddressRequestAsync(SetMigrationAddressFunction setMigrationAddressFunction)
{
return ContractHandler.SendRequestAsync(setMigrationAddressFunction);
}
public Task<TransactionReceipt> SetMigrationAddressRequestAndWaitForReceiptAsync(SetMigrationAddressFunction setMigrationAddressFunction, CancellationTokenSource cancellationToken = null)
{
return ContractHandler.SendRequestAndWaitForReceiptAsync(setMigrationAddressFunction, cancellationToken);
}
public Task<string> SetMigrationAddressRequestAsync(string migration)
{
var setMigrationAddressFunction = new SetMigrationAddressFunction();
setMigrationAddressFunction.Migration = migration;
return ContractHandler.SendRequestAsync(setMigrationAddressFunction);
}
public Task<TransactionReceipt> SetMigrationAddressRequestAndWaitForReceiptAsync(string migration, CancellationTokenSource cancellationToken = null)
{
var setMigrationAddressFunction = new SetMigrationAddressFunction();
setMigrationAddressFunction.Migration = migration;
return ContractHandler.SendRequestAndWaitForReceiptAsync(setMigrationAddressFunction, cancellationToken);
}
public Task<BigInteger> RentDueQueryAsync(RentDueFunction rentDueFunction, BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<RentDueFunction, BigInteger>(rentDueFunction, blockParameter);
}
public Task<BigInteger> RentDueQueryAsync(byte[] label, string subdomain, BlockParameter blockParameter = null)
{
var rentDueFunction = new RentDueFunction();
rentDueFunction.Label = label;
rentDueFunction.Subdomain = subdomain;
return ContractHandler.QueryAsync<RentDueFunction, BigInteger>(rentDueFunction, blockParameter);
}
public Task<string> SetResolverRequestAsync(SetResolverFunction setResolverFunction)
{
return ContractHandler.SendRequestAsync(setResolverFunction);
}
public Task<TransactionReceipt> SetResolverRequestAndWaitForReceiptAsync(SetResolverFunction setResolverFunction, CancellationTokenSource cancellationToken = null)
{
return ContractHandler.SendRequestAndWaitForReceiptAsync(setResolverFunction, cancellationToken);
}
public Task<string> SetResolverRequestAsync(string name, string resolver)
{
var setResolverFunction = new SetResolverFunction();
setResolverFunction.Name = name;
setResolverFunction.Resolver = resolver;
return ContractHandler.SendRequestAsync(setResolverFunction);
}
public Task<TransactionReceipt> SetResolverRequestAndWaitForReceiptAsync(string name, string resolver, CancellationTokenSource cancellationToken = null)
{
var setResolverFunction = new SetResolverFunction();
setResolverFunction.Name = name;
setResolverFunction.Resolver = resolver;
return ContractHandler.SendRequestAndWaitForReceiptAsync(setResolverFunction, cancellationToken);
}
public Task<bool> StoppedQueryAsync(StoppedFunction stoppedFunction, BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<StoppedFunction, bool>(stoppedFunction, blockParameter);
}
public Task<bool> StoppedQueryAsync(BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<StoppedFunction, bool>(null, blockParameter);
}
public Task<byte[]> TLD_NODEQueryAsync(TLD_NODEFunction tLD_NODEFunction, BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<TLD_NODEFunction, byte[]>(tLD_NODEFunction, blockParameter);
}
public Task<byte[]> TLD_NODEQueryAsync(BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<TLD_NODEFunction, byte[]>(null, blockParameter);
}
public Task<string> MigrateRequestAsync(MigrateFunction migrateFunction)
{
return ContractHandler.SendRequestAsync(migrateFunction);
}
public Task<TransactionReceipt> MigrateRequestAndWaitForReceiptAsync(MigrateFunction migrateFunction, CancellationTokenSource cancellationToken = null)
{
return ContractHandler.SendRequestAndWaitForReceiptAsync(migrateFunction, cancellationToken);
}
public Task<string> MigrateRequestAsync(string name)
{
var migrateFunction = new MigrateFunction();
migrateFunction.Name = name;
return ContractHandler.SendRequestAsync(migrateFunction);
}
public Task<TransactionReceipt> MigrateRequestAndWaitForReceiptAsync(string name, CancellationTokenSource cancellationToken = null)
{
var migrateFunction = new MigrateFunction();
migrateFunction.Name = name;
return ContractHandler.SendRequestAndWaitForReceiptAsync(migrateFunction, cancellationToken);
}
public Task<string> PayRentRequestAsync(PayRentFunction payRentFunction)
{
return ContractHandler.SendRequestAsync(payRentFunction);
}
public Task<TransactionReceipt> PayRentRequestAndWaitForReceiptAsync(PayRentFunction payRentFunction, CancellationTokenSource cancellationToken = null)
{
return ContractHandler.SendRequestAndWaitForReceiptAsync(payRentFunction, cancellationToken);
}
public Task<string> PayRentRequestAsync(byte[] label, string subdomain)
{
var payRentFunction = new PayRentFunction();
payRentFunction.Label = label;
payRentFunction.Subdomain = subdomain;
return ContractHandler.SendRequestAsync(payRentFunction);
}
public Task<TransactionReceipt> PayRentRequestAndWaitForReceiptAsync(byte[] label, string subdomain, CancellationTokenSource cancellationToken = null)
{
var payRentFunction = new PayRentFunction();
payRentFunction.Label = label;
payRentFunction.Subdomain = subdomain;
return ContractHandler.SendRequestAndWaitForReceiptAsync(payRentFunction, cancellationToken);
}
public Task<string> ConfigureDomainForRequestAsync(ConfigureDomainForFunction configureDomainForFunction)
{
return ContractHandler.SendRequestAsync(configureDomainForFunction);
}
public Task<TransactionReceipt> ConfigureDomainForRequestAndWaitForReceiptAsync(ConfigureDomainForFunction configureDomainForFunction, CancellationTokenSource cancellationToken = null)
{
return ContractHandler.SendRequestAndWaitForReceiptAsync(configureDomainForFunction, cancellationToken);
}
public Task<string> ConfigureDomainForRequestAsync(string name, BigInteger price, BigInteger referralFeePPM, string owner, string transfer)
{
var configureDomainForFunction = new ConfigureDomainForFunction();
configureDomainForFunction.Name = name;
configureDomainForFunction.Price = price;
configureDomainForFunction.ReferralFeePPM = referralFeePPM;
configureDomainForFunction.Owner = owner;
configureDomainForFunction.Transfer = transfer;
return ContractHandler.SendRequestAsync(configureDomainForFunction);
}
public Task<TransactionReceipt> ConfigureDomainForRequestAndWaitForReceiptAsync(string name, BigInteger price, BigInteger referralFeePPM, string owner, string transfer, CancellationTokenSource cancellationToken = null)
{
var configureDomainForFunction = new ConfigureDomainForFunction();
configureDomainForFunction.Name = name;
configureDomainForFunction.Price = price;
configureDomainForFunction.ReferralFeePPM = referralFeePPM;
configureDomainForFunction.Owner = owner;
configureDomainForFunction.Transfer = transfer;
return ContractHandler.SendRequestAndWaitForReceiptAsync(configureDomainForFunction, cancellationToken);
}
public Task<string> ConfigureDomainRequestAsync(ConfigureDomainFunction configureDomainFunction)
{
return ContractHandler.SendRequestAsync(configureDomainFunction);
}
public Task<TransactionReceipt> ConfigureDomainRequestAndWaitForReceiptAsync(ConfigureDomainFunction configureDomainFunction, CancellationTokenSource cancellationToken = null)
{
return ContractHandler.SendRequestAndWaitForReceiptAsync(configureDomainFunction, cancellationToken);
}
public Task<string> ConfigureDomainRequestAsync(string name, BigInteger price, BigInteger referralFeePPM)
{
var configureDomainFunction = new ConfigureDomainFunction();
configureDomainFunction.Name = name;
configureDomainFunction.Price = price;
configureDomainFunction.ReferralFeePPM = referralFeePPM;
return ContractHandler.SendRequestAsync(configureDomainFunction);
}
public Task<TransactionReceipt> ConfigureDomainRequestAndWaitForReceiptAsync(string name, BigInteger price, BigInteger referralFeePPM, CancellationTokenSource cancellationToken = null)
{
var configureDomainFunction = new ConfigureDomainFunction();
configureDomainFunction.Name = name;
configureDomainFunction.Price = price;
configureDomainFunction.ReferralFeePPM = referralFeePPM;
return ContractHandler.SendRequestAndWaitForReceiptAsync(configureDomainFunction, cancellationToken);
}
public Task<string> UnlistDomainRequestAsync(UnlistDomainFunction unlistDomainFunction)
{
return ContractHandler.SendRequestAsync(unlistDomainFunction);
}
public Task<TransactionReceipt> UnlistDomainRequestAndWaitForReceiptAsync(UnlistDomainFunction unlistDomainFunction, CancellationTokenSource cancellationToken = null)
{
return ContractHandler.SendRequestAndWaitForReceiptAsync(unlistDomainFunction, cancellationToken);
}
public Task<string> UnlistDomainRequestAsync(string name)
{
var unlistDomainFunction = new UnlistDomainFunction();
unlistDomainFunction.Name = name;
return ContractHandler.SendRequestAsync(unlistDomainFunction);
}
public Task<TransactionReceipt> UnlistDomainRequestAndWaitForReceiptAsync(string name, CancellationTokenSource cancellationToken = null)
{
var unlistDomainFunction = new UnlistDomainFunction();
unlistDomainFunction.Name = name;
return ContractHandler.SendRequestAndWaitForReceiptAsync(unlistDomainFunction, cancellationToken);
}
public Task<string> TransferOwnershipRequestAsync(TransferOwnershipFunction transferOwnershipFunction)
{
return ContractHandler.SendRequestAsync(transferOwnershipFunction);
}
public Task<TransactionReceipt> TransferOwnershipRequestAndWaitForReceiptAsync(TransferOwnershipFunction transferOwnershipFunction, CancellationTokenSource cancellationToken = null)
{
return ContractHandler.SendRequestAndWaitForReceiptAsync(transferOwnershipFunction, cancellationToken);
}
public Task<string> TransferOwnershipRequestAsync(string newOwner)
{
var transferOwnershipFunction = new TransferOwnershipFunction();
transferOwnershipFunction.NewOwner = newOwner;
return ContractHandler.SendRequestAsync(transferOwnershipFunction);
}
public Task<TransactionReceipt> TransferOwnershipRequestAndWaitForReceiptAsync(string newOwner, CancellationTokenSource cancellationToken = null)
{
var transferOwnershipFunction = new TransferOwnershipFunction();
transferOwnershipFunction.NewOwner = newOwner;
return ContractHandler.SendRequestAndWaitForReceiptAsync(transferOwnershipFunction, cancellationToken);
}
public Task<string> TransferRequestAsync(TransferFunction transferFunction)
{
return ContractHandler.SendRequestAsync(transferFunction);
}
public Task<TransactionReceipt> TransferRequestAndWaitForReceiptAsync(TransferFunction transferFunction, CancellationTokenSource cancellationToken = null)
{
return ContractHandler.SendRequestAndWaitForReceiptAsync(transferFunction, cancellationToken);
}
public Task<string> TransferRequestAsync(string name, string newOwner)
{
var transferFunction = new TransferFunction();
transferFunction.Name = name;
transferFunction.NewOwner = newOwner;
return ContractHandler.SendRequestAsync(transferFunction);
}
public Task<TransactionReceipt> TransferRequestAndWaitForReceiptAsync(string name, string newOwner, CancellationTokenSource cancellationToken = null)
{
var transferFunction = new TransferFunction();
transferFunction.Name = name;
transferFunction.NewOwner = newOwner;
return ContractHandler.SendRequestAndWaitForReceiptAsync(transferFunction, cancellationToken);
}
}
}
| |
using NetDimension.NanUI.Browser;
using Vanara.PInvoke;
using Xilium.CefGlue;
using static Vanara.PInvoke.User32;
namespace NetDimension.NanUI;
partial class Formium
{
private ChromeWidgetMessageInterceptor chromeWidgetMessageInterceptor = null;
private readonly object _browserSyncRoot = new object();
private string _loadUrlDeferred;
private bool _isBrowserCreated = false;
private bool _isFirstTimeToRun = true;
internal CefWindowInfo WindowInfo { get; private set; }
internal protected CefBrowser Browser => WebView?.Browser;
internal void CreateBrowser()
{
var browserSettings = OnCreateBrowserSettings();
if (browserSettings == null)
{
browserSettings = WinFormium.DefaultBrowserSettings;
}
WebView = new FormiumWebView(this, browserSettings, StartUrl);
WindowInfo = CefWindowInfo.Create();
WindowInfo.StyleEx |= Xilium.CefGlue.Platform.Windows.WindowStyleEx.WS_EX_NOACTIVATE;
GetClientRect(HostWindowHandle, out var rect);
if (WindowType == HostWindow.HostWindowType.Layered)
{
WindowInfo.SetAsWindowless(IntPtr.Zero, true);
}
else
{
WindowInfo.SetAsChild(HostWindowHandle, new CefRectangle(0, 0, rect.Width, rect.Height));
//WindowInfo.SetAsPopup(IntPtr.Zero,"");
}
WebView.CreateBrowser(WindowInfo);
}
internal async void AttachToChromeWidgetMessageHandler()
{
var retval = await ChromeWidgetMessageInterceptor.Setup(chromeWidgetMessageInterceptor, this, OnBrowserMessage);
if (retval != null)
{
if (chromeWidgetMessageInterceptor != null)
{
chromeWidgetMessageInterceptor.ReleaseBrowserHandle();
}
chromeWidgetMessageInterceptor = retval;
}
}
internal void OnBrowserCreated()
{
BrowserWindowHandle = WebView.BrowserWindowHandle;
InvokeIfRequired(() => BrowserCreated?.Invoke(this, EventArgs.Empty));
InvokeIfRequired(() => OnWindowAndBrowserReady());
_isBrowserCreated = true;
ThreadPool.QueueUserWorkItem(AfterSetBrowserTasks);
InvokeIfRequired(() => ResizeWebView());
}
private void AfterSetBrowserTasks(object state)
{
lock (_browserSyncRoot)
{
if (_loadUrlDeferred != null)
{
Browser.GetMainFrame().LoadUrl(_loadUrlDeferred);
}
}
}
private bool OnBrowserMessage(ref Message m)
{
if (!_isHostWindowCreated)
return false;
var retval = false;
switch (m.Msg)
{
case (int)WindowMessage.WM_LBUTTONDOWN:
retval = BrowserWmLButtonDown(ref m);
break;
case (int)WindowMessage.WM_RBUTTONDOWN:
retval = BrowserWmRButtonDown(ref m);
break;
case (int)WindowMessage.WM_RBUTTONUP:
retval = BrowserWmRButtonUp(ref m);
break;
case (int)WindowMessage.WM_LBUTTONUP:
retval = BrowserWmLButtonUp(ref m);
break;
case (int)WindowMessage.WM_LBUTTONDBLCLK:
retval = BrowserWmLButtonDbClick(ref m);
break;
case (int)WindowMessage.WM_MOUSEMOVE:
retval = BrowserWmMouseMove(ref m);
break;
case (int)WindowMessage.WM_SETCURSOR:
retval = BrowserWmSetCursor(ref m);
break;
case (int)WindowMessage.WM_NCHITTEST:
retval = BrowserWmNCHitTest(ref m);
break;
}
return retval;
}
private bool BrowserWmNCHitTest(ref Message m)
{
if (_isResizing)
{
return true;
}
return false;
}
internal bool BrowserWmMouseMove(ref Message m)
{
if (FullScreen)
return false;
if (WindowState != FormWindowState.Normal)
return false;
var point = new Point(Macros.GET_X_LPARAM(m.LParam), Macros.GET_Y_LPARAM(m.LParam));
var retval = IFormHostWindow.HitTest(point);
if (retval != HitTestValues.HTNOWHERE)
{
var mode = retval;
if (mode != HitTestValues.HTCLIENT && WindowState == FormWindowState.Normal)
{
return true;
}
}
return false;
}
internal void OnContextCreated(CefBrowser browser, CefFrame frame)
{
if (frame.IsMain)
{
AttachToChromeWidgetMessageHandler();
}
}
internal bool BrowserWmSetCursor(ref Message m)
{
if (FullScreen)
return false;
if (WindowState != FormWindowState.Normal)
return false;
if (!Sizable)
return false;
var pos = GetMessagePos();
var point = new Point(Macros.LOWORD(pos), Macros.HIWORD(pos));
ScreenToClient(HostWindowHandle, ref point);
var mode = IFormHostWindow.HitTest(point);
if (mode != HitTestValues.HTCLIENT && WindowState == FormWindowState.Normal)
{
SetCursor(mode);
m.Result = (IntPtr)1;
return true;
}
return false;
}
internal bool BrowserWmLButtonDown(ref Message m)
{
if (FullScreen || WindowType == HostWindow.HostWindowType.Kiosk)
return false;
var point = new Point(Macros.GET_X_LPARAM(m.LParam), Macros.GET_Y_LPARAM(m.LParam));
var isInDraggableArea = (WebView?.DraggableRegion?.IsVisible(point) ?? false);
var mode = IFormHostWindow.HitTest(point);
ClientToScreen(HostWindowHandle, ref point);
if (Sizable && mode != HitTestValues.HTCLIENT && WindowState == FormWindowState.Normal)
{
ReleaseCapture();
PostMessage(HostWindowHandle, (uint)WindowMessage.WM_NCLBUTTONDOWN, (IntPtr)mode, Macros.MAKELPARAM((ushort)point.X, (ushort)point.Y));
return true;
}
else if (isInDraggableArea)
{
ReleaseCapture();
PostMessage(HostWindowHandle, (uint)WindowMessage.WM_NCLBUTTONDOWN, (IntPtr)HitTestValues.HTCAPTION, Macros.MAKELPARAM((ushort)point.X, (ushort)point.Y));
return true;
}
//else
//{
// PostMessage(HostWindowHandle, (uint)WindowMessage.WM_LBUTTONDOWN, m.WParam, m.LParam);
//}
return false;
}
internal bool BrowserWmRButtonDown(ref Message m)
{
if (!AllowSystemMenu)
{
return false;
}
var point = new Point(Macros.GET_X_LPARAM(m.LParam), Macros.GET_Y_LPARAM(m.LParam));
var isInDraggableArea = (WebView?.DraggableRegion != null && WebView.DraggableRegion.IsVisible(point));
if (isInDraggableArea)
{
ClientToScreen(HostWindowHandle, ref point);
PostMessage(HostWindowHandle, (uint)WindowMessage.WM_NCRBUTTONDOWN, (IntPtr)HitTestValues.HTSYSMENU, Macros.MAKELPARAM((ushort)point.X, (ushort)point.Y));
return true;
}
return false;
}
internal bool BrowserWmRButtonUp(ref Message m)
{
if (!AllowSystemMenu)
{
return false;
}
var point = new Point(Macros.GET_X_LPARAM(m.LParam), Macros.GET_Y_LPARAM(m.LParam));
var isInDraggableArea = (WebView?.DraggableRegion != null && WebView.DraggableRegion.IsVisible(point));
if (isInDraggableArea)
{
ClientToScreen(HostWindowHandle, ref point);
PostMessage(HostWindowHandle, (uint)WindowMessage.WM_NCRBUTTONUP, (IntPtr)HitTestValues.HTSYSMENU, Macros.MAKELPARAM((ushort)point.X, (ushort)point.Y));
return true;
}
return false;
}
private bool BrowserWmLButtonUp(ref Message m)
{
return false;
}
internal bool BrowserWmLButtonDbClick(ref Message m)
{
var point = new Point(Macros.GET_X_LPARAM(m.LParam), Macros.GET_Y_LPARAM(m.LParam));
var isInDraggableArea = (WebView?.DraggableRegion != null && WebView.DraggableRegion.IsVisible(point));
if (isInDraggableArea && Maximizable && Sizable)
{
if (FullScreen)
{
return false;
}
PostMessage(HostWindowHandle, (uint)WindowMessage.WM_NCLBUTTONDBLCLK, (IntPtr)HitTestValues.HTCAPTION, IntPtr.Zero);
return true;
}
return false;
}
internal void ResizeWebView()
{
if (!_isHostWindowCreated || !_isBrowserCreated || BrowserWindowHandle == IntPtr.Zero)
return;
GetClientRect(HostWindowHandle, out var rect);
if (IsIconic(this.HostWindowHandle))
{
SetWindowPos(BrowserWindowHandle, HWND.NULL, 0, 0, 0, 0, SetWindowPosFlags.SWP_NOSIZE | SetWindowPosFlags.SWP_NOMOVE | SetWindowPosFlags.SWP_NOZORDER);
}
else
{
if (IsWindowVisible(HostWindowHandle))
{
SetWindowPos(BrowserWindowHandle, HWND.NULL, 0, 0, rect.Width, rect.Height, SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_SHOWWINDOW | SetWindowPosFlags.SWP_NOACTIVATE);
SetWindowLong(BrowserWindowHandle, WindowLongFlags.GWL_STYLE, (IntPtr)(WindowStyles.WS_CHILD | WindowStyles.WS_CLIPCHILDREN | WindowStyles.WS_CLIPSIBLINGS | WindowStyles.WS_TABSTOP | WindowStyles.WS_VISIBLE));
}
else
{
SetWindowPos(BrowserWindowHandle, HWND.NULL, 0, 0, 0, 0, SetWindowPosFlags.SWP_NOSIZE | SetWindowPosFlags.SWP_NOMOVE | SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_HIDEWINDOW);
SetWindowLong(BrowserWindowHandle, WindowLongFlags.GWL_STYLE, (IntPtr)(WindowStyles.WS_CHILD | WindowStyles.WS_CLIPCHILDREN | WindowStyles.WS_CLIPSIBLINGS | WindowStyles.WS_TABSTOP | WindowStyles.WS_DISABLED));
}
}
}
internal void OnDataMessageReceived(string message, string json)
{
var args = new DataMessageReceivedArgs(message, json);
DataMessageReceived?.Invoke(this, args);
}
/// <summary>
/// Send empty message to client.
/// </summary>
/// <param name="message">Message name</param>
public void SendDataMessage(string message)
{
ExecuteJavaScript($"Formium.__onDataMessageReceived__(`{message}`)");
}
/// <summary>
/// Send messege to client.
/// </summary>
/// <typeparam name="T">Data type of message</typeparam>
/// <param name="message">Message name</param>
/// <param name="data">Data structure. The data will be serialize to JSON text when sending to client.</param>
public void SendDataMessage<T>(string message, T data)
{
if (data == null)
{
ExecuteJavaScript($"Formium.__onDataMessageReceived__(`{message}`,``)");
}
else
{
var json = JsonConvert.SerializeObject(data);
var base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(json));
ExecuteJavaScript($"Formium.__onDataMessageReceived__(`{message}`,`{base64}`)");
}
}
#region Browser public members
/// <summary>
/// Returns true if current browser can navigate backwards.
/// </summary>
public bool CanGoBack => Browser?.CanGoBack ?? false;
/// <summary>
/// Returns true if current browser can navigate forwards.
/// </summary>
public bool CanGoForward => Browser?.CanGoForward ?? false;
/// <summary>
/// Returns the number of frames that currently exist.
/// </summary>
public int FrameCount => Browser?.FrameCount ?? 0;
/// <summary>
/// Returns true if a document has been loaded in the browser.
/// </summary>
public bool HasDocument => Browser?.HasDocument ?? false;
/// <summary>
/// Returns the globally unique identifier for this browser. This value is also
/// used as the tabId for extension APIs.
/// </summary>
public int Identifier => Browser?.Identifier ?? 0;
/// <summary>
/// Returns true if the browser is currently loading.
/// </summary>
public bool IsLoading => Browser?.IsLoading ?? false;
/// <summary>
/// Returns true if the window is a popup window.
/// </summary>
public bool IsPopup => Browser?.IsPopup ?? false;
/// <summary>
/// Returns the focused frame for the browser window.
/// </summary>
public CefFrame GetFocusedFrame()
{
return Browser?.GetFocusedFrame();
}
/// <summary>
/// Returns the frame with the specified identifier, or NULL if not found.
/// </summary>
/// <param name="identifier">The identifier of the frame to be get.</param>
public CefFrame GetFrame(long identifier)
{
return Browser?.GetFrame(identifier);
}
/// <summary>
/// Returns the frame with the specified name, or NULL if not found.
/// </summary>
/// <param name="name">The name of the frame to be get.</param>
public CefFrame GetFrame(string name)
{
return Browser?.GetFrame(name);
}
/// <summary>
/// Returns the identifiers of all existing frames.
/// </summary>
public long[] GetFrameIdentifiers()
{
return Browser?.GetFrameIdentifiers();
}
/// <summary>
/// Returns the names of all existing frames.
/// </summary>
public string[] GetFrameNames()
{
return Browser?.GetFrameNames();
}
/// <summary>
/// Returns the browser host object. This method can only be called in the
/// browser process.
/// </summary>
public CefBrowserHost GetHost()
{
return Browser?.GetHost();
}
/// <summary>
/// Returns the main (top-level) frame for the browser window.
/// </summary>
public CefFrame GetMainFrame()
{
return Browser?.GetMainFrame();
}
/// <summary>
/// Navigate backwards.
/// </summary>
public void GoBack()
{
Browser?.GoBack();
}
/// <summary>
/// Navigate forwards.
/// </summary>
public void GoForward()
{
Browser?.GoForward();
}
/// <summary>
/// Returns true if this object is pointing to the same handle as |that|
/// object.
/// </summary>
public bool IsSame(CefBrowser that)
{
return Browser?.IsSame(that) ?? false;
}
/// <summary>
/// Reload the current page.
/// </summary>
public void Reload(bool forceReload = false)
{
if (forceReload)
{
Browser?.ReloadIgnoreCache();
}
else
{
Browser?.Reload();
}
}
/// <summary>
/// Load page from the
/// </summary>
/// <param name="url"></param>
public void LoadUrl(string url)
{
if (Browser != null && Browser?.GetMainFrame() != null)
{
Browser.GetMainFrame().LoadUrl(url);
}
else
{
lock (_browserSyncRoot)
{
if (Browser != null && Browser?.GetMainFrame() != null)
{
Browser.GetMainFrame().LoadUrl(url);
}
else
{
_loadUrlDeferred = url;
}
}
}
}
/// <summary>
/// Stop loading the page.
/// </summary>
public void StopLoad()
{
Browser?.StopLoad();
}
DevToolsHostWindow devToolsWindow;
/// <summary>
/// Open developer tools (DevTools) in its own browser. The DevTools browser
/// will remain associated with this browser. If the DevTools browser is
/// already open then it will be focused.
/// </summary>
public void ShowDevTools()
{
InvokeIfRequired(() =>
{
if (WebView.BrowserHost == null)
{
return;
}
var windowInfo = CefWindowInfo.Create();
if (devToolsWindow == null || devToolsWindow.IsDisposed)
{
devToolsWindow = new DevToolsHostWindow(this);
}
GetClientRect(devToolsWindow.Handle, out var rect);
windowInfo.SetAsChild(devToolsWindow.Handle, new CefRectangle(0, 0, rect.Width, rect.Height));
WebView.BrowserHost.ShowDevTools(windowInfo, new DevToolsBrowserClient(devToolsWindow), new CefBrowserSettings(), new CefPoint(0, 0));
if (!devToolsWindow.Visible)
{
devToolsWindow.Show();
}
});
}
public void CloseDevTools()
{
WebView.BrowserHost.CloseDevTools();
}
#endregion
#region Events
/// <summary>
/// Occurs when Formium is ready to use.
/// </summary>
//public event EventHandler Ready;
/// <summary>
/// Occurs when DataMessage from Browser has arrived.
/// </summary>
public event EventHandler<DataMessageReceivedArgs> DataMessageReceived;
/// <summary>
/// Occurs before the browser is Created.
/// </summary>
public event EventHandler BrowserCreated;
#region LifeSpanHandler
/// <summary>
/// Called on the UI thread before a new popup browser is created. The
/// |browser| and |frame| values represent the source of the popup request. The
/// |target_url| and |target_frame_name| values indicate where the popup
/// browser should navigate and may be empty if not specified with the request.
/// The |target_disposition| value indicates where the user intended to open
/// the popup (e.g. current tab, new tab, etc). The |user_gesture| value will
/// be true if the popup was opened via explicit user gesture (e.g. clicking a
/// link) or false if the popup opened automatically (e.g. via the
/// DomContentLoaded event). The |popupFeatures| structure contains additional
/// information about the requested popup window. To allow creation of the
/// popup browser optionally modify |windowInfo|, |client|, |settings| and
/// |no_javascript_access| and return false. To cancel creation of the popup
/// browser return true. The |client| and |settings| values will default to the
/// source browser's values. If the |no_javascript_access| value is set to
/// false the new browser will not be scriptable and may not be hosted in the
/// same renderer process as the source browser. Any modifications to
/// |windowInfo| will be ignored if the parent browser is wrapped in a
/// CefBrowserView. Popup browser creation will be canceled if the parent
/// browser is destroyed before the popup browser creation completes (indicated
/// by a call to OnAfterCreated for the popup browser). The |extra_info|
/// parameter provides an opportunity to specify extra information specific
/// to the created popup browser that will be passed to
/// CefRenderProcessHandler::OnBrowserCreated() in the render process.
/// </summary>
public event EventHandler<BeforePopupEventArgs> BeforePopup;
/// <summary>
/// Called just before a browser is destroyed. Release all references to the
/// browser object and do not attempt to execute any methods on the browser
/// object (other than GetIdentifier or IsSame) after this callback returns.
/// This callback will be the last notification that references |browser| on
/// the UI thread. Any in-progress network requests associated with |browser|
/// will be aborted when the browser is destroyed, and
/// CefResourceRequestHandler callbacks related to those requests may still
/// arrive on the IO thread after this method is called. See DoClose()
/// documentation for additional usage information.
/// </summary>
public event EventHandler<FormiumCloseEventArgs> BeforeClose;
/// <summary>
/// Raises the BeforePopup event.
/// </summary>
internal protected void OnBeforePopup(BeforePopupEventArgs e)
{
BeforePopup?.Invoke(this, e);
}
/// <summary>
/// Raises the BeforeClose event.
/// </summary>
internal protected void OnBeforeClose(FormiumCloseEventArgs e)
{
BeforeClose?.Invoke(this, e);
}
#endregion
#region LoadHandler
/// <summary>
/// Called after a navigation has been committed and before the browser begins
/// loading contents in the frame. The |frame| value will never be empty --
/// call the IsMain() method to check if this frame is the main frame.
/// |transition_type| provides information about the source of the navigation
/// and an accurate value is only available in the browser process. Multiple
/// frames may be loading at the same time. Sub-frames may start or continue
/// loading after the main frame load has ended. This method will not be called
/// for same page navigations (fragments, history state, etc.) or for
/// navigations that fail or are canceled before commit. For notification of
/// overall browser load status use OnLoadingStateChange instead.
/// </summary>
public event EventHandler<LoadStartEventArgs> LoadStart;
/// <summary>
/// Called when the browser is done loading a frame. The |frame| value will
/// never be empty -- call the IsMain() method to check if this frame is the
/// main frame. Multiple frames may be loading at the same time. Sub-frames may
/// start or continue loading after the main frame load has ended. This method
/// will not be called for same page navigations (fragments, history state,
/// etc.) or for navigations that fail or are canceled before commit. For
/// notification of overall browser load status use OnLoadingStateChange
/// instead.
/// </summary>
public event EventHandler<LoadEndEventArgs> LoadEnd;
/// <summary>
/// Called when a navigation fails or is canceled. This method may be called
/// by itself if before commit or in combination with OnLoadStart/OnLoadEnd if
/// after commit. |errorCode| is the error code number, |errorText| is the
/// error text and |failedUrl| is the URL that failed to load.
/// See net\base\net_error_list.h for complete descriptions of the error codes.
/// </summary>
public event EventHandler<LoadErrorEventArgs> LoadError;
/// <summary>
/// Called when the loading state has changed. This callback will be executed
/// twice -- once when loading is initiated either programmatically or by user
/// action, and once when loading is terminated due to completion, cancellation
/// of failure. It will be called before any calls to OnLoadStart and after all
/// calls to OnLoadError and/or OnLoadEnd.
/// </summary>
public event EventHandler<LoadingStateChangeEventArgs> LoadingStateChanged;
/// <summary>
/// Raises the LoadStart event.
/// </summary>
/// <param name="e"></param>
internal protected void OnLoadStart(LoadStartEventArgs e)
{
LoadStart?.Invoke(this, e);
}
/// <summary>
/// Raises the LoadEnd event.
/// </summary>
/// <param name="e"></param>
internal protected void OnLoadEnd(LoadEndEventArgs e)
{
if (_isFirstTimeToRun && e.Frame.IsMain)
{
foreach (var script in DelayedScripts)
{
ExecuteJavaScript(script.Value);
}
DelayedScripts.Clear();
_isFirstTimeToRun = false;
}
LoadEnd?.Invoke(this, e);
}
/// <summary>
/// Raises the LoadError event.
/// </summary>
/// <param name="e"></param>
internal protected void OnLoadError(LoadErrorEventArgs e)
{
LoadError?.Invoke(this, e);
}
/// <summary>
/// Raises the LoadingStateChanged event.
/// </summary>
/// <param name="e"></param>
internal protected void OnLoadingStateChanged(LoadingStateChangeEventArgs e)
{
LoadingStateChanged?.Invoke(this, e);
}
#endregion
#region DisplayHandler
/// <summary>
/// Called when a frame's address has changed.
/// </summary>
public event EventHandler<AddressChangedEventArgs> AddressChanged;
/// <summary>
/// Called to display a console message. Return true to stop the message from
/// being output to the console.
/// </summary>
public event EventHandler<ConsoleMessageEventArgs> ConsoleMessage;
/// <summary>
/// Called when web content in the page has toggled fullscreen mode. If
/// |fullscreen| is true the content will automatically be sized to fill the
/// browser content area. If |fullscreen| is false the content will
/// automatically return to its original size and position. The client is
/// responsible for resizing the browser if desired.
/// </summary>
public event EventHandler<FullScreenModeChangedEventArgs> FullScreenModeChanged;
/// <summary>
/// Called when the overall page loading progress has changed. |progress|
/// ranges from 0.0 to 1.0.
/// </summary>
public event EventHandler<LoadingProgressChangedEventArgs> LoadingProgressChanged;
/// <summary>
/// Called when the browser receives a status message. |value| contains the
/// text that will be displayed in the status message.
/// </summary>
public event EventHandler<StatusMessageEventArgs> StatusMessage;
/// <summary>
/// Called when the page title changes.
/// </summary>
public event EventHandler<DocumentTitleChangedEventArgs> DocumentTitleChanged;
/// <summary>
/// Raises the AddressChanged event.
/// </summary>
/// <param name="e"></param>
internal protected void OnAddressChanged(AddressChangedEventArgs e)
{
AddressChanged?.Invoke(this, e);
}
/// <summary>
/// Raises the ConsoleMessage event.
/// </summary>
/// <param name="e"></param>
internal protected void OnConsoleMessage(ConsoleMessageEventArgs e)
{
ConsoleMessage?.Invoke(this, e);
}
/// <summary>
/// Raises the FullScreenModeChanged event.
/// </summary>
/// <param name="e"></param>
internal protected void OnFullscreenModeChanged(FullScreenModeChangedEventArgs e)
{
if (AllowFullScreen)
{
//TODO:FullScreen
//FullScreen(e.Fullscreen);
FullScreenModeChanged?.Invoke(this, e);
}
else
{
FullScreenModeChanged?.Invoke(this, new FullScreenModeChangedEventArgs(false));
}
}
/// <summary>
/// Raises the LoadingProgressChanged event.
/// </summary>
/// <param name="e"></param>
internal protected void OnLoadingProgressChanged(LoadingProgressChangedEventArgs e)
{
LoadingProgressChanged?.Invoke(this, e);
}
/// <summary>
/// Raises the StatusMessage event.
/// </summary>
/// <param name="e"></param>
internal protected void OnStatusMessage(StatusMessageEventArgs e)
{
StatusMessage?.Invoke(this, e);
}
/// <summary>
/// Raises the DocumentTitleChanged event.
/// </summary>
/// <param name="e"></param>
internal protected void OnDocumentTitleChanged(DocumentTitleChangedEventArgs e)
{
DocumentTitleChanged?.Invoke(this, e);
}
#endregion
#region ContextMenuHandler
/// <summary>
/// Called before a context menu is displayed. |params| provides information
/// about the context menu state. |model| initially contains the default
/// context menu. The |model| can be cleared to show no context menu or
/// modified to show a custom menu. Do not keep references to |params| or
/// |model| outside of this callback.
/// </summary>
public event EventHandler<BeforeContextMenuEventArgs> BeforeContextMenu;
/// <summary>
/// Called to execute a command selected from the context menu. Return true if
/// the command was handled or false for the default implementation. See
/// cef_menu_id_t for the command ids that have default implementations. All
/// user-defined command ids should be between MENU_ID_USER_FIRST and
/// MENU_ID_USER_LAST. |params| will have the same values as what was passed to
/// OnBeforeContextMenu(). Do not keep a reference to |params| outside of this
/// callback.
/// </summary>
public event EventHandler<ContextMenuCommandEventArgs> ContextMenuCommand;
/// <summary>
/// Called when an external drag event enters the browser window. |dragData|
/// contains the drag event data and |mask| represents the type of drag
/// operation. Return false for default drag handling behavior or true to
/// cancel the drag event.
/// </summary>
public event EventHandler<DragEnterEventArgs> DragEnter;
/// <summary>
/// Raises the BeforeContextMenu event.
/// </summary>
/// <param name="e"></param>
internal protected void OnBeforeContextMenu(BeforeContextMenuEventArgs e)
{
BeforeContextMenu?.Invoke(this, e);
}
/// <summary>
/// Raises the ContextMenuCommand event.
/// </summary>
/// <param name="e"></param>
internal protected void OnContextMenuCommand(ContextMenuCommandEventArgs e)
{
ContextMenuCommand?.Invoke(this, e);
}
/// <summary>
/// Raises the DragEnter event.
/// </summary>
/// <param name="e"></param>
internal protected void OnDragEnter(DragEnterEventArgs e)
{
DragEnter?.Invoke(this, e);
}
#endregion
#region RequestHandler
/// <summary>
/// Called on the IO thread when the browser needs credentials from the user.
/// |origin_url| is the origin making this authentication request. |isProxy|
/// indicates whether the host is a proxy server. |host| contains the hostname
/// and |port| contains the port number. |realm| is the realm of the challenge
/// and may be empty. |scheme| is the authentication scheme used, such as
/// "basic" or "digest", and will be empty if the source of the request is an
/// FTP server. Return true to continue the request and call
/// CefAuthCallback::Continue() either in this method or at a later time when
/// the authentication information is available. Return false to cancel the
/// request immediately.
/// </summary>
public event EventHandler<AuthCredentialsEventArgs> GetAuthCredentials;
/// <summary>
/// Called on the UI thread to handle requests for URLs with an invalid
/// SSL certificate. Return true and call CefRequestCallback::Continue() either
/// in this method or at a later time to continue or cancel the request. Return
/// false to cancel the request immediately. If
/// CefSettings.ignore_certificate_errors is set all invalid certificates will
/// be accepted without calling this method.
/// </summary>
public event EventHandler<CertificateErrorEventArgs> CertificateError;
/// <summary>
/// Called on the UI thread before browser navigation. Return true to cancel
/// the navigation or false to allow the navigation to proceed. The |request|
/// object cannot be modified in this callback.
/// CefLoadHandler::OnLoadingStateChange will be called twice in all cases.
/// If the navigation is allowed CefLoadHandler::OnLoadStart and
/// CefLoadHandler::OnLoadEnd will be called. If the navigation is canceled
/// CefLoadHandler::OnLoadError will be called with an |errorCode| value of
/// ERR_ABORTED. The |user_gesture| value will be true if the browser
/// navigated via explicit user gesture (e.g. clicking a link) or false if it
/// navigated automatically (e.g. via the DomContentLoaded event).
/// </summary>
public event EventHandler<BeforeBrowseEventArgs> BeforeBrowse;
/// <summary>
/// Called on the browser process UI thread when the render process
/// terminates unexpectedly. |status| indicates how the process
/// terminated.
/// </summary>
public event EventHandler<RenderProcessTerminatedEventArgs> RenderProcessTerminated;
/// <summary>
/// <inheritdoc/>
/// </summary>
public event EventHandler<GetResourceRequestHandlerEventArgs> GetResourceRequestHandler;
internal protected virtual void OnGetResourceRequestHandler(GetResourceRequestHandlerEventArgs e)
{
GetResourceRequestHandler?.Invoke(this, e);
}
/// <summary>
/// Raises the OnBeforeBrowse event.
/// </summary>
/// <param name="e"></param>
internal protected void OnBeforeBrowse(BeforeBrowseEventArgs e)
{
BeforeBrowse?.Invoke(this, e);
}
/// <summary>
/// Raises the GetAuthCredentials event.
/// </summary>
/// <param name="e"></param>
internal protected void OnGetAuthCredentials(AuthCredentialsEventArgs e)
{
GetAuthCredentials?.Invoke(this, e);
}
/// <summary>
/// Raises the CertificateError event.
/// </summary>
/// <param name="e"></param>
internal protected void OnCertificateError(CertificateErrorEventArgs e)
{
CertificateError?.Invoke(this, e);
}
/// <summary>
/// Raises the RenderProcessTerminated event.
/// </summary>
/// <param name="e"></param>
internal protected void OnRenderProcessTerminated(RenderProcessTerminatedEventArgs e)
{
RenderProcessTerminated?.Invoke(this, e);
}
#endregion
#region DownloadHandler
/// <summary>
/// Called before a download begins. |suggested_name| is the suggested name for
/// the download file. By default the download will be canceled. Execute
/// |callback| either asynchronously or in this method to continue the download
/// if desired. Do not keep a reference to |download_item| outside of this
/// method.
/// </summary>
public event EventHandler<BeforeDownloadEventArgs> BeforeDownload;
/// <summary>
/// Called when a download's status or progress information has been updated.
/// This may be called multiple times before and after OnBeforeDownload().
/// Execute |callback| either asynchronously or in this method to cancel the
/// download if desired. Do not keep a reference to |download_item| outside of
/// this method.
/// </summary>
public event EventHandler<DownloadUpdatedEventArgs> DownloadUpdated;
/// <summary>
/// Raises the BeforeDownload event.
/// </summary>
/// <param name="e"></param>
internal protected void OnBeforeDownload(BeforeDownloadEventArgs e)
{
if (BeforeDownload != null)
{
BeforeDownload.Invoke(this, e);
}
else
{
e.Continue(e.SuggestedName);
}
}
/// <summary>
/// Raises the DownloadUpdated event.
/// </summary>
/// <param name="e"></param>
internal protected void OnDownloadUpdated(DownloadUpdatedEventArgs e)
{
DownloadUpdated?.Invoke(this, e);
}
#endregion
#region KeyboardHandler
/// <summary>
/// Called after the renderer and JavaScript in the page has had a chance to
/// handle the event. |event| contains information about the keyboard event.
/// |os_event| is the operating system event message, if any. Return true if
/// the keyboard event was handled or false otherwise.
/// </summary>
public event EventHandler<Browser.KeyEventArgs> KeyEvent;
/// <summary>
/// Called before a keyboard event is sent to the renderer. |event| contains
/// information about the keyboard event. |os_event| is the operating system
/// event message, if any. Return true if the event was handled or false
/// otherwise. If the event will be handled in OnKeyEvent() as a keyboard
/// shortcut set |is_keyboard_shortcut| to true and return false.
/// </summary>
public event EventHandler<PreKeyEventArgs> PreKeyEvent;
/// <summary>
/// Raises the PreKeyEvent event.
/// </summary>
internal protected void OnKeyEvent(Browser.KeyEventArgs e)
{
KeyEvent?.Invoke(this, e);
}
/// <summary>
/// Raises the OnKeyEvent event.
/// </summary>
internal protected void OnPreKeyEvent(PreKeyEventArgs e)
{
PreKeyEvent?.Invoke(this, e);
}
#endregion
#region FindHandler
/// <summary>
/// Called to report find results returned by CefBrowserHost::Find().
/// |identifer| is the identifier passed to Find(), |count| is the number of
/// matches currently identified, |selectionRect| is the location of where the
/// match was found (in window coordinates), |activeMatchOrdinal| is the
/// current position in the search results, and |finalUpdate| is true if this
/// is the last find notification.
/// </summary>
public event EventHandler<FindResultEventArgs> FindResult;
/// <summary>
/// Raises the FindResult event.
/// </summary>
internal protected void OnFindResult(FindResultEventArgs e)
{
FindResult?.Invoke(this, e);
}
#endregion
#region FocusHandler
public event EventHandler<EventArgs> GotFocus;
public event EventHandler<SetFocusEventArgs> SetFocus;
public event EventHandler<TakeFocusEventArgs> TakeFocus;
internal protected void OnGotFocus(EventArgs e)
{
GotFocus?.Invoke(this, e);
}
internal protected void OnSetFocus(SetFocusEventArgs e)
{
SetFocus?.Invoke(this, e);
}
internal protected void OnTakeFocus(TakeFocusEventArgs e)
{
TakeFocus?.Invoke(this, e);
}
#endregion
#endregion
}
| |
//
// ActivatorTest.cs - NUnit Test Cases for System.Activator
//
// Authors:
// Nick Drochak <[email protected]>
// Gert Driesen <[email protected]>
// Sebastien Pouliot <[email protected]>
//
// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
//
using System;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Security;
using System.Security.Permissions;
using NUnit.Framework;
// The class in this namespace is used by the main test class
namespace MonoTests.System.ActivatorTestInternal {
// We need a COM class to test the Activator class
[ComVisible (true)]
public class COMTest : MarshalByRefObject {
private int id;
public bool constructorFlag = false;
public COMTest ()
{
id = 0;
}
public COMTest (int id)
{
this.id = id;
}
// This property is visible
[ComVisible (true)]
public int Id {
get { return id; }
set { id = value; }
}
}
[ComVisible (false)]
public class NonCOMTest : COMTest {
}
}
namespace MonoTests.System {
using MonoTests.System.ActivatorTestInternal;
[TestFixture]
public class ActivatorTest {
private string corlibLocation = typeof (string).Assembly.Location;
private string testLocation = typeof (ActivatorTest).Assembly.Location;
[Test]
public void CreateInstance_Type()
{
COMTest objCOMTest = (COMTest) Activator.CreateInstance (typeof (COMTest));
Assert.AreEqual ("MonoTests.System.ActivatorTestInternal.COMTest", (objCOMTest.GetType ()).ToString (), "#A02");
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void CreateInstance_TypeNull ()
{
Activator.CreateInstance ((Type)null);
}
[Test]
public void CreateInstance_StringString ()
{
ObjectHandle objHandle = Activator.CreateInstance (null, "MonoTests.System.ActivatorTestInternal.COMTest");
COMTest objCOMTest = (COMTest)objHandle.Unwrap ();
objCOMTest.Id = 2;
Assert.AreEqual (2, objCOMTest.Id, "#A03");
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void CreateInstance_StringNull ()
{
Activator.CreateInstance ((string)null, null);
}
[Test]
[ExpectedException (typeof (TypeLoadException))]
public void CreateInstance_StringTypeNameDoesNotExists ()
{
Activator.CreateInstance ((string)null, "MonoTests.System.ActivatorTestInternal.DoesntExistsCOMTest");
}
[Test]
public void CreateInstance_TypeBool ()
{
COMTest objCOMTest = (COMTest)Activator.CreateInstance (typeof (COMTest), false);
Assert.AreEqual ("MonoTests.System.ActivatorTestInternal.COMTest", objCOMTest.GetType ().ToString (), "#A04");
}
[Test]
public void CreateInstance_TypeObjectArray ()
{
object[] objArray = new object[1] { 7 };
COMTest objCOMTest = (COMTest)Activator.CreateInstance (typeof (COMTest), objArray);
Assert.AreEqual (7, objCOMTest.Id, "#A05");
}
// TODO: Implemente the test methods for all the overriden functions using activationAttribute
[Test]
#if NET_2_0
[ExpectedException(typeof(MissingMethodException))]
#else
[ExpectedException(typeof(MemberAccessException))]
#endif
public void CreateInstanceAbstract1 ()
{
Activator.CreateInstance (typeof (Type));
}
[Test]
#if NET_2_0
[ExpectedException(typeof(MissingMethodException))]
#else
[ExpectedException(typeof(MemberAccessException))]
#endif
public void CreateInstanceAbstract2 ()
{
Activator.CreateInstance (typeof (Type), true);
}
[Test]
[ExpectedException(typeof(MissingMethodException))]
public void CreateInstanceAbstract3 ()
{
Activator.CreateInstance (typeof (Type), null, null);
}
[Test]
[ExpectedException(typeof(MissingMethodException))]
public void CreateInstanceAbstract4()
{
Activator.CreateInstance (typeof (Type), BindingFlags.CreateInstance | (BindingFlags.Public | BindingFlags.Instance), null, null, CultureInfo.InvariantCulture, null);
}
[Test]
#if NET_2_0
[ExpectedException (typeof (MissingMethodException))]
#else
[ExpectedException (typeof (MemberAccessException))]
#endif
public void CreateInstanceAbstract5 ()
{
Activator.CreateInstance (typeof (Type), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, null, CultureInfo.InvariantCulture, null);
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void GetObject_TypeNull ()
{
Activator.GetObject (null, "tcp://localhost:1234/COMTestUri");
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void GetObject_UrlNull ()
{
Activator.GetObject (typeof (COMTest), null);
}
/* This test is now executed in System.Runtime.Remoting unit tests
[Test]
public void GetObject ()
{
// This will provide a COMTest object on tcp://localhost:1234/COMTestUri
COMTest objCOMTest = new COMTest (8);
TcpChannel chnServer = new TcpChannel (1234);
ChannelServices.RegisterChannel (chnServer);
RemotingServices.SetObjectUriForMarshal (objCOMTest, "COMTestUri");
RemotingServices.Marshal (objCOMTest);
// This will get the remoting object
object objRem = Activator.GetObject (typeof (COMTest), "tcp://localhost:1234/COMTestUri");
Assert.IsNotNull (objRem, "#A07");
COMTest remCOMTest = (COMTest) objRem;
Assert.AreEqual (8, remCOMTest.Id, "#A08");
ChannelServices.UnregisterChannel(chnServer);
}
*/
// TODO: Implemente the test methods for all the overriden function using activationAttribute
[Test]
public void CreateInstanceFrom ()
{
ObjectHandle objHandle = Activator.CreateInstanceFrom (testLocation, "MonoTests.System.ActivatorTestInternal.COMTest");
Assert.IsNotNull (objHandle, "#A09");
objHandle.Unwrap ();
// TODO: Implement the test methods for all the overriden function using activationAttribute
}
// note: this only ensure that the ECMA key support unification (more test required, outside corlib, for other keys, like MS final).
private const string CorlibPermissionPattern = "System.Security.Permissions.FileDialogPermission, mscorlib, Version={0}, Culture=neutral, PublicKeyToken=b77a5c561934e089";
private const string SystemPermissionPattern = "System.Net.DnsPermission, System, Version={0}, Culture=neutral, PublicKeyToken=b77a5c561934e089";
private const string fx10version = "1.0.3300.0";
private const string fx11version = "1.0.5000.0";
private const string fx20version = "2.0.0.0";
private static object[] psNone = new object [1] { PermissionState.None };
private void Unification (string fullname)
{
Type t = Type.GetType (fullname);
IPermission p = (IPermission)Activator.CreateInstance (t, psNone);
string currentVersion = typeof (string).Assembly.GetName ().Version.ToString ();
Assert.IsTrue ((p.ToString ().IndexOf (currentVersion) > 0), currentVersion);
}
[Test]
public void Unification_FromFx10 ()
{
Unification (String.Format (CorlibPermissionPattern, fx10version));
Unification (String.Format (SystemPermissionPattern, fx10version));
}
[Test]
public void Unification_FromFx11 ()
{
Unification (String.Format (CorlibPermissionPattern, fx11version));
Unification (String.Format (SystemPermissionPattern, fx11version));
}
[Test]
public void Unification_FromFx20 ()
{
Unification (String.Format (CorlibPermissionPattern, fx20version));
Unification (String.Format (SystemPermissionPattern, fx20version));
}
[Test]
public void Unification_FromFx99_Corlib ()
{
Unification (String.Format (CorlibPermissionPattern, "9.99.999.9999"));
#if NET_1_1
Unification (String.Format (SystemPermissionPattern, "9.99.999.9999"));
#endif
}
#if NET_2_0
[Test]
[Category ("NotWorking")]
public void Unification_FromFx99_System ()
{
Assert.IsNull (Type.GetType (String.Format (SystemPermissionPattern, "9.99.999.9999")));
}
#endif
}
}
| |
using Apache.NMS.Util;
using System;
using System.Collections.Generic;
using System.Threading;
namespace Lucene.Net.Index
{
using Lucene.Net.Randomized.Generators;
using Lucene.Net.Support;
using NUnit.Framework;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. The ASF
* licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
/// <summary>
/// Tests for <seealso cref="DocumentsWriterStallControl"/>
/// </summary>
[TestFixture]
public class TestDocumentsWriterStallControl : LuceneTestCase
{
[Test]
public virtual void TestSimpleStall()
{
DocumentsWriterStallControl ctrl = new DocumentsWriterStallControl();
ctrl.UpdateStalled(false);
ThreadClass[] waitThreads = WaitThreads(AtLeast(1), ctrl);
Start(waitThreads);
Assert.IsFalse(ctrl.HasBlocked());
Assert.IsFalse(ctrl.AnyStalledThreads());
Join(waitThreads);
// now stall threads and wake them up again
ctrl.UpdateStalled(true);
waitThreads = WaitThreads(AtLeast(1), ctrl);
Start(waitThreads);
AwaitState(ThreadState.WaitSleepJoin, waitThreads);
Assert.IsTrue(ctrl.HasBlocked());
Assert.IsTrue(ctrl.AnyStalledThreads());
ctrl.UpdateStalled(false);
Assert.IsFalse(ctrl.AnyStalledThreads());
Join(waitThreads);
}
[Test]
public virtual void TestRandom()
{
DocumentsWriterStallControl ctrl = new DocumentsWriterStallControl();
ctrl.UpdateStalled(false);
ThreadClass[] stallThreads = new ThreadClass[AtLeast(3)];
for (int i = 0; i < stallThreads.Length; i++)
{
int stallProbability = 1 + Random().Next(10);
stallThreads[i] = new ThreadAnonymousInnerClassHelper(ctrl, stallProbability);
}
Start(stallThreads);
long time = Environment.TickCount;
/*
* use a 100 sec timeout to make sure we not hang forever. join will fail in
* that case
*/
while ((Environment.TickCount - time) < 100 * 1000 && !Terminated(stallThreads))
{
ctrl.UpdateStalled(false);
if (Random().NextBoolean())
{
Thread.@Yield();
}
else
{
Thread.Sleep(1);
}
}
Join(stallThreads);
}
private class ThreadAnonymousInnerClassHelper : ThreadClass
{
private DocumentsWriterStallControl Ctrl;
private int StallProbability;
public ThreadAnonymousInnerClassHelper(DocumentsWriterStallControl ctrl, int stallProbability)
{
this.Ctrl = ctrl;
this.StallProbability = stallProbability;
}
public override void Run()
{
int iters = AtLeast(1000);
for (int j = 0; j < iters; j++)
{
Ctrl.UpdateStalled(Random().Next(StallProbability) == 0);
if (Random().Next(5) == 0) // thread 0 only updates
{
Ctrl.WaitIfStalled();
}
}
}
}
[Test]
public virtual void TestAccquireReleaseRace()
{
DocumentsWriterStallControl ctrl = new DocumentsWriterStallControl();
ctrl.UpdateStalled(false);
AtomicBoolean stop = new AtomicBoolean(false);
AtomicBoolean checkPoint = new AtomicBoolean(true);
int numStallers = AtLeast(1);
int numReleasers = AtLeast(1);
int numWaiters = AtLeast(1);
var sync = new Synchronizer(numStallers + numReleasers, numStallers + numReleasers + numWaiters);
var threads = new ThreadClass[numReleasers + numStallers + numWaiters];
IList<Exception> exceptions = new SynchronizedCollection<Exception>();
for (int i = 0; i < numReleasers; i++)
{
threads[i] = new Updater(stop, checkPoint, ctrl, sync, true, exceptions);
}
for (int i = numReleasers; i < numReleasers + numStallers; i++)
{
threads[i] = new Updater(stop, checkPoint, ctrl, sync, false, exceptions);
}
for (int i = numReleasers + numStallers; i < numReleasers + numStallers + numWaiters; i++)
{
threads[i] = new Waiter(stop, checkPoint, ctrl, sync, exceptions);
}
Start(threads);
int iters = AtLeast(10000);
float checkPointProbability = TEST_NIGHTLY ? 0.5f : 0.1f;
for (int i = 0; i < iters; i++)
{
if (checkPoint.Get())
{
Assert.IsTrue(sync.UpdateJoin.@await(new TimeSpan(0, 0, 0, 10)), "timed out waiting for update threads - deadlock?");
if (exceptions.Count > 0)
{
foreach (Exception throwable in exceptions)
{
Console.WriteLine(throwable.ToString());
Console.Write(throwable.StackTrace);
}
Assert.Fail("got exceptions in threads");
}
if (ctrl.HasBlocked() && ctrl.Healthy)
{
AssertState(numReleasers, numStallers, numWaiters, threads, ctrl);
}
checkPoint.Set(false);
sync.Waiter.countDown();
sync.LeftCheckpoint.@await();
}
Assert.IsFalse(checkPoint.Get());
Assert.AreEqual(0, sync.Waiter.Remaining);
if (checkPointProbability >= (float)Random().NextDouble())
{
sync.Reset(numStallers + numReleasers, numStallers + numReleasers + numWaiters);
checkPoint.Set(true);
}
}
if (!checkPoint.Get())
{
sync.Reset(numStallers + numReleasers, numStallers + numReleasers + numWaiters);
checkPoint.Set(true);
}
Assert.IsTrue(sync.UpdateJoin.@await(new TimeSpan(0, 0, 0, 10)));
AssertState(numReleasers, numStallers, numWaiters, threads, ctrl);
checkPoint.Set(false);
stop.Set(true);
sync.Waiter.countDown();
sync.LeftCheckpoint.@await();
for (int i = 0; i < threads.Length; i++)
{
ctrl.UpdateStalled(false);
threads[i].Join(2000);
if (threads[i].IsAlive && threads[i] is Waiter)
{
if (threads[i].State == ThreadState.WaitSleepJoin)
{
Assert.Fail("waiter is not released - anyThreadsStalled: " + ctrl.AnyStalledThreads());
}
}
}
}
private void AssertState(int numReleasers, int numStallers, int numWaiters, ThreadClass[] threads, DocumentsWriterStallControl ctrl)
{
int millisToSleep = 100;
while (true)
{
if (ctrl.HasBlocked() && ctrl.Healthy)
{
for (int n = numReleasers + numStallers; n < numReleasers + numStallers + numWaiters; n++)
{
if (ctrl.IsThreadQueued(threads[n]))
{
if (millisToSleep < 60000)
{
Thread.Sleep(millisToSleep);
millisToSleep *= 2;
break;
}
else
{
Assert.Fail("control claims no stalled threads but waiter seems to be blocked ");
}
}
}
break;
}
else
{
break;
}
}
}
public class Waiter : ThreadClass
{
internal Synchronizer Sync;
internal DocumentsWriterStallControl Ctrl;
internal AtomicBoolean CheckPoint;
internal AtomicBoolean Stop;
internal IList<Exception> Exceptions;
public Waiter(AtomicBoolean stop, AtomicBoolean checkPoint, DocumentsWriterStallControl ctrl, Synchronizer sync, IList<Exception> exceptions)
: base("waiter")
{
this.Stop = stop;
this.CheckPoint = checkPoint;
this.Ctrl = ctrl;
this.Sync = sync;
this.Exceptions = exceptions;
}
public override void Run()
{
try
{
while (!Stop.Get())
{
Ctrl.WaitIfStalled();
if (CheckPoint.Get())
{
try
{
Assert.IsTrue(Sync.@await());
}
catch (ThreadInterruptedException e)
{
Console.WriteLine("[Waiter] got interrupted - wait count: " + Sync.Waiter.Remaining);
throw new ThreadInterruptedException("Thread Interrupted Exception", e);
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
Console.Write(e.StackTrace);
Exceptions.Add(e);
}
}
}
public class Updater : ThreadClass
{
internal Synchronizer Sync;
internal DocumentsWriterStallControl Ctrl;
internal AtomicBoolean CheckPoint;
internal AtomicBoolean Stop;
internal bool Release;
internal IList<Exception> Exceptions;
public Updater(AtomicBoolean stop, AtomicBoolean checkPoint, DocumentsWriterStallControl ctrl, Synchronizer sync, bool release, IList<Exception> exceptions)
: base("updater")
{
this.Stop = stop;
this.CheckPoint = checkPoint;
this.Ctrl = ctrl;
this.Sync = sync;
this.Release = release;
this.Exceptions = exceptions;
}
public override void Run()
{
try
{
while (!Stop.Get())
{
int internalIters = Release && Random().NextBoolean() ? AtLeast(5) : 1;
for (int i = 0; i < internalIters; i++)
{
Ctrl.UpdateStalled(Random().NextBoolean());
}
if (CheckPoint.Get())
{
Sync.UpdateJoin.countDown();
try
{
Assert.IsTrue(Sync.@await());
}
catch (ThreadInterruptedException e)
{
Console.WriteLine("[Updater] got interrupted - wait count: " + Sync.Waiter.Remaining);
throw new ThreadInterruptedException("Thread Interrupted Exception", e);
}
Sync.LeftCheckpoint.countDown();
}
if (Random().NextBoolean())
{
Thread.@Yield();
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
Console.Write(e.StackTrace);
Exceptions.Add(e);
}
Sync.UpdateJoin.countDown();
}
}
public static bool Terminated(ThreadClass[] threads)
{
foreach (ThreadClass thread in threads)
{
if (ThreadState.Stopped != thread.State)
{
return false;
}
}
return true;
}
public static void Start(ThreadClass[] tostart)
{
foreach (ThreadClass thread in tostart)
{
thread.Start();
}
Thread.Sleep(1); // let them start
}
public static void Join(ThreadClass[] toJoin)
{
foreach (ThreadClass thread in toJoin)
{
thread.Join();
}
}
public static ThreadClass[] WaitThreads(int num, DocumentsWriterStallControl ctrl)
{
ThreadClass[] array = new ThreadClass[num];
for (int i = 0; i < array.Length; i++)
{
array[i] = new ThreadAnonymousInnerClassHelper2(ctrl);
}
return array;
}
private class ThreadAnonymousInnerClassHelper2 : ThreadClass
{
private DocumentsWriterStallControl Ctrl;
public ThreadAnonymousInnerClassHelper2(DocumentsWriterStallControl ctrl)
{
this.Ctrl = ctrl;
}
public override void Run()
{
Ctrl.WaitIfStalled();
}
}
/// <summary>
/// Waits for all incoming threads to be in wait()
/// methods.
/// </summary>
public static void AwaitState(ThreadState state, params ThreadClass[] threads)
{
while (true)
{
bool done = true;
foreach (ThreadClass thread in threads)
{
if (thread.State != state)
{
done = false;
break;
}
}
if (done)
{
return;
}
if (Random().NextBoolean())
{
Thread.@Yield();
}
else
{
Thread.Sleep(1);
}
}
}
public sealed class Synchronizer
{
internal volatile CountDownLatch Waiter;
internal volatile CountDownLatch UpdateJoin;
internal volatile CountDownLatch LeftCheckpoint;
public Synchronizer(int numUpdater, int numThreads)
{
Reset(numUpdater, numThreads);
}
public void Reset(int numUpdaters, int numThreads)
{
this.Waiter = new CountDownLatch(1);
this.UpdateJoin = new CountDownLatch(numUpdaters);
this.LeftCheckpoint = new CountDownLatch(numUpdaters);
}
public bool @await()
{
return Waiter.@await(new TimeSpan(0, 0, 0, 10));
}
}
}
}
| |
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE
file for terms.
*/
// [AUTO_HEADER]
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Globalization;
namespace TakaoPreference
{
partial class PanelPhonetic : UserControl
{
private Dictionary<string, string> m_phoneticDictionary;
private Dictionary<string, string> m_smartPhoneticDictionary;
private Button u_applyButton;
private bool m_isLoading = false;
public PanelPhonetic(Dictionary<string, string> dictionary, Dictionary<string, string> smartPhoneticDictionary, Button button)
{
InitializeComponent();
this.m_phoneticDictionary = dictionary;
this.m_smartPhoneticDictionary = smartPhoneticDictionary;
this.u_applyButton = button;
this.InitUI();
}
#region Init
/// <summary>
/// Initailizing the User Interface of the Phonetic Input Method Setting preferencePane;
/// </summary>
private void InitUI()
{
this.m_isLoading = true;
string locale = CultureInfo.CurrentCulture.Name;
string selectionKeys;
this.m_smartPhoneticDictionary.TryGetValue("CandidateSelectionKeys", out selectionKeys);
if ((selectionKeys == null )|| (selectionKeys.Length == 0))
selectionKeys = "12345678";
bool found = false;
for (int i = 0; i < this.u_selectionKeyComboBox.Items.Count; i++)
{
if (this.u_selectionKeyComboBox.Items[i].ToString() == selectionKeys)
{
this.u_selectionKeyComboBox.SelectedIndex = i;
this.u_selectionKeyComboBox.Text = selectionKeys;
found = true;
break;
}
}
if (!found)
{
this.u_selectionKeyComboBox.SelectedIndex = 0;
this.u_selectionKeyComboBox.Text = "12345678";
}
string keyboardLayout;
this.m_smartPhoneticDictionary.TryGetValue("KeyboardLayout", out keyboardLayout);
if (keyboardLayout.Equals("ETen"))
{
this.u_smartPhonetickeyboardLayoutComboBox.SelectedIndex = 1;
this.u_smartPhonetickeyboardLayoutComboBox.Text = this.u_smartPhonetickeyboardLayoutComboBox.Items[1].ToString();
}
else if (keyboardLayout.Equals("Hanyu Pinyin"))
{
this.u_smartPhonetickeyboardLayoutComboBox.SelectedIndex = 2;
this.u_smartPhonetickeyboardLayoutComboBox.Text = this.u_smartPhonetickeyboardLayoutComboBox.Items[2].ToString();
}
else if (keyboardLayout.Equals("bpmfdtnlvkhgvcgycjqwsexuaorwiqzpmntlhfjkd") ||
keyboardLayout.Equals("ETen26"))
{
string other = "Other";
if (locale.Equals("zh-TW"))
other = "\u5176\u4ed6";
else if (locale.Equals("zh-CN"))
other = "\u5176\u4ed6";
this.u_smartPhonetickeyboardLayoutComboBox.Items.Add(other);
this.u_smartPhonetickeyboardLayoutComboBox.SelectedIndex = 3;
this.u_smartPhonetickeyboardLayoutComboBox.Text = other;
}
else if (keyboardLayout.Equals("bpmfdtnlgkhjvcjvcrzasexuyhgeiawomnklldfjs") ||
keyboardLayout.Equals("Hsu"))
{
string other = "Other";
if (locale.Equals("zh-TW"))
other = "\u5176\u4ed6";
else if (locale.Equals("zh-CN"))
other = "\u5176\u4ed6";
this.u_smartPhonetickeyboardLayoutComboBox.Items.Add(other);
this.u_smartPhonetickeyboardLayoutComboBox.SelectedIndex = 3;
this.u_smartPhonetickeyboardLayoutComboBox.Text = other;
}
else if (keyboardLayout.Equals("Standard"))
{
this.u_smartPhonetickeyboardLayoutComboBox.SelectedIndex = 0;
this.u_smartPhonetickeyboardLayoutComboBox.Text = this.u_smartPhonetickeyboardLayoutComboBox.Items[0].ToString();
}
else
{
this.u_smartPhonetickeyboardLayoutComboBox.SelectedIndex = 0;
this.u_traditionalPhoneticKeyboardLayoutComboBox.Text = this.u_traditionalPhoneticKeyboardLayoutComboBox.Items[0].ToString();
}
this. m_phoneticDictionary.TryGetValue("KeyboardLayout", out keyboardLayout);
if (keyboardLayout.Equals("ETen"))
{
this.u_traditionalPhoneticKeyboardLayoutComboBox.SelectedIndex = 1;
this.u_traditionalPhoneticKeyboardLayoutComboBox.Text = this.u_traditionalPhoneticKeyboardLayoutComboBox.Items[1].ToString();
}
else if (keyboardLayout.Equals("Hanyu Pinyin"))
{
this.u_traditionalPhoneticKeyboardLayoutComboBox.SelectedIndex = 2;
this.u_traditionalPhoneticKeyboardLayoutComboBox.Text = this.u_traditionalPhoneticKeyboardLayoutComboBox.Items[2].ToString();
}
else if (keyboardLayout.Equals("bpmfdtnlvkhgvcgycjqwsexuaorwiqzpmntlhfjkd") ||
keyboardLayout.Equals("ETen26"))
{
string other = "Other";
if (locale.Equals("zh-TW"))
other = "\u5176\u4ed6";
else if (locale.Equals("zh-CN"))
other = "\u5176\u4ed6";
this.u_traditionalPhoneticKeyboardLayoutComboBox.Items.Add(other);
this.u_traditionalPhoneticKeyboardLayoutComboBox.SelectedIndex = 3;
this.u_traditionalPhoneticKeyboardLayoutComboBox.Text = other;
}
else if (keyboardLayout.Equals("bpmfdtnlgkhjvcjvcrzasexuyhgeiawomnklldfjs") ||
keyboardLayout.Equals("Hsu"))
{
string other = "Other";
if (locale.Equals("zh-TW"))
other = "\u5176\u4ed6";
else if (locale.Equals("zh-CN"))
other = "\u5176\u4ed6";
this.u_traditionalPhoneticKeyboardLayoutComboBox.Items.Add(other);
this.u_traditionalPhoneticKeyboardLayoutComboBox.SelectedIndex = 3;
this.u_traditionalPhoneticKeyboardLayoutComboBox.Text = other;
}
else if (keyboardLayout.Equals("Standard"))
{
this.u_traditionalPhoneticKeyboardLayoutComboBox.SelectedIndex = 0;
this.u_traditionalPhoneticKeyboardLayoutComboBox.Text = this.u_traditionalPhoneticKeyboardLayoutComboBox.Items[0].ToString();
}
else
{
this.u_traditionalPhoneticKeyboardLayoutComboBox.SelectedIndex = 0;
this.u_traditionalPhoneticKeyboardLayoutComboBox.Text = this.u_traditionalPhoneticKeyboardLayoutComboBox.Items[0].ToString();
}
string buffer;
this.m_smartPhoneticDictionary.TryGetValue("ShowCandidateListWithSpace", out buffer);
if (buffer != null && buffer == "true")
this.u_showCandidateWithSpaceCheckBox.Checked = true;
else
this.u_showCandidateWithSpaceCheckBox.Checked = false;
this.m_smartPhoneticDictionary.TryGetValue("ClearComposingTextWithEsc", out buffer);
if (buffer != null && buffer == "true")
this.u_clearWithEscCheckBox.Checked = true;
else
this.u_clearWithEscCheckBox.Checked = false;
string allUnicode;
this.m_smartPhoneticDictionary.TryGetValue("UseCharactersSupportedByEncoding", out allUnicode);
if (allUnicode != null && allUnicode == "")
this.u_smartPhoneticNonBig5CheckBox.Checked = true;
else
this.u_smartPhoneticNonBig5CheckBox.Checked = false;
this.m_phoneticDictionary.TryGetValue("UseCharactersSupportedByEncoding", out allUnicode);
if (allUnicode != null && allUnicode == "")
this.u_traditionalPhoneticNonBig5CheckBox.Checked = true;
else
this.u_traditionalPhoneticNonBig5CheckBox.Checked = false;
this.m_smartPhoneticDictionary.TryGetValue("ComposingTextBufferSize", out buffer);
this.u_bufferSizeNumericUpDown.Value = Convert.ToDecimal(buffer);
if (this.u_bufferSizeNumericUpDown.Value < 10)
this.u_bufferSizeNumericUpDown.Value = 10;
this.m_isLoading = false;
}
#endregion
#region Event Handlers
/// <summary>
/// Handle toggling enable or disable full unicode support.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ChangeSmartPhoneticUseNonBig5(object sender, EventArgs e)
{
try
{
this.m_smartPhoneticDictionary.Remove("UseCharactersSupportedByEncoding");
}
catch { }
if (this.u_smartPhoneticNonBig5CheckBox.Checked == true)
this.m_smartPhoneticDictionary.Add("UseCharactersSupportedByEncoding", "");
else
this.m_smartPhoneticDictionary.Add("UseCharactersSupportedByEncoding", "BIG-5");
this.u_applyButton.Enabled = true;
}
private void ChangeTraditionalPhoneticUseNonBig5(object sender, EventArgs e)
{
try
{
this.m_phoneticDictionary.Remove("UseCharactersSupportedByEncoding");
}
catch { }
if (this.u_traditionalPhoneticNonBig5CheckBox.Checked == true)
this.m_phoneticDictionary.Add("UseCharactersSupportedByEncoding", "");
else
this.m_phoneticDictionary.Add("UseCharactersSupportedByEncoding", "BIG-5");
this.u_applyButton.Enabled = true;
}
private void ChangeClearWithEscCheckBox(object sender, EventArgs e)
{
try
{
this.m_smartPhoneticDictionary.Remove("ClearComposingTextWithEsc");
}
catch { }
if (this.u_clearWithEscCheckBox.Checked == true)
this.m_smartPhoneticDictionary.Add("ClearComposingTextWithEsc", "true");
else
this.m_smartPhoneticDictionary.Add("ClearComposingTextWithEsc", "false");
this.u_applyButton.Enabled = true;
}
private void ChangeShowCandidateWithSpaceCheckBox(object sender, EventArgs e)
{
try
{
this.m_smartPhoneticDictionary.Remove("ShowCandidateListWithSpace");
}
catch
{ }
if (this.u_showCandidateWithSpaceCheckBox.Checked == true)
this.m_smartPhoneticDictionary.Add("ShowCandidateListWithSpace", "true");
else
this.m_smartPhoneticDictionary.Add("ShowCandidateListWithSpace", "false");
this.u_applyButton.Enabled = true;
}
private bool ValidateSelectionKeySet(string selectionKey)
{
int i;
for (i = 0; i < selectionKey.Length - 1; i++)
{
char currentChar = selectionKey[i];
int j;
for (j = i + 1; j < selectionKey.Length; j++)
{
char checkChar = selectionKey[j];
if (currentChar == checkChar)
return false;
}
}
return true;
}
private void UpdateSelectionKey()
{
string selectionKey = u_selectionKeyComboBox.Text;
if (this.ValidateSelectionKeySet(selectionKey) == false)
selectionKey = "12345678";
else if (selectionKey.Length < 8)
selectionKey = "12345678";
else if (selectionKey.Length > 8)
selectionKey = selectionKey.Remove(8, selectionKey.Length - 8);
this.u_selectionKeyComboBox.Text = selectionKey;
try
{
this.m_smartPhoneticDictionary.Remove("CandidateSelectionKeys");
}
catch { }
this.m_smartPhoneticDictionary.Add("CandidateSelectionKeys", selectionKey);
this.u_applyButton.Enabled = true;
}
private void ChangeSelectionKey(object sender, EventArgs e)
{
this.UpdateSelectionKey();
}
private void KeyInNewSelectionKey(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
this.UpdateSelectionKey();
}
#endregion
private void ShowExtraSelectionKeySets(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
this.u_selectionKeyComboBox.Items.Clear();
this.u_selectionKeyComboBox.Items.AddRange(new object[] {
"12345678", "asdfghjk", "asdfzxcv", "aoeuidht", "aoeu;qjk"
});
this.u_selectionKeyComboBox.SelectedIndex = 0;
this.u_selectionKeyComboBox.Text = u_selectionKeyComboBox.Items[0].ToString();
}
}
private void ChangeBufferSize(object sender, EventArgs e)
{
string bufferSize = u_bufferSizeNumericUpDown.Value.ToString();
try
{
this.m_smartPhoneticDictionary.Remove("ComposingTextBufferSize");
}
catch { }
try
{
this.m_smartPhoneticDictionary.Add("ComposingTextBufferSize", bufferSize);
}
catch { }
this.u_applyButton.Enabled = true;
}
private void ChangeSmartPhoneticKeyboardLayout(object sender, EventArgs e)
{
if (this.m_isLoading)
return;
if (sender != this.u_smartPhonetickeyboardLayoutComboBox)
return;
try
{
this.m_smartPhoneticDictionary.Remove("KeyboardLayout");
}
catch { }
string keyboardLayout = "";
switch (this.u_smartPhonetickeyboardLayoutComboBox.SelectedIndex)
{
case 0:
keyboardLayout = "Stanard";
break;
case 1:
keyboardLayout = "ETen";
break;
case 2:
keyboardLayout = "Hanyu Pinyin";
break;
case 3:
if (this.u_smartPhonetickeyboardLayoutComboBox.Items.Count < 5)
return;
keyboardLayout = "ETen26";
break;
case 4:
keyboardLayout = "Hsu";
break;
default:
break;
}
try
{
this.m_smartPhoneticDictionary.Add("KeyboardLayout", keyboardLayout);
}
catch { }
this.u_applyButton.Enabled = true;
}
private void ChangeTraditionalPhoneticKeyboardLayout(object sender, EventArgs e)
{
if (this.m_isLoading)
return;
if (sender != this.u_traditionalPhoneticKeyboardLayoutComboBox)
return;
try
{
this.m_phoneticDictionary.Remove("KeyboardLayout");
}
catch { }
string keyboardLayout = "";
switch (this.u_traditionalPhoneticKeyboardLayoutComboBox.SelectedIndex)
{
case 0:
keyboardLayout = "Stanard";
break;
case 1:
keyboardLayout = "ETen";
break;
case 2:
keyboardLayout = "Hanyu Pinyin";
break;
case 3:
if (this.u_traditionalPhoneticKeyboardLayoutComboBox.Items.Count < 5)
return;
keyboardLayout = "ETen26";
break;
case 4:
keyboardLayout = "Hsu";
break;
default:
keyboardLayout = "Stanard";
break;
}
try
{
this.m_phoneticDictionary.Add("KeyboardLayout", keyboardLayout);
}
catch { }
this.u_applyButton.Enabled = true;
}
private void ShowExtraKeyboardLayouts(object sender, EventArgs e)
{
string locale = CultureInfo.CurrentCulture.Name;
List<string> extraKeyboardLayoutList = new List<string>();
if (locale.Equals("zh-TW"))
extraKeyboardLayoutList.AddRange(new string[] { "\u6a19\u6e96", "\u501a\u5929", "\u6f22\u8a9e\u62fc\u97f3", "\u501a\u5929 26 \u9375", "\u8a31\u6c0f\u9375\u76e4" });
else if (locale.Equals("zh-CN"))
extraKeyboardLayoutList.AddRange(new string[] { "\u6807\u51c6", "\u501a\u5929", "\u6c49\u8bed\u62fc\u97f3", "\u501a\u5929 26 \u952e", "\u8bb8\u6c0f\u952e\u76d8" });
else
extraKeyboardLayoutList.AddRange(new string[] { "Standard", "Eten", "Hanyu Pinyin", "Eten 26", "Hsu" });
this.u_smartPhonetickeyboardLayoutComboBox.Items.Clear();
this.u_smartPhonetickeyboardLayoutComboBox.Items.AddRange(extraKeyboardLayoutList.ToArray());
this.u_smartPhonetickeyboardLayoutComboBox.SelectedIndex = 0;
this.u_smartPhonetickeyboardLayoutComboBox.Text = this.u_smartPhonetickeyboardLayoutComboBox.Items[0].ToString();
this.u_traditionalPhoneticKeyboardLayoutComboBox.Items.Clear();
this.u_traditionalPhoneticKeyboardLayoutComboBox.Items.AddRange(extraKeyboardLayoutList.ToArray());
this.u_traditionalPhoneticKeyboardLayoutComboBox.SelectedIndex = 0;
this.u_traditionalPhoneticKeyboardLayoutComboBox.Text = this.u_traditionalPhoneticKeyboardLayoutComboBox.Items[0].ToString();
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
public abstract class Generator : MonoBehaviour {
protected int Seed;
// Adjustable variables for Unity Inspector
[Header("Generator Values")]
[SerializeField]
protected int Width = 512;
[SerializeField]
protected int Height = 512;
[Header("Height Map")]
[SerializeField]
protected int TerrainOctaves = 6;
[SerializeField]
protected double TerrainFrequency = 1.25;
[SerializeField]
protected float DeepWater = 0.2f;
[SerializeField]
protected float ShallowWater = 0.4f;
[SerializeField]
protected float Sand = 0.5f;
[SerializeField]
protected float Grass = 0.7f;
[SerializeField]
protected float Forest = 0.8f;
[SerializeField]
protected float Rock = 0.9f;
[Header("Heat Map")]
[SerializeField]
protected int HeatOctaves = 4;
[SerializeField]
protected double HeatFrequency = 3.0;
[SerializeField]
protected float ColdestValue = 0.05f;
[SerializeField]
protected float ColderValue = 0.18f;
[SerializeField]
protected float ColdValue = 0.4f;
[SerializeField]
protected float WarmValue = 0.6f;
[SerializeField]
protected float WarmerValue = 0.8f;
[Header("Moisture Map")]
[SerializeField]
protected int MoistureOctaves = 4;
[SerializeField]
protected double MoistureFrequency = 3.0;
[SerializeField]
protected float DryerValue = 0.27f;
[SerializeField]
protected float DryValue = 0.4f;
[SerializeField]
protected float WetValue = 0.6f;
[SerializeField]
protected float WetterValue = 0.8f;
[SerializeField]
protected float WettestValue = 0.9f;
[Header("Rivers")]
[SerializeField]
protected int RiverCount = 40;
[SerializeField]
protected float MinRiverHeight = 0.6f;
[SerializeField]
protected int MaxRiverAttempts = 1000;
[SerializeField]
protected int MinRiverTurns = 18;
[SerializeField]
protected int MinRiverLength = 20;
[SerializeField]
protected int MaxRiverIntersections = 2;
protected MapData HeightData;
protected MapData HeatData;
protected MapData MoistureData;
protected MapData Clouds1;
protected MapData Clouds2;
protected Tile[,] Tiles;
protected List<TileGroup> Waters = new List<TileGroup> ();
protected List<TileGroup> Lands = new List<TileGroup> ();
protected List<River> Rivers = new List<River>();
protected List<RiverGroup> RiverGroups = new List<RiverGroup>();
// Our texture output gameobject
protected MeshRenderer HeightMapRenderer;
protected MeshRenderer HeatMapRenderer;
protected MeshRenderer MoistureMapRenderer;
protected MeshRenderer BiomeMapRenderer;
protected BiomeType[,] BiomeTable = new BiomeType[6,6] {
//COLDEST //COLDER //COLD //HOT //HOTTER //HOTTEST
{ BiomeType.Ice, BiomeType.Tundra, BiomeType.Grassland, BiomeType.Desert, BiomeType.Desert, BiomeType.Desert }, //DRYEST
{ BiomeType.Ice, BiomeType.Tundra, BiomeType.Grassland, BiomeType.Desert, BiomeType.Desert, BiomeType.Desert }, //DRYER
{ BiomeType.Ice, BiomeType.Tundra, BiomeType.Woodland, BiomeType.Woodland, BiomeType.Savanna, BiomeType.Savanna }, //DRY
{ BiomeType.Ice, BiomeType.Tundra, BiomeType.BorealForest, BiomeType.Woodland, BiomeType.Savanna, BiomeType.Savanna }, //WET
{ BiomeType.Ice, BiomeType.Tundra, BiomeType.BorealForest, BiomeType.SeasonalForest, BiomeType.TropicalRainforest, BiomeType.TropicalRainforest }, //WETTER
{ BiomeType.Ice, BiomeType.Tundra, BiomeType.BorealForest, BiomeType.TemperateRainforest, BiomeType.TropicalRainforest, BiomeType.TropicalRainforest } //WETTEST
};
void Start()
{
Instantiate ();
Generate ();
}
protected abstract void Initialize();
protected abstract void GetData();
protected abstract Tile GetTop(Tile tile);
protected abstract Tile GetBottom(Tile tile);
protected abstract Tile GetLeft(Tile tile);
protected abstract Tile GetRight(Tile tile);
protected virtual void Instantiate () {
Seed = UnityEngine.Random.Range (0, int.MaxValue);
HeightMapRenderer = transform.Find ("HeightTexture").GetComponent<MeshRenderer> ();
HeatMapRenderer = transform.Find ("HeatTexture").GetComponent<MeshRenderer> ();
MoistureMapRenderer = transform.Find ("MoistureTexture").GetComponent<MeshRenderer> ();
BiomeMapRenderer = transform.Find ("BiomeTexture").GetComponent<MeshRenderer> ();
Initialize ();
}
protected virtual void Generate()
{
GetData ();
LoadTiles ();
UpdateNeighbors ();
GenerateRivers ();
BuildRiverGroups ();
DigRiverGroups ();
AdjustMoistureMap ();
UpdateBitmasks ();
FloodFill ();
GenerateBiomeMap ();
UpdateBiomeBitmask();
HeightMapRenderer.materials [0].mainTexture = TextureGenerator.GetHeightMapTexture (Width, Height, Tiles);
HeatMapRenderer.materials[0].mainTexture = TextureGenerator.GetHeatMapTexture (Width, Height, Tiles);
MoistureMapRenderer.materials[0].mainTexture = TextureGenerator.GetMoistureMapTexture (Width, Height, Tiles);
BiomeMapRenderer.materials[0].mainTexture = TextureGenerator.GetBiomeMapTexture (Width, Height, Tiles, ColdestValue, ColderValue, ColdValue);
}
void Update()
{
// Refresh with inspector values
if (Input.GetKeyDown (KeyCode.F5)) {
Seed = UnityEngine.Random.Range(0, int.MaxValue);
Initialize();
Generate();
}
}
private void UpdateBiomeBitmask()
{
for (var x = 0; x < Width; x++) {
for (var y = 0; y < Height; y++) {
Tiles [x, y].UpdateBiomeBitmask ();
}
}
}
public BiomeType GetBiomeType(Tile tile)
{
return BiomeTable [(int)tile.MoistureType, (int)tile.HeatType];
}
private void GenerateBiomeMap()
{
for (var x = 0; x < Width; x++) {
for (var y = 0; y < Height; y++) {
if (!Tiles[x, y].Collidable) continue;
Tile t = Tiles[x,y];
t.BiomeType = GetBiomeType(t);
}
}
}
private void AddMoisture(Tile t, int radius)
{
int startx = MathHelper.Mod (t.X - radius, Width);
int endx = MathHelper.Mod (t.X + radius, Width);
Vector2 center = new Vector2(t.X, t.Y);
int curr = radius;
while (curr > 0) {
int x1 = MathHelper.Mod (t.X - curr, Width);
int x2 = MathHelper.Mod (t.X + curr, Width);
int y = t.Y;
AddMoisture(Tiles[x1, y], 0.025f / (center - new Vector2(x1, y)).magnitude);
for (int i = 0; i < curr; i++)
{
AddMoisture (Tiles[x1, MathHelper.Mod (y + i + 1, Height)], 0.025f / (center - new Vector2(x1, MathHelper.Mod (y + i + 1, Height))).magnitude);
AddMoisture (Tiles[x1, MathHelper.Mod (y - (i + 1), Height)], 0.025f / (center - new Vector2(x1, MathHelper.Mod (y - (i + 1), Height))).magnitude);
AddMoisture (Tiles[x2, MathHelper.Mod (y + i + 1, Height)], 0.025f / (center - new Vector2(x2, MathHelper.Mod (y + i + 1, Height))).magnitude);
AddMoisture (Tiles[x2, MathHelper.Mod (y - (i + 1), Height)], 0.025f / (center - new Vector2(x2, MathHelper.Mod (y - (i + 1), Height))).magnitude);
}
curr--;
}
}
private void AddMoisture(Tile t, float amount)
{
MoistureData.Data[t.X, t.Y] += amount;
t.MoistureValue += amount;
if (t.MoistureValue > 1)
t.MoistureValue = 1;
//set moisture type
if (t.MoistureValue < DryerValue) t.MoistureType = MoistureType.Dryest;
else if (t.MoistureValue < DryValue) t.MoistureType = MoistureType.Dryer;
else if (t.MoistureValue < WetValue) t.MoistureType = MoistureType.Dry;
else if (t.MoistureValue < WetterValue) t.MoistureType = MoistureType.Wet;
else if (t.MoistureValue < WettestValue) t.MoistureType = MoistureType.Wetter;
else t.MoistureType = MoistureType.Wettest;
}
private void AdjustMoistureMap()
{
for (var x = 0; x < Width; x++) {
for (var y = 0; y < Height; y++) {
Tile t = Tiles[x,y];
if (t.HeightType == HeightType.River)
{
AddMoisture (t, (int)60);
}
}
}
}
private void DigRiverGroups()
{
for (int i = 0; i < RiverGroups.Count; i++) {
RiverGroup group = RiverGroups[i];
River longest = null;
//Find longest river in this group
for (int j = 0; j < group.Rivers.Count; j++)
{
River river = group.Rivers[j];
if (longest == null)
longest = river;
else if (longest.Tiles.Count < river.Tiles.Count)
longest = river;
}
if (longest != null)
{
//Dig out longest path first
DigRiver (longest);
for (int j = 0; j < group.Rivers.Count; j++)
{
River river = group.Rivers[j];
if (river != longest)
{
DigRiver (river, longest);
}
}
}
}
}
private void BuildRiverGroups()
{
//loop each tile, checking if it belongs to multiple rivers
for (var x = 0; x < Width; x++) {
for (var y = 0; y < Height; y++) {
Tile t = Tiles[x,y];
if (t.Rivers.Count > 1)
{
// multiple rivers == intersection
RiverGroup group = null;
// Does a rivergroup already exist for this group?
for (int n=0; n < t.Rivers.Count; n++)
{
River tileriver = t.Rivers[n];
for (int i = 0; i < RiverGroups.Count; i++)
{
for (int j = 0; j < RiverGroups[i].Rivers.Count; j++)
{
River river = RiverGroups[i].Rivers[j];
if (river.ID == tileriver.ID)
{
group = RiverGroups[i];
}
if (group != null) break;
}
if (group != null) break;
}
if (group != null) break;
}
// existing group found -- add to it
if (group != null)
{
for (int n=0; n < t.Rivers.Count; n++)
{
if (!group.Rivers.Contains(t.Rivers[n]))
group.Rivers.Add(t.Rivers[n]);
}
}
else //No existing group found - create a new one
{
group = new RiverGroup();
for (int n=0; n < t.Rivers.Count; n++)
{
group.Rivers.Add(t.Rivers[n]);
}
RiverGroups.Add (group);
}
}
}
}
}
public float GetHeightValue(Tile tile)
{
if (tile == null)
return int.MaxValue;
else
return tile.HeightValue;
}
private void GenerateRivers()
{
int attempts = 0;
int rivercount = RiverCount;
Rivers = new List<River> ();
// Generate some rivers
while (rivercount > 0 && attempts < MaxRiverAttempts) {
// Get a random tile
int x = UnityEngine.Random.Range (0, Width);
int y = UnityEngine.Random.Range (0, Height);
Tile tile = Tiles[x,y];
// validate the tile
if (!tile.Collidable) continue;
if (tile.Rivers.Count > 0) continue;
if (tile.HeightValue > MinRiverHeight)
{
// Tile is good to start river from
River river = new River(rivercount);
// Figure out the direction this river will try to flow
river.CurrentDirection = tile.GetLowestNeighbor (this);
// Recursively find a path to water
FindPathToWater(tile, river.CurrentDirection, ref river);
// Validate the generated river
if (river.TurnCount < MinRiverTurns || river.Tiles.Count < MinRiverLength || river.Intersections > MaxRiverIntersections)
{
//Validation failed - remove this river
for (int i = 0; i < river.Tiles.Count; i++)
{
Tile t = river.Tiles[i];
t.Rivers.Remove (river);
}
}
else if (river.Tiles.Count >= MinRiverLength)
{
//Validation passed - Add river to list
Rivers.Add (river);
tile.Rivers.Add (river);
rivercount--;
}
}
attempts++;
}
}
// Dig river based on a parent river vein
private void DigRiver(River river, River parent)
{
int intersectionID = 0;
int intersectionSize = 0;
// determine point of intersection
for (int i = 0; i < river.Tiles.Count; i++) {
Tile t1 = river.Tiles[i];
for (int j = 0; j < parent.Tiles.Count; j++) {
Tile t2 = parent.Tiles[j];
if (t1 == t2)
{
intersectionID = i;
intersectionSize = t2.RiverSize;
}
}
}
int counter = 0;
int intersectionCount = river.Tiles.Count - intersectionID;
int size = UnityEngine.Random.Range(intersectionSize, 5);
river.Length = river.Tiles.Count;
// randomize size change
int two = river.Length / 2;
int three = two / 2;
int four = three / 2;
int five = four / 2;
int twomin = two / 3;
int threemin = three / 3;
int fourmin = four / 3;
int fivemin = five / 3;
// randomize length of each size
int count1 = UnityEngine.Random.Range (fivemin, five);
if (size < 4) {
count1 = 0;
}
int count2 = count1 + UnityEngine.Random.Range(fourmin, four);
if (size < 3) {
count2 = 0;
count1 = 0;
}
int count3 = count2 + UnityEngine.Random.Range(threemin, three);
if (size < 2) {
count3 = 0;
count2 = 0;
count1 = 0;
}
int count4 = count3 + UnityEngine.Random.Range (twomin, two);
// Make sure we are not digging past the river path
if (count4 > river.Length) {
int extra = count4 - river.Length;
while (extra > 0)
{
if (count1 > 0) { count1--; count2--; count3--; count4--; extra--; }
else if (count2 > 0) { count2--; count3--; count4--; extra--; }
else if (count3 > 0) { count3--; count4--; extra--; }
else if (count4 > 0) { count4--; extra--; }
}
}
// adjust size of river at intersection point
if (intersectionSize == 1) {
count4 = intersectionCount;
count1 = 0;
count2 = 0;
count3 = 0;
} else if (intersectionSize == 2) {
count3 = intersectionCount;
count1 = 0;
count2 = 0;
} else if (intersectionSize == 3) {
count2 = intersectionCount;
count1 = 0;
} else if (intersectionSize == 4) {
count1 = intersectionCount;
} else {
count1 = 0;
count2 = 0;
count3 = 0;
count4 = 0;
}
// dig out the river
for (int i = river.Tiles.Count - 1; i >= 0; i--) {
Tile t = river.Tiles [i];
if (counter < count1) {
t.DigRiver (river, 4);
} else if (counter < count2) {
t.DigRiver (river, 3);
} else if (counter < count3) {
t.DigRiver (river, 2);
}
else if ( counter < count4) {
t.DigRiver (river, 1);
}
else {
t.DigRiver (river, 0);
}
counter++;
}
}
// Dig river
private void DigRiver(River river)
{
int counter = 0;
// How wide are we digging this river?
int size = UnityEngine.Random.Range(1,5);
river.Length = river.Tiles.Count;
// randomize size change
int two = river.Length / 2;
int three = two / 2;
int four = three / 2;
int five = four / 2;
int twomin = two / 3;
int threemin = three / 3;
int fourmin = four / 3;
int fivemin = five / 3;
// randomize lenght of each size
int count1 = UnityEngine.Random.Range (fivemin, five);
if (size < 4) {
count1 = 0;
}
int count2 = count1 + UnityEngine.Random.Range(fourmin, four);
if (size < 3) {
count2 = 0;
count1 = 0;
}
int count3 = count2 + UnityEngine.Random.Range(threemin, three);
if (size < 2) {
count3 = 0;
count2 = 0;
count1 = 0;
}
int count4 = count3 + UnityEngine.Random.Range (twomin, two);
// Make sure we are not digging past the river path
if (count4 > river.Length) {
int extra = count4 - river.Length;
while (extra > 0)
{
if (count1 > 0) { count1--; count2--; count3--; count4--; extra--; }
else if (count2 > 0) { count2--; count3--; count4--; extra--; }
else if (count3 > 0) { count3--; count4--; extra--; }
else if (count4 > 0) { count4--; extra--; }
}
}
// Dig it out
for (int i = river.Tiles.Count - 1; i >= 0 ; i--)
{
Tile t = river.Tiles[i];
if (counter < count1) {
t.DigRiver (river, 4);
}
else if (counter < count2) {
t.DigRiver (river, 3);
}
else if (counter < count3) {
t.DigRiver (river, 2);
}
else if ( counter < count4) {
t.DigRiver (river, 1);
}
else {
t.DigRiver(river, 0);
}
counter++;
}
}
private void FindPathToWater(Tile tile, Direction direction, ref River river)
{
if (tile.Rivers.Contains (river))
return;
// check if there is already a river on this tile
if (tile.Rivers.Count > 0)
river.Intersections++;
river.AddTile (tile);
// get neighbors
Tile left = GetLeft (tile);
Tile right = GetRight (tile);
Tile top = GetTop (tile);
Tile bottom = GetBottom (tile);
float leftValue = int.MaxValue;
float rightValue = int.MaxValue;
float topValue = int.MaxValue;
float bottomValue = int.MaxValue;
// query height values of neighbors
if (left != null && left.GetRiverNeighborCount(river) < 2 && !river.Tiles.Contains(left))
leftValue = left.HeightValue;
if (right != null && right.GetRiverNeighborCount(river) < 2 && !river.Tiles.Contains(right))
rightValue = right.HeightValue;
if (top != null && top.GetRiverNeighborCount(river) < 2 && !river.Tiles.Contains(top))
topValue = top.HeightValue;
if (bottom != null && bottom.GetRiverNeighborCount(river) < 2 && !river.Tiles.Contains(bottom))
bottomValue = bottom.HeightValue;
// if neighbor is existing river that is not this one, flow into it
if (bottom != null && bottom.Rivers.Count == 0 && !bottom.Collidable)
bottomValue = 0;
if (top != null && top.Rivers.Count == 0 && !top.Collidable)
topValue = 0;
if (left != null && left.Rivers.Count == 0 && !left.Collidable)
leftValue = 0;
if (right != null && right.Rivers.Count == 0 && !right.Collidable)
rightValue = 0;
// override flow direction if a tile is significantly lower
if (direction == Direction.Left)
if (Mathf.Abs (rightValue - leftValue) < 0.1f)
rightValue = int.MaxValue;
if (direction == Direction.Right)
if (Mathf.Abs (rightValue - leftValue) < 0.1f)
leftValue = int.MaxValue;
if (direction == Direction.Top)
if (Mathf.Abs (topValue - bottomValue) < 0.1f)
bottomValue = int.MaxValue;
if (direction == Direction.Bottom)
if (Mathf.Abs (topValue - bottomValue) < 0.1f)
topValue = int.MaxValue;
// find mininum
float min = Mathf.Min (Mathf.Min (Mathf.Min (leftValue, rightValue), topValue), bottomValue);
// if no minimum found - exit
if (min == int.MaxValue)
return;
//Move to next neighbor
if (min == leftValue) {
if (left != null && left.Collidable)
{
if (river.CurrentDirection != Direction.Left){
river.TurnCount++;
river.CurrentDirection = Direction.Left;
}
FindPathToWater (left, direction, ref river);
}
} else if (min == rightValue) {
if (right != null && right.Collidable)
{
if (river.CurrentDirection != Direction.Right){
river.TurnCount++;
river.CurrentDirection = Direction.Right;
}
FindPathToWater (right, direction, ref river);
}
} else if (min == bottomValue) {
if (bottom != null && bottom.Collidable)
{
if (river.CurrentDirection != Direction.Bottom){
river.TurnCount++;
river.CurrentDirection = Direction.Bottom;
}
FindPathToWater (bottom, direction, ref river);
}
} else if (min == topValue) {
if (top != null && top.Collidable)
{
if (river.CurrentDirection != Direction.Top){
river.TurnCount++;
river.CurrentDirection = Direction.Top;
}
FindPathToWater (top, direction, ref river);
}
}
}
// Build a Tile array from our data
private void LoadTiles()
{
Tiles = new Tile[Width, Height];
for (var x = 0; x < Width; x++)
{
for (var y = 0; y < Height; y++)
{
Tile t = new Tile();
t.X = x;
t.Y = y;
//set heightmap value
float heightValue = HeightData.Data[x, y];
heightValue = (heightValue - HeightData.Min) / (HeightData.Max - HeightData.Min);
t.HeightValue = heightValue;
if (heightValue < DeepWater) {
t.HeightType = HeightType.DeepWater;
t.Collidable = false;
}
else if (heightValue < ShallowWater) {
t.HeightType = HeightType.ShallowWater;
t.Collidable = false;
}
else if (heightValue < Sand) {
t.HeightType = HeightType.Sand;
t.Collidable = true;
}
else if (heightValue < Grass) {
t.HeightType = HeightType.Grass;
t.Collidable = true;
}
else if (heightValue < Forest) {
t.HeightType = HeightType.Forest;
t.Collidable = true;
}
else if (heightValue < Rock) {
t.HeightType = HeightType.Rock;
t.Collidable = true;
}
else {
t.HeightType = HeightType.Snow;
t.Collidable = true;
}
//adjust moisture based on height
if (t.HeightType == HeightType.DeepWater) {
MoistureData.Data[t.X, t.Y] += 8f * t.HeightValue;
}
else if (t.HeightType == HeightType.ShallowWater) {
MoistureData.Data[t.X, t.Y] += 3f * t.HeightValue;
}
else if (t.HeightType == HeightType.Shore) {
MoistureData.Data[t.X, t.Y] += 1f * t.HeightValue;
}
else if (t.HeightType == HeightType.Sand) {
MoistureData.Data[t.X, t.Y] += 0.2f * t.HeightValue;
}
//Moisture Map Analyze
float moistureValue = MoistureData.Data[x,y];
moistureValue = (moistureValue - MoistureData.Min) / (MoistureData.Max - MoistureData.Min);
t.MoistureValue = moistureValue;
//set moisture type
if (moistureValue < DryerValue) t.MoistureType = MoistureType.Dryest;
else if (moistureValue < DryValue) t.MoistureType = MoistureType.Dryer;
else if (moistureValue < WetValue) t.MoistureType = MoistureType.Dry;
else if (moistureValue < WetterValue) t.MoistureType = MoistureType.Wet;
else if (moistureValue < WettestValue) t.MoistureType = MoistureType.Wetter;
else t.MoistureType = MoistureType.Wettest;
// Adjust Heat Map based on Height - Higher == colder
if (t.HeightType == HeightType.Forest) {
HeatData.Data[t.X, t.Y] -= 0.1f * t.HeightValue;
}
else if (t.HeightType == HeightType.Rock) {
HeatData.Data[t.X, t.Y] -= 0.25f * t.HeightValue;
}
else if (t.HeightType == HeightType.Snow) {
HeatData.Data[t.X, t.Y] -= 0.4f * t.HeightValue;
}
else {
HeatData.Data[t.X, t.Y] += 0.01f * t.HeightValue;
}
// Set heat value
float heatValue = HeatData.Data[x,y];
heatValue = (heatValue - HeatData.Min) / (HeatData.Max - HeatData.Min);
t.HeatValue = heatValue;
// set heat type
if (heatValue < ColdestValue) t.HeatType = HeatType.Coldest;
else if (heatValue < ColderValue) t.HeatType = HeatType.Colder;
else if (heatValue < ColdValue) t.HeatType = HeatType.Cold;
else if (heatValue < WarmValue) t.HeatType = HeatType.Warm;
else if (heatValue < WarmerValue) t.HeatType = HeatType.Warmer;
else t.HeatType = HeatType.Warmest;
if (Clouds1 != null)
{
t.Cloud1Value = Clouds1.Data[x, y];
t.Cloud1Value = (t.Cloud1Value - Clouds1.Min) / (Clouds1.Max - Clouds1.Min);
}
if (Clouds2 != null)
{
t.Cloud2Value = Clouds2.Data[x, y];
t.Cloud2Value = (t.Cloud2Value - Clouds2.Min) / (Clouds2.Max - Clouds2.Min);
}
Tiles[x,y] = t;
}
}
}
private void UpdateNeighbors()
{
for (var x = 0; x < Width; x++)
{
for (var y = 0; y < Height; y++)
{
Tile t = Tiles[x,y];
t.Top = GetTop(t);
t.Bottom = GetBottom (t);
t.Left = GetLeft (t);
t.Right = GetRight (t);
}
}
}
private void UpdateBitmasks()
{
for (var x = 0; x < Width; x++) {
for (var y = 0; y < Height; y++) {
Tiles [x, y].UpdateBitmask ();
}
}
}
private void FloodFill()
{
// Use a stack instead of recursion
Stack<Tile> stack = new Stack<Tile>();
for (int x = 0; x < Width; x++) {
for (int y = 0; y < Height; y++) {
Tile t = Tiles[x,y];
//Tile already flood filled, skip
if (t.FloodFilled) continue;
// Land
if (t.Collidable)
{
TileGroup group = new TileGroup();
group.Type = TileGroupType.Land;
stack.Push(t);
while(stack.Count > 0) {
FloodFill(stack.Pop(), ref group, ref stack);
}
if (group.Tiles.Count > 0)
Lands.Add (group);
}
// Water
else {
TileGroup group = new TileGroup();
group.Type = TileGroupType.Water;
stack.Push(t);
while(stack.Count > 0) {
FloodFill(stack.Pop(), ref group, ref stack);
}
if (group.Tiles.Count > 0)
Waters.Add (group);
}
}
}
}
private void FloodFill(Tile tile, ref TileGroup tiles, ref Stack<Tile> stack)
{
// Validate
if (tile == null)
return;
if (tile.FloodFilled)
return;
if (tiles.Type == TileGroupType.Land && !tile.Collidable)
return;
if (tiles.Type == TileGroupType.Water && tile.Collidable)
return;
// Add to TileGroup
tiles.Tiles.Add (tile);
tile.FloodFilled = true;
// floodfill into neighbors
Tile t = GetTop (tile);
if (t != null && !t.FloodFilled && tile.Collidable == t.Collidable)
stack.Push (t);
t = GetBottom (tile);
if (t != null && !t.FloodFilled && tile.Collidable == t.Collidable)
stack.Push (t);
t = GetLeft (tile);
if (t != null && !t.FloodFilled && tile.Collidable == t.Collidable)
stack.Push (t);
t = GetRight (tile);
if (t != null && !t.FloodFilled && tile.Collidable == t.Collidable)
stack.Push (t);
}
}
| |
// 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;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO
{
/*
* This class is used to access a contiguous block of memory, likely outside
* the GC heap (or pinned in place in the GC heap, but a MemoryStream may
* make more sense in those cases). It's great if you have a pointer and
* a length for a section of memory mapped in by someone else and you don't
* want to copy this into the GC heap. UnmanagedMemoryStream assumes these
* two things:
*
* 1) All the memory in the specified block is readable or writable,
* depending on the values you pass to the constructor.
* 2) The lifetime of the block of memory is at least as long as the lifetime
* of the UnmanagedMemoryStream.
* 3) You clean up the memory when appropriate. The UnmanagedMemoryStream
* currently will do NOTHING to free this memory.
* 4) All calls to Write and WriteByte may not be threadsafe currently.
*
* It may become necessary to add in some sort of
* DeallocationMode enum, specifying whether we unmap a section of memory,
* call free, run a user-provided delegate to free the memory, etc.
* We'll suggest user write a subclass of UnmanagedMemoryStream that uses
* a SafeHandle subclass to hold onto the memory.
*
*/
/// <summary>
/// Stream over a memory pointer or over a SafeBuffer
/// </summary>
public class UnmanagedMemoryStream : Stream
{
private SafeBuffer _buffer;
private unsafe byte* _mem;
private long _length;
private long _capacity;
private long _position;
private long _offset;
private FileAccess _access;
private bool _isOpen;
private Task<Int32> _lastReadTask; // The last successful task returned from ReadAsync
/// <summary>
/// This code is copied from system\buffer.cs in mscorlib
/// </summary>
/// <param name="src"></param>
/// <param name="len"></param>
private unsafe static void ZeroMemory(byte* src, long len)
{
while (len-- > 0)
*(src + len) = 0;
}
/// <summary>
/// Creates a closed stream.
/// </summary>
// Needed for subclasses that need to map a file, etc.
protected UnmanagedMemoryStream()
{
unsafe
{
_mem = null;
}
_isOpen = false;
}
/// <summary>
/// Creates a stream over a SafeBuffer.
/// </summary>
/// <param name="buffer"></param>
/// <param name="offset"></param>
/// <param name="length"></param>
public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length)
{
Initialize(buffer, offset, length, FileAccess.Read, false);
}
/// <summary>
/// Creates a stream over a SafeBuffer.
/// </summary>
public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length, FileAccess access)
{
Initialize(buffer, offset, length, access, false);
}
/// <summary>
/// Subclasses must call this method (or the other overload) to properly initialize all instance fields.
/// </summary>
/// <param name="buffer"></param>
/// <param name="offset"></param>
/// <param name="length"></param>
/// <param name="access"></param>
protected void Initialize(SafeBuffer buffer, long offset, long length, FileAccess access)
{
Initialize(buffer, offset, length, access, false);
}
private void Initialize(SafeBuffer buffer, long offset, long length, FileAccess access, bool skipSecurityCheck)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.ByteLength < (ulong)(offset + length))
{
throw new ArgumentException(SR.Argument_InvalidSafeBufferOffLen);
}
if (access < FileAccess.Read || access > FileAccess.ReadWrite)
{
throw new ArgumentOutOfRangeException(nameof(access));
}
Contract.EndContractBlock();
if (_isOpen)
{
throw new InvalidOperationException(SR.InvalidOperation_CalledTwice);
}
// check for wraparound
unsafe
{
byte* pointer = null;
try
{
buffer.AcquirePointer(ref pointer);
if ((pointer + offset + length) < pointer)
{
throw new ArgumentException(SR.ArgumentOutOfRange_UnmanagedMemStreamWrapAround);
}
}
finally
{
if (pointer != null)
{
buffer.ReleasePointer();
}
}
}
_offset = offset;
_buffer = buffer;
_length = length;
_capacity = length;
_access = access;
_isOpen = true;
}
/// <summary>
/// Creates a stream over a byte*.
/// </summary>
[CLSCompliant(false)]
public unsafe UnmanagedMemoryStream(byte* pointer, long length)
{
Initialize(pointer, length, length, FileAccess.Read, false);
}
/// <summary>
/// Creates a stream over a byte*.
/// </summary>
[CLSCompliant(false)]
public unsafe UnmanagedMemoryStream(byte* pointer, long length, long capacity, FileAccess access)
{
Initialize(pointer, length, capacity, access, false);
}
/// <summary>
/// Subclasses must call this method (or the other overload) to properly initialize all instance fields.
/// </summary>
[CLSCompliant(false)]
protected unsafe void Initialize(byte* pointer, long length, long capacity, FileAccess access)
{
Initialize(pointer, length, capacity, access, false);
}
/// <summary>
/// Subclasses must call this method (or the other overload) to properly initialize all instance fields.
/// </summary>
private unsafe void Initialize(byte* pointer, long length, long capacity, FileAccess access, bool skipSecurityCheck)
{
if (pointer == null)
throw new ArgumentNullException(nameof(pointer));
if (length < 0 || capacity < 0)
throw new ArgumentOutOfRangeException(length < 0 ? nameof(length) : nameof(capacity), SR.ArgumentOutOfRange_NeedNonNegNum);
if (length > capacity)
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_LengthGreaterThanCapacity);
Contract.EndContractBlock();
// Check for wraparound.
if (((byte*)((long)pointer + capacity)) < pointer)
throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_UnmanagedMemStreamWrapAround);
if (access < FileAccess.Read || access > FileAccess.ReadWrite)
throw new ArgumentOutOfRangeException(nameof(access), SR.ArgumentOutOfRange_Enum);
if (_isOpen)
throw new InvalidOperationException(SR.InvalidOperation_CalledTwice);
_mem = pointer;
_offset = 0;
_length = length;
_capacity = capacity;
_access = access;
_isOpen = true;
}
/// <summary>
/// Returns true if the stream can be read; otherwise returns false.
/// </summary>
public override bool CanRead
{
[Pure]
get { return _isOpen && (_access & FileAccess.Read) != 0; }
}
/// <summary>
/// Returns true if the stream can seek; otherwise returns false.
/// </summary>
public override bool CanSeek
{
[Pure]
get { return _isOpen; }
}
/// <summary>
/// Returns true if the stream can be written to; otherwise returns false.
/// </summary>
public override bool CanWrite
{
[Pure]
get { return _isOpen && (_access & FileAccess.Write) != 0; }
}
/// <summary>
/// Closes the stream. The stream's memory needs to be dealt with separately.
/// </summary>
/// <param name="disposing"></param>
protected override void Dispose(bool disposing)
{
_isOpen = false;
unsafe { _mem = null; }
// Stream allocates WaitHandles for async calls. So for correctness
// call base.Dispose(disposing) for better perf, avoiding waiting
// for the finalizers to run on those types.
base.Dispose(disposing);
}
/// <summary>
/// Since it's a memory stream, this method does nothing.
/// </summary>
public override void Flush()
{
if (!_isOpen) throw Error.GetStreamIsClosed();
}
/// <summary>
/// Since it's a memory stream, this method does nothing specific.
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public override Task FlushAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
try
{
Flush();
return Task.CompletedTask;
}
catch (Exception ex)
{
return Task.FromException(ex);
}
}
/// <summary>
/// Number of bytes in the stream.
/// </summary>
public override long Length
{
get
{
if (!_isOpen) throw Error.GetStreamIsClosed();
return Interlocked.Read(ref _length);
}
}
/// <summary>
/// Number of bytes that can be written to the stream.
/// </summary>
public long Capacity
{
get
{
if (!_isOpen) throw Error.GetStreamIsClosed();
return _capacity;
}
}
/// <summary>
/// ReadByte will read byte at the Position in the stream
/// </summary>
public override long Position
{
get
{
if (!CanSeek) throw Error.GetStreamIsClosed();
Contract.EndContractBlock();
return Interlocked.Read(ref _position);
}
set
{
if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum);
if (!CanSeek) throw Error.GetStreamIsClosed();
Contract.EndContractBlock();
if (IntPtr.Size == 4)
{
unsafe
{
// On 32 bit process, ensure we don't wrap around.
if (value > (long)Int32.MaxValue || _mem + value < _mem)
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength);
}
}
Interlocked.Exchange(ref _position, value);
}
}
/// <summary>
/// Pointer to memory at the current Position in the stream.
/// </summary>
[CLSCompliant(false)]
public unsafe byte* PositionPointer
{
get
{
if (_buffer != null) throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer);
if (!_isOpen) throw Error.GetStreamIsClosed();
// Use a temp to avoid a race
long pos = Interlocked.Read(ref _position);
if (pos > _capacity) throw new IndexOutOfRangeException(SR.IndexOutOfRange_UMSPosition);
byte* ptr = _mem + pos;
return ptr;
}
set
{
if (_buffer != null) throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer);
if (!_isOpen) throw Error.GetStreamIsClosed();
if (value < _mem) throw new IOException(SR.IO_SeekBeforeBegin);
Interlocked.Exchange(ref _position, value - _mem);
}
}
/// <summary>
/// Reads bytes from stream and puts them into the buffer
/// </summary>
/// <param name="buffer">Buffer to read the bytes to.</param>
/// <param name="offset">Starting index in the buffer.</param>
/// <param name="count">Maximum number of bytes to read.</param>
/// <returns>Number of bytes actually read.</returns>
public override int Read(byte[] buffer, int offset, int count)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock(); // Keep this in sync with contract validation in ReadAsync
if (!_isOpen) throw Error.GetStreamIsClosed();
if (!CanRead) throw Error.GetReadNotSupported();
// Use a local variable to avoid a race where another thread
// changes our position after we decide we can read some bytes.
long pos = Interlocked.Read(ref _position);
long len = Interlocked.Read(ref _length);
long n = len - pos;
if (n > count)
n = count;
if (n <= 0)
return 0;
int nInt = (int)n; // Safe because n <= count, which is an Int32
if (nInt < 0)
return 0; // _position could be beyond EOF
Debug.Assert(pos + nInt >= 0, "_position + n >= 0"); // len is less than 2^63 -1.
unsafe
{
fixed (byte* pBuffer = buffer)
{
if (_buffer != null)
{
byte* pointer = null;
try
{
_buffer.AcquirePointer(ref pointer);
Buffer.Memmove(pBuffer + offset, pointer + pos + _offset, (uint)nInt);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
else
{
Buffer.Memmove(pBuffer + offset, _mem + pos, (uint)nInt);
}
}
}
Interlocked.Exchange(ref _position, pos + n);
return nInt;
}
/// <summary>
/// Reads bytes from stream and puts them into the buffer
/// </summary>
/// <param name="buffer">Buffer to read the bytes to.</param>
/// <param name="offset">Starting index in the buffer.</param>
/// <param name="count">Maximum number of bytes to read.</param>
/// <param name="cancellationToken">Token that can be used to cancel this operation.</param>
/// <returns>Task that can be used to access the number of bytes actually read.</returns>
public override Task<Int32> ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock(); // contract validation copied from Read(...)
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled<Int32>(cancellationToken);
try
{
Int32 n = Read(buffer, offset, count);
Task<Int32> t = _lastReadTask;
return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<Int32>(n));
}
catch (Exception ex)
{
Debug.Assert(!(ex is OperationCanceledException));
return Task.FromException<Int32>(ex);
}
}
/// <summary>
/// Returns the byte at the stream current Position and advances the Position.
/// </summary>
/// <returns></returns>
public override int ReadByte()
{
if (!_isOpen) throw Error.GetStreamIsClosed();
if (!CanRead) throw Error.GetReadNotSupported();
long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition
long len = Interlocked.Read(ref _length);
if (pos >= len)
return -1;
Interlocked.Exchange(ref _position, pos + 1);
int result;
if (_buffer != null)
{
unsafe
{
byte* pointer = null;
try
{
_buffer.AcquirePointer(ref pointer);
result = *(pointer + pos + _offset);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
}
else
{
unsafe
{
result = _mem[pos];
}
}
return result;
}
/// <summary>
/// Advanced the Position to specific location in the stream.
/// </summary>
/// <param name="offset">Offset from the loc parameter.</param>
/// <param name="loc">Origin for the offset parameter.</param>
/// <returns></returns>
public override long Seek(long offset, SeekOrigin loc)
{
if (!_isOpen) throw Error.GetStreamIsClosed();
switch (loc)
{
case SeekOrigin.Begin:
if (offset < 0)
throw new IOException(SR.IO_SeekBeforeBegin);
Interlocked.Exchange(ref _position, offset);
break;
case SeekOrigin.Current:
long pos = Interlocked.Read(ref _position);
if (offset + pos < 0)
throw new IOException(SR.IO_SeekBeforeBegin);
Interlocked.Exchange(ref _position, offset + pos);
break;
case SeekOrigin.End:
long len = Interlocked.Read(ref _length);
if (len + offset < 0)
throw new IOException(SR.IO_SeekBeforeBegin);
Interlocked.Exchange(ref _position, len + offset);
break;
default:
throw new ArgumentException(SR.Argument_InvalidSeekOrigin);
}
long finalPos = Interlocked.Read(ref _position);
Debug.Assert(finalPos >= 0, "_position >= 0");
return finalPos;
}
/// <summary>
/// Sets the Length of the stream.
/// </summary>
/// <param name="value"></param>
public override void SetLength(long value)
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
if (_buffer != null)
throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer);
if (!_isOpen) throw Error.GetStreamIsClosed();
if (!CanWrite) throw Error.GetWriteNotSupported();
if (value > _capacity)
throw new IOException(SR.IO_FixedCapacity);
long pos = Interlocked.Read(ref _position);
long len = Interlocked.Read(ref _length);
if (value > len)
{
unsafe
{
ZeroMemory(_mem + len, value - len);
}
}
Interlocked.Exchange(ref _length, value);
if (pos > value)
{
Interlocked.Exchange(ref _position, value);
}
}
/// <summary>
/// Writes buffer into the stream
/// </summary>
/// <param name="buffer">Buffer that will be written.</param>
/// <param name="offset">Starting index in the buffer.</param>
/// <param name="count">Number of bytes to write.</param>
public override void Write(byte[] buffer, int offset, int count)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock(); // Keep contract validation in sync with WriteAsync(..)
if (!_isOpen) throw Error.GetStreamIsClosed();
if (!CanWrite) throw Error.GetWriteNotSupported();
long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition
long len = Interlocked.Read(ref _length);
long n = pos + count;
// Check for overflow
if (n < 0)
throw new IOException(SR.IO_StreamTooLong);
if (n > _capacity)
{
throw new NotSupportedException(SR.IO_FixedCapacity);
}
if (_buffer == null)
{
// Check to see whether we are now expanding the stream and must
// zero any memory in the middle.
if (pos > len)
{
unsafe
{
ZeroMemory(_mem + len, pos - len);
}
}
// set length after zeroing memory to avoid race condition of accessing unzeroed memory
if (n > len)
{
Interlocked.Exchange(ref _length, n);
}
}
unsafe
{
fixed (byte* pBuffer = buffer)
{
if (_buffer != null)
{
long bytesLeft = _capacity - pos;
if (bytesLeft < count)
{
throw new ArgumentException(SR.Arg_BufferTooSmall);
}
byte* pointer = null;
try
{
_buffer.AcquirePointer(ref pointer);
Buffer.Memmove(pointer + pos + _offset, pBuffer + offset, (uint)count);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
else
{
Buffer.Memmove(_mem + pos, pBuffer + offset, (uint)count);
}
}
}
Interlocked.Exchange(ref _position, n);
return;
}
/// <summary>
/// Writes buffer into the stream. The operation completes synchronously.
/// </summary>
/// <param name="buffer">Buffer that will be written.</param>
/// <param name="offset">Starting index in the buffer.</param>
/// <param name="count">Number of bytes to write.</param>
/// <param name="cancellationToken">Token that can be used to cancel the operation.</param>
/// <returns>Task that can be awaited </returns>
public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock(); // contract validation copied from Write(..)
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
try
{
Write(buffer, offset, count);
return Task.CompletedTask;
}
catch (Exception ex)
{
Debug.Assert(!(ex is OperationCanceledException));
return Task.FromException(ex);
}
}
/// <summary>
/// Writes a byte to the stream and advances the current Position.
/// </summary>
/// <param name="value"></param>
public override void WriteByte(byte value)
{
if (!_isOpen) throw Error.GetStreamIsClosed();
if (!CanWrite) throw Error.GetWriteNotSupported();
long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition
long len = Interlocked.Read(ref _length);
long n = pos + 1;
if (pos >= len)
{
// Check for overflow
if (n < 0)
throw new IOException(SR.IO_StreamTooLong);
if (n > _capacity)
throw new NotSupportedException(SR.IO_FixedCapacity);
// Check to see whether we are now expanding the stream and must
// zero any memory in the middle.
// don't do if created from SafeBuffer
if (_buffer == null)
{
if (pos > len)
{
unsafe
{
ZeroMemory(_mem + len, pos - len);
}
}
// set length after zeroing memory to avoid race condition of accessing unzeroed memory
Interlocked.Exchange(ref _length, n);
}
}
if (_buffer != null)
{
unsafe
{
byte* pointer = null;
try
{
_buffer.AcquirePointer(ref pointer);
*(pointer + pos + _offset) = value;
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
}
else
{
unsafe
{
_mem[pos] = value;
}
}
Interlocked.Exchange(ref _position, n);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.