context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsAzureResource
{
using Fixtures.Azure;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Resource Flattening for AutoRest
/// </summary>
public partial class AutoRestResourceFlatteningTestServiceClient : ServiceClient<AutoRestResourceFlatteningTestServiceClient>, IAutoRestResourceFlatteningTestServiceClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Initializes a new instance of the AutoRestResourceFlatteningTestServiceClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoRestResourceFlatteningTestServiceClient(params DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestResourceFlatteningTestServiceClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoRestResourceFlatteningTestServiceClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestResourceFlatteningTestServiceClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected AutoRestResourceFlatteningTestServiceClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestResourceFlatteningTestServiceClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected AutoRestResourceFlatteningTestServiceClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestResourceFlatteningTestServiceClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestResourceFlatteningTestServiceClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestResourceFlatteningTestServiceClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestResourceFlatteningTestServiceClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestResourceFlatteningTestServiceClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestResourceFlatteningTestServiceClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestResourceFlatteningTestServiceClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestResourceFlatteningTestServiceClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
BaseUri = new System.Uri("http://localhost");
AcceptLanguage = "en-US";
LongRunningOperationRetryTimeout = 30;
GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
/// <summary>
/// Put External Resource as an Array
/// <see href="http://tempuri.org" />
/// </summary>
/// <param name='resourceArray'>
/// External Resource as an Array to put
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PutArrayWithHttpMessagesAsync(IList<Resource> resourceArray = default(IList<Resource>), 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("resourceArray", resourceArray);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutArray", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azure/resource-flatten/array").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (GenerateClientRequestId != null && GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(resourceArray != null)
{
_requestContent = SafeJsonConvert.SerializeObject(resourceArray, 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 (Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get External Resource as an Array
/// <see href="http://tempuri.org" />
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IList<FlattenedProduct>>> GetArrayWithHttpMessagesAsync(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, "GetArray", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azure/resource-flatten/array").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (GenerateClientRequestId != null && GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, 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<IList<FlattenedProduct>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<IList<FlattenedProduct>>(_responseContent, DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put External Resource as a Dictionary
/// <see href="http://tempuri.org" />
/// </summary>
/// <param name='resourceDictionary'>
/// External Resource as a Dictionary to put
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PutDictionaryWithHttpMessagesAsync(IDictionary<string, FlattenedProduct> resourceDictionary = default(IDictionary<string, FlattenedProduct>), 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("resourceDictionary", resourceDictionary);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutDictionary", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azure/resource-flatten/dictionary").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (GenerateClientRequestId != null && GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(resourceDictionary != null)
{
_requestContent = SafeJsonConvert.SerializeObject(resourceDictionary, 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 (Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get External Resource as a Dictionary
/// <see href="http://tempuri.org" />
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IDictionary<string, FlattenedProduct>>> GetDictionaryWithHttpMessagesAsync(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, "GetDictionary", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azure/resource-flatten/dictionary").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (GenerateClientRequestId != null && GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, 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<IDictionary<string, FlattenedProduct>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<IDictionary<string, FlattenedProduct>>(_responseContent, DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put External Resource as a ResourceCollection
/// <see href="http://tempuri.org" />
/// </summary>
/// <param name='resourceComplexObject'>
/// External Resource as a ResourceCollection to put
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PutResourceCollectionWithHttpMessagesAsync(ResourceCollection resourceComplexObject = default(ResourceCollection), 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("resourceComplexObject", resourceComplexObject);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutResourceCollection", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azure/resource-flatten/resourcecollection").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (GenerateClientRequestId != null && GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(resourceComplexObject != null)
{
_requestContent = SafeJsonConvert.SerializeObject(resourceComplexObject, 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 (Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get External Resource as a ResourceCollection
/// <see href="http://tempuri.org" />
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ResourceCollection>> GetResourceCollectionWithHttpMessagesAsync(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, "GetResourceCollection", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azure/resource-flatten/resourcecollection").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (GenerateClientRequestId != null && GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, 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<ResourceCollection>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<ResourceCollection>(_responseContent, DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="ColumnInfo.cs" company="Microsoft Corporation">
// Copyright (c) 1999, Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>
// Part of the Deployment Tools Foundation project.
// </summary>
//---------------------------------------------------------------------
namespace Microsoft.PackageManagement.Msi.Internal.Deployment.WindowsInstaller
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Text;
/// <summary>
/// Defines a single column of a table in an installer database.
/// </summary>
/// <remarks>Once created, a ColumnInfo object is immutable.</remarks>
internal class ColumnInfo
{
private string name;
private Type type;
private int size;
private bool isRequired;
private bool isTemporary;
private bool isLocalizable;
/// <summary>
/// Creates a new ColumnInfo object from a column definition.
/// </summary>
/// <param name="name">name of the column</param>
/// <param name="columnDefinition">column definition string</param>
/// <seealso cref="ColumnDefinitionString"/>
public ColumnInfo(string name, string columnDefinition)
: this(name, typeof(String), 0, false, false, false)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
if (columnDefinition == null)
{
throw new ArgumentNullException("columnDefinition");
}
switch (Char.ToLower(columnDefinition[0], CultureInfo.InvariantCulture))
{
case 'i': this.type = typeof(Int32);
break;
case 'j': this.type = typeof(Int32); this.isTemporary = true;
break;
case 'g': this.type = typeof(String); this.isTemporary = true;
break;
case 'l': this.type = typeof(String); this.isLocalizable = true;
break;
case 's': this.type = typeof(String);
break;
case 'v': this.type = typeof(Stream);
break;
default: throw new InstallerException();
}
this.isRequired = Char.IsLower(columnDefinition[0]);
this.size = Int32.Parse(
columnDefinition.Substring(1),
CultureInfo.InvariantCulture.NumberFormat);
if (this.type == typeof(Int32) && this.size <= 2)
{
this.type = typeof(Int16);
}
}
/// <summary>
/// Creates a new ColumnInfo object from a list of parameters.
/// </summary>
/// <param name="name">name of the column</param>
/// <param name="type">type of the column; must be one of the following:
/// Int16, Int32, String, or Stream</param>
/// <param name="size">the maximum number of characters for String columns;
/// ignored for other column types</param>
/// <param name="isRequired">true if the column is required to have a non-null value</param>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public ColumnInfo(string name, Type type, int size, bool isRequired)
: this(name, type, size, isRequired, false, false)
{
}
/// <summary>
/// Creates a new ColumnInfo object from a list of parameters.
/// </summary>
/// <param name="name">name of the column</param>
/// <param name="type">type of the column; must be one of the following:
/// Int16, Int32, String, or Stream</param>
/// <param name="size">the maximum number of characters for String columns;
/// ignored for other column types</param>
/// <param name="isRequired">true if the column is required to have a non-null value</param>
/// <param name="isTemporary">true to if the column is only in-memory and
/// not persisted with the database</param>
/// <param name="isLocalizable">for String columns, indicates the column
/// is localizable; ignored for other column types</param>
public ColumnInfo(string name, Type type, int size, bool isRequired, bool isTemporary, bool isLocalizable)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
if (type == typeof(Int32))
{
size = 4;
isLocalizable = false;
}
else if (type == typeof(Int16))
{
size = 2;
isLocalizable = false;
}
else if (type == typeof(String))
{
}
else if (type == typeof(Stream))
{
isLocalizable = false;
}
else
{
throw new ArgumentOutOfRangeException("type");
}
this.name = name;
this.type = type;
this.size = size;
this.isRequired = isRequired;
this.isTemporary = isTemporary;
this.isLocalizable = isLocalizable;
}
/// <summary>
/// Gets the name of the column.
/// </summary>
/// <value>name of the column</value>
public string Name
{
get { return this.name; }
}
/// <summary>
/// Gets the type of the column as a System.Type. This is one of the following: Int16, Int32, String, or Stream
/// </summary>
/// <value>type of the column</value>
[SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")]
public Type Type
{
get { return this.type; }
}
/// <summary>
/// Gets the type of the column as an integer that can be cast to a System.Data.DbType. This is one of the following: Int16, Int32, String, or Binary
/// </summary>
/// <value>equivalent DbType of the column as an integer</value>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public int DBType
{
get
{
if (this.type == typeof(Int16)) return 10;
else if (this.type == typeof(Int32)) return 11;
else if (this.type == typeof(Stream)) return 1;
else return 16;
}
}
/// <summary>
/// Gets the size of the column.
/// </summary>
/// <value>The size of integer columns this is either 2 or 4. For string columns this is the maximum
/// recommended length of the string, or 0 for unlimited length. For stream columns, 0 is returned.</value>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public int Size
{
get { return this.size; }
}
/// <summary>
/// Gets a value indicating whether the column must be non-null when inserting a record.
/// </summary>
/// <value>required status of the column</value>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public bool IsRequired
{
get { return this.isRequired; }
}
/// <summary>
/// Gets a value indicating whether the column is temporary. Temporary columns are not persisted
/// when the database is saved to disk.
/// </summary>
/// <value>temporary status of the column</value>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public bool IsTemporary
{
get { return this.isTemporary; }
}
/// <summary>
/// Gets a value indicating whether the column is a string column that is localizable.
/// </summary>
/// <value>localizable status of the column</value>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public bool IsLocalizable
{
get { return this.isLocalizable; }
}
/// <summary>
/// Gets an SQL fragment that can be used to create this column within a CREATE TABLE statement.
/// </summary>
/// <value>SQL fragment to be used for creating the column</value>
/// <remarks><p>
/// Examples:
/// <list type="bullet">
/// <item>LONG</item>
/// <item>SHORT TEMPORARY</item>
/// <item>CHAR(0) LOCALIZABLE</item>
/// <item>CHAR(72) NOT NULL LOCALIZABLE</item>
/// <item>OBJECT</item>
/// </list>
/// </p></remarks>
public string SqlCreateString
{
get
{
StringBuilder s = new StringBuilder();
s.AppendFormat("`{0}` ", this.name);
if (this.type == typeof(Int16)) s.Append("SHORT");
else if (this.type == typeof(Int32)) s.Append("LONG");
else if (this.type == typeof(String)) s.AppendFormat("CHAR({0})", this.size);
else s.Append("OBJECT");
if (this.isRequired) s.Append(" NOT NULL");
if (this.isTemporary) s.Append(" TEMPORARY");
if (this.isLocalizable) s.Append(" LOCALIZABLE");
return s.ToString();
}
}
/// <summary>
/// Gets a short string defining the type and size of the column.
/// </summary>
/// <value>
/// The definition string consists
/// of a single letter representing the data type followed by the width of the column (in characters
/// when applicable, bytes otherwise). A width of zero designates an unbounded width (for example,
/// long text fields and streams). An uppercase letter indicates that null values are allowed in
/// the column.
/// </value>
/// <remarks><p>
/// <list>
/// <item>s? - String, variable length (?=1-255)</item>
/// <item>s0 - String, variable length</item>
/// <item>i2 - Short integer</item>
/// <item>i4 - Long integer</item>
/// <item>v0 - Binary Stream</item>
/// <item>g? - Temporary string (?=0-255)</item>
/// <item>j? - Temporary integer (?=0,1,2,4)</item>
/// <item>l? - Localizable string, variable length (?=1-255)</item>
/// <item>l0 - Localizable string, variable length</item>
/// </list>
/// </p></remarks>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string ColumnDefinitionString
{
get
{
char t;
if (this.type == typeof(Int16) || this.type == typeof(Int32))
{
t = (this.isTemporary ? 'j' : 'i');
}
else if (this.type == typeof(String))
{
t = (this.isTemporary ? 'g' : this.isLocalizable ? 'l' : 's');
}
else
{
t = 'v';
}
return String.Format(
CultureInfo.InvariantCulture,
"{0}{1}",
(this.isRequired ? t : Char.ToUpper(t, CultureInfo.InvariantCulture)),
this.size);
}
}
/// <summary>
/// Gets the name of the column.
/// </summary>
/// <returns>Name of the column.</returns>
public override string ToString()
{
return this.Name;
}
}
}
| |
using System.Collections.Concurrent;
using System.Data;
using System.Data.Common;
using System.Net.Sockets;
using System.Reactive.Concurrency;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using Autofac;
using AutoMapper;
using Microsoft.Extensions.Hosting;
using Miningcore.Configuration;
using Miningcore.Contracts;
using Miningcore.Extensions;
using Miningcore.Messaging;
using Miningcore.Notifications.Messages;
using Miningcore.Persistence;
using Miningcore.Persistence.Model;
using Miningcore.Persistence.Repositories;
using Miningcore.Time;
using Miningcore.Util;
using NLog;
using Polly;
namespace Miningcore.Mining;
public class StatsRecorder : BackgroundService
{
public StatsRecorder(IComponentContext ctx,
IMasterClock clock,
IConnectionFactory cf,
IMessageBus messageBus,
IMapper mapper,
ClusterConfig clusterConfig,
IShareRepository shareRepo,
IStatsRepository statsRepo)
{
Contract.RequiresNonNull(ctx, nameof(ctx));
Contract.RequiresNonNull(clock, nameof(clock));
Contract.RequiresNonNull(cf, nameof(cf));
Contract.RequiresNonNull(messageBus, nameof(messageBus));
Contract.RequiresNonNull(mapper, nameof(mapper));
Contract.RequiresNonNull(shareRepo, nameof(shareRepo));
Contract.RequiresNonNull(statsRepo, nameof(statsRepo));
this.clock = clock;
this.cf = cf;
this.mapper = mapper;
this.messageBus = messageBus;
this.shareRepo = shareRepo;
this.statsRepo = statsRepo;
this.clusterConfig = clusterConfig;
updateInterval = TimeSpan.FromSeconds(clusterConfig.Statistics?.UpdateInterval ?? 120);
gcInterval = TimeSpan.FromHours(clusterConfig.Statistics?.GcInterval ?? 4);
hashrateCalculationWindow = TimeSpan.FromMinutes(clusterConfig.Statistics?.HashrateCalculationWindow ?? 10);
cleanupDays = TimeSpan.FromDays(clusterConfig.Statistics?.CleanupDays ?? 180);
BuildFaultHandlingPolicy();
}
private readonly IMasterClock clock;
private readonly IStatsRepository statsRepo;
private readonly IConnectionFactory cf;
private readonly IMapper mapper;
private readonly IMessageBus messageBus;
private readonly IShareRepository shareRepo;
private readonly ClusterConfig clusterConfig;
private readonly CompositeDisposable disposables = new();
private readonly ConcurrentDictionary<string, IMiningPool> pools = new();
private readonly TimeSpan updateInterval;
private readonly TimeSpan cleanupDays;
private readonly TimeSpan gcInterval;
private readonly TimeSpan hashrateCalculationWindow;
private const int RetryCount = 4;
private IAsyncPolicy readFaultPolicy;
private static readonly ILogger logger = LogManager.GetCurrentClassLogger();
private void AttachPool(IMiningPool pool)
{
pools.TryAdd(pool.Config.Id, pool);
}
private void OnPoolStatusNotification(PoolStatusNotification notification)
{
if(notification.Status == PoolStatus.Online)
AttachPool(notification.Pool);
}
private async Task UpdatePoolHashratesAsync(CancellationToken ct)
{
var now = clock.Now;
var timeFrom = now.Add(-hashrateCalculationWindow);
var stats = new MinerWorkerPerformanceStats
{
Created = now
};
foreach(var poolId in pools.Keys)
{
if(ct.IsCancellationRequested)
return;
stats.PoolId = poolId;
logger.Info(() => $"[{poolId}] Updating Statistics for pool");
var pool = pools[poolId];
// fetch stats for window
var result = await readFaultPolicy.ExecuteAsync(() =>
cf.Run(con => shareRepo.GetHashAccumulationBetweenCreatedAsync(con, poolId, timeFrom, now)));
var byMiner = result.GroupBy(x => x.Miner).ToArray();
if (result.Length > 0)
{
// pool miners
pool.PoolStats.ConnectedMiners = byMiner.Length; // update connected miners
// Stats calc windows
var timeFrameBeforeFirstShare = ((result.Min(x => x.FirstShare) - timeFrom).TotalSeconds);
var timeFrameAfterLastShare = ((now - result.Max(x => x.LastShare)).TotalSeconds);
var timeFrameFirstLastShare = (hashrateCalculationWindow.TotalSeconds - timeFrameBeforeFirstShare - timeFrameAfterLastShare);
//var poolHashTimeFrame = Math.Floor(TimeFrameFirstLastShare + (TimeFrameBeforeFirstShare / 3) + (TimeFrameAfterLastShare * 3)) ;
var poolHashTimeFrame = hashrateCalculationWindow.TotalSeconds;
// pool hashrate
var poolHashesAccumulated = result.Sum(x => x.Sum);
var poolHashrate = pool.HashrateFromShares(poolHashesAccumulated, poolHashTimeFrame);
poolHashrate = Math.Floor(poolHashrate);
pool.PoolStats.PoolHashrate = (ulong) poolHashrate;
// pool shares
var poolHashesCountAccumulated = result.Sum(x => x.Count);
pool.PoolStats.SharesPerSecond = (int) (poolHashesCountAccumulated / poolHashTimeFrame);
messageBus.NotifyHashrateUpdated(pool.Config.Id, poolHashrate);
}
else
{
// reset
pool.PoolStats.ConnectedMiners = 0;
pool.PoolStats.PoolHashrate = 0;
pool.PoolStats.SharesPerSecond = 0;
messageBus.NotifyHashrateUpdated(pool.Config.Id, 0);
logger.Info(() => $"[{poolId}] Reset performance stats for pool");
}
// persist
await cf.RunTx(async (con, tx) =>
{
var mapped = new Persistence.Model.PoolStats
{
PoolId = poolId,
Created = now
};
mapper.Map(pool.PoolStats, mapped);
mapper.Map(pool.NetworkStats, mapped);
await statsRepo.InsertPoolStatsAsync(con, tx, mapped);
});
// retrieve most recent miner/worker non-zero hashrate sample
var previousMinerWorkerHashrates = await cf.Run(con =>
statsRepo.GetPoolMinerWorkerHashratesAsync(con, poolId));
const char keySeparator = '.';
string BuildKey(string miner, string worker = null)
{
return !string.IsNullOrEmpty(worker) ? $"{miner}{keySeparator}{worker}" : miner;
}
var previousNonZeroMinerWorkers = new HashSet<string>(
previousMinerWorkerHashrates.Select(x => BuildKey(x.Miner, x.Worker)));
var currentNonZeroMinerWorkers = new HashSet<string>();
foreach (var minerHashes in byMiner)
{
if(ct.IsCancellationRequested)
return;
double minerTotalHashrate = 0;
await cf.RunTx(async (con, tx) =>
{
stats.Miner = minerHashes.Key;
// book keeping
currentNonZeroMinerWorkers.Add(BuildKey(stats.Miner));
foreach (var item in minerHashes)
{
// set default values
stats.Hashrate = 0;
stats.SharesPerSecond = 0;
// miner stats calculation windows
var timeFrameBeforeFirstShare = ((minerHashes.Min(x => x.FirstShare) - timeFrom).TotalSeconds);
var timeFrameAfterLastShare = ((now - minerHashes.Max(x => x.LastShare)).TotalSeconds);
var minerHashTimeFrame = hashrateCalculationWindow.TotalSeconds;
if(timeFrameBeforeFirstShare >= (hashrateCalculationWindow.TotalSeconds * 0.1) )
minerHashTimeFrame = Math.Floor(hashrateCalculationWindow.TotalSeconds - timeFrameBeforeFirstShare );
if(timeFrameAfterLastShare >= (hashrateCalculationWindow.TotalSeconds * 0.1) )
minerHashTimeFrame = Math.Floor(hashrateCalculationWindow.TotalSeconds + timeFrameAfterLastShare );
if( (timeFrameBeforeFirstShare >= (hashrateCalculationWindow.TotalSeconds * 0.1)) && (timeFrameAfterLastShare >= (hashrateCalculationWindow.TotalSeconds * 0.1)) )
minerHashTimeFrame = (hashrateCalculationWindow.TotalSeconds - timeFrameBeforeFirstShare + timeFrameAfterLastShare);
if(minerHashTimeFrame < 1)
minerHashTimeFrame = 1;
// calculate miner/worker stats
var minerHashrate = pool.HashrateFromShares(item.Sum, minerHashTimeFrame);
minerHashrate = Math.Floor(minerHashrate);
minerTotalHashrate += minerHashrate;
stats.Hashrate = minerHashrate;
stats.Worker = item.Worker;
stats.SharesPerSecond = Math.Round(item.Count / minerHashTimeFrame, 3);
// persist
await statsRepo.InsertMinerWorkerPerformanceStatsAsync(con, tx, stats);
// broadcast
messageBus.NotifyHashrateUpdated(pool.Config.Id, minerHashrate, stats.Miner, stats.Worker);
logger.Info(() => $"[{poolId}] Worker {stats.Miner}{(!string.IsNullOrEmpty(stats.Worker) ? $".{stats.Worker}" : string.Empty)}: {FormatUtil.FormatHashrate(minerHashrate)}, {stats.SharesPerSecond} shares/sec");
// book keeping
currentNonZeroMinerWorkers.Add(BuildKey(stats.Miner, stats.Worker));
}
});
messageBus.NotifyHashrateUpdated(pool.Config.Id, minerTotalHashrate, stats.Miner, null);
logger.Info(() => $"[{poolId}] Miner {stats.Miner}: {FormatUtil.FormatHashrate(minerTotalHashrate)}");
}
// identify and reset "orphaned" miner stats
var orphanedHashrateForMinerWorker = previousNonZeroMinerWorkers.Except(currentNonZeroMinerWorkers).ToArray();
if(orphanedHashrateForMinerWorker.Any())
{
async Task Action(IDbConnection con, IDbTransaction tx)
{
// reset
stats.Hashrate = 0;
stats.SharesPerSecond = 0;
foreach(var item in orphanedHashrateForMinerWorker)
{
var parts = item.Split(keySeparator);
var miner = parts[0];
var worker = parts.Length > 1 ? parts[1] : null;
stats.Miner = miner;
stats.Worker = worker;
// persist
await statsRepo.InsertMinerWorkerPerformanceStatsAsync(con, tx, stats);
// broadcast
messageBus.NotifyHashrateUpdated(pool.Config.Id, 0, stats.Miner, stats.Worker);
if(string.IsNullOrEmpty(stats.Worker))
logger.Info(() => $"[{poolId}] Reset performance stats for miner {stats.Miner}");
else
logger.Info(() => $"[{poolId}] Reset performance stats for miner {stats.Miner}.{stats.Worker}");
}
}
await cf.RunTx(Action);
}
}
}
private async Task StatsGcAsync(CancellationToken ct)
{
logger.Info(() => "Performing Stats GC");
await cf.Run(async con =>
{
var cutOff = clock.Now.Add(-cleanupDays);
var rowCount = await statsRepo.DeletePoolStatsBeforeAsync(con, cutOff);
if(rowCount > 0)
logger.Info(() => $"Deleted {rowCount} old poolstats records");
rowCount = await statsRepo.DeleteMinerStatsBeforeAsync(con, cutOff);
if(rowCount > 0)
logger.Info(() => $"Deleted {rowCount} old minerstats records");
});
logger.Info(() => "Stats GC complete");
}
private async Task UpdateAsync(CancellationToken ct)
{
while(!ct.IsCancellationRequested)
{
try
{
await UpdatePoolHashratesAsync(ct);
}
catch(Exception ex)
{
logger.Error(ex);
}
await Task.Delay(updateInterval, ct);
}
}
private async Task GcAsync(CancellationToken ct)
{
while(!ct.IsCancellationRequested)
{
try
{
await StatsGcAsync(ct);
}
catch(Exception ex)
{
logger.Error(ex);
}
await Task.Delay(gcInterval, ct);
}
}
private void BuildFaultHandlingPolicy()
{
var retry = Policy
.Handle<DbException>()
.Or<SocketException>()
.Or<TimeoutException>()
.RetryAsync(RetryCount, OnPolicyRetry);
readFaultPolicy = retry;
}
private static void OnPolicyRetry(Exception ex, int retry, object context)
{
logger.Warn(() => $"Retry {retry} due to {ex.Source}: {ex.GetType().Name} ({ex.Message})");
}
protected override async Task ExecuteAsync(CancellationToken ct)
{
try
{
// monitor pool lifetime
disposables.Add(messageBus.Listen<PoolStatusNotification>()
.ObserveOn(TaskPoolScheduler.Default)
.Subscribe(OnPoolStatusNotification));
logger.Info(() => "Online");
// warm-up delay
await Task.Delay(TimeSpan.FromSeconds(15), ct);
await Task.WhenAll(
UpdateAsync(ct),
GcAsync(ct));
logger.Info(() => "Offline");
}
finally
{
disposables.Dispose();
}
}
}
| |
// 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.Globalization;
using Xunit;
namespace System.Tests
{
public static partial class TimeSpanTests
{
[Fact]
public static void MaxValue()
{
VerifyTimeSpan(TimeSpan.MaxValue, 10675199, 2, 48, 5, 477);
}
[Fact]
public static void MinValue()
{
VerifyTimeSpan(TimeSpan.MinValue, -10675199, -2, -48, -5, -477);
}
[Fact]
public static void Zero()
{
VerifyTimeSpan(TimeSpan.Zero, 0, 0, 0, 0, 0);
}
[Fact]
public static void Ctor_Empty()
{
VerifyTimeSpan(new TimeSpan(), 0, 0, 0, 0, 0);
VerifyTimeSpan(default(TimeSpan), 0, 0, 0, 0, 0);
}
[Fact]
public static void Ctor_Long()
{
VerifyTimeSpan(new TimeSpan(999999999999999999), 1157407, 9, 46, 39, 999);
}
[Fact]
public static void Ctor_Int_Int_Int()
{
var timeSpan = new TimeSpan(10, 9, 8);
VerifyTimeSpan(timeSpan, 0, 10, 9, 8, 0);
}
[Fact]
public static void Ctor_Int_Int_Int_Invalid()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan((int)TimeSpan.MinValue.TotalHours - 1, 0, 0)); // TimeSpan < TimeSpan.MinValue
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan((int)TimeSpan.MaxValue.TotalHours + 1, 0, 0)); // TimeSpan > TimeSpan.MaxValue
}
[Fact]
public static void Ctor_Int_Int_Int_Int_Int()
{
var timeSpan = new TimeSpan(10, 9, 8, 7, 6);
VerifyTimeSpan(timeSpan, 10, 9, 8, 7, 6);
}
[Fact]
public static void Ctor_Int_Int_Int_Int_Int_Invalid()
{
// TimeSpan > TimeSpan.MinValue
TimeSpan min = TimeSpan.MinValue;
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(min.Days - 1, min.Hours, min.Minutes, min.Seconds, min.Milliseconds));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(min.Days, min.Hours - 1, min.Minutes, min.Seconds, min.Milliseconds));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(min.Days, min.Hours, min.Minutes - 1, min.Seconds, min.Milliseconds));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(min.Days, min.Hours, min.Minutes, min.Seconds - 1, min.Milliseconds));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(min.Days, min.Hours, min.Minutes, min.Seconds, min.Milliseconds - 1));
// TimeSpan > TimeSpan.MaxValue
TimeSpan max = TimeSpan.MaxValue;
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(max.Days + 1, max.Hours, max.Minutes, max.Seconds, max.Milliseconds));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(max.Days, max.Hours + 1, max.Minutes, max.Seconds, max.Milliseconds));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(max.Days, max.Hours, max.Minutes + 1, max.Seconds, max.Milliseconds));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(max.Days, max.Hours, max.Minutes, max.Seconds + 1, max.Milliseconds));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new TimeSpan(max.Days, max.Hours, max.Minutes, max.Seconds, max.Milliseconds + 1));
}
public static IEnumerable<object[]> Total_Days_Hours_Minutes_Seconds_Milliseconds_TestData()
{
yield return new object[] { new TimeSpan(0, 0, 0, 0, 0), 0.0, 0.0, 0.0, 0.0, 0.0 };
yield return new object[] { new TimeSpan(0, 0, 0, 0, 500), 0.5 / 60.0 / 60.0 / 24.0, 0.5 / 60.0 / 60.0, 0.5 / 60.0, 0.5, 500.0 };
yield return new object[] { new TimeSpan(0, 1, 0, 0, 0), 1 / 24.0, 1, 60, 3600, 3600000 };
yield return new object[] { new TimeSpan(1, 0, 0, 0, 0), 1, 24, 1440, 86400, 86400000 };
yield return new object[] { new TimeSpan(1, 1, 0, 0, 0), 25.0 / 24.0, 25, 1500, 90000, 90000000 };
}
[Theory]
[MemberData(nameof(Total_Days_Hours_Minutes_Seconds_Milliseconds_TestData))]
public static void Total_Days_Hours_Minutes_Seconds_Milliseconds(TimeSpan timeSpan, double expectedDays, double expectedHours, double expectedMinutes, double expectedSeconds, double expectedMilliseconds)
{
// Use ToString() to prevent any rounding errors when comparing
Assert.Equal(expectedDays.ToString(), timeSpan.TotalDays.ToString());
Assert.Equal(expectedHours, timeSpan.TotalHours);
Assert.Equal(expectedMinutes, timeSpan.TotalMinutes);
Assert.Equal(expectedSeconds, timeSpan.TotalSeconds);
Assert.Equal(expectedMilliseconds, timeSpan.TotalMilliseconds);
}
[Fact]
public static void TotalMilliseconds_Invalid()
{
long maxMilliseconds = long.MaxValue / 10000;
long minMilliseconds = long.MinValue / 10000;
Assert.Equal(maxMilliseconds, TimeSpan.MaxValue.TotalMilliseconds);
Assert.Equal(minMilliseconds, TimeSpan.MinValue.TotalMilliseconds);
}
public static IEnumerable<object[]> Add_TestData()
{
yield return new object[] { new TimeSpan(0, 0, 0), new TimeSpan(1, 2, 3), new TimeSpan(1, 2, 3) };
yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(4, 5, 6), new TimeSpan(5, 7, 9) };
yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(-4, -5, -6), new TimeSpan(-3, -3, -3) };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 3), new TimeSpan(1, 3, 5, 7, 5) };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(10, 12, 13, 14, 15), new TimeSpan(11, 14, 16, 18, 20) };
yield return new object[] { new TimeSpan(10000), new TimeSpan(200000), new TimeSpan(210000) };
}
[Theory]
[MemberData(nameof(Add_TestData))]
public static void Add(TimeSpan timeSpan1, TimeSpan timeSpan2, TimeSpan expected)
{
Assert.Equal(expected, timeSpan1.Add(timeSpan2));
Assert.Equal(expected, timeSpan1 + timeSpan2);
}
[Fact]
public static void Add_Invalid()
{
Assert.Throws<OverflowException>(() => TimeSpan.MaxValue.Add(new TimeSpan(1))); // Result > TimeSpan.MaxValue
Assert.Throws<OverflowException>(() => TimeSpan.MinValue.Add(new TimeSpan(-1))); // Result < TimeSpan.MinValue
Assert.Throws<OverflowException>(() => TimeSpan.MaxValue + new TimeSpan(1)); // Result > TimeSpan.MaxValue
Assert.Throws<OverflowException>(() => TimeSpan.MinValue + new TimeSpan(-1)); // Result < TimeSpan.MinValue
}
public static IEnumerable<object[]> CompareTo_TestData()
{
yield return new object[] { new TimeSpan(10000), new TimeSpan(10000), 0 };
yield return new object[] { new TimeSpan(20000), new TimeSpan(10000), 1 };
yield return new object[] { new TimeSpan(10000), new TimeSpan(20000), -1 };
yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(1, 2, 3), 0 };
yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(1, 2, 4), -1 };
yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(1, 2, 2), 1 };
yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(1, 3, 3), -1 };
yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(1, 1, 3), 1 };
yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(2, 2, 3), -1 };
yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(0, 2, 3), 1 };
yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(1, 2, 3, 4), 0 };
yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(1, 2, 3, 5), -1 };
yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(1, 2, 3, 3), 1 };
yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(1, 2, 4, 4), -1 };
yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(1, 2, 2, 4), 1 };
yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(1, 3, 3, 4), -1 };
yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(1, 1, 3, 4), 1 };
yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(2, 2, 3, 4), -1 };
yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(0, 2, 3, 4), 1 };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 3, 4, 5), 0 };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 3, 4, 6), -1 };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 3, 4, 4), 1 };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 3, 5, 5), -1 };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 3, 3, 5), 1 };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 4, 4, 5), -1 };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 2, 4, 5), 1 };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 3, 3, 4, 5), -1 };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 1, 3, 4, 5), 1 };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(2, 2, 3, 4, 5), -1 };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(0, 2, 3, 4, 5), 1 };
yield return new object[] { new TimeSpan(10000), null, 1 };
}
[Theory]
[MemberData(nameof(CompareTo_TestData))]
public static void CompareTo(TimeSpan timeSpan1, object obj, int expected)
{
if (obj is TimeSpan)
{
TimeSpan timeSpan2 = (TimeSpan)obj;
Assert.Equal(expected, Math.Sign(timeSpan1.CompareTo(timeSpan2)));
Assert.Equal(expected, Math.Sign(TimeSpan.Compare(timeSpan1, timeSpan2)));
if (expected >= 0)
{
Assert.True(timeSpan1 >= timeSpan2);
Assert.False(timeSpan1 < timeSpan2);
}
if (expected > 0)
{
Assert.True(timeSpan1 > timeSpan2);
Assert.False(timeSpan1 <= timeSpan2);
}
if (expected <= 0)
{
Assert.True(timeSpan1 <= timeSpan2);
Assert.False(timeSpan1 > timeSpan2);
}
if (expected < 0)
{
Assert.True(timeSpan1 < timeSpan2);
Assert.False(timeSpan1 >= timeSpan2);
}
}
IComparable comparable = timeSpan1;
Assert.Equal(expected, Math.Sign(comparable.CompareTo(obj)));
}
[Fact]
public static void CompareTo_ObjectNotTimeSpan_ThrowsArgumentException()
{
IComparable comparable = new TimeSpan(10000);
AssertExtensions.Throws<ArgumentException>(null, () => comparable.CompareTo("10000")); // Obj is not a time span
}
public static IEnumerable<object[]> Duration_TestData()
{
yield return new object[] { new TimeSpan(0, 0, 0), new TimeSpan(0, 0, 0) };
yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(1, 2, 3) };
yield return new object[] { new TimeSpan(-1, -2, -3), new TimeSpan(1, 2, 3) };
yield return new object[] { new TimeSpan(12345), new TimeSpan(12345) };
yield return new object[] { new TimeSpan(-12345), new TimeSpan(12345) };
}
[Theory]
[MemberData(nameof(Duration_TestData))]
public static void Duration(TimeSpan timeSpan, TimeSpan expected)
{
Assert.Equal(expected, timeSpan.Duration());
}
[Fact]
public static void Duration_Invalid()
{
Assert.Throws<OverflowException>(() => TimeSpan.MinValue.Duration()); // TimeSpan.Ticks == TimeSpan.MinValue.Ticks
Assert.Throws<OverflowException>(() => new TimeSpan(TimeSpan.MinValue.Ticks).Duration()); // TimeSpan.Ticks == TimeSpan.MinValue.Ticks
}
public static IEnumerable<object[]> Equals_TestData()
{
yield return new object[] { new TimeSpan(0, 0, 0), new TimeSpan(0, 0, 0), true };
yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(1, 2, 3), true };
yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(1, 2, 4), false };
yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(1, 3, 3), false };
yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(2, 2, 3), false };
yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(0, 1, 2, 3), true };
yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(0, 1, 2, 3, 0), true };
yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(1, 2, 3, 4), true };
yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(1, 2, 3, 5), false };
yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(1, 2, 4, 4), false };
yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(1, 3, 3, 4), false };
yield return new object[] { new TimeSpan(1, 2, 3, 4), new TimeSpan(2, 2, 3, 4), false };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(2, 3, 4), false };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 3, 4, 5), true };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 3, 4, 6), false };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 3, 5, 5), false };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 4, 4, 5), false };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 3, 3, 4, 5), false };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(2, 2, 3, 4, 5), false };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 3, 4), false };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(2, 2, 3), false };
yield return new object[] { new TimeSpan(10000), new TimeSpan(10000), true };
yield return new object[] { new TimeSpan(10000), new TimeSpan(20000), false };
yield return new object[] { new TimeSpan(10000), "20000", false };
yield return new object[] { new TimeSpan(10000), null, false };
}
[Theory]
[MemberData(nameof(Equals_TestData))]
public static void Equals(TimeSpan timeSpan1, object obj, bool expected)
{
if (obj is TimeSpan)
{
TimeSpan timeSpan2 = (TimeSpan)obj;
Assert.Equal(expected, TimeSpan.Equals(timeSpan1, timeSpan2));
Assert.Equal(expected, timeSpan1.Equals(timeSpan2));
Assert.Equal(expected, timeSpan1 == timeSpan2);
Assert.Equal(!expected, timeSpan1 != timeSpan2);
Assert.Equal(expected, timeSpan1.GetHashCode().Equals(timeSpan2.GetHashCode()));
}
Assert.Equal(expected, timeSpan1.Equals(obj));
}
public static IEnumerable<object[]> FromDays_TestData()
{
yield return new object[] { 100.5, new TimeSpan(100, 12, 0, 0) };
yield return new object[] { 2.5, new TimeSpan(2, 12, 0, 0) };
yield return new object[] { 1.0, new TimeSpan(1, 0, 0, 0) };
yield return new object[] { 0.0, new TimeSpan(0, 0, 0, 0) };
yield return new object[] { -1.0, new TimeSpan(-1, 0, 0, 0) };
yield return new object[] { -2.5, new TimeSpan(-2, -12, 0, 0) };
yield return new object[] { -100.5, new TimeSpan(-100, -12, 0, 0) };
}
[Theory]
[MemberData(nameof(FromDays_TestData))]
public static void FromDays(double value, TimeSpan expected)
{
Assert.Equal(expected, TimeSpan.FromDays(value));
}
[Fact]
public static void FromDays_Invalid()
{
double maxDays = long.MaxValue / (TimeSpan.TicksPerMillisecond / 1000.0 / 60.0 / 60.0 / 24.0);
Assert.Throws<OverflowException>(() => TimeSpan.FromDays(double.PositiveInfinity)); // Value is positive infinity
Assert.Throws<OverflowException>(() => TimeSpan.FromDays(double.NegativeInfinity)); // Value is positive infinity
Assert.Throws<OverflowException>(() => TimeSpan.FromDays(maxDays)); // Value > TimeSpan.MaxValue
Assert.Throws<OverflowException>(() => TimeSpan.FromDays(-maxDays)); // Value < TimeSpan.MinValue
AssertExtensions.Throws<ArgumentException>(null, () => TimeSpan.FromMinutes(double.NaN)); // Value is NaN
}
public static IEnumerable<object[]> FromHours_TestData()
{
yield return new object[] { 100.5, new TimeSpan(4, 4, 30, 0) };
yield return new object[] { 2.5, new TimeSpan(2, 30, 0) };
yield return new object[] { 1.0, new TimeSpan(1, 0, 0) };
yield return new object[] { 0.0, new TimeSpan(0, 0, 0) };
yield return new object[] { -1.0, new TimeSpan(-1, 0, 0) };
yield return new object[] { -2.5, new TimeSpan(-2, -30, 0) };
yield return new object[] { -100.5, new TimeSpan(-4, -4, -30, 0) };
}
[Theory]
[MemberData(nameof(FromHours_TestData))]
public static void FromHours(double value, TimeSpan expected)
{
Assert.Equal(expected, TimeSpan.FromHours(value));
}
[Fact]
public static void FromHours_Invalid()
{
double maxHours = long.MaxValue / (TimeSpan.TicksPerMillisecond / 1000.0 / 60.0 / 60.0);
Assert.Throws<OverflowException>(() => TimeSpan.FromHours(double.PositiveInfinity)); // Value is positive infinity
Assert.Throws<OverflowException>(() => TimeSpan.FromHours(double.NegativeInfinity)); // Value is positive infinity
Assert.Throws<OverflowException>(() => TimeSpan.FromHours(maxHours)); // Value > TimeSpan.MaxValue
Assert.Throws<OverflowException>(() => TimeSpan.FromHours(-maxHours)); // Value < TimeSpan.MinValue
AssertExtensions.Throws<ArgumentException>(null, () => TimeSpan.FromMinutes(double.NaN)); // Value is NaN
}
public static IEnumerable<object[]> FromMinutes_TestData()
{
yield return new object[] { 100.5, new TimeSpan(1, 40, 30) };
yield return new object[] { 2.5, new TimeSpan(0, 2, 30) };
yield return new object[] { 1.0, new TimeSpan(0, 1, 0) };
yield return new object[] { 0.0, new TimeSpan(0, 0, 0) };
yield return new object[] { -1.0, new TimeSpan(0, -1, 0) };
yield return new object[] { -2.5, new TimeSpan(0, -2, -30) };
yield return new object[] { -100.5, new TimeSpan(-1, -40, -30) };
}
[Theory]
[MemberData(nameof(FromMinutes_TestData))]
public static void FromMinutes(double value, TimeSpan expected)
{
Assert.Equal(expected, TimeSpan.FromMinutes(value));
}
[Fact]
public static void FromMinutes_Invalid()
{
double maxMinutes = long.MaxValue / (TimeSpan.TicksPerMillisecond / 1000.0 / 60.0);
Assert.Throws<OverflowException>(() => TimeSpan.FromMinutes(double.PositiveInfinity)); // Value is positive infinity
Assert.Throws<OverflowException>(() => TimeSpan.FromMinutes(double.NegativeInfinity)); // Value is positive infinity
Assert.Throws<OverflowException>(() => TimeSpan.FromMinutes(maxMinutes)); // Value > TimeSpan.MaxValue
Assert.Throws<OverflowException>(() => TimeSpan.FromMinutes(-maxMinutes)); // Value < TimeSpan.MinValue
AssertExtensions.Throws<ArgumentException>(null, () => TimeSpan.FromMinutes(double.NaN)); // Value is NaN
}
public static IEnumerable<object[]> FromSeconds_TestData()
{
yield return new object[] { 100.5, new TimeSpan(0, 0, 1, 40, 500) };
yield return new object[] { 2.5, new TimeSpan(0, 0, 0, 2, 500) };
yield return new object[] { 1.0, new TimeSpan(0, 0, 0, 1, 0) };
yield return new object[] { 0.0, new TimeSpan(0, 0, 0, 0, 0) };
yield return new object[] { -1.0, new TimeSpan(0, 0, 0, -1, 0) };
yield return new object[] { -2.5, new TimeSpan(0, 0, 0, -2, -500) };
yield return new object[] { -100.5, new TimeSpan(0, 0, -1, -40, -500) };
}
[Theory]
[MemberData(nameof(FromSeconds_TestData))]
public static void FromSeconds(double value, TimeSpan expected)
{
Assert.Equal(expected, TimeSpan.FromSeconds(value));
}
[Fact]
public static void FromSeconds_Invalid()
{
double maxSeconds = long.MaxValue / (TimeSpan.TicksPerMillisecond / 1000.0);
Assert.Throws<OverflowException>(() => TimeSpan.FromSeconds(double.PositiveInfinity)); // Value is positive infinity
Assert.Throws<OverflowException>(() => TimeSpan.FromSeconds(double.NegativeInfinity)); // Value is positive infinity
Assert.Throws<OverflowException>(() => TimeSpan.FromSeconds(maxSeconds)); // Value > TimeSpan.MaxValue
Assert.Throws<OverflowException>(() => TimeSpan.FromSeconds(-maxSeconds)); // Value < TimeSpan.MinValue
AssertExtensions.Throws<ArgumentException>(null, () => TimeSpan.FromSeconds(double.NaN)); // Value is NaN
}
public static IEnumerable<object[]> FromMilliseconds_TestData()
{
yield return new object[] { 1500.5, new TimeSpan(0, 0, 0, 1, 501) };
yield return new object[] { 2.5, new TimeSpan(0, 0, 0, 0, 3) };
yield return new object[] { 1.0, new TimeSpan(0, 0, 0, 0, 1) };
yield return new object[] { 0.0, new TimeSpan(0, 0, 0, 0, 0) };
yield return new object[] { -1.0, new TimeSpan(0, 0, 0, 0, -1) };
yield return new object[] { -2.5, new TimeSpan(0, 0, 0, 0, -3) };
yield return new object[] { -1500.5, new TimeSpan(0, 0, 0, -1, -501) };
}
[Theory]
[MemberData(nameof(FromMilliseconds_TestData))]
public static void FromMilliseconds(double value, TimeSpan expected)
{
Assert.Equal(expected, TimeSpan.FromMilliseconds(value));
}
[Fact]
public static void FromMilliseconds_Invalid()
{
double maxMilliseconds = long.MaxValue / TimeSpan.TicksPerMillisecond;
Assert.Throws<OverflowException>(() => TimeSpan.FromMilliseconds(double.PositiveInfinity)); // Value is positive infinity
Assert.Throws<OverflowException>(() => TimeSpan.FromMilliseconds(double.NegativeInfinity)); // Value is positive infinity
Assert.Throws<OverflowException>(() => TimeSpan.FromMilliseconds(maxMilliseconds)); // Value > TimeSpan.MaxValue
Assert.Throws<OverflowException>(() => TimeSpan.FromMilliseconds(-maxMilliseconds)); // Value < TimeSpan.MinValue
AssertExtensions.Throws<ArgumentException>(null, () => TimeSpan.FromMilliseconds(double.NaN)); // Value is NaN
}
public static IEnumerable<object[]> FromTicks_TestData()
{
yield return new object[] { TimeSpan.TicksPerMillisecond, new TimeSpan(0, 0, 0, 0, 1) };
yield return new object[] { TimeSpan.TicksPerSecond, new TimeSpan(0, 0, 0, 1, 0) };
yield return new object[] { TimeSpan.TicksPerMinute, new TimeSpan(0, 0, 1, 0, 0) };
yield return new object[] { TimeSpan.TicksPerHour, new TimeSpan(0, 1, 0, 0, 0) };
yield return new object[] { TimeSpan.TicksPerDay, new TimeSpan(1, 0, 0, 0, 0) };
yield return new object[] { 1.0, new TimeSpan(1) };
yield return new object[] { 0.0, new TimeSpan(0, 0, 0) };
yield return new object[] { -1.0, new TimeSpan(-1) };
yield return new object[] { -TimeSpan.TicksPerMillisecond, new TimeSpan(0, 0, 0, 0, -1) };
yield return new object[] { -TimeSpan.TicksPerSecond, new TimeSpan(0, 0, 0, -1, 0) };
yield return new object[] { -TimeSpan.TicksPerMinute, new TimeSpan(0, 0, -1, 0, 0) };
yield return new object[] { -TimeSpan.TicksPerHour, new TimeSpan(0, -1, 0, 0, 0) };
yield return new object[] { -TimeSpan.TicksPerDay, new TimeSpan(-1, 0, 0, 0, 0) };
}
[Theory]
[MemberData(nameof(FromTicks_TestData))]
public static void FromTicks(long value, TimeSpan expected)
{
Assert.Equal(expected, TimeSpan.FromTicks(value));
}
public static IEnumerable<object[]> Negate_TestData()
{
yield return new object[] { new TimeSpan(0, 0, 0), new TimeSpan(0, 0, 0) };
yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(-1, -2, -3) };
yield return new object[] { new TimeSpan(-1, -2, -3), new TimeSpan(1, 2, 3) };
yield return new object[] { new TimeSpan(12345), new TimeSpan(-12345) };
yield return new object[] { new TimeSpan(-12345), new TimeSpan(12345) };
}
[Theory]
[MemberData(nameof(Negate_TestData))]
public static void Negate(TimeSpan timeSpan, TimeSpan expected)
{
Assert.Equal(expected, timeSpan.Negate());
Assert.Equal(expected, -timeSpan);
}
[Fact]
public static void Negate_Invalid()
{
Assert.Throws<OverflowException>(() => TimeSpan.MinValue.Negate()); // TimeSpan.MinValue cannot be negated
Assert.Throws<OverflowException>(() => -TimeSpan.MinValue); // TimeSpan.MinValue cannot be negated
}
public static IEnumerable<object[]> Parse_Valid_TestData()
{
yield return new object[] { " 12:24:02", null, new TimeSpan(0, 12, 24, 2, 0) };
yield return new object[] { "12:24", null, new TimeSpan(0, 12, 24, 0, 0) };
yield return new object[] { "12:24:02", null, new TimeSpan(0, 12, 24, 2, 0) };
yield return new object[] { "1.12:24:02", null, new TimeSpan(1, 12, 24, 2, 0) };
yield return new object[] { "1:12:24:02", null, new TimeSpan(1, 12, 24, 2, 0) };
yield return new object[] { "1.12:24:02.999", null, new TimeSpan(1, 12, 24, 2, 999) };
yield return new object[] { "-12:24:02", null, new TimeSpan(0, -12, -24, -2, 0) };
yield return new object[] { "-1.12:24:02.999", null, new TimeSpan(-1, -12, -24, -2, -999) };
// Croatia uses ',' in place of '.'
CultureInfo croatianCulture = new CultureInfo("hr-HR");
yield return new object[] { "6:12:14:45,348", croatianCulture, new TimeSpan(6, 12, 14, 45, 348) };
}
[Theory]
[MemberData(nameof(Parse_Valid_TestData))]
public static void Parse(string input, IFormatProvider provider, TimeSpan expected)
{
TimeSpan result;
if (provider == null)
{
Assert.True(TimeSpan.TryParse(input, out result));
Assert.Equal(expected, result);
Assert.Equal(expected, TimeSpan.Parse(input));
}
Assert.True(TimeSpan.TryParse(input, provider, out result));
Assert.Equal(expected, result);
Assert.Equal(expected, TimeSpan.Parse(input, provider));
}
public static IEnumerable<object[]> Parse_Invalid_TestData()
{
yield return new object[] { null, null, typeof(ArgumentNullException) };
yield return new object[] { "", null, typeof(FormatException) };
yield return new object[] { "-", null, typeof(FormatException) };
yield return new object[] { "garbage", null, typeof(FormatException) };
yield return new object[] { "12/12/12", null, typeof(FormatException) };
yield return new object[] { "1:1:1.99999999", null, typeof(OverflowException) };
// Croatia uses ',' in place of '.'
CultureInfo croatianCulture = new CultureInfo("hr-HR");
yield return new object[] { "6:12:14:45.3448", croatianCulture, typeof(FormatException) };
}
[Theory]
[MemberData(nameof(Parse_Invalid_TestData))]
public static void Parse_Invalid(string input, IFormatProvider provider, Type exceptionType)
{
TimeSpan result;
if (provider == null)
{
Assert.False(TimeSpan.TryParse(input, out result));
Assert.Equal(TimeSpan.Zero, result);
Assert.Throws(exceptionType, () => TimeSpan.Parse(input));
}
Assert.False(TimeSpan.TryParse(input, provider, out result));
Assert.Equal(TimeSpan.Zero, result);
Assert.Throws(exceptionType, () => TimeSpan.Parse(input, provider));
}
public static IEnumerable<object[]> ParseExact_Valid_TestData()
{
// Standard timespan formats 'c', 'g', 'G'
yield return new object[] { "12:24:02", "c", new TimeSpan(0, 12, 24, 2) };
yield return new object[] { "1.12:24:02", "c", new TimeSpan(1, 12, 24, 2) };
yield return new object[] { "-01.07:45:16.999", "c", new TimeSpan(1, 7, 45, 16, 999).Negate() };
yield return new object[] { "12:24:02", "g", new TimeSpan(0, 12, 24, 2) };
yield return new object[] { "1:12:24:02", "g", new TimeSpan(1, 12, 24, 2) };
yield return new object[] { "-01:07:45:16.999", "g", new TimeSpan(1, 7, 45, 16, 999).Negate() };
yield return new object[] { "1:12:24:02.243", "G", new TimeSpan(1, 12, 24, 2, 243) };
yield return new object[] { "-01:07:45:16.999", "G", new TimeSpan(1, 7, 45, 16, 999).Negate() };
// Custom timespan formats
yield return new object[] { "12.23:32:43", @"dd\.h\:m\:s", new TimeSpan(12, 23, 32, 43) };
yield return new object[] { "012.23:32:43.893", @"ddd\.h\:m\:s\.fff", new TimeSpan(12, 23, 32, 43, 893) };
yield return new object[] { "12.05:02:03", @"d\.hh\:mm\:ss", new TimeSpan(12, 5, 2, 3) };
yield return new object[] { "12:34 minutes", @"mm\:ss\ \m\i\n\u\t\e\s", new TimeSpan(0, 12, 34) };
}
[Theory]
[MemberData(nameof(ParseExact_Valid_TestData))]
public static void ParseExact(string input, string format, TimeSpan expected)
{
TimeSpan result;
Assert.Equal(expected, TimeSpan.ParseExact(input, format, new CultureInfo("en-US")));
Assert.True(TimeSpan.TryParseExact(input, format, new CultureInfo("en-US"), out result));
Assert.Equal(expected, result);
// TimeSpanStyles is interpreted only for custom formats
if (format != "c" && format != "g" && format != "G")
{
Assert.Equal(expected.Negate(), TimeSpan.ParseExact(input, format, new CultureInfo("en-US"), TimeSpanStyles.AssumeNegative));
Assert.True(TimeSpan.TryParseExact(input, format, new CultureInfo("en-US"), TimeSpanStyles.AssumeNegative, out result));
Assert.Equal(expected.Negate(), result);
}
}
public static IEnumerable<object[]> ParseExact_Invalid_TestData()
{
yield return new object[] { null, "c", typeof(ArgumentNullException) };
yield return new object[] { "", "c", typeof(FormatException) };
yield return new object[] { "-", "c", typeof(FormatException) };
yield return new object[] { "garbage", "c", typeof(FormatException) };
// Standard timespan formats 'c', 'g', 'G'
yield return new object[] { "24:24:02", "c", typeof(OverflowException) };
yield return new object[] { "1:12:24:02", "c", typeof(FormatException) };
yield return new object[] { "12:61:02", "g", typeof(OverflowException) };
yield return new object[] { "1.12:24:02", "g", typeof(FormatException) };
yield return new object[] { "1:07:45:16.99999999", "G", typeof(OverflowException) };
yield return new object[] { "1:12:24:02", "G", typeof(FormatException) };
// Custom timespan formats
yield return new object[] { "12.35:32:43", @"dd\.h\:m\:s", typeof(OverflowException) };
yield return new object[] { "12.5:2:3", @"d\.hh\:mm\:ss", typeof(FormatException) };
yield return new object[] { "12.5:2", @"d\.hh\:mm\:ss", typeof(FormatException) };
}
[Theory]
[MemberData(nameof(ParseExact_Invalid_TestData))]
public static void ParseExactTest_Invalid(string input, string format, Type exceptionType)
{
Assert.Throws(exceptionType, () => TimeSpan.ParseExact(input, format, new CultureInfo("en-US")));
TimeSpan result;
Assert.False(TimeSpan.TryParseExact(input, format, new CultureInfo("en-US"), out result));
Assert.Equal(TimeSpan.Zero, result);
}
public static IEnumerable<object[]> Subtract_TestData()
{
yield return new object[] { new TimeSpan(0, 0, 0), new TimeSpan(1, 2, 3), new TimeSpan(-1, -2, -3) };
yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(4, 5, 6), new TimeSpan(-3, -3, -3) };
yield return new object[] { new TimeSpan(1, 2, 3), new TimeSpan(-4, -5, -6), new TimeSpan(5, 7, 9) };
yield return new object[] { new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(1, 2, 3), new TimeSpan(1, 1, 1, 1, 5) };
yield return new object[] { new TimeSpan(10, 11, 12, 13, 14), new TimeSpan(1, 2, 3, 4, 5), new TimeSpan(9, 9, 9, 9, 9) };
yield return new object[] { new TimeSpan(200000), new TimeSpan(10000), new TimeSpan(190000) };
}
[Theory]
[MemberData(nameof(Subtract_TestData))]
public static void Subtract(TimeSpan ts1, TimeSpan ts2, TimeSpan expected)
{
Assert.Equal(expected, ts1.Subtract(ts2));
Assert.Equal(expected, ts1 - ts2);
}
[Fact]
public static void Subtract_Invalid()
{
Assert.Throws<OverflowException>(() => TimeSpan.MaxValue.Subtract(new TimeSpan(-1))); // Result > TimeSpan.MaxValue
Assert.Throws<OverflowException>(() => TimeSpan.MinValue.Subtract(new TimeSpan(1))); // Result < TimeSpan.MinValue
Assert.Throws<OverflowException>(() => TimeSpan.MaxValue - new TimeSpan(-1)); // Result > TimeSpan.MaxValue
Assert.Throws<OverflowException>(() => TimeSpan.MinValue - new TimeSpan(1)); // Result < TimeSpan.MinValue
}
[Fact]
public static void ToStringTest()
{
var timeSpan1 = new TimeSpan(1, 2, 3);
var timeSpan2 = new TimeSpan(1, 2, 3);
var timeSpan3 = new TimeSpan(1, 2, 4);
var timeSpan4 = new TimeSpan(1, 2, 3, 4);
var timeSpan5 = new TimeSpan(1, 2, 3, 4);
var timeSpan6 = new TimeSpan(1, 2, 3, 5);
var timeSpan7 = new TimeSpan(1, 2, 3, 4, 5);
var timeSpan8 = new TimeSpan(1, 2, 3, 4, 5);
var timeSpan9 = new TimeSpan(1, 2, 3, 4, 6);
Assert.Equal(timeSpan1.ToString(), timeSpan2.ToString());
Assert.Equal(timeSpan1.ToString("c"), timeSpan2.ToString("c"));
Assert.Equal(timeSpan1.ToString("c", null), timeSpan2.ToString("c", null));
Assert.NotEqual(timeSpan1.ToString(), timeSpan3.ToString());
Assert.NotEqual(timeSpan1.ToString(), timeSpan4.ToString());
Assert.NotEqual(timeSpan1.ToString(), timeSpan7.ToString());
Assert.Equal(timeSpan4.ToString(), timeSpan5.ToString());
Assert.Equal(timeSpan4.ToString("c"), timeSpan5.ToString("c"));
Assert.Equal(timeSpan4.ToString("c", null), timeSpan5.ToString("c", null));
Assert.NotEqual(timeSpan4.ToString(), timeSpan6.ToString());
Assert.NotEqual(timeSpan4.ToString(), timeSpan7.ToString());
Assert.Equal(timeSpan7.ToString(), timeSpan8.ToString());
Assert.Equal(timeSpan7.ToString("c"), timeSpan8.ToString("c"));
Assert.Equal(timeSpan7.ToString("c", null), timeSpan8.ToString("c", null));
Assert.NotEqual(timeSpan7.ToString(), timeSpan9.ToString());
}
[Fact]
public static void ToString_InvalidFormat_ThrowsFormatException()
{
var timeSpan = new TimeSpan();
Assert.Throws<FormatException>(() => timeSpan.ToString("y")); // Invalid format
Assert.Throws<FormatException>(() => timeSpan.ToString("cc")); // Invalid format
}
private static void VerifyTimeSpan(TimeSpan timeSpan, int days, int hours, int minutes, int seconds, int milliseconds)
{
Assert.Equal(days, timeSpan.Days);
Assert.Equal(hours, timeSpan.Hours);
Assert.Equal(minutes, timeSpan.Minutes);
Assert.Equal(seconds, timeSpan.Seconds);
Assert.Equal(milliseconds, timeSpan.Milliseconds);
Assert.Equal(timeSpan, +timeSpan);
}
[Theory]
[MemberData(nameof(CompareTo_TestData))]
public static void CompareTo_Object(TimeSpan timeSpan1, object obj, int expected)
{
Assert.Equal(expected, Math.Sign(timeSpan1.CompareTo(obj)));
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using CSJ2K;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
namespace OpenSim.Region.CoreModules.Agent.TextureSender
{
public delegate void J2KDecodeDelegate(UUID assetID);
public class J2KDecoderModule : IRegionModule, IJ2KDecoder
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>Temporarily holds deserialized layer data information in memory</summary>
private readonly ExpiringCache<UUID, OpenJPEG.J2KLayerInfo[]> m_decodedCache = new ExpiringCache<UUID,OpenJPEG.J2KLayerInfo[]>();
/// <summary>List of client methods to notify of results of decode</summary>
private readonly Dictionary<UUID, List<DecodedCallback>> m_notifyList = new Dictionary<UUID, List<DecodedCallback>>();
/// <summary>Cache that will store decoded JPEG2000 layer boundary data</summary>
private IImprovedAssetCache m_cache;
/// <summary>Reference to a scene (doesn't matter which one as long as it can load the cache module)</summary>
private Scene m_scene;
#region IRegionModule
public string Name { get { return "J2KDecoderModule"; } }
public bool IsSharedModule { get { return true; } }
public J2KDecoderModule()
{
}
public void Initialise(Scene scene, IConfigSource source)
{
if (m_scene == null)
m_scene = scene;
scene.RegisterModuleInterface<IJ2KDecoder>(this);
}
public void PostInitialise()
{
m_cache = m_scene.RequestModuleInterface<IImprovedAssetCache>();
}
public void Close()
{
}
#endregion IRegionModule
#region IJ2KDecoder
public void BeginDecode(UUID assetID, byte[] j2kData, DecodedCallback callback)
{
OpenJPEG.J2KLayerInfo[] result;
// If it's cached, return the cached results
if (m_decodedCache.TryGetValue(assetID, out result))
{
callback(assetID, result);
}
else
{
// Not cached, we need to decode it.
// Add to notify list and start decoding.
// Next request for this asset while it's decoding will only be added to the notify list
// once this is decoded, requests will be served from the cache and all clients in the notifylist will be updated
bool decode = false;
lock (m_notifyList)
{
if (m_notifyList.ContainsKey(assetID))
{
m_notifyList[assetID].Add(callback);
}
else
{
List<DecodedCallback> notifylist = new List<DecodedCallback>();
notifylist.Add(callback);
m_notifyList.Add(assetID, notifylist);
decode = true;
}
}
// Do Decode!
if (decode)
DoJ2KDecode(assetID, j2kData);
}
}
/// <summary>
/// Provides a synchronous decode so that caller can be assured that this executes before the next line
/// </summary>
/// <param name="assetID"></param>
/// <param name="j2kData"></param>
public void Decode(UUID assetID, byte[] j2kData)
{
DoJ2KDecode(assetID, j2kData);
}
#endregion IJ2KDecoder
/// <summary>
/// Decode Jpeg2000 Asset Data
/// </summary>
/// <param name="assetID">UUID of Asset</param>
/// <param name="j2kData">JPEG2000 data</param>
private void DoJ2KDecode(UUID assetID, byte[] j2kData)
{
int DecodeTime = 0;
DecodeTime = Environment.TickCount;
OpenJPEG.J2KLayerInfo[] layers;
if (!TryLoadCacheForAsset(assetID, out layers))
{
try
{
List<int> layerStarts = CSJ2K.J2kImage.GetLayerBoundaries(new MemoryStream(j2kData));
if (layerStarts != null && layerStarts.Count > 0)
{
layers = new OpenJPEG.J2KLayerInfo[layerStarts.Count];
for (int i = 0; i < layerStarts.Count; i++)
{
OpenJPEG.J2KLayerInfo layer = new OpenJPEG.J2KLayerInfo();
if (i == 0)
layer.Start = 0;
else
layer.Start = layerStarts[i];
if (i == layerStarts.Count - 1)
layer.End = j2kData.Length;
else
layer.End = layerStarts[i + 1] - 1;
layers[i] = layer;
}
}
}
catch (Exception ex)
{
m_log.Warn("[J2KDecoderModule]: CSJ2K threw an exception decoding texture " + assetID + ": " + ex.Message);
}
if (layers == null || layers.Length == 0)
{
m_log.Warn("[J2KDecoderModule]: Failed to decode layer data for texture " + assetID + ", guessing sane defaults");
// Layer decoding completely failed. Guess at sane defaults for the layer boundaries
layers = CreateDefaultLayers(j2kData.Length);
}
// Cache Decoded layers
SaveFileCacheForAsset(assetID, layers);
}
// Notify Interested Parties
lock (m_notifyList)
{
if (m_notifyList.ContainsKey(assetID))
{
foreach (DecodedCallback d in m_notifyList[assetID])
{
if (d != null)
d.DynamicInvoke(assetID, layers);
}
m_notifyList.Remove(assetID);
}
}
}
private OpenJPEG.J2KLayerInfo[] CreateDefaultLayers(int j2kLength)
{
OpenJPEG.J2KLayerInfo[] layers = new OpenJPEG.J2KLayerInfo[5];
for (int i = 0; i < layers.Length; i++)
layers[i] = new OpenJPEG.J2KLayerInfo();
// These default layer sizes are based on a small sampling of real-world texture data
// with extra padding thrown in for good measure. This is a worst case fallback plan
// and may not gracefully handle all real world data
layers[0].Start = 0;
layers[1].Start = (int)((float)j2kLength * 0.02f);
layers[2].Start = (int)((float)j2kLength * 0.05f);
layers[3].Start = (int)((float)j2kLength * 0.20f);
layers[4].Start = (int)((float)j2kLength * 0.50f);
layers[0].End = layers[1].Start - 1;
layers[1].End = layers[2].Start - 1;
layers[2].End = layers[3].Start - 1;
layers[3].End = layers[4].Start - 1;
layers[4].End = j2kLength;
return layers;
}
private void SaveFileCacheForAsset(UUID AssetId, OpenJPEG.J2KLayerInfo[] Layers)
{
m_decodedCache.AddOrUpdate(AssetId, Layers, TimeSpan.FromMinutes(10));
if (m_cache != null)
{
AssetBase layerDecodeAsset = new AssetBase();
layerDecodeAsset.ID = "j2kCache_" + AssetId.ToString();
layerDecodeAsset.Local = true;
layerDecodeAsset.Name = layerDecodeAsset.ID;
layerDecodeAsset.Temporary = true;
layerDecodeAsset.Type = (sbyte)AssetType.Notecard;
#region Serialize Layer Data
StringBuilder stringResult = new StringBuilder();
string strEnd = "\n";
for (int i = 0; i < Layers.Length; i++)
{
if (i == Layers.Length - 1)
strEnd = String.Empty;
stringResult.AppendFormat("{0}|{1}|{2}{3}", Layers[i].Start, Layers[i].End, Layers[i].End - Layers[i].Start, strEnd);
}
layerDecodeAsset.Data = Util.UTF8.GetBytes(stringResult.ToString());
#endregion Serialize Layer Data
m_cache.Cache(layerDecodeAsset);
}
}
bool TryLoadCacheForAsset(UUID AssetId, out OpenJPEG.J2KLayerInfo[] Layers)
{
if (m_decodedCache.TryGetValue(AssetId, out Layers))
{
return true;
}
else if (m_cache != null)
{
string assetName = "j2kCache_" + AssetId.ToString();
AssetBase layerDecodeAsset = m_cache.Get(assetName);
if (layerDecodeAsset != null)
{
#region Deserialize Layer Data
string readResult = Util.UTF8.GetString(layerDecodeAsset.Data);
string[] lines = readResult.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
if (lines.Length == 0)
{
m_log.Warn("[J2KDecodeCache]: Expiring corrupted layer data (empty) " + assetName);
m_cache.Expire(assetName);
return false;
}
Layers = new OpenJPEG.J2KLayerInfo[lines.Length];
for (int i = 0; i < lines.Length; i++)
{
string[] elements = lines[i].Split('|');
if (elements.Length == 3)
{
int element1, element2;
try
{
element1 = Convert.ToInt32(elements[0]);
element2 = Convert.ToInt32(elements[1]);
}
catch (FormatException)
{
m_log.Warn("[J2KDecodeCache]: Expiring corrupted layer data (format) " + assetName);
m_cache.Expire(assetName);
return false;
}
Layers[i] = new OpenJPEG.J2KLayerInfo();
Layers[i].Start = element1;
Layers[i].End = element2;
}
else
{
m_log.Warn("[J2KDecodeCache]: Expiring corrupted layer data (layout) " + assetName);
m_cache.Expire(assetName);
return false;
}
}
#endregion Deserialize Layer Data
return true;
}
}
return false;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Data.Common;
using System.Threading;
using System.Threading.Tasks;
namespace System.Data.ProviderBase
{
internal abstract partial class DbConnectionFactory
{
private Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> _connectionPoolGroups;
private readonly List<DbConnectionPool> _poolsToRelease;
private readonly List<DbConnectionPoolGroup> _poolGroupsToRelease;
private readonly Timer _pruningTimer;
private const int PruningDueTime = 4 * 60 * 1000; // 4 minutes
private const int PruningPeriod = 30 * 1000; // thirty seconds
// s_pendingOpenNonPooled is an array of tasks used to throttle creation of non-pooled connections to
// a maximum of Environment.ProcessorCount at a time.
private static uint s_pendingOpenNonPooledNext = 0;
private static Task<DbConnectionInternal>[] s_pendingOpenNonPooled = new Task<DbConnectionInternal>[Environment.ProcessorCount];
private static Task<DbConnectionInternal> s_completedTask;
protected DbConnectionFactory()
{
_connectionPoolGroups = new Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup>();
_poolsToRelease = new List<DbConnectionPool>();
_poolGroupsToRelease = new List<DbConnectionPoolGroup>();
_pruningTimer = CreatePruningTimer();
}
abstract public DbProviderFactory ProviderFactory
{
get;
}
public void ClearAllPools()
{
Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> connectionPoolGroups = _connectionPoolGroups;
foreach (KeyValuePair<DbConnectionPoolKey, DbConnectionPoolGroup> entry in connectionPoolGroups)
{
DbConnectionPoolGroup poolGroup = entry.Value;
if (null != poolGroup)
{
poolGroup.Clear();
}
}
}
public void ClearPool(DbConnection connection)
{
ADP.CheckArgumentNull(connection, nameof(connection));
DbConnectionPoolGroup poolGroup = GetConnectionPoolGroup(connection);
if (null != poolGroup)
{
poolGroup.Clear();
}
}
public void ClearPool(DbConnectionPoolKey key)
{
Debug.Assert(key != null, "key cannot be null");
ADP.CheckArgumentNull(key.ConnectionString, nameof(key) + "." + nameof(key.ConnectionString));
DbConnectionPoolGroup poolGroup;
Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> connectionPoolGroups = _connectionPoolGroups;
if (connectionPoolGroups.TryGetValue(key, out poolGroup))
{
poolGroup.Clear();
}
}
internal virtual DbConnectionPoolProviderInfo CreateConnectionPoolProviderInfo(DbConnectionOptions connectionOptions)
{
return null;
}
internal DbConnectionInternal CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions)
{
Debug.Assert(null != owningConnection, "null owningConnection?");
Debug.Assert(null != poolGroup, "null poolGroup?");
DbConnectionOptions connectionOptions = poolGroup.ConnectionOptions;
DbConnectionPoolGroupProviderInfo poolGroupProviderInfo = poolGroup.ProviderInfo;
DbConnectionPoolKey poolKey = poolGroup.PoolKey;
DbConnectionInternal newConnection = CreateConnection(connectionOptions, poolKey, poolGroupProviderInfo, null, owningConnection, userOptions);
if (null != newConnection)
{
newConnection.MakeNonPooledObject(owningConnection);
}
return newConnection;
}
internal DbConnectionInternal CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
{
Debug.Assert(null != pool, "null pool?");
DbConnectionPoolGroupProviderInfo poolGroupProviderInfo = pool.PoolGroup.ProviderInfo;
DbConnectionInternal newConnection = CreateConnection(options, poolKey, poolGroupProviderInfo, pool, owningObject, userOptions);
if (null != newConnection)
{
newConnection.MakePooledConnection(pool);
}
return newConnection;
}
virtual internal DbConnectionPoolGroupProviderInfo CreateConnectionPoolGroupProviderInfo(DbConnectionOptions connectionOptions)
{
return null;
}
private Timer CreatePruningTimer() =>
ADP.UnsafeCreateTimer(
new TimerCallback(PruneConnectionPoolGroups),
null,
PruningDueTime,
PruningPeriod);
protected DbConnectionOptions FindConnectionOptions(DbConnectionPoolKey key)
{
Debug.Assert(key != null, "key cannot be null");
if (!string.IsNullOrEmpty(key.ConnectionString))
{
DbConnectionPoolGroup connectionPoolGroup;
Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> connectionPoolGroups = _connectionPoolGroups;
if (connectionPoolGroups.TryGetValue(key, out connectionPoolGroup))
{
return connectionPoolGroup.ConnectionOptions;
}
}
return null;
}
private static Task<DbConnectionInternal> GetCompletedTask()
{
Debug.Assert(Monitor.IsEntered(s_pendingOpenNonPooled), $"Expected {nameof(s_pendingOpenNonPooled)} lock to be held.");
return s_completedTask ?? (s_completedTask = Task.FromResult<DbConnectionInternal>(null));
}
private DbConnectionPool GetConnectionPool(DbConnection owningObject, DbConnectionPoolGroup connectionPoolGroup)
{
// if poolgroup is disabled, it will be replaced with a new entry
Debug.Assert(null != owningObject, "null owningObject?");
Debug.Assert(null != connectionPoolGroup, "null connectionPoolGroup?");
// It is possible that while the outer connection object has
// been sitting around in a closed and unused state in some long
// running app, the pruner may have come along and remove this
// the pool entry from the master list. If we were to use a
// pool entry in this state, we would create "unmanaged" pools,
// which would be bad. To avoid this problem, we automagically
// re-create the pool entry whenever it's disabled.
// however, don't rebuild connectionOptions if no pooling is involved - let new connections do that work
if (connectionPoolGroup.IsDisabled && (null != connectionPoolGroup.PoolGroupOptions))
{
// reusing existing pool option in case user originally used SetConnectionPoolOptions
DbConnectionPoolGroupOptions poolOptions = connectionPoolGroup.PoolGroupOptions;
// get the string to hash on again
DbConnectionOptions connectionOptions = connectionPoolGroup.ConnectionOptions;
Debug.Assert(null != connectionOptions, "prevent expansion of connectionString");
connectionPoolGroup = GetConnectionPoolGroup(connectionPoolGroup.PoolKey, poolOptions, ref connectionOptions);
Debug.Assert(null != connectionPoolGroup, "null connectionPoolGroup?");
SetConnectionPoolGroup(owningObject, connectionPoolGroup);
}
DbConnectionPool connectionPool = connectionPoolGroup.GetConnectionPool(this);
return connectionPool;
}
internal DbConnectionPoolGroup GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, ref DbConnectionOptions userConnectionOptions)
{
if (string.IsNullOrEmpty(key.ConnectionString))
{
return (DbConnectionPoolGroup)null;
}
DbConnectionPoolGroup connectionPoolGroup;
Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> connectionPoolGroups = _connectionPoolGroups;
if (!connectionPoolGroups.TryGetValue(key, out connectionPoolGroup) || (connectionPoolGroup.IsDisabled && (null != connectionPoolGroup.PoolGroupOptions)))
{
// If we can't find an entry for the connection string in
// our collection of pool entries, then we need to create a
// new pool entry and add it to our collection.
DbConnectionOptions connectionOptions = CreateConnectionOptions(key.ConnectionString, userConnectionOptions);
if (null == connectionOptions)
{
throw ADP.InternalConnectionError(ADP.ConnectionError.ConnectionOptionsMissing);
}
if (null == userConnectionOptions)
{ // we only allow one expansion on the connection string
userConnectionOptions = connectionOptions;
}
// We don't support connection pooling on Win9x
if (null == poolOptions)
{
if (null != connectionPoolGroup)
{
// reusing existing pool option in case user originally used SetConnectionPoolOptions
poolOptions = connectionPoolGroup.PoolGroupOptions;
}
else
{
// Note: may return null for non-pooled connections
poolOptions = CreateConnectionPoolGroupOptions(connectionOptions);
}
}
lock (this)
{
connectionPoolGroups = _connectionPoolGroups;
if (!connectionPoolGroups.TryGetValue(key, out connectionPoolGroup))
{
DbConnectionPoolGroup newConnectionPoolGroup = new DbConnectionPoolGroup(connectionOptions, key, poolOptions);
newConnectionPoolGroup.ProviderInfo = CreateConnectionPoolGroupProviderInfo(connectionOptions);
// build new dictionary with space for new connection string
Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> newConnectionPoolGroups = new Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup>(1 + connectionPoolGroups.Count);
foreach (KeyValuePair<DbConnectionPoolKey, DbConnectionPoolGroup> entry in connectionPoolGroups)
{
newConnectionPoolGroups.Add(entry.Key, entry.Value);
}
// lock prevents race condition with PruneConnectionPoolGroups
newConnectionPoolGroups.Add(key, newConnectionPoolGroup);
connectionPoolGroup = newConnectionPoolGroup;
_connectionPoolGroups = newConnectionPoolGroups;
}
else
{
Debug.Assert(!connectionPoolGroup.IsDisabled, "Disabled pool entry discovered");
}
}
Debug.Assert(null != connectionPoolGroup, "how did we not create a pool entry?");
Debug.Assert(null != userConnectionOptions, "how did we not have user connection options?");
}
else if (null == userConnectionOptions)
{
userConnectionOptions = connectionPoolGroup.ConnectionOptions;
}
return connectionPoolGroup;
}
private void PruneConnectionPoolGroups(object state)
{
// First, walk the pool release list and attempt to clear each
// pool, when the pool is finally empty, we dispose of it. If the
// pool isn't empty, it's because there are active connections or
// distributed transactions that need it.
lock (_poolsToRelease)
{
if (0 != _poolsToRelease.Count)
{
DbConnectionPool[] poolsToRelease = _poolsToRelease.ToArray();
foreach (DbConnectionPool pool in poolsToRelease)
{
if (null != pool)
{
pool.Clear();
if (0 == pool.Count)
{
_poolsToRelease.Remove(pool);
}
}
}
}
}
// Next, walk the pool entry release list and dispose of each
// pool entry when it is finally empty. If the pool entry isn't
// empty, it's because there are active pools that need it.
lock (_poolGroupsToRelease)
{
if (0 != _poolGroupsToRelease.Count)
{
DbConnectionPoolGroup[] poolGroupsToRelease = _poolGroupsToRelease.ToArray();
foreach (DbConnectionPoolGroup poolGroup in poolGroupsToRelease)
{
if (null != poolGroup)
{
int poolsLeft = poolGroup.Clear(); // may add entries to _poolsToRelease
if (0 == poolsLeft)
{
_poolGroupsToRelease.Remove(poolGroup);
}
}
}
}
}
// Finally, we walk through the collection of connection pool entries
// and prune each one. This will cause any empty pools to be put
// into the release list.
lock (this)
{
Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> connectionPoolGroups = _connectionPoolGroups;
Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> newConnectionPoolGroups = new Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup>(connectionPoolGroups.Count);
foreach (KeyValuePair<DbConnectionPoolKey, DbConnectionPoolGroup> entry in connectionPoolGroups)
{
if (null != entry.Value)
{
Debug.Assert(!entry.Value.IsDisabled, "Disabled pool entry discovered");
// entries start active and go idle during prune if all pools are gone
// move idle entries from last prune pass to a queue for pending release
// otherwise process entry which may move it from active to idle
if (entry.Value.Prune())
{ // may add entries to _poolsToRelease
QueuePoolGroupForRelease(entry.Value);
}
else
{
newConnectionPoolGroups.Add(entry.Key, entry.Value);
}
}
}
_connectionPoolGroups = newConnectionPoolGroups;
}
}
internal void QueuePoolForRelease(DbConnectionPool pool, bool clearing)
{
// Queue the pool up for release -- we'll clear it out and dispose
// of it as the last part of the pruning timer callback so we don't
// do it with the pool entry or the pool collection locked.
Debug.Assert(null != pool, "null pool?");
// set the pool to the shutdown state to force all active
// connections to be automatically disposed when they
// are returned to the pool
pool.Shutdown();
lock (_poolsToRelease)
{
if (clearing)
{
pool.Clear();
}
_poolsToRelease.Add(pool);
}
}
internal void QueuePoolGroupForRelease(DbConnectionPoolGroup poolGroup)
{
Debug.Assert(null != poolGroup, "null poolGroup?");
lock (_poolGroupsToRelease)
{
_poolGroupsToRelease.Add(poolGroup);
}
}
virtual protected DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
{
return CreateConnection(options, poolKey, poolGroupProviderInfo, pool, owningConnection);
}
internal DbMetaDataFactory GetMetaDataFactory(DbConnectionPoolGroup connectionPoolGroup, DbConnectionInternal internalConnection)
{
Debug.Assert(connectionPoolGroup != null, "connectionPoolGroup may not be null.");
// get the matadatafactory from the pool entry. If it does not already have one
// create one and save it on the pool entry
DbMetaDataFactory metaDataFactory = connectionPoolGroup.MetaDataFactory;
// consider serializing this so we don't construct multiple metadata factories
// if two threads happen to hit this at the same time. One will be GC'd
if (metaDataFactory == null)
{
bool allowCache = false;
metaDataFactory = CreateMetaDataFactory(internalConnection, out allowCache);
if (allowCache)
{
connectionPoolGroup.MetaDataFactory = metaDataFactory;
}
}
return metaDataFactory;
}
protected virtual DbMetaDataFactory CreateMetaDataFactory(DbConnectionInternal internalConnection, out bool cacheMetaDataFactory)
{
// providers that support GetSchema must override this with a method that creates a meta data
// factory appropriate for them.
cacheMetaDataFactory = false;
throw ADP.NotSupported();
}
abstract protected DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection);
abstract protected DbConnectionOptions CreateConnectionOptions(string connectionString, DbConnectionOptions previous);
abstract protected DbConnectionPoolGroupOptions CreateConnectionPoolGroupOptions(DbConnectionOptions options);
abstract internal DbConnectionPoolGroup GetConnectionPoolGroup(DbConnection connection);
abstract internal DbConnectionInternal GetInnerConnection(DbConnection connection);
abstract internal void PermissionDemand(DbConnection outerConnection);
abstract internal void SetConnectionPoolGroup(DbConnection outerConnection, DbConnectionPoolGroup poolGroup);
abstract internal void SetInnerConnectionEvent(DbConnection owningObject, DbConnectionInternal to);
abstract internal bool SetInnerConnectionFrom(DbConnection owningObject, DbConnectionInternal to, DbConnectionInternal from);
abstract internal void SetInnerConnectionTo(DbConnection owningObject, DbConnectionInternal to);
}
}
| |
// Copyright (c) 2012, Event Store LLP
// 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 Event Store LLP 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.Collections.Generic;
using System.Linq;
using EventStore.Common.Options;
using EventStore.Core;
using EventStore.Core.Bus;
using EventStore.Core.Messages;
using EventStore.Core.Messaging;
using EventStore.Core.Services.TimerService;
using EventStore.Core.Services.Transport.Http;
using EventStore.Core.TransactionLog.Chunks;
using EventStore.Core.Util;
using EventStore.Projections.Core.Messages;
using EventStore.Projections.Core.Messages.EventReaders.Feeds;
using EventStore.Projections.Core.Messaging;
using EventStore.Projections.Core.Services.AwakeReaderService;
using EventStore.Projections.Core.Services.Processing;
namespace EventStore.Projections.Core
{
public sealed class ProjectionsSubsystem : ISubsystem
{
private Projections _projections;
private readonly int _projectionWorkerThreadCount;
private readonly RunProjections _runProjections;
public ProjectionsSubsystem(int projectionWorkerThreadCount, RunProjections runProjections)
{
if (runProjections <= RunProjections.System)
_projectionWorkerThreadCount = 1;
else
_projectionWorkerThreadCount = projectionWorkerThreadCount;
_runProjections = runProjections;
}
public void Register(
TFChunkDb db, QueuedHandler mainQueue, ISubscriber mainBus, TimerService timerService,
ITimeProvider timeProvider, IHttpForwarder httpForwarder, HttpService[] httpServices, IPublisher networkSendService)
{
_projections = new EventStore.Projections.Core.Projections(
db, mainQueue, mainBus, timerService, timeProvider, httpForwarder, httpServices, networkSendService,
projectionWorkerThreadCount: _projectionWorkerThreadCount, runProjections: _runProjections);
}
public void Start()
{
_projections.Start();
}
public void Stop()
{
_projections.Stop();
}
}
sealed class Projections
{
public const int VERSION = 3;
private List<QueuedHandler> _coreQueues;
private readonly int _projectionWorkerThreadCount;
private QueuedHandler _managerInputQueue;
private InMemoryBus _managerInputBus;
private ProjectionManagerNode _projectionManagerNode;
public Projections(
TFChunkDb db, QueuedHandler mainQueue, ISubscriber mainBus, TimerService timerService, ITimeProvider timeProvider,
IHttpForwarder httpForwarder, HttpService[] httpServices, IPublisher networkSendQueue,
int projectionWorkerThreadCount, RunProjections runProjections)
{
_projectionWorkerThreadCount = projectionWorkerThreadCount;
SetupMessaging(
db, mainQueue, mainBus, timerService, timeProvider, httpForwarder, httpServices, networkSendQueue,
runProjections);
}
private void SetupMessaging(
TFChunkDb db, QueuedHandler mainQueue, ISubscriber mainBus, TimerService timerService, ITimeProvider timeProvider,
IHttpForwarder httpForwarder, HttpService[] httpServices, IPublisher networkSendQueue, RunProjections runProjections)
{
_coreQueues = new List<QueuedHandler>();
_managerInputBus = new InMemoryBus("manager input bus");
_managerInputQueue = new QueuedHandler(_managerInputBus, "Projections Master");
while (_coreQueues.Count < _projectionWorkerThreadCount)
{
var coreInputBus = new InMemoryBus("bus");
var coreQueue = new QueuedHandler(
coreInputBus, "Projection Core #" + _coreQueues.Count, groupName: "Projection Core");
var projectionNode = new ProjectionWorkerNode(db, coreQueue, timeProvider, runProjections);
projectionNode.SetupMessaging(coreInputBus);
var forwarder = new RequestResponseQueueForwarder(
inputQueue: coreQueue, externalRequestQueue: mainQueue);
// forwarded messages
projectionNode.CoreOutput.Subscribe<ClientMessage.ReadEvent>(forwarder);
projectionNode.CoreOutput.Subscribe<ClientMessage.ReadStreamEventsBackward>(forwarder);
projectionNode.CoreOutput.Subscribe<ClientMessage.ReadStreamEventsForward>(forwarder);
projectionNode.CoreOutput.Subscribe<ClientMessage.ReadAllEventsForward>(forwarder);
projectionNode.CoreOutput.Subscribe<ClientMessage.WriteEvents>(forwarder);
if (runProjections >= RunProjections.System)
{
projectionNode.CoreOutput.Subscribe(
Forwarder.Create<CoreProjectionManagementMessage.StateReport>(_managerInputQueue));
projectionNode.CoreOutput.Subscribe(
Forwarder.Create<CoreProjectionManagementMessage.ResultReport>(_managerInputQueue));
projectionNode.CoreOutput.Subscribe(
Forwarder.Create<CoreProjectionManagementMessage.StatisticsReport>(_managerInputQueue));
projectionNode.CoreOutput.Subscribe(
Forwarder.Create<CoreProjectionManagementMessage.Started>(_managerInputQueue));
projectionNode.CoreOutput.Subscribe(
Forwarder.Create<CoreProjectionManagementMessage.Stopped>(_managerInputQueue));
projectionNode.CoreOutput.Subscribe(
Forwarder.Create<CoreProjectionManagementMessage.Faulted>(_managerInputQueue));
projectionNode.CoreOutput.Subscribe(
Forwarder.Create<CoreProjectionManagementMessage.Prepared>(_managerInputQueue));
projectionNode.CoreOutput.Subscribe(
Forwarder.Create<CoreProjectionManagementMessage.SlaveProjectionReaderAssigned>(
_managerInputQueue));
projectionNode.CoreOutput.Subscribe(
Forwarder.Create<ProjectionManagementMessage.ControlMessage>(_managerInputQueue));
projectionNode.CoreOutput.Subscribe(
Forwarder.Create<AwakeReaderServiceMessage.SubscribeAwake>(mainQueue));
projectionNode.CoreOutput.Subscribe(
Forwarder.Create<AwakeReaderServiceMessage.UnsubscribeAwake>(mainQueue));
}
projectionNode.CoreOutput.Subscribe<TimerMessage.Schedule>(timerService);
projectionNode.CoreOutput.Subscribe(Forwarder.Create<Message>(coreQueue)); // forward all
coreInputBus.Subscribe(new UnwrapEnvelopeHandler());
_coreQueues.Add(coreQueue);
}
_managerInputBus.Subscribe(
Forwarder.CreateBalancing<FeedReaderMessage.ReadPage>(_coreQueues.Cast<IPublisher>().ToArray()));
var awakeReaderService = new AwakeReaderService();
mainBus.Subscribe<StorageMessage.EventCommited>(awakeReaderService);
mainBus.Subscribe<AwakeReaderServiceMessage.SubscribeAwake>(awakeReaderService);
mainBus.Subscribe<AwakeReaderServiceMessage.UnsubscribeAwake>(awakeReaderService);
_projectionManagerNode = ProjectionManagerNode.Create(
db, _managerInputQueue, httpForwarder, httpServices, networkSendQueue,
_coreQueues.Cast<IPublisher>().ToArray(), runProjections);
_projectionManagerNode.SetupMessaging(_managerInputBus);
{
var forwarder = new RequestResponseQueueForwarder(
inputQueue: _managerInputQueue, externalRequestQueue: mainQueue);
_projectionManagerNode.Output.Subscribe<ClientMessage.ReadEvent>(forwarder);
_projectionManagerNode.Output.Subscribe<ClientMessage.ReadStreamEventsBackward>(forwarder);
_projectionManagerNode.Output.Subscribe<ClientMessage.ReadStreamEventsForward>(forwarder);
_projectionManagerNode.Output.Subscribe<ClientMessage.WriteEvents>(forwarder);
_projectionManagerNode.Output.Subscribe(
Forwarder.Create<ProjectionManagementMessage.RequestSystemProjections>(mainQueue));
_projectionManagerNode.Output.Subscribe(Forwarder.Create<Message>(_managerInputQueue));
_projectionManagerNode.Output.Subscribe<TimerMessage.Schedule>(timerService);
// self forward all
mainBus.Subscribe(Forwarder.Create<SystemMessage.StateChangeMessage>(_managerInputQueue));
_managerInputBus.Subscribe(new UnwrapEnvelopeHandler());
}
}
public void Start()
{
if (_managerInputQueue != null)
_managerInputQueue.Start();
foreach (var queue in _coreQueues)
queue.Start();
}
public void Stop()
{
if (_managerInputQueue != null)
_managerInputQueue.Stop();
foreach (var queue in _coreQueues)
queue.Stop();
}
}
}
| |
using System;
using System.ComponentModel;
using System.IO;
using System.Web;
using System.Web.Mvc;
using HyperSlackers.Bootstrap;
using System.Diagnostics.Contracts;
using System.Text;
using HyperSlackers.Bootstrap.Core;
using HyperSlackers.Bootstrap.Extensions;
namespace HyperSlackers.Bootstrap.Controls
{
/// <summary>
/// Constructs a Bootstrap Carousel.
/// </summary>
/// <typeparam name="TModel">The model.</typeparam>
public class CarouselBuilder<TModel> : DisposableHtmlElement<TModel, Carousel>
{
internal readonly UrlHelper urlHelper;
internal bool isFirstItem = true;
private bool disposed;
/// <summary>
/// Initializes a new instance of the <see cref="CarouselBuilder{TModel}"/> class.
/// </summary>
/// <param name="html">The HTML.</param>
/// <param name="carousel">The carousel.</param>
internal CarouselBuilder(HtmlHelper<TModel> html, Carousel carousel)
: base(html, carousel)
{
Contract.Requires<ArgumentNullException>(html != null, "html");
Contract.Requires<ArgumentNullException>(carousel != null, "carousel");
urlHelper = new UrlHelper(html.ViewContext.RequestContext);
textWriter.Write(element.StartTag);
RenderIndicators(carousel.indicators);
textWriter.Write("<div class=\"carousel-inner\">");
}
/// <summary>
/// Adds an image panel to the <see cref="Carousel"/>.
/// </summary>
/// <param name="imageUrl">The image URL.</param>
/// <param name="altText">The image alt text.</param>
/// <param name="htmlAttributes">The HTML attributes.</param>
/// <returns></returns>
public IHtmlString Image(string imageUrl, string altText, object htmlAttributes = null)
{
Contract.Requires<ArgumentException>(!imageUrl.IsNullOrWhiteSpace());
Contract.Requires<ArgumentNullException>(altText != null, "altText");
Contract.Ensures(Contract.Result<IHtmlString>() != null);
return MvcHtmlString.Create(GetPanelHtml(imageUrl, altText, string.Empty, string.Empty, string.Empty, htmlAttributes));
}
/// <summary>
/// Adds an image panel (with caption) to the <see cref="Carousel" />.
/// </summary>
/// <param name="imageUrl">The image URL.</param>
/// <param name="altText">The image alt text.</param>
/// <param name="captionHeader">The caption header.</param>
/// <param name="captionBody">The caption body.</param>
/// <param name="htmlAttributes">The HTML attributes.</param>
/// <returns></returns>
public IHtmlString Image(string imageUrl, string altText, string captionHeader, string captionBody, object htmlAttributes = null)
{
Contract.Requires<ArgumentException>(!imageUrl.IsNullOrWhiteSpace());
Contract.Requires<ArgumentNullException>(altText != null, "altText");
Contract.Ensures(Contract.Result<IHtmlString>() != null);
return MvcHtmlString.Create(GetPanelHtml(imageUrl, altText, captionHeader, captionBody, string.Empty, htmlAttributes));
}
/// <summary>
/// Adds an image panel (with click-able caption) to the <see cref="Carousel" />.
/// </summary>
/// <param name="imageUrl">The image URL.</param>
/// <param name="altText">The image alt text.</param>
/// <param name="captionHeader">The caption header.</param>
/// <param name="captionBody">The caption body.</param>
/// <param name="captionUrl">The URL to navigate to.</param>
/// <param name="htmlAttributes">The HTML attributes.</param>
/// <returns></returns>
public IHtmlString Image(string imageUrl, string altText, string captionHeader, string captionBody, string captionUrl, object htmlAttributes = null)
{
Contract.Requires<ArgumentException>(!imageUrl.IsNullOrWhiteSpace());
Contract.Requires<ArgumentNullException>(altText != null, "altText");
Contract.Ensures(Contract.Result<IHtmlString>() != null);
return MvcHtmlString.Create(GetPanelHtml(imageUrl, altText, captionHeader, captionBody, captionUrl, htmlAttributes));
}
/// <summary>
/// Creates a panel to accept custom HTML.
/// </summary>
/// <returns></returns>
public CarouselCustomItem BeginCustomPanel()
{
bool isFirstItem = this.isFirstItem;
this.isFirstItem = false;
return new CarouselCustomItem(textWriter, urlHelper, isFirstItem);
}
/// <summary>
/// Creates an image panel to accept custom caption HTML.
/// </summary>
/// <param name="imageUrl">The image URL.</param>
/// <param name="altText">The alt text.</param>
/// <param name="htmlAttributes">The HTML attributes.</param>
/// <returns></returns>
public CarouselCaptionPanel BeginImagePanelWithCaption(string imageUrl, string altText, object htmlAttributes = null)
{
Contract.Requires<ArgumentException>(!imageUrl.IsNullOrWhiteSpace());
Contract.Requires<ArgumentNullException>(altText != null, "imageAltText");
textWriter.Write(GetPanelHtml(imageUrl, altText, string.Empty, string.Empty, string.Empty, htmlAttributes, true));
return new CarouselCaptionPanel(textWriter);
}
/// <summary>
/// Renders the indicators, if specified.
/// </summary>
/// <param name="indicators">The indicator count.</param>
private void RenderIndicators(uint indicators)
{
if (indicators == 0)
{
return;
}
textWriter.Write("<ol class=\"carousel-indicators\">");
for (int i = 0; i < indicators; i++)
{
textWriter.Write("<li data-target=\"#{0}\" data-slide-to=\"{1}\"".FormatWith(element.id, i));
if (i == 0)
{
textWriter.Write(" class=\"active\"");
}
textWriter.Write("></li> ");
}
textWriter.Write("</ol>");
}
/// <summary>
/// Generates th HTML markup for the panel.
/// </summary>
/// <param name="imageUrl">The image URL.</param>
/// <param name="altText">The alt text.</param>
/// <param name="captionHeader">The caption header.</param>
/// <param name="captionBody">The caption body.</param>
/// <param name="captionUrl">The caption URL.</param>
/// <param name="htmlAttributes">The HTML attributes.</param>
/// <param name="isDisposable">if set to <c>true</c> [is disposable].</param>
/// <returns></returns>
private string GetPanelHtml(string imageUrl, string altText, string captionHeader, string captionBody, string captionUrl, object htmlAttributes, bool isDisposable = false)
{
Contract.Requires<ArgumentException>(!imageUrl.IsNullOrWhiteSpace());
Contract.Requires<ArgumentNullException>(altText != null, "altText");
//x Contract.Requires<ArgumentNullException>(captionHeader != null, "captionHeader");
//x Contract.Requires<ArgumentNullException>(captionBody != null, "captionBody");
//x Contract.Requires<ArgumentNullException>(captionUrl != null, "captionUrl");
//x Contract.Requires<ArgumentNullException>(htmlAttributes != null, "htmlAttributes");
Contract.Ensures(!Contract.Result<string>().IsNullOrWhiteSpace());
TagBuilder divTagBuilder = new TagBuilder("div");
divTagBuilder.AddCssClass("item");
if (isFirstItem)
{
divTagBuilder.AddCssClass("active");
isFirstItem = false;
}
string imageHtml = GetImageHtml(imageUrl, altText, htmlAttributes);
string captionHtml = GetCaptionHtml(captionHeader, captionBody, captionUrl);
string htmlWithoutEndTag;
if (!captionUrl.IsNullOrWhiteSpace())
{
htmlWithoutEndTag = divTagBuilder.ToString(TagRenderMode.StartTag) + "<a href=\"" + captionUrl + "\">" + imageHtml + captionHtml + "</a>";
}
else
{
htmlWithoutEndTag = divTagBuilder.ToString(TagRenderMode.StartTag) + imageHtml + captionHtml;
}
return htmlWithoutEndTag + (isDisposable ? string.Empty : divTagBuilder.ToString(TagRenderMode.EndTag));
}
/// <summary>
/// Gets the HTML tag for the panel image.
/// </summary>
/// <param name="imageUrl">The image URL.</param>
/// <param name="altText">The alt text.</param>
/// <param name="htmlAttributes">The HTML attributes.</param>
/// <returns></returns>
private string GetImageHtml(string imageUrl, string altText, object htmlAttributes)
{
Contract.Requires<ArgumentException>(!imageUrl.IsNullOrWhiteSpace());
Contract.Requires<ArgumentNullException>(altText != null, "altText");
Contract.Ensures(!Contract.Result<string>().IsNullOrWhiteSpace());
TagBuilder tagBuilder = new TagBuilder("img");
tagBuilder.MergeHtmlAttributes(htmlAttributes.ToDictionary().FormatHtmlAttributes());
tagBuilder.MergeAttribute("src", urlHelper.Content(imageUrl));
tagBuilder.MergeAttribute("alt", altText);
return tagBuilder.ToString(TagRenderMode.SelfClosing);
}
/// <summary>
/// Gets the caption HTML.
/// </summary>
/// <param name="header">The header.</param>
/// <param name="body">The body.</param>
/// <param name="url">The URL.</param>
/// <returns></returns>
private string GetCaptionHtml(string header, string body, string url)
{
Contract.Ensures(!Contract.Result<string>().IsNullOrWhiteSpace());
StringBuilder html = new StringBuilder();
string headerHtml = header.IsNullOrWhiteSpace() ? string.Empty : "<h3>" + header + "</h3>";
string bodyHtml = body.IsNullOrWhiteSpace() ? string.Empty : "<p>" + body + "</p>";
string captionHtml = headerHtml + bodyHtml;
if (!url.IsNullOrWhiteSpace())
{
captionHtml = "<a href=\"" + url + "\">" + captionHtml + "</a>";
}
return "<div class=\"carousel-caption\">" + captionHtml + "</div>";
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// REnders any closing HTML necessary.
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected override void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
textWriter.Write("</div>");
textWriter.Write("<a class=\"left carousel-control\" data-slide=\"prev\" href=\"#{0}\">{1}</a>".FormatWith(element.id, element.prevIcon.ToString()));
textWriter.Write("<a class=\"right carousel-control\" data-slide=\"next\" href=\"#{0}\">{1}</a>".FormatWith(element.id, element.nextIcon.ToString()));
textWriter.Write(element.EndTag);
if (element.withJs)
{
textWriter.Write("<script type=\"text/javascript\">\r\n $(document).ready(function(){{\r\n $('#{0}').carousel({{\r\n interval: {1}\r\n }})\r\n }});\r\n</script>".FormatWith(element.id, element.interval));
}
disposed = true;
}
}
// closing tag handled above, do not call base class
//x base.Dispose(disposing);
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WebsitePanel.Portal.ProviderControls {
public partial class IceWarp_EditDomain {
/// <summary>
/// lblPostMaster control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblPostMaster;
/// <summary>
/// ddlPostMasterAccount control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList ddlPostMasterAccount;
/// <summary>
/// lblCatchAll control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblCatchAll;
/// <summary>
/// ddlCatchAllAccount control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList ddlCatchAllAccount;
/// <summary>
/// AdvancedSettingsPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel AdvancedSettingsPanel;
/// <summary>
/// secLimits control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secLimits;
/// <summary>
/// LimitsPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel LimitsPanel;
/// <summary>
/// rowMaxDomainDiskSpace control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlTableRow rowMaxDomainDiskSpace;
/// <summary>
/// lblMaxDomainDiskSpace control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblMaxDomainDiskSpace;
/// <summary>
/// txtMaxDomainDiskSpace control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtMaxDomainDiskSpace;
/// <summary>
/// MaxDomainDiskSpaceValidator control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RangeValidator MaxDomainDiskSpaceValidator;
/// <summary>
/// MaxDomainDiskSpaceRequiredValidator control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RequiredFieldValidator MaxDomainDiskSpaceRequiredValidator;
/// <summary>
/// lblMaxDomainUsers control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblMaxDomainUsers;
/// <summary>
/// txtMaxDomainUsers control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtMaxDomainUsers;
/// <summary>
/// MaxDomainUsersValidator control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RangeValidator MaxDomainUsersValidator;
/// <summary>
/// MaxDomainUsersRequiredValidator control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RequiredFieldValidator MaxDomainUsersRequiredValidator;
/// <summary>
/// rowDomainLimits control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl rowDomainLimits;
/// <summary>
/// lblLimitVolume control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblLimitVolume;
/// <summary>
/// txtLimitVolume control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtLimitVolume;
/// <summary>
/// txtLimitVolumeValidator control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RangeValidator txtLimitVolumeValidator;
/// <summary>
/// txtLimitVolumeRequiredValidator control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RequiredFieldValidator txtLimitVolumeRequiredValidator;
/// <summary>
/// lblLimitNumber control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblLimitNumber;
/// <summary>
/// txtLimitNumber control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtLimitNumber;
/// <summary>
/// txtLimitNumberValidator control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RangeValidator txtLimitNumberValidator;
/// <summary>
/// txtLimitNumberRequiredValidator control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RequiredFieldValidator txtLimitNumberRequiredValidator;
/// <summary>
/// rowUserLimits control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl rowUserLimits;
/// <summary>
/// lblDefaultUserQuotaInMB control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblDefaultUserQuotaInMB;
/// <summary>
/// txtDefaultUserQuotaInMB control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtDefaultUserQuotaInMB;
/// <summary>
/// txtDefaultUserQuotaInMBValidator control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RangeValidator txtDefaultUserQuotaInMBValidator;
/// <summary>
/// txtDefaultUserQuotaInMBRequiredValidator control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RequiredFieldValidator txtDefaultUserQuotaInMBRequiredValidator;
/// <summary>
/// lblDefaultUserMaxMessageSizeMegaByte control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblDefaultUserMaxMessageSizeMegaByte;
/// <summary>
/// txtDefaultUserMaxMessageSizeMegaByte control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtDefaultUserMaxMessageSizeMegaByte;
/// <summary>
/// txtDefaultUserMaxMessageSizeMegaByteValidator control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RangeValidator txtDefaultUserMaxMessageSizeMegaByteValidator;
/// <summary>
/// txtDefaultUserMaxMessageSizeMegaByteRequiredValidator control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RequiredFieldValidator txtDefaultUserMaxMessageSizeMegaByteRequiredValidator;
/// <summary>
/// lblDefaultUserMegaByteSendLimit control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblDefaultUserMegaByteSendLimit;
/// <summary>
/// txtDefaultUserMegaByteSendLimit control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtDefaultUserMegaByteSendLimit;
/// <summary>
/// txtDefaultUserMegaByteSendLimitValidator control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RangeValidator txtDefaultUserMegaByteSendLimitValidator;
/// <summary>
/// txtDefaultUserMegaByteSendLimitRequiredValidator control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RequiredFieldValidator txtDefaultUserMegaByteSendLimitRequiredValidator;
/// <summary>
/// lblDefaultUserNumberSendLimit control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblDefaultUserNumberSendLimit;
/// <summary>
/// txtDefaultUserNumberSendLimit control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtDefaultUserNumberSendLimit;
/// <summary>
/// txtDefaultUserNumberSendLimitValidator control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RangeValidator txtDefaultUserNumberSendLimitValidator;
/// <summary>
/// txtDefaultUserNumberSendLimitRequiredValidator control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RequiredFieldValidator txtDefaultUserNumberSendLimitRequiredValidator;
}
}
| |
//---------------------------------------------------------------------
// <copyright file="TypeReference.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System.CodeDom;
using System.Collections.Generic;
using System.Data.Common.Utils;
namespace System.Data.EntityModel.Emitters
{
/// <summary>
/// Summary description for TypeReferences.
/// </summary>
internal class TypeReference
{
#region Fields
internal static readonly Type ObjectContextBaseClassType = typeof(System.Data.Services.Client.DataServiceContext);
public const string FQMetaDataWorkspaceTypeName = "System.Data.Metadata.Edm.MetadataWorkspace";
private static CodeTypeReference _byteArray;
private static CodeTypeReference _dateTime;
private static CodeTypeReference _guid;
private static CodeTypeReference _objectContext;
private readonly Memoizer<Type, CodeTypeReference> _forTypeMemoizer;
private readonly Memoizer<Type, CodeTypeReference> _nullableForTypeMemoizer;
private readonly Memoizer<KeyValuePair<string, bool>, CodeTypeReference> _fromStringMemoizer;
private readonly Memoizer<KeyValuePair<string, CodeTypeReference>, CodeTypeReference> _fromStringGenericMemoizer;
#endregion
#region Constructors
internal TypeReference()
{
_forTypeMemoizer = new Memoizer<Type, CodeTypeReference>(ComputeForType, null);
_fromStringMemoizer = new Memoizer<KeyValuePair<string, bool>, CodeTypeReference>(ComputeFromString, null);
_nullableForTypeMemoizer = new Memoizer<Type, CodeTypeReference>(ComputeNullableForType, null);
_fromStringGenericMemoizer = new Memoizer<KeyValuePair<string, CodeTypeReference>, CodeTypeReference>(ComputeFromStringGeneric, null);
}
#endregion
#region Public Methods
/// <summary>
/// Get TypeReference for a type represented by a Type object
/// </summary>
/// <param name="type">the type object</param>
/// <returns>the associated TypeReference object</returns>
public CodeTypeReference ForType(Type type)
{
return _forTypeMemoizer.Evaluate(type);
}
private CodeTypeReference ComputeForType(Type type)
{
// we know that we can safely global:: qualify this because it was already
// compiled before we are emitting or else we wouldn't have a Type object
CodeTypeReference value = new CodeTypeReference(type, CodeTypeReferenceOptions.GlobalReference);
return value;
}
/// <summary>
/// Get TypeReference for a type represented by a Generic Type object.
/// We don't cache the TypeReference for generic type object since the type would be the same
/// irresepective of the generic arguments. We could potentially cache it using both the type name
/// and generic type arguments.
/// </summary>
/// <param name="type">the generic type object</param>
/// <returns>the associated TypeReference object</returns>
public CodeTypeReference ForType(Type generic, params CodeTypeReference[] argument)
{
// we know that we can safely global:: qualify this because it was already
// compiled before we are emitting or else we wouldn't have a Type object
CodeTypeReference typeRef = new CodeTypeReference(generic, CodeTypeReferenceOptions.GlobalReference);
if ((null != argument) && (0 < argument.Length))
{
typeRef.TypeArguments.AddRange(argument);
}
return typeRef;
}
/// <summary>
/// Get TypeReference for a type represented by a namespace quailifed string
/// </summary>
/// <param name="type">namespace qualified string</param>
/// <returns>the TypeReference</returns>
public CodeTypeReference FromString(string type)
{
return FromString(type, false);
}
/// <summary>
/// Get TypeReference for a type represented by a namespace quailifed string,
/// with optional global qualifier
/// </summary>
/// <param name="type">namespace qualified string</param>
/// <param name="addGlobalQualifier">indicates whether the global qualifier should be added</param>
/// <returns>the TypeReference</returns>
public CodeTypeReference FromString(string type, bool addGlobalQualifier)
{
return _fromStringMemoizer.Evaluate(new KeyValuePair<string, bool>(type, addGlobalQualifier));
}
private CodeTypeReference ComputeFromString(KeyValuePair<string, bool> arguments)
{
string type = arguments.Key;
bool addGlobalQualifier = arguments.Value;
CodeTypeReference value;
if (addGlobalQualifier)
{
value = new CodeTypeReference(type, CodeTypeReferenceOptions.GlobalReference);
}
else
{
value = new CodeTypeReference(type);
}
return value;
}
/// <summary>
/// Get TypeReference for a framework type
/// </summary>
/// <param name="name">unqualified name of the framework type</param>
/// <returns>the TypeReference</returns>
public CodeTypeReference AdoFrameworkType(string name)
{
return FromString(Utils.WebFrameworkNamespace + "." + name, true);
}
/// <summary>
/// Get TypeReference for a bound generic framework class
/// </summary>
/// <param name="name">the name of the generic framework class</param>
/// <param name="typeParameter">the type parameter for the framework class</param>
/// <returns>TypeReference for the bound framework class</returns>
public CodeTypeReference AdoFrameworkGenericClass(string name, CodeTypeReference typeParameter)
{
return FrameworkGenericClass(Utils.WebFrameworkNamespace, name, typeParameter);
}
/// <summary>
/// Get TypeReference for a bound generic framework class
/// </summary>
/// <param name="namespaceName">the namespace of the generic framework class</param>
/// <param name="name">the name of the generic framework class</param>
/// <param name="typeParameter">the type parameter for the framework class</param>
/// <returns>TypeReference for the bound framework class</returns>
public CodeTypeReference FrameworkGenericClass(string namespaceName, string name, CodeTypeReference typeParameter)
{
return FrameworkGenericClass(namespaceName + "." + name, typeParameter);
}
/// <summary>
/// Get TypeReference for a bound generic framework class
/// </summary>
/// <param name="fullname">the fully qualified name of the generic framework class</param>
/// <param name="typeParameter">the type parameter for the framework class</param>
/// <returns>TypeReference for the bound framework class</returns>
public CodeTypeReference FrameworkGenericClass(string fullname, CodeTypeReference typeParameter)
{
return _fromStringGenericMemoizer.Evaluate(new KeyValuePair<string, CodeTypeReference>(fullname, typeParameter));
}
private CodeTypeReference ComputeFromStringGeneric(KeyValuePair<string, CodeTypeReference> arguments)
{
string name = arguments.Key;
CodeTypeReference typeParameter = arguments.Value;
CodeTypeReference typeRef = ComputeFromString(new KeyValuePair<string, bool>(name, true));
typeRef.TypeArguments.Add(typeParameter);
return typeRef;
}
/// <summary>
/// Get TypeReference for a bound Nullable<T>
/// </summary>
/// <param name="innerType">Type of the Nullable<T> type parameter</param>
/// <returns>TypeReference for a bound Nullable<T></returns>
public CodeTypeReference NullableForType(Type innerType)
{
return _nullableForTypeMemoizer.Evaluate(innerType);
}
private CodeTypeReference ComputeNullableForType(Type innerType)
{
// can't use FromString because it will return the same Generic type reference
// but it will already have a previous type parameter (because of caching)
CodeTypeReference typeRef = new CodeTypeReference(typeof(System.Nullable<>), CodeTypeReferenceOptions.GlobalReference);
typeRef.TypeArguments.Add(ForType(innerType));
return typeRef;
}
#endregion
#region Public Properties
/// <summary>
/// Gets a CodeTypeReference to the System.Byte[] type.
/// </summary>
/// <value></value>
public CodeTypeReference ByteArray
{
get
{
if (_byteArray == null)
_byteArray = ForType(typeof(byte[]));
return _byteArray;
}
}
/// <summary>
/// Gets a CodeTypeReference object for the System.DateTime type.
/// </summary>
public CodeTypeReference DateTime
{
get
{
if (_dateTime == null)
_dateTime = ForType(typeof(System.DateTime));
return _dateTime;
}
}
/// <summary>
/// Gets a CodeTypeReference object for the System.Guid type.
/// </summary>
public CodeTypeReference Guid
{
get
{
if (_guid == null)
_guid = ForType(typeof(System.Guid));
return _guid;
}
}
/// <summary>
/// TypeReference for the Framework's ObjectContext class
/// </summary>
public CodeTypeReference ObjectContext
{
get
{
if (_objectContext == null)
{
_objectContext = AdoFrameworkType("DataServiceContext");
}
return _objectContext;
}
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="Trace.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
*/
#define TRACE
namespace System.Diagnostics {
using System;
using System.Collections;
using System.Security.Permissions;
using System.Threading;
/// <devdoc>
/// <para>Provides a set of properties and methods to trace the execution of your code.</para>
/// </devdoc>
public sealed class Trace {
private static volatile CorrelationManager correlationManager = null;
// not creatble...
//
private Trace() {
}
/// <devdoc>
/// <para>Gets the collection of listeners that is monitoring the trace output.</para>
/// </devdoc>
public static TraceListenerCollection Listeners {
[HostProtection(SharedState=true)]
get {
// Do a full damand
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
return TraceInternal.Listeners;
}
}
/// <devdoc>
/// <para>
/// Gets or sets whether <see cref='System.Diagnostics.Trace.Flush'/> should be called on the <see cref='System.Diagnostics.Trace.Listeners'/> after every write.
/// </para>
/// </devdoc>
public static bool AutoFlush {
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
get {
return TraceInternal.AutoFlush;
}
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
set {
TraceInternal.AutoFlush = value;
}
}
public static bool UseGlobalLock {
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
get {
return TraceInternal.UseGlobalLock;
}
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
set {
TraceInternal.UseGlobalLock = value;
}
}
public static CorrelationManager CorrelationManager {
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
get {
if (correlationManager == null)
correlationManager = new CorrelationManager();
return correlationManager;
}
}
/// <devdoc>
/// <para>Gets or sets the indent level.</para>
/// </devdoc>
public static int IndentLevel {
get { return TraceInternal.IndentLevel; }
set { TraceInternal.IndentLevel = value; }
}
/// <devdoc>
/// <para>
/// Gets or sets the number of spaces in an indent.
/// </para>
/// </devdoc>
public static int IndentSize {
get { return TraceInternal.IndentSize; }
set { TraceInternal.IndentSize = value; }
}
/// <devdoc>
/// <para>Clears the output buffer, and causes buffered data to
/// be written to the <see cref='System.Diagnostics.Trace.Listeners'/>.</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Flush() {
TraceInternal.Flush();
}
/// <devdoc>
/// <para>Clears the output buffer, and then closes the <see cref='System.Diagnostics.Trace.Listeners'/> so that they no
/// longer receive debugging output.</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Close() {
// Do a full damand
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
TraceInternal.Close();
}
/// <devdoc>
/// <para>Checks for a condition, and outputs the callstack if the
/// condition
/// is <see langword='false'/>.</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Assert(bool condition) {
TraceInternal.Assert(condition);
}
/// <devdoc>
/// <para>Checks for a condition, and displays a message if the condition is
/// <see langword='false'/>. </para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Assert(bool condition, string message) {
TraceInternal.Assert(condition, message);
}
/// <devdoc>
/// <para>Checks for a condition, and displays both messages if the condition
/// is <see langword='false'/>. </para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Assert(bool condition, string message, string detailMessage) {
TraceInternal.Assert(condition, message, detailMessage);
}
/// <devdoc>
/// <para>Emits or displays a message for an assertion that always fails.</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Fail(string message) {
TraceInternal.Fail(message);
}
/// <devdoc>
/// <para>Emits or displays both messages for an assertion that always fails.</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Fail(string message, string detailMessage) {
TraceInternal.Fail(message, detailMessage);
}
public static void Refresh() {
#if CONFIGURATION_DEP
DiagnosticsConfiguration.Refresh();
#endif
Switch.RefreshAll();
TraceSource.RefreshAll();
TraceInternal.Refresh();
}
[System.Diagnostics.Conditional("TRACE")]
public static void TraceInformation(string message) {
TraceInternal.TraceEvent(TraceEventType.Information, 0, message, null);
}
[System.Diagnostics.Conditional("TRACE")]
public static void TraceInformation(string format, params object[] args) {
TraceInternal.TraceEvent(TraceEventType.Information, 0, format, args);
}
[System.Diagnostics.Conditional("TRACE")]
public static void TraceWarning(string message) {
TraceInternal.TraceEvent(TraceEventType.Warning, 0, message, null);
}
[System.Diagnostics.Conditional("TRACE")]
public static void TraceWarning(string format, params object[] args) {
TraceInternal.TraceEvent(TraceEventType.Warning, 0, format, args);
}
[System.Diagnostics.Conditional("TRACE")]
public static void TraceError(string message) {
TraceInternal.TraceEvent(TraceEventType.Error, 0, message, null);
}
[System.Diagnostics.Conditional("TRACE")]
public static void TraceError(string format, params object[] args) {
TraceInternal.TraceEvent(TraceEventType.Error, 0, format, args);
}
/// <devdoc>
/// <para>Writes a message to the trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/>
/// collection.</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Write(string message) {
TraceInternal.Write(message);
}
/// <devdoc>
/// <para>Writes the name of the <paramref name="value "/>
/// parameter to the trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection.</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Write(object value) {
TraceInternal.Write(value);
}
/// <devdoc>
/// <para>Writes a category name and message to the trace listeners
/// in the <see cref='System.Diagnostics.Trace.Listeners'/> collection.</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Write(string message, string category) {
TraceInternal.Write(message, category);
}
/// <devdoc>
/// <para>Writes a category name and the name of the value parameter to the trace listeners
/// in the <see cref='System.Diagnostics.Trace.Listeners'/> collection.</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Write(object value, string category) {
TraceInternal.Write(value, category);
}
/// <devdoc>
/// <para>Writes a message followed by a line terminator to the
/// trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection.
/// The default line terminator is a carriage return followed by a line feed (\r\n).</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void WriteLine(string message) {
TraceInternal.WriteLine(message);
}
/// <devdoc>
/// <para>Writes the name of the <paramref name="value "/> parameter followed by a line terminator to the trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection. The default line
/// terminator is a carriage return followed by a line feed (\r\n).</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void WriteLine(object value) {
TraceInternal.WriteLine(value);
}
/// <devdoc>
/// <para>Writes a category name and message followed by a line terminator to the trace
/// listeners in the <see cref='System.Diagnostics.Trace.Listeners'/>
/// collection. The default line terminator is a carriage return followed by a line
/// feed (\r\n).</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void WriteLine(string message, string category) {
TraceInternal.WriteLine(message, category);
}
/// <devdoc>
/// <para>Writes a <paramref name="category "/>name and the name of the <paramref name="value "/> parameter followed by a line
/// terminator to the trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection. The default line
/// terminator is a carriage return followed by a line feed (\r\n).</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void WriteLine(object value, string category) {
TraceInternal.WriteLine(value, category);
}
/// <devdoc>
/// <para>Writes a message to the trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection
/// if a condition is <see langword='true'/>.</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void WriteIf(bool condition, string message) {
TraceInternal.WriteIf(condition, message);
}
/// <devdoc>
/// <para>Writes the name of the <paramref name="value "/>
/// parameter to the trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection if a condition is
/// <see langword='true'/>. </para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void WriteIf(bool condition, object value) {
TraceInternal.WriteIf(condition, value);
}
/// <devdoc>
/// <para>Writes a category name and message to the trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/>
/// collection if a condition is <see langword='true'/>. </para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void WriteIf(bool condition, string message, string category) {
TraceInternal.WriteIf(condition, message, category);
}
/// <devdoc>
/// <para>Writes a category name and the name of the <paramref name="value"/> parameter to the trace
/// listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection
/// if a condition is <see langword='true'/>. </para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void WriteIf(bool condition, object value, string category) {
TraceInternal.WriteIf(condition, value, category);
}
/// <devdoc>
/// <para>Writes a message followed by a line terminator to the trace listeners in the
/// <see cref='System.Diagnostics.Trace.Listeners'/> collection if a condition is
/// <see langword='true'/>. The default line terminator is a carriage return followed
/// by a line feed (\r\n).</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void WriteLineIf(bool condition, string message) {
TraceInternal.WriteLineIf(condition, message);
}
/// <devdoc>
/// <para>Writes the name of the <paramref name="value"/> parameter followed by a line terminator to the
/// trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection
/// if a condition is
/// <see langword='true'/>. The default line
/// terminator is a carriage return followed by a line feed (\r\n).</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void WriteLineIf(bool condition, object value) {
TraceInternal.WriteLineIf(condition, value);
}
/// <devdoc>
/// <para>Writes a category name and message followed by a line terminator to the trace
/// listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection if a condition is
/// <see langword='true'/>. The default line terminator is a carriage return followed by a line feed (\r\n).</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void WriteLineIf(bool condition, string message, string category) {
TraceInternal.WriteLineIf(condition, message, category);
}
/// <devdoc>
/// <para>Writes a category name and the name of the <paramref name="value "/> parameter followed by a line
/// terminator to the trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection
/// if a <paramref name="condition"/> is <see langword='true'/>. The
/// default line terminator is a carriage return followed by a line feed (\r\n).</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void WriteLineIf(bool condition, object value, string category) {
TraceInternal.WriteLineIf(condition, value, category);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Indent() {
TraceInternal.Indent();
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Unindent() {
TraceInternal.Unindent();
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using JetBrains.Annotations;
using osu.Game.Audio;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Beatmaps.Legacy;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Legacy;
using osu.Game.Rulesets.Objects.Types;
using osu.Game.Skinning;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Beatmaps.Formats
{
public class LegacyBeatmapEncoder
{
public const int LATEST_VERSION = 128;
/// <summary>
/// osu! is generally slower than taiko, so a factor is added to increase
/// speed. This must be used everywhere slider length or beat length is used.
/// </summary>
public const float LEGACY_TAIKO_VELOCITY_MULTIPLIER = 1.4f;
private readonly IBeatmap beatmap;
[CanBeNull]
private readonly ISkin skin;
private readonly int onlineRulesetID;
/// <summary>
/// Creates a new <see cref="LegacyBeatmapEncoder"/>.
/// </summary>
/// <param name="beatmap">The beatmap to encode.</param>
/// <param name="skin">The beatmap's skin, used for encoding combo colours.</param>
public LegacyBeatmapEncoder(IBeatmap beatmap, [CanBeNull] ISkin skin)
{
this.beatmap = beatmap;
this.skin = skin;
onlineRulesetID = beatmap.BeatmapInfo.Ruleset.OnlineID;
if (onlineRulesetID < 0 || onlineRulesetID > 3)
throw new ArgumentException("Only beatmaps in the osu, taiko, catch, or mania rulesets can be encoded to the legacy beatmap format.", nameof(beatmap));
}
public void Encode(TextWriter writer)
{
writer.WriteLine($"osu file format v{LATEST_VERSION}");
writer.WriteLine();
handleGeneral(writer);
writer.WriteLine();
handleEditor(writer);
writer.WriteLine();
handleMetadata(writer);
writer.WriteLine();
handleDifficulty(writer);
writer.WriteLine();
handleEvents(writer);
writer.WriteLine();
handleControlPoints(writer);
writer.WriteLine();
handleColours(writer);
writer.WriteLine();
handleHitObjects(writer);
}
private void handleGeneral(TextWriter writer)
{
writer.WriteLine("[General]");
if (!string.IsNullOrEmpty(beatmap.Metadata.AudioFile)) writer.WriteLine(FormattableString.Invariant($"AudioFilename: {Path.GetFileName(beatmap.Metadata.AudioFile)}"));
writer.WriteLine(FormattableString.Invariant($"AudioLeadIn: {beatmap.BeatmapInfo.AudioLeadIn}"));
writer.WriteLine(FormattableString.Invariant($"PreviewTime: {beatmap.Metadata.PreviewTime}"));
writer.WriteLine(FormattableString.Invariant($"Countdown: {(int)beatmap.BeatmapInfo.Countdown}"));
writer.WriteLine(FormattableString.Invariant($"SampleSet: {toLegacySampleBank((beatmap.HitObjects.FirstOrDefault()?.SampleControlPoint ?? SampleControlPoint.DEFAULT).SampleBank)}"));
writer.WriteLine(FormattableString.Invariant($"StackLeniency: {beatmap.BeatmapInfo.StackLeniency}"));
writer.WriteLine(FormattableString.Invariant($"Mode: {onlineRulesetID}"));
writer.WriteLine(FormattableString.Invariant($"LetterboxInBreaks: {(beatmap.BeatmapInfo.LetterboxInBreaks ? '1' : '0')}"));
// if (beatmap.BeatmapInfo.UseSkinSprites)
// writer.WriteLine(@"UseSkinSprites: 1");
// if (b.AlwaysShowPlayfield)
// writer.WriteLine(@"AlwaysShowPlayfield: 1");
// if (b.OverlayPosition != OverlayPosition.NoChange)
// writer.WriteLine(@"OverlayPosition: " + b.OverlayPosition);
// if (!string.IsNullOrEmpty(b.SkinPreference))
// writer.WriteLine(@"SkinPreference:" + b.SkinPreference);
if (beatmap.BeatmapInfo.EpilepsyWarning)
writer.WriteLine(@"EpilepsyWarning: 1");
if (beatmap.BeatmapInfo.CountdownOffset > 0)
writer.WriteLine(FormattableString.Invariant($@"CountdownOffset: {beatmap.BeatmapInfo.CountdownOffset}"));
if (onlineRulesetID == 3)
writer.WriteLine(FormattableString.Invariant($"SpecialStyle: {(beatmap.BeatmapInfo.SpecialStyle ? '1' : '0')}"));
writer.WriteLine(FormattableString.Invariant($"WidescreenStoryboard: {(beatmap.BeatmapInfo.WidescreenStoryboard ? '1' : '0')}"));
if (beatmap.BeatmapInfo.SamplesMatchPlaybackRate)
writer.WriteLine(@"SamplesMatchPlaybackRate: 1");
}
private void handleEditor(TextWriter writer)
{
writer.WriteLine("[Editor]");
if (beatmap.BeatmapInfo.Bookmarks.Length > 0)
writer.WriteLine(FormattableString.Invariant($"Bookmarks: {string.Join(',', beatmap.BeatmapInfo.Bookmarks)}"));
writer.WriteLine(FormattableString.Invariant($"DistanceSpacing: {beatmap.BeatmapInfo.DistanceSpacing}"));
writer.WriteLine(FormattableString.Invariant($"BeatDivisor: {beatmap.BeatmapInfo.BeatDivisor}"));
writer.WriteLine(FormattableString.Invariant($"GridSize: {beatmap.BeatmapInfo.GridSize}"));
writer.WriteLine(FormattableString.Invariant($"TimelineZoom: {beatmap.BeatmapInfo.TimelineZoom}"));
}
private void handleMetadata(TextWriter writer)
{
writer.WriteLine("[Metadata]");
writer.WriteLine(FormattableString.Invariant($"Title: {beatmap.Metadata.Title}"));
if (!string.IsNullOrEmpty(beatmap.Metadata.TitleUnicode)) writer.WriteLine(FormattableString.Invariant($"TitleUnicode: {beatmap.Metadata.TitleUnicode}"));
writer.WriteLine(FormattableString.Invariant($"Artist: {beatmap.Metadata.Artist}"));
if (!string.IsNullOrEmpty(beatmap.Metadata.ArtistUnicode)) writer.WriteLine(FormattableString.Invariant($"ArtistUnicode: {beatmap.Metadata.ArtistUnicode}"));
writer.WriteLine(FormattableString.Invariant($"Creator: {beatmap.Metadata.Author.Username}"));
writer.WriteLine(FormattableString.Invariant($"Version: {beatmap.BeatmapInfo.DifficultyName}"));
if (!string.IsNullOrEmpty(beatmap.Metadata.Source)) writer.WriteLine(FormattableString.Invariant($"Source: {beatmap.Metadata.Source}"));
if (!string.IsNullOrEmpty(beatmap.Metadata.Tags)) writer.WriteLine(FormattableString.Invariant($"Tags: {beatmap.Metadata.Tags}"));
if (beatmap.BeatmapInfo.OnlineID > 0) writer.WriteLine(FormattableString.Invariant($"BeatmapID: {beatmap.BeatmapInfo.OnlineID}"));
if (beatmap.BeatmapInfo.BeatmapSet?.OnlineID > 0) writer.WriteLine(FormattableString.Invariant($"BeatmapSetID: {beatmap.BeatmapInfo.BeatmapSet.OnlineID}"));
}
private void handleDifficulty(TextWriter writer)
{
writer.WriteLine("[Difficulty]");
writer.WriteLine(FormattableString.Invariant($"HPDrainRate: {beatmap.Difficulty.DrainRate}"));
writer.WriteLine(FormattableString.Invariant($"CircleSize: {beatmap.Difficulty.CircleSize}"));
writer.WriteLine(FormattableString.Invariant($"OverallDifficulty: {beatmap.Difficulty.OverallDifficulty}"));
writer.WriteLine(FormattableString.Invariant($"ApproachRate: {beatmap.Difficulty.ApproachRate}"));
// Taiko adjusts the slider multiplier (see: LEGACY_TAIKO_VELOCITY_MULTIPLIER)
writer.WriteLine(onlineRulesetID == 1
? FormattableString.Invariant($"SliderMultiplier: {beatmap.Difficulty.SliderMultiplier / LEGACY_TAIKO_VELOCITY_MULTIPLIER}")
: FormattableString.Invariant($"SliderMultiplier: {beatmap.Difficulty.SliderMultiplier}"));
writer.WriteLine(FormattableString.Invariant($"SliderTickRate: {beatmap.Difficulty.SliderTickRate}"));
}
private void handleEvents(TextWriter writer)
{
writer.WriteLine("[Events]");
if (!string.IsNullOrEmpty(beatmap.BeatmapInfo.Metadata.BackgroundFile))
writer.WriteLine(FormattableString.Invariant($"{(int)LegacyEventType.Background},0,\"{beatmap.BeatmapInfo.Metadata.BackgroundFile}\",0,0"));
foreach (var b in beatmap.Breaks)
writer.WriteLine(FormattableString.Invariant($"{(int)LegacyEventType.Break},{b.StartTime},{b.EndTime}"));
}
private void handleControlPoints(TextWriter writer)
{
if (beatmap.ControlPointInfo.Groups.Count == 0)
return;
var legacyControlPoints = new LegacyControlPointInfo();
foreach (var point in beatmap.ControlPointInfo.AllControlPoints)
legacyControlPoints.Add(point.Time, point.DeepClone());
writer.WriteLine("[TimingPoints]");
SampleControlPoint lastRelevantSamplePoint = null;
DifficultyControlPoint lastRelevantDifficultyPoint = null;
bool isOsuRuleset = onlineRulesetID == 0;
// iterate over hitobjects and pull out all required sample and difficulty changes
extractDifficultyControlPoints(beatmap.HitObjects);
extractSampleControlPoints(beatmap.HitObjects);
// handle scroll speed, which is stored as "slider velocity" in legacy formats.
// this is relevant for scrolling ruleset beatmaps.
if (!isOsuRuleset)
{
foreach (var point in legacyControlPoints.EffectPoints)
legacyControlPoints.Add(point.Time, new DifficultyControlPoint { SliderVelocity = point.ScrollSpeed });
}
foreach (var group in legacyControlPoints.Groups)
{
var groupTimingPoint = group.ControlPoints.OfType<TimingControlPoint>().FirstOrDefault();
// If the group contains a timing control point, it needs to be output separately.
if (groupTimingPoint != null)
{
writer.Write(FormattableString.Invariant($"{groupTimingPoint.Time},"));
writer.Write(FormattableString.Invariant($"{groupTimingPoint.BeatLength},"));
outputControlPointAt(groupTimingPoint.Time, true);
}
// Output any remaining effects as secondary non-timing control point.
var difficultyPoint = legacyControlPoints.DifficultyPointAt(group.Time);
writer.Write(FormattableString.Invariant($"{group.Time},"));
writer.Write(FormattableString.Invariant($"{-100 / difficultyPoint.SliderVelocity},"));
outputControlPointAt(group.Time, false);
}
void outputControlPointAt(double time, bool isTimingPoint)
{
var samplePoint = legacyControlPoints.SamplePointAt(time);
var effectPoint = legacyControlPoints.EffectPointAt(time);
// Apply the control point to a hit sample to uncover legacy properties (e.g. suffix)
HitSampleInfo tempHitSample = samplePoint.ApplyTo(new ConvertHitObjectParser.LegacyHitSampleInfo(string.Empty));
// Convert effect flags to the legacy format
LegacyEffectFlags effectFlags = LegacyEffectFlags.None;
if (effectPoint.KiaiMode)
effectFlags |= LegacyEffectFlags.Kiai;
if (effectPoint.OmitFirstBarLine)
effectFlags |= LegacyEffectFlags.OmitFirstBarLine;
writer.Write(FormattableString.Invariant($"{legacyControlPoints.TimingPointAt(time).TimeSignature.Numerator},"));
writer.Write(FormattableString.Invariant($"{(int)toLegacySampleBank(tempHitSample.Bank)},"));
writer.Write(FormattableString.Invariant($"{toLegacyCustomSampleBank(tempHitSample)},"));
writer.Write(FormattableString.Invariant($"{tempHitSample.Volume},"));
writer.Write(FormattableString.Invariant($"{(isTimingPoint ? '1' : '0')},"));
writer.Write(FormattableString.Invariant($"{(int)effectFlags}"));
writer.WriteLine();
}
IEnumerable<DifficultyControlPoint> collectDifficultyControlPoints(IEnumerable<HitObject> hitObjects)
{
if (!isOsuRuleset)
yield break;
foreach (var hitObject in hitObjects)
yield return hitObject.DifficultyControlPoint;
}
void extractDifficultyControlPoints(IEnumerable<HitObject> hitObjects)
{
foreach (var hDifficultyPoint in collectDifficultyControlPoints(hitObjects).OrderBy(dp => dp.Time))
{
if (!hDifficultyPoint.IsRedundant(lastRelevantDifficultyPoint))
{
legacyControlPoints.Add(hDifficultyPoint.Time, hDifficultyPoint);
lastRelevantDifficultyPoint = hDifficultyPoint;
}
}
}
IEnumerable<SampleControlPoint> collectSampleControlPoints(IEnumerable<HitObject> hitObjects)
{
foreach (var hitObject in hitObjects)
{
yield return hitObject.SampleControlPoint;
foreach (var nested in collectSampleControlPoints(hitObject.NestedHitObjects))
yield return nested;
}
}
void extractSampleControlPoints(IEnumerable<HitObject> hitObject)
{
foreach (var hSamplePoint in collectSampleControlPoints(hitObject).OrderBy(sp => sp.Time))
{
if (!hSamplePoint.IsRedundant(lastRelevantSamplePoint))
{
legacyControlPoints.Add(hSamplePoint.Time, hSamplePoint);
lastRelevantSamplePoint = hSamplePoint;
}
}
}
}
private void handleColours(TextWriter writer)
{
var colours = skin?.GetConfig<GlobalSkinColours, IReadOnlyList<Color4>>(GlobalSkinColours.ComboColours)?.Value;
if (colours == null || colours.Count == 0)
return;
writer.WriteLine("[Colours]");
for (int i = 0; i < colours.Count; i++)
{
var comboColour = colours[i];
writer.Write(FormattableString.Invariant($"Combo{i}: "));
writer.Write(FormattableString.Invariant($"{(byte)(comboColour.R * byte.MaxValue)},"));
writer.Write(FormattableString.Invariant($"{(byte)(comboColour.G * byte.MaxValue)},"));
writer.Write(FormattableString.Invariant($"{(byte)(comboColour.B * byte.MaxValue)},"));
writer.Write(FormattableString.Invariant($"{(byte)(comboColour.A * byte.MaxValue)}"));
writer.WriteLine();
}
}
private void handleHitObjects(TextWriter writer)
{
writer.WriteLine("[HitObjects]");
if (beatmap.HitObjects.Count == 0)
return;
foreach (var h in beatmap.HitObjects)
handleHitObject(writer, h);
}
private void handleHitObject(TextWriter writer, HitObject hitObject)
{
Vector2 position = new Vector2(256, 192);
switch (onlineRulesetID)
{
case 0:
case 2:
position = ((IHasPosition)hitObject).Position;
break;
case 3:
int totalColumns = (int)Math.Max(1, beatmap.Difficulty.CircleSize);
position.X = (int)Math.Ceiling(((IHasXPosition)hitObject).X * (512f / totalColumns));
break;
}
writer.Write(FormattableString.Invariant($"{position.X},"));
writer.Write(FormattableString.Invariant($"{position.Y},"));
writer.Write(FormattableString.Invariant($"{hitObject.StartTime},"));
writer.Write(FormattableString.Invariant($"{(int)getObjectType(hitObject)},"));
writer.Write(FormattableString.Invariant($"{(int)toLegacyHitSoundType(hitObject.Samples)},"));
if (hitObject is IHasPath path)
{
addPathData(writer, path, position);
writer.Write(getSampleBank(hitObject.Samples));
}
else
{
if (hitObject is IHasDuration)
addEndTimeData(writer, hitObject);
writer.Write(getSampleBank(hitObject.Samples));
}
writer.WriteLine();
}
private LegacyHitObjectType getObjectType(HitObject hitObject)
{
LegacyHitObjectType type = 0;
if (hitObject is IHasCombo combo)
{
type = (LegacyHitObjectType)(combo.ComboOffset << 4);
if (combo.NewCombo)
type |= LegacyHitObjectType.NewCombo;
}
switch (hitObject)
{
case IHasPath _:
type |= LegacyHitObjectType.Slider;
break;
case IHasDuration _:
if (onlineRulesetID == 3)
type |= LegacyHitObjectType.Hold;
else
type |= LegacyHitObjectType.Spinner;
break;
default:
type |= LegacyHitObjectType.Circle;
break;
}
return type;
}
private void addPathData(TextWriter writer, IHasPath pathData, Vector2 position)
{
PathType? lastType = null;
for (int i = 0; i < pathData.Path.ControlPoints.Count; i++)
{
PathControlPoint point = pathData.Path.ControlPoints[i];
if (point.Type != null)
{
// We've reached a new (explicit) segment!
// Explicit segments have a new format in which the type is injected into the middle of the control point string.
// To preserve compatibility with osu-stable as much as possible, explicit segments with the same type are converted to use implicit segments by duplicating the control point.
// One exception are consecutive perfect curves, which aren't supported in osu!stable and can lead to decoding issues if encoded as implicit segments
bool needsExplicitSegment = point.Type != lastType || point.Type == PathType.PerfectCurve;
// Another exception to this is when the last two control points of the last segment were duplicated. This is not a scenario supported by osu!stable.
// Lazer does not add implicit segments for the last two control points of _any_ explicit segment, so an explicit segment is forced in order to maintain consistency with the decoder.
if (i > 1)
{
// We need to use the absolute control point position to determine equality, otherwise floating point issues may arise.
Vector2 p1 = position + pathData.Path.ControlPoints[i - 1].Position;
Vector2 p2 = position + pathData.Path.ControlPoints[i - 2].Position;
if ((int)p1.X == (int)p2.X && (int)p1.Y == (int)p2.Y)
needsExplicitSegment = true;
}
if (needsExplicitSegment)
{
switch (point.Type)
{
case PathType.Bezier:
writer.Write("B|");
break;
case PathType.Catmull:
writer.Write("C|");
break;
case PathType.PerfectCurve:
writer.Write("P|");
break;
case PathType.Linear:
writer.Write("L|");
break;
}
lastType = point.Type;
}
else
{
// New segment with the same type - duplicate the control point
writer.Write(FormattableString.Invariant($"{position.X + point.Position.X}:{position.Y + point.Position.Y}|"));
}
}
if (i != 0)
{
writer.Write(FormattableString.Invariant($"{position.X + point.Position.X}:{position.Y + point.Position.Y}"));
writer.Write(i != pathData.Path.ControlPoints.Count - 1 ? "|" : ",");
}
}
var curveData = pathData as IHasPathWithRepeats;
writer.Write(FormattableString.Invariant($"{(curveData?.RepeatCount ?? 0) + 1},"));
writer.Write(FormattableString.Invariant($"{pathData.Path.ExpectedDistance.Value ?? pathData.Path.Distance},"));
if (curveData != null)
{
for (int i = 0; i < curveData.NodeSamples.Count; i++)
{
writer.Write(FormattableString.Invariant($"{(int)toLegacyHitSoundType(curveData.NodeSamples[i])}"));
writer.Write(i != curveData.NodeSamples.Count - 1 ? "|" : ",");
}
for (int i = 0; i < curveData.NodeSamples.Count; i++)
{
writer.Write(getSampleBank(curveData.NodeSamples[i], true));
writer.Write(i != curveData.NodeSamples.Count - 1 ? "|" : ",");
}
}
}
private void addEndTimeData(TextWriter writer, HitObject hitObject)
{
var endTimeData = (IHasDuration)hitObject;
var type = getObjectType(hitObject);
char suffix = ',';
// Holds write the end time as if it's part of sample data.
if (type == LegacyHitObjectType.Hold)
suffix = ':';
writer.Write(FormattableString.Invariant($"{endTimeData.EndTime}{suffix}"));
}
private string getSampleBank(IList<HitSampleInfo> samples, bool banksOnly = false)
{
LegacySampleBank normalBank = toLegacySampleBank(samples.SingleOrDefault(s => s.Name == HitSampleInfo.HIT_NORMAL)?.Bank);
LegacySampleBank addBank = toLegacySampleBank(samples.FirstOrDefault(s => !string.IsNullOrEmpty(s.Name) && s.Name != HitSampleInfo.HIT_NORMAL)?.Bank);
StringBuilder sb = new StringBuilder();
sb.Append(FormattableString.Invariant($"{(int)normalBank}:"));
sb.Append(FormattableString.Invariant($"{(int)addBank}"));
if (!banksOnly)
{
string customSampleBank = toLegacyCustomSampleBank(samples.FirstOrDefault(s => !string.IsNullOrEmpty(s.Name)));
string sampleFilename = samples.FirstOrDefault(s => string.IsNullOrEmpty(s.Name))?.LookupNames.First() ?? string.Empty;
int volume = samples.FirstOrDefault()?.Volume ?? 100;
sb.Append(':');
sb.Append(FormattableString.Invariant($"{customSampleBank}:"));
sb.Append(FormattableString.Invariant($"{volume}:"));
sb.Append(FormattableString.Invariant($"{sampleFilename}"));
}
return sb.ToString();
}
private LegacyHitSoundType toLegacyHitSoundType(IList<HitSampleInfo> samples)
{
LegacyHitSoundType type = LegacyHitSoundType.None;
foreach (var sample in samples)
{
switch (sample.Name)
{
case HitSampleInfo.HIT_WHISTLE:
type |= LegacyHitSoundType.Whistle;
break;
case HitSampleInfo.HIT_FINISH:
type |= LegacyHitSoundType.Finish;
break;
case HitSampleInfo.HIT_CLAP:
type |= LegacyHitSoundType.Clap;
break;
}
}
return type;
}
private LegacySampleBank toLegacySampleBank(string sampleBank)
{
switch (sampleBank?.ToLowerInvariant())
{
case "normal":
return LegacySampleBank.Normal;
case "soft":
return LegacySampleBank.Soft;
case "drum":
return LegacySampleBank.Drum;
default:
return LegacySampleBank.None;
}
}
private string toLegacyCustomSampleBank(HitSampleInfo hitSampleInfo)
{
if (hitSampleInfo is ConvertHitObjectParser.LegacyHitSampleInfo legacy)
return legacy.CustomSampleBank.ToString(CultureInfo.InvariantCulture);
return "0";
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Portions derived from React Native:
// Copyright (c) 2015-present, Facebook, Inc.
// Licensed under the MIT License.
using ReactNative.Bridge;
using System;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Reactive.Disposables;
using System.Threading;
using System.Threading.Tasks;
#if WINDOWS_UWP
using Windows.UI.Core;
#endif
namespace ReactNative.DevSupport
{
/// <summary>
/// Helper class for debug server running in the host machine.
/// </summary>
sealed class DevServerHelper : IDisposable
{
private const string DeviceLocalhost = "localhost:8081";
private const string BundleUrlFormat = "http://{0}/{1}.bundle?platform=windows&dev={2}&hot={3}";
private const string SourceMapUrlFormat = "http://{0}/{1}.map?platform=windows&dev={2}&hot={3}";
private const string LaunchDevToolsCommandUrlFormat = "http://{0}/launch-js-devtools";
private const string OnChangeEndpointUrlFormat = "http://{0}/onchange";
private const string WebsocketProxyUrlFormat = "ws://{0}/debugger-proxy?role=client";
private const string PackagerStatusUrlFormat = "http://{0}/status";
private const string PackagerOkStatus = "packager-status:running";
private const int LongPollFailureDelayMs = 5000;
private readonly DevInternalSettings _settings;
private readonly HttpClient _client;
/// <summary>
/// Instantiates the <see cref="DevServerHelper"/>.
/// </summary>
/// <param name="settings">The settings.</param>
public DevServerHelper(DevInternalSettings settings)
{
_settings = settings;
_client = new HttpClient();
}
/// <summary>
/// The JavaScript debugging proxy URL.
/// </summary>
public string WebSocketProxyUrl
{
get
{
return string.Format(CultureInfo.InvariantCulture, WebSocketProxyUrl, DebugServerHost);
}
}
/// <summary>
/// The host to use when connecting to the bundle server.
/// </summary>
private string DebugServerHost
{
get
{
return _settings.DebugServerHost ?? DeviceLocalhost;
}
}
/// <summary>
/// Signals whether to enable dev mode when requesting JavaScript bundles.
/// </summary>
private bool IsJavaScriptDevModeEnabled
{
get
{
return _settings.IsJavaScriptDevModeEnabled;
}
}
/// <summary>
/// Signals whether hot module replacement is enabled.
/// </summary>
private bool IsHotModuleReplacementEnabled
{
get
{
return _settings.IsHotModuleReplacementEnabled;
}
}
/// <summary>
/// The Websocket proxy URL.
/// </summary>
public string WebsocketProxyUrl
{
get
{
return string.Format(CultureInfo.InvariantCulture, WebsocketProxyUrlFormat, DebugServerHost);
}
}
private string JavaScriptProxyHost
{
get
{
return DeviceLocalhost;
}
}
/// <summary>
/// Download the latest bundle into a local stream.
/// </summary>
/// <param name="jsModulePath">The module path.</param>
/// <param name="outputStream">The output stream.</param>
/// <param name="token">A token to cancel the request.</param>
/// <returns>A task to await completion.</returns>
public async Task DownloadBundleFromUrlAsync(string jsModulePath, Stream outputStream, CancellationToken token)
{
var bundleUrl = GetSourceUrl(jsModulePath);
using (var response = await _client.GetAsync(bundleUrl, token).ConfigureAwait(false))
{
if (!response.IsSuccessStatusCode)
{
var body = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
var exception = DebugServerException.Parse(body);
if (exception == null)
{
var nl = Environment.NewLine;
exception = new DebugServerException(
"The development server returned response error code: " +
$"{response.StatusCode}{nl}{nl}URL: {bundleUrl}{nl}{nl}Body:{nl}{body}");
}
throw exception;
}
await response.Content.CopyToAsync(outputStream).ConfigureAwait(false);
}
}
/// <summary>
/// Checks if the packager is running.
/// </summary>
/// <param name="token">A token to cancel the request.</param>
/// <returns>A task to await the packager status.</returns>
public async Task<bool> IsPackagerRunningAsync(CancellationToken token)
{
var statusUrl = CreatePackagerStatusUrl(DebugServerHost);
try
{
using (var response = await _client.GetAsync(statusUrl, token).ConfigureAwait(false))
{
if (!response.IsSuccessStatusCode)
{
return false;
}
var body = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return body == PackagerOkStatus;
}
}
catch
{
return false;
}
}
/// <summary>
/// Start the bundle change polling service.
/// </summary>
/// <param name="onServerContentChanged">
/// Callback for when the bundle content changes.
/// </param>
/// <returns>A disposable to use to stop polling.</returns>
public IDisposable StartPollingOnChangeEndpoint(Action onServerContentChanged)
{
var disposable = new CancellationDisposable();
var task = Task.Run(async () =>
{
var onChangePollingClient = new HttpClient();
onChangePollingClient.DefaultRequestHeaders.Connection.Add("keep-alive");
while (!disposable.IsDisposed)
{
var onChangeUrl = CreateOnChangeEndpointUrl(DebugServerHost);
try
{
using (var response = await onChangePollingClient.GetAsync(onChangeUrl, disposable.Token).ConfigureAwait(false))
{
if (response.StatusCode == HttpStatusCode.ResetContent)
{
#if WINDOWS_UWP
DispatcherHelpers.RunOnDispatcher(new DispatchedHandler(onServerContentChanged));
#else
DispatcherHelpers.RunOnDispatcher(onServerContentChanged);
#endif
}
}
}
catch (OperationCanceledException)
when (disposable.IsDisposed)
{
}
catch
{
await Task.Delay(LongPollFailureDelayMs).ConfigureAwait(false);
}
}
});
return disposable;
}
/// <summary>
/// Launch the developer tools.
/// </summary>
public async Task LaunchDevToolsAsync(CancellationToken token)
{
var url = CreateLaunchDevToolsCommandUrl();
await _client.GetAsync(url, token).ConfigureAwait(false);
// Ignore response, nothing to report here.
}
/// <summary>
/// Get the source map URL for the JavaScript bundle.
/// </summary>
/// <param name="mainModuleName">The main module name.</param>
/// <returns>The source map URL.</returns>
public string GetSourceMapUrl(string mainModuleName)
{
return string.Format(
CultureInfo.InvariantCulture,
SourceMapUrlFormat,
DebugServerHost,
mainModuleName,
IsJavaScriptDevModeEnabled ? "true" : "false",
IsHotModuleReplacementEnabled ? "true" : "false");
}
/// <summary>
/// Get the source URL for the JavaScript bundle.
/// </summary>
/// <param name="mainModuleName">The main module name.</param>
/// <returns>The source URL.</returns>
public string GetSourceUrl(string mainModuleName)
{
return string.Format(
CultureInfo.InvariantCulture,
BundleUrlFormat,
DebugServerHost,
mainModuleName,
IsJavaScriptDevModeEnabled ? "true" : "false",
IsHotModuleReplacementEnabled ? "true" : "false");
}
/// <summary>
/// Gets the bundle URL for remote debugging.
/// </summary>
/// <param name="mainModuleName">The main module name.</param>
/// <returns>The bundle URL.</returns>
public string GetJavaScriptBundleUrlForRemoteDebugging(string mainModuleName)
{
return string.Format(
CultureInfo.InvariantCulture,
BundleUrlFormat,
JavaScriptProxyHost,
mainModuleName,
IsJavaScriptDevModeEnabled ? "true" : "false",
IsHotModuleReplacementEnabled ? "true" : "false");
}
/// <summary>
/// Disposes the <see cref="DevServerHelper"/>.
/// </summary>
public void Dispose()
{
_client.Dispose();
}
private string CreatePackagerStatusUrl(string host)
{
return string.Format(CultureInfo.InvariantCulture, PackagerStatusUrlFormat, host);
}
private string CreateOnChangeEndpointUrl(string host)
{
return string.Format(CultureInfo.InvariantCulture, OnChangeEndpointUrlFormat, host);
}
private string CreateLaunchDevToolsCommandUrl()
{
return string.Format(
CultureInfo.InvariantCulture,
LaunchDevToolsCommandUrlFormat,
DebugServerHost);
}
}
}
| |
// 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.Globalization;
using System.Text;
namespace System.Net.Http.Headers
{
public class WarningHeaderValue : ICloneable
{
private int _code;
private string _agent;
private string _text;
private DateTimeOffset? _date;
public int Code
{
get { return _code; }
}
public string Agent
{
get { return _agent; }
}
public string Text
{
get { return _text; }
}
public DateTimeOffset? Date
{
get { return _date; }
}
public WarningHeaderValue(int code, string agent, string text)
{
CheckCode(code);
CheckAgent(agent);
HeaderUtilities.CheckValidQuotedString(text, "text");
_code = code;
_agent = agent;
_text = text;
}
public WarningHeaderValue(int code, string agent, string text, DateTimeOffset date)
{
CheckCode(code);
CheckAgent(agent);
HeaderUtilities.CheckValidQuotedString(text, "text");
_code = code;
_agent = agent;
_text = text;
_date = date;
}
private WarningHeaderValue()
{
}
private WarningHeaderValue(WarningHeaderValue source)
{
Contract.Requires(source != null);
_code = source._code;
_agent = source._agent;
_text = source._text;
_date = source._date;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
// Warning codes are always 3 digits according to RFC2616
sb.Append(_code.ToString("000", NumberFormatInfo.InvariantInfo));
sb.Append(' ');
sb.Append(_agent);
sb.Append(' ');
sb.Append(_text);
if (_date.HasValue)
{
sb.Append(" \"");
sb.Append(HttpRuleParser.DateToString(_date.Value));
sb.Append('\"');
}
return sb.ToString();
}
public override bool Equals(object obj)
{
WarningHeaderValue other = obj as WarningHeaderValue;
if (other == null)
{
return false;
}
// 'agent' is a host/token, i.e. use case-insensitive comparison. Use case-sensitive comparison for 'text'
// since it is a quoted string.
if ((_code != other._code) || (!string.Equals(_agent, other._agent, StringComparison.OrdinalIgnoreCase)) ||
(!string.Equals(_text, other._text, StringComparison.Ordinal)))
{
return false;
}
// We have a date set. Verify 'other' has also a date that matches our value.
if (_date.HasValue)
{
return other._date.HasValue && (_date.Value == other._date.Value);
}
// We don't have a date. If 'other' has a date, we're not equal.
return !other._date.HasValue;
}
public override int GetHashCode()
{
int result = _code.GetHashCode() ^
StringComparer.OrdinalIgnoreCase.GetHashCode(_agent) ^
_text.GetHashCode();
if (_date.HasValue)
{
result = result ^ _date.Value.GetHashCode();
}
return result;
}
public static WarningHeaderValue Parse(string input)
{
int index = 0;
return (WarningHeaderValue)GenericHeaderParser.SingleValueWarningParser.ParseValue(input, null, ref index);
}
public static bool TryParse(string input, out WarningHeaderValue parsedValue)
{
int index = 0;
object output;
parsedValue = null;
if (GenericHeaderParser.SingleValueWarningParser.TryParseValue(input, null, ref index, out output))
{
parsedValue = (WarningHeaderValue)output;
return true;
}
return false;
}
internal static int GetWarningLength(string input, int startIndex, out object parsedValue)
{
Contract.Requires(startIndex >= 0);
parsedValue = null;
if (string.IsNullOrEmpty(input) || (startIndex >= input.Length))
{
return 0;
}
// Read <code> in '<code> <agent> <text> ["<date>"]'
int code;
int current = startIndex;
if (!TryReadCode(input, ref current, out code))
{
return 0;
}
// Read <agent> in '<code> <agent> <text> ["<date>"]'
string agent;
if (!TryReadAgent(input, current, ref current, out agent))
{
return 0;
}
// Read <text> in '<code> <agent> <text> ["<date>"]'
int textLength = 0;
int textStartIndex = current;
if (HttpRuleParser.GetQuotedStringLength(input, current, out textLength) != HttpParseResult.Parsed)
{
return 0;
}
current = current + textLength;
// Read <date> in '<code> <agent> <text> ["<date>"]'
DateTimeOffset? date = null;
if (!TryReadDate(input, ref current, out date))
{
return 0;
}
WarningHeaderValue result = new WarningHeaderValue();
result._code = code;
result._agent = agent;
result._text = input.Substring(textStartIndex, textLength);
result._date = date;
parsedValue = result;
return current - startIndex;
}
private static bool TryReadAgent(string input, int startIndex, ref int current, out string agent)
{
agent = null;
int agentLength = HttpRuleParser.GetHostLength(input, startIndex, true, out agent);
if (agentLength == 0)
{
return false;
}
current = current + agentLength;
int whitespaceLength = HttpRuleParser.GetWhitespaceLength(input, current);
current = current + whitespaceLength;
// At least one whitespace required after <agent>. Also make sure we have characters left for <text>
if ((whitespaceLength == 0) || (current == input.Length))
{
return false;
}
return true;
}
private static bool TryReadCode(string input, ref int current, out int code)
{
code = 0;
int codeLength = HttpRuleParser.GetNumberLength(input, current, false);
// code must be a 3 digit value. We accept less digits, but we don't accept more.
if ((codeLength == 0) || (codeLength > 3))
{
return false;
}
if (!HeaderUtilities.TryParseInt32(input.Substring(current, codeLength), out code))
{
Debug.Assert(false, "Unable to parse value even though it was parsed as <=3 digits string. Input: '" +
input + "', Current: " + current + ", CodeLength: " + codeLength);
return false;
}
current = current + codeLength;
int whitespaceLength = HttpRuleParser.GetWhitespaceLength(input, current);
current = current + whitespaceLength;
// Make sure the number is followed by at least one whitespace and that we have characters left to parse.
if ((whitespaceLength == 0) || (current == input.Length))
{
return false;
}
return true;
}
private static bool TryReadDate(string input, ref int current, out DateTimeOffset? date)
{
date = null;
// Make sure we have at least one whitespace between <text> and <date> (if we have <date>)
int whitespaceLength = HttpRuleParser.GetWhitespaceLength(input, current);
current = current + whitespaceLength;
// Read <date> in '<code> <agent> <text> ["<date>"]'
if ((current < input.Length) && (input[current] == '"'))
{
if (whitespaceLength == 0)
{
return false; // we have characters after <text> but they were not separated by a whitespace
}
current++; // skip opening '"'
// Find the closing '"'
int dateStartIndex = current;
while (current < input.Length)
{
if (input[current] == '"')
{
break;
}
current++;
}
if ((current == input.Length) || (current == dateStartIndex))
{
return false; // we couldn't find the closing '"' or we have an empty quoted string.
}
DateTimeOffset temp;
if (!HttpRuleParser.TryStringToDate(input.Substring(dateStartIndex, current - dateStartIndex), out temp))
{
return false;
}
date = temp;
current++; // skip closing '"'
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
}
return true;
}
object ICloneable.Clone()
{
return new WarningHeaderValue(this);
}
private static void CheckCode(int code)
{
if ((code < 0) || (code > 999))
{
throw new ArgumentOutOfRangeException(nameof(code));
}
}
private static void CheckAgent(string agent)
{
if (string.IsNullOrEmpty(agent))
{
throw new ArgumentException(SR.net_http_argument_empty_string, nameof(agent));
}
// 'receivedBy' can either be a host or a token. Since a token is a valid host, we only verify if the value
// is a valid host.
string host = null;
if (HttpRuleParser.GetHostLength(agent, 0, true, out host) != agent.Length)
{
throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, agent));
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyrightD
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using OpenSim.Framework;
using OpenSim.Region.Framework;
using OpenSim.Region.CoreModules;
using OpenSim.Region.Physics.Manager;
using Nini.Config;
using log4net;
using OpenMetaverse;
namespace OpenSim.Region.Physics.BulletSPlugin
{
public sealed class BSTerrainMesh : BSTerrainPhys
{
static string LogHeader = "[BULLETSIM TERRAIN MESH]";
private float[] m_savedHeightMap;
int m_sizeX;
int m_sizeY;
BulletShape m_terrainShape;
BulletBody m_terrainBody;
public BSTerrainMesh(BSScene physicsScene, Vector3 regionBase, uint id, Vector3 regionSize)
: base(physicsScene, regionBase, id)
{
}
public BSTerrainMesh(BSScene physicsScene, Vector3 regionBase, uint id /* parameters for making mesh */)
: base(physicsScene, regionBase, id)
{
}
// Create terrain mesh from a heightmap.
public BSTerrainMesh(BSScene physicsScene, Vector3 regionBase, uint id, float[] initialMap,
Vector3 minCoords, Vector3 maxCoords)
: base(physicsScene, regionBase, id)
{
int indicesCount;
int[] indices;
int verticesCount;
float[] vertices;
m_savedHeightMap = initialMap;
m_sizeX = (int)(maxCoords.X - minCoords.X);
m_sizeY = (int)(maxCoords.Y - minCoords.Y);
if (!BSTerrainMesh.ConvertHeightmapToMesh(PhysicsScene, initialMap,
m_sizeX, m_sizeY,
(float)m_sizeX, (float)m_sizeY,
Vector3.Zero, 1.0f,
out indicesCount, out indices, out verticesCount, out vertices))
{
// DISASTER!!
PhysicsScene.DetailLog("{0},BSTerrainMesh.create,failedConversionOfHeightmap", ID);
PhysicsScene.Logger.ErrorFormat("{0} Failed conversion of heightmap to mesh! base={1}", LogHeader, TerrainBase);
// Something is very messed up and a crash is in our future.
return;
}
PhysicsScene.DetailLog("{0},BSTerrainMesh.create,meshed,indices={1},indSz={2},vertices={3},vertSz={4}",
ID, indicesCount, indices.Length, verticesCount, vertices.Length);
m_terrainShape = PhysicsScene.PE.CreateMeshShape(PhysicsScene.World, indicesCount, indices, verticesCount, vertices);
if (!m_terrainShape.HasPhysicalShape)
{
// DISASTER!!
PhysicsScene.DetailLog("{0},BSTerrainMesh.create,failedCreationOfShape", ID);
PhysicsScene.Logger.ErrorFormat("{0} Failed creation of terrain mesh! base={1}", LogHeader, TerrainBase);
// Something is very messed up and a crash is in our future.
return;
}
Vector3 pos = regionBase;
Quaternion rot = Quaternion.Identity;
m_terrainBody = PhysicsScene.PE.CreateBodyWithDefaultMotionState(m_terrainShape, ID, pos, rot);
if (!m_terrainBody.HasPhysicalBody)
{
// DISASTER!!
PhysicsScene.Logger.ErrorFormat("{0} Failed creation of terrain body! base={1}", LogHeader, TerrainBase);
// Something is very messed up and a crash is in our future.
return;
}
// Set current terrain attributes
PhysicsScene.PE.SetFriction(m_terrainBody, BSParam.TerrainFriction);
PhysicsScene.PE.SetHitFraction(m_terrainBody, BSParam.TerrainHitFraction);
PhysicsScene.PE.SetRestitution(m_terrainBody, BSParam.TerrainRestitution);
PhysicsScene.PE.SetCollisionFlags(m_terrainBody, CollisionFlags.CF_STATIC_OBJECT);
// Static objects are not very massive.
PhysicsScene.PE.SetMassProps(m_terrainBody, 0f, Vector3.Zero);
// Put the new terrain to the world of physical objects
PhysicsScene.PE.AddObjectToWorld(PhysicsScene.World, m_terrainBody);
// Redo its bounding box now that it is in the world
PhysicsScene.PE.UpdateSingleAabb(PhysicsScene.World, m_terrainBody);
m_terrainBody.collisionType = CollisionType.Terrain;
m_terrainBody.ApplyCollisionMask(PhysicsScene);
if (BSParam.UseSingleSidedMeshes)
{
PhysicsScene.DetailLog("{0},BSTerrainMesh.settingCustomMaterial", id);
PhysicsScene.PE.AddToCollisionFlags(m_terrainBody, CollisionFlags.CF_CUSTOM_MATERIAL_CALLBACK);
}
// Make it so the terrain will not move or be considered for movement.
PhysicsScene.PE.ForceActivationState(m_terrainBody, ActivationState.DISABLE_SIMULATION);
}
public override void Dispose()
{
if (m_terrainBody.HasPhysicalBody)
{
PhysicsScene.PE.RemoveObjectFromWorld(PhysicsScene.World, m_terrainBody);
// Frees both the body and the shape.
PhysicsScene.PE.DestroyObject(PhysicsScene.World, m_terrainBody);
m_terrainBody.Clear();
m_terrainShape.Clear();
}
}
public override float GetTerrainHeightAtXYZ(Vector3 pos)
{
// For the moment use the saved heightmap to get the terrain height.
// TODO: raycast downward to find the true terrain below the position.
float ret = BSTerrainManager.HEIGHT_GETHEIGHT_RET;
int mapIndex = (int)pos.Y * m_sizeY + (int)pos.X;
try
{
ret = m_savedHeightMap[mapIndex];
}
catch
{
// Sometimes they give us wonky values of X and Y. Give a warning and return something.
PhysicsScene.Logger.WarnFormat("{0} Bad request for terrain height. terrainBase={1}, pos={2}",
LogHeader, TerrainBase, pos);
ret = BSTerrainManager.HEIGHT_GETHEIGHT_RET;
}
return ret;
}
// The passed position is relative to the base of the region.
public override float GetWaterLevelAtXYZ(Vector3 pos)
{
return PhysicsScene.SimpleWaterLevel;
}
// Convert the passed heightmap to mesh information suitable for CreateMeshShape2().
// Return 'true' if successfully created.
public static bool ConvertHeightmapToMesh( BSScene physicsScene,
float[] heightMap, int sizeX, int sizeY, // parameters of incoming heightmap
float extentX, float extentY, // zero based range for output vertices
Vector3 extentBase, // base to be added to all vertices
float magnification, // number of vertices to create between heightMap coords
out int indicesCountO, out int[] indicesO,
out int verticesCountO, out float[] verticesO)
{
bool ret = false;
int indicesCount = 0;
int verticesCount = 0;
int[] indices = new int[0];
float[] vertices = new float[0];
// Simple mesh creation which assumes magnification == 1.
// TODO: do a more general solution that scales, adds new vertices and smoothes the result.
// Create an array of vertices that is sizeX+1 by sizeY+1 (note the loop
// from zero to <= sizeX). The triangle indices are then generated as two triangles
// per heightmap point. There are sizeX by sizeY of these squares. The extra row and
// column of vertices are used to complete the triangles of the last row and column
// of the heightmap.
try
{
// One vertice per heightmap value plus the vertices off the top and bottom edge.
int totalVertices = (sizeX + 1) * (sizeY + 1);
vertices = new float[totalVertices * 3];
int totalIndices = sizeX * sizeY * 6;
indices = new int[totalIndices];
float magX = (float)sizeX / extentX;
float magY = (float)sizeY / extentY;
if (physicsScene != null)
physicsScene.DetailLog("{0},BSTerrainMesh.ConvertHeightMapToMesh,totVert={1},totInd={2},extentBase={3},magX={4},magY={5}",
BSScene.DetailLogZero, totalVertices, totalIndices, extentBase, magX, magY);
float minHeight = float.MaxValue;
// Note that sizeX+1 vertices are created since there is land between this and the next region.
for (int yy = 0; yy <= sizeY; yy++)
{
for (int xx = 0; xx <= sizeX; xx++) // Hint: the "<=" means we go around sizeX + 1 times
{
int offset = yy * sizeX + xx;
// Extend the height with the height from the last row or column
if (yy == sizeY) offset -= sizeX;
if (xx == sizeX) offset -= 1;
float height = heightMap[offset];
minHeight = Math.Min(minHeight, height);
vertices[verticesCount + 0] = (float)xx * magX + extentBase.X;
vertices[verticesCount + 1] = (float)yy * magY + extentBase.Y;
vertices[verticesCount + 2] = height + extentBase.Z;
verticesCount += 3;
}
}
verticesCount = verticesCount / 3;
for (int yy = 0; yy < sizeY; yy++)
{
for (int xx = 0; xx < sizeX; xx++)
{
int offset = yy * (sizeX + 1) + xx;
// Each vertices is presumed to be the upper left corner of a box of two triangles
indices[indicesCount + 0] = offset;
indices[indicesCount + 1] = offset + 1;
indices[indicesCount + 2] = offset + sizeX + 1; // accounting for the extra column
indices[indicesCount + 3] = offset + 1;
indices[indicesCount + 4] = offset + sizeX + 2;
indices[indicesCount + 5] = offset + sizeX + 1;
indicesCount += 6;
}
}
ret = true;
}
catch (Exception e)
{
if (physicsScene != null)
physicsScene.Logger.ErrorFormat("{0} Failed conversion of heightmap to mesh. For={1}/{2}, e={3}",
LogHeader, physicsScene.RegionName, extentBase, e);
}
indicesCountO = indicesCount;
indicesO = indices;
verticesCountO = verticesCount;
verticesO = vertices;
return ret;
}
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Delaunay
{
public class Site : ICoord
{
private static List<Site> _pool = new List<Site>();
public static Site Create(Vector2 p, int index, float weight, uint color)
{
if (_pool.Count > 0)
{
return _pool.Pop().Init(p, index, weight, color);
}
else
{
return new Site(typeof(PrivateConstructorEnforcer), p, index, weight, color);
}
}
internal static void SortSites(List<Site> sites)
{
sites.SortFunc(Site.Compare);
}
/**
* sort sites on y, then x, coord
* also change each site's _siteIndex to match its new position in the list
* so the _siteIndex can be used to identify the site for nearest-neighbor queries
*
* haha "also" - means more than one responsibility...
*
*/
private static float Compare(Site s1, Site s2)
{
int returnValue = (int)Voronoi.CompareByYThenX(s1, s2);
// swap _siteIndex values if necessary to match new ordering:
int tempIndex;
if (returnValue == -1)
{
if (s1._siteIndex > s2._siteIndex)
{
tempIndex = (int)s1._siteIndex;
s1._siteIndex = s2._siteIndex;
s2._siteIndex = (uint)tempIndex;
}
}
else if (returnValue == 1)
{
if (s2._siteIndex > s1._siteIndex)
{
tempIndex = (int)s2._siteIndex;
s2._siteIndex = s1._siteIndex;
s1._siteIndex = (uint)tempIndex;
}
}
return returnValue;
}
private static readonly float EPSILON = .005f;
private static bool CloseEnough(Vector2 p0, Vector2 p1)
{
return Utilities.Distance(p0, p1) < EPSILON;
}
private Vector2 _coord;
public Vector2 Coord()
{
//get {
return _coord;
//}
}
internal uint color;
internal float weight;
private uint _siteIndex;
// the edges that define this Site's Voronoi region:
private List<Edge> _edges;
internal List<Edge> Edges
{
get
{
return _edges;
}
}
// which end of each edge hooks up with the previous edge in _edges:
private List<LR> _edgeOrientations;
// ordered list of Vector2s that define the region clipped to bounds:
private List<Vector2> _region;
public Site(Type pce, Vector2 p, int index, float weight, uint color)
{
if (pce != typeof(PrivateConstructorEnforcer))
{
throw new Exception("Site static readonlyructor is private");
}
Init(p, index, weight, color);
}
private Site Init(Vector2 p, int index, float weight, uint color)
{
_coord = p;
_siteIndex = (uint)index;
this.weight = weight;
this.color = color;
_edges = new List<Edge>();
_region = null;
return this;
}
public override string ToString()
{
return "Site " + _siteIndex + ": " + Coord().ToString();
}
private void Move(Vector2 p)
{
Clear();
_coord = p;
}
public void Dispose()
{
_coord = Vector2.zero;
Clear();
_pool.Add(this);
}
private void Clear()
{
if (_edges != null)
{
_edges.Clear();
_edges = null;
}
if (_edgeOrientations != null)
{
_edgeOrientations.Clear();
_edgeOrientations = null;
}
if (_region != null)
{
_region.Clear();
_region = null;
}
}
internal void AddEdge(Edge edge)
{
_edges.Add(edge);
}
internal Edge NearestEdge()
{
_edges.SortFunc(Edge.CompareSitesDistances);
return _edges[0];
}
internal List<Site> NeighborSites()
{
if (_edges == null || _edges.Count == 0)
{
return new List<Site>();
}
if (_edgeOrientations == null)
{
ReorderEdges();
}
List<Site> list = new List<Site>();
foreach (Edge edge in _edges)
{
list.Add(NeighborSite(edge));
}
return list;
}
private Site NeighborSite(Edge edge)
{
if (this == edge.LeftSite)
{
return edge.RightSite;
}
if (this == edge.RightSite)
{
return edge.LeftSite;
}
return null;
}
internal List<Vector2> Region(Rect clippingBounds)
{
if (_edges == null || _edges.Count == 0)
{
return new List<Vector2>();
}
if (_edgeOrientations == null)
{
ReorderEdges();
_region = ClipToBounds(clippingBounds);
if ((new Polygon(_region)).GetWinding() == Winding.CLOCKWISE)
{
_region.Reverse();
}
}
return _region;
}
private void ReorderEdges()
{
//trace("_edges:", _edges);
EdgeReorderer reorderer = new EdgeReorderer(_edges, typeof(Vertex));
_edges = reorderer.Edges;
//trace("reordered:", _edges);
_edgeOrientations = reorderer.EdgeOrientations;
reorderer.Dispose();
}
private List<Vector2> ClipToBounds(Rect bounds)
{
List<Vector2> Vector2s = new List<Vector2>();
int n = _edges.Count;
int i = 0;
Edge edge;
while (i < n && ((_edges[i] as Edge).Visible == false))
{
++i;
}
if (i == n)
{
// no edges visible
return new List<Vector2>();
}
edge = _edges[i];
LR orientation = _edgeOrientations[i];
Vector2s.Add(edge.ClippedEnds[orientation]);
Vector2s.Add(edge.ClippedEnds[LR.Other(orientation)]);
for (int j = i + 1; j < n; ++j)
{
edge = _edges[j];
if (edge.Visible == false)
{
continue;
}
Connect(Vector2s, j, bounds);
}
// close up the polygon by adding another corner Vector2 of the bounds if needed:
Connect(Vector2s, i, bounds, true);
return Vector2s;
}
private void Connect(List<Vector2> Vector2s, int j, Rect bounds)
{
Connect(Vector2s, j, bounds, false);
}
private void Connect(List<Vector2> Vector2s, int j, Rect bounds, bool closingUp)
{
Vector2 rightVector2 = Vector2s[Vector2s.Count - 1];
Edge newEdge = _edges[j] as Edge;
LR newOrientation = _edgeOrientations[j];
// the Vector2 that must be connected to rightVector2:
Vector2 newVector2 = newEdge.ClippedEnds[newOrientation];
if (!CloseEnough(rightVector2, newVector2))
{
// The Vector2s do not coincide, so they must have been clipped at the bounds;
// see if they are on the same border of the bounds:
if (rightVector2.x != newVector2.x
&& rightVector2.y != newVector2.y)
{
// They are on different borders of the bounds;
// insert one or two corners of bounds as needed to hook them up:
// (NOTE this will not be corRect if the region should take up more than
// half of the bounds Rect, for then we will have gone the wrong way
// around the bounds and included the smaller part rather than the larger)
int rightCheck = BoundsCheck.Check(rightVector2, bounds);
int newCheck = BoundsCheck.Check(newVector2, bounds);
float px, py;
//throw new NotImplementedException("Modified, might not work");
if (rightCheck == BoundsCheck.RIGHT)
{
px = bounds.right;
if (newCheck == BoundsCheck.BOTTOM)
{
py = bounds.bottom;
Vector2s.Add(new Vector2(px, py));
}
else if (newCheck == BoundsCheck.TOP)
{
py = bounds.top;
Vector2s.Add(new Vector2(px, py));
}
else if (newCheck == BoundsCheck.LEFT)
{
if (rightVector2.y - bounds.y + newVector2.y - bounds.y < bounds.height)
{
py = bounds.top;
}
else
{
py = bounds.bottom;
}
Vector2s.Add(new Vector2(px, py));
Vector2s.Add(new Vector2(bounds.left, py));
}
}
else if (rightCheck == BoundsCheck.LEFT)
{
px = bounds.left;
if (newCheck == BoundsCheck.BOTTOM)
{
py = bounds.bottom;
Vector2s.Add(new Vector2(px, py));
}
else if (newCheck == BoundsCheck.TOP)
{
py = bounds.top;
Vector2s.Add(new Vector2(px, py));
}
else if (newCheck == BoundsCheck.RIGHT)
{
if (rightVector2.y - bounds.y + newVector2.y - bounds.y < bounds.height)
{
py = bounds.top;
}
else
{
py = bounds.bottom;
}
Vector2s.Add(new Vector2(px, py));
Vector2s.Add(new Vector2(bounds.right, py));
}
}
else if (rightCheck == BoundsCheck.TOP)
{
py = bounds.top;
if (newCheck == BoundsCheck.RIGHT)
{
px = bounds.right;
Vector2s.Add(new Vector2(px, py));
}
else if (newCheck == BoundsCheck.LEFT)
{
px = bounds.left;
Vector2s.Add(new Vector2(px, py));
}
else if (newCheck == BoundsCheck.BOTTOM)
{
if (rightVector2.x - bounds.x + newVector2.x - bounds.x < bounds.width)
{
px = bounds.left;
}
else
{
px = bounds.right;
}
Vector2s.Add(new Vector2(px, py));
Vector2s.Add(new Vector2(px, bounds.bottom));
}
}
else if (rightCheck == BoundsCheck.BOTTOM)
{
py = bounds.bottom;
if (newCheck == BoundsCheck.RIGHT)
{
px = bounds.right;
Vector2s.Add(new Vector2(px, py));
}
else if (newCheck == BoundsCheck.LEFT)
{
px = bounds.left;
Vector2s.Add(new Vector2(px, py));
}
else if (newCheck == BoundsCheck.TOP)
{
if (rightVector2.x - bounds.x + newVector2.x - bounds.x < bounds.width)
{
px = bounds.left;
}
else
{
px = bounds.right;
}
Vector2s.Add(new Vector2(px, py));
Vector2s.Add(new Vector2(px, bounds.top));
}
}
}
if (closingUp)
{
// newEdge's ends have already been added
return;
}
Vector2s.Add(newVector2);
}
Vector2 newRightVector2 = newEdge.ClippedEnds[LR.Other(newOrientation)];
if (!CloseEnough(Vector2s[0], newRightVector2))
{
Vector2s.Add(newRightVector2);
}
}
internal float X
{
get
{
return _coord.x;
}
}
internal float Y
{
get
{
return _coord.y;
}
}
internal float Dist(ICoord p)
{
return Utilities.Distance(p.Coord(), this._coord);
}
}
class BoundsCheck
{
public static readonly int TOP = 1;
public static readonly int BOTTOM = 2;
public static readonly int LEFT = 4;
public static readonly int RIGHT = 8;
/**
*
* @param Vector2
* @param bounds
* @return an int with the appropriate bits set if the Vector2 lies on the corresponding bounds lines
*
*/
public static int Check(Vector2 point, Rect bounds)
{
int value = 0;
if (point.x == bounds.left)
{
value |= LEFT;
}
if (point.x == bounds.right)
{
value |= RIGHT;
}
if (point.y == bounds.top)
{
value |= TOP;
}
if (point.y == bounds.bottom)
{
value |= BOTTOM;
}
return value;
}
public BoundsCheck()
{
throw new Exception("BoundsCheck constructor unused");
}
}
}
| |
// 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 System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Trinity.Configuration;
using Trinity.Diagnostics;
using Trinity.TSL.Lib;
namespace Trinity.Network.Http
{
/// <summary>
/// Represents an HTTP request handler.
/// </summary>
/// <param name="context">An context object that provides access to the request and response objects.</param>
public delegate void HttpHandler(HttpListenerContext context);
/// <summary>
/// Represents an HTTP server.
/// </summary>
public class TrinityHttpServer : IDisposable
{
private HttpListener m_HttpServer = null;
private HttpHandler m_HttpHandler = null;
private List<AvailabilityGroup> m_RelayInstanceList = null;
private List<int> m_RelayRoundRobinTable = null;
private bool m_AllowCrossDomainRequest = true;
/// <summary>
/// Initializes a new instance of Trinity HTTP server with the specified <see cref="T:Trinity.Network.Http.HttpListener"/> and service endpoints.
/// </summary>
/// <param name="primaryHandler">An HTTP request handler.</param>
/// <param name="serviceEndpoints">A list of Uniform Resource Identifier (URI) prefixes handled by this HTTP server.</param>
public TrinityHttpServer(HttpHandler primaryHandler, List<string> serviceEndpoints)
{
m_HttpHandler = primaryHandler;
m_HttpServer = new HttpListener();
foreach (var prefix in serviceEndpoints)
{
m_HttpServer.Prefixes.Add(prefix);
}
m_HttpServer.Start();
}
internal void SetAuthenticationSchemes(AuthenticationSchemes schemes)
{
m_HttpServer.AuthenticationSchemes = schemes;
}
internal void AddServiceEndpoint(string serviceEndpoint)
{
m_HttpServer.Prefixes.Add(serviceEndpoint);
}
internal void RemoveServiceEndpoint(string serviceEndpoint)
{
m_HttpServer.Prefixes.Remove(serviceEndpoint);
}
/// <summary>
/// Sets the instance list. This is required for <see cref="Trinity.Network.Http.TrinityHttpServer.RelayRequest"/> to function properly.
/// This method will be called by TSL-generated code upon server start up.
/// </summary>
/// <param name="list">The server list.</param>
public void SetInstanceList(List<AvailabilityGroup> list)
{
this.m_RelayInstanceList = new List<AvailabilityGroup>(list);
this.m_RelayRoundRobinTable = new List<int>(Enumerable.Repeat(0, list.Count));
}
/// <summary>
/// Starts listening for incoming HTTP requests.
/// </summary>
public void Listen()
{
ThreadPool.QueueUserWorkItem((o) =>
{
try
{
while (m_HttpServer.IsListening)
{
ThreadPool.QueueUserWorkItem((context) =>
{
ProcessHttpRequest(context as HttpListenerContext);
}, m_HttpServer.GetContext());
}
}
catch (Exception) { }
});
}
private void ProcessHttpRequest(HttpListenerContext ctx)
{
// Error handling: Microsoft OneAPI Guidelines section 7.10.2
try
{
if (m_AllowCrossDomainRequest)
{
ctx.Response.AddHeader("Access-Control-Allow-Origin", "*");
}
if (m_HttpServer.AuthenticationSchemes != AuthenticationSchemes.None)
{
ctx.Response.AddHeader("Access-Control-Allow-Credentials", "true");
}
m_HttpHandler(ctx);
}
catch (BadRequestException ex)
{
WriteResponseForBadRequest(ex, ctx);
try { Log.WriteLine(LogLevel.Warning, "Bad http request: " + ex.Code + ": " + ex.ToString()); }
catch { }
}
catch (Exception ex)
{
WriteResponseForInternalServerError(ctx);
try { Log.WriteLine(LogLevel.Error, ex.ToString()); }
catch { }
}
finally
{
try
{
ctx.Response.OutputStream.Close();
}
catch (Exception) { }
}
}
private void WriteResponseForInternalServerError(HttpListenerContext ctx)
{
ctx.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
using (var writer = new StreamWriter(ctx.Response.OutputStream))
{
writer.Write(@"{
""error"": {
""code"": ""Unspecified"",
""message"": ""Internal server error""
}
}");
}
}
private void WriteResponseForBadRequest(BadRequestException ex, HttpListenerContext ctx)
{
ctx.Response.StatusCode = (int)HttpStatusCode.BadRequest;
using (var writer = new StreamWriter(ctx.Response.OutputStream))
{
writer.Write(@"{
""error"": {
""code"": " + JsonStringProcessor.escape(ex.Code) + @",
""message"": " + JsonStringProcessor.escape(ex.Message) + @"
}
}");
}
}
private static void _RelayRequest(HttpListenerContext context, AvailabilityGroup ag, int idx)
{
ServerInfo s = ag.Instances[idx];
int port = context.Request.LocalEndPoint.Port;
string requestUrl = context.Request.RawUrl;
if (requestUrl == String.Empty || !requestUrl.StartsWith("/", StringComparison.Ordinal))
requestUrl = requestUrl + "/";
requestUrl = requestUrl.Substring(requestUrl.IndexOf('/', 1));
string relayUrl = String.Format(CultureInfo.InvariantCulture, "http://{0}:{1}{2}", s.HostName, port, requestUrl);
HttpWebRequest relayRequest = WebRequest.CreateHttp(relayUrl);
relayRequest.Proxy = null;
if (context.Request.HttpMethod == "POST")
{
Stream relayStream = relayRequest.GetRequestStream();
context.Request.InputStream.CopyTo(relayStream);
}
WebResponse relayResponse = relayRequest.GetResponse();
context.Response.ContentType = relayResponse.ContentType;
relayResponse.GetResponseStream().CopyTo(context.Response.OutputStream);
relayResponse.Dispose();
}
/// <summary>
/// Relays an HTTP request to the specified instance. Should only be called if <see cref="Trinity.Network.Http.TrinityHttpServer.SetInstanceList"/> is properly called.
/// </summary>
/// <param name="instance_id">The server id.</param>
/// <param name="context">The context of the request to relay.</param>
public void RelayRequest(int instance_id, HttpListenerContext context)
{
if (instance_id < 0 || instance_id >= m_RelayInstanceList.Count)
{
Log.WriteLine(LogLevel.Error, "RelayRequest: relay target server index out of bound.");
Log.WriteLine(LogLevel.Error, "RelayRequest: Index: {0}.", instance_id);
Log.WriteLine(LogLevel.Error, "RelayRequest: Remote endpoint: {0}.", context.Request.RemoteEndPoint.ToString());
}
AvailabilityGroup ag = m_RelayInstanceList[instance_id];
int idx = m_RelayRoundRobinTable[instance_id] = (m_RelayRoundRobinTable[instance_id] + 1) % ag.Instances.Count;
_RelayRequest(context, ag, idx);
}
public void Dispose()
{
if (m_HttpServer != null && m_HttpServer.IsListening)
{
try
{
m_HttpServer.Stop();
(m_HttpServer as IDisposable).Dispose();
m_HttpServer = null;
}
catch { }
}
}
}
}
| |
// Track.cs
//
// Copyright (c) 2008 Scott Peterson <lunchtimemama@gmail.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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Xml;
namespace MusicBrainz
{
public sealed class Track : MusicBrainzItem
{
#region Private
const string EXTENSION = "track";
TimeSpan? duration;
ReadOnlyCollection<Release> releases;
ReadOnlyCollection<string> puids;
ReadOnlyCollection<string> isrcs;
#endregion
#region Constructors
Track (string id) : base (id)
{
}
internal Track (XmlReader reader) : base (reader, null, false)
{
}
internal Track (XmlReader reader, Artist artist, bool all_rels_loaded) : base (reader, artist, all_rels_loaded)
{
}
#endregion
#region Protected
internal override string UrlExtension {
get { return EXTENSION; }
}
internal override void CreateIncCore (StringBuilder builder)
{
if (releases == null) AppendIncParameters (builder, "releases");
if (puids == null) AppendIncParameters (builder, "puids");
if (isrcs == null) AppendIncParameters (builder, "isrcs");
base.CreateIncCore (builder);
}
internal override void LoadMissingDataCore ()
{
Track track = new Track (Id);
duration = track.GetDuration ();
if (releases == null) releases = track.GetReleases ();
if (puids == null) puids = track.GetPuids ();
if (isrcs == null) isrcs = track.GetIsrcs ();
base.LoadMissingDataCore (track);
}
internal override void ProcessXmlCore (XmlReader reader)
{
switch (reader.Name) {
case "duration":
duration = TimeSpan.FromMilliseconds (reader.ReadElementContentAsDouble ());
break;
case "release-list":
if (reader.ReadToDescendant ("release")) {
List<Release> releases = new List<Release> ();
do releases.Add (new Release (reader.ReadSubtree ()));
while (reader.ReadToNextSibling ("release"));
this.releases = releases.AsReadOnly ();
}
break;
case "puid-list":
if (reader.ReadToDescendant ("puid")) {
List<string> puids = new List<string> ();
do puids.Add (reader["id"]);
while (reader.ReadToNextSibling ("puid"));
this.puids = puids.AsReadOnly ();
}
break;
case "isrc-list":
if (reader.ReadToDescendant ("isrc")) {
List<string> isrcs = new List<string> ();
do isrcs.Add (reader["id"]);
while (reader.ReadToNextSibling ("isrc"));
this.isrcs = isrcs.AsReadOnly ();
}
break;
default:
base.ProcessXmlCore (reader);
break;
}
}
#endregion
#region Public
[Queryable ("trid")]
public override string Id {
get { return base.Id; }
}
[Queryable ("track")]
public override string GetTitle ()
{
return base.GetTitle ();
}
[Queryable ("dur")]
public TimeSpan GetDuration ()
{
return GetPropertyOrDefault (ref duration);
}
[QueryableMember ("Contains", "release")]
public ReadOnlyCollection<Release> GetReleases ()
{
return GetPropertyOrNew (ref releases);
}
public ReadOnlyCollection<string> GetPuids ()
{
return GetPropertyOrNew (ref puids);
}
public ReadOnlyCollection<string> GetIsrcs ()
{
return GetPropertyOrNew (ref isrcs, !AllRelsLoaded);
}
public int GetTrackNumber (Release release)
{
if (release == null) throw new ArgumentNullException ("release");
foreach (Release r in GetReleases ())
if (r.Equals (release))
return r.TrackNumber;
return -1;
}
#endregion
#region Static
public static Track Get (string id)
{
if (id == null) throw new ArgumentNullException ("id");
return new Track (id);
}
public static Query<Track> Query (string title)
{
if (title == null) throw new ArgumentNullException ("title");
TrackQueryParameters parameters = new TrackQueryParameters ();
parameters.Title = title;
return Query (parameters);
}
public static Query<Track> Query (string title, string artist)
{
if (title == null) throw new ArgumentNullException ("title");
if (artist == null) throw new ArgumentNullException ("artist");
TrackQueryParameters parameters = new TrackQueryParameters ();
parameters.Title = title;
parameters.Artist = artist;
return Query (parameters);
}
public static Query<Track> Query (string title, string artist, string release)
{
if (title == null) throw new ArgumentNullException ("title");
if (artist == null) throw new ArgumentNullException ("artist");
if (release == null) throw new ArgumentNullException ("release");
TrackQueryParameters parameters = new TrackQueryParameters ();
parameters.Title = title;
parameters.Artist = artist;
parameters.Release = release;
return Query (parameters);
}
public static Query<Track> Query (TrackQueryParameters parameters)
{
if (parameters == null) throw new ArgumentNullException ("parameters");
return new Query<Track> (EXTENSION, parameters.ToString ());
}
public static Query<Track> QueryLucene (string luceneQuery)
{
if(luceneQuery == null) throw new ArgumentNullException ("luceneQuery");
return new Query<Track> (EXTENSION, CreateLuceneParameter (luceneQuery));
}
public static implicit operator string (Track track)
{
return track.ToString ();
}
#endregion
}
#region Ancillary Types
public sealed class TrackQueryParameters : ItemQueryParameters
{
string release;
public string Release {
get { return release; }
set { release = value; }
}
string release_id;
public string ReleaseId {
get { return release_id; }
set { release_id = value; }
}
uint? duration;
public uint? Duration {
get { return duration; }
set { duration = value; }
}
int? track_number;
public int? TrackNumber {
get { return track_number; }
set { track_number = value; }
}
string puid;
public string Puid {
get { return puid; }
set { puid = value; }
}
internal override void ToStringCore (StringBuilder builder)
{
if (release != null) {
builder.Append ("&release=");
Utils.PercentEncode (builder, release);
}
if (release_id != null) {
builder.Append ("&releaseid=");
builder.Append (release_id);
}
if (duration != null) {
builder.Append ("&duration=");
builder.Append (duration.Value);
}
if (track_number != null) {
builder.Append ("&tracknumber=");
builder.Append (track_number.Value);
}
if (puid != null) {
builder.Append ("&puid=");
builder.Append (puid);
}
}
}
#endregion
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Diagnostics
{
using System.Xml;
using System.Runtime;
using System.Diagnostics;
/// <summary>
/// Very basic performance-oriented XmlWriter implementation. No validation/encoding is made.
/// Namespaces are not supported
/// Minimal formatting support
/// </summary>
internal class PlainXmlWriter : XmlWriter
{
internal class MaxSizeExceededException : Exception
{
}
TraceXPathNavigator navigator;
bool writingAttribute = false;
string currentAttributeName;
string currentAttributePrefix;
string currentAttributeNs;
string currentAttributeText = string.Empty;
public PlainXmlWriter()
: this(-1) //no quota
{
}
public PlainXmlWriter(int maxSize)
{
this.navigator = new TraceXPathNavigator(maxSize);
}
public TraceXPathNavigator Navigator
{
get
{
return this.navigator;
}
}
public override void WriteStartDocument() { }
public override void WriteStartDocument(bool standalone) { }
public override void WriteDocType(string name, string pubid, string sysid, string subset) { }
public override void WriteEndDocument() { }
public override string LookupPrefix(string ns)
{
return this.navigator.LookupPrefix(ns);
}
public override WriteState WriteState
{
get { return this.navigator.WriteState; }
}
public override XmlSpace XmlSpace
{
get { return XmlSpace.Default; }
}
public override string XmlLang
{
get { return string.Empty; }
}
public override void WriteValue(object value)
{
this.navigator.AddText(value.ToString());
}
public override void WriteValue(string value)
{
this.navigator.AddText(value);
}
public override void WriteBase64(byte[] buffer, int offset, int count) { }
public override void WriteStartElement(string prefix, string localName, string ns)
{
#pragma warning disable 618
Fx.Assert(!String.IsNullOrEmpty(localName), "");
#pragma warning restore 618
if (String.IsNullOrEmpty(localName))
{
throw new ArgumentNullException("localName");
}
this.navigator.AddElement(prefix, localName, ns);
}
public override void WriteFullEndElement()
{
WriteEndElement();
}
public override void WriteEndElement()
{
this.navigator.CloseElement();
}
public override void WriteStartAttribute(string prefix, string localName, string ns)
{
#pragma warning disable 618
Fx.Assert(!this.writingAttribute, "");
#pragma warning restore 618
if (this.writingAttribute)
{
throw new InvalidOperationException();
}
this.currentAttributeName = localName;
this.currentAttributePrefix = prefix;
this.currentAttributeNs = ns;
this.currentAttributeText = string.Empty;
this.writingAttribute = true;
}
public override void WriteEndAttribute()
{
#pragma warning disable 618
Fx.Assert(this.writingAttribute, "");
#pragma warning restore 618
if (!this.writingAttribute)
{
throw new InvalidOperationException();
}
this.navigator.AddAttribute(this.currentAttributeName, this.currentAttributeText, this.currentAttributeNs, this.currentAttributePrefix);
this.writingAttribute = false;
}
public override void WriteCData(string text)
{
this.WriteRaw("<![CDATA[" + text + "]]>");
}
public override void WriteComment(string text)
{
this.navigator.AddComment(text);
}
public override void WriteProcessingInstruction(string name, string text)
{
this.navigator.AddProcessingInstruction(name, text);
}
public override void WriteEntityRef(string name)
{
}
public override void WriteCharEntity(char ch)
{
}
public override void WriteSurrogateCharEntity(char lowChar, char highChar)
{
}
public override void WriteWhitespace(string ws)
{
}
public override void WriteString(string text)
{
if (this.writingAttribute)
{
currentAttributeText += text;
}
else
{
this.WriteValue(text);
}
}
public override void WriteChars(Char[] buffer, int index, int count)
{
// Exceptions being thrown as per data found at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemxmlxmlwriterclasswritecharstopic.asp
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (index < 0)
{
throw new ArgumentOutOfRangeException("index");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count");
}
if ((buffer.Length - index) < count)
{
throw new ArgumentException(TraceSR.GetString(TraceSR.WriteCharsInvalidContent));
}
this.WriteString(new string(buffer, index, count));
}
public override void WriteRaw(String data)
{
this.WriteString(data);
}
public override void WriteRaw(Char[] buffer, int index, int count)
{
this.WriteChars(buffer, index, count);
}
public override void Close()
{
}
public override void Flush()
{
}
}
}
| |
#region
/*
Copyright (c) 2002-2012, Bas Geertsema, Xih Solutions
(http://www.xihsolutions.net), Thiago.Sayao, Pang Wu, Ethem Evlice, Andy Phan, Chang Liu.
All rights reserved. http://code.google.com/p/msnp-sharp/
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the names of Bas Geertsema or Xih Solutions nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion
using System;
using System.Net;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Diagnostics;
namespace MSNPSharp
{
using MSNPSharp.P2P;
using MSNPSharp.Core;
using MSNPSharp.MSNWS.MSNABSharingService;
using System.Globalization;
using MSNPSharp.MSNWS.MSNDirectoryService;
/// <summary>
/// User in roster list.
/// </summary>
[Serializable]
public partial class Contact
{
/// <summary>
/// live.com
/// </summary>
public const string DefaultHostDomain = "live.com";
#region Serializable Fields
protected Guid guid = Guid.Empty;
protected Guid addressBookId = Guid.Empty;
private long cId = 0;
private string account = string.Empty;
private string name = string.Empty;
private string nickName = string.Empty;
private string contactType = string.Empty;
private bool hasSpace = false;
private bool mobileDevice = false;
private bool mobileAccess = false;
private bool isMessengerUser = false;
private bool isHiddenContact = false;
private PresenceStatus status = PresenceStatus.Offline;
private IMAddressInfoType clientType = IMAddressInfoType.WindowsLive;
private RoleId circleRole = RoleId.None;
private RoleLists lists = RoleLists.None;
private RoleId friendshipStatus = RoleId.None;
#endregion
#region NonSerialized fields
[NonSerialized]
private Dictionary<string, string> phoneNumbers = new Dictionary<string, string>();
[NonSerialized]
private Dictionary<string, object> coreProfile = new Dictionary<string, object>();
[NonSerialized]
private List<ContactGroup> contactGroups = new List<ContactGroup>(0);
[NonSerialized]
private Dictionary<string, Emoticon> emoticons = new Dictionary<string, Emoticon>(0);
[NonSerialized]
private Dictionary<string, Contact> siblings = new Dictionary<string, Contact>(0);
[NonSerialized]
protected Dictionary<Guid, EndPointData> endPointData = new Dictionary<Guid, EndPointData>(0);
[NonSerialized]
private List<ActivityDetailsType> activities = new List<ActivityDetailsType>(0);
[NonSerialized]
private object syncObject = new object();
[NonSerialized]
private NSMessageHandler nsMessageHandler = null;
[NonSerialized]
private string siblingString = string.Empty;
[NonSerialized]
private string hash = string.Empty;
[NonSerialized]
private string comment = string.Empty;
[NonSerialized]
private int adlCount = 1;
[NonSerialized]
private object clientData = null;
[NonSerialized]
private DisplayImage displayImage = null;
[NonSerialized]
private SceneImage sceneImage = null;
[NonSerialized]
private PersonalMessage personalMessage = null;
[NonSerialized]
private Color colorScheme = Color.Empty;
[NonSerialized]
private Uri userTile = null;
[NonSerialized]
private string userTileLocation = string.Empty;
[NonSerialized]
private string sceneContext = string.Empty;
[NonSerialized]
private P2PBridge directBridge = null;
[NonSerialized]
internal DCNonceType dcType = DCNonceType.None;
[NonSerialized]
internal Guid dcPlainKey = Guid.Empty;
[NonSerialized]
internal Guid dcLocalHashedNonce = Guid.Empty;
[NonSerialized]
internal Guid dcRemoteHashedNonce = Guid.Empty;
[NonSerialized]
internal string HostDomain = DefaultHostDomain;
[NonSerialized]
private ContactList contactList = null;
public ContactList ContactList
{
get
{
return contactList;
}
internal set
{
contactList = value;
}
}
[NonSerialized]
internal ContactType MeContact = null;
[NonSerialized]
internal CircleInverseInfoType circleInfo = null;
[NonSerialized]
private Contact gatewayContact = null;
public Contact Via
{
get
{
return gatewayContact;
}
internal set
{
gatewayContact = value;
}
}
internal void GenerateNewDCKeys()
{
dcType = DCNonceType.Sha1;
dcPlainKey = Guid.NewGuid();
dcLocalHashedNonce = HashedNonceGenerator.HashNonce(dcPlainKey);
dcRemoteHashedNonce = Guid.Empty;
}
#endregion
#region .ctor
private Contact()
{
}
protected internal Contact(string account, IMAddressInfoType cliType, NSMessageHandler handler)
: this(Guid.Empty, account, cliType, 0, handler)
{
}
protected internal Contact(string abId, string account, IMAddressInfoType cliType, long cid, NSMessageHandler handler)
: this(new Guid(abId), account, cliType, cid, handler)
{
}
protected internal Contact(Guid abId, string acc, IMAddressInfoType cliType, long cid, NSMessageHandler handler)
{
GenerateNewDCKeys();
NSMessageHandler = handler;
addressBookId = abId;
account = acc.ToLowerInvariant();
clientType = cliType;
cId = cid;
SetName(account);
siblingString = ClientType.ToString() + ":" + account;
hash = MakeHash(Account, ClientType);
if (NSMessageHandler != null)
{
NSMessageHandler.ContactManager.Add(this);
}
displayImage = DisplayImage.CreateDefaultImage(Account);
sceneImage = SceneImage.CreateDefaultImage(Account);
personalMessage = new PersonalMessage();
if (Account == RemoteNetworkGateways.FaceBookGatewayAccount ||
Account == RemoteNetworkGateways.LinkedInGateway)
{
IsHiddenContact = true;
}
}
#endregion
#region Events
/// <summary>
/// Fired when friendship with a contact changed.
/// </summary>
public event EventHandler<FriendshipStatusChangedEventArgs> FriendshipStatusChanged;
protected virtual void OnFriendshipStatusChanged(FriendshipStatusChangedEventArgs e)
{
if (FriendshipStatusChanged != null)
FriendshipStatusChanged(this, e);
}
/// <summary>
/// Fired when contact places changed.
/// </summary>
public event EventHandler<PlaceChangedEventArgs> PlacesChanged;
protected virtual void OnPlacesChanged(PlaceChangedEventArgs e)
{
if (PlacesChanged != null)
PlacesChanged(this, e);
}
/// <summary>
/// Fired when core profile updated via Directory Service.
/// </summary>
public event EventHandler<EventArgs> CoreProfileUpdated;
protected internal virtual void OnCoreProfileUpdated(EventArgs e)
{
if (CoreProfileUpdated != null)
CoreProfileUpdated(this, e);
}
/// <summary>
/// Fired when contact's display name changed.
/// </summary>
public event EventHandler<EventArgs> ScreenNameChanged;
protected virtual void OnScreenNameChanged(string oldName)
{
if (ScreenNameChanged != null)
{
ScreenNameChanged(this, EventArgs.Empty);
}
}
public event EventHandler<EventArgs> PersonalMessageChanged;
protected virtual void OnPersonalMessageChanged(PersonalMessage newmessage)
{
if (PersonalMessageChanged != null)
{
PersonalMessageChanged(this, EventArgs.Empty);
}
}
/// <summary>
/// Fired after contact's display image has been changed.
/// </summary>
public event EventHandler<DisplayImageChangedEventArgs> DisplayImageChanged;
protected virtual void OnDisplayImageChanged(DisplayImageChangedEventArgs e)
{
if (DisplayImageChanged != null)
{
DisplayImageChanged(this, e);
}
}
/// <summary>
/// Fired after contact's scene has been changed.
/// </summary>
public event EventHandler<SceneImageChangedEventArgs> SceneImageChanged;
protected virtual void OnSceneImageChanged(SceneImageChangedEventArgs e)
{
if (SceneImageChanged != null)
{
SceneImageChanged(this, e);
}
}
/// <summary>
/// Fired after received contact's display image changed notification.
/// </summary>
public event EventHandler<DisplayImageChangedEventArgs> DisplayImageContextChanged;
protected virtual void OnDisplayImageContextChanged(DisplayImageChangedEventArgs e)
{
if (DisplayImageContextChanged != null)
{
DisplayImageContextChanged(this, e);
}
}
/// <summary>
/// Fired after receiving notification that the contact's scene image has changed.
/// </summary>
public event EventHandler<SceneImageChangedEventArgs> SceneImageContextChanged;
protected virtual void OnSceneImageContextChanged(SceneImageChangedEventArgs e)
{
if (SceneImageContextChanged != null)
{
SceneImageContextChanged(this, e);
}
}
/// <summary>
/// Fired after receiving notification that the contact's color scheme has changed.
/// </summary>
public event EventHandler<EventArgs> ColorSchemeChanged;
internal virtual void OnColorSchemeChanged()
{
if (ColorSchemeChanged != null)
{
ColorSchemeChanged(this, EventArgs.Empty);
}
}
public event EventHandler<ContactGroupEventArgs> ContactGroupAdded;
protected virtual void OnContactGroupAdded(ContactGroup group)
{
if (ContactGroupAdded != null)
ContactGroupAdded(this, new ContactGroupEventArgs(group));
}
public event EventHandler<ContactGroupEventArgs> ContactGroupRemoved;
protected virtual void OnContactGroupRemoved(ContactGroup group)
{
if (ContactGroupRemoved != null)
ContactGroupRemoved(this, new ContactGroupEventArgs(group));
}
public event EventHandler<StatusChangedEventArgs> ContactOnline;
protected virtual void OnContactOnline(StatusChangedEventArgs e)
{
if (ContactOnline != null)
ContactOnline(this, e);
}
public event EventHandler<StatusChangedEventArgs> ContactOffline;
protected virtual void OnContactOffline(StatusChangedEventArgs e)
{
if (ContactOffline != null)
{
ContactOffline(this, e);
}
}
public event EventHandler<StatusChangedEventArgs> StatusChanged;
protected virtual void OnStatusChanged(StatusChangedEventArgs e)
{
if (StatusChanged != null)
StatusChanged(this, e);
}
public event EventHandler<EventArgs> DirectBridgeEstablished;
protected void OnDirectBridgeEstablished(EventArgs e)
{
if (DirectBridgeEstablished != null)
DirectBridgeEstablished(this, e);
}
#endregion
protected internal void SetCircleInfo(CircleInverseInfoType circleInfo, ContactType me)
{
MeContact = me;
CID = me.contactInfo.CID;
this.circleInfo = circleInfo;
HostDomain = circleInfo.Content.Info.HostedDomain.ToLowerInvariant();
CircleRole = circleInfo.PersonalInfo.MembershipInfo.CirclePersonalMembership.Role;
SetName(circleInfo.Content.Info.DisplayName);
SetNickName(Name);
contactList = new ContactList(AddressBookId, new Owner(AddressBookId, me.contactInfo.passportName, me.contactInfo.CID, NSMessageHandler), this, NSMessageHandler);
Lists = RoleLists.Allow | RoleLists.Forward;
}
#region Contact Properties
internal object SyncObject
{
get
{
return syncObject;
}
}
internal string SiblingString
{
get
{
return siblingString;
}
}
internal NSMessageHandler NSMessageHandler
{
get
{
return nsMessageHandler;
}
set
{
nsMessageHandler = value;
}
}
/// <summary>
/// The display image url from the webside.
/// </summary>
public Uri UserTileURL
{
get
{
return userTile;
}
internal set
{
userTile = value;
}
}
/// <summary>
/// The displayimage context.
/// </summary>
public string UserTileLocation
{
//I create this property because I don't want to play tricks with display image's OriginalContext and Context any more.
get
{
return userTileLocation;
}
internal set
{
userTileLocation = MSNObject.GetDecodeString(value);
}
}
/// <summary>
/// The scenes context.
/// </summary>
public string SceneContext
{
get
{
return sceneContext;
}
internal set
{
sceneContext = MSNObject.GetDecodeString(value);
}
}
/// <summary>
/// Get the Guid of contact, NOT CID.
/// </summary>
public Guid Guid
{
get
{
return guid;
}
internal set
{
guid = value;
}
}
/// <summary>
/// The identifier of addressbook this contact belongs to.
/// </summary>
public Guid AddressBookId
{
get
{
return addressBookId;
}
}
/// <summary>
/// The contact id of contact, only PassportMembers have CID.
/// </summary>
public long CID
{
get
{
return cId;
}
internal set
{
cId = value;
}
}
/// <summary>
/// The account of contact (E-mail address, phone number, Circle guid, FacebookID etc.)
/// </summary>
public string Account
{
get
{
return account;
}
}
/// <summary>
/// The name displayed for local user since WLM2011.
/// </summary>
public virtual string PublicProfileName
{
get
{
if (CoreProfile.ContainsKey(CoreProfileAttributeName.PublicProfile_DisplayName) &&
CoreProfile.ContainsKey(CoreProfileAttributeName.PublicProfile_DisplayLastName))
{
return CoreProfile[CoreProfileAttributeName.PublicProfile_DisplayName].ToString() + " " +
CoreProfile[CoreProfileAttributeName.PublicProfile_DisplayLastName].ToString();
}
return string.Empty;
}
}
/// <summary>
/// The name displayed to your buddies since WLM2011.
/// </summary>
public virtual string ExpressionProfileName
{
get
{
if (CoreProfile.ContainsKey(CoreProfileAttributeName.ExpressionProfile_DisplayName))
{
return CoreProfile[CoreProfileAttributeName.ExpressionProfile_DisplayName].ToString();
}
return string.Empty;
}
}
public virtual string PreferredName
{
get
{
if (PersonalMessage != null)
{
if (!string.IsNullOrEmpty(PersonalMessage.FriendlyName))
{
return PersonalMessage.FriendlyName;
}
}
if (!string.IsNullOrEmpty(ExpressionProfileName))
return ExpressionProfileName;
if (!string.IsNullOrEmpty(PublicProfileName))
return PublicProfileName;
return string.IsNullOrEmpty(Name) ? NickName : Name;
}
}
/// <summary>
/// The display name of contact.
/// </summary>
public virtual string Name
{
get
{
return name;
}
set
{
throw new NotImplementedException("Must be override in subclass.");
}
}
public string HomePhone
{
get
{
return phoneNumbers.ContainsKey(ContactPhoneTypes.ContactPhonePersonal) ?
phoneNumbers[ContactPhoneTypes.ContactPhonePersonal] : string.Empty;
}
}
public string WorkPhone
{
get
{
return phoneNumbers.ContainsKey(ContactPhoneTypes.ContactPhoneBusiness) ?
phoneNumbers[ContactPhoneTypes.ContactPhoneBusiness] : string.Empty;
}
}
public string MobilePhone
{
get
{
return phoneNumbers.ContainsKey(ContactPhoneTypes.ContactPhoneMobile) ?
phoneNumbers[ContactPhoneTypes.ContactPhoneMobile] : string.Empty;
}
}
public Dictionary<string, string> PhoneNumbers
{
get
{
return phoneNumbers;
}
}
public Dictionary<string, object> CoreProfile
{
get
{
return coreProfile;
}
}
public bool MobileDevice
{
get
{
return mobileDevice;
}
}
public bool MobileAccess
{
get
{
return mobileAccess;
}
}
/// <summary>
/// Indicates whether this contact has MSN Space.
/// </summary>
public bool HasSpace
{
get
{
return hasSpace;
}
internal set
{
hasSpace = value;
NSMessageHandler.ContactService.UpdateContact(this, AddressBookId, null);
}
}
public Dictionary<Guid, EndPointData> EndPointData
{
get
{
return endPointData;
}
}
public bool HasSignedInWithMultipleEndPoints
{
get
{
return EndPointData.Count > 1;
}
}
public int PlaceCount
{
get
{
return EndPointData.Count;
}
}
public P2PVersion P2PVersionSupported
{
get
{
if (EndPointData.Count > 0)
{
Guid ep = SelectBestEndPointId();
if (EndPointData.ContainsKey(ep))
{
return EndPointData[ep].P2PVersionSupported;
}
}
return P2PVersion.None;
}
}
public P2PBridge DirectBridge
{
get
{
return directBridge;
}
internal set
{
if (directBridge != null)
{
directBridge.BridgeOpened -= HandleDirectBridgeOpened;
directBridge.BridgeClosed -= HandleDirectBridgeClosed;
}
directBridge = value;
if (directBridge != null)
{
directBridge.BridgeOpened += HandleDirectBridgeOpened;
directBridge.BridgeClosed += HandleDirectBridgeClosed;
}
}
}
/// <summary>
/// The online status of contact.
/// </summary>
public virtual PresenceStatus Status
{
get
{
return status;
}
set
{
throw new NotImplementedException("This property is real-only for base class. Must be override in subclass.");
}
}
/// <summary>
/// Indicates whether the contact is online.
/// </summary>
public bool Online
{
get
{
return status != PresenceStatus.Offline;
}
}
/// <summary>
/// The type of contact's email account.
/// </summary>
public IMAddressInfoType ClientType
{
get
{
return clientType;
}
}
/// <summary>
/// The role of contact in the addressbook.
/// </summary>
public string ContactType
{
get
{
return contactType;
}
internal set
{
contactType = value;
}
}
public List<ContactGroup> ContactGroups
{
get
{
return contactGroups;
}
}
public Dictionary<string, Contact> Siblings
{
get
{
return siblings;
}
}
public virtual DisplayImage DisplayImage
{
get
{
LoadImageFromDeltas(displayImage);
return displayImage;
}
//Calling this will not fire DisplayImageChanged event.
internal set
{
if (displayImage != value)
{
displayImage = value;
SaveImage(displayImage);
}
}
}
public virtual SceneImage SceneImage
{
get
{
LoadImageFromDeltas(sceneImage);
return sceneImage;
}
internal set
{
if (sceneImage != value)
{
sceneImage = value;
SaveImage(sceneImage);
}
}
}
public virtual Color ColorScheme
{
get
{
return colorScheme;
}
internal set
{
if (colorScheme != value)
{
colorScheme = value;
}
}
}
public PersonalMessage PersonalMessage
{
get
{
return personalMessage;
}
protected internal set
{
if (null != value /*don't eval this: && value != personalMessage*/)
{
personalMessage = value;
OnPersonalMessageChanged(value);
}
}
}
/// <summary>
/// Emoticons[sha]
/// </summary>
public Dictionary<string, Emoticon> Emoticons
{
get
{
return emoticons;
}
}
public List<ActivityDetailsType> Activities
{
get
{
return activities;
}
}
/// <summary>
/// The string representation info of contact.
/// </summary>
public virtual string Hash
{
get
{
return hash;
}
}
public object ClientData
{
get
{
return clientData;
}
set
{
clientData = value;
}
}
/// <summary>
/// Receive updated contact information automatically.
/// <remarks>Contact details like address and phone numbers are automatically downloaded to your Address Book.</remarks>
/// </summary>
public bool AutoSubscribeToUpdates
{
get
{
return (contactType == MessengerContactType.Live || contactType == MessengerContactType.LivePending);
}
set
{
if (NSMessageHandler != null && Guid != Guid.Empty && ClientType == IMAddressInfoType.WindowsLive)
{
if (value)
{
if (!AutoSubscribeToUpdates)
{
contactType = MessengerContactType.LivePending;
NSMessageHandler.ContactService.UpdateContact(this, AddressBookId, null);
}
}
else
{
if (contactType != MessengerContactType.Regular)
{
contactType = MessengerContactType.Regular;
NSMessageHandler.ContactService.UpdateContact(this, AddressBookId, null);
}
}
}
}
}
public bool IsHiddenContact
{
get
{
return isHiddenContact;
}
private set
{
isHiddenContact = value;
}
}
/// <summary>
/// Indicates whether the contact can receive MSN message.
/// </summary>
public bool IsMessengerUser
{
get
{
return isMessengerUser;
}
set
{
if (NSMessageHandler != null && Guid != Guid.Empty && IsMessengerUser != value)
{
isMessengerUser = value;
NSMessageHandler.ContactService.UpdateContact(this, AddressBookId,
delegate //If you don't add this, you can't see the contact online until your next login
{
string payload = ContactList.GenerateMailListForAdl(this, Lists, false);
if (value)
NSMessageHandler.MessageProcessor.SendMessage(new NSPayLoadMessage("ADL", payload));
else
NSMessageHandler.MessageProcessor.SendMessage(new NSPayLoadMessage("RML", payload));
});
}
NotifyManager();
}
}
public string Comment
{
get
{
return comment;
}
set
{
if (NSMessageHandler != null && Guid != Guid.Empty && Comment != value)
{
comment = value;
NSMessageHandler.ContactService.UpdateContact(this, AddressBookId, null);
}
}
}
/// <summary>
/// The name provide by the owner.
/// </summary>
public string NickName
{
get
{
return nickName;
}
set
{
if (NSMessageHandler != null && Guid != Guid.Empty && NickName != value)
{
nickName = value;
NSMessageHandler.ContactService.UpdateContact(this, AddressBookId, null);
}
}
}
/// <summary>
/// The amount of ADL commands send for this contact.
/// </summary>
internal int ADLCount
{
get
{
return adlCount;
}
set
{
if (value < 0)
{
value = 0;
}
adlCount = value;
}
}
/// <summary>
/// The role of a contact in the addressbook.
/// </summary>
public RoleId CircleRole
{
get
{
return circleRole;
}
internal set
{
circleRole = value;
}
}
#endregion
#region List Properties
public bool AppearOnline
{
get
{
return ((lists & RoleLists.Hide) == RoleLists.None);
}
set
{
if (value != AppearOnline)
{
AppearOffline = !value;
}
}
}
public bool AppearOffline
{
get
{
return !AppearOnline;
}
set
{
if (value != AppearOffline)
{
if (value)
{
NSMessageHandler.ContactService.AddContactToList(this, ServiceName.IMAvailability, RoleLists.Hide, null);
}
else
{
NSMessageHandler.ContactService.RemoveContactFromList(this, ServiceName.IMAvailability, RoleLists.Hide, null);
}
}
}
}
public bool OnForwardList
{
get
{
return ((lists & RoleLists.Forward) == RoleLists.Forward);
}
set
{
if (value != OnForwardList)
{
if (value)
{
NSMessageHandler.ContactService.AddContactToList(this, ServiceName.Messenger, RoleLists.Forward, null);
}
else
{
NSMessageHandler.ContactService.RemoveContactFromList(this, ServiceName.Messenger, RoleLists.Forward, null);
}
}
}
}
/// <summary>
/// Adds or removes this contact into/from your AL.
/// If this contact is not in ReverseList and you want to delete forever,
/// set this property to false.
/// </summary>
public bool OnAllowedList
{
get
{
return ((lists & RoleLists.Allow) == RoleLists.Allow);
}
set
{
if (value != OnAllowedList)
{
if (value)
{
NSMessageHandler.ContactService.AddContactToList(this, ServiceName.Messenger, RoleLists.Allow, null);
}
else
{
NSMessageHandler.ContactService.RemoveContactFromList(this, ServiceName.Messenger, RoleLists.Allow, null);
}
}
}
}
/// <summary>
/// Indicates whether the contact have you on their contact list and pending your approval.
/// </summary>
public bool OnPendingList
{
get
{
return ((lists & RoleLists.Pending) == RoleLists.Pending);
}
set
{
if (value != OnPendingList && value == false)
{
NSMessageHandler.ContactService.RemoveContactFromList(this, ServiceName.Messenger, RoleLists.Pending, null);
}
}
}
/// <summary>
/// The msn lists this contact has.
/// </summary>
public virtual RoleLists Lists
{
get
{
return lists;
}
protected internal set
{
lists = value;
NotifyManager();
}
}
public RoleId FriendshipStatus
{
get
{
return friendshipStatus;
}
}
#endregion
#region Internal setters
internal void SetComment(string note)
{
comment = note;
}
internal void SetIsMessengerUser(bool isMessengerEnabled)
{
isMessengerUser = isMessengerEnabled;
NotifyManager();
}
internal virtual void SetList(RoleLists msnLists)
{
lists = msnLists;
NotifyManager();
}
internal void SetFriendshipStatus(RoleId fs, bool fireEvent)
{
if (friendshipStatus != fs)
{
RoleId oldFs = friendshipStatus;
friendshipStatus = fs;
if (fireEvent)
{
OnFriendshipStatusChanged(new FriendshipStatusChangedEventArgs(this, oldFs, fs));
}
}
}
internal void SetMobileAccess(bool enabled)
{
mobileAccess = enabled;
}
internal void SetMobileDevice(bool enabled)
{
mobileDevice = enabled;
}
internal void SetName(string newName)
{
if (name != newName)
{
string oldName = name;
name = newName;
// notify all of our buddies we changed our name
OnScreenNameChanged(oldName);
}
}
internal void SetColorScheme(Color color)
{
colorScheme = color;
}
internal void SetSceneImage(SceneImage scene)
{
sceneImage = scene;
}
internal void SetHasSpace(bool hasSpaceValue)
{
hasSpace = hasSpaceValue;
}
internal void SetNickName(string newNick)
{
nickName = newNick;
}
/// <summary>
/// Set the <see cref="Status"/> and fire <see cref="Contact.StatusChanged"/> ,
/// <see cref="Contact.ContactOnline"/> and <see cref="Contact.ContactOffline"/> event.
/// </summary>
/// <param name="newStatus"></param>
internal void SetStatus(PresenceStatus newStatus)
{
//Becareful deadlock!
PresenceStatus currentStatus = PresenceStatus.Unknown;
lock (syncObject)
{
currentStatus = status;
}
if (currentStatus != newStatus)
{
PresenceStatus oldStatus = currentStatus;
lock (syncObject)
{
status = newStatus;
}
// raise an event
OnStatusChanged(new StatusChangedEventArgs(oldStatus, newStatus));
// raise the online/offline events
if (oldStatus == PresenceStatus.Offline)
OnContactOnline(new StatusChangedEventArgs(oldStatus, newStatus));
if (newStatus == PresenceStatus.Offline)
OnContactOffline(new StatusChangedEventArgs(oldStatus, newStatus));
}
}
/// <summary>
/// This method will lead to fire <see cref="Contact.DisplayImageContextChanged"/> event if the DisplayImage.Sha has been changed.
/// </summary>
/// <param name="updatedImageContext"></param>
/// <returns>
/// false: No event was fired.<br/>
/// true: The <see cref="Contact.DisplayImageContextChanged"/> was fired.
/// </returns>
internal bool FireDisplayImageContextChangedEvent(string updatedImageContext)
{
if (DisplayImage == updatedImageContext)
return false;
// If Delta already has image, just call DisplayImageChanged instead
if (NSMessageHandler.ContactService.Deltas.HasImage(SiblingString, GetSHA(updatedImageContext), true))
{
string Sha = string.Empty;
byte[] rawImageData = NSMessageHandler.ContactService.Deltas.GetRawImageDataBySiblingString(SiblingString, out Sha, true);
if (rawImageData != null)
displayImage = new DisplayImage(Account, new MemoryStream(rawImageData));
NSMessageHandler.ContactService.Deltas.Save(true);
OnDisplayImageChanged(new DisplayImageChangedEventArgs(displayImage, DisplayImageChangedType.TransmissionCompleted, false));
return true;
}
OnDisplayImageContextChanged(new DisplayImageChangedEventArgs(null, DisplayImageChangedType.UpdateTransmissionRequired));
return true;
}
/// <summary>
/// This method will lead to fire <see cref="Contact.SceneImageContextChanged"/> event if the SceneImage.Sha has been changed.
/// </summary>
/// <param name="updatedImageContext"></param>
/// <returns>
/// false: No event was fired.<br/>
/// true: The <see cref="Contact.SceneImageContextChanged"/> was fired.
/// </returns>
internal bool FireSceneImageContextChangedEvent(string updatedImageContext)
{
if (SceneImage == updatedImageContext)
return false;
// If Delta already has image, just call SceneImageChanged instead
if (NSMessageHandler.ContactService.Deltas.HasImage(SiblingString, GetSHA(updatedImageContext), false))
{
string Sha = string.Empty;
byte[] rawImageData = NSMessageHandler.ContactService.Deltas.GetRawImageDataBySiblingString(SiblingString, out Sha, false);
if (rawImageData != null)
sceneImage = new SceneImage(Account, new MemoryStream(rawImageData));
NSMessageHandler.ContactService.Deltas.Save(true);
OnSceneImageChanged(new SceneImageChangedEventArgs(sceneImage, DisplayImageChangedType.TransmissionCompleted, false));
return true;
}
OnSceneImageContextChanged(new SceneImageChangedEventArgs(DisplayImageChangedType.UpdateTransmissionRequired, updatedImageContext == string.Empty));
return true;
}
/// <summary>
/// This method will lead to fire <see cref="Contact.DisplayImageChanged"/> event if the DisplayImage.Image has been changed.
/// </summary>
/// <param name="image"></param>
/// <returns>
/// false: No event was fired.<br/>
/// true: The <see cref="Contact.DisplayImageChanged"/> event was fired.
/// </returns>
internal bool SetDisplayImageAndFireDisplayImageChangedEvent(DisplayImage image)
{
if (image == null)
return false;
DisplayImageChangedEventArgs displayImageChangedArg = null;
//if ((displayImage != null && displayImage.Sha != image.Sha && displayImage.IsDefaultImage && image.Image != null) || //Transmission completed. default Image -> new Image
// (displayImage != null && displayImage.Sha != image.Sha && !displayImage.IsDefaultImage && image.Image != null) || //Transmission completed. old Image -> new Image.
// (displayImage != null && object.ReferenceEquals(displayImage, image) && displayImage.Image != null) || //Transmission completed. old Image -> updated old Image.
// (displayImage == null))
{
displayImageChangedArg = new DisplayImageChangedEventArgs(image, DisplayImageChangedType.TransmissionCompleted, false);
}
if (!object.ReferenceEquals(displayImage, image))
{
displayImage = image;
}
SaveOriginalDisplayImageAndFireDisplayImageChangedEvent(displayImageChangedArg);
return true;
}
internal bool SetSceneImageAndFireSceneImageChangedEvent(SceneImage image)
{
if (image == null)
return false;
SceneImageChangedEventArgs sceneImageChangedArg = null;
{
sceneImageChangedArg = new SceneImageChangedEventArgs(image, DisplayImageChangedType.TransmissionCompleted, false);
}
if (!object.ReferenceEquals(sceneImage, image))
{
sceneImage = image;
}
SaveOriginalSceneImageAndFireSceneImageChangedEvent(sceneImageChangedArg);
return true;
}
internal void SaveOriginalDisplayImageAndFireDisplayImageChangedEvent(DisplayImageChangedEventArgs arg)
{
SaveImage(displayImage);
OnDisplayImageChanged(arg);
}
internal void SaveOriginalSceneImageAndFireSceneImageChangedEvent(SceneImageChangedEventArgs arg)
{
SaveImage(sceneImage);
OnSceneImageChanged(arg);
}
internal string GetSHA(string imageContext)
{
string decodeContext = MSNObject.GetDecodeString(imageContext);
int indexSHA = decodeContext.IndexOf("SHA1D=\"", 0) + 7;
return decodeContext.Substring(indexSHA, decodeContext.IndexOf("\"", indexSHA) - indexSHA);
}
internal void NotifyManager()
{
if (AddressBookId != new Guid(WebServiceConstants.MessengerIndividualAddressBookId))
return;
if (NSMessageHandler == null)
return;
NSMessageHandler.ContactManager.SyncProperties(this);
}
#region Protected
internal void SetChangedPlace(PlaceChangedEventArgs e)
{
Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose,
"The account " + e.EndPointData.Account +
" was " + e.Reason +
" at another place: " + e.PlaceName + " " + e.EndPointData.Id, GetType().Name);
bool triggerEvent = false;
lock (SyncObject)
{
switch (e.Reason)
{
case PlaceChangedReason.SignedIn:
lock (SyncObject)
EndPointData[e.EndPointData.Id] = e.EndPointData;
triggerEvent = true;
break;
case PlaceChangedReason.SignedOut:
lock (SyncObject)
{
if (EndPointData.ContainsKey(e.EndPointData.Id))
{
EndPointData.Remove(e.EndPointData.Id);
triggerEvent = true;
}
}
break;
}
}
if (triggerEvent)
{
OnPlacesChanged(e);
}
}
protected virtual void LoadImageFromDeltas(DisplayImage image)
{
if (NSMessageHandler.ContactService.Deltas == null)
return;
if (displayImage != null && !displayImage.IsDefaultImage) //Not default, no need to restore.
return;
string Sha = string.Empty;
byte[] rawImageData = NSMessageHandler.ContactService.Deltas.GetRawImageDataBySiblingString(SiblingString, out Sha, true);
if (rawImageData != null)
{
displayImage = new DisplayImage(Account, new MemoryStream(rawImageData));
Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose, "User " + ToString() + "'s displayimage" + "restored.\r\n " +
"Old SHA: " + Sha + "\r\n " +
"Current SHA: " + displayImage.Sha + "\r\n");
}
}
protected virtual void LoadImageFromDeltas(SceneImage image)
{
if (NSMessageHandler.ContactService.Deltas == null)
return;
if (sceneImage != null && !sceneImage.IsDefaultImage) //Not default, no need to restore.
return;
string Sha = string.Empty;
byte[] rawImageData = NSMessageHandler.ContactService.Deltas.GetRawImageDataBySiblingString(SiblingString, out Sha, false);
if (rawImageData != null)
{
sceneImage = new SceneImage(Account, new MemoryStream(rawImageData));
Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose, "User " + ToString() + "'s scene image" + "restored.\r\n " +
"Old SHA: " + Sha + "\r\n " +
"Current SHA: " + displayImage.Sha + "\r\n");
}
}
protected virtual void SaveImage(DisplayImage dispImage)
{
if (NSMessageHandler.ContactService.Deltas == null || dispImage == null)
return;
if (dispImage.Image == null || string.IsNullOrEmpty(dispImage.Sha))
return;
if (NSMessageHandler.ContactService.Deltas.SaveImageAndRelationship(SiblingString, dispImage.Sha, dispImage.GetRawData(), true))
{
NSMessageHandler.ContactService.Deltas.Save(true);
}
}
protected virtual void SaveImage(SceneImage sceneImage)
{
if (NSMessageHandler.ContactService.Deltas == null || sceneImage == null)
return;
if (sceneImage.Image == null || string.IsNullOrEmpty(sceneImage.Sha))
return;
if (NSMessageHandler.ContactService.Deltas.SaveImageAndRelationship(SiblingString, sceneImage.Sha, sceneImage.GetRawData(), false))
{
NSMessageHandler.ContactService.Deltas.Save(true);
}
}
#endregion
#endregion
#region Internal contact operations
private void HandleDirectBridgeOpened(object sender, EventArgs e)
{
OnDirectBridgeEstablished(e);
}
private void HandleDirectBridgeClosed(object sender, EventArgs e)
{
DirectBridge = null;
}
internal void AddContactToGroup(ContactGroup group)
{
if (!contactGroups.Contains(group))
{
contactGroups.Add(group);
OnContactGroupAdded(group);
}
}
internal void RemoveContactFromGroup(ContactGroup group)
{
if (contactGroups.Contains(group))
{
contactGroups.Remove(group);
OnContactGroupRemoved(group);
}
}
/// <summary>
/// Add a membership list for this contact.
/// </summary>
/// <param name="list"></param>
/// <remarks>Since AllowList and BlockList are mutally exclusive, adding a member to AllowList will lead to the remove of BlockList, revese is as the same.</remarks>
internal virtual void AddToList(RoleLists list)
{
if ((lists & list) == RoleLists.None)
{
lists |= list;
NotifyManager();
}
}
internal void AddSibling(Contact contact)
{
lock (syncObject)
Siblings[contact.Hash] = contact;
}
internal void AddSibling(Contact[] contacts)
{
if (contacts == null)
return;
lock (syncObject)
{
foreach (Contact sibling in contacts)
{
Siblings[sibling.Hash] = sibling;
}
}
}
internal void RemoveFromList(RoleLists list)
{
if ((lists & list) != RoleLists.None)
{
lists ^= list;
// set this contact to offline when it is neither on the allow list or on the forward list
if (!(OnForwardList || OnAllowedList))
{
status = PresenceStatus.Offline;
//also clear the groups, becase msn loose them when removed from the two lists
contactGroups.Clear();
}
NotifyManager();
}
}
internal void RemoveFromList()
{
if (NSMessageHandler != null)
{
OnAllowedList = false;
OnForwardList = false;
NotifyManager();
}
}
internal Guid SelectBestEndPointId()
{
Guid ret = Guid.Empty;
foreach (EndPointData ep in EndPointData.Values)
{
ret = ep.Id;
if (ep.Id != Guid.Empty && ep.P2PVersionSupported != P2PVersion.None)
return ep.Id;
}
return ret;
}
internal static string MakeHash(string account, IMAddressInfoType type)
{
if (account == null)
throw new ArgumentNullException("account");
return type.ToString() + ":" + account.ToLowerInvariant();
}
internal static bool IsSpecialGatewayType(IMAddressInfoType type)
{
if (type == IMAddressInfoType.Circle || type == IMAddressInfoType.TemporaryGroup)
return true;
if (type == IMAddressInfoType.RemoteNetwork)
return true;
return false;
}
internal static bool ParseFullAccount(
string fullAccount,
out IMAddressInfoType accountAddressType,
out string account)
{
IMAddressInfoType viaAccountAddressType = IMAddressInfoType.None;
string viaAccount = string.Empty;
return ParseFullAccount(fullAccount, out accountAddressType, out account, out viaAccountAddressType, out viaAccount);
}
internal static bool ParseFullAccount(
string fullAccount,
out IMAddressInfoType accountAddressType, out string account,
out IMAddressInfoType viaAccountAddressType, out string viaAccount)
{
accountAddressType = viaAccountAddressType = IMAddressInfoType.None;
account = viaAccount = String.Empty;
string[] memberAndNetwork = fullAccount.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
if (memberAndNetwork.Length > 0)
{
if (memberAndNetwork.Length > 1)
{
// via=;
if (memberAndNetwork[1].Contains("via="))
{
string via = memberAndNetwork[1].Replace("via=", String.Empty);
string[] viaNetwork = via.Split(new char[] { ':' }, 2, StringSplitOptions.RemoveEmptyEntries);
if (viaNetwork.Length > 1)
{
viaAccountAddressType = (IMAddressInfoType)Enum.Parse(typeof(IMAddressInfoType), viaNetwork[0].ToString());
viaAccount = viaNetwork[1].ToLowerInvariant();
if (viaAccountAddressType == IMAddressInfoType.Telephone)
viaAccount = viaAccount.Replace("tel:", String.Empty);
}
else
{
// Assume windows live account
viaAccountAddressType = IMAddressInfoType.WindowsLive;
viaAccount = viaNetwork[0].ToLowerInvariant();
}
}
}
string[] member = memberAndNetwork[0].Split(new char[] { ':' }, 2, StringSplitOptions.RemoveEmptyEntries);
if (member.Length > 1)
{
accountAddressType = (IMAddressInfoType)Enum.Parse(typeof(IMAddressInfoType), member[0].ToString());
account = member[1].ToLowerInvariant();
if (accountAddressType == IMAddressInfoType.Telephone)
account = viaAccount.Replace("tel:", String.Empty);
}
else
{
// Assume windows live account
accountAddressType = IMAddressInfoType.WindowsLive;
account = member[0].ToString().ToLowerInvariant();
}
return true;
}
return false;
}
internal bool HasLists(RoleLists msnlists)
{
return ((lists & msnlists) == msnlists);
}
#endregion
/// <summary>
/// Gets core profile from directory service and fires <see cref="CoreProfileUpdated"/> event
/// after async request completed.
/// </summary>
public void GetCoreProfile()
{
GetCoreProfile(null, null);
}
public void GetCoreProfile(EventHandler<EventArgs> getCoreProfileCompletedHandler, EventHandler<ExceptionEventArgs> getCoreProfileErrorHandler)
{
if (CID != 0 && NSMessageHandler != null && NSMessageHandler.MSNTicket != MSNTicket.Empty)
{
NSMessageHandler.DirectoryService.Get(CID,
getCoreProfileCompletedHandler,
getCoreProfileErrorHandler
);
}
}
public bool HasGroup(ContactGroup group)
{
return contactGroups.Contains(group);
}
public override int GetHashCode()
{
return Hash.GetHashCode();
}
public static bool operator ==(Contact contact1, Contact contact2)
{
if (((object)contact1) == null && ((object)contact2) == null)
return true;
if (((object)contact1) == null || ((object)contact2) == null)
return false;
return contact1.GetHashCode() == contact2.GetHashCode();
}
public static bool operator !=(Contact contact1, Contact contact2)
{
return !(contact1 == contact2);
}
public override bool Equals(object obj)
{
if (obj == null || obj.GetType() != GetType())
return false;
if (ReferenceEquals(this, obj))
return true;
return obj.GetHashCode() == GetHashCode();
}
public override string ToString()
{
return Hash;
}
/// <summary>
/// Check whether two contacts represent the same user (Have the same passport account).
/// </summary>
/// <param name="contact"></param>
/// <returns></returns>
public virtual bool IsSibling(Contact contact)
{
if (contact == null)
return false;
if (ClientType == contact.ClientType && Account.ToLowerInvariant() == contact.Account.ToLowerInvariant())
return true;
return false;
}
protected virtual bool CanReceiveMessage
{
get
{
if (NSMessageHandler == null || !NSMessageHandler.IsSignedIn)
throw new InvalidOperationException("Cannot send a message without signning in to the server. Please sign in first.");
if (ClientType == IMAddressInfoType.Circle && NSMessageHandler.Owner.Status == PresenceStatus.Hidden)
throw new InvalidOperationException("Cannot send a message to the group when you are in 'Hidden' status.");
return true;
}
}
public virtual bool SupportsMultiparty
{
get
{
lock (SyncObject)
{
foreach (EndPointData ep in EndPointData.Values)
{
if (ClientCapabilitiesEx.SupportsMultipartyConversations == (ep.IMCapabilitiesEx & ClientCapabilitiesEx.SupportsMultipartyConversations))
return true;
}
}
return false;
}
}
/// <summary>
/// Send a typing message indicates that you are typing.
/// </summary>
/// <exception cref="MSNPSharpException">NSMessageHandler is null</exception>
/// <exception cref="InvalidOperationException">Not sign in to the server, or you send a message to a circle in <see cref="PresenceStatus.Hidden"/> status.</exception>
public void SendTypingMessage()
{
if (Online && CanReceiveMessage)
NSMessageHandler.SendTypingMessage(this);
}
/// <summary>
/// Send nudge.
/// </summary>
/// <exception cref="MSNPSharpException">NSMessageHandler is null</exception>
/// <exception cref="InvalidOperationException">Not sign in to the server, or you send a message to a circle in <see cref="PresenceStatus.Hidden"/> status.</exception>
public void SendNudge()
{
if (Online && CanReceiveMessage)
NSMessageHandler.SendNudge(this);
}
/// <summary>
/// Send a text message to the contact.
/// </summary>
/// <param name="textMessage"></param>
/// <exception cref="MSNPSharpException">NSMessageHandler is null</exception>
/// <exception cref="InvalidOperationException">Not sign in to the server, or you send a message to a circle in <see cref="PresenceStatus.Hidden"/> status.</exception>
public void SendMessage(TextMessage textMessage)
{
if (CanReceiveMessage)
NSMessageHandler.SendTextMessage(this, textMessage);
}
public void SendMobileMessage(string text)
{
if (MobileAccess || ClientType == IMAddressInfoType.Telephone)
{
NSMessageHandler.SendMobileMessage(this, text);
}
else
{
SendMessage(new TextMessage(text));
}
}
public void SendEmoticonDefinitions(List<Emoticon> emoticons, EmoticonType icontype)
{
if (emoticons == null)
throw new ArgumentNullException("emoticons");
foreach (Emoticon emoticon in emoticons)
{
if (!NSMessageHandler.Owner.Emoticons.ContainsKey(emoticon.Sha))
{
// Add the emotions to owner's emoticon collection.
NSMessageHandler.Owner.Emoticons.Add(emoticon.Sha, emoticon);
}
}
if (CanReceiveMessage)
NSMessageHandler.SendEmoticonDefinitions(this, emoticons, icontype);
}
}
};
| |
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 BdRestServer.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;
}
}
}
| |
#region Namespaces
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Text;
using Epi.Data.Services;
using Epi.Windows;
#endregion
namespace Epi.Windows.Controls
{
public partial class SettingsPanelDateTime : System.Windows.Forms.UserControl
{
#region Public Event Handlers
public event System.EventHandler DateFormatChanged;
public event System.EventHandler TimeFormatChanged;
public event System.EventHandler DateTimeFormatChanged;
public event System.EventHandler DateFormatTextChanged;
public event System.EventHandler TimeFormatTextChanged;
public event System.EventHandler DateTimeFormatTextChanged;
#endregion
DataView _dateTimeFormats;
DataTable _dataTypes;
#region Constructor
public SettingsPanelDateTime()
{
InitializeComponent();
_dateTimeFormats = AppData.Instance.DataPatternsDataTable.DefaultView;
_dataTypes = AppData.Instance.DataTypesDataTable;
LoadLists();
}
#endregion
#region Public Methods
public void LoadLists()
{
LoadDateFormat();
LoadTimeFormat();
LoadDateTimeFormat();
}
public void ShowSettings()
{
Configuration config = Configuration.GetNewInstance();
Epi.DataSets.Config.SettingsRow settings = config.Settings;
cmbDateFormat.SelectedItem = settings.DateFormat;
cmbTimeFormat.SelectedItem = settings.TimeFormat;
cmbDateTimeFormat.SelectedItem = settings.DateTimeFormat;
}
public void GetSettings(Configuration newConfig)
{
Epi.DataSets.Config.SettingsRow settings = newConfig.Settings;
settings.DateFormat = cmbDateFormat.Text;
settings.TimeFormat = cmbTimeFormat.Text;
settings.DateTimeFormat = cmbDateTimeFormat.Text;
}
#endregion Public Methods
#region Public Properties
public string DateFormat { get { return cmbDateFormat.Text; } }
public string TimeFormat { get { return cmbTimeFormat.Text; } }
public string DateTimeFormat { get { return cmbDateTimeFormat.Text; } }
#endregion
#region Private Methods
private void LoadDateFormat()
{
bool isNull = true;// Configuration.GetNewInstance().Settings.IsDateFormatNull();
string currentDateFormat = "MM-DD-YYYY";
if(isNull == false)
{
currentDateFormat = Configuration.GetNewInstance().Settings.DateFormat;
}
cmbDateFormat.Items.Clear();
if (!string.IsNullOrEmpty(currentDateFormat))
{
cmbDateFormat.Items.Add(currentDateFormat);
}
int dataTypeId = (int)_dataTypes.Select("Name = 'Date'")[0]["DataTypeId"];
string selectExpression = string.Format("DataTypeId = '{0}' ", dataTypeId);
DataRow[] rows = _dateTimeFormats.Table.Select(selectExpression);
foreach (DataRow row in rows)
{
string expression = row["Expression"].ToString();
if (expression != currentDateFormat)
{
cmbDateFormat.Items.Add(expression);
}
}
cmbDateFormat.SelectedIndex = 0;
}
private void LoadTimeFormat()
{
bool isNull = true;// Configuration.GetNewInstance().Settings.IsDateFormatNull();
string currenTimeFormat = "HH:MM:SS AMPM";
if (isNull == false)
{
currenTimeFormat = Configuration.GetNewInstance().Settings.TimeFormat;
}
cmbTimeFormat.Items.Clear();
if (!string.IsNullOrEmpty(currenTimeFormat))
{
cmbTimeFormat.Items.Add(currenTimeFormat);
}
int dataTypeId = (int)_dataTypes.Select("Name = 'Time'")[0]["DataTypeId"];
string selectExpression = string.Format("DataTypeId = '{0}' ", dataTypeId);
DataRow[] rows = _dateTimeFormats.Table.Select(selectExpression);
foreach (DataRow row in rows)
{
string expression = row["Expression"].ToString();
if (expression != currenTimeFormat)
{
cmbTimeFormat.Items.Add(expression);
}
}
cmbTimeFormat.SelectedIndex = 0;
}
private void LoadDateTimeFormat()
{
bool isNull = true;// Configuration.GetNewInstance().Settings.IsDateFormatNull();
string currenDateTimeFormat = "MM-DD-YYYY HH:MM:SS AMPM";
if (isNull == false)
{
currenDateTimeFormat = Configuration.GetNewInstance().Settings.DateTimeFormat;
}
cmbDateTimeFormat.Items.Clear();
if (!string.IsNullOrEmpty(currenDateTimeFormat))
{
cmbDateTimeFormat.Items.Add(currenDateTimeFormat);
}
int dataTypeId = (int)_dataTypes.Select("Name = 'DateTime'")[0]["DataTypeId"];
string selectExpression = string.Format("DataTypeId = '{0}' ", dataTypeId);
DataRow[] rows = _dateTimeFormats.Table.Select(selectExpression);
foreach (DataRow row in rows)
{
string expression = row["Expression"].ToString();
if (expression != currenDateTimeFormat)
{
cmbDateTimeFormat.Items.Add(expression);
}
}
cmbDateTimeFormat.SelectedIndex = 0;
}
#endregion Private Methods
#region Event Handlers
private void SettingsPanelDateTime_Load(object sender, System.EventArgs e)
{
//rdbNormal.Tag = ((short)RecordProcessingScope.Undeleted).ToString(); whut that heck?
//LoadMe();
}
private void cmbDateFormat_SelectedIndexChanged(object sender, System.EventArgs e)
{
if (this.DateFormatChanged != null)
{
this.DateFormatChanged(sender, e);
}
}
private void cmbDateFormat_TextChanged(object sender, System.EventArgs e)
{
if (this.DateFormatTextChanged != null)
{
this.DateFormatTextChanged(sender, e);
}
}
private void cmbTimeFormat_SelectedIndexChanged(object sender, System.EventArgs e)
{
if (this.TimeFormatChanged != null)
{
this.TimeFormatChanged(sender, e);
}
}
private void cmbTimeFormat_TextChanged(object sender, EventArgs e)
{
if (this.TimeFormatTextChanged != null)
{
this.TimeFormatTextChanged(sender, e);
}
}
private void cmbDateTimeFormat_SelectedIndexChanged(object sender, System.EventArgs e)
{
if (this.DateTimeFormatChanged != null)
{
this.DateTimeFormatChanged(sender, e);
}
}
private void cmbDateTimeFormat_TextChanged(object sender, EventArgs e)
{
if (this.DateTimeFormatTextChanged != null)
{
this.DateTimeFormatTextChanged(sender,e);
}
}
#endregion Event Handlers
}
}
| |
/*
* 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 glacier-2012-06-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.Glacier.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Glacier.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for DescribeJob operation
/// </summary>
public class DescribeJobResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
DescribeJobResponse response = new DescribeJobResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("Action", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.Action = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("ArchiveId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.ArchiveId = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("ArchiveSHA256TreeHash", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.ArchiveSHA256TreeHash = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("ArchiveSizeInBytes", targetDepth))
{
var unmarshaller = LongUnmarshaller.Instance;
response.ArchiveSizeInBytes = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Completed", targetDepth))
{
var unmarshaller = BoolUnmarshaller.Instance;
response.Completed = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("CompletionDate", targetDepth))
{
var unmarshaller = Amazon.Runtime.Internal.Transform.DateTimeUnmarshaller.Instance;
response.CompletionDate = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("CreationDate", targetDepth))
{
var unmarshaller = Amazon.Runtime.Internal.Transform.DateTimeUnmarshaller.Instance;
response.CreationDate = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("InventoryRetrievalParameters", targetDepth))
{
var unmarshaller = InventoryRetrievalJobDescriptionUnmarshaller.Instance;
response.InventoryRetrievalParameters = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("InventorySizeInBytes", targetDepth))
{
var unmarshaller = LongUnmarshaller.Instance;
response.InventorySizeInBytes = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("JobDescription", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.JobDescription = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("JobId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.JobId = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("RetrievalByteRange", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.RetrievalByteRange = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("SHA256TreeHash", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.SHA256TreeHash = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("SNSTopic", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.SNSTopic = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("StatusCode", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.StatusCode = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("StatusMessage", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.StatusMessage = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("VaultARN", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.VaultARN = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
ErrorResponse errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidParameterValueException"))
{
return new InvalidParameterValueException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("MissingParameterValueException"))
{
return new MissingParameterValueException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException"))
{
return new ResourceNotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceUnavailableException"))
{
return new ServiceUnavailableException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
return new AmazonGlacierException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
private static DescribeJobResponseUnmarshaller _instance = new DescribeJobResponseUnmarshaller();
internal static DescribeJobResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static DescribeJobResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
}
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
[assembly: Elmah.Scc("$Id: ErrorXml.cs 651 2009-06-09 17:24:36Z azizatif $")]
namespace Elmah
{
#region Imports
using System;
using System.IO;
using System.Xml;
using NameValueCollection = System.Collections.Specialized.NameValueCollection;
#endregion
/// <summary>
/// Responsible for encoding and decoding the XML representation of
/// an <see cref="Error"/> object.
/// </summary>
[ Serializable ]
public static class ErrorXml
{
/// <summary>
/// Decodes an <see cref="Error"/> object from its default XML
/// representation.
/// </summary>
public static Error DecodeString(string xml)
{
using (var sr = new StringReader(xml))
using (var reader = XmlReader.Create(sr))
{
if (!reader.IsStartElement("error"))
throw new ApplicationException("The error XML is not in the expected format.");
return Decode(reader);
}
}
/// <summary>
/// Decodes an <see cref="Error"/> object from its XML representation.
/// </summary>
public static Error Decode(XmlReader reader)
{
if (reader == null) throw new ArgumentNullException("reader");
if (!reader.IsStartElement()) throw new ArgumentException("Reader is not positioned at the start of an element.", "reader");
//
// Read out the attributes that contain the simple
// typed state.
//
var error = new Error();
ReadXmlAttributes(reader, error);
//
// Move past the element. If it's not empty, then
// read also the inner XML that contains complex
// types like collections.
//
var isEmpty = reader.IsEmptyElement;
reader.Read();
if (!isEmpty)
{
ReadInnerXml(reader, error);
reader.ReadEndElement();
}
return error;
}
/// <summary>
/// Reads the error data in XML attributes.
/// </summary>
private static void ReadXmlAttributes(XmlReader reader, Error error)
{
if (reader == null) throw new ArgumentNullException("reader");
if (!reader.IsStartElement()) throw new ArgumentException("Reader is not positioned at the start of an element.", "reader");
error.ApplicationName = reader.GetAttribute("application");
error.HostName = reader.GetAttribute("host");
error.Type = reader.GetAttribute("type");
error.Message = reader.GetAttribute("message");
error.Source = reader.GetAttribute("source");
error.Detail = reader.GetAttribute("detail");
error.User = reader.GetAttribute("user");
var timeString = reader.GetAttribute("time") ?? string.Empty;
error.Time = timeString.Length == 0 ? new DateTime() : XmlConvert.ToDateTime(timeString);
var statusCodeString = reader.GetAttribute("statusCode") ?? string.Empty;
error.StatusCode = statusCodeString.Length == 0 ? 0 : XmlConvert.ToInt32(statusCodeString);
error.WebHostHtmlMessage = reader.GetAttribute("webHostHtmlMessage");
}
/// <summary>
/// Reads the error data in child nodes.
/// </summary>
private static void ReadInnerXml(XmlReader reader, Error error)
{
if (reader == null) throw new ArgumentNullException("reader");
//
// Loop through the elements, reading those that we
// recognize. If an unknown element is found then
// this method bails out immediately without
// consuming it, assuming that it belongs to a subclass.
//
while (reader.IsStartElement())
{
//
// Optimization Note: This block could be re-wired slightly
// to be more efficient by not causing a collection to be
// created if the element is going to be empty.
//
NameValueCollection collection;
switch (reader.LocalName)
{
case "serverVariables" : collection = error.ServerVariables; break;
case "queryString" : collection = error.QueryString; break;
case "form" : collection = error.Form; break;
case "cookies" : collection = error.Cookies; break;
default : return;
}
if (reader.IsEmptyElement)
reader.Read();
else
UpcodeTo(reader, collection);
}
}
/// <summary>
/// Encodes the default XML representation of an <see cref="Error"/>
/// object to a string.
/// </summary>
public static string EncodeString(Error error)
{
var sw = new StringWriter();
using (var writer = XmlWriter.Create(sw, new XmlWriterSettings
{
Indent = true,
NewLineOnAttributes = true,
CheckCharacters = false,
OmitXmlDeclaration = true, // see issue #120: http://code.google.com/p/elmah/issues/detail?id=120
}))
{
writer.WriteStartElement("error");
Encode(error, writer);
writer.WriteEndElement();
writer.Flush();
}
return sw.ToString();
}
/// <summary>
/// Encodes the XML representation of an <see cref="Error"/> object.
/// </summary>
public static void Encode(Error error, XmlWriter writer)
{
if (writer == null) throw new ArgumentNullException("writer");
if (writer.WriteState != WriteState.Element) throw new ArgumentException("Writer is not in the expected Element state.", "writer");
//
// Write out the basic typed information in attributes
// followed by collections as inner elements.
//
WriteXmlAttributes(error, writer);
WriteInnerXml(error, writer);
}
/// <summary>
/// Writes the error data that belongs in XML attributes.
/// </summary>
private static void WriteXmlAttributes(Error error, XmlWriter writer)
{
Debug.Assert(error != null);
if (writer == null) throw new ArgumentNullException("writer");
WriteXmlAttribute(writer, "application", error.ApplicationName);
WriteXmlAttribute(writer, "host", error.HostName);
WriteXmlAttribute(writer, "type", error.Type);
WriteXmlAttribute(writer, "message", error.Message);
WriteXmlAttribute(writer, "source", error.Source);
WriteXmlAttribute(writer, "detail", error.Detail);
WriteXmlAttribute(writer, "user", error.User);
if (error.Time != DateTime.MinValue)
WriteXmlAttribute(writer, "time", XmlConvert.ToString(error.Time.ToUniversalTime(), @"yyyy-MM-dd\THH:mm:ss.fffffff\Z"));
if (error.StatusCode != 0)
WriteXmlAttribute(writer, "statusCode", XmlConvert.ToString(error.StatusCode));
WriteXmlAttribute(writer, "webHostHtmlMessage", error.WebHostHtmlMessage);
}
/// <summary>
/// Writes the error data that belongs in child nodes.
/// </summary>
private static void WriteInnerXml(Error error, XmlWriter writer)
{
Debug.Assert(error != null);
if (writer == null) throw new ArgumentNullException("writer");
WriteCollection(writer, "serverVariables", error.ServerVariables);
WriteCollection(writer, "queryString", error.QueryString);
WriteCollection(writer, "form", error.Form);
WriteCollection(writer, "cookies", error.Cookies);
}
private static void WriteCollection(XmlWriter writer, string name, NameValueCollection collection)
{
Debug.Assert(writer != null);
Debug.AssertStringNotEmpty(name);
if (collection == null || collection.Count == 0)
return;
writer.WriteStartElement(name);
Encode(collection, writer);
writer.WriteEndElement();
}
private static void WriteXmlAttribute(XmlWriter writer, string name, string value)
{
Debug.Assert(writer != null);
Debug.AssertStringNotEmpty(name);
if (!string.IsNullOrEmpty(value))
writer.WriteAttributeString(name, value);
}
/// <summary>
/// Encodes an XML representation for a
/// <see cref="NameValueCollection" /> object.
/// </summary>
private static void Encode(NameValueCollection collection, XmlWriter writer)
{
if (collection == null) throw new ArgumentNullException("collection");
if (writer == null) throw new ArgumentNullException("writer");
if (collection.Count == 0)
return;
//
// Write out a named multi-value collection as follows
// (example here is the ServerVariables collection):
//
// <item name="HTTP_URL">
// <value string="/myapp/somewhere/page.aspx" />
// </item>
// <item name="QUERY_STRING">
// <value string="a=1&b=2" />
// </item>
// ...
//
foreach (string key in collection.Keys)
{
writer.WriteStartElement("item");
writer.WriteAttributeString("name", key);
var values = collection.GetValues(key);
if (values != null)
{
foreach (var value in values)
{
writer.WriteStartElement("value");
writer.WriteAttributeString("string", value);
writer.WriteEndElement();
}
}
writer.WriteEndElement();
}
}
/// <summary>
/// Updates an existing <see cref="NameValueCollection" /> object from
/// its XML representation.
/// </summary>
private static void UpcodeTo(XmlReader reader, NameValueCollection collection)
{
if (reader == null) throw new ArgumentNullException("reader");
if (collection == null) throw new ArgumentNullException("collection");
reader.Read();
//
// Add entries into the collection as <item> elements
// with child <value> elements are found.
//
while (reader.IsStartElement("item"))
{
var name = reader.GetAttribute("name");
var isNull = reader.IsEmptyElement;
reader.Read(); // <item>
if (!isNull)
{
while (reader.IsStartElement("value")) // <value ...>
{
var value = reader.GetAttribute("string");
collection.Add(name, value);
reader.Read();
}
reader.ReadEndElement(); // </item>
}
else
{
collection.Add(name, null);
}
}
reader.ReadEndElement();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Nop.Core;
using Nop.Core.Caching;
using Nop.Core.Data;
using Nop.Core.Domain.Directory;
using Nop.Core.Plugins;
using Nop.Services.Events;
using Nop.Services.Stores;
namespace Nop.Services.Directory
{
/// <summary>
/// Currency service
/// </summary>
public partial class CurrencyService : ICurrencyService
{
#region Constants
/// <summary>
/// Key for caching
/// </summary>
/// <remarks>
/// {0} : currency ID
/// </remarks>
private const string CURRENCIES_BY_ID_KEY = "Nop.currency.id-{0}";
/// <summary>
/// Key for caching
/// </summary>
/// <remarks>
/// {0} : show hidden records?
/// </remarks>
private const string CURRENCIES_ALL_KEY = "Nop.currency.all-{0}";
/// <summary>
/// Key pattern to clear cache
/// </summary>
private const string CURRENCIES_PATTERN_KEY = "Nop.currency.";
#endregion
#region Fields
private readonly IRepository<Currency> _currencyRepository;
private readonly IStoreMappingService _storeMappingService;
private readonly ICacheManager _cacheManager;
private readonly CurrencySettings _currencySettings;
private readonly IPluginFinder _pluginFinder;
private readonly IEventPublisher _eventPublisher;
#endregion
#region Ctor
/// <summary>
/// Ctor
/// </summary>
/// <param name="cacheManager">Cache manager</param>
/// <param name="currencyRepository">Currency repository</param>
/// <param name="storeMappingService">Store mapping service</param>
/// <param name="currencySettings">Currency settings</param>
/// <param name="pluginFinder">Plugin finder</param>
/// <param name="eventPublisher">Event published</param>
public CurrencyService(ICacheManager cacheManager,
IRepository<Currency> currencyRepository,
IStoreMappingService storeMappingService,
CurrencySettings currencySettings,
IPluginFinder pluginFinder,
IEventPublisher eventPublisher)
{
this._cacheManager = cacheManager;
this._currencyRepository = currencyRepository;
this._storeMappingService = storeMappingService;
this._currencySettings = currencySettings;
this._pluginFinder = pluginFinder;
this._eventPublisher = eventPublisher;
}
#endregion
#region Methods
/// <summary>
/// Gets currency live rates
/// </summary>
/// <param name="exchangeRateCurrencyCode">Exchange rate currency code</param>
/// <returns>Exchange rates</returns>
public virtual IList<ExchangeRate> GetCurrencyLiveRates(string exchangeRateCurrencyCode)
{
var exchangeRateProvider = LoadActiveExchangeRateProvider();
if (exchangeRateProvider == null)
throw new Exception("Active exchange rate provider cannot be loaded");
return exchangeRateProvider.GetCurrencyLiveRates(exchangeRateCurrencyCode);
}
/// <summary>
/// Deletes currency
/// </summary>
/// <param name="currency">Currency</param>
public virtual void DeleteCurrency(Currency currency)
{
if (currency == null)
throw new ArgumentNullException("currency");
_currencyRepository.Delete(currency);
_cacheManager.RemoveByPattern(CURRENCIES_PATTERN_KEY);
//event notification
_eventPublisher.EntityDeleted(currency);
}
/// <summary>
/// Gets a currency
/// </summary>
/// <param name="currencyId">Currency identifier</param>
/// <returns>Currency</returns>
public virtual Currency GetCurrencyById(int currencyId)
{
if (currencyId == 0)
return null;
string key = string.Format(CURRENCIES_BY_ID_KEY, currencyId);
return _cacheManager.Get(key, () => _currencyRepository.GetById(currencyId));
}
/// <summary>
/// Gets a currency by code
/// </summary>
/// <param name="currencyCode">Currency code</param>
/// <returns>Currency</returns>
public virtual Currency GetCurrencyByCode(string currencyCode)
{
if (String.IsNullOrEmpty(currencyCode))
return null;
return GetAllCurrencies(true).FirstOrDefault(c => c.CurrencyCode.ToLower() == currencyCode.ToLower());
}
/// <summary>
/// Gets all currencies
/// </summary>
/// <param name="showHidden">A value indicating whether to show hidden records</param>
/// <param name="storeId">Load records allowed only in a specified store; pass 0 to load all records</param>
/// <returns>Currencies</returns>
public virtual IList<Currency> GetAllCurrencies(bool showHidden = false, int storeId = 0)
{
string key = string.Format(CURRENCIES_ALL_KEY, showHidden);
var currencies = _cacheManager.Get(key, () =>
{
var query = _currencyRepository.Table;
if (!showHidden)
query = query.Where(c => c.Published);
query = query.OrderBy(c => c.DisplayOrder);
return query.ToList();
});
//store mapping
if (storeId > 0)
{
currencies = currencies
.Where(c => _storeMappingService.Authorize(c, storeId))
.ToList();
}
return currencies;
}
/// <summary>
/// Inserts a currency
/// </summary>
/// <param name="currency">Currency</param>
public virtual void InsertCurrency(Currency currency)
{
if (currency == null)
throw new ArgumentNullException("currency");
_currencyRepository.Insert(currency);
_cacheManager.RemoveByPattern(CURRENCIES_PATTERN_KEY);
//event notification
_eventPublisher.EntityInserted(currency);
}
/// <summary>
/// Updates the currency
/// </summary>
/// <param name="currency">Currency</param>
public virtual void UpdateCurrency(Currency currency)
{
if (currency == null)
throw new ArgumentNullException("currency");
_currencyRepository.Update(currency);
_cacheManager.RemoveByPattern(CURRENCIES_PATTERN_KEY);
//event notification
_eventPublisher.EntityUpdated(currency);
}
/// <summary>
/// Converts currency
/// </summary>
/// <param name="amount">Amount</param>
/// <param name="exchangeRate">Currency exchange rate</param>
/// <returns>Converted value</returns>
public virtual decimal ConvertCurrency(decimal amount, decimal exchangeRate)
{
if (amount != decimal.Zero && exchangeRate != decimal.Zero)
return amount * exchangeRate;
return decimal.Zero;
}
/// <summary>
/// Converts currency
/// </summary>
/// <param name="amount">Amount</param>
/// <param name="sourceCurrencyCode">Source currency code</param>
/// <param name="targetCurrencyCode">Target currency code</param>
/// <returns>Converted value</returns>
public virtual decimal ConvertCurrency(decimal amount, Currency sourceCurrencyCode, Currency targetCurrencyCode)
{
if (targetCurrencyCode == null)
throw new ArgumentNullException("sourceCurrencyCode");
if (targetCurrencyCode == null)
throw new ArgumentNullException("targetCurrencyCode");
decimal result = amount;
if (sourceCurrencyCode.Id == targetCurrencyCode.Id)
return result;
if (result != decimal.Zero && sourceCurrencyCode.Id != targetCurrencyCode.Id)
{
result = ConvertToPrimaryExchangeRateCurrency(result, sourceCurrencyCode);
result = ConvertFromPrimaryExchangeRateCurrency(result, targetCurrencyCode);
}
return result;
}
/// <summary>
/// Converts to primary exchange rate currency
/// </summary>
/// <param name="amount">Amount</param>
/// <param name="sourceCurrencyCode">Source currency code</param>
/// <returns>Converted value</returns>
public virtual decimal ConvertToPrimaryExchangeRateCurrency(decimal amount, Currency sourceCurrencyCode)
{
if (sourceCurrencyCode == null)
throw new ArgumentNullException("sourceCurrencyCode");
var primaryExchangeRateCurrency = GetCurrencyById(_currencySettings.PrimaryExchangeRateCurrencyId);
if (primaryExchangeRateCurrency == null)
throw new Exception("Primary exchange rate currency cannot be loaded");
decimal result = amount;
if (result != decimal.Zero && sourceCurrencyCode.Id != primaryExchangeRateCurrency.Id)
{
decimal exchangeRate = sourceCurrencyCode.Rate;
if (exchangeRate == decimal.Zero)
throw new NopException(string.Format("Exchange rate not found for currency [{0}]", sourceCurrencyCode.Name));
result = result / exchangeRate;
}
return result;
}
/// <summary>
/// Converts from primary exchange rate currency
/// </summary>
/// <param name="amount">Amount</param>
/// <param name="targetCurrencyCode">Target currency code</param>
/// <returns>Converted value</returns>
public virtual decimal ConvertFromPrimaryExchangeRateCurrency(decimal amount, Currency targetCurrencyCode)
{
if (targetCurrencyCode == null)
throw new ArgumentNullException("targetCurrencyCode");
var primaryExchangeRateCurrency = GetCurrencyById(_currencySettings.PrimaryExchangeRateCurrencyId);
if (primaryExchangeRateCurrency == null)
throw new Exception("Primary exchange rate currency cannot be loaded");
decimal result = amount;
if (result != decimal.Zero && targetCurrencyCode.Id != primaryExchangeRateCurrency.Id)
{
decimal exchangeRate = targetCurrencyCode.Rate;
if (exchangeRate == decimal.Zero)
throw new NopException(string.Format("Exchange rate not found for currency [{0}]", targetCurrencyCode.Name));
result = result * exchangeRate;
}
return result;
}
/// <summary>
/// Converts to primary store currency
/// </summary>
/// <param name="amount">Amount</param>
/// <param name="sourceCurrencyCode">Source currency code</param>
/// <returns>Converted value</returns>
public virtual decimal ConvertToPrimaryStoreCurrency(decimal amount, Currency sourceCurrencyCode)
{
if (sourceCurrencyCode == null)
throw new ArgumentNullException("sourceCurrencyCode");
var primaryStoreCurrency = GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId);
if (primaryStoreCurrency == null)
throw new Exception("Primary store currency cannot be loaded");
decimal result = amount;
if (result != decimal.Zero && sourceCurrencyCode.Id != primaryStoreCurrency.Id)
{
decimal exchangeRate = sourceCurrencyCode.Rate;
if (exchangeRate == decimal.Zero)
throw new NopException(string.Format("Exchange rate not found for currency [{0}]", sourceCurrencyCode.Name));
result = result / exchangeRate;
}
return result;
}
/// <summary>
/// Converts from primary store currency
/// </summary>
/// <param name="amount">Amount</param>
/// <param name="targetCurrencyCode">Target currency code</param>
/// <returns>Converted value</returns>
public virtual decimal ConvertFromPrimaryStoreCurrency(decimal amount, Currency targetCurrencyCode)
{
var primaryStoreCurrency = GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId);
var result = ConvertCurrency(amount, primaryStoreCurrency, targetCurrencyCode);
return result;
}
/// <summary>
/// Load active exchange rate provider
/// </summary>
/// <returns>Active exchange rate provider</returns>
public virtual IExchangeRateProvider LoadActiveExchangeRateProvider()
{
var exchangeRateProvider = LoadExchangeRateProviderBySystemName(_currencySettings.ActiveExchangeRateProviderSystemName);
if (exchangeRateProvider == null)
exchangeRateProvider = LoadAllExchangeRateProviders().FirstOrDefault();
return exchangeRateProvider;
}
/// <summary>
/// Load exchange rate provider by system name
/// </summary>
/// <param name="systemName">System name</param>
/// <returns>Found exchange rate provider</returns>
public virtual IExchangeRateProvider LoadExchangeRateProviderBySystemName(string systemName)
{
var descriptor = _pluginFinder.GetPluginDescriptorBySystemName<IExchangeRateProvider>(systemName);
if (descriptor != null)
return descriptor.Instance<IExchangeRateProvider>();
return null;
}
/// <summary>
/// Load all exchange rate providers
/// </summary>
/// <returns>Exchange rate providers</returns>
public virtual IList<IExchangeRateProvider> LoadAllExchangeRateProviders()
{
var exchangeRateProviders = _pluginFinder.GetPlugins<IExchangeRateProvider>();
return exchangeRateProviders
.OrderBy(tp => tp.PluginDescriptor)
.ToList();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using AngleSharp.Common;
using AutoFixture.NUnit3;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Moq;
using NUnit.Framework;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Cache;
using Umbraco.Cms.Core.Configuration.Models;
using Umbraco.Cms.Core.ContentApps;
using Umbraco.Cms.Core.Dictionary;
using Umbraco.Cms.Core.Events;
using Umbraco.Cms.Core.Hosting;
using Umbraco.Cms.Core.IO;
using Umbraco.Cms.Core.Mapping;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Models.ContentEditing;
using Umbraco.Cms.Core.Models.Mapping;
using Umbraco.Cms.Core.Models.Membership;
using Umbraco.Cms.Core.PropertyEditors;
using Umbraco.Cms.Core.Scoping;
using Umbraco.Cms.Core.Security;
using Umbraco.Cms.Core.Serialization;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.Strings;
using Umbraco.Cms.Infrastructure.Serialization;
using Umbraco.Cms.Tests.Common.Builders;
using Umbraco.Cms.Tests.UnitTests.AutoFixture;
using Umbraco.Cms.Tests.UnitTests.Umbraco.Core.ShortStringHelper;
using Umbraco.Cms.Web.BackOffice.Controllers;
using Umbraco.Cms.Web.BackOffice.Mapping;
using Umbraco.Cms.Web.Common.ActionsResults;
using Umbraco.Cms.Web.Common.Security;
using MemberMapDefinition = Umbraco.Cms.Web.BackOffice.Mapping.MemberMapDefinition;
namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Web.BackOffice.Controllers
{
[TestFixture]
public class MemberControllerUnitTests
{
private IUmbracoMapper _mapper;
[Test]
[AutoMoqData]
public void PostSaveMember_WhenMemberIsNull_ExpectFailureResponse(
MemberController sut)
{
// arrange
// act
ArgumentNullException exception = Assert.ThrowsAsync<ArgumentNullException>(() => sut.PostSave(null));
// assert
Assert.That(exception.Message, Is.EqualTo("Value cannot be null. (Parameter 'The member content item was null')"));
}
[Test]
[AutoMoqData]
public void PostSaveMember_WhenModelStateIsNotValid_ExpectFailureResponse(
[Frozen] IMemberManager umbracoMembersUserManager,
IMemberService memberService,
IMemberTypeService memberTypeService,
IMemberGroupService memberGroupService,
IDataTypeService dataTypeService,
IBackOfficeSecurityAccessor backOfficeSecurityAccessor,
IPasswordChanger<MemberIdentityUser> passwordChanger,
IOptions<GlobalSettings> globalSettings,
IUser user)
{
// arrange
Member member = SetupMemberTestData(out MemberSave fakeMemberData, out MemberDisplay memberDisplay, ContentSaveAction.SaveNew);
MemberController sut = CreateSut(memberService, memberTypeService, memberGroupService, umbracoMembersUserManager, dataTypeService, backOfficeSecurityAccessor, passwordChanger, globalSettings, user);
sut.ModelState.AddModelError("key", "Invalid model state");
Mock.Get(umbracoMembersUserManager)
.Setup(x => x.CreateAsync(It.IsAny<MemberIdentityUser>(), It.IsAny<string>()))
.ReturnsAsync(() => IdentityResult.Success);
Mock.Get(umbracoMembersUserManager)
.Setup(x => x.ValidatePasswordAsync(It.IsAny<string>()))
.ReturnsAsync(() => IdentityResult.Success);
var value = new MemberDisplay();
// act
ActionResult<MemberDisplay> result = sut.PostSave(fakeMemberData).Result;
var validation = result.Result as ValidationErrorResult;
// assert
Assert.IsNotNull(result.Result);
Assert.IsNull(result.Value);
Assert.AreEqual(StatusCodes.Status400BadRequest, validation?.StatusCode);
}
[Test]
[AutoMoqData]
public async Task PostSaveMember_SaveNew_NoCustomField_WhenAllIsSetupCorrectly_ExpectSuccessResponse(
[Frozen] IMemberManager umbracoMembersUserManager,
IMemberService memberService,
IMemberTypeService memberTypeService,
IMemberGroupService memberGroupService,
IDataTypeService dataTypeService,
IBackOfficeSecurityAccessor backOfficeSecurityAccessor,
IBackOfficeSecurity backOfficeSecurity,
IPasswordChanger<MemberIdentityUser> passwordChanger,
IOptions<GlobalSettings> globalSettings,
IUser user)
{
// arrange
Member member = SetupMemberTestData(out MemberSave fakeMemberData, out MemberDisplay memberDisplay, ContentSaveAction.SaveNew);
Mock.Get(umbracoMembersUserManager)
.Setup(x => x.CreateAsync(It.IsAny<MemberIdentityUser>(), It.IsAny<string>()))
.ReturnsAsync(() => IdentityResult.Success);
Mock.Get(umbracoMembersUserManager)
.Setup(x => x.ValidatePasswordAsync(It.IsAny<string>()))
.ReturnsAsync(() => IdentityResult.Success);
Mock.Get(umbracoMembersUserManager)
.Setup(x => x.GetRolesAsync(It.IsAny<MemberIdentityUser>()))
.ReturnsAsync(() => Array.Empty<string>());
Mock.Get(memberTypeService).Setup(x => x.GetDefault()).Returns("fakeAlias");
Mock.Get(backOfficeSecurityAccessor).Setup(x => x.BackOfficeSecurity).Returns(backOfficeSecurity);
Mock.Get(memberService).SetupSequence(
x => x.GetByEmail(It.IsAny<string>()))
.Returns(() => null)
.Returns(() => member);
Mock.Get(memberService).Setup(x => x.GetByUsername(It.IsAny<string>())).Returns(() => member);
MemberController sut = CreateSut(memberService, memberTypeService, memberGroupService, umbracoMembersUserManager, dataTypeService, backOfficeSecurityAccessor, passwordChanger, globalSettings, user);
// act
ActionResult<MemberDisplay> result = await sut.PostSave(fakeMemberData);
// assert
Assert.IsNull(result.Result);
Assert.IsNotNull(result.Value);
AssertMemberDisplayPropertiesAreEqual(memberDisplay, result.Value);
}
[Test]
[AutoMoqData]
public async Task PostSaveMember_SaveNew_CustomField_WhenAllIsSetupCorrectly_ExpectSuccessResponse(
[Frozen] IMemberManager umbracoMembersUserManager,
IMemberService memberService,
IMemberTypeService memberTypeService,
IMemberGroupService memberGroupService,
IDataTypeService dataTypeService,
IBackOfficeSecurityAccessor backOfficeSecurityAccessor,
IBackOfficeSecurity backOfficeSecurity,
IPasswordChanger<MemberIdentityUser> passwordChanger,
IOptions<GlobalSettings> globalSettings,
IUser user)
{
// arrange
Member member = SetupMemberTestData(out MemberSave fakeMemberData, out MemberDisplay memberDisplay, ContentSaveAction.SaveNew);
Mock.Get(umbracoMembersUserManager)
.Setup(x => x.CreateAsync(It.IsAny<MemberIdentityUser>(), It.IsAny<string>()))
.ReturnsAsync(() => IdentityResult.Success);
Mock.Get(umbracoMembersUserManager)
.Setup(x => x.ValidatePasswordAsync(It.IsAny<string>()))
.ReturnsAsync(() => IdentityResult.Success);
Mock.Get(umbracoMembersUserManager)
.Setup(x => x.GetRolesAsync(It.IsAny<MemberIdentityUser>()))
.ReturnsAsync(() => Array.Empty<string>());
Mock.Get(memberTypeService).Setup(x => x.GetDefault()).Returns("fakeAlias");
Mock.Get(backOfficeSecurityAccessor).Setup(x => x.BackOfficeSecurity).Returns(backOfficeSecurity);
Mock.Get(memberService).SetupSequence(
x => x.GetByEmail(It.IsAny<string>()))
.Returns(() => null)
.Returns(() => member);
Mock.Get(memberService).Setup(x => x.GetByUsername(It.IsAny<string>())).Returns(() => member);
MemberController sut = CreateSut(memberService, memberTypeService, memberGroupService, umbracoMembersUserManager, dataTypeService, backOfficeSecurityAccessor, passwordChanger, globalSettings, user);
// act
ActionResult<MemberDisplay> result = await sut.PostSave(fakeMemberData);
// assert
Assert.IsNull(result.Result);
Assert.IsNotNull(result.Value);
AssertMemberDisplayPropertiesAreEqual(memberDisplay, result.Value);
}
[Test]
[AutoMoqData]
public async Task PostSaveMember_SaveExisting_WhenAllIsSetupCorrectly_ExpectSuccessResponse(
[Frozen] IMemberManager umbracoMembersUserManager,
IMemberService memberService,
IMemberTypeService memberTypeService,
IMemberGroupService memberGroupService,
IDataTypeService dataTypeService,
IBackOfficeSecurityAccessor backOfficeSecurityAccessor,
IBackOfficeSecurity backOfficeSecurity,
IPasswordChanger<MemberIdentityUser> passwordChanger,
IOptions<GlobalSettings> globalSettings,
IUser user)
{
// arrange
Member member = SetupMemberTestData(out MemberSave fakeMemberData, out MemberDisplay memberDisplay, ContentSaveAction.Save);
var membersIdentityUser = new MemberIdentityUser(123);
Mock.Get(umbracoMembersUserManager)
.Setup(x => x.FindByIdAsync(It.IsAny<string>()))
.ReturnsAsync(() => membersIdentityUser);
Mock.Get(umbracoMembersUserManager)
.Setup(x => x.ValidatePasswordAsync(It.IsAny<string>()))
.ReturnsAsync(() => IdentityResult.Success);
Mock.Get(umbracoMembersUserManager)
.Setup(x => x.UpdateAsync(It.IsAny<MemberIdentityUser>()))
.ReturnsAsync(() => IdentityResult.Success);
Mock.Get(umbracoMembersUserManager)
.Setup(x => x.GetRolesAsync(It.IsAny<MemberIdentityUser>()))
.ReturnsAsync(() => Array.Empty<string>());
Mock.Get(memberTypeService).Setup(x => x.GetDefault()).Returns("fakeAlias");
Mock.Get(globalSettings);
SetupUserAccess(backOfficeSecurityAccessor, backOfficeSecurity, user);
SetupPasswordSuccess(umbracoMembersUserManager, passwordChanger);
Mock.Get(memberService).Setup(x => x.GetByUsername(It.IsAny<string>())).Returns(() => member);
Mock.Get(memberService).Setup(x => x.GetById(It.IsAny<int>())).Returns(() => member);
Mock.Get(memberService).SetupSequence(
x => x.GetByEmail(It.IsAny<string>()))
.Returns(() => null)
.Returns(() => member);
MemberController sut = CreateSut(memberService, memberTypeService, memberGroupService, umbracoMembersUserManager, dataTypeService, backOfficeSecurityAccessor, passwordChanger, globalSettings, user);
// act
ActionResult<MemberDisplay> result = await sut.PostSave(fakeMemberData);
// assert
Assert.IsNull(result.Result);
Assert.IsNotNull(result.Value);
AssertMemberDisplayPropertiesAreEqual(memberDisplay, result.Value);
}
[Test]
[AutoMoqData]
public async Task PostSaveMember_SaveExisting_WhenAllIsSetupWithPasswordIncorrectly_ExpectFailureResponse(
[Frozen] IMemberManager umbracoMembersUserManager,
IMemberService memberService,
IMemberTypeService memberTypeService,
IMemberGroupService memberGroupService,
IDataTypeService dataTypeService,
IBackOfficeSecurityAccessor backOfficeSecurityAccessor,
IBackOfficeSecurity backOfficeSecurity,
IPasswordChanger<MemberIdentityUser> passwordChanger,
IOptions<GlobalSettings> globalSettings,
IUser user)
{
// arrange
Member member = SetupMemberTestData(out MemberSave fakeMemberData, out MemberDisplay memberDisplay, ContentSaveAction.Save);
var membersIdentityUser = new MemberIdentityUser(123);
Mock.Get(umbracoMembersUserManager)
.Setup(x => x.FindByIdAsync(It.IsAny<string>()))
.ReturnsAsync(() => membersIdentityUser);
Mock.Get(umbracoMembersUserManager)
.Setup(x => x.ValidatePasswordAsync(It.IsAny<string>()))
.ReturnsAsync(() => IdentityResult.Success);
Mock.Get(umbracoMembersUserManager)
.Setup(x => x.UpdateAsync(It.IsAny<MemberIdentityUser>()))
.ReturnsAsync(() => IdentityResult.Success);
Mock.Get(memberTypeService).Setup(x => x.GetDefault()).Returns("fakeAlias");
Mock.Get(globalSettings);
SetupUserAccess(backOfficeSecurityAccessor, backOfficeSecurity, user);
SetupPasswordSuccess(umbracoMembersUserManager, passwordChanger, false);
Mock.Get(memberService).Setup(x => x.GetByUsername(It.IsAny<string>())).Returns(() => member);
Mock.Get(memberService).SetupSequence(
x => x.GetByEmail(It.IsAny<string>()))
.Returns(() => null)
.Returns(() => member);
MemberController sut = CreateSut(memberService, memberTypeService, memberGroupService, umbracoMembersUserManager, dataTypeService, backOfficeSecurityAccessor, passwordChanger, globalSettings, user);
// act
ActionResult<MemberDisplay> result = await sut.PostSave(fakeMemberData);
// assert
Assert.IsNotNull(result.Result);
Assert.IsNull(result.Value);
}
private static void SetupUserAccess(IBackOfficeSecurityAccessor backOfficeSecurityAccessor, IBackOfficeSecurity backOfficeSecurity, IUser user)
{
Mock.Get(backOfficeSecurityAccessor).Setup(x => x.BackOfficeSecurity).Returns(backOfficeSecurity);
Mock.Get(user).Setup(x => x.AllowedSections).Returns(new[] { "member" });
Mock.Get(backOfficeSecurity).Setup(x => x.CurrentUser).Returns(user);
}
private static void SetupPasswordSuccess(IMemberManager umbracoMembersUserManager, IPasswordChanger<MemberIdentityUser> passwordChanger, bool successful = true)
{
var passwordChanged = new PasswordChangedModel()
{
ChangeError = null,
ResetPassword = null
};
if (!successful)
{
var attempt = Attempt.Fail<PasswordChangedModel>(passwordChanged);
Mock.Get(passwordChanger)
.Setup(x => x.ChangePasswordWithIdentityAsync(It.IsAny<ChangingPasswordModel>(), umbracoMembersUserManager))
.ReturnsAsync(() => attempt);
}
else
{
var attempt = Attempt.Succeed<PasswordChangedModel>(passwordChanged);
Mock.Get(passwordChanger)
.Setup(x => x.ChangePasswordWithIdentityAsync(It.IsAny<ChangingPasswordModel>(), umbracoMembersUserManager))
.ReturnsAsync(() => attempt);
}
}
[Test]
[AutoMoqData]
public void PostSaveMember_SaveNew_WhenMemberEmailAlreadyExists_ExpectFailResponse(
[Frozen] IMemberManager umbracoMembersUserManager,
IMemberService memberService,
IMemberTypeService memberTypeService,
IMemberGroupService memberGroupService,
IDataTypeService dataTypeService,
IBackOfficeSecurityAccessor backOfficeSecurityAccessor,
IBackOfficeSecurity backOfficeSecurity,
IPasswordChanger<MemberIdentityUser> passwordChanger,
IOptions<GlobalSettings> globalSettings,
IUser user)
{
// arrange
Member member = SetupMemberTestData(out MemberSave fakeMemberData, out MemberDisplay memberDisplay, ContentSaveAction.SaveNew);
Mock.Get(umbracoMembersUserManager)
.Setup(x => x.CreateAsync(It.IsAny<MemberIdentityUser>()))
.ReturnsAsync(() => IdentityResult.Success);
Mock.Get(memberTypeService).Setup(x => x.GetDefault()).Returns("fakeAlias");
Mock.Get(backOfficeSecurityAccessor).Setup(x => x.BackOfficeSecurity).Returns(backOfficeSecurity);
Mock.Get(umbracoMembersUserManager)
.Setup(x => x.ValidatePasswordAsync(It.IsAny<string>()))
.ReturnsAsync(() => IdentityResult.Success);
Mock.Get(umbracoMembersUserManager)
.Setup(x => x.AddToRolesAsync(It.IsAny<MemberIdentityUser>(), It.IsAny<IEnumerable<string>>()))
.ReturnsAsync(() => IdentityResult.Success);
Mock.Get(memberService).SetupSequence(
x => x.GetByEmail(It.IsAny<string>()))
.Returns(() => member);
MemberController sut = CreateSut(memberService, memberTypeService, memberGroupService, umbracoMembersUserManager, dataTypeService, backOfficeSecurityAccessor, passwordChanger, globalSettings, user);
// act
ActionResult<MemberDisplay> result = sut.PostSave(fakeMemberData).Result;
var validation = result.Result as ValidationErrorResult;
// assert
Assert.IsNotNull(result.Result);
Assert.IsNull(result.Value);
Assert.AreEqual(StatusCodes.Status400BadRequest, validation?.StatusCode);
}
[Test]
[AutoMoqData]
public async Task PostSaveMember_SaveExistingMember_WithNoRoles_Add1Role_ExpectSuccessResponse(
[Frozen] IMemberManager umbracoMembersUserManager,
IMemberService memberService,
IMemberTypeService memberTypeService,
IMemberGroupService memberGroupService,
IDataTypeService dataTypeService,
IBackOfficeSecurityAccessor backOfficeSecurityAccessor,
IBackOfficeSecurity backOfficeSecurity,
IPasswordChanger<MemberIdentityUser> passwordChanger,
IOptions<GlobalSettings> globalSettings,
IUser user)
{
// arrange
var roleName = "anyrole";
IMember member = SetupMemberTestData(out MemberSave fakeMemberData, out MemberDisplay memberDisplay, ContentSaveAction.Save);
fakeMemberData.Groups = new List<string>()
{
roleName
};
var membersIdentityUser = new MemberIdentityUser(123);
Mock.Get(umbracoMembersUserManager)
.Setup(x => x.FindByIdAsync(It.IsAny<string>()))
.ReturnsAsync(() => membersIdentityUser);
Mock.Get(umbracoMembersUserManager)
.Setup(x => x.ValidatePasswordAsync(It.IsAny<string>()))
.ReturnsAsync(() => IdentityResult.Success);
Mock.Get(umbracoMembersUserManager)
.Setup(x => x.UpdateAsync(It.IsAny<MemberIdentityUser>()))
.ReturnsAsync(() => IdentityResult.Success);
Mock.Get(umbracoMembersUserManager)
.Setup(x => x.AddToRolesAsync(It.IsAny<MemberIdentityUser>(), It.IsAny<IEnumerable<string>>()))
.ReturnsAsync(() => IdentityResult.Success);
Mock.Get(umbracoMembersUserManager)
.Setup(x => x.GetRolesAsync(It.IsAny<MemberIdentityUser>()))
.ReturnsAsync(() => Array.Empty<string>());
Mock.Get(memberTypeService).Setup(x => x.GetDefault()).Returns("fakeAlias");
Mock.Get(backOfficeSecurityAccessor).Setup(x => x.BackOfficeSecurity).Returns(backOfficeSecurity);
Mock.Get(memberService).Setup(x => x.GetByUsername(It.IsAny<string>())).Returns(() => member);
Mock.Get(memberService).Setup(x => x.GetById(It.IsAny<int>())).Returns(() => member);
SetupUserAccess(backOfficeSecurityAccessor, backOfficeSecurity, user);
SetupPasswordSuccess(umbracoMembersUserManager, passwordChanger);
Mock.Get(memberService).SetupSequence(
x => x.GetByEmail(It.IsAny<string>()))
.Returns(() => null)
.Returns(() => member);
MemberController sut = CreateSut(memberService, memberTypeService, memberGroupService, umbracoMembersUserManager, dataTypeService, backOfficeSecurityAccessor, passwordChanger, globalSettings, user);
// act
ActionResult<MemberDisplay> result = await sut.PostSave(fakeMemberData);
// assert
Assert.IsNull(result.Result);
Assert.IsNotNull(result.Value);
Mock.Get(umbracoMembersUserManager)
.Verify(u => u.GetRolesAsync(membersIdentityUser));
Mock.Get(umbracoMembersUserManager)
.Verify(u => u.AddToRolesAsync(membersIdentityUser, new[] { roleName }));
Mock.Get(umbracoMembersUserManager)
.Verify(x => x.GetRolesAsync(It.IsAny<MemberIdentityUser>()));
Mock.Get(memberService)
.Verify(m => m.Save(It.IsAny<Member>()));
AssertMemberDisplayPropertiesAreEqual(memberDisplay, result.Value);
}
/// <summary>
/// Create member controller to test
/// </summary>
/// <param name="memberService">Member service</param>
/// <param name="memberTypeService">Member type service</param>
/// <param name="memberGroupService">Member group service</param>
/// <param name="membersUserManager">Members user manager</param>
/// <param name="dataTypeService">Data type service</param>
/// <param name="backOfficeSecurityAccessor">Back office security accessor</param>
/// <param name="mockPasswordChanger">Password changer class</param>
/// <returns>A member controller for the tests</returns>
private MemberController CreateSut(
IMemberService memberService,
IMemberTypeService memberTypeService,
IMemberGroupService memberGroupService,
IUmbracoUserManager<MemberIdentityUser> membersUserManager,
IDataTypeService dataTypeService,
IBackOfficeSecurityAccessor backOfficeSecurityAccessor,
IPasswordChanger<MemberIdentityUser> passwordChanger,
IOptions<GlobalSettings> globalSettings,
IUser user)
{
var httpContextAccessor = new HttpContextAccessor();
var mockShortStringHelper = new MockShortStringHelper();
var textService = new Mock<ILocalizedTextService>();
var contentTypeBaseServiceProvider = new Mock<IContentTypeBaseServiceProvider>();
contentTypeBaseServiceProvider.Setup(x => x.GetContentTypeOf(It.IsAny<IContentBase>())).Returns(new ContentType(mockShortStringHelper, 123));
var contentAppFactories = new Mock<List<IContentAppFactory>>();
var mockContentAppFactoryCollection = new Mock<ILogger<ContentAppFactoryCollection>>();
var hybridBackOfficeSecurityAccessor = new BackOfficeSecurityAccessor(httpContextAccessor);
var contentAppFactoryCollection = new ContentAppFactoryCollection(
() => contentAppFactories.Object,
mockContentAppFactoryCollection.Object,
hybridBackOfficeSecurityAccessor);
var mockUserService = new Mock<IUserService>();
var commonMapper = new CommonMapper(
mockUserService.Object,
contentTypeBaseServiceProvider.Object,
contentAppFactoryCollection,
textService.Object);
var mockCultureDictionary = new Mock<ICultureDictionary>();
var mockPasswordConfig = new Mock<IOptions<MemberPasswordConfigurationSettings>>();
mockPasswordConfig.Setup(x => x.Value).Returns(() => new MemberPasswordConfigurationSettings());
IDataEditor dataEditor = Mock.Of<IDataEditor>(
x => x.Type == EditorType.PropertyValue
&& x.Alias == Constants.PropertyEditors.Aliases.Label);
Mock.Get(dataEditor).Setup(x => x.GetValueEditor()).Returns(new TextOnlyValueEditor( new DataEditorAttribute(Constants.PropertyEditors.Aliases.TextBox, "Test Textbox", "textbox"), textService.Object, Mock.Of<IShortStringHelper>(), Mock.Of<IJsonSerializer>(), Mock.Of<IIOHelper>()));
var propertyEditorCollection = new PropertyEditorCollection(new DataEditorCollection(() => new[] { dataEditor }));
IMapDefinition memberMapDefinition = new MemberMapDefinition(
commonMapper,
new CommonTreeNodeMapper(Mock.Of<LinkGenerator>()),
new MemberTabsAndPropertiesMapper(
mockCultureDictionary.Object,
backOfficeSecurityAccessor,
textService.Object,
memberTypeService,
memberService,
memberGroupService,
mockPasswordConfig.Object,
contentTypeBaseServiceProvider.Object,
propertyEditorCollection));
var map = new MapDefinitionCollection(() => new List<IMapDefinition>()
{
new global::Umbraco.Cms.Core.Models.Mapping.MemberMapDefinition(),
memberMapDefinition,
new ContentTypeMapDefinition(
commonMapper,
propertyEditorCollection,
dataTypeService,
new Mock<IFileService>().Object,
new Mock<IContentTypeService>().Object,
new Mock<IMediaTypeService>().Object,
memberTypeService,
new Mock<ILoggerFactory>().Object,
mockShortStringHelper,
globalSettings,
new Mock<IHostingEnvironment>().Object,
new Mock<IOptionsMonitor<ContentSettings>>().Object)
});
var scopeProvider = Mock.Of<IScopeProvider>(x => x.CreateScope(
It.IsAny<IsolationLevel>(),
It.IsAny<RepositoryCacheMode>(),
It.IsAny<IEventDispatcher>(),
It.IsAny<IScopedNotificationPublisher>(),
It.IsAny<bool?>(),
It.IsAny<bool>(),
It.IsAny<bool>()) == Mock.Of<IScope>());
_mapper = new UmbracoMapper(map, scopeProvider);
return new MemberController(
new DefaultCultureDictionary(
new Mock<ILocalizationService>().Object,
NoAppCache.Instance),
new LoggerFactory(),
mockShortStringHelper,
new DefaultEventMessagesFactory(
new Mock<IEventMessagesAccessor>().Object),
textService.Object,
propertyEditorCollection,
_mapper,
memberService,
memberTypeService,
(IMemberManager)membersUserManager,
dataTypeService,
backOfficeSecurityAccessor,
new ConfigurationEditorJsonSerializer(),
passwordChanger,
scopeProvider
);
}
/// <summary>
/// Setup all standard member data for test
/// </summary>
private Member SetupMemberTestData(
out MemberSave fakeMemberData,
out MemberDisplay memberDisplay,
ContentSaveAction contentAction)
{
// arrange
MemberType memberType = MemberTypeBuilder.CreateSimpleMemberType();
Member member = MemberBuilder.CreateSimpleMember(memberType, "Test Member", "test@example.com", "123", "test");
var memberId = 123;
member.Id = memberId;
// TODO: replace with builder for MemberSave and MemberDisplay
fakeMemberData = new MemberSave()
{
Id = memberId,
SortOrder = member.SortOrder,
ContentTypeId = memberType.Id,
Key = member.Key,
Password = new ChangingPasswordModel()
{
Id = 456,
NewPassword = member.RawPasswordValue,
OldPassword = null
},
Name = member.Name,
Email = member.Email,
Username = member.Username,
PersistedContent = member,
PropertyCollectionDto = new ContentPropertyCollectionDto()
{
},
Groups = new List<string>(),
//Alias = "fakeAlias",
ContentTypeAlias = member.ContentTypeAlias,
Action = contentAction,
Icon = "icon-document",
Path = member.Path
};
memberDisplay = new MemberDisplay()
{
Id = memberId,
SortOrder = member.SortOrder,
ContentTypeId = memberType.Id,
Key = member.Key,
Name = member.Name,
Email = member.Email,
Username = member.Username,
//Alias = "fakeAlias",
ContentTypeAlias = member.ContentTypeAlias,
ContentType = new ContentTypeBasic(),
ContentTypeName = member.ContentType.Name,
Icon = fakeMemberData.Icon,
Path = member.Path,
Tabs = new List<Tab<ContentPropertyDisplay>>()
{
new Tab<ContentPropertyDisplay>()
{
Alias = "test",
Id = 77,
Properties = new List<ContentPropertyDisplay>()
{
new ContentPropertyDisplay()
{
Alias = "_umb_id",
View = "idwithguid",
Value = new []
{
"123",
"guid"
}
},
new ContentPropertyDisplay()
{
Alias = "_umb_doctype"
},
new ContentPropertyDisplay()
{
Alias = "_umb_login"
},
new ContentPropertyDisplay()
{
Alias= "_umb_email"
},
new ContentPropertyDisplay()
{
Alias = "_umb_password"
},
new ContentPropertyDisplay()
{
Alias = "_umb_membergroup"
}
}
}
}
};
return member;
}
/// <summary>
/// Check all member properties are equal
/// </summary>
/// <param name="memberDisplay"></param>
/// <param name="resultValue"></param>
private void AssertMemberDisplayPropertiesAreEqual(MemberDisplay memberDisplay, MemberDisplay resultValue)
{
Assert.AreNotSame(memberDisplay, resultValue);
Assert.AreEqual(memberDisplay.Id, resultValue.Id);
Assert.AreEqual(memberDisplay.Alias, resultValue.Alias);
Assert.AreEqual(memberDisplay.Username, resultValue.Username);
Assert.AreEqual(memberDisplay.Email, resultValue.Email);
Assert.AreEqual(memberDisplay.AdditionalData, resultValue.AdditionalData);
Assert.AreEqual(memberDisplay.ContentApps, resultValue.ContentApps);
Assert.AreEqual(memberDisplay.ContentType.Alias, resultValue.ContentType.Alias);
Assert.AreEqual(memberDisplay.ContentTypeAlias, resultValue.ContentTypeAlias);
Assert.AreEqual(memberDisplay.ContentTypeName, resultValue.ContentTypeName);
Assert.AreEqual(memberDisplay.ContentTypeId, resultValue.ContentTypeId);
Assert.AreEqual(memberDisplay.Icon, resultValue.Icon);
Assert.AreEqual(memberDisplay.Errors, resultValue.Errors);
Assert.AreEqual(memberDisplay.Key, resultValue.Key);
Assert.AreEqual(memberDisplay.Name, resultValue.Name);
Assert.AreEqual(memberDisplay.Path, resultValue.Path);
Assert.AreEqual(memberDisplay.SortOrder, resultValue.SortOrder);
Assert.AreEqual(memberDisplay.Trashed, resultValue.Trashed);
Assert.AreEqual(memberDisplay.TreeNodeUrl, resultValue.TreeNodeUrl);
//TODO: can we check create/update dates when saving?
//Assert.AreEqual(memberDisplay.CreateDate, resultValue.CreateDate);
//Assert.AreEqual(memberDisplay.UpdateDate, resultValue.UpdateDate);
//TODO: check all properties
Assert.AreEqual(memberDisplay.Properties.Count(), resultValue.Properties.Count());
Assert.AreNotSame(memberDisplay.Properties, resultValue.Properties);
for (var index = 0; index < resultValue.Properties.Count(); index++)
{
Assert.AreNotSame(memberDisplay.Properties.GetItemByIndex(index), resultValue.Properties.GetItemByIndex(index));
//Assert.AreEqual(memberDisplay.Properties.GetItemByIndex(index), resultValue.Properties.GetItemByIndex(index));
}
}
}
}
| |
// 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.Threading.Tasks;
using Xunit;
namespace System.IO.Compression.Tests
{
public class GZipStreamTests
{
static string gzTestFile(string fileName) { return Path.Combine("GZTestData", fileName); }
[Fact]
public void BaseStream1()
{
var writeStream = new MemoryStream();
var zip = new GZipStream(writeStream, CompressionMode.Compress);
Assert.Same(zip.BaseStream, writeStream);
writeStream.Dispose();
}
[Fact]
public void BaseStream2()
{
var ms = new MemoryStream();
var zip = new GZipStream(ms, CompressionMode.Decompress);
Assert.Same(zip.BaseStream, ms);
ms.Dispose();
}
[Fact]
public async Task ModifyBaseStream()
{
var ms = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.txt.gz"));
var zip = new GZipStream(ms, CompressionMode.Decompress);
int size = 1024;
byte[] bytes = new byte[size];
zip.BaseStream.Read(bytes, 0, size); // This will throw if the underlying stream is not writable as expected
}
[Fact]
public void DecompressCanRead()
{
var ms = new MemoryStream();
var zip = new GZipStream(ms, CompressionMode.Decompress);
Assert.True(zip.CanRead, "GZipStream not CanRead in Decompress");
zip.Dispose();
Assert.False(zip.CanRead, "GZipStream CanRead after dispose in Decompress");
}
[Fact]
public void CompressCanWrite()
{
var ms = new MemoryStream();
var zip = new GZipStream(ms, CompressionMode.Compress);
Assert.True(zip.CanWrite, "GZipStream not CanWrite with CompressionMode.Compress");
zip.Dispose();
Assert.False(zip.CanWrite, "GZipStream CanWrite after dispose");
}
[Fact]
public void CanDisposeBaseStream()
{
var ms = new MemoryStream();
var zip = new GZipStream(ms, CompressionMode.Compress);
ms.Dispose(); // This would throw if this was invalid
}
[Fact]
public void CanDisposeGZipStream()
{
var ms = new MemoryStream();
var zip = new GZipStream(ms, CompressionMode.Compress);
zip.Dispose();
Assert.Null(zip.BaseStream);
zip.Dispose(); // Should be a no-op
}
[Fact]
public async Task CanReadBaseStreamAfterDispose()
{
var ms = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.txt.gz"));
var zip = new GZipStream(ms, CompressionMode.Decompress, leaveOpen: true);
var baseStream = zip.BaseStream;
zip.Dispose();
int size = 1024;
byte[] bytes = new byte[size];
baseStream.Read(bytes, 0, size); // This will throw if the underlying stream is not writable as expected
}
[Fact]
public async Task DecompressWorks()
{
var compareStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.txt"));
var gzStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.txt.gz"));
await DecompressAsync(compareStream, gzStream);
}
[Fact]
public async Task DecompressWorksWithDoc()
{
var compareStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.doc"));
var gzStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.doc.gz"));
await DecompressAsync(compareStream, gzStream);
}
[Fact]
public async Task DecompressWorksWithDocx()
{
var compareStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.docx"));
var gzStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.docx.gz"));
await DecompressAsync(compareStream, gzStream);
}
[Fact]
public async Task DecompressWorksWithPdf()
{
var compareStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.pdf"));
var gzStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.pdf.gz"));
await DecompressAsync(compareStream, gzStream);
}
// Making this async since regular read/write are tested below
private static async Task DecompressAsync(MemoryStream compareStream, MemoryStream gzStream)
{
var ms = new MemoryStream();
var zip = new GZipStream(gzStream, CompressionMode.Decompress);
var GZipStream = new MemoryStream();
await zip.CopyToAsync(GZipStream);
GZipStream.Position = 0;
compareStream.Position = 0;
byte[] compareArray = compareStream.ToArray();
byte[] writtenArray = GZipStream.ToArray();
Assert.Equal(compareArray.Length, writtenArray.Length);
for (int i = 0; i < compareArray.Length; i++)
{
Assert.Equal(compareArray[i], writtenArray[i]);
}
}
[Fact]
public void NullBaseStreamThrows()
{
Assert.Throws<ArgumentNullException>(() =>
{
var deflate = new GZipStream(null, CompressionMode.Decompress);
});
Assert.Throws<ArgumentNullException>(() =>
{
var deflate = new GZipStream(null, CompressionMode.Compress);
});
}
[Fact]
public void DisposedBaseStreamThrows()
{
var ms = new MemoryStream();
ms.Dispose();
AssertExtensions.Throws<ArgumentException>("stream", () =>
{
var deflate = new GZipStream(ms, CompressionMode.Decompress);
});
AssertExtensions.Throws<ArgumentException>("stream", () =>
{
var deflate = new GZipStream(ms, CompressionMode.Compress);
});
}
[Fact]
public void ReadOnlyStreamThrowsOnCompress()
{
var ms = new LocalMemoryStream();
ms.SetCanWrite(false);
AssertExtensions.Throws<ArgumentException>("stream", () =>
{
var gzip = new GZipStream(ms, CompressionMode.Compress);
});
}
[Fact]
public void WriteOnlyStreamThrowsOnDecompress()
{
var ms = new LocalMemoryStream();
ms.SetCanRead(false);
AssertExtensions.Throws<ArgumentException>("stream", () =>
{
var gzip = new GZipStream(ms, CompressionMode.Decompress);
});
}
[Fact]
public void CopyToAsyncArgumentValidation()
{
using (GZipStream gs = new GZipStream(new MemoryStream(), CompressionMode.Decompress))
{
AssertExtensions.Throws<ArgumentNullException>("destination", () => { gs.CopyToAsync(null); });
AssertExtensions.Throws<ArgumentOutOfRangeException>("bufferSize", () => { gs.CopyToAsync(new MemoryStream(), 0); });
Assert.Throws<NotSupportedException>(() => { gs.CopyToAsync(new MemoryStream(new byte[1], writable: false)); });
gs.Dispose();
Assert.Throws<ObjectDisposedException>(() => { gs.CopyToAsync(new MemoryStream()); });
}
using (GZipStream gs = new GZipStream(new MemoryStream(), CompressionMode.Compress))
{
Assert.Throws<NotSupportedException>(() => { gs.CopyToAsync(new MemoryStream()); });
}
}
[Fact]
public void TestCtors()
{
CompressionLevel[] legalValues = new CompressionLevel[] { CompressionLevel.Optimal, CompressionLevel.Fastest, CompressionLevel.NoCompression };
foreach (CompressionLevel level in legalValues)
{
bool[] boolValues = new bool[] { true, false };
foreach (bool remainsOpen in boolValues)
{
TestCtor(level, remainsOpen);
}
}
}
[Fact]
public void TestLevelOptimial()
{
TestCtor(CompressionLevel.Optimal);
}
[Fact]
public void TestLevelNoCompression()
{
TestCtor(CompressionLevel.NoCompression);
}
[Fact]
public void TestLevelFastest()
{
TestCtor(CompressionLevel.Fastest);
}
private static void TestCtor(CompressionLevel level, bool? leaveOpen = null)
{
//Create the GZipStream
int _bufferSize = 1024;
var bytes = new byte[_bufferSize];
var baseStream = new MemoryStream(bytes, writable: true);
GZipStream ds;
if (leaveOpen == null)
{
ds = new GZipStream(baseStream, level);
}
else
{
ds = new GZipStream(baseStream, level, leaveOpen ?? false);
}
//Write some data and Close the stream
string strData = "Test Data";
var encoding = Encoding.UTF8;
byte[] data = encoding.GetBytes(strData);
ds.Write(data, 0, data.Length);
ds.Flush();
ds.Dispose();
if (leaveOpen != true)
{
//Check that Close has really closed the underlying stream
Assert.Throws<ObjectDisposedException>(() => { baseStream.Write(bytes, 0, bytes.Length); });
}
//Read the data
byte[] data2 = new byte[_bufferSize];
baseStream = new MemoryStream(bytes, writable: false);
ds = new GZipStream(baseStream, CompressionMode.Decompress);
int size = ds.Read(data2, 0, _bufferSize - 5);
//Verify the data roundtripped
for (int i = 0; i < size + 5; i++)
{
if (i < data.Length)
{
Assert.Equal(data[i], data2[i]);
}
else
{
Assert.Equal(data2[i], (byte)0);
}
}
}
[Fact]
public async Task Flush()
{
var ms = new MemoryStream();
var ds = new GZipStream(ms, CompressionMode.Compress);
ds.Flush();
await ds.FlushAsync();
// Just ensuring Flush doesn't throw
}
[Fact]
public void FlushFailsAfterDispose()
{
var ms = new MemoryStream();
var ds = new GZipStream(ms, CompressionMode.Compress);
ds.Dispose();
Assert.Throws<ObjectDisposedException>(() => { ds.Flush(); });
}
[Fact]
public async Task FlushAsyncFailsAfterDispose()
{
var ms = new MemoryStream();
var ds = new GZipStream(ms, CompressionMode.Compress);
ds.Dispose();
await Assert.ThrowsAsync<ObjectDisposedException>(async () =>
{
await ds.FlushAsync();
});
}
[Fact]
public void TestSeekMethodsDecompress()
{
var ms = new MemoryStream();
var zip = new GZipStream(ms, CompressionMode.Decompress);
Assert.False(zip.CanSeek);
Assert.Throws<NotSupportedException>(delegate { long value = zip.Length; });
Assert.Throws<NotSupportedException>(delegate { long value = zip.Position; });
Assert.Throws<NotSupportedException>(delegate { zip.Position = 100L; });
Assert.Throws<NotSupportedException>(delegate { zip.SetLength(100L); });
Assert.Throws<NotSupportedException>(delegate { zip.Seek(100L, SeekOrigin.Begin); });
zip.Dispose();
Assert.False(zip.CanSeek);
}
[Fact]
public void TestSeekMethodsCompress()
{
var ms = new MemoryStream();
var zip = new GZipStream(ms, CompressionMode.Compress);
Assert.False(zip.CanSeek);
Assert.Throws<NotSupportedException>(delegate { long value = zip.Length; });
Assert.Throws<NotSupportedException>(delegate { long value = zip.Position; });
Assert.Throws<NotSupportedException>(delegate { zip.Position = 100L; });
Assert.Throws<NotSupportedException>(delegate { zip.SetLength(100L); });
Assert.Throws<NotSupportedException>(delegate { zip.Seek(100L, SeekOrigin.Begin); });
zip.Dispose();
Assert.False(zip.CanSeek);
}
[Fact]
public void DerivedStream_ReadWriteSpan_UsesReadWriteArray()
{
var ms = new MemoryStream();
using (var compressor = new DerivedGZipStream(ms, CompressionMode.Compress, leaveOpen:true))
{
compressor.Write(new Span<byte>(new byte[1]));
Assert.True(compressor.WriteArrayInvoked);
}
ms.Position = 0;
using (var compressor = new DerivedGZipStream(ms, CompressionMode.Decompress, leaveOpen: true))
{
compressor.Read(new Span<byte>(new byte[1]));
Assert.True(compressor.ReadArrayInvoked);
}
}
private sealed class DerivedGZipStream : GZipStream
{
public bool ReadArrayInvoked, WriteArrayInvoked;
public DerivedGZipStream(Stream stream, CompressionMode mode, bool leaveOpen) : base(stream, mode, leaveOpen) { }
public override int Read(byte[] array, int offset, int count)
{
ReadArrayInvoked = true;
return base.Read(array, offset, count);
}
public override void Write(byte[] array, int offset, int count)
{
WriteArrayInvoked = true;
base.Write(array, offset, count);
}
}
}
}
| |
// Ami Bar
// amibar@gmail.com
using System;
using System.Threading;
namespace Amib.Threading.Internal
{
#region WorkItemsQueue class
/// <summary>
/// WorkItemsQueue class.
/// </summary>
public class WorkItemsQueue : IDisposable
{
#region Member variables
/// <summary>
/// Each thread in the thread pool keeps its own waiter entry.
/// </summary>
[ThreadStatic] private static WaiterEntry _waiterEntry;
/// <summary>
/// Waiters queue (implemented as stack).
/// </summary>
private readonly WaiterEntry _headWaiterEntry = new WaiterEntry();
/// <summary>
/// Work items queue
/// </summary>
private readonly PriorityQueue _workItems = new PriorityQueue();
/// <summary>
/// A flag that indicates if the WorkItemsQueue has been disposed.
/// </summary>
private bool _isDisposed;
/// <summary>
/// Indicate that work items are allowed to be queued
/// </summary>
private bool _isWorkItemsQueueActive = true;
/// <summary>
/// Waiters count
/// </summary>
private int _waitersCount;
#endregion
#region Public properties
/// <summary>
/// Returns the current number of work items in the queue
/// </summary>
public int Count
{
get
{
lock (this)
{
ValidateNotDisposed();
return _workItems.Count;
}
}
}
/// <summary>
/// Returns the current number of waiters
/// </summary>
public int WaitersCount
{
get
{
lock (this)
{
ValidateNotDisposed();
return _waitersCount;
}
}
}
#endregion
#region Public methods
/// <summary>
/// Enqueue a work item to the queue.
/// </summary>
public bool EnqueueWorkItem(WorkItem workItem)
{
// A work item cannot be null, since null is used in the
// WaitForWorkItem() method to indicate timeout or cancel
if (null == workItem)
{
throw new ArgumentNullException("workItem", "workItem cannot be null");
}
bool enqueue = true;
// First check if there is a waiter waiting for work item. During
// the check, timed out waiters are ignored. If there is no
// waiter then the work item is queued.
lock (this)
{
ValidateNotDisposed();
if (!_isWorkItemsQueueActive)
{
return false;
}
while (_waitersCount > 0)
{
// Dequeue a waiter.
WaiterEntry waiterEntry = PopWaiter();
// Signal the waiter. On success break the loop
if (waiterEntry.Signal(workItem))
{
enqueue = false;
break;
}
}
if (enqueue)
{
// Enqueue the work item
_workItems.Enqueue(workItem);
}
}
return true;
}
/// <summary>
/// Waits for a work item or exits on timeout or cancel
/// </summary>
/// <param name = "millisecondsTimeout">Timeout in milliseconds</param>
/// <param name = "cancelEvent">Cancel wait handle</param>
/// <returns>Returns true if the resource was granted</returns>
public WorkItem DequeueWorkItem(
int millisecondsTimeout,
WaitHandle cancelEvent)
{
/// This method cause the caller to wait for a work item.
/// If there is at least one waiting work item then the
/// method returns immidiately with true.
///
/// If there are no waiting work items then the caller
/// is queued between other waiters for a work item to arrive.
///
/// If a work item didn't come within millisecondsTimeout or
/// the user canceled the wait by signaling the cancelEvent
/// then the method returns false to indicate that the caller
/// didn't get a work item.
WaiterEntry waiterEntry = null;
WorkItem workItem = null;
lock (this)
{
ValidateNotDisposed();
// If there are waiting work items then take one and return.
if (_workItems.Count > 0)
{
workItem = _workItems.Dequeue() as WorkItem;
return workItem;
}
// No waiting work items ...
else
{
// Get the wait entry for the waiters queue
waiterEntry = GetThreadWaiterEntry();
// Put the waiter with the other waiters
PushWaiter(waiterEntry);
}
}
// Prepare array of wait handle for the WaitHandle.WaitAny()
WaitHandle[] waitHandles = new[]
{
waiterEntry.WaitHandle,
cancelEvent
};
// Wait for an available resource, cancel event, or timeout.
// During the wait we are supposes to exit the synchronization
// domain. (Placing true as the third argument of the WaitAny())
// It just doesn't work, I don't know why, so I have lock(this)
// statments insted of one.
int index = WaitHandle.WaitAny(
waitHandles,
millisecondsTimeout,
true);
lock (this)
{
// success is true if it got a work item.
bool success = (0 == index);
// The timeout variable is used only for readability.
// (We treat cancel as timeout)
bool timeout = !success;
// On timeout update the waiterEntry that it is timed out
if (timeout)
{
// The Timeout() fails if the waiter has already been signaled
timeout = waiterEntry.Timeout();
// On timeout remove the waiter from the queue.
// Note that the complexity is O(1).
if (timeout)
{
RemoveWaiter(waiterEntry, false);
}
// Again readability
success = !timeout;
}
// On success return the work item
if (success)
{
workItem = waiterEntry.WorkItem;
if (null == workItem)
{
workItem = _workItems.Dequeue() as WorkItem;
}
}
}
// On failure return null.
return workItem;
}
/// <summary>
/// Cleanup the work items queue, hence no more work
/// items are allowed to be queue
/// </summary>
protected virtual void Cleanup()
{
lock (this)
{
// Deactivate only once
if (!_isWorkItemsQueueActive)
{
return;
}
// Don't queue more work items
_isWorkItemsQueueActive = false;
foreach (WorkItem workItem in _workItems)
{
workItem.DisposeOfState();
}
// Clear the work items that are already queued
_workItems.Clear();
// Note:
// I don't iterate over the queue and dispose of work items's states,
// since if a work item has a state object that is still in use in the
// application then I must not dispose it.
// Tell the waiters that they were timed out.
// It won't signal them to exit, but to ignore their
// next work item.
while (_waitersCount > 0)
{
WaiterEntry waiterEntry = PopWaiter();
waiterEntry.Timeout();
}
}
}
#endregion
#region Private methods
/// <summary>
/// Returns the WaiterEntry of the current thread
/// </summary>
/// <returns></returns>
/// In order to avoid creation and destuction of WaiterEntry
/// objects each thread has its own WaiterEntry object.
private WaiterEntry GetThreadWaiterEntry()
{
if (null == _waiterEntry)
{
_waiterEntry = new WaiterEntry();
}
_waiterEntry.Reset();
return _waiterEntry;
}
#region Waiters stack methods
/// <summary>
/// Push a new waiter into the waiter's stack
/// </summary>
/// <param name = "newWaiterEntry">A waiter to put in the stack</param>
public void PushWaiter(WaiterEntry newWaiterEntry)
{
// Remove the waiter if it is already in the stack and
// update waiter's count as needed
RemoveWaiter(newWaiterEntry, false);
// If the stack is empty then newWaiterEntry is the new head of the stack
if (null == _headWaiterEntry._nextWaiterEntry)
{
_headWaiterEntry._nextWaiterEntry = newWaiterEntry;
newWaiterEntry._prevWaiterEntry = _headWaiterEntry;
}
// If the stack is not empty then put newWaiterEntry as the new head
// of the stack.
else
{
// Save the old first waiter entry
WaiterEntry oldFirstWaiterEntry = _headWaiterEntry._nextWaiterEntry;
// Update the links
_headWaiterEntry._nextWaiterEntry = newWaiterEntry;
newWaiterEntry._nextWaiterEntry = oldFirstWaiterEntry;
newWaiterEntry._prevWaiterEntry = _headWaiterEntry;
oldFirstWaiterEntry._prevWaiterEntry = newWaiterEntry;
}
// Increment the number of waiters
++_waitersCount;
}
/// <summary>
/// Pop a waiter from the waiter's stack
/// </summary>
/// <returns>Returns the first waiter in the stack</returns>
private WaiterEntry PopWaiter()
{
// Store the current stack head
WaiterEntry oldFirstWaiterEntry = _headWaiterEntry._nextWaiterEntry;
// Store the new stack head
WaiterEntry newHeadWaiterEntry = oldFirstWaiterEntry._nextWaiterEntry;
// Update the old stack head list links and decrement the number
// waiters.
RemoveWaiter(oldFirstWaiterEntry, true);
// Update the new stack head
_headWaiterEntry._nextWaiterEntry = newHeadWaiterEntry;
if (null != newHeadWaiterEntry)
{
newHeadWaiterEntry._prevWaiterEntry = _headWaiterEntry;
}
// Return the old stack head
return oldFirstWaiterEntry;
}
/// <summary>
/// Remove a waiter from the stack
/// </summary>
/// <param name = "waiterEntry">A waiter entry to remove</param>
/// <param name = "popDecrement">If true the waiter count is always decremented</param>
private void RemoveWaiter(WaiterEntry waiterEntry, bool popDecrement)
{
// Store the prev entry in the list
WaiterEntry prevWaiterEntry = waiterEntry._prevWaiterEntry;
// Store the next entry in the list
WaiterEntry nextWaiterEntry = waiterEntry._nextWaiterEntry;
// A flag to indicate if we need to decrement the waiters count.
// If we got here from PopWaiter then we must decrement.
// If we got here from PushWaiter then we decrement only if
// the waiter was already in the stack.
bool decrementCounter = popDecrement;
// Null the waiter's entry links
waiterEntry._prevWaiterEntry = null;
waiterEntry._nextWaiterEntry = null;
// If the waiter entry had a prev link then update it.
// It also means that the waiter is already in the list and we
// need to decrement the waiters count.
if (null != prevWaiterEntry)
{
prevWaiterEntry._nextWaiterEntry = nextWaiterEntry;
decrementCounter = true;
}
// If the waiter entry had a next link then update it.
// It also means that the waiter is already in the list and we
// need to decrement the waiters count.
if (null != nextWaiterEntry)
{
nextWaiterEntry._prevWaiterEntry = prevWaiterEntry;
decrementCounter = true;
}
// Decrement the waiters count if needed
if (decrementCounter)
{
--_waitersCount;
}
}
#endregion
#endregion
#region WaiterEntry class
// A waiter entry in the _waiters queue.
public class WaiterEntry : IDisposable
{
#region Member variables
private bool _isDisposed;
/// <summary>
/// Flag to know if the waiter was signaled and got a work item.
/// </summary>
private bool _isSignaled;
/// <summary>
/// Flag to know if this waiter already quited from the queue
/// because of a timeout.
/// </summary>
private bool _isTimedout;
// Linked list members
internal WaiterEntry _nextWaiterEntry;
internal WaiterEntry _prevWaiterEntry;
/// <summary>
/// Event to signal the waiter that it got the work item.
/// </summary>
private AutoResetEvent _waitHandle = new AutoResetEvent(false);
/// <summary>
/// A work item that passed directly to the waiter withou going
/// through the queue
/// </summary>
private WorkItem _workItem;
#endregion
#region Construction
public WaiterEntry()
{
Reset();
}
#endregion
#region Public methods
public WaitHandle WaitHandle
{
get { return _waitHandle; }
}
public WorkItem WorkItem
{
get
{
lock (this)
{
return _workItem;
}
}
}
/// <summary>
/// Signal the waiter that it got a work item.
/// </summary>
/// <returns>Return true on success</returns>
/// The method fails if Timeout() preceded its call
public bool Signal(WorkItem workItem)
{
lock (this)
{
if (!_isTimedout)
{
_workItem = workItem;
_isSignaled = true;
_waitHandle.Set();
return true;
}
}
return false;
}
/// <summary>
/// Mark the wait entry that it has been timed out
/// </summary>
/// <returns>Return true on success</returns>
/// The method fails if Signal() preceded its call
public bool Timeout()
{
lock (this)
{
// Time out can happen only if the waiter wasn't marked as
// signaled
if (!_isSignaled)
{
// We don't remove the waiter from the queue, the DequeueWorkItem
// method skips _waiters that were timed out.
_isTimedout = true;
return true;
}
}
return false;
}
/// <summary>
/// Reset the wait entry so it can be used again
/// </summary>
public void Reset()
{
_workItem = null;
_isTimedout = false;
_isSignaled = false;
_waitHandle.Reset();
}
/// <summary>
/// Free resources
/// </summary>
public void Close()
{
if (null != _waitHandle)
{
_waitHandle.Close();
_waitHandle = null;
}
}
#endregion
#region IDisposable Members
public void Dispose()
{
if (!_isDisposed)
{
Close();
_isDisposed = true;
}
}
#endregion
~WaiterEntry()
{
Dispose();
}
}
#endregion
#region IDisposable Members
public void Dispose()
{
if (!_isDisposed)
{
Cleanup();
_isDisposed = true;
GC.SuppressFinalize(this);
}
}
#endregion
~WorkItemsQueue()
{
Cleanup();
}
private void ValidateNotDisposed()
{
if (_isDisposed)
{
throw new ObjectDisposedException(GetType().ToString(), "The SmartThreadPool has been shutdown");
}
}
}
#endregion
}
| |
using Lucene.Net.Index;
using Lucene.Net.Store;
using Lucene.Net.Util;
using Lucene.Net.Util.Packed;
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Lucene.Net.Codecs.BlockTerms
{
/*
* 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>
/// Selects every Nth term as and index term, and hold term
/// bytes (mostly) fully expanded in memory. This terms index
/// supports seeking by ord. See
/// <see cref="VariableGapTermsIndexWriter"/> for a more memory efficient
/// terms index that does not support seeking by ord.
/// <para/>
/// @lucene.experimental
/// </summary>
public class FixedGapTermsIndexWriter : TermsIndexWriterBase
{
protected IndexOutput m_output;
/// <summary>Extension of terms index file</summary>
internal readonly static string TERMS_INDEX_EXTENSION = "tii";
internal readonly static string CODEC_NAME = "SIMPLE_STANDARD_TERMS_INDEX";
internal readonly static int VERSION_START = 0;
internal readonly static int VERSION_APPEND_ONLY = 1;
internal readonly static int VERSION_CHECKSUM = 1000; // 4.x "skipped" trunk's monotonic addressing: give any user a nice exception
internal readonly static int VERSION_CURRENT = VERSION_CHECKSUM;
private readonly int termIndexInterval;
private readonly IList<SimpleFieldWriter> fields = new List<SimpleFieldWriter>();
private readonly FieldInfos fieldInfos; // unread
public FixedGapTermsIndexWriter(SegmentWriteState state)
{
string indexFileName = IndexFileNames.SegmentFileName(state.SegmentInfo.Name, state.SegmentSuffix, TERMS_INDEX_EXTENSION);
termIndexInterval = state.TermIndexInterval;
m_output = state.Directory.CreateOutput(indexFileName, state.Context);
bool success = false;
try
{
fieldInfos = state.FieldInfos;
WriteHeader(m_output);
m_output.WriteInt32(termIndexInterval);
success = true;
}
finally
{
if (!success)
{
IOUtils.DisposeWhileHandlingException(m_output);
}
}
}
private void WriteHeader(IndexOutput output)
{
CodecUtil.WriteHeader(output, CODEC_NAME, VERSION_CURRENT);
}
public override FieldWriter AddField(FieldInfo field, long termsFilePointer)
{
//System.out.println("FGW: addFfield=" + field.name);
SimpleFieldWriter writer = new SimpleFieldWriter(this, field, termsFilePointer);
fields.Add(writer);
return writer;
}
/// <summary>
/// NOTE: if your codec does not sort in unicode code
/// point order, you must override this method, to simply
/// return <c>indexedTerm.Length</c>.
/// </summary>
protected virtual int IndexedTermPrefixLength(BytesRef priorTerm, BytesRef indexedTerm)
{
// As long as codec sorts terms in unicode codepoint
// order, we can safely strip off the non-distinguishing
// suffix to save RAM in the loaded terms index.
int idxTermOffset = indexedTerm.Offset;
int priorTermOffset = priorTerm.Offset;
int limit = Math.Min(priorTerm.Length, indexedTerm.Length);
for (int byteIdx = 0; byteIdx < limit; byteIdx++)
{
if (priorTerm.Bytes[priorTermOffset + byteIdx] != indexedTerm.Bytes[idxTermOffset + byteIdx])
{
return byteIdx + 1;
}
}
return Math.Min(1 + priorTerm.Length, indexedTerm.Length);
}
private class SimpleFieldWriter : FieldWriter
{
private readonly FixedGapTermsIndexWriter outerInstance;
internal readonly FieldInfo fieldInfo;
internal int numIndexTerms;
internal readonly long indexStart;
internal readonly long termsStart;
internal long packedIndexStart;
internal long packedOffsetsStart;
private long numTerms;
// TODO: we could conceivably make a PackedInts wrapper
// that auto-grows... then we wouldn't force 6 bytes RAM
// per index term:
private short[] termLengths;
private int[] termsPointerDeltas;
private long lastTermsPointer;
private long totTermLength;
private readonly BytesRef lastTerm = new BytesRef();
internal SimpleFieldWriter(FixedGapTermsIndexWriter outerInstance, FieldInfo fieldInfo, long termsFilePointer)
{
this.outerInstance = outerInstance;
this.fieldInfo = fieldInfo;
indexStart = outerInstance.m_output.GetFilePointer();
termsStart = lastTermsPointer = termsFilePointer;
termLengths = new short[0];
termsPointerDeltas = new int[0];
}
public override bool CheckIndexTerm(BytesRef text, TermStats stats)
{
// First term is first indexed term:
//System.output.println("FGW: checkIndexTerm text=" + text.utf8ToString());
if (0 == (numTerms++ % outerInstance.termIndexInterval))
{
return true;
}
else
{
if (0 == numTerms % outerInstance.termIndexInterval)
{
// save last term just before next index term so we
// can compute wasted suffix
lastTerm.CopyBytes(text);
}
return false;
}
}
public override void Add(BytesRef text, TermStats stats, long termsFilePointer)
{
int indexedTermLength = outerInstance.IndexedTermPrefixLength(lastTerm, text);
//System.out.println("FGW: add text=" + text.utf8ToString() + " " + text + " fp=" + termsFilePointer);
// write only the min prefix that shows the diff
// against prior term
outerInstance.m_output.WriteBytes(text.Bytes, text.Offset, indexedTermLength);
if (termLengths.Length == numIndexTerms)
{
termLengths = ArrayUtil.Grow(termLengths);
}
if (termsPointerDeltas.Length == numIndexTerms)
{
termsPointerDeltas = ArrayUtil.Grow(termsPointerDeltas);
}
// save delta terms pointer
termsPointerDeltas[numIndexTerms] = (int)(termsFilePointer - lastTermsPointer);
lastTermsPointer = termsFilePointer;
// save term length (in bytes)
Debug.Assert(indexedTermLength <= short.MaxValue);
termLengths[numIndexTerms] = (short)indexedTermLength;
totTermLength += indexedTermLength;
lastTerm.CopyBytes(text);
numIndexTerms++;
}
public override void Finish(long termsFilePointer)
{
// write primary terms dict offsets
packedIndexStart = outerInstance.m_output.GetFilePointer();
PackedInt32s.Writer w = PackedInt32s.GetWriter(outerInstance.m_output, numIndexTerms, PackedInt32s.BitsRequired(termsFilePointer), PackedInt32s.DEFAULT);
// relative to our indexStart
long upto = 0;
for (int i = 0; i < numIndexTerms; i++)
{
upto += termsPointerDeltas[i];
w.Add(upto);
}
w.Finish();
packedOffsetsStart = outerInstance.m_output.GetFilePointer();
// write offsets into the byte[] terms
w = PackedInt32s.GetWriter(outerInstance.m_output, 1 + numIndexTerms, PackedInt32s.BitsRequired(totTermLength), PackedInt32s.DEFAULT);
upto = 0;
for (int i = 0; i < numIndexTerms; i++)
{
w.Add(upto);
upto += termLengths[i];
}
w.Add(upto);
w.Finish();
// our referrer holds onto us, while other fields are
// being written, so don't tie up this RAM:
termLengths = null;
termsPointerDeltas = null;
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (m_output != null)
{
bool success = false;
try
{
long dirStart = m_output.GetFilePointer();
int fieldCount = fields.Count;
int nonNullFieldCount = 0;
for (int i = 0; i < fieldCount; i++)
{
SimpleFieldWriter field = fields[i];
if (field.numIndexTerms > 0)
{
nonNullFieldCount++;
}
}
m_output.WriteVInt32(nonNullFieldCount);
for (int i = 0; i < fieldCount; i++)
{
SimpleFieldWriter field = fields[i];
if (field.numIndexTerms > 0)
{
m_output.WriteVInt32(field.fieldInfo.Number);
m_output.WriteVInt32(field.numIndexTerms);
m_output.WriteVInt64(field.termsStart);
m_output.WriteVInt64(field.indexStart);
m_output.WriteVInt64(field.packedIndexStart);
m_output.WriteVInt64(field.packedOffsetsStart);
}
}
WriteTrailer(dirStart);
CodecUtil.WriteFooter(m_output);
success = true;
}
finally
{
if (success)
{
IOUtils.Dispose(m_output);
}
else
{
IOUtils.DisposeWhileHandlingException(m_output);
}
m_output = null;
}
}
}
}
private void WriteTrailer(long dirStart)
{
m_output.WriteInt64(dirStart);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Globalization;
using Xunit;
namespace System.Tests
{
public static class Int32Tests
{
[Fact]
public static void Ctor_Empty()
{
var i = new int();
Assert.Equal(0, i);
}
[Fact]
public static void Ctor_Value()
{
int i = 41;
Assert.Equal(41, i);
}
[Fact]
public static void MaxValue()
{
Assert.Equal(0x7FFFFFFF, int.MaxValue);
}
[Fact]
public static void MinValue()
{
Assert.Equal(unchecked((int)0x80000000), int.MinValue);
}
[Theory]
[InlineData(234, 234, 0)]
[InlineData(234, int.MinValue, 1)]
[InlineData(234, -123, 1)]
[InlineData(234, 0, 1)]
[InlineData(234, 123, 1)]
[InlineData(234, 456, -1)]
[InlineData(234, int.MaxValue, -1)]
[InlineData(-234, -234, 0)]
[InlineData(-234, 234, -1)]
[InlineData(-234, -432, 1)]
[InlineData(234, null, 1)]
public static void CompareTo(int i, object value, int expected)
{
if (value is int)
{
Assert.Equal(expected, Math.Sign(i.CompareTo((int)value)));
}
IComparable comparable = i;
Assert.Equal(expected, Math.Sign(comparable.CompareTo(value)));
}
[Fact]
public static void CompareTo_ObjectNotInt_ThrowsArgumentException()
{
IComparable comparable = 234;
AssertExtensions.Throws<ArgumentException>(null, () => comparable.CompareTo("a")); // Obj is not an int
AssertExtensions.Throws<ArgumentException>(null, () => comparable.CompareTo((long)234)); // Obj is not an int
}
[Theory]
[InlineData(789, 789, true)]
[InlineData(789, -789, false)]
[InlineData(789, 0, false)]
[InlineData(0, 0, true)]
[InlineData(-789, -789, true)]
[InlineData(-789, 789, false)]
[InlineData(789, null, false)]
[InlineData(789, "789", false)]
[InlineData(789, (long)789, false)]
public static void Equals(int i1, object obj, bool expected)
{
if (obj is int)
{
int i2 = (int)obj;
Assert.Equal(expected, i1.Equals(i2));
Assert.Equal(expected, i1.GetHashCode().Equals(i2.GetHashCode()));
}
Assert.Equal(expected, i1.Equals(obj));
}
public static IEnumerable<object[]> ToString_TestData()
{
NumberFormatInfo emptyFormat = NumberFormatInfo.CurrentInfo;
yield return new object[] { int.MinValue, "G", emptyFormat, "-2147483648" };
yield return new object[] { -4567, "G", emptyFormat, "-4567" };
yield return new object[] { 0, "G", emptyFormat, "0" };
yield return new object[] { 4567, "G", emptyFormat, "4567" };
yield return new object[] { int.MaxValue, "G", emptyFormat, "2147483647" };
yield return new object[] { 0x2468, "x", emptyFormat, "2468" };
yield return new object[] { 2468, "N", emptyFormat, string.Format("{0:N}", 2468.00) };
NumberFormatInfo customFormat = new NumberFormatInfo();
customFormat.NegativeSign = "#";
customFormat.NumberDecimalSeparator = "~";
customFormat.NumberGroupSeparator = "*";
yield return new object[] { -2468, "N", customFormat, "#2*468~00" };
yield return new object[] { 2468, "N", customFormat, "2*468~00" };
}
[Theory]
[MemberData(nameof(ToString_TestData))]
public static void ToString(int i, string format, IFormatProvider provider, string expected)
{
// Format is case insensitive
string upperFormat = format.ToUpperInvariant();
string lowerFormat = format.ToLowerInvariant();
string upperExpected = expected.ToUpperInvariant();
string lowerExpected = expected.ToLowerInvariant();
bool isDefaultProvider = (provider == null || provider == NumberFormatInfo.CurrentInfo);
if (string.IsNullOrEmpty(format) || format.ToUpperInvariant() == "G")
{
if (isDefaultProvider)
{
Assert.Equal(upperExpected, i.ToString());
Assert.Equal(upperExpected, i.ToString((IFormatProvider)null));
}
Assert.Equal(upperExpected, i.ToString(provider));
}
if (isDefaultProvider)
{
Assert.Equal(upperExpected, i.ToString(upperFormat));
Assert.Equal(lowerExpected, i.ToString(lowerFormat));
Assert.Equal(upperExpected, i.ToString(upperFormat, null));
Assert.Equal(lowerExpected, i.ToString(lowerFormat, null));
}
Assert.Equal(upperExpected, i.ToString(upperFormat, provider));
Assert.Equal(lowerExpected, i.ToString(lowerFormat, provider));
}
[Fact]
public static void ToString_InvalidFormat_ThrowsFormatException()
{
int i = 123;
Assert.Throws<FormatException>(() => i.ToString("Y")); // Invalid format
Assert.Throws<FormatException>(() => i.ToString("Y", null)); // Invalid format
}
public static IEnumerable<object[]> Parse_Valid_TestData()
{
NumberFormatInfo samePositiveNegativeFormat = new NumberFormatInfo()
{
PositiveSign = "|",
NegativeSign = "|"
};
NumberFormatInfo emptyPositiveFormat = new NumberFormatInfo() { PositiveSign = "" };
NumberFormatInfo emptyNegativeFormat = new NumberFormatInfo() { NegativeSign = "" };
// None
yield return new object[] { "0", NumberStyles.None, null, 0 };
yield return new object[] { "123", NumberStyles.None, null, 123 };
yield return new object[] { "2147483647", NumberStyles.None, null, 2147483647 };
yield return new object[] { "123\0\0", NumberStyles.None, null, 123 };
// HexNumber
yield return new object[] { "123", NumberStyles.HexNumber, null, 0x123 };
yield return new object[] { "abc", NumberStyles.HexNumber, null, 0xabc };
yield return new object[] { "ABC", NumberStyles.HexNumber, null, 0xabc };
yield return new object[] { "12", NumberStyles.HexNumber, null, 0x12 };
yield return new object[] { "80000000", NumberStyles.HexNumber, null, -2147483648 };
yield return new object[] { "FFFFFFFF", NumberStyles.HexNumber, null, -1 };
// Currency
NumberFormatInfo currencyFormat = new NumberFormatInfo()
{
CurrencySymbol = "$",
CurrencyGroupSeparator = "|",
NumberGroupSeparator = "/"
};
yield return new object[] { "$1|000", NumberStyles.Currency, currencyFormat, 1000 };
yield return new object[] { "$1000", NumberStyles.Currency, currencyFormat, 1000 };
yield return new object[] { "$ 1000", NumberStyles.Currency, currencyFormat, 1000 };
yield return new object[] { "1000", NumberStyles.Currency, currencyFormat, 1000 };
yield return new object[] { "$(1000)", NumberStyles.Currency, currencyFormat, -1000};
yield return new object[] { "($1000)", NumberStyles.Currency, currencyFormat, -1000 };
yield return new object[] { "$-1000", NumberStyles.Currency, currencyFormat, -1000 };
yield return new object[] { "-$1000", NumberStyles.Currency, currencyFormat, -1000 };
NumberFormatInfo emptyCurrencyFormat = new NumberFormatInfo() { CurrencySymbol = "" };
yield return new object[] { "100", NumberStyles.Currency, emptyCurrencyFormat, 100 };
// If CurrencySymbol and Negative are the same, NegativeSign is preferred
NumberFormatInfo sameCurrencyNegativeSignFormat = new NumberFormatInfo()
{
NegativeSign = "|",
CurrencySymbol = "|"
};
yield return new object[] { "|1000", NumberStyles.AllowCurrencySymbol | NumberStyles.AllowLeadingSign, sameCurrencyNegativeSignFormat, -1000 };
// Any
yield return new object[] { "123", NumberStyles.Any, null, 123 };
// AllowLeadingSign
yield return new object[] { "-2147483648", NumberStyles.AllowLeadingSign, null, -2147483648 };
yield return new object[] { "-123", NumberStyles.AllowLeadingSign, null, -123 };
yield return new object[] { "+0", NumberStyles.AllowLeadingSign, null, 0 };
yield return new object[] { "-0", NumberStyles.AllowLeadingSign, null, 0 };
yield return new object[] { "+123", NumberStyles.AllowLeadingSign, null, 123 };
// If PositiveSign and NegativeSign are the same, PositiveSign is preferred
yield return new object[] { "|123", NumberStyles.AllowLeadingSign, samePositiveNegativeFormat, 123 };
// Empty PositiveSign or NegativeSign
yield return new object[] { "100", NumberStyles.AllowLeadingSign, emptyPositiveFormat, 100 };
yield return new object[] { "100", NumberStyles.AllowLeadingSign, emptyNegativeFormat, 100 };
// AllowTrailingSign
yield return new object[] { "123", NumberStyles.AllowTrailingSign, null, 123 };
yield return new object[] { "123+", NumberStyles.AllowTrailingSign, null, 123 };
yield return new object[] { "123-", NumberStyles.AllowTrailingSign, null, -123 };
// If PositiveSign and NegativeSign are the same, PositiveSign is preferred
yield return new object[] { "123|", NumberStyles.AllowTrailingSign, samePositiveNegativeFormat, 123 };
// Empty PositiveSign or NegativeSign
yield return new object[] { "100", NumberStyles.AllowTrailingSign, emptyPositiveFormat, 100 };
yield return new object[] { "100", NumberStyles.AllowTrailingSign, emptyNegativeFormat, 100 };
// AllowLeadingWhite and AllowTrailingWhite
yield return new object[] { "123 ", NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, null, 123 };
yield return new object[] { " 123", NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, null, 123 };
yield return new object[] { " 123 ", NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, null, 123 };
// AllowThousands
NumberFormatInfo thousandsFormat = new NumberFormatInfo() { NumberGroupSeparator = "|" };
yield return new object[] { "1000", NumberStyles.AllowThousands, thousandsFormat, 1000 };
yield return new object[] { "1|0|0|0", NumberStyles.AllowThousands, thousandsFormat, 1000 };
yield return new object[] { "1|||", NumberStyles.AllowThousands, thousandsFormat, 1 };
NumberFormatInfo integerNumberSeparatorFormat = new NumberFormatInfo() { NumberGroupSeparator = "1" };
yield return new object[] { "1111", NumberStyles.AllowThousands, integerNumberSeparatorFormat, 1111 };
// AllowExponent
yield return new object[] { "1E2", NumberStyles.AllowExponent, null, 100 };
yield return new object[] { "1E+2", NumberStyles.AllowExponent, null, 100 };
yield return new object[] { "1e2", NumberStyles.AllowExponent, null, 100 };
yield return new object[] { "1E0", NumberStyles.AllowExponent, null, 1 };
yield return new object[] { "(1E2)", NumberStyles.AllowExponent | NumberStyles.AllowParentheses, null, -100 };
yield return new object[] { "-1E2", NumberStyles.AllowExponent | NumberStyles.AllowLeadingSign, null, -100 };
NumberFormatInfo negativeFormat = new NumberFormatInfo() { PositiveSign = "|" };
yield return new object[] { "1E|2", NumberStyles.AllowExponent, negativeFormat, 100 };
// AllowParentheses
yield return new object[] { "123", NumberStyles.AllowParentheses, null, 123 };
yield return new object[] { "(123)", NumberStyles.AllowParentheses, null, -123 };
// AllowDecimalPoint
NumberFormatInfo decimalFormat = new NumberFormatInfo() { NumberDecimalSeparator = "|" };
yield return new object[] { "67|", NumberStyles.AllowDecimalPoint, decimalFormat, 67 };
// NumberFormatInfo has a custom property with length > 1
NumberFormatInfo integerCurrencyFormat = new NumberFormatInfo() { CurrencySymbol = "123" };
yield return new object[] { "123123", NumberStyles.AllowCurrencySymbol, integerCurrencyFormat, 123 };
NumberFormatInfo integerPositiveSignFormat = new NumberFormatInfo() { PositiveSign = "123" };
yield return new object[] { "123123", NumberStyles.AllowLeadingSign, integerPositiveSignFormat, 123 };
}
[Theory]
[MemberData(nameof(Parse_Valid_TestData))]
public static void Parse(string value, NumberStyles style, IFormatProvider provider, int expected)
{
bool isDefaultProvider = provider == null || provider == NumberFormatInfo.CurrentInfo;
int result;
if ((style & ~NumberStyles.Integer) == 0 && style != NumberStyles.None)
{
// Use Parse(string) or Parse(string, IFormatProvider)
if (isDefaultProvider)
{
Assert.True(int.TryParse(value, out result));
Assert.Equal(expected, result);
Assert.Equal(expected, int.Parse(value));
}
Assert.Equal(expected, int.Parse(value, provider));
}
// Use Parse(string, NumberStyles, IFormatProvider)
Assert.True(int.TryParse(value, style, provider, out result));
Assert.Equal(expected, result);
Assert.Equal(expected, int.Parse(value, style, provider));
if (isDefaultProvider)
{
// Use Parse(string, NumberStyles) or Parse(string, NumberStyles, IFormatProvider)
Assert.True(int.TryParse(value, style, NumberFormatInfo.CurrentInfo, out result));
Assert.Equal(expected, result);
Assert.Equal(expected, int.Parse(value, style));
Assert.Equal(expected, int.Parse(value, style, NumberFormatInfo.CurrentInfo));
}
}
public static IEnumerable<object[]> Parse_Invalid_TestData()
{
// String is null, empty or entirely whitespace
yield return new object[] { null, NumberStyles.Integer, null, typeof(ArgumentNullException) };
yield return new object[] { null, NumberStyles.Any, null, typeof(ArgumentNullException) };
yield return new object[] { "", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { "", NumberStyles.Any, null, typeof(FormatException) };
yield return new object[] { " \t \n \r ", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { " \t \n \r ", NumberStyles.Any, null, typeof(FormatException) };
// String is garbage
yield return new object[] { "Garbage", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { "Garbage", NumberStyles.Any, null, typeof(FormatException) };
// String has leading zeros
yield return new object[] { "\0\0123", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { "\0\0123", NumberStyles.Any, null, typeof(FormatException) };
// String has internal zeros
yield return new object[] { "1\023", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { "1\023", NumberStyles.Any, null, typeof(FormatException) };
// Integer doesn't allow hex, exponents, paretheses, currency, thousands, decimal
yield return new object[] { "abc", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { "1E23", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { "(123)", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { 1000.ToString("C0"), NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { 1000.ToString("N0"), NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { 678.90.ToString("F2"), NumberStyles.Integer, null, typeof(FormatException) };
// HexNumber
yield return new object[] { "0xabc", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "&habc", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "G1", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "g1", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "+abc", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "-abc", NumberStyles.HexNumber, null, typeof(FormatException) };
// None doesn't allow hex or leading or trailing whitespace
yield return new object[] { "abc", NumberStyles.None, null, typeof(FormatException) };
yield return new object[] { "123 ", NumberStyles.None, null, typeof(FormatException) };
yield return new object[] { " 123", NumberStyles.None, null, typeof(FormatException) };
yield return new object[] { " 123 ", NumberStyles.None, null, typeof(FormatException) };
// AllowLeadingSign
yield return new object[] { "+", NumberStyles.AllowLeadingSign, null, typeof(FormatException) };
yield return new object[] { "-", NumberStyles.AllowLeadingSign, null, typeof(FormatException) };
yield return new object[] { "+-123", NumberStyles.AllowLeadingSign, null, typeof(FormatException) };
yield return new object[] { "-+123", NumberStyles.AllowLeadingSign, null, typeof(FormatException) };
yield return new object[] { "- 123", NumberStyles.AllowLeadingSign, null, typeof(FormatException) };
yield return new object[] { "+ 123", NumberStyles.AllowLeadingSign, null, typeof(FormatException) };
// AllowTrailingSign
yield return new object[] { "123-+", NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
yield return new object[] { "123+-", NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
yield return new object[] { "123 -", NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
yield return new object[] { "123 +", NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
// Parentheses has priority over CurrencySymbol and PositiveSign
NumberFormatInfo currencyNegativeParenthesesFormat = new NumberFormatInfo()
{
CurrencySymbol = "(",
PositiveSign = "))"
};
yield return new object[] { "(100))", NumberStyles.AllowParentheses | NumberStyles.AllowCurrencySymbol | NumberStyles.AllowTrailingSign, currencyNegativeParenthesesFormat, typeof(FormatException) };
// AllowTrailingSign and AllowLeadingSign
yield return new object[] { "+123+", NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
yield return new object[] { "+123-", NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
yield return new object[] { "-123+", NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
yield return new object[] { "-123-", NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
// AllowLeadingSign and AllowParentheses
yield return new object[] { "-(1000)", NumberStyles.AllowLeadingSign | NumberStyles.AllowParentheses, null, typeof(FormatException) };
yield return new object[] { "(-1000)", NumberStyles.AllowLeadingSign | NumberStyles.AllowParentheses, null, typeof(FormatException) };
// AllowLeadingWhite
yield return new object[] { "1 ", NumberStyles.AllowLeadingWhite, null, typeof(FormatException) };
yield return new object[] { " 1 ", NumberStyles.AllowLeadingWhite, null, typeof(FormatException) };
// AllowTrailingWhite
yield return new object[] { " 1 ", NumberStyles.AllowTrailingWhite, null, typeof(FormatException) };
yield return new object[] { " 1", NumberStyles.AllowTrailingWhite, null, typeof(FormatException) };
// AllowThousands
NumberFormatInfo thousandsFormat = new NumberFormatInfo() { NumberGroupSeparator = "|" };
yield return new object[] { "|||1", NumberStyles.AllowThousands, null, typeof(FormatException) };
// AllowExponent
yield return new object[] { "65E", NumberStyles.AllowExponent, null, typeof(FormatException) };
yield return new object[] { "65E10", NumberStyles.AllowExponent, null, typeof(OverflowException) };
yield return new object[] { "65E+10", NumberStyles.AllowExponent, null, typeof(OverflowException) };
yield return new object[] { "65E-1", NumberStyles.AllowExponent, null, typeof(OverflowException) };
// AllowDecimalPoint
NumberFormatInfo decimalFormat = new NumberFormatInfo() { NumberDecimalSeparator = "." };
yield return new object[] { (67.9).ToString(), NumberStyles.AllowDecimalPoint, null, typeof(OverflowException) };
// Parsing integers doesn't allow NaN, PositiveInfinity or NegativeInfinity
NumberFormatInfo doubleFormat = new NumberFormatInfo()
{
NaNSymbol = "NaN",
PositiveInfinitySymbol = "Infinity",
NegativeInfinitySymbol = "-Infinity"
};
yield return new object[] { "NaN", NumberStyles.Any, doubleFormat, typeof(FormatException) };
yield return new object[] { "Infinity", NumberStyles.Any, doubleFormat, typeof(FormatException) };
yield return new object[] { "-Infinity", NumberStyles.Any, doubleFormat, typeof(FormatException) };
// NumberFormatInfo has a custom property with length > 1
NumberFormatInfo integerCurrencyFormat = new NumberFormatInfo() { CurrencySymbol = "123" };
yield return new object[] { "123", NumberStyles.AllowCurrencySymbol, integerCurrencyFormat, typeof(FormatException) };
NumberFormatInfo integerPositiveSignFormat = new NumberFormatInfo() { PositiveSign = "123" };
yield return new object[] { "123", NumberStyles.AllowLeadingSign, integerPositiveSignFormat, typeof(FormatException) };
// Not in range of Int32
yield return new object[] { "2147483648", NumberStyles.Any, null, typeof(OverflowException) };
yield return new object[] { "2147483648", NumberStyles.Integer, null, typeof(OverflowException) };
yield return new object[] { "-2147483649", NumberStyles.Any, null, typeof(OverflowException) };
yield return new object[] { "-2147483649", NumberStyles.Integer, null, typeof(OverflowException) };
yield return new object[] { "2147483649-", NumberStyles.AllowTrailingSign, null, typeof(OverflowException) };
yield return new object[] { "(2147483649)", NumberStyles.AllowParentheses, null, typeof(OverflowException) };
yield return new object[] { "2E10", NumberStyles.AllowExponent, null, typeof(OverflowException) };
yield return new object[] { "800000000", NumberStyles.AllowHexSpecifier, null, typeof(OverflowException) };
yield return new object[] { "9223372036854775808", NumberStyles.Integer, null, typeof(OverflowException) };
yield return new object[] { "-9223372036854775809", NumberStyles.Integer, null, typeof(OverflowException) };
yield return new object[] { "8000000000000000", NumberStyles.AllowHexSpecifier, null, typeof(OverflowException) };
}
[Theory]
[MemberData(nameof(Parse_Invalid_TestData))]
public static void Parse_Invalid(string value, NumberStyles style, IFormatProvider provider, Type exceptionType)
{
bool isDefaultProvider = provider == null || provider == NumberFormatInfo.CurrentInfo;
int result;
if ((style & ~NumberStyles.Integer) == 0 && style != NumberStyles.None && (style & NumberStyles.AllowLeadingWhite) == (style & NumberStyles.AllowTrailingWhite))
{
// Use Parse(string) or Parse(string, IFormatProvider)
if (isDefaultProvider)
{
Assert.False(int.TryParse(value, out result));
Assert.Equal(default(int), result);
Assert.Throws(exceptionType, () => int.Parse(value));
}
Assert.Throws(exceptionType, () => int.Parse(value, provider));
}
// Use Parse(string, NumberStyles, IFormatProvider)
Assert.False(int.TryParse(value, style, provider, out result));
Assert.Equal(default(int), result);
Assert.Throws(exceptionType, () => int.Parse(value, style, provider));
if (isDefaultProvider)
{
// Use Parse(string, NumberStyles) or Parse(string, NumberStyles, IFormatProvider)
Assert.False(int.TryParse(value, style, NumberFormatInfo.CurrentInfo, out result));
Assert.Equal(default(int), result);
Assert.Throws(exceptionType, () => int.Parse(value, style));
Assert.Throws(exceptionType, () => int.Parse(value, style, NumberFormatInfo.CurrentInfo));
}
}
[Theory]
[InlineData(NumberStyles.HexNumber | NumberStyles.AllowParentheses)]
[InlineData(unchecked((NumberStyles)0xFFFFFC00))]
public static void TryParse_InvalidNumberStyle_ThrowsArgumentException(NumberStyles style)
{
int result = 0;
Assert.Throws<ArgumentException>(() => int.TryParse("1", style, null, out result));
Assert.Equal(default(int), result);
Assert.Throws<ArgumentException>(() => int.Parse("1", style));
Assert.Throws<ArgumentException>(() => int.Parse("1", style, null));
}
}
}
| |
/*
* MindTouch Dream - a distributed REST framework
* Copyright (C) 2006-2014 MindTouch, Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit mindtouch.com;
* please review the licensing section.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using MindTouch.IO;
using MindTouch.Xml;
namespace MindTouch.Dream {
/// <summary>
/// Provides static helper methods for Php Http interop.
/// </summary>
public static class PhpUtil {
//--- Class Fields ---
/// <summary>
/// Unix "Epoch" time, i.e. seconds since January 1st, 1970, UTC.
/// </summary>
public static readonly DateTime UnixTimeZero = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private static Regex _dollarParamsRegex = new Regex(@"(?<param>\$\d+)", RegexOptions.Compiled | RegexOptions.CultureInvariant);
//--- Class Methods ---
/// <summary>
/// Convert a php $n placeholder convention format string to a .NET format string.
/// </summary>
/// <param name="paramsString"></param>
/// <returns></returns>
public static string ConvertToFormatString(string paramsString) {
// replace all string parameters of the form $x with {x-1}, where x is an integer
paramsString = _dollarParamsRegex.Replace(paramsString, m => {
int paramValue = 0;
if(Int32.TryParse(m.Groups["param"].Value.Substring(1), out paramValue)) {
return "{" + (paramValue - 1) + "}";
} else {
return m.Groups["param"].Value;
}
});
return paramsString;
}
/// <summary>
/// Convert an xml document into Php object notation.
/// </summary>
/// <param name="doc">Document to convert.</param>
/// <param name="stream">Stream to write converted document to.</param>
/// <param name="encoding">Encoding to use for output.</param>
public static void WritePhp(XDoc doc, Stream stream, Encoding encoding) {
if(doc.IsEmpty) {
stream.Write(encoding, "a:0:{}");
return;
} else {
List<XmlNode> nodeList = new List<XmlNode>();
foreach(XDoc item in doc) {
nodeList.Add(item.AsXmlNode);
}
IDictionary<string, List<XmlNode>> list = XDocUtil.CollapseNodeList(nodeList);
stream.Write(encoding, "a:{0}:{{", list.Count);
WritePhp(list, stream, encoding);
stream.Write(encoding, "}");
}
}
private static void WritePhp(XmlNode node, Stream stream, Encoding encoding) {
IDictionary<string, List<XmlNode>> list;
switch(node.NodeType) {
case XmlNodeType.Document:
list = XDocUtil.CollapseNodeList(node.ChildNodes);
stream.Write(encoding, "a:{0}:{{", list.Count);
WritePhp(list, stream, encoding);
stream.Write(encoding, "}");
break;
case XmlNodeType.Element:
// check if we have the common case of a simple node (tag and text only without attributes, or tag only without text or attributes)
if((node.Attributes.Count == 0) && (node.ChildNodes.Count == 0)) {
Serialize(string.Empty, stream, encoding);
stream.Write(encoding, ";");
} else if((node.Attributes.Count > 0) || (node.ChildNodes.Count != 1) || (node.ChildNodes[0].NodeType != XmlNodeType.Text)) {
list = XDocUtil.CollapseNodeList(node.ChildNodes);
stream.Write(encoding, "a:{0}:{{", node.Attributes.Count + list.Count);
foreach(XmlNode sub in node.Attributes) {
WritePhp(sub, stream, encoding);
}
WritePhp(list, stream, encoding);
stream.Write(encoding, "}");
} else {
WritePhp(node.ChildNodes[0], stream, encoding);
}
break;
case XmlNodeType.Text:
Serialize(node.Value, stream, encoding);
stream.Write(encoding, ";");
break;
case XmlNodeType.Attribute:
Serialize("@" + node.Name, stream, encoding);
stream.Write(encoding, ";");
Serialize(node.Value, stream, encoding);
stream.Write(encoding, ";");
break;
}
}
private static void WritePhp(IDictionary<string, List<XmlNode>> list, Stream stream, Encoding encoding) {
foreach(KeyValuePair<string, List<XmlNode>> entry in list) {
Serialize(entry.Key, stream, encoding);
stream.Write(encoding, ";");
if(entry.Value.Count > 1) {
stream.Write(encoding, "a:{0}:{{", entry.Value.Count);
int index = 0;
foreach(XmlNode node in entry.Value) {
Serialize(index, stream, encoding);
stream.Write(encoding, ";");
if(node.NodeType == XmlNodeType.Text) {
Serialize(node.Value, stream, encoding);
stream.Write(encoding, ";");
} else {
WritePhp(node, stream, encoding);
}
++index;
}
stream.Write(encoding, "}");
} else {
WritePhp(entry.Value[0], stream, encoding);
}
}
}
private static void SerializeObject(object arg, Stream stream, Encoding encoding) {
if(arg == null) {
stream.Write(encoding, "N");
} else if(arg is string) {
Serialize((string)arg, stream, encoding);
} else if(arg is int || arg is long) {
Serialize((long)arg, stream, encoding);
} else if(arg is float || arg is double) {
Serialize((double)arg, stream, encoding);
} else if(arg is bool) {
Serialize((bool)arg, stream, encoding);
} else if(arg is XDoc) {
WritePhp((XDoc)arg, stream, encoding);
} else if(arg is System.Collections.IList) {
Serialize((System.Collections.IList)arg, stream, encoding);
} else {
throw new NotSupportedException("Type " + arg.GetType() + " not supported");
}
}
private static void Serialize(string arg, Stream stream, Encoding encoding) {
stream.Write(encoding, "s:{0}:\"", encoding.GetByteCount(arg));
stream.Write(encoding, arg);
stream.Write(encoding, "\"");
}
private static void Serialize(long arg, Stream stream, Encoding encoding) {
stream.Write(encoding, "i:");
stream.Write(encoding, arg.ToInvariantString());
}
private static void Serialize(bool arg, Stream stream, Encoding encoding) {
stream.Write(encoding, "b:");
stream.Write(encoding, arg ? "1" : "0");
}
private static void Serialize(double arg, Stream stream, Encoding encoding) {
stream.Write(encoding, "d:");
stream.Write(encoding, arg.ToInvariantString());
}
private static void Serialize(System.Collections.IList list, Stream stream, Encoding encoding) {
stream.Write(encoding, "a:{0}:{{", list.Count);
for(int i = 0; i < list.Count; ++i) {
stream.Write(encoding, "i:{0};", i);
SerializeObject(list[i], stream, encoding);
stream.Write(encoding, ";");
}
stream.Write(encoding, ";");
}
}
}
| |
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace System.Threading.Tasks
{
public class Task {
static Task()
{
var tcs = new TaskCompletionSource();
tcs.TrySetCompleted();
CompletedTask = tcs.Task;
CompletedWithNull = Task<object>.FromResult((object)null);
CompletedWithTrue = Task<bool>.FromResult(true);
CompletedWithFalse = Task<bool>.FromResult(false);
}
// Actual task, can be null.
internal IEnumerator userCoroutine;
// Scheduler coroutine, can be null.
internal IEnumerator schedulerCoroutine;
// Scheduler that is set to run this coroutine;
internal TaskScheduler scheduler;
// Set task as completed after userCoroutine execution.
internal bool autoComplete = false;
// Task cancellation token.
internal CancellationToken cancellation;
/// <summary>
/// Creates a Task<TResult> that's completed
/// successfully with the specified result.
/// </summary>
/// <param name="result">The result to store into the completed task. </param>
/// <returns>The successfully completed task.</returns>
public static Task<T> FromResult<T>(T result) {
if (typeof(T) == typeof(object)) {
if (result == null && CompletedWithNull != null) {
return (Task<T>)(object)CompletedWithNull;
}
}
if (typeof(T) == typeof(bool)) {
if ((bool)(object)result && CompletedWithTrue != null) {
return (Task<T>)(object)CompletedWithTrue;
}
else if ((bool)(object)result && CompletedWithFalse != null) {
return (Task<T>)(object)CompletedWithFalse;
}
}
var t = new TaskCompletionSource<T>();
t.TrySetResult(result);
return t.Task;
}
/// <summary>
/// Creates a Task that's completed with a specified exception.
/// </summary>
/// <param name="ex">The exception with which to complete the task.</param>
/// <returns>The faulted task.</returns>
public static Task FromException(Exception ex) {
var t = new TaskCompletionSource();
t.SetException(ex);
return t.Task;
}
/// <summary>
/// Creates a Task<T> that's completed with a specified exception.
/// </summary>
/// <param name="ex">The exception with which to complete the task.</param>
/// <returns>The faulted task.</returns>
public static Task<T> FromException<T>(Exception ex) {
var t = new TaskCompletionSource<T>();
t.SetException(ex);
return t.Task;
}
public class TaskFactory {
public Task StartNew(IEnumerator coroutine, TaskScheduler scheduler = null, CancellationToken cancellation = default(CancellationToken)) {
var tcs = new TaskCompletionSource();
tcs.Task.userCoroutine = coroutine;
tcs.Task.autoComplete = true;
tcs.Task.cancellation = cancellation;
scheduler = scheduler ?? TaskScheduler.Current;
scheduler.QueueTask (tcs.Task);
return tcs.Task;
}
public Task StartNew(Func<TaskCompletionSource, IEnumerator> asyncMethod, TaskScheduler scheduler = null, CancellationToken cancellation = default(CancellationToken)) {
var tcs = new TaskCompletionSource ();
tcs.Task.userCoroutine = asyncMethod(tcs);
tcs.Task.cancellation = cancellation;
scheduler = scheduler ?? TaskScheduler.Current;
scheduler.QueueTask (tcs.Task);
return tcs.Task;
}
public Task<TResult> StartNew<TResult>(Func<TaskCompletionSource<TResult>, IEnumerator> asyncMethod, TaskScheduler scheduler = null, CancellationToken cancellation = default(CancellationToken)) {
var tcs = new TaskCompletionSource<TResult> ();
tcs.Task.userCoroutine = asyncMethod(tcs);
tcs.Task.cancellation = cancellation;
scheduler = scheduler ?? TaskScheduler.Current;
scheduler.QueueTask (tcs.Task);
return tcs.Task;
}
}
public static TaskFactory Factory = new TaskFactory();
/// <summary>
/// Creates a task that completes after a specified time interval.
/// </summary>
/// <param name="delay">The time span to wait before completing the returned task, or TimeSpan.FromMilliseconds(-1) to wait indefinitely.</param>
/// <returns>A task that represents the time delay.</returns>
public static Task Delay(TimeSpan delay, CancellationToken cancellation = default(CancellationToken)) {
return Delay((int)delay.TotalMilliseconds, cancellation);
}
/// <summary>
/// Creates a task that completes after a time delay.
/// </summary>
/// <param name="millisecondsDelay">The number of milliseconds to wait before completing the returned task, or -1 to wait indefinitely.</param>
/// <returns>A task that represents the time delay.</returns>
public static Task Delay(int millisecondsDelay, CancellationToken cancellation = default(CancellationToken)) {
if (millisecondsDelay < -1) {
throw new ArgumentOutOfRangeException("millisecondsDelay");
}
if (millisecondsDelay == -1) {
var tcs = new TaskCompletionSource();
return tcs.Task;
}
var op = new YieldOnce(new WaitForSeconds(millisecondsDelay / 1000.0f));
return Task.Factory.StartNew(op);
}
/// <summary>
/// Creates an awaitable task that asynchronously
/// yields back to the current context when awaited.
/// </summary>
/// <returns></returns>
public static Task Yield() {
var op = new YieldOnce((object)null);
return Task.Factory.StartNew(op);
}
/// <summary>
/// Creates a task that will complete when all of the
/// Task<TResult> objects in an array have completed.
/// </summary>
/// <param name="tasks">The tasks to wait on for completion.</param>
/// <returns>A task that represents the completion of all of the supplied tasks.</returns>
public static Task<TResult[]> WhenAll<TResult>(params Task<TResult>[] tasks)
{
return Task.WhenAll((Task[])tasks).ContinueWith(t => {
t.AssertCompletion();
var res = new TResult[tasks.Length];
for (int i = 0; i < tasks.Length; i++) {
res[i] = tasks[i].Result;
}
return res;
});
}
/// <summary>
/// Creates a task that will complete when any of the supplied tasks have completed.
/// </summary>
/// <param name="tasks">The tasks to wait on for completion.</param>
/// <returns>A task that represents the completion of one of the supplied tasks. The return task's Result is the task that completed.</returns>
public static Task<Task<TResult>> WhenAny<TResult>(params Task<TResult>[] tasks) {
return WhenAny((Task[])tasks).ContinueWith(t => {
return (Task<TResult>)t.Result;
});
}
/// <summary>
/// Creates a task that will complete when any of the supplied tasks have completed.
/// </summary>
/// <param name="tasks">The tasks to wait on for completion.</param>
/// <returns>A task that represents the completion of one of the supplied tasks. The return task's Result is the task that completed.</returns>
public static Task<Task> WhenAny(params Task[] tasks) {
if (tasks == null || tasks.Length <= 0 || tasks.Contains(null)) {
throw new ArgumentException("tasks");
}
var tcs = new TaskCompletionSource<Task>();
Action<Task> onComplete = t => {
lock (tcs) {
tcs.TrySetCompleted(t);
}
};
foreach (var t in tasks) {
t.ContinueWith(onComplete);
}
return tcs.Task;
}
/// <summary>
/// Creates a task that will complete when all
/// of the Task objects in an array have completed.
/// </summary>
/// <param name="tasks">The tasks to wait on for completion.</param>
/// <returns>A task that represents the completion of all of the supplied tasks.</returns>
public static Task WhenAll(params Task[] tasks)
{
if (tasks == null || tasks.Contains(null)) {
throw new ArgumentException("tasks");
}
if (tasks.Length <= 0) {
return Task.CompletedTask;
}
List<Exception> errors = new List<Exception>();
int remaining = tasks.Length;
var tcs = new TaskCompletionSource();
Action<Task> onComplete = t =>
{
if (t.Status != TaskStatus.RanToCompletion)
errors.Add(t.Error);
lock (tcs) {
remaining--;
if (remaining <= 0)
{
if (errors.Any())
tcs.TrySetException(new AggregateException(errors));
else
tcs.TrySetCompleted();
}
}
};
foreach (var t in tasks) {
t.ContinueWith(onComplete);
}
return tcs.Task;
}
/// <summary>
/// Gets a task that has already completed successfully.
/// </summary>
public static readonly Task CompletedTask;
readonly static Task<bool> CompletedWithTrue, CompletedWithFalse;
readonly static Task<object> CompletedWithNull;
internal readonly TaskCompletionSource source;
internal Task(TaskCompletionSource source) {
this.source = source;
}
public Task ContinueWith(Action<Task> action, TaskScheduler scheduler = null) {
return this.ContinueWithCR(t => new RunOnce(() => action(t)), scheduler);
}
public Task<T> ContinueWith<T>(Func<Task, T> action, TaskScheduler scheduler = null) {
return this.ContinueWithCR<T>((tcs, t) => new RunOnce(() => tcs.TrySetResult(action(t))), scheduler);
}
public TaskStatus Status {
get { return ((ITaskCompletionSourceController)source).Status; }
}
public Exception Error {
get { return source.Error; }
}
/// <summary>
/// Gets whether this Task instance has completed execution due to being canceled.
/// </summary>
/// <returns>true if the task has completed due to being canceled; otherwise false.</returns>
public bool IsCanceled {
get { return source.Status == TaskStatus.Canceled; }
}
/// <summary>
/// Gets whether this Task has completed.
/// </summary>
/// <returns>true if the task has completed; otherwise false.</returns>
public bool IsCompleted {
get { return source.Status > TaskStatus.Running; }
}
/// <summary>
/// Gets whether the Task completed due to an unhandled exception.
/// </summary>
/// <returns>true if the task has thrown an unhandled exception; otherwise false.</returns>
public bool IsFaulted {
get { return source.Status == TaskStatus.Faulted; }
}
public void AssertCompletion()
{
if (Error != null) {
throw Error;
}
}
}
public class Task<T> : Task
{
internal readonly new TaskCompletionSource<T> source;
public Task(TaskCompletionSource<T> source) : base(source) {
this.source = source;
}
public T Result {
get { return source.Result; }
}
public Task ContinueWith(Action<Task<T>> action, TaskScheduler scheduler = null) {
return base.ContinueWith(t => action((Task<T>)t), scheduler);
}
public Task<TR> ContinueWith<TR>(Func<Task<T>, TR> action, TaskScheduler scheduler = null) {
return base.ContinueWith(t => action((Task<T>)t), scheduler);
}
}
}
| |
using System;
using System.Reflection;
using System.Collections;
using Server;
using Server.Targeting;
using Server.Network;
using Server.Commands;
using Server.Commands.Generic;
namespace Server.Gumps
{
public class XmlSetPoint2DGump : Gump
{
private PropertyInfo m_Property;
private Mobile m_Mobile;
private object m_Object;
private Stack m_Stack;
private int m_Page;
private ArrayList m_List;
public static readonly bool OldStyle = PropsConfig.OldStyle;
public static readonly int GumpOffsetX = PropsConfig.GumpOffsetX;
public static readonly int GumpOffsetY = PropsConfig.GumpOffsetY;
public static readonly int TextHue = PropsConfig.TextHue;
public static readonly int TextOffsetX = PropsConfig.TextOffsetX;
public static readonly int OffsetGumpID = PropsConfig.OffsetGumpID;
public static readonly int HeaderGumpID = PropsConfig.HeaderGumpID;
public static readonly int EntryGumpID = PropsConfig.EntryGumpID;
public static readonly int BackGumpID = PropsConfig.BackGumpID;
public static readonly int SetGumpID = PropsConfig.SetGumpID;
public static readonly int SetWidth = PropsConfig.SetWidth;
public static readonly int SetOffsetX = PropsConfig.SetOffsetX, SetOffsetY = PropsConfig.SetOffsetY;
public static readonly int SetButtonID1 = PropsConfig.SetButtonID1;
public static readonly int SetButtonID2 = PropsConfig.SetButtonID2;
public static readonly int PrevWidth = PropsConfig.PrevWidth;
public static readonly int PrevOffsetX = PropsConfig.PrevOffsetX, PrevOffsetY = PropsConfig.PrevOffsetY;
public static readonly int PrevButtonID1 = PropsConfig.PrevButtonID1;
public static readonly int PrevButtonID2 = PropsConfig.PrevButtonID2;
public static readonly int NextWidth = PropsConfig.NextWidth;
public static readonly int NextOffsetX = PropsConfig.NextOffsetX, NextOffsetY = PropsConfig.NextOffsetY;
public static readonly int NextButtonID1 = PropsConfig.NextButtonID1;
public static readonly int NextButtonID2 = PropsConfig.NextButtonID2;
public static readonly int OffsetSize = PropsConfig.OffsetSize;
public static readonly int EntryHeight = PropsConfig.EntryHeight;
public static readonly int BorderSize = PropsConfig.BorderSize;
private static readonly int CoordWidth = 105;
private static readonly int EntryWidth = CoordWidth + OffsetSize + CoordWidth;
private static readonly int TotalWidth = OffsetSize + EntryWidth + OffsetSize + SetWidth + OffsetSize;
private static readonly int TotalHeight = OffsetSize + (4 * (EntryHeight + OffsetSize));
private static readonly int BackWidth = BorderSize + TotalWidth + BorderSize;
private static readonly int BackHeight = BorderSize + TotalHeight + BorderSize;
public XmlSetPoint2DGump( PropertyInfo prop, Mobile mobile, object o, Stack stack, int page, ArrayList list ) : base( GumpOffsetX, GumpOffsetY )
{
m_Property = prop;
m_Mobile = mobile;
m_Object = o;
m_Stack = stack;
m_Page = page;
m_List = list;
Point2D p = (Point2D)prop.GetValue( o, null );
AddPage( 0 );
AddBackground( 0, 0, BackWidth, BackHeight, BackGumpID );
AddImageTiled( BorderSize, BorderSize, TotalWidth - (OldStyle ? SetWidth + OffsetSize : 0), TotalHeight, OffsetGumpID );
int x = BorderSize + OffsetSize;
int y = BorderSize + OffsetSize;
AddImageTiled( x, y, EntryWidth, EntryHeight, EntryGumpID );
AddLabelCropped( x + TextOffsetX, y, EntryWidth - TextOffsetX, EntryHeight, TextHue, prop.Name );
x += EntryWidth + OffsetSize;
if ( SetGumpID != 0 )
AddImageTiled( x, y, SetWidth, EntryHeight, SetGumpID );
x = BorderSize + OffsetSize;
y += EntryHeight + OffsetSize;
AddImageTiled( x, y, EntryWidth, EntryHeight, EntryGumpID );
AddLabelCropped( x + TextOffsetX, y, EntryWidth - TextOffsetX, EntryHeight, TextHue, "Use your location" );
x += EntryWidth + OffsetSize;
if ( SetGumpID != 0 )
AddImageTiled( x, y, SetWidth, EntryHeight, SetGumpID );
AddButton( x + SetOffsetX, y + SetOffsetY, SetButtonID1, SetButtonID2, 1, GumpButtonType.Reply, 0 );
x = BorderSize + OffsetSize;
y += EntryHeight + OffsetSize;
AddImageTiled( x, y, EntryWidth, EntryHeight, EntryGumpID );
AddLabelCropped( x + TextOffsetX, y, EntryWidth - TextOffsetX, EntryHeight, TextHue, "Target a location" );
x += EntryWidth + OffsetSize;
if ( SetGumpID != 0 )
AddImageTiled( x, y, SetWidth, EntryHeight, SetGumpID );
AddButton( x + SetOffsetX, y + SetOffsetY, SetButtonID1, SetButtonID2, 2, GumpButtonType.Reply, 0 );
x = BorderSize + OffsetSize;
y += EntryHeight + OffsetSize;
AddImageTiled( x, y, CoordWidth, EntryHeight, EntryGumpID );
AddLabelCropped( x + TextOffsetX, y, CoordWidth - TextOffsetX, EntryHeight, TextHue, "X:" );
AddTextEntry( x + 16, y, CoordWidth - 16, EntryHeight, TextHue, 0, p.X.ToString() );
x += CoordWidth + OffsetSize;
AddImageTiled( x, y, CoordWidth, EntryHeight, EntryGumpID );
AddLabelCropped( x + TextOffsetX, y, CoordWidth - TextOffsetX, EntryHeight, TextHue, "Y:" );
AddTextEntry( x + 16, y, CoordWidth - 16, EntryHeight, TextHue, 1, p.Y.ToString() );
x += CoordWidth + OffsetSize;
if ( SetGumpID != 0 )
AddImageTiled( x, y, SetWidth, EntryHeight, SetGumpID );
AddButton( x + SetOffsetX, y + SetOffsetY, SetButtonID1, SetButtonID2, 3, GumpButtonType.Reply, 0 );
}
private class InternalTarget : Target
{
private PropertyInfo m_Property;
private Mobile m_Mobile;
private object m_Object;
private Stack m_Stack;
private int m_Page;
private ArrayList m_List;
public InternalTarget( PropertyInfo prop, Mobile mobile, object o, Stack stack, int page, ArrayList list ) : base( -1, true, TargetFlags.None )
{
m_Property = prop;
m_Mobile = mobile;
m_Object = o;
m_Stack = stack;
m_Page = page;
m_List = list;
}
protected override void OnTarget( Mobile from, object targeted )
{
IPoint3D p = targeted as IPoint3D;
if ( p != null )
{
try
{
CommandLogging.LogChangeProperty( m_Mobile, m_Object, m_Property.Name, new Point2D( p ).ToString() );
m_Property.SetValue( m_Object, new Point2D( p ), null );
}
catch
{
m_Mobile.SendMessage( "An exception was caught. The property may not have changed." );
}
}
}
protected override void OnTargetFinish( Mobile from )
{
m_Mobile.SendGump( new XmlPropertiesGump( m_Mobile, m_Object, m_Stack, m_List, m_Page ) );
}
}
public override void OnResponse( NetState sender, RelayInfo info )
{
Point2D toSet;
bool shouldSet, shouldSend;
switch ( info.ButtonID )
{
case 1: // Current location
{
toSet = new Point2D( m_Mobile.Location );
shouldSet = true;
shouldSend = true;
break;
}
case 2: // Pick location
{
m_Mobile.Target = new InternalTarget( m_Property, m_Mobile, m_Object, m_Stack, m_Page, m_List );
toSet = Point2D.Zero;
shouldSet = false;
shouldSend = false;
break;
}
case 3: // Use values
{
TextRelay x = info.GetTextEntry( 0 );
TextRelay y = info.GetTextEntry( 1 );
toSet = new Point2D( x == null ? 0 : Utility.ToInt32( x.Text ), y == null ? 0 : Utility.ToInt32( y.Text ) );
shouldSet = true;
shouldSend = true;
break;
}
default:
{
toSet = Point2D.Zero;
shouldSet = false;
shouldSend = true;
break;
}
}
if ( shouldSet )
{
try
{
CommandLogging.LogChangeProperty( m_Mobile, m_Object, m_Property.Name, toSet.ToString() );
m_Property.SetValue( m_Object, toSet, null );
}
catch
{
m_Mobile.SendMessage( "An exception was caught. The property may not have changed." );
}
}
if ( shouldSend )
m_Mobile.SendGump( new XmlPropertiesGump( m_Mobile, m_Object, m_Stack, m_List, m_Page ) );
}
}
}
| |
/*
* Copyright 2002-2015 Drew Noakes
*
* Modified by Yakov Danilov <yakodani@gmail.com> for Imazen LLC (Ported from Java to C#)
* 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.
*
* More information about this project is available at:
*
* https://drewnoakes.com/code/exif/
* https://github.com/drewnoakes/metadata-extractor
*/
using System.Collections.Generic;
using Com.Drew.Lang;
using JetBrains.Annotations;
using Sharpen;
namespace Com.Drew.Imaging.Tiff
{
/// <summary>
/// Processes TIFF-formatted data, calling into client code via that
/// <see cref="TiffHandler"/>
/// interface.
/// </summary>
/// <author>Drew Noakes https://drewnoakes.com</author>
public class TiffReader
{
/// <summary>Processes a TIFF data sequence.</summary>
/// <param name="reader">
/// the
/// <see cref="Com.Drew.Lang.RandomAccessReader"/>
/// from which the data should be read
/// </param>
/// <param name="handler">
/// the
/// <see cref="TiffHandler"/>
/// that will coordinate processing and accept read values
/// </param>
/// <param name="tiffHeaderOffset">the offset within <code>reader</code> at which the TIFF header starts</param>
/// <exception cref="TiffProcessingException">
/// if an error occurred during the processing of TIFF data that could not be
/// ignored or recovered from
/// </exception>
/// <exception cref="System.IO.IOException">an error occurred while accessing the required data</exception>
/// <exception cref="Com.Drew.Imaging.Tiff.TiffProcessingException"/>
public virtual void ProcessTiff([NotNull] RandomAccessReader reader, [NotNull] TiffHandler handler, int tiffHeaderOffset)
{
// This must be either "MM" or "II".
short byteOrderIdentifier = reader.GetInt16(tiffHeaderOffset);
if (byteOrderIdentifier == unchecked((int)(0x4d4d)))
{
// "MM"
reader.SetMotorolaByteOrder(true);
}
else
{
if (byteOrderIdentifier == unchecked((int)(0x4949)))
{
// "II"
reader.SetMotorolaByteOrder(false);
}
else
{
throw new TiffProcessingException("Unclear distinction between Motorola/Intel byte ordering: " + byteOrderIdentifier);
}
}
// Check the next two values for correctness.
int tiffMarker = reader.GetUInt16(2 + tiffHeaderOffset);
handler.SetTiffMarker(tiffMarker);
int firstIfdOffset = reader.GetInt32(4 + tiffHeaderOffset) + tiffHeaderOffset;
// David Ekholm sent a digital camera image that has this problem
// TODO getLength should be avoided as it causes RandomAccessStreamReader to read to the end of the stream
if (firstIfdOffset >= reader.GetLength() - 1)
{
handler.Warn("First IFD offset is beyond the end of the TIFF data segment -- trying default offset");
// First directory normally starts immediately after the offset bytes, so try that
firstIfdOffset = tiffHeaderOffset + 2 + 2 + 4;
}
ICollection<int?> processedIfdOffsets = new HashSet<int?>();
ProcessIfd(handler, reader, processedIfdOffsets, firstIfdOffset, tiffHeaderOffset);
handler.Completed(reader, tiffHeaderOffset);
}
/// <summary>Processes a TIFF IFD.</summary>
/// <remarks>
/// Processes a TIFF IFD.
/// IFD Header:
/// <ul>
/// <li><b>2 bytes</b> number of tags</li>
/// </ul>
/// Tag structure:
/// <ul>
/// <li><b>2 bytes</b> tag type</li>
/// <li><b>2 bytes</b> format code (values 1 to 12, inclusive)</li>
/// <li><b>4 bytes</b> component count</li>
/// <li><b>4 bytes</b> inline value, or offset pointer if too large to fit in four bytes</li>
/// </ul>
/// </remarks>
/// <param name="handler">
/// the
/// <see cref="TiffHandler"/>
/// that will coordinate processing and accept read values
/// </param>
/// <param name="reader">
/// the
/// <see cref="Com.Drew.Lang.RandomAccessReader"/>
/// from which the data should be read
/// </param>
/// <param name="processedIfdOffsets">the set of visited IFD offsets, to avoid revisiting the same IFD in an endless loop</param>
/// <param name="ifdOffset">the offset within <code>reader</code> at which the IFD data starts</param>
/// <param name="tiffHeaderOffset">the offset within <code>reader</code> at which the TIFF header starts</param>
/// <exception cref="System.IO.IOException">an error occurred while accessing the required data</exception>
public static void ProcessIfd([NotNull] TiffHandler handler, [NotNull] RandomAccessReader reader, [NotNull] ICollection<int?> processedIfdOffsets, int ifdOffset, int tiffHeaderOffset)
{
try
{
// check for directories we've already visited to avoid stack overflows when recursive/cyclic directory structures exist
if (processedIfdOffsets.Contains(Sharpen.Extensions.ValueOf(ifdOffset)))
{
return;
}
// remember that we've visited this directory so that we don't visit it again later
processedIfdOffsets.Add(ifdOffset);
if (ifdOffset >= reader.GetLength() || ifdOffset < 0)
{
handler.Error("Ignored IFD marked to start outside data segment");
return;
}
// First two bytes in the IFD are the number of tags in this directory
int dirTagCount = reader.GetUInt16(ifdOffset);
int dirLength = (2 + (12 * dirTagCount) + 4);
if (dirLength + ifdOffset > reader.GetLength())
{
handler.Error("Illegally sized IFD");
return;
}
//
// Handle each tag in this directory
//
int invalidTiffFormatCodeCount = 0;
for (int tagNumber = 0; tagNumber < dirTagCount; tagNumber++)
{
int tagOffset = CalculateTagOffset(ifdOffset, tagNumber);
// 2 bytes for the tag id
int tagId = reader.GetUInt16(tagOffset);
// 2 bytes for the format code
int formatCode = reader.GetUInt16(tagOffset + 2);
TiffDataFormat format = TiffDataFormat.FromTiffFormatCode(formatCode);
if (format == null)
{
// This error suggests that we are processing at an incorrect index and will generate
// rubbish until we go out of bounds (which may be a while). Exit now.
handler.Error("Invalid TIFF tag format code: " + formatCode);
// TODO specify threshold as a parameter, or provide some other external control over this behaviour
if (++invalidTiffFormatCodeCount > 5)
{
handler.Error("Stopping processing as too many errors seen in TIFF IFD");
return;
}
continue;
}
// 4 bytes dictate the number of components in this tag's data
int componentCount = reader.GetInt32(tagOffset + 4);
if (componentCount < 0)
{
handler.Error("Negative TIFF tag component count");
continue;
}
int byteCount = componentCount * format.GetComponentSizeBytes();
int tagValueOffset;
if (byteCount > 4)
{
// If it's bigger than 4 bytes, the dir entry contains an offset.
int offsetVal = reader.GetInt32(tagOffset + 8);
if (offsetVal + byteCount > reader.GetLength())
{
// Bogus pointer offset and / or byteCount value
handler.Error("Illegal TIFF tag pointer offset");
continue;
}
tagValueOffset = tiffHeaderOffset + offsetVal;
}
else
{
// 4 bytes or less and value is in the dir entry itself.
tagValueOffset = tagOffset + 8;
}
if (tagValueOffset < 0 || tagValueOffset > reader.GetLength())
{
handler.Error("Illegal TIFF tag pointer offset");
continue;
}
// Check that this tag isn't going to allocate outside the bounds of the data array.
// This addresses an uncommon OutOfMemoryError.
if (byteCount < 0 || tagValueOffset + byteCount > reader.GetLength())
{
handler.Error("Illegal number of bytes for TIFF tag data: " + byteCount);
continue;
}
//
// Special handling for tags that point to other IFDs
//
if (byteCount == 4 && handler.IsTagIfdPointer(tagId))
{
int subDirOffset = tiffHeaderOffset + reader.GetInt32(tagValueOffset);
ProcessIfd(handler, reader, processedIfdOffsets, subDirOffset, tiffHeaderOffset);
}
else
{
if (!handler.CustomProcessTag(tagValueOffset, processedIfdOffsets, tiffHeaderOffset, reader, tagId, byteCount))
{
ProcessTag(handler, tagId, tagValueOffset, componentCount, formatCode, reader);
}
}
}
// at the end of each IFD is an optional link to the next IFD
int finalTagOffset = CalculateTagOffset(ifdOffset, dirTagCount);
int nextIfdOffset = reader.GetInt32(finalTagOffset);
if (nextIfdOffset != 0)
{
nextIfdOffset += tiffHeaderOffset;
if (nextIfdOffset >= reader.GetLength())
{
// Last 4 bytes of IFD reference another IFD with an address that is out of bounds
// Note this could have been caused by jhead 1.3 cropping too much
return;
}
else
{
if (nextIfdOffset < ifdOffset)
{
// TODO is this a valid restriction?
// Last 4 bytes of IFD reference another IFD with an address that is before the start of this directory
return;
}
}
if (handler.HasFollowerIfd())
{
ProcessIfd(handler, reader, processedIfdOffsets, nextIfdOffset, tiffHeaderOffset);
}
}
}
finally
{
handler.EndingIFD();
}
}
/// <exception cref="System.IO.IOException"/>
private static void ProcessTag([NotNull] TiffHandler handler, int tagId, int tagValueOffset, int componentCount, int formatCode, [NotNull] RandomAccessReader reader)
{
switch (formatCode)
{
case TiffDataFormat.CodeUndefined:
{
// this includes exif user comments
handler.SetByteArray(tagId, reader.GetBytes(tagValueOffset, componentCount));
break;
}
case TiffDataFormat.CodeString:
{
handler.SetString(tagId, reader.GetNullTerminatedString(tagValueOffset, componentCount));
break;
}
case TiffDataFormat.CodeRationalS:
{
if (componentCount == 1)
{
handler.SetRational(tagId, new Rational(reader.GetInt32(tagValueOffset), reader.GetInt32(tagValueOffset + 4)));
}
else
{
if (componentCount > 1)
{
Rational[] array = new Rational[componentCount];
for (int i = 0; i < componentCount; i++)
{
array[i] = new Rational(reader.GetInt32(tagValueOffset + (8 * i)), reader.GetInt32(tagValueOffset + 4 + (8 * i)));
}
handler.SetRationalArray(tagId, array);
}
}
break;
}
case TiffDataFormat.CodeRationalU:
{
if (componentCount == 1)
{
handler.SetRational(tagId, new Rational(reader.GetUInt32(tagValueOffset), reader.GetUInt32(tagValueOffset + 4)));
}
else
{
if (componentCount > 1)
{
Rational[] array = new Rational[componentCount];
for (int i = 0; i < componentCount; i++)
{
array[i] = new Rational(reader.GetUInt32(tagValueOffset + (8 * i)), reader.GetUInt32(tagValueOffset + 4 + (8 * i)));
}
handler.SetRationalArray(tagId, array);
}
}
break;
}
case TiffDataFormat.CodeSingle:
{
if (componentCount == 1)
{
handler.SetFloat(tagId, reader.GetFloat32(tagValueOffset));
}
else
{
float[] array = new float[componentCount];
for (int i = 0; i < componentCount; i++)
{
array[i] = reader.GetFloat32(tagValueOffset + (i * 4));
}
handler.SetFloatArray(tagId, array);
}
break;
}
case TiffDataFormat.CodeDouble:
{
if (componentCount == 1)
{
handler.SetDouble(tagId, reader.GetDouble64(tagValueOffset));
}
else
{
double[] array = new double[componentCount];
for (int i = 0; i < componentCount; i++)
{
array[i] = reader.GetDouble64(tagValueOffset + (i * 4));
}
handler.SetDoubleArray(tagId, array);
}
break;
}
case TiffDataFormat.CodeInt8S:
{
if (componentCount == 1)
{
handler.SetInt8s(tagId, reader.GetInt8(tagValueOffset));
}
else
{
sbyte[] array = new sbyte[componentCount];
for (int i = 0; i < componentCount; i++)
{
array[i] = reader.GetInt8(tagValueOffset + i);
}
handler.SetInt8sArray(tagId, array);
}
break;
}
case TiffDataFormat.CodeInt8U:
{
if (componentCount == 1)
{
handler.SetInt8u(tagId, reader.GetUInt8(tagValueOffset));
}
else
{
short[] array = new short[componentCount];
for (int i = 0; i < componentCount; i++)
{
array[i] = reader.GetUInt8(tagValueOffset + i);
}
handler.SetInt8uArray(tagId, array);
}
break;
}
case TiffDataFormat.CodeInt16S:
{
if (componentCount == 1)
{
handler.SetInt16s(tagId, (int)reader.GetInt16(tagValueOffset));
}
else
{
short[] array = new short[componentCount];
for (int i = 0; i < componentCount; i++)
{
array[i] = reader.GetInt16(tagValueOffset + (i * 2));
}
handler.SetInt16sArray(tagId, array);
}
break;
}
case TiffDataFormat.CodeInt16U:
{
if (componentCount == 1)
{
handler.SetInt16u(tagId, reader.GetUInt16(tagValueOffset));
}
else
{
int[] array = new int[componentCount];
for (int i = 0; i < componentCount; i++)
{
array[i] = reader.GetUInt16(tagValueOffset + (i * 2));
}
handler.SetInt16uArray(tagId, array);
}
break;
}
case TiffDataFormat.CodeInt32S:
{
// NOTE 'long' in this case means 32 bit, not 64
if (componentCount == 1)
{
handler.SetInt32s(tagId, reader.GetInt32(tagValueOffset));
}
else
{
int[] array = new int[componentCount];
for (int i = 0; i < componentCount; i++)
{
array[i] = reader.GetInt32(tagValueOffset + (i * 4));
}
handler.SetInt32sArray(tagId, array);
}
break;
}
case TiffDataFormat.CodeInt32U:
{
// NOTE 'long' in this case means 32 bit, not 64
if (componentCount == 1)
{
handler.SetInt32u(tagId, reader.GetUInt32(tagValueOffset));
}
else
{
long[] array = new long[componentCount];
for (int i = 0; i < componentCount; i++)
{
array[i] = reader.GetUInt32(tagValueOffset + (i * 4));
}
handler.SetInt32uArray(tagId, array);
}
break;
}
default:
{
handler.Error(Sharpen.Extensions.StringFormat("Unknown format code %d for tag %d", formatCode, tagId));
break;
}
}
}
/// <summary>Determine the offset of a given tag within the specified IFD.</summary>
/// <param name="ifdStartOffset">the offset at which the IFD starts</param>
/// <param name="entryNumber">the zero-based entry number</param>
private static int CalculateTagOffset(int ifdStartOffset, int entryNumber)
{
// Add 2 bytes for the tag count.
// Each entry is 12 bytes.
return ifdStartOffset + 2 + (12 * entryNumber);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Dapper;
namespace Dommel;
public static partial class DommelMapper
{
/// <summary>
/// Retrieves the entity of type <typeparamref name="TEntity"/> with the specified id.
/// </summary>
/// <typeparam name="TEntity">The type of the entity.</typeparam>
/// <param name="connection">The connection to the database. This can either be open or closed.</param>
/// <param name="id">The id of the entity in the database.</param>
/// <param name="transaction">Optional transaction for the command.</param>
/// <returns>The entity with the corresponding id.</returns>
public static TEntity? Get<TEntity>(this IDbConnection connection, object id, IDbTransaction? transaction = null)
where TEntity : class
{
var sql = BuildGetById(GetSqlBuilder(connection), typeof(TEntity), id, out var parameters);
LogQuery<TEntity>(sql);
return connection.QueryFirstOrDefault<TEntity>(sql, parameters, transaction);
}
/// <summary>
/// Retrieves the entity of type <typeparamref name="TEntity"/> with the specified id.
/// </summary>
/// <typeparam name="TEntity">The type of the entity.</typeparam>
/// <param name="connection">The connection to the database. This can either be open or closed.</param>
/// <param name="id">The id of the entity in the database.</param>
/// <param name="transaction">Optional transaction for the command.</param>
/// <param name="cancellationToken">Optional cancellation token for the command.</param>
/// <returns>The entity with the corresponding id.</returns>
public static async Task<TEntity?> GetAsync<TEntity>(this IDbConnection connection, object id, IDbTransaction? transaction = null, CancellationToken cancellationToken = default)
where TEntity : class
{
var sql = BuildGetById(GetSqlBuilder(connection), typeof(TEntity), id, out var parameters);
LogQuery<TEntity>(sql);
return await connection.QueryFirstOrDefaultAsync<TEntity>(new CommandDefinition(sql, parameters, transaction: transaction, cancellationToken: cancellationToken));
}
internal static string BuildGetById(ISqlBuilder sqlBuilder, Type type, object id, out DynamicParameters parameters)
{
var cacheKey = new QueryCacheKey(QueryCacheType.Get, sqlBuilder, type);
if (!QueryCache.TryGetValue(cacheKey, out var sql))
{
var tableName = Resolvers.Table(type, sqlBuilder);
var keyProperties = Resolvers.KeyProperties(type);
if (keyProperties.Length > 1)
{
throw new InvalidOperationException($"Entity {type.Name} contains more than one key property." +
"Use the Get<T> overload which supports passing multiple IDs.");
}
var keyColumnName = Resolvers.Column(keyProperties[0].Property, sqlBuilder);
sql = $"select * from {tableName} where {keyColumnName} = {sqlBuilder.PrefixParameter("Id")}";
QueryCache.TryAdd(cacheKey, sql);
}
parameters = new DynamicParameters();
parameters.Add("Id", id);
return sql;
}
/// <summary>
/// Retrieves the entity of type <typeparamref name="TEntity"/> with the specified id.
/// </summary>
/// <typeparam name="TEntity">The type of the entity.</typeparam>
/// <param name="connection">The connection to the database. This can either be open or closed.</param>
/// <param name="ids">The id of the entity in the database.</param>
/// <returns>The entity with the corresponding id.</returns>
public static TEntity? Get<TEntity>(this IDbConnection connection, params object[] ids) where TEntity : class
=> Get<TEntity>(connection, ids, transaction: null);
/// <summary>
/// Retrieves the entity of type <typeparamref name="TEntity"/> with the specified id.
/// </summary>
/// <typeparam name="TEntity">The type of the entity.</typeparam>
/// <param name="connection">The connection to the database. This can either be open or closed.</param>
/// <param name="ids">The id of the entity in the database.</param>
/// <param name="transaction">Optional transaction for the command.</param>
/// <returns>The entity with the corresponding id.</returns>
public static TEntity? Get<TEntity>(this IDbConnection connection, object[] ids, IDbTransaction? transaction = null) where TEntity : class
{
if (ids.Length == 1)
{
return Get<TEntity>(connection, ids[0], transaction);
}
var sql = BuildGetByIds(connection, typeof(TEntity), ids, out var parameters);
LogQuery<TEntity>(sql);
return connection.QueryFirstOrDefault<TEntity>(sql, parameters, transaction);
}
/// <summary>
/// Retrieves the entity of type <typeparamref name="TEntity"/> with the specified id.
/// </summary>
/// <typeparam name="TEntity">The type of the entity.</typeparam>
/// <param name="connection">The connection to the database. This can either be open or closed.</param>
/// <param name="ids">The id of the entity in the database.</param>
/// <returns>The entity with the corresponding id.</returns>
public static Task<TEntity?> GetAsync<TEntity>(this IDbConnection connection, params object[] ids) where TEntity : class
=> GetAsync<TEntity>(connection, ids, transaction: null, cancellationToken: default);
/// <summary>
/// Retrieves the entity of type <typeparamref name="TEntity"/> with the specified id.
/// </summary>
/// <typeparam name="TEntity">The type of the entity.</typeparam>
/// <param name="connection">The connection to the database. This can either be open or closed.</param>
/// <param name="ids">The id of the entity in the database.</param>
/// <param name="transaction">Optional transaction for the command.</param>
/// <param name="cancellationToken">Optional cancellation token for the command.</param>
/// <returns>The entity with the corresponding id.</returns>
public static async Task<TEntity?> GetAsync<TEntity>(this IDbConnection connection, object[] ids, IDbTransaction? transaction = null, CancellationToken cancellationToken = default)
where TEntity : class
{
if (ids.Length == 1)
{
return await GetAsync<TEntity>(connection, ids[0], transaction);
}
var sql = BuildGetByIds(connection, typeof(TEntity), ids, out var parameters);
LogQuery<TEntity>(sql);
return await connection.QueryFirstOrDefaultAsync<TEntity>(new CommandDefinition(sql, parameters, transaction, cancellationToken: cancellationToken));
}
internal static string BuildGetByIds(IDbConnection connection, Type type, object[] ids, out DynamicParameters parameters)
{
var sqlBuilder = GetSqlBuilder(connection);
var cacheKey = new QueryCacheKey(QueryCacheType.GetByMultipleIds, sqlBuilder, type);
if (!QueryCache.TryGetValue(cacheKey, out var sql))
{
var tableName = Resolvers.Table(type, sqlBuilder);
var keyProperties = Resolvers.KeyProperties(type);
var keyColumnNames = keyProperties.Select(p => Resolvers.Column(p.Property, sqlBuilder)).ToArray();
if (keyColumnNames.Length != ids.Length)
{
throw new InvalidOperationException($"Number of key columns ({keyColumnNames.Length}) of type {type.Name} does not match with the number of specified IDs ({ids.Length}).");
}
var sb = new StringBuilder("select * from ").Append(tableName).Append(" where");
var i = 0;
foreach (var keyColumnName in keyColumnNames)
{
if (i != 0)
{
sb.Append(" and");
}
sb.Append(" ").Append(keyColumnName).Append($" = {sqlBuilder.PrefixParameter("Id")}").Append(i);
i++;
}
sql = sb.ToString();
QueryCache.TryAdd(cacheKey, sql);
}
parameters = new DynamicParameters();
for (var i = 0; i < ids.Length; i++)
{
parameters.Add("Id" + i, ids[i]);
}
return sql;
}
/// <summary>
/// Retrieves all the entities of type <typeparamref name="TEntity"/>.
/// </summary>
/// <typeparam name="TEntity">The type of the entity.</typeparam>
/// <param name="connection">The connection to the database. This can either be open or closed.</param>
/// <param name="buffered">
/// A value indicating whether the result of the query should be executed directly,
/// or when the query is materialized (using <c>ToList()</c> for example).
/// </param>
/// <param name="transaction">Optional transaction for the command.</param>
/// <returns>A collection of entities of type <typeparamref name="TEntity"/>.</returns>
public static IEnumerable<TEntity> GetAll<TEntity>(this IDbConnection connection, IDbTransaction? transaction = null, bool buffered = true) where TEntity : class
{
var sql = BuildGetAllQuery(connection, typeof(TEntity));
LogQuery<TEntity>(sql);
return connection.Query<TEntity>(sql, transaction: transaction, buffered: buffered);
}
/// <summary>
/// Retrieves all the entities of type <typeparamref name="TEntity"/>.
/// </summary>
/// <typeparam name="TEntity">The type of the entity.</typeparam>
/// <param name="connection">The connection to the database. This can either be open or closed.</param>
/// <param name="transaction">Optional transaction for the command.</param>
/// <param name="cancellationToken">Optional cancellation token for the command.</param>
/// <returns>A collection of entities of type <typeparamref name="TEntity"/>.</returns>
public static Task<IEnumerable<TEntity>> GetAllAsync<TEntity>(this IDbConnection connection, IDbTransaction? transaction = null, CancellationToken cancellationToken = default) where TEntity : class
{
var sql = BuildGetAllQuery(connection, typeof(TEntity));
LogQuery<TEntity>(sql);
return connection.QueryAsync<TEntity>(new CommandDefinition(sql, transaction: transaction, cancellationToken: cancellationToken));
}
internal static string BuildGetAllQuery(IDbConnection connection, Type type)
{
var sqlBuilder = GetSqlBuilder(connection);
var cacheKey = new QueryCacheKey(QueryCacheType.GetAll, sqlBuilder, type);
if (!QueryCache.TryGetValue(cacheKey, out var sql))
{
sql = "select * from " + Resolvers.Table(type, sqlBuilder);
QueryCache.TryAdd(cacheKey, sql);
}
return sql;
}
/// <summary>
/// Retrieves a paged set of entities of type <typeparamref name="TEntity"/>.
/// </summary>
/// <typeparam name="TEntity">The type of the entity.</typeparam>
/// <param name="connection">The connection to the database. This can either be open or closed.</param>
/// <param name="pageNumber">The number of the page to fetch, starting at 1.</param>
/// <param name="pageSize">The page size.</param>
/// <param name="buffered">
/// A value indicating whether the result of the query should be executed directly,
/// or when the query is materialized (using <c>ToList()</c> for example).
/// </param>
/// <param name="transaction">Optional transaction for the command.</param>
/// <returns>A paged collection of entities of type <typeparamref name="TEntity"/>.</returns>
public static IEnumerable<TEntity> GetPaged<TEntity>(this IDbConnection connection, int pageNumber, int pageSize, IDbTransaction? transaction = null, bool buffered = true) where TEntity : class
{
var sql = BuildPagedQuery(connection, typeof(TEntity), pageNumber, pageSize);
LogQuery<TEntity>(sql);
return connection.Query<TEntity>(sql, transaction: transaction, buffered: buffered);
}
/// <summary>
/// Retrieves a paged set of entities of type <typeparamref name="TEntity"/>.
/// </summary>
/// <typeparam name="TEntity">The type of the entity.</typeparam>
/// <param name="connection">The connection to the database. This can either be open or closed.</param>
/// <param name="pageNumber">The number of the page to fetch, starting at 1.</param>
/// <param name="pageSize">The page size.</param>
/// <param name="transaction">Optional transaction for the command.</param>
/// <param name="cancellationToken">Optional cancellation token for the command.</param>
/// <returns>A paged collection of entities of type <typeparamref name="TEntity"/>.</returns>
public static Task<IEnumerable<TEntity>> GetPagedAsync<TEntity>(this IDbConnection connection, int pageNumber, int pageSize, IDbTransaction? transaction = null, CancellationToken cancellationToken = default) where TEntity : class
{
var sql = BuildPagedQuery(connection, typeof(TEntity), pageNumber, pageSize);
LogQuery<TEntity>(sql);
return connection.QueryAsync<TEntity>(new CommandDefinition(sql, transaction: transaction, cancellationToken: cancellationToken));
}
internal static string BuildPagedQuery(IDbConnection connection, Type type, int pageNumber, int pageSize)
{
// Start with the select query part
var sql = BuildGetAllQuery(connection, type);
// Append the paging part including the order by
var keyColumns = Resolvers.KeyProperties(type).Select(p => Resolvers.Column(p.Property, connection));
var orderBy = "order by " + string.Join(", ", keyColumns);
sql += GetSqlBuilder(connection).BuildPaging(orderBy, pageNumber, pageSize);
return sql;
}
}
| |
/*
* Created by: Leslie Sanford
*
* Last modified: 02/23/2005
*
* Contact: jabberdabber@hotmail.com
*/
using System;
using System.ComponentModel;
using System.Diagnostics;
namespace Sanford.Collections.Immutable
{
/// <summary>
/// Represents a node in an AVL tree.
/// </summary>
[ImmutableObject(true)]
internal class AvlNode : IAvlNode
{
#region AvlNode Members
#region Class Fields
// For use as a null node.
public static readonly NullAvlNode NullNode = new NullAvlNode();
#endregion
#region Instance Fields
// The data represented by this node.
private readonly object data;
// The number of nodes in the subtree.
private readonly int count;
// The height of this node.
private readonly int height;
// Left and right children.
private readonly IAvlNode leftChild;
private readonly IAvlNode rightChild;
#endregion
#region Construction
/// <summary>
/// Initializes a new instance of the AvlNode class with the specified
/// data and left and right children.
/// </summary>
/// <param name="data">
/// The data for the node.
/// </param>
/// <param name="leftChild">
/// The left child.
/// </param>
/// <param name="rightChild">
/// The right child.
/// </param>
public AvlNode(object data, IAvlNode leftChild, IAvlNode rightChild)
{
// Preconditions.
Debug.Assert(leftChild != null && rightChild != null);
this.data = data;
this.leftChild = leftChild;
this.rightChild = rightChild;
count = 1 + leftChild.Count + rightChild.Count;
height = 1 + Math.Max(leftChild.Height, rightChild.Height);
}
#endregion
#region Methods
#region Rotation Methods
// Left - left single rotation.
private IAvlNode DoLLRotation(IAvlNode node)
{
/*
* An LL rotation looks like the following:
*
* A B
* / / \
* B ---> C A
* /
* C
*/
// Create right child of the new root.
IAvlNode a = new AvlNode(
node.Data,
node.LeftChild.RightChild,
node.RightChild);
IAvlNode b = new AvlNode(
node.LeftChild.Data,
node.LeftChild.LeftChild,
a);
// Postconditions.
Debug.Assert(b.Data == node.LeftChild.Data);
Debug.Assert(b.LeftChild == node.LeftChild.LeftChild);
Debug.Assert(b.RightChild.Data == node.Data);
return b;
}
// Left - right double rotation.
private IAvlNode DoLRRotation(IAvlNode node)
{
/*
* An LR rotation looks like the following:
*
* Perform an RR rotation at B:
*
* A A
* / /
* B ---> C
* \ /
* C B
*
* Perform an LL rotation at A:
*
* A C
* / / \
* C ---> B A
* /
* B
*/
IAvlNode a = new AvlNode(
node.Data,
DoRRRotation(node.LeftChild),
node.RightChild);
IAvlNode c = DoLLRotation(a);
// Postconditions.
Debug.Assert(c.Data == node.LeftChild.RightChild.Data);
Debug.Assert(c.LeftChild.Data == node.LeftChild.Data);
Debug.Assert(c.RightChild.Data == node.Data);
return c;
}
// Right - right single rotation.
private IAvlNode DoRRRotation(IAvlNode node)
{
/*
* An RR rotation looks like the following:
*
* A B
* \ / \
* B ---> A C
* \
* C
*/
// Create left child of the new root.
IAvlNode a = new AvlNode(
node.Data,
node.LeftChild,
node.RightChild.LeftChild);
IAvlNode b = new AvlNode(
node.RightChild.Data,
a,
node.RightChild.RightChild);
// Postconditions.
Debug.Assert(b.Data == node.RightChild.Data);
Debug.Assert(b.RightChild == node.RightChild.RightChild);
Debug.Assert(b.LeftChild.Data == node.Data);
return b;
}
// Right - left double rotation.
private IAvlNode DoRLRotation(IAvlNode node)
{
/*
* An RL rotation looks like the following:
*
* Perform an LL rotation at B:
*
* A A
* \ \
* B ---> C
* / \
* C B
*
* Perform an RR rotation at A:
*
* A C
* \ / \
* C ---> A B
* \
* B
*/
IAvlNode a = new AvlNode(
node.Data,
node.LeftChild,
DoLLRotation(node.RightChild));
IAvlNode c = DoRRRotation(a);
// Postconditions.
Debug.Assert(c.Data == node.RightChild.LeftChild.Data);
Debug.Assert(c.LeftChild.Data == node.Data);
Debug.Assert(c.RightChild.Data == node.RightChild.Data);
return c;
}
#endregion
#endregion
#endregion
#region IAvlNode Members
/// <summary>
/// Removes the current node from the AVL tree.
/// </summary>
/// <returns>
/// The node to in the tree to replace the current node.
/// </returns>
public IAvlNode Remove()
{
IAvlNode result;
/*
* Deal with the three cases for removing a node from a binary tree.
*/
// If the node has no right children.
if(this.RightChild == AvlNode.NullNode)
{
// The replacement node is the node's left child.
result = this.LeftChild;
}
// Else if the node's right child has no left children.
else if(this.RightChild.LeftChild == AvlNode.NullNode)
{
// The replacement node is the node's right child.
result = new AvlNode(
this.RightChild.Data,
this.LeftChild,
this.RightChild.RightChild);
}
// Else the node's right child has left children.
else
{
/*
* Go to the node's right child and descend as far left as
* possible. The node found at this point will replace the
* node to be removed.
*/
IAvlNode replacement = AvlNode.NullNode;
IAvlNode rightChild = RemoveReplacement(this.RightChild, ref replacement);
// Create new node with the replacement node and the new
// right child.
result = new AvlNode(
replacement.Data,
this.LeftChild,
rightChild);
}
return result;
}
// Finds and removes replacement node for deletion (third case).
private IAvlNode RemoveReplacement(IAvlNode node, ref IAvlNode replacement)
{
IAvlNode newNode;
// If the bottom of the left tree has been found.
if(node.LeftChild == AvlNode.NullNode)
{
// The replacement node is the node found at this point.
replacement = node;
// Get the node's right child. This will be needed as we
// ascend back up the tree.
newNode = node.RightChild;
}
// Else the bottom of the left tree has not been found.
else
{
// Create new node and continue descending down the left tree.
newNode = new AvlNode(node.Data,
RemoveReplacement(node.LeftChild, ref replacement),
node.RightChild);
// If the node is out of balance.
if(!newNode.IsBalanced())
{
// Rebalance the node.
newNode = newNode.Balance();
}
}
// Postconditions.
Debug.Assert(newNode.IsBalanced());
return newNode;
}
/// <summary>
/// Balances the subtree represented by the node.
/// </summary>
/// <returns>
/// The root node of the balanced subtree.
/// </returns>
public IAvlNode Balance()
{
IAvlNode result;
if(BalanceFactor < -1)
{
if(leftChild.BalanceFactor < 0)
{
result = DoLLRotation(this);
}
else
{
result = DoLRRotation(this);
}
}
else if(BalanceFactor > 1)
{
if(rightChild.BalanceFactor > 0)
{
result = DoRRRotation(this);
}
else
{
result = DoRLRotation(this);
}
}
else
{
result = this;
}
Debug.Assert(result.IsBalanced());
return result;
}
/// <summary>
/// Indicates whether or not the subtree the node represents is in
/// balance.
/// </summary>
/// <returns>
/// <b>true</b> if the subtree is in balance; otherwise, <b>false</b>.
/// </returns>
public bool IsBalanced()
{
return BalanceFactor >= -1 && BalanceFactor <= 1;
}
/// <summary>
/// Gets the balance factor of the subtree the node represents.
/// </summary>
public int BalanceFactor
{
get
{
return rightChild.Height - leftChild.Height;
}
}
/// <summary>
/// Gets the number of nodes in the subtree.
/// </summary>
public int Count
{
get
{
return count;
}
}
/// <summary>
/// Gets the node's data.
/// </summary>
public object Data
{
get
{
return data;
}
}
/// <summary>
/// Gets the height of the subtree the node represents.
/// </summary>
public int Height
{
get
{
return height;
}
}
/// <summary>
/// Gets the node's left child.
/// </summary>
public IAvlNode LeftChild
{
get
{
return leftChild;
}
}
/// <summary>
/// Gets the node's right child.
/// </summary>
public IAvlNode RightChild
{
get
{
return rightChild;
}
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="MachineKeySection.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.Configuration
{
using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using System.Web.Hosting;
using System.Web.Security.Cryptography;
using System.Web.Util;
using System.Xml;
/******************************************************************
* !! NOTICE !! *
* The cryptographic code in this class is a legacy code base. *
* New code should not call into these crypto APIs; use the APIs *
* provided by AspNetCryptoServiceProvider instead. *
******************************************************************/
/******************************************************************
* !! WARNING !! *
* This class contains cryptographic code. If you make changes to *
* this class, please have it reviewed by the appropriate people. *
******************************************************************/
/*
<!-- validation="[SHA1|MD5|3DES|AES|HMACSHA256|HMACSHA384|HMACSHA512|alg:algorithm_name]" decryption="[AES|EDES" -->
<machineKey validationKey="AutoGenerate,IsolateApps" decryptionKey="AutoGenerate,IsolateApps" decryption="[AES|3DES]" validation="HMACSHA256" compatibilityMode="[Framework20SP1|Framework20SP2]" />
*/
public sealed class MachineKeySection : ConfigurationSection
{
private const string OBSOLETE_CRYPTO_API_MESSAGE = "This API exists only for backward compatibility; new framework features that require cryptographic services MUST NOT call it. New features should use the AspNetCryptoServiceProvider class instead.";
// If the default validation algorithm changes, be sure to update the _HashSize and _AutoGenValidationKeySize fields also.
internal const string DefaultValidationAlgorithm = "HMACSHA256";
internal const MachineKeyValidation DefaultValidation = MachineKeyValidation.SHA1;
internal const string DefaultDataProtectorType = "";
internal const string DefaultApplicationName = "";
private static ConfigurationPropertyCollection _properties;
private static readonly ConfigurationProperty _propValidationKey =
new ConfigurationProperty("validationKey", typeof(string), "AutoGenerate,IsolateApps", StdValidatorsAndConverters.WhiteSpaceTrimStringConverter, StdValidatorsAndConverters.NonEmptyStringValidator, ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propDecryptionKey =
new ConfigurationProperty("decryptionKey", typeof(string),"AutoGenerate,IsolateApps",StdValidatorsAndConverters.WhiteSpaceTrimStringConverter, StdValidatorsAndConverters.NonEmptyStringValidator, ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propDecryption =
new ConfigurationProperty("decryption", typeof(string), "Auto", StdValidatorsAndConverters.WhiteSpaceTrimStringConverter, StdValidatorsAndConverters.NonEmptyStringValidator, ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propValidation =
new ConfigurationProperty("validation", typeof(string), DefaultValidationAlgorithm, StdValidatorsAndConverters.WhiteSpaceTrimStringConverter, StdValidatorsAndConverters.NonEmptyStringValidator, ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propDataProtectorType =
new ConfigurationProperty("dataProtectorType", typeof(string), DefaultDataProtectorType, StdValidatorsAndConverters.WhiteSpaceTrimStringConverter, null, ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propApplicationName =
new ConfigurationProperty("applicationName", typeof(string), DefaultApplicationName, StdValidatorsAndConverters.WhiteSpaceTrimStringConverter, null, ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propCompatibilityMode =
new ConfigurationProperty("compatibilityMode", typeof(MachineKeyCompatibilityMode), MachineKeyCompatibilityMode.Framework20SP1, null, null, ConfigurationPropertyOptions.None);
private static object s_initLock = new object();
private static bool s_initComplete = false;
private static MachineKeySection s_config;
private static RNGCryptoServiceProvider s_randomNumberGenerator;
private static SymmetricAlgorithm s_oSymAlgoDecryption;
private static SymmetricAlgorithm s_oSymAlgoValidation;
private static byte[] s_validationKey;
private static byte[] s_inner = null;
private static byte[] s_outer = null;
internal static bool IsDecryptionKeyAutogenerated { get { EnsureConfig(); return s_config.AutogenKey; } }
private bool _AutogenKey;
internal bool AutogenKey { get { RuntimeDataInitialize(); return _AutogenKey; } }
private byte[] _ValidationKey;
private byte[] _DecryptionKey;
private bool DataInitialized = false;
private static bool _CustomValidationTypeIsKeyed;
private static string _CustomValidationName;
private static int _IVLengthDecryption = 64;
private static int _IVLengthValidation = 64;
private static int _HashSize = HMACSHA256_HASH_SIZE;
private static int _AutoGenValidationKeySize = HMACSHA256_KEY_SIZE;
private static int _AutoGenDecryptionKeySize = 24;
private static bool _UseHMACSHA = true;
private static bool _UsingCustomEncryption = false;
private static SymmetricAlgorithm s_oSymAlgoLegacy;
private const int MD5_KEY_SIZE = 64;
private const int MD5_HASH_SIZE = 16;
private const int SHA1_KEY_SIZE = 64;
private const int HMACSHA256_KEY_SIZE = 64;
private const int HMACSHA384_KEY_SIZE = 128;
private const int HMACSHA512_KEY_SIZE = 128;
private const int SHA1_HASH_SIZE = 20;
private const int HMACSHA256_HASH_SIZE = 32;
private const int HMACSHA384_HASH_SIZE = 48;
private const int HMACSHA512_HASH_SIZE = 64;
private const string ALGO_PREFIX = "alg:";
internal byte[] ValidationKeyInternal { get { RuntimeDataInitialize(); return (byte[])_ValidationKey.Clone(); } }
internal byte[] DecryptionKeyInternal { get { RuntimeDataInitialize(); return (byte[])_DecryptionKey.Clone(); } }
internal static int HashSize { get { EnsureConfig(); s_config.RuntimeDataInitialize(); return _HashSize; } }
internal static int ValidationKeySize { get { EnsureConfig(); s_config.RuntimeDataInitialize(); return _AutoGenValidationKeySize; } }
static MachineKeySection()
{
// Property initialization
_properties = new ConfigurationPropertyCollection();
_properties.Add(_propValidationKey);
_properties.Add(_propDecryptionKey);
_properties.Add(_propValidation);
_properties.Add(_propDecryption);
_properties.Add(_propCompatibilityMode);
_properties.Add(_propDataProtectorType);
_properties.Add(_propApplicationName);
}
public MachineKeySection()
{
}
internal static MachineKeyCompatibilityMode CompatMode
{
get
{
return GetApplicationConfig().CompatibilityMode;
}
}
protected override ConfigurationPropertyCollection Properties
{
get
{
return _properties;
}
}
[ConfigurationProperty("validationKey", DefaultValue = "AutoGenerate,IsolateApps")]
[TypeConverter(typeof(WhiteSpaceTrimStringConverter))]
[StringValidator(MinLength = 1)]
public string ValidationKey
{
get
{
return (string)base[_propValidationKey];
}
set
{
base[_propValidationKey] = value;
}
}
[ConfigurationProperty("decryptionKey", DefaultValue = "AutoGenerate,IsolateApps")]
[TypeConverter(typeof(WhiteSpaceTrimStringConverter))]
[StringValidator(MinLength = 1)]
public string DecryptionKey
{
get
{
return (string)base[_propDecryptionKey];
}
set
{
base[_propDecryptionKey] = value;
}
}
[ConfigurationProperty("decryption", DefaultValue = "Auto")]
[TypeConverter(typeof(WhiteSpaceTrimStringConverter))]
[StringValidator(MinLength = 1)]
public string Decryption {
get {
string s = GetDecryptionAttributeSkipValidation();
if (s != "Auto" && s != "AES" && s != "3DES" && s != "DES" && !s.StartsWith(ALGO_PREFIX, StringComparison.Ordinal))
throw new ConfigurationErrorsException(SR.GetString(SR.Wrong_decryption_enum), ElementInformation.Properties["decryption"].Source, ElementInformation.Properties["decryption"].LineNumber);
return s;
}
set {
if (value != "AES" && value != "3DES" && value != "Auto" && value != "DES" && !value.StartsWith(ALGO_PREFIX, StringComparison.Ordinal))
throw new ConfigurationErrorsException(SR.GetString(SR.Wrong_decryption_enum), ElementInformation.Properties["decryption"].Source, ElementInformation.Properties["decryption"].LineNumber);
base[_propDecryption] = value;
}
}
// returns the value in the 'decryption' attribute (or the default value if null) without throwing an exception if the value is malformed
internal string GetDecryptionAttributeSkipValidation() {
return (string)base[_propDecryption] ?? "Auto";
}
private bool _validationIsCached;
private string _cachedValidation;
private MachineKeyValidation _cachedValidationEnum;
[ConfigurationProperty("validation", DefaultValue = DefaultValidationAlgorithm)]
[TypeConverter(typeof(WhiteSpaceTrimStringConverter))]
[StringValidator(MinLength = 1)]
public string ValidationAlgorithm
{
get {
if (!_validationIsCached)
CacheValidation();
return _cachedValidation;
} set {
if (_validationIsCached && value == _cachedValidation)
return;
if (value == null)
value = DefaultValidationAlgorithm;
_cachedValidationEnum = MachineKeyValidationConverter.ConvertToEnum(value);
_cachedValidation = value;
base[_propValidation] = value;
_validationIsCached = true;
}
}
// returns the value in the 'validation' attribute (or the default value if null) without throwing an exception if the value is malformed
internal string GetValidationAttributeSkipValidation() {
return (string)base[_propValidation] ?? DefaultValidationAlgorithm;
}
private void CacheValidation()
{
_cachedValidation = GetValidationAttributeSkipValidation();
_cachedValidationEnum = MachineKeyValidationConverter.ConvertToEnum(_cachedValidation);
_validationIsCached = true;
}
public MachineKeyValidation Validation {
get {
if (_validationIsCached == false)
CacheValidation();
return _cachedValidationEnum;
} set {
if (_validationIsCached && value == _cachedValidationEnum)
return;
_cachedValidation = MachineKeyValidationConverter.ConvertFromEnum(value);
_cachedValidationEnum = value;
base[_propValidation] = _cachedValidation;
_validationIsCached = true;
}
}
[ConfigurationProperty("dataProtectorType", DefaultValue = DefaultDataProtectorType)]
[TypeConverter(typeof(WhiteSpaceTrimStringConverter))]
public string DataProtectorType {
get {
return (string)base[_propDataProtectorType];
}
set {
base[_propDataProtectorType] = value;
}
}
[ConfigurationProperty("applicationName", DefaultValue = DefaultApplicationName)]
[TypeConverter(typeof(WhiteSpaceTrimStringConverter))]
public string ApplicationName {
get {
return (string)base[_propApplicationName];
}
set {
base[_propApplicationName] = value;
}
}
private MachineKeyCompatibilityMode _compatibilityMode = (MachineKeyCompatibilityMode)(-1); // dummy value used to mean uninitialized
[ConfigurationProperty("compatibilityMode", DefaultValue = MachineKeyCompatibilityMode.Framework20SP1)]
public MachineKeyCompatibilityMode CompatibilityMode
{
get
{
// the compatibility mode is cached since it's queried frequently
if (_compatibilityMode < 0) {
_compatibilityMode = (MachineKeyCompatibilityMode)base[_propCompatibilityMode];
}
return _compatibilityMode;
}
set
{
base[_propCompatibilityMode] = value;
_compatibilityMode = value;
}
}
protected override void Reset(ConfigurationElement parentElement)
{
MachineKeySection parent = parentElement as MachineKeySection;
base.Reset(parentElement);
// copy the privates from the parent.
if (parent != null)
{
// _ValidationKey = parent.ValidationKeyInternal;
// _DecryptionKey = parent.DecryptionKeyInternal;
// _AutogenKey = parent.AutogenKey;
}
}
private void RuntimeDataInitialize()
{
if (DataInitialized == false)
{
byte [] bKeysRandom = null;
bool fNonHttpApp = false;
string strKey = ValidationKey;
string appName = HttpRuntime.AppDomainAppVirtualPath;
string appId = HttpRuntime.AppDomainAppId;
InitValidationAndEncyptionSizes();
if( appName == null )
{
#if !FEATURE_PAL // FEATURE_PAL does not enable cryptography
// FEATURE_PAL
appName = System.Diagnostics.Process.GetCurrentProcess().MainModule.ModuleName;
if( ValidationKey.Contains( "AutoGenerate" ) ||
DecryptionKey.Contains( "AutoGenerate" ) )
{
fNonHttpApp = true;
bKeysRandom = new byte[ _AutoGenValidationKeySize + _AutoGenDecryptionKeySize ];
// Gernerate random keys
RandomNumberGenerator.GetBytes(bKeysRandom);
}
#endif // !FEATURE_PAL
}
bool fAppIdSpecific = StringUtil.StringEndsWith(strKey, ",IsolateByAppId");
if (fAppIdSpecific)
{
strKey = strKey.Substring(0, strKey.Length - ",IsolateByAppId".Length);
}
bool fAppSpecific = StringUtil.StringEndsWith(strKey, ",IsolateApps");
if (fAppSpecific)
{
strKey = strKey.Substring(0, strKey.Length - ",IsolateApps".Length);
}
if (strKey == "AutoGenerate")
{ // case sensitive
_ValidationKey = new byte[_AutoGenValidationKeySize];
if( fNonHttpApp )
{
Buffer.BlockCopy( bKeysRandom, 0, _ValidationKey, 0, _AutoGenValidationKeySize);
}
else
{
Buffer.BlockCopy(HttpRuntime.s_autogenKeys, 0, _ValidationKey, 0, _AutoGenValidationKeySize);
}
}
else
{
if (strKey.Length < 40 || (strKey.Length & 0x1) == 1)
throw new ConfigurationErrorsException(SR.GetString(SR.Unable_to_get_cookie_authentication_validation_key, strKey.Length.ToString(CultureInfo.InvariantCulture)), ElementInformation.Properties["validationKey"].Source, ElementInformation.Properties["validationKey"].LineNumber);
#pragma warning disable 618 // obsolete
_ValidationKey = HexStringToByteArray(strKey);
#pragma warning restore 618
if (_ValidationKey == null)
throw new ConfigurationErrorsException(SR.GetString(SR.Invalid_validation_key), ElementInformation.Properties["validationKey"].Source, ElementInformation.Properties["validationKey"].LineNumber);
}
if (fAppSpecific)
{
int dwCode = StringUtil.GetNonRandomizedStringComparerHashCode(appName);
_ValidationKey[0] = (byte)(dwCode & 0xff);
_ValidationKey[1] = (byte)((dwCode & 0xff00) >> 8);
_ValidationKey[2] = (byte)((dwCode & 0xff0000) >> 16);
_ValidationKey[3] = (byte)((dwCode & 0xff000000) >> 24);
}
if (fAppIdSpecific)
{
int dwCode = StringUtil.GetNonRandomizedStringComparerHashCode(appId);
_ValidationKey[4] = (byte)(dwCode & 0xff);
_ValidationKey[5] = (byte)((dwCode & 0xff00) >> 8);
_ValidationKey[6] = (byte)((dwCode & 0xff0000) >> 16);
_ValidationKey[7] = (byte)((dwCode & 0xff000000) >> 24);
}
strKey = DecryptionKey;
fAppIdSpecific = StringUtil.StringEndsWith(strKey, ",IsolateByAppId");
if (fAppIdSpecific)
{
strKey = strKey.Substring(0, strKey.Length - ",IsolateByAppId".Length);
}
fAppSpecific = StringUtil.StringEndsWith(strKey, ",IsolateApps");
if (fAppSpecific)
{
strKey = strKey.Substring(0, strKey.Length - ",IsolateApps".Length);
}
if (strKey == "AutoGenerate")
{ // case sensitive
_DecryptionKey = new byte[_AutoGenDecryptionKeySize];
if( fNonHttpApp )
{
Buffer.BlockCopy( bKeysRandom, _AutoGenValidationKeySize, _DecryptionKey, 0, _AutoGenDecryptionKeySize);
}
else
{
Buffer.BlockCopy(HttpRuntime.s_autogenKeys, _AutoGenValidationKeySize, _DecryptionKey, 0, _AutoGenDecryptionKeySize);
}
_AutogenKey = true;
}
else
{
_AutogenKey = false;
if ((strKey.Length & 1) != 0)
throw new ConfigurationErrorsException(SR.GetString(SR.Invalid_decryption_key), ElementInformation.Properties["decryptionKey"].Source, ElementInformation.Properties["decryptionKey"].LineNumber);
#pragma warning disable 618 // obsolete
_DecryptionKey = HexStringToByteArray(strKey);
#pragma warning restore 618
if (_DecryptionKey == null)
throw new ConfigurationErrorsException(SR.GetString(SR.Invalid_decryption_key), ElementInformation.Properties["decryptionKey"].Source, ElementInformation.Properties["decryptionKey"].LineNumber);
}
if (fAppSpecific)
{
int dwCode = StringUtil.GetNonRandomizedStringComparerHashCode(appName);
_DecryptionKey[0] = (byte)(dwCode & 0xff);
_DecryptionKey[1] = (byte)((dwCode & 0xff00) >> 8);
_DecryptionKey[2] = (byte)((dwCode & 0xff0000) >> 16);
_DecryptionKey[3] = (byte)((dwCode & 0xff000000) >> 24);
}
if (fAppIdSpecific)
{
int dwCode = StringUtil.GetNonRandomizedStringComparerHashCode(appId);
_DecryptionKey[4] = (byte)(dwCode & 0xff);
_DecryptionKey[5] = (byte)((dwCode & 0xff00) >> 8);
_DecryptionKey[6] = (byte)((dwCode & 0xff0000) >> 16);
_DecryptionKey[7] = (byte)((dwCode & 0xff000000) >> 24);
}
DataInitialized = true;
}
}
[Obsolete(OBSOLETE_CRYPTO_API_MESSAGE)]
internal static byte[] EncryptOrDecryptData(bool fEncrypt, byte[] buf, byte[] modifier, int start, int length)
{
// MSRC 10405: IVType.Hash has been removed; new default behavior is to use IVType.Random.
return EncryptOrDecryptData(fEncrypt, buf, modifier, start, length, false, false, IVType.Random);
}
[Obsolete(OBSOLETE_CRYPTO_API_MESSAGE)]
internal static byte[] EncryptOrDecryptData(bool fEncrypt, byte[] buf, byte[] modifier, int start, int length, bool useValidationSymAlgo)
{
// MSRC 10405: IVType.Hash has been removed; new default behavior is to use IVType.Random.
return EncryptOrDecryptData(fEncrypt, buf, modifier, start, length, useValidationSymAlgo, false, IVType.Random);
}
[Obsolete(OBSOLETE_CRYPTO_API_MESSAGE)]
internal static byte[] EncryptOrDecryptData(bool fEncrypt, byte[] buf, byte[] modifier, int start, int length,
bool useValidationSymAlgo, bool useLegacyMode, IVType ivType)
{
// MSRC 10405: Encryption is not sufficient to prevent a malicious user from tampering with the data, and the result of decryption can
// be used to discover information about the plaintext (such as via a padding or decryption oracle). We must sign anything that we
// encrypt to ensure that end users can't abuse our encryption routines.
// the new encrypt-then-sign behavior for everything EXCEPT Membership / MachineKey. We need to make it very clear that setting this
// to 'false' is a Very Bad Thing(tm).
return EncryptOrDecryptData(fEncrypt, buf, modifier, start, length, useValidationSymAlgo, useLegacyMode, ivType, !AppSettings.UseLegacyEncryption);
}
[Obsolete(OBSOLETE_CRYPTO_API_MESSAGE)]
internal static byte[] EncryptOrDecryptData(bool fEncrypt, byte[] buf, byte[] modifier, int start, int length,
bool useValidationSymAlgo, bool useLegacyMode, IVType ivType, bool signData)
{
/* This algorithm is used to perform encryption or decryption of a buffer, along with optional signing (for encryption)
* or signature verification (for decryption). Possible operation modes are:
*
* ENCRYPT + SIGN DATA (fEncrypt = true, signData = true)
* Input: buf represents plaintext to encrypt, modifier represents data to be appended to buf (but isn't part of the plaintext itself)
* Output: E(iv + buf + modifier) + HMAC(E(iv + buf + modifier))
*
* ONLY ENCRYPT DATA (fEncrypt = true, signData = false)
* Input: buf represents plaintext to encrypt, modifier represents data to be appended to buf (but isn't part of the plaintext itself)
* Output: E(iv + buf + modifier)
*
* VERIFY + DECRYPT DATA (fEncrypt = false, signData = true)
* Input: buf represents ciphertext to decrypt, modifier represents data to be removed from the end of the plaintext (since it's not really plaintext data)
* Input (buf): E(iv + m + modifier) + HMAC(E(iv + m + modifier))
* Output: m
*
* ONLY DECRYPT DATA (fEncrypt = false, signData = false)
* Input: buf represents ciphertext to decrypt, modifier represents data to be removed from the end of the plaintext (since it's not really plaintext data)
* Input (buf): E(iv + plaintext + modifier)
* Output: m
*
* The 'iv' in the above descriptions isn't an actual IV. Rather, if ivType = IVType.Random, we'll prepend random bytes ('iv')
* to the plaintext before feeding it to the crypto algorithms. Introducing randomness early in the algorithm prevents users
* from inspecting two ciphertexts to see if the plaintexts are related. If ivType = IVType.None, then 'iv' is simply
* an empty string. If ivType = IVType.Hash, we use a non-keyed hash of the plaintext.
*
* The 'modifier' in the above descriptions is a piece of metadata that should be encrypted along with the plaintext but
* which isn't actually part of the plaintext itself. It can be used for storing things like the user name for whom this
* plaintext was generated, the page that generated the plaintext, etc. On decryption, the modifier parameter is compared
* against the modifier stored in the crypto stream, and it is stripped from the message before the plaintext is returned.
*
* In all cases, if something goes wrong (e.g. invalid padding, invalid signature, invalid modifier, etc.), a generic exception is thrown.
*/
try {
EnsureConfig();
if (!fEncrypt && signData) {
if (start != 0 || length != buf.Length) {
// These transformations assume that we're operating on buf in its entirety and
// not on any subset of buf, so we'll just replace buf with the particular subset
// we're interested in.
byte[] bTemp = new byte[length];
Buffer.BlockCopy(buf, start, bTemp, 0, length);
buf = bTemp;
start = 0;
}
// buf actually contains E(iv + m + modifier) + HMAC(E(iv + m + modifier)), so we need to verify and strip off the signature
buf = GetUnHashedData(buf);
// At this point, buf contains only E(iv + m + modifier) if the signature check succeeded.
if (buf == null) {
// signature verification failed
throw new HttpException(SR.GetString(SR.Unable_to_validate_data));
}
// need to fix up again since GetUnhashedData() returned a different array
length = buf.Length;
}
if (useLegacyMode)
useLegacyMode = _UsingCustomEncryption; // only use legacy mode for custom algorithms
System.IO.MemoryStream ms = new System.IO.MemoryStream();
ICryptoTransform cryptoTransform = GetCryptoTransform(fEncrypt, useValidationSymAlgo, useLegacyMode);
CryptoStream cs = new CryptoStream(ms, cryptoTransform, CryptoStreamMode.Write);
// DevDiv Bugs 137864: Add IV to beginning of data to be encrypted.
// IVType.None is used by MembershipProvider which requires compatibility even in SP2 mode (and will set signData = false).
// MSRC 10405: If signData is set to true, we must generate an IV.
bool createIV = signData || ((ivType != IVType.None) && (CompatMode > MachineKeyCompatibilityMode.Framework20SP1));
if (fEncrypt && createIV)
{
int ivLength = (useValidationSymAlgo ? _IVLengthValidation : _IVLengthDecryption);
byte[] iv = null;
switch (ivType) {
case IVType.Hash:
// iv := H(buf)
iv = GetIVHash(buf, ivLength);
break;
case IVType.Random:
// iv := [random]
iv = new byte[ivLength];
RandomNumberGenerator.GetBytes(iv);
break;
}
Debug.Assert(iv != null, "Invalid value for IVType: " + ivType.ToString("G"));
cs.Write(iv, 0, iv.Length);
}
cs.Write(buf, start, length);
if (fEncrypt && modifier != null)
{
cs.Write(modifier, 0, modifier.Length);
}
cs.FlushFinalBlock();
byte[] paddedData = ms.ToArray();
// At this point:
// If fEncrypt = true (encrypting), paddedData := Enc(iv + buf + modifier)
// If fEncrypt = false (decrypting), paddedData := iv + plaintext + modifier
byte[] bData;
cs.Close();
// In ASP.NET 2.0, we pool ICryptoTransform objects, and this returns that ICryptoTransform
// to the pool. In ASP.NET 4.0, this just disposes of the ICryptoTransform object.
ReturnCryptoTransform(fEncrypt, cryptoTransform, useValidationSymAlgo, useLegacyMode);
// DevDiv Bugs 137864: Strip IV from beginning of unencrypted data
if (!fEncrypt && createIV)
{
// strip off the first bytes that were random bits
int ivLength = (useValidationSymAlgo ? _IVLengthValidation : _IVLengthDecryption);
int bDataLength = paddedData.Length - ivLength;
if (bDataLength < 0) {
throw new HttpException(SR.GetString(SR.Unable_to_validate_data));
}
bData = new byte[bDataLength];
Buffer.BlockCopy(paddedData, ivLength, bData, 0, bDataLength);
}
else
{
bData = paddedData;
}
// At this point:
// If fEncrypt = true (encrypting), bData := Enc(iv + buf + modifier)
// If fEncrypt = false (decrypting), bData := plaintext + modifier
if (!fEncrypt && modifier != null && modifier.Length > 0)
{
// MSRC 10405: Crypto board suggests blinding where signature failed
// to prevent timing attacks.
bool modifierCheckFailed = false;
for(int iter=0; iter<modifier.Length; iter++)
if (bData[bData.Length - modifier.Length + iter] != modifier[iter])
modifierCheckFailed = true;
if (modifierCheckFailed) {
throw new HttpException(SR.GetString(SR.Unable_to_validate_data));
}
byte[] bData2 = new byte[bData.Length - modifier.Length];
Buffer.BlockCopy(bData, 0, bData2, 0, bData2.Length);
bData = bData2;
}
// At this point:
// If fEncrypt = true (encrypting), bData := Enc(iv + buf + modifier)
// If fEncrypt = false (decrypting), bData := plaintext
if (fEncrypt && signData) {
byte[] hmac = HashData(bData, null, 0, bData.Length);
byte[] bData2 = new byte[bData.Length + hmac.Length];
Buffer.BlockCopy(bData, 0, bData2, 0, bData.Length);
Buffer.BlockCopy(hmac, 0, bData2, bData.Length, hmac.Length);
bData = bData2;
}
// At this point:
// If fEncrypt = true (encrypting), bData := Enc(iv + buf + modifier) + HMAC(Enc(iv + buf + modifier))
// If fEncrypt = false (decrypting), bData := plaintext
// And we're done
return bData;
} catch {
// It's important that we don't propagate the original exception here as we don't want a production
// server which has unintentionally left YSODs enabled to leak cryptographic information.
throw new HttpException(SR.GetString(SR.Unable_to_validate_data));
}
}
private static byte[] GetIVHash(byte[] buf, int ivLength)
{
// return an IV that is computed as a hash of the buffer
int bytesToWrite = ivLength;
int bytesWritten = 0;
byte[] iv = new byte[ivLength];
// get SHA1 hash of the buffer and copy to the IV.
// if hash length is less than IV length, re-hash the hash and
// append until IV is full.
byte[] hash = buf;
while (bytesWritten < ivLength)
{
byte[] newHash = new byte[_HashSize];
int hr = UnsafeNativeMethods.GetSHA1Hash(hash, hash.Length, newHash, newHash.Length);
Marshal.ThrowExceptionForHR(hr);
hash = newHash;
int bytesToCopy = Math.Min(_HashSize, bytesToWrite);
Buffer.BlockCopy(hash, 0, iv, bytesWritten, bytesToCopy);
bytesWritten += bytesToCopy;
bytesToWrite -= bytesToCopy;
}
return iv;
}
private static RNGCryptoServiceProvider RandomNumberGenerator {
get {
if (s_randomNumberGenerator == null) {
s_randomNumberGenerator = new RNGCryptoServiceProvider();
}
return s_randomNumberGenerator;
}
}
private static void SetInnerOuterKeys(byte[] validationKey, ref byte[] inner, ref byte[] outer) {
byte[] key = null;
if (validationKey.Length > _AutoGenValidationKeySize)
{
key = new byte[_HashSize];
int hr = UnsafeNativeMethods.GetSHA1Hash(validationKey, validationKey.Length, key, key.Length);
Marshal.ThrowExceptionForHR(hr);
}
if (inner == null)
inner = new byte[_AutoGenValidationKeySize];
if (outer == null)
outer = new byte[_AutoGenValidationKeySize];
int i;
for (i = 0; i < _AutoGenValidationKeySize; i++) {
inner[i] = 0x36;
outer[i] = 0x5C;
}
for (i=0; i < validationKey.Length; i++) {
inner[i] ^= validationKey[i];
outer[i] ^= validationKey[i];
}
}
private static byte[] GetHMACSHA1Hash(byte[] buf, byte[] modifier, int start, int length) {
if (start < 0 || start > buf.Length)
throw new ArgumentException(SR.GetString(SR.InvalidArgumentValue, "start"));
if (length < 0 || buf == null || (start + length) > buf.Length)
throw new ArgumentException(SR.GetString(SR.InvalidArgumentValue, "length"));
byte[] hash = new byte[_HashSize];
int hr = UnsafeNativeMethods.GetHMACSHA1Hash(buf, start, length,
modifier, (modifier == null) ? 0 : modifier.Length,
s_inner, s_inner.Length, s_outer, s_outer.Length,
hash, hash.Length);
if (hr == 0)
return hash;
_UseHMACSHA = false;
return null;
}
[Obsolete(OBSOLETE_CRYPTO_API_MESSAGE)]
internal static string HashAndBase64EncodeString(string s)
{
byte[] ab;
byte[] hash;
string result;
ab = Encoding.Unicode.GetBytes(s);
hash = HashData(ab, null, 0, ab.Length);
result = Convert.ToBase64String(hash);
return result;
}
static internal void DestroyByteArray(byte[] buf)
{
if (buf == null || buf.Length < 1)
return;
for (int iter = 0; iter < buf.Length; iter++)
buf[iter] = (byte)0;
}
internal void DestroyKeys()
{
MachineKeySection.DestroyByteArray(_ValidationKey);
MachineKeySection.DestroyByteArray(_DecryptionKey);
}
static void EnsureConfig()
{
if (!s_initComplete)
{
lock (s_initLock)
{
if (!s_initComplete)
{
GetApplicationConfig(); // sets s_config field
s_config.ConfigureEncryptionObject();
s_initComplete = true;
}
}
}
}
// gets the application-level MachineKeySection
internal static MachineKeySection GetApplicationConfig() {
if (s_config == null) {
lock (s_initLock) {
if (s_config == null) {
s_config = RuntimeConfig.GetAppConfig().MachineKey;
}
}
}
return s_config;
}
// NOTE: When encoding the data, this method *may* return the same reference to the input "buf" parameter
// with the hash appended in the end if there's enough space. The "length" parameter would also be
// appropriately adjusted in those cases. This is an optimization to prevent unnecessary copying of
// buffers.
[Obsolete(OBSOLETE_CRYPTO_API_MESSAGE)]
internal static byte[] GetEncodedData(byte[] buf, byte[] modifier, int start, ref int length)
{
EnsureConfig();
byte[] bHash = HashData(buf, modifier, start, length);
byte[] returnBuffer;
if (buf.Length - start - length >= bHash.Length)
{
// Append hash to end of buffer if there's space
Buffer.BlockCopy(bHash, 0, buf, start + length, bHash.Length);
returnBuffer = buf;
}
else
{
returnBuffer = new byte[length + bHash.Length];
Buffer.BlockCopy(buf, start, returnBuffer, 0, length);
Buffer.BlockCopy(bHash, 0, returnBuffer, length, bHash.Length);
start = 0;
}
length += bHash.Length;
if (s_config.Validation == MachineKeyValidation.TripleDES || s_config.Validation == MachineKeyValidation.AES) {
returnBuffer = EncryptOrDecryptData(true, returnBuffer, modifier, start, length, true);
length = returnBuffer.Length;
}
return returnBuffer;
}
// NOTE: When decoding the data, this method *may* return the same reference to the input "buf" parameter
// with the "dataLength" parameter containing the actual length of the data in the "buf" (i.e. length of actual
// data is (total length of data - hash length)). This is an optimization to prevent unnecessary copying of buffers.
[Obsolete(OBSOLETE_CRYPTO_API_MESSAGE)]
internal static byte[] GetDecodedData(byte[] buf, byte[] modifier, int start, int length, ref int dataLength)
{
EnsureConfig();
if (s_config.Validation == MachineKeyValidation.TripleDES || s_config.Validation == MachineKeyValidation.AES) {
buf = EncryptOrDecryptData(false, buf, modifier, start, length, true);
if (buf == null || buf.Length < _HashSize)
throw new HttpException(SR.GetString(SR.Unable_to_validate_data));
length = buf.Length;
start = 0;
}
if (length < _HashSize || start < 0 || start >= length)
throw new HttpException(SR.GetString(SR.Unable_to_validate_data));
byte[] bHash = HashData(buf, modifier, start, length - _HashSize);
for (int iter = 0; iter < bHash.Length; iter++)
if (bHash[iter] != buf[start + length - _HashSize + iter])
throw new HttpException(SR.GetString(SR.Unable_to_validate_data));
dataLength = length - _HashSize;
return buf;
}
[Obsolete(OBSOLETE_CRYPTO_API_MESSAGE)]
internal static byte[] HashData(byte[] buf, byte[] modifier, int start, int length)
{
EnsureConfig();
if (s_config.Validation == MachineKeyValidation.MD5)
return HashDataUsingNonKeyedAlgorithm(null, buf, modifier, start, length, s_validationKey);
if (_UseHMACSHA) {
byte [] hash = GetHMACSHA1Hash(buf, modifier, start, length);
if (hash != null)
return hash;
}
if (_CustomValidationTypeIsKeyed) {
return HashDataUsingKeyedAlgorithm(KeyedHashAlgorithm.Create(_CustomValidationName),
buf, modifier, start, length, s_validationKey);
} else {
return HashDataUsingNonKeyedAlgorithm(HashAlgorithm.Create(_CustomValidationName),
buf, modifier, start, length, s_validationKey);
}
}
private void ConfigureEncryptionObject()
{
// We suppress CS0618 since some of the algorithms we support are marked with [Obsolete].
// These deprecated algorithms are *not* enabled by default. Developers must opt-in to
// them, so we're secure by default.
#pragma warning disable 618
using (new ApplicationImpersonationContext()) {
s_validationKey = ValidationKeyInternal;
byte[] dKey = DecryptionKeyInternal;
if (_UseHMACSHA)
SetInnerOuterKeys(s_validationKey, ref s_inner, ref s_outer);
DestroyKeys();
switch (Decryption)
{
case "3DES":
s_oSymAlgoDecryption = CryptoAlgorithms.CreateTripleDES();
break;
case "DES":
s_oSymAlgoDecryption = CryptoAlgorithms.CreateDES();
break;
case "AES":
s_oSymAlgoDecryption = CryptoAlgorithms.CreateAes();
break;
case "Auto":
if (dKey.Length == 8) {
s_oSymAlgoDecryption = CryptoAlgorithms.CreateDES();
} else {
s_oSymAlgoDecryption = CryptoAlgorithms.CreateAes();
}
break;
}
if (s_oSymAlgoDecryption == null) // Shouldn't happen!
InitValidationAndEncyptionSizes();
switch(Validation)
{
case MachineKeyValidation.TripleDES:
if (dKey.Length == 8) {
s_oSymAlgoValidation = CryptoAlgorithms.CreateDES();
} else {
s_oSymAlgoValidation = CryptoAlgorithms.CreateTripleDES();
}
break;
case MachineKeyValidation.AES:
s_oSymAlgoValidation = CryptoAlgorithms.CreateAes();
break;
}
// The IV lengths should actually be equal to the block sizes rather than the key
// sizes, but we shipped with this code and unfortunately cannot change it without
// breaking back-compat.
if (s_oSymAlgoValidation != null) {
SetKeyOnSymAlgorithm(s_oSymAlgoValidation, dKey);
_IVLengthValidation = RoundupNumBitsToNumBytes(s_oSymAlgoValidation.KeySize);
}
SetKeyOnSymAlgorithm(s_oSymAlgoDecryption, dKey);
_IVLengthDecryption = RoundupNumBitsToNumBytes(s_oSymAlgoDecryption.KeySize);
InitLegacyEncAlgorithm(dKey);
DestroyByteArray(dKey);
}
#pragma warning restore 618
}
private void SetKeyOnSymAlgorithm(SymmetricAlgorithm symAlgo, byte[] dKey)
{
try {
if (dKey.Length > 8 && symAlgo is DESCryptoServiceProvider) {
byte[] bTemp = new byte[8];
Buffer.BlockCopy(dKey, 0, bTemp, 0, 8);
symAlgo.Key = bTemp;
DestroyByteArray(bTemp);
} else {
symAlgo.Key = dKey;
}
symAlgo.GenerateIV();
symAlgo.IV = new byte[symAlgo.IV.Length];
} catch (Exception e) {
throw new ConfigurationErrorsException(SR.GetString(SR.Bad_machine_key, e.Message), ElementInformation.Properties["decryptionKey"].Source, ElementInformation.Properties["decryptionKey"].LineNumber);
}
}
private static ICryptoTransform GetCryptoTransform(bool fEncrypt, bool useValidationSymAlgo, bool legacyMode)
{
SymmetricAlgorithm algo = (legacyMode ? s_oSymAlgoLegacy : (useValidationSymAlgo ? s_oSymAlgoValidation : s_oSymAlgoDecryption));
lock(algo)
return (fEncrypt ? algo.CreateEncryptor() : algo.CreateDecryptor());
}
private static void ReturnCryptoTransform(bool fEncrypt, ICryptoTransform ct, bool useValidationSymAlgo, bool legacyMode)
{
ct.Dispose();
}
[Obsolete(OBSOLETE_CRYPTO_API_MESSAGE)]
static byte[] s_ahexval;
// This API is obsolete because it is insecure: invalid hex chars are silently replaced with '0',
// which can reduce the overall security of the system. But unfortunately, some code is dependent
// on this broken behavior.
[Obsolete(OBSOLETE_CRYPTO_API_MESSAGE)]
static internal byte[] HexStringToByteArray(String str)
{
if (((uint)str.Length & 0x1) == 0x1) // must be 2 nibbles per byte
{
return null;
}
byte[] ahexval = s_ahexval; // initialize a table for faster lookups
if (ahexval == null)
{
ahexval = new byte['f' + 1];
for (int i = ahexval.Length; --i >= 0; )
{
if ('0' <= i && i <= '9')
{
ahexval[i] = (byte)(i - '0');
}
else if ('a' <= i && i <= 'f')
{
ahexval[i] = (byte)(i - 'a' + 10);
}
else if ('A' <= i && i <= 'F')
{
ahexval[i] = (byte)(i - 'A' + 10);
}
}
s_ahexval = ahexval;
}
byte[] result = new byte[str.Length / 2];
int istr = 0, ir = 0;
int n = result.Length;
while (--n >= 0)
{
int c1, c2;
try
{
c1 = ahexval[str[istr++]];
}
catch (ArgumentNullException)
{
c1 = 0;
return null;// Inavlid char
}
catch (ArgumentException)
{
c1 = 0;
return null;// Inavlid char
}
catch (IndexOutOfRangeException)
{
c1 = 0;
return null;// Inavlid char
}
try
{
c2 = ahexval[str[istr++]];
}
catch (ArgumentNullException)
{
c2 = 0;
return null;// Inavlid char
}
catch (ArgumentException)
{
c2 = 0;
return null;// Inavlid char
}
catch (IndexOutOfRangeException)
{
c2 = 0;
return null;// Inavlid char
}
result[ir++] = (byte)((c1 << 4) + c2);
}
return result;
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
private void InitValidationAndEncyptionSizes()
{
_CustomValidationName = ValidationAlgorithm;
_CustomValidationTypeIsKeyed = true;
switch(ValidationAlgorithm)
{
case "AES":
case "3DES":
_UseHMACSHA = true;
_HashSize = SHA1_HASH_SIZE;
_AutoGenValidationKeySize = SHA1_KEY_SIZE;
break;
case "SHA1":
_UseHMACSHA = true;
_HashSize = SHA1_HASH_SIZE;
_AutoGenValidationKeySize = SHA1_KEY_SIZE;
break;
case "MD5":
_CustomValidationTypeIsKeyed = false;
_UseHMACSHA = false;
_HashSize = MD5_HASH_SIZE;
_AutoGenValidationKeySize = MD5_KEY_SIZE;
break;
case "HMACSHA256":
_UseHMACSHA = true;
_HashSize = HMACSHA256_HASH_SIZE;
_AutoGenValidationKeySize = HMACSHA256_KEY_SIZE;
break;
case "HMACSHA384":
_UseHMACSHA = true;
_HashSize = HMACSHA384_HASH_SIZE;
_AutoGenValidationKeySize = HMACSHA384_KEY_SIZE;
break;
case "HMACSHA512":
_UseHMACSHA = true;
_HashSize = HMACSHA512_HASH_SIZE;
_AutoGenValidationKeySize = HMACSHA512_KEY_SIZE;
break;
default:
_UseHMACSHA = false;
if (!_CustomValidationName.StartsWith(ALGO_PREFIX, StringComparison.Ordinal)) {
throw new ConfigurationErrorsException(SR.GetString(SR.Wrong_validation_enum),
ElementInformation.Properties["validation"].Source,
ElementInformation.Properties["validation"].LineNumber);
}
_CustomValidationName = _CustomValidationName.Substring(ALGO_PREFIX.Length);
HashAlgorithm alg = null;
try {
_CustomValidationTypeIsKeyed = false;
alg = HashAlgorithm.Create(_CustomValidationName);
} catch (Exception e) {
throw new ConfigurationErrorsException(SR.GetString(SR.Wrong_validation_enum), e,
ElementInformation.Properties["validation"].Source,
ElementInformation.Properties["validation"].LineNumber);
}
if (alg == null)
throw new ConfigurationErrorsException(SR.GetString(SR.Wrong_validation_enum),
ElementInformation.Properties["validation"].Source,
ElementInformation.Properties["validation"].LineNumber);
_AutoGenValidationKeySize = 0;
_HashSize = 0;
_CustomValidationTypeIsKeyed = (alg is KeyedHashAlgorithm);
if (!_CustomValidationTypeIsKeyed) {
throw new ConfigurationErrorsException(SR.GetString(SR.Wrong_validation_enum),
ElementInformation.Properties["validation"].Source,
ElementInformation.Properties["validation"].LineNumber);
}
try {
_HashSize = RoundupNumBitsToNumBytes(alg.HashSize);
if (_CustomValidationTypeIsKeyed)
_AutoGenValidationKeySize = ((KeyedHashAlgorithm) alg).Key.Length;
if (_AutoGenValidationKeySize < 1)
_AutoGenValidationKeySize = RoundupNumBitsToNumBytes(alg.InputBlockSize);
if (_AutoGenValidationKeySize < 1)
_AutoGenValidationKeySize = RoundupNumBitsToNumBytes(alg.OutputBlockSize);
} catch {}
if (_HashSize < 1 || _AutoGenValidationKeySize < 1) {
// If we didn't get the hash-size or key-size, perform a hash and get the sizes
byte [] buf = new byte[10];
byte [] buf2 = new byte[512];
RandomNumberGenerator.GetBytes(buf);
RandomNumberGenerator.GetBytes(buf2);
byte [] bHash = alg.ComputeHash(buf);
_HashSize = bHash.Length;
if (_AutoGenValidationKeySize < 1) {
if (_CustomValidationTypeIsKeyed)
_AutoGenValidationKeySize = ((KeyedHashAlgorithm) alg).Key.Length;
else
_AutoGenValidationKeySize = RoundupNumBitsToNumBytes(alg.InputBlockSize);
}
alg.Clear();
}
if (_HashSize < 1)
_HashSize = HMACSHA512_HASH_SIZE;
if (_AutoGenValidationKeySize < 1)
_AutoGenValidationKeySize = HMACSHA512_KEY_SIZE;
break;
}
_AutoGenDecryptionKeySize = 0;
switch(Decryption) {
case "AES":
_AutoGenDecryptionKeySize = 24;
break;
case "3DES":
_AutoGenDecryptionKeySize = 24;
break;
case "Auto":
_AutoGenDecryptionKeySize = 24;
break;
case "DES":
if (ValidationAlgorithm == "AES" || ValidationAlgorithm == "3DES")
_AutoGenDecryptionKeySize = 24;
else
_AutoGenDecryptionKeySize = 8;
break;
default:
_UsingCustomEncryption = true;
if (!Decryption.StartsWith(ALGO_PREFIX, StringComparison.Ordinal)) {
throw new ConfigurationErrorsException(SR.GetString(SR.Wrong_decryption_enum),
ElementInformation.Properties["decryption"].Source,
ElementInformation.Properties["decryption"].LineNumber);
}
try {
s_oSymAlgoDecryption = SymmetricAlgorithm.Create(Decryption.Substring(ALGO_PREFIX.Length));
} catch(Exception e) {
throw new ConfigurationErrorsException(SR.GetString(SR.Wrong_decryption_enum), e,
ElementInformation.Properties["decryption"].Source,
ElementInformation.Properties["decryption"].LineNumber);
}
if (s_oSymAlgoDecryption == null)
throw new ConfigurationErrorsException(SR.GetString(SR.Wrong_decryption_enum),
ElementInformation.Properties["decryption"].Source,
ElementInformation.Properties["decryption"].LineNumber);
_AutoGenDecryptionKeySize = RoundupNumBitsToNumBytes(s_oSymAlgoDecryption.KeySize);
break;
}
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
internal static int RoundupNumBitsToNumBytes(int numBits) {
if (numBits < 0)
return 0;
return (numBits / 8) + (((numBits & 7) != 0) ? 1 : 0);
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
private static byte[] HashDataUsingNonKeyedAlgorithm(HashAlgorithm hashAlgo, byte[] buf, byte[] modifier,
int start, int length, byte[] validationKey)
{
int totalLength = length + validationKey.Length + ((modifier != null) ? modifier.Length : 0);
byte [] bAll = new byte[totalLength];
Buffer.BlockCopy(buf, start, bAll, 0, length);
if (modifier != null) {
Buffer.BlockCopy(modifier, 0, bAll, length, modifier.Length);
}
Buffer.BlockCopy(validationKey, 0, bAll, length, validationKey.Length);
if (hashAlgo != null) {
return hashAlgo.ComputeHash(bAll);
} else {
byte[] newHash = new byte[MD5_HASH_SIZE];
int hr = UnsafeNativeMethods.GetSHA1Hash(bAll, bAll.Length, newHash, newHash.Length);
Marshal.ThrowExceptionForHR(hr);
return newHash;
}
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
private static byte[] HashDataUsingKeyedAlgorithm(KeyedHashAlgorithm hashAlgo, byte[] buf, byte[] modifier,
int start, int length, byte[] validationKey)
{
int totalLength = length + ((modifier != null) ? modifier.Length : 0);
byte [] bAll = new byte[totalLength];
Buffer.BlockCopy(buf, start, bAll, 0, length);
if (modifier != null) {
Buffer.BlockCopy(modifier, 0, bAll, length, modifier.Length);
}
hashAlgo.Key = validationKey;
return hashAlgo.ComputeHash(bAll);
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
[Obsolete(OBSOLETE_CRYPTO_API_MESSAGE)]
internal static byte[] GetUnHashedData(byte[] bufHashed)
{
if (!VerifyHashedData(bufHashed))
return null;
byte[] buf2 = new byte[bufHashed.Length - _HashSize];
Buffer.BlockCopy(bufHashed, 0, buf2, 0, buf2.Length);
return buf2;
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
[Obsolete(OBSOLETE_CRYPTO_API_MESSAGE)]
internal static bool VerifyHashedData(byte[] bufHashed)
{
EnsureConfig();
//////////////////////////////////////////////////////////////////////
// Step 1: Get the MAC: Last [HashSize] bytes
if (bufHashed.Length <= _HashSize)
return false;
byte[] bMac = HashData(bufHashed, null, 0, bufHashed.Length - _HashSize);
//////////////////////////////////////////////////////////////////////
// Step 2: Make sure the MAC has expected length
if (bMac == null || bMac.Length != _HashSize)
return false;
int lastPos = bufHashed.Length - _HashSize;
// From Tolga: To prevent a timing attack, we should verify the entire hash instead of failing
// early the first time we see a mismatched byte.
bool hashCheckFailed = false;
for (int iter = 0; iter < _HashSize; iter++)
if (bMac[iter] != bufHashed[lastPos + iter])
hashCheckFailed = true;
return !hashCheckFailed;
}
internal static bool UsingCustomEncryption {
get {
EnsureConfig();
return _UsingCustomEncryption;
}
}
private static void InitLegacyEncAlgorithm(byte [] dKey)
{
if (!_UsingCustomEncryption)
return;
s_oSymAlgoLegacy = CryptoAlgorithms.CreateAes();
try {
s_oSymAlgoLegacy.Key = dKey;
} catch {
if (dKey.Length <= 24)
throw;
byte [] buf = new byte[24];
Buffer.BlockCopy(dKey, 0, buf, 0, buf.Length);
dKey = buf;
s_oSymAlgoLegacy.Key = dKey;
}
}
// This is called as the last step of the deserialization process before the newly created section is seen by the consumer.
// We can use it to change defaults on-the-fly.
protected override void SetReadOnly() {
// Unless overridden, set <machineKey compatibilityMode="Framework45" />
ConfigUtil.SetFX45DefaultValue(this, _propCompatibilityMode, MachineKeyCompatibilityMode.Framework45);
base.SetReadOnly();
}
}
}
| |
using UnityEditor;
using UnityEngine;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace AssetBundleGraph {
public class IntegratedGUIBundleConfigurator : INodeOperation {
public void Setup (BuildTarget target,
NodeData node,
IEnumerable<PerformGraph.AssetGroups> incoming,
IEnumerable<ConnectionData> connectionsToOutput,
PerformGraph.Output Output)
{
int groupCount = 0;
if(incoming != null) {
var groupNames = new List<string>();
foreach(var ag in incoming) {
foreach (var groupKey in ag.assetGroups.Keys) {
if(!groupNames.Contains(groupKey)) {
groupNames.Add(groupKey);
}
}
}
groupCount = groupNames.Count;
}
ValidateBundleNameTemplate(
node.BundleNameTemplate[target],
node.BundleConfigUseGroupAsVariants,
groupCount,
() => {
throw new NodeException(node.Name + ":Bundle Name Template is empty.", node.Id);
},
() => {
throw new NodeException(node.Name + ":Bundle Name Template can not contain '" + AssetBundleGraphSettings.KEYWORD_WILDCARD.ToString()
+ "' when group name is used for variants.", node.Id);
},
() => {
throw new NodeException(node.Name + ":Bundle Name Template must contain '" + AssetBundleGraphSettings.KEYWORD_WILDCARD.ToString()
+ "' when group name is not used for variants and expecting multiple incoming groups.", node.Id);
}
);
var variantNames = node.Variants.Select(v=>v.Name).ToList();
foreach(var variant in node.Variants) {
ValidateVariantName(variant.Name, variantNames,
() => {
throw new NodeException(node.Name + ":Variant name is empty.", node.Id);
},
() => {
throw new NodeException(node.Name + ":Variant name cannot contain whitespace \"" + variant.Name + "\".", node.Id);
},
() => {
throw new NodeException(node.Name + ":Variant name already exists \"" + variant.Name + "\".", node.Id);
});
}
if(incoming != null) {
/**
* Check if incoming asset has valid import path
*/
var invalids = new List<AssetReference>();
foreach(var ag in incoming) {
foreach (var groupKey in ag.assetGroups.Keys) {
ag.assetGroups[groupKey].ForEach( a => { if (string.IsNullOrEmpty(a.importFrom)) invalids.Add(a); } );
}
}
if (invalids.Any()) {
throw new NodeException(node.Name +
": Invalid files are found. Following files need to be imported to put into asset bundle: " +
string.Join(", ", invalids.Select(a =>a.absolutePath).ToArray()), node.Id );
}
}
Dictionary<string, List<AssetReference>> output = null;
if(Output != null) {
output = new Dictionary<string, List<AssetReference>>();
}
if(incoming != null) {
foreach(var ag in incoming) {
string variantName = null;
if(!node.BundleConfigUseGroupAsVariants) {
var currentVariant = node.Variants.Find( v => v.ConnectionPoint.Id == ag.connection.ToNodeConnectionPointId );
variantName = (currentVariant == null) ? null : currentVariant.Name;
}
// set configured assets in bundle name
foreach (var groupKey in ag.assetGroups.Keys) {
if(node.BundleConfigUseGroupAsVariants) {
variantName = groupKey;
}
var bundleName = GetBundleName(target, node, groupKey);
var assets = ag.assetGroups[groupKey];
ConfigureAssetBundleSettings(variantName, assets);
if(output != null) {
if(!output.ContainsKey(bundleName)) {
output[bundleName] = new List<AssetReference>();
}
output[bundleName].AddRange(assets);
}
}
}
}
if(Output != null) {
var dst = (connectionsToOutput == null || !connectionsToOutput.Any())?
null : connectionsToOutput.First();
Output(dst, output);
}
}
public void Run (BuildTarget target,
NodeData node,
IEnumerable<PerformGraph.AssetGroups> incoming,
IEnumerable<ConnectionData> connectionsToOutput,
PerformGraph.Output Output,
Action<NodeData, string, float> progressFunc)
{
Dictionary<string, List<AssetReference>> output = null;
if(Output != null) {
output = new Dictionary<string, List<AssetReference>>();
}
if(incoming != null) {
foreach(var ag in incoming) {
string variantName = null;
if(!node.BundleConfigUseGroupAsVariants) {
var currentVariant = node.Variants.Find( v => v.ConnectionPoint.Id == ag.connection.ToNodeConnectionPointId );
variantName = (currentVariant == null) ? null : currentVariant.Name;
}
// set configured assets in bundle name
foreach (var groupKey in ag.assetGroups.Keys) {
if(node.BundleConfigUseGroupAsVariants) {
variantName = groupKey;
}
var bundleName = GetBundleName(target, node, groupKey);
if(progressFunc != null) progressFunc(node, string.Format("Configuring {0}", bundleName), 0.5f);
var assets = ag.assetGroups[groupKey];
ConfigureAssetBundleSettings(variantName, assets);
if(output != null) {
if(!output.ContainsKey(bundleName)) {
output[bundleName] = new List<AssetReference>();
}
output[bundleName].AddRange(assets);
}
}
}
}
if(Output != null) {
var dst = (connectionsToOutput == null || !connectionsToOutput.Any())?
null : connectionsToOutput.First();
Output(dst, output);
}
}
public void ConfigureAssetBundleSettings (string variantName, List<AssetReference> assets) {
foreach(var a in assets) {
a.variantName = (string.IsNullOrEmpty(variantName))? null : variantName.ToLower();;
}
}
public static void ValidateBundleNameTemplate (string bundleNameTemplate, bool useGroupAsVariants, int groupCount,
Action NullOrEmpty,
Action InvalidBundleNameTemplateForVariants,
Action InvalidBundleNameTemplateForNotVariants
) {
if (string.IsNullOrEmpty(bundleNameTemplate)){
NullOrEmpty();
}
if(useGroupAsVariants && bundleNameTemplate.IndexOf(AssetBundleGraphSettings.KEYWORD_WILDCARD) >= 0) {
InvalidBundleNameTemplateForVariants();
}
if(!useGroupAsVariants && bundleNameTemplate.IndexOf(AssetBundleGraphSettings.KEYWORD_WILDCARD) < 0 &&
groupCount > 1) {
InvalidBundleNameTemplateForNotVariants();
}
}
public static void ValidateVariantName (string variantName, List<string> names, Action NullOrEmpty, Action ContainsSpace, Action NameAlreadyExists) {
if (string.IsNullOrEmpty(variantName)) {
NullOrEmpty();
}
if(Regex.IsMatch(variantName, "\\s")) {
ContainsSpace();
}
var overlappings = names.GroupBy(x => x)
.Where(group => 1 < group.Count())
.Select(group => group.Key)
.ToList();
if (overlappings.Any()) {
NameAlreadyExists();
}
}
public static string GetBundleName(BuildTarget target, NodeData node, string groupKey) {
var bundleName = node.BundleNameTemplate[target];
if(node.BundleConfigUseGroupAsVariants) {
return bundleName;
} else {
return bundleName.Replace(AssetBundleGraphSettings.KEYWORD_WILDCARD.ToString(), groupKey);
}
}
}
}
| |
//-------------------------------------------------------------------------------
// <copyright file="SyntaxBuilderTest.cs" company="Appccelerate">
// Copyright (c) 2008-2015
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-------------------------------------------------------------------------------
namespace Appccelerate.Bootstrapper.Syntax
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using Appccelerate.Bootstrapper.Dummies;
using Appccelerate.Formatters;
using FakeItEasy;
using FluentAssertions;
using Xunit;
using Xunit.Extensions;
public class SyntaxBuilderTest
{
private const int NumberOfExecutablesForBegin = 1;
private const int NumberOfExecutablesForEnd = 2;
private readonly StringBuilder executionChainingBuilder;
private readonly IExecutableFactory<ICustomExtension> executableFactory;
private readonly ISyntaxBuilder<ICustomExtension> testee;
public SyntaxBuilderTest()
{
this.executionChainingBuilder = new StringBuilder();
this.executableFactory = A.Fake<IExecutableFactory<ICustomExtension>>();
this.testee = new SyntaxBuilder<ICustomExtension>(this.executableFactory);
}
[Fact]
public void BeginWith_Behavior_ShouldAddExecutable()
{
this.SetupCreateActionExecutableReturnsAnyExecutable();
this.testee.Begin.With(A.Fake<IBehavior<ICustomExtension>>());
this.testee.Should().HaveCount(NumberOfExecutablesForBegin);
}
[Fact]
public void BeginWith_BehaviorMultipleTimes_ShouldOnlyAddOneExecutable()
{
this.SetupCreateActionExecutableReturnsAnyExecutable();
this.testee.Begin.With(A.Fake<IBehavior<ICustomExtension>>()).With(A.Fake<IBehavior<ICustomExtension>>()).With(A.Fake<IBehavior<ICustomExtension>>());
this.testee.Should().HaveCount(NumberOfExecutablesForBegin);
}
[Fact]
public void BeginWith_Behavior_ShouldAddBehaviorToLastExecutable()
{
var extension = A.Fake<IExecutable<ICustomExtension>>();
var behavior = A.Fake<IBehavior<ICustomExtension>>();
this.SetupCreateActionExecutableReturnsExecutable(extension);
this.testee.Begin.With(behavior);
A.CallTo(() => extension.Add(behavior)).MustHaveHappened();
}
[Fact]
public void BeginWith_BehaviorMultipleTimes_ShouldAddBehaviorToLastExecutable()
{
var extension = A.Fake<IExecutable<ICustomExtension>>();
var firstBehavior = A.Fake<IBehavior<ICustomExtension>>();
var secondBehavior = A.Fake<IBehavior<ICustomExtension>>();
var thirdBehavior = A.Fake<IBehavior<ICustomExtension>>();
this.SetupCreateActionExecutableReturnsExecutable(extension);
this.testee
.Begin
.With(firstBehavior)
.With(secondBehavior)
.With(thirdBehavior);
A.CallTo(() => extension.Add(firstBehavior)).MustHaveHappened();
A.CallTo(() => extension.Add(secondBehavior)).MustHaveHappened();
A.CallTo(() => extension.Add(thirdBehavior)).MustHaveHappened();
}
[Fact]
public void BeginWithLateBound_Behavior_ShouldAddExecutable()
{
this.SetupCreateActionExecutableReturnsAnyExecutable();
this.testee.Begin.With(() => A.Fake<IBehavior<ICustomExtension>>());
this.testee.Should().HaveCount(NumberOfExecutablesForBegin);
}
[Fact]
public void BeginWithLateBound_BehaviorMultipleTimes_ShouldOnlyAddOneExecutable()
{
this.SetupCreateActionExecutableReturnsAnyExecutable();
this.testee.Begin.With(() => A.Fake<IBehavior<ICustomExtension>>()).With(() => A.Fake<IBehavior<ICustomExtension>>()).With(() => A.Fake<IBehavior<ICustomExtension>>());
this.testee.Should().HaveCount(NumberOfExecutablesForBegin);
}
[Fact]
public void BeginWithLateBound_Behavior_ShouldAddBehaviorToLastExecutable()
{
var extension = A.Fake<IExecutable<ICustomExtension>>();
var behavior = A.Fake<IBehavior<ICustomExtension>>();
this.SetupCreateActionExecutableReturnsExecutable(extension);
this.testee.Begin.With(() => behavior);
A.CallTo(() => extension.Add(A<IBehavior<ICustomExtension>>._)).MustHaveHappened();
}
[Fact]
public void BeginWithLateBound_BehaviorMultipleTimes_ShouldAddBehaviorToLastExecutable()
{
var extension = A.Fake<IExecutable<ICustomExtension>>();
var firstBehavior = A.Fake<IBehavior<ICustomExtension>>();
var secondBehavior = A.Fake<IBehavior<ICustomExtension>>();
var thirdBehavior = A.Fake<IBehavior<ICustomExtension>>();
this.SetupCreateActionExecutableReturnsExecutable(extension);
this.testee
.Begin
.With(() => firstBehavior)
.With(() => secondBehavior)
.With(() => thirdBehavior);
A.CallTo(() => extension.Add(A<IBehavior<ICustomExtension>>._)).MustHaveHappened(Repeated.Exactly.Times(3));
}
[Fact]
public void BeginWithLateBound_Behavior_ShouldBehaveLateBound()
{
IBehavior<ICustomExtension> interceptedBehavior = null;
var extension = A.Fake<IExecutable<ICustomExtension>>();
var behavior = A.Fake<IBehavior<ICustomExtension>>();
this.SetupCreateActionExecutableReturnsExecutable(extension);
A.CallTo(() => extension.Add(A<IBehavior<ICustomExtension>>._)).Invokes((IBehavior<ICustomExtension> b) => interceptedBehavior = b);
this.testee.Begin.With(() => behavior);
interceptedBehavior.Behave(Enumerable.Empty<ICustomExtension>());
A.CallTo(() => behavior.Behave(Enumerable.Empty<ICustomExtension>())).MustHaveHappened();
}
[Fact]
public void EndWith_Behavior_ShouldAddExecutable()
{
this.SetupCreateActionExecutableReturnsAnyExecutable();
this.testee.Begin.End.With(A.Fake<IBehavior<ICustomExtension>>());
this.testee.Should().HaveCount(NumberOfExecutablesForEnd);
}
[Fact]
public void EndWith_BehaviorMultipleTimes_ShouldOnlyAddOneExecutable()
{
this.SetupCreateActionExecutableReturnsAnyExecutable();
this.testee.Begin.End.With(A.Fake<IBehavior<ICustomExtension>>()).With(A.Fake<IBehavior<ICustomExtension>>()).With(A.Fake<IBehavior<ICustomExtension>>());
this.testee.Should().HaveCount(NumberOfExecutablesForEnd);
}
[Fact]
public void EndWith_Behavior_ShouldAddBehaviorToLastExecutable()
{
var firstExtension = A.Fake<IExecutable<ICustomExtension>>();
var secondExtension = A.Fake<IExecutable<ICustomExtension>>();
var behavior = A.Fake<IBehavior<ICustomExtension>>();
A.CallTo(() => this.executableFactory.CreateExecutable(A<Expression<Action>>._))
.ReturnsNextFromSequence(firstExtension, secondExtension);
this.testee.Begin.End.With(behavior);
A.CallTo(() => firstExtension.Add(behavior)).MustNotHaveHappened();
A.CallTo(() => secondExtension.Add(behavior)).MustHaveHappened();
}
[Fact]
public void EndWith_BehaviorMultipleTimes_ShouldAddBehaviorToLastExecutable()
{
var firstExtension = A.Fake<IExecutable<ICustomExtension>>();
var secondExtension = A.Fake<IExecutable<ICustomExtension>>();
var firstBehavior = A.Fake<IBehavior<ICustomExtension>>();
var secondBehavior = A.Fake<IBehavior<ICustomExtension>>();
var thirdBehavior = A.Fake<IBehavior<ICustomExtension>>();
A.CallTo(() => this.executableFactory.CreateExecutable(A<Expression<Action>>._))
.ReturnsNextFromSequence(firstExtension, secondExtension);
this.testee
.Begin.End
.With(firstBehavior)
.With(secondBehavior)
.With(thirdBehavior);
A.CallTo(() => firstExtension.Add(firstBehavior)).MustNotHaveHappened();
A.CallTo(() => firstExtension.Add(secondBehavior)).MustNotHaveHappened();
A.CallTo(() => firstExtension.Add(thirdBehavior)).MustNotHaveHappened();
A.CallTo(() => secondExtension.Add(firstBehavior)).MustHaveHappened();
A.CallTo(() => secondExtension.Add(secondBehavior)).MustHaveHappened();
A.CallTo(() => secondExtension.Add(thirdBehavior)).MustHaveHappened();
}
[Fact]
public void EndWithLateBound_Behavior_ShouldAddExecutable()
{
this.SetupCreateActionExecutableReturnsAnyExecutable();
this.testee.Begin.End.With(() => A.Fake<IBehavior<ICustomExtension>>());
this.testee.Should().HaveCount(NumberOfExecutablesForEnd);
}
[Fact]
public void EndWithLateBound_BehaviorMultipleTimes_ShouldOnlyAddOneExecutable()
{
this.SetupCreateActionExecutableReturnsAnyExecutable();
this.testee.Begin.End.With(() => A.Fake<IBehavior<ICustomExtension>>()).With(() => A.Fake<IBehavior<ICustomExtension>>()).With(() => A.Fake<IBehavior<ICustomExtension>>());
this.testee.Should().HaveCount(NumberOfExecutablesForEnd);
}
[Fact]
public void EndWithLateBound_Behavior_ShouldAddBehaviorToLastExecutable()
{
var firstExtension = A.Fake<IExecutable<ICustomExtension>>();
var secondExtension = A.Fake<IExecutable<ICustomExtension>>();
var behavior = A.Fake<IBehavior<ICustomExtension>>();
A.CallTo(() => this.executableFactory.CreateExecutable(A<Expression<Action>>._))
.ReturnsNextFromSequence(firstExtension, secondExtension);
this.testee.Begin.End.With(() => behavior);
A.CallTo(() => firstExtension.Add(A<IBehavior<ICustomExtension>>._)).MustNotHaveHappened();
A.CallTo(() => secondExtension.Add(A<IBehavior<ICustomExtension>>._)).MustHaveHappened();
}
[Fact]
public void EndWithLateBound_BehaviorMultipleTimes_ShouldAddBehaviorToLastExecutable()
{
var firstExtension = A.Fake<IExecutable<ICustomExtension>>();
var secondExtension = A.Fake<IExecutable<ICustomExtension>>();
var firstBehavior = A.Fake<IBehavior<ICustomExtension>>();
var secondBehavior = A.Fake<IBehavior<ICustomExtension>>();
var thirdBehavior = A.Fake<IBehavior<ICustomExtension>>();
A.CallTo(() => this.executableFactory.CreateExecutable(A<Expression<Action>>._))
.ReturnsNextFromSequence(firstExtension, secondExtension);
this.testee
.Begin.End
.With(() => firstBehavior)
.With(() => secondBehavior)
.With(() => thirdBehavior);
A.CallTo(() => firstExtension.Add(A<IBehavior<ICustomExtension>>._)).MustNotHaveHappened();
A.CallTo(() => secondExtension.Add(A<IBehavior<ICustomExtension>>._)).MustHaveHappened(Repeated.Exactly.Times(3));
}
[Fact]
public void EndWithLateBound_Behavior_ShouldBehaveLateBound()
{
IBehavior<ICustomExtension> interceptedBehavior = null;
var extension = A.Fake<IExecutable<ICustomExtension>>();
var behavior = A.Fake<IBehavior<ICustomExtension>>();
this.SetupCreateActionExecutableReturnsExecutable(extension);
A.CallTo(() => extension.Add(A<IBehavior<ICustomExtension>>._)).Invokes((IBehavior<ICustomExtension> b) => interceptedBehavior = b);
this.testee.Begin.End.With(() => behavior);
interceptedBehavior.Behave(Enumerable.Empty<ICustomExtension>());
A.CallTo(() => behavior.Behave(Enumerable.Empty<ICustomExtension>())).MustHaveHappened();
}
[Fact]
public void WithAfterExecuteWithAction_Behavior_ShouldAddExecutable()
{
this.SetupCreateActionExecutableReturnsAnyExecutable();
this.testee.Execute(() => this.DoNothing()).With(A.Fake<IBehavior<ICustomExtension>>());
this.testee.Should().HaveCount(1);
}
[Fact]
public void WithAfterExecuteWithAction_BehaviorMultipleTimes_ShouldOnlyAddOneExecutable()
{
this.SetupCreateActionExecutableReturnsAnyExecutable();
this.testee.Execute(() => this.DoNothing()).With(A.Fake<IBehavior<ICustomExtension>>()).With(A.Fake<IBehavior<ICustomExtension>>()).With(A.Fake<IBehavior<ICustomExtension>>());
this.testee.Should().HaveCount(1);
}
[Fact]
public void WithAfterExecuteWithAction_Behavior_ShouldAddBehaviorToLastExecutable()
{
var extension = A.Fake<IExecutable<ICustomExtension>>();
var behavior = A.Fake<IBehavior<ICustomExtension>>();
this.SetupCreateActionExecutableReturnsExecutable(extension);
this.testee
.Execute(() => this.DoNothing())
.With(behavior);
A.CallTo(() => extension.Add(behavior)).MustHaveHappened();
}
[Fact]
public void WithAfterExecuteWithAction_BehaviorMultipleTimes_ShouldAddBehaviorToLastExecutable()
{
var extension = A.Fake<IExecutable<ICustomExtension>>();
var firstBehavior = A.Fake<IBehavior<ICustomExtension>>();
var secondBehavior = A.Fake<IBehavior<ICustomExtension>>();
var thirdBehavior = A.Fake<IBehavior<ICustomExtension>>();
this.SetupCreateActionExecutableReturnsExecutable(extension);
this.testee
.Execute(() => this.DoNothing())
.With(firstBehavior)
.With(secondBehavior)
.With(thirdBehavior);
A.CallTo(() => extension.Add(firstBehavior)).MustHaveHappened();
A.CallTo(() => extension.Add(secondBehavior)).MustHaveHappened();
A.CallTo(() => extension.Add(thirdBehavior)).MustHaveHappened();
}
[Fact]
public void WithLateBoundAfterExecuteWithAction_Behavior_ShouldAddExecutable()
{
this.SetupCreateActionExecutableReturnsAnyExecutable();
this.testee.Execute(() => this.DoNothing()).With(() => A.Fake<IBehavior<ICustomExtension>>());
this.testee.Should().HaveCount(1);
}
[Fact]
public void WithLateBoundAfterExecuteWithAction_BehaviorMultipleTimes_ShouldOnlyAddOneExecutable()
{
this.SetupCreateActionExecutableReturnsAnyExecutable();
this.testee.Execute(() => this.DoNothing()).With(() => A.Fake<IBehavior<ICustomExtension>>()).With(() => A.Fake<IBehavior<ICustomExtension>>()).With(() => A.Fake<IBehavior<ICustomExtension>>());
this.testee.Should().HaveCount(1);
}
[Fact]
public void WithLateBoundAfterExecuteWithAction_Behavior_ShouldAddBehaviorToLastExecutable()
{
var extension = A.Fake<IExecutable<ICustomExtension>>();
var behavior = A.Fake<IBehavior<ICustomExtension>>();
this.SetupCreateActionExecutableReturnsExecutable(extension);
this.testee
.Execute(() => this.DoNothing())
.With(() => behavior);
A.CallTo(() => extension.Add(A<IBehavior<ICustomExtension>>._)).MustHaveHappened();
}
[Fact]
public void WithLateBoundAfterExecuteWithAction_BehaviorMultipleTimes_ShouldAddBehaviorToLastExecutable()
{
var extension = A.Fake<IExecutable<ICustomExtension>>();
var firstBehavior = A.Fake<IBehavior<ICustomExtension>>();
var secondBehavior = A.Fake<IBehavior<ICustomExtension>>();
var thirdBehavior = A.Fake<IBehavior<ICustomExtension>>();
this.SetupCreateActionExecutableReturnsExecutable(extension);
this.testee
.Execute(() => this.DoNothing())
.With(() => firstBehavior)
.With(() => secondBehavior)
.With(() => thirdBehavior);
A.CallTo(() => extension.Add(A<IBehavior<ICustomExtension>>._)).MustHaveHappened(Repeated.Exactly.Times(3));
}
[Fact]
public void WithLateBoundAfterExecuteWithAction_Behavior_ShouldBehaveLateBound()
{
IBehavior<ICustomExtension> interceptedBehavior = null;
var extension = A.Fake<IExecutable<ICustomExtension>>();
var behavior = A.Fake<IBehavior<ICustomExtension>>();
this.SetupCreateActionExecutableReturnsExecutable(extension);
A.CallTo(() => extension.Add(A<IBehavior<ICustomExtension>>._)).Invokes((IBehavior<ICustomExtension> b) => interceptedBehavior = b);
this.testee
.Execute(() => this.DoNothing())
.With(() => behavior);
interceptedBehavior.Behave(Enumerable.Empty<ICustomExtension>());
A.CallTo(() => behavior.Behave(Enumerable.Empty<ICustomExtension>())).MustHaveHappened();
}
[Fact]
public void WithAfterExecuteWithActionOnExtension_Behavior_ShouldAddExecutable()
{
A.CallTo(() => this.executableFactory.CreateExecutable(A<Expression<Action<ICustomExtension>>>._)).Returns(A.Fake<IExecutable<ICustomExtension>>());
this.testee
.Execute(e => e.Dispose())
.With(A.Fake<IBehavior<ICustomExtension>>());
this.testee.Should().HaveCount(1);
}
[Fact]
public void WithAfterExecuteWithActionOnExtension_BehaviorMultipleTimes_ShouldOnlyAddOneExecutable()
{
A.CallTo(() => this.executableFactory.CreateExecutable(A<Expression<Action<ICustomExtension>>>._)).Returns(A.Fake<IExecutable<ICustomExtension>>());
this.testee.Execute(e => e.Dispose())
.With(A.Fake<IBehavior<ICustomExtension>>())
.With(A.Fake<IBehavior<ICustomExtension>>())
.With(A.Fake<IBehavior<ICustomExtension>>());
this.testee.Should().HaveCount(1);
}
[Fact]
public void WithAfterExecuteWithActionOnExtension_Behavior_ShouldAddBehaviorToLastExecutable()
{
var extension = A.Fake<IExecutable<ICustomExtension>>();
var behavior = A.Fake<IBehavior<ICustomExtension>>();
A.CallTo(() => this.executableFactory.CreateExecutable(A<Expression<Action<ICustomExtension>>>._)).Returns(extension);
this.testee
.Execute(e => e.Dispose())
.With(behavior);
A.CallTo(() => extension.Add(behavior)).MustHaveHappened();
}
[Fact]
public void WithAfterExecuteWithActionOnExtension_BehaviorMultipleTimes_ShouldAddBehaviorToLastExecutable()
{
var extension = A.Fake<IExecutable<ICustomExtension>>();
var firstBehavior = A.Fake<IBehavior<ICustomExtension>>();
var secondBehavior = A.Fake<IBehavior<ICustomExtension>>();
var thirdBehavior = A.Fake<IBehavior<ICustomExtension>>();
A.CallTo(() => this.executableFactory.CreateExecutable(A<Expression<Action<ICustomExtension>>>._)).Returns(extension);
this.testee
.Execute(e => e.Dispose())
.With(firstBehavior)
.With(secondBehavior)
.With(thirdBehavior);
A.CallTo(() => extension.Add(firstBehavior)).MustHaveHappened();
A.CallTo(() => extension.Add(secondBehavior)).MustHaveHappened();
A.CallTo(() => extension.Add(thirdBehavior)).MustHaveHappened();
}
[Fact]
public void WithBoundLateAfterExecuteWithActionOnExtension_Behavior_ShouldAddExecutable()
{
A.CallTo(() => this.executableFactory.CreateExecutable(A<Expression<Action<ICustomExtension>>>._)).Returns(A.Fake<IExecutable<ICustomExtension>>());
this.testee
.Execute(e => e.Dispose())
.With(() => A.Fake<IBehavior<ICustomExtension>>());
this.testee.Should().HaveCount(1);
}
[Fact]
public void WithLateBoundAfterExecuteWithActionOnExtension_BehaviorMultipleTimes_ShouldOnlyAddOneExecutable()
{
A.CallTo(() => this.executableFactory.CreateExecutable(A<Expression<Action<ICustomExtension>>>._)).Returns(A.Fake<IExecutable<ICustomExtension>>());
this.testee.Execute(e => e.Dispose())
.With(() => A.Fake<IBehavior<ICustomExtension>>())
.With(() => A.Fake<IBehavior<ICustomExtension>>())
.With(() => A.Fake<IBehavior<ICustomExtension>>());
this.testee.Should().HaveCount(1);
}
[Fact]
public void WithLateBoundAfterExecuteWithActionOnExtension_Behavior_ShouldAddBehaviorToLastExecutable()
{
var extension = A.Fake<IExecutable<ICustomExtension>>();
var behavior = A.Fake<IBehavior<ICustomExtension>>();
A.CallTo(() => this.executableFactory.CreateExecutable(A<Expression<Action<ICustomExtension>>>._)).Returns(extension);
this.testee
.Execute(e => e.Dispose())
.With(() => behavior);
A.CallTo(() => extension.Add(A<IBehavior<ICustomExtension>>._)).MustHaveHappened();
}
[Fact]
public void WithLateBoundAfterExecuteWithActionOnExtension_BehaviorMultipleTimes_ShouldAddBehaviorToLastExecutable()
{
var extension = A.Fake<IExecutable<ICustomExtension>>();
var firstBehavior = A.Fake<IBehavior<ICustomExtension>>();
var secondBehavior = A.Fake<IBehavior<ICustomExtension>>();
var thirdBehavior = A.Fake<IBehavior<ICustomExtension>>();
A.CallTo(() => this.executableFactory.CreateExecutable(A<Expression<Action<ICustomExtension>>>._)).Returns(extension);
this.testee
.Execute(e => e.Dispose())
.With(() => firstBehavior)
.With(() => secondBehavior)
.With(() => thirdBehavior);
A.CallTo(() => extension.Add(A<IBehavior<ICustomExtension>>._)).MustHaveHappened(Repeated.Exactly.Times(3));
}
[Fact]
public void WithLateBoundAfterExecuteWithActionOnExtension_Behavior_ShouldBehaveLateBound()
{
IBehavior<ICustomExtension> interceptedBehavior = null;
var extension = A.Fake<IExecutable<ICustomExtension>>();
var behavior = A.Fake<IBehavior<ICustomExtension>>();
A.CallTo(() => this.executableFactory.CreateExecutable(A<Expression<Action<ICustomExtension>>>._)).Returns(extension);
A.CallTo(() => extension.Add(A<IBehavior<ICustomExtension>>._)).Invokes((IBehavior<ICustomExtension> b) => interceptedBehavior = b);
this.testee
.Execute(e => e.Dispose())
.With(() => behavior);
interceptedBehavior.Behave(Enumerable.Empty<ICustomExtension>());
A.CallTo(() => behavior.Behave(Enumerable.Empty<ICustomExtension>())).MustHaveHappened();
}
[Fact]
public void WithAfterExecuteWithActionOnExtensionWithInitializer_Behavior_ShouldAddExecutable()
{
A.CallTo(() => this.executableFactory.CreateExecutable(A<Expression<Func<object>>>._, A<Expression<Action<ICustomExtension, object>>>._, A<Action<IBehaviorAware<ICustomExtension>, object>>._)).Returns(A.Fake<IExecutable<ICustomExtension>>());
this.testee
.Execute(() => new object(), (e, o) => e.Dispose())
.With(o => A.Fake<IBehavior<ICustomExtension>>());
this.testee.Should().HaveCount(1);
}
[Fact]
public void WithAfterExecuteWithActionOnExtensionWithInitializer_BehaviorMultipleTimes_ShouldOnlyAddOneExecutable()
{
A.CallTo(() => this.executableFactory.CreateExecutable(A<Expression<Func<object>>>._, A<Expression<Action<ICustomExtension, object>>>._, A<Action<IBehaviorAware<ICustomExtension>, object>>._)).Returns(A.Fake<IExecutable<ICustomExtension>>());
this.testee.Execute(() => new object(), (e, o) => e.Dispose())
.With(o => A.Fake<IBehavior<ICustomExtension>>())
.With(o => A.Fake<IBehavior<ICustomExtension>>())
.With(o => A.Fake<IBehavior<ICustomExtension>>());
this.testee.Should().HaveCount(1);
}
[Fact]
public void WithAfterExecuteWithActionOnExtensionWithInitializer_Behavior_ShouldAddBehaviorToLastExecutable()
{
IBehavior<ICustomExtension> behavior = null;
Action<IBehaviorAware<ICustomExtension>, object> contextInitializer = null;
var extension = A.Fake<IExecutable<ICustomExtension>>();
A.CallTo(() => extension.Add(A<IBehavior<ICustomExtension>>._)).Invokes((IBehavior<ICustomExtension> b) => behavior = b);
A.CallTo(() => this.executableFactory.CreateExecutable(
A<Expression<Func<object>>>._,
A<Expression<Action<ICustomExtension, object>>>._,
A<Action<IBehaviorAware<ICustomExtension>, object>>._))
.Invokes((Expression<Func<object>> func, Expression<Action<ICustomExtension, object>> action, Action<IBehaviorAware<ICustomExtension>, object> ctx) => contextInitializer = ctx)
.Returns(A.Fake<IExecutable<ICustomExtension>>());
var context = new object();
this.testee.Execute(() => context, (e, o) => e.Dispose()).With(o => new TestableBehavior(o));
contextInitializer(extension, context);
behavior.Should().NotBeNull();
behavior.As<TestableBehavior>().Context.Should().Be(context);
}
private class TestableBehavior : IBehavior<ICustomExtension>
{
private readonly object context;
public TestableBehavior(object context)
{
this.context = context;
}
/// <inheritdoc />
public string Name
{
get
{
return this.GetType().FullNameToString();
}
}
public object Context
{
get
{
return this.context;
}
}
public void Behave(IEnumerable<ICustomExtension> extensions)
{
}
public string Describe()
{
return "Behaves by doing nothing.";
}
}
[Theory,
InlineData("ABC", "ABCI"),
InlineData("CBA", "CIBA"),
InlineData("AAA", "AAA"),
InlineData("BBB", "BBB"),
InlineData("CCC", "CICICI")]
public void Execute_Chaining_ShouldBePossible(string execution, string expected)
{
this.ExecuteChaining(execution);
this.executionChainingBuilder.ToString().Should().Be(expected);
}
[Theory,
InlineData("ABC", 3),
InlineData("CBA", 3),
InlineData("AAA", 3),
InlineData("BBB", 3),
InlineData("CCC", 3),
InlineData("AAAA", 4),
InlineData("AAAAA", 5)]
public void Enumeration_ShouldProvideDefinedExecutables(string execution, int expected)
{
this.ExecuteChaining(execution);
this.testee.Count().Should().Be(expected);
}
private void DoNothing()
{
}
private void ExecuteChaining(string syntax)
{
this.SetupAutoExecutionOfExecutables();
Dictionary<char, Action> actions = this.DefineCharToActionMapping();
foreach (char c in syntax.ToUpperInvariant())
{
actions[c].Invoke();
}
}
private void SetupAutoExecutionOfExecutables()
{
A.CallTo(() => this.executableFactory.CreateExecutable(A<Expression<Action>>._))
.Invokes((Expression<Action> action) => action.Compile()())
.Returns(A.Fake<IExecutable<ICustomExtension>>());
A.CallTo(() => this.executableFactory.CreateExecutable(A<Expression<Action<ICustomExtension>>>._))
.Invokes((Expression<Action<ICustomExtension>> action) => action.Compile()(A.Fake<ICustomExtension>()))
.Returns(A.Fake<IExecutable<ICustomExtension>>());
A.CallTo(() => this.executableFactory.CreateExecutable(A<Expression<Func<char>>>._, A<Expression<Action<ICustomExtension, char>>>._, A<Action<IBehaviorAware<ICustomExtension>, char>>._))
.Invokes((Expression<Func<char>> func, Expression<Action<ICustomExtension, char>> action, Action<IBehaviorAware<ICustomExtension>, char> context) =>
{
var ctx = func.Compile()();
context(A.Fake<IBehaviorAware<ICustomExtension>>(), ctx);
action.Compile()(A.Fake<ICustomExtension>(), ctx);
})
.Returns(A.Fake<IExecutable<ICustomExtension>>());
}
private Dictionary<char, Action> DefineCharToActionMapping()
{
return new Dictionary<char, Action>
{
{ 'A', () => this.testee.Execute(() => this.executionChainingBuilder.Append('A')) },
{ 'B', () => this.testee.Execute(extension => this.executionChainingBuilder.Append('B')) },
{
'C', () => this.testee.Execute(
() => 'I',
(extension, context) => this.AppendValue(context))
},
};
}
private void AppendValue(char context)
{
this.executionChainingBuilder.Append('C');
this.executionChainingBuilder.Append(context);
}
private void SetupCreateActionExecutableReturnsExecutable(IExecutable<ICustomExtension> executable)
{
A.CallTo(() => this.executableFactory.CreateExecutable(A<Expression<Action>>._)).Returns(executable);
}
private void SetupCreateActionExecutableReturnsAnyExecutable()
{
this.SetupCreateActionExecutableReturnsExecutable(A.Fake<IExecutable<ICustomExtension>>());
}
}
}
| |
// 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.ApplicationInsights.Management
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.ApplicationInsights;
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>
/// ComponentsOperations operations.
/// </summary>
internal partial class ComponentsOperations : IServiceOperations<ApplicationInsightsManagementClient>, IComponentsOperations
{
/// <summary>
/// Initializes a new instance of the ComponentsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ComponentsOperations(ApplicationInsightsManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the ApplicationInsightsManagementClient
/// </summary>
public ApplicationInsightsManagementClient Client { get; private set; }
/// <summary>
/// Gets a list of all Application Insights components within a subscription.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ApplicationInsightsComponent>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/microsoft.insights/components").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<ApplicationInsightsComponent>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ApplicationInsightsComponent>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a list of Application Insights components within a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ApplicationInsightsComponent>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByResourceGroup", 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.insights/components").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<ApplicationInsightsComponent>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ApplicationInsightsComponent>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes an Application Insights component.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='resourceName'>
/// The name of the Application Insights component resource.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string resourceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceName");
}
// 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("resourceName", resourceName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{resourceName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(resourceName));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Returns an Application Insights component.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='resourceName'>
/// The name of the Application Insights component resource.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ApplicationInsightsComponent>> GetWithHttpMessagesAsync(string resourceGroupName, string resourceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceName");
}
// 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("resourceName", resourceName);
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.insights/components/{resourceName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(resourceName));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ApplicationInsightsComponent>();
_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<ApplicationInsightsComponent>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates (or updates) an Application Insights component. Note: You cannot
/// specify a different value for InstrumentationKey nor AppId in the Put
/// operation.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='resourceName'>
/// The name of the Application Insights component resource.
/// </param>
/// <param name='insightProperties'>
/// Properties that need to be specified to create an Application Insights
/// component.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ApplicationInsightsComponent>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string resourceName, ApplicationInsightsComponent insightProperties, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceName");
}
if (insightProperties == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "insightProperties");
}
if (insightProperties != null)
{
insightProperties.Validate();
}
// 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("resourceName", resourceName);
tracingParameters.Add("insightProperties", insightProperties);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{resourceName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(resourceName));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(insightProperties != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(insightProperties, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ApplicationInsightsComponent>();
_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<ApplicationInsightsComponent>(_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>
/// Updates an existing component's tags. To update other fields use the
/// CreateOrUpdate method.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='resourceName'>
/// The name of the Application Insights component resource.
/// </param>
/// <param name='tags'>
/// Resource tags
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ApplicationInsightsComponent>> UpdateTagsWithHttpMessagesAsync(string resourceGroupName, string resourceName, IDictionary<string, string> tags = default(IDictionary<string, string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceName");
}
TagsResource componentTags = new TagsResource();
if (tags != null)
{
componentTags.Tags = tags;
}
// 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("resourceName", resourceName);
tracingParameters.Add("componentTags", componentTags);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "UpdateTags", 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.insights/components/{resourceName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(resourceName));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PATCH");
_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(componentTags != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(componentTags, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ApplicationInsightsComponent>();
_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<ApplicationInsightsComponent>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a list of all Application Insights components within a subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ApplicationInsightsComponent>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<ApplicationInsightsComponent>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ApplicationInsightsComponent>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a list of Application Insights components within a resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ApplicationInsightsComponent>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByResourceGroupNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<ApplicationInsightsComponent>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ApplicationInsightsComponent>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using Xunit;
namespace System.Collections.Immutable.Tests
{
public class ImmutableStackTest : SimpleElementImmutablesTestBase
{
/// <summary>
/// A test for Empty
/// </summary>
/// <typeparam name="T">The type of elements held in the stack.</typeparam>
private void EmptyTestHelper<T>() where T : new()
{
IImmutableStack<T> actual = ImmutableStack<T>.Empty;
Assert.NotNull(actual);
Assert.True(actual.IsEmpty);
AssertAreSame(ImmutableStack<T>.Empty, actual.Clear());
AssertAreSame(ImmutableStack<T>.Empty, actual.Push(new T()).Clear());
}
private ImmutableStack<T> InitStackHelper<T>(params T[] values)
{
Assert.NotNull(values);
var result = ImmutableStack<T>.Empty;
foreach (var value in values)
{
result = result.Push(value);
}
return result;
}
private void PushAndCountTestHelper<T>() where T : new()
{
var actual0 = ImmutableStack<T>.Empty;
Assert.Equal(0, actual0.Count());
var actual1 = actual0.Push(new T());
Assert.Equal(1, actual1.Count());
Assert.Equal(0, actual0.Count());
var actual2 = actual1.Push(new T());
Assert.Equal(2, actual2.Count());
Assert.Equal(0, actual0.Count());
}
private void PopTestHelper<T>(params T[] values)
{
Assert.NotNull(values);
Assert.InRange(values.Length, 1, int.MaxValue);
var full = this.InitStackHelper(values);
var currentStack = full;
// This loop tests the immutable properties of Pop.
for (int expectedCount = values.Length; expectedCount > 0; expectedCount--)
{
Assert.Equal(expectedCount, currentStack.Count());
currentStack.Pop();
Assert.Equal(expectedCount, currentStack.Count());
var nextStack = currentStack.Pop();
Assert.Equal(expectedCount, currentStack.Count());
Assert.NotSame(currentStack, nextStack);
AssertAreSame(currentStack.Pop(), currentStack.Pop());
currentStack = nextStack;
}
}
private void PeekTestHelper<T>(params T[] values)
{
Assert.NotNull(values);
Assert.InRange(values.Length, 1, int.MaxValue);
var current = this.InitStackHelper(values);
for (int i = values.Length - 1; i >= 0; i--)
{
AssertAreSame(values[i], current.Peek());
T element;
current.Pop(out element);
AssertAreSame(current.Peek(), element);
var next = current.Pop();
AssertAreSame(values[i], current.Peek());
current = next;
}
}
private void EnumeratorTestHelper<T>(params T[] values)
{
var full = this.InitStackHelper(values);
int i = values.Length - 1;
foreach (var element in full)
{
AssertAreSame(values[i--], element);
}
Assert.Equal(-1, i);
i = values.Length - 1;
foreach (T element in (System.Collections.IEnumerable)full)
{
AssertAreSame(values[i--], element);
}
Assert.Equal(-1, i);
}
[Fact]
public void EmptyTest()
{
this.EmptyTestHelper<GenericParameterHelper>();
this.EmptyTestHelper<int>();
}
[Fact]
public void PushAndCountTest()
{
this.PushAndCountTestHelper<GenericParameterHelper>();
this.PushAndCountTestHelper<int>();
}
[Fact]
public void PopTest()
{
this.PopTestHelper(
new GenericParameterHelper(1),
new GenericParameterHelper(2),
new GenericParameterHelper(3));
this.PopTestHelper(1, 2, 3);
}
[Fact]
public void PopOutValue()
{
var stack = ImmutableStack<int>.Empty.Push(5).Push(6);
int top;
stack = stack.Pop(out top);
Assert.Equal(6, top);
var empty = stack.Pop(out top);
Assert.Equal(5, top);
Assert.True(empty.IsEmpty);
// Try again with the interface to verify extension method behavior.
IImmutableStack<int> stackInterface = stack;
Assert.Same(empty, stackInterface.Pop(out top));
Assert.Equal(5, top);
}
[Fact]
public void PeekTest()
{
this.PeekTestHelper(
new GenericParameterHelper(1),
new GenericParameterHelper(2),
new GenericParameterHelper(3));
this.PeekTestHelper(1, 2, 3);
}
[Fact]
public void EnumeratorTest()
{
this.EnumeratorTestHelper(new GenericParameterHelper(1), new GenericParameterHelper(2));
this.EnumeratorTestHelper<GenericParameterHelper>();
this.EnumeratorTestHelper(1, 2);
this.EnumeratorTestHelper<int>();
var stack = ImmutableStack.Create<int>(5);
var enumeratorStruct = stack.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumeratorStruct.Current);
Assert.True(enumeratorStruct.MoveNext());
Assert.Equal(5, enumeratorStruct.Current);
Assert.False(enumeratorStruct.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumeratorStruct.Current);
Assert.False(enumeratorStruct.MoveNext());
var enumerator = ((IEnumerable<int>)stack).GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.Equal(5, enumerator.Current);
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.False(enumerator.MoveNext());
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.Equal(5, enumerator.Current);
Assert.False(enumerator.MoveNext());
enumerator.Dispose();
Assert.Throws<ObjectDisposedException>(() => enumerator.Reset());
Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumerator.Current);
}
[Fact]
public void EqualityTest()
{
Assert.False(ImmutableStack<int>.Empty.Equals(null));
Assert.False(ImmutableStack<int>.Empty.Equals("hi"));
Assert.Equal(ImmutableStack<int>.Empty, ImmutableStack<int>.Empty);
Assert.Equal(ImmutableStack<int>.Empty.Push(3), ImmutableStack<int>.Empty.Push(3));
Assert.NotEqual(ImmutableStack<int>.Empty.Push(5), ImmutableStack<int>.Empty.Push(3));
Assert.NotEqual(ImmutableStack<int>.Empty.Push(3).Push(5), ImmutableStack<int>.Empty.Push(3));
Assert.NotEqual(ImmutableStack<int>.Empty.Push(3), ImmutableStack<int>.Empty.Push(3).Push(5));
}
[Fact]
public void GetEnumerator_EmptyStackMoveNext_ReturnsFalse()
{
ImmutableStack<int> stack = ImmutableStack<int>.Empty;
Assert.False(stack.GetEnumerator().MoveNext());
}
[Fact]
public void EmptyPeekThrows()
{
Assert.Throws<InvalidOperationException>(() => ImmutableStack<GenericParameterHelper>.Empty.Peek());
}
[Fact]
public void EmptyPopThrows()
{
Assert.Throws<InvalidOperationException>(() => ImmutableStack<GenericParameterHelper>.Empty.Pop());
}
[Fact]
public void Create()
{
ImmutableStack<int> stack = ImmutableStack.Create<int>();
Assert.True(stack.IsEmpty);
stack = ImmutableStack.Create(1);
Assert.False(stack.IsEmpty);
Assert.Equal(new[] { 1 }, stack);
stack = ImmutableStack.Create(1, 2);
Assert.False(stack.IsEmpty);
Assert.Equal(new[] { 2, 1 }, stack);
stack = ImmutableStack.CreateRange((IEnumerable<int>)new[] { 1, 2 });
Assert.False(stack.IsEmpty);
Assert.Equal(new[] { 2, 1 }, stack);
AssertExtensions.Throws<ArgumentNullException>("items", () => ImmutableStack.CreateRange((IEnumerable<int>)null));
AssertExtensions.Throws<ArgumentNullException>("items", () => ImmutableStack.Create((int[])null));
}
[Fact]
public void DebuggerAttributesValid()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableStack.Create<int>());
ImmutableStack<string> stack = ImmutableStack.Create<string>("1", "2", "3");
DebuggerAttributeInfo info = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(stack);
PropertyInfo itemProperty = info.Properties.Single(pr => pr.GetCustomAttribute<DebuggerBrowsableAttribute>().State == DebuggerBrowsableState.RootHidden);
string[] items = itemProperty.GetValue(info.Instance) as string[];
Assert.Equal(stack, items);
}
[Fact]
public static void TestDebuggerAttributes_Null()
{
Type proxyType = DebuggerAttributes.GetProxyType(ImmutableStack.Create<string>("1", "2", "3"));
TargetInvocationException tie = Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(proxyType, (object)null));
Assert.IsType<ArgumentNullException>(tie.InnerException);
}
[Fact]
public void PeekRef()
{
var stack = ImmutableStack<int>.Empty
.Push(1)
.Push(2)
.Push(3);
ref readonly var safeRef = ref stack.PeekRef();
ref var unsafeRef = ref Unsafe.AsRef(safeRef);
Assert.Equal(3, stack.PeekRef());
unsafeRef = 4;
Assert.Equal(4, stack.PeekRef());
}
[Fact]
public void PeekRef_Empty()
{
var stack = ImmutableStack<int>.Empty;
Assert.Throws<InvalidOperationException>(() => stack.PeekRef());
}
protected override IEnumerable<T> GetEnumerableOf<T>(params T[] contents)
{
var stack = ImmutableStack<T>.Empty;
foreach (var value in contents.Reverse())
{
stack = stack.Push(value);
}
return stack;
}
}
}
| |
/***************************************************************************
copyright : (C) 2005 by Brian Nickel
email : brian.nickel@gmail.com
based on : wvfile.cpp from libtunepimp
***************************************************************************/
/***************************************************************************
* This library is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License version *
* 2.1 as published by the Free Software Foundation. *
* *
* This library is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
* USA *
***************************************************************************/
using System.Collections;
using System;
namespace TagLib.WavPack
{
[SupportedMimeType("taglib/wv", "wv")]
[SupportedMimeType("audio/x-wavpack")]
public class File : TagLib.File
{
//////////////////////////////////////////////////////////////////////////
// private properties
//////////////////////////////////////////////////////////////////////////
private Ape.Tag ape_tag;
private Id3v1.Tag id3v1_tag;
private CombinedTag tag;
private Properties properties;
//////////////////////////////////////////////////////////////////////////
// public methods
//////////////////////////////////////////////////////////////////////////
public File (string file, Properties.ReadStyle properties_style) : base (file)
{
ape_tag = null;
id3v1_tag = null;
tag = new CombinedTag ();
properties = null;
Mode = AccessMode.Read;
Read (properties_style);
Mode = AccessMode.Closed;
}
public File (string file) : this (file, Properties.ReadStyle.Average)
{
}
public override void Save ()
{
Mode = AccessMode.Write;
long tag_start, tag_end;
// Update ID3v1 tag
FindId3v1 (out tag_start, out tag_end);
if (id3v1_tag == null)
RemoveBlock (tag_start, tag_end - tag_start);
else
Insert (id3v1_tag.Render (), tag_start, tag_end - tag_start);
// Update Ape tag
FindApe (id3v1_tag != null, out tag_start, out tag_end);
if (ape_tag == null)
RemoveBlock (tag_start, tag_end - tag_start);
else
Insert (ape_tag.Render (), tag_start, tag_end - tag_start);
Mode = AccessMode.Closed;
}
public override TagLib.Tag GetTag (TagTypes type, bool create)
{
switch (type)
{
case TagTypes.Id3v1:
{
if (create && id3v1_tag == null)
{
id3v1_tag = new Id3v1.Tag ();
if (tag != null)
TagLib.Tag.Duplicate (tag, id3v1_tag, true);
tag.SetTags (ape_tag, id3v1_tag);
}
return id3v1_tag;
}
case TagTypes.Ape:
{
if (create && ape_tag == null)
{
ape_tag = new Ape.Tag ();
if (tag != null)
TagLib.Tag.Duplicate (tag, ape_tag, true);
tag.SetTags (ape_tag, id3v1_tag);
}
return ape_tag;
}
default:
return null;
}
}
public void Remove (TagTypes types)
{
if ((types & TagTypes.Id3v1) != 0)
id3v1_tag = null;
if ((types & TagTypes.Ape) != 0)
ape_tag = null;
tag.SetTags (ape_tag, id3v1_tag);
}
public void Remove ()
{
Remove (TagTypes.AllTags);
}
//////////////////////////////////////////////////////////////////////////
// public properties
//////////////////////////////////////////////////////////////////////////
public override TagLib.Tag Tag {get {return tag;}}
public override TagLib.AudioProperties AudioProperties {get {return properties;}}
//////////////////////////////////////////////////////////////////////////
// private methods
//////////////////////////////////////////////////////////////////////////
private void Read (Properties.ReadStyle properties_style)
{
long tag_start, tag_end, ape_tag_start;
bool has_id3v1 = FindId3v1 (out tag_start, out tag_end);
if (has_id3v1)
id3v1_tag = new Id3v1.Tag (this, tag_start);
if (FindApe (has_id3v1, out ape_tag_start, out tag_end))
ape_tag = new Ape.Tag (this, ape_tag_start);
tag.SetTags (ape_tag, id3v1_tag);
GetTag (TagTypes.Ape, true);
// Look for MPC metadata
if (properties_style != Properties.ReadStyle.None)
{
Seek (0);
properties = new Properties (ReadBlock ((int) Properties.HeaderSize),
ape_tag_start);
}
}
private bool FindApe (bool has_id3v1, out long start, out long end)
{
Seek (has_id3v1 ? -160 : -32, System.IO.SeekOrigin.End);
start = end = Tell + 32;
ByteVector data = ReadBlock (32);
if (data.StartsWith (Ape.Tag.FileIdentifier))
{
Ape.Footer footer = new Ape.Footer (data);
start = end - footer.CompleteTagSize;
return true;
}
return false;
}
private bool FindId3v1 (out long start, out long end)
{
Seek (-128, System.IO.SeekOrigin.End);
start = Tell;
end = Length;
if (ReadBlock (3) == Id3v1.Tag.FileIdentifier)
return true;
start = end;
return false;
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Input.Events;
using osu.Game.Beatmaps;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.UserInterface;
using osu.Game.Online.Placeholders;
using osu.Game.Scoring;
using osuTK;
namespace osu.Game.Screens.Ranking.Statistics
{
public class StatisticsPanel : VisibilityContainer
{
public const float SIDE_PADDING = 30;
public readonly Bindable<ScoreInfo> Score = new Bindable<ScoreInfo>();
protected override bool StartHidden => true;
[Resolved]
private BeatmapManager beatmapManager { get; set; }
private readonly Container content;
private readonly LoadingSpinner spinner;
public StatisticsPanel()
{
InternalChild = new Container
{
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding
{
Left = ScorePanel.EXPANDED_WIDTH + SIDE_PADDING * 3,
Right = SIDE_PADDING,
Top = SIDE_PADDING,
Bottom = 50 // Approximate padding to the bottom of the score panel.
},
Children = new Drawable[]
{
content = new Container { RelativeSizeAxes = Axes.Both },
spinner = new LoadingSpinner()
}
};
}
[BackgroundDependencyLoader]
private void load()
{
Score.BindValueChanged(populateStatistics, true);
}
private CancellationTokenSource loadCancellation;
private void populateStatistics(ValueChangedEvent<ScoreInfo> score)
{
loadCancellation?.Cancel();
loadCancellation = null;
foreach (var child in content)
child.FadeOut(150).Expire();
spinner.Hide();
var newScore = score.NewValue;
if (newScore == null)
return;
spinner.Show();
var localCancellationSource = loadCancellation = new CancellationTokenSource();
IBeatmap playableBeatmap = null;
// Todo: The placement of this is temporary. Eventually we'll both generate the playable beatmap _and_ run through it in a background task to generate the hit events.
Task.Run(() =>
{
playableBeatmap = beatmapManager.GetWorkingBeatmap(newScore.BeatmapInfo).GetPlayableBeatmap(newScore.Ruleset, newScore.Mods);
}, loadCancellation.Token).ContinueWith(t => Schedule(() =>
{
bool hitEventsAvailable = newScore.HitEvents.Count != 0;
Container<Drawable> container;
var statisticRows = newScore.Ruleset.CreateInstance().CreateStatisticsForScore(newScore, playableBeatmap);
if (!hitEventsAvailable && statisticRows.SelectMany(r => r.Columns).All(c => c.RequiresHitEvents))
{
container = new FillFlowContainer
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Direction = FillDirection.Vertical,
Children = new Drawable[]
{
new MessagePlaceholder("Extended statistics are only available after watching a replay!"),
new ReplayDownloadButton(newScore)
{
Scale = new Vector2(1.5f),
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
},
}
};
}
else
{
FillFlowContainer rows;
container = new OsuScrollContainer(Direction.Vertical)
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Alpha = 0,
Children = new[]
{
rows = new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Spacing = new Vector2(30, 15)
}
}
};
bool anyRequiredHitEvents = false;
foreach (var row in statisticRows)
{
var columns = row.Columns;
if (columns.Length == 0)
continue;
var columnContent = new List<Drawable>();
var dimensions = new List<Dimension>();
foreach (var col in columns)
{
if (!hitEventsAvailable && col.RequiresHitEvents)
{
anyRequiredHitEvents = true;
continue;
}
columnContent.Add(new StatisticContainer(col)
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
});
dimensions.Add(col.Dimension ?? new Dimension());
}
rows.Add(new GridContainer
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Content = new[] { columnContent.ToArray() },
ColumnDimensions = dimensions.ToArray(),
RowDimensions = new[] { new Dimension(GridSizeMode.AutoSize) }
});
}
if (anyRequiredHitEvents)
{
rows.Add(new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
Children = new Drawable[]
{
new MessagePlaceholder("More statistics available after watching a replay!"),
new ReplayDownloadButton(newScore)
{
Scale = new Vector2(1.5f),
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
},
}
});
}
}
LoadComponentAsync(container, d =>
{
if (!Score.Value.Equals(newScore))
return;
spinner.Hide();
content.Add(d);
d.FadeIn(250, Easing.OutQuint);
}, localCancellationSource.Token);
}), localCancellationSource.Token);
}
protected override bool OnClick(ClickEvent e)
{
ToggleVisibility();
return true;
}
protected override void PopIn() => this.FadeIn(150, Easing.OutQuint);
protected override void PopOut() => this.FadeOut(150, Easing.OutQuint);
protected override void Dispose(bool isDisposing)
{
loadCancellation?.Cancel();
base.Dispose(isDisposing);
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gctv = Google.Cloud.Tasks.V2Beta3;
using sys = System;
namespace Google.Cloud.Tasks.V2Beta3
{
/// <summary>Resource name for the <c>Queue</c> resource.</summary>
public sealed partial class QueueName : gax::IResourceName, sys::IEquatable<QueueName>
{
/// <summary>The possible contents of <see cref="QueueName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/locations/{location}/queues/{queue}</c>.
/// </summary>
ProjectLocationQueue = 1,
}
private static gax::PathTemplate s_projectLocationQueue = new gax::PathTemplate("projects/{project}/locations/{location}/queues/{queue}");
/// <summary>Creates a <see cref="QueueName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="QueueName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static QueueName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new QueueName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="QueueName"/> with the pattern <c>projects/{project}/locations/{location}/queues/{queue}</c>
/// .
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="queueId">The <c>Queue</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="QueueName"/> constructed from the provided ids.</returns>
public static QueueName FromProjectLocationQueue(string projectId, string locationId, string queueId) =>
new QueueName(ResourceNameType.ProjectLocationQueue, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), queueId: gax::GaxPreconditions.CheckNotNullOrEmpty(queueId, nameof(queueId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="QueueName"/> with pattern
/// <c>projects/{project}/locations/{location}/queues/{queue}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="queueId">The <c>Queue</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="QueueName"/> with pattern
/// <c>projects/{project}/locations/{location}/queues/{queue}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string queueId) =>
FormatProjectLocationQueue(projectId, locationId, queueId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="QueueName"/> with pattern
/// <c>projects/{project}/locations/{location}/queues/{queue}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="queueId">The <c>Queue</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="QueueName"/> with pattern
/// <c>projects/{project}/locations/{location}/queues/{queue}</c>.
/// </returns>
public static string FormatProjectLocationQueue(string projectId, string locationId, string queueId) =>
s_projectLocationQueue.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(queueId, nameof(queueId)));
/// <summary>Parses the given resource name string into a new <see cref="QueueName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/queues/{queue}</c></description></item>
/// </list>
/// </remarks>
/// <param name="queueName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="QueueName"/> if successful.</returns>
public static QueueName Parse(string queueName) => Parse(queueName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="QueueName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/queues/{queue}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="queueName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="QueueName"/> if successful.</returns>
public static QueueName Parse(string queueName, bool allowUnparsed) =>
TryParse(queueName, allowUnparsed, out QueueName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="QueueName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/queues/{queue}</c></description></item>
/// </list>
/// </remarks>
/// <param name="queueName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="QueueName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string queueName, out QueueName result) => TryParse(queueName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="QueueName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/queues/{queue}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="queueName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="QueueName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string queueName, bool allowUnparsed, out QueueName result)
{
gax::GaxPreconditions.CheckNotNull(queueName, nameof(queueName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationQueue.TryParseName(queueName, out resourceName))
{
result = FromProjectLocationQueue(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(queueName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private QueueName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string projectId = null, string queueId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
LocationId = locationId;
ProjectId = projectId;
QueueId = queueId;
}
/// <summary>
/// Constructs a new instance of a <see cref="QueueName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/queues/{queue}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="queueId">The <c>Queue</c> ID. Must not be <c>null</c> or empty.</param>
public QueueName(string projectId, string locationId, string queueId) : this(ResourceNameType.ProjectLocationQueue, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), queueId: gax::GaxPreconditions.CheckNotNullOrEmpty(queueId, nameof(queueId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>Queue</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string QueueId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationQueue: return s_projectLocationQueue.Expand(ProjectId, LocationId, QueueId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as QueueName);
/// <inheritdoc/>
public bool Equals(QueueName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(QueueName a, QueueName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(QueueName a, QueueName b) => !(a == b);
}
public partial class Queue
{
/// <summary>
/// <see cref="gctv::QueueName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gctv::QueueName QueueName
{
get => string.IsNullOrEmpty(Name) ? null : gctv::QueueName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
using System;
using System.Text;
using System.Collections.Generic;
using Adaptive.Agrona;
namespace Adaptive.Archiver.Codecs {
public class TaggedReplicateRequestDecoder
{
public const ushort BLOCK_LENGTH = 52;
public const ushort TEMPLATE_ID = 62;
public const ushort SCHEMA_ID = 101;
public const ushort SCHEMA_VERSION = 6;
private TaggedReplicateRequestDecoder _parentMessage;
private IDirectBuffer _buffer;
protected int _offset;
protected int _limit;
protected int _actingBlockLength;
protected int _actingVersion;
public TaggedReplicateRequestDecoder()
{
_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 IDirectBuffer Buffer()
{
return _buffer;
}
public int Offset()
{
return _offset;
}
public TaggedReplicateRequestDecoder Wrap(
IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion)
{
this._buffer = buffer;
this._offset = offset;
this._actingBlockLength = actingBlockLength;
this._actingVersion = actingVersion;
Limit(offset + actingBlockLength);
return this;
}
public int EncodedLength()
{
return _limit - _offset;
}
public int Limit()
{
return _limit;
}
public void Limit(int limit)
{
this._limit = limit;
}
public static int ControlSessionIdId()
{
return 1;
}
public static int ControlSessionIdSinceVersion()
{
return 0;
}
public static int ControlSessionIdEncodingOffset()
{
return 0;
}
public static int ControlSessionIdEncodingLength()
{
return 8;
}
public static string ControlSessionIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long ControlSessionIdNullValue()
{
return -9223372036854775808L;
}
public static long ControlSessionIdMinValue()
{
return -9223372036854775807L;
}
public static long ControlSessionIdMaxValue()
{
return 9223372036854775807L;
}
public long ControlSessionId()
{
return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian);
}
public static int CorrelationIdId()
{
return 2;
}
public static int CorrelationIdSinceVersion()
{
return 0;
}
public static int CorrelationIdEncodingOffset()
{
return 8;
}
public static int CorrelationIdEncodingLength()
{
return 8;
}
public static string CorrelationIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long CorrelationIdNullValue()
{
return -9223372036854775808L;
}
public static long CorrelationIdMinValue()
{
return -9223372036854775807L;
}
public static long CorrelationIdMaxValue()
{
return 9223372036854775807L;
}
public long CorrelationId()
{
return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian);
}
public static int SrcRecordingIdId()
{
return 3;
}
public static int SrcRecordingIdSinceVersion()
{
return 0;
}
public static int SrcRecordingIdEncodingOffset()
{
return 16;
}
public static int SrcRecordingIdEncodingLength()
{
return 8;
}
public static string SrcRecordingIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long SrcRecordingIdNullValue()
{
return -9223372036854775808L;
}
public static long SrcRecordingIdMinValue()
{
return -9223372036854775807L;
}
public static long SrcRecordingIdMaxValue()
{
return 9223372036854775807L;
}
public long SrcRecordingId()
{
return _buffer.GetLong(_offset + 16, ByteOrder.LittleEndian);
}
public static int DstRecordingIdId()
{
return 4;
}
public static int DstRecordingIdSinceVersion()
{
return 0;
}
public static int DstRecordingIdEncodingOffset()
{
return 24;
}
public static int DstRecordingIdEncodingLength()
{
return 8;
}
public static string DstRecordingIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long DstRecordingIdNullValue()
{
return -9223372036854775808L;
}
public static long DstRecordingIdMinValue()
{
return -9223372036854775807L;
}
public static long DstRecordingIdMaxValue()
{
return 9223372036854775807L;
}
public long DstRecordingId()
{
return _buffer.GetLong(_offset + 24, ByteOrder.LittleEndian);
}
public static int ChannelTagIdId()
{
return 5;
}
public static int ChannelTagIdSinceVersion()
{
return 0;
}
public static int ChannelTagIdEncodingOffset()
{
return 32;
}
public static int ChannelTagIdEncodingLength()
{
return 8;
}
public static string ChannelTagIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long ChannelTagIdNullValue()
{
return -9223372036854775808L;
}
public static long ChannelTagIdMinValue()
{
return -9223372036854775807L;
}
public static long ChannelTagIdMaxValue()
{
return 9223372036854775807L;
}
public long ChannelTagId()
{
return _buffer.GetLong(_offset + 32, ByteOrder.LittleEndian);
}
public static int SubscriptionTagIdId()
{
return 6;
}
public static int SubscriptionTagIdSinceVersion()
{
return 0;
}
public static int SubscriptionTagIdEncodingOffset()
{
return 40;
}
public static int SubscriptionTagIdEncodingLength()
{
return 8;
}
public static string SubscriptionTagIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long SubscriptionTagIdNullValue()
{
return -9223372036854775808L;
}
public static long SubscriptionTagIdMinValue()
{
return -9223372036854775807L;
}
public static long SubscriptionTagIdMaxValue()
{
return 9223372036854775807L;
}
public long SubscriptionTagId()
{
return _buffer.GetLong(_offset + 40, ByteOrder.LittleEndian);
}
public static int SrcControlStreamIdId()
{
return 7;
}
public static int SrcControlStreamIdSinceVersion()
{
return 0;
}
public static int SrcControlStreamIdEncodingOffset()
{
return 48;
}
public static int SrcControlStreamIdEncodingLength()
{
return 4;
}
public static string SrcControlStreamIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int SrcControlStreamIdNullValue()
{
return -2147483648;
}
public static int SrcControlStreamIdMinValue()
{
return -2147483647;
}
public static int SrcControlStreamIdMaxValue()
{
return 2147483647;
}
public int SrcControlStreamId()
{
return _buffer.GetInt(_offset + 48, ByteOrder.LittleEndian);
}
public static int SrcControlChannelId()
{
return 8;
}
public static int SrcControlChannelSinceVersion()
{
return 0;
}
public static string SrcControlChannelCharacterEncoding()
{
return "US-ASCII";
}
public static string SrcControlChannelMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int SrcControlChannelHeaderLength()
{
return 4;
}
public int SrcControlChannelLength()
{
int limit = _parentMessage.Limit();
return (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
}
public int GetSrcControlChannel(IMutableDirectBuffer dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public int GetSrcControlChannel(byte[] dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public string SrcControlChannel()
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
_parentMessage.Limit(limit + headerLength + dataLength);
byte[] tmp = new byte[dataLength];
_buffer.GetBytes(limit + headerLength, tmp, 0, dataLength);
return Encoding.ASCII.GetString(tmp);
}
public static int LiveDestinationId()
{
return 9;
}
public static int LiveDestinationSinceVersion()
{
return 0;
}
public static string LiveDestinationCharacterEncoding()
{
return "US-ASCII";
}
public static string LiveDestinationMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int LiveDestinationHeaderLength()
{
return 4;
}
public int LiveDestinationLength()
{
int limit = _parentMessage.Limit();
return (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
}
public int GetLiveDestination(IMutableDirectBuffer dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public int GetLiveDestination(byte[] dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public string LiveDestination()
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
_parentMessage.Limit(limit + headerLength + dataLength);
byte[] tmp = new byte[dataLength];
_buffer.GetBytes(limit + headerLength, tmp, 0, dataLength);
return Encoding.ASCII.GetString(tmp);
}
public override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
int originalLimit = Limit();
Limit(_offset + _actingBlockLength);
builder.Append("[TaggedReplicateRequest](sbeTemplateId=");
builder.Append(TEMPLATE_ID);
builder.Append("|sbeSchemaId=");
builder.Append(SCHEMA_ID);
builder.Append("|sbeSchemaVersion=");
if (_parentMessage._actingVersion != SCHEMA_VERSION)
{
builder.Append(_parentMessage._actingVersion);
builder.Append('/');
}
builder.Append(SCHEMA_VERSION);
builder.Append("|sbeBlockLength=");
if (_actingBlockLength != BLOCK_LENGTH)
{
builder.Append(_actingBlockLength);
builder.Append('/');
}
builder.Append(BLOCK_LENGTH);
builder.Append("):");
//Token{signal=BEGIN_FIELD, name='controlSessionId', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("ControlSessionId=");
builder.Append(ControlSessionId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='correlationId', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("CorrelationId=");
builder.Append(CorrelationId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='srcRecordingId', referencedName='null', description='null', id=3, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=16, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("SrcRecordingId=");
builder.Append(SrcRecordingId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='dstRecordingId', referencedName='null', description='null', id=4, version=0, deprecated=0, encodedLength=0, offset=24, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=24, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("DstRecordingId=");
builder.Append(DstRecordingId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='channelTagId', referencedName='null', description='null', id=5, version=0, deprecated=0, encodedLength=0, offset=32, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=32, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("ChannelTagId=");
builder.Append(ChannelTagId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='subscriptionTagId', referencedName='null', description='null', id=6, version=0, deprecated=0, encodedLength=0, offset=40, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=40, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("SubscriptionTagId=");
builder.Append(SubscriptionTagId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='srcControlStreamId', referencedName='null', description='null', id=7, version=0, deprecated=0, encodedLength=0, offset=48, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int32', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=4, offset=48, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("SrcControlStreamId=");
builder.Append(SrcControlStreamId());
builder.Append('|');
//Token{signal=BEGIN_VAR_DATA, name='srcControlChannel', referencedName='null', description='null', id=8, version=0, deprecated=0, encodedLength=0, offset=52, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("SrcControlChannel=");
builder.Append(SrcControlChannel());
builder.Append('|');
//Token{signal=BEGIN_VAR_DATA, name='liveDestination', referencedName='null', description='null', id=9, version=0, deprecated=0, encodedLength=0, offset=-1, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("LiveDestination=");
builder.Append(LiveDestination());
Limit(originalLimit);
return builder;
}
}
}
| |
// 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.Text;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using Internal.Runtime.Augments;
using Internal.StackGenerator.Dia;
namespace Internal.StackTraceGenerator
{
public static class StackTraceGenerator
{
/// <summary>
/// Check the AppCompat switch 'Diagnostics.DisableDiaStackTraceResolution'.
/// This is used for testing of metadata-based stack trace resolution.
/// </summary>
private static bool IsDiaStackTraceResolutionDisabled()
{
bool disableDia = false;
AppContext.TryGetSwitch("Diagnostics.DisableDiaStackTraceResolution", out disableDia);
return disableDia;
}
//
// Makes reasonable effort to construct one useful line of a stack trace. Returns null if it can't.
//
public static String CreateStackTraceString(IntPtr ip, bool includeFileInfo)
{
if (IsDiaStackTraceResolutionDisabled())
{
return null;
}
try
{
int hr;
int rva;
IDiaSession session = GetDiaSession(ip, out rva);
if (session == null)
return null;
StringBuilder sb = new StringBuilder();
IDiaSymbol symbol;
hr = session.FindSymbolByRVA(rva, SymTagEnum.SymTagFunction, out symbol);
if (hr != S_OK)
return null;
String functionName;
hr = symbol.GetName(out functionName);
if (hr == S_OK)
sb.Append(functionName.Demanglify());
else
sb.Append("<Function Name Not Available>");
sb.Append(CreateParameterListString(session, symbol));
if (includeFileInfo)
{
sb.Append(CreateSourceInfoString(session, rva));
}
return sb.ToString();
}
catch
{
return null;
}
}
//
// Makes reasonable effort to get source info. Returns null sourceFile and 0 lineNumber/columnNumber if it can't.
//
public static void TryGetSourceLineInfo(IntPtr ip, out string fileName, out int lineNumber, out int columnNumber)
{
fileName = null;
lineNumber = 0;
columnNumber = 0;
if (!IsDiaStackTraceResolutionDisabled())
{
int rva;
IDiaSession session = GetDiaSession(ip, out rva);
if (session != null)
{
TryGetSourceLineInfo(session, rva, out fileName, out lineNumber, out columnNumber);
}
}
}
/// <summary>
/// Makes reasonable effort to find the IL offset corresponding to the given address within a method.
/// Returns StackFrame.OFFSET_UNKNOWN if not available.
/// </summary>
public static void TryGetILOffsetWithinMethod(IntPtr ip, out int ilOffset)
{
ilOffset = StackFrame.OFFSET_UNKNOWN;
if (!IsDiaStackTraceResolutionDisabled())
{
int rva;
IDiaSession session = GetDiaSession(ip, out rva);
if (session != null)
{
TryGetILOffsetInfo(session, rva, out ilOffset);
}
}
}
//
// Get a IDiaDataSource object
//
private static IDiaDataSource GetDiaDataSource()
{
Guid iid = Guids.IID_IDiaDataSource;
int hr;
foreach (Guid clsId in Guids.DiaSource_CLSIDs)
{
unsafe
{
byte[] _clsid = clsId.ToByteArray();
byte[] _iid = iid.ToByteArray();
fixed (byte* pclsid = &_clsid[0])
{
fixed (byte* piid = &_iid[0])
{
IntPtr _dataSource;
hr = CoCreateInstance(pclsid, (IntPtr)0, CLSCTX_INPROC, piid, out _dataSource);
if (hr == S_OK)
return new IDiaDataSource(_dataSource);
}
}
}
}
return null;
}
//
// Create the method parameter list.
//
private static String CreateParameterListString(IDiaSession session, IDiaSymbol symbol)
{
StringBuilder sb = new StringBuilder("(");
// find the parameters
IDiaEnumSymbols dataSymbols;
int hr = session.FindChildren(symbol, SymTagEnum.SymTagData, null, NameSearchOptions.nsNone, out dataSymbols);
if (hr == S_OK)
{
int count;
hr = dataSymbols.Count(out count);
if (hr == S_OK)
{
for (int i = 0, iParam = 0; i < count; i++)
{
IDiaSymbol dataSym;
hr = dataSymbols.Item(i, out dataSym);
if (hr != S_OK)
continue;
DataKind dataKind;
hr = dataSym.GetDataKind(out dataKind);
if (hr != S_OK || dataKind != DataKind.DataIsParam)
continue;
string paramName;
hr = dataSym.GetName(out paramName);
if (hr != S_OK)
{
continue;
}
//this approximates the way C# displays methods by not including these hidden arguments
if (paramName == "InstParam" || paramName == "this")
{
continue;
}
IDiaSymbol parameterType;
hr = dataSym.GetType(out parameterType);
if (hr != S_OK)
{
continue;
}
if (iParam++ != 0)
sb.Append(", ");
sb.Append(parameterType.ToTypeString(session));
sb.Append(' ');
sb.Append(paramName);
}
}
}
sb.Append(')');
return sb.ToString();
}
//
// Retrieve the source fileName, line number, and column
//
private static void TryGetSourceLineInfo(IDiaSession session, int rva, out string fileName, out int lineNumber, out int columnNumber)
{
fileName = null;
lineNumber = 0;
columnNumber = 0;
IDiaEnumLineNumbers lineNumbers;
int hr = session.FindLinesByRVA(rva, 1, out lineNumbers);
if (hr == S_OK)
{
int numLineNumbers;
hr = lineNumbers.Count(out numLineNumbers);
if (hr == S_OK && numLineNumbers > 0)
{
IDiaLineNumber ln;
hr = lineNumbers.Item(0, out ln);
if (hr == S_OK)
{
IDiaSourceFile sourceFile;
hr = ln.SourceFile(out sourceFile);
if (hr == S_OK)
{
hr = sourceFile.FileName(out fileName);
if (hr == S_OK)
{
hr = ln.LineNumber(out lineNumber);
if (hr == S_OK)
{
hr = ln.ColumnNumber(out columnNumber);
}
}
}
}
}
}
}
private static void TryGetILOffsetInfo(IDiaSession session, int rva, out int ilOffset)
{
IDiaEnumLineNumbers lineNumbers;
int hr = session.FindILOffsetsByRVA(rva, 1, out lineNumbers);
if (hr == S_OK)
{
int numLineNumbers;
hr = lineNumbers.Count(out numLineNumbers);
if (hr == S_OK && numLineNumbers > 0)
{
IDiaLineNumber ln;
hr = lineNumbers.Item(0, out ln);
if (hr == S_OK)
{
hr = ln.LineNumber(out ilOffset);
if (hr == S_OK)
{
return;
}
}
}
}
ilOffset = StackFrame.OFFSET_UNKNOWN;
}
//
// Generate the " in <filename>:line <line#>" section.
//
private static String CreateSourceInfoString(IDiaSession session, int rva)
{
StringBuilder sb = new StringBuilder();
string fileName;
int lineNumber, columnNumber;
TryGetSourceLineInfo(session, rva, out fileName, out lineNumber, out columnNumber);
if(!string.IsNullOrEmpty(fileName))
{
sb.Append(" in ").Append(fileName);
if(lineNumber >= 0)
{
sb.Append(":line ").Append(lineNumber);
}
}
return sb.ToString();
}
//
// Clean up all the "$2_" sweetness that ILMerge contributes and
// replace type-name separator "::" by "."
//
private static String Demanglify(this String s)
{
StringBuilder sb = new StringBuilder();
int i = 0;
while (i < s.Length)
{
sb.Append(s[i++]);
if (i == s.Length)
continue;
if (s[i - 1] == '$' && Char.IsNumber(s[i]))
{
if (i != 1 && (s[i - 2] != ' ' && s[i - 2] != '<'))
continue;
int lookAhead = i + 1;
while (lookAhead < s.Length && Char.IsNumber(s[lookAhead]))
lookAhead++;
if (lookAhead == s.Length || s[lookAhead] != '_')
continue;
sb = sb.Remove(sb.Length - 1, 1);
i = lookAhead + 1;
}
else if (s[i - 1] == ':' && s[i] == ':')
{
sb.Remove(sb.Length - 1, 1);
sb.Append('.');
i++;
}
}
return sb.ToString();
}
private static String ToTypeString(this IDiaSymbol parameterType, IDiaSession session)
{
bool ignore;
return parameterType.ToTypeStringWorker(session, 0, out ignore);
}
private static String ToTypeStringWorker(this IDiaSymbol parameterType, IDiaSession session, int recursionLevel, out bool isValueTypeOrByRef)
{
int hr;
isValueTypeOrByRef = false;
// Block runaway recursions.
if (recursionLevel++ > 10)
return "?";
SymTagEnum symTag;
hr = parameterType.GetSymTag(out symTag);
if (hr != S_OK)
return "?";
if (symTag == SymTagEnum.SymTagPointerType)
{
bool isReference;
hr = parameterType.GetReference(out isReference);
if (hr != S_OK)
return "?";
if (isReference)
{
// An isReference pointer can mean one of two things:
// 1. ELEMENT_TYPE_BYREF
// 2. An indication that the UDT that follows is actually a class, not a struct.
//
isValueTypeOrByRef = true;
IDiaSymbol targetType;
hr = parameterType.GetType(out targetType);
if (hr != S_OK)
return "?";
bool targetIsValueTypeOrByRef;
String targetTypeString = targetType.ToTypeStringWorker(session, recursionLevel, out targetIsValueTypeOrByRef);
if (targetIsValueTypeOrByRef)
return targetTypeString + "&";
else
return targetTypeString;
}
else
{
// A non-isReference pointer means an ELEMENT_TYPE_PTR
IDiaSymbol targetType;
hr = parameterType.GetType(out targetType);
if (hr != S_OK)
return "?";
bool ignore;
return targetType.ToTypeStringWorker(session, recursionLevel, out ignore) + "*";
}
}
else if (symTag == SymTagEnum.SymTagArrayType)
{
// Note: We don't actually hit this case in NUTC-generated PDB's as NUTC emits arrays as if they were UDT's with square brackets in the name.
// But just in case NUTC ever changes its PDB emission, we'll print out the most obvious interpretation and hope we're right.
IDiaSymbol elementType;
hr = parameterType.GetType(out elementType);
if (hr != S_OK)
return "?";
bool ignore;
return elementType.ToTypeStringWorker(session, recursionLevel, out ignore) + "[]";
}
else if (symTag == SymTagEnum.SymTagUDT || symTag == SymTagEnum.SymTagEnum)
{
// Need to figure out whether this is a value type as our recursive caller needs to know whether the "byref pointer" that wrapped this
// is a true managed byref or just the "byref pointer" that wraps all non-valuetypes.
if (symTag == SymTagEnum.SymTagEnum)
{
isValueTypeOrByRef = true;
}
else
{
IDiaEnumSymbols baseClasses;
hr = session.FindChildren(parameterType, SymTagEnum.SymTagBaseClass, null, 0, out baseClasses);
if (hr != S_OK)
return "?";
int count;
hr = baseClasses.Count(out count);
if (hr != S_OK)
return "?";
for (int i = 0; i < count; i++)
{
IDiaSymbol baseClass;
if (S_OK == baseClasses.Item(i, out baseClass))
{
String baseClassName;
if (S_OK == baseClass.GetName(out baseClassName))
{
if (baseClassName == "System::ValueType")
isValueTypeOrByRef = true;
}
}
}
}
String name;
hr = parameterType.GetName(out name);
if (hr != S_OK)
return "?";
return name.RemoveNamespaces().Demanglify();
}
else if (symTag == SymTagEnum.SymTagBaseType)
{
// Certain "primitive" types are encoded specially.
BasicType basicType;
hr = parameterType.GetBaseType(out basicType);
if (hr != S_OK)
return "?";
long length;
hr = parameterType.GetLength(out length);
if (hr != S_OK)
return "?";
return ConvertBasicTypeToTypeString(basicType, length, out isValueTypeOrByRef);
}
else
{
return "?";
}
}
private static String ConvertBasicTypeToTypeString(BasicType basicType, long length, out bool isValueTypeOrByRef)
{
isValueTypeOrByRef = true;
switch (basicType)
{
case BasicType.btNoType:
return "Unknown";
case BasicType.btVoid:
return "Void";
case BasicType.btChar:
return "Byte";
case BasicType.btWChar:
return "Char";
case BasicType.btInt:
if (length != 1L)
{
if (length == 2L)
{
return "Int16";
}
if ((length != 4L) && (length == 8L))
{
return "Int64";
}
return "Int32";
}
return "SByte";
case BasicType.btUInt:
if (length != 1L)
{
if (length == 2L)
{
return "UInt16";
}
if ((length != 4L) && (length == 8L))
{
return "UInt64";
}
return "UInt32";
}
return "Byte";
case BasicType.btFloat:
if (length != 8L)
{
return "Single";
}
return "Double";
case BasicType.btBCD:
return "BCD";
case BasicType.btBool:
return "Boolean";
case BasicType.btLong:
return "Int64";
case BasicType.btULong:
return "UInt64";
case BasicType.btCurrency:
return "Currency";
case BasicType.btDate:
return "Date";
case BasicType.btVariant:
return "Variant";
case BasicType.btComplex:
return "Complex";
case BasicType.btBit:
return "Bit";
case BasicType.btBSTR:
return "BSTR";
case BasicType.btHresult:
return "Hresult";
default:
return "?";
}
}
//
// Attempt to remove namespaces from types. Unfortunately, this isn't straightforward as PDB's present generic instances as "regular types with angle brackets"
// so "s" could be something like "System::Collections::Generics::List$1<System::String>". Worse, the PDB also uses "::" to separate nested types from
// their outer types so these represent collateral damage. And we assume that namespaces (unlike types) have reasonable names (i.e. no names with wierd characters.)
//
// Fortunately, this is just for diagnostic information so we don't need to let perfect be the enemy of good.
//
private static String RemoveNamespaces(this String s)
{
int firstIndexOfColonColon = s.IndexOf("::");
if (firstIndexOfColonColon == -1)
return s;
int lookBack = firstIndexOfColonColon - 1;
for (; ;)
{
if (lookBack < 0)
break;
if (!(Char.IsLetterOrDigit(s[lookBack]) || s[lookBack] == '_'))
break;
lookBack--;
}
s = s.Remove(lookBack + 1, firstIndexOfColonColon - lookBack + 1);
return s.RemoveNamespaces();
}
/// <summary>
/// Locate and lazily load debug info for the native app module overlapping given
/// virtual address.
/// </summary>
/// <param name="ip">Instruction pointer address (code address for the lookup)</param>
/// <param name="rva">Output VA relative to module base</param>
private static IDiaSession GetDiaSession(IntPtr ip, out int rva)
{
if (ip == IntPtr.Zero)
{
rva = -1;
return null;
}
IntPtr moduleBase = RuntimeAugments.GetOSModuleFromPointer(ip);
if (moduleBase == IntPtr.Zero)
{
rva = -1;
return null;
}
rva = (int)(ip.ToInt64() - moduleBase.ToInt64());
if (s_loadedModules == null)
{
// Lazily create the map from module bases to debug info
s_loadedModules = new Dictionary<IntPtr, IDiaSession>();
}
// Locate module index based on base address
IDiaSession diaSession;
if (s_loadedModules.TryGetValue(moduleBase, out diaSession))
{
return diaSession;
}
string modulePath = RuntimeAugments.TryGetFullPathToApplicationModule(moduleBase);
if (modulePath == null)
{
return null;
}
int indexOfLastDot = modulePath.LastIndexOf('.');
if (indexOfLastDot == -1)
{
return null;
}
IDiaDataSource diaDataSource = GetDiaDataSource();
if (diaDataSource == null)
{
return null;
}
// Look for .pdb next to .exe / dll - if it's not there, bail.
String pdbPath = modulePath.Substring(0, indexOfLastDot) + ".pdb";
int hr = diaDataSource.LoadDataFromPdb(pdbPath);
if (hr != S_OK)
{
return null;
}
hr = diaDataSource.OpenSession(out diaSession);
if (hr != S_OK)
{
return null;
}
s_loadedModules.Add(moduleBase, diaSession);
return diaSession;
}
// CoCreateInstance is not in WindowsApp_Downlevel.lib and ExactSpelling = true is required
// to force MCG to resolve it.
//
// This api is a WACK violation but it cannot be changed to CoCreateInstanceApp() without breaking the stack generator altogether.
// The toolchain will not include this library in the dependency closure as long as (1) the program is being compiled as a store app and not a console .exe
// and (2) the /buildType switch passed to ILC is set to the "ret".
[DllImport("api-ms-win-core-com-l1-1-0.dll", ExactSpelling = true)]
private static extern unsafe int CoCreateInstance(byte* rclsid, IntPtr pUnkOuter, int dwClsContext, byte* riid, out IntPtr ppv);
private const int S_OK = 0;
private const int CLSCTX_INPROC = 0x3;
/// <summary>
/// Loaded binary module addresses.
/// </summary>
[ThreadStatic]
private static Dictionary<IntPtr, IDiaSession> s_loadedModules;
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
using OrchardCore.DisplayManagement.Descriptors;
using OrchardCore.DisplayManagement.ViewModels;
using OrchardCore.Modules;
using OrchardCore.Mvc.Utilities;
namespace OrchardCore.DisplayManagement.Shapes
{
[Feature(Application.DefaultFeatureId)]
public class GroupShapes : IShapeAttributeProvider
{
[Shape]
public IHtmlContent AdminTabs(IShape shape)
{
var tabsGrouping = shape.GetProperty<IList<IGrouping<string, object>>>("Tabs");
if (tabsGrouping == null)
{
return HtmlString.Empty;
}
var tabs = tabsGrouping.Select(group => group.Key).ToArray();
if (!tabs.Any())
{
return HtmlString.Empty;
}
var tagBuilder = shape.GetTagBuilder("ul");
var identifier = shape.GetProperty<string>("Identifier");
tagBuilder.AddCssClass("nav nav-tabs flex-column flex-md-row");
tagBuilder.Attributes["role"] = "tablist";
var tabIndex = 0;
foreach (var tab in tabs)
{
var linkTag = new TagBuilder("li");
linkTag.AddCssClass("nav-item");
if (tabIndex != tabs.Length - 1)
{
linkTag.AddCssClass("pr-md-2");
}
var aTag = new TagBuilder("a");
aTag.AddCssClass("nav-item nav-link");
if (tabIndex == 0)
{
aTag.AddCssClass("active");
}
var tabId = $"tab-{tab}-{identifier}".HtmlClassify();
aTag.Attributes["href"] = '#' + tabId;
aTag.Attributes["data-toggle"] = "tab";
aTag.Attributes["role"] = "tab";
aTag.Attributes["aria-controls"] = tabId;
aTag.Attributes["aria-selected"] = "false";
aTag.InnerHtml.Append(tab);
linkTag.InnerHtml.AppendHtml(aTag);
tagBuilder.InnerHtml.AppendHtml(linkTag);
tabIndex++;
}
return tagBuilder;
}
[Shape]
public async Task<IHtmlContent> Card(IDisplayHelper displayAsync, GroupingViewModel shape)
{
var tagBuilder = shape.GetTagBuilder("div");
tagBuilder.AddCssClass("card-body");
shape.Metadata.Alternates.Clear();
shape.Metadata.Type = "ColumnGrouping";
tagBuilder.InnerHtml.AppendHtml(await displayAsync.ShapeExecuteAsync(shape));
var cardIdPrefix = $"card-{shape.Identifier}-{shape.Grouping.Key}".HtmlClassify();
var cardTag = new TagBuilder("div");
cardTag.AddCssClass("card");
var headerTag = new TagBuilder("div");
headerTag.AddCssClass("card-header");
headerTag.Attributes["id"] = $"heading-{cardIdPrefix}";
var buttonTag = new TagBuilder("button");
buttonTag.AddCssClass("btn btn-link btn-block text-left");
buttonTag.Attributes["type"] = "button";
buttonTag.Attributes["data-toggle"] = "collapse";
buttonTag.Attributes["data-target"] = $"#collapse-{cardIdPrefix}";
buttonTag.Attributes["aria-expanded"] = "true";
buttonTag.Attributes["aria-controls"] = $"collapse-{cardIdPrefix}";
buttonTag.InnerHtml.Append(shape.Grouping.Key);
headerTag.InnerHtml.AppendHtml(buttonTag);
var bodyTag = new TagBuilder("div");
bodyTag.AddCssClass("collapse show");
bodyTag.Attributes["id"] = $"collapse-{cardIdPrefix}";
bodyTag.InnerHtml.AppendHtml(tagBuilder);
cardTag.InnerHtml.AppendHtml(headerTag);
cardTag.InnerHtml.AppendHtml(bodyTag);
return cardTag;
}
[Shape]
public async Task<IHtmlContent> CardContainer(IDisplayHelper displayAsync, GroupViewModel shape)
{
var tagBuilder = shape.GetTagBuilder("div");
tagBuilder.AddCssClass("mb-3");
foreach (var card in shape.Items.OfType<IShape>())
{
tagBuilder.InnerHtml.AppendHtml(await displayAsync.ShapeExecuteAsync(card));
}
return tagBuilder;
}
[Shape]
public async Task<IHtmlContent> Column(IDisplayHelper displayAsync, GroupViewModel shape)
{
var tagBuilder = shape.GetTagBuilder("div");
foreach (var column in shape.Items)
{
tagBuilder.InnerHtml.AppendHtml(await displayAsync.ShapeExecuteAsync((IShape)column));
}
return tagBuilder;
}
[Shape]
public async Task<IHtmlContent> ColumnContainer(IDisplayHelper displayAsync, GroupViewModel shape)
{
var tagBuilder = shape.GetTagBuilder("div");
tagBuilder.AddCssClass("row");
foreach (var column in shape.Items)
{
tagBuilder.InnerHtml.AppendHtml(await displayAsync.ShapeExecuteAsync((IShape)column));
}
return tagBuilder;
}
[Shape]
public async Task<IHtmlContent> Tab(IDisplayHelper displayAsync, GroupingViewModel shape)
{
var tagBuilder = shape.GetTagBuilder("div");
tagBuilder.Attributes["id"] = $"tab-{shape.Grouping.Key}-{shape.Identifier}".HtmlClassify();
tagBuilder.AddCssClass("tab-pane fade");
// Morphing this shape to a grouping shape to keep Model untouched.
shape.Metadata.Alternates.Clear();
shape.Metadata.Type = "CardGrouping";
tagBuilder.InnerHtml.AppendHtml(await displayAsync.ShapeExecuteAsync(shape));
return tagBuilder;
}
[Shape]
public async Task<IHtmlContent> TabContainer(IDisplayHelper displayAsync, GroupingsViewModel shape, IShapeFactory shapeFactory)
{
var localNavigation = await shapeFactory.CreateAsync("LocalNavigation", Arguments.From(new
{
shape.Identifier,
Tabs = shape.Groupings
}));
var htmlContentBuilder = new HtmlContentBuilder();
htmlContentBuilder.AppendHtml(await displayAsync.ShapeExecuteAsync(localNavigation));
var tagBuilder = shape.GetTagBuilder("div");
tagBuilder.AddCssClass("tab-content");
htmlContentBuilder.AppendHtml(tagBuilder);
var first = true;
foreach (var tab in shape.Items.OfType<IShape>())
{
if (first)
{
first = false;
tab.Classes.Add("show active");
}
tagBuilder.InnerHtml.AppendHtml(await displayAsync.ShapeExecuteAsync(tab));
}
return htmlContentBuilder;
}
[Shape]
public Task<IHtmlContent> LocalNavigation(IDisplayHelper displayAsync, IShape shape)
{
// Morphing this shape to keep Model untouched.
shape.Metadata.Alternates.Clear();
shape.Metadata.Type = "AdminTabs";
return displayAsync.ShapeExecuteAsync(shape);
}
}
}
| |
namespace Microsoft.Protocols.TestSuites.SharedTestSuite
{
using System;
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestSuites.SharedAdapter;
using Microsoft.Protocols.TestTools;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// This class is the base class for all the test classes in the MS-FSSHTTP-FSSHTTPB test suite.
/// </summary>
[TestClass]
public abstract class SharedTestSuiteBase : TestClassBase
{
#region Variables
/// <summary>
/// A value indicate performing the merge PTF configuration file once.
/// </summary>
private static bool isPerformMergeOperation;
/// <summary>
/// Gets or sets adapter instance.
/// </summary>
protected IMS_FSSHTTP_FSSHTTPBAdapter Adapter { get; set; }
/// <summary>
/// Gets or sets the FileStatusManager instance.
/// </summary>
protected StatusManager StatusManager { get; set; }
/// <summary>
/// Gets or sets the default file URL.
/// </summary>
protected string DefaultFileUrl { get; set; }
/// <summary>
/// Gets or sets SUT PowerShell adapter instance.
/// </summary>
protected IMS_FSSHTTP_FSSHTTPBSUTControlAdapter SutPowerShellAdapter { get; set; }
/// <summary>
/// Gets or sets SUT managed adapter instance.
/// </summary>
protected IMS_FSSHTTP_FSSHTTPBManagedCodeSUTControlAdapter SutManagedAdapter { get; set; }
/// <summary>
/// Gets or sets the userName01.
/// </summary>
protected string UserName01 { get; set; }
/// <summary>
/// Gets or sets the password01.
/// </summary>
protected string Password01 { get; set; }
/// <summary>
/// Gets or sets the userName02.
/// </summary>
protected string UserName02 { get; set; }
/// <summary>
/// Gets or sets the password02.
/// </summary>
protected string Password02 { get; set; }
/// <summary>
/// Gets or sets the userName03.
/// </summary>
protected string UserName03 { get; set; }
/// <summary>
/// Gets or sets the password03.
/// </summary>
protected string Password03 { get; set; }
/// <summary>
/// Gets or sets the domain.
/// </summary>
protected string Domain { get; set; }
#endregion
#region Test Suite Initialization and clean up
/// <summary>
/// Class initialization
/// </summary>
/// <param name="testContext">The context of the test suite.</param>
[ClassInitialize]
public static void ClassInitialize(TestContext testContext)
{
TestClassBase.Initialize(testContext);
}
/// <summary>
/// Class clean up
/// </summary>
[ClassCleanup]
public static void ClassCleanup()
{
TestClassBase.Cleanup();
}
#endregion
#region Test Case Initialization
/// <summary>
/// A test case's level initialization method for TestSuiteBase class. It will perform before each test case.
/// </summary>
[TestInitialize]
public void MSFSSHTTP_FSSHTTPBTestInitialize()
{
if (!isPerformMergeOperation)
{
this.MergeConfigurationFile(this.Site);
isPerformMergeOperation = true;
}
// If the shared test code are executed in MS-WOPI mode, try to verify whether run in support products by check the MS-WOPI_Supported property of MS-WOPI.
if ("MS-WOPI".Equals(this.Site.DefaultProtocolDocShortName, System.StringComparison.OrdinalIgnoreCase))
{
if (!Common.GetConfigurationPropertyValue<bool>("MS-WOPI_Supported", this.Site))
{
SutVersion currentSutVersion = Common.GetConfigurationPropertyValue<SutVersion>("SutVersion", this.Site);
this.Site.Assume.Inconclusive(@"The server does not support this specification [MS-WOPI]. It is determined by ""MS-WOPI_Supported"" SHOULDMAY property of the [{0}_{1}_SHOULDMAY.deployment.ptfconfig] configuration file.", this.Site.DefaultProtocolDocShortName, currentSutVersion);
}
}
this.UserName01 = Common.GetConfigurationPropertyValue("UserName1", this.Site);
this.Password01 = Common.GetConfigurationPropertyValue("Password1", this.Site);
this.UserName02 = Common.GetConfigurationPropertyValue("UserName2", this.Site);
this.Password02 = Common.GetConfigurationPropertyValue("Password2", this.Site);
this.UserName03 = Common.GetConfigurationPropertyValue("UserName3", this.Site);
this.Password03 = Common.GetConfigurationPropertyValue("Password3", this.Site);
this.Domain = Common.GetConfigurationPropertyValue("Domain", this.Site);
// Initialize the web service using the configured UserName/Domain and password.
this.Adapter = Site.GetAdapter<IMS_FSSHTTP_FSSHTTPBAdapter>();
// Initialize the SUT Control Adapter instance
this.SutPowerShellAdapter = Site.GetAdapter<IMS_FSSHTTP_FSSHTTPBSUTControlAdapter>();
this.SutManagedAdapter = Site.GetAdapter<IMS_FSSHTTP_FSSHTTPBManagedCodeSUTControlAdapter>();
// Initialize the file status manager to handle the environment clean up.
this.StatusManager = new StatusManager(this.Site, this.InitializeContext);
}
/// <summary>
/// A test case's level clean up. It will perform after each test case.
/// </summary>
[TestCleanup]
public void MSFSSHTTP_FSSHTTPBTestCleanup()
{
System.Collections.Generic.Dictionary<StatusManager.ServerStatus, Action> status =
new System.Collections.Generic.Dictionary<StatusManager.ServerStatus, Action>();
foreach (System.Collections.Generic.KeyValuePair<StatusManager.ServerStatus, Action> pairs in this.StatusManager.DocumentLibraryStatusRollbackFunctions)
{
status.Add(pairs.Key, pairs.Value);
}
if (!this.StatusManager.RollbackStatus())
{
this.Site.Log.Add(
LogEntryKind.Debug,
"The error message report for the clean up environments {0}",
this.StatusManager.GenerateErrorMessageReport());
}
foreach (System.Collections.Generic.KeyValuePair<StatusManager.ServerStatus, Action> pairs in status)
{
if (pairs.Key == StatusManager.ServerStatus.DisableCoauth)
{
string url = this.PrepareFile();
int waitTime = Common.GetConfigurationPropertyValue<int>("WaitTime", this.Site);
int retryCount = Common.GetConfigurationPropertyValue<int>("RetryCount", this.Site);
int temp = retryCount;
while (retryCount > 0)
{
// Join a Coauthoring session with AllowFallbackToExclusive attribute set to true
CoauthSubRequestType subRequest = SharedTestSuiteHelper.CreateCoauthSubRequestForJoinCoauthSession(SharedTestSuiteHelper.DefaultClientID, SharedTestSuiteHelper.ReservedSchemaLockID, true, SharedTestSuiteHelper.DefaultExclusiveLockID);
CellStorageResponse cellResponse = this.Adapter.CellStorageRequest(url, new SubRequestType[] { subRequest });
CoauthSubResponseType firstJoinResponse = SharedTestSuiteHelper.ExtractSubResponse<CoauthSubResponseType>(cellResponse, 0, 0, this.Site);
if (SharedTestSuiteHelper.ConvertToErrorCodeType(firstJoinResponse.ErrorCode, this.Site) != ErrorCodeType.Success)
{
break;
}
if (temp == retryCount)
{
this.StatusManager.RecordExclusiveLock(url, SharedTestSuiteHelper.DefaultExclusiveLockID);
}
if (firstJoinResponse.SubResponseData.ExclusiveLockReturnReasonSpecified
&& firstJoinResponse.SubResponseData.ExclusiveLockReturnReason == ExclusiveLockReturnReasonTypes.CoauthoringDisabled)
{
System.Threading.Thread.Sleep(waitTime);
retryCount--;
// Release lock
ExclusiveLockSubRequestType coauthLockRequest = new ExclusiveLockSubRequestType();
coauthLockRequest.SubRequestToken = SequenceNumberGenerator.GetCurrentToken().ToString();
coauthLockRequest.SubRequestData = new ExclusiveLockSubRequestDataType();
coauthLockRequest.SubRequestData.ExclusiveLockRequestType = ExclusiveLockRequestTypes.ReleaseLock;
coauthLockRequest.SubRequestData.ExclusiveLockRequestTypeSpecified = true;
coauthLockRequest.SubRequestData.ExclusiveLockID = SharedTestSuiteHelper.DefaultExclusiveLockID;
CoauthSubResponseType subResponse = SharedTestSuiteHelper.ExtractSubResponse<CoauthSubResponseType>(
this.Adapter.CellStorageRequest(url, new SubRequestType[] { coauthLockRequest }), 0, 0, this.Site);
Site.Assert.AreEqual<string>(
"success",
subResponse.ErrorCode.ToLower(),
"Failed to release the exclusive lock.");
}
else
{
// Release lock
SchemaLockSubRequestType schemaLockRequest = SharedTestSuiteHelper.CreateSchemaLockSubRequest(SchemaLockRequestTypes.ReleaseLock, null, null);
CellStorageResponse response = Adapter.CellStorageRequest(url, new SubRequestType[] { schemaLockRequest });
SchemaLockSubResponseType schemaLockSubResponse = SharedTestSuiteHelper.ExtractSubResponse<SchemaLockSubResponseType>(response, 0, 0, this.Site);
Site.Assert.AreEqual<string>(
"success",
schemaLockSubResponse.ErrorCode.ToLower(),
"Failed to release the schema lock.");
break;
}
}
}
}
if (!this.StatusManager.CleanUpFiles())
{
this.Site.Log.Add(
LogEntryKind.Debug,
"The error message report for the clean up environments {0}",
this.StatusManager.GenerateErrorMessageReport());
}
this.Adapter.Reset();
SharedContext.Current.Clear();
}
#endregion
#region Helper Methods
/// <summary>
/// This method is used to prepare an exclusive lock on the file with the specified exclusive lock id.
/// </summary>
/// <param name="fileUrl">Specify the file which is locked.</param>
/// <param name="exclusiveLockId">Specify the exclusive lock id.</param>
/// <param name="timeout">Specify the timeout value.</param>
protected void PrepareExclusiveLock(string fileUrl, string exclusiveLockId, int timeout = SharedTestSuiteHelper.DefaultTimeOut)
{
this.PrepareExclusiveLock(fileUrl, exclusiveLockId, this.UserName01, this.Password01, this.Domain, timeout);
}
/// <summary>
/// This method is used to prepare an exclusive lock on the file with the specified exclusive lock id.
/// </summary>
/// <param name="fileUrl">Specify the file which is locked.</param>
/// <param name="exclusiveLockId">Specify the exclusive lock id.</param>
/// <param name="userName">Specify the user name of the user who calls cell storage service.</param>
/// <param name="password">Specify the password of the user who calls cell storage service.</param>
/// <param name="domain">Specify the domain of the user who calls cell storage service.</param>
/// <param name="timeout">Specify the timeout value.</param>
protected void PrepareExclusiveLock(string fileUrl, string exclusiveLockId, string userName, string password, string domain, int timeout = SharedTestSuiteHelper.DefaultTimeOut)
{
this.InitializeContext(fileUrl, userName, password, domain);
// Get an exclusive lock
ExclusiveLockSubRequestType getExclusiveLockSubRequest = SharedTestSuiteHelper.CreateExclusiveLockSubRequest(ExclusiveLockRequestTypes.GetLock);
getExclusiveLockSubRequest.SubRequestData.ExclusiveLockID = exclusiveLockId;
getExclusiveLockSubRequest.SubRequestData.Timeout = timeout.ToString();
CellStorageResponse response = this.Adapter.CellStorageRequest(fileUrl, new SubRequestType[] { getExclusiveLockSubRequest });
ExclusiveLockSubResponseType exclusiveResponse = SharedTestSuiteHelper.ExtractSubResponse<ExclusiveLockSubResponseType>(response, 0, 0, this.Site);
this.Site.Assert.AreEqual<ErrorCodeType>(
ErrorCodeType.Success,
SharedTestSuiteHelper.ConvertToErrorCodeType(exclusiveResponse.ErrorCode, this.Site),
"Get an exclusive lock with identifier {0} by the user {1}@{2} on the file {3} should succeed.",
exclusiveLockId,
userName,
domain,
fileUrl);
this.StatusManager.RecordExclusiveLock(fileUrl, exclusiveLockId, userName, password, domain);
}
/// <summary>
/// This method is used to prepare a coauthoring session on the file with the specified schema lock id and client id.
/// </summary>
/// <param name="fileUrl">Specify the file which is locked.</param>
/// <param name="clientId">Specify the client ID.</param>
/// <param name="schemaLockId">Specify the schemaLock ID.</param>
/// <param name="timeout">Specify the timeout value.</param>
/// <returns>Return the current coauthoring status when the user join the coauthoring session.</returns>
protected CoauthStatusType PrepareCoauthoringSession(string fileUrl, string clientId, string schemaLockId, int timeout = SharedTestSuiteHelper.DefaultTimeOut)
{
return this.PrepareCoauthoringSession(fileUrl, clientId, schemaLockId, this.UserName01, this.Password01, this.Domain, timeout);
}
/// <summary>
/// This method is used to prepare a coauthoring session on the file with the specified schema lock id and client id.
/// </summary>
/// <param name="fileUrl">Specify the file which is locked.</param>
/// <param name="clientId">Specify the client ID.</param>
/// <param name="schemaLockId">Specify the schemaLock ID.</param>
/// <param name="userName">Specify the user name of the user who calls cell storage service.</param>
/// <param name="password">Specify the password of the user who calls cell storage service.</param>
/// <param name="domain">Specify the domain of the user who calls cell storage service.</param>
/// <param name="timeout">Specify the timeout value.</param>
/// <returns>Return the current coauthoring status when the user join the coauthoring session.</returns>
protected CoauthStatusType PrepareCoauthoringSession(string fileUrl, string clientId, string schemaLockId, string userName, string password, string domain, int timeout = SharedTestSuiteHelper.DefaultTimeOut)
{
this.InitializeContext(fileUrl, userName, password, domain);
// Join a Coauthoring session
CoauthSubRequestType subRequest = SharedTestSuiteHelper.CreateCoauthSubRequestForJoinCoauthSession(clientId, schemaLockId, null, null, timeout);
CellStorageResponse cellResponse = this.Adapter.CellStorageRequest(fileUrl, new SubRequestType[] { subRequest });
CoauthSubResponseType joinResponse = SharedTestSuiteHelper.ExtractSubResponse<CoauthSubResponseType>(cellResponse, 0, 0, this.Site);
this.Site.Assert.AreEqual(
ErrorCodeType.Success,
SharedTestSuiteHelper.ConvertToErrorCodeType(joinResponse.ErrorCode, this.Site),
"Join coauthoring session with client ID {0} and schema lock ID {4} by the user {1}@{2} on the file {3} should succeed.",
clientId,
userName,
domain,
fileUrl,
schemaLockId);
this.StatusManager.RecordCoauthSession(fileUrl, clientId, schemaLockId, userName, password, domain);
this.Site.Assert.IsTrue(
joinResponse.SubResponseData.CoauthStatusSpecified,
"When join the coauthoring session succeeds, the coauth status should be returned.");
return joinResponse.SubResponseData.CoauthStatus;
}
/// <summary>
/// This method is used to prepare a schema lock on the file with the specified schema lock id and client id.
/// </summary>
/// <param name="fileUrl">Specify the file which is locked.</param>
/// <param name="clientId">Specify the client ID.</param>
/// <param name="schemaLockId">Specify the schemaLock ID.</param>
/// <param name="timeout">Specify the timeout value.</param>
protected void PrepareSchemaLock(string fileUrl, string clientId, string schemaLockId, int timeout = SharedTestSuiteHelper.DefaultTimeOut)
{
this.PrepareSchemaLock(fileUrl, clientId, schemaLockId, this.UserName01, this.Password01, this.Domain, timeout);
}
/// <summary>
/// This method is used to prepare a schema lock on the file with the specified schema lock id and client id.
/// </summary>
/// <param name="fileUrl">Specify the file which is locked.</param>
/// <param name="clientId">Specify the client ID.</param>
/// <param name="schemaLockId">Specify the schemaLock ID.</param>
/// <param name="userName">Specify the user name of the user who calls cell storage service.</param>
/// <param name="password">Specify the password of the user who calls cell storage service.</param>
/// <param name="domain">Specify the domain of the user who calls cell storage service.</param>
/// <param name="timeout">Specify the timeout value.</param>
protected void PrepareSchemaLock(string fileUrl, string clientId, string schemaLockId, string userName, string password, string domain, int timeout = SharedTestSuiteHelper.DefaultTimeOut)
{
this.InitializeContext(fileUrl, userName, password, domain);
// Get a schema
SchemaLockSubRequestType subRequest = SharedTestSuiteHelper.CreateSchemaLockSubRequest(SchemaLockRequestTypes.GetLock, false, null);
subRequest.SubRequestData.SchemaLockID = schemaLockId;
subRequest.SubRequestData.ClientID = clientId;
subRequest.SubRequestData.Timeout = timeout.ToString();
CellStorageResponse response = this.Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { subRequest });
SchemaLockSubResponseType schemaLockSubResponse = SharedTestSuiteHelper.ExtractSubResponse<SchemaLockSubResponseType>(response, 0, 0, this.Site);
this.Site.Assert.AreEqual<ErrorCodeType>(
ErrorCodeType.Success,
SharedTestSuiteHelper.ConvertToErrorCodeType(schemaLockSubResponse.ErrorCode, this.Site),
"Test case cannot continue unless the user {0} Get schema lock id {1} with client id {3} sub request succeeds on the file {2}.",
this.UserName01,
schemaLockId,
this.DefaultFileUrl,
clientId);
this.StatusManager.RecordSchemaLock(this.DefaultFileUrl, subRequest.SubRequestData.ClientID, subRequest.SubRequestData.SchemaLockID, userName, password, domain);
}
/// <summary>
/// This method is used to prepare a schema lock or coauthoring on the file with the specified schema lock id and client id.
/// </summary>
/// <param name="fileUrl">Specify the file which is locked.</param>
/// <param name="clientId">Specify the client ID.</param>
/// <param name="schemaLockId">Specify the schemaLock ID.</param>
/// <param name="timeout">Specify the timeout value.</param>
protected void PrepareSharedLock(string fileUrl, string clientId, string schemaLockId, int timeout = SharedTestSuiteHelper.DefaultTimeOut)
{
this.PrepareSharedLock(fileUrl, clientId, schemaLockId, this.UserName01, this.Password01, this.Domain, timeout);
}
/// <summary>
/// This method is used to prepare a schema lock or coauthoring on the file with the specified schema lock id and client id.
/// </summary>
/// <param name="fileUrl">Specify the file which is locked.</param>
/// <param name="clientId">Specify the client ID.</param>
/// <param name="schemaLockId">Specify the schemaLock ID.</param>
/// <param name="userName">Specify the user name of the user who calls cell storage service.</param>
/// <param name="password">Specify the password of the user who calls cell storage service.</param>
/// <param name="domain">Specify the domain of the user who calls cell storage service.</param>
/// <param name="timeout">Specify the timeout value.</param>
protected void PrepareSharedLock(string fileUrl, string clientId, string schemaLockId, string userName, string password, string domain, int timeout = SharedTestSuiteHelper.DefaultTimeOut)
{
if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 93101, this.Site))
{
this.PrepareCoauthoringSession(fileUrl, clientId, schemaLockId, userName, password, domain, timeout);
}
else if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 93102, this.Site))
{
this.PrepareSchemaLock(fileUrl, clientId, schemaLockId, userName, password, domain, timeout);
}
else
{
this.Site.Assert.Fail("The server should at least support one of operations: Coauthoring session and Schema Lock");
}
}
/// <summary>
/// This method is used to prepare to join a editors table on the file using the specified client id.
/// </summary>
/// <param name="fileUrl">Specify the file.</param>
/// <param name="clientId">Specify the client ID.</param>
protected void PrepareJoinEditorsTable(string fileUrl, string clientId)
{
this.PrepareJoinEditorsTable(fileUrl, clientId, this.UserName01, this.Password01, this.Domain);
}
/// <summary>
/// This method is used to prepare to join a editors table on the file using the specified client id.
/// </summary>
/// <param name="fileUrl">Specify the file.</param>
/// <param name="clientId">Specify the client ID.</param>
/// <param name="userName">Specify the user name of the user who calls cell storage service.</param>
/// <param name="password">Specify the password of the user who calls cell storage service.</param>
/// <param name="domain">Specify the domain of the user who calls cell storage service.</param>
/// <param name="timeout">Specify the timeout value.</param>
protected void PrepareJoinEditorsTable(string fileUrl, string clientId, string userName, string password, string domain, int timeout = SharedTestSuiteHelper.DefaultTimeOut)
{
this.InitializeContext(fileUrl, userName, password, domain);
// Create join editor session object.
EditorsTableSubRequestType joinEditorTable = SharedTestSuiteHelper.CreateEditorsTableSubRequestForJoinSession(clientId, timeout);
// Call protocol adapter operation CellStorageRequest with EditorsTableRequestType JoinEditingSession.
CellStorageResponse response = this.Adapter.CellStorageRequest(fileUrl, new SubRequestType[] { joinEditorTable });
EditorsTableSubResponseType subResponse = SharedTestSuiteHelper.ExtractSubResponse<EditorsTableSubResponseType>(response, 0, 0, this.Site);
this.Site.Assert.AreEqual<ErrorCodeType>(
ErrorCodeType.Success,
SharedTestSuiteHelper.ConvertToErrorCodeType(subResponse.ErrorCode, this.Site),
"The user {0} uses the client id {1} to join the editor table should succeed.",
userName,
clientId);
this.StatusManager.RecordEditorTable(this.DefaultFileUrl, clientId);
}
/// <summary>
/// This method is used to test whether the lock with the specified id exist on the file.
/// </summary>
/// <param name="file">Specify the file.</param>
/// <param name="schemaLockId">Specify the schemaLock ID.</param>
/// <returns>Return true if exist, otherwise return false.</returns>
protected bool CheckSchemaLockExist(string file, string schemaLockId)
{
return this.CheckSchemaLockExist(file, schemaLockId, this.UserName01, this.Password01, this.Domain);
}
/// <summary>
/// This method is used to test whether the lock with the specified id exist on the file.
/// </summary>
/// <param name="file">Specify the file.</param>
/// <param name="schemaLockId">Specify the schemaLock ID.</param>
/// <param name="userName">Specify the user name of the user who calls cell storage service.</param>
/// <param name="password">Specify the password of the user who calls cell storage service.</param>
/// <param name="domain">Specify the domain of the user who calls cell storage service.</param>
/// <returns>Return true if exist, otherwise return false.</returns>
protected bool CheckSchemaLockExist(string file, string schemaLockId, string userName, string password, string domain)
{
this.InitializeContext(file, userName, password, domain);
// Generate a new schema lock id value which is different with the given one.
System.Guid newId;
do
{
newId = System.Guid.NewGuid();
}
while (newId == new System.Guid(schemaLockId));
if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 93101, this.Site))
{
// Check the schema lock availability using the new schema lock id.
SchemaLockSubRequestType subRequest = SharedTestSuiteHelper.CreateSchemaLockSubRequest(SchemaLockRequestTypes.CheckLockAvailability, null, null);
subRequest.SubRequestData.SchemaLockID = newId.ToString();
CellStorageResponse response = this.Adapter.CellStorageRequest(file, new SubRequestType[] { subRequest });
SchemaLockSubResponseType schemaLockSubResponse = SharedTestSuiteHelper.ExtractSubResponse<SchemaLockSubResponseType>(response, 0, 0, this.Site);
ErrorCodeType error = SharedTestSuiteHelper.ConvertToErrorCodeType(schemaLockSubResponse.ErrorCode, this.Site);
if (error == ErrorCodeType.FileAlreadyLockedOnServer)
{
// Now there could be kind of two conditions:
// 1) There is an exclusive lock
// 2) There is a schema lock
// So it is needed to check the schema lock with the given schema lock id should exist.
subRequest = SharedTestSuiteHelper.CreateSchemaLockSubRequest(SchemaLockRequestTypes.CheckLockAvailability, null, null);
subRequest.SubRequestData.SchemaLockID = schemaLockId;
response = this.Adapter.CellStorageRequest(file, new SubRequestType[] { subRequest });
schemaLockSubResponse = SharedTestSuiteHelper.ExtractSubResponse<SchemaLockSubResponseType>(response, 0, 0, this.Site);
return SharedTestSuiteHelper.ConvertToErrorCodeType(schemaLockSubResponse.ErrorCode, this.Site) == ErrorCodeType.Success;
}
else
{
if (error != ErrorCodeType.Success)
{
this.Site.Assert.Fail(
"If the schema lock {0} does not exist, check the schema lock using the id {0} should success, but actual the result is {2}",
schemaLockId,
newId.ToString(),
error.ToString());
}
return false;
}
}
else if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 93102, this.Site))
{
// Check the schema lock availability using the new schema lock id.
CoauthSubRequestType subRequest = SharedTestSuiteHelper.CreateCoauthSubRequestForCheckLockAvailability(SharedTestSuiteHelper.DefaultClientID, newId.ToString());
CellStorageResponse response = this.Adapter.CellStorageRequest(file, new SubRequestType[] { subRequest });
CoauthSubResponseType coauthSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CoauthSubResponseType>(response, 0, 0, this.Site);
ErrorCodeType error = SharedTestSuiteHelper.ConvertToErrorCodeType(coauthSubResponse.ErrorCode, this.Site);
if (error == ErrorCodeType.FileAlreadyLockedOnServer)
{
// Now there could be kind of two conditions:
// 1) There is an exclusive lock
// 2) There is a schema lock
// So it is needed to check the schema lock with the given schema lock id should exist.
subRequest = SharedTestSuiteHelper.CreateCoauthSubRequestForCheckLockAvailability(SharedTestSuiteHelper.DefaultClientID, schemaLockId);
response = this.Adapter.CellStorageRequest(file, new SubRequestType[] { subRequest });
coauthSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CoauthSubResponseType>(response, 0, 0, this.Site);
return SharedTestSuiteHelper.ConvertToErrorCodeType(coauthSubResponse.ErrorCode, this.Site) == ErrorCodeType.Success;
}
else
{
if (error != ErrorCodeType.Success)
{
this.Site.Assert.Fail(
"If the schema lock {0} does not exist, check the schema lock using the id {0} should success, but actual the result is {2}",
schemaLockId,
newId.ToString(),
error.ToString());
}
return false;
}
}
this.Site.Assert.Fail("The server should at least support one of operations: Coauthoring session and Schema Lock");
return false;
}
/// <summary>
/// This method is used to test whether the exclusive lock with the specified id exist on the file.
/// </summary>
/// <param name="file">Specify the file.</param>
/// <param name="exclusiveLockId">Specify the exclusive lock.</param>
/// <returns>Return true if exist, otherwise return false.</returns>
protected bool CheckExclusiveLockExist(string file, string exclusiveLockId)
{
return this.CheckExclusiveLockExist(file, exclusiveLockId, this.UserName01, this.Password01, this.Domain);
}
/// <summary>
/// This method is used to test whether the exclusive lock with the specified id exist on the file.
/// </summary>
/// <param name="file">Specify the file.</param>
/// <param name="exclusiveLockId">Specify the exclusive lock.</param>
/// <param name="userName">Specify the user name of the user who calls cell storage service.</param>
/// <param name="password">Specify the password of the user who calls cell storage service.</param>
/// <param name="domain">Specify the domain of the user who calls cell storage service.</param>
/// <returns>Return true if exist, otherwise return false.</returns>
protected bool CheckExclusiveLockExist(string file, string exclusiveLockId, string userName, string password, string domain)
{
this.InitializeContext(file, userName, password, domain);
// Generate a new schema lock id value which is different with the given one.
System.Guid newId;
do
{
newId = System.Guid.NewGuid();
}
while (newId == new System.Guid(exclusiveLockId));
ExclusiveLockSubRequestType exclusiveLocksubRequest = SharedTestSuiteHelper.CreateExclusiveLockSubRequest(ExclusiveLockRequestTypes.CheckLockAvailability);
exclusiveLocksubRequest.SubRequestData.ExclusiveLockID = newId.ToString();
CellStorageResponse response = this.Adapter.CellStorageRequest(file, new SubRequestType[] { exclusiveLocksubRequest });
ExclusiveLockSubResponseType exclusiveResponse = SharedTestSuiteHelper.ExtractSubResponse<ExclusiveLockSubResponseType>(response, 0, 0, this.Site);
ErrorCodeType error = SharedTestSuiteHelper.ConvertToErrorCodeType(exclusiveResponse.ErrorCode, this.Site);
if (error == ErrorCodeType.FileAlreadyLockedOnServer)
{
// Now there could be kind of two conditions:
// 1) There is an exclusive lock
// 2) There is a schema lock
// So it is needed to check the exclusive lock with the given exclusive lock id should exist.
exclusiveLocksubRequest = SharedTestSuiteHelper.CreateExclusiveLockSubRequest(ExclusiveLockRequestTypes.CheckLockAvailability);
exclusiveLocksubRequest.SubRequestData.ExclusiveLockID = exclusiveLockId;
response = this.Adapter.CellStorageRequest(file, new SubRequestType[] { exclusiveLocksubRequest });
exclusiveResponse = SharedTestSuiteHelper.ExtractSubResponse<ExclusiveLockSubResponseType>(response, 0, 0, this.Site);
return SharedTestSuiteHelper.ConvertToErrorCodeType(exclusiveResponse.ErrorCode, this.Site) == ErrorCodeType.Success;
}
else
{
if (error != ErrorCodeType.Success)
{
this.Site.Assert.Fail(
"If the exclusive lock {0} does not exist, check the schema lock using the id {0} should success, but actual the result is {2}",
exclusiveLockId,
newId.ToString(),
error.ToString());
}
return false;
}
}
/// <summary>
/// This method is used to check the user with specified client whether exist in a coauthoring session.
/// </summary>
/// <param name="fileUrl">Specify the file which is locked.</param>
/// <param name="clientId">Specify the client ID.</param>
/// <param name="schemaLockId">Specify the schemaLock ID.</param>
/// <param name="userName">Specify the user name of the user who calls cell storage service.</param>
/// <param name="password">Specify the password of the user who calls cell storage service.</param>
/// <param name="domain">Specify the domain of the user who calls cell storage service.</param>
/// <returns>Return true is exist in the coauthoring session, otherwise return false.</returns>
protected bool IsPresentInCoauthSession(string fileUrl, string clientId, string schemaLockId, string userName, string password, string domain)
{
this.InitializeContext(fileUrl, userName, password, domain);
CoauthSubRequestType subRequest = SharedTestSuiteHelper.CreateCoauthSubRequestForMarkTransitionComplete(clientId, schemaLockId);
CellStorageResponse cellResponse = this.Adapter.CellStorageRequest(fileUrl, new SubRequestType[] { subRequest });
CoauthSubResponseType response = SharedTestSuiteHelper.ExtractSubResponse<CoauthSubResponseType>(cellResponse, 0, 0, this.Site);
return SharedTestSuiteHelper.ConvertToErrorCodeType(response.ErrorCode, this.Site) == ErrorCodeType.Success;
}
/// <summary>
/// This method is used to fetch editor table on the specified file.
/// </summary>
/// <param name="file">Specify the file URL.</param>
/// <returns>Return the editors table on the file if the server support the editor tables, otherwise return null.</returns>
protected EditorsTable FetchEditorTable(string file)
{
if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 2053, this.Site))
{
// Call QueryEditorsTable to get editors table
this.InitializeContext(file, this.UserName01, this.Password01, this.Domain);
CellSubRequestType cellSubRequestEditorsTable = SharedTestSuiteHelper.CreateCellSubRequestEmbeddedQueryEditorsTable(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID());
CellStorageResponse cellStorageResponseEditorsTable = this.Adapter.CellStorageRequest(file, new SubRequestType[] { cellSubRequestEditorsTable });
CellSubResponseType subResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(cellStorageResponseEditorsTable, 0, 0, this.Site);
FsshttpbResponse queryEditorsTableResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(subResponse, this.Site);
// Get EditorsTable
EditorsTable editorsTable = EditorsTableUtils.GetEditorsTableFromResponse(queryEditorsTableResponse, this.Site);
if (SharedContext.Current.IsMsFsshttpRequirementsCaptured)
{
// If can fetch the editors table, then the following requirement can be directly captured.
this.Site.CaptureRequirement(
"MS-FSSHTTP",
2053,
@"[In Appendix B: Product Behavior] Implementation does represent the editors table as a compressed XML fragment. (<50> Section 3.1.4.8: On servers running Office 2013, the editors table is represented as a compressed XML fragment.)");
// Verify MS-FSSHTTPB requirement: MS-FSSHTTPB_R4061
// If can fetch the editors table, then the following requirement can be directly captured.
Site.CaptureRequirement(
"MS-FSSHTTPB",
4061,
@"[In Query Changes to Editors Table Partition] If the Partition Id GUID of the Target Partition Id of the sub-request (section 2.2.2.1.1) of the associated QueryChangesRequest is the value of the Guid ""7808F4DD - 2385 - 49d6 - B7CE - 37ACA5E43602"", the protocol server will interpret the QueryChangesRequest as a download of the editors table specified in [MS-FSSHTTP] section 3.1.4.8.");
// Verify MS-FSSHTTPB requirement: MS-FSSHTTPB_R4063
// If can fetch the editors table, then the following requirement can be directly captured.
Site.CaptureRequirement(
"MS-FSSHTTPB",
4063,
@"[In Query Changes to Editors Table Partition] The protocol server MUST return the editors table in the associated data element collection using the following process:
Construct a byte array representation of the editors table using UTF-8 encoding.");
// Verify MS-FSSHTTPB requirement: MS-FSSHTTPB_R4064
// If can fetch the editors table, then the following requirement can be directly captured.
Site.CaptureRequirement(
"MS-FSSHTTPB",
4064,
@"[In Query Changes to Editors Table Partition] [The protocol server MUST return the editors table in the associated data element collection using the following process:] Compress the byte array using the DEFLATE compression algorithm.");
// Verify MS-FSSHTTPB requirement: MS-FSSHTTPB_R4065
// If can fetch the editors table, then the following requirement can be directly captured.
Site.CaptureRequirement(
"MS-FSSHTTPB",
4065,
@"[In Query Changes to Editors Table Partition] [The protocol server MUST return the editors table in the associated data element collection using the following process:] Prepend the compressed byte array with the Editors Table Zip Stream Header (section 2.2.3.1.2.1.1).");
// Verify MS-FSSHTTPB requirement: MS-FSSHTTPB_R4066
// If can fetch the editors table, then the following requirement can be directly captured.
Site.CaptureRequirement(
"MS-FSSHTTPB",
4066,
@"[In Query Changes to Editors Table Partition] [The protocol server MUST return the editors table in the associated data element collection using the following process:] Treat the byte array as a file stream and chunk it using the schema described in [MS-FSSHTTPD]. ");
// Verify MS-FSSHTTPB requirement: MS-FSSHTTPB_R4067
// If can fetch the editors table, then the following requirement can be directly captured.
Site.CaptureRequirement(
"MS-FSSHTTPB",
4067,
@"[In Query Changes to Editors Table Partition] [The protocol server MUST return the editors table in the associated data element collection using the following process:] Sync the resulting cell using this protocol as you would any other cell.");
// Verify MS-FSSHTTPB requirement: MS-FSSHTTPB_R4068
// If can fetch the editors table, then the following requirement can be directly captured.
Site.CaptureRequirement(
"MS-FSSHTTPB",
4068,
@"[In Editors Table Zip Stream Header] A header that is prepended to the compressed EditorsTable byte array.");
// Verify MS-FSSHTTPB requirement: MS-FSSHTTPB_R4069
// If can fetch the editors table, then the following requirement can be directly captured.
Site.CaptureRequirement(
"MS-FSSHTTPB",
4069,
@"[In Editors Table Zip Stream Header] This header is an array of eight bytes.");
// Verify MS-FSSHTTPB requirement: MS-FSSHTTPB_R4070
// If can fetch the editors table, then the following requirement can be directly captured.
Site.CaptureRequirement(
"MS-FSSHTTPB",
4070,
@"[In Editors Table Zip Stream Header] The value and order of these bytes MUST be as follows: 0x1A, 0x5A, 0x3A, 0x30, 0x00, 0x00, 0x00, 0x00.");
// Verify MS-FSSHTTPB requirement: MS-FSSHTTPB_R4072
// If can fetch the editors table, then the following requirement can be directly captured.
Site.CaptureRequirement(
"MS-FSSHTTPB",
4072,
@" [In EditorsTable] [EditorsTable schema is:]
<xs:element name=""EditorsTable"">
< xs:complexType >
< xs:sequence >
< xs:element ref= ""tns:EditorElement"" name = ""Editor"" minOccurs = ""0"" maxOccurs = ""unbounded"" />
</ xs:sequence >
</ xs:complexType >
</ xs:element > ");
// Verify MS-FSSHTTPB requirement: MS-FSSHTTPB_R4074
// If can fetch the editors table, then the following requirement can be directly captured.
Site.CaptureRequirement(
"MS-FSSHTTPB",
4074,
@"[In EditorElement] [EditorElement schema is:]
<xs:element name=""EditorElement"">
< xs:complexType >
< xs:sequence >
< xs:element name = ""CacheID"" minOccurs = ""1"" maxOccurs = ""1"" type = ""xs:string"" />
< xs:element name = ""FriendlyName"" minOccurs = ""0"" maxOccurs = ""1"" type = "" type=""tns: UserNameType"" />
< xs:element name = ""LoginName"" minOccurs = ""0"" maxOccurs = ""1"" type = ""tns:UserLoginType"" />
< xs:element name = ""SIPAddress"" minOccurs = ""0"" maxOccurs = ""1"" type = ""xs:string"" />
< xs:element name = ""EmailAddress"" minOccurs = ""0"" maxOccurs = ""1"" type = ""xs:string"" />
< xs:element name = ""HasEditorPermission"" minOccurs = ""0"" maxOccurs = ""1"" type = ""xs:boolean"" />
< xs:element name = ""Timeout"" minOccurs = ""1"" maxOccurs = ""1"" type = ""xs:positiveInteger"" />
< xs:element name = ""Metadata"" minOccurs = ""0"" maxOccurs = ""1"" >
< xs:complexType >
< xs:sequence >
< xs:any minOccurs = ""0"" maxOccurs = ""unbounded"" type = ""xs:binary"" />
</ xs:sequence >
</ xs:complexType >
</ xs:element >
</ xs:sequence >
</ xs:complexType >
</ xs:element > ");
}
return editorsTable;
}
return null;
}
/// <summary>
/// This method is used to upload a new Txt file to a random generated URL which is based on the current test case name.
/// </summary>
/// <returns>Return the full URL of the Txt file target location.</returns>
protected string PrepareFile()
{
string fileUri = SharedTestSuiteHelper.GenerateNonExistFileUrl(Site);
string fileUrl = fileUri.Substring(0, fileUri.LastIndexOf("/", StringComparison.OrdinalIgnoreCase));
string fileName = fileUri.Substring(fileUri.LastIndexOf("/", StringComparison.OrdinalIgnoreCase) + 1);
bool ret = this.SutPowerShellAdapter.UploadTextFile(fileUrl, fileName);
if (ret == false)
{
this.Site.Assert.Fail("Cannot upload a file in the URL {0}", fileUri);
}
this.StatusManager.RecordFileUpload(fileUri);
return fileUri;
}
/// <summary>
/// Check if a file is available to take a shared lock or exclusive lock.
/// </summary>
protected void CheckLockAvailability()
{
if (!Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 93101, this.Site))
{
return;
}
int waitTime = Common.GetConfigurationPropertyValue<int>("WaitTime", this.Site);
int retryCount = Common.GetConfigurationPropertyValue<int>("RetryCount", this.Site);
while (retryCount > 0)
{
retryCount--;
CoauthSubRequestType request = SharedTestSuiteHelper.CreateCoauthSubRequestForCheckLockAvailability(SharedTestSuiteHelper.DefaultClientID, SharedTestSuiteHelper.ReservedSchemaLockID);
CellStorageResponse storageResponse = this.Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { request });
CoauthSubResponseType subResponse = SharedTestSuiteHelper.ExtractSubResponse<CoauthSubResponseType>(storageResponse, 0, 0, this.Site);
if (SharedTestSuiteHelper.ConvertToErrorCodeType(subResponse.ErrorCode, this.Site) == ErrorCodeType.Success)
{
break;
}
else
{
System.Threading.Thread.Sleep(waitTime);
}
if (retryCount == 0)
{
this.Site.Assert.AreEqual<ErrorCodeType>(
ErrorCodeType.Success,
SharedTestSuiteHelper.ConvertToErrorCodeType(subResponse.ErrorCode, this.Site),
"Check lock availability failed after checkout file.");
}
}
}
#endregion
#region Abstract Methods
/// <summary>
/// Override to initialize the shared context based on the specified request file URL, user name, password and domain.
/// </summary>
/// <param name="requestFileUrl">Specify the request file URL.</param>
/// <param name="userName">Specify the user name.</param>
/// <param name="password">Specify the password.</param>
/// <param name="domain">Specify the domain.</param>
protected abstract void InitializeContext(string requestFileUrl, string userName, string password, string domain);
/// <summary>
/// Override to merge the common configuration and should/man configuration file.
/// </summary>
/// <param name="site">An instance of interface ITestSite which provides logging, assertions,
/// and adapters for test code onto its execution context.</param>
protected abstract void MergeConfigurationFile(ITestSite site);
#endregion
}
}
| |
// ***********************************************************************
// Copyright (c) 2009-2014 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;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Security;
using System.Web.UI;
using NUnit.Compatibility;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
#if NETSTANDARD1_6
using System.Runtime.InteropServices;
#endif
namespace NUnit.Framework.Api
{
/// <summary>
/// FrameworkController provides a facade for use in loading, browsing
/// and running tests without requiring a reference to the NUnit
/// framework. All calls are encapsulated in constructors for
/// this class and its nested classes, which only require the
/// types of the Common Type System as arguments.
///
/// The controller supports four actions: Load, Explore, Count and Run.
/// They are intended to be called by a driver, which should allow for
/// proper sequencing of calls. Load must be called before any of the
/// other actions. The driver may support other actions, such as
/// reload on run, by combining these calls.
/// </summary>
public class FrameworkController : LongLivedMarshalByRefObject
{
#if !PORTABLE
private const string LOG_FILE_FORMAT = "InternalTrace.{0}.{1}.log";
#endif
// Pre-loaded test assembly, if passed in constructor
private Assembly _testAssembly;
#region Constructors
/// <summary>
/// Construct a FrameworkController using the default builder and runner.
/// </summary>
/// <param name="assemblyNameOrPath">The AssemblyName or path to the test assembly</param>
/// <param name="idPrefix">A prefix used for all test ids created under this controller.</param>
/// <param name="settings">A Dictionary of settings to use in loading and running the tests</param>
public FrameworkController(string assemblyNameOrPath, string idPrefix, IDictionary settings)
{
Initialize(assemblyNameOrPath, settings);
this.Builder = new DefaultTestAssemblyBuilder();
this.Runner = new NUnitTestAssemblyRunner(this.Builder);
Test.IdPrefix = idPrefix;
}
/// <summary>
/// Construct a FrameworkController using the default builder and runner.
/// </summary>
/// <param name="assembly">The test assembly</param>
/// <param name="idPrefix">A prefix used for all test ids created under this controller.</param>
/// <param name="settings">A Dictionary of settings to use in loading and running the tests</param>
public FrameworkController(Assembly assembly, string idPrefix, IDictionary settings)
: this(assembly.FullName, idPrefix, settings)
{
_testAssembly = assembly;
}
/// <summary>
/// Construct a FrameworkController, specifying the types to be used
/// for the runner and builder. This constructor is provided for
/// purposes of development.
/// </summary>
/// <param name="assemblyNameOrPath">The full AssemblyName or the path to the test assembly</param>
/// <param name="idPrefix">A prefix used for all test ids created under this controller.</param>
/// <param name="settings">A Dictionary of settings to use in loading and running the tests</param>
/// <param name="runnerType">The Type of the test runner</param>
/// <param name="builderType">The Type of the test builder</param>
public FrameworkController(string assemblyNameOrPath, string idPrefix, IDictionary settings, string runnerType, string builderType)
{
Initialize(assemblyNameOrPath, settings);
Builder = (ITestAssemblyBuilder)Reflect.Construct(Type.GetType(builderType));
Runner = (ITestAssemblyRunner)Reflect.Construct(Type.GetType(runnerType), new object[] { Builder });
Test.IdPrefix = idPrefix ?? "";
}
/// <summary>
/// Construct a FrameworkController, specifying the types to be used
/// for the runner and builder. This constructor is provided for
/// purposes of development.
/// </summary>
/// <param name="assembly">The test assembly</param>
/// <param name="idPrefix">A prefix used for all test ids created under this controller.</param>
/// <param name="settings">A Dictionary of settings to use in loading and running the tests</param>
/// <param name="runnerType">The Type of the test runner</param>
/// <param name="builderType">The Type of the test builder</param>
public FrameworkController(Assembly assembly, string idPrefix, IDictionary settings, string runnerType, string builderType)
: this(assembly.FullName, idPrefix, settings, runnerType, builderType)
{
_testAssembly = assembly;
}
#if !PORTABLE
// This method invokes members on the 'System.Diagnostics.Process' class and must satisfy the link demand of
// the full-trust 'PermissionSetAttribute' on this class. Callers of this method have no influence on how the
// Process class is used, so we can safely satisfy the link demand with a 'SecuritySafeCriticalAttribute' rather
// than a 'SecurityCriticalAttribute' and allow use by security transparent callers.
[SecuritySafeCritical]
#endif
private void Initialize(string assemblyPath, IDictionary settings)
{
AssemblyNameOrPath = assemblyPath;
var newSettings = settings as IDictionary<string, object>;
Settings = newSettings ?? settings.Cast<DictionaryEntry>().ToDictionary(de => (string)de.Key, de => de.Value);
if (Settings.ContainsKey(FrameworkPackageSettings.InternalTraceLevel))
{
var traceLevel = (InternalTraceLevel)Enum.Parse(typeof(InternalTraceLevel), (string)Settings[FrameworkPackageSettings.InternalTraceLevel], true);
if (Settings.ContainsKey(FrameworkPackageSettings.InternalTraceWriter))
InternalTrace.Initialize((TextWriter)Settings[FrameworkPackageSettings.InternalTraceWriter], traceLevel);
#if !PORTABLE
else
{
var workDirectory = Settings.ContainsKey(FrameworkPackageSettings.WorkDirectory)
? (string)Settings[FrameworkPackageSettings.WorkDirectory]
: Directory.GetCurrentDirectory();
#if NETSTANDARD1_6
var id = DateTime.Now.ToString("o");
#else
var id = Process.GetCurrentProcess().Id;
#endif
var logName = string.Format(LOG_FILE_FORMAT, id, Path.GetFileName(assemblyPath));
InternalTrace.Initialize(Path.Combine(workDirectory, logName), traceLevel);
}
#endif
}
}
#endregion
#region Properties
/// <summary>
/// Gets the ITestAssemblyBuilder used by this controller instance.
/// </summary>
/// <value>The builder.</value>
public ITestAssemblyBuilder Builder { get; private set; }
/// <summary>
/// Gets the ITestAssemblyRunner used by this controller instance.
/// </summary>
/// <value>The runner.</value>
public ITestAssemblyRunner Runner { get; private set; }
/// <summary>
/// Gets the AssemblyName or the path for which this FrameworkController was created
/// </summary>
public string AssemblyNameOrPath { get; private set; }
/// <summary>
/// Gets the Assembly for which this
/// </summary>
public Assembly Assembly { get; private set; }
/// <summary>
/// Gets a dictionary of settings for the FrameworkController
/// </summary>
internal IDictionary<string, object> Settings { get; private set; }
#endregion
#region Public Action methods Used by nunit.driver for running portable tests
/// <summary>
/// Loads the tests in the assembly
/// </summary>
/// <returns></returns>
public string LoadTests()
{
if (_testAssembly != null)
Runner.Load(_testAssembly, Settings);
else
Runner.Load(AssemblyNameOrPath, Settings);
return Runner.LoadedTest.ToXml(false).OuterXml;
}
/// <summary>
/// Returns info about the tests in an assembly
/// </summary>
/// <param name="filter">A string containing the XML representation of the filter to use</param>
/// <returns>The XML result of exploring the tests</returns>
public string ExploreTests(string filter)
{
Guard.ArgumentNotNull(filter, "filter");
if (Runner.LoadedTest == null)
throw new InvalidOperationException("The Explore method was called but no test has been loaded");
return Runner.ExploreTests(TestFilter.FromXml(filter)).ToXml(true).OuterXml;
}
/// <summary>
/// Runs the tests in an assembly
/// </summary>
/// <param name="filter">A string containing the XML representation of the filter to use</param>
/// <returns>The XML result of the test run</returns>
public string RunTests(string filter)
{
Guard.ArgumentNotNull(filter, "filter");
TNode result = Runner.Run(new TestProgressReporter(null), TestFilter.FromXml(filter)).ToXml(true);
// Insert elements as first child in reverse order
if (Settings != null) // Some platforms don't have settings
InsertSettingsElement(result, Settings);
#if !PORTABLE
InsertEnvironmentElement(result);
#endif
return result.OuterXml;
}
#if !NET_2_0
class ActionCallback : ICallbackEventHandler
{
Action<string> _callback;
public ActionCallback(Action<string> callback)
{
_callback = callback;
}
public string GetCallbackResult()
{
throw new NotImplementedException();
}
public void RaiseCallbackEvent(string report)
{
if (_callback != null)
_callback.Invoke(report);
}
}
/// <summary>
/// Runs the tests in an assembly synchronously reporting back the test results through the callback
/// or through the return value
/// </summary>
/// <param name="callback">The callback that receives the test results</param>
/// <param name="filter">A string containing the XML representation of the filter to use</param>
/// <returns>The XML result of the test run</returns>
public string RunTests(Action<string> callback, string filter)
{
Guard.ArgumentNotNull(filter, "filter");
var handler = new ActionCallback(callback);
TNode result = Runner.Run(new TestProgressReporter(handler), TestFilter.FromXml(filter)).ToXml(true);
// Insert elements as first child in reverse order
if (Settings != null) // Some platforms don't have settings
InsertSettingsElement(result, Settings);
#if !PORTABLE
InsertEnvironmentElement(result);
#endif
return result.OuterXml;
}
/// <summary>
/// Runs the tests in an assembly asynchronously reporting back the test results through the callback
/// </summary>
/// <param name="callback">The callback that receives the test results</param>
/// <param name="filter">A string containing the XML representation of the filter to use</param>
private void RunAsync(Action<string> callback, string filter)
{
Guard.ArgumentNotNull(filter, "filter");
var handler = new ActionCallback(callback);
Runner.RunAsync(new TestProgressReporter(handler), TestFilter.FromXml(filter));
}
#endif
/// <summary>
/// Stops the test run
/// </summary>
/// <param name="force">True to force the stop, false for a cooperative stop</param>
public void StopRun(bool force)
{
Runner.StopRun(force);
}
/// <summary>
/// Counts the number of test cases in the loaded TestSuite
/// </summary>
/// <param name="filter">A string containing the XML representation of the filter to use</param>
/// <returns>The number of tests</returns>
public int CountTests(string filter)
{
Guard.ArgumentNotNull(filter, "filter");
return Runner.CountTestCases(TestFilter.FromXml(filter));
}
#endregion
#region Private Action Methods Used by Nested Classes
private void LoadTests(ICallbackEventHandler handler)
{
handler.RaiseCallbackEvent(LoadTests());
}
private void ExploreTests(ICallbackEventHandler handler, string filter)
{
Guard.ArgumentNotNull(filter, "filter");
if (Runner.LoadedTest == null)
throw new InvalidOperationException("The Explore method was called but no test has been loaded");
handler.RaiseCallbackEvent(Runner.ExploreTests(TestFilter.FromXml(filter)).ToXml(true).OuterXml);
}
private void RunTests(ICallbackEventHandler handler, string filter)
{
Guard.ArgumentNotNull(filter, "filter");
TNode result = Runner.Run(new TestProgressReporter(handler), TestFilter.FromXml(filter)).ToXml(true);
// Insert elements as first child in reverse order
if (Settings != null) // Some platforms don't have settings
InsertSettingsElement(result, Settings);
#if !PORTABLE
InsertEnvironmentElement(result);
#endif
handler.RaiseCallbackEvent(result.OuterXml);
}
private void RunAsync(ICallbackEventHandler handler, string filter)
{
Guard.ArgumentNotNull(filter, "filter");
Runner.RunAsync(new TestProgressReporter(handler), TestFilter.FromXml(filter));
}
private void StopRun(ICallbackEventHandler handler, bool force)
{
StopRun(force);
}
private void CountTests(ICallbackEventHandler handler, string filter)
{
handler.RaiseCallbackEvent(CountTests(filter).ToString());
}
#if !PORTABLE
/// <summary>
/// Inserts environment element
/// </summary>
/// <param name="targetNode">Target node</param>
/// <returns>The new node</returns>
#if NETSTANDARD1_6
public static TNode InsertEnvironmentElement(TNode targetNode)
{
TNode env = new TNode("environment");
targetNode.ChildNodes.Insert(0, env);
var assemblyName = AssemblyHelper.GetAssemblyName(typeof(FrameworkController).GetTypeInfo().Assembly);
env.AddAttribute("framework-version", assemblyName.Version.ToString());
env.AddAttribute("clr-version", RuntimeInformation.FrameworkDescription);
env.AddAttribute("os-version", RuntimeInformation.OSDescription);
env.AddAttribute("cwd", Directory.GetCurrentDirectory());
env.AddAttribute("machine-name", Environment.MachineName);
env.AddAttribute("culture", CultureInfo.CurrentCulture.ToString());
env.AddAttribute("uiculture", CultureInfo.CurrentUICulture.ToString());
env.AddAttribute("os-architecture", RuntimeInformation.ProcessArchitecture.ToString());
return env;
}
#else
public static TNode InsertEnvironmentElement(TNode targetNode)
{
TNode env = new TNode("environment");
targetNode.ChildNodes.Insert(0, env);
env.AddAttribute("framework-version", Assembly.GetExecutingAssembly().GetName().Version.ToString());
env.AddAttribute("clr-version", Environment.Version.ToString());
env.AddAttribute("os-version", Environment.OSVersion.ToString());
env.AddAttribute("platform", Environment.OSVersion.Platform.ToString());
env.AddAttribute("cwd", Environment.CurrentDirectory);
env.AddAttribute("machine-name", Environment.MachineName);
env.AddAttribute("user", Environment.UserName);
env.AddAttribute("user-domain", Environment.UserDomainName);
env.AddAttribute("culture", CultureInfo.CurrentCulture.ToString());
env.AddAttribute("uiculture", CultureInfo.CurrentUICulture.ToString());
env.AddAttribute("os-architecture", GetProcessorArchitecture());
return env;
}
private static string GetProcessorArchitecture()
{
return IntPtr.Size == 8 ? "x64" : "x86";
}
#endif
#endif
/// <summary>
/// Inserts settings element
/// </summary>
/// <param name="targetNode">Target node</param>
/// <param name="settings">Settings dictionary</param>
/// <returns>The new node</returns>
public static TNode InsertSettingsElement(TNode targetNode, IDictionary<string, object> settings)
{
TNode settingsNode = new TNode("settings");
targetNode.ChildNodes.Insert(0, settingsNode);
foreach (string key in settings.Keys)
AddSetting(settingsNode, key, settings[key]);
#if PARALLEL
// Add default values for display
if (!settings.ContainsKey(FrameworkPackageSettings.NumberOfTestWorkers))
AddSetting(settingsNode, FrameworkPackageSettings.NumberOfTestWorkers, NUnitTestAssemblyRunner.DefaultLevelOfParallelism);
#endif
return settingsNode;
}
private static void AddSetting(TNode settingsNode, string name, object value)
{
TNode setting = new TNode("setting");
setting.AddAttribute("name", name);
setting.AddAttribute("value", value.ToString());
settingsNode.ChildNodes.Add(setting);
}
#endregion
#region Nested Action Classes
#region TestContollerAction
/// <summary>
/// FrameworkControllerAction is the base class for all actions
/// performed against a FrameworkController.
/// </summary>
public abstract class FrameworkControllerAction : LongLivedMarshalByRefObject
{
}
#endregion
#region LoadTestsAction
/// <summary>
/// LoadTestsAction loads a test into the FrameworkController
/// </summary>
public class LoadTestsAction : FrameworkControllerAction
{
/// <summary>
/// LoadTestsAction loads the tests in an assembly.
/// </summary>
/// <param name="controller">The controller.</param>
/// <param name="handler">The callback handler.</param>
public LoadTestsAction(FrameworkController controller, object handler)
{
controller.LoadTests((ICallbackEventHandler)handler);
}
}
#endregion
#region ExploreTestsAction
/// <summary>
/// ExploreTestsAction returns info about the tests in an assembly
/// </summary>
public class ExploreTestsAction : FrameworkControllerAction
{
/// <summary>
/// Initializes a new instance of the <see cref="ExploreTestsAction"/> class.
/// </summary>
/// <param name="controller">The controller for which this action is being performed.</param>
/// <param name="filter">Filter used to control which tests are included (NYI)</param>
/// <param name="handler">The callback handler.</param>
public ExploreTestsAction(FrameworkController controller, string filter, object handler)
{
controller.ExploreTests((ICallbackEventHandler)handler, filter);
}
}
#endregion
#region CountTestsAction
/// <summary>
/// CountTestsAction counts the number of test cases in the loaded TestSuite
/// held by the FrameworkController.
/// </summary>
public class CountTestsAction : FrameworkControllerAction
{
/// <summary>
/// Construct a CountsTestAction and perform the count of test cases.
/// </summary>
/// <param name="controller">A FrameworkController holding the TestSuite whose cases are to be counted</param>
/// <param name="filter">A string containing the XML representation of the filter to use</param>
/// <param name="handler">A callback handler used to report results</param>
public CountTestsAction(FrameworkController controller, string filter, object handler)
{
controller.CountTests((ICallbackEventHandler)handler, filter);
}
}
#endregion
#region RunTestsAction
/// <summary>
/// RunTestsAction runs the loaded TestSuite held by the FrameworkController.
/// </summary>
public class RunTestsAction : FrameworkControllerAction
{
/// <summary>
/// Construct a RunTestsAction and run all tests in the loaded TestSuite.
/// </summary>
/// <param name="controller">A FrameworkController holding the TestSuite to run</param>
/// <param name="filter">A string containing the XML representation of the filter to use</param>
/// <param name="handler">A callback handler used to report results</param>
public RunTestsAction(FrameworkController controller, string filter, object handler)
{
controller.RunTests((ICallbackEventHandler)handler, filter);
}
}
#endregion
#region RunAsyncAction
/// <summary>
/// RunAsyncAction initiates an asynchronous test run, returning immediately
/// </summary>
public class RunAsyncAction : FrameworkControllerAction
{
/// <summary>
/// Construct a RunAsyncAction and run all tests in the loaded TestSuite.
/// </summary>
/// <param name="controller">A FrameworkController holding the TestSuite to run</param>
/// <param name="filter">A string containing the XML representation of the filter to use</param>
/// <param name="handler">A callback handler used to report results</param>
public RunAsyncAction(FrameworkController controller, string filter, object handler)
{
controller.RunAsync((ICallbackEventHandler)handler, filter);
}
}
#endregion
#region StopRunAction
/// <summary>
/// StopRunAction stops an ongoing run.
/// </summary>
public class StopRunAction : FrameworkControllerAction
{
/// <summary>
/// Construct a StopRunAction and stop any ongoing run. If no
/// run is in process, no error is raised.
/// </summary>
/// <param name="controller">The FrameworkController for which a run is to be stopped.</param>
/// <param name="force">True the stop should be forced, false for a cooperative stop.</param>
/// <param name="handler">>A callback handler used to report results</param>
/// <remarks>A forced stop will cause threads and processes to be killed as needed.</remarks>
public StopRunAction(FrameworkController controller, bool force, object handler)
{
controller.StopRun((ICallbackEventHandler)handler, force);
}
}
#endregion
#endregion
}
}
| |
using System;
using ChainUtils.BouncyCastle.Crypto.Parameters;
using ChainUtils.BouncyCastle.Crypto.Utilities;
namespace ChainUtils.BouncyCastle.Crypto.Engines
{
/// <remarks>A class that provides a basic DES engine.</remarks>
public class DesEngine
: IBlockCipher
{
internal const int BLOCK_SIZE = 8;
private int[] workingKey;
public virtual int[] GetWorkingKey()
{
return workingKey;
}
/**
* initialise a DES cipher.
*
* @param forEncryption whether or not we are for encryption.
* @param parameters the parameters required to set up the cipher.
* @exception ArgumentException if the parameters argument is
* inappropriate.
*/
public virtual void Init(
bool forEncryption,
ICipherParameters parameters)
{
if (!(parameters is KeyParameter))
throw new ArgumentException("invalid parameter passed to DES init - " + parameters.GetType().ToString());
workingKey = GenerateWorkingKey(forEncryption, ((KeyParameter)parameters).GetKey());
}
public virtual string AlgorithmName
{
get { return "DES"; }
}
public bool IsPartialBlockOkay
{
get { return false; }
}
public virtual int GetBlockSize()
{
return BLOCK_SIZE;
}
public virtual int ProcessBlock(
byte[] input,
int inOff,
byte[] output,
int outOff)
{
if (workingKey == null)
throw new InvalidOperationException("DES engine not initialised");
if ((inOff + BLOCK_SIZE) > input.Length)
throw new DataLengthException("input buffer too short");
if ((outOff + BLOCK_SIZE) > output.Length)
throw new DataLengthException("output buffer too short");
DesFunc(workingKey, input, inOff, output, outOff);
return BLOCK_SIZE;
}
public virtual void Reset()
{
}
/**
* what follows is mainly taken from "Applied Cryptography", by
* Bruce Schneier, however it also bears great resemblance to Richard
* Outerbridge's D3DES...
*/
// private static readonly short[] Df_Key =
// {
// 0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef,
// 0xfe,0xdc,0xba,0x98,0x76,0x54,0x32,0x10,
// 0x89,0xab,0xcd,0xef,0x01,0x23,0x45,0x67
// };
private static readonly short[] bytebit =
{
128, 64, 32, 16, 8, 4, 2, 1
};
private static readonly int[] bigbyte =
{
0x800000, 0x400000, 0x200000, 0x100000,
0x80000, 0x40000, 0x20000, 0x10000,
0x8000, 0x4000, 0x2000, 0x1000,
0x800, 0x400, 0x200, 0x100,
0x80, 0x40, 0x20, 0x10,
0x8, 0x4, 0x2, 0x1
};
/*
* Use the key schedule specified in the Standard (ANSI X3.92-1981).
*/
private static readonly byte[] pc1 =
{
56, 48, 40, 32, 24, 16, 8, 0, 57, 49, 41, 33, 25, 17,
9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35,
62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21,
13, 5, 60, 52, 44, 36, 28, 20, 12, 4, 27, 19, 11, 3
};
private static readonly byte[] totrot =
{
1, 2, 4, 6, 8, 10, 12, 14,
15, 17, 19, 21, 23, 25, 27, 28
};
private static readonly byte[] pc2 =
{
13, 16, 10, 23, 0, 4, 2, 27, 14, 5, 20, 9,
22, 18, 11, 3, 25, 7, 15, 6, 26, 19, 12, 1,
40, 51, 30, 36, 46, 54, 29, 39, 50, 44, 32, 47,
43, 48, 38, 55, 33, 52, 45, 41, 49, 35, 28, 31
};
private static readonly uint[] SP1 =
{
0x01010400, 0x00000000, 0x00010000, 0x01010404,
0x01010004, 0x00010404, 0x00000004, 0x00010000,
0x00000400, 0x01010400, 0x01010404, 0x00000400,
0x01000404, 0x01010004, 0x01000000, 0x00000004,
0x00000404, 0x01000400, 0x01000400, 0x00010400,
0x00010400, 0x01010000, 0x01010000, 0x01000404,
0x00010004, 0x01000004, 0x01000004, 0x00010004,
0x00000000, 0x00000404, 0x00010404, 0x01000000,
0x00010000, 0x01010404, 0x00000004, 0x01010000,
0x01010400, 0x01000000, 0x01000000, 0x00000400,
0x01010004, 0x00010000, 0x00010400, 0x01000004,
0x00000400, 0x00000004, 0x01000404, 0x00010404,
0x01010404, 0x00010004, 0x01010000, 0x01000404,
0x01000004, 0x00000404, 0x00010404, 0x01010400,
0x00000404, 0x01000400, 0x01000400, 0x00000000,
0x00010004, 0x00010400, 0x00000000, 0x01010004
};
private static readonly uint[] SP2 =
{
0x80108020, 0x80008000, 0x00008000, 0x00108020,
0x00100000, 0x00000020, 0x80100020, 0x80008020,
0x80000020, 0x80108020, 0x80108000, 0x80000000,
0x80008000, 0x00100000, 0x00000020, 0x80100020,
0x00108000, 0x00100020, 0x80008020, 0x00000000,
0x80000000, 0x00008000, 0x00108020, 0x80100000,
0x00100020, 0x80000020, 0x00000000, 0x00108000,
0x00008020, 0x80108000, 0x80100000, 0x00008020,
0x00000000, 0x00108020, 0x80100020, 0x00100000,
0x80008020, 0x80100000, 0x80108000, 0x00008000,
0x80100000, 0x80008000, 0x00000020, 0x80108020,
0x00108020, 0x00000020, 0x00008000, 0x80000000,
0x00008020, 0x80108000, 0x00100000, 0x80000020,
0x00100020, 0x80008020, 0x80000020, 0x00100020,
0x00108000, 0x00000000, 0x80008000, 0x00008020,
0x80000000, 0x80100020, 0x80108020, 0x00108000
};
private static readonly uint[] SP3 =
{
0x00000208, 0x08020200, 0x00000000, 0x08020008,
0x08000200, 0x00000000, 0x00020208, 0x08000200,
0x00020008, 0x08000008, 0x08000008, 0x00020000,
0x08020208, 0x00020008, 0x08020000, 0x00000208,
0x08000000, 0x00000008, 0x08020200, 0x00000200,
0x00020200, 0x08020000, 0x08020008, 0x00020208,
0x08000208, 0x00020200, 0x00020000, 0x08000208,
0x00000008, 0x08020208, 0x00000200, 0x08000000,
0x08020200, 0x08000000, 0x00020008, 0x00000208,
0x00020000, 0x08020200, 0x08000200, 0x00000000,
0x00000200, 0x00020008, 0x08020208, 0x08000200,
0x08000008, 0x00000200, 0x00000000, 0x08020008,
0x08000208, 0x00020000, 0x08000000, 0x08020208,
0x00000008, 0x00020208, 0x00020200, 0x08000008,
0x08020000, 0x08000208, 0x00000208, 0x08020000,
0x00020208, 0x00000008, 0x08020008, 0x00020200
};
private static readonly uint[] SP4 =
{
0x00802001, 0x00002081, 0x00002081, 0x00000080,
0x00802080, 0x00800081, 0x00800001, 0x00002001,
0x00000000, 0x00802000, 0x00802000, 0x00802081,
0x00000081, 0x00000000, 0x00800080, 0x00800001,
0x00000001, 0x00002000, 0x00800000, 0x00802001,
0x00000080, 0x00800000, 0x00002001, 0x00002080,
0x00800081, 0x00000001, 0x00002080, 0x00800080,
0x00002000, 0x00802080, 0x00802081, 0x00000081,
0x00800080, 0x00800001, 0x00802000, 0x00802081,
0x00000081, 0x00000000, 0x00000000, 0x00802000,
0x00002080, 0x00800080, 0x00800081, 0x00000001,
0x00802001, 0x00002081, 0x00002081, 0x00000080,
0x00802081, 0x00000081, 0x00000001, 0x00002000,
0x00800001, 0x00002001, 0x00802080, 0x00800081,
0x00002001, 0x00002080, 0x00800000, 0x00802001,
0x00000080, 0x00800000, 0x00002000, 0x00802080
};
private static readonly uint[] SP5 =
{
0x00000100, 0x02080100, 0x02080000, 0x42000100,
0x00080000, 0x00000100, 0x40000000, 0x02080000,
0x40080100, 0x00080000, 0x02000100, 0x40080100,
0x42000100, 0x42080000, 0x00080100, 0x40000000,
0x02000000, 0x40080000, 0x40080000, 0x00000000,
0x40000100, 0x42080100, 0x42080100, 0x02000100,
0x42080000, 0x40000100, 0x00000000, 0x42000000,
0x02080100, 0x02000000, 0x42000000, 0x00080100,
0x00080000, 0x42000100, 0x00000100, 0x02000000,
0x40000000, 0x02080000, 0x42000100, 0x40080100,
0x02000100, 0x40000000, 0x42080000, 0x02080100,
0x40080100, 0x00000100, 0x02000000, 0x42080000,
0x42080100, 0x00080100, 0x42000000, 0x42080100,
0x02080000, 0x00000000, 0x40080000, 0x42000000,
0x00080100, 0x02000100, 0x40000100, 0x00080000,
0x00000000, 0x40080000, 0x02080100, 0x40000100
};
private static readonly uint[] SP6 =
{
0x20000010, 0x20400000, 0x00004000, 0x20404010,
0x20400000, 0x00000010, 0x20404010, 0x00400000,
0x20004000, 0x00404010, 0x00400000, 0x20000010,
0x00400010, 0x20004000, 0x20000000, 0x00004010,
0x00000000, 0x00400010, 0x20004010, 0x00004000,
0x00404000, 0x20004010, 0x00000010, 0x20400010,
0x20400010, 0x00000000, 0x00404010, 0x20404000,
0x00004010, 0x00404000, 0x20404000, 0x20000000,
0x20004000, 0x00000010, 0x20400010, 0x00404000,
0x20404010, 0x00400000, 0x00004010, 0x20000010,
0x00400000, 0x20004000, 0x20000000, 0x00004010,
0x20000010, 0x20404010, 0x00404000, 0x20400000,
0x00404010, 0x20404000, 0x00000000, 0x20400010,
0x00000010, 0x00004000, 0x20400000, 0x00404010,
0x00004000, 0x00400010, 0x20004010, 0x00000000,
0x20404000, 0x20000000, 0x00400010, 0x20004010
};
private static readonly uint[] SP7 =
{
0x00200000, 0x04200002, 0x04000802, 0x00000000,
0x00000800, 0x04000802, 0x00200802, 0x04200800,
0x04200802, 0x00200000, 0x00000000, 0x04000002,
0x00000002, 0x04000000, 0x04200002, 0x00000802,
0x04000800, 0x00200802, 0x00200002, 0x04000800,
0x04000002, 0x04200000, 0x04200800, 0x00200002,
0x04200000, 0x00000800, 0x00000802, 0x04200802,
0x00200800, 0x00000002, 0x04000000, 0x00200800,
0x04000000, 0x00200800, 0x00200000, 0x04000802,
0x04000802, 0x04200002, 0x04200002, 0x00000002,
0x00200002, 0x04000000, 0x04000800, 0x00200000,
0x04200800, 0x00000802, 0x00200802, 0x04200800,
0x00000802, 0x04000002, 0x04200802, 0x04200000,
0x00200800, 0x00000000, 0x00000002, 0x04200802,
0x00000000, 0x00200802, 0x04200000, 0x00000800,
0x04000002, 0x04000800, 0x00000800, 0x00200002
};
private static readonly uint[] SP8 =
{
0x10001040, 0x00001000, 0x00040000, 0x10041040,
0x10000000, 0x10001040, 0x00000040, 0x10000000,
0x00040040, 0x10040000, 0x10041040, 0x00041000,
0x10041000, 0x00041040, 0x00001000, 0x00000040,
0x10040000, 0x10000040, 0x10001000, 0x00001040,
0x00041000, 0x00040040, 0x10040040, 0x10041000,
0x00001040, 0x00000000, 0x00000000, 0x10040040,
0x10000040, 0x10001000, 0x00041040, 0x00040000,
0x00041040, 0x00040000, 0x10041000, 0x00001000,
0x00000040, 0x10040040, 0x00001000, 0x00041040,
0x10001000, 0x00000040, 0x10000040, 0x10040000,
0x10040040, 0x10000000, 0x00040000, 0x10001040,
0x00000000, 0x10041040, 0x00040040, 0x10000040,
0x10040000, 0x10001000, 0x10001040, 0x00000000,
0x10041040, 0x00041000, 0x00041000, 0x00001040,
0x00001040, 0x00040040, 0x10000000, 0x10041000
};
/**
* Generate an integer based working key based on our secret key
* and what we processing we are planning to do.
*
* Acknowledgements for this routine go to James Gillogly and Phil Karn.
* (whoever, and wherever they are!).
*/
protected static int[] GenerateWorkingKey(
bool encrypting,
byte[] key)
{
var newKey = new int[32];
var pc1m = new bool[56];
var pcr = new bool[56];
for (var j = 0; j < 56; j++ )
{
int l = pc1[j];
pc1m[j] = ((key[(uint) l >> 3] & bytebit[l & 07]) != 0);
}
for (var i = 0; i < 16; i++)
{
int l, m, n;
if (encrypting)
{
m = i << 1;
}
else
{
m = (15 - i) << 1;
}
n = m + 1;
newKey[m] = newKey[n] = 0;
for (var j = 0; j < 28; j++)
{
l = j + totrot[i];
if ( l < 28 )
{
pcr[j] = pc1m[l];
}
else
{
pcr[j] = pc1m[l - 28];
}
}
for (var j = 28; j < 56; j++)
{
l = j + totrot[i];
if (l < 56 )
{
pcr[j] = pc1m[l];
}
else
{
pcr[j] = pc1m[l - 28];
}
}
for (var j = 0; j < 24; j++)
{
if (pcr[pc2[j]])
{
newKey[m] |= bigbyte[j];
}
if (pcr[pc2[j + 24]])
{
newKey[n] |= bigbyte[j];
}
}
}
//
// store the processed key
//
for (var i = 0; i != 32; i += 2)
{
int i1, i2;
i1 = newKey[i];
i2 = newKey[i + 1];
newKey[i] = (int) ( (uint) ((i1 & 0x00fc0000) << 6) |
(uint) ((i1 & 0x00000fc0) << 10) |
((uint) (i2 & 0x00fc0000) >> 10) |
((uint) (i2 & 0x00000fc0) >> 6));
newKey[i + 1] = (int) ( (uint) ((i1 & 0x0003f000) << 12) |
(uint) ((i1 & 0x0000003f) << 16) |
((uint) (i2 & 0x0003f000) >> 4) |
(uint) (i2 & 0x0000003f));
}
return newKey;
}
/**
* the DES engine.
*/
internal static void DesFunc(
int[] wKey,
byte[] input,
int inOff,
byte[] outBytes,
int outOff)
{
var left = Pack.BE_To_UInt32(input, inOff);
var right = Pack.BE_To_UInt32(input, inOff + 4);
uint work;
work = ((left >> 4) ^ right) & 0x0f0f0f0f;
right ^= work;
left ^= (work << 4);
work = ((left >> 16) ^ right) & 0x0000ffff;
right ^= work;
left ^= (work << 16);
work = ((right >> 2) ^ left) & 0x33333333;
left ^= work;
right ^= (work << 2);
work = ((right >> 8) ^ left) & 0x00ff00ff;
left ^= work;
right ^= (work << 8);
right = (right << 1) | (right >> 31);
work = (left ^ right) & 0xaaaaaaaa;
left ^= work;
right ^= work;
left = (left << 1) | (left >> 31);
for (var round = 0; round < 8; round++)
{
uint fval;
work = (right << 28) | (right >> 4);
work ^= (uint)wKey[round * 4 + 0];
fval = SP7[work & 0x3f];
fval |= SP5[(work >> 8) & 0x3f];
fval |= SP3[(work >> 16) & 0x3f];
fval |= SP1[(work >> 24) & 0x3f];
work = right ^ (uint)wKey[round * 4 + 1];
fval |= SP8[ work & 0x3f];
fval |= SP6[(work >> 8) & 0x3f];
fval |= SP4[(work >> 16) & 0x3f];
fval |= SP2[(work >> 24) & 0x3f];
left ^= fval;
work = (left << 28) | (left >> 4);
work ^= (uint)wKey[round * 4 + 2];
fval = SP7[ work & 0x3f];
fval |= SP5[(work >> 8) & 0x3f];
fval |= SP3[(work >> 16) & 0x3f];
fval |= SP1[(work >> 24) & 0x3f];
work = left ^ (uint)wKey[round * 4 + 3];
fval |= SP8[ work & 0x3f];
fval |= SP6[(work >> 8) & 0x3f];
fval |= SP4[(work >> 16) & 0x3f];
fval |= SP2[(work >> 24) & 0x3f];
right ^= fval;
}
right = (right << 31) | (right >> 1);
work = (left ^ right) & 0xaaaaaaaa;
left ^= work;
right ^= work;
left = (left << 31) | (left >> 1);
work = ((left >> 8) ^ right) & 0x00ff00ff;
right ^= work;
left ^= (work << 8);
work = ((left >> 2) ^ right) & 0x33333333;
right ^= work;
left ^= (work << 2);
work = ((right >> 16) ^ left) & 0x0000ffff;
left ^= work;
right ^= (work << 16);
work = ((right >> 4) ^ left) & 0x0f0f0f0f;
left ^= work;
right ^= (work << 4);
Pack.UInt32_To_BE(right, outBytes, outOff);
Pack.UInt32_To_BE(left, outBytes, outOff + 4);
}
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine;
using DarkMultiPlayerCommon;
using System.IO;
using MessageStream2;
namespace DarkMultiPlayer
{
public class CraftLibraryWorker
{
public bool display;
public bool workerEnabled;
//Private
private Queue<CraftChangeEntry> craftAddQueue = new Queue<CraftChangeEntry>();
private Queue<CraftChangeEntry> craftDeleteQueue = new Queue<CraftChangeEntry>();
private Queue<CraftResponseEntry> craftResponseQueue = new Queue<CraftResponseEntry>();
private bool safeDisplay;
private bool initialized;
private bool showUpload;
private bool isWindowLocked;
private string selectedPlayer;
private List<string> playersWithCrafts = new List<string>();
//Player -> Craft type -> Craft name
private Dictionary<string, Dictionary<CraftType, List<string>>> playerList = new Dictionary<string, Dictionary<CraftType, List<string>>>();
//Craft type -> Craft name
private Dictionary<CraftType, List<string>> uploadList = new Dictionary<CraftType, List<string>>();
//GUI Layout
private Rect playerWindowRect;
private Rect libraryWindowRect;
private Rect moveRect;
private GUILayoutOption[] playerLayoutOptions;
private GUILayoutOption[] libraryLayoutOptions;
private GUILayoutOption[] textAreaOptions;
private GUIStyle windowStyle;
private GUIStyle buttonStyle;
private GUIStyle labelStyle;
private GUIStyle scrollStyle;
private Vector2 playerScrollPos;
private Vector2 libraryScrollPos;
//save paths
private string savePath;
private string vabPath;
private string sphPath;
private string subassemblyPath;
//upload event
private CraftType uploadCraftType;
private string uploadCraftName;
//download event
private CraftType downloadCraftType;
private string downloadCraftName;
//delete event
private CraftType deleteCraftType;
private string deleteCraftName;
//Screen message
private bool displayCraftUploadingMessage;
public bool finishedUploadingCraft;
private float lastCraftMessageCheck;
ScreenMessage craftUploadMessage;
//const
private const float PLAYER_WINDOW_HEIGHT = 300;
private const float PLAYER_WINDOW_WIDTH = 200;
private const float LIBRARY_WINDOW_HEIGHT = 400;
private const float LIBRARY_WINDOW_WIDTH = 300;
private const float CRAFT_MESSAGE_CHECK_INTERVAL = 0.2f;
//Services
private DMPGame dmpGame;
private Settings dmpSettings;
private NetworkWorker networkWorker;
private NamedAction updateAction;
private NamedAction drawAction;
public CraftLibraryWorker(DMPGame dmpGame, Settings dmpSettings, NetworkWorker networkWorker)
{
this.dmpGame = dmpGame;
this.dmpSettings = dmpSettings;
this.networkWorker = networkWorker;
savePath = Path.Combine(Path.Combine(Client.dmpClient.kspRootPath, "saves"), "DarkMultiPlayer");
vabPath = Path.Combine(Path.Combine(savePath, "Ships"), "VAB");
sphPath = Path.Combine(Path.Combine(savePath, "Ships"), "SPH");
subassemblyPath = Path.Combine(savePath, "Subassemblies");
BuildUploadList();
updateAction = new NamedAction(Update);
drawAction = new NamedAction(Draw);
dmpGame.updateEvent.Add(updateAction);
dmpGame.drawEvent.Add(drawAction);
}
private void Update()
{
safeDisplay = display;
if (workerEnabled)
{
while (craftAddQueue.Count > 0)
{
CraftChangeEntry cce = craftAddQueue.Dequeue();
AddCraftEntry(cce.playerName, cce.craftType, cce.craftName);
}
while (craftDeleteQueue.Count > 0)
{
CraftChangeEntry cce = craftDeleteQueue.Dequeue();
DeleteCraftEntry(cce.playerName, cce.craftType, cce.craftName);
}
while (craftResponseQueue.Count > 0)
{
CraftResponseEntry cre = craftResponseQueue.Dequeue();
SaveCraftFile(cre.craftType, cre.craftName, cre.craftData);
}
if (uploadCraftName != null)
{
UploadCraftFile(uploadCraftType, uploadCraftName);
uploadCraftName = null;
uploadCraftType = CraftType.VAB;
}
if (downloadCraftName != null)
{
DownloadCraftFile(selectedPlayer, downloadCraftType, downloadCraftName);
downloadCraftName = null;
downloadCraftType = CraftType.VAB;
}
if (deleteCraftName != null)
{
DeleteCraftEntry(dmpSettings.playerName, deleteCraftType, deleteCraftName);
using (MessageWriter mw = new MessageWriter())
{
mw.Write<int>((int)CraftMessageType.DELETE_FILE);
mw.Write<string>(dmpSettings.playerName);
mw.Write<int>((int)deleteCraftType);
mw.Write<string>(deleteCraftName);
networkWorker.SendCraftLibraryMessage(mw.GetMessageBytes());
}
deleteCraftName = null;
deleteCraftType = CraftType.VAB;
}
if (displayCraftUploadingMessage && ((Client.realtimeSinceStartup - lastCraftMessageCheck) > CRAFT_MESSAGE_CHECK_INTERVAL))
{
lastCraftMessageCheck = Client.realtimeSinceStartup;
if (craftUploadMessage != null)
{
craftUploadMessage.duration = 0f;
}
if (finishedUploadingCraft)
{
displayCraftUploadingMessage = false;
craftUploadMessage = ScreenMessages.PostScreenMessage("Craft uploaded!", 2f, ScreenMessageStyle.UPPER_CENTER);
}
else
{
craftUploadMessage = ScreenMessages.PostScreenMessage("Uploading craft...", 1f, ScreenMessageStyle.UPPER_CENTER);
}
}
}
}
private void UploadCraftFile(CraftType type, string name)
{
string uploadPath = "";
switch (uploadCraftType)
{
case CraftType.VAB:
uploadPath = vabPath;
break;
case CraftType.SPH:
uploadPath = sphPath;
break;
case CraftType.SUBASSEMBLY:
uploadPath = subassemblyPath;
break;
default:
break;
}
string filePath = Path.Combine(uploadPath, name + ".craft");
if (File.Exists(filePath))
{
byte[] fileData = File.ReadAllBytes(filePath);
using (MessageWriter mw = new MessageWriter())
{
mw.Write<int>((int)CraftMessageType.UPLOAD_FILE);
mw.Write<string>(dmpSettings.playerName);
mw.Write<int>((int)type);
mw.Write<string>(name);
mw.Write<byte[]>(fileData);
networkWorker.SendCraftLibraryMessage(mw.GetMessageBytes());
AddCraftEntry(dmpSettings.playerName, uploadCraftType, uploadCraftName);
displayCraftUploadingMessage = true;
}
}
else
{
DarkLog.Debug("Cannot upload file, " + filePath + " does not exist!");
}
}
private void DownloadCraftFile(string playerName, CraftType craftType, string craftName)
{
using (MessageWriter mw = new MessageWriter())
{
mw.Write<int>((int)CraftMessageType.REQUEST_FILE);
mw.Write<string>(dmpSettings.playerName);
mw.Write<string>(playerName);
mw.Write<int>((int)craftType);
mw.Write<string>(craftName);
networkWorker.SendCraftLibraryMessage(mw.GetMessageBytes());
}
}
private void AddCraftEntry(string playerName, CraftType craftType, string craftName)
{
if (!playersWithCrafts.Contains(playerName))
{
playersWithCrafts.Add(playerName);
}
if (!playerList.ContainsKey(playerName))
{
playerList.Add(playerName, new Dictionary<CraftType, List<string>>());
}
if (!playerList[playerName].ContainsKey(craftType))
{
playerList[playerName].Add(craftType, new List<string>());
}
if (!playerList[playerName][craftType].Contains(craftName))
{
DarkLog.Debug("Adding " + craftName + ", type: " + craftType.ToString() + " from " + playerName);
playerList[playerName][craftType].Add(craftName);
}
}
private void DeleteCraftEntry(string playerName, CraftType craftType, string craftName)
{
if (playerList.ContainsKey(playerName))
{
if (playerList[playerName].ContainsKey(craftType))
{
if (playerList[playerName][craftType].Contains(craftName))
{
playerList[playerName][craftType].Remove(craftName);
if (playerList[playerName][craftType].Count == 0)
{
playerList[playerName].Remove(craftType);
}
if (playerList[playerName].Count == 0)
{
if (playerName != dmpSettings.playerName)
{
playerList.Remove(playerName);
if (playersWithCrafts.Contains(playerName))
{
playersWithCrafts.Remove(playerName);
}
}
}
}
else
{
DarkLog.Debug("Cannot remove craft entry " + craftName + " for player " + playerName + ", craft does not exist");
}
}
else
{
DarkLog.Debug("Cannot remove craft entry " + craftName + " for player " + playerName + ", player does not have any " + craftType + " entries");
}
}
else
{
DarkLog.Debug("Cannot remove craft entry " + craftName + " for player " + playerName + ", no player entry");
}
}
private void SaveCraftFile(CraftType craftType, string craftName, byte[] craftData)
{
string savePath = "";
switch (craftType)
{
case CraftType.VAB:
savePath = vabPath;
break;
case CraftType.SPH:
savePath = sphPath;
break;
case CraftType.SUBASSEMBLY:
savePath = subassemblyPath;
break;
default:
break;
}
if (!Directory.Exists(savePath))
{
Directory.CreateDirectory(savePath);
}
string craftFile = Path.Combine(savePath, craftName + ".craft");
File.WriteAllBytes(craftFile, craftData);
ScreenMessages.PostScreenMessage("Craft " + craftName + " saved!", 5f, ScreenMessageStyle.UPPER_CENTER);
}
private void InitGUI()
{
//Setup GUI stuff
//left 50, middle height
playerWindowRect = new Rect(50, (Screen.height / 2f) - (PLAYER_WINDOW_HEIGHT / 2f), PLAYER_WINDOW_WIDTH, PLAYER_WINDOW_HEIGHT);
//middle of the screen
libraryWindowRect = new Rect((Screen.width / 2f) - (LIBRARY_WINDOW_WIDTH / 2f), (Screen.height / 2f) - (LIBRARY_WINDOW_HEIGHT / 2f), LIBRARY_WINDOW_WIDTH, LIBRARY_WINDOW_HEIGHT);
moveRect = new Rect(0, 0, 10000, 20);
playerLayoutOptions = new GUILayoutOption[4];
playerLayoutOptions[0] = GUILayout.MinWidth(PLAYER_WINDOW_WIDTH);
playerLayoutOptions[1] = GUILayout.MaxWidth(PLAYER_WINDOW_WIDTH);
playerLayoutOptions[2] = GUILayout.MinHeight(PLAYER_WINDOW_HEIGHT);
playerLayoutOptions[3] = GUILayout.MaxHeight(PLAYER_WINDOW_HEIGHT);
libraryLayoutOptions = new GUILayoutOption[4];
libraryLayoutOptions[0] = GUILayout.MinWidth(LIBRARY_WINDOW_WIDTH);
libraryLayoutOptions[1] = GUILayout.MaxWidth(LIBRARY_WINDOW_WIDTH);
libraryLayoutOptions[2] = GUILayout.MinHeight(LIBRARY_WINDOW_HEIGHT);
libraryLayoutOptions[3] = GUILayout.MaxHeight(LIBRARY_WINDOW_HEIGHT);
windowStyle = new GUIStyle(GUI.skin.window);
buttonStyle = new GUIStyle(GUI.skin.button);
labelStyle = new GUIStyle(GUI.skin.label);
scrollStyle = new GUIStyle(GUI.skin.scrollView);
textAreaOptions = new GUILayoutOption[2];
textAreaOptions[0] = GUILayout.ExpandWidth(false);
textAreaOptions[1] = GUILayout.ExpandWidth(false);
}
public void Draw()
{
if (safeDisplay)
{
if (!initialized)
{
initialized = true;
InitGUI();
}
playerWindowRect = DMPGuiUtil.PreventOffscreenWindow(GUILayout.Window(6707 + Client.WINDOW_OFFSET, playerWindowRect, DrawPlayerContent, "DarkMultiPlayer - Craft Library", windowStyle, playerLayoutOptions));
}
if (safeDisplay && selectedPlayer != null)
{
//Sanity check
if (playersWithCrafts.Contains(selectedPlayer) || selectedPlayer == dmpSettings.playerName)
{
libraryWindowRect = DMPGuiUtil.PreventOffscreenWindow(GUILayout.Window(6708 + Client.WINDOW_OFFSET, libraryWindowRect, DrawLibraryContent, "DarkMultiPlayer - " + selectedPlayer + " Craft Library", windowStyle, libraryLayoutOptions));
}
else
{
selectedPlayer = null;
}
}
CheckWindowLock();
}
private void DrawPlayerContent(int windowID)
{
GUILayout.BeginVertical();
GUI.DragWindow(moveRect);
//Draw the player buttons
playerScrollPos = GUILayout.BeginScrollView(playerScrollPos, scrollStyle);
DrawPlayerButton(dmpSettings.playerName);
foreach (string playerName in playersWithCrafts)
{
if (playerName != dmpSettings.playerName)
{
DrawPlayerButton(playerName);
}
}
GUILayout.EndScrollView();
GUILayout.EndVertical();
}
private void DrawPlayerButton(string playerName)
{
bool buttonSelected = GUILayout.Toggle(selectedPlayer == playerName, playerName, buttonStyle);
if (buttonSelected && selectedPlayer != playerName)
{
//Select
selectedPlayer = playerName;
}
if (!buttonSelected && selectedPlayer == playerName)
{
//Unselect
selectedPlayer = null;
}
}
private void DrawLibraryContent(int windowID)
{
GUILayout.BeginVertical();
GUI.DragWindow(moveRect);
bool newShowUpload = false;
if (selectedPlayer == dmpSettings.playerName)
{
newShowUpload = GUILayout.Toggle(showUpload, "Upload", buttonStyle);
}
if (newShowUpload && !showUpload)
{
//Build list when the upload button is pressed.
BuildUploadList();
}
showUpload = newShowUpload;
libraryScrollPos = GUILayout.BeginScrollView(libraryScrollPos, scrollStyle);
if (showUpload)
{
//Draw upload screen
DrawUploadScreen();
}
else
{
//Draw download screen
DrawDownloadScreen();
}
GUILayout.EndScrollView();
GUILayout.EndVertical();
}
private void CheckWindowLock()
{
if (!dmpGame.running)
{
RemoveWindowLock();
return;
}
if (HighLogic.LoadedSceneIsFlight)
{
RemoveWindowLock();
return;
}
if (safeDisplay)
{
Vector2 mousePos = Input.mousePosition;
mousePos.y = Screen.height - mousePos.y;
bool shouldLock = (playerWindowRect.Contains(mousePos) || libraryWindowRect.Contains(mousePos));
if (shouldLock && !isWindowLocked)
{
InputLockManager.SetControlLock(ControlTypes.ALLBUTCAMERAS, "DMP_CraftLock");
isWindowLocked = true;
}
if (!shouldLock && isWindowLocked)
{
RemoveWindowLock();
}
}
if (!safeDisplay && isWindowLocked)
{
RemoveWindowLock();
}
}
private void RemoveWindowLock()
{
if (isWindowLocked)
{
isWindowLocked = false;
InputLockManager.RemoveControlLock("DMP_CraftLock");
}
}
private void DrawUploadScreen()
{
foreach (KeyValuePair<CraftType, List<string>> entryType in uploadList)
{
GUILayout.Label(entryType.Key.ToString(), labelStyle);
foreach (string entryName in entryType.Value)
{
if (playerList.ContainsKey(dmpSettings.playerName))
{
if (playerList[dmpSettings.playerName].ContainsKey(entryType.Key))
{
GUI.enabled &= !playerList[dmpSettings.playerName][entryType.Key].Contains(entryName);
}
}
if (GUILayout.Button(entryName, buttonStyle))
{
uploadCraftType = entryType.Key;
uploadCraftName = entryName;
}
GUI.enabled = true;
}
}
}
private void BuildUploadList()
{
uploadList = new Dictionary<CraftType, List<string>>();
if (Directory.Exists(vabPath))
{
uploadList.Add(CraftType.VAB, new List<string>());
string[] craftFiles = Directory.GetFiles(vabPath);
foreach (string craftFile in craftFiles)
{
string craftName = Path.GetFileNameWithoutExtension(craftFile);
uploadList[CraftType.VAB].Add(craftName);
}
}
if (Directory.Exists(sphPath))
{
uploadList.Add(CraftType.SPH, new List<string>());
string[] craftFiles = Directory.GetFiles(sphPath);
foreach (string craftFile in craftFiles)
{
string craftName = Path.GetFileNameWithoutExtension(craftFile);
uploadList[CraftType.SPH].Add(craftName);
}
}
if (Directory.Exists(vabPath))
{
uploadList.Add(CraftType.SUBASSEMBLY, new List<string>());
string[] craftFiles = Directory.GetFiles(subassemblyPath);
foreach (string craftFile in craftFiles)
{
string craftName = Path.GetFileNameWithoutExtension(craftFile);
uploadList[CraftType.SUBASSEMBLY].Add(craftName);
}
}
}
private void DrawDownloadScreen()
{
if (playerList.ContainsKey(selectedPlayer))
{
foreach (KeyValuePair<CraftType, List<string>> entry in playerList[selectedPlayer])
{
GUILayout.Label(entry.Key.ToString(), labelStyle);
foreach (string craftName in entry.Value)
{
if (selectedPlayer == dmpSettings.playerName)
{
//Also draw remove button on player screen
GUILayout.BeginHorizontal();
if (GUILayout.Button(craftName, buttonStyle))
{
downloadCraftType = entry.Key;
downloadCraftName = craftName;
}
if (GUILayout.Button("Remove", buttonStyle))
{
deleteCraftType = entry.Key;
deleteCraftName = craftName;
}
GUILayout.EndHorizontal();
}
else
{
if (GUILayout.Button(craftName, buttonStyle))
{
downloadCraftType = entry.Key;
downloadCraftName = craftName;
}
}
}
}
}
}
public void QueueCraftAdd(CraftChangeEntry entry)
{
craftAddQueue.Enqueue(entry);
}
public void QueueCraftDelete(CraftChangeEntry entry)
{
craftDeleteQueue.Enqueue(entry);
}
public void QueueCraftResponse(CraftResponseEntry entry)
{
craftResponseQueue.Enqueue(entry);
}
public void Stop()
{
workerEnabled = false;
RemoveWindowLock();
dmpGame.updateEvent.Remove(updateAction);
dmpGame.drawEvent.Remove(drawAction);
}
}
}
public class CraftChangeEntry
{
public string playerName;
public CraftType craftType;
public string craftName;
}
public class CraftResponseEntry
{
public string playerName;
public CraftType craftType;
public string craftName;
public byte[] craftData;
}
| |
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Athene.Inventory.Web.Services;
using Athene.Inventory.Web.Models;
using Athene.Inventory.Web.Models.ManageViewModels;
namespace Athene.Inventory.Web.Controllers
{
[Authorize(Roles="Administrator")]
public class ManageController : Controller
{
private readonly UserManager<User> _userManager;
private readonly SignInManager<User> _signInManager;
private readonly IEmailSender _emailSender;
private readonly ISmsSender _smsSender;
private readonly ILogger _logger;
public ManageController(
UserManager<User> userManager,
SignInManager<User> signInManager,
IEmailSender emailSender,
ISmsSender smsSender,
ILoggerFactory loggerFactory)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
_smsSender = smsSender;
_logger = loggerFactory.CreateLogger<ManageController>();
}
//
// GET: /Manage/Index
[HttpGet]
public async Task<IActionResult> Index(ManageMessageId? message = null)
{
ViewData["StatusMessage"] =
message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
: message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
: message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set."
: message == ManageMessageId.Error ? "An error has occurred."
: message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added."
: message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
: "";
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var model = new IndexViewModel
{
HasPassword = await _userManager.HasPasswordAsync(user),
PhoneNumber = await _userManager.GetPhoneNumberAsync(user),
TwoFactor = await _userManager.GetTwoFactorEnabledAsync(user),
Logins = await _userManager.GetLoginsAsync(user),
BrowserRemembered = await _signInManager.IsTwoFactorClientRememberedAsync(user)
};
return View(model);
}
//
// POST: /Manage/RemoveLogin
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemoveLogin(RemoveLoginViewModel account)
{
ManageMessageId? message = ManageMessageId.Error;
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.RemoveLoginAsync(user, account.LoginProvider, account.ProviderKey);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
message = ManageMessageId.RemoveLoginSuccess;
}
}
return RedirectToAction(nameof(ManageLogins), new { Message = message });
}
//
// GET: /Manage/AddPhoneNumber
public IActionResult AddPhoneNumber()
{
return View();
}
//
// POST: /Manage/AddPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddPhoneNumber(AddPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// Generate the token and send it
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, model.PhoneNumber);
await _smsSender.SendSmsAsync(model.PhoneNumber, "Your security code is: " + code);
return RedirectToAction(nameof(VerifyPhoneNumber), new { model.PhoneNumber });
}
//
// POST: /Manage/EnableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EnableTwoFactorAuthentication()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
await _userManager.SetTwoFactorEnabledAsync(user, true);
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(1, "User enabled two-factor authentication.");
}
return RedirectToAction(nameof(Index), "Manage");
}
//
// POST: /Manage/DisableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DisableTwoFactorAuthentication()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
await _userManager.SetTwoFactorEnabledAsync(user, false);
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(2, "User disabled two-factor authentication.");
}
return RedirectToAction(nameof(Index), "Manage");
}
//
// GET: /Manage/VerifyPhoneNumber
[HttpGet]
public async Task<IActionResult> VerifyPhoneNumber(string phoneNumber)
{
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, phoneNumber);
// Send an SMS to verify the phone number
return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber });
}
//
// POST: /Manage/VerifyPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.ChangePhoneNumberAsync(user, model.PhoneNumber, model.Code);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.AddPhoneSuccess });
}
}
// If we got this far, something failed, redisplay the form
ModelState.AddModelError(string.Empty, "Failed to verify phone number");
return View(model);
}
//
// POST: /Manage/RemovePhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemovePhoneNumber()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.SetPhoneNumberAsync(user, null);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.RemovePhoneSuccess });
}
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//
// GET: /Manage/ChangePassword
[HttpGet]
public IActionResult ChangePassword()
{
return View();
}
//
// POST: /Manage/ChangePassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(3, "User changed their password successfully.");
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.ChangePasswordSuccess });
}
AddErrors(result);
return View(model);
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//
// GET: /Manage/SetPassword
[HttpGet]
public IActionResult SetPassword()
{
return View();
}
//
// POST: /Manage/SetPassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SetPassword(SetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.AddPasswordAsync(user, model.NewPassword);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.SetPasswordSuccess });
}
AddErrors(result);
return View(model);
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//GET: /Manage/ManageLogins
[HttpGet]
public async Task<IActionResult> ManageLogins(ManageMessageId? message = null)
{
ViewData["StatusMessage"] =
message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
: message == ManageMessageId.AddLoginSuccess ? "The external login was added."
: message == ManageMessageId.Error ? "An error has occurred."
: "";
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var userLogins = await _userManager.GetLoginsAsync(user);
var externalAuth = await _signInManager.GetExternalAuthenticationSchemesAsync();
var otherLogins = externalAuth
.Where(auth => userLogins.All(ul => auth.Name != ul.LoginProvider))
.ToList();
ViewData["ShowRemoveButton"] = user.PasswordHash != null || userLogins.Count > 1;
return View(new ManageLoginsViewModel
{
CurrentLogins = userLogins,
OtherLogins = otherLogins
});
}
//
// POST: /Manage/LinkLogin
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult LinkLogin(string provider)
{
// Request a redirect to the external login provider to link a login for the current user
var redirectUrl = Url.Action("LinkLoginCallback", "Manage");
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, _userManager.GetUserId(User));
return Challenge(properties, provider);
}
//
// GET: /Manage/LinkLoginCallback
[HttpGet]
public async Task<ActionResult> LinkLoginCallback()
{
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var info = await _signInManager.GetExternalLoginInfoAsync(await _userManager.GetUserIdAsync(user));
if (info == null)
{
return RedirectToAction(nameof(ManageLogins), new { Message = ManageMessageId.Error });
}
var result = await _userManager.AddLoginAsync(user, info);
var message = result.Succeeded ? ManageMessageId.AddLoginSuccess : ManageMessageId.Error;
return RedirectToAction(nameof(ManageLogins), new { Message = message });
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
public enum ManageMessageId
{
AddPhoneSuccess,
AddLoginSuccess,
ChangePasswordSuccess,
SetTwoFactorSuccess,
SetPasswordSuccess,
RemoveLoginSuccess,
RemovePhoneSuccess,
Error
}
private Task<User> GetCurrentUserAsync()
{
return _userManager.GetUserAsync(HttpContext.User);
}
#endregion
}
}
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2.1
* Contact: devcenter@docusign.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter;
namespace DocuSign.eSign.Model
{
/// <summary>
/// PrefillTabs
/// </summary>
[DataContract]
public partial class PrefillTabs : IEquatable<PrefillTabs>, IValidatableObject
{
public PrefillTabs()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="PrefillTabs" /> class.
/// </summary>
/// <param name="CheckboxTabs">Specifies a tag on the document in a location where the recipient can select an option..</param>
/// <param name="RadioGroupTabs">Specifies a tag on the document in a location where the recipient can select one option from a group of options using a radio button. The radio buttons do not have to be on the same page in a document..</param>
/// <param name="SenderCompanyTabs">SenderCompanyTabs.</param>
/// <param name="SenderNameTabs">SenderNameTabs.</param>
/// <param name="TabGroups">TabGroups.</param>
/// <param name="TextTabs">Specifies a that that is an adaptable field that allows the recipient to enter different text information. When getting information that includes this tab type, the original value of the tab when the associated envelope was sent is included in the response..</param>
public PrefillTabs(List<Checkbox> CheckboxTabs = default(List<Checkbox>), List<RadioGroup> RadioGroupTabs = default(List<RadioGroup>), List<SenderCompany> SenderCompanyTabs = default(List<SenderCompany>), List<SenderName> SenderNameTabs = default(List<SenderName>), List<TabGroup> TabGroups = default(List<TabGroup>), List<Text> TextTabs = default(List<Text>))
{
this.CheckboxTabs = CheckboxTabs;
this.RadioGroupTabs = RadioGroupTabs;
this.SenderCompanyTabs = SenderCompanyTabs;
this.SenderNameTabs = SenderNameTabs;
this.TabGroups = TabGroups;
this.TextTabs = TextTabs;
}
/// <summary>
/// Specifies a tag on the document in a location where the recipient can select an option.
/// </summary>
/// <value>Specifies a tag on the document in a location where the recipient can select an option.</value>
[DataMember(Name="checkboxTabs", EmitDefaultValue=false)]
public List<Checkbox> CheckboxTabs { get; set; }
/// <summary>
/// Specifies a tag on the document in a location where the recipient can select one option from a group of options using a radio button. The radio buttons do not have to be on the same page in a document.
/// </summary>
/// <value>Specifies a tag on the document in a location where the recipient can select one option from a group of options using a radio button. The radio buttons do not have to be on the same page in a document.</value>
[DataMember(Name="radioGroupTabs", EmitDefaultValue=false)]
public List<RadioGroup> RadioGroupTabs { get; set; }
/// <summary>
/// Gets or Sets SenderCompanyTabs
/// </summary>
[DataMember(Name="senderCompanyTabs", EmitDefaultValue=false)]
public List<SenderCompany> SenderCompanyTabs { get; set; }
/// <summary>
/// Gets or Sets SenderNameTabs
/// </summary>
[DataMember(Name="senderNameTabs", EmitDefaultValue=false)]
public List<SenderName> SenderNameTabs { get; set; }
/// <summary>
/// Gets or Sets TabGroups
/// </summary>
[DataMember(Name="tabGroups", EmitDefaultValue=false)]
public List<TabGroup> TabGroups { get; set; }
/// <summary>
/// Specifies a that that is an adaptable field that allows the recipient to enter different text information. When getting information that includes this tab type, the original value of the tab when the associated envelope was sent is included in the response.
/// </summary>
/// <value>Specifies a that that is an adaptable field that allows the recipient to enter different text information. When getting information that includes this tab type, the original value of the tab when the associated envelope was sent is included in the response.</value>
[DataMember(Name="textTabs", EmitDefaultValue=false)]
public List<Text> TextTabs { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class PrefillTabs {\n");
sb.Append(" CheckboxTabs: ").Append(CheckboxTabs).Append("\n");
sb.Append(" RadioGroupTabs: ").Append(RadioGroupTabs).Append("\n");
sb.Append(" SenderCompanyTabs: ").Append(SenderCompanyTabs).Append("\n");
sb.Append(" SenderNameTabs: ").Append(SenderNameTabs).Append("\n");
sb.Append(" TabGroups: ").Append(TabGroups).Append("\n");
sb.Append(" TextTabs: ").Append(TextTabs).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as PrefillTabs);
}
/// <summary>
/// Returns true if PrefillTabs instances are equal
/// </summary>
/// <param name="other">Instance of PrefillTabs to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(PrefillTabs other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.CheckboxTabs == other.CheckboxTabs ||
this.CheckboxTabs != null &&
this.CheckboxTabs.SequenceEqual(other.CheckboxTabs)
) &&
(
this.RadioGroupTabs == other.RadioGroupTabs ||
this.RadioGroupTabs != null &&
this.RadioGroupTabs.SequenceEqual(other.RadioGroupTabs)
) &&
(
this.SenderCompanyTabs == other.SenderCompanyTabs ||
this.SenderCompanyTabs != null &&
this.SenderCompanyTabs.SequenceEqual(other.SenderCompanyTabs)
) &&
(
this.SenderNameTabs == other.SenderNameTabs ||
this.SenderNameTabs != null &&
this.SenderNameTabs.SequenceEqual(other.SenderNameTabs)
) &&
(
this.TabGroups == other.TabGroups ||
this.TabGroups != null &&
this.TabGroups.SequenceEqual(other.TabGroups)
) &&
(
this.TextTabs == other.TextTabs ||
this.TextTabs != null &&
this.TextTabs.SequenceEqual(other.TextTabs)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.CheckboxTabs != null)
hash = hash * 59 + this.CheckboxTabs.GetHashCode();
if (this.RadioGroupTabs != null)
hash = hash * 59 + this.RadioGroupTabs.GetHashCode();
if (this.SenderCompanyTabs != null)
hash = hash * 59 + this.SenderCompanyTabs.GetHashCode();
if (this.SenderNameTabs != null)
hash = hash * 59 + this.SenderNameTabs.GetHashCode();
if (this.TabGroups != null)
hash = hash * 59 + this.TabGroups.GetHashCode();
if (this.TextTabs != null)
hash = hash * 59 + this.TextTabs.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
#if ASYNC
using System.Threading.Tasks;
#endif
using System.Collections.Generic;
using System.Linq;
using ZendeskApi_v2.Models.Organizations;
using ZendeskApi_v2.Models.Shared;
namespace ZendeskApi_v2.Requests
{
public interface IOrganizations : ICore
{
#if SYNC
GroupOrganizationResponse GetOrganizations(int? perPage = null, int? page = null);
/// <summary>
/// Returns an array of organizations whose name starts with the value specified in the name parameter. The name must be at least 2 characters in length.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
GroupOrganizationResponse GetOrganizationsStartingWith(string name);
GroupOrganizationResponse SearchForOrganizationsByExternalId(string externalId);
IndividualOrganizationResponse GetOrganization(long id);
IndividualOrganizationResponse CreateOrganization(Organization organization);
IndividualOrganizationResponse UpdateOrganization(Organization organization);
bool DeleteOrganization(long id);
GroupOrganizationMembershipResponse GetOrganizationMemberships(int? perPage = null, int? page = null);
GroupOrganizationMembershipResponse GetOrganizationMembershipsByUserId(long userId, int? perPage = null, int? page = null);
GroupOrganizationMembershipResponse GetOrganizationMembershipsByOrganizationId(long organizationId, int? perPage = null, int? page = null);
IndividualOrganizationMembershipResponse GetOrganizationMembership(long id);
IndividualOrganizationMembershipResponse GetOrganizationMembershipByIdAndUserId(long id, long userid);
IndividualOrganizationMembershipResponse CreateOrganizationMembership(OrganizationMembership organizationMembership);
IndividualOrganizationMembershipResponse CreateOrganizationMembership(long userId, OrganizationMembership organizationMembership);
JobStatusResponse CreateManyOrganizationMemberships(IEnumerable<OrganizationMembership> organizationMemberships);
bool DeleteOrganizationMembership(long id);
bool DeleteOrganizationMembership(long id, long userId);
JobStatusResponse DestroyManyOrganizationMemberships(IEnumerable<long> ids);
GroupOrganizationMembershipResponse SetOrganizationMembershipAsDefault(long id, long userId);
#endif
#if ASYNC
Task<GroupOrganizationResponse> GetOrganizationsAsync(int? perPage = null, int? page = null);
/// <summary>
/// Returns an array of organizations whose name starts with the value specified in the name parameter. The name must be at least 2 characters in length.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
Task<GroupOrganizationResponse> GetOrganizationsStartingWithAsync(string name);
Task<GroupOrganizationResponse> SearchForOrganizationsAsync(string searchTerm);
Task<IndividualOrganizationResponse> GetOrganizationAsync(long id);
Task<IndividualOrganizationResponse> CreateOrganizationAsync(Organization organization);
Task<IndividualOrganizationResponse> UpdateOrganizationAsync(Organization organization);
Task<bool> DeleteOrganizationAsync(long id);
Task<GroupOrganizationMembershipResponse> GetOrganizationMembershipsAsync(int? perPage = null, int? page = null);
Task<GroupOrganizationMembershipResponse> GetOrganizationMembershipsByUserIdAsync(long userId, int? perPage = null, int? page = null);
Task<GroupOrganizationMembershipResponse> GetOrganizationMembershipsByOrganizationIdAsync(long organizationId, int? perPage = null, int? page = null);
Task<IndividualOrganizationMembershipResponse> GetOrganizationMembershipAsync(long id);
Task<IndividualOrganizationMembershipResponse> GetOrganizationMembershipByIdAndUserIdAsync(long id, long userid);
Task<IndividualOrganizationMembershipResponse> CreateOrganizationMembershipAsync(OrganizationMembership organizationMembership);
Task<IndividualOrganizationMembershipResponse> CreateOrganizationMembershipAsync(long userId, OrganizationMembership organizationMembership);
Task<JobStatusResponse> CreateManyOrganizationMembershipsAsync(IEnumerable<OrganizationMembership> organizationMemberships);
Task<bool> DeleteOrganizationMembershipAsync(long id);
Task<bool> DeleteOrganizationMembershipAsync(long id, long userId);
Task<JobStatusResponse> DestroyManyOrganizationMembershipsAsync(IEnumerable<long> ids);
Task<GroupOrganizationMembershipResponse> SetOrganizationMembershipAsDefaultAsync(long id, long userId);
#endif
}
public class Organizations : Core, IOrganizations
{
public Organizations(string yourZendeskUrl, string user, string password, string apiToken, string p_OAuthToken)
: base(yourZendeskUrl, user, password, apiToken, p_OAuthToken)
{
}
#if SYNC
public GroupOrganizationResponse GetOrganizations(int? perPage = null, int? page = null)
{
return GenericPagedGet<GroupOrganizationResponse>("organizations.json", perPage, page);
}
/// <summary>
/// Returns an array of organizations whose name starts with the value specified in the name parameter. The name must be at least 2 characters in length.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public GroupOrganizationResponse GetOrganizationsStartingWith(string name)
{
return GenericPost<GroupOrganizationResponse>(string.Format("organizations/autocomplete.json?name={0}", name));
}
public GroupOrganizationResponse SearchForOrganizationsByExternalId(string externalId)
{
return GenericGet<GroupOrganizationResponse>(string.Format("organizations/search.json?external_id={0}", externalId));
}
public IndividualOrganizationResponse GetOrganization(long id)
{
return GenericGet<IndividualOrganizationResponse>(string.Format("organizations/{0}.json", id));
}
public IndividualOrganizationResponse CreateOrganization(Organization organization)
{
var body = new {organization};
return GenericPost<IndividualOrganizationResponse>("organizations.json", body);
}
public IndividualOrganizationResponse UpdateOrganization(Organization organization)
{
var body = new { organization };
return GenericPut<IndividualOrganizationResponse>(string.Format("organizations/{0}.json", organization.Id), body);
}
public bool DeleteOrganization(long id)
{
return GenericDelete(string.Format("organizations/{0}.json", id));
}
public GroupOrganizationMembershipResponse GetOrganizationMemberships(int? perPage = null, int? page = null)
{
return GenericPagedGet<GroupOrganizationMembershipResponse>("organization_memberships.json", perPage, page);
}
public GroupOrganizationMembershipResponse GetOrganizationMembershipsByUserId(long userId, int? perPage = null, int? page = null)
{
return GenericPagedGet<GroupOrganizationMembershipResponse>(string.Format("users/{0}/organization_memberships.json", userId), perPage, page);
}
public GroupOrganizationMembershipResponse GetOrganizationMembershipsByOrganizationId(long organizationId, int? perPage = null, int? page = null)
{
return GenericPagedGet<GroupOrganizationMembershipResponse>(string.Format("organizations/{0}/organization_memberships.json", organizationId), perPage, page);
}
public IndividualOrganizationMembershipResponse GetOrganizationMembership(long id)
{
return GenericGet<IndividualOrganizationMembershipResponse>(string.Format("organization_memberships/{0}.json", id));
}
public IndividualOrganizationMembershipResponse GetOrganizationMembershipByIdAndUserId(long id, long userid)
{
return GenericGet<IndividualOrganizationMembershipResponse>(string.Format("users/{0}/organizations/organization_memberships/{1}.json", userid, id));
}
public IndividualOrganizationMembershipResponse CreateOrganizationMembership(OrganizationMembership organization_membership)
{
var body = new { organization_membership };
return GenericPost<IndividualOrganizationMembershipResponse>("organization_memberships.json", body);
}
public IndividualOrganizationMembershipResponse CreateOrganizationMembership(long userId, OrganizationMembership organization_membership)
{
var body = new { organization_membership };
return GenericPost<IndividualOrganizationMembershipResponse>(string.Format("users/{0}/organization_memberships.json", userId), body);
}
public JobStatusResponse CreateManyOrganizationMemberships(IEnumerable<OrganizationMembership> organization_memberships)
{
var body = new { organization_memberships };
return GenericPost<JobStatusResponse>("organization_memberships/create_many.json", body);
}
public bool DeleteOrganizationMembership(long id)
{
return GenericDelete(string.Format("organization_memberships/{0}.json", id));
}
public bool DeleteOrganizationMembership(long id, long userId)
{
return GenericDelete(string.Format("users/{0}/organization_memberships/{1}.json", userId, id));
}
public JobStatusResponse DestroyManyOrganizationMemberships(IEnumerable<long> ids)
{
string idList = string.Join(",", ids.Select(i => i.ToString()).ToArray());
return GenericDelete<JobStatusResponse>(string.Format("organization_memberships/destroy_many.json?ids={0}", idList));
}
public GroupOrganizationMembershipResponse SetOrganizationMembershipAsDefault(long id, long userId)
{
return GenericPut<GroupOrganizationMembershipResponse>(string.Format("users/{0}/organization_memberships/{1}/make_default.json", userId, id));
}
#endif
#if ASYNC
public async Task<GroupOrganizationResponse> GetOrganizationsAsync(int? perPage = null, int? page = null)
{
return await GenericPagedGetAsync<GroupOrganizationResponse>("organizations.json", perPage, page);
}
/// <summary>
/// Returns an array of organizations whose name starts with the value specified in the name parameter. The name must be at least 2 characters in length.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public async Task<GroupOrganizationResponse> GetOrganizationsStartingWithAsync(string name)
{
return await GenericPostAsync<GroupOrganizationResponse>(string.Format("organizations/autocomplete.json?name={0}", name));
}
public async Task<GroupOrganizationResponse> SearchForOrganizationsAsync(string searchTerm)
{
return await GenericPostAsync<GroupOrganizationResponse>(string.Format("organizations/autocomplete.json?external_id={0}", searchTerm));
}
public async Task<IndividualOrganizationResponse> GetOrganizationAsync(long id)
{
return await GenericGetAsync<IndividualOrganizationResponse>(string.Format("organizations/{0}.json", id));
}
public async Task<IndividualOrganizationResponse> CreateOrganizationAsync(Organization organization)
{
var body = new {organization};
return await GenericPostAsync<IndividualOrganizationResponse>("organizations.json", body);
}
public async Task<IndividualOrganizationResponse> UpdateOrganizationAsync(Organization organization)
{
var body = new { organization };
return await GenericPutAsync<IndividualOrganizationResponse>(string.Format("organizations/{0}.json", organization.Id), body);
}
public async Task<bool> DeleteOrganizationAsync(long id)
{
return await GenericDeleteAsync(string.Format("organizations/{0}.json", id));
}
public async Task<GroupOrganizationMembershipResponse> GetOrganizationMembershipsAsync(int? perPage = null, int? page = null)
{
return await GenericPagedGetAsync<GroupOrganizationMembershipResponse>("organization_memberships.json", perPage, page);
}
public async Task<GroupOrganizationMembershipResponse> GetOrganizationMembershipsByUserIdAsync(long userId, int? perPage = null, int? page = null)
{
return await GenericPagedGetAsync<GroupOrganizationMembershipResponse>(string.Format("users/{0}/organization_memberships.json", userId), perPage, page);
}
public async Task<GroupOrganizationMembershipResponse> GetOrganizationMembershipsByOrganizationIdAsync(long organizationId, int? perPage = null, int? page = null)
{
return await GenericPagedGetAsync<GroupOrganizationMembershipResponse>(string.Format("organizations/{0}/organization_memberships.json", organizationId), perPage, page);
}
public async Task<IndividualOrganizationMembershipResponse> GetOrganizationMembershipAsync(long id)
{
return await GenericGetAsync<IndividualOrganizationMembershipResponse>(string.Format("organization_memberships/{0}.json", id));
}
public async Task<IndividualOrganizationMembershipResponse> GetOrganizationMembershipByIdAndUserIdAsync(long id, long userid)
{
return await GenericGetAsync<IndividualOrganizationMembershipResponse>(string.Format("users/{0}/organizations/organization_memberships/{1}.json", userid, id));
}
public async Task<IndividualOrganizationMembershipResponse> CreateOrganizationMembershipAsync(OrganizationMembership organization_membership)
{
var body = new { organization_membership };
return await GenericPostAsync<IndividualOrganizationMembershipResponse>("organization_memberships.json", body);
}
public async Task<IndividualOrganizationMembershipResponse> CreateOrganizationMembershipAsync(long userId, OrganizationMembership organization_membership)
{
var body = new { organization_membership };
return await GenericPostAsync<IndividualOrganizationMembershipResponse>(string.Format("users/{0}/organization_memberships.json", userId), body);
}
public async Task<JobStatusResponse> CreateManyOrganizationMembershipsAsync(IEnumerable<OrganizationMembership> organization_memberships)
{
var body = new { organization_memberships };
return await GenericPostAsync<JobStatusResponse>("organization_memberships/create_many.json", body);
}
public async Task<bool> DeleteOrganizationMembershipAsync(long id)
{
return await GenericDeleteAsync(string.Format("organization_memberships/{0}.json", id));
}
public async Task<bool> DeleteOrganizationMembershipAsync(long id, long userId)
{
return await GenericDeleteAsync(string.Format("users/{0}/organization_memberships/{1}.json", userId, id));
}
public async Task<JobStatusResponse> DestroyManyOrganizationMembershipsAsync(IEnumerable<long> ids)
{
string idList = string.Join(",", ids.Select(i => i.ToString()).ToArray());
return await GenericDeleteAsync<JobStatusResponse>(string.Format("organization_memberships/destroy_many.json?ids={0}", idList));
}
public async Task<GroupOrganizationMembershipResponse> SetOrganizationMembershipAsDefaultAsync(long id, long userId)
{
return await GenericPutAsync<GroupOrganizationMembershipResponse>(string.Format("users/{0}/organization_memberships/{1}/make_default.json", userId, id));
}
#endif
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Serialization.dll
// Description: A module that supports common functions like serialization.
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Darrel Brown. Created 9/10/2009
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
// |-----------------|---------|---------------------------------------------------------------------
// | Name | Date | Comments
// |-----------------|---------|----------------------------------------------------------------------
//
// ********************************************************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace DotSpatial.Serialization
{
/// <summary>
/// This class stores the reflected data required for serialization.
/// </summary>
public class SerializationMap
{
private static readonly Dictionary<Type, SerializationMap> _typeToSerializationMap = new Dictionary<Type, SerializationMap>();
private readonly List<SerializationMapEntry> _memberInfos = new List<SerializationMapEntry>();
/// <summary>
/// The static constructor creates a dictionary that maps an object type to a specific SerializationMap instance.
/// </summary>
static SerializationMap()
{
var mapTypes = ReflectionHelper.FindDerivedClasses(typeof(SerializationMap));
foreach (var type in mapTypes)
{
SerializationMap mapInstance;
try
{
mapInstance = (SerializationMap)type.Assembly.CreateInstance(type.FullName);
}
catch
{
continue;
}
if (mapInstance != null)
_typeToSerializationMap[mapInstance.ForType] = mapInstance;
}
}
/// <summary>
/// Creates a new instance of the SerializationMap class.
/// </summary>
/// <param name="forType">The type associated with this SerializationMap.</param>
protected SerializationMap(Type forType)
{
ForType = forType;
FindSerializableMembers(forType);
// Update the mapping dictionary
_typeToSerializationMap[forType] = this;
}
/// <summary>
/// The type that this serialization map instance is associated with.
/// </summary>
public Type ForType { get; private set; }
/// <summary>
/// The members that participate in serialization.
/// </summary>
public List<SerializationMapEntry> Members
{
get { return _memberInfos; }
}
/// <summary>
/// This overload is used for objects that are marked with the <see cref="SerializeAttribute"/>.
/// </summary>
/// <param name="type">The type to generate a <c>SerializationMap</c> for.</param>
/// <returns>A new serialization map that can be used to serialize the given type.</returns>
public static SerializationMap FromType(Type type)
{
var cachedMap = GetCachedSerializationMap(type);
if (cachedMap != null)
return cachedMap;
return new SerializationMap(type);
}
private static SerializationMap GetCachedSerializationMap(Type type)
{
// Try to find a cached instance first
if (_typeToSerializationMap.ContainsKey(type))
return _typeToSerializationMap[type];
return null;
}
/// <summary>
/// The forward method that will serialize a property or field with the specified name.
/// The name does not have to be the same as the name of the member.
/// </summary>
/// <param name="memberInfo">The property or field information to serialize</param>
/// <param name="name">The name to remove</param>
/// <returns>The Serialization Map Entry created by the serialize method</returns>
protected SerializationMapEntry Serialize(MemberInfo memberInfo, string name)
{
SerializationMapEntry result = new SerializationMapEntry(memberInfo, new SerializeAttribute(name));
_memberInfos.Add(result);
return result;
}
private void FindSerializableMembers(Type type)
{
FindPrivateSerializableMembers(type);
FindPublicSerializableMemebers(type);
}
private void FindSerializableProperties(Type type, BindingFlags bindingFlags)
{
AddSerializableMembers(type.GetProperties(bindingFlags));
}
private void FindSerializableFields(Type type, BindingFlags bindingFlags)
{
AddSerializableMembers(type.GetFields(bindingFlags).Where(fi => (!fi.IsInitOnly || FieldIsConstructorArgument(fi))).Cast<MemberInfo>());
}
private static bool FieldIsConstructorArgument(FieldInfo fi)
{
foreach (var fieldAttribute in fi.GetCustomAttributes(typeof(SerializeAttribute), true))
{
var sa = (SerializeAttribute) fieldAttribute;
return sa.ConstructorArgumentIndex >= 0;
}
return false;
}
private void AddSerializableMembers(IEnumerable<MemberInfo> members)
{
foreach (var memberInfo in members)
{
var attribute = memberInfo.GetCustomAttributes(typeof(SerializeAttribute), true).Cast<SerializeAttribute>().FirstOrDefault();
MemberInfo info = memberInfo;
if (attribute != null &&
!_memberInfos.Any(mi => mi.Member.Name == info.Name &&
mi.Member.DeclaringType == info.DeclaringType &&
mi.Member.MemberType == info.MemberType))
{
_memberInfos.Add(new SerializationMapEntry(memberInfo, attribute));
}
}
}
private void FindPrivateSerializableMembers(Type type)
{
Type baseType = type.BaseType;
Stack<Type> typesToSerialize = new Stack<Type>();
typesToSerialize.Push(type);
while (baseType != null && !baseType.Equals(typeof(object)))
{
typesToSerialize.Push(baseType);
baseType = baseType.BaseType;
}
while (typesToSerialize.Count > 0)
{
type = typesToSerialize.Pop();
FindSerializableFields(type, BindingFlags.Instance | BindingFlags.NonPublic);
FindSerializableProperties(type, BindingFlags.Instance | BindingFlags.NonPublic);
}
}
private void FindPublicSerializableMemebers(Type type)
{
FindSerializableFields(type, BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy);
FindSerializableProperties(type, BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy);
}
}
///// <summary>
///// Generic type used to make creating custom mappings a little bit easier.
///// </summary>
///// <typeparam name="T">The type that this map will be associated with.</typeparam>
//public class SerializationMap<T> : SerializationMap
//{
// /// <summary>
// /// Constructs a new instance of the generic SerializationMap class
// /// </summary>
// protected SerializationMap() : base(typeof(T))
// {
// }
// /// <summary>
// /// Specifies that a field or property should be serialize
// /// </summary>
// /// <param name="expression">An expression that will yield a <see cref="MemberInfo"/>.</param>
// /// <param name="name">The name to use when serializing this member.</param>
// /// <returns>A <see cref="SerializationMapEntry"/> representing the member specified by <paramref name="expression"/>.</returns>
// protected SerializationMapEntry Serialize(Expression<Func<T, object>> expression, string name)
// {
// MemberExpression memberExpression = null;
// if (expression.Body.NodeType == ExpressionType.Convert)
// {
// memberExpression = ((UnaryExpression)expression.Body).Operand as MemberExpression;
// }
// else if (expression.Body.NodeType == ExpressionType.MemberAccess)
// {
// memberExpression = expression.Body as MemberExpression;
// }
// if (memberExpression == null)
// throw new ArgumentException("This type of expression not supported.", "expression");
// MemberInfo memberInfo = memberExpression.Member;
// Debug.Assert(memberInfo != null);
// // Replace an entry if the specified member has already been mapped one way or another.
// SerializeAttribute attribute = memberInfo.GetCustomAttributes(typeof(SerializeAttribute), true).
// Cast<SerializeAttribute>().
// FirstOrDefault();
// if (attribute != null)
// Members.RemoveAll(m => m.Member.Equals(memberInfo));
// SerializationMapEntry result = new SerializationMapEntry(memberInfo, new SerializeAttribute(name));
// Members.Add(result);
// return result;
// }
//}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace MS.Internal.Xml.XPath
{
using System;
using Microsoft.Xml;
using Microsoft.Xml.XPath;
using System.Diagnostics;
using System.Globalization;
using Microsoft.Xml.Xsl;
internal sealed class LogicalExpr : ValueQuery
{
private Operator.Op _op;
private Query _opnd1;
private Query _opnd2;
public LogicalExpr(Operator.Op op, Query opnd1, Query opnd2)
{
Debug.Assert(
Operator.Op.LT == op || Operator.Op.GT == op ||
Operator.Op.LE == op || Operator.Op.GE == op ||
Operator.Op.EQ == op || Operator.Op.NE == op
);
_op = op;
_opnd1 = opnd1;
_opnd2 = opnd2;
}
private LogicalExpr(LogicalExpr other) : base(other)
{
_op = other._op;
_opnd1 = Clone(other._opnd1);
_opnd2 = Clone(other._opnd2);
}
public override void SetXsltContext(XsltContext context)
{
_opnd1.SetXsltContext(context);
_opnd2.SetXsltContext(context);
}
public override object Evaluate(XPathNodeIterator nodeIterator)
{
Operator.Op op = _op;
object val1 = _opnd1.Evaluate(nodeIterator);
object val2 = _opnd2.Evaluate(nodeIterator);
int type1 = (int)GetXPathType(val1);
int type2 = (int)GetXPathType(val2);
if (type1 < type2)
{
op = Operator.InvertOperator(op);
object valTemp = val1;
val1 = val2;
val2 = valTemp;
int typeTmp = type1;
type1 = type2;
type2 = typeTmp;
}
if (op == Operator.Op.EQ || op == Operator.Op.NE)
{
return s_compXsltE[type1][type2](op, val1, val2);
}
else
{
return s_compXsltO[type1][type2](op, val1, val2);
}
}
private delegate bool cmpXslt(Operator.Op op, object val1, object val2);
// Number, String, Boolean, NodeSet, Navigator
private static readonly cmpXslt[][] s_compXsltE = {
new cmpXslt[] { new cmpXslt(cmpNumberNumber), null , null , null , null },
new cmpXslt[] { new cmpXslt(cmpStringNumber), new cmpXslt(cmpStringStringE), null , null , null },
new cmpXslt[] { new cmpXslt(cmpBoolNumberE ), new cmpXslt(cmpBoolStringE ), new cmpXslt(cmpBoolBoolE ), null , null },
new cmpXslt[] { new cmpXslt(cmpQueryNumber ), new cmpXslt(cmpQueryStringE ), new cmpXslt(cmpQueryBoolE ), new cmpXslt(cmpQueryQueryE ), null },
new cmpXslt[] { new cmpXslt(cmpRtfNumber ), new cmpXslt(cmpRtfStringE ), new cmpXslt(cmpRtfBoolE ), new cmpXslt(cmpRtfQueryE ), new cmpXslt(cmpRtfRtfE) },
};
private static readonly cmpXslt[][] s_compXsltO = {
new cmpXslt[] { new cmpXslt(cmpNumberNumber), null , null , null , null },
new cmpXslt[] { new cmpXslt(cmpStringNumber), new cmpXslt(cmpStringStringO), null , null , null },
new cmpXslt[] { new cmpXslt(cmpBoolNumberO ), new cmpXslt(cmpBoolStringO ), new cmpXslt(cmpBoolBoolO ), null , null },
new cmpXslt[] { new cmpXslt(cmpQueryNumber ), new cmpXslt(cmpQueryStringO ), new cmpXslt(cmpQueryBoolO ), new cmpXslt(cmpQueryQueryO ), null },
new cmpXslt[] { new cmpXslt(cmpRtfNumber ), new cmpXslt(cmpRtfStringO ), new cmpXslt(cmpRtfBoolO ), new cmpXslt(cmpRtfQueryO ), new cmpXslt(cmpRtfRtfO) },
};
/*cmpXslt:*/
private static bool cmpQueryQueryE(Operator.Op op, object val1, object val2)
{
Debug.Assert(op == Operator.Op.EQ || op == Operator.Op.NE);
bool isEQ = (op == Operator.Op.EQ);
NodeSet n1 = new NodeSet(val1);
NodeSet n2 = new NodeSet(val2);
while (true)
{
if (!n1.MoveNext())
{
return false;
}
if (!n2.MoveNext())
{
return false;
}
string str1 = n1.Value;
do
{
if ((str1 == n2.Value) == isEQ)
{
return true;
}
} while (n2.MoveNext());
n2.Reset();
}
}
/*cmpXslt:*/
private static bool cmpQueryQueryO(Operator.Op op, object val1, object val2)
{
Debug.Assert(
op == Operator.Op.LT || op == Operator.Op.GT ||
op == Operator.Op.LE || op == Operator.Op.GE
);
NodeSet n1 = new NodeSet(val1);
NodeSet n2 = new NodeSet(val2);
while (true)
{
if (!n1.MoveNext())
{
return false;
}
if (!n2.MoveNext())
{
return false;
}
double num1 = NumberFunctions.Number(n1.Value);
do
{
if (cmpNumberNumber(op, num1, NumberFunctions.Number(n2.Value)))
{
return true;
}
} while (n2.MoveNext());
n2.Reset();
}
}
private static bool cmpQueryNumber(Operator.Op op, object val1, object val2)
{
NodeSet n1 = new NodeSet(val1);
double n2 = (double)val2;
while (n1.MoveNext())
{
if (cmpNumberNumber(op, NumberFunctions.Number(n1.Value), n2))
{
return true;
}
}
return false;
}
private static bool cmpQueryStringE(Operator.Op op, object val1, object val2)
{
NodeSet n1 = new NodeSet(val1);
string n2 = (string)val2;
while (n1.MoveNext())
{
if (cmpStringStringE(op, n1.Value, n2))
{
return true;
}
}
return false;
}
private static bool cmpQueryStringO(Operator.Op op, object val1, object val2)
{
NodeSet n1 = new NodeSet(val1);
double n2 = NumberFunctions.Number((string)val2);
while (n1.MoveNext())
{
if (cmpNumberNumberO(op, NumberFunctions.Number(n1.Value), n2))
{
return true;
}
}
return false;
}
private static bool cmpRtfQueryE(Operator.Op op, object val1, object val2)
{
string n1 = Rtf(val1);
NodeSet n2 = new NodeSet(val2);
while (n2.MoveNext())
{
if (cmpStringStringE(op, n1, n2.Value))
{
return true;
}
}
return false;
}
private static bool cmpRtfQueryO(Operator.Op op, object val1, object val2)
{
double n1 = NumberFunctions.Number(Rtf(val1));
NodeSet n2 = new NodeSet(val2);
while (n2.MoveNext())
{
if (cmpNumberNumberO(op, n1, NumberFunctions.Number(n2.Value)))
{
return true;
}
}
return false;
}
private static bool cmpQueryBoolE(Operator.Op op, object val1, object val2)
{
NodeSet n1 = new NodeSet(val1);
bool b1 = n1.MoveNext();
bool b2 = (bool)val2;
return cmpBoolBoolE(op, b1, b2);
}
private static bool cmpQueryBoolO(Operator.Op op, object val1, object val2)
{
NodeSet n1 = new NodeSet(val1);
double d1 = n1.MoveNext() ? 1.0 : 0;
double d2 = NumberFunctions.Number((bool)val2);
return cmpNumberNumberO(op, d1, d2);
}
private static bool cmpBoolBoolE(Operator.Op op, bool n1, bool n2)
{
Debug.Assert(op == Operator.Op.EQ || op == Operator.Op.NE,
"Unexpected Operator.op code in cmpBoolBoolE()"
);
return (op == Operator.Op.EQ) == (n1 == n2);
}
private static bool cmpBoolBoolE(Operator.Op op, object val1, object val2)
{
bool n1 = (bool)val1;
bool n2 = (bool)val2;
return cmpBoolBoolE(op, n1, n2);
}
private static bool cmpBoolBoolO(Operator.Op op, object val1, object val2)
{
double n1 = NumberFunctions.Number((bool)val1);
double n2 = NumberFunctions.Number((bool)val2);
return cmpNumberNumberO(op, n1, n2);
}
private static bool cmpBoolNumberE(Operator.Op op, object val1, object val2)
{
bool n1 = (bool)val1;
bool n2 = BooleanFunctions.toBoolean((double)val2);
return cmpBoolBoolE(op, n1, n2);
}
private static bool cmpBoolNumberO(Operator.Op op, object val1, object val2)
{
double n1 = NumberFunctions.Number((bool)val1);
double n2 = (double)val2;
return cmpNumberNumberO(op, n1, n2);
}
private static bool cmpBoolStringE(Operator.Op op, object val1, object val2)
{
bool n1 = (bool)val1;
bool n2 = BooleanFunctions.toBoolean((string)val2);
return cmpBoolBoolE(op, n1, n2);
}
private static bool cmpRtfBoolE(Operator.Op op, object val1, object val2)
{
bool n1 = BooleanFunctions.toBoolean(Rtf(val1));
bool n2 = (bool)val2;
return cmpBoolBoolE(op, n1, n2);
}
private static bool cmpBoolStringO(Operator.Op op, object val1, object val2)
{
return cmpNumberNumberO(op,
NumberFunctions.Number((bool)val1),
NumberFunctions.Number((string)val2)
);
}
private static bool cmpRtfBoolO(Operator.Op op, object val1, object val2)
{
return cmpNumberNumberO(op,
NumberFunctions.Number(Rtf(val1)),
NumberFunctions.Number((bool)val2)
);
}
private static bool cmpNumberNumber(Operator.Op op, double n1, double n2)
{
switch (op)
{
case Operator.Op.LT: return (n1 < n2);
case Operator.Op.GT: return (n1 > n2);
case Operator.Op.LE: return (n1 <= n2);
case Operator.Op.GE: return (n1 >= n2);
case Operator.Op.EQ: return (n1 == n2);
case Operator.Op.NE: return (n1 != n2);
}
Debug.Fail("Unexpected Operator.op code in cmpNumberNumber()");
return false;
}
private static bool cmpNumberNumberO(Operator.Op op, double n1, double n2)
{
switch (op)
{
case Operator.Op.LT: return (n1 < n2);
case Operator.Op.GT: return (n1 > n2);
case Operator.Op.LE: return (n1 <= n2);
case Operator.Op.GE: return (n1 >= n2);
}
Debug.Fail("Unexpected Operator.op code in cmpNumberNumberO()");
return false;
}
private static bool cmpNumberNumber(Operator.Op op, object val1, object val2)
{
double n1 = (double)val1;
double n2 = (double)val2;
return cmpNumberNumber(op, n1, n2);
}
private static bool cmpStringNumber(Operator.Op op, object val1, object val2)
{
double n2 = (double)val2;
double n1 = NumberFunctions.Number((string)val1);
return cmpNumberNumber(op, n1, n2);
}
private static bool cmpRtfNumber(Operator.Op op, object val1, object val2)
{
double n2 = (double)val2;
double n1 = NumberFunctions.Number(Rtf(val1));
return cmpNumberNumber(op, n1, n2);
}
private static bool cmpStringStringE(Operator.Op op, string n1, string n2)
{
Debug.Assert(op == Operator.Op.EQ || op == Operator.Op.NE,
"Unexpected Operator.op code in cmpStringStringE()"
);
return (op == Operator.Op.EQ) == (n1 == n2);
}
private static bool cmpStringStringE(Operator.Op op, object val1, object val2)
{
string n1 = (string)val1;
string n2 = (string)val2;
return cmpStringStringE(op, n1, n2);
}
private static bool cmpRtfStringE(Operator.Op op, object val1, object val2)
{
string n1 = Rtf(val1);
string n2 = (string)val2;
return cmpStringStringE(op, n1, n2);
}
private static bool cmpRtfRtfE(Operator.Op op, object val1, object val2)
{
string n1 = Rtf(val1);
string n2 = Rtf(val2);
return cmpStringStringE(op, n1, n2);
}
private static bool cmpStringStringO(Operator.Op op, object val1, object val2)
{
double n1 = NumberFunctions.Number((string)val1);
double n2 = NumberFunctions.Number((string)val2);
return cmpNumberNumberO(op, n1, n2);
}
private static bool cmpRtfStringO(Operator.Op op, object val1, object val2)
{
double n1 = NumberFunctions.Number(Rtf(val1));
double n2 = NumberFunctions.Number((string)val2);
return cmpNumberNumberO(op, n1, n2);
}
private static bool cmpRtfRtfO(Operator.Op op, object val1, object val2)
{
double n1 = NumberFunctions.Number(Rtf(val1));
double n2 = NumberFunctions.Number(Rtf(val2));
return cmpNumberNumberO(op, n1, n2);
}
public override XPathNodeIterator Clone() { return new LogicalExpr(this); }
private struct NodeSet
{
private Query _opnd;
private XPathNavigator _current;
public NodeSet(object opnd)
{
_opnd = (Query)opnd;
_current = null;
}
public bool MoveNext()
{
_current = _opnd.Advance();
return _current != null;
}
public void Reset()
{
_opnd.Reset();
}
public string Value { get { return _current.Value; } }
}
private static string Rtf(object o) { return ((XPathNavigator)o).Value; }
public override XPathResultType StaticType { get { return XPathResultType.Boolean; } }
public override void PrintQuery(XmlWriter w)
{
w.WriteStartElement(this.GetType().Name);
w.WriteAttributeString("op", _op.ToString());
_opnd1.PrintQuery(w);
_opnd2.PrintQuery(w);
w.WriteEndElement();
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.World
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "CloudModule")]
public class CloudModule : ICloudModule, INonSharedRegionModule
{
// private static readonly log4net.ILog m_log
// = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private uint m_frame = 0;
private int m_frameUpdateRate = 1000;
private Random m_rndnums = new Random(Environment.TickCount);
private Scene m_scene = null;
private bool m_ready = false;
private bool m_enabled = false;
private float m_cloudDensity = 1.0F;
private float[] cloudCover = new float[16 * 16];
public void Initialise(IConfigSource config)
{
IConfig cloudConfig = config.Configs["Cloud"];
if (cloudConfig != null)
{
m_enabled = cloudConfig.GetBoolean("enabled", false);
m_cloudDensity = cloudConfig.GetFloat("density", 0.5F);
m_frameUpdateRate = cloudConfig.GetInt("cloud_update_rate", 1000);
}
}
public void AddRegion(Scene scene)
{
if (!m_enabled)
return;
m_scene = scene;
scene.EventManager.OnNewClient += CloudsToClient;
scene.RegisterModuleInterface<ICloudModule>(this);
scene.EventManager.OnFrame += CloudUpdate;
GenerateCloudCover();
m_ready = true;
}
public void RemoveRegion(Scene scene)
{
if (!m_enabled)
return;
m_ready = false;
// Remove our hooks
m_scene.EventManager.OnNewClient -= CloudsToClient;
m_scene.EventManager.OnFrame -= CloudUpdate;
m_scene.UnregisterModuleInterface<ICloudModule>(this);
m_scene = null;
}
public void RegionLoaded(Scene scene)
{
}
public void PostInitialise()
{
}
public void Close()
{
}
public string Name
{
get { return "CloudModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public float CloudCover(int x, int y, int z)
{
float cover = 0f;
x /= 16;
y /= 16;
if (x < 0) x = 0;
if (x > 15) x = 15;
if (y < 0) y = 0;
if (y > 15) y = 15;
if (cloudCover != null)
{
cover = cloudCover[y * 16 + x];
}
return cover;
}
private void UpdateCloudCover()
{
float[] newCover = new float[16 * 16];
int rowAbove = new int();
int rowBelow = new int();
int columnLeft = new int();
int columnRight = new int();
for (int x = 0; x < 16; x++)
{
if (x == 0)
{
columnRight = x + 1;
columnLeft = 15;
}
else if (x == 15)
{
columnRight = 0;
columnLeft = x - 1;
}
else
{
columnRight = x + 1;
columnLeft = x - 1;
}
for (int y = 0; y< 16; y++)
{
if (y == 0)
{
rowAbove = y + 1;
rowBelow = 15;
}
else if (y == 15)
{
rowAbove = 0;
rowBelow = y - 1;
}
else
{
rowAbove = y + 1;
rowBelow = y - 1;
}
float neighborAverage = (cloudCover[rowBelow * 16 + columnLeft] +
cloudCover[y * 16 + columnLeft] +
cloudCover[rowAbove * 16 + columnLeft] +
cloudCover[rowBelow * 16 + x] +
cloudCover[rowAbove * 16 + x] +
cloudCover[rowBelow * 16 + columnRight] +
cloudCover[y * 16 + columnRight] +
cloudCover[rowAbove * 16 + columnRight] +
cloudCover[y * 16 + x]) / 9;
newCover[y * 16 + x] = ((neighborAverage / m_cloudDensity) + 0.175f) % 1.0f;
newCover[y * 16 + x] *= m_cloudDensity;
}
}
Array.Copy(newCover, cloudCover, 16 * 16);
}
private void CloudUpdate()
{
if (((m_frame++ % m_frameUpdateRate) != 0) || !m_ready || (m_cloudDensity == 0))
{
return;
}
UpdateCloudCover();
}
public void CloudsToClient(IClientAPI client)
{
if (m_ready)
{
client.SendCloudData(cloudCover);
}
}
/// <summary>
/// Calculate the cloud cover over the region.
/// </summary>
private void GenerateCloudCover()
{
for (int y = 0; y < 16; y++)
{
for (int x = 0; x < 16; x++)
{
cloudCover[y * 16 + x] = (float)(m_rndnums.NextDouble()); // 0 to 1
cloudCover[y * 16 + x] *= m_cloudDensity;
}
}
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel
{
using System.ComponentModel;
using System.Configuration;
using System.Runtime;
using System.ServiceModel.Channels;
using System.ServiceModel.Configuration;
using System.Xml;
public class NetTcpBinding : Binding, IBindingRuntimePreferences
{
OptionalReliableSession reliableSession;
// private BindingElements
TcpTransportBindingElement transport;
BinaryMessageEncodingBindingElement encoding;
TransactionFlowBindingElement context;
ReliableSessionBindingElement session;
NetTcpSecurity security = new NetTcpSecurity();
public NetTcpBinding() { Initialize(); }
public NetTcpBinding(SecurityMode securityMode)
: this()
{
this.security.Mode = securityMode;
}
public NetTcpBinding(SecurityMode securityMode, bool reliableSessionEnabled)
: this(securityMode)
{
this.ReliableSession.Enabled = reliableSessionEnabled;
}
public NetTcpBinding(string configurationName)
: this()
{
ApplyConfiguration(configurationName);
}
NetTcpBinding(TcpTransportBindingElement transport, BinaryMessageEncodingBindingElement encoding, TransactionFlowBindingElement context, ReliableSessionBindingElement session, NetTcpSecurity security)
: this()
{
this.security = security;
this.ReliableSession.Enabled = session != null;
InitializeFrom(transport, encoding, context, session);
}
[DefaultValue(NetTcpDefaults.TransactionsEnabled)]
public bool TransactionFlow
{
get { return context.Transactions; }
set { context.Transactions = value; }
}
public TransactionProtocol TransactionProtocol
{
get { return this.context.TransactionProtocol; }
set { this.context.TransactionProtocol = value; }
}
[DefaultValue(ConnectionOrientedTransportDefaults.TransferMode)]
public TransferMode TransferMode
{
get { return this.transport.TransferMode; }
set { this.transport.TransferMode = value; }
}
[DefaultValue(ConnectionOrientedTransportDefaults.HostNameComparisonMode)]
public HostNameComparisonMode HostNameComparisonMode
{
get { return transport.HostNameComparisonMode; }
set { transport.HostNameComparisonMode = value; }
}
[DefaultValue(TransportDefaults.MaxBufferPoolSize)]
public long MaxBufferPoolSize
{
get { return transport.MaxBufferPoolSize; }
set
{
transport.MaxBufferPoolSize = value;
}
}
[DefaultValue(TransportDefaults.MaxBufferSize)]
public int MaxBufferSize
{
get { return transport.MaxBufferSize; }
set { transport.MaxBufferSize = value; }
}
public int MaxConnections
{
get { return transport.MaxPendingConnections; }
set
{
transport.MaxPendingConnections = value;
transport.ConnectionPoolSettings.MaxOutboundConnectionsPerEndpoint = value;
}
}
internal bool IsMaxConnectionsSet
{
get { return transport.IsMaxPendingConnectionsSet; }
}
public int ListenBacklog
{
get { return transport.ListenBacklog; }
set { transport.ListenBacklog = value; }
}
internal bool IsListenBacklogSet
{
get { return transport.IsListenBacklogSet; }
}
[DefaultValue(TransportDefaults.MaxReceivedMessageSize)]
public long MaxReceivedMessageSize
{
get { return transport.MaxReceivedMessageSize; }
set { transport.MaxReceivedMessageSize = value; }
}
[DefaultValue(TcpTransportDefaults.PortSharingEnabled)]
public bool PortSharingEnabled
{
get { return transport.PortSharingEnabled; }
set { transport.PortSharingEnabled = value; }
}
public XmlDictionaryReaderQuotas ReaderQuotas
{
get { return encoding.ReaderQuotas; }
set
{
if (value == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
value.CopyTo(encoding.ReaderQuotas);
}
}
bool IBindingRuntimePreferences.ReceiveSynchronously
{
get { return false; }
}
public OptionalReliableSession ReliableSession
{
get
{
return reliableSession;
}
set
{
if (value == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value"));
}
this.reliableSession.CopySettings(value);
}
}
public override string Scheme { get { return transport.Scheme; } }
public EnvelopeVersion EnvelopeVersion
{
get { return EnvelopeVersion.Soap12; }
}
public NetTcpSecurity Security
{
get { return security; }
set
{
if (value == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
security = value;
}
}
static TransactionFlowBindingElement GetDefaultTransactionFlowBindingElement()
{
return new TransactionFlowBindingElement(NetTcpDefaults.TransactionsEnabled);
}
void Initialize()
{
transport = new TcpTransportBindingElement();
encoding = new BinaryMessageEncodingBindingElement();
context = GetDefaultTransactionFlowBindingElement();
session = new ReliableSessionBindingElement();
this.reliableSession = new OptionalReliableSession(session);
}
void InitializeFrom(TcpTransportBindingElement transport, BinaryMessageEncodingBindingElement encoding, TransactionFlowBindingElement context, ReliableSessionBindingElement session)
{
Fx.Assert(transport != null, "Invalid (null) transport value.");
Fx.Assert(encoding != null, "Invalid (null) encoding value.");
Fx.Assert(context != null, "Invalid (null) context value.");
Fx.Assert(security != null, "Invalid (null) security value.");
// transport
this.HostNameComparisonMode = transport.HostNameComparisonMode;
this.MaxBufferPoolSize = transport.MaxBufferPoolSize;
this.MaxBufferSize = transport.MaxBufferSize;
if (transport.IsMaxPendingConnectionsSet)
{
this.MaxConnections = transport.MaxPendingConnections;
}
if (transport.IsListenBacklogSet)
{
this.ListenBacklog = transport.ListenBacklog;
}
this.MaxReceivedMessageSize = transport.MaxReceivedMessageSize;
this.PortSharingEnabled = transport.PortSharingEnabled;
this.TransferMode = transport.TransferMode;
// encoding
this.ReaderQuotas = encoding.ReaderQuotas;
// context
this.TransactionFlow = context.Transactions;
this.TransactionProtocol = context.TransactionProtocol;
//session
if (session != null)
{
// only set properties that have standard binding manifestations
this.session.InactivityTimeout = session.InactivityTimeout;
this.session.Ordered = session.Ordered;
}
}
// check that properties of the HttpTransportBindingElement and
// MessageEncodingBindingElement not exposed as properties on BasicHttpBinding
// match default values of the binding elements
bool IsBindingElementsMatch(TcpTransportBindingElement transport, BinaryMessageEncodingBindingElement encoding, TransactionFlowBindingElement context, ReliableSessionBindingElement session)
{
if (!this.transport.IsMatch(transport))
return false;
if (!this.encoding.IsMatch(encoding))
return false;
if (!this.context.IsMatch(context))
return false;
if (reliableSession.Enabled)
{
if (!this.session.IsMatch(session))
return false;
}
else if (session != null)
return false;
return true;
}
void ApplyConfiguration(string configurationName)
{
NetTcpBindingCollectionElement section = NetTcpBindingCollectionElement.GetBindingCollectionElement();
NetTcpBindingElement element = section.Bindings[configurationName];
if (element == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(
SR.GetString(SR.ConfigInvalidBindingConfigurationName,
configurationName,
ConfigurationStrings.NetTcpBindingCollectionElementName)));
}
else
{
element.ApplyConfiguration(this);
}
}
// In the Win8 profile, some settings for the binding security are not supported.
void CheckSettings()
{
if (!UnsafeNativeMethods.IsTailoredApplication.Value)
{
return;
}
NetTcpSecurity security = this.Security;
if (security == null)
{
return;
}
SecurityMode mode = security.Mode;
if (mode == SecurityMode.None)
{
return;
}
else if (mode == SecurityMode.Message)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.UnsupportedSecuritySetting, "Mode", mode)));
}
// Message.ClientCredentialType = Certificate, IssuedToken or Windows are not supported.
if (mode == SecurityMode.TransportWithMessageCredential)
{
MessageSecurityOverTcp message = security.Message;
if (message != null)
{
MessageCredentialType mct = message.ClientCredentialType;
if ((mct == MessageCredentialType.Certificate) || (mct == MessageCredentialType.IssuedToken) || (mct == MessageCredentialType.Windows))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.UnsupportedSecuritySetting, "Message.ClientCredentialType", mct)));
}
}
}
// Transport.ClientCredentialType = Certificate is not supported.
Fx.Assert((mode == SecurityMode.Transport) || (mode == SecurityMode.TransportWithMessageCredential), "Unexpected SecurityMode value: " + mode);
TcpTransportSecurity transport = security.Transport;
if ((transport != null) && (transport.ClientCredentialType == TcpClientCredentialType.Certificate))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.UnsupportedSecuritySetting, "Transport.ClientCredentialType", transport.ClientCredentialType)));
}
}
public override BindingElementCollection CreateBindingElements()
{
this.CheckSettings();
// return collection of BindingElements
BindingElementCollection bindingElements = new BindingElementCollection();
// order of BindingElements is important
// add context
bindingElements.Add(context);
// add session
if (reliableSession.Enabled)
bindingElements.Add(session);
// add security (*optional)
SecurityBindingElement wsSecurity = CreateMessageSecurity();
if (wsSecurity != null)
bindingElements.Add(wsSecurity);
// add encoding
bindingElements.Add(encoding);
// add transport security
BindingElement transportSecurity = CreateTransportSecurity();
if (transportSecurity != null)
{
bindingElements.Add(transportSecurity);
}
transport.ExtendedProtectionPolicy = security.Transport.ExtendedProtectionPolicy;
// add transport (tcp)
bindingElements.Add(transport);
return bindingElements.Clone();
}
internal static bool TryCreate(BindingElementCollection elements, out Binding binding)
{
binding = null;
if (elements.Count > 6)
return false;
// collect all binding elements
TcpTransportBindingElement transport = null;
BinaryMessageEncodingBindingElement encoding = null;
TransactionFlowBindingElement context = null;
ReliableSessionBindingElement session = null;
SecurityBindingElement wsSecurity = null;
BindingElement transportSecurity = null;
foreach (BindingElement element in elements)
{
if (element is SecurityBindingElement)
wsSecurity = element as SecurityBindingElement;
else if (element is TransportBindingElement)
transport = element as TcpTransportBindingElement;
else if (element is MessageEncodingBindingElement)
encoding = element as BinaryMessageEncodingBindingElement;
else if (element is TransactionFlowBindingElement)
context = element as TransactionFlowBindingElement;
else if (element is ReliableSessionBindingElement)
session = element as ReliableSessionBindingElement;
else
{
if (transportSecurity != null)
return false;
transportSecurity = element;
}
}
if (transport == null)
return false;
if (encoding == null)
return false;
if (context == null)
context = GetDefaultTransactionFlowBindingElement();
TcpTransportSecurity tcpTransportSecurity = new TcpTransportSecurity();
UnifiedSecurityMode mode = GetModeFromTransportSecurity(transportSecurity);
NetTcpSecurity security;
if (!TryCreateSecurity(wsSecurity, mode, session != null, transportSecurity, tcpTransportSecurity, out security))
return false;
if (!SetTransportSecurity(transportSecurity, security.Mode, tcpTransportSecurity))
return false;
NetTcpBinding netTcpBinding = new NetTcpBinding(transport, encoding, context, session, security);
if (!netTcpBinding.IsBindingElementsMatch(transport, encoding, context, session))
return false;
binding = netTcpBinding;
return true;
}
BindingElement CreateTransportSecurity()
{
return this.security.CreateTransportSecurity();
}
static UnifiedSecurityMode GetModeFromTransportSecurity(BindingElement transport)
{
return NetTcpSecurity.GetModeFromTransportSecurity(transport);
}
static bool SetTransportSecurity(BindingElement transport, SecurityMode mode, TcpTransportSecurity transportSecurity)
{
return NetTcpSecurity.SetTransportSecurity(transport, mode, transportSecurity);
}
SecurityBindingElement CreateMessageSecurity()
{
if (this.security.Mode == SecurityMode.Message || this.security.Mode == SecurityMode.TransportWithMessageCredential)
{
return this.security.CreateMessageSecurity(this.ReliableSession.Enabled);
}
else
{
return null;
}
}
static bool TryCreateSecurity(SecurityBindingElement sbe, UnifiedSecurityMode mode, bool isReliableSession, BindingElement transportSecurity, TcpTransportSecurity tcpTransportSecurity, out NetTcpSecurity security)
{
if (sbe != null)
mode &= UnifiedSecurityMode.Message | UnifiedSecurityMode.TransportWithMessageCredential;
else
mode &= ~(UnifiedSecurityMode.Message | UnifiedSecurityMode.TransportWithMessageCredential);
SecurityMode securityMode = SecurityModeHelper.ToSecurityMode(mode);
Fx.Assert(SecurityModeHelper.IsDefined(securityMode), string.Format("Invalid SecurityMode value: {0}.", securityMode.ToString()));
if (NetTcpSecurity.TryCreate(sbe, securityMode, isReliableSession, transportSecurity, tcpTransportSecurity, out security))
return true;
return false;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeReaderQuotas()
{
return (!EncoderDefaults.IsDefaultReaderQuotas(this.ReaderQuotas));
}
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeSecurity()
{
return this.security.InternalShouldSerialize();
}
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeTransactionProtocol()
{
return (TransactionProtocol != NetTcpDefaults.TransactionProtocol);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeReliableSession()
{
return (this.ReliableSession.Ordered != ReliableSessionDefaults.Ordered
|| this.ReliableSession.InactivityTimeout != ReliableSessionDefaults.InactivityTimeout
|| this.ReliableSession.Enabled != ReliableSessionDefaults.Enabled);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeListenBacklog()
{
return transport.ShouldSerializeListenBacklog();
}
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeMaxConnections()
{
return transport.ShouldSerializeListenBacklog();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using Microsoft.CodeAnalysis;
using Xunit;
namespace Microsoft.DotNet.CodeFormatting.Tests
{
/// <summary>
/// Test that fields are correctly identified as readonly.
/// </summary>
public class MarkReadonlyFieldTests : GlobalSemanticRuleTestBase
{
internal override IGlobalSemanticFormattingRule Rule
{
get { return new Rules.MarkReadonlyFieldsRule(); }
}
protected override IEnumerable<MetadataReference> GetSolutionMetadataReferences()
{
foreach (MetadataReference reference in base.GetSolutionMetadataReferences())
{
yield return reference;
}
yield return MetadataReference.CreateFromFile(typeof(ImportAttribute).Assembly.Location);
}
// In general a single sting with "READONLY" in it is used
// for the tests to simplify the before/after comparison
// The Original method will remove it, and the Readonly will replace it
// with the keyword
[Fact]
public void TestIgnoreExistingReadonlyField()
{
string text = @"
class C
{
private readonly int alreadyFine;
}
";
Verify(Original(text), Readonly(text));
}
[Fact]
public void TestMarkReadonlyWithNoReferences()
{
string text = @"
class C
{
private READONLY int read;
}
";
Verify(Original(text), Readonly(text));
}
[Fact]
public void TestMarkReadonlyInternalWithNoReferences()
{
string text = @"
class C
{
internal READONLY int read;
}
";
Verify(Original(text), Readonly(text));
}
[Fact]
public void TestIgnoredReadonlyInternalWithNoReferencesByInternalsVisibleTo()
{
string text = @"
[assembly: System.Runtime.CompilerServices.InternalsVisibleToAttribute(""Some.Other.Assembly"")]
class C
{
internal int exposed;
}
";
Verify(Original(text), Readonly(text));
}
[Fact]
public void TestIgnoredPublic()
{
string text = @"
public class C
{
public int exposed;
}
";
Verify(Original(text), Readonly(text));
}
[Fact]
public void TestMarkedPublicInInternalClass()
{
string text = @"
internal class C
{
public READONLY int notExposed;
}
";
Verify(Original(text), Readonly(text));
}
[Fact]
public void TestIgnoredReadonlyWithWriteReferences()
{
string text = @"
class C
{
private int wrote;
public void T()
{
wrote = 5;
}
}
";
Verify(Original(text), Readonly(text));
}
[Fact]
public void TestIgnoredReadonlyWithCompoundWriteReferences()
{
string text = @"
class C
{
private int wrote;
public void T()
{
wrote += 5;
}
}
";
Verify(Original(text), Readonly(text));
}
[Fact]
public void TestMarkReadonlyWithReadReferences()
{
string text = @"
class C
{
private READONLY int read;
private int writen;
public void T()
{
int x = change;
x = read;
writen = read;
X(read);
}
public void X(int a)
{
}
}
";
Verify(Original(text), Readonly(text));
}
[Fact]
public void TestIgnoredReadonlyWithRefArgument()
{
string text = @"
class C
{
private int read;
public void M(ref int a)
{
}
public void T()
{
M(ref read);
}
}
";
Verify(Original(text), Readonly(text));
}
[Fact]
public void TestIgnoredReadonlyWithOutArgument()
{
string text = @"
class C
{
private int read;
public void N(out int a)
{
}
public void T()
{
N(out read);
}
}
";
Verify(Original(text), Readonly(text));
}
[Fact]
public void TestIgnoredReadonlyWithExternRefArgument()
{
string text = @"
class C
{
private int read;
private extern void M(ref C c);
}
";
Verify(Original(text), Readonly(text));
}
[Fact]
public void TestIgnoredReadonlyWithMethodCall()
{
string text = @"
struct S
{
public void T() { }
}
class C
{
private S called;
public void T()
{
called.T();
}
}
";
Verify(Original(text), Readonly(text));
}
[Fact]
public void TestMarkReadonlyWithPrimitiveMethodCall()
{
string text = @"
class C
{
private READONLY int called;
public void T()
{
string s = called.ToString();
}
}
";
Verify(Original(text), Readonly(text));
}
[Fact]
public void TestIgnoredImportedField()
{
string text = @"
using System.ComponentModel.Composition;
public interface ITest
{
}
[Export(typeof(ITest))]
public class Test : ITest
{
}
class C
{
[Import]
private ITest imported;
}
";
Verify(Original(text), Readonly(text));
}
[Fact]
public void TestMarkReadonlyWithWriteReferencesInConstructor()
{
string text = @"
class C
{
private READONLY int read;
public C()
{
read = 5;
M(ref read);
N(out read);
}
public void M(ref int a)
{
}
public void N(out int a)
{
}
}
";
Verify(Original(text), Readonly(text));
}
[Fact]
public void TestIgnoreReadonlyWithDelegateReferencesInConstructor()
{
string text = @"
class C
{
private int wrote;
public C()
{
Action a = delegate { wrote = 5 };
}
}
";
Verify(Original(text), Readonly(text));
}
[Fact]
public void TestIgnoreStaticReadonlyWithWriteReferencesInInstanceConstructor()
{
string text = @"
class C
{
private static int wrote;
public C()
{
wrote = 5;
}
}
";
Verify(Original(text), Readonly(text));
}
[Fact]
public void TestMultipleFiles()
{
string[] text =
{
@"
class C1
{
internal READONLY int read;
internal int wrote;
public void M(C2 c)
{
c.wrote = 5;
int x = c.read;
}
}
",
@"
class C2
{
internal READONLY int read;
internal int wrote;
public void M(C1 c)
{
c.wrote = 5;
int x = c.read;
}
}
"
};
Verify(Original(text), Readonly(text), true, LanguageNames.CSharp);
}
private static string Original(string text)
{
return text.Replace("READONLY ", "");
}
private static string Readonly(string text)
{
return text.Replace("READONLY ", "readonly ");
}
private static string[] Original(string[] text)
{
return text.Select(Original).ToArray();
}
private static string[] Readonly(string[] text)
{
return text.Select(Readonly).ToArray();
}
}
}
| |
//
// JsonSerializer.cs
//
// Author:
// Marek Habersack <mhabersack@novell.com>
//
// (C) 2008 Novell, Inc. http://novell.com/
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Nancy.Json
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
internal sealed class JsonSerializer
{
internal static readonly long InitialJavaScriptDateTicks = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
static readonly DateTime MinimumJavaScriptDate = new DateTime(100, 1, 1, 0, 0, 0, DateTimeKind.Utc);
static readonly MethodInfo serializeGenericDictionary = typeof(JsonSerializer).GetMethod("SerializeGenericDictionary", BindingFlags.NonPublic | BindingFlags.Instance);
Dictionary <object, bool> objectCache;
JavaScriptSerializer serializer;
JavaScriptTypeResolver typeResolver;
int recursionLimit;
int maxJsonLength;
int recursionDepth;
Dictionary <Type, MethodInfo> serializeGenericDictionaryMethods;
public JsonSerializer (JavaScriptSerializer serializer)
{
if (serializer == null)
throw new ArgumentNullException ("serializer");
this.serializer = serializer;
typeResolver = serializer.TypeResolver;
recursionLimit = serializer.RecursionLimit;
maxJsonLength = serializer.MaxJsonLength;
}
public void Serialize (object obj, StringBuilder output)
{
if (output == null)
throw new ArgumentNullException ("output");
DoSerialize (obj, output);
}
public void Serialize (object obj, TextWriter output)
{
if (output == null)
throw new ArgumentNullException ("output");
StringBuilder sb = new StringBuilder ();
DoSerialize (obj, sb);
output.Write (sb.ToString ());
}
void DoSerialize (object obj, StringBuilder output)
{
recursionDepth = 0;
objectCache = new Dictionary <object, bool> ();
SerializeValue (obj, output);
}
void SerializeValue (object obj, StringBuilder output)
{
recursionDepth++;
SerializeValueImpl (obj, output);
recursionDepth--;
}
void SerializeValueImpl (object obj, StringBuilder output)
{
if (recursionDepth > recursionLimit)
throw new ArgumentException ("Recursion limit has been exceeded while serializing object of type '{0}'", obj != null ? obj.GetType ().ToString () : "[null]");
if (obj == null || DBNull.Value.Equals (obj)) {
StringBuilderExtensions.AppendCount (output, maxJsonLength, "null");
return;
}
#if !__MonoCS__
if (obj.GetType().Name == "RuntimeType")
{
obj = obj.ToString();
}
#else
if (obj.GetType().Name == "MonoType")
{
obj = obj.ToString();
}
#endif
Type valueType = obj.GetType ();
JavaScriptConverter jsc = serializer.GetConverter (valueType);
if (jsc != null) {
IDictionary <string, object> result = jsc.Serialize (obj, serializer);
if (result == null) {
StringBuilderExtensions.AppendCount (output, maxJsonLength, "null");
return;
}
if (typeResolver != null) {
string typeId = typeResolver.ResolveTypeId (valueType);
if (!String.IsNullOrEmpty (typeId))
result [JavaScriptSerializer.SerializedTypeNameKey] = typeId;
}
SerializeValue (result, output);
return;
}
TypeCode typeCode = Type.GetTypeCode (valueType);
switch (typeCode) {
case TypeCode.String:
WriteValue (output, (string)obj);
return;
case TypeCode.Char:
WriteValue (output, (char)obj);
return;
case TypeCode.Boolean:
WriteValue (output, (bool)obj);
return;
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.Byte:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
if (valueType.IsEnum) {
WriteEnumValue (output, obj, typeCode);
return;
}
goto case TypeCode.Decimal;
case TypeCode.Single:
WriteValue (output, (float)obj);
return;
case TypeCode.Double:
WriteValue (output, (double)obj);
return;
case TypeCode.Decimal:
WriteValue (output, obj as IConvertible);
return;
case TypeCode.DateTime:
WriteValue (output, (DateTime)obj);
return;
}
if (typeof (Uri).IsAssignableFrom (valueType)) {
WriteValue (output, (Uri)obj);
return;
}
if (typeof (Guid).IsAssignableFrom (valueType)) {
WriteValue (output, (Guid)obj);
return;
}
if (typeof (DynamicDictionaryValue).IsAssignableFrom(valueType))
{
var o = (DynamicDictionaryValue) obj;
SerializeValue(o.Value, output);
return;
}
IConvertible convertible = obj as IConvertible;
if (convertible != null) {
WriteValue (output, convertible);
return;
}
try {
if (objectCache.ContainsKey (obj))
throw new InvalidOperationException ("Circular reference detected.");
objectCache.Add (obj, true);
Type closedIDict = GetClosedIDictionaryBase(valueType);
if (closedIDict != null) {
if (serializeGenericDictionaryMethods == null)
serializeGenericDictionaryMethods = new Dictionary <Type, MethodInfo> ();
MethodInfo mi;
if (!serializeGenericDictionaryMethods.TryGetValue (closedIDict, out mi)) {
Type[] types = closedIDict.GetGenericArguments ();
mi = serializeGenericDictionary.MakeGenericMethod (types [0], types [1]);
serializeGenericDictionaryMethods.Add (closedIDict, mi);
}
mi.Invoke (this, new object[] {output, obj});
return;
}
IDictionary dict = obj as IDictionary;
if (dict != null) {
SerializeDictionary (output, dict);
return;
}
IEnumerable enumerable = obj as IEnumerable;
if (enumerable != null) {
SerializeEnumerable (output, enumerable);
return;
}
SerializeArbitraryObject (output, obj, valueType);
} finally {
objectCache.Remove (obj);
}
}
Type GetClosedIDictionaryBase(Type t) {
if(t.IsGenericType && typeof (IDictionary <,>).IsAssignableFrom (t.GetGenericTypeDefinition ()))
return t;
foreach(Type iface in t.GetInterfaces()) {
if(iface.IsGenericType && typeof (IDictionary <,>).IsAssignableFrom (iface.GetGenericTypeDefinition ()))
return iface;
}
return null;
}
bool ShouldIgnoreMember (MemberInfo mi, out MethodInfo getMethod)
{
getMethod = null;
if (mi == null)
return true;
if (mi.IsDefined (typeof (ScriptIgnoreAttribute), true))
return true;
FieldInfo fi = mi as FieldInfo;
if (fi != null)
return false;
PropertyInfo pi = mi as PropertyInfo;
if (pi == null)
return true;
getMethod = pi.GetGetMethod ();
if (getMethod == null || getMethod.GetParameters ().Length > 0) {
getMethod = null;
return true;
}
return false;
}
object GetMemberValue (object obj, MemberInfo mi)
{
FieldInfo fi = mi as FieldInfo;
if (fi != null)
return fi.GetValue (obj);
MethodInfo method = mi as MethodInfo;
if (method == null)
throw new InvalidOperationException ("Member is not a method (internal error).");
object ret;
try {
ret = method.Invoke (obj, null);
} catch (TargetInvocationException niex) {
if (niex.InnerException is NotImplementedException) {
Console.WriteLine ("!!! COMPATIBILITY WARNING. FEATURE NOT IMPLEMENTED. !!!");
Console.WriteLine (niex);
Console.WriteLine ("!!! RETURNING NULL. PLEASE LET MONO DEVELOPERS KNOW ABOUT THIS EXCEPTION. !!!");
return null;
}
throw;
}
return ret;
}
void SerializeArbitraryObject (StringBuilder output, object obj, Type type)
{
StringBuilderExtensions.AppendCount (output, maxJsonLength, "{");
bool first = true;
if (typeResolver != null) {
string typeId = typeResolver.ResolveTypeId (type);
if (!String.IsNullOrEmpty (typeId)) {
WriteDictionaryEntry (output, first, JavaScriptSerializer.SerializedTypeNameKey, typeId);
first = false;
}
}
SerializeMembers <FieldInfo> (type.GetFields (BindingFlags.Public | BindingFlags.Instance), obj, output, ref first);
SerializeMembers <PropertyInfo> (type.GetProperties (BindingFlags.Public | BindingFlags.Instance), obj, output, ref first);
StringBuilderExtensions.AppendCount (output, maxJsonLength, "}");
}
void SerializeMembers <T> (T[] members, object obj, StringBuilder output, ref bool first) where T: MemberInfo
{
MemberInfo member;
MethodInfo getMethod;
string name;
foreach (T mi in members) {
if (ShouldIgnoreMember (mi as MemberInfo, out getMethod))
continue;
name = mi.Name;
if (getMethod != null)
member = getMethod;
else
member = mi;
WriteDictionaryEntry (output, first, name, GetMemberValue (obj, member));
if (first)
first = false;
}
}
void SerializeEnumerable (StringBuilder output, IEnumerable enumerable)
{
StringBuilderExtensions.AppendCount (output, maxJsonLength, "[");
bool first = true;
foreach (object value in enumerable) {
if (!first)
StringBuilderExtensions.AppendCount (output, maxJsonLength, ',');
SerializeValue (value, output);
if (first)
first = false;
}
StringBuilderExtensions.AppendCount (output, maxJsonLength, "]");
}
void SerializeDictionary (StringBuilder output, IDictionary dict)
{
StringBuilderExtensions.AppendCount (output, maxJsonLength, "{");
bool first = true;
foreach (DictionaryEntry entry in dict) {
WriteDictionaryEntry (output, first, entry.Key as string, entry.Value);
if (first)
first = false;
}
StringBuilderExtensions.AppendCount (output, maxJsonLength, "}");
}
void SerializeGenericDictionary <TKey, TValue> (StringBuilder output, IDictionary <TKey, TValue> dict)
{
StringBuilderExtensions.AppendCount (output, maxJsonLength, "{");
bool first = true;
foreach (KeyValuePair <TKey, TValue> kvp in dict)
{
var key = typeof(TKey) == typeof(Guid) ? kvp.Key.ToString() : kvp.Key as string;
WriteDictionaryEntry (output, first, key, kvp.Value);
if (first)
first = false;
}
StringBuilderExtensions.AppendCount (output, maxJsonLength, "}");
}
void WriteDictionaryEntry (StringBuilder output, bool skipComma, string key, object value)
{
if (key == null)
throw new InvalidOperationException ("Only dictionaries with keys convertible to string, or guid keys are supported.");
if (!skipComma)
StringBuilderExtensions.AppendCount (output, maxJsonLength, ',');
WriteValue (output, key);
StringBuilderExtensions.AppendCount (output, maxJsonLength, ':');
SerializeValue (value, output);
}
void WriteEnumValue (StringBuilder output, object value, TypeCode typeCode)
{
switch (typeCode) {
case TypeCode.SByte:
StringBuilderExtensions.AppendCount (output, maxJsonLength, (sbyte)value);
return;
case TypeCode.Int16:
StringBuilderExtensions.AppendCount (output, maxJsonLength, (short)value);
return;
case TypeCode.UInt16:
StringBuilderExtensions.AppendCount (output, maxJsonLength, (ushort)value);
return;
case TypeCode.Int32:
StringBuilderExtensions.AppendCount (output, maxJsonLength, (int)value);
return;
case TypeCode.Byte:
StringBuilderExtensions.AppendCount (output, maxJsonLength, (byte)value);
return;
case TypeCode.UInt32:
StringBuilderExtensions.AppendCount (output, maxJsonLength, (uint)value);
return;
case TypeCode.Int64:
StringBuilderExtensions.AppendCount (output, maxJsonLength, (long)value);
return;
case TypeCode.UInt64:
StringBuilderExtensions.AppendCount (output, maxJsonLength, (ulong)value);
return;
default:
throw new InvalidOperationException (String.Format ("Invalid type code for enum: {0}", typeCode));
}
}
void WriteValue (StringBuilder output, float value)
{
StringBuilderExtensions.AppendCount (output, maxJsonLength, value.ToString ("r",Json.DefaultNumberFormatInfo));
}
void WriteValue (StringBuilder output, double value)
{
StringBuilderExtensions.AppendCount(output, maxJsonLength, value.ToString("r",Json.DefaultNumberFormatInfo));
}
void WriteValue (StringBuilder output, Guid value)
{
WriteValue (output, value.ToString ());
}
void WriteValue (StringBuilder output, Uri value)
{
WriteValue (output, value.GetComponents (UriComponents.AbsoluteUri, UriFormat.UriEscaped));
}
void WriteValue (StringBuilder output, DateTime value)
{
DateTime time = value.ToUniversalTime();
string suffix = "";
if (value.Kind != DateTimeKind.Utc) {
TimeSpan localTZOffset;
if (value > time) {
localTZOffset = value - time;
suffix = "+";
}
else {
localTZOffset = time - value;
suffix = "-";
}
suffix += localTZOffset.ToString("hhmm");
}
if (time < MinimumJavaScriptDate)
time = MinimumJavaScriptDate;
long ticks = (time.Ticks - InitialJavaScriptDateTicks) / (long)10000;
StringBuilderExtensions.AppendCount(output, maxJsonLength, "\"\\/Date(" + ticks + suffix + ")\\/\"");
}
void WriteValue (StringBuilder output, IConvertible value)
{
StringBuilderExtensions.AppendCount (output, maxJsonLength, value.ToString (CultureInfo.InvariantCulture));
}
void WriteValue (StringBuilder output, bool value)
{
StringBuilderExtensions.AppendCount (output, maxJsonLength, value ? "true" : "false");
}
void WriteValue (StringBuilder output, char value)
{
if (value == '\0') {
StringBuilderExtensions.AppendCount (output, maxJsonLength, "null");
return;
}
WriteValue (output, value.ToString ());
}
void WriteValue (StringBuilder output, string value)
{
if (String.IsNullOrEmpty (value)) {
StringBuilderExtensions.AppendCount (output, maxJsonLength, "\"\"");
return;
}
StringBuilderExtensions.AppendCount (output, maxJsonLength, "\"");
char c;
for (int i = 0; i < value.Length; i++) {
c = value [i];
switch (c) {
case '\t':
StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\t");
break;
case '\n':
StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\n");
break;
case '\r':
StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\r");
break;
case '\f':
StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\f");
break;
case '\b':
StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\b");
break;
case '<':
StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\u003c");
break;
case '>':
StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\u003e");
break;
case '"':
StringBuilderExtensions.AppendCount (output, maxJsonLength, "\\\"");
break;
case '\'':
StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\u0027");
break;
case '\\':
StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\\");
break;
default:
if (c > '\u001f')
StringBuilderExtensions.AppendCount (output, maxJsonLength, c);
else {
output.Append("\\u00");
int intVal = (int) c;
StringBuilderExtensions.AppendCount (output, maxJsonLength, (char) ('0' + (intVal >> 4)));
intVal &= 0xf;
StringBuilderExtensions.AppendCount (output, maxJsonLength, (char) (intVal < 10 ? '0' + intVal : 'a' + (intVal - 10)));
}
break;
}
}
StringBuilderExtensions.AppendCount (output, maxJsonLength, "\"");
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Security;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.HttpSys.Internal;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
namespace Microsoft.AspNetCore.Server.HttpSys
{
internal sealed class Request
{
private X509Certificate2? _clientCert;
// TODO: https://github.com/aspnet/HttpSysServer/issues/231
// private byte[] _providedTokenBindingId;
// private byte[] _referredTokenBindingId;
private BoundaryType _contentBoundaryType;
private long? _contentLength;
private RequestStream? _nativeStream;
private AspNetCore.HttpSys.Internal.SocketAddress? _localEndPoint;
private AspNetCore.HttpSys.Internal.SocketAddress? _remoteEndPoint;
private IReadOnlyDictionary<int, ReadOnlyMemory<byte>>? _requestInfo;
private bool _isDisposed;
internal Request(RequestContext requestContext)
{
// TODO: Verbose log
RequestContext = requestContext;
_contentBoundaryType = BoundaryType.None;
RequestId = requestContext.RequestId;
// For HTTP/2 Http.Sys assigns each request a unique connection id for use with API calls, but the RawConnectionId represents the real connection.
UConnectionId = requestContext.ConnectionId;
RawConnectionId = requestContext.RawConnectionId;
SslStatus = requestContext.SslStatus;
KnownMethod = requestContext.VerbId;
Method = requestContext.GetVerb()!;
RawUrl = requestContext.GetRawUrl()!;
var cookedUrl = requestContext.GetCookedUrl();
QueryString = cookedUrl.GetQueryString() ?? string.Empty;
var rawUrlInBytes = requestContext.GetRawUrlInBytes();
var originalPath = RequestUriBuilder.DecodeAndUnescapePath(rawUrlInBytes);
PathBase = string.Empty;
Path = originalPath;
// 'OPTIONS * HTTP/1.1'
if (KnownMethod == HttpApiTypes.HTTP_VERB.HttpVerbOPTIONS && string.Equals(RawUrl, "*", StringComparison.Ordinal))
{
PathBase = string.Empty;
Path = string.Empty;
}
else
{
var prefix = requestContext.Server.Options.UrlPrefixes.GetPrefix((int)requestContext.UrlContext);
// Prefix may be null if the requested has been transfered to our queue
if (!(prefix is null))
{
if (originalPath.Length == prefix.PathWithoutTrailingSlash.Length)
{
// They matched exactly except for the trailing slash.
PathBase = originalPath;
Path = string.Empty;
}
else
{
// url: /base/path, prefix: /base/, base: /base, path: /path
// url: /, prefix: /, base: , path: /
PathBase = originalPath.Substring(0, prefix.PathWithoutTrailingSlash.Length); // Preserve the user input casing
Path = originalPath.Substring(prefix.PathWithoutTrailingSlash.Length);
}
}
else if (requestContext.Server.Options.UrlPrefixes.TryMatchLongestPrefix(IsHttps, cookedUrl.GetHost()!, originalPath, out var pathBase, out var path))
{
PathBase = pathBase;
Path = path;
}
}
ProtocolVersion = RequestContext.GetVersion();
Headers = new RequestHeaders(RequestContext);
User = RequestContext.GetUser();
if (IsHttps)
{
GetTlsHandshakeResults();
}
// GetTlsTokenBindingInfo(); TODO: https://github.com/aspnet/HttpSysServer/issues/231
// Finished directly accessing the HTTP_REQUEST structure.
RequestContext.ReleasePins();
// TODO: Verbose log parameters
}
internal ulong UConnectionId { get; }
internal ulong RawConnectionId { get; }
// No ulongs in public APIs...
public long ConnectionId => (long)RawConnectionId;
internal ulong RequestId { get; }
private SslStatus SslStatus { get; }
private RequestContext RequestContext { get; }
// With the leading ?, if any
public string QueryString { get; }
public long? ContentLength
{
get
{
if (_contentBoundaryType == BoundaryType.None)
{
// Note Http.Sys adds the Transfer-Encoding: chunked header to HTTP/2 requests with bodies for back compat.
var transferEncoding = Headers[HeaderNames.TransferEncoding].ToString();
if (string.Equals("chunked", transferEncoding.Trim(), StringComparison.OrdinalIgnoreCase))
{
_contentBoundaryType = BoundaryType.Chunked;
}
else
{
string? length = Headers[HeaderNames.ContentLength];
if (length != null &&
long.TryParse(length.Trim(), NumberStyles.None, CultureInfo.InvariantCulture.NumberFormat, out var value))
{
_contentBoundaryType = BoundaryType.ContentLength;
_contentLength = value;
}
else
{
_contentBoundaryType = BoundaryType.Invalid;
}
}
}
return _contentLength;
}
}
public RequestHeaders Headers { get; }
internal HttpApiTypes.HTTP_VERB KnownMethod { get; }
internal bool IsHeadMethod => KnownMethod == HttpApiTypes.HTTP_VERB.HttpVerbHEAD;
public string Method { get; }
public Stream Body => EnsureRequestStream() ?? Stream.Null;
private RequestStream? EnsureRequestStream()
{
if (_nativeStream == null && HasEntityBody)
{
_nativeStream = new RequestStream(RequestContext);
}
return _nativeStream;
}
public bool HasRequestBodyStarted => _nativeStream?.HasStarted ?? false;
public long? MaxRequestBodySize
{
get => EnsureRequestStream()?.MaxSize;
set
{
EnsureRequestStream();
if (_nativeStream != null)
{
_nativeStream.MaxSize = value;
}
}
}
public string PathBase { get; }
public string Path { get; }
public bool IsHttps => SslStatus != SslStatus.Insecure;
public string RawUrl { get; }
public Version ProtocolVersion { get; }
public bool HasEntityBody
{
get
{
// accessing the ContentLength property delay creates _contentBoundaryType
return (ContentLength.HasValue && ContentLength.Value > 0 && _contentBoundaryType == BoundaryType.ContentLength)
|| _contentBoundaryType == BoundaryType.Chunked;
}
}
private AspNetCore.HttpSys.Internal.SocketAddress RemoteEndPoint
{
get
{
if (_remoteEndPoint == null)
{
_remoteEndPoint = RequestContext.GetRemoteEndPoint()!;
}
return _remoteEndPoint;
}
}
private AspNetCore.HttpSys.Internal.SocketAddress LocalEndPoint
{
get
{
if (_localEndPoint == null)
{
_localEndPoint = RequestContext.GetLocalEndPoint()!;
}
return _localEndPoint;
}
}
// TODO: Lazy cache?
public IPAddress? RemoteIpAddress => RemoteEndPoint.GetIPAddress();
public IPAddress? LocalIpAddress => LocalEndPoint.GetIPAddress();
public int RemotePort => RemoteEndPoint.GetPort();
public int LocalPort => LocalEndPoint.GetPort();
public string Scheme => IsHttps ? Constants.HttpsScheme : Constants.HttpScheme;
// HTTP.Sys allows you to upgrade anything to opaque unless content-length > 0 or chunked are specified.
internal bool IsUpgradable => ProtocolVersion < HttpVersion.Version20 && !HasEntityBody && ComNetOS.IsWin8orLater;
internal WindowsPrincipal User { get; }
public SslProtocols Protocol { get; private set; }
public CipherAlgorithmType CipherAlgorithm { get; private set; }
public int CipherStrength { get; private set; }
public HashAlgorithmType HashAlgorithm { get; private set; }
public int HashStrength { get; private set; }
public ExchangeAlgorithmType KeyExchangeAlgorithm { get; private set; }
public int KeyExchangeStrength { get; private set; }
public IReadOnlyDictionary<int, ReadOnlyMemory<byte>> RequestInfo
{
get
{
if (_requestInfo == null)
{
_requestInfo = RequestContext.GetRequestInfo();
}
return _requestInfo;
}
}
private void GetTlsHandshakeResults()
{
var handshake = RequestContext.GetTlsHandshake();
Protocol = handshake.Protocol;
// The OS considers client and server TLS as different enum values. SslProtocols choose to combine those for some reason.
// We need to fill in the client bits so the enum shows the expected protocol.
// https://docs.microsoft.com/windows/desktop/api/schannel/ns-schannel-_secpkgcontext_connectioninfo
// Compare to https://referencesource.microsoft.com/#System/net/System/Net/SecureProtocols/_SslState.cs,8905d1bf17729de3
#pragma warning disable CS0618 // Type or member is obsolete
if ((Protocol & SslProtocols.Ssl2) != 0)
{
Protocol |= SslProtocols.Ssl2;
}
if ((Protocol & SslProtocols.Ssl3) != 0)
{
Protocol |= SslProtocols.Ssl3;
}
#pragma warning restore CS0618 // Type or member is obsolete
if ((Protocol & SslProtocols.Tls) != 0)
{
Protocol |= SslProtocols.Tls;
}
if ((Protocol & SslProtocols.Tls11) != 0)
{
Protocol |= SslProtocols.Tls11;
}
if ((Protocol & SslProtocols.Tls12) != 0)
{
Protocol |= SslProtocols.Tls12;
}
if ((Protocol & SslProtocols.Tls13) != 0)
{
Protocol |= SslProtocols.Tls13;
}
CipherAlgorithm = handshake.CipherType;
CipherStrength = (int)handshake.CipherStrength;
HashAlgorithm = handshake.HashType;
HashStrength = (int)handshake.HashStrength;
KeyExchangeAlgorithm = handshake.KeyExchangeType;
KeyExchangeStrength = (int)handshake.KeyExchangeStrength;
}
public X509Certificate2? ClientCertificate
{
get
{
if (_clientCert == null && SslStatus == SslStatus.ClientCert)
{
try
{
_clientCert = RequestContext.GetClientCertificate();
}
catch (CryptographicException ce)
{
Log.ErrorInReadingCertificate(RequestContext.Logger, ce);
}
catch (SecurityException se)
{
Log.ErrorInReadingCertificate(RequestContext.Logger, se);
}
}
return _clientCert;
}
}
public bool CanDelegate => !(HasRequestBodyStarted || RequestContext.Response.HasStarted);
// Populates the client certificate. The result may be null if there is no client cert.
// TODO: Does it make sense for this to be invoked multiple times (e.g. renegotiate)? Client and server code appear to
// enable this, but it's unclear what Http.Sys would do.
public async Task<X509Certificate2?> GetClientCertificateAsync(CancellationToken cancellationToken = default(CancellationToken))
{
if (SslStatus == SslStatus.Insecure)
{
// Non-SSL
return null;
}
// TODO: Verbose log
if (_clientCert != null)
{
return _clientCert;
}
cancellationToken.ThrowIfCancellationRequested();
var certLoader = new ClientCertLoader(RequestContext, cancellationToken);
try
{
await certLoader.LoadClientCertificateAsync();
// Populate the environment.
if (certLoader.ClientCert != null)
{
_clientCert = certLoader.ClientCert;
}
// TODO: Expose errors and exceptions?
}
catch (Exception)
{
if (certLoader != null)
{
certLoader.Dispose();
}
throw;
}
return _clientCert;
}
/* TODO: https://github.com/aspnet/WebListener/issues/231
private byte[] GetProvidedTokenBindingId()
{
return _providedTokenBindingId;
}
private byte[] GetReferredTokenBindingId()
{
return _referredTokenBindingId;
}
*/
// Only call from the constructor so we can directly access the native request blob.
// This requires Windows 10 and the following reg key:
// Set Key: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\HTTP\Parameters to Value: EnableSslTokenBinding = 1 [DWORD]
// Then for IE to work you need to set these:
// Key: HKLM\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_ENABLE_TOKEN_BINDING
// Value: "iexplore.exe"=dword:0x00000001
// Key: HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_ENABLE_TOKEN_BINDING
// Value: "iexplore.exe"=dword:00000001
// TODO: https://github.com/aspnet/WebListener/issues/231
// TODO: https://github.com/aspnet/WebListener/issues/204 Move to NativeRequestContext
/*
private unsafe void GetTlsTokenBindingInfo()
{
var nativeRequest = (HttpApi.HTTP_REQUEST_V2*)_nativeRequestContext.RequestBlob;
for (int i = 0; i < nativeRequest->RequestInfoCount; i++)
{
var pThisInfo = &nativeRequest->pRequestInfo[i];
if (pThisInfo->InfoType == HttpApi.HTTP_REQUEST_INFO_TYPE.HttpRequestInfoTypeSslTokenBinding)
{
var pTokenBindingInfo = (HttpApi.HTTP_REQUEST_TOKEN_BINDING_INFO*)pThisInfo->pInfo;
_providedTokenBindingId = TokenBindingUtil.GetProvidedTokenIdFromBindingInfo(pTokenBindingInfo, out _referredTokenBindingId);
}
}
}
*/
internal uint GetChunks(ref int dataChunkIndex, ref uint dataChunkOffset, byte[] buffer, int offset, int size)
{
return RequestContext.GetChunks(ref dataChunkIndex, ref dataChunkOffset, buffer, offset, size);
}
// should only be called from RequestContext
internal void Dispose()
{
if (!_isDisposed)
{
// TODO: Verbose log
_isDisposed = true;
RequestContext.Dispose();
(User?.Identity as WindowsIdentity)?.Dispose();
_nativeStream?.Dispose();
}
}
internal void SwitchToOpaqueMode()
{
if (_nativeStream == null)
{
_nativeStream = new RequestStream(RequestContext);
}
_nativeStream.SwitchToOpaqueMode();
}
private static class Log
{
private static readonly Action<ILogger, Exception?> _errorInReadingCertificate =
LoggerMessage.Define(LogLevel.Debug, LoggerEventIds.ErrorInReadingCertificate, "An error occurred reading the client certificate.");
public static void ErrorInReadingCertificate(ILogger logger, Exception exception)
{
_errorInReadingCertificate(logger, exception);
}
}
}
}
| |
// 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 Xunit;
using System;
using System.Collections;
using System.Collections.Specialized;
using GenStrings;
namespace System.Collections.Specialized.Tests
{
public class RemoveObjTests
{
public const int MAX_LEN = 50; // max length of random strings
[Fact]
public void Test01()
{
IntlStrings intl;
HybridDictionary hd;
const int BIG_LENGTH = 100;
// simple string values
string[] valuesShort =
{
"",
" ",
"$%^#",
System.DateTime.Today.ToString(),
Int32.MaxValue.ToString()
};
// keys for simple string values
string[] keysShort =
{
Int32.MaxValue.ToString(),
" ",
System.DateTime.Today.ToString(),
"",
"$%^#"
};
string[] valuesLong = new string[BIG_LENGTH];
string[] keysLong = new string[BIG_LENGTH];
int cnt = 0; // Count
// initialize IntStrings
intl = new IntlStrings();
for (int i = 0; i < BIG_LENGTH; i++)
{
valuesLong[i] = "Item" + i;
keysLong[i] = "keY" + i;
}
// [] HybridDictionary is constructed as expected
//-----------------------------------------------------------------
hd = new HybridDictionary();
// [] Remove() on empty dictionary
//
cnt = hd.Count;
try
{
hd.Remove(null);
Assert.False(true, string.Format("Error, no exception"));
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
Assert.False(true, string.Format("Error, unexpected exception: {0}", e.ToString()));
}
cnt = hd.Count;
hd.Remove("some_string");
if (hd.Count != cnt)
{
Assert.False(true, string.Format("Error, changed dictionary after Remove(some_string)"));
}
cnt = hd.Count;
hd.Remove(new Hashtable());
if (hd.Count != cnt)
{
Assert.False(true, string.Format("Error, changed dictionary after Remove(some_string)"));
}
//
// [] Remove() on short dictionary with simple strings
//
cnt = hd.Count;
int len = valuesShort.Length;
for (int i = 0; i < len; i++)
{
hd.Add(keysShort[i], valuesShort[i]);
}
if (hd.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, valuesShort.Length));
}
//
for (int i = 0; i < len; i++)
{
cnt = hd.Count;
hd.Remove(keysShort[i]);
if (hd.Count != cnt - 1)
{
Assert.False(true, string.Format("Error, failed to remove item", i));
}
if (hd.Contains(keysShort[i]))
{
Assert.False(true, string.Format("Error, removed wrong item", i));
}
// remove second time
hd.Remove(keysShort[i]);
if (hd.Count != cnt - 1)
{
Assert.False(true, string.Format("Error, failed when Remove() second time", i));
}
}
// [] Remove() on long dictionary with simple strings
//
hd.Clear();
cnt = hd.Count;
len = valuesLong.Length;
for (int i = 0; i < len; i++)
{
hd.Add(keysLong[i], valuesLong[i]);
}
if (hd.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len));
}
//
for (int i = 0; i < len; i++)
{
cnt = hd.Count;
hd.Remove(keysLong[i]);
if (hd.Count != cnt - 1)
{
Assert.False(true, string.Format("Error, failed to remove item", i));
}
if (hd.Contains(keysLong[i]))
{
Assert.False(true, string.Format("Error, removed wrong item", i));
}
// remove second time
hd.Remove(keysLong[i]);
if (hd.Count != cnt - 1)
{
Assert.False(true, string.Format("Error, failed when Remove() second time", i));
}
}
//
// [] Remove() on long dictionary with Intl strings
// Intl strings
//
len = valuesLong.Length;
string[] intlValues = new string[len * 2];
// fill array with unique strings
//
for (int i = 0; i < len * 2; i++)
{
string val = intl.GetRandomString(MAX_LEN);
while (Array.IndexOf(intlValues, val) != -1)
val = intl.GetRandomString(MAX_LEN);
intlValues[i] = val;
}
cnt = hd.Count;
for (int i = 0; i < len; i++)
{
hd.Add(intlValues[i + len], intlValues[i]);
}
if (hd.Count != (cnt + len))
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, cnt + len));
}
for (int i = 0; i < len; i++)
{
//
cnt = hd.Count;
hd.Remove(intlValues[i + len]);
if (hd.Count != cnt - 1)
{
Assert.False(true, string.Format("Error, failed to remove item", i));
}
if (hd.Contains(intlValues[i + len]))
{
Assert.False(true, string.Format("Error, removed wrong item", i));
}
}
// [] Remove() on short dictionary with Intl strings
//
len = valuesShort.Length;
hd.Clear();
cnt = hd.Count;
for (int i = 0; i < len; i++)
{
hd.Add(intlValues[i + len], intlValues[i]);
}
if (hd.Count != (cnt + len))
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, cnt + len));
}
for (int i = 0; i < len; i++)
{
//
cnt = hd.Count;
hd.Remove(intlValues[i + len]);
if (hd.Count != cnt - 1)
{
Assert.False(true, string.Format("Error, failed to remove item", i));
}
if (hd.Contains(intlValues[i + len]))
{
Assert.False(true, string.Format("Error, removed wrong item", i));
}
}
//
// Case sensitivity
// [] Case sensitivity - hashtable
//
len = valuesLong.Length;
hd.Clear();
//
// will use first half of array as values and second half as keys
//
for (int i = 0; i < len; i++)
{
hd.Add(keysLong[i].ToUpper(), valuesLong[i].ToUpper()); // adding uppercase strings
}
//
for (int i = 0; i < len; i++)
{
// uppercase key
cnt = hd.Count;
hd.Remove(keysLong[i].ToUpper());
if (hd.Count != cnt - 1)
{
Assert.False(true, string.Format("Error, failed to remove item", i));
}
if (hd.Contains(keysLong[i].ToUpper()))
{
Assert.False(true, string.Format("Error, removed wrong item", i));
}
}
hd.Clear();
//
// will use first half of array as values and second half as keys
//
for (int i = 0; i < len; i++)
{
hd.Add(keysLong[i].ToUpper(), valuesLong[i].ToUpper()); // adding uppercase strings
}
// LD is case-sensitive by default
for (int i = 0; i < len; i++)
{
// lowercase key
cnt = hd.Count;
hd.Remove(keysLong[i].ToLower());
if (hd.Count != cnt)
{
Assert.False(true, string.Format("Error, failed: removed item using lowercase key", i));
}
}
//
// [] Case sensitivity - list
len = valuesShort.Length;
hd.Clear();
//
// will use first half of array as values and second half as keys
//
for (int i = 0; i < len; i++)
{
hd.Add(keysLong[i].ToUpper(), valuesLong[i].ToUpper()); // adding uppercase strings
}
//
for (int i = 0; i < len; i++)
{
// uppercase key
cnt = hd.Count;
hd.Remove(keysLong[i].ToUpper());
if (hd.Count != cnt - 1)
{
Assert.False(true, string.Format("Error, failed to remove item", i));
}
if (hd.Contains(keysLong[i].ToUpper()))
{
Assert.False(true, string.Format("Error, removed wrong item", i));
}
}
hd.Clear();
//
// will use first half of array as values and second half as keys
//
for (int i = 0; i < len; i++)
{
hd.Add(keysLong[i].ToUpper(), valuesLong[i].ToUpper()); // adding uppercase strings
}
// LD is case-sensitive by default
for (int i = 0; i < len; i++)
{
// lowercase key
cnt = hd.Count;
hd.Remove(keysLong[i].ToLower());
if (hd.Count != cnt)
{
Assert.False(true, string.Format("Error, failed: removed item using lowercase key", i));
}
}
//
// [] Remove() on case-insensitive HD - list
//
hd = new HybridDictionary(true);
len = valuesShort.Length;
hd.Clear();
for (int i = 0; i < len; i++)
{
hd.Add(keysLong[i].ToLower(), valuesLong[i].ToLower());
}
if (hd.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len));
}
for (int i = 0; i < len; i++)
{
cnt = hd.Count;
hd.Remove(keysLong[i].ToUpper());
if (hd.Count != cnt - 1)
{
Assert.False(true, string.Format("Error, failed to remove item", i));
}
if (hd.Contains(keysLong[i].ToLower()))
{
Assert.False(true, string.Format("Error, removed wrong item", i));
}
}
//
// [] Remove() on case-insensitive HD - hashtable
//
hd = new HybridDictionary(true);
len = valuesLong.Length;
hd.Clear();
for (int i = 0; i < len; i++)
{
hd.Add(keysLong[i].ToLower(), valuesLong[i].ToLower());
}
if (hd.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len));
}
for (int i = 0; i < len; i++)
{
cnt = hd.Count;
hd.Remove(keysLong[i].ToUpper());
if (hd.Count != cnt - 1)
{
Assert.False(true, string.Format("Error, failed to remove item", i));
}
if (hd.Contains(keysLong[i].ToLower()))
{
Assert.False(true, string.Format("Error, removed wrong item", i));
}
}
//
// [] Remove(null) from filled HD - list
//
hd = new HybridDictionary();
len = valuesShort.Length;
hd.Clear();
for (int i = 0; i < len; i++)
{
hd.Add(keysShort[i], valuesShort[i]);
}
try
{
hd.Remove(null);
Assert.False(true, string.Format("Error, no exception"));
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
Assert.False(true, string.Format("Error, unexpected exception: {0}", e.ToString()));
}
//
// [] Remove(null) from filled HD - hashtable
//
hd = new HybridDictionary();
len = valuesLong.Length;
hd.Clear();
for (int i = 0; i < len; i++)
{
hd.Add(keysLong[i], valuesLong[i]);
}
try
{
hd.Remove(null);
Assert.False(true, string.Format("Error, no exception"));
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
Assert.False(true, string.Format("Error, unexpected exception: {0}", e.ToString()));
}
//
// [] Remove(special_object) from filled HD - list
//
hd = new HybridDictionary();
hd.Clear();
len = 2;
ArrayList[] b = new ArrayList[len];
Hashtable[] lbl = new Hashtable[len];
for (int i = 0; i < len; i++)
{
lbl[i] = new Hashtable();
b[i] = new ArrayList();
hd.Add(lbl[i], b[i]);
}
if (hd.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len));
}
for (int i = 0; i < len; i++)
{
cnt = hd.Count;
hd.Remove(lbl[i]);
if (hd.Count != cnt - 1)
{
Assert.False(true, string.Format("Error, failed to remove special object"));
}
if (hd.Contains(lbl[i]))
{
Assert.False(true, string.Format("Error, removed wrong special object"));
}
}
//
// [] Remove(special_object) from filled HD - hashtable
//
hd = new HybridDictionary();
hd.Clear();
len = 40;
b = new ArrayList[len];
lbl = new Hashtable[len];
for (int i = 0; i < len; i++)
{
lbl[i] = new Hashtable();
b[i] = new ArrayList();
hd.Add(lbl[i], b[i]);
}
if (hd.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len));
}
for (int i = 0; i < len; i++)
{
cnt = hd.Count;
hd.Remove(lbl[i]);
if (hd.Count != cnt - 1)
{
Assert.False(true, string.Format("Error, failed to remove special object"));
}
if (hd.Contains(lbl[i]))
{
Assert.False(true, string.Format("Error, removed wrong special object"));
}
}
}
}
}
| |
/*
Copyright 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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache 2 License for the specific language governing permissions and
limitations under the License. */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Microsoft.Practices.ServiceLocation;
using MileageStats.Domain.Handlers;
using MileageStats.Domain.Models;
using MileageStats.Web.Models;
using MileageStats.Web.Properties;
using System.Net;
using System.Web;
namespace MileageStats.Web.Controllers
{
[Authorize]
public class ReminderController : BaseController
{
public ReminderController(GetUserByClaimId getUser, IServiceLocator serviceLocator)
: base(getUser, serviceLocator)
{
}
[HttpPost]
public ActionResult OverdueList()
{
var list = Using<GetOverdueRemindersForUser>().Execute(CurrentUserId);
var reminders = from reminder in list
let vehicle = Using<GetVehicleById>().Execute(CurrentUserId, reminder.VehicleId)
let title = GetFullTitle(reminder, vehicle)
select new OverdueReminderViewModel { FullTitle = title, Reminder = reminder };
var viewModel = new JsonRemindersOverdueListViewModel { Reminders = reminders.ToList() };
return Json(viewModel);
}
public ActionResult Details(int vehicleId, int id)
{
var reminder = Using<GetReminder>().Execute(id);
var viewModel = new ReminderSummaryModel(reminder);
return new ContentTypeAwareResult(viewModel);
}
public ActionResult ListPartial(int vehicleId)
{
var reminders = GetListOfReminderListViewModels(vehicleId)
.Where(x => x.Status != ReminderState.Fulfilled)
.SelectMany(x => x.Reminders)
.ToList();
return new ContentTypeAwareResult(reminders);
}
public ActionResult List(int vehicleId)
{
var listOfReminderListViewModels = GetListOfReminderListViewModels(vehicleId);
return new ContentTypeAwareResult(listOfReminderListViewModels);
}
private List<ReminderListViewModel> GetListOfReminderListViewModels(int vehicleId)
{
var vehicle = Using<GetVehicleById>().Execute(CurrentUserId, vehicleId);
var reminders = Using<GetAllRemindersForVehicle>().Execute(vehicleId);
foreach (var reminder in reminders)
{
reminder.CalculateIsOverdue(vehicle.Odometer ?? 0);
}
var reminderSummaryModels = reminders.Select(r => new ReminderSummaryModel(r));
var groups = from reminder in reminderSummaryModels
group reminder by reminder.Status
into grouping
select new ReminderListViewModel
{
Status = grouping.Key,
Reminders = grouping
};
var listOfReminderListViewModels = groups.ToList();
listOfReminderListViewModels.Sort(new ReminderListViewModelCompare());
return listOfReminderListViewModels;
}
public ActionResult Add(int vehicleId)
{
var vehicle = Using<GetVehicleById>()
.Execute(CurrentUserId, vehicleId);
if (vehicle == null)
throw new HttpException((int)HttpStatusCode.NotFound,
Messages.ReminderController_VehicleNotFound);
var reminder = new ReminderFormModel
{
VehicleId = vehicleId,
DueDateDay = DateTime.Now.Day.ToString(),
DueDateMonth = DateTime.Now.Month.ToString(),
DueDateYear = DateTime.Now.Year.ToString()
};
return new ContentTypeAwareResult(reminder);
}
[HttpPost]
[ValidateInput(false)]
[ValidateAntiForgeryToken]
public ActionResult Add(int vehicleId, ReminderFormModel reminder)
{
if ((reminder != null) && ModelState.IsValid)
{
var errors = Using<CanAddReminder>().Execute(CurrentUserId, reminder);
ModelState.AddModelErrors(errors, "Add");
if (ModelState.IsValid)
{
Using<AddReminderToVehicle>().Execute(CurrentUserId, vehicleId, reminder);
this.SetConfirmationMessage(Messages.ReminderController_ReminderAdded);
return RedirectToAction("List", "Reminder", new { vehicleId });
}
}
this.SetAlertMessage(Messages.PleaseFixInvalidData);
return new ContentTypeAwareResult(reminder);
}
public ActionResult Fulfill(int vehicleId, int id)
{
Using<FulfillReminder>().Execute(CurrentUserId, id);
this.SetConfirmationMessage(Messages.ReminderController_ReminderFulfilled);
return new ContentTypeAwareResult
{
WhenHtml = (x, v, t) => RedirectToAction("List", "Reminder", new { vehicleId })
};
}
[HttpPost]
public ActionResult ImminentReminders()
{
var imminentReminders = Using<GetImminentRemindersForUser>().Execute(CurrentUserId, DateTime.UtcNow);
return new ContentTypeAwareResult(imminentReminders);
}
private IEnumerable<Reminder> GetUnfulfilledRemindersByVehicle(int vehicleId)
{
var vehicle = Using<GetVehicleById>()
.Execute(CurrentUserId, vehicleId);
if (vehicle == null)
throw new HttpException((int)HttpStatusCode.NotFound,
Messages.ReminderController_VehicleNotFound);
var reminders = Using<GetUnfulfilledRemindersForVehicle>()
.Execute(CurrentUserId, vehicleId, vehicle.Odometer ?? 0);
return reminders;
}
private static string GetFullTitle(ReminderModel overdueReminder, VehicleModel vehicle)
{
string fullTitle = overdueReminder.Title + " | " + vehicle.Name + " @ ";
if (overdueReminder.DueDate != null)
{
fullTitle += overdueReminder.DueDate.Value.ToString("d");
}
if (overdueReminder.DueDistance != null)
{
if (overdueReminder.DueDate != null)
{
fullTitle += " or ";
}
fullTitle += overdueReminder.DueDistance.Value.ToString();
}
return fullTitle;
}
}
public class ReminderListViewModelCompare : IComparer<ReminderListViewModel>
{
public int Compare(ReminderListViewModel x, ReminderListViewModel y)
{
return (int)x.Status - (int)y.Status;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace System.Reflection.Internal
{
[DebuggerDisplay("{GetDebuggerDisplay(),nq}")]
internal unsafe struct MemoryBlock
{
internal readonly byte* Pointer;
internal readonly int Length;
internal MemoryBlock(byte* buffer, int length)
{
Debug.Assert(length >= 0 && (buffer != null || length == 0));
this.Pointer = buffer;
this.Length = length;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void CheckBounds(int offset, int byteCount)
{
if (unchecked((ulong)(uint)offset + (uint)byteCount) > (ulong)Length)
{
ThrowOutOfBounds();
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowOutOfBounds()
{
throw new BadImageFormatException(MetadataResources.OutOfBoundsRead);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowReferenceOverflow()
{
throw new BadImageFormatException(MetadataResources.RowIdOrHeapOffsetTooLarge);
}
internal byte[] ToArray()
{
return Pointer == null ? null : PeekBytes(0, Length);
}
private string GetDebuggerDisplay()
{
if (Pointer == null)
{
return "<null>";
}
int displayedBytes;
return GetDebuggerDisplay(out displayedBytes);
}
internal string GetDebuggerDisplay(out int displayedBytes)
{
displayedBytes = Math.Min(Length, 64);
string result = BitConverter.ToString(PeekBytes(0, displayedBytes));
if (displayedBytes < Length)
{
result += "-...";
}
return result;
}
internal MemoryBlock GetMemoryBlockAt(int offset, int length)
{
CheckBounds(offset, length);
return new MemoryBlock(Pointer + offset, length);
}
internal Byte PeekByte(int offset)
{
CheckBounds(offset, sizeof(Byte));
return Pointer[offset];
}
internal Int32 PeekInt32(int offset)
{
CheckBounds(offset, sizeof(Int32));
return *(Int32*)(Pointer + offset);
}
internal UInt32 PeekUInt32(int offset)
{
CheckBounds(offset, sizeof(UInt32));
return *(UInt32*)(Pointer + offset);
}
/// <summary>
/// Decodes a compressed integer value starting at offset.
/// See Metadata Specification section II.23.2: Blobs and signatures.
/// </summary>
/// <param name="offset">Offset to the start of the compressed data.</param>
/// <param name="numberOfBytesRead">Bytes actually read.</param>
/// <returns>
/// Value between 0 and 0x1fffffff, or <see cref="BlobReader.InvalidCompressedInteger"/> if the value encoding is invalid.
/// </returns>
internal int PeekCompressedInteger(int offset, out int numberOfBytesRead)
{
CheckBounds(offset, 0);
byte* ptr = Pointer + offset;
long limit = Length - offset;
if (limit == 0)
{
numberOfBytesRead = 0;
return BlobReader.InvalidCompressedInteger;
}
byte headerByte = ptr[0];
if ((headerByte & 0x80) == 0)
{
numberOfBytesRead = 1;
return headerByte;
}
else if ((headerByte & 0x40) == 0)
{
if (limit >= 2)
{
numberOfBytesRead = 2;
return ((headerByte & 0x3f) << 8) | ptr[1];
}
}
else if ((headerByte & 0x20) == 0)
{
if (limit >= 4)
{
numberOfBytesRead = 4;
return ((headerByte & 0x1f) << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3];
}
}
numberOfBytesRead = 0;
return BlobReader.InvalidCompressedInteger;
}
internal UInt16 PeekUInt16(int offset)
{
CheckBounds(offset, sizeof(UInt16));
return *(UInt16*)(Pointer + offset);
}
// When reference has tag bits.
internal uint PeekTaggedReference(int offset, bool smallRefSize)
{
return PeekReferenceUnchecked(offset, smallRefSize);
}
// Use when searching for a tagged or non-tagged reference.
// The result may be an invalid reference and shall only be used to compare with a valid reference.
internal uint PeekReferenceUnchecked(int offset, bool smallRefSize)
{
return smallRefSize ? PeekUInt16(offset) : PeekUInt32(offset);
}
// When reference has at most 24 bits.
internal int PeekReference(int offset, bool smallRefSize)
{
if (smallRefSize)
{
return PeekUInt16(offset);
}
uint value = PeekUInt32(offset);
if (!TokenTypeIds.IsValidRowId(value))
{
ThrowReferenceOverflow();
}
return (int)value;
}
// #String, #Blob heaps
internal int PeekHeapReference(int offset, bool smallRefSize)
{
if (smallRefSize)
{
return PeekUInt16(offset);
}
uint value = PeekUInt32(offset);
if (!HeapHandleType.IsValidHeapOffset(value))
{
ThrowReferenceOverflow();
}
return (int)value;
}
internal Guid PeekGuid(int offset)
{
CheckBounds(offset, sizeof(Guid));
return *(Guid*)(Pointer + offset);
}
internal string PeekUtf16(int offset, int byteCount)
{
CheckBounds(offset, byteCount);
// doesn't allocate a new string if byteCount == 0
return new string((char*)(Pointer + offset), 0, byteCount / sizeof(char));
}
internal string PeekUtf8(int offset, int byteCount)
{
CheckBounds(offset, byteCount);
return Encoding.UTF8.GetString(Pointer + offset, byteCount);
}
/// <summary>
/// Read UTF8 at the given offset up to the given terminator, null terminator, or end-of-block.
/// </summary>
/// <param name="offset">Offset in to the block where the UTF8 bytes start.</param>
/// <param name="prefix">UTF8 encoded prefix to prepend to the bytes at the offset before decoding.</param>
/// <param name="utf8Decoder">The UTF8 decoder to use that allows user to adjust fallback and/or reuse existing strings without allocating a new one.</param>
/// <param name="numberOfBytesRead">The number of bytes read, which includes the terminator if we did not hit the end of the block.</param>
/// <param name="terminator">A character in the ASCII range that marks the end of the string.
/// If a value other than '\0' is passed we still stop at the null terminator if encountered first.</param>
/// <returns>The decoded string.</returns>
internal string PeekUtf8NullTerminated(int offset, byte[] prefix, MetadataStringDecoder utf8Decoder, out int numberOfBytesRead, char terminator = '\0')
{
Debug.Assert(terminator <= 0x7F);
CheckBounds(offset, 0);
int length = GetUtf8NullTerminatedLength(offset, out numberOfBytesRead, terminator);
return EncodingHelper.DecodeUtf8(Pointer + offset, length, prefix, utf8Decoder);
}
/// <summary>
/// Get number of bytes from offset to given terminator, null terminator, or end-of-block (whichever comes first).
/// Returned length does not include the terminator, but numberOfBytesRead out parameter does.
/// </summary>
/// <param name="offset">Offset in to the block where the UTF8 bytes start.</param>
/// <param name="terminator">A character in the ASCII range that marks the end of the string.
/// If a value other than '\0' is passed we still stop at the null terminator if encountered first.</param>
/// <param name="numberOfBytesRead">The number of bytes read, which includes the terminator if we did not hit the end of the block.</param>
/// <returns>Length (byte count) not including terminator.</returns>
internal int GetUtf8NullTerminatedLength(int offset, out int numberOfBytesRead, char terminator = '\0')
{
CheckBounds(offset, 0);
Debug.Assert(terminator <= 0x7f);
byte* start = Pointer + offset;
byte* end = Pointer + Length;
byte* current = start;
while (current < end)
{
byte b = *current;
if (b == 0 || b == terminator)
{
break;
}
current++;
}
int length = (int)(current - start);
numberOfBytesRead = length;
if (current < end)
{
// we also read the terminator
numberOfBytesRead++;
}
return length;
}
internal int Utf8NullTerminatedOffsetOfAsciiChar(int startOffset, char asciiChar)
{
CheckBounds(startOffset, 0);
Debug.Assert(asciiChar != 0 && asciiChar <= 0x7f);
for (int i = startOffset; i < Length; i++)
{
byte b = Pointer[i];
if (b == 0)
{
break;
}
if (b == asciiChar)
{
return i;
}
}
return -1;
}
// comparison stops at null terminator, terminator parameter, or end-of-block -- whichever comes first.
internal bool Utf8NullTerminatedEquals(int offset, string text, MetadataStringDecoder utf8Decoder, char terminator = '\0')
{
FastComparisonResult result = Utf8NullTerminatedFastCompare(offset, text, terminator);
switch (result)
{
case FastComparisonResult.Equal:
return true;
case FastComparisonResult.IsPrefix:
case FastComparisonResult.Unequal:
return false;
default:
Debug.Assert(result == FastComparisonResult.Inconclusive);
int bytesRead;
string decoded = PeekUtf8NullTerminated(offset, null, utf8Decoder, out bytesRead, terminator);
return decoded.Equals(text, StringComparison.Ordinal);
}
}
// comparison stops at null terminator, terminator parameter, or end-of-block -- whichever comes first.
internal bool Utf8NullTerminatedStartsWith(int offset, string text, MetadataStringDecoder utf8Decoder, char terminator = '\0')
{
FastComparisonResult result = Utf8NullTerminatedFastCompare(offset, text, terminator);
switch (result)
{
case FastComparisonResult.Equal:
case FastComparisonResult.IsPrefix:
return true;
case FastComparisonResult.Unequal:
return false;
default:
Debug.Assert(result == FastComparisonResult.Inconclusive);
int bytesRead;
string decoded = PeekUtf8NullTerminated(offset, null, utf8Decoder, out bytesRead, terminator);
return decoded.StartsWith(text, StringComparison.Ordinal);
}
}
internal enum FastComparisonResult
{
Equal,
IsPrefix,
Unequal,
Inconclusive
}
// comparison stops at null terminator, terminator parameter, or end-of-block -- whichever comes first.
private FastComparisonResult Utf8NullTerminatedFastCompare(int offset, string text, char terminator = '\0')
{
CheckBounds(offset, 0);
Debug.Assert(terminator <= 0x7F);
byte* startPointer = Pointer + offset;
byte* endPointer = Pointer + Length;
byte* currentPointer = startPointer;
int currentIndex = 0;
while (currentIndex < text.Length && currentPointer != endPointer)
{
byte currentByte = *currentPointer++;
if (currentByte == 0 || currentByte == terminator)
{
break;
}
char currentChar = text[currentIndex++];
if ((currentByte & 0x80) == 0)
{
// current byte is in ascii range.
// --> strings are unequal if current char and current byte are unequal
if (currentChar != currentByte)
{
return FastComparisonResult.Unequal;
}
}
else if (currentChar <= 0x7F)
{
// current byte is not in ascii range, but current char is.
// --> strings are unequal.
return FastComparisonResult.Unequal;
}
else
{
// uncommon non-ascii case --> fall back to slow allocating comparison.
return FastComparisonResult.Inconclusive;
}
}
if (currentIndex != text.Length)
{
return FastComparisonResult.Unequal;
}
if (currentPointer != endPointer && *currentPointer != 0 && *currentPointer != terminator)
{
return FastComparisonResult.IsPrefix;
}
return FastComparisonResult.Equal;
}
// comparison stops at null terminator, terminator parameter, or end-of-block -- whichever comes first.
internal bool Utf8NullTerminatedStringStartsWithAsciiPrefix(int offset, string asciiPrefix)
{
// Assumes stringAscii only contains ASCII characters and no nil characters.
CheckBounds(offset, 0);
// Make sure that we won't read beyond the block even if the block doesn't end with 0 byte.
if (asciiPrefix.Length > Length - offset)
{
return false;
}
byte* p = Pointer + offset;
for (int i = 0; i < asciiPrefix.Length; i++)
{
Debug.Assert((int)asciiPrefix[i] > 0 && (int)asciiPrefix[i] <= 0x7f);
if (asciiPrefix[i] != *p)
{
return false;
}
p++;
}
return true;
}
internal int CompareUtf8NullTerminatedStringWithAsciiString(int offset, string asciiString)
{
// Assumes stringAscii only contains ASCII characters and no nil characters.
CheckBounds(offset, 0);
byte* p = Pointer + offset;
int limit = Length - offset;
for (int i = 0; i < asciiString.Length; i++)
{
Debug.Assert((int)asciiString[i] > 0 && (int)asciiString[i] <= 0x7f);
if (i > limit)
{
// Heap value is shorter.
return -1;
}
if (*p != asciiString[i])
{
// If we hit the end of the heap value (*p == 0)
// the heap value is shorter than the string, so we return negative value.
return *p - asciiString[i];
}
p++;
}
// Either the heap value name matches exactly the given string or
// it is longer so it is considered "greater".
return (*p == 0) ? 0 : +1;
}
internal byte[] PeekBytes(int offset, int byteCount)
{
CheckBounds(offset, byteCount);
if (byteCount == 0)
{
return EmptyArray<byte>.Instance;
}
byte[] result = new byte[byteCount];
Marshal.Copy((IntPtr)(Pointer + offset), result, 0, byteCount);
return result;
}
internal int IndexOf(byte b, int start)
{
CheckBounds(start, 0);
byte* p = Pointer + start;
byte* end = Pointer + Length;
while (p < end)
{
if (*p == b)
{
return (int)(p - Pointer);
}
p++;
}
return -1;
}
// same as Array.BinarySearch, but without using IComparer
internal int BinarySearch(string[] asciiKeys, int offset)
{
var low = 0;
var high = asciiKeys.Length - 1;
while (low <= high)
{
var middle = low + ((high - low) >> 1);
var midValue = asciiKeys[middle];
int comparison = CompareUtf8NullTerminatedStringWithAsciiString(offset, midValue);
if (comparison == 0)
{
return middle;
}
if (comparison < 0)
{
high = middle - 1;
}
else
{
low = middle + 1;
}
}
return ~low;
}
// Returns row number [0..RowCount) or -1 if not found.
internal int BinarySearchForSlot(
int rowCount,
int rowSize,
int referenceOffset,
uint referenceValue,
bool isReferenceSmall)
{
int startRowNumber = 0;
int endRowNumber = rowCount - 1;
uint startValue = PeekReferenceUnchecked(startRowNumber * rowSize + referenceOffset, isReferenceSmall);
uint endValue = PeekReferenceUnchecked(endRowNumber * rowSize + referenceOffset, isReferenceSmall);
if (endRowNumber == 1)
{
if (referenceValue >= endValue)
{
return endRowNumber;
}
return startRowNumber;
}
while ((endRowNumber - startRowNumber) > 1)
{
if (referenceValue <= startValue)
{
return referenceValue == startValue ? startRowNumber : startRowNumber - 1;
}
if (referenceValue >= endValue)
{
return referenceValue == endValue ? endRowNumber : endRowNumber + 1;
}
int midRowNumber = (startRowNumber + endRowNumber) / 2;
uint midReferenceValue = PeekReferenceUnchecked(midRowNumber * rowSize + referenceOffset, isReferenceSmall);
if (referenceValue > midReferenceValue)
{
startRowNumber = midRowNumber;
startValue = midReferenceValue;
}
else if (referenceValue < midReferenceValue)
{
endRowNumber = midRowNumber;
endValue = midReferenceValue;
}
else
{
return midRowNumber;
}
}
return startRowNumber;
}
// Returns row number [0..RowCount) or -1 if not found.
internal int BinarySearchReference(
int rowCount,
int rowSize,
int referenceOffset,
uint referenceValue,
bool isReferenceSmall)
{
int startRowNumber = 0;
int endRowNumber = rowCount - 1;
while (startRowNumber <= endRowNumber)
{
int midRowNumber = (startRowNumber + endRowNumber) / 2;
uint midReferenceValue = PeekReferenceUnchecked(midRowNumber * rowSize + referenceOffset, isReferenceSmall);
if (referenceValue > midReferenceValue)
{
startRowNumber = midRowNumber + 1;
}
else if (referenceValue < midReferenceValue)
{
endRowNumber = midRowNumber - 1;
}
else
{
return midRowNumber;
}
}
return -1;
}
// Row number [0, ptrTable.Length) or -1 if not found.
internal int BinarySearchReference(
int[] ptrTable,
int rowSize,
int referenceOffset,
uint referenceValue,
bool isReferenceSmall)
{
int startRowNumber = 0;
int endRowNumber = ptrTable.Length - 1;
while (startRowNumber <= endRowNumber)
{
int midRowNumber = (startRowNumber + endRowNumber) / 2;
uint midReferenceValue = PeekReferenceUnchecked((ptrTable[midRowNumber] - 1) * rowSize + referenceOffset, isReferenceSmall);
if (referenceValue > midReferenceValue)
{
startRowNumber = midRowNumber + 1;
}
else if (referenceValue < midReferenceValue)
{
endRowNumber = midRowNumber - 1;
}
else
{
return midRowNumber;
}
}
return -1;
}
/// <summary>
/// Calculates a range of rows that have specified value in the specified column in a table that is sorted by that column.
/// </summary>
internal void BinarySearchReferenceRange(
int rowCount,
int rowSize,
int referenceOffset,
uint referenceValue,
bool isReferenceSmall,
out int startRowNumber, // [0, rowCount) or -1
out int endRowNumber) // [0, rowCount) or -1
{
int foundRowNumber = BinarySearchReference(
rowCount,
rowSize,
referenceOffset,
referenceValue,
isReferenceSmall
);
if (foundRowNumber == -1)
{
startRowNumber = -1;
endRowNumber = -1;
return;
}
startRowNumber = foundRowNumber;
while (startRowNumber > 0 &&
PeekReferenceUnchecked((startRowNumber - 1) * rowSize + referenceOffset, isReferenceSmall) == referenceValue)
{
startRowNumber--;
}
endRowNumber = foundRowNumber;
while (endRowNumber + 1 < rowCount &&
PeekReferenceUnchecked((endRowNumber + 1) * rowSize + referenceOffset, isReferenceSmall) == referenceValue)
{
endRowNumber++;
}
}
/// <summary>
/// Calculates a range of rows that have specified value in the specified column in a table that is sorted by that column.
/// </summary>
internal void BinarySearchReferenceRange(
int[] ptrTable,
int rowSize,
int referenceOffset,
uint referenceValue,
bool isReferenceSmall,
out int startRowNumber, // [0, ptrTable.Length) or -1
out int endRowNumber) // [0, ptrTable.Length) or -1
{
int foundRowNumber = BinarySearchReference(
ptrTable,
rowSize,
referenceOffset,
referenceValue,
isReferenceSmall
);
if (foundRowNumber == -1)
{
startRowNumber = -1;
endRowNumber = -1;
return;
}
startRowNumber = foundRowNumber;
while (startRowNumber > 0 &&
PeekReferenceUnchecked((ptrTable[startRowNumber - 1] - 1) * rowSize + referenceOffset, isReferenceSmall) == referenceValue)
{
startRowNumber--;
}
endRowNumber = foundRowNumber;
while (endRowNumber + 1 < ptrTable.Length &&
PeekReferenceUnchecked((ptrTable[endRowNumber + 1] - 1) * rowSize + referenceOffset, isReferenceSmall) == referenceValue)
{
endRowNumber++;
}
}
// Always RowNumber....
internal int LinearSearchReference(
int rowSize,
int referenceOffset,
uint referenceValue,
bool isReferenceSmall)
{
int currOffset = referenceOffset;
int totalSize = this.Length;
while (currOffset < totalSize)
{
uint currReference = PeekReferenceUnchecked(currOffset, isReferenceSmall);
if (currReference == referenceValue)
{
return currOffset / rowSize;
}
currOffset += rowSize;
}
return -1;
}
internal bool IsOrderedByReferenceAscending(
int rowSize,
int referenceOffset,
bool isReferenceSmall)
{
int offset = referenceOffset;
int totalSize = this.Length;
uint previous = 0;
while (offset < totalSize)
{
uint current = PeekReferenceUnchecked(offset, isReferenceSmall);
if (current < previous)
{
return false;
}
previous = current;
offset += rowSize;
}
return true;
}
internal int[] BuildPtrTable(
int numberOfRows,
int rowSize,
int referenceOffset,
bool isReferenceSmall)
{
int[] ptrTable = new int[numberOfRows];
uint[] unsortedReferences = new uint[numberOfRows];
for (int i = 0; i < ptrTable.Length; i++)
{
ptrTable[i] = i + 1;
}
ReadColumn(unsortedReferences, rowSize, referenceOffset, isReferenceSmall);
Array.Sort(ptrTable, (int a, int b) => { return unsortedReferences[a - 1].CompareTo(unsortedReferences[b - 1]); });
return ptrTable;
}
private void ReadColumn(
uint[] result,
int rowSize,
int referenceOffset,
bool isReferenceSmall)
{
int offset = referenceOffset;
int totalSize = this.Length;
int i = 0;
while (offset < totalSize)
{
result[i] = PeekReferenceUnchecked(offset, isReferenceSmall);
offset += rowSize;
i++;
}
Debug.Assert(i == result.Length);
}
internal bool PeekHeapValueOffsetAndSize(int index, out int offset, out int size)
{
int bytesRead;
int numberOfBytes = PeekCompressedInteger(index, out bytesRead);
if (numberOfBytes == BlobReader.InvalidCompressedInteger)
{
offset = 0;
size = 0;
return false;
}
offset = index + bytesRead;
size = numberOfBytes;
return true;
}
}
}
| |
using UnityEngine;
using System.Collections;
using UnityEditor;
[CustomEditor(typeof(EasyJoystick))]
public class GUIEasyJoystickInspector : Editor{
GUIStyle paddingStyle1;
public GUIEasyJoystickInspector(){
}
void OnEnable(){
paddingStyle1 = new GUIStyle();
paddingStyle1.padding = new RectOffset(15, 0, 0, 0);
EasyJoystick t = (EasyJoystick)target;
if (t.areaTexture==null){
t.areaTexture = (Texture)Resources.Load("RadialJoy_Area");
EditorUtility.SetDirty(t);
}
if (t.touchTexture==null){
t.touchTexture = (Texture)Resources.Load("RadialJoy_Touch");
EditorUtility.SetDirty(t);
}
if (t.deadTexture==null){
t.deadTexture = (Texture)Resources.Load("RadialJoy_Dead");
EditorUtility.SetDirty(t);
}
t.showDebugRadius = true;
}
void OnDisable(){
EasyJoystick t = (EasyJoystick)target;
t.showDebugRadius = false;
}
public override void OnInspectorGUI(){
EasyJoystick t = (EasyJoystick)target;
// Joystick Properties
HTGUILayout.FoldOut( ref t.showProperties,"Joystick properties",false);
if (t.showProperties){
EditorGUILayout.BeginVertical(paddingStyle1);
t.name = EditorGUILayout.TextField("Joystick name",t.name);
if (t.enable) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.enable = EditorGUILayout.Toggle("Enable joystick",t.enable);
if (t.isActivated) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.isActivated = EditorGUILayout.Toggle("Activated",t.isActivated);
if (t.showDebugRadius) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.showDebugRadius = EditorGUILayout.Toggle("Show debug area",t.showDebugRadius);
GUI.backgroundColor = Color.white;
HTGUILayout.DrawSeparatorLine(paddingStyle1.padding.left);
EditorGUILayout.Separator();
if (t.useFixedUpdate) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.useFixedUpdate = EditorGUILayout.Toggle("Use fixed update",t.useFixedUpdate);
if (t.isUseGuiLayout) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.isUseGuiLayout = EditorGUILayout.Toggle("Use GUI Layout",t.isUseGuiLayout);
GUI.backgroundColor = Color.white;
if (!t.isUseGuiLayout){
EditorGUILayout.HelpBox("This lets you skip the GUI layout phase (Increase GUI performance). It can only be used if you do not use GUI.Window and GUILayout inside of this OnGUI call.",MessageType.Warning);
}
EditorGUILayout.EndVertical();
}
HTGUILayout.FoldOut( ref t.showPosition,"Joystick position & size",false);
if (t.showPosition){
// Dynamic joystick
if (t.DynamicJoystick) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.DynamicJoystick = EditorGUILayout.Toggle("Dynamic joystick",t.DynamicJoystick);
GUI.backgroundColor = Color.white;
if (t.DynamicJoystick){
GUI.backgroundColor = Color.cyan;
t.area = (EasyJoystick.DynamicArea) EditorGUILayout.EnumPopup("Free area",t.area);
GUI.backgroundColor = Color.white;
}
else{
GUI.backgroundColor = Color.cyan;
t.JoyAnchor = (EasyJoystick.JoystickAnchor)EditorGUILayout.EnumPopup("Anchor",t.JoyAnchor);
GUI.backgroundColor = Color.white;
t.JoystickPositionOffset = EditorGUILayout.Vector2Field("Offset",t.JoystickPositionOffset);
}
HTGUILayout.DrawSeparatorLine(paddingStyle1.padding.left);
EditorGUILayout.Separator();
t.ZoneRadius = EditorGUILayout.FloatField("Area radius",t.ZoneRadius);
t.TouchSize = EditorGUILayout.FloatField("Touch radius",t.TouchSize);
if (t.RestrictArea) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.RestrictArea = EditorGUILayout.Toggle(" Restrict to area",t.RestrictArea);
if (t.resetFingerExit) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.resetFingerExit = EditorGUILayout.Toggle(" Reset finger exit",t.resetFingerExit);
GUI.backgroundColor = Color.white;
t.deadZone = EditorGUILayout.FloatField("Dead zone radius",t.deadZone);
}
// Joystick axes properties
HTGUILayout.FoldOut( ref t.showInteraction,"Joystick axes properties & events",false);
if (t.showInteraction){
EditorGUILayout.BeginVertical(paddingStyle1);
// Interaction
GUI.backgroundColor = Color.cyan;
t.Interaction = (EasyJoystick.InteractionType)EditorGUILayout.EnumPopup("Interaction type",t.Interaction);
GUI.backgroundColor = Color.white;
if (t.Interaction == EasyJoystick.InteractionType.EventNotification || t.Interaction == EasyJoystick.InteractionType.DirectAndEvent){
if (t.useBroadcast) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.useBroadcast = EditorGUILayout.Toggle("Broadcast messages",t.useBroadcast);
GUI.backgroundColor = Color.white;
if (t.useBroadcast){
t.receiverGameObject =(GameObject) EditorGUILayout.ObjectField(" Receiver gameobject",t.receiverGameObject,typeof(GameObject),true);
GUI.backgroundColor = Color.cyan;
t.messageMode =(EasyJoystick.Broadcast) EditorGUILayout.EnumPopup(" Sending mode",t.messageMode);
GUI.backgroundColor = Color.white;
}
}
HTGUILayout.DrawSeparatorLine(paddingStyle1.padding.left);
// X axis
GUI.color = new Color(255f/255f,69f/255f,40f/255f);
t.enableXaxis = EditorGUILayout.BeginToggleGroup("Enable X axis",t.enableXaxis);
GUI.color = Color.white;
if (t.enableXaxis){
EditorGUILayout.BeginVertical(paddingStyle1);
t.speed.x = EditorGUILayout.FloatField("Speed",t.speed.x);
if (t.inverseXAxis) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.inverseXAxis = EditorGUILayout.Toggle("Inverse axis",t.inverseXAxis);
GUI.backgroundColor = Color.white;
EditorGUILayout.Separator();
if (t.Interaction == EasyJoystick.InteractionType.Direct || t.Interaction == EasyJoystick.InteractionType.DirectAndEvent){
t.XAxisTransform = (Transform)EditorGUILayout.ObjectField("Joystick X to",t.XAxisTransform,typeof(Transform),true);
if ( t.XAxisTransform!=null){
// characterCollider
if (t.XAxisTransform.GetComponent<CharacterController>() && (t.XTI==EasyJoystick.PropertiesInfluenced.Translate || t.XTI==EasyJoystick.PropertiesInfluenced.TranslateLocal)){
EditorGUILayout.HelpBox("CharacterController detected",MessageType.Info);
t.xAxisGravity = EditorGUILayout.FloatField("Gravity",t.xAxisGravity);
}
else{
t.xAxisGravity=0;
}
GUI.backgroundColor = Color.cyan;
t.XTI = (EasyJoystick.PropertiesInfluenced)EditorGUILayout.EnumPopup("Influenced",t.XTI);
GUI.backgroundColor = Color.white;
switch( t.xAI){
case EasyJoystick.AxisInfluenced.X:
GUI.color = new Color(255f/255f,69f/255f,40f/255f);
break;
case EasyJoystick.AxisInfluenced.Y:
GUI.color = Color.green;
break;
case EasyJoystick.AxisInfluenced.Z:
GUI.color = new Color(63f/255f,131f/255f,245f/255f);
break;
}
GUI.backgroundColor = Color.cyan;
t.xAI = (EasyJoystick.AxisInfluenced)EditorGUILayout.EnumPopup("Axis influenced",t.xAI);
GUI.backgroundColor = Color.white;
GUI.color = Color.white;
EditorGUILayout.Separator();
if (t.XTI == EasyJoystick.PropertiesInfluenced.RotateLocal){
// auto stab
if (t.enableXAutoStab) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.enableXAutoStab = EditorGUILayout.Toggle( "AutoStab",t.enableXAutoStab);
GUI.backgroundColor = Color.white;
if (t.enableXAutoStab){
EditorGUILayout.BeginVertical(paddingStyle1);
t.ThresholdX = EditorGUILayout.FloatField("Threshold ", t.ThresholdX);
t.StabSpeedX = EditorGUILayout.FloatField("Speed",t.StabSpeedX);
EditorGUILayout.EndVertical();
}
EditorGUILayout.Separator();
// Clamp
if (t.enableXClamp) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.enableXClamp = EditorGUILayout.Toggle("Clamp rotation",t.enableXClamp);
GUI.backgroundColor = Color.white;
if (t.enableXClamp){
EditorGUILayout.BeginVertical(paddingStyle1);
t.clampXMax = EditorGUILayout.FloatField("Max angle value",t.clampXMax);
t.clampXMin = EditorGUILayout.FloatField("Min angle value",t.clampXMin);
EditorGUILayout.EndVertical();
}
}
}
}
EditorGUILayout.EndVertical();
}
EditorGUILayout.EndToggleGroup();
HTGUILayout.DrawSeparatorLine(paddingStyle1.padding.left);
// Y axis
GUI.color = Color.green;
t.enableYaxis = EditorGUILayout.BeginToggleGroup("Enable Y axis",t.enableYaxis);
GUI.color = Color.white;
if (t.enableYaxis){
EditorGUILayout.BeginVertical(paddingStyle1);
t.speed.y = EditorGUILayout.FloatField("Speed",t.speed.y);
if (t.inverseYAxis) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.inverseYAxis = EditorGUILayout.Toggle("Inverse axis",t.inverseYAxis);
GUI.backgroundColor = Color.white;
EditorGUILayout.Separator();
if (t.Interaction == EasyJoystick.InteractionType.Direct || t.Interaction == EasyJoystick.InteractionType.DirectAndEvent){
t.YAxisTransform = (Transform)EditorGUILayout.ObjectField("Joystick Y to",t.YAxisTransform,typeof(Transform),true);
if ( t.YAxisTransform!=null){
// characterCollider
if (t.YAxisTransform.GetComponent<CharacterController>() && (t.YTI==EasyJoystick.PropertiesInfluenced.Translate || t.YTI==EasyJoystick.PropertiesInfluenced.TranslateLocal)){
EditorGUILayout.HelpBox("CharacterController detected",MessageType.Info);
t.yAxisGravity = EditorGUILayout.FloatField("Gravity",t.yAxisGravity);
}
else{
t.yAxisGravity=0;
}
GUI.backgroundColor = Color.cyan;
t.YTI = (EasyJoystick.PropertiesInfluenced)EditorGUILayout.EnumPopup("Influenced",t.YTI);
GUI.backgroundColor = Color.white;
switch( t.yAI){
case EasyJoystick.AxisInfluenced.X:
GUI.color = new Color(255f/255f,69f/255f,40f/255f);
break;
case EasyJoystick.AxisInfluenced.Y:
GUI.color = Color.green;
break;
case EasyJoystick.AxisInfluenced.Z:
GUI.color = new Color(63f/255f,131f/255f,245f/255f);
break;
}
GUI.backgroundColor = Color.cyan;
t.yAI = (EasyJoystick.AxisInfluenced)EditorGUILayout.EnumPopup("Axis influenced",t.yAI);
GUI.backgroundColor = Color.white;
GUI.color = Color.white;
EditorGUILayout.Separator();
if (t.YTI == EasyJoystick.PropertiesInfluenced.RotateLocal){
// auto stab
if (t.enableYAutoStab) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.enableYAutoStab = EditorGUILayout.Toggle( "AutoStab",t.enableYAutoStab);
GUI.backgroundColor = Color.white;
if (t.enableYAutoStab){
EditorGUILayout.BeginVertical(paddingStyle1);
t.ThresholdY = EditorGUILayout.FloatField("Threshold ", t.ThresholdY);
t.StabSpeedY = EditorGUILayout.FloatField("Speed",t.StabSpeedY);
EditorGUILayout.EndVertical();
}
EditorGUILayout.Separator();
// Clamp
if (t.enableYClamp) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.enableYClamp = EditorGUILayout.Toggle("Clamp rotation",t.enableYClamp);
GUI.backgroundColor = Color.white;
if (t.enableYClamp){
EditorGUILayout.BeginVertical(paddingStyle1);
t.clampYMax = EditorGUILayout.FloatField("Max angle value",t.clampYMax);
t.clampYMin = EditorGUILayout.FloatField("Min angle value",t.clampYMin);
EditorGUILayout.EndVertical();
}
}
}
}
EditorGUILayout.EndVertical();
}
EditorGUILayout.EndToggleGroup();
HTGUILayout.DrawSeparatorLine(paddingStyle1.padding.left);
EditorGUILayout.Separator();
// Smoothing return
if (t.enableSmoothing) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.enableSmoothing = EditorGUILayout.BeginToggleGroup("Smoothing return",t.enableSmoothing);
GUI.backgroundColor = Color.white;
if (t.enableSmoothing){
EditorGUILayout.BeginVertical(paddingStyle1);
t.Smoothing = EditorGUILayout.Vector2Field( "Smoothing",t.Smoothing);
EditorGUILayout.EndVertical();
}
EditorGUILayout.EndToggleGroup();
if (t.enableInertia) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.enableInertia = EditorGUILayout.BeginToggleGroup("Enable inertia",t.enableInertia);
GUI.backgroundColor = Color.white;
if (t.enableInertia){
EditorGUILayout.BeginVertical(paddingStyle1);
t.Inertia = EditorGUILayout.Vector2Field( "Inertia",t.Inertia);
EditorGUILayout.EndVertical();
}
EditorGUILayout.EndToggleGroup();
EditorGUILayout.EndVertical();
}
// Joystick Texture
HTGUILayout.FoldOut(ref t.showAppearance,"Joystick textures",false);
if (t.showAppearance){
EditorGUILayout.BeginVertical(paddingStyle1);
t.guiDepth = EditorGUILayout.IntField("Gui depth",t.guiDepth);
EditorGUILayout.Separator();
if (t.showZone) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.showZone = EditorGUILayout.Toggle("Show area",t.showZone);
GUI.backgroundColor = Color.white;
if (t.showZone){
t.areaColor = EditorGUILayout.ColorField( "Color",t.areaColor);
t.areaTexture = (Texture)EditorGUILayout.ObjectField("Area texture",t.areaTexture,typeof(Texture),true);
}
EditorGUILayout.Separator();
if (t.showTouch) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.showTouch = EditorGUILayout.Toggle("Show touch",t.showTouch);
GUI.backgroundColor = Color.white;
if (t.showTouch){
t.touchColor = EditorGUILayout.ColorField("Color",t.touchColor);
t.touchTexture = (Texture)EditorGUILayout.ObjectField("Area texture",t.touchTexture,typeof(Texture),true);
}
EditorGUILayout.Separator();
if (t.showDeadZone) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
t.showDeadZone = EditorGUILayout.Toggle("Show dead",t.showDeadZone);
GUI.backgroundColor = Color.white;
if (t.showDeadZone){
t.deadTexture = (Texture)EditorGUILayout.ObjectField("Dead zone texture",t.deadTexture,typeof(Texture),true);
}
EditorGUILayout.EndVertical();
}
// Refresh
if (GUI.changed){
EditorUtility.SetDirty(t);
}
}
}
| |
// 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 WebApplicationApiClient
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Models;
/// <summary>
/// Athletes operations.
/// </summary>
public partial class Athletes : IServiceOperations<WebApiApplication>, IAthletes
{
/// <summary>
/// Initializes a new instance of the Athletes class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
public Athletes(WebApiApplication client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the WebApiApplication
/// </summary>
public WebApiApplication Client { get; private set; }
/// <summary>
/// Gets all athletes.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<IList<Athlete>>> GetWithHttpMessagesAsync(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, "Get", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "api/Athletes").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.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));
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<IList<Athlete>>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<IList<Athlete>>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Creates a new athlete.
/// </summary>
/// <param name='value'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<object>> PostWithHttpMessagesAsync(Athlete value, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (value == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "value");
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("value", value);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Post", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "api/Athletes").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("POST");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Serialize Request
string requestContent = JsonConvert.SerializeObject(value, this.Client.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.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") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "Created")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<object>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<object>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Deletes an athlete by id.
/// </summary>
/// <param name='id'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<bool?>> DeleteWithHttpMessagesAsync(int? id, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (id == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "id");
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("id", id);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "api/Athletes/{id}").ToString();
url = url.Replace("{id}", Uri.EscapeDataString(JsonConvert.SerializeObject(id, this.Client.SerializationSettings).Trim('"')));
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("DELETE");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.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") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "NotFound")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<bool?>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<bool?>(responseContent, this.Client.DeserializationSettings);
}
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "NotFound"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<bool?>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
using System.IO;
using System;
using System.Collections.Generic;
namespace NPOI.XSSF.Util
{
/**
* This is a seriously sick fix for the fact that some .xlsx
* files contain raw bits of HTML, without being escaped
* or properly turned into XML.
* The result is that they contain things like >br<,
* which breaks the XML parsing.
* This very sick InputStream wrapper attempts to spot
* these go past, and fix them.
* Only works for UTF-8 and US-ASCII based streams!
* It should only be used where experience Shows the problem
* can occur...
*/
public class EvilUnclosedBRFixingInputStream : Stream
{
private Stream source;
private byte[] spare;
private static byte[] detect = new byte[] {
(byte)'<', (byte)'b', (byte)'r', (byte)'>'
};
public EvilUnclosedBRFixingInputStream(Stream source)
{
this.source = source;
}
/**
* Warning - doesn't fix!
*/
public int Read()
{
return source.ReadByte();
}
public override int Read(byte[] b, int off, int len)
{
// Grab any data left from last time
int readA = ReadFromSpare(b, off, len);
// Now read from the stream
int readB = source.Read(b, off + readA, len - readA);
// Figure out how much we've done
int read;
if (readB == -1 || readB == 0)
{
read = readA;
}
else
{
read = readA + readB;
}
// Fix up our data
if (read > 0)
{
read = fixUp(b, off, read);
}
// All done
return read;
}
public int Read(byte[] b)
{
return this.Read(b, 0, b.Length);
}
/**
* Reads into the buffer from the spare bytes
*/
private int ReadFromSpare(byte[] b, int offset, int len)
{
if (spare == null) return 0;
if (len == 0) throw new ArgumentException("Asked to read 0 bytes");
if (spare.Length <= len)
{
// All fits, good
Array.Copy(spare, 0, b, offset, spare.Length);
int read = spare.Length;
spare = null;
return read;
}
else
{
// We have more spare than they can copy with...
byte[] newspare = new byte[spare.Length - len];
Array.Copy(spare, 0, b, offset, len);
Array.Copy(spare, len, newspare, 0, newspare.Length);
spare = newspare;
return len;
}
}
private void AddToSpare(byte[] b, int offset, int len, bool atTheEnd)
{
if (spare == null)
{
spare = new byte[len];
Array.Copy(b, offset, spare, 0, len);
}
else
{
byte[] newspare = new byte[spare.Length + len];
if (atTheEnd)
{
Array.Copy(spare, 0, newspare, 0, spare.Length);
Array.Copy(b, offset, newspare, spare.Length, len);
}
else
{
Array.Copy(b, offset, newspare, 0, len);
Array.Copy(spare, 0, newspare, len, spare.Length);
}
spare = newspare;
}
}
private int fixUp(byte[] b, int offset, int read)
{
// Do we have any potential overhanging ones?
for (int i = 0; i < detect.Length - 1; i++)
{
int base1 = offset + read - 1 - i;
if (base1 < 0) continue;
bool going = true;
for (int j = 0; j <= i && going; j++)
{
if (b[base1 + j] == detect[j])
{
// Matches
}
else
{
going = false;
}
}
if (going)
{
// There could be a <br> handing over the end, eg <br|
AddToSpare(b, base1, i + 1, true);
read -= 1;
read -= i;
break;
}
}
// Find places to fix
List<int> fixAt = new List<int>();
for (int i = offset; i <= offset + read - detect.Length; i++)
{
bool going = true;
for (int j = 0; j < detect.Length && going; j++)
{
if (b[i + j] != detect[j])
{
going = false;
}
}
if (going)
{
fixAt.Add(i);
}
}
if (fixAt.Count == 0)
{
return read;
}
// If there isn't space in the buffer to contain
// all the fixes, then save the overshoot for next time
int needed = offset + read + fixAt.Count;
int overshoot = needed - b.Length;
if (overshoot > 0)
{
// Make sure we don't loose part of a <br>!
int fixes = 0;
foreach (int at in fixAt)
{
if (at > offset + read - detect.Length - overshoot - fixes)
{
overshoot = needed - at - 1 - fixes;
break;
}
fixes++;
}
AddToSpare(b, offset + read - overshoot, overshoot, false);
read -= overshoot;
}
// Fix them, in reverse order so the
// positions are valid
for (int j = fixAt.Count - 1; j >= 0; j--)
{
int i = fixAt[j];
if (i >= read + offset)
{
// This one has Moved into the overshoot
continue;
}
if (i > read - 3)
{
// This one has Moved into the overshoot
continue;
}
byte[] tmp = new byte[read - i - 3];
Array.Copy(b, i + 3, tmp, 0, tmp.Length);
b[i + 3] = (byte)'/';
Array.Copy(tmp, 0, b, i + 4, tmp.Length);
// It got one longer
read++;
}
return read;
}
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return true; }
}
public override bool CanWrite
{
get { return false; }
}
public override void Flush()
{
}
public override long Length
{
get { return source.Length; }
}
public override long Position
{
get
{
return source.Position;
}
set
{
source.Position = value;
}
}
public override long Seek(long offset, SeekOrigin origin)
{
return source.Seek(offset, origin);
}
public override void SetLength(long value)
{
throw new InvalidOperationException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new InvalidOperationException();
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the PnParto class.
/// </summary>
[Serializable]
public partial class PnPartoCollection : ActiveList<PnParto, PnPartoCollection>
{
public PnPartoCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>PnPartoCollection</returns>
public PnPartoCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
PnParto o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the PN_partos table.
/// </summary>
[Serializable]
public partial class PnParto : ActiveRecord<PnParto>, IActiveRecord
{
#region .ctors and Default Settings
public PnParto()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public PnParto(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public PnParto(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public PnParto(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("PN_partos", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdPar = new TableSchema.TableColumn(schema);
colvarIdPar.ColumnName = "id_par";
colvarIdPar.DataType = DbType.Int32;
colvarIdPar.MaxLength = 0;
colvarIdPar.AutoIncrement = true;
colvarIdPar.IsNullable = false;
colvarIdPar.IsPrimaryKey = true;
colvarIdPar.IsForeignKey = false;
colvarIdPar.IsReadOnly = false;
colvarIdPar.DefaultSetting = @"";
colvarIdPar.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdPar);
TableSchema.TableColumn colvarCuie = new TableSchema.TableColumn(schema);
colvarCuie.ColumnName = "cuie";
colvarCuie.DataType = DbType.AnsiString;
colvarCuie.MaxLength = -1;
colvarCuie.AutoIncrement = false;
colvarCuie.IsNullable = false;
colvarCuie.IsPrimaryKey = false;
colvarCuie.IsForeignKey = false;
colvarCuie.IsReadOnly = false;
colvarCuie.DefaultSetting = @"";
colvarCuie.ForeignKeyTableName = "";
schema.Columns.Add(colvarCuie);
TableSchema.TableColumn colvarClave = new TableSchema.TableColumn(schema);
colvarClave.ColumnName = "clave";
colvarClave.DataType = DbType.AnsiString;
colvarClave.MaxLength = -1;
colvarClave.AutoIncrement = false;
colvarClave.IsNullable = true;
colvarClave.IsPrimaryKey = false;
colvarClave.IsForeignKey = false;
colvarClave.IsReadOnly = false;
colvarClave.DefaultSetting = @"";
colvarClave.ForeignKeyTableName = "";
schema.Columns.Add(colvarClave);
TableSchema.TableColumn colvarTipoDoc = new TableSchema.TableColumn(schema);
colvarTipoDoc.ColumnName = "tipo_doc";
colvarTipoDoc.DataType = DbType.AnsiString;
colvarTipoDoc.MaxLength = -1;
colvarTipoDoc.AutoIncrement = false;
colvarTipoDoc.IsNullable = true;
colvarTipoDoc.IsPrimaryKey = false;
colvarTipoDoc.IsForeignKey = false;
colvarTipoDoc.IsReadOnly = false;
colvarTipoDoc.DefaultSetting = @"";
colvarTipoDoc.ForeignKeyTableName = "";
schema.Columns.Add(colvarTipoDoc);
TableSchema.TableColumn colvarNumDoc = new TableSchema.TableColumn(schema);
colvarNumDoc.ColumnName = "num_doc";
colvarNumDoc.DataType = DbType.Decimal;
colvarNumDoc.MaxLength = 0;
colvarNumDoc.AutoIncrement = false;
colvarNumDoc.IsNullable = true;
colvarNumDoc.IsPrimaryKey = false;
colvarNumDoc.IsForeignKey = false;
colvarNumDoc.IsReadOnly = false;
colvarNumDoc.DefaultSetting = @"";
colvarNumDoc.ForeignKeyTableName = "";
schema.Columns.Add(colvarNumDoc);
TableSchema.TableColumn colvarApellido = new TableSchema.TableColumn(schema);
colvarApellido.ColumnName = "apellido";
colvarApellido.DataType = DbType.AnsiString;
colvarApellido.MaxLength = -1;
colvarApellido.AutoIncrement = false;
colvarApellido.IsNullable = true;
colvarApellido.IsPrimaryKey = false;
colvarApellido.IsForeignKey = false;
colvarApellido.IsReadOnly = false;
colvarApellido.DefaultSetting = @"";
colvarApellido.ForeignKeyTableName = "";
schema.Columns.Add(colvarApellido);
TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema);
colvarNombre.ColumnName = "nombre";
colvarNombre.DataType = DbType.AnsiString;
colvarNombre.MaxLength = -1;
colvarNombre.AutoIncrement = false;
colvarNombre.IsNullable = true;
colvarNombre.IsPrimaryKey = false;
colvarNombre.IsForeignKey = false;
colvarNombre.IsReadOnly = false;
colvarNombre.DefaultSetting = @"";
colvarNombre.ForeignKeyTableName = "";
schema.Columns.Add(colvarNombre);
TableSchema.TableColumn colvarFechaParto = new TableSchema.TableColumn(schema);
colvarFechaParto.ColumnName = "fecha_parto";
colvarFechaParto.DataType = DbType.DateTime;
colvarFechaParto.MaxLength = 0;
colvarFechaParto.AutoIncrement = false;
colvarFechaParto.IsNullable = true;
colvarFechaParto.IsPrimaryKey = false;
colvarFechaParto.IsForeignKey = false;
colvarFechaParto.IsReadOnly = false;
colvarFechaParto.DefaultSetting = @"";
colvarFechaParto.ForeignKeyTableName = "";
schema.Columns.Add(colvarFechaParto);
TableSchema.TableColumn colvarApgar = new TableSchema.TableColumn(schema);
colvarApgar.ColumnName = "apgar";
colvarApgar.DataType = DbType.Decimal;
colvarApgar.MaxLength = 0;
colvarApgar.AutoIncrement = false;
colvarApgar.IsNullable = true;
colvarApgar.IsPrimaryKey = false;
colvarApgar.IsForeignKey = false;
colvarApgar.IsReadOnly = false;
colvarApgar.DefaultSetting = @"";
colvarApgar.ForeignKeyTableName = "";
schema.Columns.Add(colvarApgar);
TableSchema.TableColumn colvarPeso = new TableSchema.TableColumn(schema);
colvarPeso.ColumnName = "peso";
colvarPeso.DataType = DbType.Decimal;
colvarPeso.MaxLength = 0;
colvarPeso.AutoIncrement = false;
colvarPeso.IsNullable = true;
colvarPeso.IsPrimaryKey = false;
colvarPeso.IsForeignKey = false;
colvarPeso.IsReadOnly = false;
colvarPeso.DefaultSetting = @"";
colvarPeso.ForeignKeyTableName = "";
schema.Columns.Add(colvarPeso);
TableSchema.TableColumn colvarVdrl = new TableSchema.TableColumn(schema);
colvarVdrl.ColumnName = "vdrl";
colvarVdrl.DataType = DbType.AnsiString;
colvarVdrl.MaxLength = -1;
colvarVdrl.AutoIncrement = false;
colvarVdrl.IsNullable = true;
colvarVdrl.IsPrimaryKey = false;
colvarVdrl.IsForeignKey = false;
colvarVdrl.IsReadOnly = false;
colvarVdrl.DefaultSetting = @"";
colvarVdrl.ForeignKeyTableName = "";
schema.Columns.Add(colvarVdrl);
TableSchema.TableColumn colvarAntitetanica = new TableSchema.TableColumn(schema);
colvarAntitetanica.ColumnName = "antitetanica";
colvarAntitetanica.DataType = DbType.AnsiString;
colvarAntitetanica.MaxLength = -1;
colvarAntitetanica.AutoIncrement = false;
colvarAntitetanica.IsNullable = true;
colvarAntitetanica.IsPrimaryKey = false;
colvarAntitetanica.IsForeignKey = false;
colvarAntitetanica.IsReadOnly = false;
colvarAntitetanica.DefaultSetting = @"";
colvarAntitetanica.ForeignKeyTableName = "";
schema.Columns.Add(colvarAntitetanica);
TableSchema.TableColumn colvarFechaConserjeria = new TableSchema.TableColumn(schema);
colvarFechaConserjeria.ColumnName = "fecha_conserjeria";
colvarFechaConserjeria.DataType = DbType.DateTime;
colvarFechaConserjeria.MaxLength = 0;
colvarFechaConserjeria.AutoIncrement = false;
colvarFechaConserjeria.IsNullable = true;
colvarFechaConserjeria.IsPrimaryKey = false;
colvarFechaConserjeria.IsForeignKey = false;
colvarFechaConserjeria.IsReadOnly = false;
colvarFechaConserjeria.DefaultSetting = @"";
colvarFechaConserjeria.ForeignKeyTableName = "";
schema.Columns.Add(colvarFechaConserjeria);
TableSchema.TableColumn colvarObservaciones = new TableSchema.TableColumn(schema);
colvarObservaciones.ColumnName = "observaciones";
colvarObservaciones.DataType = DbType.AnsiString;
colvarObservaciones.MaxLength = -1;
colvarObservaciones.AutoIncrement = false;
colvarObservaciones.IsNullable = true;
colvarObservaciones.IsPrimaryKey = false;
colvarObservaciones.IsForeignKey = false;
colvarObservaciones.IsReadOnly = false;
colvarObservaciones.DefaultSetting = @"";
colvarObservaciones.ForeignKeyTableName = "";
schema.Columns.Add(colvarObservaciones);
TableSchema.TableColumn colvarFechaCarga = new TableSchema.TableColumn(schema);
colvarFechaCarga.ColumnName = "fecha_carga";
colvarFechaCarga.DataType = DbType.DateTime;
colvarFechaCarga.MaxLength = 0;
colvarFechaCarga.AutoIncrement = false;
colvarFechaCarga.IsNullable = true;
colvarFechaCarga.IsPrimaryKey = false;
colvarFechaCarga.IsForeignKey = false;
colvarFechaCarga.IsReadOnly = false;
colvarFechaCarga.DefaultSetting = @"";
colvarFechaCarga.ForeignKeyTableName = "";
schema.Columns.Add(colvarFechaCarga);
TableSchema.TableColumn colvarUsuario = new TableSchema.TableColumn(schema);
colvarUsuario.ColumnName = "usuario";
colvarUsuario.DataType = DbType.AnsiString;
colvarUsuario.MaxLength = -1;
colvarUsuario.AutoIncrement = false;
colvarUsuario.IsNullable = true;
colvarUsuario.IsPrimaryKey = false;
colvarUsuario.IsForeignKey = false;
colvarUsuario.IsReadOnly = false;
colvarUsuario.DefaultSetting = @"";
colvarUsuario.ForeignKeyTableName = "";
schema.Columns.Add(colvarUsuario);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("PN_partos",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdPar")]
[Bindable(true)]
public int IdPar
{
get { return GetColumnValue<int>(Columns.IdPar); }
set { SetColumnValue(Columns.IdPar, value); }
}
[XmlAttribute("Cuie")]
[Bindable(true)]
public string Cuie
{
get { return GetColumnValue<string>(Columns.Cuie); }
set { SetColumnValue(Columns.Cuie, value); }
}
[XmlAttribute("Clave")]
[Bindable(true)]
public string Clave
{
get { return GetColumnValue<string>(Columns.Clave); }
set { SetColumnValue(Columns.Clave, value); }
}
[XmlAttribute("TipoDoc")]
[Bindable(true)]
public string TipoDoc
{
get { return GetColumnValue<string>(Columns.TipoDoc); }
set { SetColumnValue(Columns.TipoDoc, value); }
}
[XmlAttribute("NumDoc")]
[Bindable(true)]
public decimal? NumDoc
{
get { return GetColumnValue<decimal?>(Columns.NumDoc); }
set { SetColumnValue(Columns.NumDoc, value); }
}
[XmlAttribute("Apellido")]
[Bindable(true)]
public string Apellido
{
get { return GetColumnValue<string>(Columns.Apellido); }
set { SetColumnValue(Columns.Apellido, value); }
}
[XmlAttribute("Nombre")]
[Bindable(true)]
public string Nombre
{
get { return GetColumnValue<string>(Columns.Nombre); }
set { SetColumnValue(Columns.Nombre, value); }
}
[XmlAttribute("FechaParto")]
[Bindable(true)]
public DateTime? FechaParto
{
get { return GetColumnValue<DateTime?>(Columns.FechaParto); }
set { SetColumnValue(Columns.FechaParto, value); }
}
[XmlAttribute("Apgar")]
[Bindable(true)]
public decimal? Apgar
{
get { return GetColumnValue<decimal?>(Columns.Apgar); }
set { SetColumnValue(Columns.Apgar, value); }
}
[XmlAttribute("Peso")]
[Bindable(true)]
public decimal? Peso
{
get { return GetColumnValue<decimal?>(Columns.Peso); }
set { SetColumnValue(Columns.Peso, value); }
}
[XmlAttribute("Vdrl")]
[Bindable(true)]
public string Vdrl
{
get { return GetColumnValue<string>(Columns.Vdrl); }
set { SetColumnValue(Columns.Vdrl, value); }
}
[XmlAttribute("Antitetanica")]
[Bindable(true)]
public string Antitetanica
{
get { return GetColumnValue<string>(Columns.Antitetanica); }
set { SetColumnValue(Columns.Antitetanica, value); }
}
[XmlAttribute("FechaConserjeria")]
[Bindable(true)]
public DateTime? FechaConserjeria
{
get { return GetColumnValue<DateTime?>(Columns.FechaConserjeria); }
set { SetColumnValue(Columns.FechaConserjeria, value); }
}
[XmlAttribute("Observaciones")]
[Bindable(true)]
public string Observaciones
{
get { return GetColumnValue<string>(Columns.Observaciones); }
set { SetColumnValue(Columns.Observaciones, value); }
}
[XmlAttribute("FechaCarga")]
[Bindable(true)]
public DateTime? FechaCarga
{
get { return GetColumnValue<DateTime?>(Columns.FechaCarga); }
set { SetColumnValue(Columns.FechaCarga, value); }
}
[XmlAttribute("Usuario")]
[Bindable(true)]
public string Usuario
{
get { return GetColumnValue<string>(Columns.Usuario); }
set { SetColumnValue(Columns.Usuario, value); }
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varCuie,string varClave,string varTipoDoc,decimal? varNumDoc,string varApellido,string varNombre,DateTime? varFechaParto,decimal? varApgar,decimal? varPeso,string varVdrl,string varAntitetanica,DateTime? varFechaConserjeria,string varObservaciones,DateTime? varFechaCarga,string varUsuario)
{
PnParto item = new PnParto();
item.Cuie = varCuie;
item.Clave = varClave;
item.TipoDoc = varTipoDoc;
item.NumDoc = varNumDoc;
item.Apellido = varApellido;
item.Nombre = varNombre;
item.FechaParto = varFechaParto;
item.Apgar = varApgar;
item.Peso = varPeso;
item.Vdrl = varVdrl;
item.Antitetanica = varAntitetanica;
item.FechaConserjeria = varFechaConserjeria;
item.Observaciones = varObservaciones;
item.FechaCarga = varFechaCarga;
item.Usuario = varUsuario;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdPar,string varCuie,string varClave,string varTipoDoc,decimal? varNumDoc,string varApellido,string varNombre,DateTime? varFechaParto,decimal? varApgar,decimal? varPeso,string varVdrl,string varAntitetanica,DateTime? varFechaConserjeria,string varObservaciones,DateTime? varFechaCarga,string varUsuario)
{
PnParto item = new PnParto();
item.IdPar = varIdPar;
item.Cuie = varCuie;
item.Clave = varClave;
item.TipoDoc = varTipoDoc;
item.NumDoc = varNumDoc;
item.Apellido = varApellido;
item.Nombre = varNombre;
item.FechaParto = varFechaParto;
item.Apgar = varApgar;
item.Peso = varPeso;
item.Vdrl = varVdrl;
item.Antitetanica = varAntitetanica;
item.FechaConserjeria = varFechaConserjeria;
item.Observaciones = varObservaciones;
item.FechaCarga = varFechaCarga;
item.Usuario = varUsuario;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdParColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn CuieColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn ClaveColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn TipoDocColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn NumDocColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn ApellidoColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn NombreColumn
{
get { return Schema.Columns[6]; }
}
public static TableSchema.TableColumn FechaPartoColumn
{
get { return Schema.Columns[7]; }
}
public static TableSchema.TableColumn ApgarColumn
{
get { return Schema.Columns[8]; }
}
public static TableSchema.TableColumn PesoColumn
{
get { return Schema.Columns[9]; }
}
public static TableSchema.TableColumn VdrlColumn
{
get { return Schema.Columns[10]; }
}
public static TableSchema.TableColumn AntitetanicaColumn
{
get { return Schema.Columns[11]; }
}
public static TableSchema.TableColumn FechaConserjeriaColumn
{
get { return Schema.Columns[12]; }
}
public static TableSchema.TableColumn ObservacionesColumn
{
get { return Schema.Columns[13]; }
}
public static TableSchema.TableColumn FechaCargaColumn
{
get { return Schema.Columns[14]; }
}
public static TableSchema.TableColumn UsuarioColumn
{
get { return Schema.Columns[15]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdPar = @"id_par";
public static string Cuie = @"cuie";
public static string Clave = @"clave";
public static string TipoDoc = @"tipo_doc";
public static string NumDoc = @"num_doc";
public static string Apellido = @"apellido";
public static string Nombre = @"nombre";
public static string FechaParto = @"fecha_parto";
public static string Apgar = @"apgar";
public static string Peso = @"peso";
public static string Vdrl = @"vdrl";
public static string Antitetanica = @"antitetanica";
public static string FechaConserjeria = @"fecha_conserjeria";
public static string Observaciones = @"observaciones";
public static string FechaCarga = @"fecha_carga";
public static string Usuario = @"usuario";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Castle.DynamicProxy.Generators.Emitters
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
public static class TypeUtil
{
public static FieldInfo[] GetAllFields(this Type type)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
if (!(type.IsClass()))
{
throw new ArgumentException(string.Format("Type {0} is not a class type. This method supports only classes", type));
}
var fields = new List<FieldInfo>();
var currentType = type;
while (currentType != typeof(object))
{
Debug.Assert(currentType != null);
var currentFields = currentType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
fields.AddRange(currentFields);
currentType = currentType.BaseType();
}
return fields.ToArray();
}
/// <summary>
/// Returns list of all unique interfaces implemented given types, including their base interfaces.
/// </summary>
/// <param name = "types"></param>
/// <returns></returns>
public static ICollection<Type> GetAllInterfaces(params Type[] types)
{
if (types == null)
{
return TypeExtender.EmptyTypes;
}
var dummy = new object();
// we should move this to HashSet once we no longer support .NET 2.0
IDictionary<Type, object> interfaces = new Dictionary<Type, object>();
foreach (var type in types)
{
if (type == null)
{
continue;
}
if (type.IsInterface())
{
interfaces[type] = dummy;
}
foreach (var @interface in type.GetInterfaces())
{
interfaces[@interface] = dummy;
}
}
return Sort(interfaces.Keys);
}
public static ICollection<Type> GetAllInterfaces(this Type type)
{
return GetAllInterfaces(new[] { type });
}
public static Type GetClosedParameterType(this AbstractTypeEmitter type, Type parameter)
{
if (parameter.IsGenericTypeDefinition())
{
return parameter.GetGenericTypeDefinition().MakeGenericType(type.GetGenericArgumentsFor(parameter));
}
if (parameter.IsGenericType())
{
var arguments = parameter.GetGenericArguments();
if (CloseGenericParametersIfAny(type, arguments))
{
return parameter.GetGenericTypeDefinition().MakeGenericType(arguments);
}
}
if (parameter.IsGenericParameter)
{
return type.GetGenericArgument(parameter.Name);
}
if (parameter.IsArray)
{
var elementType = GetClosedParameterType(type, parameter.GetElementType());
return elementType.MakeArrayType();
}
if (parameter.IsByRef)
{
var elementType = GetClosedParameterType(type, parameter.GetElementType());
return elementType.MakeByRefType();
}
return parameter;
}
public static bool IsFinalizer(this MethodInfo methodInfo)
{
return string.Equals("Finalize", methodInfo.Name) && methodInfo.GetBaseDefinition().DeclaringType == typeof(object);
}
public static bool IsGetType(this MethodInfo methodInfo)
{
return methodInfo.DeclaringType == typeof(object) && string.Equals("GetType", methodInfo.Name, StringComparison.OrdinalIgnoreCase);
}
public static bool IsMemberwiseClone(this MethodInfo methodInfo)
{
return methodInfo.DeclaringType == typeof(object) && string.Equals("MemberwiseClone", methodInfo.Name, StringComparison.OrdinalIgnoreCase);
}
public static void SetStaticField(this Type type, string fieldName, BindingFlags additionalFlags, object value)
{
#if !NETFX_CORE
var flags = additionalFlags | BindingFlags.Static | BindingFlags.SetField;
try
{
type.InvokeMember(fieldName, flags, null, null, new[] { value });
}
catch (MissingFieldException e)
{
throw new ProxyGenerationException(
string.Format(
"Could not find field named '{0}' on type {1}. This is likely a bug in DynamicProxy. Please report it.",
fieldName,
type), e);
}
catch (TargetException e)
{
throw new ProxyGenerationException(
string.Format(
"There was an error trying to set field named '{0}' on type {1}. This is likely a bug in DynamicProxy. Please report it.",
fieldName,
type), e);
}
catch (TargetInvocationException e) // yes, this is not documented in MSDN. Yay for documentation
{
if ((e.InnerException is TypeInitializationException) == false)
{
throw;
}
throw new ProxyGenerationException(
string.Format(
"There was an error in static constructor on type {0}. This is likely a bug in DynamicProxy. Please report it.",
type), e);
}
#else
// @mbrit - 2012-05-30 - invoke tricky to implement in WinRT, so we're using a field and calling it...
var field = type.GetField(fieldName, BindingFlags.Static | additionalFlags);
field.SetValue(null, value);
#endif
}
public static MemberInfo[] Sort(MemberInfo[] members)
{
var sortedMembers = new MemberInfo[members.Length];
Array.Copy(members, sortedMembers, members.Length);
Array.Sort(sortedMembers, (l, r) => string.Compare(l.Name, r.Name, StringComparison.OrdinalIgnoreCase));
return sortedMembers;
}
private static bool CloseGenericParametersIfAny(AbstractTypeEmitter emitter, Type[] arguments)
{
var hasAnyGenericParameters = false;
for (var i = 0; i < arguments.Length; i++)
{
var newType = GetClosedParameterType(emitter, arguments[i]);
if (!ReferenceEquals(newType, arguments[i]))
{
arguments[i] = newType;
hasAnyGenericParameters = true;
}
}
return hasAnyGenericParameters;
}
private static Type[] Sort(IEnumerable<Type> types)
{
var array = types.ToArray();
//NOTE: is there a better, stable way to sort Types. We will need to revise this once we allow open generics
Array.Sort(array, (l, r) => string.Compare(l.AssemblyQualifiedName, r.AssemblyQualifiedName, StringComparison.OrdinalIgnoreCase));
return array;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics; // for debugger display attribute
using Microsoft.Build.Framework;
using Microsoft.Build.BuildEngine.Shared;
namespace Microsoft.Build.BuildEngine
{
/// <summary>
/// This class is used to construct and analyze the graph of inprogress targets in order to find
/// cycles inside the graph. To find cycles a post order traversal is used to assign a post order
/// traversal to each node. Back edges indicate cycles in the graph and they can indentified by
/// a link from lower index node to a higher index node.
///
/// The graph arrives in pieces from individual nodes and needs to be stiched together by identifying
/// the parent and child for each cross node link. To do that it is necessary to match up parent
/// build request for a child with and outstanding request from the parent (see LinkCrossNodeBuildRequests)
/// </summary>
internal class TargetCycleDetector
{
#region Constructors
internal TargetCycleDetector(EngineLoggingServices engineLoggingService, EngineCallback engineCallback)
{
this.engineLoggingService = engineLoggingService;
this.engineCallback = engineCallback;
dependencyGraph = new Hashtable();
outstandingExternalRequests = new Hashtable();
cycleParent = null;
cycleChild = null;
}
#endregion
#region Properties
internal TargetInProgessState CycleEdgeParent
{
get
{
return this.cycleParent;
}
}
internal TargetInProgessState CycleEdgeChild
{
get
{
return this.cycleChild;
}
}
#endregion
#region Methods
/// <summary>
/// Add a information about an array of inprogress targets to the graph
/// </summary>
internal void AddTargetsToGraph(TargetInProgessState[] inprogressTargets)
{
if (inprogressTargets != null)
{
for (int i = 0; i < inprogressTargets.Length; i++)
{
if (inprogressTargets[i] != null)
{
AddTargetToGraph(inprogressTargets[i]);
}
}
}
}
/// <summary>
/// Add a information about a given inprogress target to the graph
/// </summary>
private void AddTargetToGraph(TargetInProgessState inProgressTarget)
{
// Check if the target is already in the graph in which
// case reuse the current object
GraphNode targetNode = (GraphNode)dependencyGraph[inProgressTarget.TargetId];
if (targetNode == null)
{
targetNode = new GraphNode(inProgressTarget);
dependencyGraph.Add(inProgressTarget.TargetId, targetNode);
}
else
{
ErrorUtilities.VerifyThrow(targetNode.targetState == null, "Target should only be added once");
targetNode.targetState = inProgressTarget;
}
// For each parent target - add parent links creating parent targets if necessary
foreach (TargetInProgessState.TargetIdWrapper parentTarget in inProgressTarget.ParentTargets)
{
GraphNode parentNode = (GraphNode)dependencyGraph[parentTarget];
if (parentNode == null)
{
parentNode = new GraphNode(null);
dependencyGraph.Add(parentTarget, parentNode);
}
parentNode.children.Add(targetNode);
}
// For all outgoing requests add them to the list of outstanding requests for the system
if (inProgressTarget.OutstandingBuildRequests != null)
{
// Since the nodeIndex is not serialized it is necessary to restore it after the request
// travels across the wire
for (int i = 0; i < inProgressTarget.OutstandingBuildRequests.Length; i++)
{
inProgressTarget.OutstandingBuildRequests[i].NodeIndex = inProgressTarget.TargetId.nodeId;
}
outstandingExternalRequests.Add(inProgressTarget.TargetId, inProgressTarget.OutstandingBuildRequests);
}
// If the target has no parents mark it as root (such targets are created due to host requests)
if (inProgressTarget.RequestedByHost)
{
targetNode.isRoot = true;
}
}
/// <summary>
/// Analyze the graph and try to find cycles. Returns true if a cycle is found.
/// </summary>
internal bool FindCycles()
{
// Add the edges for the cross node connections
LinkCrossNodeBuildRequests();
// Perform post-order traversal of the forest of directed graphs
traversalCount = 0;
// First try to perform the traversal from the roots (i.e nodes that are due to host requests)
foreach (GraphNode node in dependencyGraph.Values)
{
if (node.isRoot && node.traversalIndex == GraphNode.InvalidIndex)
{
BreadthFirstTraversal(node);
}
}
// Verify that all nodes have been reached
foreach (GraphNode node in dependencyGraph.Values)
{
if (node.traversalIndex == GraphNode.InvalidIndex)
{
BreadthFirstTraversal(node);
}
}
// Check every edge for being a back edge
foreach (GraphNode node in dependencyGraph.Values)
{
// Check the edges from the current node to its children
FindBackEdges(node);
// Stop looking as soon as the first cycle is found
if (cycleParent != null)
{
break;
}
}
return cycleParent != null;
}
/// <summary>
/// For each target that has a cross node build request waiting for it to complete, iterate
/// over the list of outstanding requests and find the matching out going request. Once
/// the matching request is found - link the parent and child targets.
/// </summary>
private void LinkCrossNodeBuildRequests()
{
foreach (GraphNode node in dependencyGraph.Values)
{
TargetInProgessState.TargetIdWrapper[] parentsForBuildRequests =
new TargetInProgessState.TargetIdWrapper[node.targetState.ParentBuildRequests.Count];
for (int j = 0; j < node.targetState.ParentBuildRequests.Count; j++ )
{
BuildRequest buildRequest = node.targetState.ParentBuildRequests[j];
int nodeIndex = buildRequest.NodeIndex;
int handleId = buildRequest.HandleId;
int requestId = buildRequest.RequestId;
bool foundParent = false;
// Skip requests that originated from the host
if (handleId == EngineCallback.invalidEngineHandle)
{
node.isRoot = true;
continue;
}
// If the request being analyzed came from one of the child nodes, its incoming external request's
// handleId will point at a routing context on the parent engine. If the outgoing request
// orginated from another child the two requests (outgoing and incoming) point at different
// routing contexts. In that case it is necessary to unwind the incoming request to the routing
// context of the outgoing request. If outgoing request originated from the parent node -
// there will be only one routing request.
if (node.targetState.TargetId.nodeId != 0)
{
ExecutionContext executionContext = engineCallback.GetExecutionContextFromHandleId(buildRequest.HandleId);
RequestRoutingContext routingContext = executionContext as RequestRoutingContext;
if (routingContext != null && routingContext.ParentHandleId != EngineCallback.invalidEngineHandle)
{
ExecutionContext nextExecutionContext = engineCallback.GetExecutionContextFromHandleId(routingContext.ParentHandleId);
if (nextExecutionContext is RequestRoutingContext)
{
nodeIndex = nextExecutionContext.NodeIndex;
handleId = routingContext.ParentHandleId;
requestId = routingContext.ParentRequestId;
}
}
else
{
// Skip requests that originated from the host
node.isRoot = true;
continue;
}
}
// Iterate over all outstanding requests until a match is found
foreach (DictionaryEntry entry in outstandingExternalRequests)
{
BuildRequest[] externalRequests = (BuildRequest[])entry.Value;
for (int i = 0; i < externalRequests.Length && !foundParent; i++)
{
if (handleId == externalRequests[i].HandleId &&
requestId == externalRequests[i].RequestId &&
nodeIndex == externalRequests[i].NodeIndex)
{
// Verify that the project name is the same
ErrorUtilities.VerifyThrow(
String.Equals(buildRequest.ProjectFileName, externalRequests[i].ProjectFileName, StringComparison.OrdinalIgnoreCase),
"The two requests should have the same project name");
// Link the two graph nodes together
GraphNode parentNode = (GraphNode)dependencyGraph[entry.Key];
parentNode.children.Add(node);
parentsForBuildRequests[j] = parentNode.targetState.TargetId;
foundParent = true;
}
}
if (foundParent)
{
break;
}
}
}
node.targetState.ParentTargetsForBuildRequests = parentsForBuildRequests;
}
}
/// <summary>
/// Breadth first traversal over the DAG, assigning post order indecies to each node in the graph. This
/// function should be called at least once for each tree in the forest in order to assign
/// indecies to every node in the graph
/// </summary>
private void BreadthFirstTraversal(GraphNode node)
{
ErrorUtilities.VerifyThrow(node.traversalIndex == GraphNode.InvalidIndex,
"Should only consider each node once");
node.traversalIndex = GraphNode.InProgressIndex;
for (int i = 0; i < node.children.Count; i++)
{
if (node.children[i].traversalIndex == GraphNode.InvalidIndex)
{
BreadthFirstTraversal(node.children[i]);
}
}
node.traversalIndex = traversalCount;
traversalCount++;
}
/// <summary>
/// Check for back edges from the given node to its children
/// </summary>
private void FindBackEdges(GraphNode node)
{
ErrorUtilities.VerifyThrow(node.traversalIndex != GraphNode.InvalidIndex,
"Each node should have a valid traversal index");
for (int i = 0; i < node.children.Count; i++)
{
// Check for a back edge
if (node.children[i].traversalIndex > node.traversalIndex )
{
cycleParent = node.targetState;
cycleChild = node.children[i].targetState;
DumpCycleSequence(node.children[i], node);
break;
}
// Check for an edge from the node to itself
if (node.children[i].targetState.TargetId == node.targetState.TargetId)
{
cycleParent = node.targetState;
cycleChild = node.targetState;
break;
}
}
}
private void DumpCycleSequence(GraphNode parent, GraphNode child)
{
foreach (GraphNode node in dependencyGraph.Values)
{
node.traversalIndex = GraphNode.InvalidIndex;
}
BuildEventContext buildEventContext =
new BuildEventContext(child.targetState.TargetId.nodeId,
child.targetState.TargetId.id,
BuildEventContext.InvalidProjectContextId,
BuildEventContext.InvalidTaskId
);
DumpCycleSequenceOutput(parent, child, buildEventContext);
}
private bool DumpCycleSequenceOutput(GraphNode parent, GraphNode child, BuildEventContext buildEventContext)
{
if (parent == child )
{
engineLoggingService.LogComment(buildEventContext, "cycleTraceTitle");
engineLoggingService.LogComment
(buildEventContext, "cycleTraceLine", parent.targetState.TargetId.name, parent.targetState.ProjectName);
return true;
}
if (parent.traversalIndex == GraphNode.InProgressIndex)
{
return false;
}
parent.traversalIndex = GraphNode.InProgressIndex;
for (int i = 0; i < parent.children.Count; i++)
{
if (DumpCycleSequenceOutput(parent.children[i], child, buildEventContext))
{
engineLoggingService.LogComment
(buildEventContext, "cycleTraceLine", parent.targetState.TargetId.name, parent.targetState.ProjectName);
return true;
}
}
return false;
}
#endregion
#region Data
/// <summary>
/// The table of all targets in the dependency graph, indexed by TargetNameStructure which
/// contains Target name, Project Id, Node Id which uniquely identifies every target in the system
/// </summary>
private Hashtable dependencyGraph;
/// <summary>
/// List of all outstanding cross node build requests
/// </summary>
private Hashtable outstandingExternalRequests;
/// <summary>
/// The index used for the breadth first traversal
/// </summary>
private int traversalCount;
/// <summary>
/// The TargetNameStructure for the parent of the edge creating the cycle
/// </summary>
private TargetInProgessState cycleParent;
/// <summary>
/// The TargetNameStructure for the parent of the edge creating the cycle
/// </summary>
private TargetInProgessState cycleChild;
/// <summary>
/// Logging service for outputing the loop trace
/// </summary>
private EngineLoggingServices engineLoggingService;
/// <summary>
/// Engine callback which is to walk the inprogress execution contexts
/// </summary>
private EngineCallback engineCallback;
#endregion
[DebuggerDisplay("Node (Name = { targetState.TargetId.name }, Project = { targetState.TargetId.projectId }), Node = { targetState.TargetId.nodeId })")]
private class GraphNode
{
#region Constructors
internal GraphNode(TargetInProgessState targetState)
{
this.targetState = targetState;
this.children = new List<GraphNode>();
this.traversalIndex = InvalidIndex;
this.isRoot = false;
}
#endregion
#region Data
internal TargetInProgessState targetState;
internal List<GraphNode> children;
internal bool isRoot;
internal int traversalIndex;
internal const int InvalidIndex = -1;
internal const int InProgressIndex = -2;
#endregion
}
}
}
| |
// Copyright 2015 XLGAMES Inc.
//
// Distributed under the MIT License (See
// accompanying file "LICENSE" or the website
// http://www.opensource.org/licenses/mit-license.php)
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.Windows.Forms;
using System.Drawing;
using System.Collections.Generic;
using System;
using Sce.Atf;
using Sce.Atf.Applications;
using LevelEditorXLE.Extensions;
using LevelEditorCore;
namespace LevelEditorXLE.Terrain
{
[Export(typeof(TerrainNamingBridge))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class TerrainNamingBridge
{
public IEnumerable<Tuple<string, int>> BaseTextureMaterials { get { return _baseTextureMaterials; } }
public IEnumerable<Tuple<string, int>> DecorationMaterials { get { return _decorationMaterials; } }
public event EventHandler<EventArgs> OnBaseTextureMaterialsChanged;
public event EventHandler<EventArgs> OnDecorationMaterialsChanged;
public void SetBaseTextureMaterials(IEnumerable<Tuple<string, int>> range)
{
_baseTextureMaterials.Clear();
_baseTextureMaterials.AddRange(range);
if (OnBaseTextureMaterialsChanged != null)
OnBaseTextureMaterialsChanged(this, EventArgs.Empty);
}
public void SetDecorationMaterials(IEnumerable<Tuple<string, int>> range)
{
_decorationMaterials.Clear();
_decorationMaterials.AddRange(range);
if (OnDecorationMaterialsChanged != null)
OnDecorationMaterialsChanged(this, EventArgs.Empty);
}
public TerrainNamingBridge()
{
_baseTextureMaterials = new List<Tuple<string, int>>();
_decorationMaterials = new List<Tuple<string, int>>();
}
private List<Tuple<string, int>> _baseTextureMaterials;
private List<Tuple<string, int>> _decorationMaterials;
}
[Export(typeof(IManipulator))]
[Export(typeof(XLEBridgeUtils.IShutdownWithEngine))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class TerrainManipulator
: IManipulator, IDisposable
, XLEBridgeUtils.IShutdownWithEngine, XLEBridgeUtils.IManipulatorExtra
{
public ManipulatorPickResult Pick(ViewControl vc, Point scrPt)
{
try
{
if (_nativeManip.OnHover(vc as GUILayer.IViewContext, scrPt))
return ManipulatorPickResult.ImmediateBeginDrag;
return ManipulatorPickResult.Miss;
}
catch (Exception e)
{
Outputs.Write(OutputMessageType.Warning, "Suppressing error in TerrainManipulator: " + e.Message);
return ManipulatorPickResult.Miss;
}
}
public void OnBeginDrag(ViewControl vc, Point scrPt)
{
try
{
_nativeManip.OnBeginDrag(vc as GUILayer.IViewContext, scrPt);
}
catch (Exception e)
{
Outputs.Write(OutputMessageType.Warning, "Suppressing error in TerrainManipulator: " + e.Message);
}
}
public void OnDragging(ViewControl vc, Point scrPt)
{
try
{
_nativeManip.OnDragging(vc as GUILayer.IViewContext, scrPt);
}
catch (Exception e)
{
// we want to report this error as a hover message above "srcPt" in the view control
Point msgPt = scrPt;
msgPt.X += 20;
msgPt.Y -= 20;
vc.ShowHoverMessage(e.Message, msgPt);
}
}
public void OnEndDrag(ViewControl vc, Point scrPt)
{
try
{
_nativeManip.OnEndDrag(vc as GUILayer.IViewContext, scrPt);
}
catch (Exception e)
{
// we want to report this error as a hover message above "srcPt" in the view control
Point msgPt = scrPt;
msgPt.X += 20;
msgPt.Y -= 20;
vc.ShowHoverMessage(e.Message, msgPt);
}
}
public void OnMouseWheel(ViewControl vc, Point scrPt, int delta)
{
try
{
_nativeManip.OnMouseWheel(vc as GUILayer.IViewContext, scrPt, delta);
// Scrolling the mouse wheel will often change the properties... We need to raise
// an event to make sure the new property values are reflected in the interface.
_manipContext.RaisePropertyChange();
}
catch (Exception e)
{
Outputs.Write(OutputMessageType.Warning, "Suppressing error in TerrainManipulator: " + e.Message);
}
}
public void Render(object opaqueContext, ViewControl vc)
{
var context = opaqueContext as GUILayer.SimpleRenderingContext;
if (context == null) return;
_nativeManip.Render(context);
}
public bool ClearBeforeDraw() { return false; }
public Control GetHoveringControl()
{
if (_manipContext.ActiveManipulator == "Paint Coverage")
{
if ( _attachedTerrainManiContext != null
&& _attachedTerrainManiContext.ActiveLayer == 1001) {
return _decorationMaterialCombo;
}
return _baseTextureCombo;
}
return null;
}
public event System.EventHandler OnHoveringControlChanged;
public ManipulatorInfo ManipulatorInfo
{
get
{
return new ManipulatorInfo(
"Terrain".Localize(),
"Activate Terrain editing".Localize(),
Resources.TerrainManip,
Keys.None);
}
}
public GUILayer.ActiveManipulatorContext ManipulatorContext
{
get { return _manipContext; }
}
public void Shutdown()
{
var r = _contextRegistry.Target as IContextRegistry;
if (r != null) r.ActiveContextChanged -= OnActiveContextChanged;
if (_nativeManip != null) { _nativeManip.Dispose(); _nativeManip = null; }
if (_manipContext != null) { _manipContext.Dispose(); _manipContext = null; }
}
[ImportingConstructor]
public TerrainManipulator(IContextRegistry contextRegistry, TerrainNamingBridge namingBridge)
{
_manipContext = new GUILayer.ActiveManipulatorContext();
_manipContext.OnActiveManipulatorChange +=
(object sender, EventArgs e) =>
{
if (this.OnHoveringControlChanged != null)
this.OnHoveringControlChanged(null, EventArgs.Empty);
};
_nativeManip = null;
_attachedSceneManager = new WeakReference(null);
_attachedTerrainManiContext = null;
_contextRegistry = new WeakReference(contextRegistry);
contextRegistry.ActiveContextChanged += OnActiveContextChanged;
_nativeManip = new GUILayer.NativeManipulatorLayer(_manipContext);
_baseTextureCombo = new System.Windows.Forms.ComboBox();
_baseTextureCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
_baseTextureCombo.DisplayMember = "Text";
_baseTextureCombo.ValueMember = "Value";
_decorationMaterialCombo = new System.Windows.Forms.ComboBox();
_decorationMaterialCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
_decorationMaterialCombo.DisplayMember = "Text";
_decorationMaterialCombo.ValueMember = "Value";
_namingBridge = namingBridge;
_namingBridge.OnBaseTextureMaterialsChanged += OnBaseTextureMaterialsChanged;
_namingBridge.OnDecorationMaterialsChanged += OnDecorationMaterialsChanged;
}
public void Dispose() { Shutdown(); }
private void OnActiveContextChanged(object obj, EventArgs args)
{
GUILayer.EditorSceneManager sceneMan = null;
GUILayer.TerrainManipulatorContext maniContext = null;
IContextRegistry registry = obj as IContextRegistry;
if (registry != null)
{
var gameExt = registry.GetActiveContext<Game.GameExtensions>();
if (gameExt != null)
{
sceneMan = gameExt.SceneManager;
maniContext = gameExt.TerrainManipulatorContext;
}
}
if (sceneMan == null || maniContext == null)
{
if (_attachedTerrainManiContext != null)
_attachedTerrainManiContext.OnActiveLayerChange -= OnActiveLayerChanged;
_manipContext.ManipulatorSet = null;
_attachedSceneManager.Target = null;
_attachedTerrainManiContext = null;
return;
}
if (sceneMan != _attachedSceneManager.Target || maniContext != _attachedTerrainManiContext)
{
if (_attachedTerrainManiContext != null)
_attachedTerrainManiContext.OnActiveLayerChange -= OnActiveLayerChanged;
_manipContext.ManipulatorSet = sceneMan.CreateTerrainManipulators(maniContext);
_attachedSceneManager.Target = sceneMan;
_attachedTerrainManiContext = maniContext;
if (_attachedTerrainManiContext != null)
_attachedTerrainManiContext.OnActiveLayerChange += OnActiveLayerChanged;
}
}
private void OnBaseTextureMaterialsChanged(object sender, EventArgs e)
{
var selected = _manipContext.GetPaintCoverageMaterial();
_baseTextureCombo.SelectedIndexChanged -= _baseTextureCombo_SelectedIndexChanged;
_baseTextureCombo.Items.Clear();
foreach (var m in _namingBridge.BaseTextureMaterials)
{
var idx = _baseTextureCombo.Items.Add(new { Text = m.Item1, Value = m.Item2 });
if (m.Item2 == selected)
_baseTextureCombo.SelectedIndex = idx;
}
_baseTextureCombo.SelectedIndexChanged += _baseTextureCombo_SelectedIndexChanged;
}
private void OnDecorationMaterialsChanged(object sender, EventArgs e)
{
var selected = _manipContext.GetPaintCoverageMaterial();
_decorationMaterialCombo.SelectedIndexChanged -= _decorationMaterialCombo_SelectedIndexChanged;
_decorationMaterialCombo.Items.Clear();
foreach (var m in _namingBridge.DecorationMaterials)
{
var idx = _decorationMaterialCombo.Items.Add(new { Text = m.Item1, Value = m.Item2 });
if (m.Item2 == selected)
_decorationMaterialCombo.SelectedIndex = idx;
}
_decorationMaterialCombo.SelectedIndexChanged += _decorationMaterialCombo_SelectedIndexChanged;
}
private void OnActiveLayerChanged(object sender, EventArgs e)
{
// Update the "hovering control" as a result of the active coverage layer changing
if (OnHoveringControlChanged != null)
OnHoveringControlChanged(this, EventArgs.Empty);
}
void _baseTextureCombo_SelectedIndexChanged(object sender, EventArgs e)
{
dynamic o = _baseTextureCombo.SelectedItem;
_manipContext.SetPaintCoverageMaterial((System.Int32)o.Value);
}
void _decorationMaterialCombo_SelectedIndexChanged(object sender, EventArgs e)
{
dynamic o = _decorationMaterialCombo.SelectedItem;
_manipContext.SetPaintCoverageMaterial((System.Int32)o.Value);
}
private GUILayer.NativeManipulatorLayer _nativeManip;
private GUILayer.ActiveManipulatorContext _manipContext;
private WeakReference _contextRegistry;
private TerrainNamingBridge _namingBridge;
private System.Windows.Forms.ComboBox _baseTextureCombo;
private System.Windows.Forms.ComboBox _decorationMaterialCombo;
private WeakReference _attachedSceneManager;
private GUILayer.TerrainManipulatorContext _attachedTerrainManiContext;
}
}
| |
// 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.Runtime.Serialization;
namespace System.Globalization
{
// This abstract class represents a calendar. A calendar reckons time in
// divisions such as weeks, months and years. The number, length and start of
// the divisions vary in each calendar.
//
// Any instant in time can be represented as an n-tuple of numeric values using
// a particular calendar. For example, the next vernal equinox occurs at (0.0, 0
// , 46, 8, 20, 3, 1999) in the Gregorian calendar. An implementation of
// Calendar can map any DateTime value to such an n-tuple and vice versa. The
// DateTimeFormat class can map between such n-tuples and a textual
// representation such as "8:46 AM March 20th 1999 AD".
//
// Most calendars identify a year which begins the current era. There may be any
// number of previous eras. The Calendar class identifies the eras as enumerated
// integers where the current era (CurrentEra) has the value zero.
//
// For consistency, the first unit in each interval, e.g. the first month, is
// assigned the value one.
// The calculation of hour/minute/second is moved to Calendar from GregorianCalendar,
// since most of the calendars (or all?) have the same way of calcuating hour/minute/second.
public abstract class Calendar : ICloneable
{
// Number of 100ns (10E-7 second) ticks per time unit
internal const long TicksPerMillisecond = 10000;
internal const long TicksPerSecond = TicksPerMillisecond * 1000;
internal const long TicksPerMinute = TicksPerSecond * 60;
internal const long TicksPerHour = TicksPerMinute * 60;
internal const long TicksPerDay = TicksPerHour * 24;
// Number of milliseconds per time unit
internal const int MillisPerSecond = 1000;
internal const int MillisPerMinute = MillisPerSecond * 60;
internal const int MillisPerHour = MillisPerMinute * 60;
internal const int MillisPerDay = MillisPerHour * 24;
// Number of days in a non-leap year
internal const int DaysPerYear = 365;
// Number of days in 4 years
internal const int DaysPer4Years = DaysPerYear * 4 + 1;
// Number of days in 100 years
internal const int DaysPer100Years = DaysPer4Years * 25 - 1;
// Number of days in 400 years
internal const int DaysPer400Years = DaysPer100Years * 4 + 1;
// Number of days from 1/1/0001 to 1/1/10000
internal const int DaysTo10000 = DaysPer400Years * 25 - 366;
internal const long MaxMillis = (long)DaysTo10000 * MillisPerDay;
private int _currentEraValue = -1;
private bool _isReadOnly = false;
// The minimum supported DateTime range for the calendar.
public virtual DateTime MinSupportedDateTime
{
get
{
return (DateTime.MinValue);
}
}
// The maximum supported DateTime range for the calendar.
public virtual DateTime MaxSupportedDateTime
{
get
{
return (DateTime.MaxValue);
}
}
public virtual CalendarAlgorithmType AlgorithmType
{
get
{
return CalendarAlgorithmType.Unknown;
}
}
protected Calendar()
{
//Do-nothing constructor.
}
///
// This can not be abstract, otherwise no one can create a subclass of Calendar.
//
internal virtual CalendarId ID
{
get
{
return CalendarId.UNINITIALIZED_VALUE;
}
}
///
// Return the Base calendar ID for calendars that didn't have defined data in calendarData
//
internal virtual CalendarId BaseCalendarID
{
get { return ID; }
}
////////////////////////////////////////////////////////////////////////
//
// IsReadOnly
//
// Detect if the object is readonly.
//
////////////////////////////////////////////////////////////////////////
public bool IsReadOnly
{
get { return (_isReadOnly); }
}
////////////////////////////////////////////////////////////////////////
//
// Clone
//
// Is the implementation of ICloneable.
//
////////////////////////////////////////////////////////////////////////
public virtual object Clone()
{
object o = MemberwiseClone();
((Calendar)o).SetReadOnlyState(false);
return (o);
}
////////////////////////////////////////////////////////////////////////
//
// ReadOnly
//
// Create a cloned readonly instance or return the input one if it is
// readonly.
//
////////////////////////////////////////////////////////////////////////
public static Calendar ReadOnly(Calendar calendar)
{
if (calendar == null) { throw new ArgumentNullException(nameof(calendar)); }
if (calendar.IsReadOnly) { return (calendar); }
Calendar clonedCalendar = (Calendar)(calendar.MemberwiseClone());
clonedCalendar.SetReadOnlyState(true);
return (clonedCalendar);
}
internal void VerifyWritable()
{
if (_isReadOnly)
{
throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
}
}
internal void SetReadOnlyState(bool readOnly)
{
_isReadOnly = readOnly;
}
/*=================================CurrentEraValue==========================
**Action: This is used to convert CurretEra(0) to an appropriate era value.
**Returns:
**Arguments:
**Exceptions:
**Notes:
** The value is from calendar.nlp.
============================================================================*/
internal virtual int CurrentEraValue
{
get
{
// The following code assumes that the current era value can not be -1.
if (_currentEraValue == -1)
{
Debug.Assert(BaseCalendarID != CalendarId.UNINITIALIZED_VALUE, "[Calendar.CurrentEraValue] Expected a real calendar ID");
_currentEraValue = CalendarData.GetCalendarData(BaseCalendarID).iCurrentEra;
}
return (_currentEraValue);
}
}
// The current era for a calendar.
public const int CurrentEra = 0;
internal int twoDigitYearMax = -1;
internal static void CheckAddResult(long ticks, DateTime minValue, DateTime maxValue)
{
if (ticks < minValue.Ticks || ticks > maxValue.Ticks)
{
throw new ArgumentException(
String.Format(CultureInfo.InvariantCulture, SR.Format(SR.Argument_ResultCalendarRange,
minValue, maxValue)));
}
}
internal DateTime Add(DateTime time, double value, int scale)
{
// From ECMA CLI spec, Partition III, section 3.27:
//
// If overflow occurs converting a floating-point type to an integer, or if the floating-point value
// being converted to an integer is a NaN, the value returned is unspecified.
//
// Based upon this, this method should be performing the comparison against the double
// before attempting a cast. Otherwise, the result is undefined.
double tempMillis = (value * scale + (value >= 0 ? 0.5 : -0.5));
if (!((tempMillis > -(double)MaxMillis) && (tempMillis < (double)MaxMillis)))
{
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_AddValue);
}
long millis = (long)tempMillis;
long ticks = time.Ticks + millis * TicksPerMillisecond;
CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime);
return (new DateTime(ticks));
}
// Returns the DateTime resulting from adding the given number of
// milliseconds to the specified DateTime. The result is computed by rounding
// the number of milliseconds given by value to the nearest integer,
// and adding that interval to the specified DateTime. The value
// argument is permitted to be negative.
//
public virtual DateTime AddMilliseconds(DateTime time, double milliseconds)
{
return (Add(time, milliseconds, 1));
}
// Returns the DateTime resulting from adding a fractional number of
// days to the specified DateTime. The result is computed by rounding the
// fractional number of days given by value to the nearest
// millisecond, and adding that interval to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddDays(DateTime time, int days)
{
return (Add(time, days, MillisPerDay));
}
// Returns the DateTime resulting from adding a fractional number of
// hours to the specified DateTime. The result is computed by rounding the
// fractional number of hours given by value to the nearest
// millisecond, and adding that interval to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddHours(DateTime time, int hours)
{
return (Add(time, hours, MillisPerHour));
}
// Returns the DateTime resulting from adding a fractional number of
// minutes to the specified DateTime. The result is computed by rounding the
// fractional number of minutes given by value to the nearest
// millisecond, and adding that interval to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddMinutes(DateTime time, int minutes)
{
return (Add(time, minutes, MillisPerMinute));
}
// Returns the DateTime resulting from adding the given number of
// months to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year and month parts of the specified DateTime by
// value months, and, if required, adjusting the day part of the
// resulting date downwards to the last day of the resulting month in the
// resulting year. The time-of-day part of the result is the same as the
// time-of-day part of the specified DateTime.
//
// In more precise terms, considering the specified DateTime to be of the
// form y / m / d + t, where y is the
// year, m is the month, d is the day, and t is the
// time-of-day, the result is y1 / m1 / d1 + t,
// where y1 and m1 are computed by adding value months
// to y and m, and d1 is the largest value less than
// or equal to d that denotes a valid day in month m1 of year
// y1.
//
public abstract DateTime AddMonths(DateTime time, int months);
// Returns the DateTime resulting from adding a number of
// seconds to the specified DateTime. The result is computed by rounding the
// fractional number of seconds given by value to the nearest
// millisecond, and adding that interval to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddSeconds(DateTime time, int seconds)
{
return Add(time, seconds, MillisPerSecond);
}
// Returns the DateTime resulting from adding a number of
// weeks to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddWeeks(DateTime time, int weeks)
{
return (AddDays(time, weeks * 7));
}
// Returns the DateTime resulting from adding the given number of
// years to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year part of the specified DateTime by value
// years. If the month and day of the specified DateTime is 2/29, and if the
// resulting year is not a leap year, the month and day of the resulting
// DateTime becomes 2/28. Otherwise, the month, day, and time-of-day
// parts of the result are the same as those of the specified DateTime.
//
public abstract DateTime AddYears(DateTime time, int years);
// Returns the day-of-month part of the specified DateTime. The returned
// value is an integer between 1 and 31.
//
public abstract int GetDayOfMonth(DateTime time);
// Returns the day-of-week part of the specified DateTime. The returned value
// is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
// Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
// Thursday, 5 indicates Friday, and 6 indicates Saturday.
//
public abstract DayOfWeek GetDayOfWeek(DateTime time);
// Returns the day-of-year part of the specified DateTime. The returned value
// is an integer between 1 and 366.
//
public abstract int GetDayOfYear(DateTime time);
// Returns the number of days in the month given by the year and
// month arguments.
//
public virtual int GetDaysInMonth(int year, int month)
{
return (GetDaysInMonth(year, month, CurrentEra));
}
// Returns the number of days in the month given by the year and
// month arguments for the specified era.
//
public abstract int GetDaysInMonth(int year, int month, int era);
// Returns the number of days in the year given by the year argument for the current era.
//
public virtual int GetDaysInYear(int year)
{
return (GetDaysInYear(year, CurrentEra));
}
// Returns the number of days in the year given by the year argument for the current era.
//
public abstract int GetDaysInYear(int year, int era);
// Returns the era for the specified DateTime value.
public abstract int GetEra(DateTime time);
/*=================================Eras==========================
**Action: Get the list of era values.
**Returns: The int array of the era names supported in this calendar.
** null if era is not used.
**Arguments: None.
**Exceptions: None.
============================================================================*/
public abstract int[] Eras
{
get;
}
// Returns the hour part of the specified DateTime. The returned value is an
// integer between 0 and 23.
//
public virtual int GetHour(DateTime time)
{
return ((int)((time.Ticks / TicksPerHour) % 24));
}
// Returns the millisecond part of the specified DateTime. The returned value
// is an integer between 0 and 999.
//
public virtual double GetMilliseconds(DateTime time)
{
return (double)((time.Ticks / TicksPerMillisecond) % 1000);
}
// Returns the minute part of the specified DateTime. The returned value is
// an integer between 0 and 59.
//
public virtual int GetMinute(DateTime time)
{
return ((int)((time.Ticks / TicksPerMinute) % 60));
}
// Returns the month part of the specified DateTime. The returned value is an
// integer between 1 and 12.
//
public abstract int GetMonth(DateTime time);
// Returns the number of months in the specified year in the current era.
public virtual int GetMonthsInYear(int year)
{
return (GetMonthsInYear(year, CurrentEra));
}
// Returns the number of months in the specified year and era.
public abstract int GetMonthsInYear(int year, int era);
// Returns the second part of the specified DateTime. The returned value is
// an integer between 0 and 59.
//
public virtual int GetSecond(DateTime time)
{
return ((int)((time.Ticks / TicksPerSecond) % 60));
}
/*=================================GetFirstDayWeekOfYear==========================
**Action: Get the week of year using the FirstDay rule.
**Returns: the week of year.
**Arguments:
** time
** firstDayOfWeek the first day of week (0=Sunday, 1=Monday, ... 6=Saturday)
**Notes:
** The CalendarWeekRule.FirstDay rule: Week 1 begins on the first day of the year.
** Assume f is the specifed firstDayOfWeek,
** and n is the day of week for January 1 of the specified year.
** Assign offset = n - f;
** Case 1: offset = 0
** E.g.
** f=1
** weekday 0 1 2 3 4 5 6 0 1
** date 1/1
** week# 1 2
** then week of year = (GetDayOfYear(time) - 1) / 7 + 1
**
** Case 2: offset < 0
** e.g.
** n=1 f=3
** weekday 0 1 2 3 4 5 6 0
** date 1/1
** week# 1 2
** This means that the first week actually starts 5 days before 1/1.
** So week of year = (GetDayOfYear(time) + (7 + offset) - 1) / 7 + 1
** Case 3: offset > 0
** e.g.
** f=0 n=2
** weekday 0 1 2 3 4 5 6 0 1 2
** date 1/1
** week# 1 2
** This means that the first week actually starts 2 days before 1/1.
** So Week of year = (GetDayOfYear(time) + offset - 1) / 7 + 1
============================================================================*/
internal int GetFirstDayWeekOfYear(DateTime time, int firstDayOfWeek)
{
int dayOfYear = GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
// Calculate the day of week for the first day of the year.
// dayOfWeek - (dayOfYear % 7) is the day of week for the first day of this year. Note that
// this value can be less than 0. It's fine since we are making it positive again in calculating offset.
int dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7);
int offset = (dayForJan1 - firstDayOfWeek + 14) % 7;
Debug.Assert(offset >= 0, "Calendar.GetFirstDayWeekOfYear(): offset >= 0");
return ((dayOfYear + offset) / 7 + 1);
}
private int GetWeekOfYearFullDays(DateTime time, int firstDayOfWeek, int fullDays)
{
int dayForJan1;
int offset;
int day;
int dayOfYear = GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
//
// Calculate the number of days between the first day of year (1/1) and the first day of the week.
// This value will be a positive value from 0 ~ 6. We call this value as "offset".
//
// If offset is 0, it means that the 1/1 is the start of the first week.
// Assume the first day of the week is Monday, it will look like this:
// Sun Mon Tue Wed Thu Fri Sat
// 12/31 1/1 1/2 1/3 1/4 1/5 1/6
// +--> First week starts here.
//
// If offset is 1, it means that the first day of the week is 1 day ahead of 1/1.
// Assume the first day of the week is Monday, it will look like this:
// Sun Mon Tue Wed Thu Fri Sat
// 1/1 1/2 1/3 1/4 1/5 1/6 1/7
// +--> First week starts here.
//
// If offset is 2, it means that the first day of the week is 2 days ahead of 1/1.
// Assume the first day of the week is Monday, it will look like this:
// Sat Sun Mon Tue Wed Thu Fri Sat
// 1/1 1/2 1/3 1/4 1/5 1/6 1/7 1/8
// +--> First week starts here.
// Day of week is 0-based.
// Get the day of week for 1/1. This can be derived from the day of week of the target day.
// Note that we can get a negative value. It's ok since we are going to make it a positive value when calculating the offset.
dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7);
// Now, calculate the offset. Subtract the first day of week from the dayForJan1. And make it a positive value.
offset = (firstDayOfWeek - dayForJan1 + 14) % 7;
if (offset != 0 && offset >= fullDays)
{
//
// If the offset is greater than the value of fullDays, it means that
// the first week of the year starts on the week where Jan/1 falls on.
//
offset -= 7;
}
//
// Calculate the day of year for specified time by taking offset into account.
//
day = dayOfYear - offset;
if (day >= 0)
{
//
// If the day of year value is greater than zero, get the week of year.
//
return (day / 7 + 1);
}
//
// Otherwise, the specified time falls on the week of previous year.
// Call this method again by passing the last day of previous year.
//
// the last day of the previous year may "underflow" to no longer be a valid date time for
// this calendar if we just subtract so we need the subclass to provide us with
// that information
if (time <= MinSupportedDateTime.AddDays(dayOfYear))
{
return GetWeekOfYearOfMinSupportedDateTime(firstDayOfWeek, fullDays);
}
return (GetWeekOfYearFullDays(time.AddDays(-(dayOfYear + 1)), firstDayOfWeek, fullDays));
}
private int GetWeekOfYearOfMinSupportedDateTime(int firstDayOfWeek, int minimumDaysInFirstWeek)
{
int dayOfYear = GetDayOfYear(MinSupportedDateTime) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
int dayOfWeekOfFirstOfYear = (int)GetDayOfWeek(MinSupportedDateTime) - dayOfYear % 7;
// Calculate the offset (how many days from the start of the year to the start of the week)
int offset = (firstDayOfWeek + 7 - dayOfWeekOfFirstOfYear) % 7;
if (offset == 0 || offset >= minimumDaysInFirstWeek)
{
// First of year falls in the first week of the year
return 1;
}
int daysInYearBeforeMinSupportedYear = DaysInYearBeforeMinSupportedYear - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
int dayOfWeekOfFirstOfPreviousYear = dayOfWeekOfFirstOfYear - 1 - (daysInYearBeforeMinSupportedYear % 7);
// starting from first day of the year, how many days do you have to go forward
// before getting to the first day of the week?
int daysInInitialPartialWeek = (firstDayOfWeek - dayOfWeekOfFirstOfPreviousYear + 14) % 7;
int day = daysInYearBeforeMinSupportedYear - daysInInitialPartialWeek;
if (daysInInitialPartialWeek >= minimumDaysInFirstWeek)
{
// If the offset is greater than the minimum Days in the first week, it means that
// First of year is part of the first week of the year even though it is only a partial week
// add another week
day += 7;
}
return (day / 7 + 1);
}
// it would be nice to make this abstract but we can't since that would break previous implementations
protected virtual int DaysInYearBeforeMinSupportedYear
{
get
{
return 365;
}
}
// Returns the week of year for the specified DateTime. The returned value is an
// integer between 1 and 53.
//
public virtual int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
{
if ((int)firstDayOfWeek < 0 || (int)firstDayOfWeek > 6)
{
throw new ArgumentOutOfRangeException(
nameof(firstDayOfWeek), SR.Format(SR.ArgumentOutOfRange_Range,
DayOfWeek.Sunday, DayOfWeek.Saturday));
}
switch (rule)
{
case CalendarWeekRule.FirstDay:
return (GetFirstDayWeekOfYear(time, (int)firstDayOfWeek));
case CalendarWeekRule.FirstFullWeek:
return (GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 7));
case CalendarWeekRule.FirstFourDayWeek:
return (GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 4));
}
throw new ArgumentOutOfRangeException(
nameof(rule), SR.Format(SR.ArgumentOutOfRange_Range,
CalendarWeekRule.FirstDay, CalendarWeekRule.FirstFourDayWeek));
}
// Returns the year part of the specified DateTime. The returned value is an
// integer between 1 and 9999.
//
public abstract int GetYear(DateTime time);
// Checks whether a given day in the current era is a leap day. This method returns true if
// the date is a leap day, or false if not.
//
public virtual bool IsLeapDay(int year, int month, int day)
{
return (IsLeapDay(year, month, day, CurrentEra));
}
// Checks whether a given day in the specified era is a leap day. This method returns true if
// the date is a leap day, or false if not.
//
public abstract bool IsLeapDay(int year, int month, int day, int era);
// Checks whether a given month in the current era is a leap month. This method returns true if
// month is a leap month, or false if not.
//
public virtual bool IsLeapMonth(int year, int month)
{
return (IsLeapMonth(year, month, CurrentEra));
}
// Checks whether a given month in the specified era is a leap month. This method returns true if
// month is a leap month, or false if not.
//
public abstract bool IsLeapMonth(int year, int month, int era);
// Returns the leap month in a calendar year of the current era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
public virtual int GetLeapMonth(int year)
{
return (GetLeapMonth(year, CurrentEra));
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
public virtual int GetLeapMonth(int year, int era)
{
if (!IsLeapYear(year, era))
return 0;
int monthsCount = GetMonthsInYear(year, era);
for (int month = 1; month <= monthsCount; month++)
{
if (IsLeapMonth(year, month, era))
return month;
}
return 0;
}
// Checks whether a given year in the current era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public virtual bool IsLeapYear(int year)
{
return (IsLeapYear(year, CurrentEra));
}
// Checks whether a given year in the specified era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public abstract bool IsLeapYear(int year, int era);
// Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
//
public virtual DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond)
{
return (ToDateTime(year, month, day, hour, minute, second, millisecond, CurrentEra));
}
// Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
//
public abstract DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era);
internal virtual Boolean TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result)
{
result = DateTime.MinValue;
try
{
result = ToDateTime(year, month, day, hour, minute, second, millisecond, era);
return true;
}
catch (ArgumentException)
{
return false;
}
}
internal virtual bool IsValidYear(int year, int era)
{
return (year >= GetYear(MinSupportedDateTime) && year <= GetYear(MaxSupportedDateTime));
}
internal virtual bool IsValidMonth(int year, int month, int era)
{
return (IsValidYear(year, era) && month >= 1 && month <= GetMonthsInYear(year, era));
}
internal virtual bool IsValidDay(int year, int month, int day, int era)
{
return (IsValidMonth(year, month, era) && day >= 1 && day <= GetDaysInMonth(year, month, era));
}
// Returns and assigns the maximum value to represent a two digit year. This
// value is the upper boundary of a 100 year range that allows a two digit year
// to be properly translated to a four digit year. For example, if 2029 is the
// upper boundary, then a two digit value of 30 should be interpreted as 1930
// while a two digit value of 29 should be interpreted as 2029. In this example
// , the 100 year range would be from 1930-2029. See ToFourDigitYear().
public virtual int TwoDigitYearMax
{
get
{
return (twoDigitYearMax);
}
set
{
VerifyWritable();
twoDigitYearMax = value;
}
}
// Converts the year value to the appropriate century by using the
// TwoDigitYearMax property. For example, if the TwoDigitYearMax value is 2029,
// then a two digit value of 30 will get converted to 1930 while a two digit
// value of 29 will get converted to 2029.
public virtual int ToFourDigitYear(int year)
{
if (year < 0)
{
throw new ArgumentOutOfRangeException(nameof(year),
SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (year < 100)
{
return ((TwoDigitYearMax / 100 - (year > TwoDigitYearMax % 100 ? 1 : 0)) * 100 + year);
}
// If the year value is above 100, just return the year value. Don't have to do
// the TwoDigitYearMax comparison.
return (year);
}
// Return the tick count corresponding to the given hour, minute, second.
// Will check the if the parameters are valid.
internal static long TimeToTicks(int hour, int minute, int second, int millisecond)
{
if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60)
{
if (millisecond < 0 || millisecond >= MillisPerSecond)
{
throw new ArgumentOutOfRangeException(
nameof(millisecond),
String.Format(
CultureInfo.InvariantCulture,
SR.Format(SR.ArgumentOutOfRange_Range, 0, MillisPerSecond - 1)));
}
return InternalGlobalizationHelper.TimeToTicks(hour, minute, second) + millisecond * TicksPerMillisecond;
}
throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond);
}
internal static int GetSystemTwoDigitYearSetting(CalendarId CalID, int defaultYearValue)
{
int twoDigitYearMax = CalendarData.GetTwoDigitYearMax(CalID);
if (twoDigitYearMax < 0)
{
twoDigitYearMax = defaultYearValue;
}
return (twoDigitYearMax);
}
}
}
| |
using System;
using System.Net;
using System.Web;
using System.Text;
using System.Text.RegularExpressions;
using NUnit.Framework;
namespace Braintree.Tests
{
//NOTE: good
[TestFixture]
public class ClientTokenTest
{
[Test]
public void Generate_DefaultToken()
{
var gateway = new BraintreeGateway();
Assert.IsNotNull(gateway.ClientToken);
string token = gateway.ClientToken.Generate();
Assert.IsNotEmpty(token);
}
[Test]
public void Generate_RaisesExceptionIfVerifyCardIsIncludedWithoutCustomerId()
{
var gateway = new BraintreeGateway();
try {
gateway.ClientToken.Generate(
new ClientTokenRequest
{
Options = new ClientTokenOptionsRequest
{
VerifyCard = true
}
}
);
Assert.Fail("Should raise ArgumentException");
} catch (ArgumentException e) {
Match match = Regex.Match(e.Message, @"VerifyCard");
Assert.IsTrue(match.Success);
}
}
[Test]
public void Generate_RaisesExceptionIfMakeDefaultIsIncludedWithoutCustomerId()
{
var gateway = new BraintreeGateway();
try {
gateway.ClientToken.Generate(
new ClientTokenRequest
{
Options = new ClientTokenOptionsRequest
{
MakeDefault = true
}
}
);
Assert.Fail("Should raise ArgumentException");
} catch (ArgumentException e) {
Match match = Regex.Match(e.Message, @"MakeDefault");
Assert.IsTrue(match.Success);
}
}
[Test]
public void Generate_RaisesExceptionIfFailOnDuplicatePaymentMethodIsIncludedWithoutCustomerId()
{
var gateway = new BraintreeGateway();
try {
gateway.ClientToken.Generate(
new ClientTokenRequest
{
Options = new ClientTokenOptionsRequest
{
FailOnDuplicatePaymentMethod = true
}
}
);
Assert.Fail("Should raise ArgumentException");
} catch (ArgumentException e) {
Match match = Regex.Match(e.Message, @"FailOnDuplicatePaymentMethod");
Assert.IsTrue(match.Success);
}
}
}
[TestFixture]
public class ClientTokenTestIT
{
[Test]
public void Generate_GeneratedFingerprintIsAcceptedByGateway()
{
var gateway = new BraintreeGateway();
var clientToken = TestHelper.GenerateDecodedClientToken(gateway);
var authorizationFingerprint = TestHelper.extractParamFromJson("authorizationFingerprint", clientToken);
var encodedFingerprint = HttpUtility.UrlEncode(authorizationFingerprint, Encoding.UTF8);
var url = "v1/payment_methods.json";
url += "?authorizationFingerprint=" + encodedFingerprint;
url += "&sharedCustomerIdentifierType=testing";
url += "&sharedCustomerIdentifier=test-identifier";
HttpWebResponse response = new BraintreeTestHttpService().Get(gateway.MerchantId, url);
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
response.Close();
}
[Test]
public void Generate_SupportsVersionOption()
{
var gateway = new BraintreeGateway();
var clientToken = gateway.ClientToken.Generate(
new ClientTokenRequest
{
Version = 1
}
);
int version = TestHelper.extractIntParamFromJson("version", clientToken);
Assert.AreEqual(1, version);
}
[Test]
public void Generate_DefaultsToVersionTwo()
{
var gateway = new BraintreeGateway();
var encodedClientToken = gateway.ClientToken.Generate();
var decodedClientToken = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(encodedClientToken));
int version = TestHelper.extractIntParamFromJson("version", decodedClientToken);
Assert.AreEqual(2, version);
}
[Test]
public void Generate_GatewayRespectsVerifyCard()
{
var gateway = new BraintreeGateway();
Result<Customer> result = gateway.Customer.Create(new CustomerRequest());
Assert.IsTrue(result.IsSuccess());
string customerId = result.Target.Id;
var clientToken = TestHelper.GenerateDecodedClientToken(gateway,
new ClientTokenRequest
{
CustomerId = customerId,
Options = new ClientTokenOptionsRequest
{
VerifyCard = true
}
}
);
var authorizationFingerprint = TestHelper.extractParamFromJson("authorizationFingerprint", clientToken);
var builder = new RequestBuilder("");
builder.AddTopLevelElement("authorization_fingerprint", authorizationFingerprint).
AddTopLevelElement("shared_customer_identifier_type", "testing").
AddTopLevelElement("shared_customer_identifier", "test-identifier").
AddTopLevelElement("credit_card[number]", "4000111111111115").
AddTopLevelElement("credit_card[expiration_month]", "11").
AddTopLevelElement("credit_card[expiration_year]", "2099");
HttpWebResponse response = new BraintreeTestHttpService().Post(gateway.MerchantId, "v1/payment_methods/credit_cards.json", builder.ToQueryString());
Assert.AreEqual(422, (int)response.StatusCode);
response.Close();
Customer customer = gateway.Customer.Find(customerId);
Assert.AreEqual(0, customer.CreditCards.Length);
}
[Test]
public void Generate_GatewayRespectsFailOnDuplicatePaymentMethod()
{
var gateway = new BraintreeGateway();
Result<Customer> result = gateway.Customer.Create(new CustomerRequest());
Assert.IsTrue(result.IsSuccess());
string customerId = result.Target.Id;
var request = new CreditCardRequest
{
CustomerId = customerId,
Number = "4111111111111111",
ExpirationDate = "05/2099"
};
Result<CreditCard> creditCardResult = gateway.CreditCard.Create(request);
Assert.IsTrue(creditCardResult.IsSuccess());
var clientToken = TestHelper.GenerateDecodedClientToken(gateway,
new ClientTokenRequest
{
CustomerId = customerId,
Options = new ClientTokenOptionsRequest
{
FailOnDuplicatePaymentMethod = true
}
}
);
var authorizationFingerprint = TestHelper.extractParamFromJson("authorizationFingerprint", clientToken);
var builder = new RequestBuilder("");
builder.AddTopLevelElement("authorization_fingerprint", authorizationFingerprint).
AddTopLevelElement("shared_customer_identifier_type", "testing").
AddTopLevelElement("shared_customer_identifier", "test-identifier").
AddTopLevelElement("credit_card[number]", "4111111111111111").
AddTopLevelElement("credit_card[expiration_month]", "11").
AddTopLevelElement("credit_card[expiration_year]", "2099");
HttpWebResponse response = new BraintreeTestHttpService().Post(gateway.MerchantId, "v1/payment_methods/credit_cards.json", builder.ToQueryString());
response = new BraintreeTestHttpService().Post(gateway.MerchantId, "v1/payment_methods/credit_cards.json", builder.ToQueryString());
Assert.AreEqual(422, (int)response.StatusCode);
response.Close();
Customer customer = gateway.Customer.Find(customerId);
Assert.AreEqual(1, customer.CreditCards.Length);
}
[Test]
public void Generate_GatewayRespectsMakeDefault()
{
var gateway = new BraintreeGateway();
Result<Customer> result = gateway.Customer.Create(new CustomerRequest());
Assert.IsTrue(result.IsSuccess());
string customerId = result.Target.Id;
var request = new CreditCardRequest
{
CustomerId = customerId,
Number = "5555555555554444",
ExpirationDate = "05/2099"
};
Result<CreditCard> creditCardResult = gateway.CreditCard.Create(request);
Assert.IsTrue(creditCardResult.IsSuccess());
var clientToken = TestHelper.GenerateDecodedClientToken(gateway,
new ClientTokenRequest
{
CustomerId = customerId,
Options = new ClientTokenOptionsRequest
{
MakeDefault = true
}
}
);
var authorizationFingerprint = TestHelper.extractParamFromJson("authorizationFingerprint", clientToken);
var builder = new RequestBuilder("");
builder.AddTopLevelElement("authorization_fingerprint", authorizationFingerprint).
AddTopLevelElement("shared_customer_identifier_type", "testing").
AddTopLevelElement("shared_customer_identifier", "test-identifier").
AddTopLevelElement("credit_card[number]", "4111111111111111").
AddTopLevelElement("credit_card[expiration_month]", "11").
AddTopLevelElement("credit_card[expiration_year]", "2099");
HttpWebResponse response = new BraintreeTestHttpService().Post(gateway.MerchantId, "v1/payment_methods/credit_cards.json", builder.ToQueryString());
Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);
response.Close();
Customer customer = gateway.Customer.Find(customerId);
Assert.AreEqual(2, customer.CreditCards.Length);
foreach (CreditCard creditCard in customer.CreditCards)
{
if (creditCard.LastFour == "1111") {
Assert.IsTrue(creditCard.IsDefault.Value);
}
}
}
[Test]
public void Generate_ThrowExceptionWhenCustomerNotFound()
{
var gateway = new BraintreeGateway();
string encodedClientToken = "";
try
{
encodedClientToken += gateway.ClientToken.Generate(
new ClientTokenRequest
{
CustomerId = "NON_EXISTENT_CUSTOMER_ID"
}
);
Assert.Fail("Should raise ArgumentException");
} catch (ArgumentException e) {
Match match = Regex.Match(e.Message, @"customer_id");
Assert.IsTrue(match.Success);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace MinimalContainer
{
public enum DefaultLifestyle { Undefined, Transient, Singleton }
internal enum Lifestyle { Undefined, Transient, Singleton, Instance, Factory }
internal sealed class Registration
{
internal TypeInfo Type;
internal TypeInfo? TypeConcrete;
internal Lifestyle Lifestyle;
internal Func<object>? Factory;
internal Expression? Expression;
internal Delegate? FuncDelegate;
internal Registration(TypeInfo type)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
if (type.AsType() == typeof(string) || (!type.IsClass && !type.IsInterface))
throw new TypeAccessException("Type is neither a class nor an interface.");
Type = type;
}
public override string ToString() =>
$"{(TypeConcrete == null || Equals(TypeConcrete, Type) ? "" : TypeConcrete.AsString() + "->")}{Type.AsString()}, {Lifestyle}.";
}
public sealed class Container : IDisposable
{
private readonly DefaultLifestyle DefaultLifestyle;
private readonly Lazy<List<TypeInfo>> AllTypesConcrete;
private readonly Dictionary<Type, Registration> Registrations = new Dictionary<Type, Registration>();
private readonly Stack<TypeInfo> TypeStack = new Stack<TypeInfo>();
private readonly ILogger Logger;
public Container(DefaultLifestyle defaultLifestyle = DefaultLifestyle.Undefined, ILogger<Container>? logger = null, params Assembly[]? assemblies)
{
Logger = logger ?? NullLogger<Container>.Instance;
Logger.LogInformation("Constructing Container.");
DefaultLifestyle = defaultLifestyle;
if (assemblies == null)
throw new ArgumentNullException(nameof(assemblies));
var assemblyList = assemblies.ToList();
if (!assemblyList.Any())
assemblyList.Add(Assembly.GetCallingAssembly());
AllTypesConcrete = new Lazy<List<TypeInfo>>(() => assemblyList
.Select(a => a.DefinedTypes.Where(t => t.IsClass && !t.IsAbstract && !t.IsInterface))
.SelectMany(x => x)
.ToList());
}
public Container RegisterTransient<T>() => RegisterTransient(typeof(T));
public Container RegisterTransient<T, TConcrete>() where TConcrete : T => RegisterTransient(typeof(T), typeof(TConcrete));
public Container RegisterTransient(Type type, Type? typeConcrete = null) => Register(type, typeConcrete, Lifestyle.Transient);
public Container RegisterSingleton<T>() => RegisterSingleton(typeof(T));
public Container RegisterSingleton<T, TConcrete>() where TConcrete : T => RegisterSingleton(typeof(T), typeof(TConcrete));
public Container RegisterSingleton(Type type, Type? typeConcrete = null) => Register(type, typeConcrete, Lifestyle.Singleton);
public Container RegisterInstance<T>(T instance) => RegisterInstance(typeof(T), instance);
public Container RegisterInstance(Type type, object? instance) => Register(type, null, Lifestyle.Instance, instance);
public Container RegisterFactory<T>(Func<T> factory) where T : class => RegisterFactory(typeof(T), factory);
public Container RegisterFactory(Type type, Func<object> factory) => Register(type, null, Lifestyle.Factory, null, factory);
private Container Register(Type type, Type? typeConcrete, Lifestyle lifestyle, object? instance = null, Func<object>? factory = null, [CallerMemberName] string? caller = null)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
var reg = AddRegistration(type.GetTypeInfo());
Logger.LogInformation($"Registering {caller}: {reg},");
reg.TypeConcrete = typeConcrete?.GetTypeInfo();
reg.Lifestyle = lifestyle;
if (lifestyle == Lifestyle.Instance)
{
if (instance == null)
throw new ArgumentNullException(nameof(instance));
object notNullInstance = instance;
reg.Factory = () => notNullInstance;
reg.Expression = Expression.Constant(instance);
}
else if (lifestyle == Lifestyle.Factory)
{
reg.Factory = factory ?? throw new ArgumentNullException(nameof(factory));
reg.Expression = Expression.Call(Expression.Constant(factory.Target), factory.GetMethodInfo());
}
return this;
}
//////////////////////////////////////////////////////////////////////////////
private Registration AddRegistration(TypeInfo type)
{
try
{
var reg = new Registration(type);
Registrations.Add(type.AsType(), reg);
return reg;
}
catch (ArgumentException ex)
{
throw new TypeAccessException($"Type '{type.AsString()}' is already registered.", ex);
}
}
//////////////////////////////////////////////////////////////////////////////
public T Resolve<T>() => (T)Resolve(typeof(T));
public object Resolve(in Type type)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
try
{
(Registration reg, bool isFunc) = GetOrAddInitializeRegistration(type, null);
if (!isFunc)
{
var factory = reg.Factory ?? throw new Exception("Factory is null.");
return factory();
}
return reg.FuncDelegate ?? (reg.FuncDelegate = Expression.Lambda(reg.Expression).Compile());
}
catch (TypeAccessException ex)
{
if (!TypeStack.Any())
TypeStack.Push(type.GetTypeInfo());
var typePath = TypeStack.Select(t => t.AsString()).JoinStrings("->");
throw new TypeAccessException($"Could not get instance of type {typePath}. {ex.Message}", ex);
}
}
private Expression GetOrAddExpression(in Type type, in Registration dependent)
{
(Registration reg, bool isFunc) = GetOrAddInitializeRegistration(type, dependent);
var expression = reg.Expression ?? throw new Exception("Expression is null.");
return isFunc ? Expression.Lambda(expression) : expression;
}
private (Registration reg, bool isFunc) GetOrAddInitializeRegistration(Type type, in Registration? dependent)
{
Registration reg;
bool isFunc = false;
GetOrAddRegistration();
if (reg.Expression == null)
Initialize(reg, dependent, isFunc);
return (reg, isFunc);
// local function
void GetOrAddRegistration()
{
if (Registrations.TryGetValue(type, out reg))
return;
TypeInfo typeInfo = type.GetTypeInfo();
if (typeInfo.GetFuncArgumentType(out TypeInfo? funcType))
{
isFunc = true;
typeInfo = funcType ?? throw new NullReferenceException();
if (Registrations.TryGetValue(typeInfo.AsType(), out reg))
{
if (reg.Lifestyle == Lifestyle.Singleton || reg.Lifestyle == Lifestyle.Instance)
throw new TypeAccessException($"Func argument type '{typeInfo.AsString()}' must be Transient or Factory.");
return;
}
}
if (DefaultLifestyle == DefaultLifestyle.Undefined && !typeInfo.IsEnumerable())
throw new TypeAccessException($"Cannot resolve unregistered type '{typeInfo.AsString()}'.");
reg = AddRegistration(typeInfo);
if (isFunc)
reg.Lifestyle = Lifestyle.Transient;
}
}
private void Initialize(Registration reg, Registration? dependent, bool isFunc)
{
if (dependent == null)
{
TypeStack.Clear();
Logger.LogDebug($"Getting instance of type: '{reg.Type.AsString()}'.");
}
else if (reg.Lifestyle == Lifestyle.Undefined && (dependent?.Lifestyle == Lifestyle.Singleton || dependent?.Lifestyle == Lifestyle.Instance))
reg.Lifestyle = Lifestyle.Singleton;
TypeStack.Push(reg.Type);
if (TypeStack.Count(t => t.Equals(reg.Type)) != 1)
throw new TypeAccessException("Recursive dependency.");
InitializeTypes();
if ((dependent?.Lifestyle == Lifestyle.Singleton || dependent?.Lifestyle == Lifestyle.Instance)
&& (reg.Lifestyle == Lifestyle.Transient || reg.Lifestyle == Lifestyle.Factory) && !isFunc)
throw new TypeAccessException($"Captive dependency: the singleton '{dependent?.Type.AsString()}' depends on transient '{reg.Type.AsString()}'.");
TypeStack.Pop();
// local function
void InitializeTypes()
{
if (reg.Type.IsEnumerable())
InitializeList(reg);
else
InitializeType(reg);
if (reg.Lifestyle == Lifestyle.Undefined)
reg.Lifestyle = (DefaultLifestyle == DefaultLifestyle.Singleton)
? Lifestyle.Singleton : Lifestyle.Transient;
if (reg.Lifestyle == Lifestyle.Singleton)
{
if (reg.Factory == null)
throw new Exception("Factory is null.");
var instance = reg.Factory();
reg.Factory = () => instance;
reg.Expression = Expression.Constant(instance);
}
}
}
private void InitializeType(Registration reg)
{
if (reg.TypeConcrete == null)
reg.TypeConcrete = AllTypesConcrete.Value.FindConcreteType(reg.Type);
var ctor = reg.TypeConcrete.GetConstructor();
var parameters = ctor.GetParameters()
.Select(GetValueOfParameter)
.ToArray();
Logger.LogDebug($"Constructing type '{reg.TypeConcrete.AsString()}" +
$"({parameters.Select(p => (p == null ? "" : p.Type.AsString())).JoinStrings(", ")})'.");
reg.Expression = Expression.New(ctor, parameters);
reg.Factory = Expression.Lambda<Func<object>>(reg.Expression).Compile();
// local function
Expression GetValueOfParameter(ParameterInfo p)
{
var type = p.ParameterType;
if (type.IsByRef)
{
if (!p.GetCustomAttributes().Any(x => x.ToString().EndsWith("IsReadOnlyAttribute")))
throw new TypeAccessException($"Invalid ref or out parameter type '{type.Name}'.");
type = type.GetElementType(); // support 'In' parameter type only
}
if (p.HasDefaultValue)
return Expression.Constant(p.DefaultValue, type);
return GetOrAddExpression(type, reg);
}
}
private void InitializeList(Registration reg)
{
var genericType = reg.Type.GenericTypeArguments.Single().GetTypeInfo();
var assignableTypes = (DefaultLifestyle == DefaultLifestyle.Undefined
? Registrations.Values.Select(r => r.Type) : AllTypesConcrete.Value)
.Where(t => genericType.IsAssignableFrom(t)).ToList();
if (!assignableTypes.Any())
throw new TypeAccessException($"No types found assignable to generic type '{genericType.AsString()}'.");
if (assignableTypes.Any(IsTransientRegistration))
{
if (reg.Lifestyle == Lifestyle.Singleton || reg.Lifestyle == Lifestyle.Instance)
throw new TypeAccessException($"Captive dependency: the singleton list '{reg.Type.AsString()}' depends on one of more transient items.");
reg.Lifestyle = Lifestyle.Transient;
}
var expressions = assignableTypes.Select(t => GetOrAddExpression(t.AsType(), reg)).ToList();
Logger.LogDebug($"Constructing list of {expressions.Count} types assignable to '{genericType.AsString()}'.");
reg.Expression = Expression.NewArrayInit(genericType.AsType(), expressions);
reg.Factory = Expression.Lambda<Func<object>>(reg.Expression).Compile();
// local function
bool IsTransientRegistration(TypeInfo type) =>
(Registrations.TryGetValue(type.AsType(), out Registration r) ||
(type.GetFuncArgumentType(out TypeInfo? funcType) && funcType != null && Registrations.TryGetValue(funcType.AsType(), out r))) &&
(r.Lifestyle == Lifestyle.Transient || r.Lifestyle == Lifestyle.Factory);
}
//////////////////////////////////////////////////////////////////////////////
public override string ToString()
{
var regs = Registrations.Values.Select(r => r.ToString()).ToList();
return new StringBuilder()
.AppendLine($"Container: {DefaultLifestyle}, {regs.Count} registered types:")
.AppendLine(regs.JoinStrings(Environment.NewLine))
.ToString();
}
/// <summary>
/// Disposing the container disposes any registered disposable singletons and instances.
/// </summary>
public void Dispose()
{
foreach (var disposable in Registrations.Values
.Where(r => r.Lifestyle == Lifestyle.Singleton || r.Lifestyle == Lifestyle.Instance)
.Select(r => r.Factory)
.Where(f => f != null)
.Select(f => new Func<object>(f!))
.Select(f => f())
.Where(i => i != null && i != this)
.OfType<IDisposable>())
{
Logger.LogTrace($"Disposing type '{disposable.GetType().AsString()}'.");
disposable.Dispose();
}
Registrations.Clear();
Logger.LogTrace("Container disposed.");
}
}
}
| |
namespace FakeItEasy.Specs
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using FakeItEasy.Core;
using FakeItEasy.Creation;
using FakeItEasy.Tests.TestHelpers;
using FluentAssertions;
using Xbehave;
using Xunit;
public abstract class CreationSpecsBase
{
[SuppressMessage("Microsoft.Design", "CA1040:AvoidEmptyInterfaces", Justification = "It's just used for testing.")]
public interface ICollectionItem
{
}
public interface IInterfaceWithSimilarMethods
{
void Test1<T>(IEnumerable<T> enumerable);
void Test1<T>(IList<T> enumerable);
}
[SuppressMessage("Microsoft.Design", "CA1040:AvoidEmptyInterfaces", Justification = "It's just used for testing.")]
public interface IInterface
{
}
public interface IFakeCreator
{
Type FakeType { get; }
object CreateFake(CreationSpecsBase specs);
}
[Scenario]
[MemberData(nameof(SupportedTypes))]
public void FakingSupportedTypes(IFakeCreator fakeCreator, object fake)
{
"Given a supported fake type"
.See(fakeCreator.FakeType.ToString());
"When I create a fake of the supported type"
.x(() => fake = fakeCreator.CreateFake(this));
"Then the result is a fake"
.x(() => Fake.GetFakeManager(fake).Should().NotBeNull());
"And the fake is of the correct type"
.x(() => fake.Should().BeAssignableTo(fakeCreator.FakeType));
}
[Scenario]
public void ThrowingConstructor(
Exception exception)
{
"Given a class with a parameterless constructor"
.See<ClassWhoseConstructorThrows>();
"And the constructor throws an exception"
.See(() => new ClassWhoseConstructorThrows());
"When I create a fake of the class"
.x(() => exception = Record.Exception(() => this.CreateFake<ClassWhoseConstructorThrows>()));
"Then it throws a fake creation exception"
.x(() => exception.Should().BeOfType<FakeCreationException>());
"And the exception message indicates why construction failed"
.x(() => exception.Message.Should().StartWithModuloLineEndings(@"
Failed to create fake of type FakeItEasy.Specs.CreationSpecsBase+ClassWhoseConstructorThrows:
Below is a list of reasons for failure per attempted constructor:
Constructor with signature () failed:
No usable default constructor was found on the type FakeItEasy.Specs.CreationSpecsBase+ClassWhoseConstructorThrows.
An exception of type System.NotSupportedException was caught during this call. Its message was:
I don't like being constructed.
"));
"And the exception message includes the original exception stack trace"
.x(() => exception.Message.Should().Contain("FakeItEasy.Specs.CreationSpecsBase.ClassWhoseConstructorThrows..ctor()"));
}
[Scenario]
public void FailureViaMultipleConstructors(
Exception exception)
{
"Given a class with multiple constructors"
.See<ClassWithMultipleConstructors>();
"And one constructor throws"
.See(() => new ClassWithMultipleConstructors());
"And another constructor throws"
.See(() => new ClassWithMultipleConstructors(string.Empty));
"And a third constructor has an argument that cannot be resolved"
.See(() => new ClassWithMultipleConstructors(new UnresolvableArgument(), string.Empty));
"When I create a fake of the class"
.x(() => exception = Record.Exception(() => this.CreateFake<ClassWithMultipleConstructors>()));
"Then it throws a fake creation exception"
.x(() => exception.Should().BeOfType<FakeCreationException>());
"And the exception message indicates why construction failed"
.x(() => exception.Message.Should().MatchModuloLineEndings(@"
Failed to create fake of type FakeItEasy.Specs.CreationSpecsBase+ClassWithMultipleConstructors:
Below is a list of reasons for failure per attempted constructor:
Constructor with signature () failed:
No usable default constructor was found on the type FakeItEasy.Specs.CreationSpecsBase+ClassWithMultipleConstructors.
An exception of type System.Exception was caught during this call. Its message was:
parameterless constructor failed
*FakeItEasy.Specs.CreationSpecsBase.ClassWithMultipleConstructors..ctor()*
Constructor with signature (System.String) failed:
No constructor matches the passed arguments for constructor.
An exception of type System.Exception was caught during this call. Its message was:
string constructor failed
with reason on two lines
*FakeItEasy.Specs.CreationSpecsBase.ClassWithMultipleConstructors..ctor(String s)*
The constructors with the following signatures were not tried:
(*FakeItEasy.Specs.CreationSpecsBase+UnresolvableArgument, System.String)
Types marked with * could not be resolved. Please provide a Dummy Factory to enable these constructors.
"));
}
// This spec proves that we can cope with throwing constructors (e.g. ensures that FakeManagers won't be reused):
[Scenario]
public void UseSuccessfulConstructor(
FakedClass fake,
IEnumerable<int> parameterListLengthsForAttemptedConstructors)
{
"Given a class with multiple constructors"
.See<FakedClass>();
"And the parameterless constructor throws"
.See(() => new FakedClass());
"And the class has a one-parameter constructor"
.See(() => new FakedClass(new ArgumentThatShouldNeverBeResolved()));
"And the class has a two-parameter constructor"
.See(() => new FakedClass(A.Dummy<IDisposable>(), string.Empty));
"When I create a fake of the class"
.x(() =>
{
lock (FakedClass.ParameterListLengthsForAttemptedConstructors)
{
FakedClass.ParameterListLengthsForAttemptedConstructors.Clear();
fake = this.CreateFake<FakedClass>();
parameterListLengthsForAttemptedConstructors = new List<int>(FakedClass.ParameterListLengthsForAttemptedConstructors);
}
});
"Then the fake is instantiated using the two-parameter constructor"
.x(() => fake.WasTwoParameterConstructorCalled.Should().BeTrue());
"And the fake doesn't remember the failing constructor call"
.x(() => fake.WasParameterlessConstructorCalled
.Should().BeFalse("because the parameterless constructor was called for a different fake object"));
"And the one-parameter constructor was not tried"
.x(() => parameterListLengthsForAttemptedConstructors.Should().NotContain(1));
"And the argument for the unused constructor was never resolved"
.x(() => ArgumentThatShouldNeverBeResolved.WasResolved.Should().BeFalse());
}
[Scenario]
public void CacheSuccessfulConstructor(
ClassWhosePreferredConstructorsThrow fake1,
ClassWhosePreferredConstructorsThrow fake2)
{
"Given a class with multiple constructors"
.See<ClassWhosePreferredConstructorsThrow>();
"And the class has a parameterless constructor that throws"
.See(() => new ClassWhosePreferredConstructorsThrow());
"And the class has a two-parameter constructor that throws"
.See(() => new ClassWhosePreferredConstructorsThrow(A.Dummy<IDisposable>(), string.Empty));
"And the class has a one-parameter constructor that succeeds"
.See(() => new ClassWhosePreferredConstructorsThrow(default));
// If multiple theads attempt to create the fake at the same time, the
// unsuccessful constructors may be called more than once, so serialize fake
// creation for this test.
"And nobody else is trying to fake the class right now"
.x(() => Monitor.TryEnter(ClassWhosePreferredConstructorsThrow.SyncRoot, TimeSpan.FromSeconds(30)).Should().BeTrue("we must enter the monitor"))
.Teardown(() => Monitor.Exit(ClassWhosePreferredConstructorsThrow.SyncRoot));
"When I create a fake of the class"
.x(() => fake1 = this.CreateFake<ClassWhosePreferredConstructorsThrow>());
"And I create another fake of the class"
.x(() => fake2 = this.CreateFake<ClassWhosePreferredConstructorsThrow>());
"Then the two fakes are distinct"
.x(() => fake1.Should().NotBeSameAs(fake2));
"And the parameterless constructor was only called once"
.x(() => ClassWhosePreferredConstructorsThrow.NumberOfTimesParameterlessConstructorWasCalled.Should().Be(1));
"And the two-parameter constructor was only called once"
.x(() => ClassWhosePreferredConstructorsThrow.NumberOfTimesTwoParameterConstructorWasCalled.Should().Be(1));
}
public class ClassWhosePreferredConstructorsThrow
{
public static readonly object SyncRoot = new object();
public static int NumberOfTimesParameterlessConstructorWasCalled => numberOfTimesParameterlessConstructorWasCalled;
public static int NumberOfTimesTwoParameterConstructorWasCalled => numberOfTimesTwoParameterConstructorWasCalled;
private static int numberOfTimesTwoParameterConstructorWasCalled;
private static int numberOfTimesParameterlessConstructorWasCalled;
public ClassWhosePreferredConstructorsThrow()
{
Interlocked.Increment(ref numberOfTimesParameterlessConstructorWasCalled);
throw new NotImplementedException();
}
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "anInt", Justification = "This is just a dummy argument.")]
public ClassWhosePreferredConstructorsThrow(int anInt)
{
}
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "disposable", Justification = "This is just a dummy argument.")]
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "aString", Justification = "This is just a dummy argument.")]
public ClassWhosePreferredConstructorsThrow(IDisposable disposable, string aString)
{
Interlocked.Increment(ref numberOfTimesTwoParameterConstructorWasCalled);
throw new NotImplementedException();
}
}
[Scenario]
[Example(2)]
[Example(10)]
public void CollectionOfFake(
int count,
IList<ICollectionItem> fakes)
{
"When I create a collection of {0} fakes"
.x(() => fakes = this.CreateCollectionOfFake<ICollectionItem>(count));
"Then {0} items are created"
.x(() => fakes.Should().HaveCount(count));
"And all items extend the specified type"
.x(() => fakes.Should().ContainItemsAssignableTo<ICollectionItem>());
"And all items are fakes"
.x(() => fakes.Should().OnlyContain(item => Fake.GetFakeManager(item) is object));
}
[Scenario]
[Example(2)]
[Example(10)]
public void CollectionOfFakeWithOptionBuilder(
int count,
IList<ICollectionItem> fakes)
{
"When I create a collection of {0} fakes that also implement another interface"
.x(() => fakes = this.CreateCollectionOfFake<ICollectionItem>(count, options => options.Implements<IDisposable>()));
"Then {0} items are created"
.x(() => fakes.Should().HaveCount(count));
"And all items extend the specified type and the extra interface"
.x(() => fakes.Should().ContainItemsAssignableTo<ICollectionItem>().And.ContainItemsAssignableTo<IDisposable>());
"And all items are fakes"
.x(() => fakes.Should().OnlyContain(item => Fake.GetFakeManager(item) is object));
}
[Scenario]
public void InterfaceWithAlikeGenericMethod(IInterfaceWithSimilarMethods fake)
{
"Given an interface with an overloaded methods containing generic arguments"
.See<IInterfaceWithSimilarMethods>();
"When I create a fake of the interface"
.x(() => fake = this.CreateFake<IInterfaceWithSimilarMethods>());
"Then the fake is created"
.x(() => fake.Should().BeAFake());
}
[Scenario]
public void PrivateClassCannotBeFaked(Exception exception)
{
"Given a private class"
.See<PrivateClass>();
"When I create a fake of the class"
.x(() => exception = Record.Exception(this.CreateFake<PrivateClass>));
"Then it throws a fake creation exception"
.x(() => exception.Should().BeOfType<FakeCreationException>());
"And the exception message indicates the reason for failure"
.x(() => exception.Message.Should().MatchModuloLineEndings(@"
Failed to create fake of type FakeItEasy.Specs.CreationSpecsBase+PrivateClass:
Below is a list of reasons for failure per attempted constructor:
Constructor with signature () failed:
No usable default constructor was found on the type FakeItEasy.Specs.CreationSpecsBase+PrivateClass.
An exception of type Castle.DynamicProxy.Generators.GeneratorException was caught during this call. Its message was:
Can not create proxy for type FakeItEasy.Specs.CreationSpecsBase+PrivateClass because it is not accessible. Make it public, or internal and mark your assembly with [assembly: InternalsVisibleTo(*DynamicProxyGenAssembly2*)] attribute*
"));
}
[Scenario]
public void PrivateDelegateCannotBeFaked(Exception exception)
{
"Given a private delegate"
.See<PrivateDelegate>();
"When I create a fake of the delegate"
.x(() => exception = Record.Exception(this.CreateFake<PrivateDelegate>));
"Then it throws a fake creation exception"
.x(() => exception.Should().BeOfType<FakeCreationException>());
"And the exception message indicates the reason for failure"
.x(() => exception.Message.Should().MatchModuloLineEndings(@"
Failed to create fake of type FakeItEasy.Specs.CreationSpecsBase+PrivateDelegate:
Can not create proxy for type FakeItEasy.Specs.CreationSpecsBase+PrivateDelegate because it is not accessible. Make it public, or internal and mark your assembly with [assembly: InternalsVisibleTo(*DynamicProxyGenAssembly2*)] attribute*
"));
}
[Scenario]
public void PublicDelegateWithPrivateTypeArgumentCannotBeFaked(Exception exception)
{
"Given a public delegate with a private type argument"
.See<Func<PrivateClass>>();
"When I create a fake of the delegate"
.x(() => exception = Record.Exception(this.CreateFake<Func<PrivateClass>>));
"Then it throws a fake creation exception"
.x(() => exception.Should().BeOfType<FakeCreationException>());
"And the exception message indicates the reason for failure"
.x(() => exception.Message.Should().MatchModuloLineEndings(@"
Failed to create fake of type System.Func`1[FakeItEasy.Specs.CreationSpecsBase+PrivateClass]:
Can not create proxy for type System.Func`1[[FakeItEasy.Specs.CreationSpecsBase+PrivateClass, FakeItEasy.Specs, Version=1.0.0.0, Culture=neutral, PublicKeyToken=eff28e2146d5fd2c]] because type FakeItEasy.Specs.CreationSpecsBase+PrivateClass is not accessible. Make it public, or internal and mark your assembly with [assembly: InternalsVisibleTo(*DynamicProxyGenAssembly2*)] attribute*
"));
}
[Scenario]
public void ClassWithPrivateConstructorCannotBeFaked(Exception exception)
{
"Given a class with a private constructor"
.See<ClassWithPrivateConstructor>();
"When I create a fake of the class"
.x(() => exception = Record.Exception(this.CreateFake<ClassWithPrivateConstructor>));
"Then it throws a fake creation exception"
.x(() => exception.Should().BeOfType<FakeCreationException>());
"And the exception message indicates the reason for failure"
.x(() => exception.Message.Should().StartWithModuloLineEndings(@"
Failed to create fake of type FakeItEasy.Specs.CreationSpecsBase+ClassWithPrivateConstructor:
Below is a list of reasons for failure per attempted constructor:
Constructor with signature () failed:
No usable default constructor was found on the type FakeItEasy.Specs.CreationSpecsBase+ClassWithPrivateConstructor.
An exception of type Castle.DynamicProxy.InvalidProxyConstructorArgumentsException was caught during this call. Its message was:
Can not instantiate proxy of class: FakeItEasy.Specs.CreationSpecsBase+ClassWithPrivateConstructor.
Could not find a parameterless constructor.
"));
}
[Scenario]
public void SealedClassCannotBeFaked(Exception exception)
{
"Given a sealed class"
.See<SealedClass>();
"When I create a fake of the class"
.x(() => exception = Record.Exception(() => this.CreateFake<SealedClass>()));
"Then it throws a fake creation exception"
.x(() => exception.Should().BeOfType<FakeCreationException>());
"And the exception message indicates the reason for failure"
.x(() => exception.Message.Should().BeModuloLineEndings(@"
Failed to create fake of type FakeItEasy.Specs.CreationSpecsBase+SealedClass:
The type of proxy FakeItEasy.Specs.CreationSpecsBase+SealedClass is sealed.
"));
}
[Scenario]
public void CannotFakeInterfaceWithConstructorArguments(Exception exception)
{
"Given a fakeable interface"
.See<IInterface>();
"When I create a fake of the interface supplying constructor arguments"
.x(() => exception = Record.Exception(() => this.CreateFake<IInterface>(options =>
options.WithArgumentsForConstructor(new object[] { 7 }))));
"Then it throws a fake creation exception"
.x(() => exception.Should().BeOfType<ArgumentException>());
"And the exception message indicates the reason for failure"
.x(() => exception.Message.Should().Be("Arguments for constructor specified for interface type."));
}
[Scenario]
public void SuppliedConstructorArgumentsArePassedToClassConstructor(AClassThatCouldBeFakedWithTheRightConstructorArguments fake)
{
"Given a fakeable class"
.See<AClassThatCouldBeFakedWithTheRightConstructorArguments>();
"When I create a fake of the class supplying valid constructor arguments"
.x(() => fake = this.CreateFake<AClassThatCouldBeFakedWithTheRightConstructorArguments>(options =>
options.WithArgumentsForConstructor(() => new AClassThatCouldBeFakedWithTheRightConstructorArguments(17))));
"Then it passes the supplied arguments to the constructor"
.x(() => fake.ID.Should().Be(17));
}
[Scenario]
public void CannotFakeWithBadConstructorArguments(Exception exception)
{
"Given a fakeable class"
.See<AClassThatCouldBeFakedWithTheRightConstructorArguments>();
"When I create a fake of the class supplying invalid constructor arguments"
.x(() => exception = Record.Exception(() => this.CreateFake<AClassThatCouldBeFakedWithTheRightConstructorArguments>(options =>
options.WithArgumentsForConstructor(new object[] { 7, "magenta" }))));
"Then it throws a fake creation exception"
.x(() => exception.Should().BeOfType<FakeCreationException>());
"And the exception message indicates the reason for failure"
.x(() => exception.Message.Should().StartWithModuloLineEndings(@"
Failed to create fake of type FakeItEasy.Specs.CreationSpecsBase+AClassThatCouldBeFakedWithTheRightConstructorArguments:
No constructor matches the passed arguments for constructor.
An exception of type Castle.DynamicProxy.InvalidProxyConstructorArgumentsException was caught during this call. Its message was:
Can not instantiate proxy of class: FakeItEasy.Specs.CreationSpecsBase+AClassThatCouldBeFakedWithTheRightConstructorArguments.
Could not find a constructor that would match given arguments:
System.Int32
System.String"));
}
[Scenario]
public void FakeDelegateCreation(Func<int> fake)
{
"Given a delegate"
.See<Func<int>>();
"When I create a fake of the delegate"
.x(() => fake = this.CreateFake<Func<int>>());
"Then it creates the fake"
.x(() => fake.Should().NotBeNull());
}
[Scenario]
public void FakeDelegateCreationWithAttributes(Exception exception)
{
"Given a delegate"
.See<Func<int>>();
"When I create a fake of the delegate with custom attributes"
.x(() => exception = Record.Exception(() => this.CreateFake<Func<int>>(options => options.WithAttributes(() => new ObsoleteAttribute()))));
"Then it throws a fake creation exception"
.x(() => exception.Should().BeOfType<FakeCreationException>());
"And the exception message indicates the reason for failure"
.x(() => exception.Message.Should().BeModuloLineEndings(@"
Failed to create fake of type System.Func`1[System.Int32]:
Faked delegates cannot have custom attributes applied to them.
"));
}
[Scenario]
public void FakeDelegateCreationWithArgumentsForConstructor(Exception exception)
{
"Given a delegate"
.See<Func<int>>();
"When I create a fake of the delegate using explicit constructor arguments"
.x(() => exception = Record.Exception(() => this.CreateFake<Func<int>>(options => options.WithArgumentsForConstructor(new object[] { 7 }))));
"Then it throws a fake creation exception"
.x(() => exception.Should().BeOfType<FakeCreationException>());
"And the exception message indicates the reason for failure"
.x(() => exception.Message.Should().BeModuloLineEndings(@"
Failed to create fake of type System.Func`1[System.Int32]:
Faked delegates cannot be made using explicit constructor arguments.
"));
}
[Scenario]
public void FakeDelegateCreationWithAdditionalInterfaces(Exception exception)
{
"Given a delegate"
.See<Func<int>>();
"When I create a fake of the delegate with additional implemented interfaces"
.x(() => exception = Record.Exception(() => this.CreateFake<Func<int>>(options => options.Implements<IList<string>>())));
"Then it throws a fake creation exception"
.x(() => exception.Should().BeOfType<FakeCreationException>());
"And the exception message indicates the reason for failure"
.x(() => exception.Message.Should().BeModuloLineEndings(@"
Failed to create fake of type System.Func`1[System.Int32]:
Faked delegates cannot be made to implement additional interfaces.
"));
}
[Scenario]
public void NamedFakeToString(object fake, string? toStringResult)
{
"Given a named fake"
.x(() => fake = A.Fake<object>(o => o.Named("Foo")));
"When I call ToString() on the fake"
.x(() => toStringResult = fake.ToString());
"Then it returns the configured name of the fake"
.x(() => toStringResult.Should().Be("Foo"));
}
[Scenario]
public void NamedFakeAsArgument(object fake, Action<object> fakeAction, Exception exception)
{
"Given a named fake"
.x(() => fake = A.Fake<object>(o => o.Named("Foo")));
"And a fake action that takes an object as the parameter"
.x(() => fakeAction = A.Fake<Action<object>>());
"When I assert that the fake action was called with the named fake"
.x(() => exception = Record.Exception(() => A.CallTo(() => fakeAction(fake)).MustHaveHappened()));
"Then the exception message describes the named fake by its name"
.x(() => exception.Message.Should().Contain(".Invoke(obj: Foo)"));
}
[Scenario]
public void NamedFakeDelegateToString(Action fake, string? toStringResult)
{
"Given a named delegate fake"
.x(() => fake = A.Fake<Action>(o => o.Named("Foo")));
"When I call ToString() on the fake"
.x(() => toStringResult = fake.ToString());
"Then it returns the name of the faked object type, because ToString() can't be faked for a delegate"
.x(() => toStringResult.Should().Be("System.Action"));
}
[Scenario]
public void NamedFakeDelegateAsArgument(Action fake, Action<Action> fakeAction, Exception exception)
{
"Given a named delegate fake"
.x(() => fake = A.Fake<Action>(o => o.Named("Foo")));
"And a fake action that takes an action as the parameter"
.x(() => fakeAction = A.Fake<Action<Action>>());
"When I assert that the fake action was called with the named fake"
.x(() => exception = Record.Exception(() => A.CallTo(() => fakeAction(fake)).MustHaveHappened()));
"Then the exception message describes the named fake by its name"
.x(() => exception.Message.Should().Contain(".Invoke(obj: Foo)"));
}
[Scenario]
public void AvoidLongSelfReferentialConstructor(
ClassWithLongSelfReferentialConstructor fake1,
ClassWithLongSelfReferentialConstructor fake2)
{
"Given a class with multiple constructors"
.See<ClassWithLongSelfReferentialConstructor>();
"And the class has a one-parameter constructor not using its own type"
.See(() => new ClassWithLongSelfReferentialConstructor(typeof(object)));
"And the class has a two-parameter constructor using its own type"
.See(() => new ClassWithLongSelfReferentialConstructor(typeof(object), A.Dummy<ClassWithLongSelfReferentialConstructor>()));
"When I create a fake of the class"
.x(() => fake1 = A.Fake<ClassWithLongSelfReferentialConstructor>());
"And I create another fake of the class"
.x(() => fake2 = A.Fake<ClassWithLongSelfReferentialConstructor>());
"Then the first fake is not null"
.x(() => fake1.Should().NotBeNull());
"And it was created using the one-parameter constructor"
.x(() => fake1.NumberOfConstructorParameters.Should().Be(1));
"And the second fake is not null"
.x(() => fake2.Should().NotBeNull());
"And it was created using the one-parameter constructor"
.x(() => fake2.NumberOfConstructorParameters.Should().Be(1));
}
protected abstract T CreateFake<T>() where T : class;
protected abstract T CreateFake<T>(Action<IFakeOptions<T>> optionsBuilder) where T : class;
protected abstract IList<T> CreateCollectionOfFake<T>(int numberOfFakes) where T : class;
protected abstract IList<T> CreateCollectionOfFake<T>(int numberOfFakes, Action<IFakeOptions<T>> optionsBuilder) where T : class;
public class ClassWhoseConstructorThrows
{
public ClassWhoseConstructorThrows()
{
throw new NotSupportedException("I don't like being constructed.");
}
}
public class FakedClass
{
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "This anti-pattern is part of the the tested scenario.")]
public FakedClass()
{
ParameterListLengthsForAttemptedConstructors.Add(0);
this.WasParameterlessConstructorCalled = true;
throw new InvalidOperationException();
}
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "This anti-pattern is part of the the tested scenario.")]
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "someInterface", Justification = "This is just a dummy argument.")]
public FakedClass(ArgumentThatShouldNeverBeResolved argument)
{
ParameterListLengthsForAttemptedConstructors.Add(1);
}
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "This anti-pattern is part of the the tested scenario.")]
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "someInterface", Justification = "This is just a dummy argument.")]
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "someName", Justification = "This is just a dummy argument.")]
public FakedClass(IDisposable someInterface, string someName)
{
ParameterListLengthsForAttemptedConstructors.Add(2);
this.WasTwoParameterConstructorCalled = true;
}
public static ISet<int> ParameterListLengthsForAttemptedConstructors { get; } = new SortedSet<int>();
public bool WasParameterlessConstructorCalled { get; set; }
public bool WasTwoParameterConstructorCalled { get; set; }
}
public sealed class ArgumentThatShouldNeverBeResolved
{
public static bool WasResolved { get; private set; }
public ArgumentThatShouldNeverBeResolved()
{
WasResolved = true;
}
}
public sealed class SealedClass
{
}
public struct Struct
{
}
public class AClassThatCouldBeFakedWithTheRightConstructorArguments
{
public AClassThatCouldBeFakedWithTheRightConstructorArguments(int id)
{
this.ID = id;
}
public int ID { get; }
}
public sealed class UnresolvableArgument
{
public UnresolvableArgument() => throw new InvalidOperationException();
}
public class ClassWithMultipleConstructors
{
public ClassWithMultipleConstructors() => throw new Exception("parameterless constructor failed");
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "s", Justification = "Required for testing.")]
public ClassWithMultipleConstructors(string s) => throw new Exception("string constructor failed" + Environment.NewLine + "with reason on two lines");
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "u", Justification = "Required for testing.")]
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "s", Justification = "Required for testing.")]
public ClassWithMultipleConstructors(UnresolvableArgument u, string s)
{
}
}
public abstract class AbstractClass
{
}
public class ClassWithProtectedConstructor
{
protected ClassWithProtectedConstructor()
{
}
}
public class ClassWithPrivateConstructor
{
private ClassWithPrivateConstructor()
{
}
}
private static IEnumerable<object?[]> SupportedTypes() => TestCases.FromObject(
new FakeCreator<IInterface>(),
new FakeCreator<AbstractClass>(),
new FakeCreator<ClassWithProtectedConstructor>(),
new FakeCreator<ClassWithInternalConstructorVisibleToDynamicProxy>(),
new FakeCreator<InternalClassVisibleToDynamicProxy>(),
new FakeCreator<Action>(),
new FakeCreator<Func<int, string>>(),
new FakeCreator<EventHandler<EventArgs>>());
private class FakeCreator<TFake> : IFakeCreator where TFake : class
{
public Type FakeType => typeof(TFake);
public object CreateFake(CreationSpecsBase testRunner)
{
return testRunner.CreateFake<TFake>();
}
public override string ToString() => typeof(TFake).Name;
}
[SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Required for testing.")]
private class PrivateClass
{
}
private delegate void PrivateDelegate();
}
public class GenericCreationSpecs : CreationSpecsBase
{
protected override T CreateFake<T>()
{
return A.Fake<T>();
}
protected override T CreateFake<T>(Action<IFakeOptions<T>> optionsBuilder)
{
return A.Fake(optionsBuilder);
}
protected override IList<T> CreateCollectionOfFake<T>(int numberOfFakes)
{
return A.CollectionOfFake<T>(numberOfFakes);
}
protected override IList<T> CreateCollectionOfFake<T>(int numberOfFakes, Action<IFakeOptions<T>> optionsBuilder)
{
return A.CollectionOfFake(numberOfFakes, optionsBuilder);
}
}
public class NonGenericCreationSpecs : CreationSpecsBase
{
[Scenario]
public void StructCannotBeFaked(Exception exception)
{
"Given a struct"
.See<Struct>();
"When I create a fake of the struct"
.x(() => exception = Record.Exception(() => (Struct)Sdk.Create.Fake(typeof(Struct))));
"Then it throws a fake creation exception"
.x(() => exception.Should().BeOfType<FakeCreationException>());
"And the exception message indicates the reason for failure"
.x(() => exception.Message.Should().StartWithModuloLineEndings(@"
Failed to create fake of type FakeItEasy.Specs.CreationSpecsBase+Struct:
The type of proxy must be an interface or a class but it was FakeItEasy.Specs.CreationSpecsBase+Struct.
"));
}
protected override T CreateFake<T>()
{
return (T)Sdk.Create.Fake(typeof(T));
}
protected override T CreateFake<T>(Action<IFakeOptions<T>> optionsBuilder)
{
return (T)Sdk.Create.Fake(typeof(T), options => optionsBuilder((IFakeOptions<T>)options));
}
protected override IList<T> CreateCollectionOfFake<T>(int numberOfFakes)
{
return Sdk.Create.CollectionOfFake(typeof(T), numberOfFakes).Cast<T>().ToList();
}
protected override IList<T> CreateCollectionOfFake<T>(int numberOfFakes, Action<IFakeOptions<T>> optionsBuilder)
{
return Sdk.Create.CollectionOfFake(typeof(T), numberOfFakes, options => optionsBuilder((IFakeOptions<T>)options)).Cast<T>().ToList();
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="Transactions.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
* Transactions support for ASP.NET pages
*
* Copyright (c) 2000, Microsoft Corporation
*/
namespace System.Web.Util {
using System.Collections;
using System.EnterpriseServices;
using System.Security.Permissions;
//
// Delegate to the transacted managed code
//
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public delegate void TransactedCallback();
//
// Delegate for the internal transacted execution
//
internal enum TransactedExecState {
CommitPending = 0,
AbortPending = 1,
Error = 2
}
internal delegate int TransactedExecCallback(); // return value 'int' for interop
//
// Utility class with to be called to do transactions
//
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public class Transactions {
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static void InvokeTransacted(TransactedCallback callback, TransactionOption mode) {
bool aborted = false;
InvokeTransacted(callback, mode, ref aborted);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static void InvokeTransacted(TransactedCallback callback, TransactionOption mode, ref bool transactionAborted) {
// check for hosting permission even if no user code on the stack
HttpRuntime.CheckAspNetHostingPermission(AspNetHostingPermissionLevel.Medium, SR.Transaction_not_supported_in_low_trust);
bool executeWithoutTransaction = false;
#if !FEATURE_PAL // FEATURE_PAL does not enable Transactions
if (Environment.OSVersion.Platform != PlatformID.Win32NT || Environment.OSVersion.Version.Major <= 4)
throw new PlatformNotSupportedException(SR.GetString(SR.RequiresNT));
#else // !FEATURE_PAL
throw new NotImplementedException("ROTORTODO");
#endif // !FEATURE_PAL
if (mode == TransactionOption.Disabled)
executeWithoutTransaction = true;
if (executeWithoutTransaction) {
// bypass the transaction logic
callback();
transactionAborted = false;
return;
}
TransactedInvocation call = new TransactedInvocation(callback);
TransactedExecCallback execCallback = new TransactedExecCallback(call.ExecuteTransactedCode);
PerfCounters.IncrementCounter(AppPerfCounter.TRANSACTIONS_PENDING);
int rc;
try {
rc = UnsafeNativeMethods.TransactManagedCallback(execCallback, (int)mode);
}
finally {
PerfCounters.DecrementCounter(AppPerfCounter.TRANSACTIONS_PENDING);
}
// rethrow the expection originally caught in managed code
if (call.Error != null)
throw new HttpException(null, call.Error);
PerfCounters.IncrementCounter(AppPerfCounter.TRANSACTIONS_TOTAL);
if (rc == 1) {
PerfCounters.IncrementCounter(AppPerfCounter.TRANSACTIONS_COMMITTED);
transactionAborted = false;
}
else if (rc == 0) {
PerfCounters.IncrementCounter(AppPerfCounter.TRANSACTIONS_ABORTED);
transactionAborted = true;
}
else {
throw new HttpException(SR.GetString(SR.Cannot_execute_transacted_code));
}
}
// Class with wrappers to ContextUtil that don't throw
internal class Utils {
private Utils() {
}
/*
internal static String TransactionId {
get {
String id = null;
try {
id = ContextUtil.TransactionId.ToString();
}
catch {
}
return id;
}
}
*/
internal static bool IsInTransaction {
get {
bool inTransaction = false;
try {
inTransaction = ContextUtil.IsInTransaction;
}
catch {
}
return inTransaction;
}
}
internal static bool AbortPending {
get {
bool aborted = false;
try {
if (ContextUtil.MyTransactionVote == TransactionVote.Abort)
aborted = true;
}
catch {
}
return aborted;
}
}
}
// Managed class encapsulating the transacted call
internal class TransactedInvocation {
private TransactedCallback _callback;
private Exception _error;
internal TransactedInvocation(TransactedCallback callback) {
_callback = callback;
}
internal int ExecuteTransactedCode() {
TransactedExecState state = TransactedExecState.CommitPending;
try {
_callback();
if (Transactions.Utils.AbortPending)
state = TransactedExecState.AbortPending;
}
catch (Exception e) {
_error = e; // remember exception to be rethrown back in managed code
state = TransactedExecState.Error;
}
return (int)state;
}
internal Exception Error {
get { return _error; }
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Runtime.Serialization;
namespace HTLib2
{
public partial class Matlab
{
public class NumericSolver : HTLib2.NumericSolver
{
static NumericSolver _singletol = null;
public static void Register()
{
if(_singletol != null)
return;
_singletol = new NumericSolver();
NumericSolver.Register(_singletol);
}
public static void Unregister()
{
if(_singletol == null)
return;
NumericSolver.Unregister(_singletol);
_singletol = null;
}
protected override bool InvImpl(Matrix mat, out Matrix inv, InfoPack extra)
{
NamedLock.FuncO<Matrix,bool> func = delegate(out Matrix linv)
{
Matlab.Clear("HTLib2_Matlab_InvImpl");
Matlab.PutMatrix("HTLib2_Matlab_InvImpl", mat.ToArray());
if(extra != null)
extra.SetValue("rank", Matlab.GetValueInt("rank(HTLib2_Matlab_InvImpl)"));
Matlab.Execute("HTLib2_Matlab_InvImpl = inv(HTLib2_Matlab_InvImpl);");
linv = Matlab.GetMatrix("HTLib2_Matlab_InvImpl");
Matlab.Clear("HTLib2_Matlab_InvImpl");
return true;
};
//return NamedLock.LockedCall("bool HTLib2.Matlab.NumericSolver.InvImpl(Matrix , out Matrix , InfoPack)", func, out inv);
return NamedLock.LockedCall(Matlab.NamedLock.GetName("HTLib2_Matlab_InvImpl"), func, out inv);
}
protected override bool RankImpl(Matrix mat, out int rank)
{
NamedLock.FuncO<int,bool> func = delegate(out int lrank)
{
string varname = "HTLib2_Matlab_RankImpl";
Matlab.Clear(varname);
Matlab.PutMatrix(varname, mat.ToArray());
lrank = Matlab.GetValueInt("rank("+varname+")");
Matlab.Clear(varname);
return true;
};
//return NamedLock.LockedCall("bool HTLib2.Matlab.NumericSolver.RankImpl(Matrix, out int)", func, out rank);
return NamedLock.LockedCall(Matlab.NamedLock.GetName("HTLib2_Matlab_RankImpl"), func, out rank);
}
protected override bool PinvImpl(Matrix mat, out Matrix pinv, InfoPack extra)
{
NamedLock.FuncO<Matrix,bool> func = delegate(out Matrix lpinv)
{
Matlab.Clear("HTLib2_Matlab_PinvImpl");
Matlab.PutMatrix("HTLib2_Matlab_PinvImpl", mat.ToArray());
if(extra != null)
extra.SetValue("rank", Matlab.GetValueInt("rank(HTLib2_Matlab_PinvImpl)"));
Matlab.Execute("HTLib2_Matlab_PinvImpl = pinv(HTLib2_Matlab_PinvImpl);");
lpinv = Matlab.GetMatrix("HTLib2_Matlab_PinvImpl");
Matlab.Clear("HTLib2_Matlab_PinvImpl");
return true;
};
//return NamedLock.LockedCall("bool HTLib2.Matlab.NumericSolver.PinvImpl(Matrix, out Matrix, InfoPack)", func, out pinv);
return NamedLock.LockedCall(Matlab.NamedLock.GetName("HTLib2_Matlab_PinvImpl"), func, out pinv);
}
protected override bool CorrImpl(Vector vec1, Vector vec2, out double corr)
{
NamedLock.FuncO<double,bool> func = delegate(out double lcorr)
{
Matlab.Clear("HTLib2_Matlab_CorrImpl");
Matlab.PutVector("HTLib2_Matlab_CorrImpl.vec1", vec1.ToArray());
Matlab.PutVector("HTLib2_Matlab_CorrImpl.vec2", vec2.ToArray());
Matlab.Execute("HTLib2_Matlab_CorrImpl.corr = corr(HTLib2_Matlab_CorrImpl.vec1, HTLib2_Matlab_CorrImpl.vec2);");
lcorr = Matlab.GetValue("HTLib2_Matlab_CorrImpl.corr");
Matlab.Clear("HTLib2_Matlab_CorrImpl");
return true;
};
//return NamedLock.LockedCall("bool HTLib2.Matlab.NumericSolver.CorrImpl(Vector, Vector, out double)", func, out corr);
return NamedLock.LockedCall(Matlab.NamedLock.GetName("HTLib2_Matlab_CorrImpl"), func, out corr);
}
protected override bool EigImpl(Matrix mat, out Matrix eigvec, out Vector eigval)
{
NamedLock.FuncOO<Matrix,Vector,bool> func = delegate(out Matrix leigvec, out Vector leigval)
{
bool bUseFile = (mat.ColSize*mat.ColSize > 1000*1000);
Matlab.Clear("HTLib2_Matlab_EigImpl");
Matlab.PutMatrix("HTLib2_Matlab_EigImpl.A", mat.ToArray(), bUseFile);
Matlab.Execute("[HTLib2_Matlab_EigImpl.V, HTLib2_Matlab_EigImpl.D] = eig(HTLib2_Matlab_EigImpl.A);");
Matlab.Execute("HTLib2_Matlab_EigImpl.D = diag(HTLib2_Matlab_EigImpl.D);");
leigvec = Matlab.GetMatrix("HTLib2_Matlab_EigImpl.V", bUseFile);
leigval = Matlab.GetVector("HTLib2_Matlab_EigImpl.D");
Matlab.Clear("HTLib2_Matlab_EigImpl");
return true;
};
//return NamedLock.LockedCall("bool HTLib2.Matlab.NumericSolver.EigImpl(Matrix, out Matrix, out Vector)", func, out eigvec, out eigval);
return NamedLock.LockedCall(Matlab.NamedLock.GetName("HTLib2_Matlab_EigImpl"), func, out eigvec, out eigval);
}
protected override bool EigImpl(Matrix A, Matrix B, out Matrix eigvec, out Vector eigval)
{
NamedLock.FuncOO<Matrix,Vector,bool> func = delegate(out Matrix leigvec, out Vector leigval)
{
Matlab.Clear("HTLib2_Matlab_EigImpl");
Matlab.PutMatrix("HTLib2_Matlab_EigImpl.A", A.ToArray());
Matlab.PutMatrix("HTLib2_Matlab_EigImpl.B", B.ToArray());
Matlab.Execute("[HTLib2_Matlab_EigImpl.V, HTLib2_Matlab_EigImpl.D] = eig(HTLib2_Matlab_EigImpl.A, HTLib2_Matlab_EigImpl.B);");
Matlab.Execute("HTLib2_Matlab_EigImpl.D = diag(HTLib2_Matlab_EigImpl.D);");
leigvec = Matlab.GetMatrix("HTLib2_Matlab_EigImpl.V");
leigval = Matlab.GetVector("HTLib2_Matlab_EigImpl.D");
Matlab.Clear("HTLib2_Matlab_EigImpl");
return true;
};
//return NamedLock.LockedCall("bool HTLib2.Matlab.NumericSolver.EigImpl(Matrix, Matrix, out Matrix, out Vector)", func, out eigvec, out eigval);
return NamedLock.LockedCall(Matlab.NamedLock.GetName("HTLib2_Matlab_EigImpl"), func, out eigvec, out eigval);
}
protected override bool InvEigImpl(Matrix mat, double? thresEigval, int? numZeroEigval, out Matrix inv, InfoPack extra)
{
NamedLock.FuncO<Matrix,bool> func = delegate(out Matrix linv)
{
Matlab.Clear("HTLib2_Matlab_InvEigImpl");
Matlab.PutMatrix("HTLib2_Matlab_InvEigImpl.A", mat.ToArray());
Matlab.PutValue("HTLib2_Matlab_InvEigImpl.ze", numZeroEigval.GetValueOrDefault(0));
Matlab.PutValue("HTLib2_Matlab_InvEigImpl.th", Math.Abs(thresEigval.GetValueOrDefault(0)));
Matlab.Execute("[HTLib2_Matlab_InvEigImpl.V, HTLib2_Matlab_InvEigImpl.D] = eig(HTLib2_Matlab_InvEigImpl.A);");
Matlab.Execute("HTLib2_Matlab_InvEigImpl.D = diag(HTLib2_Matlab_InvEigImpl.D);");
Matlab.Execute("HTLib2_Matlab_InvEigImpl.sortAbsD = sort(abs(HTLib2_Matlab_InvEigImpl.D));");
Matlab.Execute("HTLib2_Matlab_InvEigImpl.sortAbsD0 = [0; HTLib2_Matlab_InvEigImpl.sortAbsD];"); // add zero to the first list, for the case ze=0 (null)
Matlab.Execute("HTLib2_Matlab_InvEigImpl.ze = HTLib2_Matlab_InvEigImpl.sortAbsD0(HTLib2_Matlab_InvEigImpl.ze+1);");
Matlab.Execute("HTLib2_Matlab_InvEigImpl.th = max(HTLib2_Matlab_InvEigImpl.th, HTLib2_Matlab_InvEigImpl.ze);");
Matlab.Execute("HTLib2_Matlab_InvEigImpl.idx = abs(HTLib2_Matlab_InvEigImpl.D) <= HTLib2_Matlab_InvEigImpl.th;");
Matlab.Execute("HTLib2_Matlab_InvEigImpl.invD = ones(size(HTLib2_Matlab_InvEigImpl.D)) ./ HTLib2_Matlab_InvEigImpl.D;");
Matlab.Execute("HTLib2_Matlab_InvEigImpl.invD(HTLib2_Matlab_InvEigImpl.idx) = 0;");
Matlab.Execute("HTLib2_Matlab_InvEigImpl.invD = diag(HTLib2_Matlab_InvEigImpl.invD);");
Matlab.Execute("HTLib2_Matlab_InvEigImpl.invA = HTLib2_Matlab_InvEigImpl.V * HTLib2_Matlab_InvEigImpl.invD * inv(HTLib2_Matlab_InvEigImpl.V);");
linv = Matlab.GetMatrix("HTLib2_Matlab_InvEigImpl.invA");
if(extra != null)
{
int num_zero_eigvals = Matlab.GetValueInt("sum(HTLib2_Matlab_InvEigImpl.idx)");
HDebug.AssertIf(numZeroEigval != null, numZeroEigval.GetValueOrDefault() <= num_zero_eigvals);
extra["num_zero_eigvals"] = num_zero_eigvals;
extra["eigenvalues" ] = Matlab.GetVector("HTLib2_Matlab_InvEigImpl.D");
}
Matlab.Clear("HTLib2_Matlab_InvEigImpl");
return true;
};
//return NamedLock.LockedCall("bool HTLib2.Matlab.NumericSolver.InvEigImpl(Matrix, double?, int?, out Matrix, InfoPack)", func, out inv);
return NamedLock.LockedCall(Matlab.NamedLock.GetName("HTLib2_Matlab_InvEigImpl"), func, out inv);
}
protected override bool SvdImpl(Matrix X, out Matrix U, out Vector S, out Matrix V)
{
using(new Matlab.NamedLock("NUMSLV"))
{
Matlab.Clear("NUMSLV");
Matlab.PutMatrix("NUMSLV.X", X.ToArray());
Matlab.Execute("[NUMSLV.U, NUMSLV.S, NUMSLV.V] = svd(NUMSLV.X);");
Matlab.Execute("NUMSLV.S = diag(NUMSLV.S);");
U = Matlab.GetMatrix("NUMSLV.U");
S = Matlab.GetVector("NUMSLV.S");
V = Matlab.GetMatrix("NUMSLV.V");
Matlab.Clear("NUMSLV");
}
return true;
}
protected override bool LeastSquareConstrainedImpl( out Vector x
, Matrix C, Vector d
, Matrix A=null, Vector b=null
, Matrix Aeq=null, Vector beq=null
, Vector lb=null, Vector ub=null
, Vector x0=null
, string options=null
)
{
using(new Matlab.NamedLock("NUMSLV"))
{
Matlab.Clear("NUMSLV");
Matlab.PutMatrix("NUMSLV.C", C.ToArray());
Matlab.PutVector("NUMSLV.d", d.ToArray());
Matlab.Execute("NUMSLV.A = [];"); if(A != null) Matlab.PutMatrix("NUMSLV.A" , A .ToArray());
Matlab.Execute("NUMSLV.b = [];"); if(b != null) Matlab.PutVector("NUMSLV.b" , b .ToArray());
Matlab.Execute("NUMSLV.Aeq = [];"); if(Aeq != null) Matlab.PutMatrix("NUMSLV.Aeq", Aeq.ToArray());
Matlab.Execute("NUMSLV.beq = [];"); if(beq != null) Matlab.PutVector("NUMSLV.beq", beq.ToArray());
Matlab.Execute("NUMSLV.lb = [];"); if(lb != null) Matlab.PutVector("NUMSLV.lb" , lb .ToArray());
Matlab.Execute("NUMSLV.ub = [];"); if(ub != null) Matlab.PutVector("NUMSLV.ub" , ub .ToArray());
Matlab.Execute("NUMSLV.x0 = [];"); if(x0 != null) Matlab.PutVector("NUMSLV.x0" , x0 .ToArray());
if(options == null) options = "[]";
Matlab.Execute("NUMSLV.x = lsqlin(NUMSLV.C, NUMSLV.d, NUMSLV.A, NUMSLV.b, NUMSLV.Aeq, NUMSLV.beq, NUMSLV.lb, NUMSLV.ub, NUMSLV.x0, "+options+");", true);
x = Matlab.GetVector("NUMSLV.x");
Matlab.Clear("NUMSLV");
}
return true;
}
protected override bool QuadraticProgrammingConstrainedImpl( out Vector x
, Matrix H, Vector f
, Matrix A=null, Vector b=null
, Matrix Aeq=null, Vector beq=null
, Vector lb=null, Vector ub=null
, Vector x0=null
, string options=null
)
{
using(new Matlab.NamedLock("NUMSLV"))
{
Matlab.Clear("NUMSLV");
Matlab.PutMatrix("NUMSLV.H", H.ToArray());
Matlab.PutVector("NUMSLV.f", f.ToArray());
Matlab.Execute("NUMSLV.A = [];"); if(A != null) Matlab.PutMatrix("NUMSLV.A" , A .ToArray());
Matlab.Execute("NUMSLV.b = [];"); if(b != null) Matlab.PutVector("NUMSLV.b" , b .ToArray());
Matlab.Execute("NUMSLV.Aeq = [];"); if(Aeq != null) Matlab.PutMatrix("NUMSLV.Aeq", Aeq.ToArray());
Matlab.Execute("NUMSLV.beq = [];"); if(beq != null) Matlab.PutVector("NUMSLV.beq", beq.ToArray());
Matlab.Execute("NUMSLV.lb = [];"); if(lb != null) Matlab.PutVector("NUMSLV.lb" , lb .ToArray());
Matlab.Execute("NUMSLV.ub = [];"); if(ub != null) Matlab.PutVector("NUMSLV.ub" , ub .ToArray());
Matlab.Execute("NUMSLV.x0 = [];"); if(x0 != null) Matlab.PutVector("NUMSLV.x0" , x0 .ToArray());
if(options == null) options = "[]";
Matlab.Execute("NUMSLV.x = quadprog(NUMSLV.H, NUMSLV.f, NUMSLV.A, NUMSLV.b, NUMSLV.Aeq, NUMSLV.beq, NUMSLV.lb, NUMSLV.ub, NUMSLV.x0, "+options+");", true);
x = Matlab.GetVector("NUMSLV.x");
Matlab.Clear("NUMSLV");
}
return true;
}
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using Mono.Data.Sqlite;
using Cheapster.Data.Models;
using Cheapster.Data;
namespace Cheapster.Data
{
public static class DataService
{
private const string _lastRowId = "select last_insert_rowid();";
private const string _selectComparison = "select c.Id, c.UnitTypeId, c.UnitId, c.CategoryId, c.Name, cc.Store, cc.Price, cc.Quantity, cc.UnitId, cc.Id, cc.Product from Comparison c left outer join Comparable cc on c.CheapestComparableId = cc.Id";
#region Comparison
public static List<ComparisonModel> GetComparisons()
{
var comparisons = new List<ComparisonModel>();
var commandText = _selectComparison + ";";
SqlConnection.ReaderWithCommand(commandText, (reader) =>
{
while(reader.Read()) {
comparisons.Add(CreateComparison(reader));
}
});
return comparisons;
}
public static ComparisonModel GetComparison(int id)
{
var commandText = _selectComparison + " where c.Id = @Id;";
var parameters = new Dictionary<string, object>();
parameters.Add("@Id", id);
ComparisonModel comparison = null;
SqlConnection.ReaderWithCommand(commandText, parameters, (reader) =>
{
if(reader.Read())
{
comparison = CreateComparison(reader);
}
});
return comparison;
}
/// <summary>
/// Deletes a comparison with the given id.
/// </summary>
/// <param name="id">
/// The comparison to delete.
/// </param>
/// <returns>
/// A value whether a comparison has been deleted. False if nothing was deleted.
/// </returns>
public static bool DeleteComparison(int id)
{
var commandText = "delete from Comparison where Id = @Id;";
var parameters = new Dictionary<string, object>();
parameters.Add("@Id", id);
return SqlConnection.ExecuteNonQuery(commandText, parameters) > 0;
}
public static int SaveComparison(ComparisonModel comparison)
{
if(comparison.Id != 0)
{
throw new ArgumentException("Comparison with non-zero id cannot be saved.");
}
var commandText = "insert into Comparison (UnitTypeId, UnitId, Name, CheapestComparableId) values (@UnitTypeId, @UnitId, @Name, @CheapestComparableId);";
commandText += "select last_insert_rowid();";
var parameters = new Dictionary<string, object>();
parameters.Add("@UnitTypeId", comparison.UnitTypeId);
parameters.Add("@Name", comparison.Name);
parameters.Add("@UnitId", comparison.UnitId);
parameters.Add("@CheapestComparableId", comparison.CheapestComparableId);
int newId = 0;
SqlConnection.ReaderWithCommand(commandText, parameters, (reader) => {
newId = reader.Read() ? reader.GetInt32(0) : 0;
});
return newId;
}
public static bool UpdateComparison(ComparisonModel comparison)
{
var commandText = "update Comparison set UnitTypeId=@UnitTypeId, UnitId=@UnitId, CheapestComparableId=@CheapestComparableId, Name=@Name where Id=@Id;";
var parameters = new Dictionary<string, object>();
parameters.Add("@UnitTypeId", comparison.UnitTypeId);
parameters.Add("@Name", comparison.Name);
parameters.Add("@UnitId", comparison.UnitId);
parameters.Add("@Id", comparison.Id);
parameters.Add("@CheapestComparableId", comparison.CheapestComparableId);
return SqlConnection.ExecuteNonQuery(commandText, parameters) > 0;
}
private static ComparisonModel CreateComparison(SqliteDataReader reader)
{
return new ComparisonModel {
Id = reader.GetInt32(0),
UnitTypeId = reader.GetInt32(1),
UnitId = reader.GetInt32(2),
//CategoryId = reader.GetInt32(3),
Name = reader.IsDBNull(4) ? null : reader.GetString(4),
CheapestStore = reader.IsDBNull(5) ? null : reader.GetString(5),
CheapestPrice = reader.IsDBNull(6) ? (double?)null : reader.GetDouble(6),
CheapestQuantity = reader.IsDBNull(7) ? (double?)null : reader.GetDouble(7),
CheapestUnitId = reader.IsDBNull(8) ? (int?)null : reader.GetInt32(8),
CheapestComparableId = reader.IsDBNull(9) ? (int?)null : reader.GetInt32(9),
CheapestProduct = reader.IsDBNull(10) ? null : reader.GetString(10)
};
}
#endregion
#region Comparable
public static List<ComparableModel> GetComparables(int comparisonId)
{
var comparables = new List<ComparableModel>();
var commandText = "select Id, ComparisonId, UnitId, Store, Product, Price, Quantity, ModifiedOn from Comparable where ComparisonId = @ComparisonId;";
var parameters = new Dictionary<string, object>();
parameters.Add("@ComparisonId", comparisonId);
SqlConnection.ReaderWithCommand(commandText, parameters, (reader) =>
{
while(reader.Read()) {
comparables.Add(CreateComparable(reader));
}
});
return comparables;
}
public static ComparableModel GetComparable(int id)
{
var commandText = "select Id, ComparisonId, UnitId, Store, Product, Price, Quantity, ModifiedOn from Comparable where Id=@Id;";
var parameters = new Dictionary<string, object>();
parameters.Add("@Id", id);
ComparableModel comparable = null;
SqlConnection.ReaderWithCommand(commandText, parameters, (reader) =>
{
if(reader.Read())
{
comparable = CreateComparable(reader);
}
});
return comparable;
}
public static int SaveComparable(ComparableModel comparable)
{
if(comparable.Id != 0)
{
throw new ArgumentException("Comparable with non-zero id cannot be saved.");
}
comparable.ModifiedOn = DateTime.Now;
var commandText = "insert into Comparable (ComparisonId, UnitId, Store, Product, Price, Quantity, ModifiedOn) values (@ComparisonId, @UnitId, @Store, @Product, @Price, @Quantity, @ModifiedOn);";
commandText += "select last_insert_rowid();";
var parameters = new Dictionary<string, object>();
parameters.Add("@ComparisonId", comparable.ComparisonId);
parameters.Add("@UnitId", comparable.UnitId);
parameters.Add("@Store", comparable.Store);
parameters.Add("@Product", comparable.Product);
parameters.Add("@Price", comparable.Price);
parameters.Add("@Quantity", comparable.Quantity);
parameters.Add("@ModifiedOn", comparable.ModifiedOn);
int newId = 0;
SqlConnection.ReaderWithCommand(commandText, parameters, (reader) => {
newId = reader.Read() ? reader.GetInt32(0) : 0;
});
return newId;
}
/// <summary>
/// Updates all properties of a comparable except for the ComparisonId.
/// </summary>
/// <param name="comparable">
/// A <see cref="ComparableModel"/>
/// </param>
/// <returns>
/// True if rows were updated.
/// </returns>
public static bool UpdateComparable(ComparableModel comparable)
{
comparable.ModifiedOn = DateTime.Now;
var commandText = "update Comparable set UnitId=@UnitId, Store=@Store, Product=@Product, Price=@Price, Quantity=@Quantity, ModifiedOn=@ModifiedOn where Id=@Id;";
var parameters = new Dictionary<string, object>();
parameters.Add("@Id", comparable.Id);
parameters.Add("@UnitId", comparable.UnitId);
parameters.Add("@Store", comparable.Store);
parameters.Add("@Product", comparable.Product);
parameters.Add("@Price", comparable.Price);
parameters.Add("@Quantity", comparable.Quantity);
parameters.Add("@ModifiedOn", comparable.ModifiedOn);
return SqlConnection.ExecuteNonQuery(commandText, parameters) > 0;
}
/// <summary>
/// Deletes a comparable with the given id.
/// </summary>
/// <param name="id">
/// The comparable to delete.
/// </param>
/// <returns>
/// A value whether a comparable has been deleted. False if nothing was deleted.
/// </returns>
public static bool DeleteComparable(int id)
{
var commandText = "delete from Comparable where Id = @Id;";
var parameters = new Dictionary<string, object>();
parameters.Add("@Id", id);
return SqlConnection.ExecuteNonQuery(commandText, parameters) > 0;
}
private static ComparableModel CreateComparable(SqliteDataReader reader)
{
return new ComparableModel() {
Id = reader.GetInt32(0),
ComparisonId = reader.GetInt32(1),
UnitId = reader.GetInt32(2),
Store = reader.IsDBNull(3) ? null : reader.GetString(3),
Product = reader.IsDBNull(4) ? null : reader.GetString(4),
Price = reader.GetDouble(5),
Quantity = reader.GetDouble(6),
ModifiedOn = reader.GetDateTime(7)
};
}
#endregion
#region Unit
public static List<UnitModel> GetUnits(int unitTypeId)
{
var units = new List<UnitModel>();
var commandText = "select Id, UnitTypeId, Name, FullName, Multiplier from Unit where UnitTypeId = @UnitTypeId;";
var parameters = new Dictionary<string, object>();
parameters.Add("@UnitTypeId", unitTypeId);
SqlConnection.ReaderWithCommand(commandText, parameters, (reader) =>
{
while(reader.Read()) {
units.Add(new UnitModel() {
Id = reader.GetInt32(0),
UnitTypeId = reader.GetInt32(1),
Name = reader.GetString(2),
FullName = reader.GetString(3),
Multiplier = reader.GetDouble(4)
});
}
});
return units;
}
private static List<UnitModel> _units;
public static List<UnitModel> GetUnits()
{
if(_units != null)
{
return _units;
}
_units = new List<UnitModel>();
var commandText = "select Id, UnitTypeId, Name, FullName, Multiplier from Unit;";
SqlConnection.ReaderWithCommand(commandText, (reader) =>
{
while(reader.Read()) {
_units.Add(new UnitModel() {
Id = reader.GetInt32(0),
UnitTypeId = reader.GetInt32(1),
Name = reader.GetString(2),
FullName = reader.GetString(3),
Multiplier = reader.GetDouble(4)
});
}
});
return _units;
}
public static Dictionary<int, UnitModel> GetUnitsAsDictionary()
{
return (from u in DataService.GetUnits() select u).ToDictionary(u => u.Id, u => u);
}
#endregion
#region Store Names
public static List<RecentStore> GetRecentStoreNames()
{
var stores = new List<RecentStore>();
var commandText = "select Store, max(ModifiedOn) as ModifiedOn, count(Store) as Count from Comparable where Store is not null or Store <> '' group by Store;";
SqlConnection.ReaderWithCommand(commandText, (reader) =>
{
while(reader.Read()) {
stores.Add(new RecentStore() {
Name = reader.GetString(0),
LastModifiedOn = reader.GetDateTime(1),
UsedCount = reader.GetInt32(2)
});
}
});
return stores;
}
#endregion
#region Database
public static double GetDbVersion(string pathToDb)
{
var commandText = "select DbVersion from Meta;";
double version = 0;
using(var connection = SqlConnection.NewConnection(pathToDb))
using(var command = connection.CreateCommand())
{
command.CommandText = commandText;
connection.Open();
using(var reader = command.ExecuteReader())
{
while(reader.Read())
{
version = reader.GetFloat(0);
}
}
}
return version;
}
#endregion
}
}
| |
using NetApp.Tests.Helpers;
using Microsoft.Azure.Management.NetApp;
using Microsoft.Azure.Management.Resources;
using Microsoft.Azure.Test.HttpRecorder;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using Xunit;
using System;
using System.Collections.Generic;
using Microsoft.Azure.Management.NetApp.Models;
using Microsoft.Rest.Azure;
using Newtonsoft.Json;
using System.Threading;
namespace NetApp.Tests.ResourceTests
{
public class SnapshotPolicyTests : TestBase
{
[Fact]
public void CreateDeleteSnapshotPolicy()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
//create account
ResourceUtils.CreateAccount(netAppMgmtClient);
var snapshotPolicy = CreatePolicy(ResourceUtils.location, ResourceUtils.snapshotPolicyName1);
// create the snapshotPolicy
//ResourceUtils.CreateSnapshot(netAppMgmtClient);
var snapshotsBefore = netAppMgmtClient.SnapshotPolicies.Create(snapshotPolicy, ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.snapshotPolicyName1);
// check snapshotPolicy exists
var snapshotPolciesBefore = netAppMgmtClient.SnapshotPolicies.List(ResourceUtils.resourceGroup, ResourceUtils.accountName1);
Assert.Single(snapshotPolciesBefore);
var resultSnapshotPolicy = netAppMgmtClient.SnapshotPolicies.Get(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.snapshotPolicyName1);
Assert.Equal($"{ResourceUtils.accountName1}/{ResourceUtils.snapshotPolicyName1}", resultSnapshotPolicy.Name);
// delete the snapshotPolicy and check again
netAppMgmtClient.SnapshotPolicies.Delete(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.snapshotPolicyName1);
var snapshotsAfter = netAppMgmtClient.SnapshotPolicies.List(ResourceUtils.resourceGroup, ResourceUtils.accountName1);
Assert.Empty(snapshotsAfter);
// cleanup - remove the resources
ResourceUtils.DeleteAccount(netAppMgmtClient);
}
}
[Fact]
public void ListSnapshotPolicies()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
ResourceUtils.CreateAccount(netAppMgmtClient);
// create two snapshots under same account
var snapshotPolicy1 = CreatePolicy(ResourceUtils.location, ResourceUtils.snapshotPolicyName1);
var snapshotPolicy2 = CreatePolicy(ResourceUtils.location, ResourceUtils.snapshotPolicyName2);
var resultSnapshotPolicy1 = netAppMgmtClient.SnapshotPolicies.Create(snapshotPolicy1, ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.snapshotPolicyName1);
var resultSnapshotPolicy2 = netAppMgmtClient.SnapshotPolicies.Create(snapshotPolicy2, ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.snapshotPolicyName2);
// get the snapshotPolicy list and check
var snapshotPolicies = netAppMgmtClient.SnapshotPolicies.List(ResourceUtils.resourceGroup, ResourceUtils.accountName1);
Assert.Equal($"{ResourceUtils.accountName1}/{ResourceUtils.snapshotPolicyName1}", snapshotPolicies.ElementAt(0).Name );
Assert.Equal($"{ResourceUtils.accountName1}/{ResourceUtils.snapshotPolicyName2}", snapshotPolicies.ElementAt(1).Name);
Assert.Equal(2, snapshotPolicies.Count());
// clean up
netAppMgmtClient.SnapshotPolicies.Delete(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.snapshotPolicyName1);
netAppMgmtClient.SnapshotPolicies.Delete(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.snapshotPolicyName2);
ResourceUtils.DeleteAccount(netAppMgmtClient);
}
}
[Fact]
public void GetSnapshotPolicyByName()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
//Create account
ResourceUtils.CreateAccount(netAppMgmtClient);
var snapshotPolicy = CreatePolicy(ResourceUtils.location, ResourceUtils.snapshotPolicyName1);
// create the snapshotPolicy
var createSnapshotPolicy = netAppMgmtClient.SnapshotPolicies.Create(snapshotPolicy, ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.snapshotPolicyName1);
var resultSnapshotPolicy = netAppMgmtClient.SnapshotPolicies.Get(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.snapshotPolicyName1);
Assert.Equal($"{ResourceUtils.accountName1}/{ResourceUtils.snapshotPolicyName1}", resultSnapshotPolicy.Name);
Assert.Equal(createSnapshotPolicy.Name, resultSnapshotPolicy.Name);
// cleanup - remove the resources
netAppMgmtClient.SnapshotPolicies.Delete(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.snapshotPolicyName1);
ResourceUtils.DeletePool(netAppMgmtClient);
ResourceUtils.DeleteAccount(netAppMgmtClient);
}
}
[Fact]
public void CreateVolumeWithSnapshotPolicy()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
// create the Pool and account
ResourceUtils.CreatePool(netAppMgmtClient);
// create the snapshotPolicy
var snapshotPolicy = CreatePolicy(ResourceUtils.location, ResourceUtils.snapshotPolicyName1);
var createSnapshotPolicy = netAppMgmtClient.SnapshotPolicies.Create(snapshotPolicy, ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.snapshotPolicyName1);
// Create volume with snapshotPolicy
var createVolume = ResourceUtils.CreateVolume(netAppMgmtClient, snapshotPolicyId: createSnapshotPolicy.Id);
Assert.NotNull(createVolume.DataProtection);
Assert.NotNull(createVolume.DataProtection.Snapshot);
Assert.NotNull(createVolume.DataProtection.Snapshot.SnapshotPolicyId);
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(30000);
}
//Get volume and check
var getVolume = netAppMgmtClient.Volumes.Get(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1, ResourceUtils.volumeName1);
Assert.NotNull(getVolume.DataProtection);
Assert.NotNull(getVolume.DataProtection.Snapshot);
Assert.NotNull(getVolume.DataProtection.Snapshot.SnapshotPolicyId);
//ListVolumes
///TODO this is not ready, due to an issue with the result causing serialization errors, needs service side fix will be added in 2020-11-01
//var listVolumes = netAppMgmtClient.SnapshotPolicies.ListVolumes(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.snapshotPolicyName1);
//Assert.NotNull(listVolumes);
// clean up
ResourceUtils.DeleteVolume(netAppMgmtClient);
netAppMgmtClient.SnapshotPolicies.Delete(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.snapshotPolicyName1);
ResourceUtils.DeletePool(netAppMgmtClient);
ResourceUtils.DeleteAccount(netAppMgmtClient);
}
}
[Fact]
public void PatchSnapshotPolicy()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
//Create acccount
ResourceUtils.CreateAccount(netAppMgmtClient);
//create the snapshotPolicy
var snapshotPolicy = CreatePolicy(ResourceUtils.location, ResourceUtils.snapshotPolicyName1);
var createSnapshotPolicy = netAppMgmtClient.SnapshotPolicies.Create(snapshotPolicy, ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.snapshotPolicyName1);
var dict = new Dictionary<string, string>();
dict.Add("Tag1", "Value1");
var patchDailySchedule = new DailySchedule(1, 1, 1);
// Now try and modify it
var patchSnapshotPolicy = new SnapshotPolicyPatch()
{
//DailySchedule = patchDailySchedule,
Tags = dict,
DailySchedule = patchDailySchedule
};
var resultSnapshotPolicy = netAppMgmtClient.SnapshotPolicies.Update(patchSnapshotPolicy, ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.snapshotPolicyName1);
Assert.NotNull(resultSnapshotPolicy);
Assert.NotNull(resultSnapshotPolicy.DailySchedule);
//Assert.Equal(patchDailySchedule.SnapshotsToKeep, resultSnapShotPolicy.DailySchedule.SnapshotsToKeep);
// cleanup
netAppMgmtClient.SnapshotPolicies.Delete(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.snapshotPolicyName1);
ResourceUtils.DeletePool(netAppMgmtClient);
ResourceUtils.DeleteAccount(netAppMgmtClient);
}
}
private static SnapshotPolicy CreatePolicy(string location , string name = "")
{
// Create basic policy records with a selection of data
HourlySchedule HourlySchedule = new HourlySchedule
{
SnapshotsToKeep = 2,
Minute = 50
};
DailySchedule DailySchedule = new DailySchedule
{
SnapshotsToKeep = 4,
Hour = 14,
Minute = 30
};
WeeklySchedule WeeklySchedule = new WeeklySchedule
{
SnapshotsToKeep = 3,
Day = "Wednesday",
Hour = 14,
Minute = 45
};
MonthlySchedule MonthlySchedule = new MonthlySchedule
{
SnapshotsToKeep = 5,
DaysOfMonth = "10,11,12",
Hour = 14,
Minute = 15
};
SnapshotPolicy testSnapshotPolicy = new SnapshotPolicy(location: location, name: name)
{
Enabled = true,
HourlySchedule = HourlySchedule,
DailySchedule = DailySchedule,
WeeklySchedule = WeeklySchedule,
MonthlySchedule = MonthlySchedule
};
return testSnapshotPolicy;
}
private static string GetSessionsDirectoryPath()
{
string executingAssemblyPath = typeof(NetApp.Tests.ResourceTests.SnapshotTests).GetTypeInfo().Assembly.Location;
return Path.Combine(Path.GetDirectoryName(executingAssemblyPath), "SessionRecords");
}
}
}
| |
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 WSExample.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>();
}
/// <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 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 get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and 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))
{
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="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <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.ActionDescriptor.ReturnType;
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,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenSim.Framework;
using OpenMetaverse;
namespace OpenSim.Region.PhysicsModules.SharedBase
{
public delegate void physicsCrash();
public delegate void RaycastCallback(bool hitYN, Vector3 collisionPoint, uint localid, float distance, Vector3 normal);
public delegate void RayCallback(List<ContactResult> list);
public delegate void ProbeBoxCallback(List<ContactResult> list);
public delegate void ProbeSphereCallback(List<ContactResult> list);
public delegate void ProbePlaneCallback(List<ContactResult> list);
public delegate void SitAvatarCallback(int status, uint partID, Vector3 offset, Quaternion Orientation);
public delegate void JointMoved(PhysicsJoint joint);
public delegate void JointDeactivated(PhysicsJoint joint);
public delegate void JointErrorMessage(PhysicsJoint joint, string message); // this refers to an "error message due to a problem", not "amount of joint constraint violation"
public enum RayFilterFlags : ushort
{
// the flags
water = 0x01,
land = 0x02,
agent = 0x04,
nonphysical = 0x08,
physical = 0x10,
phantom = 0x20,
volumedtc = 0x40,
// ray cast colision control (may only work for meshs)
ContactsUnImportant = 0x2000,
BackFaceCull = 0x4000,
ClosestHit = 0x8000,
// some combinations
LSLPhantom = phantom | volumedtc,
PrimsNonPhantom = nonphysical | physical,
PrimsNonPhantomAgents = nonphysical | physical | agent,
AllPrims = nonphysical | phantom | volumedtc | physical,
AllButLand = agent | nonphysical | physical | phantom | volumedtc,
ClosestAndBackCull = ClosestHit | BackFaceCull,
All = 0x3f
}
public delegate void RequestAssetDelegate(UUID assetID, AssetReceivedDelegate callback);
public delegate void AssetReceivedDelegate(AssetBase asset);
/// <summary>
/// Contact result from a raycast.
/// </summary>
public struct ContactResult
{
public Vector3 Pos;
public float Depth;
public uint ConsumerID;
public Vector3 Normal;
}
public abstract class PhysicsScene
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// A unique identifying string for this instance of the physics engine.
/// Useful in debug messages to distinguish one OdeScene instance from another.
/// Usually set to include the region name that the physics engine is acting for.
/// </summary>
public string PhysicsSceneName { get; protected set; }
/// <summary>
/// A string identifying the family of this physics engine. Most common values returned
/// are "OpenDynamicsEngine" and "BulletSim" but others are possible.
/// </summary>
public string EngineType { get; protected set; }
public string EngineName { get; protected set; }
// The only thing that should register for this event is the SceneGraph
// Anything else could cause problems.
public event physicsCrash OnPhysicsCrash;
public static PhysicsScene Null
{
get { return new NullPhysicsScene(); }
}
public RequestAssetDelegate RequestAssetMethod { get; set; }
protected void Initialise(RequestAssetDelegate m, float[] terrain, float waterHeight)
{
RequestAssetMethod = m;
SetTerrain(terrain);
SetWaterLevel(waterHeight);
}
public virtual void TriggerPhysicsBasedRestart()
{
physicsCrash handler = OnPhysicsCrash;
if (handler != null)
{
OnPhysicsCrash();
}
}
/// <summary>
/// Add an avatar
/// </summary>
/// <param name="avName"></param>
/// <param name="position"></param>
/// <param name="velocity"></param>
/// <param name="size"></param>
/// <param name="isFlying"></param>
/// <returns></returns>
public abstract PhysicsActor AddAvatar(
string avName, Vector3 position, Vector3 velocity, Vector3 size, bool isFlying);
/// <summary>
/// Add an avatar
/// </summary>
/// <param name="localID"></param>
/// <param name="avName"></param>
/// <param name="position"></param>
/// <param name="velocity"></param>
/// <param name="size"></param>
/// <param name="isFlying"></param>
/// <returns></returns>
public virtual PhysicsActor AddAvatar(
uint localID, string avName, Vector3 position, Vector3 velocity, Vector3 size, bool isFlying)
{
PhysicsActor ret = AddAvatar(avName, position, velocity, size, isFlying);
if (ret != null)
ret.LocalID = localID;
return ret;
}
public virtual PhysicsActor AddAvatar(
uint localID, string avName, Vector3 position, Vector3 size, bool isFlying)
{
PhysicsActor ret = AddAvatar(localID, avName, position, Vector3.Zero, size, isFlying);
return ret;
}
public virtual PhysicsActor AddAvatar(
uint localID, string avName, Vector3 position, Vector3 size, float feetOffset, bool isFlying)
{
PhysicsActor ret = AddAvatar(localID, avName, position, Vector3.Zero, size, isFlying);
return ret;
}
/// <summary>
/// Remove an avatar.
/// </summary>
/// <param name="actor"></param>
public abstract void RemoveAvatar(PhysicsActor actor);
/// <summary>
/// Remove a prim.
/// </summary>
/// <param name="prim"></param>
public abstract void RemovePrim(PhysicsActor prim);
public abstract PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, Vector3 position,
Vector3 size, Quaternion rotation, bool isPhysical, uint localid);
public virtual PhysicsActor AddPrimShape(string primName, PhysicsActor parent, PrimitiveBaseShape pbs, Vector3 position,
uint localid, byte[] sdata)
{
return null;
}
public virtual PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, Vector3 position,
Vector3 size, Quaternion rotation, bool isPhysical, bool isPhantom, uint localid)
{
return AddPrimShape(primName, pbs, position, size, rotation, isPhysical, localid);
}
public virtual PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, Vector3 position,
Vector3 size, Quaternion rotation, bool isPhysical, bool isPhantom, byte shapetype, uint localid)
{
return AddPrimShape(primName, pbs, position, size, rotation, isPhysical, localid);
}
public virtual float TimeDilation
{
get { return 1.0f; }
}
public virtual bool SupportsNINJAJoints
{
get { return false; }
}
public virtual PhysicsJoint RequestJointCreation(string objectNameInScene, PhysicsJointType jointType, Vector3 position,
Quaternion rotation, string parms, List<string> bodyNames, string trackedBodyName, Quaternion localRotation)
{ return null; }
public virtual void RequestJointDeletion(string objectNameInScene)
{ return; }
public virtual void RemoveAllJointsConnectedToActorThreadLocked(PhysicsActor actor)
{ return; }
public virtual void DumpJointInfo()
{ return; }
public event JointMoved OnJointMoved;
protected virtual void DoJointMoved(PhysicsJoint joint)
{
// We need this to allow subclasses (but not other classes) to invoke the event; C# does
// not allow subclasses to invoke the parent class event.
if (OnJointMoved != null)
{
OnJointMoved(joint);
}
}
public event JointDeactivated OnJointDeactivated;
protected virtual void DoJointDeactivated(PhysicsJoint joint)
{
// We need this to allow subclasses (but not other classes) to invoke the event; C# does
// not allow subclasses to invoke the parent class event.
if (OnJointDeactivated != null)
{
OnJointDeactivated(joint);
}
}
public event JointErrorMessage OnJointErrorMessage;
protected virtual void DoJointErrorMessage(PhysicsJoint joint, string message)
{
// We need this to allow subclasses (but not other classes) to invoke the event; C# does
// not allow subclasses to invoke the parent class event.
if (OnJointErrorMessage != null)
{
OnJointErrorMessage(joint, message);
}
}
public virtual Vector3 GetJointAnchor(PhysicsJoint joint)
{ return Vector3.Zero; }
public virtual Vector3 GetJointAxis(PhysicsJoint joint)
{ return Vector3.Zero; }
public abstract void AddPhysicsActorTaint(PhysicsActor prim);
public virtual void ProcessPreSimulation() { }
/// <summary>
/// Perform a simulation of the current physics scene over the given timestep.
/// </summary>
/// <param name="timeStep"></param>
/// <returns>The number of frames simulated over that period.</returns>
public abstract float Simulate(float timeStep);
/// <summary>
/// Get statistics about this scene.
/// </summary>
/// <remarks>This facility is currently experimental and subject to change.</remarks>
/// <returns>
/// A dictionary where the key is the statistic name. If no statistics are supplied then returns null.
/// </returns>
public virtual Dictionary<string, float> GetStats() { return null; }
public abstract void GetResults();
public abstract void SetTerrain(float[] heightMap);
public abstract void SetWaterLevel(float baseheight);
public abstract void DeleteTerrain();
public abstract void Dispose();
public abstract Dictionary<uint, float> GetTopColliders();
public abstract bool IsThreaded { get; }
/// <summary>
/// True if the physics plugin supports raycasting against the physics scene
/// </summary>
public virtual bool SupportsRayCast()
{
return false;
}
/// <summary>
/// Queue a raycast against the physics scene.
/// The provided callback method will be called when the raycast is complete
///
/// Many physics engines don't support collision testing at the same time as
/// manipulating the physics scene, so we queue the request up and callback
/// a custom method when the raycast is complete.
/// This allows physics engines that give an immediate result to callback immediately
/// and ones that don't, to callback when it gets a result back.
///
/// ODE for example will not allow you to change the scene while collision testing or
/// it asserts, 'opteration not valid for locked space'. This includes adding a ray to the scene.
///
/// This is named RayCastWorld to not conflict with modrex's Raycast method.
/// </summary>
/// <param name="position">Origin of the ray</param>
/// <param name="direction">Direction of the ray</param>
/// <param name="length">Length of ray in meters</param>
/// <param name="retMethod">Method to call when the raycast is complete</param>
public virtual void RaycastWorld(Vector3 position, Vector3 direction, float length, RaycastCallback retMethod)
{
if (retMethod != null)
retMethod(false, Vector3.Zero, 0, 999999999999f, Vector3.Zero);
}
public virtual void RaycastWorld(Vector3 position, Vector3 direction, float length, int Count, RayCallback retMethod)
{
if (retMethod != null)
retMethod(new List<ContactResult>());
}
public virtual List<ContactResult> RaycastWorld(Vector3 position, Vector3 direction, float length, int Count)
{
return new List<ContactResult>();
}
public virtual object RaycastWorld(Vector3 position, Vector3 direction, float length, int Count, RayFilterFlags filter)
{
return null;
}
public virtual bool SupportsRaycastWorldFiltered()
{
return false;
}
public virtual List<ContactResult> RaycastActor(PhysicsActor actor, Vector3 position, Vector3 direction, float length, int Count, RayFilterFlags flags)
{
return new List<ContactResult>();
}
public virtual List<ContactResult> BoxProbe(Vector3 position, Vector3 size, Quaternion orientation, int Count, RayFilterFlags flags)
{
return new List<ContactResult>();
}
public virtual List<ContactResult> SphereProbe(Vector3 position, float radius, int Count, RayFilterFlags flags)
{
return new List<ContactResult>();
}
public virtual List<ContactResult> PlaneProbe(PhysicsActor actor, Vector4 plane, int Count, RayFilterFlags flags)
{
return new List<ContactResult>();
}
public virtual int SitAvatar(PhysicsActor actor, Vector3 AbsolutePosition, Vector3 CameraPosition, Vector3 offset, Vector3 AvatarSize, SitAvatarCallback PhysicsSitResponse)
{
return 0;
}
// Extendable interface for new, physics engine specific operations
public virtual object Extension(string pFunct, params object[] pParams)
{
// A NOP if the extension thing is not implemented by the physics engine
return null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
namespace Wpf.Behaviours
{
/// <summary>
/// Static class used to attach to wpf control
/// </summary>
public static class GridViewColumnResize
{
#region DependencyProperties
public static readonly DependencyProperty WidthProperty =
DependencyProperty.RegisterAttached("Width", typeof (string), typeof (GridViewColumnResize),
new PropertyMetadata(OnSetWidthCallback));
public static readonly DependencyProperty GridViewColumnResizeBehaviorProperty =
DependencyProperty.RegisterAttached("GridViewColumnResizeBehavior",
typeof (GridViewColumnResizeBehavior), typeof (GridViewColumnResize),
null);
public static readonly DependencyProperty EnabledProperty =
DependencyProperty.RegisterAttached("Enabled", typeof (bool), typeof (GridViewColumnResize),
new PropertyMetadata(OnSetEnabledCallback));
public static readonly DependencyProperty ListViewResizeBehaviorProperty =
DependencyProperty.RegisterAttached("ListViewResizeBehaviorProperty",
typeof (ListViewResizeBehavior), typeof (GridViewColumnResize), null);
#endregion
public static string GetWidth(DependencyObject obj)
{
return (string) obj.GetValue(WidthProperty);
}
public static void SetWidth(DependencyObject obj, string value)
{
try
{
obj.SetValue(WidthProperty, value);
}
catch { }
}
public static bool GetEnabled(DependencyObject obj)
{
return (bool) obj.GetValue(EnabledProperty);
}
public static void SetEnabled(DependencyObject obj, bool value)
{
try
{
obj.SetValue(EnabledProperty, value);
}
catch { }
}
#region CallBack
private static void OnSetWidthCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
var element = dependencyObject as GridViewColumn;
if (element != null)
{
GridViewColumnResizeBehavior behavior = GetOrCreateBehavior(element);
behavior.Width = e.NewValue as string;
}
else
{
Console.Error.WriteLine("Error: Expected type GridViewColumn but found " +
dependencyObject.GetType().Name);
}
}
private static void OnSetEnabledCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
var element = dependencyObject as ListView;
if (element != null)
{
ListViewResizeBehavior behavior = GetOrCreateBehavior(element);
behavior.Enabled = (bool) e.NewValue;
}
else
{
Console.Error.WriteLine("Error: Expected type ListView but found " + dependencyObject.GetType().Name);
}
}
private static ListViewResizeBehavior GetOrCreateBehavior(ListView element)
{
var behavior = element.GetValue(GridViewColumnResizeBehaviorProperty) as ListViewResizeBehavior;
if (behavior == null)
{
behavior = new ListViewResizeBehavior(element);
element.SetValue(ListViewResizeBehaviorProperty, behavior);
}
return behavior;
}
private static GridViewColumnResizeBehavior GetOrCreateBehavior(GridViewColumn element)
{
var behavior = element.GetValue(GridViewColumnResizeBehaviorProperty) as GridViewColumnResizeBehavior;
if (behavior == null)
{
behavior = new GridViewColumnResizeBehavior(element);
element.SetValue(GridViewColumnResizeBehaviorProperty, behavior);
}
return behavior;
}
#endregion
#region Nested type: GridViewColumnResizeBehavior
/// <summary>
/// GridViewColumn class that gets attached to the GridViewColumn control
/// </summary>
public class GridViewColumnResizeBehavior
{
private readonly GridViewColumn _element;
public GridViewColumnResizeBehavior(GridViewColumn element)
{
_element = element;
}
public string Width { get; set; }
public bool IsStatic
{
get { return StaticWidth >= 0; }
}
public double StaticWidth
{
get
{
double result;
return double.TryParse(Width, out result) ? result : -1;
}
}
public double Percentage
{
get
{
if (!IsStatic)
{
return Mulitplier*100;
}
return 0;
}
}
public double Mulitplier
{
get
{
if (Width == "*" || Width == "1*") return 1;
if (Width.EndsWith("*"))
{
double perc;
if (double.TryParse(Width.Substring(0, Width.Length-1), out perc))
{
return perc;
}
}
return 1;
}
}
public void SetWidth(double allowedSpace, double totalPercentage)
{
if (IsStatic)
{
_element.Width = StaticWidth;
}
else
{
double width = allowedSpace*(Percentage/totalPercentage);
_element.Width = width;
}
}
}
#endregion
#region Nested type: ListViewResizeBehavior
/// <summary>
/// ListViewResizeBehavior class that gets attached to the ListView control
/// </summary>
public class ListViewResizeBehavior
{
private const int Margin = 25;
private const long RefreshTime = Timeout.Infinite;
private const long Delay = 50;
private readonly ListView _element;
private readonly Timer _timer;
public ListViewResizeBehavior(ListView element)
{
if (element == null) throw new ArgumentNullException("element");
_element = element;
element.Loaded += OnLoaded;
// Action for resizing and re-enable the size lookup
// This stops the columns from constantly resizing to improve performance
Action resizeAndEnableSize = () =>
{
Resize();
_element.SizeChanged += OnSizeChanged;
};
_timer = new Timer(x => element.Dispatcher.BeginInvoke(resizeAndEnableSize), null, Delay,
RefreshTime);
}
public bool Enabled { get; set; }
private void OnLoaded(object sender, RoutedEventArgs e)
{
_element.SizeChanged += OnSizeChanged;
}
private void OnSizeChanged(object sender, SizeChangedEventArgs e)
{
if (e.WidthChanged)
{
_element.SizeChanged -= OnSizeChanged;
_timer.Change(Delay, RefreshTime);
}
}
private void Resize()
{
if (Enabled)
{
double totalWidth = _element.ActualWidth;
var gv = _element.View as GridView;
if (gv != null)
{
double allowedSpace = totalWidth - GetAllocatedSpace(gv);
allowedSpace = allowedSpace - Margin;
if (allowedSpace < 0)
return;
double totalPercentage = GridViewColumnResizeBehaviors(gv).Sum(x => x.Percentage);
foreach (GridViewColumnResizeBehavior behavior in GridViewColumnResizeBehaviors(gv))
{
behavior.SetWidth(allowedSpace, totalPercentage);
}
}
}
}
private static IEnumerable<GridViewColumnResizeBehavior> GridViewColumnResizeBehaviors(GridView gv)
{
foreach (GridViewColumn t in gv.Columns)
{
var gridViewColumnResizeBehavior =
t.GetValue(GridViewColumnResizeBehaviorProperty) as GridViewColumnResizeBehavior;
if (gridViewColumnResizeBehavior != null)
{
yield return gridViewColumnResizeBehavior;
}
}
}
private static double GetAllocatedSpace(GridView gv)
{
double totalWidth = 0;
foreach (GridViewColumn t in gv.Columns)
{
var gridViewColumnResizeBehavior =
t.GetValue(GridViewColumnResizeBehaviorProperty) as GridViewColumnResizeBehavior;
if (gridViewColumnResizeBehavior != null)
{
if (gridViewColumnResizeBehavior.IsStatic)
{
totalWidth += gridViewColumnResizeBehavior.StaticWidth;
}
}
else
{
totalWidth += t.ActualWidth;
}
}
return totalWidth;
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Threading;
namespace System.Xaml
{
// XamlNode Double Buffering object that multi-threaded access
// ONE reader and ONE writer.
// This is the bridge used to Parse on one thread and Build on a second.
public class XamlBackgroundReader : XamlReader, IXamlLineInfo
{
EventWaitHandle _providerFullEvent;
EventWaitHandle _dataReceivedEvent;
XamlNode[] _incoming;
int _inIdx;
XamlNode[] _outgoing;
int _outIdx;
int _outValid;
XamlNode _currentNode;
XamlReader _wrappedReader;
XamlReader _internalReader;
XamlWriter _writer;
bool _wrappedReaderHasLineInfo;
int _lineNumber=0;
int _linePosition=0;
Thread _thread;
Exception _caughtException;
public XamlBackgroundReader(XamlReader wrappedReader)
{
if (wrappedReader == null)
{
throw new ArgumentNullException(nameof(wrappedReader));
}
Initialize(wrappedReader, 64);
}
private void Initialize(XamlReader wrappedReader, int bufferSize)
{
_providerFullEvent = new EventWaitHandle(false, EventResetMode.AutoReset);
_dataReceivedEvent = new EventWaitHandle(false, EventResetMode.AutoReset);
_incoming = new XamlNode[bufferSize];
_outgoing = new XamlNode[bufferSize];
_wrappedReader = wrappedReader;
_wrappedReaderHasLineInfo = ((IXamlLineInfo)_wrappedReader).HasLineInfo;
var xamlNodeAddDelegate = new XamlNodeAddDelegate(Add);
XamlLineInfoAddDelegate lineInfoAddDelegate = null;
if (_wrappedReaderHasLineInfo)
{
lineInfoAddDelegate = new XamlLineInfoAddDelegate(AddLineInfo);
}
_writer = new WriterDelegate(xamlNodeAddDelegate, lineInfoAddDelegate, _wrappedReader.SchemaContext);
XamlNodeNextDelegate xamlNodeNextDelegate;
if(_wrappedReaderHasLineInfo)
{
xamlNodeNextDelegate = new XamlNodeNextDelegate(Next_ProcessLineInfo);
}
else
{
xamlNodeNextDelegate = new XamlNodeNextDelegate(Next);
}
_internalReader = new ReaderDelegate(_wrappedReader.SchemaContext, xamlNodeNextDelegate, _wrappedReaderHasLineInfo);
//Standin so it won't start null
_currentNode = new XamlNode(XamlNode.InternalNodeType.StartOfStream);
}
public void StartThread()
{
StartThread("XAML reader thread");
}
public void StartThread(string threadName)
{
if (_thread != null)
{
throw new InvalidOperationException(SR.Get(SRID.ThreadAlreadyStarted));
}
ParameterizedThreadStart start = new ParameterizedThreadStart(XamlReaderThreadStart);
_thread = new Thread(start);
_thread.Name = threadName;
_thread.Start();
}
// The "ThreadStart" function
private void XamlReaderThreadStart(object none)
{
try
{
InterruptableTransform(_wrappedReader, _writer, true);
}
catch (Exception ex)
{
_writer.Close();
_caughtException = ex;
}
}
internal bool IncomingFull
{
get { return _inIdx >= _incoming.Length; }
}
internal bool OutgoingEmpty
{
get { return _outIdx >= _outValid; }
}
private void SwapBuffers()
{
XamlNode[] tmp = _incoming;
_incoming = _outgoing;
_outgoing = tmp;
_outIdx = 0;
_outValid = _inIdx; // in the EOF case the buffer can be short.
_inIdx = 0;
}
private void AddToBuffer(XamlNode node)
{
_incoming[_inIdx] = node;
_inIdx += 1;
if (IncomingFull)
{
_providerFullEvent.Set(); // Reader is Full
_dataReceivedEvent.WaitOne(); // Wait for data to be picked up.
}
}
private void Add(XamlNodeType nodeType, object data)
{
if (IsDisposed)
{
return;
}
if (nodeType != XamlNodeType.None)
{
AddToBuffer(new XamlNode(nodeType, data));
return;
}
Debug.Assert(XamlNode.IsEof_Helper(nodeType, data));
AddToBuffer(new XamlNode(XamlNode.InternalNodeType.EndOfStream));
_providerFullEvent.Set();
}
private void AddLineInfo(int lineNumber, int linePosition)
{
if (IsDisposed)
{
return;
}
LineInfo lineInfo = new LineInfo(lineNumber, linePosition);
XamlNode node = new XamlNode(lineInfo);
AddToBuffer(node);
}
private XamlNode Next()
{
if (IsDisposed)
{
throw new ObjectDisposedException("XamlBackgroundReader");
}
if (OutgoingEmpty)
{
// This is for users that read PAST the EOF record.
// Don't let them hang on WaitOne() return EOF Again!
if (_currentNode.IsEof)
{
return _currentNode;
}
_providerFullEvent.WaitOne(); // Wait for provider to fill up.
SwapBuffers();
_dataReceivedEvent.Set(); // Let the Reader run.
}
_currentNode = _outgoing[_outIdx++];
if (_currentNode.IsEof)
{
if (_thread != null)
{
// If the input ended due to an (caught) exception on the background thread,
// then at the end of reading the input re-throw the exception on the
// foreground thread.
_thread.Join();
if (_caughtException != null)
{
Exception ex = _caughtException;
_caughtException = null;
throw ex;
}
}
}
return _currentNode;
}
private XamlNode Next_ProcessLineInfo()
{
bool done = false;
while (!done)
{
Next();
if (_currentNode.IsLineInfo)
{
_lineNumber = _currentNode.LineInfo.LineNumber;
_linePosition = _currentNode.LineInfo.LinePosition;
}
else
{
done = true;
}
}
return _currentNode;
}
private void InterruptableTransform(XamlReader reader, XamlWriter writer, bool closeWriter)
{
IXamlLineInfo xamlLineInfo = reader as IXamlLineInfo;
IXamlLineInfoConsumer xamlLineInfoConsumer = writer as IXamlLineInfoConsumer;
bool shouldPassLineNumberInfo = false;
if ((xamlLineInfo != null && xamlLineInfo.HasLineInfo)
&& (xamlLineInfoConsumer != null && xamlLineInfoConsumer.ShouldProvideLineInfo))
{
shouldPassLineNumberInfo = true;
}
while (reader.Read())
{
if (IsDisposed)
{
break;
}
if (shouldPassLineNumberInfo)
{
if (xamlLineInfo.LineNumber != 0)
{
xamlLineInfoConsumer.SetLineInfo(xamlLineInfo.LineNumber, xamlLineInfo.LinePosition);
}
}
writer.WriteNode(reader);
}
if (closeWriter)
{
writer.Close();
}
}
#region XamlReader
public override bool Read()
{
return _internalReader.Read();
}
public override XamlNodeType NodeType
{
get { return _internalReader.NodeType; }
}
public override bool IsEof
{
get { return _internalReader.IsEof; }
}
public override NamespaceDeclaration Namespace
{
get { return _internalReader.Namespace; }
}
public override XamlType Type
{
get { return _internalReader.Type; }
}
public override object Value
{
get { return _internalReader.Value; }
}
public override XamlMember Member
{
get { return _internalReader.Member; }
}
public override XamlSchemaContext SchemaContext
{
get { return _internalReader.SchemaContext; }
}
#endregion
#region IXamlLineInfo Members
public bool HasLineInfo
{
get { return _wrappedReaderHasLineInfo; }
}
public int LineNumber
{
get { return _lineNumber; }
}
public int LinePosition
{
get { return _linePosition; }
}
#endregion
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
_dataReceivedEvent.Set(); // Release any blocked writers.
((IDisposable)_dataReceivedEvent).Dispose();
((IDisposable)_internalReader).Dispose();
((IDisposable)_providerFullEvent).Dispose();
((IDisposable)_writer).Dispose();
}
}
}
| |
// 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.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor.CSharp.Formatting.Indentation;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Formatting;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting.Indentation
{
public class SmartIndenterEnterOnTokenTests : FormatterTestsBase
{
[WorkItem(537808)]
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void MethodBody1()
{
var code = @"class Class1
{
void method()
{ }
}
";
AssertIndentUsingSmartTokenFormatter(
code,
'{',
indentationLine: 3,
expectedIndentation: 4);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void Preprocessor1()
{
var code = @"class A
{
#region T
#endregion
}
";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 3,
expectedIndentation: 4);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void Preprocessor2()
{
var code = @"class A
{
#line 1
#lien 2
}
";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 3,
expectedIndentation: 4);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void Comments()
{
var code = @"using System;
class Class
{
// Comments
// Comments
";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 5,
expectedIndentation: 4);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void UsingDirective()
{
var code = @"using System;
using System.Linq;
";
AssertIndentUsingSmartTokenFormatter(
code,
'u',
indentationLine: 1,
expectedIndentation: 0);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void AfterTopOfFileComment()
{
var code = @"// comment
class
";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 2,
expectedIndentation: 0);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void DottedName()
{
var code = @"using System.
Collection;
";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 1,
expectedIndentation: 4);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void Namespace()
{
var code = @"using System;
namespace NS
{
";
AssertIndentUsingSmartTokenFormatter(
code,
'{',
indentationLine: 3,
expectedIndentation: 0);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void NamespaceDottedName()
{
var code = @"using System;
namespace NS.
NS2
";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 3,
expectedIndentation: 4);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void NamespaceBody()
{
var code = @"using System;
namespace NS
{
class
";
AssertIndentUsingSmartTokenFormatter(
code,
'c',
indentationLine: 4,
expectedIndentation: 4);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void NamespaceCloseBrace()
{
var code = @"using System;
namespace NS
{
}
";
AssertIndentUsingSmartTokenFormatter(
code,
'}',
indentationLine: 4,
expectedIndentation: 0);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void Class()
{
var code = @"using System;
namespace NS
{
class Class
{
";
AssertIndentUsingSmartTokenFormatter(
code,
'{',
indentationLine: 5,
expectedIndentation: 4);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void ClassBody()
{
var code = @"using System;
namespace NS
{
class Class
{
int
";
AssertIndentUsingSmartTokenFormatter(
code,
'i',
indentationLine: 6,
expectedIndentation: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void ClassCloseBrace()
{
var code = @"using System;
namespace NS
{
class Class
{
}
";
AssertIndentUsingSmartTokenFormatter(
code,
'}',
indentationLine: 6,
expectedIndentation: 4);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void Method()
{
var code = @"using System;
namespace NS
{
class Class
{
void Method()
{
";
AssertIndentUsingSmartTokenFormatter(
code,
'{',
indentationLine: 7,
expectedIndentation: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void MethodBody()
{
var code = @"using System;
namespace NS
{
class Class
{
void Method()
{
int
";
AssertIndentUsingSmartTokenFormatter(
code,
'i',
indentationLine: 8,
expectedIndentation: 12);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void MethodCloseBrace()
{
var code = @"using System;
namespace NS
{
class Class
{
void Method()
{
}
";
AssertIndentUsingSmartTokenFormatter(
code,
'}',
indentationLine: 8,
expectedIndentation: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void Statement()
{
var code = @"using System;
namespace NS
{
class Class
{
void Method()
{
int i = 10;
int
";
AssertIndentUsingSmartTokenFormatter(
code,
'i',
indentationLine: 9,
expectedIndentation: 12);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void MethodCall()
{
var code = @"class c
{
void Method()
{
M(
a: 1,
b: 1);
}
}";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 5,
expectedIndentation: 12);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void Switch()
{
var code = @"using System;
namespace NS
{
class Class
{
void Method()
{
switch (10)
{
";
AssertIndentUsingSmartTokenFormatter(
code,
'{',
indentationLine: 9,
expectedIndentation: 12);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void SwitchBody()
{
var code = @"using System;
namespace NS
{
class Class
{
void Method()
{
switch (10)
{
case
";
AssertIndentUsingSmartTokenFormatter(
code,
'c',
indentationLine: 10,
expectedIndentation: 16);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void SwitchCase()
{
var code = @"using System;
namespace NS
{
class Class
{
void Method()
{
switch (10)
{
case 10 :
int
";
AssertIndentUsingSmartTokenFormatter(
code,
'i',
indentationLine: 11,
expectedIndentation: 20);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void SwitchCaseBlock()
{
var code = @"using System;
namespace NS
{
class Class
{
void Method()
{
switch (10)
{
case 10 :
{
";
AssertIndentUsingSmartTokenFormatter(
code,
'{',
indentationLine: 11,
expectedIndentation: 20);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void Block()
{
var code = @"using System;
namespace NS
{
class Class
{
void Method()
{
switch (10)
{
case 10 :
{
int
";
AssertIndentUsingSmartTokenFormatter(
code,
'i',
indentationLine: 12,
expectedIndentation: 24);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void MultilineStatement1()
{
var code = @"using System;
namespace NS
{
class Class
{
void Method()
{
int i = 10 +
1
";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 9,
expectedIndentation: 16);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void MultilineStatement2()
{
var code = @"using System;
namespace NS
{
class Class
{
void Method()
{
int i = 10 +
20 +
30
";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 10,
expectedIndentation: 20);
}
// Bug number 902477
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void Comments2()
{
var code = @"class Class
{
void Method()
{
if (true) // Test
int
}
}
";
AssertIndentUsingSmartTokenFormatter(
code,
'i',
indentationLine: 5,
expectedIndentation: 12);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void AfterCompletedBlock()
{
var code = @"class Program
{
static void Main(string[] args)
{
foreach(var a in x) {}
int
}
}
";
AssertIndentUsingSmartTokenFormatter(
code,
'i',
indentationLine: 5,
expectedIndentation: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void AfterTopLevelAttribute()
{
var code = @"class Program
{
[Attr]
[
}
";
AssertIndentUsingSmartTokenFormatter(
code,
'[',
indentationLine: 3,
expectedIndentation: 4);
}
[WorkItem(537802)]
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void EmbededStatement()
{
var code = @"class Program
{
static void Main(string[] args)
{
if (true)
Console.WriteLine(1);
int
}
}
";
AssertIndentUsingSmartTokenFormatter(
code,
'i',
indentationLine: 6,
expectedIndentation: 8);
}
[WorkItem(537808)]
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void MethodBraces1()
{
var code = @"class Class1
{
void method()
{ }
}
";
AssertIndentUsingSmartTokenFormatter(
code,
'{',
indentationLine: 3,
expectedIndentation: 4);
}
[WorkItem(537808)]
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void MethodBraces2()
{
var code = @"class Class1
{
void method()
{
}
}
";
AssertIndentUsingSmartTokenFormatter(
code,
'}',
indentationLine: 4,
expectedIndentation: 4);
}
[WorkItem(537795)]
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void Property1()
{
var code = @"class C
{
string Name
{
get;
set;
}
}
";
AssertIndentUsingSmartTokenFormatter(
code,
'}',
indentationLine: 6,
expectedIndentation: 4);
}
[WorkItem(537563)]
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void Class1()
{
var code = @"class C
{
}
";
AssertIndentUsingSmartTokenFormatter(
code,
'}',
indentationLine: 2,
expectedIndentation: 0);
}
[Fact]
[WorkItem(1070773)]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void ArrayInitializer1()
{
var code = @"class C
{
var a = new []
{ 1, 2, 3 }
}
";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 3,
expectedIndentation: 4);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void ArrayInitializer2()
{
var code = @"class C
{
var a = new []
{
1, 2, 3
}
}
";
AssertIndentUsingSmartTokenFormatter(
code,
'}',
indentationLine: 5,
expectedIndentation: 4);
}
[Fact]
[WorkItem(1070773)]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void ArrayInitializer3()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
{
var a = new []
{
}";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 7,
expectedIndentation: 12);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void QueryExpression2()
{
var code = @"class C
{
void Method()
{
var a = from c in b
where
}
}
";
AssertIndentUsingSmartTokenFormatter(
code,
'w',
indentationLine: 5,
expectedIndentation: 16);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void QueryExpression3()
{
var code = @"class C
{
void Method()
{
var a = from c in b
where select
}
}
";
AssertIndentUsingSmartTokenFormatter(
code,
'w',
indentationLine: 5,
expectedIndentation: 16);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void QueryExpression4()
{
var code = @"class C
{
void Method()
{
var a = from c in b where c > 10
select
}
}
";
AssertIndentUsingSmartTokenFormatter(
code,
's',
indentationLine: 5,
expectedIndentation: 16);
}
[Fact]
[WorkItem(853748)]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void ArrayInitializer()
{
var code = @"class C
{
void Method()
{
var l = new int[] {
}
}
}
";
AssertIndentUsingSmartTokenFormatter(
code,
'}',
indentationLine: 5,
expectedIndentation: 8);
}
[Fact]
[WorkItem(939305)]
[WorkItem(1070773)]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void ArrayExpression()
{
var code = @"class C
{
void M(object[] q)
{
M(
q: new object[]
{ });
}
}
";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 6,
expectedIndentation: 14);
}
[Fact]
[WorkItem(1070773)]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void CollectionExpression()
{
var code = @"class C
{
void M(List<int> e)
{
M(
new List<int>
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
}
}
";
AssertIndentUsingSmartTokenFormatter(
code,
'{',
indentationLine: 6,
expectedIndentation: 12);
}
[Fact]
[WorkItem(1070773)]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void ObjectInitializer()
{
var code = @"class C
{
void M(What dd)
{
M(
new What
{ d = 3, dd = "" });
}
}
class What
{
public int d;
public string dd;
}";
AssertIndentUsingSmartTokenFormatter(
code,
'{',
indentationLine: 6,
expectedIndentation: 12);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void Preprocessor()
{
var code = @"
#line 1 """"Bar""""class Foo : [|IComparable|]#line default#line hidden";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 1,
expectedIndentation: 0);
}
[Fact]
[WorkItem(1070774)]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void InsideInitializerWithTypeBody_Implicit()
{
var code = @"class X {
int[] a = {
1,
};
}";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 3,
expectedIndentation: 8);
}
[Fact]
[WorkItem(1070774)]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void InsideInitializerWithTypeBody_ImplicitNew()
{
var code = @"class X {
int[] a = new[] {
1,
};
}";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 3,
expectedIndentation: 8);
}
[Fact]
[WorkItem(1070774)]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void InsideInitializerWithTypeBody_Explicit()
{
var code = @"class X {
int[] a = new int[] {
1,
};
}";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 3,
expectedIndentation: 8);
}
[Fact]
[WorkItem(1070774)]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void InsideInitializerWithTypeBody_Collection()
{
var code = @"using System.Collections.Generic;
class X {
private List<int> a = new List<int>() {
1,
};
}";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 4,
expectedIndentation: 8);
}
[Fact]
[WorkItem(1070774)]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void InsideInitializerWithTypeBody_ObjectInitializers()
{
var code = @"class C
{
private What sdfsd = new What
{
d = 3,
}
}
class What
{
public int d;
public string dd;
}";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 5,
expectedIndentation: 8);
}
[Fact]
[WorkItem(872)]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void InsideInterpolationString_1()
{
var code = @"class Program
{
static void Main(string[] args)
{
var s = $@""
{Program.number}"";
}
static int number;
}";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 5,
expectedIndentation: 0);
}
[Fact]
[WorkItem(872)]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void InsideInterpolationString_2()
{
var code = @"class Program
{
static void Main(string[] args)
{
var s = $@""Comment
{Program.number}"";
}
static int number;
}";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 5,
expectedIndentation: 0);
}
[Fact]
[WorkItem(872)]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void InsideInterpolationString_3()
{
var code = @"class Program
{
static void Main(string[] args)
{
var s = $@""Comment{Program.number}
"";
}
static int number;
}";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 5,
expectedIndentation: 0);
}
[Fact]
[WorkItem(872)]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void InsideInterpolationString_4()
{
var code = @"class Program
{
static void Main(string[] args)
{
var s = $@""Comment{Program.number}Comment here
"";
}
static int number;
}";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 5,
expectedIndentation: 0);
}
[Fact]
[WorkItem(872)]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void OutsideInterpolationString()
{
var code = @"class Program
{
static void Main(string[] args)
{
var s = $@""Comment{Program.number}Comment here""
;
}
static int number;
}";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 5,
expectedIndentation: 12);
}
[Fact]
[WorkItem(872)]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void InsideInterpolationSyntax_1()
{
var code = @"class Program
{
static void Main(string[] args)
{
var s = $@""{
Program.number}"";
}
static int number;
}";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 5,
expectedIndentation: 12);
}
[Fact]
[WorkItem(872)]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void InsideInterpolationSyntax_2()
{
var code = @"class Program
{
static void Main(string[] args)
{
var s = $@""{
Program
.number}"";
}
static int number;
}";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 6,
expectedIndentation: 12);
}
[Fact]
[WorkItem(872)]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void InsideInterpolationSyntax_3()
{
var code = @"class Program
{
static void Main(string[] args)
{
var s = $@""{
}"";
}
static int number;
}";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 5,
expectedIndentation: 12);
}
[Fact]
[WorkItem(872)]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void InsideInterpolationSyntax_4()
{
var code = @"class Program
{
static void Main(string[] args)
{
Console.WriteLine($@""PPP{
((Func<int, int>)((int s) => { return number; })).Invoke(3):(408) ###-####}"");
}
static int number;
}";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 5,
expectedIndentation: 12);
}
[Fact]
[WorkItem(872)]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void InsideInterpolationSyntax_5()
{
var code = @"class Program
{
static void Main(string[] args)
{
Console.WriteLine($@""PPP{ ((Func<int, int>)((int s)
=> { return number; })).Invoke(3):(408) ###-####}"");
}
static int number;
}";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 5,
expectedIndentation: 12);
}
[Fact]
[WorkItem(872)]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void InsideInterpolationSyntax_6()
{
var code = @"class Program
{
static void Main(string[] args)
{
Console.WriteLine($@""PPP{ ((Func<int, int>)((int s) => { return number; }))
.Invoke(3):(408) ###-####}"");
}
static int number;
}";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 5,
expectedIndentation: 12);
}
[Fact]
[WorkItem(872)]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void InsideInterpolationSyntax_7()
{
var code = @"class Program
{
static void Main(string[] args)
{
Console.WriteLine($@""PPP{ ((Func<int, int>)((int s) =>
{ return number; })).Invoke(3):(408) ###-####}"");
}
static int number;
}";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 5,
expectedIndentation: 8);
}
[Fact]
[WorkItem(872)]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void IndentLambdaBodyOneIndentationToFirstTokenOfTheStatement()
{
var code = @"class Program
{
static void Main(string[] args)
{
Console.WriteLine(((Func<int, int>)((int s) =>
{ return number; })).Invoke(3));
}
static int number;
}";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 5,
expectedIndentation: 8);
}
[Fact]
[WorkItem(1339, "https://github.com/dotnet/roslyn/issues/1339")]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void IndentAutoPropertyInitializerAsPartOfTheDeclaration()
{
var code = @"class Program
{
public int d { get; }
= 3;
static void Main(string[] args)
{
}
}";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 3,
expectedIndentation: 8);
}
private void AssertIndentUsingSmartTokenFormatter(
string code,
char ch,
int indentationLine,
int? expectedIndentation)
{
// create tree service
using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(code))
{
var hostdoc = workspace.Documents.First();
var buffer = hostdoc.GetTextBuffer();
var snapshot = buffer.CurrentSnapshot;
var line = snapshot.GetLineFromLineNumber(indentationLine);
var document = workspace.CurrentSolution.GetDocument(hostdoc.Id);
var root = document.GetSyntaxRootAsync().Result as CompilationUnitSyntax;
Assert.True(
CSharpIndentationService.ShouldUseSmartTokenFormatterInsteadOfIndenter(
Formatter.GetDefaultFormattingRules(workspace, root.Language),
root, line, workspace.Options, CancellationToken.None));
var actualIndentation = GetSmartTokenFormatterIndentationWorker(workspace, buffer, indentationLine, ch);
Assert.Equal(expectedIndentation.Value, actualIndentation);
}
}
private void AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
string code,
int indentationLine,
int? expectedIndentation)
{
// create tree service
using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(code))
{
var hostdoc = workspace.Documents.First();
var buffer = hostdoc.GetTextBuffer();
var snapshot = buffer.CurrentSnapshot;
var line = snapshot.GetLineFromLineNumber(indentationLine);
var document = workspace.CurrentSolution.GetDocument(hostdoc.Id);
var root = document.GetSyntaxRootAsync().Result as CompilationUnitSyntax;
Assert.False(
CSharpIndentationService.ShouldUseSmartTokenFormatterInsteadOfIndenter(
Formatter.GetDefaultFormattingRules(workspace, root.Language),
root, line, workspace.Options, CancellationToken.None));
TestIndentation(indentationLine, expectedIndentation, workspace);
}
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.IO;
namespace FileSystemTest
{
public class WriteByte : IMFTestInterface
{
[SetUp]
public InitializeResult Initialize()
{
Log.Comment("Adding set up for the tests.");
// TODO: Add your set up steps here.
return InitializeResult.ReadyToGo;
}
[TearDown]
public void CleanUp()
{
Log.Comment("Cleaning up after the tests.");
// TODO: Add your clean up steps here.
}
#region Helper methods
private bool TestWrite(MemoryStream ms, int BytesToWrite)
{
return TestWrite(ms, BytesToWrite, ms.Position + BytesToWrite);
}
private bool TestWrite(MemoryStream ms, int BytesToWrite, long ExpectedLength)
{
bool result = true;
long startLength = ms.Position;
byte nextbyte = (byte)(startLength & 0xFF);
for (int i = 0; i < BytesToWrite; i++)
{
ms.WriteByte((byte)nextbyte);
nextbyte++;
}
ms.Flush();
if (ExpectedLength < ms.Length)
{
result = false;
Log.Exception("Expeceted final length of " + ExpectedLength + " bytes, but got " + ms.Length + " bytes");
}
return result;
}
#endregion Helper methods
#region Test Cases
[TestMethod]
public MFTestResults ExtendBuffer()
{
MFTestResults result = MFTestResults.Pass;
try
{
using (MemoryStream ms = new MemoryStream())
{
Log.Comment("Set Position past end of stream");
// Internal buffer is initialized to 256, if this changes, this test is no longer valid.
// Exposing capcity would have made this test easier/dynamic.
ms.Position = 300;
ms.WriteByte(123);
if (ms.Length != 301)
{
Log.Exception( "Expected length 301, got length " + ms.Length );
return MFTestResults.Fail;
}
ms.Position = 300;
int read = ms.ReadByte();
if (read != 123)
{
Log.Exception( "Expected value 123, but got value " + result );
return MFTestResults.Fail;
}
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception", ex);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults InvalidRange()
{
MFTestResults result = MFTestResults.Pass;
try
{
byte[] buffer = new byte[100];
using (MemoryStream ms = new MemoryStream(buffer))
{
Log.Comment("Set Position past end of static stream");
ms.Position = buffer.Length + 1;
try
{
ms.WriteByte(1);
Log.Exception( "Expected NotSupportedException" );
return MFTestResults.Fail;
}
catch (NotSupportedException nse)
{
/* pass case */ Log.Comment( "Got correct exception: " + nse.Message );
result = MFTestResults.Pass;
}
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception", ex);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults VanillaWrite()
{
MFTestResults result = MFTestResults.Pass;
try
{
Log.Comment("Static Buffer");
byte[] buffer = new byte[100];
using (MemoryStream ms = new MemoryStream(buffer))
{
Log.Comment("Write 50 bytes of data");
if (!TestWrite(ms, 50, 100))
return MFTestResults.Fail;
Log.Comment("Write final 50 bytes of data");
if (!TestWrite(ms, 50, 100))
return MFTestResults.Fail;
Log.Comment("Any more bytes written should throw");
try
{
ms.WriteByte(50);
Log.Exception( "Expected NotSupportedException" );
return MFTestResults.Fail;
}
catch (NotSupportedException nse)
{
/* pass case */ Log.Comment( "Got correct exception: " + nse.Message );
result = MFTestResults.Pass;
}
Log.Comment("Rewind and verify all bytes written");
ms.Seek(0, SeekOrigin.Begin);
if (!MemoryStreamHelper.VerifyRead(ms))
return MFTestResults.Fail;
}
Log.Comment("Dynamic Buffer");
using (MemoryStream ms = new MemoryStream())
{
Log.Comment("Write 100 bytes of data");
if (!TestWrite(ms, 100))
return MFTestResults.Fail;
Log.Comment("Extend internal buffer, write 160");
if (!TestWrite(ms, 160))
return MFTestResults.Fail;
Log.Comment("Double extend internal buffer, write 644");
if (!TestWrite(ms, 644))
return MFTestResults.Fail;
Log.Comment("write another 1100");
if (!TestWrite(ms, 1100))
return MFTestResults.Fail;
Log.Comment("Rewind and verify all bytes written");
ms.Seek(0, SeekOrigin.Begin);
if (!MemoryStreamHelper.VerifyRead(ms))
return MFTestResults.Fail; }
}
catch (Exception ex)
{
Log.Exception("Unexpected exception", ex);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults BoundaryCheck()
{
MFTestResults result = MFTestResults.Pass;
try
{
for (int i = 250; i < 260; i++)
{
using (MemoryStream ms = new MemoryStream())
{
MemoryStreamHelper.Write(ms, i);
ms.Position = 0;
if (!MemoryStreamHelper.VerifyRead(ms))
return MFTestResults.Fail;
Log.Comment("Position: " + ms.Position);
Log.Comment("Length: " + ms.Length);
if (i != ms.Position | i != ms.Length)
{
Log.Exception( "Expected Position and Length to be " + i );
return MFTestResults.Fail;
}
}
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
#endregion Test Cases
public MFTestMethod[] Tests
{
get
{
return new MFTestMethod[]
{
new MFTestMethod( ExtendBuffer, "ExtendBuffer" ),
new MFTestMethod( InvalidRange, "InvalidRange" ),
new MFTestMethod( VanillaWrite, "VanillaWrite" ),
new MFTestMethod( BoundaryCheck, "BoundaryCheck" ),
};
}
}
}
}
| |
// 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.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Diagnostics.Contracts;
namespace TicTacToeEngine
{
public class TicTacToe
{
//Enumerates the possible marks
public enum marks { none=10, X, O }
//Make the board array
public int[,] board = { {1,2,3}, {4,5,6}, {7,8,9}};
//int[,] board2 = { {1,2,3}, {4,5,6}, {7,8,9}};
public int yourMark = (int)marks.none;
public int compMark = (int)marks.none;
public void ObjectInvariant()
{
CodeContract.Invariant(board != null);
}
public static void Main()
{
//Empty
}
//public int[,] Board2
//{
// get
// {
// CodeContract.Ensures(CodeContract.Result<int[,]>() != null);
// return board2;
// }
//}
//Check to see if the board has any marks on it, thus determining if it's the first turn or not.
public bool checkFirstTurn()
{
if (compMark == (int)marks.none & yourMark == (int)marks.none)
{
return true;
}
return false;
}
//Returns the move the player or the computer makes
public void assignMarks(int turn)
{
CodeContract.Requires(0 <= turn);
CodeContract.Requires(turn <= 1);
//check to see if this is the first turn
bool firstTurn = checkFirstTurn();
if (firstTurn == true)
{
//If it's the players, assign the marks accordingly
if (turn == 0)
{
yourMark = (int)marks.X;
compMark = (int)marks.O;
}
//If it's not the user's turn, and thus it is the computer's, assign marks accordingly
else if (turn == 1)
{
yourMark = (int)marks.O;
compMark = (int)marks.X;
}
}
}
//Places the move on the board, and then writes it in the Console
public int placeMove(int turn, int squareNumber)
{
CodeContract.Requires(0 <= turn);
CodeContract.Requires(turn <= 1);
CodeContract.Requires(0 <= squareNumber);
CodeContract.Requires(squareNumber <= 9);
CodeContract.Ensures(CodeContract.Result<int>() != 2);
//CodeContract.Ensures(CodeContract.Result<int>() <= 2);
//if it was the user's turn, plug his move into the array
if (turn == 0 || turn == 2)
{
if (squareNumber.Equals(1) & board[0, 0].Equals(1))
{
board[0, 0] = yourMark;
}
else if (squareNumber.Equals(2) & board[0, 1].Equals(2))
{
board[0, 1] = yourMark;
}
else if (squareNumber.Equals(3) & board[0, 2].Equals(3))
{
board[0, 2] = yourMark;
}
else if (squareNumber.Equals(4) & board[1, 0].Equals(4))
{
board[1, 0] = yourMark;
}
else if (squareNumber.Equals(5) & board[1, 1].Equals(5))
{
board[1, 1] = yourMark;
}
else if (squareNumber.Equals(6) & board[1, 2].Equals(6))
{
board[1, 2] = yourMark;
}
else if (squareNumber.Equals(7) & board[2, 0].Equals(7))
{
board[2, 0] = yourMark;
}
else if (squareNumber.Equals(8) & board[2, 1].Equals(8))
{
board[2, 1] = yourMark;
}
else if (squareNumber.Equals(9) & board[2, 2].Equals(9))
{
board[2, 2] = yourMark;
}
//If he inputed a space where there is already another mark there
else
{
//2 = incorrect space
return 2;
}
}
return turn;
}
//Checks to see if there is a winner yet.
public int checkEndGame()
{
CodeContract.Ensures(CodeContract.Result<int>() <= 3);
CodeContract.Ensures(0 <= CodeContract.Result<int>());
//Checks to see if the user won
if (checkWinner(yourMark).Equals(1))
{
//1 = user win
return 1;
}
//Checks to see if the computer won
else if (checkWinner(compMark).Equals(1))
{
//2 = comp win
return 2;
}
//Check for draw
else if (!board[0, 0].Equals(1)
& !board[0, 1].Equals(2)
& !board[0, 2].Equals(3)
& !board[1, 0].Equals(4)
& !board[1, 1].Equals(5)
& !board[1, 2].Equals(6)
& !board[2, 0].Equals(7)
& !board[2, 1].Equals(8)
& !board[2, 2].Equals(9)
)
{
//3 = draw
return 3;
}
//0 = no win
return 0;
}
//Checks to see if there is a winner yet
public int checkWinner(int mark)
{
CodeContract.Ensures(CodeContract.Result<int>() <= 1);
CodeContract.Ensures(0 <= CodeContract.Result<int>());
if (//horizontal ways to win
board[0, 0].Equals(mark) & board[0, 1].Equals(mark) & board[0, 2].Equals(mark)
|| board[1, 0].Equals(mark) & board[1, 1].Equals(mark) & board[1, 2].Equals(mark)
|| board[2, 0].Equals(mark) & board[2, 1].Equals(mark) & board[2, 2].Equals(mark)
//vertical ways to win
|| board[0, 0].Equals(mark) & board[1, 0].Equals(mark) & board[2, 0].Equals(mark)
|| board[0, 1].Equals(mark) & board[1, 1].Equals(mark) & board[2, 1].Equals(mark)
|| board[0, 2].Equals(mark) & board[1, 2].Equals(mark) & board[2, 2].Equals(mark)
//diagonal ways to win
|| board[0, 0].Equals(mark) & board[1, 1].Equals(mark) & board[2, 2].Equals(mark)
|| board[0, 2].Equals(mark) & board[1, 1].Equals(mark) & board[2, 0].Equals(mark)
)
{
return 1;
}
return 0;
}
//How the computer makes it's move
public void compMove()
{
//PLACE MARK TO WIN
//Place a mark at 1 if it leads to a win
if (
//Horizontal
board[0, 1].Equals(compMark) & board[0, 2].Equals(compMark) & board[0, 0].Equals(1)
//Vertical
|| board[1, 0].Equals(compMark) & board[2, 0].Equals(compMark) & board[0, 0].Equals(1)
//Diagonal
|| board[1, 1].Equals(compMark) & board[2, 2].Equals(compMark) & board[0, 0].Equals(1))
{
board[0, 0] = compMark;
}
//Place mark at 2 if it leads to a win
else if (
//Horizontal
board[0, 0].Equals(compMark) & board[0, 2].Equals(compMark) & board[0, 1].Equals(2)
//Vertical
|| board[1, 1].Equals(compMark) & board[2, 1].Equals(compMark) & board[0, 1].Equals(2))
{
board[0, 1] = compMark;
}
//Place mark at 3 if it leads to a win
else if (
//Horizontal
board[0, 0].Equals(compMark) & board[0, 1].Equals(compMark) & board[0, 2].Equals(3)
//Vertical
|| board[1, 2].Equals(compMark) & board[2, 2].Equals(compMark) & board[0, 2].Equals(3)
//Diagonal
|| board[1, 1].Equals(compMark) & board[2, 0].Equals(compMark) & board[0, 2].Equals(3))
{
board[0, 2] = compMark;
}
//Place mark at 4 if it leads to a win
else if (
//horizontal
board[1, 1].Equals(compMark) & board[1, 2].Equals(compMark) & board[1, 0].Equals(4)
//vertical
|| board[0, 0].Equals(compMark) & board[2, 0].Equals(compMark) & board[1, 0].Equals(4))
{
board[1, 0] = compMark;
}
//Place mark at 5 if it leads to a winn
else if (
//horizontal
board[1, 0].Equals(compMark) & board[1, 2].Equals(compMark) & board[1, 1].Equals(5)
//vertical
|| board[1, 1].Equals(compMark) & board[2, 1].Equals(compMark) & board[1, 1].Equals(5)
//diagonal +
|| board[2, 0].Equals(compMark) & board[0, 2].Equals(compMark) & board[1, 1].Equals(5)
//diagonal -
|| board[0, 0].Equals(compMark) & board[2, 2].Equals(compMark) & board[1, 1].Equals(5)
)
{
board[1, 1] = compMark;
}
//Place mark at 6 if it leads to a win
else if (
//horizontal
board[1, 0].Equals(compMark) & board[1, 1].Equals(compMark) & board[1, 2].Equals(6)
//vertical
|| board[0, 2].Equals(compMark) & board[2, 2].Equals(compMark) & board[1, 2].Equals(6))
{
board[1, 2] = compMark;
}
//Place mark at 7 if it leads to a win
else if (
//Horizontal
board[2, 1].Equals(compMark) & board[2, 2].Equals(compMark) & board[2, 0].Equals(7)
//Vertical
|| board[0, 0].Equals(compMark) & board[1, 0].Equals(compMark) & board[2, 0].Equals(7)
//Diagonal
|| board[1, 1].Equals(compMark) & board[0, 2].Equals(compMark) & board[2, 0].Equals(7)
)
{
board[2, 0] = compMark;
}
//Place mark at 8 if it leads to a win
else if (
//Horizontal
board[2, 0].Equals(compMark) & board[2, 2].Equals(compMark) & board[2, 1].Equals(8)
//Vertical
|| board[0, 1].Equals(compMark) & board[1, 1].Equals(compMark) & board[2, 1].Equals(8)
)
{
board[2, 1] = compMark;
}
//Place mark at 9 if it leads to a win
else if (
//Horizontal
board[2, 0].Equals(compMark) & board[2, 1].Equals(compMark) & board[2, 2].Equals(9)
//Vertical
|| board[0, 2].Equals(compMark) & board[1, 2].Equals(compMark) & board[2, 2].Equals(9)
//Diagonal
|| board[0, 0].Equals(compMark) & board[1, 1].Equals(compMark) & board[2, 2].Equals(9))
{
board[2, 2] = compMark;
}
// <BLOCK WIN>
//Place mark at 1 if it blocks a win
else if (
//Horizontal
board[0, 1].Equals(yourMark) & board[0, 2].Equals(yourMark) & board[0, 0].Equals(1)
//Vertical
|| board[1, 0].Equals(yourMark) & board[2, 0].Equals(yourMark) & board[0, 0].Equals(1)
//Diagonal
|| board[1, 1].Equals(yourMark) & board[2, 2].Equals(yourMark) & board[0, 0].Equals(1))
{
board[0, 0] = compMark;
}
//Place mark at 2 if it blocks a win
else if (
//Horizontal
board[0, 0].Equals(yourMark) & board[0, 2].Equals(yourMark) & board[0, 1].Equals(2)
//Vertical
|| board[1, 1].Equals(yourMark) & board[2, 1].Equals(yourMark) & board[0, 1].Equals(2))
{
board[0, 1] = compMark;
}
//Place mark at 3 if it block a win
else if (
//Horizontal
board[0, 0].Equals(yourMark) & board[0, 1].Equals(yourMark) & board[0, 2].Equals(3)
//Vertical
|| board[1, 2].Equals(yourMark) & board[2, 2].Equals(yourMark) & board[0, 2].Equals(3)
//Diagonal
|| board[1, 1].Equals(yourMark) & board[2, 0].Equals(yourMark) & board[0, 2].Equals(3))
{
board[0, 2] = compMark;
}
//Place mark at 4 if it blocks a win
else if (
//horizontal
board[1, 1].Equals(yourMark) & board[1, 2].Equals(yourMark) & board[1, 0].Equals(4)
//vertical
|| board[0, 0].Equals(yourMark) & board[2, 0].Equals(yourMark) & board[1, 0].Equals(4))
{
board[1, 0] = compMark;
}
//Place mark at 5 if it blocks a win
else if (
//horizontal
board[1, 0].Equals(yourMark) & board[1, 2].Equals(yourMark) & board[1, 1].Equals(5)
//vertical
|| board[1, 1].Equals(yourMark) & board[2, 1].Equals(yourMark) & board[1, 1].Equals(5)
//diagonal +
|| board[2, 0].Equals(yourMark) & board[0, 2].Equals(yourMark) & board[1, 1].Equals(5)
//diagonal -
|| board[0, 0].Equals(yourMark) & board[2, 2].Equals(yourMark) & board[1, 1].Equals(5)
)
{
board[1, 1] = compMark;
}
//Place mark at 6 if it blocks a win
else if (
//horizontal
board[1, 0].Equals(yourMark) & board[1, 1].Equals(yourMark) & board[1, 2].Equals(6)
//vertical
|| board[0, 2].Equals(yourMark) & board[2, 2].Equals(yourMark) & board[1, 2].Equals(6))
{
board[1, 2] = compMark;
}
//Place mark at 7 if it blocks a win
else if (
//Horizontal
board[2, 1].Equals(yourMark) & board[2, 2].Equals(yourMark) & board[2, 0].Equals(7)
//Vertical
|| board[0, 0].Equals(yourMark) & board[1, 0].Equals(yourMark) & board[2, 0].Equals(7)
//Diagonal
|| board[1, 1].Equals(yourMark) & board[0, 2].Equals(yourMark) & board[2, 0].Equals(7)
)
{
board[2, 0] = compMark;
}
//Place mark at 8 if it blocks a win
else if (
//Horizontal
board[2, 0].Equals(yourMark) & board[2, 2].Equals(yourMark) & board[2, 1].Equals(8)
//Vertical
|| board[0, 1].Equals(yourMark) & board[1, 1].Equals(yourMark) & board[2, 1].Equals(8)
)
{
board[2, 1] = compMark;
}
//Place mark at 9 if it blocks a win
else if (
//Horizontal
board[2, 0].Equals(yourMark) & board[2, 1].Equals(yourMark) & board[2, 2].Equals(9)
//Vertical
|| board[0, 2].Equals(yourMark) & board[1, 2].Equals(yourMark) & board[2, 2].Equals(9)
//Diagonal
|| board[0, 0].Equals(yourMark) & board[1, 1].Equals(yourMark) & board[2, 2].Equals(9))
{
board[2, 2] = compMark;
}
//<MAKE FORK>
//Place a mark at 1 if it makes a fork
else if (board[0, 2].Equals(compMark) & board[2, 0].Equals(compMark) & board[1, 0].Equals(4) & board[0, 1].Equals(2) & board[0, 0].Equals(1))
{
board[0, 0] = compMark;
}
//PLace a mark at 2 if it makes a fork
else if (board[0, 2].Equals(compMark) & board[1, 1].Equals(compMark) & board[2, 1].Equals(8) & board[1, 0].Equals(4) & board[0, 1].Equals(2))
{
board[0, 1] = compMark;
}
//Place a mark at 3 if it makes a fork
else if (board[0, 0].Equals(compMark) & board[2, 2].Equals(compMark) & board[0, 1].Equals(2) & board[1, 2].Equals(6) & board[0, 2].Equals(3))
{
board[0, 2] = compMark;
}
//Place a mark at 4 if it makes a fork
else if (board[0, 0].Equals(compMark) & board[1, 1].Equals(compMark) & board[1, 2].Equals(6) & board[2, 0].Equals(7) & board[1, 0].Equals(4))
{
board[1, 0] = compMark;
}
//Place a mark at 6 if it makes a fork
else if (board[1, 1].Equals(compMark) & board[2, 0].Equals(compMark) & board[0, 2].Equals(3) & board[1, 0].Equals(4) & board[1, 2].Equals(6))
{
board[1, 2] = compMark;
}
//Place a mark at 7 if it makes a fork
else if (board[0, 0].Equals(compMark) & board[2, 2].Equals(compMark) & board[1, 0].Equals(6) & board[2, 1].Equals(7) & board[2, 0].Equals(7))
{
board[2, 0] = compMark;
}
//Place a mark at 8 if it makes a fork
else if (board[1, 1].Equals(compMark) & board[2, 0].Equals(compMark) & board[0, 1].Equals(2) & board[2, 2].Equals(9) & board[2, 0].Equals(8))
{
board[2, 1] = compMark;
}
//Place a mark at 9 if it makes a fork
else if (board[0, 2].Equals(compMark) & board[2, 0].Equals(compMark) & board[2, 1].Equals(8) & board[1, 2].Equals(6) & board[2, 2].Equals(9))
{
board[2, 2] = compMark;
}
//<BLOCK FORK>
//Place a mark at 1 if it blocks a fork
else if (board[0, 2].Equals(yourMark) & board[2, 0].Equals(yourMark) & board[1,0].Equals(4) & board[0,1].Equals(2) & board[0, 0].Equals(1) )
{
board[0, 0] = compMark;
}
//PLace a mark at 2 if it blocks a fork
else if (board[0, 2].Equals(yourMark) & board[1, 1].Equals(yourMark) & board[2, 1].Equals(8) & board[1, 0].Equals(4) & board[0, 1].Equals(2))
{
board[0, 1] = compMark;
}
//Place a mark at 3 if it blocks a fork
else if (board[0, 0].Equals(yourMark) & board[2, 2].Equals(yourMark) & board[0, 1].Equals(2) & board[1, 2].Equals(6) & board[0, 2].Equals(3))
{
board[0, 2] = compMark;
}
//Place a mark at 4 if it blocks a fork
else if (board[0, 0].Equals(yourMark) & board[1, 1].Equals(yourMark) & board[1, 2].Equals(6) & board[2, 0].Equals(7) & board[1, 0].Equals(4))
{
board[1, 0] = compMark;
}
//Place a mark at 6 if it blocks a fork
else if (board[1, 1].Equals(yourMark) & board[2, 0].Equals(yourMark) & board[0, 2].Equals(3) & board[1, 0].Equals(4) & board[1, 2].Equals(6))
{
board[1, 2] = compMark;
}
//Place a mark at 7 if it blocks a fork
else if (board[0, 0].Equals(yourMark) & board[2, 2].Equals(yourMark) & board[1, 0].Equals(6) & board[2, 1].Equals(7) & board[2, 0].Equals(7))
{
board[2, 0] = compMark;
}
//Place a mark at 8 if it blocks a fork
else if (board[1, 1].Equals(yourMark) & board[2, 0].Equals(yourMark) & board[0, 1].Equals(2) & board[2, 2].Equals(9) & board[2, 0].Equals(8))
{
board[2, 1] = compMark;
}
//Place a mark at 9 if it blocks a fork
else if (board[0, 2].Equals(yourMark) & board[2, 0].Equals(yourMark) & board[2, 1].Equals(8) & board[1, 2].Equals(6) & board[2, 2].Equals(9))
{
board[2, 2] = compMark;
}
//<PLAY CENTER>
else if (board[1, 1].Equals(5))
{
board[1, 1] = compMark;
}
//PLAY CORNER
else if (board[0, 0].Equals(1))
{
board[0, 0] = compMark;
}
else if (board[0, 2].Equals(3))
{
board[0, 2] = compMark;
}
else if (board[2, 0].Equals(7))
{
board[2, 0] = compMark;
}
else if (board[2, 2].Equals(9))
{
board[2, 2] = compMark;
}
//PLAY SIDE
else if (board[0, 1].Equals(2))
{
board[0, 1] = compMark;
}
else if (board[1, 0].Equals(4))
{
board[1, 0] = compMark;
}
else if (board[1, 2].Equals(6))
{
board[1, 2] = compMark;
}
else if (board[2, 1].Equals(8))
{
board[2, 1] = compMark;
}
}
}
}
| |
using System;
using System.Text;
using System.Linq.Expressions;
using System.Reflection;
namespace DalSoft.Dynamic.DynamicExpressions
{
//Thanks and credit to http://www.codeproject.com/Articles/74018/How-to-Parse-and-Convert-a-Delegate-into-an-Expres
internal static class TypeHelper
{
public const string InvalidMultiPartNameChars = " +-*/^[]{}!\"\\%&()=?";
public const string InvalidMemberNameChars = "." + InvalidMultiPartNameChars;
/// <summary>
/// Indicates whether the type given is a nullable type or not.
/// </summary>
/// <param name="type">The Type to validate.</param>
/// <returns>If the references to objects of this type can be null or not.</returns>
public static bool IsNullableType( Type type )
{
if( type == null ) throw new ArgumentNullException( "Type" );
if( type.IsValueType ) return false;
if( type.IsClass ) return true;
Type generic = type.IsGenericType ? type.GetGenericTypeDefinition() : null;
bool r = generic == null ? false : generic.Equals( typeof( Nullable<> ) );
return r;
}
public static bool IsNullableType<T>()
{
return IsNullableType( typeof( T ) );
}
#region
internal static Delegate _CreateConverterDelegate( Type sourceType, Type targetType )
{
// Following is a variation of code courtesy of Richard Deeming...
var input = Expression.Parameter( sourceType, "input" );
Expression body;
try { body = Expression.Convert( input, targetType ); }
catch( InvalidOperationException ) {
var conversionType = Expression.Constant( targetType );
body = Expression.Call( typeof( Convert ), "ChangeType", null, input, conversionType );
}
var result = Expression.Lambda( body, input );
return result.Compile();
}
#endregion
public static object ConvertTo( object source, Type targetType )
{
// Following code courtesy of Richard Deeming, answering an original article posted by MBarbaC.
if( targetType == null ) throw new ArgumentNullException( "Target Type" );
Type sourceType = ( source == null ) ? typeof( object ) : source.GetType();
Delegate converter = _CreateConverterDelegate( sourceType, targetType );
return converter.DynamicInvoke( source );
}
public static T ConvertTo<T>( object source )
{
T target = (T)ConvertTo( source, typeof( T ) );
return target;
}
public static string GetMemberName<T>( Expression<Func<T, object>> exp, bool raise = true )
{
if( exp == null ) throw new ArgumentNullException( "Member access expression" );
Type type = typeof( T );
var member = exp.Body as MemberExpression; if( member != null ) return member.Member.Name;
var unary = exp.Body as UnaryExpression; if( unary != null ) {
MemberExpression temp = unary.Operand as MemberExpression;
if( temp != null ) return temp.Member.Name;
}
if( raise ) throw new ArgumentException( "Invalid member access expression '" + exp.ToString() + "' for type '" + type + "'." );
return null;
}
#region
static BindingFlags _memberFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;
#endregion
public static MemberInfo GetMemberInfo( Type declaringType, string memberName, bool raise = true )
{
if( declaringType == null ) throw new ArgumentNullException( "Declaring Type" );
memberName = memberName.Validated( "Member name", invalidChars: InvalidMemberNameChars );
MemberInfo info = null;
// Trying properties...
info = declaringType.GetProperty( memberName, _memberFlags );
if( info != null ) return info;
// Trying fields...
info = declaringType.GetField( memberName, _memberFlags );
if( info != null ) return info;
// Not found...
if( raise ) throw new ArgumentException( "Member '" + memberName + "' not found in type '" + declaringType + "'." );
return null;
}
public static MemberInfo GetMemberInfo<T>( string memberName, bool raise = true )
{
return TypeHelper.GetMemberInfo( typeof( T ), memberName, raise );
}
public static Type GetMemberType( Type declaringType, string memberName, bool raise = true )
{
if( declaringType == null ) throw new ArgumentNullException( "Declaring Type" );
memberName = memberName.Validated( "Member name", invalidChars: InvalidMemberNameChars );
PropertyInfo pinfo = declaringType.GetProperty( memberName, _memberFlags );
if( pinfo != null ) return pinfo.PropertyType;
FieldInfo finfo = declaringType.GetField( memberName, _memberFlags );
if( finfo != null ) return finfo.FieldType;
if( raise ) throw new ArgumentException( "Cannot find member '" + memberName + "' for type '" + declaringType + "'." );
return null;
}
public static Type GetMemberType<T>( string memberName, bool raise = true )
{
return GetMemberType( typeof( T ), memberName, raise );
}
public static object GetMemberValue( object obj, MemberInfo info )
{
if( info == null ) throw new ArgumentNullException( "MemberInfo" );
switch( info.MemberType ) {
case MemberTypes.Property: return ( (PropertyInfo)info ).GetValue( obj, null );
case MemberTypes.Field: return ( (FieldInfo)info ).GetValue( obj );
}
throw new InvalidOperationException( "Member '" + info.Name + "' is not a property or a field." );
}
public static object GetMemberValue<T>( T obj, string memberName )
{
MemberInfo info = GetMemberInfo<T>( memberName, raise: true );
return TypeHelper.GetMemberValue( obj, info );
}
public static void SetMemberValue( object obj, MemberInfo info, object val )
{
if( info == null ) throw new ArgumentNullException( "MemberInfo" );
switch( info.MemberType ) {
case MemberTypes.Property: ( (PropertyInfo)info ).SetValue( obj, val, null ); return;
case MemberTypes.Field: ( (FieldInfo)info ).SetValue( obj, val ); return;
}
throw new InvalidOperationException( "Member '" + info.Name + "' is not a property or a field." );
}
public static void SetMemberValue<T>( T obj, string memberName, object val )
{
MemberInfo info = GetMemberInfo<T>( memberName, raise: true );
TypeHelper.SetMemberValue( obj, info, val );
}
public static MethodInfo GetMethodInfo( Type declaringType, string methodName, bool raise = true )
{
if( declaringType == null ) throw new ArgumentNullException( "Declaring Type" );
methodName = methodName.Validated( "Member name", invalidChars: InvalidMemberNameChars );
MethodInfo info = declaringType.GetMethod( methodName, _memberFlags );
if( info == null && raise ) throw new ArgumentException( "Method: '" + methodName + "' not found in type '" + declaringType + "'." );
return info;
}
public static MethodInfo GetMethodInfo<T>( string methodName, bool raise = true )
{
return GetMethodInfo( typeof( T ), methodName, raise );
}
public static object InvokeMethod( Type declaringType, string methodName, object target, params object[] args )
{
MethodInfo info = GetMethodInfo( declaringType, methodName, raise: true );
object obj = info.Invoke( target, args );
return obj;
}
public static object InvokeMethod<T>( string methodName, object target, params object[] args )
{
MethodInfo info = GetMethodInfo<T>( methodName, raise: true );
object obj = info.Invoke( target, args );
return obj;
}
public static string ObjectStateToString( object obj )
{
if( obj == null ) throw new ArgumentNullException( "Object reference" );
Type type = obj.GetType();
MemberInfo[] members = type.GetMembers( _memberFlags );
StringBuilder sb = new StringBuilder();
bool first = true;
foreach( MemberInfo member in members ) {
if( member.MemberType == MemberTypes.Field || member.MemberType == MemberTypes.Property ) {
if( member.Name[ 0 ] == '<' ) continue;
object value = TypeHelper.GetMemberValue( obj, member );
if( !first ) sb.Append( ", " ); else first = false;
sb.AppendFormat( "{0}:'{1}'", member.Name, value == null ? "[null]" : value.ToString() );
}
}
return sb.ToString();
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.ComponentModel;
namespace esmesim.smpp
{
public enum BindType : int
{
Receiver,
Transmitter,
Transceiver
}
public enum BindResult : int
{
Ok,
InvalidUser,
InvalidPassword,
InvalidAddress,
InvalidCommand,
Fail
}
public enum DeliveryResult : int
{
Ok,
Rejected,
InvalidSourceAddress,
InvalidDestinationAddress,
Fail
}
public enum DisconnectReason : int
{
Unbind,
Kicked,
NetworkError
}
public enum DataCoding : int
{
Default = 0,
Ansi = 1,
Gsm0338 = 2,
Latin1 = 3,
Unicode = 8,
UTF8 = 11
}
/// <summary>
/// Defines setting for message delivering and reception
/// Allows us to execute proper workaround to common SMSC limitations
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public sealed class MessageSettings
{
/// <summary>
/// Defines the data coding used to sent messages (default = 0)
/// </summary>
[MarshalAs(UnmanagedType.U4)]
public DataCoding DeliverDataCoding;
/// <summary>
/// Defines the encoding used by the SMSC, used when \c DeliverDataCoding = 0
/// </summary>
[MarshalAs(UnmanagedType.U4)]
public DataCoding ServerDefaultEncoding;
/// <summary>
/// Determines when the message content should be encoded using GSM-7bit packing (default=0)
/// </summary>
[MarshalAs(UnmanagedType.U1)]
public bool EnableGSM7bitPacking;
/// <summary>
/// The maximum count in characters of a message (default = 0: MAX_MESSAGE_LENGTH)
/// Please note that if \c EnablePayload is set longer messages can be sent
/// </summary>
[MarshalAs(UnmanagedType.U4)]
public int MaxMessageLength;
/// <summary>
/// Allows to use the SMPP concatenated message function (default = 1)
/// </summary>
[MarshalAs(UnmanagedType.U1)]
public bool EnableMessageConcatenation;
/// <summary>
/// Allows the long messages as a payload (TLV) (default = 1)
/// </summary>
[MarshalAs(UnmanagedType.U1)]
public bool EnablePayload;
/// <summary>
/// This flag indicates if the SUBMIT_MULTI_SM operation is supported by the server.
/// If it is not then requests of this type are split into individual
/// SUBMIT_SM operations (default = 1)
/// </summary>
[MarshalAs(UnmanagedType.U1)]
public bool EnableSubmitMulti;
}
/// <summary>
/// Represents the method that will handle the <typeparamref name="SMPPClient.NewMessage"/> event.
/// </summary>
/// <param name="from">Number the message is from</param>
/// <param name="to">Number the message is directed to</param>
/// <param name="content">The message content</param>
public delegate void NewMessageEventHandler(string from, string to, string content);
/// <summary>
/// Represents the method that will handle the <typeparamref name="SMPPClient.ConnectionLost"/> event.
/// </summary>
public delegate void ConnectionLostEventHandler();
/// <summary>
///
/// </summary>
public class DeliveryException : Exception
{
public DeliveryException(DeliveryResult r)
{
m_result = r;
}
public DeliveryResult Result
{
get
{
return m_result;
}
}
private DeliveryResult m_result;
}
/// <summary>
///
/// </summary>
public class BindException : Exception
{
/// <summary>
///
/// </summary>
/// <param name="r"></param>
public BindException(BindResult r)
{
m_result = r;
}
/// <summary>
///
/// </summary>
public BindResult Result
{
get
{
return m_result;
}
}
private BindResult m_result;
}
public unsafe class SMPPClient : IDisposable
{
/// <summary>
/// Internal structure to handle incoming text messages
/// </summary>
private struct MessageInfo
{
public readonly string From;
public readonly string To;
public readonly string Message;
public MessageInfo(string from, string to, string msg)
{
From = from;
To = to;
Message = msg;
}
}
#region Native Types
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void Callback_OnIncomingMessage(
IntPtr hClient,
string from,
string to,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] byte[] content,
[MarshalAs(UnmanagedType.U4)] int bufferSize
);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void Callback_OnConnectionLost(
IntPtr hClient,
[MarshalAs(UnmanagedType.I4)] int reason
);
[DllImport("opensmpp", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
private static extern void libSMPP_CreateDefaultMessageSettings(
[MarshalAs(UnmanagedType.Struct)] ref MessageSettings ms
);
[DllImport("opensmpp", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr libSMPP_ClientCreate(
[MarshalAs(UnmanagedType.FunctionPtr)] Callback_OnIncomingMessage onNewMessage,
[MarshalAs(UnmanagedType.FunctionPtr)] Callback_OnConnectionLost onConnectionLost
);
[DllImport("opensmpp", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr libSMPP_ClientDelete(
IntPtr hClient
);
[DllImport("opensmpp", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
private static extern void libSMPP_ClientSetServerAddress (
IntPtr hClient, string serverIP, ushort serverPort
);
[DllImport("opensmpp", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
private static extern void libSMPP_ClientSetLoginType(
IntPtr hClient, BindType loginType
);
[DllImport("opensmpp", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
private static extern void libSMPP_ClientSetSystemId(
IntPtr hClient, string systemId
);
[DllImport("opensmpp", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
private static extern void libSMPP_ClientSetSystemType(
IntPtr hClient, string systemType
);
[DllImport("opensmpp", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
private static extern void libSMPP_ClientSetPassword(
IntPtr hClient, string password
);
[DllImport("opensmpp", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
private static extern void libSMPP_ClientSetAddressRange(
IntPtr hClient, string pattern
);
[DllImport("opensmpp", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
private static extern void libSMPP_ClientSetMessageSettings(
IntPtr hClient,
[MarshalAs(UnmanagedType.LPStruct)] MessageSettings ms
);
[DllImport("opensmpp", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
private static extern BindResult libSMPP_ClientBind(
IntPtr hClient
);
[DllImport("opensmpp", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
private static extern void libSMPP_ClientUnBind(
IntPtr hClient
);
[DllImport("opensmpp", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
private static extern DeliveryResult libSMPP_ClientSendMessage(
IntPtr hClient,
string from,
string to,
[MarshalAs(UnmanagedType.LPArray)] byte[] content,
[MarshalAs(UnmanagedType.U4)] int size
);
#endregion // Native Types
private IntPtr m_handle;
private MessageSettings m_settings;
private bool m_bound = false;
private string m_systemId = String.Empty;
private string m_systemType = String.Empty;
private string m_password = String.Empty;
private List<string> m_addresses = new List<string>();
private NewMessageEventHandler m_onNewMessage;
private ConnectionLostEventHandler m_onConnectionLost;
private Callback_OnIncomingMessage m_onNewMessageNative;
private Callback_OnConnectionLost m_onConnectionLostNative;
public SMPPClient()
{
Queue<MessageInfo> messageQueue = new Queue<MessageInfo>();
m_onNewMessageNative = new Callback_OnIncomingMessage(delegate(IntPtr hClient, string from, string to, byte[] content, int bufferSize)
{
lock (messageQueue)
{
int size = messageQueue.Count;
messageQueue.Enqueue(new MessageInfo(from, to, Encoding.UTF8.GetString(content)));
if (size == 0)
{
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(delegate(object sender, DoWorkEventArgs e)
{
MessageInfo info;
while (true)
{
lock (messageQueue)
{
if (messageQueue.Count == 0)
{
break;
}
info = messageQueue.Dequeue();
}
try
{
if (m_onNewMessage != null)
{
m_onNewMessage(info.From, info.To, info.Message);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
}
});
bw.RunWorkerAsync();
}
}
});
m_onConnectionLostNative = new Callback_OnConnectionLost(delegate(IntPtr hClient, int reason)
{
if (!m_bound)
{
Debug.WriteLine("OnConnectionLost called unbound");
}
m_bound = false;
if (m_onConnectionLost != null)
{
m_onConnectionLost();
}
});
m_handle = libSMPP_ClientCreate(m_onNewMessageNative, m_onConnectionLostNative);
m_settings = new MessageSettings();
libSMPP_CreateDefaultMessageSettings(ref m_settings);
}
/// <summary>
/// Fired when a new text message arrives
/// </summary>
public event NewMessageEventHandler NewMessage
{
add
{
m_onNewMessage += value;
}
remove
{
m_onNewMessage -= value;
}
}
/// <summary>
/// Fired when the connection with the server is lost
/// </summary>
public event ConnectionLostEventHandler ConnectionLost
{
add
{
m_onConnectionLost += value;
}
remove
{
m_onConnectionLost -= value;
}
}
/// <summary>
/// Returns <c>true</c> if the client is connected with the server
/// </summary>
public bool Bound
{
get
{
return m_bound;
}
}
/// <summary>
/// Gets or sets the login user (aka system id)
/// </summary>
public string SystemId
{
get
{
return m_systemId;
}
set
{
OnUsernameChanged(value);
}
}
/// <summary>
/// Gets or sets the user password
/// </summary>
public string Password
{
get
{
return m_password;
}
set
{
OnPasswordChanged(value);
}
}
/// <summary>
/// Gets or sets the system type
/// </summary>
public string SystemType
{
get
{
return m_systemType;
}
set
{
OnSystemTypeChanged(value);
}
}
/// <summary>
/// Contains the list of numbers being handled by this user
/// </summary>
public ICollection<string> Addresses
{
get
{
return m_addresses;
}
}
public MessageSettings Settings
{
get
{
return m_settings;
}
}
/// <summary>
///
/// </summary>
/// <param name="bindType"></param>
/// <param name="server"></param>
/// <param name="port"></param>
public void Bind(BindType bindType, string server, ushort port)
{
if (m_bound)
{
throw new InvalidOperationException("Already bound");
}
libSMPP_ClientSetLoginType(m_handle, bindType);
libSMPP_ClientSetServerAddress(m_handle, server, port);
libSMPP_ClientSetAddressRange(m_handle, String.Join("|", m_addresses.ToArray()));
libSMPP_ClientSetMessageSettings(m_handle, m_settings);
BindResult result = libSMPP_ClientBind(m_handle);
if (result != BindResult.Ok)
{
throw new BindException(result);
}
m_bound = true;
}
/// <summary>
///
/// </summary>
public void Unbind()
{
if (!m_bound)
{
throw new InvalidOperationException("Not bound");
}
libSMPP_ClientUnBind(m_handle);
m_bound = false;
}
/// <summary>
///
/// </summary>
/// <param name="from"></param>
/// <param name="to"></param>
/// <param name="content"></param>
public void SendMessage(string from, string to, string content)
{
if (!m_bound)
{
throw new InvalidOperationException("Not bound");
}
byte[] contentBytes = Encoding.UTF8.GetBytes(content);
DeliveryResult result = libSMPP_ClientSendMessage(m_handle, from, to, contentBytes, contentBytes.Length);
if (result != DeliveryResult.Ok)
{
throw new DeliveryException(result);
}
}
private void OnUsernameChanged(string newvalue)
{
if (m_bound)
{
throw new InvalidOperationException("Already bound");
}
if (newvalue != m_systemId)
{
m_systemId = newvalue;
libSMPP_ClientSetSystemId(m_handle, m_systemId);
}
}
private void OnPasswordChanged(string newvalue)
{
if (m_bound)
{
throw new InvalidOperationException("Already bound");
}
if (newvalue != m_password)
{
m_password = newvalue;
libSMPP_ClientSetPassword(m_handle, m_password);
}
}
private void OnSystemTypeChanged(string newvalue)
{
if (m_bound)
{
throw new InvalidOperationException("Already bound");
}
if (newvalue != m_systemType)
{
m_systemType = newvalue;
libSMPP_ClientSetSystemType(m_handle, m_systemType);
}
}
#region IDisposable implementation
public void Dispose()
{
if (m_bound)
{
Unbind();
}
libSMPP_ClientDelete(m_handle);
m_handle = IntPtr.Zero;
GC.SuppressFinalize(this);
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.Build.Engine
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.DocAsCode.Common;
using Microsoft.DocAsCode.Plugins;
using Microsoft.DocAsCode.Utility;
public class TemplateProcessor : IDisposable
{
private readonly ResourceCollection _resourceProvider;
private readonly object _global;
private readonly TemplateCollection _templateCollection;
public static List<TemplateManifestItem> Process(TemplateProcessor processor, List<ManifestItem> manifest, DocumentBuildContext context, ApplyTemplateSettings settings)
{
if (processor == null)
{
processor = new TemplateProcessor(new EmptyResourceCollection(), 1);
}
return processor.Process(manifest, context, settings);
}
/// <summary>
/// TemplateName can be either file or folder
/// 1. If TemplateName is file, it is considered as the default template
/// 2. If TemplateName is a folder, files inside the folder is considered as the template, each file is named after {DocumentType}.{extension}
/// </summary>
/// <param name="templateName"></param>
/// <param name="resourceProvider"></param>
public TemplateProcessor(ResourceCollection resourceProvider, int maxParallelism = 0)
{
if (maxParallelism <= 0)
{
maxParallelism = Environment.ProcessorCount;
}
_resourceProvider = resourceProvider;
_global = LoadGlobalJson(resourceProvider);
_templateCollection = new TemplateCollection(resourceProvider, maxParallelism);
}
public bool TryGetFileExtension(string documentType, out string fileExtension)
{
if (string.IsNullOrEmpty(documentType)) throw new ArgumentNullException(nameof(documentType));
fileExtension = string.Empty;
if (_templateCollection.Count == 0) return false;
var templateBundle = _templateCollection[documentType];
// Get default template extension
if (templateBundle == null) return false;
fileExtension = templateBundle.Extension;
return true;
}
public List<TemplateManifestItem> Process(List<ManifestItem> manifest, DocumentBuildContext context, ApplyTemplateSettings settings)
{
using (new LoggerPhaseScope("Apply Templates"))
{
var documentTypes = manifest.Select(s => s.DocumentType).Distinct();
var notSupportedDocumentTypes = documentTypes.Where(s => s != "Resource" && _templateCollection[s] == null);
if (notSupportedDocumentTypes.Any())
{
Logger.LogWarning($"There is no template processing document type(s): {notSupportedDocumentTypes.ToDelimitedString()}");
}
Logger.LogInfo($"Applying templates to {manifest.Count} model(s)...");
if (settings.Options.HasFlag(ApplyTemplateOptions.TransformDocument))
{
var templatesInUse = documentTypes.Select(s => _templateCollection[s]).Where(s => s != null).ToList();
ProcessDependencies(settings.OutputFolder, templatesInUse);
}
else
{
Logger.LogInfo("Dryrun, no template will be applied to the documents.");
}
var outputDirectory = context.BuildOutputFolder;
var templateManifest = ProcessCore(manifest, context, settings);
SaveManifest(templateManifest, outputDirectory, context);
return templateManifest;
}
}
private void ProcessDependencies(string outputDirectory, IEnumerable<TemplateBundle> templateBundles)
{
foreach (var resourceInfo in templateBundles.SelectMany(s => s.Resources).Distinct())
{
try
{
// TODO: support glob pattern
if (resourceInfo.IsRegexPattern)
{
var regex = new Regex(resourceInfo.ResourceKey, RegexOptions.IgnoreCase);
foreach (var name in _resourceProvider.Names)
{
if (regex.IsMatch(name))
{
using (var stream = _resourceProvider.GetResourceStream(name))
{
ProcessSingleDependency(stream, outputDirectory, name);
}
}
}
}
else
{
using (var stream = _resourceProvider.GetResourceStream(resourceInfo.ResourceKey))
{
ProcessSingleDependency(stream, outputDirectory, resourceInfo.FilePath);
}
}
}
catch (Exception e)
{
Logger.Log(LogLevel.Info, $"Unable to get relative resource for {resourceInfo.FilePath}: {e.Message}");
}
}
}
private void ProcessSingleDependency(Stream stream, string outputDirectory, string filePath)
{
if (stream != null)
{
var path = Path.Combine(outputDirectory, filePath);
var dir = Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
using (var writer = new FileStream(path, FileMode.Create, FileAccess.ReadWrite))
{
stream.CopyTo(writer);
}
Logger.Log(LogLevel.Verbose, $"Saved resource {filePath} that template dependants on to {path}");
}
else
{
Logger.Log(LogLevel.Info, $"Unable to get relative resource for {filePath}");
}
}
private List<TemplateManifestItem> ProcessCore(List<ManifestItem> items, DocumentBuildContext context, ApplyTemplateSettings settings)
{
var manifest = new ConcurrentBag<TemplateManifestItem>();
var systemAttributeGenerator = new SystemMetadataGenerator(context);
var transformer = new TemplateModelTransformer(context, _templateCollection, settings, _global);
items.RunAll(
item =>
{
var manifestItem = transformer.Transform(item);
manifest.Add(manifestItem);
},
context.MaxParallelism);
return manifest.ToList();
}
private static object LoadGlobalJson(ResourceCollection resource)
{
var globalJson = resource.GetResource("global.json");
if (!string.IsNullOrEmpty(globalJson))
{
return JsonUtility.FromJsonString<object>(globalJson);
}
return null;
}
private static void SaveManifest(List<TemplateManifestItem> templateManifest, string outputDirectory, IDocumentBuildContext context)
{
// Save manifest from template
// TODO: Keep .manifest for backward-compatability, will remove next sprint
var manifestPath = Path.Combine(outputDirectory ?? string.Empty, Constants.ObsoleteManifestFileName);
JsonUtility.Serialize(manifestPath, templateManifest);
// Logger.LogInfo($"Manifest file saved to {manifestPath}. NOTE: This file is out-of-date and will be removed in version 1.8, if you rely on this file, please change to use {Constants.ManifestFileName} instead.");
var manifestJsonPath = Path.Combine(outputDirectory ?? string.Empty, Constants.ManifestFileName);
var toc = context.GetTocInfo();
var manifestObject = GenerateManifest(context, templateManifest);
JsonUtility.Serialize(manifestJsonPath, manifestObject);
Logger.LogInfo($"Manifest file saved to {manifestJsonPath}.");
}
private static Manifest GenerateManifest(IDocumentBuildContext context, List<TemplateManifestItem> items)
{
var toc = context.GetTocInfo();
var homepages = toc
.Where(s => !string.IsNullOrEmpty(s.Homepage))
.Select(s => new HomepageInfo
{
Homepage = RelativePath.GetPathWithoutWorkingFolderChar(s.Homepage),
TocPath = RelativePath.GetPathWithoutWorkingFolderChar(context.GetFilePath(s.TocFileKey))
}).ToList();
return new Manifest
{
Homepages = homepages,
Files = items,
XRefMap = DocumentBuilder.XRefMapFileName,
};
}
public void Dispose()
{
_resourceProvider?.Dispose();
}
}
}
| |
/* ====================================================================
*/
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Xml;
using System.Text;
namespace Oranikle.ReportDesigner
{
/// <summary>
/// Filters specification: used for DataRegions (List, Chart, Table, Matrix), DataSets, group instances
/// </summary>
internal class FiltersCtl : Oranikle.ReportDesigner.Base.BaseControl, IProperty
{
private DesignXmlDraw _Draw;
private XmlNode _FilterParent;
private DataGridViewTextBoxColumn dgtbFE;
private DataGridViewComboBoxColumn dgtbOP;
private DataGridViewTextBoxColumn dgtbFV;
private Oranikle.Studio.Controls.StyledButton bDelete;
private System.Windows.Forms.DataGridView dgFilters;
private Oranikle.Studio.Controls.StyledButton bUp;
private Oranikle.Studio.Controls.StyledButton bDown;
private Oranikle.Studio.Controls.StyledButton bValueExpr;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
internal FiltersCtl(DesignXmlDraw dxDraw, XmlNode filterParent)
{
_Draw = dxDraw;
_FilterParent = filterParent;
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// Initialize form using the style node values
InitValues();
}
private void InitValues()
{
// Initialize the DataGrid columns
dgtbFE = new DataGridViewTextBoxColumn();
dgtbOP = new DataGridViewComboBoxColumn();
dgtbOP.Items.AddRange(new string[]
{ "Equal", "Like", "NotEqual", "GreaterThan", "GreaterThanOrEqual", "LessThan",
"LessThanOrEqual", "TopN", "BottomN", "TopPercent", "BottomPercent", "In", "Between" });
dgtbFV = new DataGridViewTextBoxColumn();
dgFilters.Columns.Add(dgtbFE);
dgFilters.Columns.Add(dgtbOP);
dgFilters.Columns.Add(dgtbFV);
//
// dgtbFE
//
dgtbFE.HeaderText = "Filter Expression";
dgtbFE.Width = 130;
// Get the parent's dataset name
//string dataSetName = _Draw.GetDataSetNameValue(_FilterParent);
// unfortunately no way to make combo box editable
//string[] fields = _Draw.GetFields(dataSetName, true);
//if (fields != null)
// dgtbFE.Items.AddRange(fields);
dgtbOP.HeaderText = "Operator";
dgtbOP.Width = 100;
dgtbOP.DropDownWidth = 140;
//
// dgtbFV
//
this.dgtbFV.HeaderText = "Value(s)";
this.dgtbFV.Width = 130;
//string[] parms = _Draw.GetReportParameters(true);
//if (parms != null)
// dgtbFV.Items.AddRange(parms);
XmlNode filters = _Draw.GetNamedChildNode(_FilterParent, "Filters");
if (filters != null)
foreach (XmlNode fNode in filters.ChildNodes)
{
if (fNode.NodeType != XmlNodeType.Element ||
fNode.Name != "Filter")
continue;
// Get the values
XmlNode vNodes = _Draw.GetNamedChildNode(fNode, "FilterValues");
StringBuilder sb = new StringBuilder();
if (vNodes != null)
{
foreach (XmlNode v in vNodes.ChildNodes)
{
if (v.InnerText.Length <= 0)
continue;
if (sb.Length != 0)
sb.Append(", ");
sb.Append(v.InnerText);
}
}
// Add the row
dgFilters.Rows.Add(_Draw.GetElementValue(fNode, "FilterExpression", ""),
_Draw.GetElementValue(fNode, "Operator", "Equal"),
sb.ToString());
}
if (dgFilters.Rows.Count == 0)
dgFilters.Rows.Add("","Equal","");
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.dgFilters = new System.Windows.Forms.DataGridView();
this.bDelete = new Oranikle.Studio.Controls.StyledButton();
this.bUp = new Oranikle.Studio.Controls.StyledButton();
this.bDown = new Oranikle.Studio.Controls.StyledButton();
this.bValueExpr = new Oranikle.Studio.Controls.StyledButton();
((System.ComponentModel.ISupportInitialize)(this.dgFilters)).BeginInit();
this.SuspendLayout();
//
// dgFilters
//
this.dgFilters.BackgroundColor = System.Drawing.Color.White;
this.dgFilters.Location = new System.Drawing.Point(8, 8);
this.dgFilters.Name = "dgFilters";
this.dgFilters.Size = new System.Drawing.Size(376, 264);
this.dgFilters.TabIndex = 2;
//
// bDelete
//
this.bDelete.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.bDelete.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.bDelete.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.bDelete.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.bDelete.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.bDelete.Font = new System.Drawing.Font("Arial", 9F);
this.bDelete.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.bDelete.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bDelete.Location = new System.Drawing.Point(392, 40);
this.bDelete.Name = "bDelete";
this.bDelete.OverriddenSize = null;
this.bDelete.Size = new System.Drawing.Size(48, 21);
this.bDelete.TabIndex = 1;
this.bDelete.Text = "Delete";
this.bDelete.UseVisualStyleBackColor = true;
this.bDelete.Click += new System.EventHandler(this.bDelete_Click);
//
// bUp
//
this.bUp.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.bUp.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.bUp.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.bUp.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.bUp.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.bUp.Font = new System.Drawing.Font("Arial", 9F);
this.bUp.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.bUp.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bUp.Location = new System.Drawing.Point(392, 71);
this.bUp.Name = "bUp";
this.bUp.OverriddenSize = null;
this.bUp.Size = new System.Drawing.Size(48, 21);
this.bUp.TabIndex = 3;
this.bUp.Text = "Up";
this.bUp.UseVisualStyleBackColor = true;
this.bUp.Click += new System.EventHandler(this.bUp_Click);
//
// bDown
//
this.bDown.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.bDown.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.bDown.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.bDown.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.bDown.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.bDown.Font = new System.Drawing.Font("Arial", 9F);
this.bDown.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.bDown.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bDown.Location = new System.Drawing.Point(392, 102);
this.bDown.Name = "bDown";
this.bDown.OverriddenSize = null;
this.bDown.Size = new System.Drawing.Size(48, 21);
this.bDown.TabIndex = 4;
this.bDown.Text = "Down";
this.bDown.UseVisualStyleBackColor = true;
this.bDown.Click += new System.EventHandler(this.bDown_Click);
//
// bValueExpr
//
this.bValueExpr.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.bValueExpr.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.bValueExpr.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.bValueExpr.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.bValueExpr.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.bValueExpr.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.bValueExpr.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.bValueExpr.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bValueExpr.Location = new System.Drawing.Point(392, 16);
this.bValueExpr.Name = "bValueExpr";
this.bValueExpr.OverriddenSize = null;
this.bValueExpr.Size = new System.Drawing.Size(22, 21);
this.bValueExpr.TabIndex = 5;
this.bValueExpr.Tag = "value";
this.bValueExpr.Text = "fx";
this.bValueExpr.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bValueExpr.UseVisualStyleBackColor = true;
this.bValueExpr.Click += new System.EventHandler(this.bValueExpr_Click);
//
// FiltersCtl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.Controls.Add(this.bValueExpr);
this.Controls.Add(this.bDown);
this.Controls.Add(this.bUp);
this.Controls.Add(this.bDelete);
this.Controls.Add(this.dgFilters);
this.Name = "FiltersCtl";
this.Size = new System.Drawing.Size(488, 304);
((System.ComponentModel.ISupportInitialize)(this.dgFilters)).EndInit();
this.ResumeLayout(false);
}
#endregion
public bool IsValid()
{
return true;
}
public void Apply()
{
// Remove the old filters
XmlNode filters = null;
_Draw.RemoveElement(_FilterParent, "Filters");
// Loop thru and add all the filters
foreach (DataGridViewRow dr in this.dgFilters.Rows)
{
string fe = dr.Cells[0].Value as string;
string op = dr.Cells[1].Value as string;
string fv = dr.Cells[2].Value as string;
if (fe == null || fe.Length <= 0 ||
op == null || op.Length <= 0 ||
fv == null || fv.Length <= 0)
continue;
if (filters == null)
filters = _Draw.CreateElement(_FilterParent, "Filters", null);
XmlNode fNode = _Draw.CreateElement(filters, "Filter", null);
_Draw.CreateElement(fNode, "FilterExpression", fe);
_Draw.CreateElement(fNode, "Operator", op);
XmlNode fvNode = _Draw.CreateElement(fNode, "FilterValues", null);
if (op == "In")
{
string[] vs = fv.Split(',');
foreach (string v in vs)
_Draw.CreateElement(fvNode, "FilterValue", v.Trim());
}
else if (op == "Between")
{
string[] vs = fv.Split(new char[] {','}, 2);
foreach (string v in vs)
_Draw.CreateElement(fvNode, "FilterValue", v.Trim());
}
else
{
_Draw.CreateElement(fvNode, "FilterValue", fv);
}
}
}
private void bDelete_Click(object sender, System.EventArgs e)
{
if (dgFilters.CurrentRow == null)
return;
if (!dgFilters.Rows[dgFilters.CurrentRow.Index].IsNewRow) // can't delete the new row
dgFilters.Rows.RemoveAt(this.dgFilters.CurrentRow.Index);
else
{ // just empty out the values
DataGridViewRow dgrv = dgFilters.Rows[this.dgFilters.CurrentRow.Index];
dgrv.Cells[0].Value = null;
dgrv.Cells[1].Value = "Equal";
dgrv.Cells[2].Value = null;
}
}
private void bUp_Click(object sender, System.EventArgs e)
{
int cr = dgFilters.CurrentRow == null ? 0 : dgFilters.CurrentRow.Index;
if (cr <= 0) // already at the top
return;
SwapRow(dgFilters.Rows[cr - 1], dgFilters.Rows[cr]);
dgFilters.CurrentCell =
dgFilters.Rows[cr-1].Cells[dgFilters.CurrentCell.ColumnIndex];
}
private void bDown_Click(object sender, System.EventArgs e)
{
int cr = dgFilters.CurrentRow == null ? 0 : dgFilters.CurrentRow.Index;
if (cr < 0) // invalid index
return;
if (cr + 1 >= dgFilters.Rows.Count)
return; // already at end
SwapRow(dgFilters.Rows[cr+1], dgFilters.Rows[cr]);
dgFilters.CurrentCell =
dgFilters.Rows[cr + 1].Cells[dgFilters.CurrentCell.ColumnIndex];
}
private void SwapRow(DataGridViewRow tdr, DataGridViewRow fdr)
{
// column 1
object save = tdr.Cells[0].Value;
tdr.Cells[0].Value = fdr.Cells[0].Value;
fdr.Cells[0].Value = save;
// column 2
save = tdr.Cells[1].Value;
tdr.Cells[1].Value = fdr.Cells[1].Value;
fdr.Cells[1].Value = save;
// column 3
save = tdr.Cells[2].Value;
tdr.Cells[2].Value = fdr.Cells[2].Value;
fdr.Cells[2].Value = save;
return;
}
private void bValueExpr_Click(object sender, System.EventArgs e)
{
if (dgFilters.CurrentCell == null)
dgFilters.Rows.Add("", "Equal", "");
DataGridViewCell dgc = dgFilters.CurrentCell;
int cc = dgc.ColumnIndex;
string cv = dgc.Value as string;
if (cc == 1)
{ // This is the FilterOperator
DialogFilterOperator fo = new DialogFilterOperator(cv);
try
{
DialogResult dlgr = fo.ShowDialog();
if (dlgr == DialogResult.OK)
dgc.Value = fo.Operator;
}
finally
{
fo.Dispose();
}
}
else
{
DialogExprEditor ee = new DialogExprEditor(_Draw, cv, _FilterParent, false);
try
{
DialogResult dlgr = ee.ShowDialog();
if (dlgr == DialogResult.OK)
dgc.Value = ee.Expression;
}
finally
{
ee.Dispose();
}
}
}
}
}
| |
namespace SubtextUpgrader {
partial class UpgradeForm {
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent() {
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(UpgradeForm));
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.Backup = new System.Windows.Forms.TextBox();
this.button2 = new System.Windows.Forms.Button();
this.Destination = new System.Windows.Forms.TextBox();
this.button3 = new System.Windows.Forms.Button();
this.Verbose = new System.Windows.Forms.CheckBox();
this.button4 = new System.Windows.Forms.Button();
this.folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog();
this.progressBar1 = new System.Windows.Forms.ProgressBar();
this.backgroundWorker1 = new System.ComponentModel.BackgroundWorker();
this.Cancel = new System.Windows.Forms.Button();
this.Message = new System.Windows.Forms.TextBox();
this.tableLayoutPanel1.SuspendLayout();
this.SuspendLayout();
//
// tableLayoutPanel1
//
this.tableLayoutPanel1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tableLayoutPanel1.ColumnCount = 2;
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 74.65753F));
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25.34247F));
this.tableLayoutPanel1.Controls.Add(this.Backup, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.button2, 1, 0);
this.tableLayoutPanel1.Controls.Add(this.Destination, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.button3, 1, 1);
this.tableLayoutPanel1.Location = new System.Drawing.Point(13, 12);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
this.tableLayoutPanel1.RowCount = 2;
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F));
this.tableLayoutPanel1.Size = new System.Drawing.Size(432, 68);
this.tableLayoutPanel1.TabIndex = 0;
//
// Backup
//
this.Backup.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.Backup.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Backup.Location = new System.Drawing.Point(3, 37);
this.Backup.Name = "Backup";
this.Backup.Size = new System.Drawing.Size(316, 23);
this.Backup.TabIndex = 4;
//
// button2
//
this.button2.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.button2.Location = new System.Drawing.Point(325, 3);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(100, 28);
this.button2.TabIndex = 3;
this.button2.Text = "Destination...";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// Destination
//
this.Destination.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.Destination.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Destination.Location = new System.Drawing.Point(3, 3);
this.Destination.Name = "Destination";
this.Destination.Size = new System.Drawing.Size(316, 23);
this.Destination.TabIndex = 0;
//
// button3
//
this.button3.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.button3.Location = new System.Drawing.Point(325, 37);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(100, 28);
this.button3.TabIndex = 5;
this.button3.Text = "Backup...";
this.button3.UseVisualStyleBackColor = true;
this.button3.Click += new System.EventHandler(this.button3_Click);
//
// Verbose
//
this.Verbose.AutoSize = true;
this.Verbose.Location = new System.Drawing.Point(16, 86);
this.Verbose.Name = "Verbose";
this.Verbose.Size = new System.Drawing.Size(70, 17);
this.Verbose.TabIndex = 1;
this.Verbose.Text = "Verbose?";
this.Verbose.UseVisualStyleBackColor = true;
//
// button4
//
this.button4.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button4.Font = new System.Drawing.Font("Tahoma", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.button4.Location = new System.Drawing.Point(124, 86);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(188, 52);
this.button4.TabIndex = 3;
this.button4.Text = "Upgrade SubText!";
this.button4.UseVisualStyleBackColor = true;
this.button4.Click += new System.EventHandler(this.button4_Click);
//
// progressBar1
//
this.progressBar1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.progressBar1.Location = new System.Drawing.Point(14, 144);
this.progressBar1.Name = "progressBar1";
this.progressBar1.Size = new System.Drawing.Size(422, 23);
this.progressBar1.TabIndex = 5;
//
// backgroundWorker1
//
this.backgroundWorker1.WorkerReportsProgress = true;
this.backgroundWorker1.WorkerSupportsCancellation = true;
this.backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork);
this.backgroundWorker1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker1_RunWorkerCompleted);
this.backgroundWorker1.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.backgroundWorker1_ProgressChanged);
//
// Cancel
//
this.Cancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.Cancel.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Cancel.Location = new System.Drawing.Point(318, 86);
this.Cancel.Name = "Cancel";
this.Cancel.Size = new System.Drawing.Size(118, 52);
this.Cancel.TabIndex = 6;
this.Cancel.Text = "Cancel";
this.Cancel.UseVisualStyleBackColor = true;
this.Cancel.Click += new System.EventHandler(this.Cancel_Click);
//
// Message
//
this.Message.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.Message.Location = new System.Drawing.Point(13, 173);
this.Message.Multiline = true;
this.Message.Name = "Message";
this.Message.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.Message.Size = new System.Drawing.Size(422, 216);
this.Message.TabIndex = 6;
//
// UpgradeForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(447, 401);
this.Controls.Add(this.Message);
this.Controls.Add(this.Cancel);
this.Controls.Add(this.progressBar1);
this.Controls.Add(this.button4);
this.Controls.Add(this.Verbose);
this.Controls.Add(this.tableLayoutPanel1);
this.Font = new System.Drawing.Font("Tahoma", 7.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MinimumSize = new System.Drawing.Size(423, 300);
this.Name = "UpgradeForm";
this.Text = "SubText Upgrader";
this.Load += new System.EventHandler(this.UpgradeForm_Load);
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.TextBox Destination;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.CheckBox Verbose;
private System.Windows.Forms.TextBox Backup;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.Button button4;
private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog1;
private System.Windows.Forms.ProgressBar progressBar1;
private System.ComponentModel.BackgroundWorker backgroundWorker1;
private System.Windows.Forms.Button Cancel;
private System.Windows.Forms.TextBox Message;
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
namespace Site.Areas.Account.Models
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Caching;
using System.Web.Mvc;
using System.Web.WebPages;
using AccountManagement;
using Adxstudio.Xrm;
using Adxstudio.Xrm.AspNet.Cms;
using Adxstudio.Xrm.AspNet.Identity;
using Adxstudio.Xrm.Resources;
using Adxstudio.Xrm.Web;
using Adxstudio.Xrm.AspNet.Mvc;
using Adxstudio.Xrm.Configuration;
using Adxstudio.Xrm.Services;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Client;
using System.Data.Services.Client;
/// <summary>
/// Validating the Registration details
/// </summary>
public class LoginManager
{
/// <summary>
/// Initializes a new instance of the <see cref="LoginManager" /> class.
/// </summary>
/// <param name="httpContext">The context.</param>
/// <param name="controller">The controller.</param>
public LoginManager(HttpContextBase httpContext, Controller controller = null)
{
this.HttpContext = httpContext;
this.Controller = controller;
this.Error = new List<string>();
this.SetAuthSettings();
}
/// <summary>
/// Token Cache Key
/// </summary>
private const string TokenCacheKey = "EssGraphAuthToken";
/// <summary>
/// Token refresh retry count
/// </summary>
private const int TokenRetryCount = 3;
/// <summary>
/// Graph Cache total minutes
/// </summary>
private const int GraphCacheTtlMinutes = 5;
/// <summary>
/// Http Context base
/// </summary>
public HttpContextBase HttpContext { get; private set; }
/// <summary>
/// Login Controller
/// </summary>
public Controller Controller { get; private set; }
/// <summary>
/// Holds error messages retrieved while validations
/// </summary>
public List<string> Error { get; private set; }
/// <summary>
/// Holds Authentication settings required for the page
/// </summary>
public Adxstudio.Xrm.AspNet.Mvc.AuthenticationSettings AuthSettings { get; private set; }
/// <summary>
/// Application Invitation Manager local variable
/// </summary>
private ApplicationInvitationManager invitationManager;
/// <summary>
/// Application Invitation Manager
/// </summary>
public ApplicationInvitationManager InvitationManager
{
get
{
return this.invitationManager ?? this.HttpContext.GetOwinContext().Get<ApplicationInvitationManager>();
}
set
{
this.invitationManager = value;
}
}
/// <summary>
/// Application User Manager local variable
/// </summary>
private ApplicationUserManager userManager;
/// <summary>
/// Application User Manager
/// </summary>
public ApplicationUserManager UserManager
{
get
{
return this.userManager ?? this.HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
set
{
this.userManager = value;
}
}
/// <summary>
/// Application Website Manager local variable
/// </summary>
private ApplicationWebsiteManager websiteManager;
/// <summary>
/// Application Website Manager
/// </summary>
public ApplicationWebsiteManager WebsiteManager
{
get
{
return this.websiteManager ?? this.HttpContext.GetOwinContext().Get<ApplicationWebsiteManager>();
}
set
{
this.websiteManager = value;
}
}
/// <summary>
/// Application SignIn Manager local variable
/// </summary>
private ApplicationSignInManager signInManager;
/// <summary>
/// Application SignIn Manager
/// </summary>
public ApplicationSignInManager SignInManager
{
get
{
return this.signInManager ?? this.HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
}
set
{
this.signInManager = value;
}
}
/// <summary>
/// Identity Errors to get error descriptions
/// </summary>
public CrmIdentityErrorDescriber IdentityErrors { get; set; }
/// <summary>
/// Authentication Manager
/// </summary>
public IAuthenticationManager AuthenticationManager
{
get
{
return this.HttpContext.GetOwinContext().Authentication;
}
}
/// <summary>
/// Application Startup Settings Manager local variable
/// </summary>
private ApplicationStartupSettingsManager startupSettingsManager;
/// <summary>
/// Application Startup Settings Manager
/// </summary>
public ApplicationStartupSettingsManager StartupSettingsManager
{
get
{
return this.startupSettingsManager ?? this.HttpContext.GetOwinContext().Get<ApplicationStartupSettingsManager>();
}
private set
{
this.startupSettingsManager = value;
}
}
/// <summary>
/// Gets Graph Client
/// </summary>
/// <param name="loginInfo">login info</param>
/// <param name="graphRoot">graph root</param>
/// <param name="tenantId">tenant id</param>
/// <returns>retuns Active Directory Client</returns>
private Microsoft.Azure.ActiveDirectory.GraphClient.ActiveDirectoryClient GetGraphClient(ExternalLoginInfo loginInfo, string graphRoot, string tenantId)
{
var accessCodeClaim = loginInfo.ExternalIdentity.FindFirst("AccessCode");
var accessCode = accessCodeClaim?.Value;
return new Microsoft.Azure.ActiveDirectory.GraphClient.ActiveDirectoryClient(
new Uri(graphRoot + "/" + tenantId),
async () => await this.TokenManager.GetTokenAsync(accessCode));
}
/// <summary>
/// token Manager
/// </summary>
private Lazy<CrmTokenManager> tokenManager = new Lazy<CrmTokenManager>(CreateCrmTokenManager);
/// <summary>
/// Create Crm TokenManager
/// </summary>
/// <returns>Crm Token Manager</returns>
private static CrmTokenManager CreateCrmTokenManager()
{
return new CrmTokenManager(PortalSettings.Instance.Authentication, PortalSettings.Instance.Certificate, PortalSettings.Instance.Graph.RootUrl);
}
/// <summary>
/// Token Manager property
/// </summary>
private ICrmTokenManager TokenManager => this.tokenManager.Value;
/// <summary>
/// ToEmail: Gets the email for the graph user
/// </summary>
/// <param name="graphUser">graph user</param>
/// <returns>returns email id</returns>
public static string ToEmail(Microsoft.Azure.ActiveDirectory.GraphClient.IUser graphUser)
{
if (!string.IsNullOrWhiteSpace(graphUser.Mail))
{
return graphUser.Mail;
}
return graphUser.OtherMails != null ? graphUser.OtherMails.FirstOrDefault() : graphUser.UserPrincipalName;
}
/// <summary>
/// Apply Claims Mapping
/// </summary>
/// <param name="user">Application User</param>
/// <param name="loginInfo">Login Info</param>
/// <param name="claimsMapping">Claims mapping</param>
private static void ApplyClaimsMapping(ApplicationUser user, ExternalLoginInfo loginInfo, string claimsMapping)
{
try
{
if (user != null && !string.IsNullOrWhiteSpace(claimsMapping))
{
foreach (var pair in claimsMapping.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
var pieces = pair.Split('=');
var claimValue = loginInfo.ExternalIdentity.Claims.FirstOrDefault(c => c.Type == pieces[1]);
if (pieces.Length == 2
&& !user.Entity.Attributes.ContainsKey(pieces[0])
&& claimValue != null)
{
user.Entity.SetAttributeValue(pieces[0], claimValue.Value);
user.IsDirty = true;
}
}
}
}
catch (Exception ex)
{
WebEventSource.Log.GenericErrorException(ex);
}
}
/// <summary>
/// Get Auth Settings
/// </summary>
/// <returns>Return Auth Settings</returns>
private void SetAuthSettings()
{
var isLocal = this.HttpContext.IsDebuggingEnabled && this.HttpContext.Request.IsLocal;
var website = this.HttpContext.GetWebsite();
this.AuthSettings = website.GetAuthenticationSettings(isLocal);
}
/// <summary>
/// Add validation errors
/// </summary>
/// <param name="error">error identified</param>
public void AddErrors(IdentityError error)
{
this.AddErrors(IdentityResult.Failed(error.Description));
}
/// <summary>
/// Format error
/// </summary>
/// <param name="result">error description</param>
public void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
if (this.Controller != null)
{
this.Controller.ModelState.AddModelError(string.Empty, error);
}
else
{
this.Error.Add(string.Concat(this.Error.Count == 0 ? string.Empty : "<li>", error, this.Error.Count == 0 ? "\n" : "</li>\n"));
}
}
}
/// <summary>
/// Validate Email
/// </summary>
/// <param name="email">email value to validate</param>
/// <returns>returns true if validated</returns>
public bool ValidateEmail(string email)
{
try
{
MailAddress m = new MailAddress(email);
return true;
}
catch (FormatException)
{
return false;
}
}
/// <summary>
/// To ContactId
/// </summary>
/// <param name="invitation">Application Invitation</param>
/// <returns>returns Invitation entity reference</returns>
public EntityReference ToContactId(ApplicationInvitation invitation)
{
return invitation != null && invitation.InvitedContact != null
? new EntityReference(invitation.InvitedContact.LogicalName, invitation.InvitedContact.Id) { Name = invitation.Email }
: null;
}
/// <summary>
/// Find Invitation value by Code Async
/// </summary>
/// <param name="invitationCode">invitation code</param>
/// <returns>returns application invitation value</returns>
public async Task<ApplicationInvitation> FindInvitationByCodeAsync(string invitationCode)
{
if (string.IsNullOrWhiteSpace(invitationCode))
{
return null;
}
return await this.InvitationManager.FindByCodeAsync(invitationCode);
}
/// <summary>
/// Sign In Async
/// </summary>
/// <param name="user">user value</param>
/// <param name="returnUrl">return url</param>
/// <param name="isPersistent">is persistent value</param>
/// <param name="rememberBrowser">remeber browser value</param>
/// <returns>action result</returns>
public async Task<Enums.RedirectTo> SignInAsync(ApplicationUser user, string returnUrl, bool isPersistent = false, bool rememberBrowser = false)
{
await this.SignInManager.SignInAsync(user, isPersistent, rememberBrowser);
return await this.RedirectOnPostAuthenticate(returnUrl, null);
}
/// <summary>
/// Updates the current request language based on user preferences. If needed, updates the return URL as well.
/// </summary>
/// <param name="user">Application User that is currently being logged in.</param>
/// <param name="returnUrl">Return URL to be updated if needed.</param>
private void UpdateCurrentLanguage(ApplicationUser user, ref string returnUrl)
{
var languageContext = this.HttpContext.GetContextLanguageInfo();
if (languageContext.IsCrmMultiLanguageEnabled)
{
// At this point, ContextLanguageInfo.UserPreferredLanguage is not set, as the user is technically not yet logged in
// As this is a one-time operation, accessing adx_preferredlanguageid here directly instead of modifying CrmUser
var preferredLanguage = user.Entity.GetAttributeValue<EntityReference>("adx_preferredlanguageid");
if (preferredLanguage != null)
{
var websiteLangauges = languageContext.ActiveWebsiteLanguages.ToArray();
// Only consider published website languages for users
var newLanguage = languageContext.GetWebsiteLanguageByPortalLanguageId(preferredLanguage.Id, websiteLangauges, true);
if (newLanguage != null)
{
if (ContextLanguageInfo.DisplayLanguageCodeInUrl && !string.IsNullOrEmpty(returnUrl))
{
returnUrl = languageContext.FormatUrlWithLanguage(false, newLanguage.Code, returnUrl.AsAbsoluteUri(this.HttpContext.Request.Url));
}
}
}
}
}
/// <summary>
/// Redirect page on post Authentication
/// </summary>
/// <param name="returnUrl">return Url</param>
/// <param name="invitationCode">invitation code</param>
/// <param name="loginInfo">login information</param>
/// <param name="cancellationToken">cancellation token</param>
/// <returns>Action result</returns>
private async Task<Enums.RedirectTo> RedirectOnPostAuthenticate(string returnUrl, string invitationCode, ExternalLoginInfo loginInfo = null, CancellationToken cancellationToken = default(CancellationToken))
{
var identity = this.AuthenticationManager.AuthenticationResponseGrant.Identity;
var userId = identity.GetUserId();
var user = await this.UserManager.FindByIdAsync(userId);
if (user != null && loginInfo != null)
{
var options = await this.StartupSettingsManager.GetAuthenticationOptionsExtendedAsync(loginInfo, cancellationToken);
var claimsMapping = options?.LoginClaimsMapping;
if (!string.IsNullOrWhiteSpace(claimsMapping))
{
ApplyClaimsMapping(user, loginInfo, claimsMapping);
}
}
return await this.RedirectOnPostAuthenticate(user, returnUrl, invitationCode, loginInfo, cancellationToken);
}
/// <summary>
/// Post Authentication, redirect to appropirate page.
/// </summary>
/// <param name="user">Application user</param>
/// <param name="returnUrl">return url</param>
/// <param name="invitationCode">invitation code</param>
/// <param name="loginInfo">Login info</param>
/// <param name="cancellationToken">cancellation token</param>
/// <returns>return enum</returns>
private async Task<Enums.RedirectTo> RedirectOnPostAuthenticate(ApplicationUser user, string returnUrl, string invitationCode, ExternalLoginInfo loginInfo = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (user != null)
{
this.UpdateCurrentLanguage(user, ref returnUrl);
this.UpdateLastSuccessfulLogin(user);
await this.ApplyGraphUser(user, loginInfo, cancellationToken);
if (user.IsDirty)
{
await this.UserManager.UpdateAsync(user);
user.IsDirty = false;
}
IdentityResult redeemResult;
var invitation = await this.FindInvitationByCodeAsync(invitationCode);
if (invitation != null)
{
// Redeem invitation for the existing/registered contact
redeemResult = await this.InvitationManager.RedeemAsync(invitation, user, this.HttpContext.Request.UserHostAddress);
}
else if (!string.IsNullOrWhiteSpace(invitationCode))
{
redeemResult = IdentityResult.Failed(this.IdentityErrors.InvalidInvitationCode().Description);
}
else
{
redeemResult = IdentityResult.Success;
}
if (!redeemResult.Succeeded)
{
return Enums.RedirectTo.Redeem;
}
if (!this.DisplayModeIsActive() && (user.HasProfileAlert || user.ProfileModifiedOn == null))
{
return Enums.RedirectTo.Profile;
}
}
return Enums.RedirectTo.Local;
}
/// <summary>
/// Updates date and time of last successful login
/// </summary>
/// <param name="user">Application User that is currently being logged in.</param>
private void UpdateLastSuccessfulLogin(ApplicationUser user)
{
if (!this.AuthSettings.LoginTrackingEnabled)
{
return;
}
user.Entity.SetAttributeValue("adx_identity_lastsuccessfullogin", DateTime.UtcNow);
user.IsDirty = true;
}
/// <summary>
/// Apply Graph User
/// </summary>
/// <param name="user">Application user</param>
/// <param name="loginInfo">Login Info</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>async task</returns>
private async Task ApplyGraphUser(ApplicationUser user, ExternalLoginInfo loginInfo, CancellationToken cancellationToken)
{
if (loginInfo != null
&& this.StartupSettingsManager.AzureAdOptions != null
&& !string.IsNullOrWhiteSpace(this.StartupSettingsManager.AzureAdOptions.AuthenticationType)
&& !string.IsNullOrWhiteSpace(PortalSettings.Instance.Graph.RootUrl)
&& string.IsNullOrWhiteSpace(user.FirstName)
&& string.IsNullOrWhiteSpace(user.LastName)
&& string.IsNullOrWhiteSpace(user.Email))
{
var authenticationType = await this.StartupSettingsManager.GetAuthenticationTypeAsync(loginInfo, cancellationToken);
if (this.StartupSettingsManager.AzureAdOptions.AuthenticationType == authenticationType)
{
// update the contact using Graph
try
{
var graphUser = await this.GetGraphUser(loginInfo);
user.FirstName = graphUser.GivenName;
user.LastName = graphUser.Surname;
user.Email = ToEmail(graphUser);
user.IsDirty = true;
}
catch (Exception ex)
{
var guid = WebEventSource.Log.GenericErrorException(ex);
this.Error.Add(string.Format(ResourceManager.GetString("Generic_Error_Message"), guid));
}
}
}
}
/// <summary>
/// Check whether Display Mode Is Active or not
/// </summary>
/// <returns>returns true/false</returns>
private bool DisplayModeIsActive()
{
return DisplayModeProvider.Instance
.GetAvailableDisplayModesForContext(this.HttpContext, null)
.OfType<HostNameSettingDisplayMode>()
.Any();
}
/// <summary>
/// Gets Graph User
/// </summary>
/// <param name="loginInfo">Login information</param>
/// <returns>user value</returns>
private async Task<Microsoft.Azure.ActiveDirectory.GraphClient.IUser> GetGraphUser(ExternalLoginInfo loginInfo)
{
var userCacheKey = $"{loginInfo.Login.ProviderKey}_graphUser";
var userAuthResultCacheKey = $"{loginInfo.Login.ProviderKey}_userAuthResult";
// if the user's already gone through the Graph check, this will be set with the error that happened
if (this.HttpContext.Cache[userAuthResultCacheKey] != null)
{
return null;
}
// if the cache here is null, we haven't retrieved the Graph user yet. retrieve it
if (this.HttpContext.Cache[userCacheKey] == null)
{
return await this.GetGraphUser(loginInfo, userCacheKey, userAuthResultCacheKey);
}
return (Microsoft.Azure.ActiveDirectory.GraphClient.IUser)this.HttpContext.Cache[userCacheKey];
}
/// <summary>
/// Gets Graphical User
/// </summary>
/// <param name="loginInfo">login information</param>
/// <param name="userCacheKey">User Cache key value</param>
/// <param name="userAuthResultCacheKey">User authentication cache key</param>
/// <returns>User value</returns>
private async Task<Microsoft.Azure.ActiveDirectory.GraphClient.IUser> GetGraphUser(ExternalLoginInfo loginInfo, string userCacheKey, string userAuthResultCacheKey)
{
var client = this.GetGraphClient(loginInfo,
PortalSettings.Instance.Authentication.RootUrl,
PortalSettings.Instance.Authentication.TenantId);
Microsoft.Azure.ActiveDirectory.GraphClient.IUser user = null;
// retry tokenRetryCount times to retrieve the users. each time it fails, it will nullify the cache and try again
for (var x = 0; x < TokenRetryCount; x++)
{
try
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, $"Attempting to retrieve user from Graph with NameIdentifier {loginInfo.Login.ProviderKey}.");
// when we call this, the client will try to retrieve a token from GetAuthTokenTask()
user = await client.Me.ExecuteAsync();
// if we get here then everything is alright. stop looping
break;
}
catch (AggregateException ex)
{
var handled = false;
foreach (var innerEx in ex.InnerExceptions)
{
if (innerEx.InnerException == null)
{
break;
}
// if the exception can be cast to a DataServiceClientException
// NOTE: the version of Microsoft.Data.Services.Client MUST match the one Microsoft.Azure.ActiveDirectory.GraphClient uses (currently 5.6.4.0. 5.7.0.0 won't cast the exception correctly.)
var clientException = innerEx.InnerException as DataServiceClientException;
if (clientException?.StatusCode == (int)HttpStatusCode.Unauthorized)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Current GraphClient auth token didn't seem to work. Discarding...");
// the token didn't seem to work. throw away cached token to retrieve new one
this.HttpContext.Cache.Remove(TokenCacheKey);
handled = true;
}
}
if (!handled)
{
throw;
}
}
}
// if users is null here, we have a config problem where we can't get correct auth tokens despite repeated attempts
if (user == null)
{
this.OutputGraphError(Enums.AzureADGraphAuthResults.AuthConfigProblem, userAuthResultCacheKey, loginInfo);
return null;
}
// add cache entry for graph user object. it will expire in GraphCacheTtlMinutes minutes
HttpRuntime.Cache.Add(userCacheKey, user, null, DateTime.MaxValue, TimeSpan.FromMinutes(GraphCacheTtlMinutes), CacheItemPriority.Normal, null);
return user;
}
/// <summary>
/// Adds error occured while creating Graph user to trace
/// </summary>
/// <param name="result">Azure AD Graph Authentication Results</param>
/// <param name="userAuthResultCacheKey">User authentication result cache key</param>
/// <param name="loginInfo">Login information</param>
/// <returns>Azure AD graph authentication results</returns>
private Enums.AzureADGraphAuthResults OutputGraphError(Enums.AzureADGraphAuthResults result, string userAuthResultCacheKey, ExternalLoginInfo loginInfo)
{
// add cache entry for graph check result. it will expire in GraphCacheTtlMinutes minutes
HttpRuntime.Cache.Add(userAuthResultCacheKey, result, null, DateTime.MaxValue, TimeSpan.FromMinutes(GraphCacheTtlMinutes), CacheItemPriority.Normal, null);
switch (result)
{
case Enums.AzureADGraphAuthResults.UserNotFound:
ADXTrace.Instance.TraceError(TraceCategory.Application, $"Azure AD didn't have the user with the specified NameIdentifier: {loginInfo.Login.ProviderKey}");
return Enums.AzureADGraphAuthResults.UserNotFound;
case Enums.AzureADGraphAuthResults.UserHasNoEmail:
ADXTrace.Instance.TraceError(TraceCategory.Application, "UPN was not set on user.");
return Enums.AzureADGraphAuthResults.UserHasNoEmail;
case Enums.AzureADGraphAuthResults.NoValidLicense:
ADXTrace.Instance.TraceError(TraceCategory.Application, $"No valid license was found assigned to the user: {loginInfo.Login.ProviderKey}");
return Enums.AzureADGraphAuthResults.NoValidLicense;
case Enums.AzureADGraphAuthResults.AuthConfigProblem:
ADXTrace.Instance.TraceError(TraceCategory.Application, "There's a critical problem with retrieving Graph auth tokens.");
return Enums.AzureADGraphAuthResults.AuthConfigProblem;
}
ADXTrace.Instance.TraceError(TraceCategory.Application, $"An unknown graph error occurred. Passed through UserNotFound, UserHasNoEmail, and NoValidLicense. NameIdentifier: {loginInfo.Login.ProviderKey}");
return Enums.AzureADGraphAuthResults.UnknownError;
}
}
}
| |
using SIL.Windows.Forms.Widgets;
namespace TestApp
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this._keymanTestBox = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this._keyman6TestBox = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.button4 = new System.Windows.Forms.Button();
this.button5 = new System.Windows.Forms.Button();
this.button6 = new System.Windows.Forms.Button();
this.WritingSystemPickerButton = new System.Windows.Forms.Button();
this.button7 = new System.Windows.Forms.Button();
this._probWithExitButton = new System.Windows.Forms.Button();
this.button8 = new System.Windows.Forms.Button();
this.button9 = new System.Windows.Forms.Button();
this.betterLabel1 = new BetterLabel();
this.button10 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(34, 38);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(226, 23);
this.button1.TabIndex = 0;
this.button1.Text = "Problem Notification with once per session";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(34, 121);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(144, 23);
this.button2.TabIndex = 0;
this.button2.Text = "Yellow Box Dialog";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// button3
//
this.button3.Location = new System.Drawing.Point(34, 161);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(144, 23);
this.button3.TabIndex = 0;
this.button3.Text = "Green Box Dialog";
this.button3.UseVisualStyleBackColor = true;
this.button3.Click += new System.EventHandler(this.button3_Click);
//
// _keymanTestBox
//
this._keymanTestBox.Location = new System.Drawing.Point(155, 379);
this._keymanTestBox.Name = "_keymanTestBox";
this._keymanTestBox.Size = new System.Drawing.Size(100, 20);
this._keymanTestBox.TabIndex = 1;
this._keymanTestBox.Enter += new System.EventHandler(this._keyman7TestBox_Enter);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(23, 379);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(126, 13);
this.label1.TabIndex = 2;
this.label1.Text = "First Keyman 7 keyboard:";
//
// _keyman6TestBox
//
this._keyman6TestBox.Location = new System.Drawing.Point(155, 406);
this._keyman6TestBox.Name = "_keyman6TestBox";
this._keyman6TestBox.Size = new System.Drawing.Size(100, 20);
this._keyman6TestBox.TabIndex = 1;
this._keyman6TestBox.Enter += new System.EventHandler(this._keyman6TestBox_Enter);
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(23, 409);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(126, 13);
this.label2.TabIndex = 2;
this.label2.Text = "First Keyman 6 keyboard:";
//
// button4
//
this.button4.Location = new System.Drawing.Point(34, 226);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(226, 23);
this.button4.TabIndex = 0;
this.button4.Text = "NonFatal Exception with once per session policy";
this.button4.UseVisualStyleBackColor = true;
this.button4.Click += new System.EventHandler(this.OnExceptionWithPolicyClick);
//
// button5
//
this.button5.Location = new System.Drawing.Point(34, 265);
this.button5.Name = "button5";
this.button5.Size = new System.Drawing.Size(226, 23);
this.button5.TabIndex = 0;
this.button5.Text = "NonFatal MessageWithStack";
this.button5.UseVisualStyleBackColor = true;
this.button5.Click += new System.EventHandler(this.OnNonFatalMessageWithStack);
//
// button6
//
this.button6.Location = new System.Drawing.Point(34, 305);
this.button6.Name = "button6";
this.button6.Size = new System.Drawing.Size(226, 23);
this.button6.TabIndex = 0;
this.button6.Text = "Writing System Dialog";
this.button6.UseVisualStyleBackColor = true;
this.button6.Click += new System.EventHandler(this.button6_Click);
//
// WritingSystemPickerButton
//
this.WritingSystemPickerButton.Location = new System.Drawing.Point(34, 335);
this.WritingSystemPickerButton.Name = "WritingSystemPickerButton";
this.WritingSystemPickerButton.Size = new System.Drawing.Size(221, 23);
this.WritingSystemPickerButton.TabIndex = 3;
this.WritingSystemPickerButton.Text = "Writing System Picker";
this.WritingSystemPickerButton.UseVisualStyleBackColor = true;
this.WritingSystemPickerButton.Click += new System.EventHandler(this.WritingSystemPickerButton_Click);
//
// button7
//
this.button7.Location = new System.Drawing.Point(34, 67);
this.button7.Name = "button7";
this.button7.Size = new System.Drawing.Size(226, 23);
this.button7.TabIndex = 0;
this.button7.Text = "Really long Notification";
this.button7.UseVisualStyleBackColor = true;
this.button7.Click += new System.EventHandler(this.button7_Click);
//
// _probWithExitButton
//
this._probWithExitButton.Location = new System.Drawing.Point(266, 38);
this._probWithExitButton.Name = "_probWithExitButton";
this._probWithExitButton.Size = new System.Drawing.Size(226, 23);
this._probWithExitButton.TabIndex = 0;
this._probWithExitButton.Text = "Problem Notification with Alternate Button";
this._probWithExitButton.UseVisualStyleBackColor = true;
this._probWithExitButton.Click += new System.EventHandler(this._probWithExitButton_Click);
//
// button8
//
this.button8.Location = new System.Drawing.Point(216, 121);
this.button8.Name = "button8";
this.button8.Size = new System.Drawing.Size(226, 23);
this.button8.TabIndex = 4;
this.button8.Text = "Problem Notification with Details";
this.button8.UseVisualStyleBackColor = true;
this.button8.Click += new System.EventHandler(this.button8_Click);
//
// button9
//
this.button9.Location = new System.Drawing.Point(266, 67);
this.button9.Name = "button9";
this.button9.Size = new System.Drawing.Size(226, 23);
this.button9.TabIndex = 5;
this.button9.Text = "Notification tool long to fit screen height";
this.button9.UseVisualStyleBackColor = true;
this.button9.Click += new System.EventHandler(this.button9_Click);
//
// betterLabel1
//
this.betterLabel1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.betterLabel1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.betterLabel1.Enabled = false;
this.betterLabel1.Font = new System.Drawing.Font("Segoe UI", 9F);
this.betterLabel1.Location = new System.Drawing.Point(330, 362);
this.betterLabel1.Multiline = true;
this.betterLabel1.Name = "betterLabel1";
this.betterLabel1.ReadOnly = true;
this.betterLabel1.Size = new System.Drawing.Size(122, 49);
this.betterLabel1.TabIndex = 6;
this.betterLabel1.TabStop = false;
this.betterLabel1.Text = "This is a test of the emergency BetterLabel system.";
//
// button10
//
this.button10.Location = new System.Drawing.Point(216, 161);
this.button10.Name = "button10";
this.button10.Size = new System.Drawing.Size(144, 23);
this.button10.TabIndex = 7;
this.button10.Text = "Uncaught Exception";
this.button10.UseVisualStyleBackColor = true;
this.button10.Click += new System.EventHandler(this.button10_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(505, 480);
this.Controls.Add(this.button10);
this.Controls.Add(this.betterLabel1);
this.Controls.Add(this.button9);
this.Controls.Add(this.button8);
this.Controls.Add(this.WritingSystemPickerButton);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this._keyman6TestBox);
this.Controls.Add(this._keymanTestBox);
this.Controls.Add(this.button3);
this.Controls.Add(this.button2);
this.Controls.Add(this.button6);
this.Controls.Add(this.button5);
this.Controls.Add(this.button4);
this.Controls.Add(this.button7);
this.Controls.Add(this._probWithExitButton);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.TextBox _keymanTestBox;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox _keyman6TestBox;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button button4;
private System.Windows.Forms.Button button5;
private System.Windows.Forms.Button button6;
private System.Windows.Forms.Button WritingSystemPickerButton;
private System.Windows.Forms.Button button7;
private System.Windows.Forms.Button _probWithExitButton;
private System.Windows.Forms.Button button8;
private System.Windows.Forms.Button button9;
private BetterLabel betterLabel1;
private System.Windows.Forms.Button button10;
}
}
| |
using System;
using UnityEngine;
using UnityEngine.Rendering;
[ExecuteInEditMode]
[RequireComponent(typeof (Light))]
public partial class LightShafts : MonoBehaviour
{
public void Start()
{
CheckMinRequirements();
if (cameras == null || cameras.Length == 0)
{
cameras = new Camera[] {Camera.main};
}
UpdateCameraDepthMode();
}
private void UpdateShadowmap()
{
if (shadowmapMode == LightShaftsShadowmapMode.Static && !m_ShadowmapDirty)
{
return;
}
InitShadowmap();
if (m_ShadowmapCamera == null)
{
GameObject go = new GameObject("Depth Camera");
go.AddComponent(typeof (Camera));
m_ShadowmapCamera = go.GetComponent<Camera>();
go.hideFlags = HideFlags.HideAndDontSave;
m_ShadowmapCamera.enabled = false;
m_ShadowmapCamera.clearFlags = CameraClearFlags.SolidColor;
}
Transform cam = m_ShadowmapCamera.transform;
cam.position = transform.position;
cam.rotation = transform.rotation;
if (directional)
{
m_ShadowmapCamera.orthographic = true;
m_ShadowmapCamera.nearClipPlane = 0;
m_ShadowmapCamera.farClipPlane = size.z;
m_ShadowmapCamera.orthographicSize = size.y*0.5f;
m_ShadowmapCamera.aspect = size.x/size.y;
}
else
{
m_ShadowmapCamera.orthographic = false;
m_ShadowmapCamera.nearClipPlane = spotNear*GetComponent<Light>().range;
m_ShadowmapCamera.farClipPlane = spotFar*GetComponent<Light>().range;
m_ShadowmapCamera.fieldOfView = GetComponent<Light>().spotAngle;
m_ShadowmapCamera.aspect = 1.0f;
}
m_ShadowmapCamera.renderingPath = RenderingPath.Forward;
m_ShadowmapCamera.targetTexture = m_Shadowmap;
m_ShadowmapCamera.cullingMask = cullingMask;
m_ShadowmapCamera.backgroundColor = Color.white;
m_ShadowmapCamera.RenderWithShader(depthShader, "RenderType");
if (colored)
{
m_ShadowmapCamera.targetTexture = m_ColorFilter;
m_ShadowmapCamera.cullingMask = colorFilterMask;
m_ShadowmapCamera.backgroundColor = new Color(colorBalance, colorBalance, colorBalance);
m_ShadowmapCamera.RenderWithShader(colorFilterShader, "");
}
m_ShadowmapDirty = false;
}
private void RenderCoords(int width, int height, Vector4 lightPos)
{
SetFrustumRays(m_CoordMaterial);
RenderBuffer[] buffers = {m_CoordEpi.colorBuffer, m_DepthEpi.colorBuffer};
Graphics.SetRenderTarget(buffers, m_DepthEpi.depthBuffer);
m_CoordMaterial.SetVector("_LightPos", lightPos);
m_CoordMaterial.SetVector("_CoordTexDim",
new Vector4(m_CoordEpi.width, m_CoordEpi.height, 1.0f/m_CoordEpi.width,
1.0f/m_CoordEpi.height));
m_CoordMaterial.SetVector("_ScreenTexDim", new Vector4(width, height, 1.0f/width, 1.0f/height));
m_CoordMaterial.SetPass(0);
RenderQuad();
}
private void RenderInterpolationTexture(Vector4 lightPos)
{
Graphics.SetRenderTarget(m_InterpolationEpi.colorBuffer, m_RaymarchedLightEpi.depthBuffer);
if (!m_DX11Support &&
(Application.platform == RuntimePlatform.WindowsEditor ||
Application.platform == RuntimePlatform.WindowsPlayer ||
Application.platform == RuntimePlatform.WindowsWebPlayer))
{
// Looks like in dx9 stencil is not cleared properly with GL.Clear()
// Edit: fixed in 4.5, so this hack can be removed
m_DepthBreaksMaterial.SetPass(1);
RenderQuad();
}
else
{
GL.Clear(true, true, new Color(0, 0, 0, 1));
}
m_DepthBreaksMaterial.SetFloat("_InterpolationStep", interpolationStep);
m_DepthBreaksMaterial.SetFloat("_DepthThreshold", GetDepthThresholdAdjusted());
m_DepthBreaksMaterial.SetTexture("_DepthEpi", m_DepthEpi);
m_DepthBreaksMaterial.SetVector("_DepthEpiTexDim",
new Vector4(m_DepthEpi.width, m_DepthEpi.height, 1.0f/m_DepthEpi.width,
1.0f/m_DepthEpi.height));
m_DepthBreaksMaterial.SetPass(0);
RenderQuadSections(lightPos);
}
private void InterpolateAlongRays(Vector4 lightPos)
{
Graphics.SetRenderTarget(m_InterpolateAlongRaysEpi);
m_InterpolateAlongRaysMaterial.SetFloat("_InterpolationStep", interpolationStep);
m_InterpolateAlongRaysMaterial.SetTexture("_InterpolationEpi", m_InterpolationEpi);
m_InterpolateAlongRaysMaterial.SetTexture("_RaymarchedLightEpi", m_RaymarchedLightEpi);
m_InterpolateAlongRaysMaterial.SetVector("_RaymarchedLightEpiTexDim",
new Vector4(m_RaymarchedLightEpi.width, m_RaymarchedLightEpi.height,
1.0f/m_RaymarchedLightEpi.width,
1.0f/m_RaymarchedLightEpi.height));
m_InterpolateAlongRaysMaterial.SetPass(0);
RenderQuadSections(lightPos);
}
private void RenderSamplePositions(int width, int height, Vector4 lightPos)
{
InitRenderTexture(ref m_SamplePositions, width, height, 0, RenderTextureFormat.ARGB32, false);
// Unfortunately can't be a temporary RT if we want random write
m_SamplePositions.enableRandomWrite = true;
m_SamplePositions.filterMode = FilterMode.Point;
Graphics.SetRenderTarget(m_SamplePositions);
GL.Clear(false, true, new Color(0, 0, 0, 1));
Graphics.ClearRandomWriteTargets();
Graphics.SetRandomWriteTarget(1, m_SamplePositions);
//We need a render target with m_Coord dimensions, but reading and writing
//to the same target produces wrong read results, so using a dummy.
Graphics.SetRenderTarget(m_RaymarchedLightEpi);
m_SamplePositionsMaterial.SetVector("_OutputTexDim", new Vector4(width - 1, height - 1, 0, 0));
m_SamplePositionsMaterial.SetVector("_CoordTexDim", new Vector4(m_CoordEpi.width, m_CoordEpi.height, 0, 0));
m_SamplePositionsMaterial.SetTexture("_Coord", m_CoordEpi);
m_SamplePositionsMaterial.SetTexture("_InterpolationEpi", m_InterpolationEpi);
if (showInterpolatedSamples)
{
m_SamplePositionsMaterial.SetFloat("_SampleType", 1);
m_SamplePositionsMaterial.SetVector("_Color", new Vector4(0.4f, 0.4f, 0, 0));
m_SamplePositionsMaterial.SetPass(0);
RenderQuad();
}
m_SamplePositionsMaterial.SetFloat("_SampleType", 0);
m_SamplePositionsMaterial.SetVector("_Color", new Vector4(1, 0, 0, 0));
m_SamplePositionsMaterial.SetPass(0);
RenderQuadSections(lightPos);
Graphics.ClearRandomWriteTargets();
}
private void ShowSamples(int width, int height, Vector4 lightPos)
{
bool showSamples = this.showSamples && m_DX11Support;
SetKeyword(showSamples, "SHOW_SAMPLES_ON", "SHOW_SAMPLES_OFF");
if (showSamples)
{
RenderSamplePositions(width, height, lightPos);
}
m_FinalInterpolationMaterial.SetFloat("_ShowSamplesBackgroundFade", showSamplesBackgroundFade);
}
private void Raymarch(int width, int height, Vector4 lightPos)
{
SetFrustumRays(m_RaymarchMaterial);
int shadowmapWidth = m_Shadowmap.width;
int shadowmapHeight = m_Shadowmap.height;
Graphics.SetRenderTarget(m_RaymarchedLightEpi.colorBuffer, m_RaymarchedLightEpi.depthBuffer);
GL.Clear(false, true, new Color(0, 0, 0, 1));
m_RaymarchMaterial.SetTexture("_Coord", m_CoordEpi);
m_RaymarchMaterial.SetTexture("_InterpolationEpi", m_InterpolationEpi);
m_RaymarchMaterial.SetTexture("_Shadowmap", m_Shadowmap);
float brightness = colored ? brightnessColored/colorBalance : this.brightness;
brightness *= GetComponent<Light>().intensity;
m_RaymarchMaterial.SetFloat("_Brightness", brightness);
m_RaymarchMaterial.SetFloat("_Extinction", -extinction);
m_RaymarchMaterial.SetVector("_ShadowmapDim",
new Vector4(shadowmapWidth, shadowmapHeight, 1.0f/shadowmapWidth,
1.0f/shadowmapHeight));
m_RaymarchMaterial.SetVector("_ScreenTexDim", new Vector4(width, height, 1.0f/width, 1.0f/height));
m_RaymarchMaterial.SetVector("_LightColor", GetComponent<Light>().color.linear);
m_RaymarchMaterial.SetFloat("_MinDistFromCamera", minDistFromCamera);
SetKeyword(colored, "COLORED_ON", "COLORED_OFF");
m_RaymarchMaterial.SetTexture("_ColorFilter", m_ColorFilter);
SetKeyword(attenuationCurveOn, "ATTENUATION_CURVE_ON", "ATTENUATION_CURVE_OFF");
m_RaymarchMaterial.SetTexture("_AttenuationCurveTex", m_AttenuationCurveTex);
Texture cookie = GetComponent<Light>().cookie;
SetKeyword(cookie != null, "COOKIE_TEX_ON", "COOKIE_TEX_OFF");
if (cookie != null)
{
m_RaymarchMaterial.SetTexture("_Cookie", cookie);
}
m_RaymarchMaterial.SetPass(0);
RenderQuadSections(lightPos);
}
// This can be safely removed in Unity 4.5, along with the corresponding check in the shader.
private void FlipWorkaround()
{
// In Unity 4.3 and earlier _ProjectionParams.x doesn't get properly set when not rendering with a camera,
// so the shader will get confused whether to counter the flip or not.
// The incorrectly detected case is when rendering straight to the screen, so not in deferred and no image effects.
bool enable = Convert.ToSingle(Application.unityVersion.Substring(0, 3)) < 4.5f;
enable &= currentCamera.actualRenderingPath != RenderingPath.DeferredLighting;
if (enable)
{
// If you have any image effects not deriving from PostEffectsBase, include them in this check too.
// MonoBehaviour imageEffect = m_CurrentCamera.GetComponent<PostEffectsBase>() as MonoBehaviour;
// enable &= imageEffect == null || !imageEffect.enabled;
}
SetKeyword(enable, "FLIP_WORKAROUND_ON", "FLIP_WORKAROUND_OFF");
}
public void OnRenderObject()
{
currentCamera = Camera.current;
if (!m_MinRequirements || !CheckCamera() || !IsVisible())
{
return;
}
// Prepare
RenderBuffer depthBuffer = Graphics.activeDepthBuffer;
RenderBuffer colorBuffer = Graphics.activeColorBuffer;
InitResources();
Vector4 lightPos = GetLightViewportPos();
bool lightOnScreen = lightPos.x >= -1 && lightPos.x <= 1 && lightPos.y >= -1 && lightPos.y <= 1;
SetKeyword(lightOnScreen, "LIGHT_ON_SCREEN", "LIGHT_OFF_SCREEN");
int width = Screen.width;
int height = Screen.height;
// Render the buffers, raymarch, interpolate along rays
UpdateShadowmap();
SetKeyword(directional, "DIRECTIONAL_SHAFTS", "SPOT_SHAFTS");
RenderCoords(width, height, lightPos);
RenderInterpolationTexture(lightPos);
Raymarch(width, height, lightPos);
InterpolateAlongRays(lightPos);
ShowSamples(width, height, lightPos);
// Final interpolation and blending onto the screen
FlipWorkaround();
SetFrustumRays(m_FinalInterpolationMaterial);
m_FinalInterpolationMaterial.SetTexture("_InterpolationEpi", m_InterpolationEpi);
m_FinalInterpolationMaterial.SetTexture("_DepthEpi", m_DepthEpi);
m_FinalInterpolationMaterial.SetTexture("_Shadowmap", m_Shadowmap);
m_FinalInterpolationMaterial.SetTexture("_Coord", m_CoordEpi);
m_FinalInterpolationMaterial.SetTexture("_SamplePositions", m_SamplePositions);
m_FinalInterpolationMaterial.SetTexture("_RaymarchedLight", m_InterpolateAlongRaysEpi);
m_FinalInterpolationMaterial.SetVector("_CoordTexDim",
new Vector4(m_CoordEpi.width, m_CoordEpi.height, 1.0f/m_CoordEpi.width,
1.0f/m_CoordEpi.height));
m_FinalInterpolationMaterial.SetVector("_ScreenTexDim", new Vector4(width, height, 1.0f/width, 1.0f/height));
m_FinalInterpolationMaterial.SetVector("_LightPos", lightPos);
m_FinalInterpolationMaterial.SetFloat("_DepthThreshold", GetDepthThresholdAdjusted());
bool renderAsQuad = directional || IntersectsNearPlane();
m_FinalInterpolationMaterial.SetFloat("_ZTest",
(float)
(renderAsQuad
? CompareFunction.Always
: CompareFunction.Less));
SetKeyword(renderAsQuad, "QUAD_SHAFTS", "FRUSTUM_SHAFTS");
Graphics.SetRenderTarget(colorBuffer, depthBuffer);
m_FinalInterpolationMaterial.SetPass(0);
if (renderAsQuad)
{
RenderQuad();
}
else
{
RenderSpotFrustum();
}
ReleaseResources();
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Nini.Config;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Server.Base;
using OpenSim.Server.Handlers.Base;
using OpenSim.Services.Interfaces;
using System;
using System.Collections;
using System.Net;
using System.Reflection;
namespace OpenSim.Server.Handlers.Hypergrid
{
public class InstantMessageServerConnector : ServiceConnector
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private IInstantMessage m_IMService;
public InstantMessageServerConnector(IConfigSource config, IHttpServer server) :
this(config, server, (IInstantMessageSimConnector)null)
{
}
public InstantMessageServerConnector(IConfigSource config, IHttpServer server, string configName) :
this(config, server)
{
}
public InstantMessageServerConnector(IConfigSource config, IHttpServer server, IInstantMessageSimConnector simConnector) :
base(config, server, String.Empty)
{
IConfig gridConfig = config.Configs["HGInstantMessageService"];
if (gridConfig != null)
{
string serviceDll = gridConfig.GetString("LocalServiceModule", string.Empty);
Object[] args = new Object[] { config, simConnector };
m_IMService = ServerUtils.LoadPlugin<IInstantMessage>(serviceDll, args);
}
if (m_IMService == null)
throw new Exception("InstantMessage server connector cannot proceed because of missing service");
server.AddXmlRPCHandler("grid_instant_message", ProcessInstantMessage, false);
}
public IInstantMessage GetService()
{
return m_IMService;
}
protected virtual XmlRpcResponse ProcessInstantMessage(XmlRpcRequest request, IPEndPoint remoteClient)
{
bool successful = false;
try
{
// various rational defaults
UUID fromAgentID = UUID.Zero;
UUID toAgentID = UUID.Zero;
UUID imSessionID = UUID.Zero;
uint timestamp = 0;
string fromAgentName = "";
string message = "";
byte dialog = (byte)0;
bool fromGroup = false;
byte offline = (byte)0;
uint ParentEstateID = 0;
Vector3 Position = Vector3.Zero;
UUID RegionID = UUID.Zero;
byte[] binaryBucket = new byte[0];
float pos_x = 0;
float pos_y = 0;
float pos_z = 0;
//m_log.Info("Processing IM");
Hashtable requestData = (Hashtable)request.Params[0];
// Check if it's got all the data
if (requestData.ContainsKey("from_agent_id")
&& requestData.ContainsKey("to_agent_id") && requestData.ContainsKey("im_session_id")
&& requestData.ContainsKey("timestamp") && requestData.ContainsKey("from_agent_name")
&& requestData.ContainsKey("message") && requestData.ContainsKey("dialog")
&& requestData.ContainsKey("from_group")
&& requestData.ContainsKey("offline") && requestData.ContainsKey("parent_estate_id")
&& requestData.ContainsKey("position_x") && requestData.ContainsKey("position_y")
&& requestData.ContainsKey("position_z") && requestData.ContainsKey("region_id")
&& requestData.ContainsKey("binary_bucket"))
{
// Do the easy way of validating the UUIDs
UUID.TryParse((string)requestData["from_agent_id"], out fromAgentID);
UUID.TryParse((string)requestData["to_agent_id"], out toAgentID);
UUID.TryParse((string)requestData["im_session_id"], out imSessionID);
UUID.TryParse((string)requestData["region_id"], out RegionID);
try
{
timestamp = (uint)Convert.ToInt32((string)requestData["timestamp"]);
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
fromAgentName = (string)requestData["from_agent_name"];
message = (string)requestData["message"];
if (message == null)
message = string.Empty;
// Bytes don't transfer well over XMLRPC, so, we Base64 Encode them.
string requestData1 = (string)requestData["dialog"];
if (string.IsNullOrEmpty(requestData1))
{
dialog = 0;
}
else
{
byte[] dialogdata = Convert.FromBase64String(requestData1);
try
{
dialog = dialogdata[0];
}
catch
{
dialog = 0;
}
}
if ((string)requestData["from_group"] == "TRUE")
fromGroup = true;
string requestData2 = (string)requestData["offline"];
if (String.IsNullOrEmpty(requestData2))
{
offline = 0;
}
else
{
byte[] offlinedata = Convert.FromBase64String(requestData2);
try
{
offline = offlinedata[0];
}
catch
{
offline = 0;
}
}
try
{
ParentEstateID = (uint)Convert.ToInt32((string)requestData["parent_estate_id"]);
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
float.TryParse((string)requestData["position_x"], out pos_x);
float.TryParse((string)requestData["position_y"], out pos_y);
float.TryParse((string)requestData["position_z"], out pos_z);
Position = new Vector3(pos_x, pos_y, pos_z);
string requestData3 = (string)requestData["binary_bucket"];
if (string.IsNullOrEmpty(requestData3))
{
binaryBucket = new byte[0];
}
else
{
binaryBucket = Convert.FromBase64String(requestData3);
}
// Create a New GridInstantMessageObject the the data
GridInstantMessage gim = new GridInstantMessage();
gim.fromAgentID = fromAgentID.Guid;
gim.fromAgentName = fromAgentName;
gim.fromGroup = fromGroup;
gim.imSessionID = imSessionID.Guid;
gim.RegionID = RegionID.Guid;
gim.timestamp = timestamp;
gim.toAgentID = toAgentID.Guid;
gim.message = message;
gim.dialog = dialog;
gim.offline = offline;
gim.ParentEstateID = ParentEstateID;
gim.Position = Position;
gim.binaryBucket = binaryBucket;
successful = m_IMService.IncomingInstantMessage(gim);
}
}
catch (Exception e)
{
m_log.Error("[INSTANT MESSAGE]: Caught unexpected exception:", e);
successful = false;
}
//Send response back to region calling if it was successful
// calling region uses this to know when to look up a user's location again.
XmlRpcResponse resp = new XmlRpcResponse();
Hashtable respdata = new Hashtable();
if (successful)
respdata["success"] = "TRUE";
else
respdata["success"] = "FALSE";
resp.Value = respdata;
return resp;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using NUnit.Framework;
using SIL.Data;
using SIL.DictionaryServices.Model;
using SIL.IO;
using SIL.TestUtilities;
using SIL.WritingSystems;
namespace SIL.DictionaryServices.Tests
{
[TestFixture]
public class LiftLexEntryRepositoryCachingTests
{
private TemporaryFolder _tempfolder;
private TempFile _tempFile;
private LiftLexEntryRepository _repository;
[SetUp]
public void Setup()
{
_tempfolder = new TemporaryFolder("LiftLexEntryRepositoryCachingTests");
_tempFile = _tempfolder.GetNewTempFile(true);
_repository = new LiftLexEntryRepository(_tempFile.Path);
}
[TearDown]
public void Teardown()
{
_repository.Dispose();
_tempFile.Dispose();
_tempfolder.Dispose();
}
[Test]
public void GetAllEntriesSortedByHeadWord_CreateItemAfterFirstCall_EntryIsReturnedAndSortedInResultSet()
{
CreateEntryWithLexicalFormBeforeFirstQuery("de", "word 1");
_repository.GetAllEntriesSortedByHeadword(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont));
_repository.CreateItem();
ResultSet<LexEntry> results = _repository.GetAllEntriesSortedByHeadword(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont));
Assert.AreEqual(2, results.Count);
Assert.AreEqual(null, results[0]["Form"]);
Assert.AreEqual("word 1", results[1]["Form"]);
}
private LexEntry CreateEntryWithLexicalFormBeforeFirstQuery(string writingSystem, string lexicalForm)
{
LexEntry entryBeforeFirstQuery = _repository.CreateItem();
entryBeforeFirstQuery.LexicalForm.SetAlternative(writingSystem, lexicalForm);
_repository.SaveItem(entryBeforeFirstQuery);
return entryBeforeFirstQuery;
}
private static WritingSystemDefinition WritingSystemDefinitionForTest(string languageIso, Font font)
{
return new WritingSystemDefinition
{
Language = languageIso,
DefaultFont = new FontDefinition(font.Name),
DefaultFontSize = font.Size,
DefaultCollation = new IcuRulesCollationDefinition("standard")
};
}
[Test]
public void GetAllEntriesSortedByHeadWord_ModifyAndSaveAfterFirstCall_EntryIsModifiedAndSortedInResultSet()
{
LexEntry entryBeforeFirstQuery = CreateEntryWithLexicalFormBeforeFirstQuery("de", "word 0");
_repository.GetAllEntriesSortedByHeadword(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont));
entryBeforeFirstQuery.LexicalForm.SetAlternative("de", "word 1");
_repository.SaveItem(entryBeforeFirstQuery);
ResultSet<LexEntry> results = _repository.GetAllEntriesSortedByHeadword(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont));
Assert.AreEqual(1, results.Count);
Assert.AreEqual("word 1", results[0]["Form"]);
}
[Test]
public void GetAllEntriesSortedByHeadWord_ModifyAndSaveMultipleAfterFirstCall_EntriesModifiedAndSortedInResultSet()
{
List<LexEntry> entriesToModify = new List<LexEntry>();
entriesToModify.Add(CreateEntryWithLexicalFormBeforeFirstQuery("de", "word 0"));
entriesToModify.Add(CreateEntryWithLexicalFormBeforeFirstQuery("de", "word 1"));
_repository.GetAllEntriesSortedByHeadword(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont));
entriesToModify[0].LexicalForm["de"] = "word 3";
entriesToModify[1].LexicalForm["de"] = "word 2";
_repository.SaveItems(entriesToModify);
ResultSet<LexEntry> results = _repository.GetAllEntriesSortedByHeadword(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont));
Assert.AreEqual(2, results.Count);
Assert.AreEqual("word 2", results[0]["Form"]);
Assert.AreEqual("word 3", results[1]["Form"]);
}
[Test]
public void GetAllEntriesSortedByHeadWord_DeleteAfterFirstCall_EntryIsDeletedInResultSet()
{
LexEntry entrytoBeDeleted = CreateEntryWithLexicalFormBeforeFirstQuery("de", "word 0");
_repository.GetAllEntriesSortedByHeadword(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont));
_repository.DeleteItem(entrytoBeDeleted);
ResultSet<LexEntry> results = _repository.GetAllEntriesSortedByHeadword(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont));
Assert.AreEqual(0, results.Count);
}
[Test]
public void GetAllEntriesSortedByHeadWord_DeleteByIdAfterFirstCall_EntryIsDeletedInResultSet()
{
LexEntry entrytoBeDeleted = CreateEntryWithLexicalFormBeforeFirstQuery("de", "word 0");
_repository.GetAllEntriesSortedByHeadword(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont));
_repository.DeleteItem(_repository.GetId(entrytoBeDeleted));
ResultSet<LexEntry> results = _repository.GetAllEntriesSortedByHeadword(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont));
Assert.AreEqual(0, results.Count);
}
[Test]
public void GetAllEntriesSortedByHeadWord_DeleteAllItemsAfterFirstCall_EntryIsDeletedInResultSet()
{
CreateEntryWithLexicalFormBeforeFirstQuery("de", "word 0");
_repository.GetAllEntriesSortedByHeadword(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont));
_repository.DeleteAllItems();
ResultSet<LexEntry> results = _repository.GetAllEntriesSortedByHeadword(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont));
Assert.AreEqual(0, results.Count);
}
[Test]
public void GetAllEntriesSortedByLexicalForm_CreateItemAfterFirstCall_EntryIsReturnedAndSortedInResultSet()
{
CreateEntryWithLexicalFormBeforeFirstQuery("de", "word 1");
_repository.GetAllEntriesSortedByLexicalFormOrAlternative(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont));
_repository.CreateItem();
ResultSet<LexEntry> results = _repository.GetAllEntriesSortedByLexicalFormOrAlternative(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont));
Assert.AreEqual(2, results.Count);
Assert.AreEqual(null, results[0]["Form"]);
Assert.AreEqual("word 1", results[1]["Form"]);
}
[Test]
public void GetAllEntriesSortedByLexicalForm_ModifyAndSaveAfterFirstCall_EntryIsModifiedAndSortedInResultSet()
{
LexEntry entryBeforeFirstQuery = CreateEntryWithLexicalFormBeforeFirstQuery("de", "word 0");
_repository.GetAllEntriesSortedByLexicalFormOrAlternative(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont));
entryBeforeFirstQuery.LexicalForm.SetAlternative("de", "word 1");
_repository.SaveItem(entryBeforeFirstQuery);
ResultSet<LexEntry> results = _repository.GetAllEntriesSortedByLexicalFormOrAlternative(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont));
Assert.AreEqual(1, results.Count);
Assert.AreEqual("word 1", results[0]["Form"]);
}
[Test]
public void GetAllEntriesSortedByLexicalForm_ModifyAndSaveMultipleAfterFirstCall_EntriesModifiedAndSortedInResultSet()
{
var entriesToModify = new List<LexEntry>();
entriesToModify.Add(CreateEntryWithLexicalFormBeforeFirstQuery("de", "word 0"));
entriesToModify.Add(CreateEntryWithLexicalFormBeforeFirstQuery("de", "word 1"));
_repository.GetAllEntriesSortedByLexicalFormOrAlternative(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont));
entriesToModify[0].LexicalForm["de"] = "word 3";
entriesToModify[1].LexicalForm["de"] = "word 2";
_repository.SaveItems(entriesToModify);
ResultSet<LexEntry> results = _repository.GetAllEntriesSortedByLexicalFormOrAlternative(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont));
Assert.AreEqual(2, results.Count);
Assert.AreEqual("word 2", results[0]["Form"]);
Assert.AreEqual("word 3", results[1]["Form"]);
}
[Test]
public void GetAllEntriesSortedByLexicalForm_DeleteAfterFirstCall_EntryIsDeletedInResultSet()
{
LexEntry entrytoBeDeleted = CreateEntryWithLexicalFormBeforeFirstQuery("de", "word 0");
_repository.GetAllEntriesSortedByLexicalFormOrAlternative(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont));
_repository.DeleteItem(entrytoBeDeleted);
ResultSet<LexEntry> results = _repository.GetAllEntriesSortedByLexicalFormOrAlternative(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont));
Assert.AreEqual(0, results.Count);
}
[Test]
public void GetAllEntriesSortedByLexicalForm_DeleteByIdAfterFirstCall_EntryIsDeletedInResultSet()
{
LexEntry entrytoBeDeleted = CreateEntryWithLexicalFormBeforeFirstQuery("de", "word 0");
_repository.GetAllEntriesSortedByLexicalFormOrAlternative(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont));
_repository.DeleteItem(_repository.GetId(entrytoBeDeleted));
ResultSet<LexEntry> results = _repository.GetAllEntriesSortedByLexicalFormOrAlternative(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont));
Assert.AreEqual(0, results.Count);
}
[Test]
public void GetAllEntriesSortedByLexicalForm_DeleteAllItemsAfterFirstCall_EntryIsDeletedInResultSet()
{
CreateEntryWithLexicalFormBeforeFirstQuery("de", "word 0");
_repository.GetAllEntriesSortedByLexicalFormOrAlternative(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont));
_repository.DeleteAllItems();
ResultSet<LexEntry> results = _repository.GetAllEntriesSortedByLexicalFormOrAlternative(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont));
Assert.AreEqual(0, results.Count);
}
[Test]
public void NotifyThatLexEntryHasBeenUpdated_LexEntry_CachesAreUpdated()
{
LexEntry entryToUpdate = _repository.CreateItem();
entryToUpdate.LexicalForm.SetAlternative("de", "word 0");
_repository.SaveItem(entryToUpdate);
CreateCaches();
entryToUpdate.LexicalForm.SetAlternative("de", "word 1");
_repository.NotifyThatLexEntryHasBeenUpdated(entryToUpdate);
var writingSystemToMatch = WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont);
ResultSet<LexEntry> headWordResults = _repository.GetAllEntriesSortedByHeadword(writingSystemToMatch);
ResultSet<LexEntry> lexicalFormResults = _repository.GetAllEntriesSortedByLexicalFormOrAlternative(writingSystemToMatch);
Assert.AreEqual("word 1", headWordResults[0]["Form"]);
Assert.AreEqual("word 1", lexicalFormResults[0]["Form"]);
}
private void CreateCaches()
{
var writingSystemToMatch = WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont);
_repository.GetAllEntriesSortedByHeadword(writingSystemToMatch);
_repository.GetAllEntriesSortedByLexicalFormOrAlternative(writingSystemToMatch);
//_repository.GetAllEntriesSortedByDefinitionOrGloss(writingSystemToMatch);
}
[Test]
public void NotifyThatLexEntryHasBeenUpdated_Null_Throws()
{
Assert.Throws<ArgumentNullException>(() =>
_repository.NotifyThatLexEntryHasBeenUpdated(null));
}
[Test]
public void NotifyThatLexEntryHasBeenUpdated_LexEntryDoesNotExistInRepository_Throws()
{
var entryToUpdate = new LexEntry();
Assert.Throws<ArgumentOutOfRangeException>(() =>
_repository.NotifyThatLexEntryHasBeenUpdated(entryToUpdate));
}
private LexEntry CreateEntryWithDefinitionBeforeFirstQuery(string writingSystem, string lexicalForm)
{
LexEntry entryBeforeFirstQuery = _repository.CreateItem();
entryBeforeFirstQuery.Senses.Add(new LexSense());
entryBeforeFirstQuery.Senses[0].Definition.SetAlternative(writingSystem, lexicalForm);
_repository.SaveItem(entryBeforeFirstQuery);
return entryBeforeFirstQuery;
}
[Test]
public void GetAllEntriesSortedByDefinition_CreateItemAfterFirstCall_EntryIsReturnedAndSortedInResultSet()
{
CreateEntryWithDefinitionBeforeFirstQuery("de", "word 1");
_repository.GetAllEntriesSortedByDefinitionOrGloss(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont));
CreateEntryWithDefinitionBeforeFirstQuery("de", "word 2");
ResultSet<LexEntry> results = _repository.GetAllEntriesSortedByDefinitionOrGloss(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont));
Assert.AreEqual(2, results.Count);
Assert.AreEqual("word 1", results[0]["Form"]);
Assert.AreEqual("word 2", results[1]["Form"]);
}
[Test]
public void GetAllEntriesSortedByDefinition_ModifyAndSaveAfterFirstCall_EntryIsModifiedAndSortedInResultSet()
{
LexEntry entryBeforeFirstQuery = CreateEntryWithDefinitionBeforeFirstQuery("de", "word 0");
_repository.GetAllEntriesSortedByDefinitionOrGloss(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont));
entryBeforeFirstQuery.Senses[0].Definition.SetAlternative("de", "word 1");
_repository.SaveItem(entryBeforeFirstQuery);
ResultSet<LexEntry> results = _repository.GetAllEntriesSortedByDefinitionOrGloss(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont));
Assert.AreEqual(1, results.Count);
Assert.AreEqual("word 1", results[0]["Form"]);
}
[Test]
public void GetAllEntriesSortedByDefinition_ModifyAndSaveMultipleAfterFirstCall_EntriesModifiedAndSortedInResultSet()
{
List<LexEntry> entriesToModify = new List<LexEntry>();
entriesToModify.Add(CreateEntryWithDefinitionBeforeFirstQuery("de", "word 0"));
entriesToModify.Add(CreateEntryWithDefinitionBeforeFirstQuery("de", "word 1"));
_repository.GetAllEntriesSortedByDefinitionOrGloss(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont));
entriesToModify[0].Senses[0].Definition["de"] = "word 3";
entriesToModify[1].Senses[0].Definition["de"] = "word 2";
_repository.SaveItems(entriesToModify);
ResultSet<LexEntry> results = _repository.GetAllEntriesSortedByDefinitionOrGloss(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont));
Assert.AreEqual(2, results.Count);
Assert.AreEqual("word 2", results[0]["Form"]);
Assert.AreEqual("word 3", results[1]["Form"]);
}
[Test]
public void GetAllEntriesSortedByDefinition_DeleteAfterFirstCall_EntryIsDeletedInResultSet()
{
LexEntry entrytoBeDeleted = CreateEntryWithDefinitionBeforeFirstQuery("de", "word 0");
_repository.GetAllEntriesSortedByDefinitionOrGloss(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont));
_repository.DeleteItem(entrytoBeDeleted);
ResultSet<LexEntry> results = _repository.GetAllEntriesSortedByDefinitionOrGloss(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont));
Assert.AreEqual(0, results.Count);
}
[Test]
public void GetAllEntriesSortedByDefinition_DeleteByIdAfterFirstCall_EntryIsDeletedInResultSet()
{
LexEntry entrytoBeDeleted = CreateEntryWithDefinitionBeforeFirstQuery("de", "word 0");
_repository.GetAllEntriesSortedByDefinitionOrGloss(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont));
_repository.DeleteItem(_repository.GetId(entrytoBeDeleted));
ResultSet<LexEntry> results = _repository.GetAllEntriesSortedByDefinitionOrGloss(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont));
Assert.AreEqual(0, results.Count);
}
[Test]
public void GetAllEntriesSortedByDefinition_DeleteAllItemsAfterFirstCall_EntryIsDeletedInResultSet()
{
CreateEntryWithDefinitionBeforeFirstQuery("de", "word 0");
_repository.GetAllEntriesSortedByDefinitionOrGloss(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont));
_repository.DeleteAllItems();
ResultSet<LexEntry> results = _repository.GetAllEntriesSortedByDefinitionOrGloss(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont));
Assert.AreEqual(0, results.Count);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// QuerySettings.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
namespace System.Linq.Parallel
{
/// <summary>
/// This type contains query execution options specified by the user.
/// QuerySettings are used as follows:
/// - in the query construction phase, some settings may be uninitialized.
/// - at the start of the query opening phase, the WithDefaults method
/// is used to initialize all uninitialized settings.
/// - in the rest of the query opening phase, we assume that all settings
/// have been initialized.
/// </summary>
internal struct QuerySettings
{
private TaskScheduler _taskScheduler;
private int? _degreeOfParallelism;
private CancellationState _cancellationState;
private ParallelExecutionMode? _executionMode;
private ParallelMergeOptions? _mergeOptions;
private int _queryId;
internal CancellationState CancellationState
{
get { return _cancellationState; }
set
{
_cancellationState = value;
Debug.Assert(_cancellationState != null);
}
}
// The task manager on which to execute the query.
internal TaskScheduler TaskScheduler
{
get { return _taskScheduler; }
set { _taskScheduler = value; }
}
// The number of parallel tasks to utilize.
internal int? DegreeOfParallelism
{
get { return _degreeOfParallelism; }
set { _degreeOfParallelism = value; }
}
// The mode in which to execute this query.
internal ParallelExecutionMode? ExecutionMode
{
get { return _executionMode; }
set { _executionMode = value; }
}
internal ParallelMergeOptions? MergeOptions
{
get { return _mergeOptions; }
set { _mergeOptions = value; }
}
internal int QueryId
{
get
{
return _queryId;
}
}
//-----------------------------------------------------------------------------------
// Constructs a new settings structure.
//
internal QuerySettings(TaskScheduler taskScheduler, int? degreeOfParallelism,
CancellationToken externalCancellationToken, ParallelExecutionMode? executionMode,
ParallelMergeOptions? mergeOptions)
{
_taskScheduler = taskScheduler;
_degreeOfParallelism = degreeOfParallelism;
_cancellationState = new CancellationState(externalCancellationToken);
_executionMode = executionMode;
_mergeOptions = mergeOptions;
_queryId = -1;
Debug.Assert(_cancellationState != null);
}
//-----------------------------------------------------------------------------------
// Combines two sets of options.
//
internal QuerySettings Merge(QuerySettings settings2)
{
if (this.TaskScheduler != null && settings2.TaskScheduler != null)
{
throw new InvalidOperationException(SR.ParallelQuery_DuplicateTaskScheduler);
}
if (this.DegreeOfParallelism != null && settings2.DegreeOfParallelism != null)
{
throw new InvalidOperationException(SR.ParallelQuery_DuplicateDOP);
}
if (this.CancellationState.ExternalCancellationToken.CanBeCanceled && settings2.CancellationState.ExternalCancellationToken.CanBeCanceled)
{
throw new InvalidOperationException(SR.ParallelQuery_DuplicateWithCancellation);
}
if (this.ExecutionMode != null && settings2.ExecutionMode != null)
{
throw new InvalidOperationException(SR.ParallelQuery_DuplicateExecutionMode);
}
if (this.MergeOptions != null && settings2.MergeOptions != null)
{
throw new InvalidOperationException(SR.ParallelQuery_DuplicateMergeOptions);
}
TaskScheduler tm = (this.TaskScheduler == null) ? settings2.TaskScheduler : this.TaskScheduler;
int? dop = this.DegreeOfParallelism.HasValue ? this.DegreeOfParallelism : settings2.DegreeOfParallelism;
CancellationToken externalCancellationToken = (this.CancellationState.ExternalCancellationToken.CanBeCanceled) ? this.CancellationState.ExternalCancellationToken : settings2.CancellationState.ExternalCancellationToken;
ParallelExecutionMode? executionMode = this.ExecutionMode.HasValue ? this.ExecutionMode : settings2.ExecutionMode;
ParallelMergeOptions? mergeOptions = this.MergeOptions.HasValue ? this.MergeOptions : settings2.MergeOptions;
return new QuerySettings(tm, dop, externalCancellationToken, executionMode, mergeOptions);
}
internal QuerySettings WithPerExecutionSettings()
{
return WithPerExecutionSettings(new CancellationTokenSource(), new Shared<bool>(false));
}
internal QuerySettings WithPerExecutionSettings(CancellationTokenSource topLevelCancellationTokenSource, Shared<bool> topLevelDisposedFlag)
{
//Initialize a new QuerySettings structure and copy in the current settings.
//Note: this has the very important effect of newing a fresh CancellationSettings,
// and _not_ copying in the current internalCancellationSource or topLevelDisposedFlag which should not be
// propagated to internal query executions. (This affects SelectMany execution)
// The fresh toplevel parameters are used instead.
QuerySettings settings = new QuerySettings(TaskScheduler, DegreeOfParallelism, CancellationState.ExternalCancellationToken, ExecutionMode, MergeOptions);
Debug.Assert(topLevelCancellationTokenSource != null, "There should always be a top-level cancellation signal specified.");
settings.CancellationState.InternalCancellationTokenSource = topLevelCancellationTokenSource;
//Merge internal and external tokens to form the combined token
settings.CancellationState.MergedCancellationTokenSource =
CancellationTokenSource.CreateLinkedTokenSource(settings.CancellationState.InternalCancellationTokenSource.Token, settings.CancellationState.ExternalCancellationToken);
// and copy in the topLevelDisposedFlag
settings.CancellationState.TopLevelDisposedFlag = topLevelDisposedFlag;
Debug.Assert(settings.CancellationState.InternalCancellationTokenSource != null);
Debug.Assert(settings.CancellationState.MergedCancellationToken.CanBeCanceled);
Debug.Assert(settings.CancellationState.TopLevelDisposedFlag != null);
// Finally, assign a query Id to the settings
settings._queryId = PlinqEtwProvider.NextQueryId();
return settings;
}
//-----------------------------------------------------------------------------------
// Copies the settings, replacing unspecified settings with defaults.
//
internal QuerySettings WithDefaults()
{
QuerySettings settings = this;
if (settings.TaskScheduler == null)
{
settings.TaskScheduler = TaskScheduler.Default;
}
if (settings.DegreeOfParallelism == null)
{
settings.DegreeOfParallelism = Scheduling.GetDefaultDegreeOfParallelism();
}
if (settings.ExecutionMode == null)
{
settings.ExecutionMode = ParallelExecutionMode.Default;
}
if (settings.MergeOptions == null)
{
settings.MergeOptions = ParallelMergeOptions.Default;
}
if (settings.MergeOptions == ParallelMergeOptions.Default)
{
settings.MergeOptions = ParallelMergeOptions.AutoBuffered;
}
Debug.Assert(settings.TaskScheduler != null);
Debug.Assert(settings.DegreeOfParallelism.HasValue);
Debug.Assert(settings.DegreeOfParallelism.Value >= 1 && settings.DegreeOfParallelism <= Scheduling.MAX_SUPPORTED_DOP);
Debug.Assert(settings.ExecutionMode != null);
Debug.Assert(settings.MergeOptions != null);
Debug.Assert(settings.MergeOptions != ParallelMergeOptions.Default);
return settings;
}
// Returns the default settings
internal static QuerySettings Empty
{
get { return new QuerySettings(null, null, new CancellationToken(), null, null); }
}
// Cleanup internal state once the entire query is complete.
// (this should not be performed after a 'premature-query' completes as the state should live
// uninterrupted for the duration of the full query.)
public void CleanStateAtQueryEnd()
{
_cancellationState.MergedCancellationTokenSource.Dispose();
}
}
}
| |
// 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 XorUInt32()
{
var test = new SimpleBinaryOpTest__XorUInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__XorUInt32
{
private const int VectorSize = 16;
private const int ElementCount = VectorSize / sizeof(UInt32);
private static UInt32[] _data1 = new UInt32[ElementCount];
private static UInt32[] _data2 = new UInt32[ElementCount];
private static Vector128<UInt32> _clsVar1;
private static Vector128<UInt32> _clsVar2;
private Vector128<UInt32> _fld1;
private Vector128<UInt32> _fld2;
private SimpleBinaryOpTest__DataTable<UInt32> _dataTable;
static SimpleBinaryOpTest__XorUInt32()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); _data2[i] = (uint)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__XorUInt32()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); _data2[i] = (uint)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); _data2[i] = (uint)(random.Next(0, int.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<UInt32>(_data1, _data2, new UInt32[ElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.Xor(
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.Xor(
Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.Xor(
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Xor), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Xor), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Xor), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.Xor(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr);
var result = Sse2.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr));
var result = Sse2.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr));
var result = Sse2.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__XorUInt32();
var result = Sse2.Xor(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.Xor(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<UInt32> left, Vector128<UInt32> right, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[ElementCount];
UInt32[] inArray2 = new UInt32[ElementCount];
UInt32[] outArray = new UInt32[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[ElementCount];
UInt32[] inArray2 = new UInt32[ElementCount];
UInt32[] outArray = new UInt32[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt32[] left, UInt32[] right, UInt32[] result, [CallerMemberName] string method = "")
{
if ((uint)(left[0] ^ right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if ((uint)(left[i] ^ right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.Xor)}<UInt32>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using AspNetCoreSpa.Server.Entities;
using AspNetCoreSpa.Server.Extensions;
using AspNetCoreSpa.Server.Services.Abstract;
using AspNetCoreSpa.Server.ViewModels.AccountViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Logging;
namespace AspNetCoreSpa.Server.Controllers.api
{
[Authorize]
[Route("api/[controller]")]
public class AccountController : BaseController
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IEmailSender _emailSender;
private readonly ISmsSender _smsSender;
private readonly ILogger _logger;
public AccountController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IEmailSender emailSender,
ISmsSender smsSender,
ILoggerFactory loggerFactory)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
_smsSender = smsSender;
_logger = loggerFactory.CreateLogger<AccountController>();
}
[HttpPost("login")]
[AllowAnonymous]
public async Task<IActionResult> Login([FromBody]LoginViewModel model)
{
if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
var user = await _userManager.FindByEmailAsync(model.Email);
var roles = await _userManager.GetRolesAsync(user);
_logger.LogInformation(1, "User logged in.");
return AppUtils.SignIn(user, roles);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(SendCode), new { RememberMe = model.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning(2, "User account locked out.");
return BadRequest("Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return BadRequest(ModelState.GetModelErrors());
}
}
return BadRequest(new string[] { "Unable to login" });
}
[HttpPost("register")]
[AllowAnonymous]
public async Task<IActionResult> Register([FromBody]RegisterViewModel model, string returnUrl = null)
{
if (ModelState.IsValid)
{
var currentUser = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(currentUser, model.Password);
if (result.Succeeded)
{
// Add to roles
var roleAddResult = await _userManager.AddToRoleAsync(currentUser, "User");
if (roleAddResult.Succeeded)
{
var code = await _userManager.GenerateEmailConfirmationTokenAsync(currentUser);
var host = Request.Scheme + "://" + Request.Host;
var callbackUrl = host + "?userId=" + currentUser.Id + "&emailConfirmCode=" + code;
var confirmationLink = "<a class='btn-primary' href=\"" + callbackUrl + "\">Confirm email address</a>";
_logger.LogInformation(3, "User created a new account with password.");
//await _emailSender.SendEmailAsync(MailType.Register, new EmailModel { To = model.Email }, confirmationLink);
return Json(new { });
}
}
AddErrors(result);
}
else
{
return BadRequest(ModelState.GetModelErrors());
}
// If we got this far, something failed, redisplay form
return BadRequest(ModelState.GetModelErrors());
}
[HttpPost("logout")]
public async Task<IActionResult> LogOff()
{
await _signInManager.SignOutAsync();
_logger.LogInformation(4, "User logged out.");
return Ok();
}
[HttpGet("ExternalLogin")]
[AllowAnonymous]
public IActionResult ExternalLogin(string provider, string returnUrl = null)
{
// Request a redirect to the external login provider.
var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl });
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
return Challenge(properties, provider);
}
[HttpGet("ExternalLoginCallback")]
[AllowAnonymous]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
{
if (remoteError != null)
{
return Render(ExternalLoginStatus.Error);
}
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return Render(ExternalLoginStatus.Invalid);
}
// Sign in the user with this external login provider if the user already has a login.
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);
if (result.Succeeded)
{
_logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider);
return Render(ExternalLoginStatus.Ok); // Everything Ok, login user
}
if (result.RequiresTwoFactor)
{
return Render(ExternalLoginStatus.TwoFactor);
}
if (result.IsLockedOut)
{
return Render(ExternalLoginStatus.Lockout);
}
else
{
// If the user does not have an account, then ask the user to create an account.
// ViewData["ReturnUrl"] = returnUrl;
// ViewData["LoginProvider"] = info.LoginProvider;
// var email = info.Principal.FindFirstValue(ClaimTypes.Email);
// return RedirectToAction("Index", "Home", new ExternalLoginCreateAccountViewModel { Email = email });
return Render(ExternalLoginStatus.CreateAccount);
}
}
[HttpPost("ExternalLoginCreateAccount")]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ExternalLoginCreateAccount([FromBody]ExternalLoginConfirmationViewModel model, string returnUrl = null)
{
if (ModelState.IsValid)
{
// Get the information about the user from the external login provider
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return BadRequest("External login information cannot be accessed, try again.");
}
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user);
if (result.Succeeded)
{
result = await _userManager.AddLoginAsync(user, info);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider);
return Ok(); // Everything ok
}
}
ModelState.AddModelError("", "Email already exists");
}
return BadRequest(ModelState.GetModelErrors());
}
[HttpGet("ConfirmEmail")]
[AllowAnonymous]
public async Task<IActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return View("Error");
}
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
return View("Error");
}
var result = await _userManager.ConfirmEmailAsync(user, code);
return View(result.Succeeded ? "ConfirmEmail" : "Error");
}
[HttpGet("ForgotPassword")]
[AllowAnonymous]
public IActionResult ForgotPassword()
{
return View();
}
[HttpPost("ForgotPassword")]
[AllowAnonymous]
public async Task<IActionResult> ForgotPassword([FromBody]ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var currentUser = await _userManager.FindByNameAsync(model.Email);
if (currentUser == null || !(await _userManager.IsEmailConfirmedAsync(currentUser)))
{
// Don't reveal that the user does not exist or is not confirmed
return View("ForgotPasswordConfirmation");
}
// For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
var code = await _userManager.GeneratePasswordResetTokenAsync(currentUser);
var host = Request.Scheme + "://" + Request.Host;
var callbackUrl = host + "?userId=" + currentUser.Id + "&passwordResetCode=" + code;
var confirmationLink = "<a class='btn-primary' href=\"" + callbackUrl + "\">Reset your password</a>";
await _emailSender.SendEmailAsync(MailType.ForgetPassword, new EmailModel { To = model.Email }, confirmationLink);
return Json(new { });
}
// If we got this far, something failed, redisplay form
return BadRequest(model);
}
[HttpPost("resetpassword")]
[AllowAnonymous]
public async Task<IActionResult> ResetPassword([FromBody]ResetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await _userManager.FindByNameAsync(model.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return Ok("Reset confirmed");
}
var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password);
if (result.Succeeded)
{
return Ok("Reset confirmed"); ;
}
AddErrors(result);
return BadRequest(ModelState.GetModelErrors());
}
[HttpGet("SendCode")]
[AllowAnonymous]
public async Task<ActionResult> SendCode(string returnUrl = null, bool rememberMe = false)
{
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return BadRequest("Error");
}
var userFactors = await _userManager.GetValidTwoFactorProvidersAsync(user);
var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
[HttpPost("SendCode")]
[AllowAnonymous]
public async Task<IActionResult> SendCode([FromBody]SendCodeViewModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState.GetModelErrors());
}
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return BadRequest("Error");
}
// Generate the token and send it
var code = await _userManager.GenerateTwoFactorTokenAsync(user, model.SelectedProvider);
if (string.IsNullOrWhiteSpace(code))
{
return BadRequest("Error");
}
var message = "Your security code is: " + code;
if (model.SelectedProvider == "Email")
{
await _emailSender.SendEmailAsync(MailType.SecurityCode, new EmailModel { }, null);
//await _emailSender.SendEmailAsync(Email, await _userManager.GetEmailAsync(user), "Security Code", message);
}
else if (model.SelectedProvider == "Phone")
{
await _smsSender.SendSmsAsync(await _userManager.GetPhoneNumberAsync(user), message);
}
return RedirectToAction(nameof(VerifyCode), new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
}
[HttpGet("VerifyCode")]
[AllowAnonymous]
public async Task<IActionResult> VerifyCode(string provider, bool rememberMe, string returnUrl = null)
{
// Require that the user has already logged in via username/password or external login
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return BadRequest("Error");
}
return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
[HttpPost("VerifyCode")]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyCode(VerifyCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// The following code protects for brute force attacks against the two factor codes.
// If a user enters incorrect codes for a specified amount of time then the user account
// will be locked out for a specified amount of time.
var result = await _signInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser);
if (result.Succeeded)
{
return RedirectToLocal(model.ReturnUrl);
}
if (result.IsLockedOut)
{
_logger.LogWarning(7, "User account locked out.");
return View("Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid code.");
return View(model);
}
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
private Task<ApplicationUser> GetCurrentUserAsync()
{
return _userManager.GetUserAsync(HttpContext.User);
}
private IActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction(nameof(HomeController.Index), "Home");
}
}
private IActionResult Render(ExternalLoginStatus status)
{
return RedirectToAction("Index", "Home", new { externalLoginStatus = (int)status });
}
#endregion
}
}
| |
/*
* Copyright (c) 2006-2016, openmetaverse.co
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.co nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Text;
using System.Collections.Generic;
using OpenMetaverse.Packets;
namespace OpenMetaverse
{
/// <summary>
///
/// </summary>
[Flags]
public enum FriendRights : int
{
/// <summary>The avatar has no rights</summary>
None = 0,
/// <summary>The avatar can see the online status of the target avatar</summary>
CanSeeOnline = 1,
/// <summary>The avatar can see the location of the target avatar on the map</summary>
CanSeeOnMap = 2,
/// <summary>The avatar can modify the ojects of the target avatar </summary>
CanModifyObjects = 4
}
/// <summary>
/// This class holds information about an avatar in the friends list. There are two ways
/// to interface to this class. The first is through the set of boolean properties. This is the typical
/// way clients of this class will use it. The second interface is through two bitflag properties,
/// TheirFriendsRights and MyFriendsRights
/// </summary>
public class FriendInfo
{
private UUID m_id;
private string m_name;
private bool m_isOnline;
private bool m_canSeeMeOnline;
private bool m_canSeeMeOnMap;
private bool m_canModifyMyObjects;
private bool m_canSeeThemOnline;
private bool m_canSeeThemOnMap;
private bool m_canModifyTheirObjects;
#region Properties
/// <summary>
/// System ID of the avatar
/// </summary>
public UUID UUID { get { return m_id; } }
/// <summary>
/// full name of the avatar
/// </summary>
public string Name
{
get { return m_name; }
set { m_name = value; }
}
/// <summary>
/// True if the avatar is online
/// </summary>
public bool IsOnline
{
get { return m_isOnline; }
set { m_isOnline = value; }
}
/// <summary>
/// True if the friend can see if I am online
/// </summary>
public bool CanSeeMeOnline
{
get { return m_canSeeMeOnline; }
set
{
m_canSeeMeOnline = value;
// if I can't see them online, then I can't see them on the map
if (!m_canSeeMeOnline)
m_canSeeMeOnMap = false;
}
}
/// <summary>
/// True if the friend can see me on the map
/// </summary>
public bool CanSeeMeOnMap
{
get { return m_canSeeMeOnMap; }
set
{
// if I can't see them online, then I can't see them on the map
if (m_canSeeMeOnline)
m_canSeeMeOnMap = value;
}
}
/// <summary>
/// True if the freind can modify my objects
/// </summary>
public bool CanModifyMyObjects
{
get { return m_canModifyMyObjects; }
set { m_canModifyMyObjects = value; }
}
/// <summary>
/// True if I can see if my friend is online
/// </summary>
public bool CanSeeThemOnline { get { return m_canSeeThemOnline; } }
/// <summary>
/// True if I can see if my friend is on the map
/// </summary>
public bool CanSeeThemOnMap { get { return m_canSeeThemOnMap; } }
/// <summary>
/// True if I can modify my friend's objects
/// </summary>
public bool CanModifyTheirObjects { get { return m_canModifyTheirObjects; } }
/// <summary>
/// My friend's rights represented as bitmapped flags
/// </summary>
public FriendRights TheirFriendRights
{
get
{
FriendRights results = FriendRights.None;
if (m_canSeeMeOnline)
results |= FriendRights.CanSeeOnline;
if (m_canSeeMeOnMap)
results |= FriendRights.CanSeeOnMap;
if (m_canModifyMyObjects)
results |= FriendRights.CanModifyObjects;
return results;
}
set
{
m_canSeeMeOnline = (value & FriendRights.CanSeeOnline) != 0;
m_canSeeMeOnMap = (value & FriendRights.CanSeeOnMap) != 0;
m_canModifyMyObjects = (value & FriendRights.CanModifyObjects) != 0;
}
}
/// <summary>
/// My rights represented as bitmapped flags
/// </summary>
public FriendRights MyFriendRights
{
get
{
FriendRights results = FriendRights.None;
if (m_canSeeThemOnline)
results |= FriendRights.CanSeeOnline;
if (m_canSeeThemOnMap)
results |= FriendRights.CanSeeOnMap;
if (m_canModifyTheirObjects)
results |= FriendRights.CanModifyObjects;
return results;
}
set
{
m_canSeeThemOnline = (value & FriendRights.CanSeeOnline) != 0;
m_canSeeThemOnMap = (value & FriendRights.CanSeeOnMap) != 0;
m_canModifyTheirObjects = (value & FriendRights.CanModifyObjects) != 0;
}
}
#endregion Properties
/// <summary>
/// Used internally when building the initial list of friends at login time
/// </summary>
/// <param name="id">System ID of the avatar being prepesented</param>
/// <param name="theirRights">Rights the friend has to see you online and to modify your objects</param>
/// <param name="myRights">Rights you have to see your friend online and to modify their objects</param>
internal FriendInfo(UUID id, FriendRights theirRights, FriendRights myRights)
{
m_id = id;
m_canSeeMeOnline = (theirRights & FriendRights.CanSeeOnline) != 0;
m_canSeeMeOnMap = (theirRights & FriendRights.CanSeeOnMap) != 0;
m_canModifyMyObjects = (theirRights & FriendRights.CanModifyObjects) != 0;
m_canSeeThemOnline = (myRights & FriendRights.CanSeeOnline) != 0;
m_canSeeThemOnMap = (myRights & FriendRights.CanSeeOnMap) != 0;
m_canModifyTheirObjects = (myRights & FriendRights.CanModifyObjects) != 0;
}
/// <summary>
/// FriendInfo represented as a string
/// </summary>
/// <returns>A string reprentation of both my rights and my friends rights</returns>
public override string ToString()
{
if (!String.IsNullOrEmpty(m_name))
return String.Format("{0} (Their Rights: {1}, My Rights: {2})", m_name, TheirFriendRights,
MyFriendRights);
else
return String.Format("{0} (Their Rights: {1}, My Rights: {2})", m_id, TheirFriendRights,
MyFriendRights);
}
}
/// <summary>
/// This class is used to add and remove avatars from your friends list and to manage their permission.
/// </summary>
public class FriendsManager
{
#region Delegates
/// <summary>The event subscribers. null if no subcribers</summary>
private EventHandler<FriendInfoEventArgs> m_FriendOnline;
/// <summary>Raises the FriendOnline event</summary>
/// <param name="e">A FriendInfoEventArgs object containing the
/// data returned from the data server</param>
protected virtual void OnFriendOnline(FriendInfoEventArgs e)
{
EventHandler<FriendInfoEventArgs> handler = m_FriendOnline;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_FriendOnlineLock = new object();
/// <summary>Raised when the simulator sends notification one of the members in our friends list comes online</summary>
public event EventHandler<FriendInfoEventArgs> FriendOnline
{
add { lock (m_FriendOnlineLock) { m_FriendOnline += value; } }
remove { lock (m_FriendOnlineLock) { m_FriendOnline -= value; } }
}
/// <summary>The event subscribers. null if no subcribers</summary>
private EventHandler<FriendInfoEventArgs> m_FriendOffline;
/// <summary>Raises the FriendOffline event</summary>
/// <param name="e">A FriendInfoEventArgs object containing the
/// data returned from the data server</param>
protected virtual void OnFriendOffline(FriendInfoEventArgs e)
{
EventHandler<FriendInfoEventArgs> handler = m_FriendOffline;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_FriendOfflineLock = new object();
/// <summary>Raised when the simulator sends notification one of the members in our friends list goes offline</summary>
public event EventHandler<FriendInfoEventArgs> FriendOffline
{
add { lock (m_FriendOfflineLock) { m_FriendOffline += value; } }
remove { lock (m_FriendOfflineLock) { m_FriendOffline -= value; } }
}
/// <summary>The event subscribers. null if no subcribers</summary>
private EventHandler<FriendInfoEventArgs> m_FriendRights;
/// <summary>Raises the FriendRightsUpdate event</summary>
/// <param name="e">A FriendInfoEventArgs object containing the
/// data returned from the data server</param>
protected virtual void OnFriendRights(FriendInfoEventArgs e)
{
EventHandler<FriendInfoEventArgs> handler = m_FriendRights;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_FriendRightsLock = new object();
/// <summary>Raised when the simulator sends notification one of the members in our friends list grants or revokes permissions</summary>
public event EventHandler<FriendInfoEventArgs> FriendRightsUpdate
{
add { lock (m_FriendRightsLock) { m_FriendRights += value; } }
remove { lock (m_FriendRightsLock) { m_FriendRights -= value; } }
}
/// <summary>The event subscribers. null if no subcribers</summary>
private EventHandler<FriendNamesEventArgs> m_FriendNames;
/// <summary>Raises the FriendNames event</summary>
/// <param name="e">A FriendNamesEventArgs object containing the
/// data returned from the data server</param>
protected virtual void OnFriendNames(FriendNamesEventArgs e)
{
EventHandler<FriendNamesEventArgs> handler = m_FriendNames;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_FriendNamesLock = new object();
/// <summary>Raised when the simulator sends us the names on our friends list</summary>
public event EventHandler<FriendNamesEventArgs> FriendNames
{
add { lock (m_FriendNamesLock) { m_FriendNames += value; } }
remove { lock (m_FriendNamesLock) { m_FriendNames -= value; } }
}
/// <summary>The event subscribers. null if no subcribers</summary>
private EventHandler<FriendshipOfferedEventArgs> m_FriendshipOffered;
/// <summary>Raises the FriendshipOffered event</summary>
/// <param name="e">A FriendshipOfferedEventArgs object containing the
/// data returned from the data server</param>
protected virtual void OnFriendshipOffered(FriendshipOfferedEventArgs e)
{
EventHandler<FriendshipOfferedEventArgs> handler = m_FriendshipOffered;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_FriendshipOfferedLock = new object();
/// <summary>Raised when the simulator sends notification another agent is offering us friendship</summary>
public event EventHandler<FriendshipOfferedEventArgs> FriendshipOffered
{
add { lock (m_FriendshipOfferedLock) { m_FriendshipOffered += value; } }
remove { lock (m_FriendshipOfferedLock) { m_FriendshipOffered -= value; } }
}
/// <summary>The event subscribers. null if no subcribers</summary>
private EventHandler<FriendshipResponseEventArgs> m_FriendshipResponse;
/// <summary>Raises the FriendshipResponse event</summary>
/// <param name="e">A FriendshipResponseEventArgs object containing the
/// data returned from the data server</param>
protected virtual void OnFriendshipResponse(FriendshipResponseEventArgs e)
{
EventHandler<FriendshipResponseEventArgs> handler = m_FriendshipResponse;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_FriendshipResponseLock = new object();
/// <summary>Raised when a request we sent to friend another agent is accepted or declined</summary>
public event EventHandler<FriendshipResponseEventArgs> FriendshipResponse
{
add { lock (m_FriendshipResponseLock) { m_FriendshipResponse += value; } }
remove { lock (m_FriendshipResponseLock) { m_FriendshipResponse -= value; } }
}
/// <summary>The event subscribers. null if no subcribers</summary>
private EventHandler<FriendshipTerminatedEventArgs> m_FriendshipTerminated;
/// <summary>Raises the FriendshipTerminated event</summary>
/// <param name="e">A FriendshipTerminatedEventArgs object containing the
/// data returned from the data server</param>
protected virtual void OnFriendshipTerminated(FriendshipTerminatedEventArgs e)
{
EventHandler<FriendshipTerminatedEventArgs> handler = m_FriendshipTerminated;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_FriendshipTerminatedLock = new object();
/// <summary>Raised when the simulator sends notification one of the members in our friends list has terminated
/// our friendship</summary>
public event EventHandler<FriendshipTerminatedEventArgs> FriendshipTerminated
{
add { lock (m_FriendshipTerminatedLock) { m_FriendshipTerminated += value; } }
remove { lock (m_FriendshipTerminatedLock) { m_FriendshipTerminated -= value; } }
}
/// <summary>The event subscribers. null if no subcribers</summary>
private EventHandler<FriendFoundReplyEventArgs> m_FriendFound;
/// <summary>Raises the FriendFoundReply event</summary>
/// <param name="e">A FriendFoundReplyEventArgs object containing the
/// data returned from the data server</param>
protected virtual void OnFriendFoundReply(FriendFoundReplyEventArgs e)
{
EventHandler<FriendFoundReplyEventArgs> handler = m_FriendFound;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_FriendFoundLock = new object();
/// <summary>Raised when the simulator sends the location of a friend we have
/// requested map location info for</summary>
public event EventHandler<FriendFoundReplyEventArgs> FriendFoundReply
{
add { lock (m_FriendFoundLock) { m_FriendFound += value; } }
remove { lock (m_FriendFoundLock) { m_FriendFound -= value; } }
}
#endregion Delegates
#region Events
#endregion Events
private GridClient Client;
/// <summary>
/// A dictionary of key/value pairs containing known friends of this avatar.
///
/// The Key is the <seealso cref="UUID"/> of the friend, the value is a <seealso cref="FriendInfo"/>
/// object that contains detailed information including permissions you have and have given to the friend
/// </summary>
public InternalDictionary<UUID, FriendInfo> FriendList = new InternalDictionary<UUID, FriendInfo>();
/// <summary>
/// A Dictionary of key/value pairs containing current pending frienship offers.
///
/// The key is the <seealso cref="UUID"/> of the avatar making the request,
/// the value is the <seealso cref="UUID"/> of the request which is used to accept
/// or decline the friendship offer
/// </summary>
public InternalDictionary<UUID, UUID> FriendRequests = new InternalDictionary<UUID, UUID>();
/// <summary>
/// Internal constructor
/// </summary>
/// <param name="client">A reference to the GridClient Object</param>
internal FriendsManager(GridClient client)
{
Client = client;
Client.Network.LoginProgress += Network_OnConnect;
Client.Avatars.UUIDNameReply += new EventHandler<UUIDNameReplyEventArgs>(Avatars_OnAvatarNames);
Client.Self.IM += Self_IM;
Client.Network.RegisterCallback(PacketType.OnlineNotification, OnlineNotificationHandler);
Client.Network.RegisterCallback(PacketType.OfflineNotification, OfflineNotificationHandler);
Client.Network.RegisterCallback(PacketType.ChangeUserRights, ChangeUserRightsHandler);
Client.Network.RegisterCallback(PacketType.TerminateFriendship, TerminateFriendshipHandler);
Client.Network.RegisterCallback(PacketType.FindAgent, OnFindAgentReplyHandler);
Client.Network.RegisterLoginResponseCallback(new NetworkManager.LoginResponseCallback(Network_OnLoginResponse),
new string[] { "buddy-list" });
}
#region Public Methods
/// <summary>
/// Accept a friendship request
/// </summary>
/// <param name="fromAgentID">agentID of avatatar to form friendship with</param>
/// <param name="imSessionID">imSessionID of the friendship request message</param>
public void AcceptFriendship(UUID fromAgentID, UUID imSessionID)
{
UUID callingCardFolder = Client.Inventory.FindFolderForType(AssetType.CallingCard);
AcceptFriendshipPacket request = new AcceptFriendshipPacket();
request.AgentData.AgentID = Client.Self.AgentID;
request.AgentData.SessionID = Client.Self.SessionID;
request.TransactionBlock.TransactionID = imSessionID;
request.FolderData = new AcceptFriendshipPacket.FolderDataBlock[1];
request.FolderData[0] = new AcceptFriendshipPacket.FolderDataBlock();
request.FolderData[0].FolderID = callingCardFolder;
Client.Network.SendPacket(request);
FriendInfo friend = new FriendInfo(fromAgentID, FriendRights.CanSeeOnline,
FriendRights.CanSeeOnline);
if (!FriendList.ContainsKey(fromAgentID))
FriendList.Add(friend.UUID, friend);
if (FriendRequests.ContainsKey(fromAgentID))
FriendRequests.Remove(fromAgentID);
Client.Avatars.RequestAvatarName(fromAgentID);
}
/// <summary>
/// Decline a friendship request
/// </summary>
/// <param name="fromAgentID"><seealso cref="UUID"/> of friend</param>
/// <param name="imSessionID">imSessionID of the friendship request message</param>
public void DeclineFriendship(UUID fromAgentID, UUID imSessionID)
{
DeclineFriendshipPacket request = new DeclineFriendshipPacket();
request.AgentData.AgentID = Client.Self.AgentID;
request.AgentData.SessionID = Client.Self.SessionID;
request.TransactionBlock.TransactionID = imSessionID;
Client.Network.SendPacket(request);
if (FriendRequests.ContainsKey(fromAgentID))
FriendRequests.Remove(fromAgentID);
}
/// <summary>
/// Overload: Offer friendship to an avatar.
/// </summary>
/// <param name="agentID">System ID of the avatar you are offering friendship to</param>
public void OfferFriendship(UUID agentID)
{
OfferFriendship(agentID, "Do ya wanna be my buddy?");
}
/// <summary>
/// Offer friendship to an avatar.
/// </summary>
/// <param name="agentID">System ID of the avatar you are offering friendship to</param>
/// <param name="message">A message to send with the request</param>
public void OfferFriendship(UUID agentID, string message)
{
Client.Self.InstantMessage(Client.Self.Name,
agentID,
message,
UUID.Random(),
InstantMessageDialog.FriendshipOffered,
InstantMessageOnline.Offline,
Client.Self.SimPosition,
Client.Network.CurrentSim.ID,
null);
}
/// <summary>
/// Terminate a friendship with an avatar
/// </summary>
/// <param name="agentID">System ID of the avatar you are terminating the friendship with</param>
public void TerminateFriendship(UUID agentID)
{
if (FriendList.ContainsKey(agentID))
{
TerminateFriendshipPacket request = new TerminateFriendshipPacket();
request.AgentData.AgentID = Client.Self.AgentID;
request.AgentData.SessionID = Client.Self.SessionID;
request.ExBlock.OtherID = agentID;
Client.Network.SendPacket(request);
if (FriendList.ContainsKey(agentID))
FriendList.Remove(agentID);
}
}
/// <summary>Process an incoming packet and raise the appropriate events</summary>
/// <param name="sender">The sender</param>
/// <param name="e">The EventArgs object containing the packet data</param>
private void TerminateFriendshipHandler(object sender, PacketReceivedEventArgs e)
{
Packet packet = e.Packet;
TerminateFriendshipPacket itsOver = (TerminateFriendshipPacket)packet;
string name = String.Empty;
if (FriendList.ContainsKey(itsOver.ExBlock.OtherID))
{
name = FriendList[itsOver.ExBlock.OtherID].Name;
FriendList.Remove(itsOver.ExBlock.OtherID);
}
if (m_FriendshipTerminated != null)
{
OnFriendshipTerminated(new FriendshipTerminatedEventArgs(itsOver.ExBlock.OtherID, name));
}
}
/// <summary>
/// Change the rights of a friend avatar.
/// </summary>
/// <param name="friendID">the <seealso cref="UUID"/> of the friend</param>
/// <param name="rights">the new rights to give the friend</param>
/// <remarks>This method will implicitly set the rights to those passed in the rights parameter.</remarks>
public void GrantRights(UUID friendID, FriendRights rights)
{
GrantUserRightsPacket request = new GrantUserRightsPacket();
request.AgentData.AgentID = Client.Self.AgentID;
request.AgentData.SessionID = Client.Self.SessionID;
request.Rights = new GrantUserRightsPacket.RightsBlock[1];
request.Rights[0] = new GrantUserRightsPacket.RightsBlock();
request.Rights[0].AgentRelated = friendID;
request.Rights[0].RelatedRights = (int)rights;
Client.Network.SendPacket(request);
}
/// <summary>
/// Use to map a friends location on the grid.
/// </summary>
/// <param name="friendID">Friends UUID to find</param>
/// <remarks><seealso cref="E:OnFriendFound"/></remarks>
public void MapFriend(UUID friendID)
{
FindAgentPacket stalk = new FindAgentPacket();
stalk.AgentBlock.Hunter = Client.Self.AgentID;
stalk.AgentBlock.Prey = friendID;
stalk.AgentBlock.SpaceIP = 0; // Will be filled in by the simulator
stalk.LocationBlock = new FindAgentPacket.LocationBlockBlock[1];
stalk.LocationBlock[0] = new FindAgentPacket.LocationBlockBlock();
stalk.LocationBlock[0].GlobalX = 0.0; // Filled in by the simulator
stalk.LocationBlock[0].GlobalY = 0.0;
Client.Network.SendPacket(stalk);
}
/// <summary>
/// Use to track a friends movement on the grid
/// </summary>
/// <param name="friendID">Friends Key</param>
public void TrackFriend(UUID friendID)
{
TrackAgentPacket stalk = new TrackAgentPacket();
stalk.AgentData.AgentID = Client.Self.AgentID;
stalk.AgentData.SessionID = Client.Self.SessionID;
stalk.TargetData.PreyID = friendID;
Client.Network.SendPacket(stalk);
}
/// <summary>
/// Ask for a notification of friend's online status
/// </summary>
/// <param name="friendID">Friend's UUID</param>
public void RequestOnlineNotification(UUID friendID)
{
GenericMessagePacket gmp = new GenericMessagePacket();
gmp.AgentData.AgentID = Client.Self.AgentID;
gmp.AgentData.SessionID = Client.Self.SessionID;
gmp.AgentData.TransactionID = UUID.Zero;
gmp.MethodData.Method = Utils.StringToBytes("requestonlinenotification");
gmp.MethodData.Invoice = UUID.Zero;
gmp.ParamList = new GenericMessagePacket.ParamListBlock[1];
gmp.ParamList[0] = new GenericMessagePacket.ParamListBlock();
gmp.ParamList[0].Parameter = Utils.StringToBytes(friendID.ToString());
Client.Network.SendPacket(gmp);
}
#endregion
#region Internal events
private void Network_OnConnect(object sender, LoginProgressEventArgs e)
{
if (e.Status != LoginStatus.Success)
{
return;
}
List<UUID> names = new List<UUID>();
if (FriendList.Count > 0)
{
FriendList.ForEach(
delegate(KeyValuePair<UUID, FriendInfo> kvp)
{
if (String.IsNullOrEmpty(kvp.Value.Name))
names.Add(kvp.Key);
}
);
Client.Avatars.RequestAvatarNames(names);
}
}
/// <summary>
/// This handles the asynchronous response of a RequestAvatarNames call.
/// </summary>
/// <param name="sender"></param>
/// <param name="e">names cooresponding to the the list of IDs sent the the RequestAvatarNames call.</param>
private void Avatars_OnAvatarNames(object sender, UUIDNameReplyEventArgs e)
{
Dictionary<UUID, string> newNames = new Dictionary<UUID, string>();
foreach (KeyValuePair<UUID, string> kvp in e.Names)
{
FriendInfo friend;
lock (FriendList.Dictionary)
{
if (FriendList.TryGetValue(kvp.Key, out friend))
{
if (friend.Name == null)
newNames.Add(kvp.Key, e.Names[kvp.Key]);
friend.Name = e.Names[kvp.Key];
FriendList[kvp.Key] = friend;
}
}
}
if (newNames.Count > 0 && m_FriendNames != null)
{
OnFriendNames(new FriendNamesEventArgs(newNames));
}
}
#endregion
#region Packet Handlers
/// <summary>Process an incoming packet and raise the appropriate events</summary>
/// <param name="sender">The sender</param>
/// <param name="e">The EventArgs object containing the packet data</param>
protected void OnlineNotificationHandler(object sender, PacketReceivedEventArgs e)
{
Packet packet = e.Packet;
if (packet.Type == PacketType.OnlineNotification)
{
OnlineNotificationPacket notification = ((OnlineNotificationPacket)packet);
foreach (OnlineNotificationPacket.AgentBlockBlock block in notification.AgentBlock)
{
FriendInfo friend;
lock (FriendList.Dictionary)
{
if (!FriendList.ContainsKey(block.AgentID))
{
friend = new FriendInfo(block.AgentID, FriendRights.CanSeeOnline,
FriendRights.CanSeeOnline);
FriendList.Add(block.AgentID, friend);
}
else
{
friend = FriendList[block.AgentID];
}
}
bool doNotify = !friend.IsOnline;
friend.IsOnline = true;
if (m_FriendOnline != null && doNotify)
{
OnFriendOnline(new FriendInfoEventArgs(friend));
}
}
}
}
/// <summary>Process an incoming packet and raise the appropriate events</summary>
/// <param name="sender">The sender</param>
/// <param name="e">The EventArgs object containing the packet data</param>
protected void OfflineNotificationHandler(object sender, PacketReceivedEventArgs e)
{
Packet packet = e.Packet;
if (packet.Type == PacketType.OfflineNotification)
{
OfflineNotificationPacket notification = (OfflineNotificationPacket)packet;
foreach (OfflineNotificationPacket.AgentBlockBlock block in notification.AgentBlock)
{
FriendInfo friend = new FriendInfo(block.AgentID, FriendRights.CanSeeOnline, FriendRights.CanSeeOnline);
lock (FriendList.Dictionary)
{
if (!FriendList.Dictionary.ContainsKey(block.AgentID))
FriendList.Dictionary[block.AgentID] = friend;
friend = FriendList.Dictionary[block.AgentID];
}
friend.IsOnline = false;
if (m_FriendOffline != null)
{
OnFriendOffline(new FriendInfoEventArgs(friend));
}
}
}
}
/// <summary>Process an incoming packet and raise the appropriate events</summary>
/// <param name="sender">The sender</param>
/// <param name="e">The EventArgs object containing the packet data</param>
private void ChangeUserRightsHandler(object sender, PacketReceivedEventArgs e)
{
Packet packet = e.Packet;
if (packet.Type == PacketType.ChangeUserRights)
{
FriendInfo friend;
ChangeUserRightsPacket rights = (ChangeUserRightsPacket)packet;
foreach (ChangeUserRightsPacket.RightsBlock block in rights.Rights)
{
FriendRights newRights = (FriendRights)block.RelatedRights;
if (FriendList.TryGetValue(block.AgentRelated, out friend))
{
friend.TheirFriendRights = newRights;
if (m_FriendRights != null)
{
OnFriendRights(new FriendInfoEventArgs(friend));
}
}
else if (block.AgentRelated == Client.Self.AgentID)
{
if (FriendList.TryGetValue(rights.AgentData.AgentID, out friend))
{
friend.MyFriendRights = newRights;
if (m_FriendRights != null)
{
OnFriendRights(new FriendInfoEventArgs(friend));
}
}
}
}
}
}
/// <summary>Process an incoming packet and raise the appropriate events</summary>
/// <param name="sender">The sender</param>
/// <param name="e">The EventArgs object containing the packet data</param>
public void OnFindAgentReplyHandler(object sender, PacketReceivedEventArgs e)
{
if (m_FriendFound != null)
{
Packet packet = e.Packet;
FindAgentPacket reply = (FindAgentPacket)packet;
float x, y;
UUID prey = reply.AgentBlock.Prey;
ulong regionHandle = Helpers.GlobalPosToRegionHandle((float)reply.LocationBlock[0].GlobalX,
(float)reply.LocationBlock[0].GlobalY, out x, out y);
Vector3 xyz = new Vector3(x, y, 0f);
OnFriendFoundReply(new FriendFoundReplyEventArgs(prey, regionHandle, xyz));
}
}
#endregion
private void Self_IM(object sender, InstantMessageEventArgs e)
{
if (e.IM.Dialog == InstantMessageDialog.FriendshipOffered)
{
if (m_FriendshipOffered != null)
{
if (FriendRequests.ContainsKey(e.IM.FromAgentID))
FriendRequests[e.IM.FromAgentID] = e.IM.IMSessionID;
else
FriendRequests.Add(e.IM.FromAgentID, e.IM.IMSessionID);
OnFriendshipOffered(new FriendshipOfferedEventArgs(e.IM.FromAgentID, e.IM.FromAgentName, e.IM.IMSessionID));
}
}
else if (e.IM.Dialog == InstantMessageDialog.FriendshipAccepted)
{
FriendInfo friend = new FriendInfo(e.IM.FromAgentID, FriendRights.CanSeeOnline,
FriendRights.CanSeeOnline);
friend.Name = e.IM.FromAgentName;
lock (FriendList.Dictionary) FriendList[friend.UUID] = friend;
if (m_FriendshipResponse != null)
{
OnFriendshipResponse(new FriendshipResponseEventArgs(e.IM.FromAgentID, e.IM.FromAgentName, true));
}
RequestOnlineNotification(e.IM.FromAgentID);
}
else if (e.IM.Dialog == InstantMessageDialog.FriendshipDeclined)
{
if (m_FriendshipResponse != null)
{
OnFriendshipResponse(new FriendshipResponseEventArgs(e.IM.FromAgentID, e.IM.FromAgentName, false));
}
}
}
/// <summary>
/// Populate FriendList <seealso cref="InternalDictionary"/> with data from the login reply
/// </summary>
/// <param name="loginSuccess">true if login was successful</param>
/// <param name="redirect">true if login request is requiring a redirect</param>
/// <param name="message">A string containing the response to the login request</param>
/// <param name="reason">A string containing the reason for the request</param>
/// <param name="replyData">A <seealso cref="LoginResponseData"/> object containing the decoded
/// reply from the login server</param>
private void Network_OnLoginResponse(bool loginSuccess, bool redirect, string message, string reason,
LoginResponseData replyData)
{
int uuidLength = UUID.Zero.ToString().Length;
if (loginSuccess && replyData.BuddyList != null)
{
foreach (BuddyListEntry buddy in replyData.BuddyList)
{
UUID bubid;
string id = buddy.buddy_id.Length > uuidLength ? buddy.buddy_id.Substring(0, uuidLength) : buddy.buddy_id;
if (UUID.TryParse(id, out bubid))
{
lock (FriendList.Dictionary)
{
if (!FriendList.ContainsKey(bubid))
{
FriendList[bubid] = new FriendInfo(bubid,
(FriendRights)buddy.buddy_rights_given,
(FriendRights)buddy.buddy_rights_has);
}
}
}
}
}
}
}
#region EventArgs
/// <summary>Contains information on a member of our friends list</summary>
public class FriendInfoEventArgs : EventArgs
{
private readonly FriendInfo m_Friend;
/// <summary>Get the FriendInfo</summary>
public FriendInfo Friend { get { return m_Friend; } }
/// <summary>
/// Construct a new instance of the FriendInfoEventArgs class
/// </summary>
/// <param name="friend">The FriendInfo</param>
public FriendInfoEventArgs(FriendInfo friend)
{
this.m_Friend = friend;
}
}
/// <summary>Contains Friend Names</summary>
public class FriendNamesEventArgs : EventArgs
{
private readonly Dictionary<UUID, string> m_Names;
/// <summary>A dictionary where the Key is the ID of the Agent,
/// and the Value is a string containing their name</summary>
public Dictionary<UUID, string> Names { get { return m_Names; } }
/// <summary>
/// Construct a new instance of the FriendNamesEventArgs class
/// </summary>
/// <param name="names">A dictionary where the Key is the ID of the Agent,
/// and the Value is a string containing their name</param>
public FriendNamesEventArgs(Dictionary<UUID, string> names)
{
this.m_Names = names;
}
}
/// <summary>Sent when another agent requests a friendship with our agent</summary>
public class FriendshipOfferedEventArgs : EventArgs
{
private readonly UUID m_AgentID;
private readonly string m_AgentName;
private readonly UUID m_SessionID;
/// <summary>Get the ID of the agent requesting friendship</summary>
public UUID AgentID { get { return m_AgentID; } }
/// <summary>Get the name of the agent requesting friendship</summary>
public string AgentName { get { return m_AgentName; } }
/// <summary>Get the ID of the session, used in accepting or declining the
/// friendship offer</summary>
public UUID SessionID { get { return m_SessionID; } }
/// <summary>
/// Construct a new instance of the FriendshipOfferedEventArgs class
/// </summary>
/// <param name="agentID">The ID of the agent requesting friendship</param>
/// <param name="agentName">The name of the agent requesting friendship</param>
/// <param name="imSessionID">The ID of the session, used in accepting or declining the
/// friendship offer</param>
public FriendshipOfferedEventArgs(UUID agentID, string agentName, UUID imSessionID)
{
this.m_AgentID = agentID;
this.m_AgentName = agentName;
this.m_SessionID = imSessionID;
}
}
/// <summary>A response containing the results of our request to form a friendship with another agent</summary>
public class FriendshipResponseEventArgs : EventArgs
{
private readonly UUID m_AgentID;
private readonly string m_AgentName;
private readonly bool m_Accepted;
/// <summary>Get the ID of the agent we requested a friendship with</summary>
public UUID AgentID { get { return m_AgentID; } }
/// <summary>Get the name of the agent we requested a friendship with</summary>
public string AgentName { get { return m_AgentName; } }
/// <summary>true if the agent accepted our friendship offer</summary>
public bool Accepted { get { return m_Accepted; } }
/// <summary>
/// Construct a new instance of the FriendShipResponseEventArgs class
/// </summary>
/// <param name="agentID">The ID of the agent we requested a friendship with</param>
/// <param name="agentName">The name of the agent we requested a friendship with</param>
/// <param name="accepted">true if the agent accepted our friendship offer</param>
public FriendshipResponseEventArgs(UUID agentID, string agentName, bool accepted)
{
this.m_AgentID = agentID;
this.m_AgentName = agentName;
this.m_Accepted = accepted;
}
}
/// <summary>Contains data sent when a friend terminates a friendship with us</summary>
public class FriendshipTerminatedEventArgs : EventArgs
{
private readonly UUID m_AgentID;
private readonly string m_AgentName;
/// <summary>Get the ID of the agent that terminated the friendship with us</summary>
public UUID AgentID { get { return m_AgentID; } }
/// <summary>Get the name of the agent that terminated the friendship with us</summary>
public string AgentName { get { return m_AgentName; } }
/// <summary>
/// Construct a new instance of the FrindshipTerminatedEventArgs class
/// </summary>
/// <param name="agentID">The ID of the friend who terminated the friendship with us</param>
/// <param name="agentName">The name of the friend who terminated the friendship with us</param>
public FriendshipTerminatedEventArgs(UUID agentID, string agentName)
{
this.m_AgentID = agentID;
this.m_AgentName = agentName;
}
}
/// <summary>
/// Data sent in response to a <see cref="FindFriend"/> request which contains the information to allow us to map the friends location
/// </summary>
public class FriendFoundReplyEventArgs : EventArgs
{
private readonly UUID m_AgentID;
private readonly ulong m_RegionHandle;
private readonly Vector3 m_Location;
/// <summary>Get the ID of the agent we have received location information for</summary>
public UUID AgentID { get { return m_AgentID; } }
/// <summary>Get the region handle where our mapped friend is located</summary>
public ulong RegionHandle { get { return m_RegionHandle; } }
/// <summary>Get the simulator local position where our friend is located</summary>
public Vector3 Location { get { return m_Location; } }
/// <summary>
/// Construct a new instance of the FriendFoundReplyEventArgs class
/// </summary>
/// <param name="agentID">The ID of the agent we have requested location information for</param>
/// <param name="regionHandle">The region handle where our friend is located</param>
/// <param name="location">The simulator local position our friend is located</param>
public FriendFoundReplyEventArgs(UUID agentID, ulong regionHandle, Vector3 location)
{
this.m_AgentID = agentID;
this.m_RegionHandle = regionHandle;
this.m_Location = location;
}
}
#endregion
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.