context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace ApplicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using 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>
/// SecurityRulesOperations operations.
/// </summary>
internal partial class SecurityRulesOperations : IServiceOperations<NetworkClient>, ISecurityRulesOperations
{
/// <summary>
/// Initializes a new instance of the SecurityRulesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal SecurityRulesOperations(NetworkClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkClient
/// </summary>
public NetworkClient Client { get; private set; }
/// <summary>
/// Deletes the specified network security rule.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string securityRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get the specified network security rule.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='customHeaders'>
/// 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<SecurityRule>> GetWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string securityRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkSecurityGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkSecurityGroupName");
}
if (securityRuleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "securityRuleName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("networkSecurityGroupName", networkSecurityGroupName);
tracingParameters.Add("securityRuleName", securityRuleName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkSecurityGroupName}", System.Uri.EscapeDataString(networkSecurityGroupName));
_url = _url.Replace("{securityRuleName}", System.Uri.EscapeDataString(securityRuleName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<SecurityRule>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<SecurityRule>(_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 a security rule in the specified network security group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='securityRuleParameters'>
/// Parameters supplied to the create or update network security rule
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<SecurityRule>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string securityRuleName, SecurityRule securityRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<SecurityRule> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, securityRuleParameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all security rules in a network security group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='customHeaders'>
/// 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<SecurityRule>>> ListWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkSecurityGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkSecurityGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("networkSecurityGroupName", networkSecurityGroupName);
tracingParameters.Add("apiVersion", apiVersion);
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}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkSecurityGroupName}", System.Uri.EscapeDataString(networkSecurityGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<SecurityRule>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SecurityRule>>(_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 the specified network security rule.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='customHeaders'>
/// 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> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string securityRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkSecurityGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkSecurityGroupName");
}
if (securityRuleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "securityRuleName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("networkSecurityGroupName", networkSecurityGroupName);
tracingParameters.Add("securityRuleName", securityRuleName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", 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.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkSecurityGroupName}", System.Uri.EscapeDataString(networkSecurityGroupName));
_url = _url.Replace("{securityRuleName}", System.Uri.EscapeDataString(securityRuleName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("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 != 204 && (int)_statusCode != 202 && (int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_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>
/// Creates or updates a security rule in the specified network security group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='securityRuleParameters'>
/// Parameters supplied to the create or update network security rule
/// operation.
/// </param>
/// <param name='customHeaders'>
/// 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<SecurityRule>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string securityRuleName, SecurityRule securityRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkSecurityGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkSecurityGroupName");
}
if (securityRuleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "securityRuleName");
}
if (securityRuleParameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "securityRuleParameters");
}
if (securityRuleParameters != null)
{
securityRuleParameters.Validate();
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("networkSecurityGroupName", networkSecurityGroupName);
tracingParameters.Add("securityRuleName", securityRuleName);
tracingParameters.Add("securityRuleParameters", securityRuleParameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", 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.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkSecurityGroupName}", System.Uri.EscapeDataString(networkSecurityGroupName));
_url = _url.Replace("{securityRuleName}", System.Uri.EscapeDataString(securityRuleName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("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(securityRuleParameters != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(securityRuleParameters, 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 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<SecurityRule>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<SecurityRule>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<SecurityRule>(_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 all security rules in a network security group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// 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<SecurityRule>>> 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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<SecurityRule>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SecurityRule>>(_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;
}
}
}
| |
// This file is part of the C5 Generic Collection Library for C# and CLI
// See https://github.com/sestoft/C5/blob/master/LICENSE for licensing details.
using System;
using SCG = System.Collections.Generic;
namespace C5
{
/// <summary>
/// A set collection class based on linear hashing
/// </summary>
[Serializable]
public class HashSet<T> : CollectionBase<T>, ICollection<T>
{
#region Feature
/// <summary>
/// Enum class to assist printing of compilation alternatives.
/// </summary>
[Flags]
public enum Feature : short
{
/// <summary>
/// Nothing
/// </summary>
Dummy = 0,
/// <summary>
/// Buckets are of reference type
/// </summary>
RefTypeBucket = 1,
/// <summary>
/// Primary buckets are of value type
/// </summary>
ValueTypeBucket = 2,
/// <summary>
/// Using linear probing to resolve index clashes
/// </summary>
LinearProbing = 4,
/// <summary>
/// Shrink table when very sparsely filled
/// </summary>
ShrinkTable = 8,
/// <summary>
/// Use chaining to resolve index clashes
/// </summary>
Chaining = 16,
/// <summary>
/// Use hash function on item hash code
/// </summary>
InterHashing = 32,
/// <summary>
/// Use a universal family of hash functions on item hash code
/// </summary>
RandomInterHashing = 64
}
private static readonly Feature features = Feature.Dummy
| Feature.RefTypeBucket
| Feature.Chaining
| Feature.RandomInterHashing;
/// <summary>
/// Show which implementation features was chosen at compilation time
/// </summary>
public static Feature Features => features;
#endregion
#region Fields
private int indexmask;
private int bits;
private int bitsc;
private readonly int origbits;
private int lastchosen;
private Bucket?[] table;
private readonly double fillfactor = 0.66;
private int resizethreshhold;
private static readonly Random Random = new Random();
private uint _randomhashfactor;
#endregion
#region Events
/// <summary>
///
/// </summary>
/// <value></value>
public override EventType ListenableEvents => EventType.Basic;
#endregion
#region Bucket nested class(es)
[Serializable]
private class Bucket
{
internal T item;
internal int hashval; //Cache!
internal Bucket? overflow;
internal Bucket(T item, int hashval, Bucket? overflow)
{
this.item = item;
this.hashval = hashval;
this.overflow = overflow;
}
}
#endregion
#region Basic Util
private bool Equals(T i1, T i2) { return itemequalityComparer.Equals(i1, i2); }
private int GetHashCode(T item) { return itemequalityComparer.GetHashCode(item); }
private int Hv2i(int hashval)
{
return (int)(((uint)hashval * _randomhashfactor) >> bitsc);
}
private void Expand()
{
Logger.Log(string.Format(string.Format("Expand to {0} bits", bits + 1)));
Resize(bits + 1);
}
/*
void shrink()
{
if (bits > 3)
{
Logger.Log(string.Format(string.Format("Shrink to {0} bits", bits - 1)));
resize(bits - 1);
}
} */
private void Resize(int bits)
{
Logger.Log(string.Format(string.Format("Resize to {0} bits", bits)));
this.bits = bits;
bitsc = 32 - bits;
indexmask = (1 << bits) - 1;
Bucket[] newtable = new Bucket[indexmask + 1];
for (int i = 0, s = table.Length; i < s; i++)
{
Bucket? b = table[i];
while (b != null)
{
int j = Hv2i(b.hashval);
newtable[j] = new Bucket(b.item, b.hashval, newtable[j]);
b = b.overflow;
}
}
table = newtable;
resizethreshhold = (int)(table.Length * fillfactor);
Logger.Log(string.Format(string.Format("Resize to {0} bits done", bits)));
}
/// <summary>
/// Search for an item equal (according to itemequalityComparer) to the supplied item.
/// </summary>
/// <param name="item"></param>
/// <param name="add">If true, add item to table if not found.</param>
/// <param name="update">If true, update table entry if item found.</param>
/// <param name="raise">If true raise events</param>
/// <returns>True if found</returns>
private bool SearchOrAdd(ref T item, bool add, bool update, bool raise)
{
int hashval = GetHashCode(item);
int i = Hv2i(hashval);
Bucket? b = table[i];
Bucket? bold = null;
if (b != null)
{
while (b != null)
{
T olditem = b.item;
if (Equals(olditem, item))
{
if (update)
{
b.item = item;
}
if (raise && update)
{
RaiseForUpdate(item, olditem);
}
// bug20071112:
item = olditem;
return true;
}
bold = b;
b = b.overflow;
}
if (!add)
{
goto notfound;
}
bold!.overflow = new Bucket(item, hashval, null);
}
else
{
if (!add)
{
goto notfound;
}
table[i] = new Bucket(item, hashval, null);
}
size++;
if (size > resizethreshhold)
{
Expand();
}
notfound:
if (raise && add)
{
RaiseForAdd(item);
}
if (update)
{
item = default;
}
return false;
}
private bool Remove(ref T item)
{
if (size == 0)
{
return false;
}
int hashval = GetHashCode(item);
int index = Hv2i(hashval);
Bucket? b = table[index], bold;
if (b == null)
{
return false;
}
if (Equals(item, b.item))
{
//ref
item = b.item;
table[index] = b.overflow;
}
else
{
bold = b;
b = b.overflow;
while (b != null && !Equals(item, b.item))
{
bold = b;
b = b.overflow;
}
if (b == null)
{
return false;
}
//ref
item = b.item;
bold.overflow = b.overflow;
}
size--;
return true;
}
private void ClearInner()
{
bits = origbits;
bitsc = 32 - bits;
indexmask = (1 << bits) - 1;
size = 0;
table = new Bucket[indexmask + 1];
resizethreshhold = (int)(table.Length * fillfactor);
}
#endregion
#region Constructors
/// <summary>
/// Create a hash set with natural item equalityComparer and default fill threshold (66%)
/// and initial table size (16).
/// </summary>
public HashSet()
: this(EqualityComparer<T>.Default) { }
/// <summary>
/// Create a hash set with external item equalityComparer and default fill threshold (66%)
/// and initial table size (16).
/// </summary>
/// <param name="itemequalityComparer">The external item equalitySCG.Comparer</param>
public HashSet(SCG.IEqualityComparer<T> itemequalityComparer)
: this(16, itemequalityComparer) { }
/// <summary>
/// Create a hash set with external item equalityComparer and default fill threshold (66%)
/// </summary>
/// <param name="capacity">Initial table size (rounded to power of 2, at least 16)</param>
/// <param name="itemequalityComparer">The external item equalitySCG.Comparer</param>
public HashSet(int capacity, SCG.IEqualityComparer<T> itemequalityComparer)
: this(capacity, 0.66, itemequalityComparer) { }
/// <summary>
/// Create a hash set with external item equalityComparer.
/// </summary>
/// <param name="capacity">Initial table size (rounded to power of 2, at least 16)</param>
/// <param name="fill">Fill threshold (in range 10% to 90%)</param>
/// <param name="itemequalityComparer">The external item equalitySCG.Comparer</param>
public HashSet(int capacity, double fill, SCG.IEqualityComparer<T> itemequalityComparer)
: base(itemequalityComparer)
{
_randomhashfactor = (Debug.UseDeterministicHashing) ? 1529784659 : (2 * (uint)Random.Next() + 1) * 1529784659;
if (fill < 0.1 || fill > 0.9)
{
throw new ArgumentException("Fill outside valid range [0.1, 0.9]");
}
if (capacity <= 0)
{
throw new ArgumentException("Capacity must be non-negative");
}
//this.itemequalityComparer = itemequalityComparer;
origbits = 4;
while (capacity - 1 >> origbits > 0)
{
origbits++;
}
ClearInner();
}
#endregion
#region IEditableCollection<T> Members
/// <summary>
/// The complexity of the Contains operation
/// </summary>
/// <value>Always returns Speed.Constant</value>
public virtual Speed ContainsSpeed => Speed.Constant;
/// <summary>
/// Check if an item is in the set
/// </summary>
/// <param name="item">The item to look for</param>
/// <returns>True if set contains item</returns>
public virtual bool Contains(T item) { return SearchOrAdd(ref item, false, false, false); }
/// <summary>
/// Check if an item (collection equal to a given one) is in the set and
/// if so report the actual item object found.
/// </summary>
/// <param name="item">On entry, the item to look for.
/// On exit the item found, if any</param>
/// <returns>True if set contains item</returns>
public virtual bool Find(ref T item) { return SearchOrAdd(ref item, false, false, false); }
/// <summary>
/// Check if an item (collection equal to a given one) is in the set and
/// if so replace the item object in the set with the supplied one.
/// </summary>
/// <param name="item">The item object to update with</param>
/// <returns>True if item was found (and updated)</returns>
public virtual bool Update(T item)
{ UpdateCheck(); return SearchOrAdd(ref item, false, true, true); }
/// <summary>
/// Check if an item (collection equal to a given one) is in the set and
/// if so replace the item object in the set with the supplied one.
/// </summary>
/// <param name="item">The item object to update with</param>
/// <param name="olditem"></param>
/// <returns>True if item was found (and updated)</returns>
public virtual bool Update(T item, out T olditem)
{ UpdateCheck(); olditem = item; return SearchOrAdd(ref olditem, false, true, true); }
/// <summary>
/// Check if an item (collection equal to a given one) is in the set.
/// If found, report the actual item object in the set,
/// else add the supplied one.
/// </summary>
/// <param name="item">On entry, the item to look for or add.
/// On exit the actual object found, if any.</param>
/// <returns>True if item was found</returns>
public virtual bool FindOrAdd(ref T item)
{ UpdateCheck(); return SearchOrAdd(ref item, true, false, true); }
/// <summary>
/// Check if an item (collection equal to a supplied one) is in the set and
/// if so replace the item object in the set with the supplied one; else
/// add the supplied one.
/// </summary>
/// <param name="item">The item to look for and update or add</param>
/// <returns>True if item was updated</returns>
public virtual bool UpdateOrAdd(T item)
{ UpdateCheck(); return SearchOrAdd(ref item, true, true, true); }
/// <summary>
/// Check if an item (collection equal to a supplied one) is in the set and
/// if so replace the item object in the set with the supplied one; else
/// add the supplied one.
/// </summary>
/// <param name="item">The item to look for and update or add</param>
/// <param name="olditem"></param>
/// <returns>True if item was updated</returns>
public virtual bool UpdateOrAdd(T item, out T olditem)
{ UpdateCheck(); olditem = item; return SearchOrAdd(ref olditem, true, true, true); }
/// <summary>
/// Remove an item from the set
/// </summary>
/// <param name="item">The item to remove</param>
/// <returns>True if item was (found and) removed </returns>
public virtual bool Remove(T item)
{
UpdateCheck();
if (Remove(ref item))
{
RaiseForRemove(item);
return true;
}
else
{
return false;
}
}
/// <summary>
/// Remove an item from the set, reporting the actual matching item object.
/// </summary>
/// <param name="item">The value to remove.</param>
/// <param name="removeditem">The removed value.</param>
/// <returns>True if item was found.</returns>
public virtual bool Remove(T item, out T removeditem)
{
UpdateCheck();
removeditem = item;
if (Remove(ref removeditem))
{
RaiseForRemove(removeditem);
return true;
}
else
{
return false;
}
}
/// <summary>
/// Remove all items in a supplied collection from this set.
/// </summary>
/// <param name="items">The items to remove.</param>
public virtual void RemoveAll(SCG.IEnumerable<T> items)
{
UpdateCheck();
RaiseForRemoveAllHandler raiseHandler = new RaiseForRemoveAllHandler(this);
bool raise = raiseHandler.MustFire;
T jtem;
foreach (var item in items)
{
jtem = item; if (Remove(ref jtem) && raise)
{
raiseHandler.Remove(jtem);
}
}
if (raise)
{
raiseHandler.Raise();
}
}
/// <summary>
/// Remove all items from the set, resetting internal table to initial size.
/// </summary>
public virtual void Clear()
{
UpdateCheck();
int oldsize = size;
ClearInner();
if (ActiveEvents != 0 && oldsize > 0)
{
RaiseCollectionCleared(true, oldsize);
RaiseCollectionChanged();
}
}
/// <summary>
/// Remove all items *not* in a supplied collection from this set.
/// </summary>
/// <param name="items">The items to retain</param>
public virtual void RetainAll(SCG.IEnumerable<T> items)
{
UpdateCheck();
HashSet<T> aux = new HashSet<T>(EqualityComparer);
//This only works for sets:
foreach (var item in items)
{
if (Contains(item))
{
T jtem = item;
aux.SearchOrAdd(ref jtem, true, false, false);
}
}
if (size == aux.size)
{
return;
}
CircularQueue<T>? wasRemoved = null;
if ((ActiveEvents & EventType.Removed) != 0)
{
wasRemoved = new CircularQueue<T>();
foreach (T item in this)
{
if (!aux.Contains(item))
{
wasRemoved.Enqueue(item);
}
}
}
table = aux.table;
size = aux.size;
indexmask = aux.indexmask;
resizethreshhold = aux.resizethreshhold;
bits = aux.bits;
bitsc = aux.bitsc;
_randomhashfactor = aux._randomhashfactor;
if ((ActiveEvents & EventType.Removed) != 0)
{
RaiseForRemoveAll(wasRemoved);
}
else if ((ActiveEvents & EventType.Changed) != 0)
{
RaiseCollectionChanged();
}
}
/// <summary>
/// Check if all items in a supplied collection is in this set
/// (ignoring multiplicities).
/// </summary>
/// <param name="items">The items to look for.</param>
/// <returns>True if all items are found.</returns>
public virtual bool ContainsAll(SCG.IEnumerable<T> items)
{
foreach (var item in items)
{
if (!Contains(item))
{
return false;
}
}
return true;
}
/// <summary>
/// Create an array containing all items in this set (in enumeration order).
/// </summary>
/// <returns>The array</returns>
public override T[] ToArray()
{
T[] res = new T[size];
int index = 0;
for (int i = 0; i < table.Length; i++)
{
Bucket? b = table[i];
while (b != null)
{
res[index++] = b.item;
b = b.overflow;
}
}
System.Diagnostics.Debug.Assert(size == index);
return res;
}
/// <summary>
/// Count the number of times an item is in this set (either 0 or 1).
/// </summary>
/// <param name="item">The item to look for.</param>
/// <returns>1 if item is in set, 0 else</returns>
public virtual int ContainsCount(T item) { return Contains(item) ? 1 : 0; }
/// <summary>
///
/// </summary>
/// <returns></returns>
public virtual ICollectionValue<T> UniqueItems() { return this; }
/// <summary>
///
/// </summary>
/// <returns></returns>
public virtual ICollectionValue<System.Collections.Generic.KeyValuePair<T, int>> ItemMultiplicities()
{
return new MultiplicityOne<T>(this);
}
/// <summary>
/// Remove all (at most 1) copies of item from this set.
/// </summary>
/// <param name="item">The item to remove</param>
public virtual void RemoveAllCopies(T item) { Remove(item); }
#endregion
#region IEnumerable<T> Members
/// <summary>
/// Choose some item of this collection.
/// </summary>
/// <exception cref="NoSuchItemException">if collection is empty.</exception>
/// <returns></returns>
public override T Choose()
{
int len = table.Length;
if (size == 0)
{
throw new NoSuchItemException();
}
do { if (++lastchosen >= len) { lastchosen = 0; } } while (table[lastchosen] == null);
return (table[lastchosen])!.item;
}
/// <summary>
/// Create an enumerator for this set.
/// </summary>
/// <returns>The enumerator</returns>
public override SCG.IEnumerator<T> GetEnumerator()
{
int index = -1;
int mystamp = stamp;
int len = table.Length;
Bucket? b = null;
while (true)
{
if (mystamp != stamp)
{
throw new CollectionModifiedException();
}
if (b == null || b.overflow == null)
{
do
{
if (++index >= len)
{
yield break;
}
} while (table[index] == null);
b = table[index];
yield return b!.item;
}
else
{
b = b.overflow;
yield return b.item;
}
}
}
#endregion
#region ISink<T> Members
/// <summary>
/// Report if this is a set collection.
/// </summary>
/// <value>Always false</value>
public virtual bool AllowsDuplicates => false;
/// <summary>
/// By convention this is true for any collection with set semantics.
/// </summary>
/// <value>True if only one representative of a group of equal items
/// is kept in the collection together with the total count.</value>
public virtual bool DuplicatesByCounting => true;
/// <summary>
/// Add an item to this set.
/// </summary>
/// <param name="item">The item to add.</param>
/// <returns>True if item was added (i.e. not found)</returns>
public virtual bool Add(T item)
{
UpdateCheck();
return !SearchOrAdd(ref item, true, false, true);
}
/// <summary>
/// Add an item to this set.
/// </summary>
/// <param name="item">The item to add.</param>
void SCG.ICollection<T>.Add(T item)
{
Add(item);
}
/// <summary>
/// Add the elements from another collection with a more specialized item type
/// to this collection. Since this
/// collection has set semantics, only items not already in the collection
/// will be added.
/// </summary>
/// <param name="items">The items to add</param>
public virtual void AddAll(SCG.IEnumerable<T> items)
{
UpdateCheck();
bool wasChanged = false;
bool raiseAdded = (ActiveEvents & EventType.Added) != 0;
CircularQueue<T>? wasAdded = raiseAdded ? new CircularQueue<T>() : null;
foreach (T item in items)
{
T jtem = item;
if (!SearchOrAdd(ref jtem, true, false, false))
{
wasChanged = true;
if (raiseAdded)
{
wasAdded?.Enqueue(item);
}
}
}
//TODO: implement a RaiseForAddAll() method
if (raiseAdded & wasChanged)
{
if (wasAdded != null)
{
foreach (T item in wasAdded)
{
RaiseItemsAdded(item, 1);
}
}
}
if (((ActiveEvents & EventType.Changed) != 0 && wasChanged))
{
RaiseCollectionChanged();
}
}
#endregion
#region Diagnostics
/// <summary>
/// Test internal structure of data (invariants)
/// </summary>
/// <returns>True if pass</returns>
public virtual bool Check()
{
int count = 0;
bool retval = true;
if (bitsc != 32 - bits)
{
Logger.Log(string.Format("bitsc != 32 - bits ({0}, {1})", bitsc, bits));
retval = false;
}
if (indexmask != (1 << bits) - 1)
{
Logger.Log(string.Format("indexmask != (1 << bits) - 1 ({0}, {1})", indexmask, bits));
retval = false;
}
if (table.Length != indexmask + 1)
{
Logger.Log(string.Format("table.Length != indexmask + 1 ({0}, {1})", table.Length, indexmask));
retval = false;
}
if (bitsc != 32 - bits)
{
Logger.Log(string.Format("resizethreshhold != (int)(table.Length * fillfactor) ({0}, {1}, {2})", resizethreshhold, table.Length, fillfactor));
retval = false;
}
for (int i = 0, s = table.Length; i < s; i++)
{
int level = 0;
Bucket? b = table[i];
while (b != null)
{
if (i != Hv2i(b.hashval))
{
Logger.Log(string.Format("Bad cell item={0}, hashval={1}, index={2}, level={3}", b.item, b.hashval, i, level));
retval = false;
}
count++;
level++;
b = b.overflow;
}
}
if (count != size)
{
Logger.Log(string.Format("size({0}) != count({1})", size, count));
retval = false;
}
return retval;
}
/// <summary>
/// Produce statistics on distribution of bucket sizes. Current implementation is incomplete.
/// </summary>
/// <returns>Histogram data.</returns>
public ISortedDictionary<int, int> BucketCostDistribution()
{
TreeDictionary<int, int> res = new TreeDictionary<int, int>();
for (int i = 0, s = table.Length; i < s; i++)
{
int count = 0;
Bucket? b = table[i];
while (b != null)
{
count++;
b = b.overflow;
}
if (res.Contains(count))
{
res[count]++;
}
else
{
res[count] = 1;
}
}
return res;
}
#endregion
}
}
| |
/*
* Copyright (C) Sony Computer Entertainment America LLC.
* All Rights Reserved.
*/
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Sce.Sled.Shared.Services;
namespace Sce.Sled
{
/// <summary>
/// ISledFindAndReplaceSubForm Interface
/// </summary>
interface ISledFindAndReplaceSubForm
{
/// <summary>
/// Gets the underlying UserControl
/// </summary>
Control Control
{
get;
}
/// <summary>
/// Sets the initial text shown in the find or replace form
/// </summary>
string InitialText { set; }
/// <summary>
/// Event fired when a subform is doing a find or replace event
/// </summary>
event EventHandler<SledFindAndReplaceEventArgs> FindAndReplaceEvent;
}
/// <summary>
/// Enumeration describing the places to look when finding or replacing
/// </summary>
enum SledFindAndReplaceLookIn
{
Invalid,
CurrentDocument,
AllOpenDocuments,
CurrentProject,
EntireSolution,
Custom,
}
/// <summary>
/// Enumeration describing the possible search patterns to use when finding or replacing
/// </summary>
enum SledFindAndReplaceSearchType
{
Normal,
RegularExpressions,
WildCards,
}
/// <summary>
/// Which find and replace window to use
/// </summary>
enum SledFindAndReplaceResultsWindow
{
None,
One,
Two,
}
/// <summary>
/// Result of a find or replace action
/// </summary>
enum SledFindAndReplaceResult
{
Invalid,
NothingToSearch,
NothingFound,
Success,
}
/// <summary>
/// Abstract class for find and replace event arguments to derive from
/// </summary>
abstract class SledFindAndReplaceEventArgs : EventArgs, ICloneable
{
#region ICloneable Interface
public abstract object Clone();
#endregion
#region SledFindAndReplaceEventArgs Specific Stuff
protected SledFindAndReplaceEventArgs(SledFindAndReplaceModes mode)
{
m_mode = mode;
}
public SledFindAndReplaceModes Mode
{
get { return m_mode; }
}
public SledFindAndReplaceResult Result
{
get { return m_result; }
set { m_result = value; }
}
private readonly SledFindAndReplaceModes m_mode;
private SledFindAndReplaceResult m_result = SledFindAndReplaceResult.Invalid;
#endregion
#region Quick Find Specific Event Args Class
public class QuickFind : SledFindAndReplaceEventArgs
{
public QuickFind(string szFindWhat, SledFindAndReplaceLookIn lookIn, bool bMatchCase, bool bMatchWholeWord, bool bSearchUp, SledFindAndReplaceSearchType searchType)
: base(SledFindAndReplaceModes.QuickFind)
{
FindWhat = szFindWhat;
LookIn = lookIn;
MatchCase = bMatchCase;
MatchWholeWord = bMatchWholeWord;
SearchUp = bSearchUp;
SearchType = searchType;
}
public string FindWhat { get; private set; }
public SledFindAndReplaceLookIn LookIn { get; private set; }
public bool MatchCase { get; private set; }
public bool MatchWholeWord { get; private set; }
public bool SearchUp { get; private set; }
public SledFindAndReplaceSearchType SearchType { get; private set; }
#region ICloneable Override
public override object Clone()
{
var obj = new QuickFind(
FindWhat,
LookIn,
MatchCase,
MatchWholeWord,
SearchUp,
SearchType);
return obj;
}
#endregion
}
#endregion
#region Find in Files Specific Event Args Class
public class FindInFiles : SledFindAndReplaceEventArgs
{
public FindInFiles(string szFindWhat, SledFindAndReplaceLookIn lookIn, string[] lookInFolders, bool bIncludeSubFolders, string[] fileExts, bool bMatchCase, bool bMatchWholeWord, SledFindAndReplaceSearchType searchType, bool bUseResults1Window)
: base(SledFindAndReplaceModes.FindInFiles)
{
m_szFindWhat = szFindWhat;
m_lookIn = lookIn;
m_lookInFolders = lookInFolders;
m_bIncludeSubFolders = bIncludeSubFolders;
m_fileExts = fileExts;
m_bMatchCase = bMatchCase;
m_bMatchWholeWord = bMatchWholeWord;
m_searchType = searchType;
m_bUseResults1Window = bUseResults1Window;
}
public string FindWhat
{
get { return m_szFindWhat; }
}
public SledFindAndReplaceLookIn LookIn
{
get { return m_lookIn; }
}
public string[] LookInFolders
{
get { return m_lookInFolders; }
}
public bool IncludeSubFolders
{
get { return m_bIncludeSubFolders; }
}
public string[] FileExts
{
get { return m_fileExts; }
}
public bool MatchCase
{
get { return m_bMatchCase; }
}
public bool MatchWholeWord
{
get { return m_bMatchWholeWord; }
}
public SledFindAndReplaceSearchType SearchType
{
get { return m_searchType; }
}
public bool UseResults1Window
{
get { return m_bUseResults1Window; }
}
private readonly string m_szFindWhat;
private readonly SledFindAndReplaceLookIn m_lookIn;
private readonly string[] m_lookInFolders;
private readonly bool m_bIncludeSubFolders;
private readonly string[] m_fileExts;
private readonly bool m_bMatchCase;
private readonly bool m_bMatchWholeWord;
private readonly SledFindAndReplaceSearchType m_searchType;
private readonly bool m_bUseResults1Window;
#region ICloneable Override
public override object Clone()
{
var obj = new FindInFiles(
m_szFindWhat,
m_lookIn,
m_lookInFolders,
m_bIncludeSubFolders,
m_fileExts,
m_bMatchCase,
m_bMatchWholeWord,
m_searchType,
m_bUseResults1Window);
return obj;
}
#endregion
}
#endregion
#region Quick Replace Specific Event Args Class
public class QuickReplace : SledFindAndReplaceEventArgs
{
public QuickReplace(string szFindWhat, string szReplaceWith, SledFindAndReplaceLookIn lookIn, bool bMatchCase, bool bMatchWholeWord, bool bSearchUp, SledFindAndReplaceSearchType searchType)
: base(SledFindAndReplaceModes.QuickReplace)
{
m_szFindWhat = szFindWhat;
m_szReplaceWith = szReplaceWith;
m_lookIn = lookIn;
m_bMatchCase = bMatchCase;
m_bMatchWholeWord = bMatchWholeWord;
m_bSearchUp = bSearchUp;
m_searchType = searchType;
}
public string FindWhat
{
get { return m_szFindWhat; }
}
public string ReplaceWith
{
get { return m_szReplaceWith; }
}
public SledFindAndReplaceLookIn LookIn
{
get { return m_lookIn; }
}
public bool MatchCase
{
get { return m_bMatchCase; }
}
public bool MatchWholeWord
{
get { return m_bMatchWholeWord; }
}
public bool SearchUp
{
get { return m_bSearchUp; }
}
public SledFindAndReplaceSearchType SearchType
{
get { return m_searchType; }
}
private readonly string m_szFindWhat;
private readonly string m_szReplaceWith;
private readonly SledFindAndReplaceLookIn m_lookIn;
private readonly bool m_bMatchCase;
private readonly bool m_bMatchWholeWord;
private readonly bool m_bSearchUp;
private readonly SledFindAndReplaceSearchType m_searchType;
#region ICloneable Override
public override object Clone()
{
var obj = new QuickReplace(
m_szFindWhat,
m_szReplaceWith,
m_lookIn,
m_bMatchCase,
m_bMatchWholeWord,
m_bSearchUp,
m_searchType);
return obj;
}
#endregion
}
#endregion
#region Replace in Files Specific Event Args Class
public class ReplaceInFiles : SledFindAndReplaceEventArgs
{
public ReplaceInFiles(string szFindWhat, string szReplaceWith, SledFindAndReplaceLookIn lookIn, string[] lookInFolders, bool bIncludeSubFolders, string[] fileExts, bool bMatchCase, bool bMatchWholeWord, SledFindAndReplaceSearchType searchType, SledFindAndReplaceResultsWindow resultsWindow, bool bKeepModifiedDocsOpen)
: base(SledFindAndReplaceModes.ReplaceInFiles)
{
m_szFindWhat = szFindWhat;
m_szReplaceWith = szReplaceWith;
m_lookIn = lookIn;
m_lookInFolders = lookInFolders;
m_bIncludeSubFolders = bIncludeSubFolders;
m_fileExts = fileExts;
m_bMatchCase = bMatchCase;
m_bMatchWholeWord = bMatchWholeWord;
m_searchType = searchType;
m_resultsWindow = resultsWindow;
m_bKeepModifiedDocsOpen = bKeepModifiedDocsOpen;
}
public string FindWhat
{
get { return m_szFindWhat; }
}
public string ReplaceWith
{
get { return m_szReplaceWith; }
}
public SledFindAndReplaceLookIn LookIn
{
get { return m_lookIn; }
}
public string[] LookInFolders
{
get { return m_lookInFolders; }
}
public bool IncludeSubFolders
{
get { return m_bIncludeSubFolders; }
}
public string[] FileExts
{
get { return m_fileExts; }
}
public bool MatchCase
{
get { return m_bMatchCase; }
}
public bool MatchWholeWord
{
get { return m_bMatchWholeWord; }
}
public SledFindAndReplaceSearchType SearchType
{
get { return m_searchType; }
}
public SledFindAndReplaceResultsWindow ResultsWindow
{
get { return m_resultsWindow; }
}
public bool KeepModifiedDocsOpen
{
get { return m_bKeepModifiedDocsOpen; }
}
private readonly string m_szFindWhat;
private readonly string m_szReplaceWith;
private readonly SledFindAndReplaceLookIn m_lookIn;
private readonly string[] m_lookInFolders;
private readonly bool m_bIncludeSubFolders;
private readonly string[] m_fileExts;
private readonly bool m_bMatchCase;
private readonly bool m_bMatchWholeWord;
private readonly SledFindAndReplaceSearchType m_searchType;
private readonly SledFindAndReplaceResultsWindow m_resultsWindow;
private readonly bool m_bKeepModifiedDocsOpen;
#region ICloneable Override
public override object Clone()
{
var obj = new ReplaceInFiles(
m_szFindWhat,
m_szReplaceWith,
m_lookIn,
m_lookInFolders,
m_bIncludeSubFolders,
m_fileExts,
m_bMatchCase,
m_bMatchWholeWord,
m_searchType,
m_resultsWindow,
m_bKeepModifiedDocsOpen);
return obj;
}
#endregion
}
#endregion
}
/// <summary>
/// Static class to hold settings for the find & replace forms that need to be persisted
/// </summary>
static class SledFindAndReplaceSettings
{
public class WordList
{
public WordList(int capacity)
{
m_cap = capacity;
m_lstWhat = new List<string>();
}
public string[] Items
{
get { return m_lstWhat.ToArray(); }
}
public void Add(string item)
{
if (string.IsNullOrEmpty(item))
return;
var idx = m_lstWhat.IndexOf(item);
if (idx != -1)
{
// Item already in list so bump to top
m_lstWhat.RemoveAt(idx);
}
// Add to top
m_lstWhat.Insert(0, item);
// If now over capacity remove last item
if (m_lstWhat.Count > m_cap)
m_lstWhat.RemoveAt(m_lstWhat.Count - 1);
}
public void Clear()
{
m_lstWhat.Clear();
}
private readonly int m_cap;
private readonly List<string> m_lstWhat;
}
public static WordList GlobalFindWhat
{
get { return s_findWhat; }
}
public static WordList GlobalReplaceWith
{
get { return s_replaceWith; }
}
private static readonly WordList s_findWhat = new WordList(20);
private static readonly WordList s_replaceWith = new WordList(20);
#region Quick Find settings
public class QuickFindSettings
{
public int LookInIndex { get; set; }
public bool FindOptionsExpanded { get; set; }
public bool MatchCaseChecked { get; set; }
public bool MatchWholeWordChecked { get; set; }
public bool SearchUpChecked { get; set; }
public bool UseChecked { get; set; }
public int UseIndex { get; set; }
}
public static QuickFindSettings QuickFind
{
get { return s_quickFind; }
}
private static readonly QuickFindSettings s_quickFind = new QuickFindSettings();
#endregion
#region Find in Files settings
public class FindInFilesSettings
{
public int LookInIndex { get; set; }
public bool IncludeSubFolders { get; set; }
public bool FindOptionsExpanded { get; set; }
public bool MatchCaseChecked { get; set; }
public bool MatchWholeWordChecked { get; set; }
public bool UseChecked { get; set; }
public int UseIndex { get; set; }
public bool ResultOptionsExpanded { get; set; }
public bool Results1WindowChecked
{
get { return m_bResults1WindowChecked; }
set { m_bResults1WindowChecked = value; }
}
public bool DisplayFileNamesOnlyChecked { get; set; }
private bool m_bResults1WindowChecked = true;
}
public static FindInFilesSettings FindInFiles
{
get { return s_findInFiles; }
}
private static readonly FindInFilesSettings s_findInFiles = new FindInFilesSettings();
#endregion
#region Quick Replace settings
public class QuickReplaceSettings
{
public int LookInIndex { get; set; }
public bool FindOptionsExpanded { get; set; }
public bool MatchCaseChecked { get; set; }
public bool MatchWholeWordChecked { get; set; }
public bool SearchUpChecked { get; set; }
public bool UseChecked { get; set; }
public int UseIndex { get; set; }
}
public static QuickReplaceSettings QuickReplace
{
get { return s_quickReplace; }
}
private static readonly QuickReplaceSettings s_quickReplace = new QuickReplaceSettings();
#endregion
#region Replace in Files settings
public class ReplaceInFilesSettings
{
public int LookInIndex { get; set; }
public bool IncludeSubFolders { get; set; }
public bool FindOptionsExpanded { get; set; }
public bool MatchCaseChecked { get; set; }
public bool MatchWholeWordChecked { get; set; }
public bool UseChecked { get; set; }
public int UseIndex { get; set; }
public bool ResultOptionsExpanded { get; set; }
public bool Results1WindowChecked
{
get { return m_bResults1WindowChecked; }
set { m_bResults1WindowChecked = value; }
}
public bool DisplayFileNamesOnlyChecked { get; set; }
public bool KeepModifiedFilesOpen { get; set; }
private bool m_bResults1WindowChecked = true;
}
public static ReplaceInFilesSettings ReplaceInFiles
{
get { return s_replaceInFiles; }
}
private static readonly ReplaceInFilesSettings s_replaceInFiles = new ReplaceInFilesSettings();
#endregion
}
}
| |
using System;
using System.ComponentModel;
using Eto.Drawing;
namespace Eto.Forms
{
/// <summary>
/// Control for the user to enter a numeric value
/// </summary>
/// <remarks>
/// This usually presents with a spinner to increase/decrease the value, or a specific numeric keyboard.
/// </remarks>
[Handler(typeof(NumericUpDown.IHandler))]
public class NumericUpDown : CommonControl
{
new IHandler Handler { get { return (IHandler)base.Handler; } }
/// <summary>
/// Occurs when the <see cref="Value"/> changed.
/// </summary>
public event EventHandler<EventArgs> ValueChanged;
/// <summary>
/// Raises the <see cref="ValueChanged"/> event.
/// </summary>
/// <param name="e">Event arguments.</param>
protected virtual void OnValueChanged(EventArgs e)
{
if (ValueChanged != null)
ValueChanged(this, e);
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="Eto.Forms.NumericUpDown"/> is read only.
/// </summary>
/// <remarks>
/// A read only control can copy the value and focus the control, but cannot edit or change the value.
/// </remarks>
/// <value><c>true</c> if the control is read only; otherwise, <c>false</c>.</value>
public bool ReadOnly
{
get { return Handler.ReadOnly; }
set { Handler.ReadOnly = value; }
}
/// <summary>
/// Gets or sets the value.
/// </summary>
/// <remarks>
/// The value will be limited to a value between the <see cref="MinValue"/> and <see cref="MaxValue"/>.
/// </remarks>
/// <value>The value.</value>
public double Value
{
get { return Handler.Value; }
set { Handler.Value = value; }
}
/// <summary>
/// Gets or sets the minimum value that can be entered.
/// </summary>
/// <remarks>
/// Changing this will limit the current <see cref="Value"/> of the control.
/// </remarks>
/// <value>The minimum value.</value>
[DefaultValue(double.MinValue)]
public double MinValue
{
get { return Handler.MinValue; }
set { Handler.MinValue = value; }
}
/// <summary>
/// Gets or sets the maximum value that can be entered.
/// </summary>
/// <remarks>
/// Changing this will limit the current <see cref="Value"/> of the control.
/// </remarks>
/// <value>The maximum value.</value>
[DefaultValue(double.MaxValue)]
public double MaxValue
{
get { return Handler.MaxValue; }
set { Handler.MaxValue = value; }
}
/// <summary>
/// Gets or sets the color of the text.
/// </summary>
/// <remarks>
/// By default, the text will get a color based on the user's theme. However, this is usually black.
/// </remarks>
/// <value>The color of the text.</value>
public Color TextColor
{
get { return Handler.TextColor; }
set { Handler.TextColor = value; }
}
/// <summary>
/// Gets or sets the number of digits to display after the decimal.
/// </summary>
/// <value>The number of decimal places.</value>
public int DecimalPlaces
{
get { return Handler.DecimalPlaces; }
set { Handler.DecimalPlaces = value; }
}
/// <summary>
/// Gets or sets the value to increment when the user clicks on the stepper buttons.
/// </summary>
/// <value>The step increment.</value>
public double Increment
{
get { return Handler.Increment; }
set { Handler.Increment = value; }
}
/// <summary>
/// Gets the binding for the <see cref="Value"/> property.
/// </summary>
/// <value>The value binding.</value>
public BindableBinding<NumericUpDown, double> ValueBinding
{
get
{
return new BindableBinding<NumericUpDown, double>(
this,
c => c.Value,
(c, v) => c.Value = v,
(c, h) => c.ValueChanged += h,
(c, h) => c.ValueChanged -= h
)
{
SettingNullValue = 0
};
}
}
static readonly object callback = new Callback();
/// <summary>
/// Gets an instance of an object used to perform callbacks to the widget from handler implementations
/// </summary>
/// <returns>The callback instance to use for this widget</returns>
protected override object GetCallback()
{
return callback;
}
/// <summary>
/// Callback interface for the <see cref="NumericUpDown"/>
/// </summary>
public new interface ICallback : CommonControl.ICallback
{
/// <summary>
/// Raises the value changed event.
/// </summary>
void OnValueChanged(NumericUpDown widget, EventArgs e);
}
/// <summary>
/// Callback implementation for handlers of the <see cref="NumericUpDown"/>
/// </summary>
protected new class Callback : CommonControl.Callback, ICallback
{
/// <summary>
/// Raises the value changed event.
/// </summary>
public void OnValueChanged(NumericUpDown widget, EventArgs e)
{
widget.Platform.Invoke(() => widget.OnValueChanged(e));
}
}
/// <summary>
/// Handler interface for the <see cref="NumericUpDown"/> control.
/// </summary>
public new interface IHandler : CommonControl.IHandler
{
/// <summary>
/// Gets or sets a value indicating whether this <see cref="Eto.Forms.NumericUpDown"/> is read only.
/// </summary>
/// <remarks>
/// A read only control can copy the value and focus the control, but cannot edit or change the value.
/// </remarks>
/// <value><c>true</c> if the control is read only; otherwise, <c>false</c>.</value>
bool ReadOnly { get; set; }
/// <summary>
/// Gets or sets the value.
/// </summary>
/// <remarks>
/// The value will be limited to a value between the <see cref="MinValue"/> and <see cref="MaxValue"/>.
/// </remarks>
/// <value>The value.</value>
double Value { get; set; }
/// <summary>
/// Gets or sets the minimum value that can be entered.
/// </summary>
/// <remarks>
/// Changing this will limit the current <see cref="Value"/> of the control.
/// </remarks>
/// <value>The minimum value.</value>
double MinValue { get; set; }
/// <summary>
/// Gets or sets the maximum value that can be entered.
/// </summary>
/// <remarks>
/// Changing this will limit the current <see cref="Value"/> of the control.
/// </remarks>
/// <value>The maximum value.</value>
double MaxValue { get; set; }
/// <summary>
/// Gets or sets the number of digits to display after the decimal.
/// </summary>
/// <value>The number of decimal places.</value>
int DecimalPlaces { get; set; }
/// <summary>
/// Gets or sets the value to increment when the user clicks on the stepper buttons.
/// </summary>
/// <value>The step increment.</value>
double Increment { get; set; }
/// <summary>
/// Gets or sets the color of the text.
/// </summary>
/// <remarks>
/// By default, the text will get a color based on the user's theme. However, this is usually black.
/// </remarks>
/// <value>The color of the text.</value>
Color TextColor { get; set; }
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.IO;
using Newtonsoft.Json.Utilities;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Bson
{
/// <summary>
/// Represents a reader that provides fast, non-cached, forward-only access to serialized Json data.
/// </summary>
public class BsonReader : JsonReader
{
private const int MaxCharBytesSize = 128;
private static readonly byte[] SeqRange1 = new byte[] {0, 127}; // range of 1-byte sequence
private static readonly byte[] SeqRange2 = new byte[] {194, 223}; // range of 2-byte sequence
private static readonly byte[] SeqRange3 = new byte[] {224, 239}; // range of 3-byte sequence
private static readonly byte[] SeqRange4 = new byte[] {240, 244}; // range of 4-byte sequence
private readonly BinaryReader _reader;
private readonly List<ContainerContext> _stack;
private byte[] _byteBuffer;
private char[] _charBuffer;
private BsonType _currentElementType;
private BsonReaderState _bsonReaderState;
private ContainerContext _currentContext;
private bool _readRootValueAsArray;
private bool _jsonNet35BinaryCompatibility;
private DateTimeKind _dateTimeKindHandling;
private enum BsonReaderState
{
Normal,
ReferenceStart,
ReferenceRef,
ReferenceId,
CodeWScopeStart,
CodeWScopeCode,
CodeWScopeScope,
CodeWScopeScopeObject,
CodeWScopeScopeEnd
}
private class ContainerContext
{
public readonly BsonType Type;
public int Length;
public int Position;
public ContainerContext(BsonType type)
{
Type = type;
}
}
/// <summary>
/// Gets or sets a value indicating whether binary data reading should compatible with incorrect Json.NET 3.5 written binary.
/// </summary>
/// <value>
/// <c>true</c> if binary data reading will be compatible with incorrect Json.NET 3.5 written binary; otherwise, <c>false</c>.
/// </value>
[Obsolete("JsonNet35BinaryCompatibility will be removed in a future version of Json.NET.")]
public bool JsonNet35BinaryCompatibility
{
get { return _jsonNet35BinaryCompatibility; }
set { _jsonNet35BinaryCompatibility = value; }
}
/// <summary>
/// Gets or sets a value indicating whether the root object will be read as a JSON array.
/// </summary>
/// <value>
/// <c>true</c> if the root object will be read as a JSON array; otherwise, <c>false</c>.
/// </value>
public bool ReadRootValueAsArray
{
get { return _readRootValueAsArray; }
set { _readRootValueAsArray = value; }
}
/// <summary>
/// Gets or sets the <see cref="DateTimeKind" /> used when reading <see cref="DateTime"/> values from BSON.
/// </summary>
/// <value>The <see cref="DateTimeKind" /> used when reading <see cref="DateTime"/> values from BSON.</value>
public DateTimeKind DateTimeKindHandling
{
get { return _dateTimeKindHandling; }
set { _dateTimeKindHandling = value; }
}
/// <summary>
/// Initializes a new instance of the <see cref="BsonReader"/> class.
/// </summary>
/// <param name="stream">The stream.</param>
public BsonReader(Stream stream)
: this(stream, false, DateTimeKind.Local)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BsonReader"/> class.
/// </summary>
/// <param name="reader">The reader.</param>
public BsonReader(BinaryReader reader)
: this(reader, false, DateTimeKind.Local)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BsonReader"/> class.
/// </summary>
/// <param name="stream">The stream.</param>
/// <param name="readRootValueAsArray">if set to <c>true</c> the root object will be read as a JSON array.</param>
/// <param name="dateTimeKindHandling">The <see cref="DateTimeKind" /> used when reading <see cref="DateTime"/> values from BSON.</param>
public BsonReader(Stream stream, bool readRootValueAsArray, DateTimeKind dateTimeKindHandling)
{
ValidationUtils.ArgumentNotNull(stream, "stream");
_reader = new BinaryReader(stream);
_stack = new List<ContainerContext>();
_readRootValueAsArray = readRootValueAsArray;
_dateTimeKindHandling = dateTimeKindHandling;
}
/// <summary>
/// Initializes a new instance of the <see cref="BsonReader"/> class.
/// </summary>
/// <param name="reader">The reader.</param>
/// <param name="readRootValueAsArray">if set to <c>true</c> the root object will be read as a JSON array.</param>
/// <param name="dateTimeKindHandling">The <see cref="DateTimeKind" /> used when reading <see cref="DateTime"/> values from BSON.</param>
public BsonReader(BinaryReader reader, bool readRootValueAsArray, DateTimeKind dateTimeKindHandling)
{
ValidationUtils.ArgumentNotNull(reader, "reader");
_reader = reader;
_stack = new List<ContainerContext>();
_readRootValueAsArray = readRootValueAsArray;
_dateTimeKindHandling = dateTimeKindHandling;
}
private string ReadElement()
{
_currentElementType = ReadType();
string elementName = ReadString();
return elementName;
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="T:Byte[]"/>.
/// </summary>
/// <returns>
/// A <see cref="T:Byte[]"/> or a null reference if the next JSON token is null. This method will return <c>null</c> at the end of an array.
/// </returns>
public override byte[] ReadAsBytes()
{
return ReadAsBytesInternal();
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{Decimal}"/>.
/// </summary>
/// <returns>A <see cref="Nullable{Decimal}"/>. This method will return <c>null</c> at the end of an array.</returns>
public override decimal? ReadAsDecimal()
{
return ReadAsDecimalInternal();
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{Int32}"/>.
/// </summary>
/// <returns>A <see cref="Nullable{Int32}"/>. This method will return <c>null</c> at the end of an array.</returns>
public override int? ReadAsInt32()
{
return ReadAsInt32Internal();
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="String"/>.
/// </summary>
/// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns>
public override string ReadAsString()
{
return ReadAsStringInternal();
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{DateTime}"/>.
/// </summary>
/// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns>
public override DateTime? ReadAsDateTime()
{
return ReadAsDateTimeInternal();
}
#if !NET20
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{DateTimeOffset}"/>.
/// </summary>
/// <returns>
/// A <see cref="Nullable{DateTimeOffset}"/>. This method will return <c>null</c> at the end of an array.
/// </returns>
public override DateTimeOffset? ReadAsDateTimeOffset()
{
return ReadAsDateTimeOffsetInternal();
}
#endif
/// <summary>
/// Reads the next JSON token from the stream.
/// </summary>
/// <returns>
/// true if the next token was read successfully; false if there are no more tokens to read.
/// </returns>
public override bool Read()
{
_readType = Json.ReadType.Read;
return ReadInternal();
}
internal override bool ReadInternal()
{
try
{
bool success;
switch (_bsonReaderState)
{
case BsonReaderState.Normal:
success = ReadNormal();
break;
case BsonReaderState.ReferenceStart:
case BsonReaderState.ReferenceRef:
case BsonReaderState.ReferenceId:
success = ReadReference();
break;
case BsonReaderState.CodeWScopeStart:
case BsonReaderState.CodeWScopeCode:
case BsonReaderState.CodeWScopeScope:
case BsonReaderState.CodeWScopeScopeObject:
case BsonReaderState.CodeWScopeScopeEnd:
success = ReadCodeWScope();
break;
default:
throw JsonReaderException.Create(this, "Unexpected state: {0}".FormatWith(CultureInfo.InvariantCulture, _bsonReaderState));
}
if (!success)
{
SetToken(JsonToken.None);
return false;
}
return true;
}
catch (EndOfStreamException)
{
SetToken(JsonToken.None);
return false;
}
}
/// <summary>
/// Changes the <see cref="JsonReader.State"/> to Closed.
/// </summary>
public override void Close()
{
base.Close();
if (CloseInput && _reader != null)
#if !(NETFX_CORE || PORTABLE40 || PORTABLE)
_reader.Close();
#else
_reader.Dispose();
#endif
}
private bool ReadCodeWScope()
{
switch (_bsonReaderState)
{
case BsonReaderState.CodeWScopeStart:
SetToken(JsonToken.PropertyName, "$code");
_bsonReaderState = BsonReaderState.CodeWScopeCode;
return true;
case BsonReaderState.CodeWScopeCode:
// total CodeWScope size - not used
ReadInt32();
SetToken(JsonToken.String, ReadLengthString());
_bsonReaderState = BsonReaderState.CodeWScopeScope;
return true;
case BsonReaderState.CodeWScopeScope:
if (CurrentState == State.PostValue)
{
SetToken(JsonToken.PropertyName, "$scope");
return true;
}
else
{
SetToken(JsonToken.StartObject);
_bsonReaderState = BsonReaderState.CodeWScopeScopeObject;
ContainerContext newContext = new ContainerContext(BsonType.Object);
PushContext(newContext);
newContext.Length = ReadInt32();
return true;
}
case BsonReaderState.CodeWScopeScopeObject:
bool result = ReadNormal();
if (result && TokenType == JsonToken.EndObject)
_bsonReaderState = BsonReaderState.CodeWScopeScopeEnd;
return result;
case BsonReaderState.CodeWScopeScopeEnd:
SetToken(JsonToken.EndObject);
_bsonReaderState = BsonReaderState.Normal;
return true;
default:
throw new ArgumentOutOfRangeException();
}
}
private bool ReadReference()
{
switch (CurrentState)
{
case State.ObjectStart:
{
SetToken(JsonToken.PropertyName, "$ref");
_bsonReaderState = BsonReaderState.ReferenceRef;
return true;
}
case State.Property:
{
if (_bsonReaderState == BsonReaderState.ReferenceRef)
{
SetToken(JsonToken.String, ReadLengthString());
return true;
}
else if (_bsonReaderState == BsonReaderState.ReferenceId)
{
SetToken(JsonToken.Bytes, ReadBytes(12));
return true;
}
else
{
throw JsonReaderException.Create(this, "Unexpected state when reading BSON reference: " + _bsonReaderState);
}
}
case State.PostValue:
{
if (_bsonReaderState == BsonReaderState.ReferenceRef)
{
SetToken(JsonToken.PropertyName, "$id");
_bsonReaderState = BsonReaderState.ReferenceId;
return true;
}
else if (_bsonReaderState == BsonReaderState.ReferenceId)
{
SetToken(JsonToken.EndObject);
_bsonReaderState = BsonReaderState.Normal;
return true;
}
else
{
throw JsonReaderException.Create(this, "Unexpected state when reading BSON reference: " + _bsonReaderState);
}
}
default:
throw JsonReaderException.Create(this, "Unexpected state when reading BSON reference: " + CurrentState);
}
}
private bool ReadNormal()
{
switch (CurrentState)
{
case State.Start:
{
JsonToken token = (!_readRootValueAsArray) ? JsonToken.StartObject : JsonToken.StartArray;
BsonType type = (!_readRootValueAsArray) ? BsonType.Object : BsonType.Array;
SetToken(token);
ContainerContext newContext = new ContainerContext(type);
PushContext(newContext);
newContext.Length = ReadInt32();
return true;
}
case State.Complete:
case State.Closed:
return false;
case State.Property:
{
ReadType(_currentElementType);
return true;
}
case State.ObjectStart:
case State.ArrayStart:
case State.PostValue:
ContainerContext context = _currentContext;
if (context == null)
return false;
int lengthMinusEnd = context.Length - 1;
if (context.Position < lengthMinusEnd)
{
if (context.Type == BsonType.Array)
{
ReadElement();
ReadType(_currentElementType);
return true;
}
else
{
SetToken(JsonToken.PropertyName, ReadElement());
return true;
}
}
else if (context.Position == lengthMinusEnd)
{
if (ReadByte() != 0)
throw JsonReaderException.Create(this, "Unexpected end of object byte value.");
PopContext();
if (_currentContext != null)
MovePosition(context.Length);
JsonToken endToken = (context.Type == BsonType.Object) ? JsonToken.EndObject : JsonToken.EndArray;
SetToken(endToken);
return true;
}
else
{
throw JsonReaderException.Create(this, "Read past end of current container context.");
}
case State.ConstructorStart:
break;
case State.Constructor:
break;
case State.Error:
break;
case State.Finished:
break;
default:
throw new ArgumentOutOfRangeException();
}
return false;
}
private void PopContext()
{
_stack.RemoveAt(_stack.Count - 1);
if (_stack.Count == 0)
_currentContext = null;
else
_currentContext = _stack[_stack.Count - 1];
}
private void PushContext(ContainerContext newContext)
{
_stack.Add(newContext);
_currentContext = newContext;
}
private byte ReadByte()
{
MovePosition(1);
return _reader.ReadByte();
}
private void ReadType(BsonType type)
{
switch (type)
{
case BsonType.Number:
double d = ReadDouble();
if (_floatParseHandling == FloatParseHandling.Decimal)
SetToken(JsonToken.Float, Convert.ToDecimal(d, CultureInfo.InvariantCulture));
else
SetToken(JsonToken.Float, d);
break;
case BsonType.String:
case BsonType.Symbol:
SetToken(JsonToken.String, ReadLengthString());
break;
case BsonType.Object:
{
SetToken(JsonToken.StartObject);
ContainerContext newContext = new ContainerContext(BsonType.Object);
PushContext(newContext);
newContext.Length = ReadInt32();
break;
}
case BsonType.Array:
{
SetToken(JsonToken.StartArray);
ContainerContext newContext = new ContainerContext(BsonType.Array);
PushContext(newContext);
newContext.Length = ReadInt32();
break;
}
case BsonType.Binary:
SetToken(JsonToken.Bytes, ReadBinary());
break;
case BsonType.Undefined:
SetToken(JsonToken.Undefined);
break;
case BsonType.Oid:
byte[] oid = ReadBytes(12);
SetToken(JsonToken.Bytes, oid);
break;
case BsonType.Boolean:
bool b = Convert.ToBoolean(ReadByte());
SetToken(JsonToken.Boolean, b);
break;
case BsonType.Date:
long ticks = ReadInt64();
DateTime utcDateTime = DateTimeUtils.ConvertJavaScriptTicksToDateTime(ticks);
DateTime dateTime;
switch (DateTimeKindHandling)
{
case DateTimeKind.Unspecified:
dateTime = DateTime.SpecifyKind(utcDateTime, DateTimeKind.Unspecified);
break;
case DateTimeKind.Local:
dateTime = utcDateTime.ToLocalTime();
break;
default:
dateTime = utcDateTime;
break;
}
SetToken(JsonToken.Date, dateTime);
break;
case BsonType.Null:
SetToken(JsonToken.Null);
break;
case BsonType.Regex:
string expression = ReadString();
string modifiers = ReadString();
string regex = @"/" + expression + @"/" + modifiers;
SetToken(JsonToken.String, regex);
break;
case BsonType.Reference:
SetToken(JsonToken.StartObject);
_bsonReaderState = BsonReaderState.ReferenceStart;
break;
case BsonType.Code:
SetToken(JsonToken.String, ReadLengthString());
break;
case BsonType.CodeWScope:
SetToken(JsonToken.StartObject);
_bsonReaderState = BsonReaderState.CodeWScopeStart;
break;
case BsonType.Integer:
SetToken(JsonToken.Integer, (long) ReadInt32());
break;
case BsonType.TimeStamp:
case BsonType.Long:
SetToken(JsonToken.Integer, ReadInt64());
break;
default:
throw new ArgumentOutOfRangeException("type", "Unexpected BsonType value: " + type);
}
}
private byte[] ReadBinary()
{
int dataLength = ReadInt32();
BsonBinaryType binaryType = (BsonBinaryType) ReadByte();
#pragma warning disable 612,618
// the old binary type has the data length repeated in the data for some reason
if (binaryType == BsonBinaryType.BinaryOld && !_jsonNet35BinaryCompatibility)
{
dataLength = ReadInt32();
}
#pragma warning restore 612,618
return ReadBytes(dataLength);
}
private string ReadString()
{
EnsureBuffers();
StringBuilder builder = null;
int totalBytesRead = 0;
// used in case of left over multibyte characters in the buffer
int offset = 0;
do
{
int count = offset;
byte b;
while (count < MaxCharBytesSize && (b = _reader.ReadByte()) > 0)
{
_byteBuffer[count++] = b;
}
int byteCount = count - offset;
totalBytesRead += byteCount;
if (count < MaxCharBytesSize && builder == null)
{
// pref optimization to avoid reading into a string builder
// if string is smaller than the buffer then return it directly
int length = Encoding.UTF8.GetChars(_byteBuffer, 0, byteCount, _charBuffer, 0);
MovePosition(totalBytesRead + 1);
return new string(_charBuffer, 0, length);
}
else
{
// calculate the index of the end of the last full character in the buffer
int lastFullCharStop = GetLastFullCharStop(count - 1);
int charCount = Encoding.UTF8.GetChars(_byteBuffer, 0, lastFullCharStop + 1, _charBuffer, 0);
if (builder == null)
builder = new StringBuilder(MaxCharBytesSize*2);
builder.Append(_charBuffer, 0, charCount);
if (lastFullCharStop < byteCount - 1)
{
offset = byteCount - lastFullCharStop - 1;
// copy left over multi byte characters to beginning of buffer for next iteration
Array.Copy(_byteBuffer, lastFullCharStop + 1, _byteBuffer, 0, offset);
}
else
{
// reached end of string
if (count < MaxCharBytesSize)
{
MovePosition(totalBytesRead + 1);
return builder.ToString();
}
offset = 0;
}
}
} while (true);
}
private string ReadLengthString()
{
int length = ReadInt32();
MovePosition(length);
string s = GetString(length - 1);
_reader.ReadByte();
return s;
}
private string GetString(int length)
{
if (length == 0)
return string.Empty;
EnsureBuffers();
StringBuilder builder = null;
int totalBytesRead = 0;
// used in case of left over multibyte characters in the buffer
int offset = 0;
do
{
int count = ((length - totalBytesRead) > MaxCharBytesSize - offset)
? MaxCharBytesSize - offset
: length - totalBytesRead;
int byteCount = _reader.Read(_byteBuffer, offset, count);
if (byteCount == 0)
throw new EndOfStreamException("Unable to read beyond the end of the stream.");
totalBytesRead += byteCount;
// Above, byteCount is how many bytes we read this time.
// Below, byteCount is how many bytes are in the _byteBuffer.
byteCount += offset;
if (byteCount == length)
{
// pref optimization to avoid reading into a string builder
// first iteration and all bytes read then return string directly
int charCount = Encoding.UTF8.GetChars(_byteBuffer, 0, byteCount, _charBuffer, 0);
return new string(_charBuffer, 0, charCount);
}
else
{
int lastFullCharStop = GetLastFullCharStop(byteCount - 1);
if (builder == null)
builder = new StringBuilder(length);
int charCount = Encoding.UTF8.GetChars(_byteBuffer, 0, lastFullCharStop + 1, _charBuffer, 0);
builder.Append(_charBuffer, 0, charCount);
if (lastFullCharStop < byteCount - 1)
{
offset = byteCount - lastFullCharStop - 1;
// copy left over multi byte characters to beginning of buffer for next iteration
Array.Copy(_byteBuffer, lastFullCharStop + 1, _byteBuffer, 0, offset);
}
else
{
offset = 0;
}
}
} while (totalBytesRead < length);
return builder.ToString();
}
private int GetLastFullCharStop(int start)
{
int lookbackPos = start;
int bis = 0;
while (lookbackPos >= 0)
{
bis = BytesInSequence(_byteBuffer[lookbackPos]);
if (bis == 0)
{
lookbackPos--;
continue;
}
else if (bis == 1)
{
break;
}
else
{
lookbackPos--;
break;
}
}
if (bis == start - lookbackPos)
{
//Full character.
return start;
}
else
{
return lookbackPos;
}
}
private int BytesInSequence(byte b)
{
if (b <= SeqRange1[1]) return 1;
if (b >= SeqRange2[0] && b <= SeqRange2[1]) return 2;
if (b >= SeqRange3[0] && b <= SeqRange3[1]) return 3;
if (b >= SeqRange4[0] && b <= SeqRange4[1]) return 4;
return 0;
}
private void EnsureBuffers()
{
if (_byteBuffer == null)
{
_byteBuffer = new byte[MaxCharBytesSize];
}
if (_charBuffer == null)
{
int charBufferSize = Encoding.UTF8.GetMaxCharCount(MaxCharBytesSize);
_charBuffer = new char[charBufferSize];
}
}
private double ReadDouble()
{
MovePosition(8);
return _reader.ReadDouble();
}
private int ReadInt32()
{
MovePosition(4);
return _reader.ReadInt32();
}
private long ReadInt64()
{
MovePosition(8);
return _reader.ReadInt64();
}
private BsonType ReadType()
{
MovePosition(1);
return (BsonType) _reader.ReadSByte();
}
private void MovePosition(int count)
{
_currentContext.Position += count;
}
private byte[] ReadBytes(int count)
{
MovePosition(count);
return _reader.ReadBytes(count);
}
}
}
| |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Infoplus.Model
{
/// <summary>
///
/// </summary>
[DataContract]
public partial class ReceivingProcess : IEquatable<ReceivingProcess>
{
/// <summary>
/// Initializes a new instance of the <see cref="ReceivingProcess" /> class.
/// Initializes a new instance of the <see cref="ReceivingProcess" />class.
/// </summary>
/// <param name="WarehouseId">WarehouseId (required).</param>
/// <param name="Status">Status (required).</param>
/// <param name="WorkBatchId">WorkBatchId.</param>
/// <param name="ReceivingWorksheetId">ReceivingWorksheetId.</param>
/// <param name="CustomFields">CustomFields.</param>
public ReceivingProcess(int? WarehouseId = null, string Status = null, int? WorkBatchId = null, int? ReceivingWorksheetId = null, Dictionary<string, Object> CustomFields = null)
{
// to ensure "WarehouseId" is required (not null)
if (WarehouseId == null)
{
throw new InvalidDataException("WarehouseId is a required property for ReceivingProcess and cannot be null");
}
else
{
this.WarehouseId = WarehouseId;
}
// to ensure "Status" is required (not null)
if (Status == null)
{
throw new InvalidDataException("Status is a required property for ReceivingProcess and cannot be null");
}
else
{
this.Status = Status;
}
this.WorkBatchId = WorkBatchId;
this.ReceivingWorksheetId = ReceivingWorksheetId;
this.CustomFields = CustomFields;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=false)]
public int? Id { get; private set; }
/// <summary>
/// Gets or Sets WarehouseId
/// </summary>
[DataMember(Name="warehouseId", EmitDefaultValue=false)]
public int? WarehouseId { get; set; }
/// <summary>
/// Gets or Sets Status
/// </summary>
[DataMember(Name="status", EmitDefaultValue=false)]
public string Status { get; set; }
/// <summary>
/// Gets or Sets WorkBatchId
/// </summary>
[DataMember(Name="workBatchId", EmitDefaultValue=false)]
public int? WorkBatchId { get; set; }
/// <summary>
/// Gets or Sets ReceivingWorksheetId
/// </summary>
[DataMember(Name="receivingWorksheetId", EmitDefaultValue=false)]
public int? ReceivingWorksheetId { get; set; }
/// <summary>
/// Gets or Sets CreateDate
/// </summary>
[DataMember(Name="createDate", EmitDefaultValue=false)]
public DateTime? CreateDate { get; private set; }
/// <summary>
/// Gets or Sets ModifyDate
/// </summary>
[DataMember(Name="modifyDate", EmitDefaultValue=false)]
public DateTime? ModifyDate { get; private set; }
/// <summary>
/// Gets or Sets CustomFields
/// </summary>
[DataMember(Name="customFields", EmitDefaultValue=false)]
public Dictionary<string, Object> CustomFields { 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 ReceivingProcess {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" WarehouseId: ").Append(WarehouseId).Append("\n");
sb.Append(" Status: ").Append(Status).Append("\n");
sb.Append(" WorkBatchId: ").Append(WorkBatchId).Append("\n");
sb.Append(" ReceivingWorksheetId: ").Append(ReceivingWorksheetId).Append("\n");
sb.Append(" CreateDate: ").Append(CreateDate).Append("\n");
sb.Append(" ModifyDate: ").Append(ModifyDate).Append("\n");
sb.Append(" CustomFields: ").Append(CustomFields).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 ReceivingProcess);
}
/// <summary>
/// Returns true if ReceivingProcess instances are equal
/// </summary>
/// <param name="other">Instance of ReceivingProcess to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ReceivingProcess other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.WarehouseId == other.WarehouseId ||
this.WarehouseId != null &&
this.WarehouseId.Equals(other.WarehouseId)
) &&
(
this.Status == other.Status ||
this.Status != null &&
this.Status.Equals(other.Status)
) &&
(
this.WorkBatchId == other.WorkBatchId ||
this.WorkBatchId != null &&
this.WorkBatchId.Equals(other.WorkBatchId)
) &&
(
this.ReceivingWorksheetId == other.ReceivingWorksheetId ||
this.ReceivingWorksheetId != null &&
this.ReceivingWorksheetId.Equals(other.ReceivingWorksheetId)
) &&
(
this.CreateDate == other.CreateDate ||
this.CreateDate != null &&
this.CreateDate.Equals(other.CreateDate)
) &&
(
this.ModifyDate == other.ModifyDate ||
this.ModifyDate != null &&
this.ModifyDate.Equals(other.ModifyDate)
) &&
(
this.CustomFields == other.CustomFields ||
this.CustomFields != null &&
this.CustomFields.SequenceEqual(other.CustomFields)
);
}
/// <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.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.WarehouseId != null)
hash = hash * 59 + this.WarehouseId.GetHashCode();
if (this.Status != null)
hash = hash * 59 + this.Status.GetHashCode();
if (this.WorkBatchId != null)
hash = hash * 59 + this.WorkBatchId.GetHashCode();
if (this.ReceivingWorksheetId != null)
hash = hash * 59 + this.ReceivingWorksheetId.GetHashCode();
if (this.CreateDate != null)
hash = hash * 59 + this.CreateDate.GetHashCode();
if (this.ModifyDate != null)
hash = hash * 59 + this.ModifyDate.GetHashCode();
if (this.CustomFields != null)
hash = hash * 59 + this.CustomFields.GetHashCode();
return hash;
}
}
}
}
| |
// 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.Metadata.ManagedReference
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.MSBuild;
using Microsoft.DotNet.ProjectModel.Workspaces;
using Microsoft.DocAsCode.Common;
using Microsoft.DocAsCode.DataContracts.Common;
using Microsoft.DocAsCode.DataContracts.ManagedReference;
using Microsoft.DocAsCode.Exceptions;
public sealed class ExtractMetadataWorker : IDisposable
{
private const string XmlCommentFileExtension = "xml";
private readonly Dictionary<FileType, List<FileInformation>> _files;
private readonly bool _rebuild;
private readonly bool _shouldSkipMarkup;
private readonly bool _preserveRawInlineComments;
private readonly bool _useCompatibilityFileName;
private readonly string _filterConfigFile;
private readonly string _outputFolder;
private readonly Dictionary<string, string> _msbuildProperties;
//Lacks UT for shared workspace
private readonly Lazy<MSBuildWorkspace> _workspace;
internal const string IndexFileName = ".manifest";
public ExtractMetadataWorker(ExtractMetadataInputModel input)
{
if (input == null)
{
throw new ArgumentNullException(nameof(input));
}
if (string.IsNullOrEmpty(input.OutputFolder))
{
throw new ArgumentNullException(nameof(input.OutputFolder), "Output folder must be specified");
}
_files = input.Files?.Select(s => new FileInformation(s))
.GroupBy(f => f.Type)
.ToDictionary(s => s.Key, s => s.Distinct().ToList());
_rebuild = input.ForceRebuild;
_shouldSkipMarkup = input.ShouldSkipMarkup;
_preserveRawInlineComments = input.PreserveRawInlineComments;
_useCompatibilityFileName = input.UseCompatibilityFileName;
_outputFolder = input.OutputFolder;
if (input.FilterConfigFile != null)
{
_filterConfigFile = new FileInformation(input.FilterConfigFile).NormalizedPath;
}
_msbuildProperties = input.MSBuildProperties ?? new Dictionary<string, string>();
if (!_msbuildProperties.ContainsKey("Configuration"))
{
_msbuildProperties["Configuration"] = "Release";
}
_workspace = new Lazy<MSBuildWorkspace>(() =>
{
var workspace = MSBuildWorkspace.Create(_msbuildProperties);
workspace.WorkspaceFailed += (s, e) =>
{
Logger.LogWarning($"Workspace failed with: {e.Diagnostic}");
};
return workspace;
});
}
public async Task ExtractMetadataAsync()
{
if (_files == null || _files.Count == 0)
{
Logger.Log(LogLevel.Warning, "No project detected for extracting metadata.");
return;
}
try
{
if (_files.TryGetValue(FileType.NotSupported, out List<FileInformation> unsupportedFiles))
{
Logger.LogWarning($"Projects {GetPrintableFileList(unsupportedFiles)} are not supported");
}
await SaveAllMembersFromCacheAsync();
}
catch (AggregateException e)
{
throw new ExtractMetadataException($"Error extracting metadata for {GetPrintableFileList(_files.SelectMany(s => s.Value))}: {e.GetBaseException()?.Message}", e);
}
catch (Exception e)
{
var files = GetPrintableFileList(_files.SelectMany(s => s.Value));
throw new ExtractMetadataException($"Error extracting metadata for {files}: {e.Message}", e);
}
}
public void Dispose()
{
}
#region Internal For UT
internal static MetadataItem GenerateYamlMetadata(Compilation compilation, IAssemblySymbol assembly = null, bool preserveRawInlineComments = false, string filterConfigFile = null, IReadOnlyDictionary<Compilation, IEnumerable<IMethodSymbol>> extensionMethods = null)
{
if (compilation == null)
{
return null;
}
var options = new ExtractMetadataOptions
{
PreserveRawInlineComments = preserveRawInlineComments,
FilterConfigFile = filterConfigFile,
ExtensionMethods = extensionMethods,
};
return new MetadataExtractor(compilation, assembly).Extract(options);
}
internal static IReadOnlyDictionary<Compilation, IEnumerable<IMethodSymbol>> GetAllExtensionMethodsFromCompilation(IEnumerable<Compilation> compilations)
{
var methods = new Dictionary<Compilation, IEnumerable<IMethodSymbol>>();
foreach (var compilation in compilations)
{
if (compilation.Assembly.MightContainExtensionMethods)
{
var extensions = (from n in GetAllNamespaceMembers(compilation.Assembly).Distinct()
from m in GetExtensionMethodPerNamespace(n)
select m).ToList();
if (extensions.Count > 0)
{
methods[compilation] = extensions;
}
}
}
return methods;
}
internal static IReadOnlyDictionary<Compilation, IEnumerable<IMethodSymbol>> GetAllExtensionMethodsFromAssembly(Compilation compilation, IEnumerable<IAssemblySymbol> assemblies)
{
var methods = new Dictionary<Compilation, IEnumerable<IMethodSymbol>>();
foreach (var assembly in assemblies)
{
if (assembly.MightContainExtensionMethods)
{
var extensions = (from n in GetAllNamespaceMembers(assembly).Distinct()
from m in GetExtensionMethodPerNamespace(n)
select m).ToList();
if (extensions.Count > 0)
{
if (methods.TryGetValue(compilation, out IEnumerable<IMethodSymbol> ext))
{
methods[compilation] = ext.Union(extensions);
}
else
{
methods[compilation] = extensions;
}
}
}
}
return methods;
}
#endregion
#region Private
private async Task SaveAllMembersFromCacheAsync()
{
var forceRebuild = _rebuild;
var outputFolder = _outputFolder;
var projectCache = new ConcurrentDictionary<string, Project>();
// Project<=>Documents
var documentCache = new ProjectDocumentCache();
var projectDependencyGraph = new ConcurrentDictionary<string, List<string>>();
DateTime triggeredTime = DateTime.UtcNow;
// Exclude not supported files from inputs
var cacheKey = GetCacheKey(_files.SelectMany(s => s.Value));
// Add filter config file into inputs and cache
if (!string.IsNullOrEmpty(_filterConfigFile))
{
cacheKey = cacheKey.Concat(new string[] { _filterConfigFile });
documentCache.AddDocument(_filterConfigFile, _filterConfigFile);
}
if (_files.TryGetValue(FileType.Solution, out var sln))
{
var solutions = sln.Select(s => s.NormalizedPath);
// No matter is incremental or not, we have to load solutions into memory
foreach (var path in solutions)
{
documentCache.AddDocument(path, path);
var solution = await GetSolutionAsync(path);
if (solution != null)
{
foreach (var project in solution.Projects)
{
var projectFile = new FileInformation(project.FilePath);
// If the project is csproj/vbproj, add to project dictionary, otherwise, ignore
if (projectFile.IsSupportedProject())
{
projectCache.GetOrAdd(projectFile.NormalizedPath, s => project);
}
else
{
Logger.LogWarning($"Project {projectFile.RawPath} inside solution {path} is ignored, supported projects are csproj and vbproj.");
}
}
}
}
}
if (_files.TryGetValue(FileType.Project, out var p))
{
foreach (var pp in p)
{
GetProject(projectCache, pp.NormalizedPath);
}
}
if (_files.TryGetValue(FileType.ProjectJsonProject, out var pjp))
{
await pjp.Select(s => s.NormalizedPath).ForEachInParallelAsync(path =>
{
projectCache.GetOrAdd(path, s => GetProjectJsonProject(s));
return Task.CompletedTask;
}, 60);
}
foreach (var item in projectCache)
{
var path = item.Key;
var project = item.Value;
documentCache.AddDocument(path, path);
if (project.HasDocuments)
{
documentCache.AddDocuments(path, project.Documents.Select(s => s.FilePath));
}
else
{
Logger.Log(LogLevel.Warning, $"Project '{project.FilePath}' does not contain any documents.");
}
documentCache.AddDocuments(path, project.MetadataReferences
.Where(s => s is PortableExecutableReference)
.Select(s => ((PortableExecutableReference)s).FilePath));
FillProjectDependencyGraph(projectCache, projectDependencyGraph, project);
// duplicate project references will fail Project.GetCompilationAsync
var groups = project.ProjectReferences.GroupBy(r => r);
if (groups.Any(g => g.Count() > 1))
{
projectCache[path] = project.WithProjectReferences(groups.Select(g => g.Key));
}
}
var csFiles = new List<string>();
var vbFiles = new List<string>();
var assemblyFiles = new List<string>();
if (_files.TryGetValue(FileType.CSSourceCode, out var cs))
{
csFiles.AddRange(cs.Select(s => s.NormalizedPath));
documentCache.AddDocuments(csFiles);
}
if (_files.TryGetValue(FileType.VBSourceCode, out var vb))
{
vbFiles.AddRange(vb.Select(s => s.NormalizedPath));
documentCache.AddDocuments(vbFiles);
}
if (_files.TryGetValue(FileType.Assembly, out var asm))
{
assemblyFiles.AddRange(asm.Select(s => s.NormalizedPath));
documentCache.AddDocuments(assemblyFiles);
}
// Incremental check for inputs as a whole:
var applicationCache = ApplicationLevelCache.Get(cacheKey);
if (!forceRebuild)
{
var buildInfo = applicationCache.GetValidConfig(cacheKey);
if (buildInfo != null && buildInfo.ShouldSkipMarkup == _shouldSkipMarkup)
{
IncrementalCheck check = new IncrementalCheck(buildInfo);
// 1. Check if sln files/ project files and its contained documents/ source files are modified
var projectModified = check.AreFilesModified(documentCache.Documents) || check.MSBuildPropertiesUpdated(_msbuildProperties);
if (!projectModified)
{
// 2. Check if documents/ assembly references are changed in a project
// e.g. <Compile Include="*.cs* /> and file added/deleted
foreach (var project in projectCache.Values)
{
var key = StringExtension.ToNormalizedFullPath(project.FilePath);
IEnumerable<string> currentContainedFiles = documentCache.GetDocuments(project.FilePath);
var previousDocumentCache = new ProjectDocumentCache(buildInfo.ContainedFiles);
IEnumerable<string> previousContainedFiles = previousDocumentCache.GetDocuments(project.FilePath);
if (previousContainedFiles != null && currentContainedFiles != null)
{
projectModified = !previousContainedFiles.SequenceEqual(currentContainedFiles);
}
else
{
// When one of them is not null, project is modified
if (!object.Equals(previousContainedFiles, currentContainedFiles))
{
projectModified = true;
}
}
if (projectModified) break;
}
}
if (!projectModified)
{
// Nothing modified, use the result in cache
try
{
CopyFromCachedResult(buildInfo, cacheKey, outputFolder);
return;
}
catch (Exception e)
{
Logger.Log(LogLevel.Warning, $"Unable to copy results from cache: {e.Message}. Rebuild starts.");
}
}
}
}
// Build all the projects to get the output and save to cache
List<MetadataItem> projectMetadataList = new List<MetadataItem>();
ConcurrentDictionary<string, bool> projectRebuildInfo = new ConcurrentDictionary<string, bool>();
ConcurrentDictionary<string, Compilation> compilationCache = await GetProjectCompilationAsync(projectCache);
var extensionMethods = GetAllExtensionMethodsFromCompilation(compilationCache.Values);
foreach (var key in GetTopologicalSortedItems(projectDependencyGraph))
{
var dependencyRebuilt = projectDependencyGraph[key].Any(r => projectRebuildInfo[r]);
var projectMetadataResult = await GetProjectMetadataFromCacheAsync(projectCache[key], compilationCache[key], outputFolder, documentCache, forceRebuild, _shouldSkipMarkup, _preserveRawInlineComments, _filterConfigFile, extensionMethods, dependencyRebuilt);
var projectMetadata = projectMetadataResult.Item1;
if (projectMetadata != null) projectMetadataList.Add(projectMetadata);
projectRebuildInfo[key] = projectMetadataResult.Item2;
}
if (csFiles.Count > 0)
{
var csContent = string.Join(Environment.NewLine, csFiles.Select(s => File.ReadAllText(s)));
var csCompilation = CompilationUtility.CreateCompilationFromCsharpCode(csContent);
if (csCompilation != null)
{
var csMetadata = await GetFileMetadataFromCacheAsync(csFiles, csCompilation, outputFolder, forceRebuild, _shouldSkipMarkup, _preserveRawInlineComments, _filterConfigFile, extensionMethods);
if (csMetadata != null) projectMetadataList.Add(csMetadata.Item1);
}
}
if (vbFiles.Count > 0)
{
var vbContent = string.Join(Environment.NewLine, vbFiles.Select(s => File.ReadAllText(s)));
var vbCompilation = CompilationUtility.CreateCompilationFromVBCode(vbContent);
if (vbCompilation != null)
{
var vbMetadata = await GetFileMetadataFromCacheAsync(vbFiles, vbCompilation, outputFolder, forceRebuild, _preserveRawInlineComments, _shouldSkipMarkup, _filterConfigFile, extensionMethods);
if (vbMetadata != null) projectMetadataList.Add(vbMetadata.Item1);
}
}
if (assemblyFiles.Count > 0)
{
var assemblyCompilation = CompilationUtility.CreateCompilationFromAssembly(assemblyFiles);
if (assemblyCompilation != null)
{
var commentFiles = (from file in assemblyFiles
select Path.ChangeExtension(file, XmlCommentFileExtension) into xmlFile
where File.Exists(xmlFile)
select xmlFile).ToList();
var referencedAssemblyList = CompilationUtility.GetAssemblyFromAssemblyComplation(assemblyCompilation).ToList();
var assemblyExtension = GetAllExtensionMethodsFromAssembly(assemblyCompilation, referencedAssemblyList.Select(s => s.Item2));
foreach (var assembly in referencedAssemblyList)
{
var mta = await GetAssemblyMetadataFromCacheAsync(new string[] { assembly.Item1.Display }, assemblyCompilation, assembly.Item2, outputFolder, forceRebuild, _filterConfigFile, assemblyExtension);
if (mta != null)
{
MergeCommentsHelper.MergeComments(mta.Item1, commentFiles);
projectMetadataList.Add(mta.Item1);
}
}
}
}
var allMemebers = MergeYamlProjectMetadata(projectMetadataList);
var allReferences = MergeYamlProjectReferences(projectMetadataList);
if (allMemebers == null || allMemebers.Count == 0)
{
var value = StringExtension.ToDelimitedString(projectMetadataList.Select(s => s.Name));
Logger.Log(LogLevel.Warning, $"No metadata is generated for {value}.");
applicationCache.SaveToCache(cacheKey, null, triggeredTime, outputFolder, null, _shouldSkipMarkup, _msbuildProperties);
}
else
{
// TODO: need an intermediate folder? when to clean it up?
// Save output to output folder
var outputFiles = ResolveAndExportYamlMetadata(allMemebers, allReferences, outputFolder, _preserveRawInlineComments, _shouldSkipMarkup, _useCompatibilityFileName).ToList();
applicationCache.SaveToCache(cacheKey, documentCache.Cache, triggeredTime, outputFolder, outputFiles, _shouldSkipMarkup, _msbuildProperties);
}
}
private static void FillProjectDependencyGraph(ConcurrentDictionary<string, Project> projectCache, ConcurrentDictionary<string, List<string>> projectDependencyGraph, Project project)
{
projectDependencyGraph.GetOrAdd(project.FilePath.ToNormalizedFullPath(), _ => GetTransitiveProjectReferences(projectCache, project).Distinct().ToList());
}
private static IEnumerable<string> GetTransitiveProjectReferences(ConcurrentDictionary<string, Project> projectCache, Project project)
{
var solution = project.Solution;
foreach (var pr in project.ProjectReferences)
{
var refProject = solution.GetProject(pr.ProjectId);
var path = StringExtension.ToNormalizedFullPath(refProject.FilePath);
if (projectCache.ContainsKey(path))
{
yield return path;
}
else
{
foreach (var rpr in GetTransitiveProjectReferences(projectCache, refProject))
{
yield return rpr;
}
}
}
}
private static async Task<ConcurrentDictionary<string, Compilation>> GetProjectCompilationAsync(ConcurrentDictionary<string, Project> projectCache)
{
var compilations = new ConcurrentDictionary<string, Compilation>();
var sb = new StringBuilder();
foreach (var project in projectCache)
{
try
{
var compilation = await project.Value.GetCompilationAsync();
compilations.TryAdd(project.Key, compilation);
}
catch (Exception e)
{
if (sb.Length > 0)
{
sb.AppendLine();
}
sb.Append($"Error extracting metadata for project \"{project.Key}\": {e.Message}");
}
}
if (sb.Length > 0)
{
throw new ExtractMetadataException(sb.ToString());
}
return compilations;
}
private static IEnumerable<IMethodSymbol> GetExtensionMethodPerNamespace(INamespaceSymbol space)
{
var typesWithExtensionMethods = space.GetTypeMembers().Where(t => t.MightContainExtensionMethods);
foreach (var type in typesWithExtensionMethods)
{
var members = type.GetMembers();
foreach (var member in members)
{
if (member.Kind == SymbolKind.Method)
{
var method = (IMethodSymbol)member;
if (method.IsExtensionMethod)
{
yield return method;
}
}
}
}
}
private static IEnumerable<INamespaceSymbol> GetAllNamespaceMembers(IAssemblySymbol assembly)
{
var queue = new Queue<INamespaceSymbol>();
queue.Enqueue(assembly.GlobalNamespace);
while (queue.Count > 0)
{
var space = queue.Dequeue();
yield return space;
var childSpaces = space.GetNamespaceMembers();
foreach (var child in childSpaces)
{
queue.Enqueue(child);
}
}
}
private static void CopyFromCachedResult(BuildInfo buildInfo, IEnumerable<string> inputs, string outputFolder)
{
var outputFolderSource = buildInfo.OutputFolder;
var relativeFiles = buildInfo.RelatvieOutputFiles;
if (relativeFiles == null)
{
Logger.Log(LogLevel.Warning, $"No metadata is generated for '{StringExtension.ToDelimitedString(inputs)}'.");
return;
}
Logger.Log(LogLevel.Info, $"'{StringExtension.ToDelimitedString(inputs)}' keep up-to-date since '{buildInfo.TriggeredUtcTime.ToString()}', cached result from '{buildInfo.OutputFolder}' is used.");
PathUtility.CopyFilesToFolder(relativeFiles.Select(s => Path.Combine(outputFolderSource, s)), outputFolderSource, outputFolder, true, s => Logger.Log(LogLevel.Info, s), null);
}
private Task<Tuple<MetadataItem, bool>> GetProjectMetadataFromCacheAsync(Project project, Compilation compilation, string outputFolder, ProjectDocumentCache documentCache, bool forceRebuild, bool shouldSkipMarkup, bool preserveRawInlineComments, string filterConfigFile, IReadOnlyDictionary<Compilation, IEnumerable<IMethodSymbol>> extensionMethods, bool isReferencedProjectRebuilt)
{
var projectFilePath = project.FilePath;
var k = documentCache.GetDocuments(projectFilePath);
return GetMetadataFromProjectLevelCacheAsync(
project,
new[] { projectFilePath, filterConfigFile },
s => Task.FromResult(forceRebuild || s.AreFilesModified(k.Concat(new string[] { filterConfigFile })) || isReferencedProjectRebuilt || s.MSBuildPropertiesUpdated(_msbuildProperties)),
s => Task.FromResult(compilation),
s => Task.FromResult(compilation.Assembly),
s =>
{
return new Dictionary<string, List<string>> { { StringExtension.ToNormalizedFullPath(s.FilePath), k.ToList() } };
},
outputFolder,
preserveRawInlineComments,
shouldSkipMarkup,
filterConfigFile,
extensionMethods);
}
private Task<Tuple<MetadataItem, bool>> GetAssemblyMetadataFromCacheAsync(IEnumerable<string> files, Compilation compilation, IAssemblySymbol assembly, string outputFolder, bool forceRebuild, string filterConfigFile, IReadOnlyDictionary<Compilation, IEnumerable<IMethodSymbol>> extensionMethods)
{
if (files == null || !files.Any()) return null;
return GetMetadataFromProjectLevelCacheAsync(
files,
files.Concat(new string[] { filterConfigFile }), s => Task.FromResult(forceRebuild || s.AreFilesModified(files.Concat(new string[] { filterConfigFile }))),
s => Task.FromResult(compilation),
s => Task.FromResult(assembly),
s => null,
outputFolder,
false,
false,
filterConfigFile,
extensionMethods);
}
private Task<Tuple<MetadataItem, bool>> GetFileMetadataFromCacheAsync(IEnumerable<string> files, Compilation compilation, string outputFolder, bool forceRebuild, bool shouldSkipMarkup, bool preserveRawInlineComments, string filterConfigFile, IReadOnlyDictionary<Compilation, IEnumerable<IMethodSymbol>> extensionMethods)
{
if (files == null || !files.Any()) return null;
return GetMetadataFromProjectLevelCacheAsync(
files,
files.Concat(new string[] { filterConfigFile }), s => Task.FromResult(forceRebuild || s.AreFilesModified(files.Concat(new string[] { filterConfigFile })) || s.MSBuildPropertiesUpdated(_msbuildProperties)),
s => Task.FromResult(compilation),
s => Task.FromResult(compilation.Assembly),
s => null,
outputFolder,
preserveRawInlineComments,
shouldSkipMarkup,
filterConfigFile,
extensionMethods);
}
private async Task<Tuple<MetadataItem, bool>> GetMetadataFromProjectLevelCacheAsync<T>(
T input,
IEnumerable<string> inputKey,
Func<IncrementalCheck, Task<bool>> rebuildChecker,
Func<T, Task<Compilation>> compilationProvider,
Func<T, Task<IAssemblySymbol>> assemblyProvider,
Func<T, IDictionary<string, List<string>>> containedFilesProvider,
string outputFolder,
bool preserveRawInlineComments,
bool shouldSkipMarkup,
string filterConfigFile,
IReadOnlyDictionary<Compilation, IEnumerable<IMethodSymbol>> extensionMethods)
{
DateTime triggeredTime = DateTime.UtcNow;
var projectLevelCache = ProjectLevelCache.Get(inputKey);
var projectConfig = projectLevelCache.GetValidConfig(inputKey);
var rebuildProject = true;
if (projectConfig != null)
{
var projectCheck = new IncrementalCheck(projectConfig);
rebuildProject = await rebuildChecker(projectCheck);
}
MetadataItem projectMetadata;
if (!rebuildProject)
{
// Load from cache
var cacheFile = Path.Combine(projectConfig.OutputFolder, projectConfig.RelatvieOutputFiles.First());
Logger.Log(LogLevel.Info, $"'{projectConfig.InputFilesKey}' keep up-to-date since '{projectConfig.TriggeredUtcTime.ToString()}', cached intermediate result '{cacheFile}' is used.");
if (TryParseYamlMetadataFile(cacheFile, out projectMetadata))
{
return Tuple.Create(projectMetadata, rebuildProject);
}
else
{
Logger.Log(LogLevel.Info, $"'{projectConfig.InputFilesKey}' is invalid, rebuild needed.");
}
}
var compilation = await compilationProvider(input);
var assembly = await assemblyProvider(input);
projectMetadata = GenerateYamlMetadata(compilation, assembly, preserveRawInlineComments, filterConfigFile, extensionMethods);
var file = Path.GetRandomFileName();
var cacheOutputFolder = projectLevelCache.OutputFolder;
var path = Path.Combine(cacheOutputFolder, file);
YamlUtility.Serialize(path, projectMetadata);
Logger.Log(LogLevel.Verbose, $"Successfully generated metadata {cacheOutputFolder} for {projectMetadata.Name}");
IDictionary<string, List<string>> containedFiles = null;
if (containedFilesProvider != null)
{
containedFiles = containedFilesProvider(input);
}
// Save to cache
projectLevelCache.SaveToCache(inputKey, containedFiles, triggeredTime, cacheOutputFolder, new List<string>() { file }, shouldSkipMarkup, _msbuildProperties);
return Tuple.Create(projectMetadata, rebuildProject);
}
private static IEnumerable<string> ResolveAndExportYamlMetadata(
Dictionary<string, MetadataItem> allMembers,
Dictionary<string, ReferenceItem> allReferences,
string folder,
bool preserveRawInlineComments,
bool shouldSkipMarkup,
bool useCompatibilityFileName)
{
var outputFileNames = new Dictionary<string, int>(FilePathComparer.OSPlatformSensitiveStringComparer);
var model = YamlMetadataResolver.ResolveMetadata(allMembers, allReferences, preserveRawInlineComments);
var tocFileName = Constants.TocYamlFileName;
// 0. load last Manifest and remove files
CleanupHistoricalFile(folder);
// 1. generate toc.yml
model.TocYamlViewModel.Type = MemberType.Toc;
// TOC do not change
var tocViewModel = model.TocYamlViewModel.ToTocViewModel();
string tocFilePath = Path.Combine(folder, tocFileName);
YamlUtility.Serialize(tocFilePath, tocViewModel, YamlMime.TableOfContent);
outputFileNames.Add(tocFilePath, 1);
yield return tocFileName;
ApiReferenceViewModel indexer = new ApiReferenceViewModel();
// 2. generate each item's yaml
var members = model.Members;
foreach (var memberModel in members)
{
var fileName = useCompatibilityFileName ? memberModel.Name : memberModel.Name.Replace('`', '-');
var outputFileName = GetUniqueFileNameWithSuffix(fileName + Constants.YamlExtension, outputFileNames);
string itemFilePath = Path.Combine(folder, outputFileName);
Directory.CreateDirectory(Path.GetDirectoryName(itemFilePath));
var memberViewModel = memberModel.ToPageViewModel();
memberViewModel.ShouldSkipMarkup = shouldSkipMarkup;
YamlUtility.Serialize(itemFilePath, memberViewModel, YamlMime.ManagedReference);
Logger.Log(LogLevel.Diagnostic, $"Metadata file for {memberModel.Name} is saved to {itemFilePath}.");
AddMemberToIndexer(memberModel, outputFileName, indexer);
yield return outputFileName;
}
// 3. generate manifest file
string indexFilePath = Path.Combine(folder, IndexFileName);
JsonUtility.Serialize(indexFilePath, indexer, Newtonsoft.Json.Formatting.Indented);
yield return IndexFileName;
}
private static void CleanupHistoricalFile(string outputFolder)
{
var indexFilePath = Path.Combine(outputFolder, IndexFileName);
ApiReferenceViewModel index;
if (!File.Exists(indexFilePath))
{
return;
}
try
{
index = JsonUtility.Deserialize<ApiReferenceViewModel>(indexFilePath);
}
catch (Exception e)
{
Logger.LogInfo($"{indexFilePath} is not in a valid metadata manifest file format, ignored: {e.Message}.");
return;
}
foreach (var pair in index)
{
var filePath = Path.Combine(outputFolder, pair.Value);
try
{
File.Delete(filePath);
}
catch (Exception e)
{
Logger.LogDiagnostic($"Error deleting file {filePath}: {e.Message}");
}
}
}
private static string GetUniqueFileNameWithSuffix(string fileName, Dictionary<string, int> existingFileNames)
{
if (existingFileNames.TryGetValue(fileName, out int suffix))
{
existingFileNames[fileName] = suffix + 1;
var newFileName = $"{fileName}_{suffix}";
var extensionIndex = fileName.LastIndexOf('.');
if (extensionIndex > -1)
{
newFileName = $"{fileName.Substring(0, extensionIndex)}_{suffix}.{fileName.Substring(extensionIndex + 1)}";
}
var extension = Path.GetExtension(fileName);
var name = Path.GetFileNameWithoutExtension(fileName);
return GetUniqueFileNameWithSuffix(newFileName, existingFileNames);
}
else
{
existingFileNames[fileName] = 1;
return fileName;
}
}
private static void AddMemberToIndexer(MetadataItem memberModel, string outputPath, ApiReferenceViewModel indexer)
{
if (memberModel.Type == MemberType.Namespace)
{
indexer.Add(memberModel.Name, outputPath);
}
else
{
TreeIterator.Preorder(memberModel, null, s => s.Items, (member, parent) =>
{
if (indexer.TryGetValue(member.Name, out string path))
{
Logger.LogWarning($"{member.Name} already exists in {path}, the duplicate one {outputPath} will be ignored.");
}
else
{
indexer.Add(member.Name, outputPath);
}
return true;
});
}
}
private static Dictionary<string, MetadataItem> MergeYamlProjectMetadata(List<MetadataItem> projectMetadataList)
{
if (projectMetadataList == null || projectMetadataList.Count == 0)
{
return null;
}
Dictionary<string, MetadataItem> namespaceMapping = new Dictionary<string, MetadataItem>();
Dictionary<string, MetadataItem> allMembers = new Dictionary<string, MetadataItem>();
foreach (var project in projectMetadataList)
{
if (project.Items != null)
{
foreach (var ns in project.Items)
{
if (ns.Type == MemberType.Namespace)
{
if (namespaceMapping.TryGetValue(ns.Name, out MetadataItem nsOther))
{
if (ns.Items != null)
{
if (nsOther.Items == null)
{
nsOther.Items = new List<MetadataItem>();
}
foreach (var i in ns.Items)
{
if (!nsOther.Items.Any(s => s.Name == i.Name))
{
nsOther.Items.Add(i);
}
else
{
Logger.Log(LogLevel.Info, $"{i.Name} already exists in {nsOther.Name}, ignore current one");
}
}
}
}
else
{
namespaceMapping.Add(ns.Name, ns);
}
}
if (!allMembers.ContainsKey(ns.Name))
{
allMembers.Add(ns.Name, ns);
}
ns.Items?.ForEach(s =>
{
if (allMembers.TryGetValue(s.Name, out MetadataItem existingMetadata))
{
Logger.Log(LogLevel.Warning, $"Duplicate member {s.Name} is found from {existingMetadata.Source.Path} and {s.Source.Path}, use the one in {existingMetadata.Source.Path} and ignore the one from {s.Source.Path}");
}
else
{
allMembers.Add(s.Name, s);
}
s.Items?.ForEach(s1 =>
{
if (allMembers.TryGetValue(s1.Name, out MetadataItem existingMetadata1))
{
Logger.Log(LogLevel.Warning, $"Duplicate member {s1.Name} is found from {existingMetadata1.Source.Path} and {s1.Source.Path}, use the one in {existingMetadata1.Source.Path} and ignore the one from {s1.Source.Path}");
}
else
{
allMembers.Add(s1.Name, s1);
}
});
});
}
}
}
return allMembers;
}
private static bool TryParseYamlMetadataFile(string metadataFileName, out MetadataItem projectMetadata)
{
projectMetadata = null;
try
{
using (StreamReader reader = new StreamReader(metadataFileName))
{
projectMetadata = YamlUtility.Deserialize<MetadataItem>(reader);
return true;
}
}
catch (Exception e)
{
Logger.LogInfo($"Error parsing yaml metadata file: {e.Message}");
return false;
}
}
private static Dictionary<string, ReferenceItem> MergeYamlProjectReferences(List<MetadataItem> projectMetadataList)
{
if (projectMetadataList == null || projectMetadataList.Count == 0)
{
return null;
}
var result = new Dictionary<string, ReferenceItem>();
foreach (var project in projectMetadataList)
{
if (project.References != null)
{
foreach (var pair in project.References)
{
if (!result.ContainsKey(pair.Key))
{
result[pair.Key] = pair.Value;
}
else
{
result[pair.Key].Merge(pair.Value);
}
}
}
}
return result;
}
private async Task<Solution> GetSolutionAsync(string path)
{
try
{
Logger.LogVerbose($"Loading solution {path}", file: path);
var solution = await _workspace.Value.OpenSolutionAsync(path);
_workspace.Value.CloseSolution();
return solution;
}
catch (Exception e)
{
Logger.Log(LogLevel.Warning, $"Error opening solution {path}: {e.Message}. Ignored.");
return null;
}
}
private Project GetProject(ConcurrentDictionary<string, Project> cache, string path)
{
return cache.GetOrAdd(path.ToNormalizedFullPath(), s =>
{
try
{
Logger.LogVerbose($"Loading project {s}", file: s);
var project = _workspace.Value.CurrentSolution.Projects.FirstOrDefault(
p => FilePathComparer.OSPlatformSensitiveRelativePathComparer.Equals(p.FilePath, s));
if (project != null)
{
return project;
}
return _workspace.Value.OpenProjectAsync(s).Result;
}
catch (AggregateException e)
{
Logger.Log(LogLevel.Warning, $"Error opening project {path}: {e.GetBaseException()?.Message}. Ignored.");
return null;
}
catch (Exception e)
{
Logger.Log(LogLevel.Warning, $"Error opening project {path}: {e.Message}. Ignored.");
return null;
}
});
}
private Project GetProjectJsonProject(string path)
{
try
{
Logger.LogVerbose($"Loading project {path}", file: path);
var workspace = new ProjectJsonWorkspace(path);
return workspace.CurrentSolution.Projects.FirstOrDefault(p => p.FilePath == Path.GetFullPath(path));
}
catch (Exception e)
{
Logger.Log(LogLevel.Warning, $"Error opening project {path}: {e.Message}. Ignored.");
return null;
}
}
/// <summary>
/// use DFS to get topological sorted items
/// </summary>
private static IEnumerable<string> GetTopologicalSortedItems(IDictionary<string, List<string>> graph)
{
var visited = new HashSet<string>();
var result = new List<string>();
foreach (var node in graph.Keys)
{
DepthFirstTraverse(graph, node, visited, result);
}
return result;
}
private static void DepthFirstTraverse(IDictionary<string, List<string>> graph, string start, HashSet<string> visited, List<string> result)
{
if (!visited.Add(start))
{
return;
}
foreach (var presequisite in graph[start])
{
DepthFirstTraverse(graph, presequisite, visited, result);
}
result.Add(start);
}
private static string GetPrintableFileList(IEnumerable<FileInformation> files)
{
return files?.Select(s => s.RawPath).ToDelimitedString();
}
private static IEnumerable<string> GetCacheKey(IEnumerable<FileInformation> files)
{
return files.Where(s => s.Type != FileType.NotSupported).OrderBy(s => s.Type).Select(s => s.NormalizedPath);
}
#endregion
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// Stored Procedure Return Values Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class SPOUTDataSet : EduHubDataSet<SPOUT>
{
/// <inheritdoc />
public override string Name { get { return "SPOUT"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal SPOUTDataSet(EduHubContext Context)
: base(Context)
{
Index_SPOUTKEY = new Lazy<Dictionary<string, SPOUT>>(() => this.ToDictionary(i => i.SPOUTKEY));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="SPOUT" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="SPOUT" /> fields for each CSV column header</returns>
internal override Action<SPOUT, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<SPOUT, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "SPOUTKEY":
mapper[i] = (e, v) => e.SPOUTKEY = v;
break;
case "FILE_NAME":
mapper[i] = (e, v) => e.FILE_NAME = v;
break;
case "ENTITYID":
mapper[i] = (e, v) => e.ENTITYID = v;
break;
case "FLAG01":
mapper[i] = (e, v) => e.FLAG01 = v;
break;
case "FLAG02":
mapper[i] = (e, v) => e.FLAG02 = v;
break;
case "FLAG03":
mapper[i] = (e, v) => e.FLAG03 = v;
break;
case "FLAG04":
mapper[i] = (e, v) => e.FLAG04 = v;
break;
case "TXT01":
mapper[i] = (e, v) => e.TXT01 = v;
break;
case "TXT02":
mapper[i] = (e, v) => e.TXT02 = v;
break;
case "TXT03":
mapper[i] = (e, v) => e.TXT03 = v;
break;
case "TXT04":
mapper[i] = (e, v) => e.TXT04 = v;
break;
case "NUM01":
mapper[i] = (e, v) => e.NUM01 = v == null ? (int?)null : int.Parse(v);
break;
case "NUM02":
mapper[i] = (e, v) => e.NUM02 = v == null ? (int?)null : int.Parse(v);
break;
case "NUM03":
mapper[i] = (e, v) => e.NUM03 = v == null ? (int?)null : int.Parse(v);
break;
case "NUM04":
mapper[i] = (e, v) => e.NUM04 = v == null ? (int?)null : int.Parse(v);
break;
case "NOTES":
mapper[i] = (e, v) => e.NOTES = v;
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="SPOUT" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="SPOUT" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="SPOUT" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{SPOUT}"/> of entities</returns>
internal override IEnumerable<SPOUT> ApplyDeltaEntities(IEnumerable<SPOUT> Entities, List<SPOUT> DeltaEntities)
{
HashSet<string> Index_SPOUTKEY = new HashSet<string>(DeltaEntities.Select(i => i.SPOUTKEY));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.SPOUTKEY;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_SPOUTKEY.Remove(entity.SPOUTKEY);
if (entity.SPOUTKEY.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<Dictionary<string, SPOUT>> Index_SPOUTKEY;
#endregion
#region Index Methods
/// <summary>
/// Find SPOUT by SPOUTKEY field
/// </summary>
/// <param name="SPOUTKEY">SPOUTKEY value used to find SPOUT</param>
/// <returns>Related SPOUT entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public SPOUT FindBySPOUTKEY(string SPOUTKEY)
{
return Index_SPOUTKEY.Value[SPOUTKEY];
}
/// <summary>
/// Attempt to find SPOUT by SPOUTKEY field
/// </summary>
/// <param name="SPOUTKEY">SPOUTKEY value used to find SPOUT</param>
/// <param name="Value">Related SPOUT entity</param>
/// <returns>True if the related SPOUT entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindBySPOUTKEY(string SPOUTKEY, out SPOUT Value)
{
return Index_SPOUTKEY.Value.TryGetValue(SPOUTKEY, out Value);
}
/// <summary>
/// Attempt to find SPOUT by SPOUTKEY field
/// </summary>
/// <param name="SPOUTKEY">SPOUTKEY value used to find SPOUT</param>
/// <returns>Related SPOUT entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public SPOUT TryFindBySPOUTKEY(string SPOUTKEY)
{
SPOUT value;
if (Index_SPOUTKEY.Value.TryGetValue(SPOUTKEY, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a SPOUT table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[SPOUT]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[SPOUT](
[SPOUTKEY] varchar(100) NOT NULL,
[FILE_NAME] varchar(200) NULL,
[ENTITYID] varchar(10) NULL,
[FLAG01] varchar(1) NULL,
[FLAG02] varchar(1) NULL,
[FLAG03] varchar(1) NULL,
[FLAG04] varchar(1) NULL,
[TXT01] varchar(40) NULL,
[TXT02] varchar(40) NULL,
[TXT03] varchar(40) NULL,
[TXT04] varchar(40) NULL,
[NUM01] int NULL,
[NUM02] int NULL,
[NUM03] int NULL,
[NUM04] int NULL,
[NOTES] varchar(MAX) NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [SPOUT_Index_SPOUTKEY] PRIMARY KEY CLUSTERED (
[SPOUTKEY] ASC
)
);
END");
}
/// <summary>
/// Returns null as <see cref="SPOUTDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns null as <see cref="SPOUTDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="SPOUT"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="SPOUT"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<SPOUT> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<string> Index_SPOUTKEY = new List<string>();
foreach (var entity in Entities)
{
Index_SPOUTKEY.Add(entity.SPOUTKEY);
}
builder.AppendLine("DELETE [dbo].[SPOUT] WHERE");
// Index_SPOUTKEY
builder.Append("[SPOUTKEY] IN (");
for (int index = 0; index < Index_SPOUTKEY.Count; index++)
{
if (index != 0)
builder.Append(", ");
// SPOUTKEY
var parameterSPOUTKEY = $"@p{parameterIndex++}";
builder.Append(parameterSPOUTKEY);
command.Parameters.Add(parameterSPOUTKEY, SqlDbType.VarChar, 100).Value = Index_SPOUTKEY[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the SPOUT data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the SPOUT data set</returns>
public override EduHubDataSetDataReader<SPOUT> GetDataSetDataReader()
{
return new SPOUTDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the SPOUT data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the SPOUT data set</returns>
public override EduHubDataSetDataReader<SPOUT> GetDataSetDataReader(List<SPOUT> Entities)
{
return new SPOUTDataReader(new EduHubDataSetLoadedReader<SPOUT>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class SPOUTDataReader : EduHubDataSetDataReader<SPOUT>
{
public SPOUTDataReader(IEduHubDataSetReader<SPOUT> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 19; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // SPOUTKEY
return Current.SPOUTKEY;
case 1: // FILE_NAME
return Current.FILE_NAME;
case 2: // ENTITYID
return Current.ENTITYID;
case 3: // FLAG01
return Current.FLAG01;
case 4: // FLAG02
return Current.FLAG02;
case 5: // FLAG03
return Current.FLAG03;
case 6: // FLAG04
return Current.FLAG04;
case 7: // TXT01
return Current.TXT01;
case 8: // TXT02
return Current.TXT02;
case 9: // TXT03
return Current.TXT03;
case 10: // TXT04
return Current.TXT04;
case 11: // NUM01
return Current.NUM01;
case 12: // NUM02
return Current.NUM02;
case 13: // NUM03
return Current.NUM03;
case 14: // NUM04
return Current.NUM04;
case 15: // NOTES
return Current.NOTES;
case 16: // LW_DATE
return Current.LW_DATE;
case 17: // LW_TIME
return Current.LW_TIME;
case 18: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 1: // FILE_NAME
return Current.FILE_NAME == null;
case 2: // ENTITYID
return Current.ENTITYID == null;
case 3: // FLAG01
return Current.FLAG01 == null;
case 4: // FLAG02
return Current.FLAG02 == null;
case 5: // FLAG03
return Current.FLAG03 == null;
case 6: // FLAG04
return Current.FLAG04 == null;
case 7: // TXT01
return Current.TXT01 == null;
case 8: // TXT02
return Current.TXT02 == null;
case 9: // TXT03
return Current.TXT03 == null;
case 10: // TXT04
return Current.TXT04 == null;
case 11: // NUM01
return Current.NUM01 == null;
case 12: // NUM02
return Current.NUM02 == null;
case 13: // NUM03
return Current.NUM03 == null;
case 14: // NUM04
return Current.NUM04 == null;
case 15: // NOTES
return Current.NOTES == null;
case 16: // LW_DATE
return Current.LW_DATE == null;
case 17: // LW_TIME
return Current.LW_TIME == null;
case 18: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // SPOUTKEY
return "SPOUTKEY";
case 1: // FILE_NAME
return "FILE_NAME";
case 2: // ENTITYID
return "ENTITYID";
case 3: // FLAG01
return "FLAG01";
case 4: // FLAG02
return "FLAG02";
case 5: // FLAG03
return "FLAG03";
case 6: // FLAG04
return "FLAG04";
case 7: // TXT01
return "TXT01";
case 8: // TXT02
return "TXT02";
case 9: // TXT03
return "TXT03";
case 10: // TXT04
return "TXT04";
case 11: // NUM01
return "NUM01";
case 12: // NUM02
return "NUM02";
case 13: // NUM03
return "NUM03";
case 14: // NUM04
return "NUM04";
case 15: // NOTES
return "NOTES";
case 16: // LW_DATE
return "LW_DATE";
case 17: // LW_TIME
return "LW_TIME";
case 18: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "SPOUTKEY":
return 0;
case "FILE_NAME":
return 1;
case "ENTITYID":
return 2;
case "FLAG01":
return 3;
case "FLAG02":
return 4;
case "FLAG03":
return 5;
case "FLAG04":
return 6;
case "TXT01":
return 7;
case "TXT02":
return 8;
case "TXT03":
return 9;
case "TXT04":
return 10;
case "NUM01":
return 11;
case "NUM02":
return 12;
case "NUM03":
return 13;
case "NUM04":
return 14;
case "NOTES":
return 15;
case "LW_DATE":
return 16;
case "LW_TIME":
return 17;
case "LW_USER":
return 18;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
using System;
using System.Globalization;
using System.Threading;
using Eto.Forms;
#if GTK3
using NewWindowPolicyDecisionRequestedArgs = WebKit.NewWindowPolicyDecisionRequestedArgs;
#endif
namespace Eto.GtkSharp.Forms.Controls
{
public class WebViewHandler : GtkControl<EtoWebView, WebView, WebView.ICallback>, WebView.IHandler
{
readonly Gtk.ScrolledWindow scroll;
readonly ManualResetEventSlim returnResetEvent = new ManualResetEventSlim();
string scriptReturnValue;
const string EtoReturnPrefix = "etoscriptreturn://";
public Gtk.ScrolledWindow Scroll
{
get { return scroll; }
}
public override Gtk.Widget ContainerControl
{
get { return scroll; }
}
public WebViewHandler()
{
scroll = new Gtk.ScrolledWindow();
try
{
Control = new EtoWebView();
}
catch (Exception ex)
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "GTK WebView is only supported on Linux, and requires webkit-sharp", ex));
}
scroll.Add(Control);
}
protected override void Initialize()
{
base.Initialize();
Control.PopulatePopup += Connector.HandlePopulatePopup;
HandleEvent(WebView.DocumentLoadingEvent);
}
public override void AttachEvent(string id)
{
switch (id)
{
case WebView.NavigatedEvent:
HandleEvent(WebView.DocumentLoadedEvent);
break;
case WebView.DocumentLoadedEvent:
Control.LoadFinished += Connector.HandleLoadFinished;
break;
case WebView.DocumentLoadingEvent:
#if GTK2
Control.NavigationRequested += Connector.HandleNavigationRequested;
#else
Control.NavigationPolicyDecisionRequested += Connector.HandleNavigationPolicyDecisitionRequested;
#endif
break;
case WebView.OpenNewWindowEvent:
// note: requires libwebkitgtk 1.1.4+
Control.NewWindowPolicyDecisionRequested += Connector.HandleNewWindowPolicyDecisionRequested;
break;
case WebView.DocumentTitleChangedEvent:
Control.TitleChanged += Connector.HandleTitleChanged;
break;
default:
base.AttachEvent(id);
break;
}
}
protected new WebViewConnector Connector { get { return (WebViewConnector)base.Connector; } }
protected override WeakConnector CreateConnector()
{
return new WebViewConnector();
}
protected class WebViewConnector : GtkControlConnector
{
public new WebViewHandler Handler { get { return (WebViewHandler)base.Handler; } }
public void HandlePopulatePopup(object o, WebKit.PopulatePopupArgs args)
{
var handler = Handler;
if (handler.BrowserContextMenuEnabled)
return;
// don't allow context menu by default
foreach (var child in args.Menu.Children)
{
args.Menu.Remove(child);
}
}
public void HandleLoadFinished(object o, WebKit.LoadFinishedArgs args)
{
var handler = Handler;
var uri = args.Frame.Uri != null ? new Uri(args.Frame.Uri) : null;
var e = new WebViewLoadedEventArgs(uri);
if (args.Frame == handler.Control.MainFrame)
handler.Callback.OnNavigated(handler.Widget, e);
handler.Callback.OnDocumentLoaded(handler.Widget, e);
}
#if GTK2
public void HandleNavigationRequested(object o, WebKit.NavigationRequestedArgs args)
{
var handler = Handler;
if (args.Request.Uri.StartsWith(EtoReturnPrefix, StringComparison.Ordinal))
{
// pass back the response to ExecuteScript()
handler.scriptReturnValue = Uri.UnescapeDataString(args.Request.Uri.Substring(EtoReturnPrefix.Length).Replace('+', ' '));
handler.returnResetEvent.Set();
args.RetVal = WebKit.NavigationResponse.Ignore;
}
else
{
var e = new WebViewLoadingEventArgs(new Uri(args.Request.Uri), false);
handler.Callback.OnDocumentLoading(handler.Widget, e);
args.RetVal = e.Cancel ? WebKit.NavigationResponse.Ignore : WebKit.NavigationResponse.Accept;
}
}
#else
public void HandleNavigationPolicyDecisitionRequested(object o, WebKit.NavigationPolicyDecisionRequestedArgs args)
{
var handler = Handler;
if (args.Request.Uri.StartsWith(EtoReturnPrefix, StringComparison.Ordinal))
{
// pass back the response to ExecuteScript()
handler.scriptReturnValue = Uri.UnescapeDataString(args.Request.Uri.Substring(EtoReturnPrefix.Length).Replace('+', ' '));
handler.returnResetEvent.Set();
args.PolicyDecision.Ignore();
}
else
{
var e = new WebViewLoadingEventArgs(new Uri(args.Request.Uri), false);
handler.Callback.OnDocumentLoading(handler.Widget, e);
if (e.Cancel)
args.PolicyDecision.Ignore();
else
args.PolicyDecision.Use();
}
}
#endif
public void HandleNewWindowPolicyDecisionRequested(object sender, NewWindowPolicyDecisionRequestedArgs args)
{
var handler = Handler;
var e = new WebViewNewWindowEventArgs(new Uri(args.Request.Uri), args.Frame.Name);
handler.Callback.OnOpenNewWindow(handler.Widget, e);
#if GTK2
var decision = args.Decision;
#else
var decision = args.PolicyDecision;
#endif
if (decision != null)
{
if (e.Cancel)
decision.Ignore();
else
{
decision.Use();
Application.Instance.Open(args.Request.Uri);
}
}
args.RetVal = true;
}
public void HandleTitleChanged(object o, WebKit.TitleChangedArgs args)
{
Handler.Callback.OnDocumentTitleChanged(Handler.Widget, new WebViewTitleEventArgs(args.Title));
}
}
public Uri Url
{
get { return new Uri(Control.Uri); }
set
{
if (value != null)
{
Control.LoadUri(value.AbsoluteUri);
}
else
Control.LoadHtmlString(string.Empty, string.Empty);
}
}
public string DocumentTitle
{
get
{
return Control.MainFrame.Title;
}
}
public string ExecuteScript(string script)
{
// no access to DOM or return value, so get return value via URL (limited length, but better than nothing)
var getResultScript = @"try {{ var fn = function () {{ {0} }}; window.location.href = '" + EtoReturnPrefix + @"' + encodeURIComponent(fn()); }} catch (e) {{ window.location.href = '" + EtoReturnPrefix + @"'; }}";
returnResetEvent.Reset();
Control.ExecuteScript(string.Format(getResultScript, script));
while (!returnResetEvent.Wait(0))
{
Gtk.Application.RunIteration();
}
return scriptReturnValue;
}
public void LoadHtml(string html, Uri baseUri)
{
Control.LoadHtmlString(html, baseUri != null ? baseUri.AbsoluteUri : null);
}
public void Stop()
{
Control.StopLoading();
}
public void Reload()
{
Control.Reload();
}
public void GoBack()
{
Control.GoBack();
}
public void GoForward()
{
Control.GoForward();
}
public bool CanGoBack
{
get { return Control.CanGoBack(); }
}
public bool CanGoForward
{
get { return Control.CanGoForward(); }
}
public void ShowPrintDialog()
{
Control.ExecuteScript("print();");
}
public bool BrowserContextMenuEnabled
{
get;
set;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using Microsoft.Azure.Commands.Compute.Automation.Models;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
using Microsoft.Azure.Management.Compute.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Compute.Automation
{
[Cmdlet(VerbsCommon.New, ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "VmssConfig", SupportsShouldProcess = true, DefaultParameterSetName = "DefaultParameterSet")]
[OutputType(typeof(PSVirtualMachineScaleSet))]
public partial class NewAzureRmVmssConfigCommand : Microsoft.Azure.Commands.ResourceManager.Common.AzureRMCmdlet
{
[Parameter(
Mandatory = false,
Position = 0,
ValueFromPipelineByPropertyName = true)]
public bool? Overprovision { get; set; }
[Parameter(
Mandatory = false,
Position = 1,
ValueFromPipelineByPropertyName = true)]
[LocationCompleter("Microsoft.Compute/virtualMachineScaleSets")]
public string Location { get; set; }
[Parameter(
Mandatory = false,
Position = 2,
ValueFromPipelineByPropertyName = true)]
public Hashtable Tag { get; set; }
[Parameter(
Mandatory = false,
Position = 3,
ValueFromPipelineByPropertyName = true)]
[Alias("AccountType")]
public string SkuName { get; set; }
[Parameter(
Mandatory = false,
Position = 4,
ValueFromPipelineByPropertyName = true)]
public string SkuTier { get; set; }
[Parameter(
Mandatory = false,
Position = 5,
ValueFromPipelineByPropertyName = true)]
public int SkuCapacity { get; set; }
[Parameter(
Mandatory = false,
Position = 6,
ValueFromPipelineByPropertyName = true)]
public UpgradeMode? UpgradePolicyMode { get; set; }
[Parameter(
Mandatory = false,
Position = 7,
ValueFromPipelineByPropertyName = true)]
public VirtualMachineScaleSetOSProfile OsProfile { get; set; }
[Parameter(
Mandatory = false,
Position = 8,
ValueFromPipelineByPropertyName = true)]
public VirtualMachineScaleSetStorageProfile StorageProfile { get; set; }
[Parameter(
Mandatory = false,
Position = 9,
ValueFromPipelineByPropertyName = true)]
public VirtualMachineScaleSetNetworkConfiguration[] NetworkInterfaceConfiguration { get; set; }
[Parameter(
Mandatory = false,
Position = 10,
ValueFromPipelineByPropertyName = true)]
public VirtualMachineScaleSetExtension[] Extension { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public bool? SinglePlacementGroup { get; set; }
[Parameter(
Mandatory = false)]
public SwitchParameter ZoneBalance { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public int PlatformFaultDomainCount { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string[] Zone { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string PlanName { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string PlanPublisher { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string PlanProduct { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string PlanPromotionCode { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public RollingUpgradePolicy RollingUpgradePolicy { get; set; }
[Parameter(
Mandatory = false)]
public SwitchParameter AutoOSUpgrade { get; set; }
[Parameter(
Mandatory = false)]
public bool DisableAutoRollback { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public SwitchParameter EnableUltraSSD { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string HealthProbeId { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public BootDiagnostics BootDiagnostic { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string LicenseType { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string Priority { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
[PSArgumentCompleter("Deallocate", "Delete")]
public string EvictionPolicy { get; set; }
[Parameter(
Mandatory = true,
ParameterSetName = "ExplicitIdentityParameterSet",
ValueFromPipelineByPropertyName = true)]
public ResourceIdentityType? IdentityType { get; set; }
[Parameter(
Mandatory = false,
ParameterSetName = "ExplicitIdentityParameterSet",
ValueFromPipelineByPropertyName = true)]
public string[] IdentityId { get; set; }
protected override void ProcessRecord()
{
if (ShouldProcess("VirtualMachineScaleSet", "New"))
{
Run();
}
}
private void Run()
{
// Sku
Sku vSku = null;
// Plan
Plan vPlan = null;
// UpgradePolicy
UpgradePolicy vUpgradePolicy = null;
// VirtualMachineProfile
VirtualMachineScaleSetVMProfile vVirtualMachineProfile = null;
// Identity
VirtualMachineScaleSetIdentity vIdentity = null;
if (this.MyInvocation.BoundParameters.ContainsKey("SkuName"))
{
if (vSku == null)
{
vSku = new Sku();
}
vSku.Name = this.SkuName;
}
if (this.MyInvocation.BoundParameters.ContainsKey("SkuTier"))
{
if (vSku == null)
{
vSku = new Sku();
}
vSku.Tier = this.SkuTier;
}
if (this.MyInvocation.BoundParameters.ContainsKey("SkuCapacity"))
{
if (vSku == null)
{
vSku = new Sku();
}
vSku.Capacity = this.SkuCapacity;
}
if (this.MyInvocation.BoundParameters.ContainsKey("PlanName"))
{
if (vPlan == null)
{
vPlan = new Plan();
}
vPlan.Name = this.PlanName;
}
if (this.MyInvocation.BoundParameters.ContainsKey("PlanPublisher"))
{
if (vPlan == null)
{
vPlan = new Plan();
}
vPlan.Publisher = this.PlanPublisher;
}
if (this.MyInvocation.BoundParameters.ContainsKey("PlanProduct"))
{
if (vPlan == null)
{
vPlan = new Plan();
}
vPlan.Product = this.PlanProduct;
}
if (this.MyInvocation.BoundParameters.ContainsKey("PlanPromotionCode"))
{
if (vPlan == null)
{
vPlan = new Plan();
}
vPlan.PromotionCode = this.PlanPromotionCode;
}
if (this.MyInvocation.BoundParameters.ContainsKey("UpgradePolicyMode"))
{
if (vUpgradePolicy == null)
{
vUpgradePolicy = new UpgradePolicy();
}
vUpgradePolicy.Mode = this.UpgradePolicyMode;
}
if (this.MyInvocation.BoundParameters.ContainsKey("RollingUpgradePolicy"))
{
if (vUpgradePolicy == null)
{
vUpgradePolicy = new UpgradePolicy();
}
vUpgradePolicy.RollingUpgradePolicy = this.RollingUpgradePolicy;
}
if (vUpgradePolicy == null)
{
vUpgradePolicy = new UpgradePolicy();
}
if (vUpgradePolicy.AutomaticOSUpgradePolicy == null)
{
vUpgradePolicy.AutomaticOSUpgradePolicy = new AutomaticOSUpgradePolicy();
}
vUpgradePolicy.AutomaticOSUpgradePolicy.EnableAutomaticOSUpgrade = this.AutoOSUpgrade.IsPresent;
if (this.MyInvocation.BoundParameters.ContainsKey("DisableAutoRollback"))
{
if (vUpgradePolicy == null)
{
vUpgradePolicy = new UpgradePolicy();
}
if (vUpgradePolicy.AutomaticOSUpgradePolicy == null)
{
vUpgradePolicy.AutomaticOSUpgradePolicy = new AutomaticOSUpgradePolicy();
}
vUpgradePolicy.AutomaticOSUpgradePolicy.DisableAutomaticRollback = this.DisableAutoRollback;
}
if (this.MyInvocation.BoundParameters.ContainsKey("OsProfile"))
{
if (vVirtualMachineProfile == null)
{
vVirtualMachineProfile = new VirtualMachineScaleSetVMProfile();
}
vVirtualMachineProfile.OsProfile = this.OsProfile;
}
if (this.MyInvocation.BoundParameters.ContainsKey("StorageProfile"))
{
if (vVirtualMachineProfile == null)
{
vVirtualMachineProfile = new VirtualMachineScaleSetVMProfile();
}
vVirtualMachineProfile.StorageProfile = this.StorageProfile;
}
if (this.EnableUltraSSD.IsPresent)
{
if (vVirtualMachineProfile == null)
{
vVirtualMachineProfile = new VirtualMachineScaleSetVMProfile();
}
if (vVirtualMachineProfile.AdditionalCapabilities == null)
{
vVirtualMachineProfile.AdditionalCapabilities = new AdditionalCapabilities(true);
}
}
if (this.MyInvocation.BoundParameters.ContainsKey("HealthProbeId"))
{
if (vVirtualMachineProfile == null)
{
vVirtualMachineProfile = new VirtualMachineScaleSetVMProfile();
}
if (vVirtualMachineProfile.NetworkProfile == null)
{
vVirtualMachineProfile.NetworkProfile = new VirtualMachineScaleSetNetworkProfile();
}
if (vVirtualMachineProfile.NetworkProfile.HealthProbe == null)
{
vVirtualMachineProfile.NetworkProfile.HealthProbe = new ApiEntityReference();
}
vVirtualMachineProfile.NetworkProfile.HealthProbe.Id = this.HealthProbeId;
}
if (this.MyInvocation.BoundParameters.ContainsKey("NetworkInterfaceConfiguration"))
{
if (vVirtualMachineProfile == null)
{
vVirtualMachineProfile = new VirtualMachineScaleSetVMProfile();
}
if (vVirtualMachineProfile.NetworkProfile == null)
{
vVirtualMachineProfile.NetworkProfile = new VirtualMachineScaleSetNetworkProfile();
}
vVirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations = this.NetworkInterfaceConfiguration;
}
if (this.MyInvocation.BoundParameters.ContainsKey("BootDiagnostic"))
{
if (vVirtualMachineProfile == null)
{
vVirtualMachineProfile = new VirtualMachineScaleSetVMProfile();
}
if (vVirtualMachineProfile.DiagnosticsProfile == null)
{
vVirtualMachineProfile.DiagnosticsProfile = new DiagnosticsProfile();
}
vVirtualMachineProfile.DiagnosticsProfile.BootDiagnostics = this.BootDiagnostic;
}
if (this.MyInvocation.BoundParameters.ContainsKey("Extension"))
{
if (vVirtualMachineProfile == null)
{
vVirtualMachineProfile = new VirtualMachineScaleSetVMProfile();
}
if (vVirtualMachineProfile.ExtensionProfile == null)
{
vVirtualMachineProfile.ExtensionProfile = new VirtualMachineScaleSetExtensionProfile();
}
vVirtualMachineProfile.ExtensionProfile.Extensions = this.Extension;
}
if (this.MyInvocation.BoundParameters.ContainsKey("LicenseType"))
{
if (vVirtualMachineProfile == null)
{
vVirtualMachineProfile = new VirtualMachineScaleSetVMProfile();
}
vVirtualMachineProfile.LicenseType = this.LicenseType;
}
if (this.MyInvocation.BoundParameters.ContainsKey("Priority"))
{
if (vVirtualMachineProfile == null)
{
vVirtualMachineProfile = new VirtualMachineScaleSetVMProfile();
}
vVirtualMachineProfile.Priority = this.Priority;
}
if (this.MyInvocation.BoundParameters.ContainsKey("EvictionPolicy"))
{
if (vVirtualMachineProfile == null)
{
vVirtualMachineProfile = new VirtualMachineScaleSetVMProfile();
}
vVirtualMachineProfile.EvictionPolicy = this.EvictionPolicy;
}
if (this.AssignIdentity.IsPresent)
{
if (vIdentity == null)
{
vIdentity = new VirtualMachineScaleSetIdentity();
}
vIdentity.Type = ResourceIdentityType.SystemAssigned;
}
if (this.MyInvocation.BoundParameters.ContainsKey("IdentityType"))
{
if (vIdentity == null)
{
vIdentity = new VirtualMachineScaleSetIdentity();
}
vIdentity.Type = this.IdentityType;
}
if (this.MyInvocation.BoundParameters.ContainsKey("IdentityId"))
{
if (vIdentity == null)
{
vIdentity = new VirtualMachineScaleSetIdentity();
}
vIdentity.UserAssignedIdentities = new Dictionary<string, VirtualMachineScaleSetIdentityUserAssignedIdentitiesValue>();
foreach (var id in this.IdentityId)
{
vIdentity.UserAssignedIdentities.Add(id, new VirtualMachineScaleSetIdentityUserAssignedIdentitiesValue());
}
}
var vVirtualMachineScaleSet = new PSVirtualMachineScaleSet
{
Overprovision = this.MyInvocation.BoundParameters.ContainsKey("Overprovision") ? this.Overprovision : (bool?)null,
SinglePlacementGroup = this.MyInvocation.BoundParameters.ContainsKey("SinglePlacementGroup") ? this.SinglePlacementGroup : (bool?)null,
ZoneBalance = this.ZoneBalance.IsPresent ? true : (bool?)null,
PlatformFaultDomainCount = this.MyInvocation.BoundParameters.ContainsKey("PlatformFaultDomainCount") ? this.PlatformFaultDomainCount : (int?)null,
Zones = this.MyInvocation.BoundParameters.ContainsKey("Zone") ? this.Zone : null,
Location = this.MyInvocation.BoundParameters.ContainsKey("Location") ? this.Location : null,
Tags = this.MyInvocation.BoundParameters.ContainsKey("Tag") ? this.Tag.Cast<DictionaryEntry>().ToDictionary(ht => (string)ht.Key, ht => (string)ht.Value) : null,
Sku = vSku,
Plan = vPlan,
UpgradePolicy = (vUpgradePolicy == null) ? null : new PSUpgradePolicy(vUpgradePolicy),
VirtualMachineProfile = vVirtualMachineProfile,
Identity = (vIdentity == null) ? null : new PSVirtualMachineScaleSetIdentity(vIdentity),
};
WriteObject(vVirtualMachineScaleSet);
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Web.UI.TemplateControl.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Web.UI
{
abstract public partial class TemplateControl : Control, INamingContainer, IFilterResolutionService
{
#region Methods and constructors
protected virtual new void Construct()
{
}
protected LiteralControl CreateResourceBasedLiteralControl(int offset, int size, bool fAsciiOnly)
{
return default(LiteralControl);
}
protected internal Object Eval(string expression)
{
return default(Object);
}
protected internal string Eval(string expression, string format)
{
return default(string);
}
protected virtual new void FrameworkInitialize()
{
}
protected Object GetGlobalResourceObject(string className, string resourceKey, Type objType, string propName)
{
return default(Object);
}
protected Object GetGlobalResourceObject(string className, string resourceKey)
{
return default(Object);
}
protected Object GetLocalResourceObject(string resourceKey)
{
return default(Object);
}
protected Object GetLocalResourceObject(string resourceKey, Type objType, string propName)
{
return default(Object);
}
public Control LoadControl(string virtualPath)
{
return default(Control);
}
public Control LoadControl(Type t, Object[] parameters)
{
return default(Control);
}
public ITemplate LoadTemplate(string virtualPath)
{
return default(ITemplate);
}
protected virtual new void OnAbortTransaction(EventArgs e)
{
}
protected virtual new void OnCommitTransaction(EventArgs e)
{
}
protected virtual new void OnError(EventArgs e)
{
}
public Control ParseControl(string content)
{
return default(Control);
}
public Control ParseControl(string content, bool ignoreParserFilter)
{
return default(Control);
}
public Object ReadStringResource()
{
return default(Object);
}
public static Object ReadStringResource(Type t)
{
return default(Object);
}
protected void SetStringResourcePointer(Object stringResourcePointer, int maxResourceOffset)
{
}
int System.Web.UI.IFilterResolutionService.CompareFilters(string filter1, string filter2)
{
return default(int);
}
bool System.Web.UI.IFilterResolutionService.EvaluateFilter(string filterName)
{
return default(bool);
}
protected TemplateControl()
{
}
public virtual new bool TestDeviceFilter(string filterName)
{
return default(bool);
}
protected void WriteUTF8ResourceString(HtmlTextWriter output, int offset, int size, bool fAsciiOnly)
{
}
protected internal Object XPath(string xPathExpression, System.Xml.IXmlNamespaceResolver resolver)
{
return default(Object);
}
protected internal Object XPath(string xPathExpression)
{
return default(Object);
}
protected internal string XPath(string xPathExpression, string format, System.Xml.IXmlNamespaceResolver resolver)
{
return default(string);
}
protected internal string XPath(string xPathExpression, string format)
{
return default(string);
}
protected internal System.Collections.IEnumerable XPathSelect(string xPathExpression)
{
return default(System.Collections.IEnumerable);
}
protected internal System.Collections.IEnumerable XPathSelect(string xPathExpression, System.Xml.IXmlNamespaceResolver resolver)
{
return default(System.Collections.IEnumerable);
}
#endregion
#region Properties and indexers
public string AppRelativeVirtualPath
{
get
{
return default(string);
}
set
{
}
}
protected virtual new int AutoHandlers
{
get
{
return default(int);
}
set
{
}
}
public override bool EnableTheming
{
get
{
return default(bool);
}
set
{
}
}
protected virtual new bool SupportAutoEvents
{
get
{
return default(bool);
}
}
#endregion
#region Events
public event EventHandler AbortTransaction
{
add
{
}
remove
{
}
}
public event EventHandler CommitTransaction
{
add
{
}
remove
{
}
}
public event EventHandler Error
{
add
{
}
remove
{
}
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Net;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.CoreModules.Framework.InterfaceCommander;
using OpenSim.Region.CoreModules.World.Terrain.FileLoaders;
using OpenSim.Region.CoreModules.World.Terrain.FloodBrushes;
using OpenSim.Region.CoreModules.World.Terrain.PaintBrushes;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.World.Terrain
{
public class TerrainModule : INonSharedRegionModule, ICommandableModule, ITerrainModule
{
#region StandardTerrainEffects enum
/// <summary>
/// A standard set of terrain brushes and effects recognised by viewers
/// </summary>
public enum StandardTerrainEffects : byte
{
Flatten = 0,
Raise = 1,
Lower = 2,
Smooth = 3,
Noise = 4,
Revert = 5,
// Extended brushes
Erode = 255,
Weather = 254,
Olsen = 253
}
#endregion
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private readonly Commander m_commander = new Commander("terrain");
private readonly Dictionary<StandardTerrainEffects, ITerrainFloodEffect> m_floodeffects =
new Dictionary<StandardTerrainEffects, ITerrainFloodEffect>();
private readonly Dictionary<string, ITerrainLoader> m_loaders = new Dictionary<string, ITerrainLoader>();
private readonly Dictionary<StandardTerrainEffects, ITerrainPaintableEffect> m_painteffects =
new Dictionary<StandardTerrainEffects, ITerrainPaintableEffect>();
private ITerrainChannel m_channel;
private Dictionary<string, ITerrainEffect> m_plugineffects;
private ITerrainChannel m_revert;
private Scene m_scene;
private volatile bool m_tainted;
private readonly UndoStack<LandUndoState> m_undo = new UndoStack<LandUndoState>(5);
#region ICommandableModule Members
public ICommander CommandInterface
{
get { return m_commander; }
}
#endregion
#region INonSharedRegionModule Members
/// <summary>
/// Creates and initialises a terrain module for a region
/// </summary>
/// <param name="scene">Region initialising</param>
/// <param name="config">Config for the region</param>
public void Initialise(IConfigSource config)
{
}
public void AddRegion(Scene scene)
{
m_scene = scene;
// Install terrain module in the simulator
lock (m_scene)
{
if (m_scene.Heightmap == null)
{
m_channel = new TerrainChannel();
m_scene.Heightmap = m_channel;
m_revert = new TerrainChannel();
UpdateRevertMap();
}
else
{
m_channel = m_scene.Heightmap;
m_revert = new TerrainChannel();
UpdateRevertMap();
}
m_scene.RegisterModuleInterface<ITerrainModule>(this);
m_scene.EventManager.OnNewClient += EventManager_OnNewClient;
m_scene.EventManager.OnPluginConsole += EventManager_OnPluginConsole;
m_scene.EventManager.OnTerrainTick += EventManager_OnTerrainTick;
InstallInterfaces();
}
InstallDefaultEffects();
LoadPlugins();
}
public void RegionLoaded(Scene scene)
{
}
public void RemoveRegion(Scene scene)
{
lock (m_scene)
{
// remove the commands
m_scene.UnregisterModuleCommander(m_commander.Name);
// remove the event-handlers
m_scene.EventManager.OnTerrainTick -= EventManager_OnTerrainTick;
m_scene.EventManager.OnPluginConsole -= EventManager_OnPluginConsole;
m_scene.EventManager.OnNewClient -= EventManager_OnNewClient;
// remove the interface
m_scene.UnregisterModuleInterface<ITerrainModule>(this);
}
}
public void Close()
{
}
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "TerrainModule"; }
}
#endregion
#region ITerrainModule Members
public void UndoTerrain(ITerrainChannel channel)
{
m_channel = channel;
}
/// <summary>
/// Loads a terrain file from disk and installs it in the scene.
/// </summary>
/// <param name="filename">Filename to terrain file. Type is determined by extension.</param>
public void LoadFromFile(string filename)
{
foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders)
{
if (filename.EndsWith(loader.Key))
{
lock (m_scene)
{
try
{
ITerrainChannel channel = loader.Value.LoadFile(filename);
if (channel.Width != Constants.RegionSize || channel.Height != Constants.RegionSize)
{
// TerrainChannel expects a RegionSize x RegionSize map, currently
throw new ArgumentException(String.Format("wrong size, use a file with size {0} x {1}",
Constants.RegionSize, Constants.RegionSize));
}
m_log.DebugFormat("[TERRAIN]: Loaded terrain, wd/ht: {0}/{1}", channel.Width, channel.Height);
m_scene.Heightmap = channel;
m_channel = channel;
UpdateRevertMap();
}
catch (NotImplementedException)
{
m_log.Error("[TERRAIN]: Unable to load heightmap, the " + loader.Value +
" parser does not support file loading. (May be save only)");
throw new TerrainException(String.Format("unable to load heightmap: parser {0} does not support loading", loader.Value));
}
catch (FileNotFoundException)
{
m_log.Error(
"[TERRAIN]: Unable to load heightmap, file not found. (A directory permissions error may also cause this)");
throw new TerrainException(
String.Format("unable to load heightmap: file {0} not found (or permissions do not allow access", filename));
}
catch (ArgumentException e)
{
m_log.ErrorFormat("[TERRAIN]: Unable to load heightmap: {0}", e.Message);
throw new TerrainException(
String.Format("Unable to load heightmap: {0}", e.Message));
}
}
CheckForTerrainUpdates();
m_log.Info("[TERRAIN]: File (" + filename + ") loaded successfully");
return;
}
}
m_log.Error("[TERRAIN]: Unable to load heightmap, no file loader available for that format.");
throw new TerrainException(String.Format("unable to load heightmap from file {0}: no loader available for that format", filename));
}
/// <summary>
/// Saves the current heightmap to a specified file.
/// </summary>
/// <param name="filename">The destination filename</param>
public void SaveToFile(string filename)
{
try
{
foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders)
{
if (filename.EndsWith(loader.Key))
{
loader.Value.SaveFile(filename, m_channel);
return;
}
}
}
catch (NotImplementedException)
{
m_log.Error("Unable to save to " + filename + ", saving of this file format has not been implemented.");
throw new TerrainException(String.Format("Unable to save heightmap: saving of this file format not implemented"));
}
catch (IOException ioe)
{
m_log.Error(String.Format("[TERRAIN]: Unable to save to {0}, {1}", filename, ioe.Message));
throw new TerrainException(String.Format("Unable to save heightmap: {0}", ioe.Message));
}
}
/// <summary>
/// Loads a terrain file from the specified URI
/// </summary>
/// <param name="filename">The name of the terrain to load</param>
/// <param name="pathToTerrainHeightmap">The URI to the terrain height map</param>
public void LoadFromStream(string filename, Uri pathToTerrainHeightmap)
{
LoadFromStream(filename, URIFetch(pathToTerrainHeightmap));
}
/// <summary>
/// Loads a terrain file from a stream and installs it in the scene.
/// </summary>
/// <param name="filename">Filename to terrain file. Type is determined by extension.</param>
/// <param name="stream"></param>
public void LoadFromStream(string filename, Stream stream)
{
foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders)
{
if (filename.EndsWith(loader.Key))
{
lock (m_scene)
{
try
{
ITerrainChannel channel = loader.Value.LoadStream(stream);
m_scene.Heightmap = channel;
m_channel = channel;
UpdateRevertMap();
}
catch (NotImplementedException)
{
m_log.Error("[TERRAIN]: Unable to load heightmap, the " + loader.Value +
" parser does not support file loading. (May be save only)");
throw new TerrainException(String.Format("unable to load heightmap: parser {0} does not support loading", loader.Value));
}
}
CheckForTerrainUpdates();
m_log.Info("[TERRAIN]: File (" + filename + ") loaded successfully");
return;
}
}
m_log.Error("[TERRAIN]: Unable to load heightmap, no file loader available for that format.");
throw new TerrainException(String.Format("unable to load heightmap from file {0}: no loader available for that format", filename));
}
private static Stream URIFetch(Uri uri)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
// request.Credentials = credentials;
request.ContentLength = 0;
request.KeepAlive = false;
WebResponse response = request.GetResponse();
Stream file = response.GetResponseStream();
if (response.ContentLength == 0)
throw new Exception(String.Format("{0} returned an empty file", uri.ToString()));
// return new BufferedStream(file, (int) response.ContentLength);
return new BufferedStream(file, 1000000);
}
/// <summary>
/// Modify Land
/// </summary>
/// <param name="pos">Land-position (X,Y,0)</param>
/// <param name="size">The size of the brush (0=small, 1=medium, 2=large)</param>
/// <param name="action">0=LAND_LEVEL, 1=LAND_RAISE, 2=LAND_LOWER, 3=LAND_SMOOTH, 4=LAND_NOISE, 5=LAND_REVERT</param>
/// <param name="agentId">UUID of script-owner</param>
public void ModifyTerrain(UUID user, Vector3 pos, byte size, byte action, UUID agentId)
{
float duration = 0.25f;
if (action == 0)
duration = 4.0f;
client_OnModifyTerrain(user, (float)pos.Z, duration, size, action, pos.Y, pos.X, pos.Y, pos.X, agentId);
}
/// <summary>
/// Saves the current heightmap to a specified stream.
/// </summary>
/// <param name="filename">The destination filename. Used here only to identify the image type</param>
/// <param name="stream"></param>
public void SaveToStream(string filename, Stream stream)
{
try
{
foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders)
{
if (filename.EndsWith(loader.Key))
{
loader.Value.SaveStream(stream, m_channel);
return;
}
}
}
catch (NotImplementedException)
{
m_log.Error("Unable to save to " + filename + ", saving of this file format has not been implemented.");
throw new TerrainException(String.Format("Unable to save heightmap: saving of this file format not implemented"));
}
}
public void TaintTerrain ()
{
CheckForTerrainUpdates();
}
#region Plugin Loading Methods
private void LoadPlugins()
{
m_plugineffects = new Dictionary<string, ITerrainEffect>();
// Load the files in the Terrain/ dir
string[] files = Directory.GetFiles("Terrain");
foreach (string file in files)
{
m_log.Info("Loading effects in " + file);
try
{
Assembly library = Assembly.LoadFrom(file);
foreach (Type pluginType in library.GetTypes())
{
try
{
if (pluginType.IsAbstract || pluginType.IsNotPublic)
continue;
string typeName = pluginType.Name;
if (pluginType.GetInterface("ITerrainEffect", false) != null)
{
ITerrainEffect terEffect = (ITerrainEffect) Activator.CreateInstance(library.GetType(pluginType.ToString()));
InstallPlugin(typeName, terEffect);
}
else if (pluginType.GetInterface("ITerrainLoader", false) != null)
{
ITerrainLoader terLoader = (ITerrainLoader) Activator.CreateInstance(library.GetType(pluginType.ToString()));
m_loaders[terLoader.FileExtension] = terLoader;
m_log.Info("L ... " + typeName);
}
}
catch (AmbiguousMatchException)
{
}
}
}
catch (BadImageFormatException)
{
}
}
}
public void InstallPlugin(string pluginName, ITerrainEffect effect)
{
lock (m_plugineffects)
{
if (!m_plugineffects.ContainsKey(pluginName))
{
m_plugineffects.Add(pluginName, effect);
m_log.Info("E ... " + pluginName);
}
else
{
m_plugineffects[pluginName] = effect;
m_log.Warn("E ... " + pluginName + " (Replaced)");
}
}
}
#endregion
#endregion
/// <summary>
/// Installs into terrain module the standard suite of brushes
/// </summary>
private void InstallDefaultEffects()
{
// Draggable Paint Brush Effects
m_painteffects[StandardTerrainEffects.Raise] = new RaiseSphere();
m_painteffects[StandardTerrainEffects.Lower] = new LowerSphere();
m_painteffects[StandardTerrainEffects.Smooth] = new SmoothSphere();
m_painteffects[StandardTerrainEffects.Noise] = new NoiseSphere();
m_painteffects[StandardTerrainEffects.Flatten] = new FlattenSphere();
m_painteffects[StandardTerrainEffects.Revert] = new RevertSphere(m_revert);
m_painteffects[StandardTerrainEffects.Erode] = new ErodeSphere();
m_painteffects[StandardTerrainEffects.Weather] = new WeatherSphere();
m_painteffects[StandardTerrainEffects.Olsen] = new OlsenSphere();
// Area of effect selection effects
m_floodeffects[StandardTerrainEffects.Raise] = new RaiseArea();
m_floodeffects[StandardTerrainEffects.Lower] = new LowerArea();
m_floodeffects[StandardTerrainEffects.Smooth] = new SmoothArea();
m_floodeffects[StandardTerrainEffects.Noise] = new NoiseArea();
m_floodeffects[StandardTerrainEffects.Flatten] = new FlattenArea();
m_floodeffects[StandardTerrainEffects.Revert] = new RevertArea(m_revert);
// Filesystem load/save loaders
m_loaders[".r32"] = new RAW32();
m_loaders[".f32"] = m_loaders[".r32"];
m_loaders[".ter"] = new Terragen();
m_loaders[".raw"] = new LLRAW();
m_loaders[".jpg"] = new JPEG();
m_loaders[".jpeg"] = m_loaders[".jpg"];
m_loaders[".bmp"] = new BMP();
m_loaders[".png"] = new PNG();
m_loaders[".gif"] = new GIF();
m_loaders[".tif"] = new TIFF();
m_loaders[".tiff"] = m_loaders[".tif"];
}
/// <summary>
/// Saves the current state of the region into the revert map buffer.
/// </summary>
public void UpdateRevertMap()
{
int x;
for (x = 0; x < m_channel.Width; x++)
{
int y;
for (y = 0; y < m_channel.Height; y++)
{
m_revert[x, y] = m_channel[x, y];
}
}
}
/// <summary>
/// Loads a tile from a larger terrain file and installs it into the region.
/// </summary>
/// <param name="filename">The terrain file to load</param>
/// <param name="fileWidth">The width of the file in units</param>
/// <param name="fileHeight">The height of the file in units</param>
/// <param name="fileStartX">Where to begin our slice</param>
/// <param name="fileStartY">Where to begin our slice</param>
public void LoadFromFile(string filename, int fileWidth, int fileHeight, int fileStartX, int fileStartY)
{
int offsetX = (int) m_scene.RegionInfo.RegionLocX - fileStartX;
int offsetY = (int) m_scene.RegionInfo.RegionLocY - fileStartY;
if (offsetX >= 0 && offsetX < fileWidth && offsetY >= 0 && offsetY < fileHeight)
{
// this region is included in the tile request
foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders)
{
if (filename.EndsWith(loader.Key))
{
lock (m_scene)
{
ITerrainChannel channel = loader.Value.LoadFile(filename, offsetX, offsetY,
fileWidth, fileHeight,
(int) Constants.RegionSize,
(int) Constants.RegionSize);
m_scene.Heightmap = channel;
m_channel = channel;
UpdateRevertMap();
}
return;
}
}
}
}
/// <summary>
/// Performs updates to the region periodically, synchronising physics and other heightmap aware sections
/// </summary>
private void EventManager_OnTerrainTick()
{
if (m_tainted)
{
m_tainted = false;
m_scene.PhysicsScene.SetTerrain(m_channel.GetFloatsSerialised());
m_scene.SaveTerrain();
// Clients who look at the map will never see changes after they looked at the map, so i've commented this out.
//m_scene.CreateTerrainTexture(true);
}
}
/// <summary>
/// Processes commandline input. Do not call directly.
/// </summary>
/// <param name="args">Commandline arguments</param>
private void EventManager_OnPluginConsole(string[] args)
{
if (args[0] == "terrain")
{
if (args.Length == 1)
{
m_commander.ProcessConsoleCommand("help", new string[0]);
return;
}
string[] tmpArgs = new string[args.Length - 2];
int i;
for (i = 2; i < args.Length; i++)
tmpArgs[i - 2] = args[i];
m_commander.ProcessConsoleCommand(args[1], tmpArgs);
}
}
/// <summary>
/// Installs terrain brush hook to IClientAPI
/// </summary>
/// <param name="client"></param>
private void EventManager_OnNewClient(IClientAPI client)
{
client.OnModifyTerrain += client_OnModifyTerrain;
client.OnBakeTerrain += client_OnBakeTerrain;
client.OnLandUndo += client_OnLandUndo;
}
/// <summary>
/// Checks to see if the terrain has been modified since last check
/// but won't attempt to limit those changes to the limits specified in the estate settings
/// currently invoked by the command line operations in the region server only
/// </summary>
private void CheckForTerrainUpdates()
{
CheckForTerrainUpdates(false);
}
/// <summary>
/// Checks to see if the terrain has been modified since last check.
/// If it has been modified, every all the terrain patches are sent to the client.
/// If the call is asked to respect the estate settings for terrain_raise_limit and
/// terrain_lower_limit, it will clamp terrain updates between these values
/// currently invoked by client_OnModifyTerrain only and not the Commander interfaces
/// <param name="respectEstateSettings">should height map deltas be limited to the estate settings limits</param>
/// </summary>
private void CheckForTerrainUpdates(bool respectEstateSettings)
{
bool shouldTaint = false;
float[] serialised = m_channel.GetFloatsSerialised();
int x;
for (x = 0; x < m_channel.Width; x += Constants.TerrainPatchSize)
{
int y;
for (y = 0; y < m_channel.Height; y += Constants.TerrainPatchSize)
{
if (m_channel.Tainted(x, y))
{
// if we should respect the estate settings then
// fixup and height deltas that don't respect them
if (respectEstateSettings && LimitChannelChanges(x, y))
{
// this has been vetoed, so update
// what we are going to send to the client
serialised = m_channel.GetFloatsSerialised();
}
SendToClients(serialised, x, y);
shouldTaint = true;
}
}
}
if (shouldTaint)
{
m_tainted = true;
}
}
/// <summary>
/// Checks to see height deltas in the tainted terrain patch at xStart ,yStart
/// are all within the current estate limits
/// <returns>true if changes were limited, false otherwise</returns>
/// </summary>
private bool LimitChannelChanges(int xStart, int yStart)
{
bool changesLimited = false;
double minDelta = m_scene.RegionInfo.RegionSettings.TerrainLowerLimit;
double maxDelta = m_scene.RegionInfo.RegionSettings.TerrainRaiseLimit;
// loop through the height map for this patch and compare it against
// the revert map
for (int x = xStart; x < xStart + Constants.TerrainPatchSize; x++)
{
for (int y = yStart; y < yStart + Constants.TerrainPatchSize; y++)
{
double requestedHeight = m_channel[x, y];
double bakedHeight = m_revert[x, y];
double requestedDelta = requestedHeight - bakedHeight;
if (requestedDelta > maxDelta)
{
m_channel[x, y] = bakedHeight + maxDelta;
changesLimited = true;
}
else if (requestedDelta < minDelta)
{
m_channel[x, y] = bakedHeight + minDelta; //as lower is a -ve delta
changesLimited = true;
}
}
}
return changesLimited;
}
private void client_OnLandUndo(IClientAPI client)
{
lock (m_undo)
{
if (m_undo.Count > 0)
{
LandUndoState goback = m_undo.Pop();
if (goback != null)
goback.PlaybackState();
}
}
}
/// <summary>
/// Sends a copy of the current terrain to the scenes clients
/// </summary>
/// <param name="serialised">A copy of the terrain as a 1D float array of size w*h</param>
/// <param name="x">The patch corner to send</param>
/// <param name="y">The patch corner to send</param>
private void SendToClients(float[] serialised, int x, int y)
{
m_scene.ForEachClient(
delegate(IClientAPI controller)
{ controller.SendLayerData(
x / Constants.TerrainPatchSize, y / Constants.TerrainPatchSize, serialised);
}
);
}
private void client_OnModifyTerrain(UUID user, float height, float seconds, byte size, byte action,
float north, float west, float south, float east, UUID agentId)
{
bool god = m_scene.Permissions.IsGod(user);
bool allowed = false;
if (north == south && east == west)
{
if (m_painteffects.ContainsKey((StandardTerrainEffects) action))
{
bool[,] allowMask = new bool[m_channel.Width,m_channel.Height];
allowMask.Initialize();
int n = size + 1;
if (n > 2)
n = 4;
int zx = (int) (west + 0.5);
int zy = (int) (north + 0.5);
int dx;
for (dx=-n; dx<=n; dx++)
{
int dy;
for (dy=-n; dy<=n; dy++)
{
int x = zx + dx;
int y = zy + dy;
if (x>=0 && y>=0 && x<m_channel.Width && y<m_channel.Height)
{
if (m_scene.Permissions.CanTerraformLand(agentId, new Vector3(x,y,0)))
{
allowMask[x, y] = true;
allowed = true;
}
}
}
}
if (allowed)
{
StoreUndoState();
m_painteffects[(StandardTerrainEffects) action].PaintEffect(
m_channel, allowMask, west, south, height, size, seconds);
CheckForTerrainUpdates(!god); //revert changes outside estate limits
}
}
else
{
m_log.Debug("Unknown terrain brush type " + action);
}
}
else
{
if (m_floodeffects.ContainsKey((StandardTerrainEffects) action))
{
bool[,] fillArea = new bool[m_channel.Width,m_channel.Height];
fillArea.Initialize();
int x;
for (x = 0; x < m_channel.Width; x++)
{
int y;
for (y = 0; y < m_channel.Height; y++)
{
if (x < east && x > west)
{
if (y < north && y > south)
{
if (m_scene.Permissions.CanTerraformLand(agentId, new Vector3(x,y,0)))
{
fillArea[x, y] = true;
allowed = true;
}
}
}
}
}
if (allowed)
{
StoreUndoState();
m_floodeffects[(StandardTerrainEffects) action].FloodEffect(
m_channel, fillArea, size);
CheckForTerrainUpdates(!god); //revert changes outside estate limits
}
}
else
{
m_log.Debug("Unknown terrain flood type " + action);
}
}
}
private void client_OnBakeTerrain(IClientAPI remoteClient)
{
// Not a good permissions check (see client_OnModifyTerrain above), need to check the entire area.
// for now check a point in the centre of the region
if (m_scene.Permissions.CanIssueEstateCommand(remoteClient.AgentId, true))
{
InterfaceBakeTerrain(null); //bake terrain does not use the passed in parameter
}
}
private void StoreUndoState()
{
lock (m_undo)
{
if (m_undo.Count > 0)
{
LandUndoState last = m_undo.Peek();
if (last != null)
{
if (last.Compare(m_channel))
return;
}
}
LandUndoState nUndo = new LandUndoState(this, m_channel);
m_undo.Push(nUndo);
}
}
#region Console Commands
private void InterfaceLoadFile(Object[] args)
{
LoadFromFile((string) args[0]);
CheckForTerrainUpdates();
}
private void InterfaceLoadTileFile(Object[] args)
{
LoadFromFile((string) args[0],
(int) args[1],
(int) args[2],
(int) args[3],
(int) args[4]);
CheckForTerrainUpdates();
}
private void InterfaceSaveFile(Object[] args)
{
SaveToFile((string) args[0]);
}
private void InterfaceBakeTerrain(Object[] args)
{
UpdateRevertMap();
}
private void InterfaceRevertTerrain(Object[] args)
{
int x, y;
for (x = 0; x < m_channel.Width; x++)
for (y = 0; y < m_channel.Height; y++)
m_channel[x, y] = m_revert[x, y];
CheckForTerrainUpdates();
}
private void InterfaceFlipTerrain(Object[] args)
{
String direction = (String)args[0];
if (direction.ToLower().StartsWith("y"))
{
for (int x = 0; x < Constants.RegionSize; x++)
{
for (int y = 0; y < Constants.RegionSize / 2; y++)
{
double height = m_channel[x, y];
double flippedHeight = m_channel[x, (int)Constants.RegionSize - 1 - y];
m_channel[x, y] = flippedHeight;
m_channel[x, (int)Constants.RegionSize - 1 - y] = height;
}
}
}
else if (direction.ToLower().StartsWith("x"))
{
for (int y = 0; y < Constants.RegionSize; y++)
{
for (int x = 0; x < Constants.RegionSize / 2; x++)
{
double height = m_channel[x, y];
double flippedHeight = m_channel[(int)Constants.RegionSize - 1 - x, y];
m_channel[x, y] = flippedHeight;
m_channel[(int)Constants.RegionSize - 1 - x, y] = height;
}
}
}
else
{
m_log.Error("Unrecognised direction - need x or y");
}
CheckForTerrainUpdates();
}
private void InterfaceRescaleTerrain(Object[] args)
{
double desiredMin = (double)args[0];
double desiredMax = (double)args[1];
// determine desired scaling factor
double desiredRange = desiredMax - desiredMin;
//m_log.InfoFormat("Desired {0}, {1} = {2}", new Object[] { desiredMin, desiredMax, desiredRange });
if (desiredRange == 0d)
{
// delta is zero so flatten at requested height
InterfaceFillTerrain(new Object[] { args[1] });
}
else
{
//work out current heightmap range
double currMin = double.MaxValue;
double currMax = double.MinValue;
int width = m_channel.Width;
int height = m_channel.Height;
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
double currHeight = m_channel[x, y];
if (currHeight < currMin)
{
currMin = currHeight;
}
else if (currHeight > currMax)
{
currMax = currHeight;
}
}
}
double currRange = currMax - currMin;
double scale = desiredRange / currRange;
//m_log.InfoFormat("Current {0}, {1} = {2}", new Object[] { currMin, currMax, currRange });
//m_log.InfoFormat("Scale = {0}", scale);
// scale the heightmap accordingly
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
double currHeight = m_channel[x, y] - currMin;
m_channel[x, y] = desiredMin + (currHeight * scale);
}
}
CheckForTerrainUpdates();
}
}
private void InterfaceElevateTerrain(Object[] args)
{
int x, y;
for (x = 0; x < m_channel.Width; x++)
for (y = 0; y < m_channel.Height; y++)
m_channel[x, y] += (double) args[0];
CheckForTerrainUpdates();
}
private void InterfaceMultiplyTerrain(Object[] args)
{
int x, y;
for (x = 0; x < m_channel.Width; x++)
for (y = 0; y < m_channel.Height; y++)
m_channel[x, y] *= (double) args[0];
CheckForTerrainUpdates();
}
private void InterfaceLowerTerrain(Object[] args)
{
int x, y;
for (x = 0; x < m_channel.Width; x++)
for (y = 0; y < m_channel.Height; y++)
m_channel[x, y] -= (double) args[0];
CheckForTerrainUpdates();
}
private void InterfaceFillTerrain(Object[] args)
{
int x, y;
for (x = 0; x < m_channel.Width; x++)
for (y = 0; y < m_channel.Height; y++)
m_channel[x, y] = (double) args[0];
CheckForTerrainUpdates();
}
private void InterfaceShowDebugStats(Object[] args)
{
double max = Double.MinValue;
double min = double.MaxValue;
double sum = 0;
int x;
for (x = 0; x < m_channel.Width; x++)
{
int y;
for (y = 0; y < m_channel.Height; y++)
{
sum += m_channel[x, y];
if (max < m_channel[x, y])
max = m_channel[x, y];
if (min > m_channel[x, y])
min = m_channel[x, y];
}
}
double avg = sum / (m_channel.Height * m_channel.Width);
m_log.Info("Channel " + m_channel.Width + "x" + m_channel.Height);
m_log.Info("max/min/avg/sum: " + max + "/" + min + "/" + avg + "/" + sum);
}
private void InterfaceEnableExperimentalBrushes(Object[] args)
{
if ((bool) args[0])
{
m_painteffects[StandardTerrainEffects.Revert] = new WeatherSphere();
m_painteffects[StandardTerrainEffects.Flatten] = new OlsenSphere();
m_painteffects[StandardTerrainEffects.Smooth] = new ErodeSphere();
}
else
{
InstallDefaultEffects();
}
}
private void InterfaceRunPluginEffect(Object[] args)
{
if ((string) args[0] == "list")
{
m_log.Info("List of loaded plugins");
foreach (KeyValuePair<string, ITerrainEffect> kvp in m_plugineffects)
{
m_log.Info(kvp.Key);
}
return;
}
if ((string) args[0] == "reload")
{
LoadPlugins();
return;
}
if (m_plugineffects.ContainsKey((string) args[0]))
{
m_plugineffects[(string) args[0]].RunEffect(m_channel);
CheckForTerrainUpdates();
}
else
{
m_log.Warn("No such plugin effect loaded.");
}
}
private void InstallInterfaces()
{
// Load / Save
string supportedFileExtensions = "";
foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders)
supportedFileExtensions += " " + loader.Key + " (" + loader.Value + ")";
Command loadFromFileCommand =
new Command("load", CommandIntentions.COMMAND_HAZARDOUS, InterfaceLoadFile, "Loads a terrain from a specified file.");
loadFromFileCommand.AddArgument("filename",
"The file you wish to load from, the file extension determines the loader to be used. Supported extensions include: " +
supportedFileExtensions, "String");
Command saveToFileCommand =
new Command("save", CommandIntentions.COMMAND_NON_HAZARDOUS, InterfaceSaveFile, "Saves the current heightmap to a specified file.");
saveToFileCommand.AddArgument("filename",
"The destination filename for your heightmap, the file extension determines the format to save in. Supported extensions include: " +
supportedFileExtensions, "String");
Command loadFromTileCommand =
new Command("load-tile", CommandIntentions.COMMAND_HAZARDOUS, InterfaceLoadTileFile, "Loads a terrain from a section of a larger file.");
loadFromTileCommand.AddArgument("filename",
"The file you wish to load from, the file extension determines the loader to be used. Supported extensions include: " +
supportedFileExtensions, "String");
loadFromTileCommand.AddArgument("file width", "The width of the file in tiles", "Integer");
loadFromTileCommand.AddArgument("file height", "The height of the file in tiles", "Integer");
loadFromTileCommand.AddArgument("minimum X tile", "The X region coordinate of the first section on the file",
"Integer");
loadFromTileCommand.AddArgument("minimum Y tile", "The Y region coordinate of the first section on the file",
"Integer");
// Terrain adjustments
Command fillRegionCommand =
new Command("fill", CommandIntentions.COMMAND_HAZARDOUS, InterfaceFillTerrain, "Fills the current heightmap with a specified value.");
fillRegionCommand.AddArgument("value", "The numeric value of the height you wish to set your region to.",
"Double");
Command elevateCommand =
new Command("elevate", CommandIntentions.COMMAND_HAZARDOUS, InterfaceElevateTerrain, "Raises the current heightmap by the specified amount.");
elevateCommand.AddArgument("amount", "The amount of height to add to the terrain in meters.", "Double");
Command lowerCommand =
new Command("lower", CommandIntentions.COMMAND_HAZARDOUS, InterfaceLowerTerrain, "Lowers the current heightmap by the specified amount.");
lowerCommand.AddArgument("amount", "The amount of height to remove from the terrain in meters.", "Double");
Command multiplyCommand =
new Command("multiply", CommandIntentions.COMMAND_HAZARDOUS, InterfaceMultiplyTerrain, "Multiplies the heightmap by the value specified.");
multiplyCommand.AddArgument("value", "The value to multiply the heightmap by.", "Double");
Command bakeRegionCommand =
new Command("bake", CommandIntentions.COMMAND_HAZARDOUS, InterfaceBakeTerrain, "Saves the current terrain into the regions revert map.");
Command revertRegionCommand =
new Command("revert", CommandIntentions.COMMAND_HAZARDOUS, InterfaceRevertTerrain, "Loads the revert map terrain into the regions heightmap.");
Command flipCommand =
new Command("flip", CommandIntentions.COMMAND_HAZARDOUS, InterfaceFlipTerrain, "Flips the current terrain about the X or Y axis");
flipCommand.AddArgument("direction", "[x|y] the direction to flip the terrain in", "String");
Command rescaleCommand =
new Command("rescale", CommandIntentions.COMMAND_HAZARDOUS, InterfaceRescaleTerrain, "Rescales the current terrain to fit between the given min and max heights");
rescaleCommand.AddArgument("min", "min terrain height after rescaling", "Double");
rescaleCommand.AddArgument("max", "max terrain height after rescaling", "Double");
// Debug
Command showDebugStatsCommand =
new Command("stats", CommandIntentions.COMMAND_STATISTICAL, InterfaceShowDebugStats,
"Shows some information about the regions heightmap for debugging purposes.");
Command experimentalBrushesCommand =
new Command("newbrushes", CommandIntentions.COMMAND_HAZARDOUS, InterfaceEnableExperimentalBrushes,
"Enables experimental brushes which replace the standard terrain brushes. WARNING: This is a debug setting and may be removed at any time.");
experimentalBrushesCommand.AddArgument("Enabled?", "true / false - Enable new brushes", "Boolean");
//Plugins
Command pluginRunCommand =
new Command("effect", CommandIntentions.COMMAND_HAZARDOUS, InterfaceRunPluginEffect, "Runs a specified plugin effect");
pluginRunCommand.AddArgument("name", "The plugin effect you wish to run, or 'list' to see all plugins", "String");
m_commander.RegisterCommand("load", loadFromFileCommand);
m_commander.RegisterCommand("load-tile", loadFromTileCommand);
m_commander.RegisterCommand("save", saveToFileCommand);
m_commander.RegisterCommand("fill", fillRegionCommand);
m_commander.RegisterCommand("elevate", elevateCommand);
m_commander.RegisterCommand("lower", lowerCommand);
m_commander.RegisterCommand("multiply", multiplyCommand);
m_commander.RegisterCommand("bake", bakeRegionCommand);
m_commander.RegisterCommand("revert", revertRegionCommand);
m_commander.RegisterCommand("newbrushes", experimentalBrushesCommand);
m_commander.RegisterCommand("stats", showDebugStatsCommand);
m_commander.RegisterCommand("effect", pluginRunCommand);
m_commander.RegisterCommand("flip", flipCommand);
m_commander.RegisterCommand("rescale", rescaleCommand);
// Add this to our scene so scripts can call these functions
m_scene.RegisterModuleCommander(m_commander);
}
#endregion
}
}
| |
// Copyright 2009 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
using NUnit.Framework;
using System.Linq;
namespace NodaTime.Test
{
/// <summary>
/// Provides methods to help run tests for some of the system interfaces and object support.
/// </summary>
public static class TestHelper
{
public static readonly bool IsRunningOnMono = Type.GetType("Mono.Runtime") != null;
/// <summary>
/// Does nothing other than let us prove method or constructor calls don't throw.
/// </summary>
internal static void Consume<T>(this T ignored)
{
}
/// <summary>
/// Asserts that calling the specified delegate with the specified value throws ArgumentException.
/// </summary>
internal static void AssertInvalid<TArg, TOut>(Func<TArg, TOut> func, TArg arg)
{
Assert.Throws<ArgumentException>(() => func(arg));
}
/// <summary>
/// Asserts that calling the specified delegate with the specified values throws ArgumentException.
/// </summary>
internal static void AssertInvalid<TArg1, TArg2, TOut>(Func<TArg1, TArg2, TOut> func, TArg1 arg1, TArg2 arg2)
{
Assert.Throws<ArgumentException>(() => func(arg1, arg2));
}
/// <summary>
/// Asserts that calling the specified delegate with the specified value throws ArgumentNullException.
/// </summary>
internal static void AssertArgumentNull<TArg, TOut>(Func<TArg, TOut> func, TArg arg)
{
Assert.Throws<ArgumentNullException>(() => func(arg));
}
/// <summary>
/// Asserts that calling the specified delegate with the specified value throws ArgumentOutOfRangeException.
/// </summary>
internal static void AssertOutOfRange<TArg, TOut>(Func<TArg, TOut> func, TArg arg)
{
Assert.Throws<ArgumentOutOfRangeException>(() => func(arg));
}
/// <summary>
/// Asserts that calling the specified delegate with the specified value doesn't throw an exception.
/// </summary>
internal static void AssertValid<TArg, TOut>(Func<TArg, TOut> func, TArg arg)
{
func(arg);
}
/// <summary>
/// Asserts that calling the specified delegate with the specified values throws ArgumentOutOfRangeException.
/// </summary>
internal static void AssertOutOfRange<TArg1, TArg2, TOut>(Func<TArg1, TArg2, TOut> func, TArg1 arg1, TArg2 arg2)
{
Assert.Throws<ArgumentOutOfRangeException>(() => func(arg1, arg2));
}
/// <summary>
/// Asserts that calling the specified delegate with the specified values throws ArgumentNullException.
/// </summary>
internal static void AssertArgumentNull<TArg1, TArg2, TOut>(Func<TArg1, TArg2, TOut> func, TArg1 arg1, TArg2 arg2)
{
Assert.Throws<ArgumentNullException>(() => func(arg1, arg2));
}
/// <summary>
/// Asserts that calling the specified delegate with the specified values doesn't throw an exception.
/// </summary>
internal static void AssertValid<TArg1, TArg2, TOut>(Func<TArg1, TArg2, TOut> func, TArg1 arg1, TArg2 arg2)
{
func(arg1, arg2);
}
/// <summary>
/// Asserts that calling the specified delegate with the specified values throws ArgumentOutOfRangeException.
/// </summary>
internal static void AssertOutOfRange<TArg1, TArg2, TArg3, TOut>(Func<TArg1, TArg2, TArg3, TOut> func, TArg1 arg1, TArg2 arg2, TArg3 arg3)
{
Assert.Throws<ArgumentOutOfRangeException>(() => func(arg1, arg2, arg3));
}
/// <summary>
/// Asserts that calling the specified delegate with the specified values throws ArgumentNullException.
/// </summary>
internal static void AssertArgumentNull<TArg1, TArg2, TArg3, TOut>(Func<TArg1, TArg2, TArg3, TOut> func, TArg1 arg1, TArg2 arg2, TArg3 arg3)
{
Assert.Throws<ArgumentNullException>(() => func(arg1, arg2, arg3));
}
/// <summary>
/// Asserts that calling the specified delegate with the specified values doesn't throw an exception.
/// </summary>
internal static void AssertValid<TArg1, TArg2, TArg3, TOut>(Func<TArg1, TArg2, TArg3, TOut> func, TArg1 arg1, TArg2 arg2, TArg3 arg3)
{
func(arg1, arg2, arg3);
}
/// <summary>
/// Asserts that the given operation throws one of InvalidOperationException, ArgumentException (including
/// ArgumentOutOfRangeException) or OverflowException. (It's hard to always be consistent bearing in mind
/// one method calling another.)
/// </summary>
internal static void AssertOverflow<TArg1, TOut>(Func<TArg1, TOut> func, TArg1 arg1)
{
AssertOverflow(() => func(arg1));
}
/// <summary>
/// Asserts that the given operation throws one of InvalidOperationException, ArgumentException (including
/// ArgumentOutOfRangeException) or OverflowException. (It's hard to always be consistent bearing in mind
/// one method calling another.)
/// </summary>
internal static void AssertOverflow(Action action)
{
try
{
action();
Assert.Fail("Expected OverflowException, ArgumentException, ArgumentOutOfRangeException or InvalidOperationException");
}
catch (OverflowException)
{
}
catch (ArgumentException e)
{
Assert.IsTrue(e.GetType() == typeof(ArgumentException) || e.GetType() == typeof(ArgumentOutOfRangeException),
"Exception should not be a subtype of ArgumentException, other than ArgumentOutOfRangeException");
}
catch (InvalidOperationException)
{
}
}
public static void TestComparerStruct<T>(IComparer<T> comparer, T value, T equalValue, T greaterValue) where T : struct
{
Assert.AreEqual(0, comparer.Compare(value, equalValue));
Assert.AreEqual(1, Math.Sign(comparer.Compare(greaterValue, value)));
Assert.AreEqual(-1, Math.Sign(comparer.Compare(value, greaterValue)));
}
/// <summary>
/// Tests the <see cref="IComparable{T}.CompareTo" /> method for reference objects.
/// </summary>
/// <typeparam name="T">The type to test.</typeparam>
/// <param name="value">The base value.</param>
/// <param name="equalValue">The value equal to but not the same object as the base value.</param>
/// <param name="greaterValue">The values greater than the base value, in ascending order.</param>
public static void TestCompareToClass<T>(T value, T equalValue, params T[] greaterValues) where T : class, IComparable<T>
{
ValidateInput(value, equalValue, greaterValues, "greaterValue");
Assert.Greater(value.CompareTo(null), 0, "value.CompareTo<T>(null)");
Assert.AreEqual(value.CompareTo(value), 0, "value.CompareTo<T>(value)");
Assert.AreEqual(value.CompareTo(equalValue), 0, "value.CompareTo<T>(equalValue)");
Assert.AreEqual(equalValue.CompareTo(value), 0, "equalValue.CompareTo<T>(value)");
foreach (var greaterValue in greaterValues)
{
Assert.Less(value.CompareTo(greaterValue), 0, "value.CompareTo<T>(greaterValue)");
Assert.Greater(greaterValue.CompareTo(value), 0, "greaterValue.CompareTo<T>(value)");
// Now move up to the next pair...
value = greaterValue;
}
}
/// <summary>
/// Tests the <see cref="IComparable{T}.CompareTo" /> method for value objects.
/// </summary>
/// <typeparam name="T">The type to test.</typeparam>
/// <param name="value">The base value.</param>
/// <param name="equalValue">The value equal to but not the same object as the base value.</param>
/// <param name="greaterValue">The values greater than the base value, in ascending order.</param>
public static void TestCompareToStruct<T>(T value, T equalValue, params T[] greaterValues) where T : struct, IComparable<T>
{
Assert.AreEqual(value.CompareTo(value), 0, "value.CompareTo(value)");
Assert.AreEqual(value.CompareTo(equalValue), 0, "value.CompareTo(equalValue)");
Assert.AreEqual(equalValue.CompareTo(value), 0, "equalValue.CompareTo(value)");
foreach (var greaterValue in greaterValues)
{
Assert.Less(value.CompareTo(greaterValue), 0, "value.CompareTo(greaterValue)");
Assert.Greater(greaterValue.CompareTo(value), 0, "greaterValue.CompareTo(value)");
// Now move up to the next pair...
value = greaterValue;
}
}
/// <summary>
/// Tests the <see cref="IComparable.CompareTo" /> method - note that this is the non-generic interface.
/// </summary>
/// <typeparam name="T">The type to test.</typeparam>
/// <param name="value">The base value.</param>
/// <param name="equalValue">The value equal to but not the same object as the base value.</param>
/// <param name="greaterValue">The values greater than the base value, in ascending order.</param>
public static void TestNonGenericCompareTo<T>(T value, T equalValue, params T[] greaterValues) where T : IComparable
{
// Just type the values as plain IComparable for simplicity
IComparable value2 = value;
IComparable equalValue2 = equalValue;
ValidateInput(value2, equalValue2, greaterValues, "greaterValues");
Assert.Greater(value2.CompareTo(null), 0, "value.CompareTo(null)");
Assert.AreEqual(value2.CompareTo(value2), 0, "value.CompareTo(value)");
Assert.AreEqual(value2.CompareTo(equalValue2), 0, "value.CompareTo(equalValue)");
Assert.AreEqual(equalValue2.CompareTo(value2), 0, "equalValue.CompareTo(value)");
foreach (IComparable greaterValue in greaterValues)
{
Assert.Less(value2.CompareTo(greaterValue), 0, "value.CompareTo(greaterValue)");
Assert.Greater(greaterValue.CompareTo(value2), 0, "greaterValue.CompareTo(value)");
// Now move up to the next pair...
value2 = greaterValue;
}
Assert.Throws<ArgumentException>(() => value2.CompareTo(new object()));
}
/// <summary>
/// Tests the IEquatable.Equals method for reference objects. Also tests the
/// object equals method.
/// </summary>
/// <typeparam name="T">The type to test.</typeparam>
/// <param name="value">The base value.</param>
/// <param name="equalValue">The value equal to but not the same object as the base value.</param>
/// <param name="unEqualValue">The value not equal to the base value.</param>
public static void TestEqualsClass<T>(T value, T equalValue, T unEqualValue) where T : class, IEquatable<T>
{
TestObjectEquals(value, equalValue, unEqualValue);
Assert.False(value.Equals(null), "value.Equals<T>(null)");
Assert.True(value.Equals(value), "value.Equals<T>(value)");
Assert.True(value.Equals(equalValue), "value.Equals<T>(equalValue)");
Assert.True(equalValue.Equals(value), "equalValue.Equals<T>(value)");
Assert.False(value.Equals(unEqualValue), "value.Equals<T>(unEqualValue)");
}
/// <summary>
/// Tests the IEquatable.Equals method for value objects. Also tests the
/// object equals method.
/// </summary>
/// <typeparam name="T">The type to test.</typeparam>
/// <param name="value">The base value.</param>
/// <param name="equalValue">The value equal to but not the same object as the base value.</param>
/// <param name="unEqualValue">The value not equal to the base value.</param>
public static void TestEqualsStruct<T>(T value, T equalValue, params T[] unEqualValues) where T : struct, IEquatable<T>
{
var unEqualArray = unEqualValues.Cast<object>().ToArray();
TestObjectEquals(value, equalValue, unEqualArray);
Assert.True(value.Equals(value), "value.Equals<T>(value)");
Assert.True(value.Equals(equalValue), "value.Equals<T>(equalValue)");
Assert.True(equalValue.Equals(value), "equalValue.Equals<T>(value)");
foreach (var unEqualValue in unEqualValues)
{
Assert.False(value.Equals(unEqualValue), "value.Equals<T>(unEqualValue)");
}
}
/// <summary>
/// Tests the Object.Equals method.
/// </summary>
/// <remarks>
/// It takes two equal values, and then an array of values which should not be equal to the first argument.
/// </remarks>
/// <param name="value">The base value.</param>
/// <param name="equalValue">The value equal to but not the same object as the base value.</param>
/// <param name="unEqualValue">The value not equal to the base value.</param>
public static void TestObjectEquals(object value, object equalValue, params object[] unEqualValues)
{
ValidateInput(value, equalValue, unEqualValues, "unEqualValue");
Assert.False(value.Equals(null), "value.Equals(null)");
Assert.True(value.Equals(value), "value.Equals(value)");
Assert.True(value.Equals(equalValue), "value.Equals(equalValue)");
Assert.True(equalValue.Equals(value), "equalValue.Equals(value)");
foreach (var unEqualValue in unEqualValues)
{
Assert.False(value.Equals(unEqualValue), "value.Equals(unEqualValue)");
}
Assert.AreEqual(value.GetHashCode(), value.GetHashCode(), "GetHashCode() twice for same object");
Assert.AreEqual(value.GetHashCode(), equalValue.GetHashCode(), "GetHashCode() for two different but equal objects");
}
/// <summary>
/// Tests the less than (^lt;) and greater than (>) operators if they exist on the object.
/// </summary>
/// <typeparam name="T">The type to test.</typeparam>
/// <param name="value">The base value.</param>
/// <param name="equalValue">The value equal to but not the same object as the base value.</param>
/// <param name="greaterValue">The values greater than the base value, in ascending order.</param>
public static void TestOperatorComparison<T>(T value, T equalValue, params T[] greaterValues)
{
ValidateInput(value, equalValue, greaterValues, "greaterValue");
Type type = typeof(T);
var greaterThan = type.GetMethod("op_GreaterThan", new[] { type, type });
var lessThan = type.GetMethod("op_LessThan", new[] { type, type });
// Comparisons only involving equal values
if (greaterThan != null)
{
if (!type.IsValueType)
{
Assert.True((bool) greaterThan.Invoke(null, new object[] { value, null }), "value > null");
Assert.False((bool) greaterThan.Invoke(null, new object[] { null, value }), "null > value");
}
Assert.False((bool) greaterThan.Invoke(null, new object[] { value, value }), "value > value");
Assert.False((bool) greaterThan.Invoke(null, new object[] { value, equalValue }), "value > equalValue");
Assert.False((bool) greaterThan.Invoke(null, new object[] { equalValue, value }), "equalValue > value");
}
if (lessThan != null)
{
if (!type.IsValueType)
{
Assert.False((bool) lessThan.Invoke(null, new object[] { value, null }), "value < null");
Assert.True((bool) lessThan.Invoke(null, new object[] { null, value }), "null < value");
}
Assert.False((bool) lessThan.Invoke(null, new object[] { value, value }), "value < value");
Assert.False((bool) lessThan.Invoke(null, new object[] { value, equalValue }), "value < equalValue");
Assert.False((bool) lessThan.Invoke(null, new object[] { equalValue, value }), "equalValue < value");
}
// Then comparisons involving the greater values
foreach (var greaterValue in greaterValues)
{
if (greaterThan != null)
{
Assert.False((bool) greaterThan.Invoke(null, new object[] { value, greaterValue }), "value > greaterValue");
Assert.True((bool) greaterThan.Invoke(null, new object[] { greaterValue, value }), "greaterValue > value");
}
if (lessThan != null)
{
Assert.True((bool) lessThan.Invoke(null, new object[] { value, greaterValue }), "value < greaterValue");
Assert.False((bool) lessThan.Invoke(null, new object[] { greaterValue, value }), "greaterValue < value");
}
// Now move up to the next pair...
value = greaterValue;
}
}
/// <summary>
/// Tests the equality (==), inequality (!=), less than (<), greater than (>), less than or equals (<=),
/// and greater than or equals (>=) operators if they exist on the object.
/// </summary>
/// <typeparam name="T">The type to test.</typeparam>
/// <param name="value">The base value.</param>
/// <param name="equalValue">The value equal to but not the same object as the base value.</param>
/// <param name="greaterValue">The values greater than the base value, in ascending order.</param>
public static void TestOperatorComparisonEquality<T>(T value, T equalValue, params T[] greaterValues)
{
foreach (var greaterValue in greaterValues)
{
TestOperatorEquality(value, equalValue, greaterValue);
}
TestOperatorComparison(value, equalValue, greaterValues);
Type type = typeof(T);
var greaterThanOrEqual = type.GetMethod("op_GreaterThanOrEqual", new[] { type, type });
var lessThanOrEqual = type.GetMethod("op_LessThanOrEqual", new[] { type, type });
// First the comparisons with equal values
if (greaterThanOrEqual != null)
{
if (!type.IsValueType)
{
Assert.True((bool) greaterThanOrEqual.Invoke(null, new object[] { value, null }), "value >= null");
Assert.False((bool) greaterThanOrEqual.Invoke(null, new object[] { null, value }), "null >= value");
}
Assert.True((bool) greaterThanOrEqual.Invoke(null, new object[] { value, value }), "value >= value");
Assert.True((bool) greaterThanOrEqual.Invoke(null, new object[] { value, equalValue }), "value >= equalValue");
Assert.True((bool) greaterThanOrEqual.Invoke(null, new object[] { equalValue, value }), "equalValue >= value");
}
if (lessThanOrEqual != null)
{
if (!type.IsValueType)
{
Assert.False((bool) lessThanOrEqual.Invoke(null, new object[] { value, null }), "value <= null");
Assert.True((bool) lessThanOrEqual.Invoke(null, new object[] { null, value }), "null <= value");
}
Assert.True((bool) lessThanOrEqual.Invoke(null, new object[] { value, value }), "value <= value");
Assert.True((bool) lessThanOrEqual.Invoke(null, new object[] { value, equalValue }), "value <= equalValue");
Assert.True((bool) lessThanOrEqual.Invoke(null, new object[] { equalValue, value }), "equalValue <= value");
}
// Now the "greater than" values
foreach (var greaterValue in greaterValues)
{
if (greaterThanOrEqual != null)
{
Assert.False((bool) greaterThanOrEqual.Invoke(null, new object[] { value, greaterValue }), "value >= greaterValue");
Assert.True((bool) greaterThanOrEqual.Invoke(null, new object[] { greaterValue, value }), "greaterValue >= value");
}
if (lessThanOrEqual != null)
{
Assert.True((bool) lessThanOrEqual.Invoke(null, new object[] { value, greaterValue }), "value <= greaterValue");
Assert.False((bool) lessThanOrEqual.Invoke(null, new object[] { greaterValue, value }), "greaterValue <= value");
}
// Now move up to the next pair...
value = greaterValue;
}
}
/// <summary>
/// Tests the equality and inequality operators (==, !=) if they exist on the object.
/// </summary>
/// <typeparam name="T">The type to test.</typeparam>
/// <param name="value">The base value.</param>
/// <param name="equalValue">The value equal to but not the same object as the base value.</param>
/// <param name="unEqualValue">The value not equal to the base value.</param>
public static void TestOperatorEquality<T>(T value, T equalValue, T unEqualValue)
{
ValidateInput(value, equalValue, unEqualValue, "unEqualValue");
Type type = typeof(T);
var equality = type.GetMethod("op_Equality", new[] { type, type });
if (equality != null)
{
if (!type.IsValueType)
{
Assert.True((bool)equality.Invoke(null, new object[] { null, null }), "null == null");
Assert.False((bool)equality.Invoke(null, new object[] { value, null }), "value == null");
Assert.False((bool)equality.Invoke(null, new object[] { null, value }), "null == value");
}
Assert.True((bool)equality.Invoke(null, new object[] { value, value }), "value == value");
Assert.True((bool)equality.Invoke(null, new object[] { value, equalValue }), "value == equalValue");
Assert.True((bool)equality.Invoke(null, new object[] { equalValue, value }), "equalValue == value");
Assert.False((bool)equality.Invoke(null, new object[] { value, unEqualValue }), "value == unEqualValue");
}
var inequality = type.GetMethod("op_Inequality", new[] { type, type });
if (inequality != null)
{
if (!type.IsValueType)
{
Assert.False((bool)inequality.Invoke(null, new object[] { null, null }), "null != null");
Assert.True((bool)inequality.Invoke(null, new object[] { value, null }), "value != null");
Assert.True((bool)inequality.Invoke(null, new object[] { null, value }), "null != value");
}
Assert.False((bool)inequality.Invoke(null, new object[] { value, value }), "value != value");
Assert.False((bool)inequality.Invoke(null, new object[] { value, equalValue }), "value != equalValue");
Assert.False((bool)inequality.Invoke(null, new object[] { equalValue, value }), "equalValue != value");
Assert.True((bool)inequality.Invoke(null, new object[] { value, unEqualValue }), "value != unEqualValue");
}
}
internal static void AssertXmlRoundtrip<T>(T value, string expectedXml) where T : IXmlSerializable, new()
{
AssertXmlRoundtrip(value, expectedXml, EqualityComparer<T>.Default);
}
/// <summary>
/// Validates that the given value can be serialized, and that deserializing the same data
/// returns an equal value.
/// </summary>
/// <remarks>
/// This method is effectively ignored in the PCL tests - that means all the binary serialization tests
/// do nothing on the PCL, but it's simpler than conditionalizing each one of them.
/// </remarks>
internal static void AssertBinaryRoundtrip<T>(T value)
{
// Can't use [Conditional("!PCL")] as ConditionalAttribute is only positive.
// This approach seems to confuse the build system less, too.
#if !PCL
var stream = new MemoryStream();
new BinaryFormatter().Serialize(stream, value);
stream.Position = 0;
var rehydrated = (T)new BinaryFormatter().Deserialize(stream);
Assert.AreEqual(value, rehydrated);
#endif
}
/// <summary>
/// Validates that a value can be serialized to the expected XML, deserialized to an equal
/// value, and that a direct call of ReadXml on a value with an XmlReader initially positioned
/// at an element will read to the end of that element.
/// </summary>
internal static void AssertXmlRoundtrip<T>(T value, string expectedXml, IEqualityComparer<T> comparer)
where T : IXmlSerializable, new()
{
XmlSerializer serializer = new XmlSerializer(typeof(SerializationHelper<T>));
var helper = new SerializationHelper<T> { Value = value, Before = 100, After = 200 };
using (var stream = new MemoryStream())
{
serializer.Serialize(stream, helper);
stream.Position = 0;
var result = (SerializationHelper<T>) serializer.Deserialize(stream);
Assert.IsTrue(comparer.Equals(result.Value, value), "Expected " + value + "; was " + result.Value);
// Validate the rest of the object deserialization is still okay.
Assert.AreEqual(100, result.Before);
Assert.AreEqual(200, result.After);
stream.Position = 0;
var element = XElement.Load(stream).Element("value");
Assert.AreEqual(element.ToString(), expectedXml);
}
AssertReadXmlConsumesElement<T>(expectedXml);
}
internal static void AssertParsableXml<T>(T expectedValue, string validXml) where T : IXmlSerializable, new()
{
AssertParsableXml(expectedValue, validXml, EqualityComparer<T>.Default);
}
internal static void AssertParsableXml<T>(T expectedValue, string validXml, IEqualityComparer<T> comparer)
where T : IXmlSerializable, new()
{
XmlSerializer serializer = new XmlSerializer(typeof(SerializationHelper<T>));
// Serialize any value, just so we can replace the <value> element.
var helper = new SerializationHelper<T> { Value = new T(), Before = 100, After = 200 };
using (var stream = new MemoryStream())
{
serializer.Serialize(stream, helper);
stream.Position = 0;
var doc = XElement.Load(stream);
doc.Element("value").ReplaceWith(XElement.Parse(validXml));
var result = (SerializationHelper<T>) serializer.Deserialize(doc.CreateReader());
Assert.IsTrue(comparer.Equals(result.Value, expectedValue), "Expected " + expectedValue + "; was " + result.Value);
// Validate the rest of the object deserialization is still okay.
Assert.AreEqual(100, result.Before);
Assert.AreEqual(200, result.After);
}
AssertReadXmlConsumesElement<T>(validXml);
}
private static void AssertReadXmlConsumesElement<T>(string validXml) where T : IXmlSerializable, new()
{
XElement element = XElement.Parse(validXml);
var root = new XElement("root", element, new XElement("after"));
var reader = root.CreateReader();
reader.ReadToDescendant(element.Name.LocalName);
var value = new T();
value.ReadXml(reader);
Assert.AreEqual(XmlNodeType.Element, reader.NodeType);
Assert.AreEqual("after", reader.Name);
}
internal static void AssertXmlInvalid<T>(string invalidXml, Type expectedExceptionType) where T : new()
{
XmlSerializer serializer = new XmlSerializer(typeof(SerializationHelper<T>));
// Serialize any value, just so we can replace the <value> element.
var helper = new SerializationHelper<T> { Value = new T() };
using (var stream = new MemoryStream())
{
serializer.Serialize(stream, helper);
stream.Position = 0;
var doc = XElement.Load(stream);
doc.Element("value").ReplaceWith(XElement.Parse(invalidXml));
// Sometimes exceptions are wrapped in InvalidOperationException, sometimes they're not. It's not
// always easy to predict. (.NET always does; old Mono never does; new Mono sometimes does - I think.)
// Odd that I can't just specify "well it throws something, I'll check the details later". Oh well.
var exception = Assert.Throws(Is.InstanceOf(typeof(Exception)), () => serializer.Deserialize(doc.CreateReader()));
if (exception is InvalidOperationException)
{
exception = exception.InnerException;
}
Assert.IsInstanceOf(expectedExceptionType, exception);
}
}
/// <summary>
/// Validates that the input parameters to the test methods are valid.
/// </summary>
/// <param name="value">The base value.</param>
/// <param name="equalValue">The value equal to but not the same object as the base value.</param>
/// <param name="unEqualValues">The values not equal to the base value.</param>
/// <param name="unEqualName">The name to use in "not equal value" error messages.</param>
private static void ValidateInput(object value, object equalValue, object[] unEqualValues, string unEqualName)
{
Assert.NotNull(value, "value cannot be null in TestObjectEquals() method");
Assert.NotNull(equalValue, "equalValue cannot be null in TestObjectEquals() method");
Assert.AreNotSame(value, equalValue, "value and equalValue MUST be different objects");
foreach (var unEqualValue in unEqualValues)
{
Assert.NotNull(unEqualValue, unEqualName + " cannot be null in TestObjectEquals() method");
Assert.AreNotSame(value, unEqualValue, unEqualName + " and value MUST be different objects");
}
}
/// <summary>
/// Validates that the input parameters to the test methods are valid.
/// </summary>
/// <param name="value">The base value.</param>
/// <param name="equalValue">The value equal to but not the same object as the base value.</param>
/// <param name="unEqualValue">The value not equal to the base value.</param>
/// <param name="unEqualName">The name to use in "not equal value" error messages.</param>
private static void ValidateInput(object value, object equalValue, object unEqualValue, string unEqualName)
{
ValidateInput(value, equalValue, new object[] { unEqualValue }, unEqualName);
}
}
/// <summary>
/// Class used in XML serialization tests. This would be nested within TestHelper,
/// but some environments don't like serializing nested types within static types.
/// </summary>
/// <typeparam name="T">Type of value to serialize</typeparam>
public class SerializationHelper<T>
{
[XmlElement("before")]
public int Before { get; set; }
[XmlElement("value")]
public T Value { get; set; }
[XmlElement("after")]
public int After { get; set; }
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.Eventhub.Fluent
{
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.Azure.Management.Eventhub.Fluent.EventHubDisasterRecoveryPairing.Definition;
using Microsoft.Azure.Management.Eventhub.Fluent.EventHubDisasterRecoveryPairing.Update;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions;
using Microsoft.Azure.Management.EventHub.Fluent.Models;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
internal partial class EventHubDisasterRecoveryPairingImpl
{
/// <summary>
/// Specifies that the given namespace should be used as secondary namespace in disaster recovery pairing.
/// </summary>
/// <param name="namespaceId">The secondary namespace.</param>
/// <return>Next stage of the disaster recovery pairing definition.</return>
EventHubDisasterRecoveryPairing.Definition.IWithCreate EventHubDisasterRecoveryPairing.Definition.IWithSecondaryNamespace.WithExistingSecondaryNamespaceId(string namespaceId)
{
return this.WithExistingSecondaryNamespaceId(namespaceId);
}
/// <summary>
/// Specifies that the given namespace should be used as secondary namespace in disaster recovery pairing.
/// </summary>
/// <param name="namespaceCreatable">Creatable definition for the primary namespace.</param>
/// <return>Next stage of the event hub definition.</return>
EventHubDisasterRecoveryPairing.Definition.IWithCreate EventHubDisasterRecoveryPairing.Definition.IWithSecondaryNamespace.WithNewSecondaryNamespace(ICreatable<Microsoft.Azure.Management.Eventhub.Fluent.IEventHubNamespace> namespaceCreatable)
{
return this.WithNewSecondaryNamespace(namespaceCreatable);
}
/// <summary>
/// Specifies that the given namespace should be used as secondary namespace in disaster recovery pairing.
/// </summary>
/// <param name="namespace">The secondary namespace.</param>
/// <return>Next stage of the disaster recovery pairing definition.</return>
EventHubDisasterRecoveryPairing.Definition.IWithCreate EventHubDisasterRecoveryPairing.Definition.IWithSecondaryNamespace.WithExistingSecondaryNamespace(IEventHubNamespace ehNamespace)
{
return this.WithExistingSecondaryNamespace(ehNamespace);
}
/// <summary>
/// Specifies that the given namespace should be used as secondary namespace in disaster recovery pairing.
/// </summary>
/// <param name="namespaceId">The secondary namespace.</param>
/// <return>Next stage of the disaster recovery pairing update.</return>
EventHubDisasterRecoveryPairing.Update.IUpdate EventHubDisasterRecoveryPairing.Update.IWithSecondaryNamespace.WithExistingSecondaryNamespaceId(string namespaceId)
{
return this.WithExistingSecondaryNamespaceId(namespaceId);
}
/// <summary>
/// Specifies that the given namespace should be used as secondary namespace in disaster recovery pairing.
/// </summary>
/// <param name="namespaceCreatable">Creatable definition for the secondary namespace.</param>
/// <return>Next stage of the disaster recovery pairing update.</return>
EventHubDisasterRecoveryPairing.Update.IUpdate EventHubDisasterRecoveryPairing.Update.IWithSecondaryNamespace.WithNewSecondaryNamespace(ICreatable<Microsoft.Azure.Management.Eventhub.Fluent.IEventHubNamespace> namespaceCreatable)
{
return this.WithNewSecondaryNamespace(namespaceCreatable);
}
/// <summary>
/// Specifies that the given namespace should be used as secondary namespace in disaster recovery pairing.
/// </summary>
/// <param name="namespace">The secondary event hub namespace.</param>
/// <return>Next stage of the disaster recovery pairing update.</return>
EventHubDisasterRecoveryPairing.Update.IUpdate EventHubDisasterRecoveryPairing.Update.IWithSecondaryNamespace.WithExistingSecondaryNamespace(IEventHubNamespace ehNamespace)
{
return this.WithExistingSecondaryNamespace(ehNamespace);
}
/// <summary>
/// Specifies that the given namespace should be used as primary namespace in disaster recovery pairing.
/// </summary>
/// <param name="namespaceId">The primary namespace.</param>
/// <return>Next stage of the disaster recovery pairing definition.</return>
EventHubDisasterRecoveryPairing.Definition.IWithSecondaryNamespace EventHubDisasterRecoveryPairing.Definition.IWithPrimaryNamespace.WithExistingPrimaryNamespaceId(string namespaceId)
{
return this.WithExistingPrimaryNamespaceId(namespaceId);
}
/// <summary>
/// Specifies that the given namespace should be used as primary namespace in disaster recovery pairing.
/// </summary>
/// <param name="namespaceCreatable">Creatable definition for the primary namespace.</param>
/// <return>Next stage of the disaster recovery pairing definition.</return>
EventHubDisasterRecoveryPairing.Definition.IWithSecondaryNamespace EventHubDisasterRecoveryPairing.Definition.IWithPrimaryNamespace.WithNewPrimaryNamespace(ICreatable<Microsoft.Azure.Management.Eventhub.Fluent.IEventHubNamespace> namespaceCreatable)
{
return this.WithNewPrimaryNamespace(namespaceCreatable);
}
/// <summary>
/// Specifies that the given namespace should be used as primary namespace in disaster recovery pairing.
/// </summary>
/// <param name="namespace">The primary event hub namespace.</param>
/// <return>Next stage of the disaster recovery pairing definition.</return>
EventHubDisasterRecoveryPairing.Definition.IWithSecondaryNamespace EventHubDisasterRecoveryPairing.Definition.IWithPrimaryNamespace.WithExistingPrimaryNamespace(IEventHubNamespace ehNamespace)
{
return this.WithExistingPrimaryNamespace(ehNamespace);
}
/// <summary>
/// Specifies that the given namespace should be used as primary namespace in disaster recovery pairing.
/// </summary>
/// <param name="resourceGroupName">Resource group name of primary namespace.</param>
/// <param name="namespaceName">The primary namespace.</param>
/// <return>Next stage of the disaster recovery pairing definition.</return>
EventHubDisasterRecoveryPairing.Definition.IWithSecondaryNamespace EventHubDisasterRecoveryPairing.Definition.IWithPrimaryNamespace.WithExistingPrimaryNamespace(string resourceGroupName, string namespaceName)
{
return this.WithExistingPrimaryNamespace(resourceGroupName, namespaceName);
}
/// <summary>
/// Gets Perform fail over so that the secondary namespace becomes the primary.
/// </summary>
/// <summary>
/// Gets completable representing the fail-over action.
/// </summary>
async Task Microsoft.Azure.Management.Eventhub.Fluent.IEventHubDisasterRecoveryPairing.FailOverAsync(CancellationToken cancellationToken = default(CancellationToken))
{
await this.FailOverAsync(cancellationToken);
}
/// <summary>
/// Gets secondary event hub namespace in the pairing.
/// </summary>
string Microsoft.Azure.Management.Eventhub.Fluent.IEventHubDisasterRecoveryPairing.SecondaryNamespaceId
{
get
{
return this.SecondaryNamespaceId();
}
}
/// <summary>
/// Gets provisioning state of the pairing.
/// </summary>
ProvisioningStateDR? Microsoft.Azure.Management.Eventhub.Fluent.IEventHubDisasterRecoveryPairing.ProvisioningState
{
get
{
return this.ProvisioningState();
}
}
/// <summary>
/// Gets primary event hub namespace resource group.
/// </summary>
string Microsoft.Azure.Management.Eventhub.Fluent.IEventHubDisasterRecoveryPairing.PrimaryNamespaceResourceGroupName
{
get
{
return this.PrimaryNamespaceResourceGroupName();
}
}
/// <summary>
/// Gets primary event hub namespace in the pairing.
/// </summary>
string Microsoft.Azure.Management.Eventhub.Fluent.IEventHubDisasterRecoveryPairing.PrimaryNamespaceName
{
get
{
return this.PrimaryNamespaceName();
}
}
/// <summary>
/// Gets the namespace role.
/// </summary>
RoleDisasterRecovery? Microsoft.Azure.Management.Eventhub.Fluent.IEventHubDisasterRecoveryPairing.NamespaceRole
{
get
{
return this.NamespaceRole();
}
}
/// <summary>
/// Gets Break the pairing between a primary and secondary namespace.
/// </summary>
/// <summary>
/// Gets completable representing the pairing break action.
/// </summary>
async Task Microsoft.Azure.Management.Eventhub.Fluent.IEventHubDisasterRecoveryPairing.BreakPairingAsync(CancellationToken cancellationToken = default(CancellationToken))
{
await this.BreakPairingAsync(cancellationToken);
}
/// <summary>
/// Perform fail over so that the secondary namespace becomes the primary.
/// </summary>
void Microsoft.Azure.Management.Eventhub.Fluent.IEventHubDisasterRecoveryPairing.FailOver()
{
this.FailOver();
}
/// <return>The authorization rules for the event hub disaster recovery pairing.</return>
System.Collections.Generic.IEnumerable<Microsoft.Azure.Management.Eventhub.Fluent.IDisasterRecoveryPairingAuthorizationRule> Microsoft.Azure.Management.Eventhub.Fluent.IEventHubDisasterRecoveryPairing.ListAuthorizationRules()
{
return this.ListAuthorizationRules();
}
/// <return>The authorization rules for the event hub disaster recovery pairing.</return>
async Task<IPagedCollection<Microsoft.Azure.Management.Eventhub.Fluent.IDisasterRecoveryPairingAuthorizationRule>> Microsoft.Azure.Management.Eventhub.Fluent.IEventHubDisasterRecoveryPairing.ListAuthorizationRulesAsync(CancellationToken cancellationToken)
{
return await this.ListAuthorizationRulesAsync(cancellationToken);
}
/// <summary>
/// Break the pairing between a primary and secondary namespace.
/// </summary>
void Microsoft.Azure.Management.Eventhub.Fluent.IEventHubDisasterRecoveryPairing.BreakPairing()
{
this.BreakPairing();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Recipe.Web.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
if (createdObjectReferences.TryGetValue(type, out object result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(bool), index => true },
{ typeof(byte), index => (byte)64 },
{ typeof(char), index => (char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(decimal), index => (decimal)index },
{ typeof(double), index => (double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(short), index => (short)(index % short.MaxValue) },
{ typeof(int), index => (int)(index % int.MaxValue) },
{ typeof(long), index => (long)index },
{ typeof(object), index => new object() },
{ typeof(sbyte), index => (sbyte)64 },
{ typeof(float), index => (float)(index + 0.1) },
{
typeof(string), index =>
{
return string.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(ushort), index => (ushort)(index % ushort.MaxValue) },
{ typeof(uint), index => (uint)(index % uint.MaxValue) },
{ typeof(ulong), index => (ulong)index },
{
typeof(Uri), index =>
{
return new Uri(string.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
namespace UnityStandardAssets.Characters.FirstPerson
{
[RequireComponent(typeof (Rigidbody))]
[RequireComponent(typeof (CapsuleCollider))]
public class RigidbodyFirstPersonController : MonoBehaviour
{
[Serializable]
public class MovementSettings
{
public float ForwardSpeed = 8.0f; // Speed when walking forward
public float BackwardSpeed = 4.0f; // Speed when walking backwards
public float StrafeSpeed = 4.0f; // Speed when walking sideways
public float RunMultiplier = 2.0f; // Speed when sprinting
public KeyCode RunKey = KeyCode.LeftShift;
public float JumpForce = 30f;
public AnimationCurve SlopeCurveModifier = new AnimationCurve(new Keyframe(-90.0f, 1.0f), new Keyframe(0.0f, 1.0f), new Keyframe(90.0f, 0.0f));
[HideInInspector] public float CurrentTargetSpeed = 8f;
#if !MOBILE_INPUT
private bool m_Running;
#endif
public void UpdateDesiredTargetSpeed(Vector2 input)
{
if (input == Vector2.zero) return;
if (input.x > 0 || input.x < 0)
{
//strafe
CurrentTargetSpeed = StrafeSpeed;
}
if (input.y < 0)
{
//backwards
CurrentTargetSpeed = BackwardSpeed;
}
if (input.y > 0)
{
//forwards
//handled last as if strafing and moving forward at the same time forwards speed should take precedence
CurrentTargetSpeed = ForwardSpeed;
}
#if !MOBILE_INPUT
if (Input.GetKey(RunKey))
{
CurrentTargetSpeed *= RunMultiplier;
m_Running = true;
}
else
{
m_Running = false;
}
#endif
}
#if !MOBILE_INPUT
public bool Running
{
get { return m_Running; }
}
#endif
}
[Serializable]
public class AdvancedSettings
{
public float groundCheckDistance = 0.01f; // distance for checking if the controller is grounded ( 0.01f seems to work best for this )
public float stickToGroundHelperDistance = 0.5f; // stops the character
public float slowDownRate = 20f; // rate at which the controller comes to a stop when there is no input
public bool airControl; // can the user control the direction that is being moved in the air
[Tooltip("set it to 0.1 or more if you get stuck in wall")]
public float shellOffset; //reduce the radius by that ratio to avoid getting stuck in wall (a value of 0.1f is nice)
}
public Camera cam;
public MovementSettings movementSettings = new MovementSettings();
public MouseLook mouseLook = new MouseLook();
public AdvancedSettings advancedSettings = new AdvancedSettings();
private Rigidbody m_RigidBody;
private CapsuleCollider m_Capsule;
#pragma warning disable 0649, 0169
private float m_YRotation;
private Vector3 m_GroundContactNormal;
private bool m_Jump, m_PreviouslyGrounded, m_Jumping, m_IsGrounded;
public Vector3 Velocity
{
get { return m_RigidBody.velocity; }
}
public bool Grounded
{
get { return m_IsGrounded; }
}
public bool Jumping
{
get { return m_Jumping; }
}
public bool Running
{
get
{
#if !MOBILE_INPUT
return movementSettings.Running;
#else
return false;
#endif
}
}
private void Start()
{
m_RigidBody = GetComponent<Rigidbody>();
m_Capsule = GetComponent<CapsuleCollider>();
mouseLook.Init (transform, cam.transform);
}
private void Update()
{
RotateView();
if (CrossPlatformInputManager.GetButtonDown("Jump") && !m_Jump)
{
m_Jump = true;
}
}
private void FixedUpdate()
{
GroundCheck();
Vector2 input = GetInput();
if ((Mathf.Abs(input.x) > float.Epsilon || Mathf.Abs(input.y) > float.Epsilon) && (advancedSettings.airControl || m_IsGrounded))
{
// always move along the camera forward as it is the direction that it being aimed at
Vector3 desiredMove = cam.transform.forward*input.y + cam.transform.right*input.x;
desiredMove = Vector3.ProjectOnPlane(desiredMove, m_GroundContactNormal).normalized;
desiredMove.x = desiredMove.x*movementSettings.CurrentTargetSpeed;
desiredMove.z = desiredMove.z*movementSettings.CurrentTargetSpeed;
desiredMove.y = desiredMove.y*movementSettings.CurrentTargetSpeed;
if (m_RigidBody.velocity.sqrMagnitude <
(movementSettings.CurrentTargetSpeed*movementSettings.CurrentTargetSpeed))
{
m_RigidBody.AddForce(desiredMove*SlopeMultiplier(), ForceMode.Impulse);
}
}
if (m_IsGrounded)
{
m_RigidBody.drag = 5f;
if (m_Jump)
{
m_RigidBody.drag = 0f;
m_RigidBody.velocity = new Vector3(m_RigidBody.velocity.x, 0f, m_RigidBody.velocity.z);
m_RigidBody.AddForce(new Vector3(0f, movementSettings.JumpForce, 0f), ForceMode.Impulse);
m_Jumping = true;
}
if (!m_Jumping && Mathf.Abs(input.x) < float.Epsilon && Mathf.Abs(input.y) < float.Epsilon && m_RigidBody.velocity.magnitude < 1f)
{
m_RigidBody.Sleep();
}
}
else
{
m_RigidBody.drag = 0f;
if (m_PreviouslyGrounded && !m_Jumping)
{
StickToGroundHelper();
}
}
m_Jump = false;
}
private float SlopeMultiplier()
{
float angle = Vector3.Angle(m_GroundContactNormal, Vector3.up);
return movementSettings.SlopeCurveModifier.Evaluate(angle);
}
private void StickToGroundHelper()
{
RaycastHit hitInfo;
if (Physics.SphereCast(transform.position, m_Capsule.radius * (1.0f - advancedSettings.shellOffset), Vector3.down, out hitInfo,
((m_Capsule.height/2f) - m_Capsule.radius) +
advancedSettings.stickToGroundHelperDistance, Physics.AllLayers, QueryTriggerInteraction.Ignore))
{
if (Mathf.Abs(Vector3.Angle(hitInfo.normal, Vector3.up)) < 85f)
{
m_RigidBody.velocity = Vector3.ProjectOnPlane(m_RigidBody.velocity, hitInfo.normal);
}
}
}
private Vector2 GetInput()
{
Vector2 input = new Vector2
{
x = CrossPlatformInputManager.GetAxis("Horizontal"),
y = CrossPlatformInputManager.GetAxis("Vertical")
};
movementSettings.UpdateDesiredTargetSpeed(input);
return input;
}
private void RotateView()
{
//avoids the mouse looking if the game is effectively paused
if (Mathf.Abs(Time.timeScale) < float.Epsilon) return;
// get the rotation before it's changed
float oldYRotation = transform.eulerAngles.y;
mouseLook.LookRotation (transform, cam.transform);
if (m_IsGrounded || advancedSettings.airControl)
{
// Rotate the rigidbody velocity to match the new direction that the character is looking
Quaternion velRotation = Quaternion.AngleAxis(transform.eulerAngles.y - oldYRotation, Vector3.up);
m_RigidBody.velocity = velRotation*m_RigidBody.velocity;
}
}
/// sphere cast down just beyond the bottom of the capsule to see if the capsule is colliding round the bottom
private void GroundCheck()
{
m_PreviouslyGrounded = m_IsGrounded;
RaycastHit hitInfo;
if (Physics.SphereCast(transform.position, m_Capsule.radius * (1.0f - advancedSettings.shellOffset), Vector3.down, out hitInfo,
((m_Capsule.height/2f) - m_Capsule.radius) + advancedSettings.groundCheckDistance, Physics.AllLayers, QueryTriggerInteraction.Ignore))
{
m_IsGrounded = true;
m_GroundContactNormal = hitInfo.normal;
}
else
{
m_IsGrounded = false;
m_GroundContactNormal = Vector3.up;
}
if (!m_PreviouslyGrounded && m_IsGrounded && m_Jumping)
{
m_Jumping = false;
}
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Drawing.Drawing2D;
using System.Drawing.Printing;
using Microsoft.Win32;
//using AxSHDocVw;
//using MSHTML;
using UWin32;
namespace UWin32
{
public class user32
{
[DllImport("user32.dll", EntryPoint="TrackMouseEvent", SetLastError=true, CharSet=CharSet.Auto)]
public static extern bool TrackMouseEvent(
[In, Out, MarshalAs(UnmanagedType.Struct)] ref TRACKMOUSEEVENT lpEventTrack);
[StructLayout(LayoutKind.Sequential)]
public struct TRACKMOUSEEVENT
{
[MarshalAs(UnmanagedType.U4)]
public int cbSize;
[MarshalAs(UnmanagedType.U4)]
public int dwFlags;
public IntPtr hwndTrack;
[MarshalAs(UnmanagedType.U4)]
public int dwHoverTime;
}
}
}
namespace bg
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class BgGraph : System.Windows.Forms.Form
{
private System.Windows.Forms.PictureBox m_picbUpper;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private System.Windows.Forms.HScrollBar m_sbhUpper;
private object m_oData;
private System.Windows.Forms.Button m_pbPrint;
private Hover m_ch = null;
private GrapherParams m_gp;
private System.Windows.Forms.VScrollBar m_sbvUpper;
private System.Windows.Forms.PictureBox m_picbLower;
private System.Windows.Forms.HScrollBar m_sbhLower;
private System.Windows.Forms.VScrollBar m_sbvLower;
/* B G G R A P H */
/*----------------------------------------------------------------------------
%%Function: BgGraph
%%Qualified: bg.BgGraph.BgGraph
%%Contact: rlittle
----------------------------------------------------------------------------*/
public BgGraph()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
m_gp.dBgLow = 30.0;
m_gp.dBgHigh = 220.0;
m_gp.nHalfDays = 14;
m_gp.nIntervals = 19;
m_gp.fShowMeals = false;
m_bvUpper = BoxView.Graph;
m_bvLower = BoxView.Log;
m_sbvUpper.Tag = m_picbUpper;
m_sbvLower.Tag = m_picbLower;
m_sbhUpper.Tag = m_picbUpper;
m_sbhLower.Tag = m_picbLower;
SetupViews(this.ClientSize.Height);
}
/* S E T U P V I E W S */
/*----------------------------------------------------------------------------
%%Function: SetupViews
%%Qualified: bg.BgGraph.SetupViews
%%Contact: rlittle
----------------------------------------------------------------------------*/
void SetupViews(int nHeight)
{
int nMarginTop = 32;
int nMarginBottom = 13;
int nMarginBetween = 0;
int nPctUpper = 68;
int nPctLower = 32;
int nHeightAvail = (nHeight - nMarginTop - nMarginBottom - m_sbhUpper.Height - m_sbhLower.Height);
if (m_bvUpper == BoxView.None)
{
nPctUpper = 0;
nPctLower = 100;
m_picbUpper.Visible = false;
m_sbhUpper.Visible = false;
m_sbvUpper.Visible = false;
}
if (m_bvLower == BoxView.None)
{
nPctLower = 0;
nPctUpper = 100;
m_picbLower.Visible = false;
m_sbhLower.Visible = false;
m_sbvLower.Visible = false;
}
m_picbUpper.Location = new Point(m_picbUpper.Location.X, nMarginTop);
m_picbUpper.Height = (nHeightAvail * nPctUpper) / 100;
m_sbhUpper.Location = new Point(m_sbhUpper.Location.X, m_picbUpper.Location.Y + m_picbUpper.Height);
m_sbvUpper.Location = new Point(m_sbvUpper.Location.X, m_picbUpper.Location.Y);
m_sbvUpper.Height = m_picbUpper.Height;
m_picbLower.Location = new Point(m_picbLower.Location.X, m_sbhUpper.Location.Y + m_sbhUpper.Height + nMarginBetween);
m_picbLower.Height = (nHeightAvail * nPctLower) / 100;
m_sbhLower.Location = new Point(m_sbhLower.Location.X, m_picbLower.Location.Y + m_picbLower.Height);
m_sbvLower.Location = new Point(m_sbvLower.Location.X, m_picbLower.Location.Y);
m_sbvLower.Height = m_picbLower.Height;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.m_picbUpper = new System.Windows.Forms.PictureBox();
this.m_sbhUpper = new System.Windows.Forms.HScrollBar();
this.m_pbPrint = new System.Windows.Forms.Button();
this.m_sbvUpper = new System.Windows.Forms.VScrollBar();
this.m_picbLower = new System.Windows.Forms.PictureBox();
this.m_sbhLower = new System.Windows.Forms.HScrollBar();
this.m_sbvLower = new System.Windows.Forms.VScrollBar();
this.SuspendLayout();
//
// m_picbUpper
//
this.m_picbUpper.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right);
this.m_picbUpper.BackColor = System.Drawing.SystemColors.Window;
this.m_picbUpper.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.m_picbUpper.Location = new System.Drawing.Point(16, 32);
this.m_picbUpper.Name = "m_picbUpper";
this.m_picbUpper.Size = new System.Drawing.Size(648, 176);
this.m_picbUpper.TabIndex = 0;
this.m_picbUpper.TabStop = false;
this.m_picbUpper.Paint += new System.Windows.Forms.PaintEventHandler(this.PaintGraph);
this.m_picbUpper.MouseHover += new System.EventHandler(this.HoverGraph);
this.m_picbUpper.MouseMove += new System.Windows.Forms.MouseEventHandler(this.HandleMouse);
//
// m_sbhUpper
//
this.m_sbhUpper.Anchor = ((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right);
this.m_sbhUpper.Location = new System.Drawing.Point(16, 392);
this.m_sbhUpper.Name = "m_sbhUpper";
this.m_sbhUpper.Size = new System.Drawing.Size(648, 17);
this.m_sbhUpper.SmallChange = 10;
this.m_sbhUpper.TabIndex = 1;
this.m_sbhUpper.Visible = false;
this.m_sbhUpper.ValueChanged += new System.EventHandler(this.ScrollPaint);
//
// m_pbPrint
//
this.m_pbPrint.Location = new System.Drawing.Point(600, 8);
this.m_pbPrint.Name = "m_pbPrint";
this.m_pbPrint.TabIndex = 2;
this.m_pbPrint.Text = "Print";
this.m_pbPrint.Click += new System.EventHandler(this.PrintGraph);
this.m_pbPrint.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right;
//
// m_sbvUpper
//
this.m_sbvUpper.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Right);
this.m_sbvUpper.Location = new System.Drawing.Point(664, 32);
this.m_sbvUpper.Name = "m_sbvUpper";
this.m_sbvUpper.Size = new System.Drawing.Size(16, 360);
this.m_sbvUpper.TabIndex = 3;
this.m_sbvUpper.ValueChanged += new System.EventHandler(this.ScrollVertPaint);
//
// m_picbLower
//
this.m_picbLower.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right);
this.m_picbLower.BackColor = System.Drawing.SystemColors.Window;
this.m_picbLower.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.m_picbLower.Location = new System.Drawing.Point(16, 416);
this.m_picbLower.Name = "m_picbLower";
this.m_picbLower.Size = new System.Drawing.Size(648, 144);
this.m_picbLower.TabIndex = 4;
this.m_picbLower.TabStop = false;
this.m_picbLower.Paint += new System.Windows.Forms.PaintEventHandler(this.PaintGraph);
//
// m_sbhLower
//
this.m_sbhLower.Anchor = ((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right);
this.m_sbhLower.Location = new System.Drawing.Point(16, 560);
this.m_sbhLower.Name = "m_sbhLower";
this.m_sbhLower.Size = new System.Drawing.Size(648, 17);
this.m_sbhLower.SmallChange = 10;
this.m_sbhLower.TabIndex = 5;
this.m_sbhLower.Visible = false;
this.m_sbhLower.ValueChanged += new System.EventHandler(this.ScrollPaint);
//
// m_sbvLower
//
this.m_sbvLower.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Right);
this.m_sbvLower.Location = new System.Drawing.Point(664, 416);
this.m_sbvLower.Name = "m_sbvLower";
this.m_sbvLower.Size = new System.Drawing.Size(16, 144);
this.m_sbvLower.TabIndex = 6;
this.m_sbvLower.ValueChanged += new System.EventHandler(this.ScrollVertPaint);
//
// BgGraph
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(696, 590);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.m_sbvLower,
this.m_sbhLower,
this.m_picbLower,
this.m_sbvUpper,
this.m_pbPrint,
this.m_sbhUpper,
this.m_picbUpper});
this.Name = "BgGraph";
this.Text = "Form1";
this.SizeChanged += new System.EventHandler(this.HandleSizeChange);
this.ResumeLayout(false);
}
#endregion
/* S E T P B D A T A P O I N T S */
/*----------------------------------------------------------------------------
%%Function: SetPbDataPoints
%%Qualified: bg.BgGraph.SetPbDataPoints
%%Contact: rlittle
----------------------------------------------------------------------------*/
void SetPbDataPoints(PictureBox pb, VScrollBar sbv, HScrollBar sbh)
{
if (pb.Tag != null)
((GraphicBox)pb.Tag).SetDataPoints(m_oData, sbv, sbh);
}
/* S E T P B D A T A P O I N T S */
/*----------------------------------------------------------------------------
%%Function: SetPbDataPoints
%%Qualified: bg.BgGraph.SetPbDataPoints
%%Contact: rlittle
----------------------------------------------------------------------------*/
public void SetDataPoints(object oData)
{
m_oData = oData;
SetPbDataPoints(m_picbUpper, m_sbvUpper, m_sbhUpper);
SetPbDataPoints(m_picbLower, m_sbvLower, m_sbhLower);
}
/* S E T P B B O U N D S */
/*----------------------------------------------------------------------------
%%Function: SetPbBounds
%%Qualified: bg.BgGraph.SetPbBounds
%%Contact: rlittle
----------------------------------------------------------------------------*/
void SetPbBounds(PictureBox pb)
{
if (BvFromPb(pb) != BoxView.None)
((GraphicBox)pb.Tag).SetProps(m_gp);
}
/* S E T B O U N D S */
/*----------------------------------------------------------------------------
%%Function: SetBounds
%%Qualified: bg.BgGraph.SetBounds
%%Contact: rlittle
----------------------------------------------------------------------------*/
public void SetBounds(double dLow, double dHigh, int nDays, int nBgIntervals, bool fShowMeals, bool fLandscape)
{
m_gp.dBgLow = dLow;
m_gp.dBgHigh = dHigh;
m_gp.nHalfDays = nDays * 2;
m_gp.nIntervals = nBgIntervals;
m_gp.fShowMeals = fShowMeals;
m_gp.fLandscape = fLandscape;
m_gp.fGraphAvg = true; // false;
SetPbBounds(m_picbUpper);
SetPbBounds(m_picbLower);
AutosizeGraph(m_bvUpper, m_bvLower, (GraphicBox)m_picbUpper.Tag, (GraphicBox)m_picbLower.Tag, ref m_gp);
}
public enum BoxView
{
None,
Graph,
Log,
Meal
};
public void AutosizeGraph(BoxView bvUpper, BoxView bvLower, GraphicBox gbUpper, GraphicBox gbLower, ref GrapherParams gp)
{
int nDays;
if (bvUpper == BoxView.Log)
{
// get the number of lines expected in this item
nDays = gbUpper.GetDaysPerPage();
if (bvLower == BoxView.Graph)
{
gbLower.SetDaysPerPage(nDays);
gp.nHalfDays = nDays * 2;
}
}
else if (bvLower == BoxView.Log)
{
// get the number of lines expected in this item
nDays = gbLower.GetDaysPerPage();
if (bvUpper == BoxView.Graph)
{
gbUpper.SetDaysPerPage(nDays);
gp.nHalfDays = nDays * 2;
}
}
}
/* S E T G R A P H I C V I E W S */
/*----------------------------------------------------------------------------
%%Function: SetGraphicViews
%%Qualified: bg.BgGraph.SetGraphicViews
%%Contact: rlittle
----------------------------------------------------------------------------*/
public void SetGraphicViews(BoxView bvUpper, BoxView bvLower)
{
if (bvUpper == BoxView.None && bvLower == BoxView.None)
throw(new Exception("Illegal BoxView parameters"));
m_bvUpper = bvUpper;
m_bvLower = bvLower;
SetupViews(this.ClientSize.Height);
Graphics gr = this.CreateGraphics();
RectangleF rectfUpper = new RectangleF(Reporter.DxpFromDxa(gr, 100),
Reporter.DypFromDya(gr, 100),
m_picbUpper.Width - Reporter.DxpFromDxa(gr, 200),
m_picbUpper.Height - Reporter.DypFromDya(gr, 200));
RectangleF rectfLower = new RectangleF(Reporter.DxpFromDxa(gr, 100),
Reporter.DypFromDya(gr, 100),
m_picbLower.Width - Reporter.DxpFromDxa(gr, 200),
m_picbLower.Height - Reporter.DypFromDya(gr, 200));
switch (bvUpper)
{
case BoxView.Log:
m_picbUpper.Tag = new Reporter(rectfUpper, gr);
break;
case BoxView.Graph:
m_picbUpper.Tag = new Grapher(rectfUpper, gr);
break;
case BoxView.Meal:
m_picbUpper.Tag = new MealCharter(rectfUpper, gr);
break;
}
switch (bvLower)
{
case BoxView.Log:
m_picbLower.Tag = new Reporter(rectfLower, gr);
break;
case BoxView.Graph:
m_picbLower.Tag = new Grapher(rectfLower, gr);
break;
case BoxView.Meal:
m_picbLower.Tag = new MealCharter(rectfLower, gr);
break;
}
}
BoxView m_bvUpper;
BoxView m_bvLower;
/* B V F R O M S T R I N G */
/*----------------------------------------------------------------------------
%%Function: BvFromString
%%Qualified: bg.BgGraph.BvFromString
%%Contact: rlittle
----------------------------------------------------------------------------*/
static public BoxView BvFromString(string s)
{
if (String.Compare(s, "None", true) == 0)
return BoxView.None;
else if (String.Compare(s, "Graph", true) == 0)
return BoxView.Graph;
else if (String.Compare(s, "Log", true) == 0)
return BoxView.Log;
else if (String.Compare(s, "Meal", true) == 0)
return BoxView.Meal;
return BoxView.None;
}
/* P A I N T G R A P H */
/*----------------------------------------------------------------------------
%%Function: PaintGraph
%%Qualified: bg.BgGraph.PaintGraph
%%Contact: rlittle
----------------------------------------------------------------------------*/
private void PaintGraph(object sender, System.Windows.Forms.PaintEventArgs e)
{
PictureBox pb = (PictureBox)sender;
e.Graphics.Clear(pb.BackColor);
if (pb.Tag != null)
((GraphicBox)pb.Tag).Paint(e.Graphics);
}
bool m_fInPaint = false;
/* S C R O L L P A I N T */
/*----------------------------------------------------------------------------
%%Function: ScrollPaint
%%Qualified: bg.BgGraph.ScrollPaint
%%Contact: rlittle
----------------------------------------------------------------------------*/
private void ScrollPaint(object sender, System.EventArgs e)
{
if (m_fInPaint)
return;
m_fInPaint = true;
HScrollBar sbh = (HScrollBar)sender;
PictureBox pb = (PictureBox)sbh.Tag;
if (BvFromPb(pb) == BoxView.Graph)
{
// its a report
Grapher grph = (Grapher)pb.Tag;
int iFirstQuarter = -1;
grph.SetFirstFromScroll(iFirstQuarter = sbh.Value);
DateTime dttm = grph.GetFirstDateTime();
SetViewDateTimeScroll(m_picbUpper, m_sbhUpper, m_sbvUpper, dttm, iFirstQuarter);
SetViewDateTimeScroll(m_picbLower, m_sbhLower, m_sbvLower, dttm, iFirstQuarter);
pb.Invalidate();
}
m_fInPaint = false;
}
/* P I C T U R E B O X S I Z E C H A N G E */
/*----------------------------------------------------------------------------
%%Function: PictureBoxSizeChange
%%Qualified: bg.BgGraph.PictureBoxSizeChange
%%Contact: rlittle
----------------------------------------------------------------------------*/
void PictureBoxSizeChange(PictureBox pb, HScrollBar sbh, VScrollBar sbv)
{
Graphics gr = this.CreateGraphics();
RectangleF rcf = new RectangleF(Reporter.DxpFromDxa(gr, 100),
Reporter.DypFromDya(gr, 100),
pb.Width - Reporter.DxpFromDxa(gr, 200),
pb.Height - Reporter.DypFromDya(gr, 200));
if (pb.Tag != null)
{
int iFirst = ((GraphicBox)pb.Tag).GetFirstForScroll();
GraphicBox gb = null;
if (BvFromPb(pb) == BoxView.Graph)
pb.Tag = gb = (GraphicBox) new Grapher(rcf, gr);
else if (BvFromPb(pb) == BoxView.Log)
pb.Tag = gb = (GraphicBox) new Reporter(rcf, gr);
if (gb != null)
{
gb.SetProps(m_gp);
gb.SetDataPoints(m_oData, sbv, sbh);
gb.Calc();
gb.SetFirstFromScroll(iFirst);
}
pb.Invalidate();
}
}
/* H A N D L E S I Z E C H A N G E */
/*----------------------------------------------------------------------------
%%Function: HandleSizeChange
%%Qualified: bg.BgGraph.HandleSizeChange
%%Contact: rlittle
----------------------------------------------------------------------------*/
private void HandleSizeChange(object sender, System.EventArgs e)
{
SetupViews(this.ClientSize.Height);
AutosizeGraph(m_bvUpper, m_bvLower, (GraphicBox)m_picbUpper.Tag, (GraphicBox)m_picbLower.Tag, ref m_gp);
PictureBoxSizeChange(m_picbUpper, m_sbhUpper, m_sbvUpper);
PictureBoxSizeChange(m_picbLower, m_sbhLower, m_sbvLower);
}
/* C A L C P I C T U R E B O X */
/*----------------------------------------------------------------------------
%%Function: CalcPictureBox
%%Qualified: bg.BgGraph.CalcPictureBox
%%Contact: rlittle
----------------------------------------------------------------------------*/
void CalcPictureBox(PictureBox pb, HScrollBar sbh)
{
if (pb.Tag != null)
((GraphicBox)pb.Tag).Calc();
}
/* C A L C G R A P H */
/*----------------------------------------------------------------------------
%%Function: CalcGraph
%%Qualified: bg.BgGraph.CalcGraph
%%Contact: rlittle
----------------------------------------------------------------------------*/
public void CalcGraph()
{
CalcPictureBox(m_picbUpper, m_sbhUpper);
CalcPictureBox(m_picbLower, m_sbhLower);
}
/* H O V E R G R A P H */
/*----------------------------------------------------------------------------
%%Function: HoverGraph
%%Qualified: bg.BgGraph.HoverGraph
%%Contact: rlittle
----------------------------------------------------------------------------*/
private void HoverGraph(object sender, System.EventArgs e)
{
PictureBox pb = (PictureBox)sender;
if (BvFromPb(pb) != BoxView.Graph)
return;
Grapher grph = (Grapher)pb.Tag;
Point ptRaw = Cursor.Position;
Point pt = pb.PointToClient(ptRaw);
PTFI ptfiHit = new PTFI();
bool fHit = false;
RectangleF rectfHit;
object oHit;
fHit = grph.FHitTest(pt, out oHit, out rectfHit);
ptfiHit = (PTFI)oHit;
if (fHit)
{
if (m_ch == null)
m_ch = new Hover();
m_ch.ShowTip(ptRaw, ptfiHit.bge);
this.Focus();
m_fTipShowing = true;
m_rectfTipHitRegion = rectfHit;
}
this.Focus();
// now lets register for this again
user32.TRACKMOUSEEVENT tme = new user32.TRACKMOUSEEVENT();
tme.cbSize = Marshal.SizeOf(tme);
tme.dwFlags = 1;
tme.dwHoverTime = -1;
tme.hwndTrack = pb.Handle;
user32.TrackMouseEvent(ref tme);
}
/* H A N D L E M O U S E */
/*----------------------------------------------------------------------------
%%Function: HandleMouse
%%Qualified: bg.BgGraph.HandleMouse
%%Contact: rlittle
----------------------------------------------------------------------------*/
private void HandleMouse(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (m_fTipShowing == false)
return;
if (m_rectfTipHitRegion.Contains(new PointF((float)e.X, (float)e.Y)))
return;
m_fTipShowing = false;
m_ch.Hide();
}
private bool m_fTipShowing;
private RectangleF m_rectfTipHitRegion;
/* G R A P H P R I N T R E G I O N */
/*----------------------------------------------------------------------------
%%Function: GraphPrintRegion
%%Qualified: bg.BgGraph.GraphPrintRegion
%%Contact: rlittle
----------------------------------------------------------------------------*/
GraphicBox GraphPrintRegion(RectangleF rcf, RectangleF rcfBanner, PrintPageEventArgs ev, bool fColor)
{
Grapher grph = new Grapher(rcf, ev.Graphics);
grph.SetProps(gpPrint);
grph.DrawBanner(ev.Graphics, rcfBanner);
// grph.SetFirstQuarter(grphRef.GetFirstQuarter());
grph.SetDataPoints(m_oData, null, null);
grph.SetColor(fColor);
return (GraphicBox)grph;
}
/* L O G P R I N T R E G I O N */
/*----------------------------------------------------------------------------
%%Function: LogPrintRegion
%%Qualified: bg.BgGraph.LogPrintRegion
%%Contact: rlittle
----------------------------------------------------------------------------*/
GraphicBox LogPrintRegion(RectangleF rcf, PrintPageEventArgs ev, bool fColor)
{
Reporter rpt = new Reporter(rcf, ev.Graphics);
rpt.SetProps(gpPrint);
rpt.SetDataPoints(m_oData, null, null);
// rpt.SetFirstLine(rptRef.GetFirstLine());
rpt.SetColor(fColor);
return (GraphicBox)rpt;
}
void PaintPrintRegion(GraphicBox gb, BoxView bv, Graphics gr, DateTime dttmFirst)
{
if (gb == null)
return;
gb.Calc();
if (bv == BoxView.Log)
gb.SetFirstDateTime(dttmFirst);
else if (bv == BoxView.Graph)
gb.SetFirstDateTime(dttmFirst.AddDays(-1.0));
gb.Paint(gr);
}
/* P R I N T P A G E H A N D L E R */
/*----------------------------------------------------------------------------
%%Function: PrintPageHandler
%%Qualified: bg.BgGraph.PrintPageHandler
%%Contact: rlittle
----------------------------------------------------------------------------*/
private void PrintPageHandler(object sender, PrintPageEventArgs ev)
{
Rectangle rectMargins = ev.MarginBounds;
Rectangle rectPage = ev.PageBounds;
PrintDocument ppd = (PrintDocument)sender;
rectMargins = new Rectangle((int)Reporter.DxpFromDxaPrint(ev.Graphics, (float)(ev.MarginBounds.X * 14.40)),
(int)Reporter.DypFromDyaPrint(ev.Graphics, (float)(ev.MarginBounds.Y * 14.40)),
(int)Reporter.DxpFromDxaPrint(ev.Graphics, (float)(ev.MarginBounds.Width * 14.40)),
(int)Reporter.DypFromDyaPrint(ev.Graphics, (float)(ev.MarginBounds.Height * 14.40)));
// adjust the bottom margin...
rectMargins.Height -= (int)Reporter.DypFromDyaPrint(ev.Graphics, 70);
// page size is 8.5 x 11. we are shooting for 8" x 10.5"
// ev.Graphics.DrawRectangle(new Pen(new SolidBrush(Color.Blue), 1.0F), rectMargins);
int nPctUpper = 70;
int nMarginTop = (int)Reporter.DypFromDyaPrint(ev.Graphics, 25);
int nMarginBetween = nMarginTop;
bool fColor = ppd.PrinterSettings.SupportsColor;
int nHeightTotal = (int)Reporter.DypFromDyaPrint(ev.Graphics, 1440.0F * 10.5F);
int nWidthTotal = (int)Reporter.DxpFromDxaPrint(ev.Graphics, 1440.0F * 8.0F);
if (ev.PageSettings.Landscape)
{
nWidthTotal = (int)Reporter.DypFromDyaPrint(ev.Graphics, 1440.0F * 10.5F);
nHeightTotal= (int)Reporter.DxpFromDxaPrint(ev.Graphics, 1440.0F * 8.0F);
}
int nHeightAvail = nHeightTotal - nMarginBetween - nMarginTop;
int nWidth = nWidthTotal - (int)Reporter.DxpFromDxaPrint(ev.Graphics, 10);
if (m_bvUpper == BoxView.None)
nPctUpper = 0;
else if (m_bvLower == BoxView.None)
nPctUpper = 100;
// we have to apportion the regions...
RectangleF rcfUpperBanner = new RectangleF(0, 0, nWidth, nMarginTop);
RectangleF rcfUpper = new RectangleF(0, rcfUpperBanner.Bottom, nWidth, ((nHeightAvail) * nPctUpper) / 100);
RectangleF rcfLowerBanner = new RectangleF(0, rcfUpper.Bottom, nWidth, nMarginBetween);
RectangleF rcfLower = new RectangleF(0, rcfUpper.Bottom + nMarginBetween, nWidth, nHeightAvail - (rcfUpper.Bottom + nMarginBetween * 2));
// whenever we go to print, if there's a log, then the first date in the log becomes the first date for the graph too
// paint the upper region
GraphicBox gbUpper = null;
GraphicBox gbLower = null;
switch (m_bvUpper)
{
case BoxView.Graph:
{
Grapher grph = (Grapher)m_picbUpper.Tag;
gbUpper = GraphPrintRegion(rcfUpper, rcfUpperBanner, ev, fColor);
break;
}
case BoxView.Log:
{
Reporter rpt = (Reporter)m_picbUpper.Tag;
gbUpper = LogPrintRegion(rcfUpper, ev, fColor);
break;
}
}
switch (m_bvLower)
{
case BoxView.Graph:
{
Grapher grph = (Grapher)m_picbLower.Tag;
gbLower = GraphPrintRegion(rcfLower, rcfLowerBanner, ev, fColor);
break;
}
case BoxView.Log:
{
Reporter rpt = (Reporter)m_picbLower.Tag;
gbLower = LogPrintRegion(rcfLower, ev, fColor);
break;
}
}
AutosizeGraph(m_bvUpper, m_bvLower, gbUpper, gbLower, ref gpPrint);
PaintPrintRegion(gbUpper, m_bvUpper, ev.Graphics, dttmCurPage);
PaintPrintRegion(gbLower, m_bvLower, ev.Graphics, dttmCurPage);
// setup dttmCurPage for the next page
// again, the log wins
bool fMore = false;
if (gbUpper != null)
{
fMore = gbUpper.FGetLastDateTimeOnPage(out dttmCurPage);
// if we are getting the "last date" from a graph region, then
// don't overlap the last day of page N with the page N+1.
if (fMore && m_bvUpper == BoxView.Graph)
dttmCurPage = dttmCurPage.AddDays(1.0f);
}
if (m_bvLower == BoxView.Log)
fMore = gbLower.FGetLastDateTimeOnPage(out dttmCurPage);
ev.HasMorePages = fMore;
}
PrinterSettings m_prtSettings = null;
PageSettings m_pgSettings = null;
DateTime dttmCurPage;
GrapherParams gpPrint;
/* P R I N T G R A P H */
/*----------------------------------------------------------------------------
%%Function: PrintGraph
%%Qualified: bg.BgGraph.PrintGraph
%%Contact: rlittle
----------------------------------------------------------------------------*/
private void PrintGraph(object sender, System.EventArgs e)
{
PrintDocument ppd = new PrintDocument();
PrintDialog dlgPrint = new PrintDialog();
if (m_pgSettings != null)
{
ppd.DefaultPageSettings = m_pgSettings;
}
else
{
ppd.DefaultPageSettings.Landscape = m_gp.fLandscape;
ppd.DefaultPageSettings.Margins = new Margins(25, 25, 25, 25);
}
if (m_prtSettings != null)
{
ppd.PrinterSettings = m_prtSettings;
}
ppd.PrintPage += new PrintPageEventHandler(PrintPageHandler);
dlgPrint.Document = ppd;
dlgPrint.ShowDialog();
m_prtSettings = ppd.PrinterSettings;
m_pgSettings = ppd.DefaultPageSettings;
dttmCurPage = ((GraphicBox)m_picbUpper.Tag).GetFirstDateTime();
gpPrint = m_gp;
#if DEBUG
DateTime dttmOld = dttmCurPage;
((GraphicBox)m_picbUpper.Tag).SetFirstDateTime(dttmCurPage);
dttmCurPage = ((GraphicBox)m_picbUpper.Tag).GetFirstDateTime();
if (DateTime.Compare(dttmOld, dttmCurPage) != 0)
throw new Exception("SetFirstDateTime identity failed!");
#endif
if (m_bvLower == BoxView.Log)
dttmCurPage = ((GraphicBox)m_picbLower.Tag).GetFirstDateTime();
ppd.Print();
}
// int m_iFirstLine;
/* B V F R O M P B */
/*----------------------------------------------------------------------------
%%Function: BvFromPb
%%Qualified: bg.BgGraph.BvFromPb
%%Contact: rlittle
----------------------------------------------------------------------------*/
BoxView BvFromPb(PictureBox pb)
{
if (pb.Tag == null)
return BoxView.None;
if (String.Compare(pb.Tag.GetType().ToString(), "bg.Grapher", true) == 0)
return BoxView.Graph;
else if (String.Compare(pb.Tag.GetType().ToString(), "bg.Reporter", true) == 0)
return BoxView.Log;
else if (String.Compare(pb.Tag.GetType().ToString(), "bg.MealCharter", true) == 0)
return BoxView.Meal;
else
return BoxView.None;
}
/* S E T V I E W D A T E T I M E S C R O L L */
/*----------------------------------------------------------------------------
%%Function: SetViewDateTimeScroll
%%Qualified: bg.BgGraph.SetViewDateTimeScroll
%%Contact: rlittle
----------------------------------------------------------------------------*/
void SetViewDateTimeScroll(PictureBox pb, HScrollBar sbh, VScrollBar sbv, DateTime dttm, int iFirstQuarter)
{
if (BvFromPb(pb) == BoxView.Log)
{
Reporter rpt = (Reporter)pb.Tag;
rpt.SetFirstDateTime(dttm);
sbv.Value = rpt.GetFirstLine();
}
else if (BvFromPb(pb) == BoxView.Graph)
{
Grapher grph = (Grapher)pb.Tag;
if (iFirstQuarter >= 0)
{
grph.SetFirstFromScroll(iFirstQuarter);
sbh.Value = iFirstQuarter;
}
else
{
grph.SetFirstDateTime(dttm.AddDays(-1.0));
if (grph.GetFirstForScroll() > sbh.Maximum) // if we have exceeded the scrolling regions, then we want to act as if we've scrolled to the end
grph.SetFirstFromScroll(sbh.Value);
if (grph.GetFirstForScroll() < 0)
grph.SetFirstFromScroll(0);
sbh.Value = grph.GetFirstForScroll();
}
}
pb.Invalidate();
}
/* S C R O L L V E R T P A I N T */
/*----------------------------------------------------------------------------
%%Function: ScrollVertPaint
%%Qualified: bg.BgGraph.ScrollVertPaint
%%Contact: rlittle
----------------------------------------------------------------------------*/
private void ScrollVertPaint(object sender, System.EventArgs e)
{
if (m_fInPaint)
return;
m_fInPaint = true;
VScrollBar sbv = (VScrollBar)sender;
PictureBox pb = (PictureBox)sbv.Tag;
if (BvFromPb(pb) == BoxView.Log)
{
// its a report. scroll both views to this item.
Reporter rpt = (Reporter)pb.Tag;
rpt.SetFirstLine(sbv.Value);
DateTime dttm = rpt.GetFirstDateTime();
SetViewDateTimeScroll(m_picbUpper, m_sbhUpper, m_sbvUpper, dttm, -1);
SetViewDateTimeScroll(m_picbLower, m_sbhLower, m_sbvLower, dttm, -1);
pb.Invalidate();
}
m_fInPaint = false;
}
}
}
| |
namespace DD.CBU.Compute.Api.Client.Interfaces
{
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using DD.CBU.Compute.Api.Contracts.Datacenter;
using DD.CBU.Compute.Api.Contracts.Directory;
using DD.CBU.Compute.Api.Contracts.General;
using DD.CBU.Compute.Api.Contracts.Image;
using DD.CBU.Compute.Api.Contracts.Server;
using DD.CBU.Compute.Api.Contracts.Server10;
using DD.CBU.Compute.Api.Contracts.Software;
/// <summary>
/// The interface of the CaaS API Client
/// </summary>
public interface IDeprecatedComputeApiClient
{
/// <summary>
/// The login async.
/// </summary>
/// <param name="accountCredentials">
/// The account credentials.
/// </param>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
[Obsolete("Use Login() instead")]
Task<IAccount> LoginAsync(ICredentials accountCredentials);
/// <summary>
/// Gets a list of software labels.
/// </summary>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
[Obsolete]
Task<IEnumerable<SoftwareLabel>> GetListOfSoftwareLabels();
/// <summary>
/// Gets a list of multi geography regions
/// </summary>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
[Obsolete]
Task<IEnumerable<Geo>> GetListOfMultiGeographyRegions();
/// <summary>
/// Deletes a sub administrator account
/// </summary>
/// <param name="username">
/// The username
/// </param>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
[Obsolete]
Task<Status> DeleteSubAdministratorAccount(string username);
/// <summary>
/// Get a (sub) administrator account
/// </summary>
/// <param name="username">
/// The username
/// </param>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
[Obsolete]
Task<AccountWithPhoneNumber> GetAdministratorAccount(string username);
/// <summary>
/// Designate a primary administrator account
/// </summary>
/// <param name="username">
/// The username
/// </param>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
[Obsolete]
Task<Status> DesignatePrimaryAdministratorAccount(string username);
/// <summary>
/// Gets all the data centres for the organisation.
/// </summary>
/// <returns>
/// The data centres.
/// </returns>
[Obsolete]
Task<IEnumerable<DatacenterWithMaintenanceStatusType>> GetDataCentersWithMaintenanceStatuses();
/// <summary>
/// Gets the account of the organisation.
/// </summary>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
[Obsolete]
Task<IEnumerable<Contracts.Directory.Account>> GetAccounts();
/// <summary>
/// Adds a sub administrator account
/// </summary>
/// <param name="account">
/// The account
/// </param>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
[Obsolete]
Task<Status> AddSubAdministratorAccount(AccountWithPhoneNumber account);
/// <summary>
/// Updates an administrator account
/// </summary>
/// <param name="account">
/// The account
/// </param>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
[Obsolete]
Task<Status> UpdateAdministratorAccount(AccountWithPhoneNumber account);
/// <summary>
/// Gets available data centres
/// </summary>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
[Obsolete("Use GetDataCentersWithMaintenanceStatuses instead!")]
Task<IReadOnlyList<DatacenterWithDiskSpeedDetails>> GetAvailableDataCenters();
/// <summary>
/// Gets the OS images at a particular location.
/// </summary>
/// <param name="locationName">
/// The location.
/// </param>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
[Obsolete]
Task<IReadOnlyList<DeployedImageWithSoftwareLabelsType>> GetImages(string locationName);
/// <summary>
/// Get OS server images
/// </summary>
/// <param name="imageId">
/// The imageId filter
/// </param>
/// <param name="name">
/// The name filter
/// </param>
/// <param name="location">
/// The location filter
/// </param>
/// <param name="operatingSystemId">
/// The OS id
/// </param>
/// <param name="operatingSystemFamily">
/// The OS family
/// </param>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
[Obsolete]
Task<IReadOnlyList<ImagesWithDiskSpeedImage>> GetImages(
string imageId,
string name,
string location,
string operatingSystemId,
string operatingSystemFamily);
/// <summary>
/// Gets the deployed customer server images.
/// </summary>
/// <param name="networkLocation">
/// The location.
/// </param>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
[Obsolete]
Task<IEnumerable<DeployedImageWithSoftwareLabelsType>> GetCustomerServerImages(string networkLocation);
/// <summary>
/// Get customer server images
/// </summary>
/// <param name="imageId">
/// The imageId filter
/// </param>
/// <param name="name">
/// The name filter
/// </param>
/// <param name="location">
/// The location filter
/// </param>
/// <param name="operatingSystemId">
/// The OS id
/// </param>
/// <param name="operatingSystemFamily">
/// The OS family
/// </param>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
Task<IReadOnlyList<ImagesWithDiskSpeedImage>> GetCustomerServerImages(
string imageId,
string name,
string location,
string operatingSystemId,
string operatingSystemFamily);
/// <summary>
/// Remove customer images
/// </summary>
/// <param name="imageid">
/// The image id
/// </param>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
[Obsolete]
Task<Status> RemoveCustomerServerImage(string imageid);
/// <summary>
/// Deploy a server using an image in a specified network.
/// </summary>
/// <param name="name">
/// The name of the new server.
/// </param>
/// <param name="description">
/// The description of the new server.
/// </param>
/// <param name="networkId">
/// The network id to deploy the server.
/// </param>
/// <param name="imageId">
/// The image id to deploy the server.
/// </param>
/// <param name="adminPassword">
/// The administrator password.
/// </param>
/// <param name="isStarted">
/// Will the server powers on after deployment?
/// </param>
/// <returns>
/// The status of the deployment.
/// </returns>
[Obsolete("Use DeployServerWithDiskSpeedImageTask")]
Task<Status> DeployServerImageTask(
string name,
string description,
string networkId,
string imageId,
string adminPassword,
bool isStarted);
/// <summary>
/// Deploy a server using an image in a specified network.
/// </summary>
/// <param name="name">
/// The name of the new server.
/// </param>
/// <param name="description">
/// The description of the new server.
/// </param>
/// <param name="networkId">
/// The network id to deploy the server.
/// </param>
/// <param name="privateIp">
/// The privateIp address to deploy the server.
/// </param>
/// <param name="imageId">
/// The image id to deploy the server.
/// </param>
/// <param name="adminPassword">
/// The administrator password.
/// </param>
/// <param name="start">
/// Will the server powers on after deployment?
/// </param>
/// <param name="disk">
/// Array od disk configurations
/// </param>
/// <returns>
/// The status of the deployment.
/// </returns>
[Obsolete]
Task<Status> DeployServerWithDiskSpeedImageTask(
string name,
string description,
string networkId,
string privateIp,
string imageId,
string adminPassword,
bool start,
Disk[] disk
);
/// <summary>
/// Deploy a server using an image in a specified network.
/// </summary>
/// <param name="name">
/// The name of the new server.
/// </param>
/// <param name="description">
/// The description of the new server.
/// </param>
/// <param name="networkId">
/// The network id to deploy the server.
/// </param>
/// <param name="privateIp">
/// The network id or privateIp address to deploy the server.
/// </param>
/// <param name="imageId">
/// The image id to deploy the server.
/// </param>
/// <param name="adminPassword">
/// The administrator password.
/// </param>
/// <param name="start">
/// Will the server powers on after deployment?
/// </param>
/// <returns>
/// The status of the deployment.
/// </returns>
[Obsolete]
Task<Status> DeployServerWithDiskSpeedImageTask(
string name,
string description,
string networkId,
string privateIp,
string imageId,
string adminPassword,
bool start
);
/// <summary>
/// The modify server.
/// </summary>
/// <param name="serverId">
/// The server id.
/// </param>
/// <param name="name">
/// The name.
/// </param>
/// <param name="description">
/// The description.
/// </param>
/// <param name="memory">
/// The memory.
/// </param>
/// <param name="cpucount">
/// The CPU count.
/// </param>
/// <param name="privateIp">
/// The private IP.
/// </param>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
[Obsolete]
Task<Status> ModifyServer(string serverId, string name, string description, int memory, int cpucount, string privateIp);
/// <summary>
/// Powers on the server.
/// </summary>
/// <param name="serverId">
/// The server id.
/// </param>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
[Obsolete]
Task<Status> ServerPowerOn(string serverId);
/// <summary>
/// Powers off the server.
/// </summary>
/// <param name="serverId">
/// Server Id
/// </param>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
[Obsolete]
Task<Status> ServerPowerOff(string serverId);
/// <summary>
/// Restart the server.
/// </summary>
/// <param name="serverId">
/// The server id.
/// </param>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
[Obsolete]
Task<Status> ServerRestart(string serverId);
/// <summary> Power cycles an existing deployed server. This is the equivalent of pulling and replacing the power cord for
/// a physical server. Requires your organization ID and the ID of the target server.. </summary>
/// <param name="serverId"> The server id. </param>
/// <returns> Returns a status of the HTTP request </returns>
[Obsolete]
Task<Status> ServerReset(string serverId);
/// <summary>
/// Shutdown the server.
/// </summary>
/// <param name="serverId">
/// The server id.
/// </param>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
[Obsolete]
Task<Status> ServerShutdown(string serverId);
/// <summary>
/// Modify server disk size.
/// </summary>
/// <param name="serverId">
/// The server id.
/// </param>
/// <param name="diskId">
/// The SCSI disk Id.
/// </param>
/// <param name="sizeInGb">
/// Size In GB.
/// </param>
/// <returns>
/// The status of the deployment.
/// </returns>
[Obsolete]
Task<Status> ChangeServerDiskSize(string serverId, string diskId, string sizeInGb);
/// <summary>
/// Modify server disk speed.
/// </summary>
/// <param name="serverId">
/// The server id.
/// </param>
/// <param name="diskId">
/// The SCSI disk Id.
/// </param>
/// <param name="speedId">
/// Size in GB.
/// </param>
/// <returns>
/// The status of the deployment.
/// </returns>
[Obsolete]
Task<Status> ChangeServerDiskSpeed(string serverId, string diskId, string speedId);
/// <summary>
/// Add Disk to Server
/// </summary>
/// <param name="serverId">
/// The server id
/// </param>
/// <param name="size">
/// The size of the new disk
/// </param>
/// <param name="speedId">
/// The speed Id.
/// </param>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
[Obsolete]
Task<Status> AddServerDisk(string serverId, string size, string speedId);
/// <summary>
/// Modify server server settings.
/// </summary>
/// <param name="serverId">
/// The server id.
/// </param>
/// <param name="diskId">
/// The SCSI disk Id.
/// </param>
/// <returns>
/// The status of the deployment.
/// </returns>
[Obsolete]
Task<Status> RemoveServerDisk(string serverId, string diskId);
/// <summary>
/// Triggers an update of the VMWare Tools software running on the guest OS of a virtual server
/// </summary>
/// <param name="serverId">
/// The server id.
/// </param>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
[Obsolete]
Task<Status> ServerUpdateVMwareTools(string serverId);
/// <summary>
/// Delete the server.
/// </summary>
/// <param name="serverId">
/// The server id.
/// </param>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
[Obsolete]
Task<Status> ServerDelete(string serverId);
/// <summary>
/// Initiates a clone of a server to create a Customer Image
/// </summary>
/// <param name="serverId">
/// The server id.
/// </param>
/// <param name="imageName">
/// The customer image name.
/// </param>
/// <param name="imageDesc">
/// The customer image description.
/// </param>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
[Obsolete]
Task<Status> ServerCloneToCustomerImage(string serverId, string imageName, string imageDesc);
/// <summary>
/// Gets the deployed servers.
/// </summary>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
[Obsolete]
Task<IEnumerable<ServerWithBackupType>> GetDeployedServers();
/// <summary>
/// Gets a filtered list of deployed servers.
/// </summary>
/// <param name="serverid">
/// The server Id.
/// </param>
/// <param name="name">
/// The name.
/// </param>
/// <param name="networkId">
/// The network Id.
/// </param>
/// <param name="location">
/// The location.
/// </param>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
[Obsolete]
Task<IEnumerable<ServerWithBackupType>> GetDeployedServers(
string serverid,
string name,
string networkId,
string location);
/// <summary>
/// Creates a new Server Anti-Affinity Rule between two servers on the same Cloud network.
/// </summary>
/// <param name="serverId1">
/// The server Id for the 1'st server
/// </param>
/// <param name="serverId2">
/// The server Id for the 2'nd server
/// </param>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
[Obsolete]
Task<Status> CreateServerAntiAffinityRule(string serverId1, string serverId2);
/// <summary>
/// List all Server Anti-Affinity Rules
/// </summary>
/// <param name="ruleId">
/// Filter by rule Id
/// </param>
/// <param name="location">
/// Filter by location
/// </param>
/// <param name="networkId">
/// Filter by network Id
/// </param>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
[Obsolete]
Task<IEnumerable<AntiAffinityRuleType>> GetServerAntiAffinityRules(
string ruleId,
string location,
string networkId);
/// <summary>
/// Remove a server Anti-Affinity Rule between two servers on the same Cloud network.
/// </summary>
/// <param name="ruleId">
/// The ruleId
/// </param>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
[Obsolete]
Task<Status> RemoveServerAntiAffinityRule(string ruleId);
/// <summary>
/// Since MultiGeo call is only valid for the home geo, use this method to discover what is your home geo and the
/// applicable regions for this user.
/// This is a multithreaded call that uses the underlying ComputeApiClient.GetListOfMultiGeographyRegions()
/// to discover the home geo and multi geo for this user to all API endpoints known for vendor.
/// Note: Most of the user vendor is DimensionData. Use this if you have to guess which vendor the user is under.
/// </summary>
/// <param name="vendor">
/// The vendor of the user
/// </param>
/// <param name="credential">
/// Credential of the user
/// </param>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
[Obsolete("Use static method ComputeApiClient.GetListOfMultiGeographyRegionsFromHomeRegion instead")]
Task<IEnumerable<Geo>> DiscoverHomeMultiGeo(KnownApiVendor vendor, ICredentials credential);
}
}
| |
//
// ClientService.cs
//
// Author:
// Ventsislav Mladenov <[email protected]>
//
// Copyright (c) 2013 Ventsislav Mladenov
//
// 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 Microsoft.TeamFoundation.Client.Services;
using System.Xml.Linq;
using Microsoft.TeamFoundation.Client;
using System.Collections.Generic;
using Microsoft.TeamFoundation.WorkItemTracking.Client.Enums;
using Microsoft.TeamFoundation.WorkItemTracking.Client.Objects;
using Microsoft.TeamFoundation.WorkItemTracking.Client.Metadata;
using Microsoft.TeamFoundation.WorkItemTracking.Client.Query;
using System.Linq;
using System.IO;
namespace Microsoft.TeamFoundation.WorkItemTracking.Client
{
public class ClientService : TFSCollectionService
{
private class ClientServiceResolver : IServiceResolver
{
#region IServiceResolver implementation
public string Id
{
get
{
return "ca87fa49-58c9-4089-8535-1299fa60eebc";
}
}
public string ServiceType
{
get
{
return "WorkitemService3";
}
}
#endregion
}
#region implemented abstract members of TFSService
public override XNamespace MessageNs
{
get
{
return "http://schemas.microsoft.com/TeamFoundation/2005/06/WorkItemTracking/ClientServices/03";
}
}
#endregion
#region implemented abstract members of TFSCollectionService
public override IServiceResolver ServiceResolver
{
get
{
return new ClientServiceResolver();
}
}
#endregion
private static readonly string headerName = "RequestHeader";
private static readonly string requestId = "uuid:" + Guid.NewGuid().ToString("D");
private XElement GetHeaderElement()
{
return new XElement(this.MessageNs + "Id", requestId);
}
private List<T> GetMetadata<T>(MetadataRowSetNames table)
where T: class
{
var invoker = new SoapInvoker(this);
var envelope = invoker.CreateEnvelope("GetMetadataEx2", headerName);
envelope.Header.Add(GetHeaderElement());
envelope.Body.Add(new XElement(MessageNs + "metadataHave",
new XElement(MessageNs + "MetadataTableHaveEntry",
new XElement(MessageNs + "TableName", table),
new XElement(MessageNs + "RowVersion", 0))));
envelope.Body.Add(new XElement(MessageNs + "useMaster", "false"));
var response = invoker.InvokeResponse();
var extractor = new TableExtractor<T>(response, table.ToString());
return extractor.Extract();
}
public List<Hierarchy> GetHierarchy()
{
return GetMetadata<Hierarchy>(MetadataRowSetNames.Hierarchy).Where(h => !h.IsDeleted).ToList();
}
public List<Field> GetFields()
{
return this.GetMetadata<Field>(MetadataRowSetNames.Fields);
}
public List<Constant> GetConstants()
{
return this.GetMetadata<Constant>(MetadataRowSetNames.Constants).Where(c => !c.IsDeleted).ToList();
}
public List<WorkItemType> GetWorkItemTypes()
{
return this.GetMetadata<WorkItemType>(MetadataRowSetNames.WorkItemTypes).Where(t => !t.IsDeleted).ToList();
}
public List<Objects.Action> GetActions()
{
return this.GetMetadata<Objects.Action>(MetadataRowSetNames.Actions).Where(t => !t.IsDeleted).ToList();
}
public List<StoredQuery> GetStoredQueries(Project project)
{
var invoker = new SoapInvoker(this);
var msg = invoker.CreateEnvelope("GetStoredQueries", headerName);
msg.Header.Add(GetHeaderElement());
msg.Body.Add(new XElement(MessageNs + "rowVersion", 0));
msg.Body.Add(new XElement(MessageNs + "projectId", project.Id));
var response = invoker.InvokeResponse();
var extractor = new TableExtractor<StoredQuery>(response, "StoredQueries");
return extractor.Extract();
}
public List<int> GetWorkItemIds(StoredQuery query, FieldList fields)
{
WorkItemContext context = new WorkItemContext { ProjectId = query.ProjectId, Me = WorkItemsContext.WhoAmI };
var invoker = new SoapInvoker(this);
var envelope = invoker.CreateEnvelope("QueryWorkitems", headerName);
envelope.Header.Add(GetHeaderElement());
XNamespace queryNs = XNamespace.Get("");
envelope.Body.Add(new XElement(MessageNs + "psQuery",
new XElement(queryNs + "Query", new XAttribute("Product", this.Url.ToString()), query.GetQueryXml(context, fields))));
XElement sorting = query.GetSortingXml();
foreach (var items in sorting.DescendantsAndSelf())
{
items.Name = MessageNs + items.Name.LocalName;
}
envelope.Body.Add(sorting);
envelope.Body.Add(new XElement(MessageNs + "useMaster", "false"));
var response = invoker.InvokeResponse();
var queryIds = response.Element(MessageNs + "resultIds").Element("QueryIds");
if (queryIds == null)
return new List<int>();
var list = new List<int>();
foreach (var item in queryIds.Elements("id"))
{
var startId = item.Attribute("s");
if (startId == null)
continue;
var s = Convert.ToInt32(startId.Value);
var endId = item.Attribute("e");
if (endId != null)
{
var e = Convert.ToInt32(endId.Value);
var range = Enumerable.Range(s, e - s + 1);
list.AddRange(range);
}
else
{
list.Add(s);
}
}
return list;
}
public WorkItem GetWorkItem(int id)
{
var invoker = new SoapInvoker(this);
var msg = invoker.CreateEnvelope("GetWorkItem", headerName);
msg.Header.Add(GetHeaderElement());
msg.Body.Add(new XElement(MessageNs + "workItemId", id));
var response = invoker.InvokeResponse();
var extractor = new TableDictionaryExtractor(response, "WorkItemInfo");
var workItem = new WorkItem();
//workItem.Id = id;
var data = extractor.Extract().Single();
workItem.WorkItemInfo = new Dictionary<string, object>();
foreach (var item in data)
{
workItem.WorkItemInfo.Add(item.Key, item.Value);
}
return workItem;
}
public List<WorkItem> PageWorkitemsByIds(StoredQuery query, List<int> ids)
{
if (ids.Count > 50)
throw new Exception("Page only by 50");
var invoker = new SoapInvoker(this);
var msg = invoker.CreateEnvelope("PageWorkitemsByIds", headerName);
msg.Header.Add(GetHeaderElement());
msg.Body.Add(new XElement(MessageNs + "ids", ids.Select(i => new XElement(MessageNs + "int", i))));
var columns = query.GetSelectColumns();
var fields = CachedMetaData.Instance.Fields.GetFieldsByNames(columns);
if (fields["System.Id"] == null) //If No id Exists add it
{
fields.Insert(0, CachedMetaData.Instance.Fields["System.Id"]);
}
msg.Body.Add(new XElement(MessageNs + "columns", fields.Where(f => !f.IsLongField).Select(c => new XElement(MessageNs + "string", c.ReferenceName))));
msg.Body.Add(new XElement(MessageNs + "longTextColumns", fields.Where(f => f.IsLongField).Select(c => new XElement(MessageNs + "int", c.Id))));
var response = invoker.InvokeResponse();
var extractor = new TableDictionaryExtractor(response, "Items");
var data = extractor.Extract();
List<WorkItem> list = new List<WorkItem>();
foreach (var item in data)
{
list.Add(new WorkItem { WorkItemInfo = item });
}
return list;
}
public void Associate(int workItemId, int changeSet, string comment)
{
var workItem = GetWorkItem(workItemId);
var revision = Convert.ToInt32(workItem.WorkItemInfo["System.Rev"]);
string historyMsg = string.Format("Associated with changeset {0}.", changeSet);
string changeSetLink = "vstfs:///VersionControl/Changeset/" + changeSet;
string oneLineComment = comment.Replace(Environment.NewLine, " ");
oneLineComment = oneLineComment.Substring(0, Math.Min(oneLineComment.Length, 120));
var invoker = new SoapInvoker(this);
var msg = invoker.CreateEnvelope("Update", headerName);
msg.Header.Add(GetHeaderElement());
XNamespace packageNs = XNamespace.Get("");
msg.Body.Add(new XElement(MessageNs + "package",
new XElement(packageNs + "Package", new XAttribute("Product", this.Url.ToString()),
new XElement("UpdateWorkItem", new XAttribute("ObjectType", "WorkItem"), new XAttribute("Revision", revision), new XAttribute("WorkItemID", workItemId),
new XElement("ComputedColumns",
new XElement("ComputedColumn", new XAttribute("Column", "System.RevisedDate")),
new XElement("ComputedColumn", new XAttribute("Column", "System.ChangedDate")),
new XElement("ComputedColumn", new XAttribute("Column", "System.PersonId")),
new XElement("ComputedColumn", new XAttribute("Column", "System.AuthorizedDate"))),
new XElement("InsertText", new XAttribute("FieldDisplayName", "History"), new XAttribute("FieldName", "System.History"), historyMsg),
new XElement("InsertResourceLink", new XAttribute("Comment", oneLineComment), new XAttribute("FieldName", "System.BISLinks"), new XAttribute("LinkType", "Fixed in Changeset"), new XAttribute("Location", changeSetLink))
))));
invoker.InvokeResponse();
}
public void Resolve(int workItemId, int changeSet, string comment)
{
throw new NotImplementedException();
}
}
}
| |
#region License
/*
* Copyright 2010 OpenEngSB Division, Vienna University of Technology
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
#region Imports
using System;
using System.Collections;
using Common.Logging;
using System.Text;
#endregion
namespace EngSB.Connector.Common
{
/// <summary>
/// Description of EngsbMessageBuilder.
/// </summary>
public class EngsbMessageBuilder
{
#region Logger
private ILog log = LogManager.GetLogger(typeof(EngsbMessageBuilder));
#endregion
#region Constants
private static readonly string BASE = "base";
private static readonly string SERVICE = "service";
private static readonly string ASB_BASE_NAMESPACE = "http://www.ifs.tuwien.ac.at/asb/";
private static readonly string BASE_NAMESPACE = "http://www.ifs.tuwien.ac.at/asb/AbstractMessage";
private static readonly string SERVICE_NAMESPACE = "http://www.ifs.tuwien.ac.at/engsb/AbstractServiceMessage";
private static readonly string BASE_NAMESPACE_LOCATION = "http://www.ifs.tuwien.ac.at/asb/AbstractMessage/abstract-message.xsd";
private static readonly string BASE_SERVICE_LOCATION = "http://www.ifs.tuwien.ac.at/asb/abstrac-service-message.xsd";
#endregion
//Object used to temporarly store the data required for building the
//message.
private EngsbMessage message = new EngsbMessage();
// /** Storing the namespaces used to build the message. */
private Hashtable namespaces = new Hashtable();
// /** Storing the locations mapped to the namespaces. */
private Hashtable namespaceLocations = new Hashtable();
// /** Body of the message containing the data to be sent. */
private string body;
/** An alternative root namespace. */
private string rootNamespace;
/** An alternative root location. */
private string rootLocation;
/**
* Defines if a message have to be build with schemas and namespaces or
* without.
*/
private bool withSchemasAndNamespace;
/** Uses full own namespaces and does not set base ASB namespace before. */
private bool withOwnFullNamespaces;
private EngsbMessageBuilder() { }
public static EngsbMessageBuilder CreateMessage(string messageType)
{
EngsbMessageBuilder builder = new EngsbMessageBuilder();
builder.message.MessageType = messageType;
return builder;
}
public EngsbMessageBuilder WithSchemasAndNamespace()
{
this.withSchemasAndNamespace = true;
return this;
}
/**
* This method is quite similar to the {@link #withSchemasAndNamespace()}
* method with the different that all namespaces set via the
* {@link #addNamespace(String, String)} method are seen as REAL namespaces
* and not only as parts added to the base ASB base.
*/
public EngsbMessageBuilder WithOwnFullNamespaces()
{
this.withOwnFullNamespaces = true;
this.withSchemasAndNamespace = true;
return this;
}
/**
* This method appends an own namespace to the message. Regularly namespaces
* are written in the form xmlns:namespaceIdentifier=namespace. This method
* allows two kinds of namespaces. If the {@link #withOwnFullNamespaces()}
* flag is set a full namespace is required. Otherwise its ok only putting
* the messagetype in which is appended to the asb base path.
*/
public EngsbMessageBuilder AddNamespace(string namespaceIdentifier, string namespc)
{
this.namespaces.Add(namespaceIdentifier, namespc);
return this;
}
/**
* Appends an own namespace location. If a namespace is constructued added
* by the {@link #addNamespace(String, String)} method also the locations
* added by {@link #addNamespaceLocation(String, String)} is called and if
* one with the same namespaceIdentfier is found this location is used.
* Otherwise the pattern ASB_BASE_NAMESPACE plus messageType + .xsd is used.
*/
public EngsbMessageBuilder AddNamespaceLocation(string namespaceIdentifier, string namespaceLocation)
{
this.namespaceLocations.Add(namespaceIdentifier, namespaceLocation);
return this;
}
public EngsbMessageBuilder SetMessageId(Guid id) {
this.message.MessageId = id;
return this;
}
public EngsbMessageBuilder SetParentId(Guid id)
{
this.message.ParentMessageId = id;
return this;
}
public EngsbMessageBuilder SetCorrelationId(Guid id)
{
this.message.CorrelationId = id;
return this;
}
public EngsbMessageBuilder SetTimestamp(DateTime ts)
{
this.message.Timestamp = ts;
return this;
}
public EngsbMessageBuilder SetBody(string body)
{
this.body = body;
return this;
}
public EngsbMessageBuilder SetReplyQueue(string replyQueue)
{
this.message.ReplyQueue = replyQueue;
return this;
}
/**
* Actually the root namespace is build out of
* xmlns=\"http://www.ifs.tuwien.ac.at/asb/ plus the name of the message.
* Since this may not be enough or is defined in some user way this method
* allows to set an alternative namesapce completely different from the one
* presented.
*/
public EngsbMessageBuilder SetAlternativeRootNamespace(string nmspc)
{
this.rootNamespace = nmspc;
return this;
}
/**
* Actually the root location (of the xsd file) is build out of
* xmlns=\"http://www.ifs.tuwien.ac.at/asb/ plus the name of the message
* plus .xsd. Nevertheless since its possible that the file is named in
* another way it have to be possible to add an own location at all.
*/
public EngsbMessageBuilder SetAlternativeRootLocation(string location)
{
this.rootLocation = location;
return this;
}
/**
* Access to the internal data without to analyse the created xml.
*/
public EngsbMessage GetInnerMessage()
{
return this.message;
}
/**
* This method is quite similar to the {@link #finish()} method with the
* difference that it used the "new" way to build messages. The difference
* is that also service messages are allowed which is completely ignored by
* the {@link #finish()} method and further more the explicit definition of
* namespaces which is also not allowed by the {@link #finish()} method.
*/
public string Finish()
{
StringBuilder builder = new StringBuilder();
char first = char.ToLower(this.message.MessageType[0]);
string rootName = first + this.message.MessageType.Substring(1);
builder.Append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n");
builder.Append("<");
builder.Append(rootName);
if (this.withSchemasAndNamespace) AppendSchemasAndNamespaceNew(builder);
builder.Append(">\n");
builder.Append("\t<header>\n");
AppendElement(builder, "messageId", this.message.MessageId.ToString());
AppendElement(builder, "timestamp", formatTimestamp(this.message.Timestamp));
if (this.message.ParentMessageId != null) AppendElement(builder, "parentMessageId", this.message.ParentMessageId.ToString());
if (this.message.CorrelationId != null) AppendElement(builder, "correlationId", this.message.CorrelationId.ToString());
if (!String.IsNullOrEmpty(this.message.ReplyQueue)) AppendServiceMessageHeader(builder, "replyQueue", this.message.ReplyQueue);
builder.Append(" </header>\n");
builder.Append(" <body>\n");
builder.Append(this.body);
builder.Append(" </body>\n");
builder.Append("</");
builder.Append(rootName);
builder.Append(">");
String finalXml = builder.ToString();
this.log.Debug(finalXml);
return finalXml;
}
private string formatTimestamp(DateTime timestamp) {
return timestamp.ToString("yyyy-MM-ddTHH:mm:ss.fff+01:00");
}
private void AppendElement(StringBuilder builder, String name, String value) {
GeneralAppend(builder, name, value, BASE);
}
private void AppendServiceMessageHeader(StringBuilder builder, String name, String value) {
GeneralAppend(builder, name, value, SERVICE);
}
private void GeneralAppend(StringBuilder builder, String name, String value, String type) {
builder.Append("\t\t<").Append(type).Append(":");
builder.Append(name);
builder.Append(">");
builder.Append(value);
builder.Append("</").Append(type).Append(":");
builder.Append(name);
builder.Append(">\n");
}
private void AppendSchemasAndNamespaceNew(StringBuilder builder) {
builder.Append(" xmlns=").Append("\"");
if (String.IsNullOrEmpty(this.rootNamespace))
{
builder.Append(ASB_BASE_NAMESPACE).Append(this.message.MessageType);
} else {
builder.Append(this.rootNamespace);
}
builder.Append("\"");
builder.Append(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n");
builder.Append(" xmlns:").Append(BASE).Append("=\"").Append(BASE_NAMESPACE).Append("\"\n");
if (!String.IsNullOrEmpty(this.message.ReplyQueue))
{
builder.Append(" xmlns:").Append(SERVICE).Append("=\"").Append(SERVICE_NAMESPACE).Append("\"\n");
}
foreach (DictionaryEntry entry in this.namespaces) {
builder.Append(" xmlns:");
builder.Append(entry.Key);
builder.Append("=\"");
if (!this.withOwnFullNamespaces) {
builder.Append(ASB_BASE_NAMESPACE);
}
builder.Append(entry.Value);
builder.Append("\"\n");
}
builder.Append("xsi:schemaLocation=\"");
AppendSchemaLocationWithOwnNamespace(builder, BASE_NAMESPACE, BASE_NAMESPACE_LOCATION);
if (!String.IsNullOrEmpty(this.message.ReplyQueue))
{
AppendSchemaLocationWithOwnNamespace(builder, SERVICE_NAMESPACE, BASE_SERVICE_LOCATION);
}
if (String.IsNullOrEmpty(this.rootLocation))
{
AppendSchemaLocation(builder, this.message.MessageType);
}
else
{
AppendSchemaLocationWithOwnNamespace(builder, this.rootNamespace, this.rootLocation);
}
if (!this.withOwnFullNamespaces)
{
foreach (DictionaryEntry entry in this.namespaces)
{
AppendSchemaLocation(builder, (string)entry.Value);
}
}
else
{
foreach (DictionaryEntry entry in this.namespaces) {
AppendSchemaLocationWithOwnNamespace(builder,(string) entry.Value,(string) this.namespaceLocations[entry.Key]);
}
}
builder.Append("\"");
}
private void AppendSchemaLocationWithOwnNamespace(StringBuilder builder, String nmspace, String namespaceLocation)
{
builder.Append(" ").Append(nmspace).Append(" ").Append(namespaceLocation).Append("\n");
}
private void AppendSchemaLocation(StringBuilder builder, String messageType) {
String uri = "http://www.ifs.tuwien.ac.at/asb/" + messageType;
builder.Append("\n ");
builder.Append(uri);
builder.Append(' ');
builder.Append(uri);
builder.Append('/');
builder.Append(char.ToLower(messageType[0]));
for (int i = 1; i < messageType.Length; ++i) {
char ch = messageType[i];
if (char.IsUpper(ch)) {
builder.Append('-');
}
builder.Append(char.ToLower(ch));
}
builder.Append(".xsd");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Resources;
using System.Threading;
using System.Windows.Forms;
using TCPRelayCommon;
using TCPRelayControls;
using System.Drawing;
namespace TCPRelayWindow
{
public partial class TCPRelayForm : Form, IConnectionListener
{
private TCPRelay relay = new TCPRelay();
private ResourceManager rm;
private AdvancedSettingsForm advForm;
public TCPRelayForm()
{
InitializeComponent();
rm = new ResourceManager("TCPRelayWindow.WinFormStrings", typeof(TCPRelayForm).Assembly);
advForm = new AdvancedSettingsForm(this, relay.Parameters);
AssemblyInfoHelper helper = new AssemblyInfoHelper(typeof(TCPRelayWindow));
lblVersionCopyright.Text = "TCPRelay v" + helper.AssemblyInformationalVersion;
lblTargetURI.Text = rm.GetString("strTargetURI") + ":";
lblListenPort.Text = rm.GetString("strListenPort") + ":";
btnAdvancedSettings.Text = rm.GetString("strAdvancedSettings");
lblRunning.Text = rm.GetString("strStopped");
btnStartStop.Text = rm.GetString("strStart");
toolTip1.SetToolTip(btnStartStop, rm.GetString("strStartsTheRelay"));
toolTip1.SetToolTip(cbxTargetURI, rm.GetString("strTargetURIHint"));
toolTip1.SetToolTip(numListenPort, rm.GetString("strListenPortHint"));
toolTip1.SetToolTip(btnLoadTTVServers, rm.GetString("strLoadTwitchTVServersHint"));
RebuildLayout();
}
private int FindWidestString(Font font, params string[] strings)
{
int max = 0;
using (Graphics g = CreateGraphics())
{
foreach (string str in strings)
{
SizeF size = g.MeasureString(str, font);
int newWidth = (int)Math.Ceiling(size.Width);
max = Math.Max(max, newWidth);
}
}
return max;
}
private void RebuildLayout()
{
const int margin = 4;
// TODO find a better way to layout the components... for now this will do
// resize and reposition Load Twitch.tv button
int ttvWidth = 10 + FindWidestString(btnLoadTTVServers.Font,
rm.GetString("strLoadTwitchTVServers"),
rm.GetString("strLoading"));
int ttvDelta = btnLoadTTVServers.Width - ttvWidth;
btnLoadTTVServers.Width = ttvWidth;
btnLoadTTVServers.Left += ttvDelta;
// align Target URI and Listen Port fields
int uriPortLeft = Math.Max(lblTargetURI.Right, lblListenPort.Right) + margin;
int uriDelta = cbxTargetURI.Left - uriPortLeft;
cbxTargetURI.Left = uriPortLeft;
numListenPort.Left = uriPortLeft;
// move Advanced Settings button to the right of the Listen Port
btnAdvancedSettings.Left = numListenPort.Right + margin;
btnAdvancedSettings.Width = 10 + FindWidestString(lblRunning.Font, rm.GetString("strAdvancedSettings"));
// resize and reposition Target URI field width to fit the new position
cbxTargetURI.Width += uriDelta + ttvDelta;
// resize and reposition Start/Stop button
int ssWidth = 10 + FindWidestString(btnStartStop.Font,
rm.GetString("strStart"),
rm.GetString("strStarting"),
rm.GetString("strStop"),
rm.GetString("strStopping"));
int ssDelta = btnStartStop.Width - ssWidth;
btnStartStop.Width = ssWidth;
btnStartStop.Left += ssDelta;
// resize and reposition status label
int stWidth = 5 + FindWidestString(lblRunning.Font,
rm.GetString("strStarted"),
rm.GetString("strStopped"),
rm.GetString("strFailed"));
lblRunning.Width = stWidth;
lblRunning.Left = btnStartStop.Left - stWidth - margin;
}
private void TCPRelayForm_Load(object sender, EventArgs e)
{
btnLoadTTVServers.Enabled = false;
btnLoadTTVServers.Text = rm.GetString("strLoading");
string val = RegistryUtils.GetString("LastTargetURI");
if (val != null)
cbxTargetURI.Text = val;
int? listenPort = RegistryUtils.GetDWord("LastListenPort");
if (listenPort != null)
numListenPort.Value = (decimal)listenPort;
initTargetURIListWorker.RunWorkerAsync();
relay.Listeners.Add(this);
}
private void TCPRelayForm_FormClosing(object sender, FormClosingEventArgs e)
{
relay.Stop();
SaveURIList();
}
private Uri GetTargetURI()
{
object item = cbxTargetURI.SelectedItem;
return ToURI(item);
}
private Uri ToURI(object item)
{
Uri rtmpUri;
TwitchTvIngestServerData sd = item as TwitchTvIngestServerData;
if (sd != null)
rtmpUri = new Uri(sd.Uri);
else if (item != null)
rtmpUri = new Uri(item.ToString());
else
{
string txt = cbxTargetURI.Text;
if (txt.Contains("://"))
rtmpUri = new Uri(txt);
else
rtmpUri = new Uri("tcp://" + txt);
}
return rtmpUri;
}
private int GetListenPort()
{
return (int)numListenPort.Value;
}
private void btnStartStop_Click(object sender, EventArgs e)
{
if (relay.IsRunning)
{
btnStartStop.Enabled = false;
btnStartStop.Text = rm.GetString("strStopping");
relay.Stop();
btnStartStop.Enabled = true;
btnStartStop.Text = rm.GetString("strStart");
}
else
{
btnStartStop.Enabled = false;
btnStartStop.Text = rm.GetString("strStarting");
Uri rtmpUri = GetTargetURI();
relay.TargetHost = rtmpUri.Host;
relay.TargetPort = rtmpUri.Port == -1 ? 1935 : rtmpUri.Port;
relay.ListenPort = GetListenPort();
relay.Start();
}
}
private void btnLoadTTVServers_Click(object sender, EventArgs e)
{
btnLoadTTVServers.Enabled = false;
btnLoadTTVServers.Text = rm.GetString("strLoading");
initTargetURIListWorker.RunWorkerAsync();
}
private void initTargetURIListWorker_DoWork(object sender, DoWorkEventArgs e)
{
DelegateUtils.DoAction(this, cbxTargetURI, (cbx) => LoadURIList());
try
{
List<TwitchTvIngestServerData> servers = TwitchTvIngestServerData.Retrieve();
servers.Sort();
e.Result = servers;
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
private void initTargetURIListWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (IsDisposed)
return;
if (!e.Cancelled)
{
int st = cbxTargetURI.SelectionStart;
int ln = cbxTargetURI.SelectionLength;
// TODO refactor this!
// This is an ugly hack to:
// - preserve user entries in the Target URI combo list
// - remove old justin.tv entries generated by earlier versions of TCPRelay
// The Target URI code should be completely revamped/redesigned
HashSet<Uri> currentURIs = new HashSet<Uri>();
List<object> itemsToRemove = new List<object>();
foreach (object item in cbxTargetURI.Items)
{
Uri uri = ToURI(item);
if (uri.Host.Contains("justin.tv"))
{
itemsToRemove.Add(item);
}
else
{
currentURIs.Add(ToURI(item));
}
}
foreach (object item in itemsToRemove)
{
cbxTargetURI.Items.Remove(item);
}
// TODO handle error
if (e.Result != null)
{
(e.Result as List<TwitchTvIngestServerData>).ForEach((server) =>
{
Uri serverUri = new Uri(server.Uri);
if (!currentURIs.Contains(serverUri))
{
cbxTargetURI.Items.Add(server);
currentURIs.Add(serverUri);
}
});
}
cbxTargetURI.SelectionStart = st;
cbxTargetURI.SelectionLength = ln;
}
DelegateUtils.SetEnabled(this, btnLoadTTVServers, true);
DelegateUtils.SetText(this, btnLoadTTVServers, rm.GetString("strLoadTwitchTVServers"));
}
private void cbxTargetURI_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
// TODO refactor this!
HashSet<Uri> currentURIs = new HashSet<Uri>();
foreach (object item in cbxTargetURI.Items)
currentURIs.Add(ToURI(item));
Uri newUri = GetTargetURI();
if (!currentURIs.Contains(newUri))
cbxTargetURI.Items.Add(newUri);
}
}
private void btnAdvancedSettings_Click(object sender, EventArgs e)
{
if (advForm.IsDisposed)
{
advForm = new AdvancedSettingsForm(this, relay.Parameters);
}
advForm.LoadSettings();
advForm.ShowDialog(this);
}
private void AddControl(Control container, Control control)
{
DelegateUtils.DoAction(this, container, control, (ctr, ctl) => ctr.Controls.Add(ctl));
}
private void LoadURIList()
{
// TODO refactor this!
HashSet<Uri> currentURIs = new HashSet<Uri>();
foreach (object item in cbxTargetURI.Items)
currentURIs.Add(ToURI(item));
try
{
string serverListPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\TCPRelay\\";
if (!Directory.Exists(serverListPath))
Directory.CreateDirectory(serverListPath);
using (FileStream file = File.OpenRead(serverListPath + "serverlist.txt"))
using (StreamReader reader = new StreamReader(file))
{
string line;
while ((line = reader.ReadLine()) != null)
{
try
{
if (line.Contains("|"))
{
string[] split = line.Split('|');
if (split.Length < 3)
{
// invalid data; just ignore
continue;
}
string textUri = split[0];
string name = split[1];
string def = split[2];
Uri uri = new Uri(textUri);
TwitchTvIngestServerData data = new TwitchTvIngestServerData(name, textUri, Boolean.Parse(def));
if (!currentURIs.Contains(uri))
{
cbxTargetURI.Items.Add(data);
currentURIs.Add(uri);
}
}
else
{
Uri uri = new Uri(line);
if (!currentURIs.Contains(uri))
{
cbxTargetURI.Items.Add(uri);
currentURIs.Add(uri);
}
}
}
catch (UriFormatException e)
{
Console.WriteLine(e);
}
}
}
}
catch (FileNotFoundException)
{
// ignore
}
}
private void SaveURIList()
{
// TODO refactor this!
HashSet<Uri> currentURIs = new HashSet<Uri>();
foreach (object item in cbxTargetURI.Items)
currentURIs.Add(ToURI(item));
Uri currentUri = GetTargetURI();
if (!currentURIs.Contains(currentUri))
{
cbxTargetURI.Items.Add(currentUri);
currentURIs.Add(currentUri);
}
string serverListPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\TCPRelay\\";
if (!Directory.Exists(serverListPath))
Directory.CreateDirectory(serverListPath);
using (FileStream file = File.OpenWrite(serverListPath + "serverlist.txt"))
using (StreamWriter writer = new StreamWriter(file))
foreach (object item in cbxTargetURI.Items)
{
if (item is TwitchTvIngestServerData)
{
TwitchTvIngestServerData data = item as TwitchTvIngestServerData;
writer.WriteLine(data.Uri + "|" + data.Name + "|" + data.Default);
}
else
{
writer.WriteLine(ToURI(item));
}
}
}
private void TCPRelayStarted()
{
DelegateUtils.SetEnabled(this, cbxTargetURI, false);
DelegateUtils.SetEnabled(this, numListenPort, false);
DelegateUtils.SetEnabled(this, btnAdvancedSettings, false);
DelegateUtils.SetEnabled(this, btnLoadTTVServers, false);
DelegateUtils.SetEnabled(this, btnStartStop, true);
DelegateUtils.SetText(this, btnStartStop, rm.GetString("strStop"));
DelegateUtils.SetText(this, lblRunning, rm.GetString("strStarted"));
DelegateUtils.SetToolTip(this, toolTip1, lblRunning, "");
DelegateUtils.SetToolTip(this, toolTip1, btnStartStop, rm.GetString("strStopsTheRelay"));
DelegateUtils.DoAction(this, cbxTargetURI, (cbx) => RegistryUtils.SetString("LastTargetURI", GetTargetURI().ToString()));
DelegateUtils.DoAction(this, numListenPort, (cbx) => RegistryUtils.SetDWord("LastListenPort", GetListenPort()));
// TODO refactor this!
DelegateUtils.DoAction(this, cbxTargetURI, (cbx) =>
{
HashSet<Uri> currentURIs = new HashSet<Uri>();
foreach (object item in cbx.Items)
currentURIs.Add(ToURI(item));
Uri newUri = GetTargetURI();
if (!currentURIs.Contains(newUri))
cbx.Items.Add(newUri);
});
}
private void TCPRelayStopped()
{
DelegateUtils.SetEnabled(this, cbxTargetURI, true);
DelegateUtils.SetEnabled(this, numListenPort, true);
DelegateUtils.SetEnabled(this, btnAdvancedSettings, true);
DelegateUtils.SetEnabled(this, btnLoadTTVServers, true);
DelegateUtils.SetEnabled(this, btnStartStop, true);
DelegateUtils.SetText(this, btnStartStop, rm.GetString("strStart"));
DelegateUtils.SetText(this, lblRunning, rm.GetString("strStopped"));
DelegateUtils.SetToolTip(this, toolTip1, lblRunning, "");
DelegateUtils.SetToolTip(this, toolTip1, btnStartStop, rm.GetString("strStartsTheRelay"));
}
private void TCPRelayFailed(Exception e)
{
DelegateUtils.SetEnabled(this, cbxTargetURI, true);
DelegateUtils.SetEnabled(this, numListenPort, true);
DelegateUtils.SetEnabled(this, btnAdvancedSettings, true);
DelegateUtils.SetEnabled(this, btnStartStop, true);
DelegateUtils.SetText(this, btnStartStop, rm.GetString("strStart"));
DelegateUtils.SetText(this, lblRunning, rm.GetString("strFailed"));
DelegateUtils.SetToolTip(this, toolTip1, lblRunning, e.Message);
DelegateUtils.SetToolTip(this, toolTip1, btnStartStop, rm.GetString("strStartsTheRelay"));
DelegateUtils.DoAction(this, this, (frm) =>
{
SocketException se = e as SocketException;
if (se == null)
ShowDefaultError(frm, e);
else
{
switch (se.SocketErrorCode)
{
case SocketError.AddressAlreadyInUse:
ShowAddressAlreadyInUseError(frm);
break;
case SocketError.TryAgain:
ShowCustomError(frm, rm.GetString("strCouldNotResolveHostName") + ": " + relay.TargetHost);
break;
default:
ShowDefaultError(frm, e);
break;
}
}
});
}
private void ShowDefaultError(TCPRelayForm frm, Exception e)
{
MessageBox.Show(frm, e.Message, rm.GetString("strFailedToStartTCPRelay"), MessageBoxButtons.OK, MessageBoxIcon.Error);
}
private void ShowCustomError(TCPRelayForm frm, string errorMessage)
{
MessageBox.Show(frm, errorMessage, rm.GetString("strFailedToStartTCPRelay"), MessageBoxButtons.OK, MessageBoxIcon.Error);
}
private void ShowAddressAlreadyInUseError(TCPRelayForm frm)
{
TcpConnection[] conns = TcpConnectionHelper.GetTcpConnections();
TcpConnection curr = null;
foreach (TcpConnection conn in conns)
{
if (conn.LocalEndPoint.Port == relay.ListenPort)
{
curr = conn;
break;
}
}
if (curr == null || curr.Process == null)
{
MessageBox.Show(frm,
String.Format(rm.GetString("strPortAlreadyInUse"), relay.ListenPort),
rm.GetString("strFailedToStartTCPRelay"), MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
MessageBox.Show(frm,
String.Format(rm.GetString("strPortAlreadyInUseByProcess"), relay.ListenPort, curr.Process.MainModule.ModuleName, curr.Process.Id),
rm.GetString("strFailedToStartTCPRelay"), MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public void Started(TCPRelay relay)
{
TCPRelayStarted();
}
public void Stopped(TCPRelay relay)
{
TCPRelayStopped();
}
public void StartFailed(TCPRelay relay, Exception e)
{
TCPRelayFailed(e);
}
public void ConnectionAttempt(TCPRelay relay, IPEndPoint src, string targetHost, int targetPort)
{
tcpRelayConnectionsPanel1.AddConnectionAttempt(src, targetHost, targetPort);
}
public void ConnectionAccepted(TCPRelay relay, Connection c)
{
tcpRelayConnectionsPanel1.AddConnection(c);
}
public void ConnectionClosed(TCPRelay relay, Connection c)
{
tcpRelayConnectionsPanel1.ConnectionClosed(c);
}
public void ConnectionRefused(TCPRelay relay, IPEndPoint src, string targetHost, int targetPort, SocketException e)
{
tcpRelayConnectionsPanel1.AddError(src, targetHost, targetPort, e.Message);
}
public void ConnectionFailed(TCPRelay relay, IPEndPoint src, string targetHost, int targetPort, SocketException e)
{
DelegateUtils.DoAction(this, tcpRelayConnectionsPanel1, (pnl) => pnl.ClearConnectionAttempts());
TCPRelayFailed(e);
}
public void OpenPipe(TCPRelay relay, Connection c, IPEndPoint src, IPEndPoint dest) { }
public void ClosePipe(TCPRelay relay, Connection c, IPEndPoint src, IPEndPoint dest) { }
public void PipeFailure(TCPRelay relay, Connection c, IPEndPoint src, IPEndPoint dest, Exception e) { }
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.11.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsHttp
{
using System;
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>
/// HttpSuccess operations.
/// </summary>
public partial class HttpSuccess : IServiceOperations<AutoRestHttpInfrastructureTestService>, IHttpSuccess
{
/// <summary>
/// Initializes a new instance of the HttpSuccess class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
public HttpSuccess(AutoRestHttpInfrastructureTestService client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestHttpInfrastructureTestService
/// </summary>
public AutoRestHttpInfrastructureTestService Client { get; private set; }
/// <summary>
/// Return 200 status code if successful
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Head200WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Head200", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/http/success/200").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("HEAD");
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));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Get 200 success
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<bool?>> Get200WithHttpMessagesAsync(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, "Get200", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/http/success/200").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));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new 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);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Put boolean value true returning 200 success
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Put200WithHttpMessagesAsync(bool? booleanValue = default(bool?), 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("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Put200", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/http/success/200").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PUT");
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(booleanValue, 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")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Patch true Boolean value in request returning 200
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Patch200WithHttpMessagesAsync(bool? booleanValue = default(bool?), 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("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Patch200", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/http/success/200").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PATCH");
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(booleanValue, 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")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Post bollean value true in request that returns a 200
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Post200WithHttpMessagesAsync(bool? booleanValue = default(bool?), 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("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Post200", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/http/success/200").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(booleanValue, 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")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Delete simple boolean value true returns 200
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Delete200WithHttpMessagesAsync(bool? booleanValue = default(bool?), 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("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Delete200", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/http/success/200").ToString();
// 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);
}
}
// Serialize Request
string requestContent = JsonConvert.SerializeObject(booleanValue, 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")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Put true Boolean value in request returns 201
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Put201WithHttpMessagesAsync(bool? booleanValue = default(bool?), 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("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Put201", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/http/success/201").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PUT");
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(booleanValue, 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), "Created")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Post true Boolean value in request returns 201 (Created)
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Post201WithHttpMessagesAsync(bool? booleanValue = default(bool?), 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("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Post201", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/http/success/201").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(booleanValue, 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), "Created")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Put true Boolean value in request returns 202 (Accepted)
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Put202WithHttpMessagesAsync(bool? booleanValue = default(bool?), 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("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Put202", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/http/success/202").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PUT");
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(booleanValue, 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), "Accepted")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Patch true Boolean value in request returns 202
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Patch202WithHttpMessagesAsync(bool? booleanValue = default(bool?), 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("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Patch202", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/http/success/202").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PATCH");
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(booleanValue, 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), "Accepted")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Post true Boolean value in request returns 202 (Accepted)
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Post202WithHttpMessagesAsync(bool? booleanValue = default(bool?), 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("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Post202", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/http/success/202").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(booleanValue, 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), "Accepted")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Delete true Boolean value in request returns 202 (accepted)
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Delete202WithHttpMessagesAsync(bool? booleanValue = default(bool?), 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("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Delete202", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/http/success/202").ToString();
// 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);
}
}
// Serialize Request
string requestContent = JsonConvert.SerializeObject(booleanValue, 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), "Accepted")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Return 204 status code if successful
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Head204WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Head204", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/http/success/204").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("HEAD");
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), "NoContent")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Put true Boolean value in request returns 204 (no content)
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Put204WithHttpMessagesAsync(bool? booleanValue = default(bool?), 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("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Put204", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/http/success/204").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PUT");
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(booleanValue, 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), "NoContent")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Patch true Boolean value in request returns 204 (no content)
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Patch204WithHttpMessagesAsync(bool? booleanValue = default(bool?), 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("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Patch204", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/http/success/204").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PATCH");
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(booleanValue, 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), "NoContent")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Post true Boolean value in request returns 204 (no content)
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Post204WithHttpMessagesAsync(bool? booleanValue = default(bool?), 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("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Post204", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/http/success/204").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(booleanValue, 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), "NoContent")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Delete true Boolean value in request returns 204 (no content)
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Delete204WithHttpMessagesAsync(bool? booleanValue = default(bool?), 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("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Delete204", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/http/success/204").ToString();
// 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);
}
}
// Serialize Request
string requestContent = JsonConvert.SerializeObject(booleanValue, 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), "NoContent")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Return 404 status code
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Head404WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Head404", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/http/success/404").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("HEAD");
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), "NoContent") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "NotFound")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Projection
// Description: The basic module for MapWindow version 6.0
// ********************************************************************************************************
//
// The original content was ported from the C language from the 4.6 version of Proj4 libraries.
// Frank Warmerdam has released the full content of that version under the MIT license which is
// recognized as being approximately equivalent to public domain. The original work was done
// mostly by Gerald Evenden. The latest versions of the C libraries can be obtained here:
// http://trac.osgeo.org/proj/
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 8/13/2009 10:18:14 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
// Name | Date | Comment
// --------------------|------------|------------------------------------------------------------
// Ted Dunsford | 5/3/2010 | Updated project to DotSpatial.Projection and license to LGPL
// ********************************************************************************************************
using System;
namespace DotSpatial.Projections.Transforms
{
/// <summary>
/// GeostationarySatellite
/// </summary>
public class GeostationarySatellite : EllipticalTransform
{
#region Private Variables
private double _c;
private double _h;
private double _radiusG;
private double _radiusG1;
private double _radiusP;
private double _radiusP2;
private double _radiusPInv2;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of GeostationarySatellite
/// </summary>
public GeostationarySatellite()
{
Name = "Geostationary_Satellite";
Proj4Name = "geos";
}
#endregion
#region Methods
/// <inheritdoc />
protected override void SphericalForward(double[] lp, double[] xy, int startIndex, int numPoints)
{
for (int i = startIndex; i < startIndex + numPoints; i++)
{
int phi = i * 2 + PHI;
int lam = i * 2 + LAMBDA;
int x = i * 2 + X;
int y = i * 2 + Y;
/* Calculation of the three components of the vector from satellite to
** position on earth surface (lon, lat).*/
double tmp = Math.Cos(lp[phi]);
double vx = Math.Cos(lp[lam]) * tmp;
double vy = Math.Sin(lp[lam]) * tmp;
double vz = Math.Sin(lp[phi]);
/* Check visibility.*/
if (((_radiusG - vx) * vx - vy * vy - vz * vz) < 0)
{
xy[x] = double.NaN;
xy[y] = double.NaN;
continue;
//throw new ProjectionException(20);
}
/* Calculation based on view angles from satellite.*/
tmp = _radiusG - vx;
xy[x] = _radiusG1 * Math.Atan(vy / tmp);
xy[y] = _radiusG1 * Math.Atan(vz / Proj.Hypot(vy, tmp));
}
}
/// <inheritdoc />
protected override void EllipticalForward(double[] lp, double[] xy, int startIndex, int numPoints)
{
for (int i = startIndex; i < startIndex + numPoints; i++)
{
int phi = i * 2 + PHI;
int lam = i * 2 + LAMBDA;
int x = i * 2 + X;
int y = i * 2 + Y;
/* Calculation of geocentric latitude. */
lp[phi] = Math.Atan(_radiusP2 * Math.Tan(lp[phi]));
/* Calculation of the three components of the vector from satellite to
** position on earth surface (lon, lat).*/
double r = (_radiusP) / Proj.Hypot(_radiusP * Math.Cos(lp[phi]), Math.Sin(lp[phi]));
double vx = r * Math.Cos(lp[lam]) * Math.Cos(lp[phi]);
double vy = r * Math.Sin(lp[lam]) * Math.Cos(lp[phi]);
double vz = r * Math.Sin(lp[phi]);
/* Check visibility. */
if (((_radiusG - vx) * vx - vy * vy - vz * vz * _radiusPInv2) < 0)
{
xy[x] = double.NaN;
xy[y] = double.NaN;
continue;
// throw new ProjectionException(20);
}
/* Calculation based on view angles from satellite. */
double tmp = _radiusG - vx;
xy[x] = _radiusG1 * Math.Atan(vy / tmp);
xy[y] = _radiusG1 * Math.Atan(vz / Proj.Hypot(vy, tmp));
}
}
/// <inheritdoc />
protected override void SphericalInverse(double[] xy, double[] lp, int startIndex, int numPoints)
{
for (int i = startIndex; i < startIndex + numPoints; i++)
{
int phi = i * 2 + PHI;
int lam = i * 2 + LAMBDA;
int x = i * 2 + X;
int y = i * 2 + Y;
double det;
/* Setting three components of vector from satellite to position.*/
double vx = -1.0;
double vy = Math.Tan(xy[x] / (_radiusG - 1.0));
double vz = Math.Tan(xy[y] / (_radiusG - 1.0)) * Math.Sqrt(1.0 + vy * vy);
/* Calculation of terms in cubic equation and determinant.*/
double a = vy * vy + vz * vz + vx * vx;
double b = 2 * _radiusG * vx;
if ((det = (b * b) - 4 * a * _c) < 0)
{
lp[lam] = double.NaN;
lp[phi] = double.NaN;
continue;
// throw new ProjectionException(20);
}
/* Calculation of three components of vector from satellite to position.*/
double k = (-b - Math.Sqrt(det)) / (2 * a);
vx = _radiusG + k * vx;
vy *= k;
vz *= k;
/* Calculation of longitude and latitude.*/
lp[lam] = Math.Atan2(vy, vx);
lp[phi] = Math.Atan(vz * Math.Cos(lp[lam]) / vx);
}
}
/// <inheritdoc />
protected override void EllipticalInverse(double[] xy, double[] lp, int startIndex, int numPoints)
{
for (int i = startIndex; i < startIndex + numPoints; i++)
{
int phi = i * 2 + PHI;
int lam = i * 2 + LAMBDA;
int x = i * 2 + X;
int y = i * 2 + Y;
double det;
/* Setting three components of vector from satellite to position.*/
double vx = -1.0;
double vy = Math.Tan(xy[x] / _radiusG1);
double vz = Math.Tan(xy[y] / _radiusG1) * Proj.Hypot(1.0, vy);
/* Calculation of terms in cubic equation and determinant.*/
double a = vz / _radiusP;
a = vy * vy + a * a + vx * vx;
double b = 2 * _radiusG * vx;
if ((det = (b * b) - 4 * a * _c) < 0)
{
lp[lam] = double.NaN;
lp[phi] = double.NaN;
continue;
//throw new ProjectionException(20);
}
/* Calculation of three components of vector from satellite to position.*/
double k = (-b - Math.Sqrt(det)) / (2 * a);
vx = _radiusG + k * vx;
vy *= k;
vz *= k;
/* Calculation of longitude and latitude.*/
lp[lam] = Math.Atan2(vy, vx);
lp[phi] = Math.Atan(vz * Math.Cos(lp[lam]) / vx);
lp[phi] = Math.Atan(_radiusPInv2 * Math.Tan(lp[phi]));
}
}
/// <summary>
/// Initializes the transform using the parameters from the specified coordinate system information
/// </summary>
/// <param name="projInfo">A ProjectionInfo class contains all the standard and custom parameters needed to initialize this transform</param>
protected override void OnInit(ProjectionInfo projInfo)
{
if ((_h = projInfo.h.Value) <= 0) throw new ProjectionException(-30);
if (Phi0 == 0) throw new ProjectionException(-46);
_radiusG = 1 + (_radiusG1 = _h / A);
_c = _radiusG * _radiusG - 1.0;
if (IsElliptical)
{
_radiusP = Math.Sqrt(OneEs);
_radiusP2 = OneEs;
_radiusPInv2 = ROneEs;
}
else
{
_radiusP = _radiusP2 = _radiusPInv2 = 1.0;
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;
using System.Windows.Forms;
using System.Xml.Serialization;
using ScanMaster.Acquire.Plugin;
using ScanMaster.Acquire.Plugins;
using ScanMaster.GUI;
namespace ScanMaster
{
public delegate void TweakEventHandler(object sender, TweakEventArgs e);
/// <summary>
/// The profile manager stores and edits profiles. It owns a window and a command processor
/// and handles control flow between them.
/// </summary>
[Serializable]
public class ProfileManager
{
// when the profile manager is in tweak mode it will fire Tweak events
public event TweakEventHandler Tweak;
private ControllerWindow window;
public ControllerWindow Window
{
get { return window; }
set { window = value; }
}
private CommandProcessor processor;
public CommandProcessor Processor
{
get { return processor; }
}
private ArrayList profiles = new ArrayList();
public ArrayList Profiles
{
get { return profiles; }
set { profiles = value; }
}
private Profile currentProfile;
public Profile CurrentProfile
{
get { return currentProfile; }
set { currentProfile = value; }
}
public bool ProfilesChanged = false;
public void Start()
{
// stick in a dummy profiles for now
profiles.Add(new Profile());
processor = new CommandProcessor(this);
processor.Start();
window.UpdateUI();
}
public void Exit()
{
if (ProfilesChanged)
{
if (MessageBox.Show("Profile set has been modified. Save ?", "Save profiles", MessageBoxButtons.YesNo,
MessageBoxIcon.Exclamation) == DialogResult.Yes)
{
Controller.GetController().SaveProfileSet();
}
}
}
public void LoadProfileSetFromSoap(FileStream stream)
{
// load the settings; soap format
SoapFormatter s = new SoapFormatter();
profiles = (ArrayList)s.Deserialize(stream);
currentProfile = null;
window.UpdateUI();
}
public void LoadProfileSetFromXml(FileStream stream)
{
// load the settings; xml format
XmlSerializer s = new XmlSerializer(typeof(ProfileSet));
ProfileSet ps = (ProfileSet)s.Deserialize(stream);
profiles = ps.Profiles;
currentProfile = null;
// Xml serialization cannot handle circular referencing, so each of the plugins need to be
// assigned their AquisitorConfigurations 'by hand'.
foreach(Profile p in profiles)
{
p.AcquisitorConfig.outputPlugin.Config = p.AcquisitorConfig;
p.AcquisitorConfig.switchPlugin.Config = p.AcquisitorConfig;
p.AcquisitorConfig.shotGathererPlugin.Config = p.AcquisitorConfig;
p.AcquisitorConfig.pgPlugin.Config = p.AcquisitorConfig;
p.AcquisitorConfig.yagPlugin.Config = p.AcquisitorConfig;
p.AcquisitorConfig.analogPlugin.Config = p.AcquisitorConfig;
}
window.UpdateUI();
}
public void SaveProfileSetAsSoap(FileStream stream)
{
//save the settings; soap format
SoapFormatter s = new SoapFormatter();
s.Serialize(stream, Profiles);
}
public void SaveProfileSetAsXml(FileStream stream)
{
// save the settings; xml format
XmlSerializer s = new XmlSerializer(typeof(ProfileSet));
ProfileSet ps = new ProfileSet();
ps.Profiles = this.Profiles;
s.Serialize(stream, ps);
}
public void AddNewProfile()
{
profiles.Add(new Profile());
ProfilesChanged = true;
}
public void DeleteProfile(int index)
{
profiles.RemoveAt(index);
ProfilesChanged = true;
}
public void SelectProfile(int index)
{
// no changing profiles while the thing is running - just too confusing !
if (Controller.GetController().appState == Controller.AppState.running) return;
currentProfile = (Profile)profiles[index];
window.WriteLine("Profile changed");
if (processor.groupEditMode)
{
window.WriteLine("Group changed to " + currentProfile.Group);
window.Prompt = currentProfile.Group + ":>";
}
window.UpdateUI();
}
public void SelectProfile(String profile)
{
int index = -1;
for (int i = 0 ; i < profiles.Count ; i++)
{
if (((Profile)profiles[i]).Name == profile) index = i;
}
if (index != -1) SelectProfile(index);
}
public void CloneProfile(int index)
{
profiles.Add(((Profile)profiles[index]).Clone());
ProfilesChanged = true;
}
public Profile GetCloneOfCurrentProfile()
{
return (Profile)currentProfile.Clone();
}
public ArrayList ProfilesInGroup(String group)
{
ArrayList groupProfiles = new ArrayList();
foreach (Profile p in profiles) if (p.Group == group) groupProfiles.Add(p);
return groupProfiles;
}
public void FireTweak(TweakEventArgs e)
{
OnTweak(e);
}
protected virtual void OnTweak( TweakEventArgs e )
{
if (Tweak != null) Tweak(this, e);
}
// When a new setting is introduced into a plugin, there needs to be a way to introduce it into existing
// profile sets. This is the code that does it.
// For each profile, p, a dummy profile, d, is created whose plugins are the same as those of p.
// Because d is constructed anew, all plugin settings will have their default values and any newly
// introduced settings will be present in d. Any settings that are in d, but not in p, are then copied over
// into p. This is done for all the profiles in the set.
public void UpdateProfiles()
{
Type pluginType;
System.Reflection.ConstructorInfo info;
Profile tempProfile = new Profile();
foreach (Profile prof in profiles)
{
// analog input plugin
pluginType = (Type)prof.AcquisitorConfig.analogPlugin.GetType();
info = pluginType.GetConstructor(new Type[] { });
tempProfile.AcquisitorConfig.analogPlugin = (AnalogInputPlugin)info.Invoke(new object[] { });
updateSettings(prof.AcquisitorConfig.analogPlugin.Settings, tempProfile.AcquisitorConfig.analogPlugin.Settings);
// scan output plugin
pluginType = (Type)prof.AcquisitorConfig.outputPlugin.GetType();
info = pluginType.GetConstructor(new Type[] { });
tempProfile.AcquisitorConfig.outputPlugin = (ScanOutputPlugin)info.Invoke(new object[] { });
updateSettings(prof.AcquisitorConfig.outputPlugin.Settings, tempProfile.AcquisitorConfig.outputPlugin.Settings);
// pattern plugin
pluginType = (Type)prof.AcquisitorConfig.pgPlugin.GetType();
info = pluginType.GetConstructor(new Type[] { });
tempProfile.AcquisitorConfig.pgPlugin = (PatternPlugin)info.Invoke(new object[] { });
updateSettings(prof.AcquisitorConfig.pgPlugin.Settings, tempProfile.AcquisitorConfig.pgPlugin.Settings);
// shot gatherer plugin
pluginType = (Type)prof.AcquisitorConfig.shotGathererPlugin.GetType();
info = pluginType.GetConstructor(new Type[] { });
tempProfile.AcquisitorConfig.shotGathererPlugin = (ShotGathererPlugin)info.Invoke(new object[] { });
updateSettings(prof.AcquisitorConfig.shotGathererPlugin.Settings, tempProfile.AcquisitorConfig.shotGathererPlugin.Settings);
// switch plugin
pluginType = (Type)prof.AcquisitorConfig.switchPlugin.GetType();
info = pluginType.GetConstructor(new Type[] { });
tempProfile.AcquisitorConfig.switchPlugin = (SwitchOutputPlugin)info.Invoke(new object[] { });
updateSettings(prof.AcquisitorConfig.switchPlugin.Settings, tempProfile.AcquisitorConfig.switchPlugin.Settings);
// yag plugin
pluginType = (Type)prof.AcquisitorConfig.yagPlugin.GetType();
info = pluginType.GetConstructor(new Type[] { });
tempProfile.AcquisitorConfig.yagPlugin = (YAGPlugin)info.Invoke(new object[] { });
updateSettings(prof.AcquisitorConfig.yagPlugin.Settings, tempProfile.AcquisitorConfig.yagPlugin.Settings);
}
}
// Supports the updateProfiles method
private void updateSettings(PluginSettings currentSettings, PluginSettings defaultSettings)
{
ICollection defaultKeys = defaultSettings.Keys;
String[] defaults = new String[defaultKeys.Count];
defaultKeys.CopyTo(defaults, 0);
foreach (String s in defaults)
if (currentSettings[s] == null) currentSettings[s] = defaultSettings[s];
}
}
public class TweakEventArgs : EventArgs
{
public String parameter;
public double newValue;
public TweakEventArgs( String parameter, int newValue)
{
this.parameter = parameter;
this.newValue = newValue;
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.IO;
using FluentAssertions;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.PlatformAbstractions;
using Microsoft.DotNet.TestFramework;
using Microsoft.DotNet.Tools.Test.Utilities;
using Xunit;
using LocalizableStrings = Microsoft.DotNet.Tools.Run.LocalizableStrings;
namespace Microsoft.DotNet.Cli.Run.Tests
{
public class GivenDotnetRunBuildsCsproj : TestBase
{
[Fact]
public void ItCanRunAMSBuildProject()
{
var testAppName = "MSBuildTestApp";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
new RestoreCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute("/p:SkipInvalidConfigurations=true")
.Should().Pass();
new BuildCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute()
.Should().Pass();
new RunCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput()
.Should().Pass()
.And.HaveStdOutContaining("Hello World!");
}
[Fact]
public void ItImplicitlyRestoresAProjectWhenRunning()
{
var testAppName = "MSBuildTestApp";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
new RunCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput()
.Should().Pass()
.And.HaveStdOutContaining("Hello World!");
}
[Fact]
public void ItCanRunAMultiTFMProjectWithImplicitRestore()
{
var testInstance = TestAssets.Get(
TestAssetKinds.DesktopTestProjects,
"NETFrameworkReferenceNETStandard20")
.CreateInstance()
.WithSourceFiles();
string projectDirectory = Path.Combine(testInstance.Root.FullName, "MultiTFMTestApp");
new RunCommand()
.WithWorkingDirectory(projectDirectory)
.ExecuteWithCapturedOutput("--framework netcoreapp3.0")
.Should().Pass()
.And.HaveStdOutContaining("This string came from the test library!");
}
[Fact]
public void ItDoesNotImplicitlyBuildAProjectWhenRunningWithTheNoBuildOption()
{
var testAppName = "MSBuildTestApp";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var result = new RunCommand()
.WithWorkingDirectory(testInstance.Root.FullName)
.ExecuteWithCapturedOutput("--no-build -v:m");
result.Should().Fail();
if (!DotnetUnderTest.IsLocalized())
{
result.Should().NotHaveStdOutContaining("Restore");
}
}
[Fact]
public void ItDoesNotImplicitlyRestoreAProjectWhenRunningWithTheNoRestoreOption()
{
var testAppName = "MSBuildTestApp";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
new RunCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput("--no-restore")
.Should().Fail()
.And.HaveStdOutContaining("project.assets.json");
}
[Fact]
public void ItBuildsTheProjectBeforeRunning()
{
var testAppName = "MSBuildTestApp";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
new RestoreCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute("/p:SkipInvalidConfigurations=true")
.Should().Pass();
new RunCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput()
.Should().Pass()
.And.HaveStdOutContaining("Hello World!");
}
[Fact]
public void ItCanRunAMSBuildProjectWhenSpecifyingAFramework()
{
var testAppName = "MSBuildTestApp";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
new RestoreCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute("/p:SkipInvalidConfigurations=true")
.Should().Pass();
new RunCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput("--framework netcoreapp3.0")
.Should().Pass()
.And.HaveStdOut("Hello World!");
}
[Fact]
public void ItRunsPortableAppsFromADifferentPathAfterBuilding()
{
var testInstance = TestAssets.Get("MSBuildTestApp")
.CreateInstance()
.WithSourceFiles()
.WithRestoreFiles();
new BuildCommand()
.WithWorkingDirectory(testInstance.Root)
.Execute()
.Should().Pass();
new RunCommand()
.WithWorkingDirectory(testInstance.Root)
.ExecuteWithCapturedOutput($"--no-build")
.Should().Pass()
.And.HaveStdOutContaining("Hello World!");
}
[Fact]
public void ItRunsPortableAppsFromADifferentPathWithoutBuilding()
{
var testAppName = "MSBuildTestApp";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles()
.WithRestoreFiles();
var projectFile = testInstance.Root.GetFile(testAppName + ".csproj");
new RunCommand()
.WithWorkingDirectory(testInstance.Root.Parent)
.ExecuteWithCapturedOutput($"--project {projectFile.FullName}")
.Should().Pass()
.And.HaveStdOutContaining("Hello World!");
}
[Fact]
public void ItRunsPortableAppsFromADifferentPathSpecifyingOnlyTheDirectoryWithoutBuilding()
{
var testAppName = "MSBuildTestApp";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles()
.WithRestoreFiles();
var testProjectDirectory = testInstance.Root.FullName;
new RunCommand()
.WithWorkingDirectory(testInstance.Root.Parent)
.ExecuteWithCapturedOutput($"--project {testProjectDirectory}")
.Should().Pass()
.And.HaveStdOutContaining("Hello World!");
}
[Fact]
public void ItRunsAppWhenRestoringToSpecificPackageDirectory()
{
var rootPath = TestAssets.CreateTestDirectory().FullName;
string dir = "pkgs";
string args = $"--packages {dir}";
string newArgs = $"console -o \"{rootPath}\" --no-restore";
new NewCommandShim()
.WithWorkingDirectory(rootPath)
.Execute(newArgs)
.Should()
.Pass();
new RestoreCommand()
.WithWorkingDirectory(rootPath)
.Execute(args)
.Should()
.Pass();
new RunCommand()
.WithWorkingDirectory(rootPath)
.ExecuteWithCapturedOutput("--no-restore")
.Should().Pass()
.And.HaveStdOutContaining("Hello World");
}
[Fact]
public void ItReportsAGoodErrorWhenProjectHasMultipleFrameworks()
{
var testAppName = "MSBuildAppWithMultipleFrameworks";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles()
.WithRestoreFiles();
// use --no-build so this test can run on all platforms.
// the test app targets net451, which can't be built on non-Windows
new RunCommand()
.WithWorkingDirectory(testInstance.Root)
.ExecuteWithCapturedOutput("--no-build")
.Should().Fail()
.And.HaveStdErrContaining("--framework");
}
[Fact]
public void ItCanPassArgumentsToSubjectAppByDoubleDash()
{
const string testAppName = "MSBuildTestApp";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles()
.WithRestoreFiles();
var testProjectDirectory = testInstance.Root.FullName;
new RunCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput("-- foo bar baz")
.Should()
.Pass()
.And.HaveStdOutContaining("echo args:foo;bar;baz");
}
[Fact]
public void ItGivesAnErrorWhenAttemptingToUseALaunchProfileThatDoesNotExistWhenThereIsNoLaunchSettingsFile()
{
var testAppName = "MSBuildTestApp";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
new RestoreCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute("/p:SkipInvalidConfigurations=true")
.Should().Pass();
new BuildCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute()
.Should().Pass();
new RunCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput("--launch-profile test")
.Should().Pass()
.And.HaveStdOutContaining("Hello World!")
.And.HaveStdErrContaining(LocalizableStrings.RunCommandExceptionCouldNotLocateALaunchSettingsFile);
}
[Fact]
public void ItUsesLaunchProfileOfTheSpecifiedName()
{
var testAppName = "AppWithLaunchSettings";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
new RestoreCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute("/p:SkipInvalidConfigurations=true")
.Should().Pass();
new BuildCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute()
.Should().Pass();
var cmd = new RunCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput("--launch-profile Second");
cmd.Should().Pass()
.And.HaveStdOutContaining("Second");
cmd.StdErr.Should().BeEmpty();
}
[Fact]
public void ItDefaultsToTheFirstUsableLaunchProfile()
{
var testAppName = "AppWithLaunchSettings";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
var launchSettingsPath = Path.Combine(testProjectDirectory, "Properties", "launchSettings.json");
new RestoreCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute("/p:SkipInvalidConfigurations=true")
.Should().Pass();
new BuildCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute()
.Should().Pass();
var cmd = new RunCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput();
cmd.Should().Pass()
.And.NotHaveStdOutContaining(string.Format(LocalizableStrings.UsingLaunchSettingsFromMessage, launchSettingsPath))
.And.HaveStdOutContaining("First");
cmd.StdErr.Should().BeEmpty();
}
[Fact]
public void ItPrintsUsingLaunchSettingsMessageWhenNotQuiet()
{
var testInstance = TestAssets.Get("AppWithLaunchSettings")
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
var launchSettingsPath = Path.Combine(testProjectDirectory, "Properties", "launchSettings.json");
var cmd = new RunCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput("-v:m");
cmd.Should().Pass()
.And.HaveStdOutContaining(string.Format(LocalizableStrings.UsingLaunchSettingsFromMessage, launchSettingsPath))
.And.HaveStdOutContaining("First");
cmd.StdErr.Should().BeEmpty();
}
[Fact]
public void ItPrefersTheValueOfAppUrlFromEnvVarOverTheProp()
{
var testAppName = "AppWithApplicationUrlInLaunchSettings";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
new RestoreCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute("/p:SkipInvalidConfigurations=true")
.Should().Pass();
new BuildCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute()
.Should().Pass();
var cmd = new RunCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput("--launch-profile First");
cmd.Should().Pass()
.And.HaveStdOutContaining("http://localhost:12345/");
cmd.StdErr.Should().BeEmpty();
}
[Fact]
public void ItUsesTheValueOfAppUrlIfTheEnvVarIsNotSet()
{
var testAppName = "AppWithApplicationUrlInLaunchSettings";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
new RestoreCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute("/p:SkipInvalidConfigurations=true")
.Should().Pass();
new BuildCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute()
.Should().Pass();
var cmd = new RunCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput("--launch-profile Second");
cmd.Should().Pass()
.And.HaveStdOutContaining("http://localhost:54321/");
cmd.StdErr.Should().BeEmpty();
}
[Fact]
public void ItGivesAnErrorWhenTheLaunchProfileNotFound()
{
var testAppName = "AppWithLaunchSettings";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
new RestoreCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute("/p:SkipInvalidConfigurations=true")
.Should().Pass();
new BuildCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute()
.Should().Pass();
new RunCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput("--launch-profile Third")
.Should().Pass()
.And.HaveStdOutContaining("(NO MESSAGE)")
.And.HaveStdErrContaining(string.Format(LocalizableStrings.RunCommandExceptionCouldNotApplyLaunchSettings, "Third", "").Trim());
}
[Fact]
public void ItGivesAnErrorWhenTheLaunchProfileCanNotBeHandled()
{
var testAppName = "AppWithLaunchSettings";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
new RestoreCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute("/p:SkipInvalidConfigurations=true")
.Should().Pass();
new BuildCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute()
.Should().Pass();
new RunCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput("--launch-profile \"IIS Express\"")
.Should().Pass()
.And.HaveStdOutContaining("(NO MESSAGE)")
.And.HaveStdErrContaining(string.Format(LocalizableStrings.RunCommandExceptionCouldNotApplyLaunchSettings, "IIS Express", "").Trim());
}
[Fact]
public void ItSkipsLaunchProfilesWhenTheSwitchIsSupplied()
{
var testAppName = "AppWithLaunchSettings";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
new RestoreCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute("/p:SkipInvalidConfigurations=true")
.Should().Pass();
new BuildCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute()
.Should().Pass();
var cmd = new RunCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput("--no-launch-profile");
cmd.Should().Pass()
.And.HaveStdOutContaining("(NO MESSAGE)");
cmd.StdErr.Should().BeEmpty();
}
[Fact]
public void ItSkipsLaunchProfilesWhenTheSwitchIsSuppliedWithoutErrorWhenThereAreNoLaunchSettings()
{
var testAppName = "MSBuildTestApp";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
new RestoreCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute("/p:SkipInvalidConfigurations=true")
.Should().Pass();
new BuildCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute()
.Should().Pass();
var cmd = new RunCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput("--no-launch-profile");
cmd.Should().Pass()
.And.HaveStdOutContaining("Hello World!");
cmd.StdErr.Should().BeEmpty();
}
[Fact]
public void ItSkipsLaunchProfilesWhenThereIsNoUsableDefault()
{
var testAppName = "AppWithLaunchSettingsNoDefault";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
new RestoreCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute("/p:SkipInvalidConfigurations=true")
.Should().Pass();
new BuildCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute()
.Should().Pass();
var cmd = new RunCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput();
cmd.Should().Pass()
.And.HaveStdOutContaining("(NO MESSAGE)")
.And.HaveStdErrContaining(string.Format(LocalizableStrings.RunCommandExceptionCouldNotApplyLaunchSettings, LocalizableStrings.DefaultLaunchProfileDisplayName, "").Trim());
}
[Fact]
public void ItPrintsAnErrorWhenLaunchSettingsAreCorrupted()
{
var testAppName = "AppWithCorruptedLaunchSettings";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
new RestoreCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute("/p:SkipInvalidConfigurations=true")
.Should().Pass();
new BuildCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute()
.Should().Pass();
var cmd = new RunCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput();
cmd.Should().Pass()
.And.HaveStdOutContaining("(NO MESSAGE)")
.And.HaveStdErrContaining(string.Format(LocalizableStrings.RunCommandExceptionCouldNotApplyLaunchSettings, LocalizableStrings.DefaultLaunchProfileDisplayName, "").Trim());
}
[Fact]
public void ItRunsWithTheSpecifiedVerbosity()
{
var testAppName = "MSBuildTestApp";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var result = new RunCommand()
.WithWorkingDirectory( testInstance.Root.FullName)
.ExecuteWithCapturedOutput("-v:n");
result.Should().Pass()
.And.HaveStdOutContaining("Hello World!");
if (!DotnetUnderTest.IsLocalized())
{
result.Should().HaveStdOutContaining("Restore")
.And.HaveStdOutContaining("CoreCompile");
}
}
[Fact]
public void ItRunsWithDotnetWithoutApphost()
{
var testInstance = TestAssets.Get("AppOutputsExecutablePath").CreateInstance().WithSourceFiles();
var command = new RunCommand()
.WithWorkingDirectory(testInstance.Root.FullName);
command.Environment["UseAppHost"] = "false";
command.ExecuteWithCapturedOutput()
.Should()
.Pass()
.And
.HaveStdOutContaining($"dotnet{Constants.ExeSuffix}");
}
[Fact]
public void ItRunsWithApphost()
{
var testInstance = TestAssets.Get("AppOutputsExecutablePath").CreateInstance().WithSourceFiles();
var result = new RunCommand()
.WithWorkingDirectory(testInstance.Root.FullName)
.ExecuteWithCapturedOutput();
result.Should().Pass()
.And.HaveStdOutContaining($"AppOutputsExecutablePath{Constants.ExeSuffix}");
}
}
}
| |
using System;
using System.IO;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Macs;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Crypto.Modes
{
/**
* Implements the Counter with Cipher Block Chaining mode (CCM) detailed in
* NIST Special Publication 800-38C.
* <p>
* <b>Note</b>: this mode is a packet mode - it needs all the data up front.
* </p>
*/
public class CcmBlockCipher
: IAeadBlockCipher
{
private static readonly int BlockSize = 16;
private readonly IBlockCipher cipher;
private readonly byte[] macBlock;
private bool forEncryption;
private byte[] nonce;
private byte[] associatedText;
private int macSize;
private ICipherParameters keyParam;
private readonly MemoryStream data = new MemoryStream();
/**
* Basic constructor.
*
* @param cipher the block cipher to be used.
*/
public CcmBlockCipher(
IBlockCipher cipher)
{
this.cipher = cipher;
this.macBlock = new byte[BlockSize];
if (cipher.GetBlockSize() != BlockSize)
throw new ArgumentException("cipher required with a block size of " + BlockSize + ".");
}
/**
* return the underlying block cipher that we are wrapping.
*
* @return the underlying block cipher that we are wrapping.
*/
public virtual IBlockCipher GetUnderlyingCipher()
{
return cipher;
}
public virtual void Init(
bool forEncryption,
ICipherParameters parameters)
{
this.forEncryption = forEncryption;
if (parameters is AeadParameters)
{
AeadParameters param = (AeadParameters) parameters;
nonce = param.GetNonce();
associatedText = param.GetAssociatedText();
macSize = param.MacSize / 8;
keyParam = param.Key;
}
else if (parameters is ParametersWithIV)
{
ParametersWithIV param = (ParametersWithIV) parameters;
nonce = param.GetIV();
associatedText = null;
macSize = macBlock.Length / 2;
keyParam = param.Parameters;
}
else
{
throw new ArgumentException("invalid parameters passed to CCM");
}
}
public virtual string AlgorithmName
{
get { return cipher.AlgorithmName + "/CCM"; }
}
public virtual int GetBlockSize()
{
return cipher.GetBlockSize();
}
public virtual int ProcessByte(
byte input,
byte[] outBytes,
int outOff)
{
data.WriteByte(input);
return 0;
}
public virtual int ProcessBytes(
byte[] inBytes,
int inOff,
int inLen,
byte[] outBytes,
int outOff)
{
data.Write(inBytes, inOff, inLen);
return 0;
}
public virtual int DoFinal(
byte[] outBytes,
int outOff)
{
byte[] text = data.ToArray();
byte[] enc = ProcessPacket(text, 0, text.Length);
Array.Copy(enc, 0, outBytes, outOff, enc.Length);
Reset();
return enc.Length;
}
public virtual void Reset()
{
cipher.Reset();
data.SetLength(0);
}
/**
* Returns a byte array containing the mac calculated as part of the
* last encrypt or decrypt operation.
*
* @return the last mac calculated.
*/
public virtual byte[] GetMac()
{
byte[] mac = new byte[macSize];
Array.Copy(macBlock, 0, mac, 0, mac.Length);
return mac;
}
public virtual int GetUpdateOutputSize(
int len)
{
return 0;
}
public int GetOutputSize(
int len)
{
if (forEncryption)
{
return (int) data.Length + len + macSize;
}
return (int) data.Length + len - macSize;
}
public byte[] ProcessPacket(
byte[] input,
int inOff,
int inLen)
{
if (keyParam == null)
throw new InvalidOperationException("CCM cipher unitialized.");
IBlockCipher ctrCipher = new SicBlockCipher(cipher);
byte[] iv = new byte[BlockSize];
byte[] output;
iv[0] = (byte)(((15 - nonce.Length) - 1) & 0x7);
Array.Copy(nonce, 0, iv, 1, nonce.Length);
ctrCipher.Init(forEncryption, new ParametersWithIV(keyParam, iv));
if (forEncryption)
{
int index = inOff;
int outOff = 0;
output = new byte[inLen + macSize];
calculateMac(input, inOff, inLen, macBlock);
ctrCipher.ProcessBlock(macBlock, 0, macBlock, 0); // S0
while (index < inLen - BlockSize) // S1...
{
ctrCipher.ProcessBlock(input, index, output, outOff);
outOff += BlockSize;
index += BlockSize;
}
byte[] block = new byte[BlockSize];
Array.Copy(input, index, block, 0, inLen - index);
ctrCipher.ProcessBlock(block, 0, block, 0);
Array.Copy(block, 0, output, outOff, inLen - index);
outOff += inLen - index;
Array.Copy(macBlock, 0, output, outOff, output.Length - outOff);
}
else
{
int index = inOff;
int outOff = 0;
output = new byte[inLen - macSize];
Array.Copy(input, inOff + inLen - macSize, macBlock, 0, macSize);
ctrCipher.ProcessBlock(macBlock, 0, macBlock, 0);
for (int i = macSize; i != macBlock.Length; i++)
{
macBlock[i] = 0;
}
while (outOff < output.Length - BlockSize)
{
ctrCipher.ProcessBlock(input, index, output, outOff);
outOff += BlockSize;
index += BlockSize;
}
byte[] block = new byte[BlockSize];
Array.Copy(input, index, block, 0, output.Length - outOff);
ctrCipher.ProcessBlock(block, 0, block, 0);
Array.Copy(block, 0, output, outOff, output.Length - outOff);
byte[] calculatedMacBlock = new byte[BlockSize];
calculateMac(output, 0, output.Length, calculatedMacBlock);
if (!Arrays.AreEqual(macBlock, calculatedMacBlock))
throw new InvalidCipherTextException("mac check in CCM failed");
}
return output;
}
private int calculateMac(byte[] data, int dataOff, int dataLen, byte[] macBlock)
{
IMac cMac = new CbcBlockCipherMac(cipher, macSize * 8);
cMac.Init(keyParam);
//
// build b0
//
byte[] b0 = new byte[16];
if (hasAssociatedText())
{
b0[0] |= 0x40;
}
b0[0] |= (byte)((((cMac.GetMacSize() - 2) / 2) & 0x7) << 3);
b0[0] |= (byte)(((15 - nonce.Length) - 1) & 0x7);
Array.Copy(nonce, 0, b0, 1, nonce.Length);
int q = dataLen;
int count = 1;
while (q > 0)
{
b0[b0.Length - count] = (byte)(q & 0xff);
q >>= 8;
count++;
}
cMac.BlockUpdate(b0, 0, b0.Length);
//
// process associated text
//
if (hasAssociatedText())
{
int extra;
if (associatedText.Length < ((1 << 16) - (1 << 8)))
{
cMac.Update((byte)(associatedText.Length >> 8));
cMac.Update((byte)associatedText.Length);
extra = 2;
}
else // can't go any higher than 2^32
{
cMac.Update((byte)0xff);
cMac.Update((byte)0xfe);
cMac.Update((byte)(associatedText.Length >> 24));
cMac.Update((byte)(associatedText.Length >> 16));
cMac.Update((byte)(associatedText.Length >> 8));
cMac.Update((byte)associatedText.Length);
extra = 6;
}
cMac.BlockUpdate(associatedText, 0, associatedText.Length);
extra = (extra + associatedText.Length) % 16;
if (extra != 0)
{
for (int i = 0; i != 16 - extra; i++)
{
cMac.Update((byte)0x00);
}
}
}
//
// add the text
//
cMac.BlockUpdate(data, dataOff, dataLen);
return cMac.DoFinal(macBlock, 0);
}
private bool hasAssociatedText()
{
return associatedText != null && associatedText.Length != 0;
}
}
}
| |
using System;
using System.Linq;
using System.Text.RegularExpressions;
using cstsd.Core.Extensions;
using cstsd.Core.Net;
using cstsd.Core.Ts;
using System.Collections.Generic;
namespace cstsd.TypeScript
{
//TODO: rename to API generator?
public class NetCsControllerConverter
{
public virtual NetClass GetControllerApiClientCsClass(NetClass controllerNetClass)
{
var controllerMethods = controllerNetClass
.Methods
.ToList();
return new NetClass
{
Name = controllerNetClass.Name,
Methods = controllerMethods
.Where(m => m.ReturnType.Name != "IActionResult")
.Where(m => m.IsPublic && m.Attributes.Any(a => a == "CsExport"))
.Select(a => GetCsProxy(a, controllerNetClass.Name))
.ToList(),
Fields = GetFields(controllerMethods, controllerNetClass),
IsPublic = true,
Constructor = GetConstructor(controllerNetClass)
};
}
private static NetMethod GetConstructor(NetClass controllerNetClass)
{
return new NetMethod
{
IsPublic = true,
Parameters = new[]
{
new NetParameter
{
FieldType = new NetType
{
Name = "string"
},
Name = "baseUrl"
}
},
MethodBody = "_baseUrl = baseUrl;"
};
}
private static string GetControllerName(string controllerName)
{
if (controllerName.EndsWith("Controller"))
return controllerName.Substring(0, controllerName.Length - "Controller".Length);
return controllerName;
}
private ICollection<NetField> GetFields(IReadOnlyCollection<NetMethod> controllerMethods, NetClass controllerNetClass)
{
var distinctControllerMethods = controllerMethods.Select(m => m.Name)
.Distinct()
.GroupJoin(
controllerMethods,
name => name,
netMethod => netMethod.Name,
(name, netMethods) => netMethods.First())
.ToArray();
//these are just the url fields
var urlStringFields =
distinctControllerMethods.Select(m => GetUrlNavigateConstFieldDeclaration(m, controllerNetClass));
//these are the route data objects
//var routeDataFields =
// distinctControllerMethods.Select(m => GetRouteDataFieldDeclaration(m, controllerNetClass));
return urlStringFields.Cast<NetField>().Union(new [] { new NetFieldDeclaration
{
Name = "_baseUrl",
FieldDeclarationType = NetFieldDeclarationType.ReadOnly,
IsPublic = false,
FieldType = new NetType
{
Name = "string"
}
} }).ToArray(); //.Union(routeDataFields).ToList();
}
private NetMethod GetCsProxy(NetMethod controllerMethod, string controllerName)
{
var csProxy = new NetMethod
{
ReturnType = new NetType
{
Name = "RestRequestAsyncHandle"
},
Name = controllerMethod.Name,
IsPublic = true
};
//get HTTP verb from controller attributes if present. Default to Post
var actionType = controllerMethod.Attributes.Any(attr => attr.Contains("HttpGet")) ? "GET" : "POST";
actionType = controllerMethod.Attributes.Any(attr => attr.Contains("HttpPost")) ? "POST" : actionType;
//gets the param names from controller
var dataParametersString = string.Join(",\r\n", controllerMethod.Parameters.Select(p => $"{p.Name}"));
//these are value params
csProxy.Parameters = controllerMethod.Parameters.Select(p => new NetParameter
{
Name = p.Name,
FieldType = new NetType
{
Name = p.FieldType.Name
}
}).ToList();
csProxy.Parameters.Add(new NetParameter
{
//Action<IRestResponse<{functionReturnType}>>
FieldType = new NetType
{
Name = "Action",
GenericParameters = new[] {
new NetGenericParameter
{
Name = "IRestResponse",
NetGenericParameters = controllerMethod.ReturnType.Name == "void" ? null : new[]
{
new NetGenericParameter(controllerMethod.ReturnType)
}
}
}
//Name = $"Action<IRestResponse<{functionReturnType}>>"
},
Name = "callback"
});
csProxy.MethodBody =
@"return ServiceFramework.FrameworkExec(
baseUrl: _baseUrl,
url: " + $"{csProxy.Name}Url" + @",
data: new {
" + dataParametersString.Indent("\t\t") + @"
},
method: Method." + actionType + @",
callback: callback
);";
return csProxy;
}
private NetFieldDeclaration GetUrlNavigateConstFieldDeclaration(NetMethod netMethod, NetClass controllerNetClass)
{
var route = GetRouteInfo(controllerNetClass, netMethod);
var a = new NetFieldDeclaration
{
DefaultValue = "\"" + route.Url + "\"",
FieldDeclarationType = NetFieldDeclarationType.Const,
FieldType = new NetType { Name = "string" },
IsPublic = true,
Name = netMethod.Name + "Url"
};
return a;
}
//TODO: no route info classes for now
// public NetFieldDeclaration GetRouteDataFieldDeclaration(NetMethod netMethod, NetClass controllerNetClass)
// {
// var route = GetRouteInfo(controllerNetClass, netMethod);
// var a = new NetFieldDeclaration
// {
// DefaultValue =
//$@"{{
// baseUrl: '/',
// controller: '{route.Controller}',
// action: '{route.Action}'
//}}",
// FieldDeclarationType = NetFieldDeclarationType.Const,
// FieldType = new NetType { Name = "IRouteData" },
// IsStatic = true,
// Name = netMethod.Name + "Route"
// };
// return a;
// }
private RouteInfo GetRouteInfo(NetClass controllerNetClass, NetMethod netMethod)
{
var controllerName = GetControllerName(controllerNetClass.Name);
var actionName = netMethod.Name;
var routeInfo = controllerNetClass.Attributes.FirstOrDefault(attr => attr.StartsWith("Route"));
if (string.IsNullOrWhiteSpace(routeInfo))
{
routeInfo = "[controller]/[action]";
}
else
{
var m = Regex.Match(routeInfo, "\"(.*?)\"");
if (m.Success && m.Groups.Count > 1 && m.Groups[1].Success)
{
routeInfo = m.Groups[1].Value;
}
}
var route = routeInfo
.Replace("[controller]", controllerName)
.Replace("[action]", actionName);
if (!route.StartsWith("/"))
route = "/" + route;
return new RouteInfo
{
Url = route,
Controller = controllerName,
Action = actionName
};
}
public class RouteInfo
{
public string Controller { get; set; }
public string Action { get; set; }
public string Url { get; set; }
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
#if !SILVERLIGHT
#if !CLR2
using System.Linq.Expressions;
#else
using Microsoft.Scripting.Ast;
#endif
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Dynamic;
using ComTypes = System.Runtime.InteropServices.ComTypes;
namespace System.Management.Automation.ComInterop
{
internal sealed class ComInvokeBinder
{
private readonly ComMethodDesc _methodDesc;
private readonly Expression _method; // ComMethodDesc to be called
private readonly Expression _dispatch; // IDispatch
private readonly CallInfo _callInfo;
private readonly DynamicMetaObject[] _args;
private readonly bool[] _isByRef;
private readonly Expression _instance;
private BindingRestrictions _restrictions;
private VarEnumSelector _varEnumSelector;
private string[] _keywordArgNames;
private int _totalExplicitArgs; // Includes the individual elements of ArgumentKind.Dictionary (if any)
private ParameterExpression _dispatchObject;
private ParameterExpression _dispatchPointer;
private ParameterExpression _dispId;
private ParameterExpression _dispParams;
private ParameterExpression _paramVariants;
private ParameterExpression _invokeResult;
private ParameterExpression _returnValue;
private ParameterExpression _dispIdsOfKeywordArgsPinned;
private ParameterExpression _propertyPutDispId;
internal ComInvokeBinder(
CallInfo callInfo,
DynamicMetaObject[] args,
bool[] isByRef,
BindingRestrictions restrictions,
Expression method,
Expression dispatch,
ComMethodDesc methodDesc
)
{
Debug.Assert(callInfo != null, "arguments");
Debug.Assert(args != null, "args");
Debug.Assert(isByRef != null, "isByRef");
Debug.Assert(method != null, "method");
Debug.Assert(dispatch != null, "dispatch");
Debug.Assert(TypeUtils.AreReferenceAssignable(typeof(ComMethodDesc), method.Type), "method");
Debug.Assert(TypeUtils.AreReferenceAssignable(typeof(IDispatch), dispatch.Type), "dispatch");
_method = method;
_dispatch = dispatch;
_methodDesc = methodDesc;
_callInfo = callInfo;
_args = args;
_isByRef = isByRef;
_restrictions = restrictions;
// Set Instance to some value so that CallBinderHelper has the right number of parameters to work with
_instance = dispatch;
}
private ParameterExpression DispatchObjectVariable
{
get { return EnsureVariable(ref _dispatchObject, typeof(IDispatch), "dispatchObject"); }
}
private ParameterExpression DispatchPointerVariable
{
get { return EnsureVariable(ref _dispatchPointer, typeof(IntPtr), "dispatchPointer"); }
}
private ParameterExpression DispIdVariable
{
get { return EnsureVariable(ref _dispId, typeof(int), "dispId"); }
}
private ParameterExpression DispParamsVariable
{
get { return EnsureVariable(ref _dispParams, typeof(ComTypes.DISPPARAMS), "dispParams"); }
}
private ParameterExpression InvokeResultVariable
{
get { return EnsureVariable(ref _invokeResult, typeof(Variant), "invokeResult"); }
}
private ParameterExpression ReturnValueVariable
{
get { return EnsureVariable(ref _returnValue, typeof(object), "returnValue"); }
}
private ParameterExpression DispIdsOfKeywordArgsPinnedVariable
{
get { return EnsureVariable(ref _dispIdsOfKeywordArgsPinned, typeof(GCHandle), "dispIdsOfKeywordArgsPinned"); }
}
private ParameterExpression PropertyPutDispIdVariable
{
get { return EnsureVariable(ref _propertyPutDispId, typeof(int), "propertyPutDispId"); }
}
private ParameterExpression ParamVariantsVariable
{
get {
return _paramVariants ??
(_paramVariants = Expression.Variable(VariantArray.GetStructType(_args.Length), "paramVariants"));
}
}
private static ParameterExpression EnsureVariable(ref ParameterExpression var, Type type, string name)
{
if (var != null)
{
return var;
}
return var = Expression.Variable(type, name);
}
private static Type MarshalType(DynamicMetaObject mo, bool isByRef)
{
Type marshalType = (mo.Value == null && mo.HasValue && !mo.LimitType.IsValueType) ? null : mo.LimitType;
// we are not checking that mo.Expression is writeable or whether evaluating it has no sideeffects
// the assumption is that whoever matched it with ByRef arginfo took care of this.
if (isByRef)
{
// Null just means that null was supplied.
if (marshalType == null)
{
marshalType = mo.Expression.Type;
}
marshalType = marshalType.MakeByRefType();
}
return marshalType;
}
internal DynamicMetaObject Invoke()
{
_keywordArgNames = _callInfo.ArgumentNames.ToArray();
_totalExplicitArgs = _args.Length;
Type[] marshalArgTypes = new Type[_args.Length];
// We already tested the instance, so no need to test it again
for (int i = 0; i < _args.Length; i++)
{
DynamicMetaObject curMo = _args[i];
marshalArgTypes[i] = MarshalType(curMo, _isByRef[i]);
}
_varEnumSelector = new VarEnumSelector(marshalArgTypes);
return new DynamicMetaObject(
CreateScope(MakeIDispatchInvokeTarget()),
BindingRestrictions.Combine(_args).Merge(_restrictions)
);
}
private static void AddNotNull(List<ParameterExpression> list, ParameterExpression var)
{
if (var != null) list.Add(var);
}
private Expression CreateScope(Expression expression)
{
List<ParameterExpression> vars = new List<ParameterExpression>();
AddNotNull(vars, _dispatchObject);
AddNotNull(vars, _dispatchPointer);
AddNotNull(vars, _dispId);
AddNotNull(vars, _dispParams);
AddNotNull(vars, _paramVariants);
AddNotNull(vars, _invokeResult);
AddNotNull(vars, _returnValue);
AddNotNull(vars, _dispIdsOfKeywordArgsPinned);
AddNotNull(vars, _propertyPutDispId);
return vars.Count > 0 ? Expression.Block(vars, expression) : expression;
}
private Expression GenerateTryBlock()
{
//
// Declare variables
//
ParameterExpression excepInfo = Expression.Variable(typeof(ExcepInfo), "excepInfo");
ParameterExpression argErr = Expression.Variable(typeof(uint), "argErr");
ParameterExpression hresult = Expression.Variable(typeof(int), "hresult");
List<Expression> tryStatements = new List<Expression>();
Expression expr;
if (_keywordArgNames.Length > 0)
{
string[] names = _keywordArgNames.AddFirst(_methodDesc.Name);
tryStatements.Add(
Expression.Assign(
Expression.Field(
DispParamsVariable,
typeof(ComTypes.DISPPARAMS).GetField("rgdispidNamedArgs")
),
Expression.Call(typeof(UnsafeMethods).GetMethod("GetIdsOfNamedParameters"),
DispatchObjectVariable,
Expression.Constant(names),
DispIdVariable,
DispIdsOfKeywordArgsPinnedVariable
)
)
);
}
//
// Marshal the arguments to Variants
//
// For a call like this:
// comObj.Foo(100, 101, 102, x=123, z=125)
// DISPPARAMS needs to be setup like this:
// cArgs: 5
// cNamedArgs: 2
// rgArgs: 123, 125, 102, 101, 100
// rgdispidNamedArgs: dispid x, dispid z (the dispids of x and z respectively)
Expression[] parameters = MakeArgumentExpressions();
int reverseIndex = _varEnumSelector.VariantBuilders.Length - 1;
int positionalArgs = _varEnumSelector.VariantBuilders.Length - _keywordArgNames.Length; // args passed by position order and not by name
for (int i = 0; i < _varEnumSelector.VariantBuilders.Length; i++, reverseIndex--)
{
int variantIndex;
if (i >= positionalArgs)
{
// Named arguments are in order at the start of rgArgs
variantIndex = i - positionalArgs;
}
else
{
// Positional arguments are in reverse order at the tail of rgArgs
variantIndex = reverseIndex;
}
VariantBuilder variantBuilder = _varEnumSelector.VariantBuilders[i];
Expression marshal = variantBuilder.InitializeArgumentVariant(
VariantArray.GetStructField(ParamVariantsVariable, variantIndex),
parameters[i + 1]
);
if (marshal != null)
{
tryStatements.Add(marshal);
}
}
//
// Call Invoke
//
ComTypes.INVOKEKIND invokeKind;
if (_methodDesc.IsPropertyPut)
{
if (_methodDesc.IsPropertyPutRef)
{
invokeKind = ComTypes.INVOKEKIND.INVOKE_PROPERTYPUTREF;
}
else
{
invokeKind = ComTypes.INVOKEKIND.INVOKE_PROPERTYPUT;
}
}
else
{
// INVOKE_PROPERTYGET should only be needed for COM objects without typeinfo, where we might have to treat properties as methods
invokeKind = ComTypes.INVOKEKIND.INVOKE_FUNC | ComTypes.INVOKEKIND.INVOKE_PROPERTYGET;
}
MethodCallExpression invoke = Expression.Call(
typeof(UnsafeMethods).GetMethod("IDispatchInvoke"),
DispatchPointerVariable,
DispIdVariable,
Expression.Constant(invokeKind),
DispParamsVariable,
InvokeResultVariable,
excepInfo,
argErr
);
expr = Expression.Assign(hresult, invoke);
tryStatements.Add(expr);
//
// ComRuntimeHelpers.CheckThrowException(int hresult, ref ExcepInfo excepInfo, ComMethodDesc method, object args, uint argErr)
List<Expression> args = new List<Expression>();
foreach (Expression parameter in parameters)
{
args.Add(Expression.TypeAs(parameter, typeof(object)));
}
expr = Expression.Call(
typeof(ComRuntimeHelpers).GetMethod("CheckThrowException"),
hresult,
excepInfo,
Expression.Constant(_methodDesc, typeof(ComMethodDesc)),
Expression.NewArrayInit(typeof(object), args),
argErr
);
tryStatements.Add(expr);
//
// _returnValue = (ReturnType)_invokeResult.ToObject();
//
Expression invokeResultObject =
Expression.Call(
InvokeResultVariable,
typeof(Variant).GetMethod("ToObject"));
VariantBuilder[] variants = _varEnumSelector.VariantBuilders;
Expression[] parametersForUpdates = MakeArgumentExpressions();
tryStatements.Add(Expression.Assign(ReturnValueVariable, invokeResultObject));
for (int i = 0, n = variants.Length; i < n; i++)
{
Expression updateFromReturn = variants[i].UpdateFromReturn(parametersForUpdates[i + 1]);
if (updateFromReturn != null)
{
tryStatements.Add(updateFromReturn);
}
}
tryStatements.Add(Expression.Empty());
return Expression.Block(new[] { excepInfo, argErr, hresult }, tryStatements);
}
private Expression GenerateFinallyBlock()
{
List<Expression> finallyStatements = new List<Expression>();
//
// UnsafeMethods.IUnknownRelease(dispatchPointer);
//
finallyStatements.Add(
Expression.Call(
typeof(UnsafeMethods).GetMethod("IUnknownRelease"),
DispatchPointerVariable
)
);
//
// Clear memory allocated for marshalling
//
for (int i = 0, n = _varEnumSelector.VariantBuilders.Length; i < n; i++)
{
Expression clear = _varEnumSelector.VariantBuilders[i].Clear();
if (clear != null)
{
finallyStatements.Add(clear);
}
}
//
// _invokeResult.Clear()
//
finallyStatements.Add(
Expression.Call(
InvokeResultVariable,
typeof(Variant).GetMethod("Clear")
)
);
//
// _dispIdsOfKeywordArgsPinned.Free()
//
if (_dispIdsOfKeywordArgsPinned != null)
{
finallyStatements.Add(
Expression.Call(
DispIdsOfKeywordArgsPinnedVariable,
typeof(GCHandle).GetMethod("Free")
)
);
}
finallyStatements.Add(Expression.Empty());
return Expression.Block(finallyStatements);
}
/// <summary>
/// Create a stub for the target of the optimized lopop.
/// </summary>
/// <returns></returns>
private Expression MakeIDispatchInvokeTarget()
{
Debug.Assert(_varEnumSelector.VariantBuilders.Length == _totalExplicitArgs);
List<Expression> exprs = new List<Expression>();
//
// _dispId = ((DispCallable)this).ComMethodDesc.DispId;
//
exprs.Add(
Expression.Assign(
DispIdVariable,
Expression.Property(_method, typeof(ComMethodDesc).GetProperty("DispId"))
)
);
//
// _dispParams.rgvararg = RuntimeHelpers.UnsafeMethods.ConvertVariantByrefToPtr(ref _paramVariants._element0)
//
if (_totalExplicitArgs != 0)
{
exprs.Add(
Expression.Assign(
Expression.Field(
DispParamsVariable,
typeof(ComTypes.DISPPARAMS).GetField("rgvarg")
),
Expression.Call(
typeof(UnsafeMethods).GetMethod("ConvertVariantByrefToPtr"),
VariantArray.GetStructField(ParamVariantsVariable, 0)
)
)
);
}
//
// _dispParams.cArgs = <number_of_params>;
//
exprs.Add(
Expression.Assign(
Expression.Field(
DispParamsVariable,
typeof(ComTypes.DISPPARAMS).GetField("cArgs")
),
Expression.Constant(_totalExplicitArgs)
)
);
if (_methodDesc.IsPropertyPut)
{
//
// dispParams.cNamedArgs = 1;
// dispParams.rgdispidNamedArgs = RuntimeHelpers.UnsafeMethods.GetNamedArgsForPropertyPut()
//
exprs.Add(
Expression.Assign(
Expression.Field(
DispParamsVariable,
typeof(ComTypes.DISPPARAMS).GetField("cNamedArgs")
),
Expression.Constant(1)
)
);
exprs.Add(
Expression.Assign(
PropertyPutDispIdVariable,
Expression.Constant(ComDispIds.DISPID_PROPERTYPUT)
)
);
exprs.Add(
Expression.Assign(
Expression.Field(
DispParamsVariable,
typeof(ComTypes.DISPPARAMS).GetField("rgdispidNamedArgs")
),
Expression.Call(
typeof(UnsafeMethods).GetMethod("ConvertInt32ByrefToPtr"),
PropertyPutDispIdVariable
)
)
);
}
else
{
//
// _dispParams.cNamedArgs = N;
//
exprs.Add(
Expression.Assign(
Expression.Field(
DispParamsVariable,
typeof(ComTypes.DISPPARAMS).GetField("cNamedArgs")
),
Expression.Constant(_keywordArgNames.Length)
)
);
}
//
// _dispatchObject = _dispatch
// _dispatchPointer = Marshal.GetIDispatchForObject(_dispatchObject);
//
exprs.Add(Expression.Assign(DispatchObjectVariable, _dispatch));
exprs.Add(
Expression.Assign(
DispatchPointerVariable,
Expression.Call(
typeof(Marshal).GetMethod("GetIDispatchForObject"),
DispatchObjectVariable
)
)
);
Expression tryStatements = GenerateTryBlock();
Expression finallyStatements = GenerateFinallyBlock();
exprs.Add(Expression.TryFinally(tryStatements, finallyStatements));
exprs.Add(ReturnValueVariable);
var vars = new List<ParameterExpression>();
foreach (var variant in _varEnumSelector.VariantBuilders)
{
if (variant.TempVariable != null)
{
vars.Add(variant.TempVariable);
}
}
// If the method returns void, return AutomationNull
if (_methodDesc.ReturnType == typeof(void))
{
exprs.Add(System.Management.Automation.Language.ExpressionCache.AutomationNullConstant);
}
return Expression.Block(vars, exprs); ;
}
/// <summary>
/// Gets expressions to access all the arguments. This includes the instance argument.
/// </summary>
private Expression[] MakeArgumentExpressions()
{
Expression[] res;
int copy = 0;
if (_instance != null)
{
res = new Expression[_args.Length + 1];
res[copy++] = _instance;
}
else
{
res = new Expression[_args.Length];
}
for (int i = 0; i < _args.Length; i++)
{
res[copy++] = _args[i].Expression;
}
return res;
}
}
}
#endif
| |
//------------------------------------------------------------------------------
// <copyright file="XPathScanner.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
namespace MS.Internal.Xml.XPath {
using System;
using System.Xml;
using System.Xml.XPath;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Collections;
internal sealed class XPathScanner {
private string xpathExpr;
private int xpathExprIndex;
private LexKind kind;
private char currentChar;
private string name;
private string prefix;
private string stringValue;
private double numberValue = double.NaN;
private bool canBeFunction;
private XmlCharType xmlCharType = XmlCharType.Instance;
public XPathScanner(string xpathExpr) {
if (xpathExpr == null) {
throw XPathException.Create(Res.Xp_ExprExpected, string.Empty);
}
this.xpathExpr = xpathExpr;
NextChar();
NextLex();
}
public string SourceText { get { return this.xpathExpr; } }
private char CurerntChar { get { return currentChar; } }
private bool NextChar() {
Debug.Assert(0 <= xpathExprIndex && xpathExprIndex <= xpathExpr.Length);
if (xpathExprIndex < xpathExpr.Length) {
currentChar = xpathExpr[xpathExprIndex ++];
return true;
}
else {
currentChar = '\0';
return false;
}
}
#if XML10_FIFTH_EDITION
private char PeekNextChar() {
Debug.Assert(0 <= xpathExprIndex && xpathExprIndex <= xpathExpr.Length);
if (xpathExprIndex < xpathExpr.Length) {
return xpathExpr[xpathExprIndex];
}
else {
Debug.Assert(xpathExprIndex == xpathExpr.Length);
return '\0';
}
}
#endif
public LexKind Kind { get { return this.kind; } }
public string Name {
get {
Debug.Assert(this.kind == LexKind.Name || this.kind == LexKind.Axe);
Debug.Assert(this.name != null);
return this.name;
}
}
public string Prefix {
get {
Debug.Assert(this.kind == LexKind.Name);
Debug.Assert(this.prefix != null);
return this.prefix;
}
}
public string StringValue {
get {
Debug.Assert(this.kind == LexKind.String);
Debug.Assert(this.stringValue != null);
return this.stringValue;
}
}
public double NumberValue {
get {
Debug.Assert(this.kind == LexKind.Number);
Debug.Assert(this.numberValue != double.NaN);
return this.numberValue;
}
}
// To parse PathExpr we need a way to distinct name from function.
// THis distinction can't be done without context: "or (1 != 0)" this this a function or 'or' in OrExp
public bool CanBeFunction {
get {
Debug.Assert(this.kind == LexKind.Name);
return this.canBeFunction;
}
}
void SkipSpace() {
while (xmlCharType.IsWhiteSpace(this.CurerntChar) && NextChar()) ;
}
public bool NextLex() {
SkipSpace();
switch (this.CurerntChar) {
case '\0' :
kind = LexKind.Eof;
return false;
case ',': case '@': case '(': case ')':
case '|': case '*': case '[': case ']':
case '+': case '-': case '=': case '#':
case '$':
kind = (LexKind) Convert.ToInt32(this.CurerntChar, CultureInfo.InvariantCulture);
NextChar();
break;
case '<':
kind = LexKind.Lt;
NextChar();
if (this.CurerntChar == '=') {
kind = LexKind.Le;
NextChar();
}
break;
case '>':
kind = LexKind.Gt;
NextChar();
if (this.CurerntChar == '=') {
kind = LexKind.Ge;
NextChar();
}
break;
case '!':
kind = LexKind.Bang;
NextChar();
if (this.CurerntChar == '=') {
kind = LexKind.Ne;
NextChar();
}
break;
case '.':
kind = LexKind.Dot;
NextChar();
if (this.CurerntChar == '.') {
kind = LexKind.DotDot;
NextChar();
}
else if (XmlCharType.IsDigit(this.CurerntChar)) {
kind = LexKind.Number;
numberValue = ScanFraction();
}
break;
case '/':
kind = LexKind.Slash;
NextChar();
if (this.CurerntChar == '/') {
kind = LexKind.SlashSlash;
NextChar();
}
break;
case '"':
case '\'':
this.kind = LexKind.String;
this.stringValue = ScanString();
break;
default:
if (XmlCharType.IsDigit(this.CurerntChar)) {
kind = LexKind.Number;
numberValue = ScanNumber();
}
else if (xmlCharType.IsStartNCNameSingleChar(this.CurerntChar)
#if XML10_FIFTH_EDITION
|| xmlCharType.IsNCNameHighSurrogateChar(this.CurerntChar)
#endif
) {
kind = LexKind.Name;
this.name = ScanName();
this.prefix = string.Empty;
// "foo:bar" is one lexem not three because it doesn't allow spaces in between
// We should distinct it from "foo::" and need process "foo ::" as well
if (this.CurerntChar == ':') {
NextChar();
// can be "foo:bar" or "foo::"
if (this.CurerntChar == ':') { // "foo::"
NextChar();
kind = LexKind.Axe;
}
else { // "foo:*", "foo:bar" or "foo: "
this.prefix = this.name;
if (this.CurerntChar == '*') {
NextChar();
this.name = "*";
}
else if (xmlCharType.IsStartNCNameSingleChar(this.CurerntChar)
#if XML10_FIFTH_EDITION
|| xmlCharType.IsNCNameHighSurrogateChar(this.CurerntChar)
#endif
) {
this.name = ScanName();
}
else {
throw XPathException.Create(Res.Xp_InvalidName, SourceText);
}
}
}
else {
SkipSpace();
if (this.CurerntChar == ':') {
NextChar();
// it can be "foo ::" or just "foo :"
if (this.CurerntChar == ':') {
NextChar();
kind = LexKind.Axe;
}
else {
throw XPathException.Create(Res.Xp_InvalidName, SourceText);
}
}
}
SkipSpace();
this.canBeFunction = (this.CurerntChar == '(');
}
else {
throw XPathException.Create(Res.Xp_InvalidToken, SourceText);
}
break;
}
return true;
}
private double ScanNumber() {
Debug.Assert(this.CurerntChar == '.' || XmlCharType.IsDigit(this.CurerntChar));
int start = xpathExprIndex - 1;
int len = 0;
while (XmlCharType.IsDigit(this.CurerntChar)) {
NextChar(); len ++;
}
if (this.CurerntChar == '.') {
NextChar(); len ++;
while (XmlCharType.IsDigit(this.CurerntChar)) {
NextChar(); len ++;
}
}
return XmlConvert.ToXPathDouble(this.xpathExpr.Substring(start, len));
}
private double ScanFraction() {
Debug.Assert(XmlCharType.IsDigit(this.CurerntChar));
int start = xpathExprIndex - 2;
Debug.Assert(0 <= start && this.xpathExpr[start] == '.');
int len = 1; // '.'
while (XmlCharType.IsDigit(this.CurerntChar)) {
NextChar(); len ++;
}
return XmlConvert.ToXPathDouble(this.xpathExpr.Substring(start, len));
}
private string ScanString() {
char endChar = this.CurerntChar;
NextChar();
int start = xpathExprIndex - 1;
int len = 0;
while(this.CurerntChar != endChar) {
if (! NextChar()) {
throw XPathException.Create(Res.Xp_UnclosedString);
}
len ++;
}
Debug.Assert(this.CurerntChar == endChar);
NextChar();
return this.xpathExpr.Substring(start, len);
}
private string ScanName() {
Debug.Assert(xmlCharType.IsStartNCNameSingleChar(this.CurerntChar)
#if XML10_FIFTH_EDITION
|| xmlCharType.IsNCNameHighSurrogateChar(this.CurerntChar)
#endif
);
int start = xpathExprIndex - 1;
int len = 0;
for (;;) {
if (xmlCharType.IsNCNameSingleChar(this.CurerntChar)) {
NextChar();
len ++;
}
#if XML10_FIFTH_EDITION
else if (xmlCharType.IsNCNameSurrogateChar(this.PeekNextChar(), this.CurerntChar)) {
NextChar();
NextChar();
len += 2;
}
#endif
else {
break;
}
}
return this.xpathExpr.Substring(start, len);
}
public enum LexKind {
Comma = ',',
Slash = '/',
At = '@',
Dot = '.',
LParens = '(',
RParens = ')',
LBracket = '[',
RBracket = ']',
Star = '*',
Plus = '+',
Minus = '-',
Eq = '=',
Lt = '<',
Gt = '>',
Bang = '!',
Dollar = '$',
Apos = '\'',
Quote = '"',
Union = '|',
Ne = 'N', // !=
Le = 'L', // <=
Ge = 'G', // >=
And = 'A', // &&
Or = 'O', // ||
DotDot = 'D', // ..
SlashSlash = 'S', // //
Name = 'n', // XML _Name
String = 's', // Quoted string constant
Number = 'd', // _Number constant
Axe = 'a', // Axe (like child::)
Eof = 'E',
};
}
}
| |
using S7.Net.Types;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Threading.Tasks;
using S7.Net.Protocol;
namespace S7.Net
{
/// <summary>
/// Creates an instance of S7.Net driver
/// </summary>
public partial class Plc
{
/// <summary>
/// Connects to the PLC and performs a COTP ConnectionRequest and S7 CommunicationSetup.
/// </summary>
/// <returns>A task that represents the asynchronous open operation.</returns>
public async Task OpenAsync()
{
await ConnectAsync();
await stream.WriteAsync(ConnectionRequest.GetCOTPConnectionRequest(CPU, Rack, Slot), 0, 22);
var response = await COTP.TPDU.ReadAsync(stream);
if (response.PDUType != 0xd0) //Connect Confirm
{
throw new WrongNumberOfBytesException("Waiting for COTP connect confirm");
}
await stream.WriteAsync(GetS7ConnectionSetup(), 0, 25);
var s7data = await COTP.TSDU.ReadAsync(stream);
if (s7data == null || s7data[1] != 0x03) //Check for S7 Ack Data
{
throw new WrongNumberOfBytesException("Waiting for S7 connection setup");
}
MaxPDUSize = (short)(s7data[18] * 256 + s7data[19]);
}
private async Task ConnectAsync()
{
tcpClient = new TcpClient();
await tcpClient.ConnectAsync(IP, 102);
stream = tcpClient.GetStream();
}
/// <summary>
/// Reads a number of bytes from a DB starting from a specified index. This handles more than 200 bytes with multiple requests.
/// If the read was not successful, check LastErrorCode or LastErrorString.
/// </summary>
/// <param name="dataType">Data type of the memory area, can be DB, Timer, Counter, Merker(Memory), Input, Output.</param>
/// <param name="db">Address of the memory area (if you want to read DB1, this is set to 1). This must be set also for other memory area types: counters, timers,etc.</param>
/// <param name="startByteAdr">Start byte address. If you want to read DB1.DBW200, this is 200.</param>
/// <param name="count">Byte count, if you want to read 120 bytes, set this to 120.</param>
/// <returns>Returns the bytes in an array</returns>
public async Task<byte[]> ReadBytesAsync(DataType dataType, int db, int startByteAdr, int count)
{
List<byte> resultBytes = new List<byte>();
int index = startByteAdr;
while (count > 0)
{
//This works up to MaxPDUSize-1 on SNAP7. But not MaxPDUSize-0.
var maxToRead = (int)Math.Min(count, MaxPDUSize - 18);
byte[] bytes = await ReadBytesWithSingleRequestAsync(dataType, db, index, maxToRead);
if (bytes == null)
return resultBytes.ToArray();
resultBytes.AddRange(bytes);
count -= maxToRead;
index += maxToRead;
}
return resultBytes.ToArray();
}
/// <summary>
/// Read and decode a certain number of bytes of the "VarType" provided.
/// This can be used to read multiple consecutive variables of the same type (Word, DWord, Int, etc).
/// If the read was not successful, check LastErrorCode or LastErrorString.
/// </summary>
/// <param name="dataType">Data type of the memory area, can be DB, Timer, Counter, Merker(Memory), Input, Output.</param>
/// <param name="db">Address of the memory area (if you want to read DB1, this is set to 1). This must be set also for other memory area types: counters, timers,etc.</param>
/// <param name="startByteAdr">Start byte address. If you want to read DB1.DBW200, this is 200.</param>
/// <param name="varType">Type of the variable/s that you are reading</param>
/// <param name="bitAdr">Address of bit. If you want to read DB1.DBX200.6, set 6 to this parameter.</param>
/// <param name="varCount"></param>
public async Task<object> ReadAsync(DataType dataType, int db, int startByteAdr, VarType varType, int varCount, byte bitAdr = 0)
{
int cntBytes = VarTypeToByteLength(varType, varCount);
byte[] bytes = await ReadBytesAsync(dataType, db, startByteAdr, cntBytes);
return ParseBytes(varType, bytes, varCount, bitAdr);
}
/// <summary>
/// Reads a single variable from the PLC, takes in input strings like "DB1.DBX0.0", "DB20.DBD200", "MB20", "T45", etc.
/// If the read was not successful, check LastErrorCode or LastErrorString.
/// </summary>
/// <param name="variable">Input strings like "DB1.DBX0.0", "DB20.DBD200", "MB20", "T45", etc.</param>
/// <returns>Returns an object that contains the value. This object must be cast accordingly.</returns>
public async Task<object> ReadAsync(string variable)
{
var adr = new PLCAddress(variable);
return await ReadAsync(adr.DataType, adr.DbNumber, adr.StartByte, adr.VarType, 1, (byte)adr.BitNumber);
}
/// <summary>
/// Reads all the bytes needed to fill a struct in C#, starting from a certain address, and return an object that can be casted to the struct.
/// </summary>
/// <param name="structType">Type of the struct to be readed (es.: TypeOf(MyStruct)).</param>
/// <param name="db">Address of the DB.</param>
/// <param name="startByteAdr">Start byte address. If you want to read DB1.DBW200, this is 200.</param>
/// <returns>Returns a struct that must be cast.</returns>
public async Task<object> ReadStructAsync(Type structType, int db, int startByteAdr = 0)
{
int numBytes = Types.Struct.GetStructSize(structType);
// now read the package
var resultBytes = await ReadBytesAsync(DataType.DataBlock, db, startByteAdr, numBytes);
// and decode it
return Types.Struct.FromBytes(structType, resultBytes);
}
/// <summary>
/// Reads all the bytes needed to fill a struct in C#, starting from a certain address, and returns the struct or null if nothing was read.
/// </summary>
/// <typeparam name="T">The struct type</typeparam>
/// <param name="db">Address of the DB.</param>
/// <param name="startByteAdr">Start byte address. If you want to read DB1.DBW200, this is 200.</param>
/// <returns>Returns a nulable struct. If nothing was read null will be returned.</returns>
public async Task<T?> ReadStructAsync<T>(int db, int startByteAdr = 0) where T : struct
{
return await ReadStructAsync(typeof(T), db, startByteAdr) as T?;
}
/// <summary>
/// Reads all the bytes needed to fill a class in C#, starting from a certain address, and set all the properties values to the value that are read from the PLC.
/// This reads only properties, it doesn't read private variable or public variable without {get;set;} specified.
/// </summary>
/// <param name="sourceClass">Instance of the class that will store the values</param>
/// <param name="db">Index of the DB; es.: 1 is for DB1</param>
/// <param name="startByteAdr">Start byte address. If you want to read DB1.DBW200, this is 200.</param>
/// <returns>The number of read bytes</returns>
public async Task<Tuple<int, object>> ReadClassAsync(object sourceClass, int db, int startByteAdr = 0)
{
int numBytes = Class.GetClassSize(sourceClass);
if (numBytes <= 0)
{
throw new Exception("The size of the class is less than 1 byte and therefore cannot be read");
}
// now read the package
var resultBytes = await ReadBytesAsync(DataType.DataBlock, db, startByteAdr, numBytes);
// and decode it
Class.FromBytes(sourceClass, resultBytes);
return new Tuple<int, object>(resultBytes.Length, sourceClass);
}
/// <summary>
/// Reads all the bytes needed to fill a class in C#, starting from a certain address, and set all the properties values to the value that are read from the PLC.
/// This reads only properties, it doesn't read private variable or public variable without {get;set;} specified. To instantiate the class defined by the generic
/// type, the class needs a default constructor.
/// </summary>
/// <typeparam name="T">The class that will be instantiated. Requires a default constructor</typeparam>
/// <param name="db">Index of the DB; es.: 1 is for DB1</param>
/// <param name="startByteAdr">Start byte address. If you want to read DB1.DBW200, this is 200.</param>
/// <returns>An instance of the class with the values read from the PLC. If no data has been read, null will be returned</returns>
public async Task<T> ReadClassAsync<T>(int db, int startByteAdr = 0) where T : class
{
return await ReadClassAsync(() => Activator.CreateInstance<T>(), db, startByteAdr);
}
/// <summary>
/// Reads all the bytes needed to fill a class in C#, starting from a certain address, and set all the properties values to the value that are read from the PLC.
/// This reads only properties, it doesn't read private variable or public variable without {get;set;} specified.
/// </summary>
/// <typeparam name="T">The class that will be instantiated</typeparam>
/// <param name="classFactory">Function to instantiate the class</param>
/// <param name="db">Index of the DB; es.: 1 is for DB1</param>
/// <param name="startByteAdr">Start byte address. If you want to read DB1.DBW200, this is 200.</param>
/// <returns>An instance of the class with the values read from the PLC. If no data has been read, null will be returned</returns>
public async Task<T> ReadClassAsync<T>(Func<T> classFactory, int db, int startByteAdr = 0) where T : class
{
var instance = classFactory();
var res = await ReadClassAsync(instance, db, startByteAdr);
int readBytes = res.Item1;
if (readBytes <= 0)
{
return null;
}
return (T)res.Item2;
}
/// <summary>
/// Reads multiple vars in a single request.
/// You have to create and pass a list of DataItems and you obtain in response the same list with the values.
/// Values are stored in the property "Value" of the dataItem and are already converted.
/// If you don't want the conversion, just create a dataItem of bytes.
/// DataItems must not be more than 20 (protocol restriction) and bytes must not be more than 200 + 22 of header (protocol restriction).
/// </summary>
/// <param name="dataItems">List of dataitems that contains the list of variables that must be read. Maximum 20 dataitems are accepted.</param>
public async Task<List<DataItem>> ReadMultipleVarsAsync(List<DataItem> dataItems)
{
int cntBytes = dataItems.Sum(dataItem => VarTypeToByteLength(dataItem.VarType, dataItem.Count));
//TODO: Figure out how to use MaxPDUSize here
//Snap7 seems to choke on PDU sizes above 256 even if snap7
//replies with bigger PDU size in connection setup.
if (dataItems.Count > 20)
throw new Exception("Too many vars requested");
if (cntBytes > 222)
throw new Exception("Too many bytes requested"); // TODO: proper TDU check + split in multiple requests
try
{
// first create the header
int packageSize = 19 + (dataItems.Count * 12);
ByteArray package = new ByteArray(packageSize);
package.Add(ReadHeaderPackage(dataItems.Count));
// package.Add(0x02); // datenart
foreach (var dataItem in dataItems)
{
package.Add(CreateReadDataRequestPackage(dataItem.DataType, dataItem.DB, dataItem.StartByteAdr, VarTypeToByteLength(dataItem.VarType, dataItem.Count)));
}
await stream.WriteAsync(package.Array, 0, package.Array.Length);
var s7data = await COTP.TSDU.ReadAsync(stream); //TODO use Async
if (s7data == null || s7data[14] != 0xff)
throw new PlcException(ErrorCode.WrongNumberReceivedBytes);
ParseDataIntoDataItems(s7data, dataItems);
}
catch (SocketException socketException)
{
throw new PlcException(ErrorCode.ReadData, socketException);
}
catch (Exception exc)
{
throw new PlcException(ErrorCode.ReadData, exc);
}
return dataItems;
}
/// <summary>
/// Write a number of bytes from a DB starting from a specified index. This handles more than 200 bytes with multiple requests.
/// If the write was not successful, check LastErrorCode or LastErrorString.
/// </summary>
/// <param name="dataType">Data type of the memory area, can be DB, Timer, Counter, Merker(Memory), Input, Output.</param>
/// <param name="db">Address of the memory area (if you want to read DB1, this is set to 1). This must be set also for other memory area types: counters, timers,etc.</param>
/// <param name="startByteAdr">Start byte address. If you want to write DB1.DBW200, this is 200.</param>
/// <param name="value">Bytes to write. If more than 200, multiple requests will be made.</param>
/// <returns>A task that represents the asynchronous write operation.</returns>
public async Task WriteBytesAsync(DataType dataType, int db, int startByteAdr, byte[] value)
{
int localIndex = 0;
int count = value.Length;
while (count > 0)
{
//TODO: Figure out how to use MaxPDUSize here
//Snap7 seems to choke on PDU sizes above 256 even if snap7
//replies with bigger PDU size in connection setup.
var maxToWrite = (int)Math.Min(count, 200);
await WriteBytesWithASingleRequestAsync(dataType, db, startByteAdr + localIndex, value.Skip(localIndex).Take(maxToWrite).ToArray());
count -= maxToWrite;
localIndex += maxToWrite;
}
}
/// <summary>
/// Write a single bit from a DB with the specified index.
/// </summary>
/// <param name="dataType">Data type of the memory area, can be DB, Timer, Counter, Merker(Memory), Input, Output.</param>
/// <param name="db">Address of the memory area (if you want to read DB1, this is set to 1). This must be set also for other memory area types: counters, timers,etc.</param>
/// <param name="startByteAdr">Start byte address. If you want to write DB1.DBW200, this is 200.</param>
/// <param name="bitAdr">The address of the bit. (0-7)</param>
/// <param name="value">Bytes to write. If more than 200, multiple requests will be made.</param>
/// <returns>A task that represents the asynchronous write operation.</returns>
public async Task WriteBitAsync(DataType dataType, int db, int startByteAdr, int bitAdr, bool value)
{
if (bitAdr < 0 || bitAdr > 7)
throw new InvalidAddressException(string.Format("Addressing Error: You can only reference bitwise locations 0-7. Address {0} is invalid", bitAdr));
await WriteBitWithASingleRequestAsync(dataType, db, startByteAdr, bitAdr, value);
}
/// <summary>
/// Write a single bit from a DB with the specified index.
/// </summary>
/// <param name="dataType">Data type of the memory area, can be DB, Timer, Counter, Merker(Memory), Input, Output.</param>
/// <param name="db">Address of the memory area (if you want to read DB1, this is set to 1). This must be set also for other memory area types: counters, timers,etc.</param>
/// <param name="startByteAdr">Start byte address. If you want to write DB1.DBW200, this is 200.</param>
/// <param name="bitAdr">The address of the bit. (0-7)</param>
/// <param name="value">Bytes to write. If more than 200, multiple requests will be made.</param>
/// <returns>A task that represents the asynchronous write operation.</returns>
public async Task WriteBitAsync(DataType dataType, int db, int startByteAdr, int bitAdr, int value)
{
if (value < 0 || value > 1)
throw new ArgumentException("Value must be 0 or 1", nameof(value));
await WriteBitAsync(dataType, db, startByteAdr, bitAdr, value == 1);
}
/// <summary>
/// Takes in input an object and tries to parse it to an array of values. This can be used to write many data, all of the same type.
/// You must specify the memory area type, memory are address, byte start address and bytes count.
/// If the read was not successful, check LastErrorCode or LastErrorString.
/// </summary>
/// <param name="dataType">Data type of the memory area, can be DB, Timer, Counter, Merker(Memory), Input, Output.</param>
/// <param name="db">Address of the memory area (if you want to read DB1, this is set to 1). This must be set also for other memory area types: counters, timers,etc.</param>
/// <param name="startByteAdr">Start byte address. If you want to read DB1.DBW200, this is 200.</param>
/// <param name="value">Bytes to write. The lenght of this parameter can't be higher than 200. If you need more, use recursion.</param>
/// <param name="bitAdr">The address of the bit. (0-7)</param>
/// <returns>A task that represents the asynchronous write operation.</returns>
public async Task WriteAsync(DataType dataType, int db, int startByteAdr, object value, int bitAdr = -1)
{
if (bitAdr != -1)
{
//Must be writing a bit value as bitAdr is specified
if (value is bool)
{
await WriteBitAsync(dataType, db, startByteAdr, bitAdr, (bool) value);
}
else if (value is int intValue)
{
if (intValue < 0 || intValue > 7)
throw new ArgumentOutOfRangeException(
string.Format(
"Addressing Error: You can only reference bitwise locations 0-7. Address {0} is invalid",
bitAdr), nameof(bitAdr));
await WriteBitAsync(dataType, db, startByteAdr, bitAdr, intValue == 1);
}
else throw new ArgumentException("Value must be a bool or an int to write a bit", nameof(value));
}
else await WriteBytesAsync(dataType, db, startByteAdr, Serialization.SerializeValue(value));
}
/// <summary>
/// Writes a single variable from the PLC, takes in input strings like "DB1.DBX0.0", "DB20.DBD200", "MB20", "T45", etc.
/// If the write was not successful, check <see cref="LastErrorCode"/> or <see cref="LastErrorString"/>.
/// </summary>
/// <param name="variable">Input strings like "DB1.DBX0.0", "DB20.DBD200", "MB20", "T45", etc.</param>
/// <param name="value">Value to be written to the PLC</param>
/// <returns>A task that represents the asynchronous write operation.</returns>
public async Task WriteAsync(string variable, object value)
{
var adr = new PLCAddress(variable);
await WriteAsync(adr.DataType, adr.DbNumber, adr.StartByte, value, adr.BitNumber);
}
/// <summary>
/// Writes a C# struct to a DB in the PLC
/// </summary>
/// <param name="structValue">The struct to be written</param>
/// <param name="db">Db address</param>
/// <param name="startByteAdr">Start bytes on the PLC</param>
/// <returns>A task that represents the asynchronous write operation.</returns>
public async Task WriteStructAsync(object structValue, int db, int startByteAdr = 0)
{
var bytes = Struct.ToBytes(structValue).ToList();
await WriteBytesAsync(DataType.DataBlock, db, startByteAdr, bytes.ToArray());
}
/// <summary>
/// Writes a C# class to a DB in the PLC
/// </summary>
/// <param name="classValue">The class to be written</param>
/// <param name="db">Db address</param>
/// <param name="startByteAdr">Start bytes on the PLC</param>
/// <returns>A task that represents the asynchronous write operation.</returns>
public async Task WriteClassAsync(object classValue, int db, int startByteAdr = 0)
{
var bytes = Types.Class.ToBytes(classValue).ToList();
await WriteBytesAsync(DataType.DataBlock, db, startByteAdr, bytes.ToArray());
}
private async Task<byte[]> ReadBytesWithSingleRequestAsync(DataType dataType, int db, int startByteAdr, int count)
{
byte[] bytes = new byte[count];
// first create the header
int packageSize = 31;
ByteArray package = new ByteArray(packageSize);
package.Add(ReadHeaderPackage());
// package.Add(0x02); // datenart
package.Add(CreateReadDataRequestPackage(dataType, db, startByteAdr, count));
await stream.WriteAsync(package.Array, 0, package.Array.Length);
var s7data = await COTP.TSDU.ReadAsync(stream);
if (s7data == null || s7data[14] != 0xff)
throw new PlcException(ErrorCode.WrongNumberReceivedBytes);
for (int cnt = 0; cnt < count; cnt++)
bytes[cnt] = s7data[cnt + 18];
return bytes;
}
/// <summary>
/// Write DataItem(s) to the PLC. Throws an exception if the response is invalid
/// or when the PLC reports errors for item(s) written.
/// </summary>
/// <param name="dataItems">The DataItem(s) to write to the PLC.</param>
/// <returns>Task that completes when response from PLC is parsed.</returns>
public async Task WriteAsync(params DataItem[] dataItems)
{
var message = new ByteArray();
var length = S7WriteMultiple.CreateRequest(message, dataItems);
await stream.WriteAsync(message.Array, 0, length).ConfigureAwait(false);
var response = await COTP.TSDU.ReadAsync(stream).ConfigureAwait(false);
S7WriteMultiple.ParseResponse(response, response.Length, dataItems);
}
/// <summary>
/// Writes up to 200 bytes to the PLC. You must specify the memory area type, memory are address, byte start address and bytes count.
/// </summary>
/// <param name="dataType">Data type of the memory area, can be DB, Timer, Counter, Merker(Memory), Input, Output.</param>
/// <param name="db">Address of the memory area (if you want to read DB1, this is set to 1). This must be set also for other memory area types: counters, timers,etc.</param>
/// <param name="startByteAdr">Start byte address. If you want to read DB1.DBW200, this is 200.</param>
/// <param name="value">Bytes to write. The lenght of this parameter can't be higher than 200. If you need more, use recursion.</param>
/// <returns>A task that represents the asynchronous write operation.</returns>
private async Task WriteBytesWithASingleRequestAsync(DataType dataType, int db, int startByteAdr, byte[] value)
{
byte[] bReceive = new byte[513];
int varCount = 0;
try
{
varCount = value.Length;
// first create the header
int packageSize = 35 + value.Length;
ByteArray package = new ByteArray(packageSize);
package.Add(new byte[] { 3, 0, 0 });
package.Add((byte)packageSize);
package.Add(new byte[] { 2, 0xf0, 0x80, 0x32, 1, 0, 0 });
package.Add(Word.ToByteArray((ushort)(varCount - 1)));
package.Add(new byte[] { 0, 0x0e });
package.Add(Word.ToByteArray((ushort)(varCount + 4)));
package.Add(new byte[] { 0x05, 0x01, 0x12, 0x0a, 0x10, 0x02 });
package.Add(Word.ToByteArray((ushort)varCount));
package.Add(Word.ToByteArray((ushort)(db)));
package.Add((byte)dataType);
var overflow = (int)(startByteAdr * 8 / 0xffffU); // handles words with address bigger than 8191
package.Add((byte)overflow);
package.Add(Word.ToByteArray((ushort)(startByteAdr * 8)));
package.Add(new byte[] { 0, 4 });
package.Add(Word.ToByteArray((ushort)(varCount * 8)));
// now join the header and the data
package.Add(value);
await stream.WriteAsync(package.Array, 0, package.Array.Length);
var s7data = await COTP.TSDU.ReadAsync(stream);
if (s7data == null || s7data[14] != 0xff)
{
throw new PlcException(ErrorCode.WrongNumberReceivedBytes);
}
}
catch (Exception exc)
{
throw new PlcException(ErrorCode.WriteData, exc);
}
}
private async Task WriteBitWithASingleRequestAsync(DataType dataType, int db, int startByteAdr, int bitAdr, bool bitValue)
{
byte[] bReceive = new byte[513];
int varCount = 0;
try
{
var value = new[] {bitValue ? (byte) 1 : (byte) 0};
varCount = value.Length;
// first create the header
int packageSize = 35 + value.Length;
ByteArray package = new Types.ByteArray(packageSize);
package.Add(new byte[] { 3, 0, 0 });
package.Add((byte)packageSize);
package.Add(new byte[] { 2, 0xf0, 0x80, 0x32, 1, 0, 0 });
package.Add(Word.ToByteArray((ushort)(varCount - 1)));
package.Add(new byte[] { 0, 0x0e });
package.Add(Word.ToByteArray((ushort)(varCount + 4)));
package.Add(new byte[] { 0x05, 0x01, 0x12, 0x0a, 0x10, 0x01 }); //ending 0x01 is used for writing a sinlge bit
package.Add(Word.ToByteArray((ushort)varCount));
package.Add(Word.ToByteArray((ushort)(db)));
package.Add((byte)dataType);
int overflow = (int)(startByteAdr * 8 / 0xffffU); // handles words with address bigger than 8191
package.Add((byte)overflow);
package.Add(Word.ToByteArray((ushort)(startByteAdr * 8 + bitAdr)));
package.Add(new byte[] { 0, 0x03 }); //ending 0x03 is used for writing a sinlge bit
package.Add(Word.ToByteArray((ushort)(varCount)));
// now join the header and the data
package.Add(value);
await stream.WriteAsync(package.Array, 0, package.Array.Length);
var s7data = await COTP.TSDU.ReadAsync(stream);
if (s7data == null || s7data[14] != 0xff)
throw new PlcException(ErrorCode.WrongNumberReceivedBytes);
}
catch (Exception exc)
{
throw new PlcException(ErrorCode.WriteData, exc);
}
}
}
}
| |
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD.
// All rights reserved. Licensed under the BSD 3-Clause License; see License.txt.
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using Moq.Properties;
namespace Moq
{
/// <summary>
/// Defines the number of invocations allowed by a mocked method.
/// </summary>
public readonly struct Times : IEquatable<Times>
{
private readonly int from;
private readonly int to;
private readonly Kind kind;
private Times(Kind kind, int from, int to)
{
this.from = from;
this.to = to;
this.kind = kind;
}
/// <summary>Deconstructs this instance.</summary>
/// <param name="from">This output parameter will receive the minimum required number of calls satisfying this instance (i.e. the lower inclusive bound).</param>
/// <param name="to">This output parameter will receive the maximum allowed number of calls satisfying this instance (i.e. the upper inclusive bound).</param>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public void Deconstruct(out int from, out int to)
{
if (this.kind == default)
{
// This branch makes `default(Times)` equivalent to `Times.AtLeastOnce()`,
// which is the implicit default across Moq's API for overloads that don't
// accept a `Times` instance. While user code shouldn't use `default(Times)`
// (but instead either specify `Times` explicitly or not at all), it is
// easy enough to correct:
Debug.Assert(this.kind == Kind.AtLeastOnce);
from = 1;
to = int.MaxValue;
}
else
{
from = this.from;
to = this.to;
}
}
/// <summary>
/// Specifies that a mocked method should be invoked <paramref name="callCount"/> times
/// as minimum.
/// </summary>
/// <param name="callCount">The minimum number of times.</param>
/// <returns>An object defining the allowed number of invocations.</returns>
public static Times AtLeast(int callCount)
{
if (callCount < 1)
{
throw new ArgumentOutOfRangeException(nameof(callCount));
}
return new Times(Kind.AtLeast, callCount, int.MaxValue);
}
/// <summary>
/// Specifies that a mocked method should be invoked one time as minimum.
/// </summary>
/// <returns>An object defining the allowed number of invocations.</returns>
public static Times AtLeastOnce()
{
return new Times(Kind.AtLeastOnce, 1, int.MaxValue);
}
/// <summary>
/// Specifies that a mocked method should be invoked <paramref name="callCount"/> times
/// as maximum.
/// </summary>
/// <param name="callCount">The maximum number of times.</param>
/// <returns>An object defining the allowed number of invocations.</returns>
public static Times AtMost(int callCount)
{
if (callCount < 0)
{
throw new ArgumentOutOfRangeException(nameof(callCount));
}
return new Times(Kind.AtMost, 0, callCount);
}
/// <summary>
/// Specifies that a mocked method should be invoked one time as maximum.
/// </summary>
/// <returns>An object defining the allowed number of invocations.</returns>
public static Times AtMostOnce()
{
return new Times(Kind.AtMostOnce, 0, 1);
}
/// <summary>
/// Specifies that a mocked method should be invoked between
/// <paramref name="callCountFrom"/> and <paramref name="callCountTo"/> times.
/// </summary>
/// <param name="callCountFrom">The minimum number of times.</param>
/// <param name="callCountTo">The maximum number of times.</param>
/// <param name="rangeKind">The kind of range. See <see cref="Range"/>.</param>
/// <returns>An object defining the allowed number of invocations.</returns>
public static Times Between(int callCountFrom, int callCountTo, Range rangeKind)
{
if (rangeKind == Range.Exclusive)
{
if (callCountFrom <= 0 || callCountTo <= callCountFrom)
{
throw new ArgumentOutOfRangeException(nameof(callCountFrom));
}
if (callCountTo - callCountFrom == 1)
{
throw new ArgumentOutOfRangeException(nameof(callCountTo));
}
return new Times(Kind.BetweenExclusive, callCountFrom + 1, callCountTo - 1);
}
if (callCountFrom < 0 || callCountTo < callCountFrom)
{
throw new ArgumentOutOfRangeException(nameof(callCountFrom));
}
return new Times(Kind.BetweenInclusive, callCountFrom, callCountTo);
}
/// <summary>
/// Specifies that a mocked method should be invoked exactly
/// <paramref name="callCount"/> times.
/// </summary>
/// <param name="callCount">The times that a method or property can be called.</param>
/// <returns>An object defining the allowed number of invocations.</returns>
public static Times Exactly(int callCount)
{
if (callCount < 0)
{
throw new ArgumentOutOfRangeException(nameof(callCount));
}
return new Times(Kind.Exactly, callCount, callCount);
}
/// <summary>
/// Specifies that a mocked method should not be invoked.
/// </summary>
/// <returns>An object defining the allowed number of invocations.</returns>
public static Times Never()
{
return new Times(Kind.Never, 0, 0);
}
/// <summary>
/// Specifies that a mocked method should be invoked exactly one time.
/// </summary>
/// <returns>An object defining the allowed number of invocations.</returns>
public static Times Once()
{
return new Times(Kind.Once, 1, 1);
}
/// <summary>
/// Returns a value indicating whether this instance is equal to a specified <see cref="Times"/> value.
/// </summary>
/// <param name="other">A <see cref="Times"/> value to compare to this instance.</param>
/// <returns>
/// <see langword="true"/> if <paramref name="other"/> has the same value as this instance;
/// otherwise, <see langword="false"/>.
/// </returns>
public bool Equals(Times other)
{
var (from, to) = this;
var (otherFrom, otherTo) = other;
return from == otherFrom && to == otherTo;
}
/// <summary>
/// Returns a value indicating whether this instance is equal to a specified <see cref="Times"/> value.
/// </summary>
/// <param name="obj">An object to compare to this instance.</param>
/// <returns>
/// <see langword="true"/> if <paramref name="obj"/> has the same value as this instance;
/// otherwise, <see langword="false"/>.
/// </returns>
public override bool Equals(object obj)
{
return obj is Times other && this.Equals(other);
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms
/// and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
var (from, to) = this;
return from.GetHashCode() ^ to.GetHashCode();
}
/// <summary>
/// Determines whether two specified <see cref="Times"/> objects have the same value.
/// </summary>
/// <param name="left">The first <see cref="Times"/>.</param>
/// <param name="right">The second <see cref="Times"/>.</param>
/// <returns>
/// <see langword="true"/> if <paramref name="left"/> has the same value as <paramref name="right"/>;
/// otherwise, <see langword="false"/>.
/// </returns>
public static bool operator ==(Times left, Times right)
{
return left.Equals(right);
}
/// <summary>
/// Determines whether two specified <see cref="Times"/> objects have different values.
/// </summary>
/// <param name="left">The first <see cref="Times"/>.</param>
/// <param name="right">The second <see cref="Times"/>.</param>
/// <returns>
/// <see langword="true"/> if the value of <paramref name="left"/> is different from
/// <paramref name="right"/>'s; otherwise, <see langword="false"/>.
/// </returns>
public static bool operator !=(Times left, Times right)
{
return !left.Equals(right);
}
internal string GetExceptionMessage(int callCount)
{
var (from, to) = this;
if (this.kind == Kind.BetweenExclusive)
{
--from;
++to;
}
string message = null;
switch (this.kind)
{
case Kind.AtLeast: message = Resources.NoMatchingCallsAtLeast; break;
case Kind.AtLeastOnce: message = Resources.NoMatchingCallsAtLeastOnce; break;
case Kind.AtMost: message = Resources.NoMatchingCallsAtMost; break;
case Kind.AtMostOnce: message = Resources.NoMatchingCallsAtMostOnce; break;
case Kind.BetweenExclusive: message = Resources.NoMatchingCallsBetweenExclusive; break;
case Kind.BetweenInclusive: message = Resources.NoMatchingCallsBetweenInclusive; break;
case Kind.Exactly: message = Resources.NoMatchingCallsExactly; break;
case Kind.Once: message = Resources.NoMatchingCallsOnce; break;
case Kind.Never: message = Resources.NoMatchingCallsNever; break;
}
return string.Format(CultureInfo.CurrentCulture, message, from, to, callCount);
}
internal bool Verify(int callCount)
{
var (from, to) = this;
return from <= callCount && callCount <= to;
}
private enum Kind
{
AtLeastOnce,
AtLeast,
AtMost,
AtMostOnce,
BetweenExclusive,
BetweenInclusive,
Exactly,
Once,
Never,
}
}
}
| |
using UnityEngine;
/// <summary>
/// Functionality common to both NGUI and 2D sprites brought out into a single common parent.
/// Mostly contains everything related to drawing the sprite.
/// </summary>
public abstract class UIBasicSprite : UIWidget
{
public enum Type
{
Simple,
Sliced,
Tiled,
Filled,
Advanced,
}
public enum FillDirection
{
Horizontal,
Vertical,
Radial90,
Radial180,
Radial360,
}
public enum AdvancedType
{
Invisible,
Sliced,
Tiled,
}
public enum Flip
{
Nothing,
Horizontally,
Vertically,
Both,
}
[HideInInspector][SerializeField] protected Type mType = Type.Simple;
[HideInInspector][SerializeField] protected FillDirection mFillDirection = FillDirection.Radial360;
[Range(0f, 1f)]
[HideInInspector][SerializeField] protected float mFillAmount = 1.0f;
[HideInInspector][SerializeField] protected bool mInvert = false;
[HideInInspector][SerializeField] protected Flip mFlip = Flip.Nothing;
// Cached to avoid allocations
[System.NonSerialized] Rect mInnerUV = new Rect();
[System.NonSerialized] Rect mOuterUV = new Rect();
/// <summary>
/// When the sprite type is advanced, this determines whether the center is tiled or sliced.
/// </summary>
public AdvancedType centerType = AdvancedType.Sliced;
/// <summary>
/// When the sprite type is advanced, this determines whether the left edge is tiled or sliced.
/// </summary>
public AdvancedType leftType = AdvancedType.Sliced;
/// <summary>
/// When the sprite type is advanced, this determines whether the right edge is tiled or sliced.
/// </summary>
public AdvancedType rightType = AdvancedType.Sliced;
/// <summary>
/// When the sprite type is advanced, this determines whether the bottom edge is tiled or sliced.
/// </summary>
public AdvancedType bottomType = AdvancedType.Sliced;
/// <summary>
/// When the sprite type is advanced, this determines whether the top edge is tiled or sliced.
/// </summary>
public AdvancedType topType = AdvancedType.Sliced;
/// <summary>
/// How the sprite is drawn. It's virtual for legacy reasons (UISlicedSprite, UITiledSprite, UIFilledSprite).
/// </summary>
public virtual Type type
{
get
{
return mType;
}
set
{
if (mType != value)
{
mType = value;
MarkAsChanged();
}
}
}
/// <summary>
/// Sprite flip setting.
/// </summary>
public Flip flip
{
get
{
return mFlip;
}
set
{
if (mFlip != value)
{
mFlip = value;
MarkAsChanged();
}
}
}
/// <summary>
/// Direction of the cut procedure.
/// </summary>
public FillDirection fillDirection
{
get
{
return mFillDirection;
}
set
{
if (mFillDirection != value)
{
mFillDirection = value;
mChanged = true;
}
}
}
/// <summary>
/// Amount of the sprite shown. 0-1 range with 0 being nothing shown, and 1 being the full sprite.
/// </summary>
public float fillAmount
{
get
{
return mFillAmount;
}
set
{
float val = Mathf.Clamp01(value);
if (mFillAmount != val)
{
mFillAmount = val;
mChanged = true;
}
}
}
/// <summary>
/// Minimum allowed width for this widget.
/// </summary>
override public int minWidth
{
get
{
if (type == Type.Sliced || type == Type.Advanced)
{
Vector4 b = border * pixelSize;
int min = Mathf.RoundToInt(b.x + b.z);
return Mathf.Max(base.minWidth, ((min & 1) == 1) ? min + 1 : min);
}
return base.minWidth;
}
}
/// <summary>
/// Minimum allowed height for this widget.
/// </summary>
override public int minHeight
{
get
{
if (type == Type.Sliced || type == Type.Advanced)
{
Vector4 b = border * pixelSize;
int min = Mathf.RoundToInt(b.y + b.w);
return Mathf.Max(base.minHeight, ((min & 1) == 1) ? min + 1 : min);
}
return base.minHeight;
}
}
/// <summary>
/// Whether the sprite should be filled in the opposite direction.
/// </summary>
public bool invert
{
get
{
return mInvert;
}
set
{
if (mInvert != value)
{
mInvert = value;
mChanged = true;
}
}
}
/// <summary>
/// Whether the widget has a border for 9-slicing.
/// </summary>
public bool hasBorder
{
get
{
Vector4 br = border;
return (br.x != 0f || br.y != 0f || br.z != 0f || br.w != 0f);
}
}
/// <summary>
/// Whether the sprite's material is using a pre-multiplied alpha shader.
/// </summary>
public virtual bool premultipliedAlpha { get { return false; } }
/// <summary>
/// Size of the pixel. Overwritten in the NGUI sprite to pull a value from the atlas.
/// </summary>
public virtual float pixelSize { get { return 1f; } }
#if UNITY_EDITOR
/// <summary>
/// Keep sane values.
/// </summary>
protected override void OnValidate ()
{
base.OnValidate();
mFillAmount = Mathf.Clamp01(mFillAmount);
}
#endif
#region Fill Functions
// Static variables to reduce garbage collection
static protected Vector2[] mTempPos = new Vector2[4];
static protected Vector2[] mTempUVs = new Vector2[4];
/// <summary>
/// Convenience function that returns the drawn UVs after flipping gets considered.
/// X = left, Y = bottom, Z = right, W = top.
/// </summary>
Vector4 drawingUVs
{
get
{
switch (mFlip)
{
case Flip.Horizontally: return new Vector4(mOuterUV.xMax, mOuterUV.yMin, mOuterUV.xMin, mOuterUV.yMax);
case Flip.Vertically: return new Vector4(mOuterUV.xMin, mOuterUV.yMax, mOuterUV.xMax, mOuterUV.yMin);
case Flip.Both: return new Vector4(mOuterUV.xMax, mOuterUV.yMax, mOuterUV.xMin, mOuterUV.yMin);
default: return new Vector4(mOuterUV.xMin, mOuterUV.yMin, mOuterUV.xMax, mOuterUV.yMax);
}
}
}
/// <summary>
/// Final widget's color passed to the draw buffer.
/// </summary>
Color32 drawingColor
{
get
{
Color colF = color;
colF.a = finalAlpha;
if (premultipliedAlpha) colF = NGUITools.ApplyPMA(colF);
if (QualitySettings.activeColorSpace == ColorSpace.Linear)
{
colF.r = Mathf.Pow(colF.r, 2.2f);
colF.g = Mathf.Pow(colF.g, 2.2f);
colF.b = Mathf.Pow(colF.b, 2.2f);
}
return colF;
}
}
/// <summary>
/// Fill the draw buffers.
/// </summary>
protected void Fill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols, Rect outer, Rect inner)
{
mOuterUV = outer;
mInnerUV = inner;
switch (type)
{
case Type.Simple:
SimpleFill(verts, uvs, cols);
break;
case Type.Sliced:
SlicedFill(verts, uvs, cols);
break;
case Type.Filled:
FilledFill(verts, uvs, cols);
break;
case Type.Tiled:
TiledFill(verts, uvs, cols);
break;
case Type.Advanced:
AdvancedFill(verts, uvs, cols);
break;
}
}
/// <summary>
/// Regular sprite fill function is quite simple.
/// </summary>
void SimpleFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
Vector4 v = drawingDimensions;
Vector4 u = drawingUVs;
Color32 c = drawingColor;
verts.Add(new Vector3(v.x, v.y));
verts.Add(new Vector3(v.x, v.w));
verts.Add(new Vector3(v.z, v.w));
verts.Add(new Vector3(v.z, v.y));
uvs.Add(new Vector2(u.x, u.y));
uvs.Add(new Vector2(u.x, u.w));
uvs.Add(new Vector2(u.z, u.w));
uvs.Add(new Vector2(u.z, u.y));
cols.Add(c);
cols.Add(c);
cols.Add(c);
cols.Add(c);
}
/// <summary>
/// Sliced sprite fill function is more complicated as it generates 9 quads instead of 1.
/// </summary>
void SlicedFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
Vector4 br = border * pixelSize;
if (br.x == 0f && br.y == 0f && br.z == 0f && br.w == 0f)
{
SimpleFill(verts, uvs, cols);
return;
}
Color32 c = drawingColor;
Vector4 v = drawingDimensions;
mTempPos[0].x = v.x;
mTempPos[0].y = v.y;
mTempPos[3].x = v.z;
mTempPos[3].y = v.w;
if (mFlip == Flip.Horizontally || mFlip == Flip.Both)
{
mTempPos[1].x = mTempPos[0].x + br.z;
mTempPos[2].x = mTempPos[3].x - br.x;
mTempUVs[3].x = mOuterUV.xMin;
mTempUVs[2].x = mInnerUV.xMin;
mTempUVs[1].x = mInnerUV.xMax;
mTempUVs[0].x = mOuterUV.xMax;
}
else
{
mTempPos[1].x = mTempPos[0].x + br.x;
mTempPos[2].x = mTempPos[3].x - br.z;
mTempUVs[0].x = mOuterUV.xMin;
mTempUVs[1].x = mInnerUV.xMin;
mTempUVs[2].x = mInnerUV.xMax;
mTempUVs[3].x = mOuterUV.xMax;
}
if (mFlip == Flip.Vertically || mFlip == Flip.Both)
{
mTempPos[1].y = mTempPos[0].y + br.w;
mTempPos[2].y = mTempPos[3].y - br.y;
mTempUVs[3].y = mOuterUV.yMin;
mTempUVs[2].y = mInnerUV.yMin;
mTempUVs[1].y = mInnerUV.yMax;
mTempUVs[0].y = mOuterUV.yMax;
}
else
{
mTempPos[1].y = mTempPos[0].y + br.y;
mTempPos[2].y = mTempPos[3].y - br.w;
mTempUVs[0].y = mOuterUV.yMin;
mTempUVs[1].y = mInnerUV.yMin;
mTempUVs[2].y = mInnerUV.yMax;
mTempUVs[3].y = mOuterUV.yMax;
}
for (int x = 0; x < 3; ++x)
{
int x2 = x + 1;
for (int y = 0; y < 3; ++y)
{
if (centerType == AdvancedType.Invisible && x == 1 && y == 1) continue;
int y2 = y + 1;
verts.Add(new Vector3(mTempPos[x].x, mTempPos[y].y));
verts.Add(new Vector3(mTempPos[x].x, mTempPos[y2].y));
verts.Add(new Vector3(mTempPos[x2].x, mTempPos[y2].y));
verts.Add(new Vector3(mTempPos[x2].x, mTempPos[y].y));
uvs.Add(new Vector2(mTempUVs[x].x, mTempUVs[y].y));
uvs.Add(new Vector2(mTempUVs[x].x, mTempUVs[y2].y));
uvs.Add(new Vector2(mTempUVs[x2].x, mTempUVs[y2].y));
uvs.Add(new Vector2(mTempUVs[x2].x, mTempUVs[y].y));
cols.Add(c);
cols.Add(c);
cols.Add(c);
cols.Add(c);
}
}
}
/// <summary>
/// Tiled sprite fill function.
/// </summary>
void TiledFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
Texture tex = mainTexture;
if (tex == null) return;
Vector2 size = new Vector2(mInnerUV.width * tex.width, mInnerUV.height * tex.height);
size *= pixelSize;
if (tex == null || size.x < 2f || size.y < 2f) return;
Color32 c = drawingColor;
Vector4 v = drawingDimensions;
Vector4 u;
if (mFlip == Flip.Horizontally || mFlip == Flip.Both)
{
u.x = mInnerUV.xMax;
u.z = mInnerUV.xMin;
}
else
{
u.x = mInnerUV.xMin;
u.z = mInnerUV.xMax;
}
if (mFlip == Flip.Vertically || mFlip == Flip.Both)
{
u.y = mInnerUV.yMax;
u.w = mInnerUV.yMin;
}
else
{
u.y = mInnerUV.yMin;
u.w = mInnerUV.yMax;
}
float x0 = v.x;
float y0 = v.y;
float u0 = u.x;
float v0 = u.y;
while (y0 < v.w)
{
x0 = v.x;
float y1 = y0 + size.y;
float v1 = u.w;
if (y1 > v.w)
{
v1 = Mathf.Lerp(u.y, u.w, (v.w - y0) / size.y);
y1 = v.w;
}
while (x0 < v.z)
{
float x1 = x0 + size.x;
float u1 = u.z;
if (x1 > v.z)
{
u1 = Mathf.Lerp(u.x, u.z, (v.z - x0) / size.x);
x1 = v.z;
}
verts.Add(new Vector3(x0, y0));
verts.Add(new Vector3(x0, y1));
verts.Add(new Vector3(x1, y1));
verts.Add(new Vector3(x1, y0));
uvs.Add(new Vector2(u0, v0));
uvs.Add(new Vector2(u0, v1));
uvs.Add(new Vector2(u1, v1));
uvs.Add(new Vector2(u1, v0));
cols.Add(c);
cols.Add(c);
cols.Add(c);
cols.Add(c);
x0 += size.x;
}
y0 += size.y;
}
}
/// <summary>
/// Filled sprite fill function.
/// </summary>
void FilledFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
if (mFillAmount < 0.001f) return;
Vector4 v = drawingDimensions;
Vector4 u = drawingUVs;
Color32 c = drawingColor;
// Horizontal and vertical filled sprites are simple -- just end the sprite prematurely
if (mFillDirection == FillDirection.Horizontal || mFillDirection == FillDirection.Vertical)
{
if (mFillDirection == FillDirection.Horizontal)
{
float fill = (u.z - u.x) * mFillAmount;
if (mInvert)
{
v.x = v.z - (v.z - v.x) * mFillAmount;
u.x = u.z - fill;
}
else
{
v.z = v.x + (v.z - v.x) * mFillAmount;
u.z = u.x + fill;
}
}
else if (mFillDirection == FillDirection.Vertical)
{
float fill = (u.w - u.y) * mFillAmount;
if (mInvert)
{
v.y = v.w - (v.w - v.y) * mFillAmount;
u.y = u.w - fill;
}
else
{
v.w = v.y + (v.w - v.y) * mFillAmount;
u.w = u.y + fill;
}
}
}
mTempPos[0] = new Vector2(v.x, v.y);
mTempPos[1] = new Vector2(v.x, v.w);
mTempPos[2] = new Vector2(v.z, v.w);
mTempPos[3] = new Vector2(v.z, v.y);
mTempUVs[0] = new Vector2(u.x, u.y);
mTempUVs[1] = new Vector2(u.x, u.w);
mTempUVs[2] = new Vector2(u.z, u.w);
mTempUVs[3] = new Vector2(u.z, u.y);
if (mFillAmount < 1f)
{
if (mFillDirection == FillDirection.Radial90)
{
if (RadialCut(mTempPos, mTempUVs, mFillAmount, mInvert, 0))
{
for (int i = 0; i < 4; ++i)
{
verts.Add(mTempPos[i]);
uvs.Add(mTempUVs[i]);
cols.Add(c);
}
}
return;
}
if (mFillDirection == FillDirection.Radial180)
{
for (int side = 0; side < 2; ++side)
{
float fx0, fx1, fy0, fy1;
fy0 = 0f;
fy1 = 1f;
if (side == 0) { fx0 = 0f; fx1 = 0.5f; }
else { fx0 = 0.5f; fx1 = 1f; }
mTempPos[0].x = Mathf.Lerp(v.x, v.z, fx0);
mTempPos[1].x = mTempPos[0].x;
mTempPos[2].x = Mathf.Lerp(v.x, v.z, fx1);
mTempPos[3].x = mTempPos[2].x;
mTempPos[0].y = Mathf.Lerp(v.y, v.w, fy0);
mTempPos[1].y = Mathf.Lerp(v.y, v.w, fy1);
mTempPos[2].y = mTempPos[1].y;
mTempPos[3].y = mTempPos[0].y;
mTempUVs[0].x = Mathf.Lerp(u.x, u.z, fx0);
mTempUVs[1].x = mTempUVs[0].x;
mTempUVs[2].x = Mathf.Lerp(u.x, u.z, fx1);
mTempUVs[3].x = mTempUVs[2].x;
mTempUVs[0].y = Mathf.Lerp(u.y, u.w, fy0);
mTempUVs[1].y = Mathf.Lerp(u.y, u.w, fy1);
mTempUVs[2].y = mTempUVs[1].y;
mTempUVs[3].y = mTempUVs[0].y;
float val = !mInvert ? fillAmount * 2f - side : mFillAmount * 2f - (1 - side);
if (RadialCut(mTempPos, mTempUVs, Mathf.Clamp01(val), !mInvert, NGUIMath.RepeatIndex(side + 3, 4)))
{
for (int i = 0; i < 4; ++i)
{
verts.Add(mTempPos[i]);
uvs.Add(mTempUVs[i]);
cols.Add(c);
}
}
}
return;
}
if (mFillDirection == FillDirection.Radial360)
{
for (int corner = 0; corner < 4; ++corner)
{
float fx0, fx1, fy0, fy1;
if (corner < 2) { fx0 = 0f; fx1 = 0.5f; }
else { fx0 = 0.5f; fx1 = 1f; }
if (corner == 0 || corner == 3) { fy0 = 0f; fy1 = 0.5f; }
else { fy0 = 0.5f; fy1 = 1f; }
mTempPos[0].x = Mathf.Lerp(v.x, v.z, fx0);
mTempPos[1].x = mTempPos[0].x;
mTempPos[2].x = Mathf.Lerp(v.x, v.z, fx1);
mTempPos[3].x = mTempPos[2].x;
mTempPos[0].y = Mathf.Lerp(v.y, v.w, fy0);
mTempPos[1].y = Mathf.Lerp(v.y, v.w, fy1);
mTempPos[2].y = mTempPos[1].y;
mTempPos[3].y = mTempPos[0].y;
mTempUVs[0].x = Mathf.Lerp(u.x, u.z, fx0);
mTempUVs[1].x = mTempUVs[0].x;
mTempUVs[2].x = Mathf.Lerp(u.x, u.z, fx1);
mTempUVs[3].x = mTempUVs[2].x;
mTempUVs[0].y = Mathf.Lerp(u.y, u.w, fy0);
mTempUVs[1].y = Mathf.Lerp(u.y, u.w, fy1);
mTempUVs[2].y = mTempUVs[1].y;
mTempUVs[3].y = mTempUVs[0].y;
float val = mInvert ?
mFillAmount * 4f - NGUIMath.RepeatIndex(corner + 2, 4) :
mFillAmount * 4f - (3 - NGUIMath.RepeatIndex(corner + 2, 4));
if (RadialCut(mTempPos, mTempUVs, Mathf.Clamp01(val), mInvert, NGUIMath.RepeatIndex(corner + 2, 4)))
{
for (int i = 0; i < 4; ++i)
{
verts.Add(mTempPos[i]);
uvs.Add(mTempUVs[i]);
cols.Add(c);
}
}
}
return;
}
}
// Fill the buffer with the quad for the sprite
for (int i = 0; i < 4; ++i)
{
verts.Add(mTempPos[i]);
uvs.Add(mTempUVs[i]);
cols.Add(c);
}
}
/// <summary>
/// Advanced sprite fill function. Contributed by Nicki Hansen.
/// </summary>
void AdvancedFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
Texture tex = mainTexture;
if (tex == null) return;
Vector4 br = border * pixelSize;
if (br.x == 0f && br.y == 0f && br.z == 0f && br.w == 0f)
{
SimpleFill(verts, uvs, cols);
return;
}
Color32 c = drawingColor;
Vector4 v = drawingDimensions;
Vector2 tileSize = new Vector2(mInnerUV.width * tex.width, mInnerUV.height * tex.height);
tileSize *= pixelSize;
if (tileSize.x < 1f) tileSize.x = 1f;
if (tileSize.y < 1f) tileSize.y = 1f;
mTempPos[0].x = v.x;
mTempPos[0].y = v.y;
mTempPos[3].x = v.z;
mTempPos[3].y = v.w;
if (mFlip == Flip.Horizontally || mFlip == Flip.Both)
{
mTempPos[1].x = mTempPos[0].x + br.z;
mTempPos[2].x = mTempPos[3].x - br.x;
mTempUVs[3].x = mOuterUV.xMin;
mTempUVs[2].x = mInnerUV.xMin;
mTempUVs[1].x = mInnerUV.xMax;
mTempUVs[0].x = mOuterUV.xMax;
}
else
{
mTempPos[1].x = mTempPos[0].x + br.x;
mTempPos[2].x = mTempPos[3].x - br.z;
mTempUVs[0].x = mOuterUV.xMin;
mTempUVs[1].x = mInnerUV.xMin;
mTempUVs[2].x = mInnerUV.xMax;
mTempUVs[3].x = mOuterUV.xMax;
}
if (mFlip == Flip.Vertically || mFlip == Flip.Both)
{
mTempPos[1].y = mTempPos[0].y + br.w;
mTempPos[2].y = mTempPos[3].y - br.y;
mTempUVs[3].y = mOuterUV.yMin;
mTempUVs[2].y = mInnerUV.yMin;
mTempUVs[1].y = mInnerUV.yMax;
mTempUVs[0].y = mOuterUV.yMax;
}
else
{
mTempPos[1].y = mTempPos[0].y + br.y;
mTempPos[2].y = mTempPos[3].y - br.w;
mTempUVs[0].y = mOuterUV.yMin;
mTempUVs[1].y = mInnerUV.yMin;
mTempUVs[2].y = mInnerUV.yMax;
mTempUVs[3].y = mOuterUV.yMax;
}
for (int x = 0; x < 3; ++x)
{
int x2 = x + 1;
for (int y = 0; y < 3; ++y)
{
if (centerType == AdvancedType.Invisible && x == 1 && y == 1) continue;
int y2 = y + 1;
if (x == 1 && y == 1) // Center
{
if (centerType == AdvancedType.Tiled)
{
float startPositionX = mTempPos[x].x;
float endPositionX = mTempPos[x2].x;
float startPositionY = mTempPos[y].y;
float endPositionY = mTempPos[y2].y;
float textureStartX = mTempUVs[x].x;
float textureStartY = mTempUVs[y].y;
float tileStartY = startPositionY;
while (tileStartY < endPositionY)
{
float tileStartX = startPositionX;
float textureEndY = mTempUVs[y2].y;
float tileEndY = tileStartY + tileSize.y;
if (tileEndY > endPositionY)
{
textureEndY = Mathf.Lerp(textureStartY, textureEndY, (endPositionY - tileStartY) / tileSize.y);
tileEndY = endPositionY;
}
while (tileStartX < endPositionX)
{
float tileEndX = tileStartX + tileSize.x;
float textureEndX = mTempUVs[x2].x;
if (tileEndX > endPositionX)
{
textureEndX = Mathf.Lerp(textureStartX, textureEndX, (endPositionX - tileStartX) / tileSize.x);
tileEndX = endPositionX;
}
Fill(verts, uvs, cols,
tileStartX, tileEndX,
tileStartY, tileEndY,
textureStartX, textureEndX,
textureStartY, textureEndY, c);
tileStartX += tileSize.x;
}
tileStartY += tileSize.y;
}
}
else if (centerType == AdvancedType.Sliced)
{
Fill(verts, uvs, cols,
mTempPos[x].x, mTempPos[x2].x,
mTempPos[y].y, mTempPos[y2].y,
mTempUVs[x].x, mTempUVs[x2].x,
mTempUVs[y].y, mTempUVs[y2].y, c);
}
}
else if (x == 1) // Top or bottom
{
if ((y == 0 && bottomType == AdvancedType.Tiled) || (y == 2 && topType == AdvancedType.Tiled))
{
float startPositionX = mTempPos[x].x;
float endPositionX = mTempPos[x2].x;
float startPositionY = mTempPos[y].y;
float endPositionY = mTempPos[y2].y;
float textureStartX = mTempUVs[x].x;
float textureStartY = mTempUVs[y].y;
float textureEndY = mTempUVs[y2].y;
float tileStartX = startPositionX;
while (tileStartX < endPositionX)
{
float tileEndX = tileStartX + tileSize.x;
float textureEndX = mTempUVs[x2].x;
if (tileEndX > endPositionX)
{
textureEndX = Mathf.Lerp(textureStartX, textureEndX, (endPositionX - tileStartX) / tileSize.x);
tileEndX = endPositionX;
}
Fill(verts, uvs, cols,
tileStartX, tileEndX,
startPositionY, endPositionY,
textureStartX, textureEndX,
textureStartY, textureEndY, c);
tileStartX += tileSize.x;
}
}
else if ((y == 0 && bottomType == AdvancedType.Sliced) || (y == 2 && topType == AdvancedType.Sliced))
{
Fill(verts, uvs, cols,
mTempPos[x].x, mTempPos[x2].x,
mTempPos[y].y, mTempPos[y2].y,
mTempUVs[x].x, mTempUVs[x2].x,
mTempUVs[y].y, mTempUVs[y2].y, c);
}
}
else if (y == 1) // Left or right
{
if ((x == 0 && leftType == AdvancedType.Tiled) || (x == 2 && rightType == AdvancedType.Tiled))
{
float startPositionX = mTempPos[x].x;
float endPositionX = mTempPos[x2].x;
float startPositionY = mTempPos[y].y;
float endPositionY = mTempPos[y2].y;
float textureStartX = mTempUVs[x].x;
float textureEndX = mTempUVs[x2].x;
float textureStartY = mTempUVs[y].y;
float tileStartY = startPositionY;
while (tileStartY < endPositionY)
{
float textureEndY = mTempUVs[y2].y;
float tileEndY = tileStartY + tileSize.y;
if (tileEndY > endPositionY)
{
textureEndY = Mathf.Lerp(textureStartY, textureEndY, (endPositionY - tileStartY) / tileSize.y);
tileEndY = endPositionY;
}
Fill(verts, uvs, cols,
startPositionX, endPositionX,
tileStartY, tileEndY,
textureStartX, textureEndX,
textureStartY, textureEndY, c);
tileStartY += tileSize.y;
}
}
else if ((x == 0 && leftType == AdvancedType.Sliced) || (x == 2 && rightType == AdvancedType.Sliced))
{
Fill(verts, uvs, cols,
mTempPos[x].x, mTempPos[x2].x,
mTempPos[y].y, mTempPos[y2].y,
mTempUVs[x].x, mTempUVs[x2].x,
mTempUVs[y].y, mTempUVs[y2].y, c);
}
}
else // Corner
{
if ((y == 0 && bottomType == AdvancedType.Sliced) || (y == 2 && topType == AdvancedType.Sliced) ||
(x == 0 && leftType == AdvancedType.Sliced) || (x == 2 && rightType == AdvancedType.Sliced))
{
Fill(verts, uvs, cols,
mTempPos[x].x, mTempPos[x2].x,
mTempPos[y].y, mTempPos[y2].y,
mTempUVs[x].x, mTempUVs[x2].x,
mTempUVs[y].y, mTempUVs[y2].y, c);
}
}
}
}
}
/// <summary>
/// Adjust the specified quad, making it be radially filled instead.
/// </summary>
static bool RadialCut (Vector2[] xy, Vector2[] uv, float fill, bool invert, int corner)
{
// Nothing to fill
if (fill < 0.001f) return false;
// Even corners invert the fill direction
if ((corner & 1) == 1) invert = !invert;
// Nothing to adjust
if (!invert && fill > 0.999f) return true;
// Convert 0-1 value into 0 to 90 degrees angle in radians
float angle = Mathf.Clamp01(fill);
if (invert) angle = 1f - angle;
angle *= 90f * Mathf.Deg2Rad;
// Calculate the effective X and Y factors
float cos = Mathf.Cos(angle);
float sin = Mathf.Sin(angle);
RadialCut(xy, cos, sin, invert, corner);
RadialCut(uv, cos, sin, invert, corner);
return true;
}
/// <summary>
/// Adjust the specified quad, making it be radially filled instead.
/// </summary>
static void RadialCut (Vector2[] xy, float cos, float sin, bool invert, int corner)
{
int i0 = corner;
int i1 = NGUIMath.RepeatIndex(corner + 1, 4);
int i2 = NGUIMath.RepeatIndex(corner + 2, 4);
int i3 = NGUIMath.RepeatIndex(corner + 3, 4);
if ((corner & 1) == 1)
{
if (sin > cos)
{
cos /= sin;
sin = 1f;
if (invert)
{
xy[i1].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos);
xy[i2].x = xy[i1].x;
}
}
else if (cos > sin)
{
sin /= cos;
cos = 1f;
if (!invert)
{
xy[i2].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin);
xy[i3].y = xy[i2].y;
}
}
else
{
cos = 1f;
sin = 1f;
}
if (!invert) xy[i3].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos);
else xy[i1].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin);
}
else
{
if (cos > sin)
{
sin /= cos;
cos = 1f;
if (!invert)
{
xy[i1].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin);
xy[i2].y = xy[i1].y;
}
}
else if (sin > cos)
{
cos /= sin;
sin = 1f;
if (invert)
{
xy[i2].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos);
xy[i3].x = xy[i2].x;
}
}
else
{
cos = 1f;
sin = 1f;
}
if (invert) xy[i3].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin);
else xy[i1].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos);
}
}
/// <summary>
/// Helper function that adds the specified values to the buffers.
/// </summary>
static void Fill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols,
float v0x, float v1x, float v0y, float v1y, float u0x, float u1x, float u0y, float u1y, Color col)
{
verts.Add(new Vector3(v0x, v0y));
verts.Add(new Vector3(v0x, v1y));
verts.Add(new Vector3(v1x, v1y));
verts.Add(new Vector3(v1x, v0y));
uvs.Add(new Vector2(u0x, u0y));
uvs.Add(new Vector2(u0x, u1y));
uvs.Add(new Vector2(u1x, u1y));
uvs.Add(new Vector2(u1x, u0y));
cols.Add(col);
cols.Add(col);
cols.Add(col);
cols.Add(col);
}
#endregion // Fill functions
}
| |
// 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.Windows;
using System.Windows.Media;
using System.Windows.Ink;
using System.Windows.Input;
using System.Diagnostics;
namespace MS.Internal.Ink
{
/// <summary>
/// StrokeNodeOperations implementation for elliptical nodes
/// </summary>
internal class EllipticalNodeOperations : StrokeNodeOperations
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="nodeShape"></param>
internal EllipticalNodeOperations(StylusShape nodeShape)
: base(nodeShape)
{
System.Diagnostics.Debug.Assert((nodeShape != null) && nodeShape.IsEllipse);
_radii = new Size(nodeShape.Width * 0.5, nodeShape.Height * 0.5);
// All operations with ellipses become simple(r) if transfrom ellipses into circles.
// Use the max of the radii for the radius of the circle
_radius = Math.Max(_radii.Width, _radii.Height);
// Compute ellipse-to-circle and circle-to-elliipse transforms. The former is used
// in hit-testing operations while the latter is used when computing vertices of
// a quadrangle connecting two ellipses
_transform = nodeShape.Transform;
_nodeShapeToCircle = _transform;
Debug.Assert(_nodeShapeToCircle.HasInverse, "About to invert a non-invertible transform");
_nodeShapeToCircle.Invert();
if (DoubleUtil.AreClose(_radii.Width, _radii.Height))
{
_circleToNodeShape = _transform;
}
else
{
// Reverse the rotation
if (false == DoubleUtil.IsZero(nodeShape.Rotation))
{
_nodeShapeToCircle.Rotate(-nodeShape.Rotation);
Debug.Assert(_nodeShapeToCircle.HasInverse, "Just rotated an invertible transform and produced a non-invertible one");
}
// Scale to enlarge
double sx, sy;
if (_radii.Width > _radii.Height)
{
sx = 1;
sy = _radii.Width / _radii.Height;
}
else
{
sx = _radii.Height / _radii.Width;
sy = 1;
}
_nodeShapeToCircle.Scale(sx, sy);
Debug.Assert(_nodeShapeToCircle.HasInverse, "Just scaled an invertible transform and produced a non-invertible one");
_circleToNodeShape = _nodeShapeToCircle;
_circleToNodeShape.Invert();
}
}
/// <summary>
/// This is probably not the best (design-wise) but the cheapest way to tell
/// EllipticalNodeOperations from all other implementations of node operations.
/// </summary>
internal override bool IsNodeShapeEllipse { get { return true; } }
/// <summary>
/// Finds connecting points for a pair of stroke nodes
/// </summary>
/// <param name="beginNode">a node to connect</param>
/// <param name="endNode">another node, next to beginNode</param>
/// <returns>connecting quadrangle</returns>
internal override Quad GetConnectingQuad(StrokeNodeData beginNode, StrokeNodeData endNode)
{
if (beginNode.IsEmpty || endNode.IsEmpty || DoubleUtil.AreClose(beginNode.Position, endNode.Position))
{
return Quad.Empty;
}
// Get the vector between the node positions
Vector spine = endNode.Position - beginNode.Position;
if (_nodeShapeToCircle.IsIdentity == false)
{
spine = _nodeShapeToCircle.Transform(spine);
}
double beginRadius = _radius * beginNode.PressureFactor;
double endRadius = _radius * endNode.PressureFactor;
// Get the vector and the distance between the node positions
double distanceSquared = spine.LengthSquared;
double delta = endRadius - beginRadius;
double deltaSquared = DoubleUtil.IsZero(delta) ? 0 : (delta * delta);
if (DoubleUtil.LessThanOrClose(distanceSquared, deltaSquared))
{
// One circle is contained within the other
return Quad.Empty;
}
// Thus, at this point, distance > 0, which avoids the DivideByZero error
// Also, here, distanceSquared > deltaSquared
// Thus, 0 <= rSin < 1
// Get the components of the radius vectors
double distance = Math.Sqrt(distanceSquared);
spine /= distance;
Vector rad = spine;
// Turn left
double temp = rad.Y;
rad.Y = -rad.X;
rad.X = temp;
Vector vectorToLeftTangent, vectorToRightTangent;
double rSinSquared = deltaSquared / distanceSquared;
if (DoubleUtil.IsZero(rSinSquared))
{
vectorToLeftTangent = rad;
vectorToRightTangent = -rad;
}
else
{
rad *= Math.Sqrt(1 - rSinSquared);
spine *= Math.Sqrt(rSinSquared);
if (beginNode.PressureFactor < endNode.PressureFactor)
{
spine = -spine;
}
vectorToLeftTangent = spine + rad;
vectorToRightTangent = spine - rad;
}
// Get the common tangent points
if (_circleToNodeShape.IsIdentity == false)
{
vectorToLeftTangent = _circleToNodeShape.Transform(vectorToLeftTangent);
vectorToRightTangent = _circleToNodeShape.Transform(vectorToRightTangent);
}
return new Quad(beginNode.Position + (vectorToLeftTangent * beginRadius),
endNode.Position + (vectorToLeftTangent * endRadius),
endNode.Position + (vectorToRightTangent * endRadius),
beginNode.Position + (vectorToRightTangent * beginRadius));
}
/// <summary>
///
/// </summary>
/// <param name="node"></param>
/// <param name="quad"></param>
/// <returns></returns>
internal override IEnumerable<ContourSegment> GetContourSegments(StrokeNodeData node, Quad quad)
{
System.Diagnostics.Debug.Assert(node.IsEmpty == false);
if (quad.IsEmpty)
{
Point point = node.Position;
point.X += _radius;
yield return new ContourSegment(point, point, node.Position);
}
else if (_nodeShapeToCircle.IsIdentity)
{
yield return new ContourSegment(quad.A, quad.B);
yield return new ContourSegment(quad.B, quad.C, node.Position);
yield return new ContourSegment(quad.C, quad.D);
yield return new ContourSegment(quad.D, quad.A);
}
}
/// <summary>
/// ISSUE-2004/06/15- temporary workaround to avoid hit-testing ellipses with ellipses
/// </summary>
/// <param name="beginNode"></param>
/// <param name="endNode"></param>
/// <returns></returns>
internal override IEnumerable<ContourSegment> GetNonBezierContourSegments(StrokeNodeData beginNode, StrokeNodeData endNode)
{
Quad quad = beginNode.IsEmpty ? Quad.Empty : base.GetConnectingQuad(beginNode, endNode);
return base.GetContourSegments(endNode, quad);
}
/// <summary>
/// Hit-tests a stroke segment defined by two nodes against a linear segment.
/// </summary>
/// <param name="beginNode">Begin node of the stroke segment to hit-test. Can be empty (none)</param>
/// <param name="endNode">End node of the stroke segment</param>
/// <param name="quad">Pre-computed quadrangle connecting the two nodes.
/// Can be empty if the begion node is empty or when one node is entirely inside the other</param>
/// <param name="hitBeginPoint">an end point of the hitting linear segment</param>
/// <param name="hitEndPoint">an end point of the hitting linear segment</param>
/// <returns>true if the hitting segment intersect the contour comprised of the two stroke nodes</returns>
internal override bool HitTest(
StrokeNodeData beginNode, StrokeNodeData endNode, Quad quad, Point hitBeginPoint, Point hitEndPoint)
{
StrokeNodeData bigNode, smallNode;
if (beginNode.IsEmpty || (quad.IsEmpty && (endNode.PressureFactor > beginNode.PressureFactor)))
{
// Need to test one node only
bigNode = endNode;
smallNode = StrokeNodeData.Empty;
}
else
{
// In this case the size doesn't matter.
bigNode = beginNode;
smallNode = endNode;
}
// Compute the positions of the involved points relative to bigNode.
Vector hitBegin = hitBeginPoint - bigNode.Position;
Vector hitEnd = hitEndPoint - bigNode.Position;
// If the node shape is an ellipse, transform the scene to turn the shape to a circle
if (_nodeShapeToCircle.IsIdentity == false)
{
hitBegin = _nodeShapeToCircle.Transform(hitBegin);
hitEnd = _nodeShapeToCircle.Transform(hitEnd);
}
bool isHit = false;
// Hit-test the big node
double bigRadius = _radius * bigNode.PressureFactor;
Vector nearest = GetNearest(hitBegin, hitEnd);
if (nearest.LengthSquared <= (bigRadius * bigRadius))
{
isHit = true;
}
else if (quad.IsEmpty == false)
{
// Hit-test the other node
Vector spineVector = smallNode.Position - bigNode.Position;
if (_nodeShapeToCircle.IsIdentity == false)
{
spineVector = _nodeShapeToCircle.Transform(spineVector);
}
double smallRadius = _radius * smallNode.PressureFactor;
nearest = GetNearest(hitBegin - spineVector, hitEnd - spineVector);
if ((nearest.LengthSquared <= (smallRadius * smallRadius)) || HitTestQuadSegment(quad, hitBeginPoint, hitEndPoint))
{
isHit = true;
}
}
return isHit;
}
/// <summary>
/// Hit-tests a stroke segment defined by two nodes against another stroke segment.
/// </summary>
/// <param name="beginNode">Begin node of the stroke segment to hit-test. Can be empty (none)</param>
/// <param name="endNode">End node of the stroke segment</param>
/// <param name="quad">Pre-computed quadrangle connecting the two nodes.
/// Can be empty if the begion node is empty or when one node is entirely inside the other</param>
/// <param name="hitContour">a collection of basic segments outlining the hitting contour</param>
/// <returns>true if the contours intersect or overlap</returns>
internal override bool HitTest(
StrokeNodeData beginNode, StrokeNodeData endNode, Quad quad, IEnumerable<ContourSegment> hitContour)
{
StrokeNodeData bigNode, smallNode;
double bigRadiusSquared, smallRadiusSquared = 0;
Vector spineVector;
if (beginNode.IsEmpty || (quad.IsEmpty && (endNode.PressureFactor > beginNode.PressureFactor)))
{
// Need to test one node only
bigNode = endNode;
smallNode = StrokeNodeData.Empty;
spineVector = new Vector();
}
else
{
// In this case the size doesn't matter.
bigNode = beginNode;
smallNode = endNode;
smallRadiusSquared = _radius * smallNode.PressureFactor;
smallRadiusSquared *= smallRadiusSquared;
// Find position of smallNode relative to the bigNode.
spineVector = smallNode.Position - bigNode.Position;
// If the node shape is an ellipse, transform the scene to turn the shape to a circle
if (_nodeShapeToCircle.IsIdentity == false)
{
spineVector = _nodeShapeToCircle.Transform(spineVector);
}
}
bigRadiusSquared = _radius * bigNode.PressureFactor;
bigRadiusSquared *= bigRadiusSquared;
bool isHit = false;
// When hit-testing a contour against another contour, like in this case,
// the default implementation checks whether any edge (segment) of the hitting
// contour intersects with the contour of the ink segment. But this doesn't cover
// the case when the ink segment is entirely inside of the hitting segment.
// The bool variable isInside is used here to track that case. It answers the question
// 'Is ink contour inside if the hitting contour?'. It's initialized to 'true"
// and then verified for each edge of the hitting contour until there's a hit or
// until it's false.
bool isInside = true;
foreach (ContourSegment hitSegment in hitContour)
{
if (hitSegment.IsArc)
{
// ISSUE-2004/06/15-vsmirnov - ellipse vs arc hit-testing is not implemented
// and currently disabled in ErasingStroke
}
else
{
// Find position of the hitting segment relative to bigNode transformed to circle.
Vector hitBegin = hitSegment.Begin - bigNode.Position;
Vector hitEnd = hitBegin + hitSegment.Vector;
if (_nodeShapeToCircle.IsIdentity == false)
{
hitBegin = _nodeShapeToCircle.Transform(hitBegin);
hitEnd = _nodeShapeToCircle.Transform(hitEnd);
}
// Hit-test the big node
Vector nearest = GetNearest(hitBegin, hitEnd);
if (nearest.LengthSquared <= bigRadiusSquared)
{
isHit = true;
break;
}
// Hit-test the other node
if (quad.IsEmpty == false)
{
nearest = GetNearest(hitBegin - spineVector, hitEnd - spineVector);
if ((nearest.LengthSquared <= smallRadiusSquared) ||
HitTestQuadSegment(quad, hitSegment.Begin, hitSegment.End))
{
isHit = true;
break;
}
}
// While there's still a chance to find the both nodes inside the hitting contour,
// continue checking on position of the endNode relative to the edges of the hitting contour.
if (isInside &&
(WhereIsVectorAboutVector(endNode.Position - hitSegment.Begin, hitSegment.Vector) != HitResult.Right))
{
isInside = false;
}
}
}
return (isHit || isInside);
}
/// <summary>
/// Cut-test ink segment defined by two nodes and a connecting quad against a linear segment
/// </summary>
/// <param name="beginNode">Begin node of the ink segment</param>
/// <param name="endNode">End node of the ink segment</param>
/// <param name="quad">Pre-computed quadrangle connecting the two ink nodes</param>
/// <param name="hitBeginPoint">egin point of the hitting segment</param>
/// <param name="hitEndPoint">End point of the hitting segment</param>
/// <returns>Exact location to cut at represented by StrokeFIndices</returns>
internal override StrokeFIndices CutTest(
StrokeNodeData beginNode, StrokeNodeData endNode, Quad quad, Point hitBeginPoint, Point hitEndPoint)
{
// Compute the positions of the involved points relative to the endNode.
Vector spineVector = beginNode.IsEmpty ? new Vector(0, 0) : (beginNode.Position - endNode.Position);
Vector hitBegin = hitBeginPoint - endNode.Position;
Vector hitEnd = hitEndPoint - endNode.Position;
// If the node shape is an ellipse, transform the scene to turn the shape to a circle
if (_nodeShapeToCircle.IsIdentity == false)
{
spineVector = _nodeShapeToCircle.Transform(spineVector);
hitBegin = _nodeShapeToCircle.Transform(hitBegin);
hitEnd = _nodeShapeToCircle.Transform(hitEnd);
}
StrokeFIndices result = StrokeFIndices.Empty;
// Hit-test the end node
double beginRadius = 0, endRadius = _radius * endNode.PressureFactor;
Vector nearest = GetNearest(hitBegin, hitEnd);
if (nearest.LengthSquared <= (endRadius * endRadius))
{
result.EndFIndex = StrokeFIndices.AfterLast;
result.BeginFIndex = beginNode.IsEmpty ? StrokeFIndices.BeforeFirst : 1;
}
if (beginNode.IsEmpty == false)
{
// Hit-test the first node
beginRadius = _radius * beginNode.PressureFactor;
nearest = GetNearest(hitBegin - spineVector, hitEnd - spineVector);
if (nearest.LengthSquared <= (beginRadius * beginRadius))
{
result.BeginFIndex = StrokeFIndices.BeforeFirst;
if (!DoubleUtil.AreClose(result.EndFIndex, StrokeFIndices.AfterLast))
{
result.EndFIndex = 0;
}
}
}
// If both nodes are hit or nothing is hit at all, return.
if (result.IsFull || quad.IsEmpty
|| (result.IsEmpty && (HitTestQuadSegment(quad, hitBeginPoint, hitEndPoint) == false)))
{
return result;
}
// Find out whether the {begin, end} segment intersects with the contour
// of the stroke segment {_lastNode, _thisNode}, and find the lower index
// of the fragment to cut out.
if (!DoubleUtil.AreClose(result.BeginFIndex, StrokeFIndices.BeforeFirst))
{
result.BeginFIndex = ClipTest(-spineVector, beginRadius, endRadius, hitBegin - spineVector, hitEnd - spineVector);
}
if (!DoubleUtil.AreClose(result.EndFIndex, StrokeFIndices.AfterLast))
{
result.EndFIndex = 1 - ClipTest(spineVector, endRadius, beginRadius, hitBegin, hitEnd);
}
if (IsInvalidCutTestResult(result))
{
return StrokeFIndices.Empty;
}
return result;
}
/// <summary>
/// CutTest an inking StrokeNode segment (two nodes and a connecting quadrangle) against a hitting contour
/// (represented by an enumerator of Contoursegments).
/// </summary>
/// <param name="beginNode">The begin StrokeNodeData</param>
/// <param name="endNode">The end StrokeNodeData</param>
/// <param name="quad">Connecing quadrangle between the begin and end inking node</param>
/// <param name="hitContour">The hitting ContourSegments</param>
/// <returns>StrokeFIndices representing the location for cutting</returns>
internal override StrokeFIndices CutTest(
StrokeNodeData beginNode, StrokeNodeData endNode, Quad quad, IEnumerable<ContourSegment> hitContour)
{
// Compute the positions of the beginNode relative to the endNode.
Vector spineVector = beginNode.IsEmpty ? new Vector(0, 0) : (beginNode.Position - endNode.Position);
// If the node shape is an ellipse, transform the scene to turn the shape to a circle
if (_nodeShapeToCircle.IsIdentity == false)
{
spineVector = _nodeShapeToCircle.Transform(spineVector);
}
double beginRadius = 0, endRadius;
double beginRadiusSquared = 0, endRadiusSquared;
endRadius = _radius * endNode.PressureFactor;
endRadiusSquared = endRadius * endRadius;
if (beginNode.IsEmpty == false)
{
beginRadius = _radius * beginNode.PressureFactor;
beginRadiusSquared = beginRadius * beginRadius;
}
bool isInside = true;
StrokeFIndices result = StrokeFIndices.Empty;
foreach (ContourSegment hitSegment in hitContour)
{
if (hitSegment.IsArc)
{
// ISSUE-2004/06/15-vsmirnov - ellipse vs arc hit-testing is not implemented
// and currently disabled in ErasingStroke
}
else
{
Vector hitBegin = hitSegment.Begin - endNode.Position;
Vector hitEnd = hitBegin + hitSegment.Vector;
// If the node shape is an ellipse, transform the scene to turn
// the shape into circle.
if (_nodeShapeToCircle.IsIdentity == false)
{
hitBegin = _nodeShapeToCircle.Transform(hitBegin);
hitEnd = _nodeShapeToCircle.Transform(hitEnd);
}
bool isHit = false;
// Hit-test the end node
Vector nearest = GetNearest(hitBegin, hitEnd);
if (nearest.LengthSquared < endRadiusSquared)
{
isHit = true;
if (!DoubleUtil.AreClose(result.EndFIndex, StrokeFIndices.AfterLast))
{
result.EndFIndex = StrokeFIndices.AfterLast;
if (beginNode.IsEmpty)
{
result.BeginFIndex = StrokeFIndices.BeforeFirst;
break;
}
if (DoubleUtil.AreClose(result.BeginFIndex, StrokeFIndices.BeforeFirst))
{
break;
}
}
}
if ((beginNode.IsEmpty == false) && (!isHit || !DoubleUtil.AreClose(result.BeginFIndex, StrokeFIndices.BeforeFirst)))
{
// Hit-test the first node
nearest = GetNearest(hitBegin - spineVector, hitEnd - spineVector);
if (nearest.LengthSquared < beginRadiusSquared)
{
isHit = true;
if (!DoubleUtil.AreClose(result.BeginFIndex, StrokeFIndices.BeforeFirst))
{
result.BeginFIndex = StrokeFIndices.BeforeFirst;
if (DoubleUtil.AreClose(result.EndFIndex, StrokeFIndices.AfterLast))
{
break;
}
}
}
}
// If both nodes are hit or nothing is hit at all, return.
if (beginNode.IsEmpty || (!isHit && (quad.IsEmpty ||
(HitTestQuadSegment(quad, hitSegment.Begin, hitSegment.End) == false))))
{
if (isInside && (WhereIsVectorAboutVector(
endNode.Position - hitSegment.Begin, hitSegment.Vector) != HitResult.Right))
{
isInside = false;
}
continue;
}
isInside = false;
// Calculate the exact locations to cut.
CalculateCutLocations(spineVector, hitBegin, hitEnd, endRadius, beginRadius, ref result);
if (result.IsFull)
{
break;
}
}
}
//
if (!result.IsFull)
{
if (isInside == true)
{
System.Diagnostics.Debug.Assert(result.IsEmpty);
result = StrokeFIndices.Full;
}
else if ((DoubleUtil.AreClose(result.EndFIndex, StrokeFIndices.BeforeFirst)) && (!DoubleUtil.AreClose(result.BeginFIndex, StrokeFIndices.AfterLast)))
{
result.EndFIndex = StrokeFIndices.AfterLast;
}
else if ((DoubleUtil.AreClose(result.BeginFIndex,StrokeFIndices.AfterLast)) && (!DoubleUtil.AreClose(result.EndFIndex, StrokeFIndices.BeforeFirst)))
{
result.BeginFIndex = StrokeFIndices.BeforeFirst;
}
}
if (IsInvalidCutTestResult(result))
{
return StrokeFIndices.Empty;
}
return result;
}
/// <summary>
/// Clip-Testing a circluar inking segment against a linear segment.
/// See http://tabletpc/longhorn/Specs/Rendering%20and%20Hit-Testing%20Ink%20in%20Avalon%20M11.doc section
/// 5.4.4.14 Clip-Testing a Circular Inking Segment against a Linear Segment for details of the algorithm
/// </summary>
/// <param name="spineVector">Represent the spine of the inking segment pointing from the beginNode to endNode</param>
/// <param name="beginRadius">Radius of the beginNode</param>
/// <param name="endRadius">Radius of the endNode</param>
/// <param name="hitBegin">Hitting segment start point</param>
/// <param name="hitEnd">Hitting segment end point</param>
/// <returns>A double which represents the location for cutting</returns>
private static double ClipTest(Vector spineVector, double beginRadius, double endRadius, Vector hitBegin, Vector hitEnd)
{
// First handle the special case when the spineVector is (0,0). In other words, this is the case
// when the stylus stays at the the location but pressure changes.
if (DoubleUtil.IsZero(spineVector.X) && DoubleUtil.IsZero(spineVector.Y))
{
System.Diagnostics.Debug.Assert(DoubleUtil.AreClose(beginRadius, endRadius) == false);
Vector nearest = GetNearest(hitBegin, hitEnd);
double radius;
if (nearest.X == 0)
{
radius = Math.Abs(nearest.Y);
}
else if (nearest.Y == 0)
{
radius = Math.Abs(nearest.X);
}
else
{
radius = nearest.Length;
}
return AdjustFIndex((radius - beginRadius) / (endRadius - beginRadius));
}
// This change to ClipTest with a point if the two hitting segment are close enough.
if (DoubleUtil.AreClose(hitBegin, hitEnd))
{
return ClipTest(spineVector, beginRadius, endRadius, hitBegin);
}
double findex;
Vector hitVector = hitEnd - hitBegin;
if (DoubleUtil.IsZero(Vector.Determinant(spineVector, hitVector)))
{
// hitVector and spineVector are parallel
findex = ClipTest(spineVector, beginRadius, endRadius, GetNearest(hitBegin, hitEnd));
System.Diagnostics.Debug.Assert(!double.IsNaN(findex));
}
else
{
// On the line defined by the segment find point P1Xp, the nearest to the beginNode.Position
double x = GetProjectionFIndex(hitBegin, hitEnd);
Vector P1Xp = hitBegin + (hitVector * x);
if (P1Xp.LengthSquared < (beginRadius * beginRadius))
{
System.Diagnostics.Debug.Assert(DoubleUtil.IsBetweenZeroAndOne(x) == false);
findex = ClipTest(spineVector, beginRadius, endRadius, (0 > x) ? hitBegin : hitEnd);
System.Diagnostics.Debug.Assert(!double.IsNaN(findex));
}
else
{
// Find the projection point P of endNode.Position to the line (beginNode.Position, B).
Vector P1P2p = spineVector + GetProjection(-spineVector, P1Xp - spineVector);
//System.Diagnostics.Debug.Assert(false == DoubleUtil.IsZero(P1P2p.LengthSquared));
//System.Diagnostics.Debug.Assert(false == DoubleUtil.IsZero(endRadius - beginRadius + P1P2p.Length));
// There checks are here since if either fail no real solution can be caculated and we may
// as well bail out now and save the caculations that are below.
if (DoubleUtil.IsZero(P1P2p.LengthSquared) || DoubleUtil.IsZero(endRadius - beginRadius + P1P2p.Length))
return 1d;
// Calculate the findex of the point to split the ink segment at.
findex = (P1Xp.Length - beginRadius) / (endRadius - beginRadius + P1P2p.Length);
System.Diagnostics.Debug.Assert(!double.IsNaN(findex));
// Find the projection of the split point to the line of this segment.
Vector S = spineVector * findex;
double r = GetProjectionFIndex(hitBegin - S, hitEnd - S);
// If the nearest point misses the segment, then find the findex
// of the node nearest to the segment.
if (false == DoubleUtil.IsBetweenZeroAndOne(r))
{
findex = ClipTest(spineVector, beginRadius, endRadius, (0 > r) ? hitBegin : hitEnd);
System.Diagnostics.Debug.Assert(!double.IsNaN(findex));
}
}
}
return AdjustFIndex(findex);
}
/// <summary>
/// Clip-Testing a circular inking segment again a hitting point.
///
/// What need to find out a doulbe value s, which is between 0 and 1, such that
/// DistanceOf(hit - s*spine) = beginRadius + s * (endRadius - beginRadius)
/// That is
/// (hit.X-s*spine.X)^2 + (hit.Y-s*spine.Y)^2 = [beginRadius + s*(endRadius-beginRadius)]^2
/// Rearrange
/// A*s^2 + B*s + C = 0
/// where the value of A, B and C are described in the source code.
/// Solving for s:
/// s = (-B + sqrt(B^2-4A*C))/(2A) or s = (-B - sqrt(B^2-4A*C))/(2A)
/// The smaller value between 0 and 1 is the one we want and discard the other one.
/// </summary>
/// <param name="spine">Represent the spine of the inking segment pointing from the beginNode to endNode</param>
/// <param name="beginRadius">Radius of the beginNode</param>
/// <param name="endRadius">Radius of the endNode</param>
/// <param name="hit">The hitting point</param>
/// <returns>A double which represents the location for cutting</returns>
private static double ClipTest(Vector spine, double beginRadius, double endRadius, Vector hit)
{
double radDiff = endRadius - beginRadius;
double A = spine.X*spine.X + spine.Y*spine.Y - radDiff*radDiff;
double B = -2.0f*(hit.X*spine.X + hit.Y * spine.Y + beginRadius*radDiff);
double C = hit.X * hit.X + hit.Y * hit.Y - beginRadius * beginRadius;
// There checks are here since if either fail no real solution can be caculated and we may
// as well bail out now and save the caculations that are below.
if (DoubleUtil.IsZero(A) || !DoubleUtil.GreaterThanOrClose(B*B, 4.0f*A*C))
return 1d;
double tmp = Math.Sqrt(B*B-4.0f * A * C);
double s1 = (-B + tmp)/(2.0f * A);
double s2 = (-B - tmp)/(2.0f * A);
double findex;
if (DoubleUtil.IsBetweenZeroAndOne(s1) && DoubleUtil.IsBetweenZeroAndOne(s1))
{
findex = Math.Min(s1, s2);
}
else if (DoubleUtil.IsBetweenZeroAndOne(s1))
{
findex = s1;
}
else if (DoubleUtil.IsBetweenZeroAndOne(s2))
{
findex = s2;
}
else
{
// There is still possiblity that value like 1.0000000000000402 is not considered
// as "IsOne" by DoubleUtil class. We should be at either one of the following two cases:
// 1. s1/s2 around 0 but not close enough (say -0.0000000000001)
// 2. s1/s2 around 1 but not close enought (say 1.0000000000000402)
if (s1 > 1d && s2 > 1d)
{
findex = 1d;
}
else if (s1 < 0d && s2 < 0d)
{
findex = 0d;
}
else
{
findex = Math.Abs(Math.Min(s1, s2) - 0d) < Math.Abs(Math.Max(s1, s2) - 1d) ? 0d : 1d;
}
}
return AdjustFIndex(findex);
}
/// <summary>
/// Helper function to find out the relative location of a segment {segBegin, segEnd} against
/// a strokeNode (spine).
/// </summary>
/// <param name="spine">the spineVector of the StrokeNode</param>
/// <param name="segBegin">Start position of the line segment</param>
/// <param name="segEnd">End position of the line segment</param>
/// <returns>HitResult</returns>
private static HitResult WhereIsNodeAboutSegment(Vector spine, Vector segBegin, Vector segEnd)
{
HitResult whereabout = HitResult.Right;
Vector segVector = segEnd - segBegin;
if ((WhereIsVectorAboutVector(-segBegin, segVector) == HitResult.Left)
&& !DoubleUtil.IsZero(Vector.Determinant(spine, segVector)))
{
whereabout = HitResult.Left;
}
return whereabout;
}
/// <summary>
/// Helper method to calculate the exact location to cut
/// </summary>
/// <param name="spineVector">Vector the relative location of the two inking nodes</param>
/// <param name="hitBegin">the begin point of the hitting segment</param>
/// <param name="hitEnd">the end point of the hitting segment</param>
/// <param name="endRadius">endNode radius</param>
/// <param name="beginRadius">beginNode radius</param>
/// <param name="result">StrokeFIndices representing the location for cutting</param>
private void CalculateCutLocations(
Vector spineVector, Vector hitBegin, Vector hitEnd, double endRadius, double beginRadius, ref StrokeFIndices result)
{
// Find out whether the {hitBegin, hitEnd} segment intersects with the contour
// of the stroke segment, and find the lower index of the fragment to cut out.
if (!DoubleUtil.AreClose(result.EndFIndex, StrokeFIndices.AfterLast))
{
if (WhereIsNodeAboutSegment(spineVector, hitBegin, hitEnd) == HitResult.Left)
{
double findex = 1 - ClipTest(spineVector, endRadius, beginRadius, hitBegin, hitEnd);
if (findex > result.EndFIndex)
{
result.EndFIndex = findex;
}
}
}
// Find out whether the {hitBegin, hitEnd} segment intersects with the contour
// of the stroke segment, and find the higher index of the fragment to cut out.
if (!DoubleUtil.AreClose(result.BeginFIndex, StrokeFIndices.BeforeFirst))
{
hitBegin -= spineVector;
hitEnd -= spineVector;
if (WhereIsNodeAboutSegment(-spineVector, hitBegin, hitEnd) == HitResult.Left)
{
double findex = ClipTest(-spineVector, beginRadius, endRadius, hitBegin, hitEnd);
if (findex < result.BeginFIndex)
{
result.BeginFIndex = findex;
}
}
}
}
private double _radius = 0;
private Size _radii;
private Matrix _transform;
private Matrix _nodeShapeToCircle;
private Matrix _circleToNodeShape;
}
}
| |
#region Copyright and license information
// Copyright 2001-2009 Stephen Colebourne
// Copyright 2009-2011 Jon Skeet
//
// 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
using System;
using System.Text;
namespace NodaTime.TimeZones
{
/// <summary>
/// Represents a transition two different time references.
/// </summary>
/// <remarks>
/// <para>
/// Normally this is between standard time and daylight savings time but it might be for other
/// purposes like the discontinuity in the Gregorian calendar to account for leap time.
/// </para>
/// <para>
/// Immutable, thread safe.
/// </para>
/// </remarks>
[Serializable]
internal class ZoneTransition : IEquatable<ZoneTransition>, IComparable<ZoneTransition>
{
private readonly Instant instant;
private readonly string name;
private readonly Offset savings;
private readonly Offset standardOffset;
/// <summary>
/// Initializes a new instance of the <see cref="ZoneTransition"/> class.
/// </summary>
/// <remarks>
/// <para>
/// Assumption 1: Offset.MaxValue << Instant.MaxValue
/// </para>
/// <para>
/// Assumption 2: Offset.MinValue >> Instant.MinValue
/// </para>
/// <para>
/// Therefore the sum of an Instant with an Offset of the opposite sign cannot overflow or
/// underflow. We only have to worry about summing an Instant with an Offset of the same
/// sign over/underflowing.
/// </para>
/// </remarks>
/// <param name="instant">The instant that this transistion occurs at.</param>
/// <param name="name">The name for the time at this transition e.g. PDT or PST.</param>
/// <param name="standardOffset">The standard offset at this transition.</param>
/// <param name="savings">The actual offset at this transition.</param>
internal ZoneTransition(Instant instant, String name, Offset standardOffset, Offset savings)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
this.instant = instant;
this.name = name;
this.standardOffset = standardOffset;
this.savings = savings;
//
// Make sure that the math will not overflow later.
//
if (instant.Ticks < 0 && WallOffset.TotalMilliseconds < 0)
{
long distanceFromEndOfTime = instant.Ticks - Instant.MinValue.Ticks;
if (distanceFromEndOfTime < Math.Abs(WallOffset.TotalTicks))
{
this.standardOffset = Offset.FromTicks(-distanceFromEndOfTime);
this.savings = Offset.Zero;
}
}
else if (instant.Ticks > 0 && savings.TotalMilliseconds > 0)
{
long distanceFromEndOfTime = Instant.MaxValue.Ticks - instant.Ticks;
if (distanceFromEndOfTime < WallOffset.TotalTicks)
{
this.standardOffset = Offset.FromTicks(distanceFromEndOfTime);
this.savings = Offset.Zero;
}
}
}
internal Instant Instant { get { return instant; } }
internal string Name { get { return name; } }
internal Offset StandardOffset { get { return standardOffset; } }
internal Offset Savings { get { return savings; } }
internal Offset WallOffset { get { return StandardOffset + Savings; } }
#region IComparable<ZoneTransition> Members
/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the objects being compared.
/// The return value has the following meanings:
/// Value
/// Meaning
/// Less than zero
/// This object is less than the <paramref name="other"/> parameter.
/// Zero
/// This object is equal to <paramref name="other"/>.
/// Greater than zero
/// This object is greater than <paramref name="other"/>.
/// </returns>
public int CompareTo(ZoneTransition other)
{
return other == null ? 1 : Instant.CompareTo(other.Instant);
}
#endregion
#region Operator overloads
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static bool operator ==(ZoneTransition left, ZoneTransition right)
{
return ReferenceEquals(null, left) ? ReferenceEquals(null, right) : left.Equals(right);
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static bool operator !=(ZoneTransition left, ZoneTransition right)
{
return !(left == right);
}
#endregion
#region IEquatable<ZoneTransition> Members
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// true if the current object is equal to the <paramref name="other"/> parameter;
/// otherwise, false.
/// </returns>
public bool Equals(ZoneTransition other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return Instant == other.Instant;
}
#endregion
/// <summary>
/// Determines whether is a transition from the given transition.
/// </summary>
/// <remarks>
/// To be a transition from another the instant at which the transition occurs must be
/// greater than the given transition's and either the wall offset or the name must be
/// different. If this is not true then this transition is considered to be redundant
/// and should not be used.
/// TODO: Consider whether going from "standard=0,savings=1" to "standard=1,savings=0"
/// should be considered a transition. Currently we don't expose the standard/savings
/// aspect of a time zone, but we may well in the future.
/// </remarks>
/// <param name="other">The <see cref="ZoneTransition"/> to compare to.</param>
/// <returns>
/// <c>true</c> if this is a transition from the given transition; otherwise, <c>false</c>.
/// </returns>
internal bool IsTransitionFrom(ZoneTransition other)
{
if (other == null)
{
return true;
}
return Instant > other.Instant && (WallOffset != other.WallOffset || Name != other.Name);
}
#region Object overrides
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance;
/// otherwise, <c>false</c>.
/// </returns>
/// <exception cref="T:System.NullReferenceException">
/// The <paramref name="obj"/> parameter is null.
/// </exception>
public override bool Equals(object obj)
{
return Equals(obj as ZoneTransition);
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data
/// structures like a hash table.
/// </returns>
public override int GetHashCode()
{
return Instant.GetHashCode();
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override string ToString()
{
var builder = new StringBuilder();
builder.Append(name);
builder.Append(" at ").Append(Instant);
builder.Append(" ").Append(StandardOffset);
builder.Append(" [").Append(Savings).Append("]");
return builder.ToString();
}
#endregion // Object overrides
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
/// <summary>
/// Convert.ToChar(Object)
/// Converts the value of the specified Object to a Unicode character.
/// </summary>
public class ConvertTochar
{
public static int Main()
{
ConvertTochar testObj = new ConvertTochar();
TestLibrary.TestFramework.BeginTestCase("for method: Convert.ToChar(Object)");
if(testObj.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
retVal = NegTest5() && retVal;
retVal = NegTest6() && retVal;
return retVal;
}
#region Positive tests
public bool PosTest1()
{
bool retVal = true;
string errorDesc;
object obj;
char expectedValue;
char actualValue;
Int64 i = TestLibrary.Generator.GetInt64(-55) % (UInt16.MaxValue + 1);
obj = i;
TestLibrary.TestFramework.BeginScenario("PosTest1: Object is Int64 value between 0 and UInt16.MaxValue.");
try
{
actualValue = Convert.ToChar(obj);
expectedValue = (char)i;
if (actualValue != expectedValue)
{
errorDesc = string.Format("The character of Int64 value " +
obj + " is not the value \\u{0:x}" +
" as expected: actual(\\u{1:x})", (int)expectedValue, (int)actualValue);
TestLibrary.TestFramework.LogError("001", errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpect exception:" + e;
errorDesc += "\nThe Int64 value is " + obj;
TestLibrary.TestFramework.LogError("002", errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
string errorDesc;
object obj;
char expectedValue;
char actualValue;
byte b = TestLibrary.Generator.GetByte(-55);
obj = b;
TestLibrary.TestFramework.BeginScenario("PosTest2: Object is byte value");
try
{
actualValue = Convert.ToChar(obj);
expectedValue = (char)b;
if (actualValue != expectedValue)
{
errorDesc = string.Format("The character of byte value " +
obj + " is not the value \\u{0:x}" +
" as expected: actual(\\u{1:x})", (int)expectedValue, (int)actualValue);
TestLibrary.TestFramework.LogError("003", errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpect exception:" + e;
errorDesc += "\nThe byte value is " + obj;
TestLibrary.TestFramework.LogError("004", errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
string errorDesc;
object obj;
char expectedValue;
char actualValue;
expectedValue = TestLibrary.Generator.GetChar(-55);
obj = new string(expectedValue, 1);
TestLibrary.TestFramework.BeginScenario("PosTest3: Object instance is string");
try
{
actualValue = Convert.ToChar(obj);
if (actualValue != expectedValue)
{
errorDesc = string.Format("The character of \"" +
obj + "\" is not the value \\u{0:x}" +
" as expected: actual(\\u{1:x})", (int)expectedValue, (int)actualValue);
TestLibrary.TestFramework.LogError("005", errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpect exception:" + e;
errorDesc += "\nThe string is " + obj;
TestLibrary.TestFramework.LogError("006", errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
string errorDesc;
object obj;
char expectedValue;
char actualValue;
obj = TestLibrary.Generator.GetChar(-55);
TestLibrary.TestFramework.BeginScenario("PosTest4: Object instance is character.");
try
{
actualValue = Convert.ToChar(obj);
expectedValue = (char)obj;
if (actualValue != expectedValue)
{
errorDesc = string.Format("The character of \"" +
obj + "\" is not the value \\u{0:x}" +
" as expected: actual(\\u{1:x})", (int)expectedValue, (int)actualValue);
TestLibrary.TestFramework.LogError("007", errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpect exception:" + e;
errorDesc += "\nThe string is \"" + obj + "\"";
TestLibrary.TestFramework.LogError("008", errorDesc);
retVal = false;
}
return retVal;
}
#endregion
#region Negative tests
//OverflowException
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_ID = "N001";
const string c_TEST_DESC = "NegTest1: Object instance is a negative Int32 value between Int32.MinValue and -1.";
string errorDesc;
Int32 i = -1 * TestLibrary.Generator.GetInt32(-55) - 1;
object obj = i;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
Convert.ToChar(obj);
errorDesc = "OverflowException is not thrown as expected.";
errorDesc += string.Format("\nThe Int32 value is {0}", i);
TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (OverflowException)
{ }
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += string.Format("\nThe Int32 value is {0}", i);
TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
const string c_TEST_ID = "N002";
const string c_TEST_DESC = "NegTest2: Object instance is a Int64 value between UInt16.MaxValue and Int64.MaxValue.";
string errorDesc;
Int64 i = TestLibrary.Generator.GetInt64(-55) % (Int64.MaxValue - UInt16.MaxValue) +
UInt16.MaxValue + 1;
object obj = i;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
Convert.ToChar(obj);
errorDesc = "OverflowException is not thrown as expected.";
errorDesc += string.Format("\nThe Int64 value is {0}", i);
TestLibrary.TestFramework.LogError("011" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (OverflowException)
{ }
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += string.Format("\nThe Int64 value is {0}", i);
TestLibrary.TestFramework.LogError("012" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
//InvalidCastException
public bool NegTest3()
{
bool retVal = true;
const string c_TEST_ID = "N003";
const string c_TEST_DESC = "NegTes3: Object instance does not implement the IConvertible interface. ";
string errorDesc;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
Convert.ToChar(new MyFoo());
errorDesc = "InvalidCastException is not thrown as expected.";
TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (InvalidCastException)
{ }
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
TestLibrary.TestFramework.LogError("014" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
//FormatException
public bool NegTest4()
{
bool retVal = true;
const string c_TEST_ID = "N004";
const string c_TEST_DESC = "NegTest4: Object instance is a string whose length is longer than 1 characters.";
string errorDesc;
string str = TestLibrary.Generator.GetString(-55, false, 2, 256);
object obj = str;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
Convert.ToChar(obj);
errorDesc = "FormatException is not thrown as expected.";
errorDesc += "\nThe string is \"" + str + "\"";
TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (FormatException)
{ }
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += "\nThe string is \"" + str + "\"";
TestLibrary.TestFramework.LogError("015" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
//ArgumentNullException
public bool NegTest5()
{
bool retVal = true;
const string c_TEST_ID = "N005";
const string c_TEST_DESC = "NegTes5: Object instance is a null reference.";
string errorDesc;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
Convert.ToChar(null);
errorDesc = "ArgumentNullException is not thrown as expected.";
errorDesc += "\nThe string is <null>";
TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (ArgumentNullException)
{ }
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += "\nThe object is a null reference";
TestLibrary.TestFramework.LogError("016" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
//InvalidCastException
public bool NegTest6()
{
bool retVal = true;
const string c_TEST_ID = "N006";
const string c_TEST_DESC = "NegTes6: Object instance is double value.";
string errorDesc;
double d = TestLibrary.Generator.GetDouble(-55);
object obj = d;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
Convert.ToChar(obj);
errorDesc = "InvalidCastException is not thrown as expected.";
errorDesc += "\nThe string is \"" + obj.ToString() + "\"";
TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (InvalidCastException)
{ }
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += "\nThe object is a null reference";
TestLibrary.TestFramework.LogError("016" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
#endregion
#region Helper type
//A class which does not implement the interface IConvertible
internal class MyFoo
{}
#endregion
}
| |
/*
* 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;
using java = biz.ritter.javapi;
namespace biz.ritter.javapi.util{
/**
* WeakHashMap is an implementation of Map with keys which are WeakReferences. A
* key/value mapping is removed when the key is no longer referenced. All
* optional operations (adding and removing) are supported. Keys and values can
* be any objects. Note that the garbage collector acts similar to a second
* thread on this collection, possibly removing keys.
*
* @since 1.2
* @see HashMap
* @see WeakReference
*/
public class WeakHashMap<K, V> : AbstractMap<K, V> {//implements Map<K, V> {
private const int DEFAULT_SIZE = 16;
private readonly java.lang.refj.ReferenceQueue<K> referenceQueue;
int elementCount;
internal Entry<K, V>[] elementData;
private readonly int loadFactor;
private int threshold;
internal volatile int modCount;
// Simple utility method to isolate unchecked cast for array creation
internal static Entry<K, V>[] newEntryArray<K, V>(int size) {
return new Entry<K,V>[size];
}
internal sealed class Entry<K, V> : java.lang.refj.WeakReference<K>,
MapNS.Entry<K, V> {
internal int hash;
internal bool isNull;
internal V valueJ;
internal Entry<K, V> next;
internal interface Type<R, K, V> {
R get(MapNS.Entry<K, V> entry);
}
private readonly WeakHashMap<K,V> outerInstance;
internal Entry(K key, V objectJ, java.lang.refj.ReferenceQueue<K> queue, WeakHashMap<K,V> outer) :
base(key, queue){
isNull = key == null;
hash = isNull ? 0 : key.GetHashCode();
valueJ = objectJ;
this.outerInstance = outer;
}
public K getKey() {
return base.get();
}
public V getValue() {
return valueJ;
}
public V setValue(V objectJ) {
V result = valueJ;
valueJ = objectJ;
return result;
}
public override bool Equals(Object other) {
if (!(other is MapNS.Entry<K,V>)) {
return false;
}
MapNS.Entry<Object, Object> entry = (MapNS.Entry<Object, Object>) other;
Object key = base.get();
return (key == null ? key == entry.getKey() : key.equals(entry
.getKey()))
&& (valueJ == null ? null == entry.getValue() : valueJ
.equals(entry.getValue()));
}
public override int GetHashCode() {
return hash + (valueJ == null ? 0 : valueJ.GetHashCode());
}
public override String ToString() {
return base.get() + "=" + valueJ; //$NON-NLS-1$
}
}
/**
* Constructs a new empty {@code WeakHashMap} instance.
*/
public WeakHashMap() :
this(DEFAULT_SIZE){
}
/**
* Constructs a new {@code WeakHashMap} instance with the specified
* capacity.
*
* @param capacity
* the initial capacity of this map.
* @throws IllegalArgumentException
* if the capacity is less than zero.
*/
public WeakHashMap(int capacity) {
if (capacity >= 0) {
elementCount = 0;
elementData = newEntryArray<K,V>(capacity == 0 ? 1 : 0);
loadFactor = 7500; // Default load factor of 0.75
computeMaxSize();
referenceQueue = new java.lang.refj.ReferenceQueue<K>();
} else {
throw new java.lang.IllegalArgumentException();
}
}
/**
* Constructs a new {@code WeakHashMap} instance with the specified capacity
* and load factor.
*
* @param capacity
* the initial capacity of this map.
* @param loadFactor
* the initial load factor.
* @throws IllegalArgumentException
* if the capacity is less than zero or the load factor is less
* or equal to zero.
*/
public WeakHashMap(int capacity, float loadFactor) {
if (capacity >= 0 && loadFactor > 0) {
elementCount = 0;
elementData = newEntryArray<K,V>(capacity == 0 ? 1 : capacity);
this.loadFactor = (int) (loadFactor * 10000);
computeMaxSize();
referenceQueue = new java.lang.refj.ReferenceQueue<K>();
} else {
throw new java.lang.IllegalArgumentException();
}
}
/**
* Constructs a new {@code WeakHashMap} instance containing the mappings
* from the specified map.
*
* @param map
* the mappings to add.
*/
public WeakHashMap(Map<K, V> map) :
this(map.size() < 6 ? 11 : map.size() * 2){
putAllImpl(map);
}
/**
* Removes all mappings from this map, leaving it empty.
*
* @see #isEmpty()
* @see #size()
*/
public override void clear() {
if (elementCount > 0) {
elementCount = 0;
java.util.Arrays<Entry<K,V>>.fill(elementData, null);
modCount++;
while (referenceQueue.poll() != null) {
// do nothing
}
}
}
private void computeMaxSize() {
threshold = (int) ((long) elementData.Length * loadFactor / 10000);
}
/**
* Returns whether this map contains the specified key.
*
* @param key
* the key to search for.
* @return {@code true} if this map contains the specified key,
* {@code false} otherwise.
*/
public override bool containsKey(Object key) {
return getEntry(key) != null;
}
/**
* Returns a set containing all of the mappings in this map. Each mapping is
* an instance of {@link Map.Entry}. As the set is backed by this map,
* changes in one will be reflected in the other. It does not support adding
* operations.
*
* @return a set of the mappings.
*/
public override Set<MapNS.Entry<K, V>> entrySet() {
poll();
return new IAC_EntrySet(this);
}
internal class IAC_EntrySet : AbstractSet<MapNS.Entry<K,V>> {
private readonly WeakHashMap<K,V> outerInstance;
public IAC_EntrySet (WeakHashMap<K,V> outer) {
this.outerInstance = outer;
}
public override int size() {
return this.outerInstance.size();
}
public override void clear() {
this.outerInstance.clear();
}
public override bool remove(Object objectJ) {
if (contains(objectJ)) {
this.outerInstance.remove(((MapNS.Entry<Object, Object>) objectJ).getKey());
return true;
}
return false;
}
public override bool contains(Object objectJ) {
if (objectJ is MapNS.Entry<K,V>) {
Entry<K, V> entry = outerInstance.getEntry(((MapNS.Entry<Object, Object>) objectJ)
.getKey());
if (entry != null) {
Object key = entry.get();
if (key != null || entry.isNull) {
return objectJ.Equals(entry);
}
}
}
return false;
}
public override Iterator<MapNS.Entry<K, V>> iterator() {
return new HashIterator<MapNS.Entry<K, V>,K,V>(
new IAC_Entry() ,this.outerInstance
);
}
internal class IAC_Entry : Entry<K,V>.Type<MapNS.Entry<K, V>, K, V>{
public MapNS.Entry<K, V> get(MapNS.Entry<K, V> entry) {
return entry;
}
}
/*
public Iterator<V> iterator2() {
return new HashIterator<V,K,V>(
new IAC_EntryValue(), this.outerInstance
);
}
internal class IAC_EntryValue : Entry<K,V>.Type<V, K, V>{
public V get(MapNS.Entry<K, V> entry) {
return entry.getValue();
}
}
*/
}
/**
* Returns a set of the keys contained in this map. The set is backed by
* this map so changes to one are reflected by the other. The set does not
* support adding.
*
* @return a set of the keys.
*/
public override Set<K> keySet() {
poll();
if (keySetJ == null) {
keySetJ = new IAC_KeySet(this);
}
return keySetJ;
}
internal class IAC_KeySet : AbstractSet<K>{
private readonly WeakHashMap<K,V> outerInstance;
public IAC_KeySet (WeakHashMap<K,V> outer) {
this.outerInstance = outer;
}
public override bool contains(Object objectJ) {
return this.outerInstance.containsKey(objectJ);
}
public override int size() {
return this.outerInstance.size();
}
public override void clear() {
this.outerInstance.clear();
}
public override bool remove(Object key) {
if (this.outerInstance.containsKey(key)) {
this.outerInstance.remove(key);
return true;
}
return false;
}
public override Iterator<K> iterator() {
return new HashIterator<K,K,V>(new IAC_KeyValue(), this.outerInstance);
}
internal class IAC_KeyValue : Entry<K,V>.Type<K, K, V>{
public K get(MapNS.Entry<K, V> entry) {
return entry.getKey();
}
}
public override Object[] toArray() {
Collection<K> coll = new ArrayList<K>(size());
for (Iterator<K> iter = iterator(); iter.hasNext();) {
coll.add(iter.next());
}
return coll.toArray();
}
public override T[] toArray<T>(T[] contents) {
Collection<K> coll = new ArrayList<K>(size());
for (Iterator<K> iter = iterator(); iter.hasNext();) {
coll.add(iter.next());
}
return coll.toArray(contents);
}
}
/**
* Returns a collection of the values contained in this map. The collection
* is backed by this map so changes to one are reflected by the other. The
* collection supports remove, removeAll, retainAll and clear operations,
* and it does not support add or addAll operations.
* <p/>
* This method returns a collection which is the subclass of
* AbstractCollection. The iterator method of this subclass returns a
* "wrapper object" over the iterator of map's entrySet(). The size method
* wraps the map's size method and the contains method wraps the map's
* containsValue method.
* <p/>
* The collection is created when this method is called at first time and
* returned in response to all subsequent calls. This method may return
* different Collection when multiple calls to this method, since it has no
* synchronization performed.
*
* @return a collection of the values contained in this map.
*/
public override Collection<V> values() {
poll();
if (valuesCollection == null) {
valuesCollection = new IAC_ValuesCollection(this);
}
return valuesCollection;
}
class IAC_ValuesCollection : AbstractCollection<V> {
private readonly WeakHashMap<K,V> outerInstance;
public IAC_ValuesCollection (WeakHashMap<K,V> outer){
this.outerInstance = outer;
}
public override int size() {
return this.outerInstance.size();
}
public override void clear() {
this.outerInstance.clear();
}
public override bool contains(Object objectJ) {
return this.outerInstance.containsValue(objectJ);
}
public override Iterator<V> iterator() {
return new HashIterator<V,K,V>(new IAC_EntryValue(), this.outerInstance);
}
internal class IAC_EntryValue : Entry<K,V>.Type<V, K, V>{
public V get(MapNS.Entry<K, V> entry) {
return entry.getValue();
}
}
}
/**
* Returns the value of the mapping with the specified key.
*
* @param key
* the key.
* @return the value of the mapping with the specified key, or {@code null}
* if no mapping for the specified key is found.
*/
public override V get(Object key) {
poll();
if (key != null) {
int index = (key.GetHashCode() & 0x7FFFFFFF) % elementData.Length;
Entry<K, V> entry1 = elementData[index];
while (entry1 != null) {
if (key.equals(entry1.get())) {
return entry1.valueJ;
}
entry1 = entry1.next;
}
return default(V);
}
Entry<K, V> entry2 = elementData[0];
while (entry2 != null) {
if (entry2.isNull) {
return entry2.valueJ;
}
entry2 = entry2.next;
}
return default(V);
}
Entry<K, V> getEntry(Object key) {
poll();
if (key != null) {
int index = (key.GetHashCode() & 0x7FFFFFFF) % elementData.Length;
Entry<K, V> entry1 = elementData[index];
while (entry1 != null) {
if (key.equals(entry1.get())) {
return entry1;
}
entry1 = entry1.next;
}
return null;
}
Entry<K, V> entry2 = elementData[0];
while (entry2 != null) {
if (entry2.isNull) {
return entry2;
}
entry2 = entry2.next;
}
return null;
}
/**
* Returns whether this map contains the specified value.
*
* @param value
* the value to search for.
* @return {@code true} if this map contains the specified value,
* {@code false} otherwise.
*/
public override bool containsValue(Object valueJ) {
poll();
if (valueJ != null) {
for (int i = elementData.Length; --i >= 0;) {
Entry<K, V> entry = elementData[i];
while (entry != null) {
K key = entry.get();
if ((key != null || entry.isNull)
&& valueJ.equals(entry.valueJ)) {
return true;
}
entry = entry.next;
}
}
} else {
for (int i = elementData.Length; --i >= 0;) {
Entry<K, V> entry = elementData[i];
while (entry != null) {
K key = entry.get();
if ((key != null || entry.isNull) && entry.valueJ == null) {
return true;
}
entry = entry.next;
}
}
}
return false;
}
/**
* Returns the number of elements in this map.
*
* @return the number of elements in this map.
*/
public override bool isEmpty() {
return size() == 0;
}
void poll() {
Entry<K, V> toRemove;
while ((toRemove = (Entry<K, V>) referenceQueue.poll()) != null) {
removeEntry(toRemove);
}
}
internal void removeEntry(Entry<K, V> toRemove) {
Entry<K, V> entry, last = null;
int index = (toRemove.hash & 0x7FFFFFFF) % elementData.Length;
entry = elementData[index];
// Ignore queued entries which cannot be found, the user could
// have removed them before they were queued, i.e. using clear()
while (entry != null) {
if (toRemove == entry) {
modCount++;
if (last == null) {
elementData[index] = entry.next;
} else {
last.next = entry.next;
}
elementCount--;
break;
}
last = entry;
entry = entry.next;
}
}
/**
* Maps the specified key to the specified value.
*
* @param key
* the key.
* @param value
* the value.
* @return the value of any previous mapping with the specified key or
* {@code null} if there was no mapping.
*/
public override V put(K key, V valueJ) {
poll();
int index = 0;
Entry<K, V> entry;
if (key != null) {
index = (key.GetHashCode() & 0x7FFFFFFF) % elementData.Length;
entry = elementData[index];
while (entry != null && !key.equals(entry.get())) {
entry = entry.next;
}
} else {
entry = elementData[0];
while (entry != null && !entry.isNull) {
entry = entry.next;
}
}
if (entry == null) {
modCount++;
if (++elementCount > threshold) {
rehash();
index = key == null ? 0 : (key.GetHashCode() & 0x7FFFFFFF)
% elementData.Length;
}
entry = new Entry<K, V>(key, valueJ, referenceQueue, this);
entry.next = elementData[index];
elementData[index] = entry;
return default(V);
}
V result = entry.valueJ;
entry.valueJ = valueJ;
return result;
}
private void rehash() {
int length = elementData.Length << 1;
if (length == 0) {
length = 1;
}
Entry<K, V>[] newData = newEntryArray<K,V>(length);
for (int i = 0; i < elementData.Length; i++) {
Entry<K, V> entry = elementData[i];
while (entry != null) {
int index = entry.isNull ? 0 : (entry.hash & 0x7FFFFFFF)
% length;
Entry<K, V> next = entry.next;
entry.next = newData[index];
newData[index] = entry;
entry = next;
}
}
elementData = newData;
computeMaxSize();
}
/**
* Copies all the mappings in the given map to this map. These mappings will
* replace all mappings that this map had for any of the keys currently in
* the given map.
*
* @param map
* the map to copy mappings from.
* @throws NullPointerException
* if {@code map} is {@code null}.
*/
public override void putAll(Map<K, V> map) {
putAllImpl(map);
}
/**
* Removes the mapping with the specified key from this map.
*
* @param key
* the key of the mapping to remove.
* @return the value of the removed mapping or {@code null} if no mapping
* for the specified key was found.
*/
public override V remove(Object key) {
poll();
int index = 0;
Entry<K, V> entry, last = null;
if (key != null) {
index = (key.GetHashCode() & 0x7FFFFFFF) % elementData.Length;
entry = elementData[index];
while (entry != null && !key.equals(entry.get())) {
last = entry;
entry = entry.next;
}
} else {
entry = elementData[0];
while (entry != null && !entry.isNull) {
last = entry;
entry = entry.next;
}
}
if (entry != null) {
modCount++;
if (last == null) {
elementData[index] = entry.next;
} else {
last.next = entry.next;
}
elementCount--;
return entry.valueJ;
}
return default(V);
}
/**
* Returns the number of elements in this map.
*
* @return the number of elements in this map.
*/
public override int size() {
poll();
return elementCount;
}
private void putAllImpl(Map<K, V> map) {
if (map.entrySet() != null) {
base.putAll(map);
}
}
}
internal class HashIterator<R,K,V> : Iterator<R> {
private readonly WeakHashMap<K,V> outerInstance;
private int position = 0, expectedModCount;
private WeakHashMap<K,V>.Entry<K, V> currentEntry, nextEntry;
private K nextKey;
readonly WeakHashMap<K,V>.Entry<K,V>.Type<R, K, V> type;
internal HashIterator(WeakHashMap<K,V>.Entry<K,V>.Type<R, K, V> type, WeakHashMap<K,V> outer) {
this.type = type;
expectedModCount = this.outerInstance.modCount;
this.outerInstance = outer;
}
public bool hasNext() {
if (nextEntry != null && (nextKey != null || nextEntry.isNull)) {
return true;
}
while (true) {
if (nextEntry == null) {
while (position < this.outerInstance.elementData.Length) {
if ((nextEntry = this.outerInstance.elementData[position++]) != null) {
break;
}
}
if (nextEntry == null) {
return false;
}
}
// ensure key of next entry is not gc'ed
nextKey = nextEntry.get();
if (nextKey != null || nextEntry.isNull) {
return true;
}
nextEntry = nextEntry.next;
}
}
public R next() {
if (expectedModCount == this.outerInstance.modCount) {
if (hasNext()) {
currentEntry = nextEntry;
nextEntry = currentEntry.next;
R result = type.get(currentEntry);
// free the key
nextKey = default(K);
return result;
}
throw new NoSuchElementException();
}
throw new ConcurrentModificationException();
}
public void remove() {
if (expectedModCount == this.outerInstance.modCount) {
if (currentEntry != null) {
this.outerInstance.removeEntry(currentEntry);
currentEntry = null;
expectedModCount++;
// cannot poll() as that would change the expectedModCount
} else {
throw new java.lang.IllegalStateException();
}
} else {
throw new ConcurrentModificationException();
}
}
}
}
| |
using System.Collections.Generic;
using MbUnit.Framework;
using Moq;
using Subtext.Framework.Components;
using Subtext.Framework.Providers;
using Subtext.Framework.Services;
namespace UnitTests.Subtext.Framework.Services
{
[TestFixture]
public class KeywordExpanderTests
{
[Test]
public void Replace_WithStringContainingKeyword_ExpandsKeyword()
{
//arrange
var keywords = new List<KeyWord>
{
new KeyWord
{
Word = "sucky example",
Text = "cool example",
Url = "http://example.com/",
}
};
var keywordExpander = new KeywordExpander(keywords);
//act
string result = keywordExpander.Transform("This is a sucky example");
//assert
Assert.AreEqual("This is a <a href=\"http://example.com/\">cool example</a>", result);
}
[Test]
public void Replace_WithStringContainingKeyword_ExpandsKeywordWithFirstMatchOnly()
{
//arrange
var keywords = new List<KeyWord>
{
new KeyWord
{
Word = "sucky example",
Text = "cool example",
Url = "http://example.com/",
ReplaceFirstTimeOnly = true,
}
};
var keywordExpander = new KeywordExpander(keywords);
//act
string result = keywordExpander.Transform("This is a sucky example");
//assert
Assert.AreEqual("This is a <a href=\"http://example.com/\">cool example</a>", result);
}
[Test]
public void Replace_WithStringContainingKeyword_ExpandsKeywordWithTitle()
{
//arrange
var keywords = new List<KeyWord>
{
new KeyWord
{
Word = "sucky example",
Text = "cool example",
Url = "http://example.com/",
Title = "the title"
}
};
var keywordExpander = new KeywordExpander(keywords);
//act
string result = keywordExpander.Transform("This is a sucky example");
//assert
Assert.AreEqual("This is a <a href=\"http://example.com/\" title=\"the title\">cool example</a>", result);
}
[Test]
public void Replace_WithKeywordSurroundedByUnderscores_IsNotExpanded()
{
//arrange
var keywords = new List<KeyWord>
{
new KeyWord
{
Word = "is",
Text = "is",
Url = "http://example.com/{0}",
}
};
var keywordExpander = new KeywordExpander(keywords);
//act
string result = keywordExpander.Transform(" _is_ ");
//assert
Assert.AreEqual(" _is_ ", result);
}
[Test]
public void Replace_WithStringContainingKeyword_IsNotCaseSensitive()
{
//arrange
var keywords = new List<KeyWord>
{
new KeyWord
{
Word = "is",
Text = "is",
Url = "http://example.com/",
}
};
var keywordExpander = new KeywordExpander(keywords);
//act
string result = keywordExpander.Transform(" it IS true ");
//assert
Assert.AreEqual(" it <a href=\"http://example.com/\">is</a> true ", result);
}
[Test]
public void Replace_WithStringContainingKeywordSpecifiedAsCaseSensitive_IsCaseSensitive()
{
//arrange
var keywords = new List<KeyWord>
{
new KeyWord
{
Word = "is",
Text = "is",
Url = "http://example.com/",
CaseSensitive = true
}
};
var keywordExpander = new KeywordExpander(keywords);
//act
string result = keywordExpander.Transform(" it IS true ");
//assert
Assert.AreEqual(" it IS true ", result);
}
[Test]
public void Replace_WithStringContainingKeywordInsideAnchorTagAttribute_DoesNotExpandKeyword()
{
//arrange
var keywords = new List<KeyWord>
{
new KeyWord
{
Word = "keyword",
Text = "keyword",
Url = "http://example.com/",
}
};
var keywordExpander = new KeywordExpander(keywords);
//act
string result = keywordExpander.Transform("<a title=\"keyword\" href=\"http://x\">test</a>");
//assert
Assert.AreEqual("<a title=\"keyword\" href=\"http://x\">test</a>", result);
}
[Test]
public void Replace_WithStringContainingKeywordInsideAnchorTagInnerText_DoesNotExpandKeyword()
{
//arrange
var keywords = new List<KeyWord>
{
new KeyWord
{
Word = "keyword",
Text = "keyword",
Url = "http://example.com/",
}
};
var keywordExpander = new KeywordExpander(keywords);
//act
string result = keywordExpander.Transform("<a href=\"http://x\">a keyword test</a>");
//assert
Assert.AreEqual("<a href=\"http://x\">a keyword test</a>", result);
}
[Test]
public void Replace_WithStringContainingKeywordInAnotherWord_DoesNotExpandKeyword()
{
//arrange
var keywords = new List<KeyWord>
{
new KeyWord
{
Word = "is",
Text = "is",
Url = "http://example.com/",
}
};
var keywordExpander = new KeywordExpander(keywords);
//act
string result = keywordExpander.Transform("This should not expand");
//assert
Assert.AreEqual("This should not expand", result);
}
// Issue #132: http://code.google.com/p/subtext/issues/detail?id=132
[Test]
public void Transform_WithStringContainingBracketsAndReplacingFirstOccurrenceOnly_ReturnsConvertedKeywordAndBrackets()
{
//arrange
var keywords = new List<KeyWord>
{
new KeyWord
{
Word = "OLD",
Text = "NEW",
Url = "http://example.com/",
Title = "NEW",
ReplaceFirstTimeOnly = true
}
};
var keywordExpander = new KeywordExpander(keywords);
//act
string result = keywordExpander.Transform("OLD {} OLD");
//assert
Assert.AreEqual(@"<a href=""http://example.com/"" title=""NEW"">NEW</a> {} OLD", result);
}
[Test]
public void Transform_WithStringContainingBrackets_ReturnsConvertedKeywordAndBrackets()
{
//arrange
var keywords = new List<KeyWord>
{
new KeyWord
{
Word = "OLD",
Text = "NEW",
Url = "http://example.com/",
Title = "NEW",
ReplaceFirstTimeOnly = false
}
};
var keywordExpander = new KeywordExpander(keywords);
//act
string result = keywordExpander.Transform("OLD {} OLD {}");
//assert
Assert.AreEqual(@"<a href=""http://example.com/"" title=""NEW"">NEW</a> {} <a href=""http://example.com/"" title=""NEW"">NEW</a> {}", result);
}
[Test]
public void Ctor_WithRepository_GetsKeywordsFromRepository()
{
//arrange
var keywords = new List<KeyWord>
{
new KeyWord
{
Word = "is",
Text = "is",
Url = "http://example.com/",
}
};
var repository = new Mock<ObjectProvider>();
repository.Setup(r => r.GetKeyWords()).Returns(keywords);
//act
var keywordExpander = new KeywordExpander(keywords);
//assert
Assert.AreEqual(keywords, keywordExpander.Keywords);
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using NUnit.Framework;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Interfaces;
using QuantConnect.Logging;
using QuantConnect.Orders;
using QuantConnect.Securities;
namespace QuantConnect.Tests.Brokerages
{
public abstract class BrokerageTests
{
// ideally this class would be abstract, but I wanted to keep the order test cases here which use the
// various parameters required from derived types
private IBrokerage _brokerage;
private OrderProvider _orderProvider;
private SecurityProvider _securityProvider;
/// <summary>
/// Provides the data required to test each order type in various cases
/// </summary>
public virtual TestCaseData[] OrderParameters
{
get
{
return new[]
{
new TestCaseData(new MarketOrderTestParameters(Symbol)).SetName("MarketOrder"),
new TestCaseData(new LimitOrderTestParameters(Symbol, HighPrice, LowPrice)).SetName("LimitOrder"),
new TestCaseData(new StopMarketOrderTestParameters(Symbol, HighPrice, LowPrice)).SetName("StopMarketOrder"),
new TestCaseData(new StopLimitOrderTestParameters(Symbol, HighPrice, LowPrice)).SetName("StopLimitOrder")
};
}
}
#region Test initialization and cleanup
[SetUp]
public void Setup()
{
Log.Trace("");
Log.Trace("");
Log.Trace("--- SETUP ---");
Log.Trace("");
Log.Trace("");
// we want to regenerate these for each test
_brokerage = null;
_orderProvider = null;
_securityProvider = null;
Thread.Sleep(1000);
CancelOpenOrders();
LiquidateHoldings();
Thread.Sleep(1000);
}
[TearDown]
public void Teardown()
{
try
{
Log.Trace("");
Log.Trace("");
Log.Trace("--- TEARDOWN ---");
Log.Trace("");
Log.Trace("");
Thread.Sleep(1000);
CancelOpenOrders();
LiquidateHoldings();
Thread.Sleep(1000);
}
finally
{
if (_brokerage != null)
{
DisposeBrokerage(_brokerage);
}
}
}
public IBrokerage Brokerage
{
get
{
if (_brokerage == null)
{
_brokerage = InitializeBrokerage();
}
return _brokerage;
}
}
private IBrokerage InitializeBrokerage()
{
Log.Trace("");
Log.Trace("- INITIALIZING BROKERAGE -");
Log.Trace("");
var brokerage = CreateBrokerage(OrderProvider, SecurityProvider);
brokerage.Connect();
if (!brokerage.IsConnected)
{
Assert.Fail("Failed to connect to brokerage");
}
//gdax does not have a user data stream. Instead, we need to symbol subscribe and monitor for our orders.
if (brokerage.Name == "GDAX")
{
((QuantConnect.Brokerages.GDAX.GDAXBrokerage)brokerage).Subscribe(new[] { Symbol });
}
Log.Trace("");
Log.Trace("GET OPEN ORDERS");
Log.Trace("");
foreach (var openOrder in brokerage.GetOpenOrders())
{
OrderProvider.Add(openOrder);
}
Log.Trace("");
Log.Trace("GET ACCOUNT HOLDINGS");
Log.Trace("");
foreach (var accountHolding in brokerage.GetAccountHoldings())
{
// these securities don't need to be real, just used for the ISecurityProvider impl, required
// by brokerages to track holdings
SecurityProvider[accountHolding.Symbol] = CreateSecurity(accountHolding.Symbol);
}
brokerage.OrderStatusChanged += (sender, args) =>
{
Log.Trace("");
Log.Trace("ORDER STATUS CHANGED: " + args);
Log.Trace("");
// we need to keep this maintained properly
if (args.Status == OrderStatus.Filled || args.Status == OrderStatus.PartiallyFilled)
{
Log.Trace("FILL EVENT: " + args.FillQuantity + " units of " + args.Symbol.ToString());
Security security;
if (_securityProvider.TryGetValue(args.Symbol, out security))
{
var holding = _securityProvider[args.Symbol].Holdings;
holding.SetHoldings(args.FillPrice, holding.Quantity + args.FillQuantity);
}
else
{
_securityProvider[args.Symbol] = CreateSecurity(args.Symbol);
_securityProvider[args.Symbol].Holdings.SetHoldings(args.FillPrice, args.FillQuantity);
}
Log.Trace("--HOLDINGS: " + _securityProvider[args.Symbol]);
// update order mapping
var order = _orderProvider.GetOrderById(args.OrderId);
order.Status = args.Status;
}
};
return brokerage;
}
internal static Security CreateSecurity(Symbol symbol)
{
return new Security(
SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork),
new SubscriptionDataConfig(
typeof(TradeBar),
symbol,
Resolution.Minute,
TimeZones.NewYork,
TimeZones.NewYork,
false,
false,
false
),
new Cash(CashBook.AccountCurrency, 0, 1m),
SymbolProperties.GetDefault(CashBook.AccountCurrency),
ErrorCurrencyConverter.Instance
);
}
public OrderProvider OrderProvider
{
get { return _orderProvider ?? (_orderProvider = new OrderProvider()); }
}
public SecurityProvider SecurityProvider
{
get { return _securityProvider ?? (_securityProvider = new SecurityProvider()); }
}
/// <summary>
/// Creates the brokerage under test and connects it
/// </summary>
/// <returns>A connected brokerage instance</returns>
protected abstract IBrokerage CreateBrokerage(IOrderProvider orderProvider, ISecurityProvider securityProvider);
/// <summary>
/// Disposes of the brokerage and any external resources started in order to create it
/// </summary>
/// <param name="brokerage">The brokerage instance to be disposed of</param>
protected virtual void DisposeBrokerage(IBrokerage brokerage)
{
}
/// <summary>
/// This is used to ensure each test starts with a clean, known state.
/// </summary>
protected void LiquidateHoldings()
{
Log.Trace("");
Log.Trace("LIQUIDATE HOLDINGS");
Log.Trace("");
var holdings = Brokerage.GetAccountHoldings();
foreach (var holding in holdings)
{
if (holding.Quantity == 0) continue;
Log.Trace("Liquidating: " + holding);
var order = new MarketOrder(holding.Symbol, -holding.Quantity, DateTime.UtcNow);
_orderProvider.Add(order);
PlaceOrderWaitForStatus(order, OrderStatus.Filled);
}
}
protected void CancelOpenOrders()
{
Log.Trace("");
Log.Trace("CANCEL OPEN ORDERS");
Log.Trace("");
var openOrders = Brokerage.GetOpenOrders();
foreach (var openOrder in openOrders)
{
Log.Trace("Canceling: " + openOrder);
Brokerage.CancelOrder(openOrder);
}
}
#endregion
/// <summary>
/// Gets the symbol to be traded, must be shortable
/// </summary>
protected abstract Symbol Symbol { get; }
/// <summary>
/// Gets the security type associated with the <see cref="Symbol"/>
/// </summary>
protected abstract SecurityType SecurityType { get; }
/// <summary>
/// Gets a high price for the specified symbol so a limit sell won't fill
/// </summary>
protected abstract decimal HighPrice { get; }
/// <summary>
/// Gets a low price for the specified symbol so a limit buy won't fill
/// </summary>
protected abstract decimal LowPrice { get; }
/// <summary>
/// Returns whether or not the brokers order methods implementation are async
/// </summary>
protected abstract bool IsAsync();
/// <summary>
/// Returns whether or not the brokers order cancel method implementation is async
/// </summary>
protected virtual bool IsCancelAsync()
{
return IsAsync();
}
/// <summary>
/// Gets the current market price of the specified security
/// </summary>
protected abstract decimal GetAskPrice(Symbol symbol);
/// <summary>
/// Gets the default order quantity
/// </summary>
protected virtual decimal GetDefaultQuantity()
{
return 1;
}
[Test]
public void IsConnected()
{
Assert.IsTrue(Brokerage.IsConnected);
}
[Test, TestCaseSource("OrderParameters")]
public void CancelOrders(OrderTestParameters parameters)
{
const int secondsTimeout = 20;
Log.Trace("");
Log.Trace("CANCEL ORDERS");
Log.Trace("");
var order = PlaceOrderWaitForStatus(parameters.CreateLongOrder(GetDefaultQuantity()), parameters.ExpectedStatus);
var canceledOrderStatusEvent = new ManualResetEvent(false);
EventHandler<OrderEvent> orderStatusCallback = (sender, fill) =>
{
if (fill.Status == OrderStatus.Canceled)
{
canceledOrderStatusEvent.Set();
}
};
Brokerage.OrderStatusChanged += orderStatusCallback;
var cancelResult = false;
try
{
cancelResult = Brokerage.CancelOrder(order);
}
catch (Exception exception)
{
Log.Error(exception);
}
Assert.AreEqual(IsCancelAsync() || parameters.ExpectedCancellationResult, cancelResult);
if (parameters.ExpectedCancellationResult)
{
// We expect the OrderStatus.Canceled event
canceledOrderStatusEvent.WaitOneAssertFail(1000 * secondsTimeout, "Order timedout to cancel");
}
var openOrders = Brokerage.GetOpenOrders();
var cancelledOrder = openOrders.FirstOrDefault(x => x.Id == order.Id);
Assert.IsNull(cancelledOrder);
canceledOrderStatusEvent.Reset();
var cancelResultSecondTime = false;
try
{
cancelResultSecondTime = Brokerage.CancelOrder(order);
}
catch (Exception exception)
{
Log.Error(exception);
}
Assert.AreEqual(IsCancelAsync(), cancelResultSecondTime);
// We do NOT expect the OrderStatus.Canceled event
Assert.IsFalse(canceledOrderStatusEvent.WaitOne(new TimeSpan(0, 0, 10)));
Brokerage.OrderStatusChanged -= orderStatusCallback;
}
[Test, TestCaseSource("OrderParameters")]
public void LongFromZero(OrderTestParameters parameters)
{
Log.Trace("");
Log.Trace("LONG FROM ZERO");
Log.Trace("");
PlaceOrderWaitForStatus(parameters.CreateLongOrder(GetDefaultQuantity()), parameters.ExpectedStatus);
}
[Test, TestCaseSource("OrderParameters")]
public void CloseFromLong(OrderTestParameters parameters)
{
Log.Trace("");
Log.Trace("CLOSE FROM LONG");
Log.Trace("");
// first go long
PlaceOrderWaitForStatus(parameters.CreateLongMarketOrder(GetDefaultQuantity()), OrderStatus.Filled);
// now close it
PlaceOrderWaitForStatus(parameters.CreateShortOrder(GetDefaultQuantity()), parameters.ExpectedStatus);
}
[Test, TestCaseSource("OrderParameters")]
public virtual void ShortFromZero(OrderTestParameters parameters)
{
Log.Trace("");
Log.Trace("SHORT FROM ZERO");
Log.Trace("");
PlaceOrderWaitForStatus(parameters.CreateShortOrder(GetDefaultQuantity()), parameters.ExpectedStatus);
}
[Test, TestCaseSource("OrderParameters")]
public virtual void CloseFromShort(OrderTestParameters parameters)
{
Log.Trace("");
Log.Trace("CLOSE FROM SHORT");
Log.Trace("");
// first go short
PlaceOrderWaitForStatus(parameters.CreateShortMarketOrder(GetDefaultQuantity()), OrderStatus.Filled);
// now close it
PlaceOrderWaitForStatus(parameters.CreateLongOrder(GetDefaultQuantity()), parameters.ExpectedStatus);
}
[Test, TestCaseSource("OrderParameters")]
public virtual void ShortFromLong(OrderTestParameters parameters)
{
Log.Trace("");
Log.Trace("SHORT FROM LONG");
Log.Trace("");
// first go long
PlaceOrderWaitForStatus(parameters.CreateLongMarketOrder(GetDefaultQuantity()));
// now go net short
var order = PlaceOrderWaitForStatus(parameters.CreateShortOrder(2 * GetDefaultQuantity()), parameters.ExpectedStatus);
if (parameters.ModifyUntilFilled)
{
ModifyOrderUntilFilled(order, parameters);
}
}
[Test, TestCaseSource("OrderParameters")]
public virtual void LongFromShort(OrderTestParameters parameters)
{
Log.Trace("");
Log.Trace("LONG FROM SHORT");
Log.Trace("");
// first fo short
PlaceOrderWaitForStatus(parameters.CreateShortMarketOrder(-GetDefaultQuantity()), OrderStatus.Filled);
// now go long
var order = PlaceOrderWaitForStatus(parameters.CreateLongOrder(2 * GetDefaultQuantity()), parameters.ExpectedStatus);
if (parameters.ModifyUntilFilled)
{
ModifyOrderUntilFilled(order, parameters);
}
}
[Test]
public void GetCashBalanceContainsUSD()
{
Log.Trace("");
Log.Trace("GET CASH BALANCE");
Log.Trace("");
var balance = Brokerage.GetCashBalance();
Assert.AreEqual(1, balance.Count(x => x.Symbol == "USD"));
}
[Test]
public void GetAccountHoldings()
{
Log.Trace("");
Log.Trace("GET ACCOUNT HOLDINGS");
Log.Trace("");
var before = Brokerage.GetAccountHoldings();
PlaceOrderWaitForStatus(new MarketOrder(Symbol, GetDefaultQuantity(), DateTime.UtcNow));
Thread.Sleep(3000);
var after = Brokerage.GetAccountHoldings();
var beforeHoldings = before.FirstOrDefault(x => x.Symbol == Symbol);
var afterHoldings = after.FirstOrDefault(x => x.Symbol == Symbol);
var beforeQuantity = beforeHoldings == null ? 0 : beforeHoldings.Quantity;
var afterQuantity = afterHoldings == null ? 0 : afterHoldings.Quantity;
Assert.AreEqual(GetDefaultQuantity(), afterQuantity - beforeQuantity);
}
[Test, Ignore("This test requires reading the output and selection of a low volume security for the Brokerage")]
public void PartialFills()
{
var manualResetEvent = new ManualResetEvent(false);
var qty = 1000000m;
var remaining = qty;
var sync = new object();
Brokerage.OrderStatusChanged += (sender, orderEvent) =>
{
lock (sync)
{
remaining -= orderEvent.FillQuantity;
Console.WriteLine("Remaining: " + remaining + " FillQuantity: " + orderEvent.FillQuantity);
if (orderEvent.Status == OrderStatus.Filled)
{
manualResetEvent.Set();
}
}
};
// pick a security with low, but some, volume
var symbol = Symbols.EURUSD;
var order = new MarketOrder(symbol, qty, DateTime.UtcNow) { Id = 1 };
OrderProvider.Add(order);
Brokerage.PlaceOrder(order);
// pause for a while to wait for fills to come in
manualResetEvent.WaitOne(2500);
manualResetEvent.WaitOne(2500);
manualResetEvent.WaitOne(2500);
Console.WriteLine("Remaining: " + remaining);
Assert.AreEqual(0, remaining);
}
/// <summary>
/// Updates the specified order in the brokerage until it fills or reaches a timeout
/// </summary>
/// <param name="order">The order to be modified</param>
/// <param name="parameters">The order test parameters that define how to modify the order</param>
/// <param name="secondsTimeout">Maximum amount of time to wait until the order fills</param>
protected virtual void ModifyOrderUntilFilled(Order order, OrderTestParameters parameters, double secondsTimeout = 90)
{
if (order.Status == OrderStatus.Filled)
{
return;
}
var filledResetEvent = new ManualResetEvent(false);
EventHandler<OrderEvent> brokerageOnOrderStatusChanged = (sender, args) =>
{
if (args.Status == OrderStatus.Filled)
{
filledResetEvent.Set();
}
if (args.Status == OrderStatus.Canceled || args.Status == OrderStatus.Invalid)
{
Log.Trace("ModifyOrderUntilFilled(): " + order);
Assert.Fail("Unexpected order status: " + args.Status);
}
};
Brokerage.OrderStatusChanged += brokerageOnOrderStatusChanged;
Log.Trace("");
Log.Trace("MODIFY UNTIL FILLED: " + order);
Log.Trace("");
var stopwatch = Stopwatch.StartNew();
while (!filledResetEvent.WaitOne(3000) && stopwatch.Elapsed.TotalSeconds < secondsTimeout)
{
filledResetEvent.Reset();
if (order.Status == OrderStatus.PartiallyFilled) continue;
var marketPrice = GetAskPrice(order.Symbol);
Log.Trace("BrokerageTests.ModifyOrderUntilFilled(): Ask: " + marketPrice);
var updateOrder = parameters.ModifyOrderToFill(Brokerage, order, marketPrice);
if (updateOrder)
{
if (order.Status == OrderStatus.Filled) break;
Log.Trace("BrokerageTests.ModifyOrderUntilFilled(): " + order);
if (!Brokerage.UpdateOrder(order))
{
Assert.Fail("Brokerage failed to update the order");
}
}
}
Brokerage.OrderStatusChanged -= brokerageOnOrderStatusChanged;
}
/// <summary>
/// Places the specified order with the brokerage and wait until we get the <paramref name="expectedStatus"/> back via an OrderStatusChanged event.
/// This function handles adding the order to the <see cref="IOrderProvider"/> instance as well as incrementing the order ID.
/// </summary>
/// <param name="order">The order to be submitted</param>
/// <param name="expectedStatus">The status to wait for</param>
/// <param name="secondsTimeout">Maximum amount of time to wait for <paramref name="expectedStatus"/></param>
/// <param name="allowFailedSubmission">Allow failed order submission</param>
/// <returns>The same order that was submitted.</returns>
protected Order PlaceOrderWaitForStatus(Order order, OrderStatus expectedStatus = OrderStatus.Filled,
double secondsTimeout = 10.0, bool allowFailedSubmission = false)
{
var requiredStatusEvent = new ManualResetEvent(false);
var desiredStatusEvent = new ManualResetEvent(false);
EventHandler<OrderEvent> brokerageOnOrderStatusChanged = (sender, args) =>
{
// no matter what, every order should fire at least one of these
if (args.Status == OrderStatus.Submitted || args.Status == OrderStatus.Invalid)
{
Log.Trace("");
Log.Trace("SUBMITTED: " + args);
Log.Trace("");
requiredStatusEvent.Set();
}
// make sure we fire the status we're expecting
if (args.Status == expectedStatus)
{
Log.Trace("");
Log.Trace("EXPECTED: " + args);
Log.Trace("");
desiredStatusEvent.Set();
}
};
Brokerage.OrderStatusChanged += brokerageOnOrderStatusChanged;
OrderProvider.Add(order);
if (!Brokerage.PlaceOrder(order) && !allowFailedSubmission)
{
Assert.Fail("Brokerage failed to place the order: " + order);
}
// This is due to IB simulating stop orders https://www.interactivebrokers.com/en/trading/orders/stop.php
// which causes the Status.Submitted order event to never be set
bool assertOrderEventStatus = !(Brokerage.Name == "Interactive Brokers Brokerage"
&& new[] { OrderType.StopMarket, OrderType.StopLimit }.Contains(order.Type));
if (assertOrderEventStatus)
{
requiredStatusEvent.WaitOneAssertFail((int)(1000 * secondsTimeout), "Expected every order to fire a submitted or invalid status event");
desiredStatusEvent.WaitOneAssertFail((int)(1000 * secondsTimeout), "OrderStatus " + expectedStatus + " was not encountered within the timeout. Order Id:" + order.Id);
}
else
{
requiredStatusEvent.WaitOne((int)(1000 * secondsTimeout));
}
Brokerage.OrderStatusChanged -= brokerageOnOrderStatusChanged;
return order;
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Globalization;
using System.Text.RegularExpressions;
// https://github.com/dotnet/roslyn/blob/master/src/Compilers/Core/MSBuildTask/CanonicalError.cs
namespace Microsoft.DotNet.Tools.Compiler
{
/// <summary>
/// Functions for dealing with the specially formatted errors returned by
/// build tools.
/// </summary>
/// <remarks>
/// Various tools produce and consume CanonicalErrors in various formats.
///
/// DEVENV Format When Clicking on Items in the Output Window
/// (taken from env\msenv\core\findutil.cpp ParseLocation function)
///
/// v:\dir\file.ext (loc) : msg
/// \\server\share\dir\file.ext(loc):msg
/// url
///
/// loc:
/// (line)
/// (line-line)
/// (line,col)
/// (line,col-col)
/// (line,col,len)
/// (line,col,line,col)
///
/// DevDiv Build Process
/// (taken from tools\devdiv2.def)
///
/// To echo warnings and errors to the build console, the
/// "description block" must be recognized by build. To do this,
/// add a $(ECHO_COMPILING_COMMAND) or $(ECHO_PROCESSING_COMMAND)
/// to the first line of the description block, e.g.
///
/// $(ECHO_COMPILING_CMD) Resgen_$<
///
/// Errors must have the format:
///
/// <text> : error [num]: <msg>
///
/// Warnings must have the format:
///
/// <text> : warning [num]: <msg>
/// </remarks>
/// <owner>JomoF</owner>
internal static class CanonicalError
{
// Defines the main pattern for matching messages.
private static readonly Regex s_originCategoryCodeTextExpression = new Regex
(
// Beginning of line and any amount of whitespace.
@"^\s*"
// Match a [optional project number prefix 'ddd>'], single letter + colon + remaining filename, or
// string with no colon followed by a colon.
+ @"(((?<ORIGIN>(((\d+>)?[a-zA-Z]?:[^:]*)|([^:]*))):)"
// Origin may also be empty. In this case there's no trailing colon.
+ "|())"
// Match the empty string or a string without a colon that ends with a space
+ "(?<SUBCATEGORY>(()|([^:]*? )))"
// Match 'error' or 'warning'.
+ @"(?<CATEGORY>(error|warning))"
// Match anything starting with a space that's not a colon/space, followed by a colon.
// Error code is optional in which case "error"/"warning" can be followed immediately by a colon.
+ @"( \s*(?<CODE>[^: ]*))?\s*:"
// Whatever's left on this line, including colons.
+ "(?<TEXT>.*)$",
RegexOptions.IgnoreCase
);
// Matches and extracts filename and location from an 'origin' element.
private static readonly Regex s_filenameLocationFromOrigin = new Regex
(
"^" // Beginning of line
+ @"(\d+>)?" // Optional ddd> project number prefix
+ "(?<FILENAME>.*)" // Match anything.
+ @"\(" // Find a parenthesis.
+ @"(?<LOCATION>[\,,0-9,-]*)" // Match any combination of numbers and ',' and '-'
+ @"\)\s*" // Find the closing paren then any amount of spaces.
+ "$", // End-of-line
RegexOptions.IgnoreCase
);
// Matches location that is a simple number.
private static readonly Regex s_lineFromLocation = new Regex // Example: line
(
"^" // Beginning of line
+ "(?<LINE>[0-9]*)" // Match any number.
+ "$", // End-of-line
RegexOptions.IgnoreCase
);
// Matches location that is a range of lines.
private static readonly Regex s_lineLineFromLocation = new Regex // Example: line-line
(
"^" // Beginning of line
+ "(?<LINE>[0-9]*)" // Match any number.
+ "-" // Dash
+ "(?<ENDLINE>[0-9]*)" // Match any number.
+ "$", // End-of-line
RegexOptions.IgnoreCase
);
// Matches location that is a line and column
private static readonly Regex s_lineColFromLocation = new Regex // Example: line,col
(
"^" // Beginning of line
+ "(?<LINE>[0-9]*)" // Match any number.
+ "," // Comma
+ "(?<COLUMN>[0-9]*)" // Match any number.
+ "$", // End-of-line
RegexOptions.IgnoreCase
);
// Matches location that is a line and column-range
private static readonly Regex s_lineColColFromLocation = new Regex // Example: line,col-col
(
"^" // Beginning of line
+ "(?<LINE>[0-9]*)" // Match any number.
+ "," // Comma
+ "(?<COLUMN>[0-9]*)" // Match any number.
+ "-" // Dash
+ "(?<ENDCOLUMN>[0-9]*)" // Match any number.
+ "$", // End-of-line
RegexOptions.IgnoreCase
);
// Matches location that is line,col,line,col
private static readonly Regex s_lineColLineColFromLocation = new Regex // Example: line,col,line,col
(
"^" // Beginning of line
+ "(?<LINE>[0-9]*)" // Match any number.
+ "," // Comma
+ "(?<COLUMN>[0-9]*)" // Match any number.
+ "," // Dash
+ "(?<ENDLINE>[0-9]*)" // Match any number.
+ "," // Dash
+ "(?<ENDCOLUMN>[0-9]*)" // Match any number.
+ "$", // End-of-line
RegexOptions.IgnoreCase
);
/// <summary>
/// Represents the parts of a decomposed canonical message.
/// </summary>
/// <owner>JomoF</owner>
internal sealed class Parts
{
/// <summary>
/// Defines the error category\severity level.
/// </summary>
internal enum Category
{
Warning,
Error
}
/// <summary>
/// Value used for unspecified line and column numbers, which are 1-relative.
/// </summary>
internal const int numberNotSpecified = 0;
/// <summary>
/// Initializes a new instance of the <see cref="Parts"/> class.
/// </summary>
internal Parts()
{
}
/// <summary>
/// Name of the file or tool (not localized)
/// </summary>
internal string origin;
/// <summary>
/// The line number.
/// </summary>
internal int line = Parts.numberNotSpecified;
/// <summary>
/// The column number.
/// </summary>
internal int column = Parts.numberNotSpecified;
/// <summary>
/// The ending line number.
/// </summary>
internal int endLine = Parts.numberNotSpecified;
/// <summary>
/// The ending column number.
/// </summary>
internal int endColumn = Parts.numberNotSpecified;
/// <summary>
/// The category/severity level
/// </summary>
internal Category category;
/// <summary>
/// The sub category (localized)
/// </summary>
internal string subcategory;
/// <summary>
/// The error code (not localized)
/// </summary>
internal string code;
/// <summary>
/// The error message text (localized)
/// </summary>
internal string text;
#if NEVER
internal new string ToString()
{
return String.Format
(
"Origin='{0}'\n"
+"Filename='{1}'\n"
+"Line='{2}'\n"
+"Column='{3}'\n"
+"EndLine='{4}'\n"
+"EndColumn='{5}'\n"
+"Category='{6}'\n"
+"Subcategory='{7}'\n"
+"Text='{8}'\n"
, origin, line, column, endLine, endColumn, category.ToString(), subcategory, code, text
);
}
#endif
}
/// <summary>
/// A small custom int conversion method that treats invalid entries as missing (0). This is done to work around tools
/// that don't fully conform to the canonical message format - we still want to salvage what we can from the message.
/// </summary>
/// <param name="value"></param>
/// <returns>'value' converted to int or 0 if it can't be parsed or is negative</returns>
/// <owner>LukaszG</owner>
private static int ConvertToIntWithDefault(string value)
{
int result;
bool success = int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out result);
if (!success || (result < 0))
{
result = CanonicalError.Parts.numberNotSpecified;
}
return result;
}
/// <summary>
/// Decompose an error or warning message into constituent parts. If the message isn't in the canonical form, return null.
/// </summary>
/// <remarks>This method is thread-safe, because the Regex class is thread-safe (per MSDN).</remarks>
/// <owner>JomoF</owner>
/// <param name="message"></param>
/// <returns>Decomposed canonical message, or null.</returns>
internal static Parts Parse(string message)
{
// An unusually long string causes pathologically slow Regex back-tracking.
// To avoid that, only scan the first 400 characters. That's enough for
// the longest possible prefix: MAX_PATH, plus a huge subcategory string, and an error location.
// After the regex is done, we can append the overflow.
string messageOverflow = String.Empty;
if (message.Length > 400)
{
messageOverflow = message.Substring(400);
message = message.Substring(0, 400);
}
// If a tool has a large amount of output that isn't an error or warning (eg., "dir /s %hugetree%")
// the regex below is slow. It's faster to pre-scan for "warning" and "error"
// and bail out if neither are present.
if (message.IndexOf("warning", StringComparison.OrdinalIgnoreCase) == -1 &&
message.IndexOf("error", StringComparison.OrdinalIgnoreCase) == -1)
{
return null;
}
Parts parsedMessage = new Parts();
// First, split the message into three parts--Origin, Category, Code, Text.
// Example,
// Main.cs(17,20):Command line warning CS0168: The variable 'foo' is declared but never used
// -------------- ------------ ------- ------ ----------------------------------------------
// Origin SubCategory Cat. Code Text
//
// To accommodate absolute filenames in Origin, tolerate a colon in the second position
// as long as its preceded by a letter.
//
// Localization Note:
// Even in foreign-language versions of tools, the category field needs to be in English.
// Also, if origin is a tool name, then that needs to be in English.
//
// Here's an example from the Japanese version of CL.EXE:
// cl : ???? ??? warning D4024 : ?????????? 'AssemblyInfo.cs' ?????????????????? ???????????
//
// Here's an example from the Japanese version of LINK.EXE:
// AssemblyInfo.cpp : fatal error LNK1106: ???????????? ??????????????: 0x6580 ??????????
//
Match match = s_originCategoryCodeTextExpression.Match(message);
if (!match.Success)
{
// If no match here, then this message is not an error or warning.
return null;
}
string origin = match.Groups["ORIGIN"].Value.Trim();
string category = match.Groups["CATEGORY"].Value.Trim();
parsedMessage.code = match.Groups["CODE"].Value.Trim();
parsedMessage.text = (match.Groups["TEXT"].Value + messageOverflow).Trim();
parsedMessage.subcategory = match.Groups["SUBCATEGORY"].Value.Trim();
// Next, see if category is something that is recognized.
if (0 == String.Compare(category, "error", StringComparison.OrdinalIgnoreCase))
{
parsedMessage.category = Parts.Category.Error;
}
else if (0 == String.Compare(category, "warning", StringComparison.OrdinalIgnoreCase))
{
parsedMessage.category = Parts.Category.Warning;
}
else
{
// Not an error\warning message.
return null;
}
// Origin is not a simple file, but it still could be of the form,
// foo.cpp(location)
match = s_filenameLocationFromOrigin.Match(origin);
if (match.Success)
{
// The origin is in the form,
// foo.cpp(location)
// Assume the filename exists, but don't verify it. What else could it be?
string location = match.Groups["LOCATION"].Value.Trim();
parsedMessage.origin = match.Groups["FILENAME"].Value.Trim();
// Now, take apart the location. It can be one of these:
// loc:
// (line)
// (line-line)
// (line,col)
// (line,col-col)
// (line,col,len)
// (line,col,line,col)
if (location.Length > 0)
{
match = s_lineFromLocation.Match(location);
if (match.Success)
{
parsedMessage.line = ConvertToIntWithDefault(match.Groups["LINE"].Value.Trim());
}
else
{
match = s_lineLineFromLocation.Match(location);
if (match.Success)
{
parsedMessage.line = ConvertToIntWithDefault(match.Groups["LINE"].Value.Trim());
parsedMessage.endLine = ConvertToIntWithDefault(match.Groups["ENDLINE"].Value.Trim());
}
else
{
match = s_lineColFromLocation.Match(location);
if (match.Success)
{
parsedMessage.line = ConvertToIntWithDefault(match.Groups["LINE"].Value.Trim());
parsedMessage.column = ConvertToIntWithDefault(match.Groups["COLUMN"].Value.Trim());
}
else
{
match = s_lineColColFromLocation.Match(location);
if (match.Success)
{
parsedMessage.line = ConvertToIntWithDefault(match.Groups["LINE"].Value.Trim());
parsedMessage.column = ConvertToIntWithDefault(match.Groups["COLUMN"].Value.Trim());
parsedMessage.endColumn = ConvertToIntWithDefault(match.Groups["ENDCOLUMN"].Value.Trim());
}
else
{
match = s_lineColLineColFromLocation.Match(location);
if (match.Success)
{
parsedMessage.line = ConvertToIntWithDefault(match.Groups["LINE"].Value.Trim());
parsedMessage.column = ConvertToIntWithDefault(match.Groups["COLUMN"].Value.Trim());
parsedMessage.endLine = ConvertToIntWithDefault(match.Groups["ENDLINE"].Value.Trim());
parsedMessage.endColumn = ConvertToIntWithDefault(match.Groups["ENDCOLUMN"].Value.Trim());
}
}
}
}
}
}
}
else
{
// The origin does not fit the filename(location) pattern.
parsedMessage.origin = origin;
}
return parsedMessage;
}
}
}
| |
// 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.Collections.Specialized;
using System.Diagnostics;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace System.Collections.ObjectModel
{
/// <summary>
/// Implementation of a dynamic data collection based on generic Collection<T>,
/// implementing INotifyCollectionChanged to notify listeners
/// when items get added, removed or the whole list is refreshed.
/// </summary>
[DebuggerTypeProxy(typeof(CollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
public class ObservableCollection<T> : Collection<T>, INotifyCollectionChanged, INotifyPropertyChanged
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
/// <summary>
/// Initializes a new instance of ObservableCollection that is empty and has default initial capacity.
/// </summary>
public ObservableCollection() : base() { }
/// <summary>
/// Initializes a new instance of the ObservableCollection class that contains
/// elements copied from the specified collection and has sufficient capacity
/// to accommodate the number of elements copied.
/// </summary>
/// <param name="collection">The collection whose elements are copied to the new list.</param>
/// <remarks>
/// The elements are copied onto the ObservableCollection in the
/// same order they are read by the enumerator of the collection.
/// </remarks>
/// <exception cref="ArgumentNullException"> collection is a null reference </exception>
public ObservableCollection(IEnumerable<T> collection) : base(CreateCopy(collection)) { }
private static List<T> CreateCopy(IEnumerable<T> collection)
{
if (collection == null)
throw new ArgumentNullException("collection");
return new List<T>(collection);
}
#endregion Constructors
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Move item at oldIndex to newIndex.
/// </summary>
public void Move(int oldIndex, int newIndex)
{
MoveItem(oldIndex, newIndex);
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Events
//
//------------------------------------------------------
#region Public Events
//------------------------------------------------------
#region INotifyPropertyChanged implementation
/// <summary>
/// PropertyChanged event (per <see cref="INotifyPropertyChanged" />).
/// </summary>
event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged
{
add
{
PropertyChanged += value;
}
remove
{
PropertyChanged -= value;
}
}
#endregion INotifyPropertyChanged implementation
//------------------------------------------------------
/// <summary>
/// Occurs when the collection changes, either by adding or removing an item.
/// </summary>
/// <remarks>
/// see <seealso cref="INotifyCollectionChanged"/>
/// </remarks>
public virtual event NotifyCollectionChangedEventHandler CollectionChanged;
#endregion Public Events
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
#region Protected Methods
/// <summary>
/// Called by base class Collection<T> when the list is being cleared;
/// raises a CollectionChanged event to any listeners.
/// </summary>
protected override void ClearItems()
{
CheckReentrancy();
base.ClearItems();
OnPropertyChanged(CountString);
OnPropertyChanged(IndexerName);
OnCollectionReset();
}
/// <summary>
/// Called by base class Collection<T> when an item is removed from list;
/// raises a CollectionChanged event to any listeners.
/// </summary>
protected override void RemoveItem(int index)
{
CheckReentrancy();
T removedItem = this[index];
base.RemoveItem(index);
OnPropertyChanged(CountString);
OnPropertyChanged(IndexerName);
OnCollectionChanged(NotifyCollectionChangedAction.Remove, removedItem, index);
}
/// <summary>
/// Called by base class Collection<T> when an item is added to list;
/// raises a CollectionChanged event to any listeners.
/// </summary>
protected override void InsertItem(int index, T item)
{
CheckReentrancy();
base.InsertItem(index, item);
OnPropertyChanged(CountString);
OnPropertyChanged(IndexerName);
OnCollectionChanged(NotifyCollectionChangedAction.Add, item, index);
}
/// <summary>
/// Called by base class Collection<T> when an item is set in list;
/// raises a CollectionChanged event to any listeners.
/// </summary>
protected override void SetItem(int index, T item)
{
CheckReentrancy();
T originalItem = this[index];
base.SetItem(index, item);
OnPropertyChanged(IndexerName);
OnCollectionChanged(NotifyCollectionChangedAction.Replace, originalItem, item, index);
}
/// <summary>
/// Called by base class ObservableCollection<T> when an item is to be moved within the list;
/// raises a CollectionChanged event to any listeners.
/// </summary>
protected virtual void MoveItem(int oldIndex, int newIndex)
{
CheckReentrancy();
T removedItem = this[oldIndex];
base.RemoveItem(oldIndex);
base.InsertItem(newIndex, removedItem);
OnPropertyChanged(IndexerName);
OnCollectionChanged(NotifyCollectionChangedAction.Move, removedItem, newIndex, oldIndex);
}
/// <summary>
/// Raises a PropertyChanged event (per <see cref="INotifyPropertyChanged" />).
/// </summary>
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != null)
{
PropertyChanged(this, e);
}
}
/// <summary>
/// PropertyChanged event (per <see cref="INotifyPropertyChanged" />).
/// </summary>
protected virtual event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Raise CollectionChanged event to any listeners.
/// Properties/methods modifying this ObservableCollection will raise
/// a collection changed event through this virtual method.
/// </summary>
/// <remarks>
/// When overriding this method, either call its base implementation
/// or call <see cref="BlockReentrancy"/> to guard against reentrant collection changes.
/// </remarks>
protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
if (CollectionChanged != null)
{
using (BlockReentrancy())
{
CollectionChanged(this, e);
}
}
}
/// <summary>
/// Disallow reentrant attempts to change this collection. E.g. a event handler
/// of the CollectionChanged event is not allowed to make changes to this collection.
/// </summary>
/// <remarks>
/// typical usage is to wrap e.g. a OnCollectionChanged call with a using() scope:
/// <code>
/// using (BlockReentrancy())
/// {
/// CollectionChanged(this, new NotifyCollectionChangedEventArgs(action, item, index));
/// }
/// </code>
/// </remarks>
protected IDisposable BlockReentrancy()
{
_monitor.Enter();
return _monitor;
}
/// <summary> Check and assert for reentrant attempts to change this collection. </summary>
/// <exception cref="InvalidOperationException"> raised when changing the collection
/// while another collection change is still being notified to other listeners </exception>
protected void CheckReentrancy()
{
if (_monitor.Busy)
{
// we can allow changes if there's only one listener - the problem
// only arises if reentrant changes make the original event args
// invalid for later listeners. This keeps existing code working
// (e.g. Selector.SelectedItems).
if ((CollectionChanged != null) && (CollectionChanged.GetInvocationList().Length > 1))
throw new InvalidOperationException(SR.ObservableCollectionReentrancyNotAllowed);
}
}
#endregion Protected Methods
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private Methods
/// <summary>
/// Helper to raise a PropertyChanged event />).
/// </summary>
private void OnPropertyChanged(string propertyName)
{
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
/// <summary>
/// Helper to raise CollectionChanged event to any listeners
/// </summary>
private void OnCollectionChanged(NotifyCollectionChangedAction action, object item, int index)
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, item, index));
}
/// <summary>
/// Helper to raise CollectionChanged event to any listeners
/// </summary>
private void OnCollectionChanged(NotifyCollectionChangedAction action, object item, int index, int oldIndex)
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, item, index, oldIndex));
}
/// <summary>
/// Helper to raise CollectionChanged event to any listeners
/// </summary>
private void OnCollectionChanged(NotifyCollectionChangedAction action, object oldItem, object newItem, int index)
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, newItem, oldItem, index));
}
/// <summary>
/// Helper to raise CollectionChanged event with action == Reset to any listeners
/// </summary>
private void OnCollectionReset()
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
#endregion Private Methods
//------------------------------------------------------
//
// Private Types
//
//------------------------------------------------------
#region Private Types
// this class helps prevent reentrant calls
private class SimpleMonitor : IDisposable
{
public void Enter()
{
++_busyCount;
}
public void Dispose()
{
--_busyCount;
}
public bool Busy { get { return _busyCount > 0; } }
private int _busyCount;
}
#endregion Private Types
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
private const string CountString = "Count";
// This must agree with Binding.IndexerName. It is declared separately
// here so as to avoid a dependency on PresentationFramework.dll.
private const string IndexerName = "Item[]";
private SimpleMonitor _monitor = new SimpleMonitor();
#endregion Private Fields
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Content.Client.Clothing;
using Content.Client.HUD;
using Content.Shared.Input;
using Content.Client.Items.Managers;
using Content.Client.Items.UI;
using Content.Shared.CCVar;
using Content.Shared.Hands.Components;
using Content.Shared.Inventory;
using Content.Shared.Inventory.Events;
using Content.Shared.Item;
using JetBrains.Annotations;
using Robust.Client.GameObjects;
using Robust.Client.UserInterface;
using Robust.Client.UserInterface.Controls;
using Robust.Client.UserInterface.CustomControls;
using Robust.Shared.Configuration;
using Robust.Shared.Containers;
using Robust.Shared.GameObjects;
using Robust.Shared.Input;
using Robust.Shared.Input.Binding;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Maths;
using Robust.Shared.Prototypes;
namespace Content.Client.Inventory
{
[UsedImplicitly]
public sealed class ClientInventorySystem : InventorySystem
{
[Dependency] private readonly IGameHud _gameHud = default!;
[Dependency] private readonly IPrototypeManager _prototypeManager = default!;
[Dependency] private readonly IConfigurationManager _config = default!;
[Dependency] private readonly IItemSlotManager _itemSlotManager = default!;
[Dependency] private readonly ClothingSystem _clothingSystem = default!;
public const int ButtonSize = 64;
private const int ButtonSeparation = 4;
private const int RightSeparation = 2;
/// <summary>
/// Stores delegates used to create controls for a given <see cref="InventoryTemplatePrototype"/>.
/// </summary>
private readonly
Dictionary<string, Func<EntityUid, Dictionary<string, List<ItemSlotButton>>, (DefaultWindow window, Control bottomLeft, Control bottomRight, Control
topQuick)>>
_uiGenerateDelegates = new();
public override void Initialize()
{
base.Initialize();
CommandBinds.Builder
.Bind(ContentKeyFunctions.OpenInventoryMenu,
InputCmdHandler.FromDelegate(_ => HandleOpenInventoryMenu()))
.Register<ClientInventorySystem>();
SubscribeLocalEvent<ClientInventoryComponent, PlayerAttachedEvent>(OnPlayerAttached);
SubscribeLocalEvent<ClientInventoryComponent, PlayerDetachedEvent>(OnPlayerDetached);
SubscribeLocalEvent<ClientInventoryComponent, ComponentInit>(OnInit);
SubscribeLocalEvent<ClientInventoryComponent, ComponentShutdown>(OnShutdown);
SubscribeLocalEvent<ClientInventoryComponent, DidEquipEvent>(OnDidEquip);
SubscribeLocalEvent<ClientInventoryComponent, DidUnequipEvent>(OnDidUnequip);
_config.OnValueChanged(CCVars.HudTheme, UpdateHudTheme);
}
private void OnDidUnequip(EntityUid uid, ClientInventoryComponent component, DidUnequipEvent args)
{
UpdateComponentUISlot(uid, args.Slot, null, component);
}
private void OnDidEquip(EntityUid uid, ClientInventoryComponent component, DidEquipEvent args)
{
UpdateComponentUISlot(uid, args.Slot, args.Equipment, component);
}
private void UpdateComponentUISlot(EntityUid uid, string slot, EntityUid? item, ClientInventoryComponent? component = null)
{
if (!Resolve(uid, ref component))
return;
if (!component.SlotButtons.TryGetValue(slot, out var buttons))
return;
UpdateUISlot(buttons, item);
}
private void UpdateUISlot(List<ItemSlotButton> buttons, EntityUid? entity)
{
foreach (var button in buttons)
{
_itemSlotManager.SetItemSlot(button, entity);
}
}
private void OnPlayerDetached(EntityUid uid, ClientInventoryComponent component, PlayerDetachedEvent? args = null)
{
if(!component.AttachedToGameHud) return;
_gameHud.InventoryButtonVisible = false;
_gameHud.BottomLeftInventoryQuickButtonContainer.RemoveChild(component.BottomLeftButtons);
_gameHud.BottomRightInventoryQuickButtonContainer.RemoveChild(component.BottomRightButtons);
_gameHud.TopInventoryQuickButtonContainer.RemoveChild(component.TopQuickButtons);
component.AttachedToGameHud = false;
}
private void OnShutdown(EntityUid uid, ClientInventoryComponent component, ComponentShutdown args)
{
OnPlayerDetached(uid, component);
}
private void OnPlayerAttached(EntityUid uid, ClientInventoryComponent component, PlayerAttachedEvent args)
{
if(component.AttachedToGameHud) return;
_gameHud.InventoryButtonVisible = true;
_gameHud.BottomLeftInventoryQuickButtonContainer.AddChild(component.BottomLeftButtons);
_gameHud.BottomRightInventoryQuickButtonContainer.AddChild(component.BottomRightButtons);
_gameHud.TopInventoryQuickButtonContainer.AddChild(component.TopQuickButtons);
component.AttachedToGameHud = true;
}
private void UpdateHudTheme(int obj)
{
if (!_gameHud.ValidateHudTheme(obj))
{
return;
}
foreach (var inventoryComponent in EntityManager.EntityQuery<ClientInventoryComponent>(true))
{
foreach (var slotButton in inventoryComponent.SlotButtons)
{
foreach (var btn in slotButton.Value)
{
btn.RefreshTextures(_gameHud);
}
}
}
}
public override void Shutdown()
{
CommandBinds.Unregister<ClientInventorySystem>();
_config.UnsubValueChanged(CCVars.HudTheme, UpdateHudTheme);
base.Shutdown();
}
private void OnInit(EntityUid uid, ClientInventoryComponent component, ComponentInit args)
{
_clothingSystem.InitClothing(uid, component);
if (!TryGetUIElements(uid, out var window, out var bottomLeft, out var bottomRight, out var topQuick,
component))
return;
if (TryComp<ContainerManagerComponent>(uid, out var containerManager))
{
foreach (var (slot, buttons) in component.SlotButtons)
{
if (!TryGetSlotEntity(uid, slot, out var entity, component, containerManager))
continue;
UpdateUISlot(buttons, entity);
}
}
component.InventoryWindow = window;
component.BottomLeftButtons = bottomLeft;
component.BottomRightButtons = bottomRight;
component.TopQuickButtons = topQuick;
}
private void HoverInSlotButton(EntityUid uid, string slot, ItemSlotButton button, InventoryComponent? inventoryComponent = null, SharedHandsComponent? hands = null)
{
if (!Resolve(uid, ref inventoryComponent))
return;
if (!Resolve(uid, ref hands, false))
return;
if (!hands.TryGetActiveHeldEntity(out var heldEntity))
return;
if(!TryGetSlotContainer(uid, slot, out var containerSlot, out var slotDef, inventoryComponent))
return;
_itemSlotManager.HoverInSlot(button, heldEntity.Value,
CanEquip(uid, heldEntity.Value, slot, out _, slotDef, inventoryComponent) &&
containerSlot.CanInsert(heldEntity.Value, EntityManager));
}
private void HandleSlotButtonPressed(EntityUid uid, string slot, ItemSlotButton button,
GUIBoundKeyEventArgs args)
{
if (TryGetSlotEntity(uid, slot, out var itemUid) && _itemSlotManager.OnButtonPressed(args, itemUid.Value))
return;
if (args.Function != EngineKeyFunctions.UIClick)
return;
// only raise event if either itemUid is not null, or the user is holding something
if (itemUid != null || TryComp(uid, out SharedHandsComponent? hands) && hands.TryGetActiveHeldEntity(out _))
EntityManager.RaisePredictiveEvent(new UseSlotNetworkMessage(slot));
}
private bool TryGetUIElements(EntityUid uid, [NotNullWhen(true)] out DefaultWindow? invWindow,
[NotNullWhen(true)] out Control? invBottomLeft, [NotNullWhen(true)] out Control? invBottomRight,
[NotNullWhen(true)] out Control? invTopQuick, ClientInventoryComponent? component = null)
{
invWindow = null;
invBottomLeft = null;
invBottomRight = null;
invTopQuick = null;
if (!Resolve(uid, ref component))
return false;
if(!_prototypeManager.TryIndex<InventoryTemplatePrototype>(component.TemplateId, out var template))
return false;
if (!_uiGenerateDelegates.TryGetValue(component.TemplateId, out var genfunc))
{
_uiGenerateDelegates[component.TemplateId] = genfunc = (entityUid, list) =>
{
var window = new DefaultWindow()
{
Title = Loc.GetString("human-inventory-window-title"),
Resizable = false
};
window.OnClose += () =>
{
_gameHud.InventoryButtonDown = false;
_gameHud.TopInventoryQuickButtonContainer.Visible = false;
};
var windowContents = new LayoutContainer
{
MinSize = (ButtonSize * 4 + ButtonSeparation * 3 + RightSeparation,
ButtonSize * 4 + ButtonSeparation * 3)
};
window.Contents.AddChild(windowContents);
ItemSlotButton GetButton(SlotDefinition definition, string textureBack)
{
var btn = new ItemSlotButton(ButtonSize, $"{definition.TextureName}.png", textureBack,
_gameHud)
{
OnStoragePressed = (e) =>
{
if (e.Function != EngineKeyFunctions.UIClick &&
e.Function != ContentKeyFunctions.ActivateItemInWorld)
return;
RaiseNetworkEvent(new OpenSlotStorageNetworkMessage(definition.Name));
}
};
btn.OnHover = (_) =>
{
HoverInSlotButton(entityUid, definition.Name, btn);
};
btn.OnPressed = (e) =>
{
HandleSlotButtonPressed(entityUid, definition.Name, btn, e);
};
return btn;
}
void AddButton(SlotDefinition definition, Vector2i position)
{
var button = GetButton(definition, "back.png");
LayoutContainer.SetPosition(button, position);
windowContents.AddChild(button);
if (!list.ContainsKey(definition.Name))
list[definition.Name] = new();
list[definition.Name].Add(button);
}
void AddHUDButton(BoxContainer container, SlotDefinition definition)
{
var button = GetButton(definition, "back.png");
container.AddChild(button);
if (!list.ContainsKey(definition.Name))
list[definition.Name] = new();
list[definition.Name].Add(button);
}
var topQuick = new BoxContainer
{
Orientation = BoxContainer.LayoutOrientation.Horizontal,
SeparationOverride = 5
};
var bottomRight = new BoxContainer
{
Orientation = BoxContainer.LayoutOrientation.Horizontal,
SeparationOverride = 5
};
var bottomLeft = new BoxContainer
{
Orientation = BoxContainer.LayoutOrientation.Horizontal,
SeparationOverride = 5
};
const int sizep = (ButtonSize + ButtonSeparation);
foreach (var slotDefinition in template.Slots)
{
switch (slotDefinition.UIContainer)
{
case SlotUIContainer.BottomLeft:
AddHUDButton(bottomLeft, slotDefinition);
break;
case SlotUIContainer.BottomRight:
AddHUDButton(bottomRight, slotDefinition);
break;
case SlotUIContainer.Top:
AddHUDButton(topQuick, slotDefinition);
break;
}
AddButton(slotDefinition, slotDefinition.UIWindowPosition * sizep);
}
return (window, bottomLeft, bottomRight, topQuick);
};
}
var res = genfunc(uid, component.SlotButtons);
invWindow = res.window;
invBottomLeft = res.bottomLeft;
invBottomRight = res.bottomRight;
invTopQuick = res.topQuick;
return true;
}
private void HandleOpenInventoryMenu()
{
_gameHud.InventoryButtonDown = !_gameHud.InventoryButtonDown;
_gameHud.TopInventoryQuickButtonContainer.Visible = _gameHud.InventoryButtonDown;
}
}
}
| |
using System;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.SessionState;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Configuration;
using Umbraco.Core.Models;
using Umbraco.Web.Models;
using Umbraco.Web.Routing;
using umbraco.cms.businesslogic.template;
using System.Collections.Generic;
namespace Umbraco.Web.Mvc
{
public class RenderRouteHandler : IRouteHandler
{
// Define reserved dictionary keys for controller, action and area specified in route additional values data
private static class ReservedAdditionalKeys
{
internal const string Controller = "c";
internal const string Action = "a";
internal const string Area = "ar";
}
public RenderRouteHandler(IControllerFactory controllerFactory)
{
if (controllerFactory == null) throw new ArgumentNullException("controllerFactory");
_controllerFactory = controllerFactory;
}
/// <summary>
/// Contructor generally used for unit testing
/// </summary>
/// <param name="controllerFactory"></param>
/// <param name="umbracoContext"></param>
internal RenderRouteHandler(IControllerFactory controllerFactory, UmbracoContext umbracoContext)
{
if (controllerFactory == null) throw new ArgumentNullException("controllerFactory");
if (umbracoContext == null) throw new ArgumentNullException("umbracoContext");
_controllerFactory = controllerFactory;
_umbracoContext = umbracoContext;
}
private readonly IControllerFactory _controllerFactory;
private readonly UmbracoContext _umbracoContext;
/// <summary>
/// Returns the current UmbracoContext
/// </summary>
public UmbracoContext UmbracoContext
{
get { return _umbracoContext ?? UmbracoContext.Current; }
}
#region IRouteHandler Members
/// <summary>
/// Assigns the correct controller based on the Umbraco request and returns a standard MvcHandler to prcess the response,
/// this also stores the render model into the data tokens for the current RouteData.
/// </summary>
/// <param name="requestContext"></param>
/// <returns></returns>
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
if (UmbracoContext == null)
{
throw new NullReferenceException("There is not current UmbracoContext, it must be initialized before the RenderRouteHandler executes");
}
var docRequest = UmbracoContext.PublishedContentRequest;
if (docRequest == null)
{
throw new NullReferenceException("There is not current PublishedContentRequest, it must be initialized before the RenderRouteHandler executes");
}
SetupRouteDataForRequest(
new RenderModel(docRequest.PublishedContent, docRequest.Culture),
requestContext,
docRequest);
return GetHandlerForRoute(requestContext, docRequest);
}
#endregion
/// <summary>
/// Ensures that all of the correct DataTokens are added to the route values which are all required for rendering front-end umbraco views
/// </summary>
/// <param name="renderModel"></param>
/// <param name="requestContext"></param>
/// <param name="docRequest"></param>
internal void SetupRouteDataForRequest(RenderModel renderModel, RequestContext requestContext, PublishedContentRequest docRequest)
{
//put essential data into the data tokens, the 'umbraco' key is required to be there for the view engine
requestContext.RouteData.DataTokens.Add("umbraco", renderModel); //required for the RenderModelBinder and view engine
requestContext.RouteData.DataTokens.Add("umbraco-doc-request", docRequest); //required for RenderMvcController
requestContext.RouteData.DataTokens.Add("umbraco-context", UmbracoContext); //required for UmbracoTemplatePage
}
private void UpdateRouteDataForRequest(RenderModel renderModel, RequestContext requestContext)
{
if (renderModel == null) throw new ArgumentNullException("renderModel");
if (requestContext == null) throw new ArgumentNullException("requestContext");
requestContext.RouteData.DataTokens["umbraco"] = renderModel;
// the rest should not change -- it's only the published content that has changed
}
/// <summary>
/// Checks the request and query strings to see if it matches the definition of having a Surface controller
/// posted/get value, if so, then we return a PostedDataProxyInfo object with the correct information.
/// </summary>
/// <param name="requestContext"></param>
/// <returns></returns>
private static PostedDataProxyInfo GetFormInfo(RequestContext requestContext)
{
if (requestContext == null) throw new ArgumentNullException("requestContext");
//if it is a POST/GET then a value must be in the request
if (requestContext.HttpContext.Request.QueryString["ufprt"].IsNullOrWhiteSpace()
&& requestContext.HttpContext.Request.Form["ufprt"].IsNullOrWhiteSpace())
{
return null;
}
string encodedVal;
switch (requestContext.HttpContext.Request.RequestType)
{
case "POST":
//get the value from the request.
//this field will contain an encrypted version of the surface route vals.
encodedVal = requestContext.HttpContext.Request.Form["ufprt"];
break;
case "GET":
//this field will contain an encrypted version of the surface route vals.
encodedVal = requestContext.HttpContext.Request.QueryString["ufprt"];
break;
default:
return null;
}
string decryptedString;
try
{
decryptedString = encodedVal.DecryptWithMachineKey();
}
catch (FormatException)
{
LogHelper.Warn<RenderRouteHandler>("A value was detected in the ufprt parameter but Umbraco could not decrypt the string");
return null;
}
var parsedQueryString = HttpUtility.ParseQueryString(decryptedString);
var decodedParts = new Dictionary<string, string>();
foreach (var key in parsedQueryString.AllKeys)
{
decodedParts[key] = parsedQueryString[key];
}
//validate all required keys exist
//the controller
if (decodedParts.All(x => x.Key != ReservedAdditionalKeys.Controller))
return null;
//the action
if (decodedParts.All(x => x.Key != ReservedAdditionalKeys.Action))
return null;
//the area
if (decodedParts.All(x => x.Key != ReservedAdditionalKeys.Area))
return null;
foreach (var item in decodedParts.Where(x => new[] {
ReservedAdditionalKeys.Controller,
ReservedAdditionalKeys.Action,
ReservedAdditionalKeys.Area }.Contains(x.Key) == false))
{
// Populate route with additional values which aren't reserved values so they eventually to action parameters
requestContext.RouteData.Values[item.Key] = item.Value;
}
//return the proxy info without the surface id... could be a local controller.
return new PostedDataProxyInfo
{
ControllerName = HttpUtility.UrlDecode(decodedParts.Single(x => x.Key == ReservedAdditionalKeys.Controller).Value),
ActionName = HttpUtility.UrlDecode(decodedParts.Single(x => x.Key == ReservedAdditionalKeys.Action).Value),
Area = HttpUtility.UrlDecode(decodedParts.Single(x => x.Key == ReservedAdditionalKeys.Area).Value),
};
}
/// <summary>
/// Handles a posted form to an Umbraco Url and ensures the correct controller is routed to and that
/// the right DataTokens are set.
/// </summary>
/// <param name="requestContext"></param>
/// <param name="postedInfo"></param>
private IHttpHandler HandlePostedValues(RequestContext requestContext, PostedDataProxyInfo postedInfo)
{
if (requestContext == null) throw new ArgumentNullException("requestContext");
if (postedInfo == null) throw new ArgumentNullException("postedInfo");
//set the standard route values/tokens
requestContext.RouteData.Values["controller"] = postedInfo.ControllerName;
requestContext.RouteData.Values["action"] = postedInfo.ActionName;
IHttpHandler handler;
//get the route from the defined routes
using (RouteTable.Routes.GetReadLock())
{
Route surfaceRoute;
if (postedInfo.Area.IsNullOrWhiteSpace())
{
//find the controller in the route table without an area
surfaceRoute = RouteTable.Routes.OfType<Route>()
.SingleOrDefault(x => x.Defaults != null &&
x.Defaults.ContainsKey("controller") &&
x.Defaults["controller"].ToString() == postedInfo.ControllerName &&
!x.DataTokens.ContainsKey("area"));
}
else
{
//find the controller in the route table with the specified area
surfaceRoute = RouteTable.Routes.OfType<Route>()
.SingleOrDefault(x => x.Defaults != null &&
x.Defaults.ContainsKey("controller") &&
x.Defaults["controller"].ToString().InvariantEquals(postedInfo.ControllerName) &&
x.DataTokens.ContainsKey("area") &&
x.DataTokens["area"].ToString().InvariantEquals(postedInfo.Area));
}
if (surfaceRoute == null)
throw new InvalidOperationException("Could not find a Surface controller route in the RouteTable for controller name " + postedInfo.ControllerName);
//set the area if one is there.
if (surfaceRoute.DataTokens.ContainsKey("area"))
{
requestContext.RouteData.DataTokens["area"] = surfaceRoute.DataTokens["area"];
}
//set the 'Namespaces' token so the controller factory knows where to look to construct it
if (surfaceRoute.DataTokens.ContainsKey("Namespaces"))
{
requestContext.RouteData.DataTokens["Namespaces"] = surfaceRoute.DataTokens["Namespaces"];
}
handler = surfaceRoute.RouteHandler.GetHttpHandler(requestContext);
}
return handler;
}
/// <summary>
/// Returns a RouteDefinition object based on the current renderModel
/// </summary>
/// <param name="requestContext"></param>
/// <param name="publishedContentRequest"></param>
/// <returns></returns>
internal virtual RouteDefinition GetUmbracoRouteDefinition(RequestContext requestContext, PublishedContentRequest publishedContentRequest)
{
if (requestContext == null) throw new ArgumentNullException("requestContext");
if (publishedContentRequest == null) throw new ArgumentNullException("publishedContentRequest");
var defaultControllerType = DefaultRenderMvcControllerResolver.Current.GetDefaultControllerType();
var defaultControllerName = ControllerExtensions.GetControllerName(defaultControllerType);
//creates the default route definition which maps to the 'UmbracoController' controller
var def = new RouteDefinition
{
ControllerName = defaultControllerName,
ControllerType = defaultControllerType,
PublishedContentRequest = publishedContentRequest,
ActionName = ((Route)requestContext.RouteData.Route).Defaults["action"].ToString(),
HasHijackedRoute = false
};
//check that a template is defined), if it doesn't and there is a hijacked route it will just route
// to the index Action
if (publishedContentRequest.HasTemplate)
{
//the template Alias should always be already saved with a safe name.
//if there are hyphens in the name and there is a hijacked route, then the Action will need to be attributed
// with the action name attribute.
var templateName = publishedContentRequest.TemplateAlias.Split('.')[0].ToSafeAlias();
def.ActionName = templateName;
}
//check if there's a custom controller assigned, base on the document type alias.
var controllerType = _controllerFactory.GetControllerTypeInternal(requestContext, publishedContentRequest.PublishedContent.DocumentTypeAlias);
//check if that controller exists
if (controllerType != null)
{
//ensure the controller is of type 'IRenderMvcController' and ControllerBase
if (TypeHelper.IsTypeAssignableFrom<IRenderMvcController>(controllerType)
&& TypeHelper.IsTypeAssignableFrom<ControllerBase>(controllerType))
{
//set the controller and name to the custom one
def.ControllerType = controllerType;
def.ControllerName = ControllerExtensions.GetControllerName(controllerType);
if (def.ControllerName != defaultControllerName)
{
def.HasHijackedRoute = true;
}
}
else
{
LogHelper.Warn<RenderRouteHandler>(
"The current Document Type {0} matches a locally declared controller of type {1}. Custom Controllers for Umbraco routing must implement '{2}' and inherit from '{3}'.",
() => publishedContentRequest.PublishedContent.DocumentTypeAlias,
() => controllerType.FullName,
() => typeof(IRenderMvcController).FullName,
() => typeof(ControllerBase).FullName);
//we cannot route to this custom controller since it is not of the correct type so we'll continue with the defaults
// that have already been set above.
}
}
//store the route definition
requestContext.RouteData.DataTokens["umbraco-route-def"] = def;
return def;
}
internal IHttpHandler GetHandlerOnMissingTemplate(PublishedContentRequest pcr)
{
if (pcr == null) throw new ArgumentNullException("pcr");
// missing template, so we're in a 404 here
// so the content, if any, is a custom 404 page of some sort
if (!pcr.HasPublishedContent)
// means the builder could not find a proper document to handle 404
return new PublishedContentNotFoundHandler();
if (!pcr.HasTemplate)
// means the engine could find a proper document, but the document has no template
// at that point there isn't much we can do and there is no point returning
// to Mvc since Mvc can't do much
return new PublishedContentNotFoundHandler("In addition, no template exists to render the custom 404.");
// so we have a template, so we should have a rendering engine
if (pcr.RenderingEngine == RenderingEngine.WebForms) // back to webforms ?
return (global::umbraco.UmbracoDefault)System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath("~/default.aspx", typeof(global::umbraco.UmbracoDefault));
else if (pcr.RenderingEngine != RenderingEngine.Mvc) // else ?
return new PublishedContentNotFoundHandler("In addition, no rendering engine exists to render the custom 404.");
return null;
}
/// <summary>
/// this will determine the controller and set the values in the route data
/// </summary>
/// <param name="requestContext"></param>
/// <param name="publishedContentRequest"></param>
internal IHttpHandler GetHandlerForRoute(RequestContext requestContext, PublishedContentRequest publishedContentRequest)
{
if (requestContext == null) throw new ArgumentNullException("requestContext");
if (publishedContentRequest == null) throw new ArgumentNullException("publishedContentRequest");
var routeDef = GetUmbracoRouteDefinition(requestContext, publishedContentRequest);
//Need to check for a special case if there is form data being posted back to an Umbraco URL
var postedInfo = GetFormInfo(requestContext);
if (postedInfo != null)
{
return HandlePostedValues(requestContext, postedInfo);
}
//here we need to check if there is no hijacked route and no template assigned, if this is the case
//we want to return a blank page, but we'll leave that up to the NoTemplateHandler.
if (!publishedContentRequest.HasTemplate && !routeDef.HasHijackedRoute)
{
publishedContentRequest.UpdateOnMissingTemplate(); // will go 404
// HandleHttpResponseStatus returns a value indicating that the request should
// not be processed any further, eg because it has been redirect. then, exit.
if (UmbracoModule.HandleHttpResponseStatus(requestContext.HttpContext, publishedContentRequest))
return null;
var handler = GetHandlerOnMissingTemplate(publishedContentRequest);
// if it's not null it can be either the PublishedContentNotFoundHandler (no document was
// found to handle 404, or document with no template was found) or the WebForms handler
// (a document was found and its template is WebForms)
// if it's null it means that a document was found and its template is Mvc
// if we have a handler, return now
if (handler != null)
return handler;
// else we are running Mvc
// update the route data - because the PublishedContent has changed
UpdateRouteDataForRequest(
new RenderModel(publishedContentRequest.PublishedContent, publishedContentRequest.Culture),
requestContext);
// update the route definition
routeDef = GetUmbracoRouteDefinition(requestContext, publishedContentRequest);
}
//no post values, just route to the controller/action requried (local)
requestContext.RouteData.Values["controller"] = routeDef.ControllerName;
if (!string.IsNullOrWhiteSpace(routeDef.ActionName))
{
requestContext.RouteData.Values["action"] = routeDef.ActionName;
}
// Set the session state requirements
requestContext.HttpContext.SetSessionStateBehavior(GetSessionStateBehavior(requestContext, routeDef.ControllerName));
// reset the friendly path so in the controllers and anything occuring after this point in time,
//the URL is reset back to the original request.
requestContext.HttpContext.RewritePath(UmbracoContext.OriginalRequestUrl.PathAndQuery);
return new UmbracoMvcHandler(requestContext);
}
private SessionStateBehavior GetSessionStateBehavior(RequestContext requestContext, string controllerName)
{
return _controllerFactory.GetControllerSessionBehavior(requestContext, controllerName);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.Samples.Chirper.GrainInterfaces;
namespace Orleans.Samples.Chirper.Network.Loader
{
/// <summary>
/// Read a GraphML data file for the Chirper network and create appropriate Orleans grains to represent that data.
/// </summary>
public class ChirperNetworkLoader
{
private const int ProgressInterval = 1000;
private const int DefaultPipelineSize = 20;
public int PipelineSize { get; set; }
public FileInfo FileToLoad { get; set; }
public Dictionary<long, IChirperAccount> Users { get; private set; }
private int numUsers;
private int numRelationships;
private int numErrors;
private int duplicateNodes = 0;
private AsyncPipeline pipeline;
private NetworkDataReader loader;
private List<Task> promises;
private readonly Stopwatch runtimeStopwatch = new Stopwatch();
private readonly Stopwatch edgeStopwatch = new Stopwatch();
private readonly Stopwatch loadStopwatch = new Stopwatch();
public ChirperNetworkLoader(AsyncPipeline pipeline = null)
{
this.pipeline = pipeline;
this.Users = new Dictionary<long, IChirperAccount>();
this.PipelineSize = (pipeline == null) ? DefaultPipelineSize : pipeline.Capacity;
if (!GrainClient.IsInitialized)
{
var config = ClientConfiguration.LocalhostSilo();
GrainClient.Initialize(config);
}
runtimeStopwatch.Start();
}
public async Task<int> Run()
{
LogMessage("********************************************************");
LogMessage("{0}\t{1:G}", "Network Load Starting at:", DateTime.Now);
LoadData();
LogMessage("Pipeline={0}", this.PipelineSize);
if (pipeline == null)
this.pipeline = new AsyncPipeline(this.PipelineSize);
try
{
loadStopwatch.Start();
LogMessage("Creating {0} user nodes...", loader.Nodes.Count);
List<Task> work = CreateUserNodes();
LogMessage("Waiting for {0} promises to complete.", work.Count);
await Task.WhenAll(work);
LogMessage("Finished creating {0} users in {1}", numUsers, runtimeStopwatch.Elapsed);
LogMessage("Creating {0} user relationship links...", loader.Edges.Count);
edgeStopwatch.Start();
LogMessage("Processing user relationship links group #1");
work = CreateRelationshipEdges(true);
LogMessage("Waiting for {0} promises to complete.", work.Count);
await Task.WhenAll(work);
LogMessage("Processing user relationship links group #2");
work = CreateRelationshipEdges(false);
LogMessage("Waiting for {0} promises to complete.", work.Count);
await Task.WhenAll(work);
edgeStopwatch.Stop();
LogMessage("Finished creating {0} user relationship links in {1}", numRelationships, runtimeStopwatch.Elapsed);
}
catch(Exception exc)
{
ReportError("Error creating Chirper data network", exc);
throw exc.GetBaseException();
}
loadStopwatch.Stop();
runtimeStopwatch.Stop();
LogMessage(string.Empty);
LogMessage("Loading Completed:");
LogMessage("\t{0} users ({1} duplicates, {2} new)", this.numUsers, this.duplicateNodes, this.numUsers - this.duplicateNodes);
LogMessage("\t{0} relationship links", this.numRelationships);
LogMessage("\t{0} errors", this.numErrors);
LogMessage(string.Empty);
LogMessage("\tNode Processing Time:\t{0}", loadStopwatch.Elapsed - edgeStopwatch.Elapsed);
LogMessage("\tEdge Processing Time:\t{0}", edgeStopwatch.Elapsed);
LogMessage("\tTotal Load Time:\t{0}", loadStopwatch.Elapsed);
LogMessage(string.Empty);
LogMessage("Execution Time:\t\t{0}", runtimeStopwatch.Elapsed);
LogMessage("Network Load Finished at:\t{0:G}", DateTime.Now);
LogMessage(string.Empty);
return 0;
}
public void LoadData()
{
if (FileToLoad == null) throw new ArgumentNullException("FileToLoad", "No load file specified");
if (!FileToLoad.Exists) throw new FileNotFoundException("Cannot find file to load: " + this.FileToLoad.FullName);
LogMessage("Loading GraphML file:\t" + FileToLoad.FullName);
loader = new NetworkDataReader();
loader.ProgressInterval = ProgressInterval;
loader.LoadData(FileToLoad);
}
public void WaitForCompletion()
{
Console.WriteLine("---Press any key to exit---");
Console.ReadKey();
LogMessage("Loading Completed: {0} users, {1} relationship links, {2} errors", this.numUsers, this.numRelationships, this.numErrors);
}
public bool ParseArguments(string[] args)
{
bool ok = true;
int argPos = 1;
for (int i = 0; i < args.Length; i++)
{
string a = args[i];
if (a.StartsWith("-") || a.StartsWith("/"))
{
a = a.Substring(1).ToLowerInvariant();
switch (a)
{
case "pipeline":
this.PipelineSize = Int32.Parse(args[++i]);
break;
case "?":
case "help":
default:
ok = false;
break;
}
}
// unqualified arguments below
else if (argPos == 1)
{
this.FileToLoad = new FileInfo(a);
argPos++;
}
else
{
// Too many command line arguments
ReportError("Too many command line arguments supplied: " + a);
return false;
}
}
return ok;
}
public void PrintUsage()
{
using (StringWriter usageStr = new StringWriter())
{
usageStr.WriteLine(Assembly.GetExecutingAssembly().GetName().Name + ".exe"
+ " [/pipeline {n}] {file}");
usageStr.WriteLine("Where:");
usageStr.WriteLine(" {file} = GraphML file to load");
usageStr.WriteLine(" /pipeline {n} = Request pipeline size [default " + DefaultPipelineSize + "]");
Console.WriteLine(usageStr.ToString());
}
}
public List<Task> CreateUserNodes()
{
TimeSpan intervalStart = runtimeStopwatch.Elapsed;
promises = loader.ProcessNodes(
AddChirperUser,
i =>
{
// Show progress interval breakdown
TimeSpan currentRuntime = runtimeStopwatch.Elapsed;
LogMessage("Users Created: {0,10} Time: {1} Cumulative: {2}",
i, currentRuntime - intervalStart, currentRuntime); // Show progress
intervalStart = runtimeStopwatch.Elapsed; // Don't include log writing in the interval.
}, pipeline);
return promises;
}
public List<Task> CreateRelationshipEdges(bool forward)
{
TimeSpan intervalStart = runtimeStopwatch.Elapsed;
promises = loader.ProcessEdges((fromUserId, toUserId) =>
{
// Segment updates into disjoint update groups, based on source / target node id
bool skip = forward ? fromUserId > toUserId : fromUserId < toUserId;
if (skip)
{
return null; // skip this edge for this time round
}
IChirperAccount fromUser = this.Users[fromUserId];
return AddChirperFollower(fromUser, fromUserId, toUserId);
},
i =>
{
// Show progress interval breakdown
TimeSpan currentRuntime = runtimeStopwatch.Elapsed;
LogMessage("Links created: {0,10} Time: {1} Cumulative: {2}", i, currentRuntime - intervalStart, currentRuntime);
intervalStart = runtimeStopwatch.Elapsed; // Don't include log writing in the interval.
}, pipeline);
return promises;
}
public string DumpStatus()
{
int completedTasks = promises.Count(t => t.IsCompleted);
int faultedTasks = promises.Count(t => t.IsFaulted);
int cancelledTasks = promises.Count(t => t.IsCanceled);
int totalTasks = promises.Count;
int pipelineCount = pipeline.Count;
string statusDump = string.Format(
"Promises: Completed={0} Faulted={1} Cancelled={2} Total={3} Unfinished={4} Pipeline={5}",
completedTasks, faultedTasks, cancelledTasks, totalTasks,
totalTasks - completedTasks - faultedTasks - cancelledTasks,
pipelineCount);
Console.WriteLine(statusDump);
return statusDump;
}
private async Task AddChirperUser(ChirperUserInfo userData)
{
// Create Chirper account grain for this user
long userId = userData.UserId;
string userAlias = userData.UserAlias;
IChirperAccount grain = GrainClient.GrainFactory.GetGrain<IChirperAccount>(userId);
this.Users[userId] = grain;
try
{
// Force creation of the grain by sending it a first message to set user alias
ChirperUserInfo userInfo = ChirperUserInfo.GetUserInfo(userId, userAlias);
await grain.SetUserDetails(userInfo);
Interlocked.Increment(ref numUsers);
}
catch (Exception exc)
{
ReportError("Error creating user id " + userId, exc);
throw exc.GetBaseException();
}
}
private async Task AddChirperFollower(IChirperAccount fromUser, long fromUserId, long toUserId)
{
// Create subscriptions between two Chirper users
try
{
await fromUser.FollowUserId(toUserId);
Interlocked.Increment(ref numRelationships);
}
catch (Exception exc)
{
ReportError(string.Format("Error adding follower relationship from user id {0} to user id {1}", fromUserId, toUserId), exc);
throw exc.GetBaseException();
}
}
#region Status message capture / logging
internal void LogMessage(string message, params object[] args)
{
if (args.Length > 0)
{
message = String.Format(message, args);
}
message = String.Format("[{0}] {1}", TraceLogger.PrintDate(DateTime.UtcNow), message);
Console.WriteLine(message);
}
internal void ReportError(string msg, Exception exc)
{
msg = "*****\t" + msg + "\n --->" + TraceLogger.PrintException(exc);
ReportError(msg);
}
internal void ReportError(string msg)
{
Interlocked.Increment(ref numErrors);
msg = string.Format("Error Time: {0:G}\n\t{1}", TraceLogger.PrintDate(DateTime.UtcNow), msg);
Console.WriteLine(msg);
}
#endregion
}
}
| |
// <copyright file="IluptElementSorterTest.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
//
// Copyright (c) 2009-2013 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using MathNet.Numerics.LinearAlgebra.Complex32;
using MathNet.Numerics.LinearAlgebra.Complex32.Solvers;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Complex32.Solvers.Preconditioners
{
/// <summary>
/// Test for element sort algorithm of Ilupt class.
/// </summary>
[TestFixture, Category("LASolver")]
public sealed class IluptElementSorterTest
{
/// <summary>
/// Heap sort with increasing integer array.
/// </summary>
[Test]
public void HeapSortWithIncreasingIntegerArray()
{
var sortedIndices = new[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
ILUTPElementSorter.SortIntegersDecreasing(sortedIndices);
for (var i = 0; i < sortedIndices.Length; i++)
{
Assert.AreEqual(sortedIndices.Length - 1 - i, sortedIndices[i], "#01-" + i);
}
}
/// <summary>
/// Heap sort with decreasing integer array.
/// </summary>
[Test]
public void HeapSortWithDecreasingIntegerArray()
{
var sortedIndices = new[] {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
ILUTPElementSorter.SortIntegersDecreasing(sortedIndices);
for (var i = 0; i < sortedIndices.Length; i++)
{
Assert.AreEqual(sortedIndices.Length - 1 - i, sortedIndices[i], "#01-" + i);
}
}
/// <summary>
/// Heap sort with random integer array.
/// </summary>
[Test]
public void HeapSortWithRandomIntegerArray()
{
var sortedIndices = new[] {5, 2, 8, 6, 0, 4, 1, 7, 3, 9};
ILUTPElementSorter.SortIntegersDecreasing(sortedIndices);
for (var i = 0; i < sortedIndices.Length; i++)
{
Assert.AreEqual(sortedIndices.Length - 1 - i, sortedIndices[i], "#01-" + i);
}
}
/// <summary>
/// Heap sort with duplicate entries.
/// </summary>
[Test]
public void HeapSortWithDuplicateEntries()
{
var sortedIndices = new[] {1, 1, 1, 1, 2, 2, 2, 2, 3, 4};
ILUTPElementSorter.SortIntegersDecreasing(sortedIndices);
for (var i = 0; i < sortedIndices.Length; i++)
{
if (i == 0)
{
Assert.AreEqual(4, sortedIndices[i], "#01-" + i);
}
else
{
if (i == 1)
{
Assert.AreEqual(3, sortedIndices[i], "#01-" + i);
}
else
{
if (i < 6)
{
if (sortedIndices[i] != 2)
{
Assert.Fail("#01-" + i);
}
}
else
{
if (sortedIndices[i] != 1)
{
Assert.Fail("#01-" + i);
}
}
}
}
}
}
/// <summary>
/// Heap sort with special constructed integer array.
/// </summary>
[Test]
public void HeapSortWithSpecialConstructedIntegerArray()
{
var sortedIndices = new[] {0, 0, 0, 0, 0, 1, 0, 0, 0, 0};
ILUTPElementSorter.SortIntegersDecreasing(sortedIndices);
for (var i = 0; i < sortedIndices.Length; i++)
{
if (i == 0)
{
Assert.AreEqual(1, sortedIndices[i], "#01-" + i);
break;
}
}
sortedIndices = new[] {1, 0, 0, 0, 0, 0, 0, 0, 0, 0};
ILUTPElementSorter.SortIntegersDecreasing(sortedIndices);
for (var i = 0; i < sortedIndices.Length; i++)
{
if (i == 0)
{
Assert.AreEqual(1, sortedIndices[i], "#02-" + i);
break;
}
}
sortedIndices = new[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
ILUTPElementSorter.SortIntegersDecreasing(sortedIndices);
for (var i = 0; i < sortedIndices.Length; i++)
{
if (i == 0)
{
Assert.AreEqual(1, sortedIndices[i], "#03-" + i);
break;
}
}
sortedIndices = new[] {1, 1, 1, 0, 1, 1, 1, 1, 1, 1};
ILUTPElementSorter.SortIntegersDecreasing(sortedIndices);
for (var i = 0; i < sortedIndices.Length; i++)
{
if (i == 9)
{
Assert.AreEqual(0, sortedIndices[i], "#04-" + i);
break;
}
}
}
/// <summary>
/// Heap sort with increasing double array.
/// </summary>
[Test]
public void HeapSortWithIncreasingDoubleArray()
{
var sortedIndices = new int[10];
var values = new DenseVector(10);
values[0] = 0;
values[1] = 1;
values[2] = 2;
values[3] = 3;
values[4] = 4;
values[5] = 5;
values[6] = 6;
values[7] = 7;
values[8] = 8;
values[9] = 9;
for (var i = 0; i < sortedIndices.Length; i++)
{
sortedIndices[i] = i;
}
ILUTPElementSorter.SortDoubleIndicesDecreasing(0, sortedIndices.Length - 1, sortedIndices, values);
for (var i = 0; i < sortedIndices.Length; i++)
{
Assert.AreEqual(sortedIndices.Length - 1 - i, sortedIndices[i], "#01-" + i);
}
}
/// <summary>
/// Heap sort with decreasing doubleArray
/// </summary>
[Test]
public void HeapSortWithDecreasingDoubleArray()
{
var sortedIndices = new int[10];
var values = new DenseVector(10);
values[0] = 9;
values[1] = 8;
values[2] = 7;
values[3] = 6;
values[4] = 5;
values[5] = 4;
values[6] = 3;
values[7] = 2;
values[8] = 1;
values[9] = 0;
for (var i = 0; i < sortedIndices.Length; i++)
{
sortedIndices[i] = i;
}
ILUTPElementSorter.SortDoubleIndicesDecreasing(0, sortedIndices.Length - 1, sortedIndices, values);
for (var i = 0; i < sortedIndices.Length; i++)
{
Assert.AreEqual(i, sortedIndices[i], "#01-" + i);
}
}
/// <summary>
/// Heap sort with random double array.
/// </summary>
[Test]
public void HeapSortWithRandomDoubleArray()
{
var sortedIndices = new int[10];
var values = new DenseVector(10);
values[0] = 5;
values[1] = 2;
values[2] = 8;
values[3] = 6;
values[4] = 0;
values[5] = 4;
values[6] = 1;
values[7] = 7;
values[8] = 3;
values[9] = 9;
for (var i = 0; i < sortedIndices.Length; i++)
{
sortedIndices[i] = i;
}
ILUTPElementSorter.SortDoubleIndicesDecreasing(0, sortedIndices.Length - 1, sortedIndices, values);
for (var i = 0; i < sortedIndices.Length; i++)
{
switch (i)
{
case 0:
Assert.AreEqual(9, sortedIndices[i], "#01-" + i);
break;
case 1:
Assert.AreEqual(2, sortedIndices[i], "#01-" + i);
break;
case 2:
Assert.AreEqual(7, sortedIndices[i], "#01-" + i);
break;
case 3:
Assert.AreEqual(3, sortedIndices[i], "#01-" + i);
break;
case 4:
Assert.AreEqual(0, sortedIndices[i], "#01-" + i);
break;
case 5:
Assert.AreEqual(5, sortedIndices[i], "#01-" + i);
break;
case 6:
Assert.AreEqual(8, sortedIndices[i], "#01-" + i);
break;
case 7:
Assert.AreEqual(1, sortedIndices[i], "#01-" + i);
break;
case 8:
Assert.AreEqual(6, sortedIndices[i], "#01-" + i);
break;
case 9:
Assert.AreEqual(4, sortedIndices[i], "#01-" + i);
break;
}
}
}
/// <summary>
/// Heap sort with duplicate double entries.
/// </summary>
[Test]
public void HeapSortWithDuplicateDoubleEntries()
{
var sortedIndices = new int[10];
var values = new DenseVector(10);
values[0] = 1;
values[1] = 1;
values[2] = 1;
values[3] = 1;
values[4] = 2;
values[5] = 2;
values[6] = 2;
values[7] = 2;
values[8] = 3;
values[9] = 4;
for (var i = 0; i < sortedIndices.Length; i++)
{
sortedIndices[i] = i;
}
ILUTPElementSorter.SortDoubleIndicesDecreasing(0, sortedIndices.Length - 1, sortedIndices, values);
for (var i = 0; i < sortedIndices.Length; i++)
{
if (i == 0)
{
Assert.AreEqual(9, sortedIndices[i], "#01-" + i);
}
else
{
if (i == 1)
{
Assert.AreEqual(8, sortedIndices[i], "#01-" + i);
}
else
{
if (i < 6)
{
if ((sortedIndices[i] != 4) &&
(sortedIndices[i] != 5) &&
(sortedIndices[i] != 6) &&
(sortedIndices[i] != 7))
{
Assert.Fail("#01-" + i);
}
}
else
{
if ((sortedIndices[i] != 0) &&
(sortedIndices[i] != 1) &&
(sortedIndices[i] != 2) &&
(sortedIndices[i] != 3))
{
Assert.Fail("#01-" + i);
}
}
}
}
}
}
/// <summary>
/// Heap sort with special constructed double array.
/// </summary>
[Test]
public void HeapSortWithSpecialConstructedDoubleArray()
{
var sortedIndices = new int[10];
var values = new DenseVector(10);
values[0] = 0;
values[1] = 0;
values[2] = 0;
values[3] = 0;
values[4] = 0;
values[5] = 1;
values[6] = 0;
values[7] = 0;
values[8] = 0;
values[9] = 0;
for (var i = 0; i < sortedIndices.Length; i++)
{
sortedIndices[i] = i;
}
ILUTPElementSorter.SortDoubleIndicesDecreasing(0, sortedIndices.Length - 1, sortedIndices, values);
for (var i = 0; i < sortedIndices.Length; i++)
{
if (i == 0)
{
Assert.AreEqual(5, sortedIndices[i], "#01-" + i);
break;
}
}
values[0] = 1;
values[1] = 0;
values[2] = 0;
values[3] = 0;
values[4] = 0;
values[5] = 0;
values[6] = 0;
values[7] = 0;
values[8] = 0;
values[9] = 0;
for (var i = 0; i < sortedIndices.Length; i++)
{
sortedIndices[i] = i;
}
ILUTPElementSorter.SortDoubleIndicesDecreasing(0, sortedIndices.Length - 1, sortedIndices, values);
for (var i = 0; i < sortedIndices.Length; i++)
{
if (i == 0)
{
Assert.AreEqual(0, sortedIndices[i], "#02-" + i);
break;
}
}
values[0] = 0;
values[1] = 0;
values[2] = 0;
values[3] = 0;
values[4] = 0;
values[5] = 0;
values[6] = 0;
values[7] = 0;
values[8] = 0;
values[9] = 1;
for (var i = 0; i < sortedIndices.Length; i++)
{
sortedIndices[i] = i;
}
ILUTPElementSorter.SortDoubleIndicesDecreasing(0, sortedIndices.Length - 1, sortedIndices, values);
for (var i = 0; i < sortedIndices.Length; i++)
{
if (i == 0)
{
Assert.AreEqual(9, sortedIndices[i], "#03-" + i);
break;
}
}
values[0] = 1;
values[1] = 1;
values[2] = 1;
values[3] = 0;
values[4] = 1;
values[5] = 1;
values[6] = 1;
values[7] = 1;
values[8] = 1;
values[9] = 1;
for (var i = 0; i < sortedIndices.Length; i++)
{
sortedIndices[i] = i;
}
ILUTPElementSorter.SortDoubleIndicesDecreasing(0, sortedIndices.Length - 1, sortedIndices, values);
for (var i = 0; i < sortedIndices.Length; i++)
{
if (i == 9)
{
Assert.AreEqual(3, sortedIndices[i], "#04-" + i);
break;
}
}
}
/// <summary>
/// Heap sort with increasing double array with lower bound
/// </summary>
[Test]
public void HeapSortWithIncreasingDoubleArrayWithLowerBound()
{
var sortedIndices = new int[10];
var values = new DenseVector(10);
values[0] = 0;
values[1] = 1;
values[2] = 2;
values[3] = 3;
values[4] = 4;
values[5] = 5;
values[6] = 6;
values[7] = 7;
values[8] = 8;
values[9] = 9;
for (var i = 0; i < sortedIndices.Length; i++)
{
sortedIndices[i] = i;
}
ILUTPElementSorter.SortDoubleIndicesDecreasing(4, sortedIndices.Length - 1, sortedIndices, values);
for (var i = 0; i < sortedIndices.Length - 4; i++)
{
Assert.AreEqual(sortedIndices.Length - 1 - i, sortedIndices[i], "#01-" + i);
}
}
/// <summary>
/// Heap sort with increasing double array with upper bound.
/// </summary>
[Test]
public void HeapSortWithIncreasingDoubleArrayWithUpperBound()
{
var sortedIndices = new int[10];
var values = new DenseVector(10);
values[0] = 0;
values[1] = 1;
values[2] = 2;
values[3] = 3;
values[4] = 4;
values[5] = 5;
values[6] = 6;
values[7] = 7;
values[8] = 8;
values[9] = 9;
for (var i = 0; i < sortedIndices.Length; i++)
{
sortedIndices[i] = i;
}
ILUTPElementSorter.SortDoubleIndicesDecreasing(0, sortedIndices.Length - 5, sortedIndices, values);
for (var i = 0; i < sortedIndices.Length - 5; i++)
{
Assert.AreEqual(sortedIndices.Length - 5 - i, sortedIndices[i], "#01-" + i);
}
}
/// <summary>
/// Heap sort with increasing double array with lower and upper bound.
/// </summary>
[Test]
public void HeapSortWithIncreasingDoubleArrayWithLowerAndUpperBound()
{
var sortedIndices = new int[10];
var values = new DenseVector(10);
values[0] = 0;
values[1] = 1;
values[2] = 2;
values[3] = 3;
values[4] = 4;
values[5] = 5;
values[6] = 6;
values[7] = 7;
values[8] = 8;
values[9] = 9;
for (var i = 0; i < sortedIndices.Length; i++)
{
sortedIndices[i] = i;
}
ILUTPElementSorter.SortDoubleIndicesDecreasing(2, sortedIndices.Length - 3, sortedIndices, values);
for (var i = 0; i < sortedIndices.Length - 4; i++)
{
Assert.AreEqual(sortedIndices.Length - 3 - i, sortedIndices[i], "#01-" + i);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Security;
using System.Text; // For UriEncode
using Windows.ApplicationModel.Resources.Core;
using Windows.ApplicationModel;
using Windows.Foundation.Collections;
using Windows.Storage;
namespace System.Resources
{
#if FEATURE_APPX
[FriendAccessAllowed]
// Please see the comments regarding thread safety preceding the implementations
// of Initialize() and GetString() below.
internal sealed class WindowsRuntimeResourceManager : WindowsRuntimeResourceManagerBase
{
private ResourceMap _resourceMap;
private ResourceContext _clonedResourceContext;
private string _clonedResourceContextFallBackList;
private static char[] s_charCultureSeparator;
private struct PackageInfo
{
public string Path;
public string Name;
public string FullName;
}
private static PackageInfo s_currentPackageInfo;
private static List<PackageInfo> s_dependentPackageInfoList;
private static ResourceContext s_globalResourceContext; // Read from it but do not modify it or call Reset() on it as that would affect the app-wide state
private static volatile string s_globalResourceContextFallBackList;
private static volatile CultureInfo s_globalResourceContextBestFitCultureInfo;
private static volatile global::Windows.ApplicationModel.Resources.Core.ResourceManager s_globalResourceManager;
private static Object s_objectForLock = new Object(); // Used by InitializeStatics
private static bool InitializeStatics()
{
global::Windows.ApplicationModel.Resources.Core.ResourceManager globalResourceManager = null;
if (s_globalResourceManager == null)
{
lock (s_objectForLock)
{
if (s_globalResourceManager == null)
{
globalResourceManager = global::Windows.ApplicationModel.Resources.Core.ResourceManager.Current;
InitializeStaticGlobalResourceContext(globalResourceManager);
s_charCultureSeparator = new char[] { ';' };
Package currentPackage = Package.Current;
if (currentPackage != null)
{
StorageFolder currentPackageLocation = currentPackage.InstalledLocation;
s_currentPackageInfo.Path = null;
s_currentPackageInfo.Name = null;
s_currentPackageInfo.FullName = null;
if (currentPackageLocation != null)
s_currentPackageInfo.Path = currentPackageLocation.Path;
PackageId id = currentPackage.Id;
if (id != null)
{
s_currentPackageInfo.Name = id.Name; // We do not enforce this to be non-null.
s_currentPackageInfo.FullName = id.FullName;
}
}
if (globalResourceManager != null &&
s_globalResourceContext != null &&
s_globalResourceContextFallBackList != null &&
s_globalResourceContextFallBackList.Length > 0 && // Should never be empty
s_charCultureSeparator != null &&
s_currentPackageInfo.Path != null)
s_globalResourceManager = globalResourceManager;
}
}
}
return s_globalResourceManager != null;
}
private static void InitializeStaticGlobalResourceContext(global::Windows.ApplicationModel.Resources.Core.ResourceManager resourceManager)
{
if (s_globalResourceContext == null)
{
lock (s_objectForLock)
{
if (s_globalResourceContext == null)
{
resourceManager = resourceManager ?? global::Windows.ApplicationModel.Resources.Core.ResourceManager.Current;
if (resourceManager != null)
{
#pragma warning disable 618
ResourceContext globalResourceContext = resourceManager.DefaultContext;
#pragma warning restore 618
if (globalResourceContext != null)
{
List<String> languages = new List<string>(globalResourceContext.Languages);
s_globalResourceContextBestFitCultureInfo = GetBestFitCultureFromLanguageList(languages);
s_globalResourceContextFallBackList = ReadOnlyListToString(languages);
s_globalResourceContext = globalResourceContext;
s_globalResourceContext.QualifierValues.MapChanged += new MapChangedEventHandler<string, string>(GlobalResourceContextChanged);
}
}
}
}
}
}
// Returns the CultureInfo representing the first language in the list that we can construct a CultureInfo for or null if
// no such culture exists.
private static CultureInfo GetBestFitCultureFromLanguageList(List<string> languages)
{
StringBuilder localeNameBuffer = new StringBuilder(Interop.mincore.LOCALE_NAME_MAX_LENGTH);
for (int i = 0; i < languages.Count; i++)
{
if (CultureData.GetCultureData(languages[i], true) != null)
{
return new CultureInfo(languages[i]);
}
if (Interop.mincore.ResolveLocaleName(languages[i], localeNameBuffer, localeNameBuffer.MaxCapacity) != 0)
{
string localeName = localeNameBuffer.ToString();
if (CultureData.GetCultureData(localeName, true) != null)
{
return new CultureInfo(localeName);
}
}
}
return null;
}
// Can be called independently of/simultaneously with InitializeStatics.
// Does not use the results of InitializeStatics.
// Does not require the use of a lock because, given that the results of all the callees of
// this function are idempotent for the process lifetime, this function will always store
// the same information in s_dependentPackagePath no matter how many times it is called.
private static void InitializeStaticsForDependentPackages()
{
if (s_dependentPackageInfoList == null)
{
// Create an empty list. If there are no dependencies, this will be our way of knowing that we ran
// through this function once.
List<PackageInfo> dependentPackageInfoList = new List<PackageInfo>();
// We call Package.Current here and in InitializeStatics. This may cause a small perf hit.
// In theory we could have cached it as a static variable.
// However, we don't want to have to keep a reference to it alive for the lifetime of the AppDomain.
// Also having InitializeStaticsForDependentPackages not depend on InitializeStatics leads to a simpler design.
Package currentPackage = Package.Current;
if (currentPackage != null)
{
IReadOnlyList<Package> dependencies = currentPackage.Dependencies;
if (dependencies != null)
{
int dependenciesCount = dependencies.Count;
if (dependenciesCount > 0)
{
// We have dependencies. Throw away the old empty list, and create a list with
// capacity exactly equal to the number of dependencies.
dependentPackageInfoList = new List<PackageInfo>(dependenciesCount);
foreach (Package package in dependencies)
{
if (package != null)
{
StorageFolder dependentPackageLocation = package.InstalledLocation;
PackageInfo dependentPackageInfo;
dependentPackageInfo.Path = null;
dependentPackageInfo.Name = null;
dependentPackageInfo.FullName = null;
if (dependentPackageLocation != null)
dependentPackageInfo.Path = dependentPackageLocation.Path;
PackageId id = package.Id;
if (id != null)
{
dependentPackageInfo.Name = id.Name;
dependentPackageInfo.FullName = id.FullName;
}
dependentPackageInfoList.Add(dependentPackageInfo);
}
}
}
}
}
// Assign even if the list is empty. That way we know we ran through this function once.
s_dependentPackageInfoList = dependentPackageInfoList;
}
Debug.Assert(s_dependentPackageInfoList != null);
}
private static void GlobalResourceContextChanged(object sender, IMapChangedEventArgs<string> e)
{
Debug.Assert(s_globalResourceContextFallBackList != null);
Debug.Assert(s_globalResourceContext != null);
List<String> languages = new List<string>(s_globalResourceContext.Languages);
s_globalResourceContextBestFitCultureInfo = GetBestFitCultureFromLanguageList(languages);
s_globalResourceContextFallBackList = ReadOnlyListToString(languages);
}
private static bool LibpathMatchesPackagepath(String libpath, String packagepath)
{
Debug.Assert(libpath != null);
Debug.Assert(packagepath != null);
return packagepath.Length < libpath.Length &&
String.Compare(packagepath, 0,
libpath, 0,
packagepath.Length,
StringComparison.OrdinalIgnoreCase) == 0 &&
// Ensure wzPackagePath is not just a prefix, but a path prefix
// This says: packagepath is c:\foo || c:\foo\
(libpath[packagepath.Length] == '\\' || packagepath.EndsWith("\\"));
}
#if netstandard
/* Returns true if libpath is path to an ni image and if the path contains packagename as a subfolder */
private static bool LibpathContainsPackagename(String libpath, String packagename)
{
Debug.Assert(libpath != null);
Debug.Assert(packagename != null);
return libpath.IndexOf("\\" + packagename + "\\", StringComparison.OrdinalIgnoreCase) >= 0 &&
(libpath.EndsWith("ni.dll", StringComparison.OrdinalIgnoreCase) || libpath.EndsWith("ni.exe", StringComparison.OrdinalIgnoreCase));
}
#endif
private static string FindPackageSimpleNameForFilename(string libpath)
{
Debug.Assert(libpath != null);
Debug.Assert(s_currentPackageInfo.Path != null); // Set in InitializeStatics()
// s_currentPackageInfo.Name may be null (see note below)
if (LibpathMatchesPackagepath(libpath, s_currentPackageInfo.Path))
return s_currentPackageInfo.Name; // This may be null, in which case we failed to get the name (in InitializeStatics), but matched the path, so stop looking.
else // Look at dependent packages
{
InitializeStaticsForDependentPackages();
// s_dependentPackageInfoList is empty (but non-null) if there are no dependent packages.
foreach (PackageInfo dependentPackageInfo in s_dependentPackageInfoList)
{
if (LibpathMatchesPackagepath(libpath, dependentPackageInfo.Path))
return dependentPackageInfo.Name; // This may be null, in which case we failed to get the name (in InitializeStaticsForDependentPackages), but matched the path, so stop looking.
}
}
#if netstandard
/* On phone libpath is usually ni path and not IL path as we do not touch the IL on phone.
On Phone NI images are no longer under package root. Due to this above logic fails to
find the package to which the library belongs. We assume that NI paths usually have
package name as subfolder in its path. Based on this assumption we can find the package
to which an NI belongs. Below code does that.
*/
if (LibpathContainsPackagename(libpath, s_currentPackageInfo.FullName))
return s_currentPackageInfo.Name;
else // Look at dependent packages
{
// s_dependentPackageInfoList is empty (but non-null) if there are no dependent packages.
foreach (PackageInfo dependentPackageInfo in s_dependentPackageInfoList)
{
if (LibpathContainsPackagename(libpath, dependentPackageInfo.FullName))
return dependentPackageInfo.Name;
}
}
#endif
return null;
}
// Obtain instances of the Resource Map and Resource Context provided by
// the Windows Modern Resource Manager (MRM).
// Not thread-safe. Only call this once on one thread for each object instance.
// For example, System.Runtime.ResourceManager only calls this from its constructors,
// guaranteeing that this only gets called once, on one thread, for each new instance
// of System.Runtime.ResourceManager.
// Throws exceptions
// Only returns true if the function succeeded completely.
// Outputs exceptionInfo since it may be needed for debugging purposes
// if an exception is thrown by one of Initialize's callees.
public override bool Initialize(string libpath, string reswFilename, out PRIExceptionInfo exceptionInfo)
{
Debug.Assert(libpath != null);
Debug.Assert(reswFilename != null);
exceptionInfo = null;
if (InitializeStatics())
{
// AllResourceMaps can throw ERROR_MRM_MAP_NOT_FOUND,
// although in that case we are not sure for which package it failed to find
// resources (if we are looking for resources for a framework package,
// it might throw ERROR_MRM_MAP_NOT_FOUND if the app package
// resources could not be loaded, even if the framework package
// resources are properly configured). So we will not fill in the
// exceptionInfo structure at this point since we don't have any
// reliable information to include in it.
IReadOnlyDictionary<String, ResourceMap>
resourceMapDictionary = s_globalResourceManager.AllResourceMaps;
if (resourceMapDictionary != null)
{
string packageSimpleName = FindPackageSimpleNameForFilename(libpath);
#if netstandard
// If we have found a simple package name for the assembly, lets make sure it is not *.resource.dll that
// an application may have packaged in its AppX. This is to enforce AppX apps to use PRI resources.
if (packageSimpleName != null)
{
if (packageSimpleName.EndsWith(".resources.dll", StringComparison.CurrentCultureIgnoreCase))
{
// Pretend we didnt get a package name. When an attempt is made to get resource string, GetString implementation
// will see that we are going to use modern resource manager but we don't have PRI and will thrown an exception indicating
// so. This will force the developer to have a valid PRI based resource.
packageSimpleName = null;
}
}
#endif // netstandard
if (packageSimpleName != null)
{
ResourceMap packageResourceMap = null;
// Win8 enforces that package simple names are unique (for example, the App Store will not
// allow two apps with the same package simple name). That is why the Modern Resource Manager
// keys access to resources based on the package simple name.
if (resourceMapDictionary.TryGetValue(packageSimpleName, out packageResourceMap))
{
if (packageResourceMap != null)
{
// GetSubtree returns null when it cannot find resource strings
// named "reswFilename/*" for the package we are looking up.
reswFilename = UriUtility.UriEncode(reswFilename);
_resourceMap = packageResourceMap.GetSubtree(reswFilename);
if (_resourceMap == null)
{
exceptionInfo = new PRIExceptionInfo();
exceptionInfo._PackageSimpleName = packageSimpleName;
exceptionInfo._ResWFile = reswFilename;
}
else
{
_clonedResourceContext = s_globalResourceContext.Clone();
if (_clonedResourceContext != null)
{
// Will need to be changed the first time it is used. But we can't set it to "" since we will take a lock on it.
_clonedResourceContextFallBackList = ReadOnlyListToString(_clonedResourceContext.Languages);
if (_clonedResourceContextFallBackList != null)
return true;
}
}
}
}
}
}
}
return false;
}
private static IReadOnlyList<string> StringToReadOnlyList(string s)
{
Debug.Assert(s != null);
Debug.Assert(s_charCultureSeparator != null);
List<string> newList = new List<string>(s.Split(s_charCultureSeparator));
return newList.AsReadOnly();
}
private static string ReadOnlyListToString(IReadOnlyList<string> list)
{
Debug.Assert(list != null);
return String.Join(";", list);
}
public override CultureInfo GlobalResourceContextBestFitCultureInfo
{
get
{
InitializeStaticGlobalResourceContext(null);
return s_globalResourceContextBestFitCultureInfo;
}
}
// This method will set the culture ci as default language in the default resource context
// which is global for the whole app
public override bool SetGlobalResourceContextDefaultCulture(CultureInfo ci)
{
Debug.Assert(ci != null);
InitializeStaticGlobalResourceContext(null);
if (s_globalResourceContext == null)
{
return false;
}
if (s_globalResourceContextBestFitCultureInfo != null && s_globalResourceContextBestFitCultureInfo.Name.Equals(ci.Name, StringComparison.OrdinalIgnoreCase))
{
// the default culture is already set. nothing more need to be done
return true;
}
List<String> languages = new List<String>(s_globalResourceContext.Languages);
languages.Insert(0, ci.Name);
// remove any duplication in the list
int i = languages.Count - 1;
while (i > 0)
{
if (languages[i].Equals(ci.Name, StringComparison.OrdinalIgnoreCase))
{
languages.RemoveAt(i);
}
i--;
}
s_globalResourceContext.Languages = languages;
// update s_globalResourceContextBestFitCultureInfo and don't wait to be overridden by GlobalResourceContextChanged
// to avoid any timing problem
s_globalResourceContextBestFitCultureInfo = ci;
return true;
}
// Obtains a resource string given the name of the string resource, and optional starting
// and neutral resource cultures (e.g. "de-DE").
// Thread-safe provided that the call to Initialize() happened only once on one thread
// and has already completed successfully, and that the WinRT APIs called below
// continue to be thread-safe.
// Throws exceptions
public override String GetString(String stringName,
String startingCulture, String neutralResourcesCulture)
{
Debug.Assert(stringName != null);
Debug.Assert(_resourceMap != null); // Should have been initialized by now
ResourceCandidate resourceCandidate = null;
stringName = UriUtility.UriEncode(stringName);
if (startingCulture == null && neutralResourcesCulture == null)
{
#pragma warning disable 618
resourceCandidate = _resourceMap.GetValue(stringName);
#pragma warning restore 618
}
else
{
Debug.Assert(_clonedResourceContext != null); // Should have been initialized by now
Debug.Assert(_clonedResourceContextFallBackList != null); // Should have been initialized by now
Debug.Assert(s_globalResourceContextFallBackList != null); // Should have been initialized by now
Debug.Assert(s_globalResourceContextFallBackList.Length > 0); // Should never be empty
// We need to modify the culture fallback list used by the Modern Resource Manager
// The starting culture has to be looked up first, and neutral resources culture has
// to be looked up last.
string newResourceFallBackList = null;
newResourceFallBackList =
(startingCulture == null ? "" : startingCulture + ";") +
s_globalResourceContextFallBackList + // Our tests do not test this line of code, so be extra careful if you modify or move it.
(neutralResourcesCulture == null ? "" : ";" + neutralResourcesCulture);
lock (_clonedResourceContext)
{
// s_globalResourceContextFallBackList may have changed on another thread by now.
// We cannot prevent that from happening because it may have happened on a native
// thread, and we do not share the same lock mechanisms with native code.
// The worst that can happen is that a string is unexpectedly missing
// or in the wrong language.
if (!String.Equals(newResourceFallBackList, _clonedResourceContextFallBackList, StringComparison.Ordinal))
{
_clonedResourceContext.Languages = StringToReadOnlyList(newResourceFallBackList);
_clonedResourceContextFallBackList = newResourceFallBackList;
}
resourceCandidate = _resourceMap.GetValue(stringName, _clonedResourceContext);
}
}
if (resourceCandidate != null)
return resourceCandidate.ValueAsString;
return null;
}
}
// Adapted from the UrlEncode functions at file:alm\tfs_core\framework\common\UriUtility\HttpUtility.cs
// using methods which were in turn borrowed from
// file:ndp\fx\src\xsp\system\web\util\httpencoder.cs
// file:ndp\fx\src\xsp\system\web\httpserverutility.cs
// and file:ndp\fx\src\xsp\system\web\util\httpencoderutility.cs
internal static class UriUtility
{
// This method percent encodes the UTF8 encoding of a string.
// All characters are percent encoded except the unreserved characters from RFC 3986.
// We cannot use the System.Uri class since by default it respects
// the set of unreserved characters from RFC 2396, which is different
// by the 5 characters !*'()
// Adapted from the UrlEncode methods originally
// in file:ndp\fx\src\xsp\system\web\httpserverutility.cs
// and file:ndp\fx\src\xsp\system\web\util\httpencoder.cs
public static string UriEncode(string str)
{
if (str == null)
return null;
byte[] bytes = Encoding.UTF8.GetBytes(str);
int count = bytes.Length;
if (count == 0)
return null;
int cBytesToEncode = 0;
// count them first
for (int i = 0; i < count; i++)
{
if (!IsUriUnreservedChar((char)bytes[i]))
cBytesToEncode++;
}
byte[] expandedBytes = null;
// nothing to expand?
if (cBytesToEncode == 0)
expandedBytes = bytes;
else
{
// expand not 'safe' characters into %xx
expandedBytes = new byte[count + cBytesToEncode * 2];
int pos = 0;
for (int i = 0; i < count; i++)
{
byte b = bytes[i];
if (IsUriUnreservedChar((char)b))
{
expandedBytes[pos++] = b;
}
else
{
expandedBytes[pos++] = (byte)'%';
expandedBytes[pos++] = (byte)IntToHex((b >> 4) & 0xf);
expandedBytes[pos++] = (byte)IntToHex(b & 0xf);
}
}
}
// Since all the bytes in expandedBytes are ascii characters UTF8 encoding can be used
return Encoding.UTF8.GetString(expandedBytes);
}
// Adapted from IntToHex originally in file:ndp\fx\src\xsp\system\web\util\httpencoderutility.cs
private static char IntToHex(int n)
{
if (n <= 9)
return (char)(n + (int)'0');
else
return (char)(n - 10 + (int)'a');
}
// Modified from IsUrlSafeChar originally in file:ndp\fx\src\xsp\system\web\util\httpencoderutility.cs
// Set of unreserved characters from RFC 3986
private static bool IsUriUnreservedChar(char ch)
{
if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9')
return true;
switch (ch)
{
case '-':
case '_':
case '.':
case '~':
return true;
}
return false;
}
}
#endif //FEATURE_APPX
}
| |
//
// PlayerEngine.cs
//
// Author:
// Aaron Bockover <[email protected]>
//
// Copyright (C) 2006-2007 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using Hyena;
using Banshee.Base;
using Banshee.Streaming;
using Banshee.Collection;
using Banshee.ServiceStack;
namespace Banshee.MediaEngine
{
public abstract class PlayerEngine : IDisposable
{
public const int VolumeDelta = 10;
public const int SkipDelta = 10;
public event PlayerEventHandler EventChanged;
private TrackInfo current_track;
private TrackInfo pending_track;
private PlayerState current_state = PlayerState.NotReady;
private PlayerState last_state = PlayerState.NotReady;
public DateTime CurrentTrackTimeStamp {
get;
private set;
}
// will be changed to PlayerState.Idle after going to PlayerState.Ready
private PlayerState idle_state = PlayerState.NotReady;
protected abstract void OpenUri (SafeUri uri, bool maybeVideo);
internal protected virtual bool DelayedInitialize {
get { return false; }
}
public bool IsInitialized { get; internal set; }
internal protected virtual void Initialize ()
{
}
public void Reset ()
{
CurrentTrackTimeStamp = DateTime.Now;
current_track = null;
OnStateChanged (idle_state);
}
public virtual void Close (bool fullShutdown)
{
if (fullShutdown) {
Reset ();
} else {
OnStateChanged (idle_state);
}
}
public virtual void Dispose ()
{
Close (true);
}
public void Open (SafeUri uri)
{
HandleOpen (new UnknownTrackInfo (uri));
}
public void Open (TrackInfo track)
{
pending_track = null;
HandleOpen (track);
}
public void SetNextTrack (SafeUri uri)
{
SetNextTrack (new UnknownTrackInfo (uri));
}
public void SetNextTrack (TrackInfo track)
{
HandleNextTrack (track);
}
private void HandleNextTrack (TrackInfo track)
{
pending_track = track;
if (current_state != PlayerState.Playing) {
// Pre-buffering the next track only makes sense when we're currently playing
// Instead, just open.
if (track != null && track.Uri != null) {
HandleOpen (track);
Play ();
}
return;
}
try {
// Setting the next track doesn't change the player state.
SetNextTrackUri (track == null ? null : track.Uri,
track == null || track.HasAttribute (TrackMediaAttributes.VideoStream) || track is UnknownTrackInfo);
} catch (Exception e) {
Log.Error ("Failed to pre-buffer next track", e);
}
}
private void HandleOpen (TrackInfo track)
{
var uri = track.Uri;
if (current_state != PlayerState.Idle && current_state != PlayerState.NotReady && current_state != PlayerState.Contacting) {
Close (false);
}
try {
CurrentTrackTimeStamp = DateTime.Now;
current_track = track;
OnStateChanged (PlayerState.Loading);
OpenUri (uri, track.HasAttribute (TrackMediaAttributes.VideoStream) || track is UnknownTrackInfo);
} catch (Exception e) {
Close (true);
OnEventChanged (new PlayerEventErrorArgs (e.Message));
}
}
public abstract void Play ();
public abstract void Pause ();
public abstract void Seek (uint position, bool accurate_seek);
public void Seek (uint position)
{
Seek (position, false);
}
public virtual void SetNextTrackUri (SafeUri uri, bool maybeVideo)
{
// Opening files on SetNextTrack is a sane default behaviour.
// This only wants to be overridden if the PlayerEngine sends out RequestNextTrack signals before EoS
OpenUri (uri, maybeVideo);
}
public virtual void VideoExpose (IntPtr displayContext, bool direct)
{
throw new NotImplementedException ("Engine must implement VideoExpose since this method only gets called when SupportsVideo is true");
}
public virtual void VideoWindowRealize (IntPtr displayContext)
{
throw new NotImplementedException ("Engine must implement VideoWindowRealize since this method only gets called when SupportsVideo is true");
}
public virtual IntPtr [] GetBaseElements ()
{
return null;
}
protected virtual void OnStateChanged (PlayerState state)
{
if (current_state == state) {
return;
}
if (idle_state == PlayerState.NotReady && state != PlayerState.Ready) {
Hyena.Log.Warning ("Engine must transition to the ready state before other states can be entered", false);
return;
} else if (idle_state == PlayerState.NotReady && state == PlayerState.Ready) {
idle_state = PlayerState.Idle;
}
last_state = current_state;
current_state = state;
Log.DebugFormat ("Player state change: {0} -> {1}", last_state, current_state);
OnEventChanged (new PlayerEventStateChangeArgs (last_state, current_state));
// Going to the Ready state automatically transitions to the Idle state
// The Ready state is advertised so one-time startup processes can easily
// happen outside of the engine itself
if (state == PlayerState.Ready) {
OnStateChanged (PlayerState.Idle);
}
}
protected void OnEventChanged (PlayerEvent evnt)
{
OnEventChanged (new PlayerEventArgs (evnt));
}
protected virtual void OnEventChanged (PlayerEventArgs args)
{
if (args.Event == PlayerEvent.StartOfStream && pending_track != null) {
Log.DebugFormat ("OnEventChanged called with StartOfStream. Replacing current_track with pending_track: \"{0}\"",
pending_track.DisplayTrackTitle);
CurrentTrackTimeStamp = DateTime.Now;
current_track = pending_track;
pending_track = null;
}
ThreadAssist.ProxyToMain (() => RaiseEventChanged (args));
}
private void RaiseEventChanged (PlayerEventArgs args)
{
PlayerEventHandler handler = EventChanged;
if (handler != null) {
handler (args);
}
}
private uint track_info_updated_timeout = 0;
protected void OnTagFound (StreamTag tag)
{
if (tag.Equals (StreamTag.Zero) || current_track == null
|| (current_track.Uri != null && current_track.Uri.IsFile)) {
return;
}
StreamTagger.TrackInfoMerge (current_track, tag);
if (track_info_updated_timeout <= 0) {
track_info_updated_timeout = Application.RunTimeout (250, OnTrackInfoUpdated);
}
}
private bool OnTrackInfoUpdated ()
{
TrackInfoUpdated ();
track_info_updated_timeout = 0;
return false;
}
public void TrackInfoUpdated ()
{
OnEventChanged (PlayerEvent.TrackInfoUpdated);
}
public abstract string GetSubtitleDescription (int index);
public TrackInfo CurrentTrack {
get { return current_track; }
}
public SafeUri CurrentUri {
get { return current_track == null ? null : current_track.Uri; }
}
public PlayerState CurrentState {
get { return current_state; }
}
public PlayerState LastState {
get { return last_state; }
}
public abstract ushort Volume {
get;
set;
}
public virtual bool CanSeek {
get { return true; }
}
public abstract uint Position {
get;
set;
}
public abstract uint Length {
get;
}
public abstract IEnumerable SourceCapabilities {
get;
}
public abstract IEnumerable ExplicitDecoderCapabilities {
get;
}
public abstract string Id {
get;
}
public abstract string Name {
get;
}
public abstract bool SupportsEqualizer {
get;
}
public abstract VideoDisplayContextType VideoDisplayContextType {
get;
}
public virtual IntPtr VideoDisplayContext {
set { }
get { return IntPtr.Zero; }
}
public abstract int SubtitleCount {
get;
}
public abstract int SubtitleIndex {
set;
}
public abstract SafeUri SubtitleUri {
set;
get;
}
public abstract bool InDvdMenu {
get;
}
public abstract void NotifyMouseMove (double x, double y);
public abstract void NotifyMouseButtonPressed (int button, double x, double y);
public abstract void NotifyMouseButtonReleased (int button, double x, double y);
public abstract void NavigateToLeftMenu ();
public abstract void NavigateToRightMenu ();
public abstract void NavigateToUpMenu ();
public abstract void NavigateToDownMenu ();
public abstract void NavigateToMenu ();
public abstract void ActivateCurrentMenu ();
public abstract void GoToNextChapter ();
public abstract void GoToPreviousChapter ();
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Utilities.Solvers
{
/// <summary>
/// ConstantViewSize solver scales to maintain a constant size relative to the view (currently tied to the Camera)
/// </summary>
[AddComponentMenu("Scripts/MRTK/SDK/ConstantViewSize")]
public class ConstantViewSize : Solver
{
#region ConstantViewSize Parameters
[Range(0f, 1f)]
[SerializeField]
[Tooltip("The object take up this percent vertically in our view (not technically a percent use 0.5 for 50%)")]
private float targetViewPercentV = 0.5f;
/// <summary>
/// The object take up this percent vertically in our view (not technically a percent use 0.5 for 50%)
/// </summary>
public float TargetViewPercentV
{
get { return targetViewPercentV; }
set { targetViewPercentV = value; }
}
[SerializeField]
[Tooltip("If the object is closer than MinDistance, the distance used is clamped here")]
private float minDistance = 0.5f;
/// <summary>
/// If the object is closer than MinDistance, the distance used is clamped here
/// </summary>
public float MinDistance
{
get { return minDistance; }
set { minDistance = value; }
}
[SerializeField]
[Tooltip("If the object is farther than MaxDistance, the distance used is clamped here")]
private float maxDistance = 3.5f;
/// <summary>
/// If the object is farther than MaxDistance, the distance used is clamped here
/// </summary>
public float MaxDistance
{
get { return maxDistance; }
set { maxDistance = value; }
}
[SerializeField]
[Tooltip("Minimum scale value possible (world space scale)")]
private float minScale = 0.01f;
/// <summary>
/// Minimum scale value possible (world space scale)
/// </summary>
public float MinScale
{
get { return minScale; }
set { minScale = value; }
}
[SerializeField]
[Tooltip("Maximum scale value possible (world space scale)")]
private float maxScale = 100f;
/// <summary>
/// Maximum scale value possible (world space scale)
/// </summary>
public float MaxScale
{
get { return maxScale; }
set { maxScale = value; }
}
[SerializeField]
[Tooltip("Used for dead zone for scaling")]
private float scaleBuffer = 0.01f;
/// <summary>
/// Used for dead zone for scaling
/// </summary>
public float ScaleBuffer
{
get { return scaleBuffer; }
set { scaleBuffer = value; }
}
[SerializeField]
[Tooltip("Overrides auto size calculation with provided manual size. If 0, solver calculates size")]
private float manualObjectSize = 0;
/// <summary>
/// Overrides auto size calculation with provided manual size. If 0, solver calculates size
/// </summary>
public float ManualObjectSize
{
get { return manualObjectSize; }
set
{
manualObjectSize = value;
RecalculateBounds();
}
}
public ScaleState ScaleState { get; private set; } = ScaleState.Static;
/// <summary>
/// 0 to 1 between MinScale and MaxScale. If current is less than max, then scaling is being applied.
/// This value is subject to inaccuracies due to smoothing/interpolation/momentum.
/// </summary>
public float CurrentScalePercent { get; private set; } = 1f;
/// <summary>
/// 0 to 1 between MinDistance and MaxDistance. If current is less than max, object is potentially on a surface [or some other condition like interpolating] (since it may still be on surface, but scale percent may be clamped at max).
/// This value is subject to inaccuracies due to smoothing/interpolation/momentum.
/// </summary>
public float CurrentDistancePercent { get; private set; } = 1f;
/// <summary>
/// Returns the scale to be applied based on the FOV. This scale will be multiplied by distance as part of
/// the final scale calculation, so this is the ratio of vertical fov to distance.
/// </summary>
public float FovScale
{
get
{
float cameraFovRadians = (CameraCache.Main.aspect * CameraCache.Main.fieldOfView) * Mathf.Deg2Rad;
float sinFov = Mathf.Sin(cameraFovRadians * 0.5f);
return 2f * targetViewPercentV * sinFov / objectSize;
}
}
#endregion
private float fovScalar = 1f;
private float objectSize = 1f;
protected override void Start()
{
base.Start();
RecalculateBounds();
}
/// <inheritdoc />
public override void SolverUpdate()
{
float lastScalePct = CurrentScalePercent;
if (SolverHandler.TransformTarget != null)
{
// Get current fov each time instead of trying to cache it. Can never count on init order these days
fovScalar = FovScale;
// Set the linked alt scale ahead of our work. This is an attempt to minimize jittering by having solvers work with an interpolated scale.
SolverHandler.AltScale.SetGoal(transform.localScale);
// Calculate scale based on distance from view. Do not interpolate so we can appear at a constant size if possible. Borrowed from greybox.
Vector3 targetPosition = SolverHandler.TransformTarget.position;
float distance = Mathf.Clamp(Vector3.Distance(transform.position, targetPosition), minDistance, maxDistance);
float scale = Mathf.Clamp(fovScalar * distance, minScale, maxScale);
GoalScale = Vector3.one * scale;
// Save some state information for external use
CurrentDistancePercent = Mathf.InverseLerp(minDistance, maxDistance, distance);
CurrentScalePercent = Mathf.InverseLerp(minScale, maxScale, scale);
}
float scaleDifference = (CurrentScalePercent - lastScalePct) / SolverHandler.DeltaTime;
if (scaleDifference > scaleBuffer)
{
ScaleState = ScaleState.Growing;
}
else if (scaleDifference < -scaleBuffer)
{
ScaleState = ScaleState.Shrinking;
}
else
{
ScaleState = ScaleState.Static;
}
}
/// <summary>
/// Attempts to calculate the size of the bounds which contains all child renderers for attached GameObject. This information is used in the core solver calculations
/// </summary>
public void RecalculateBounds()
{
float baseSize;
// If user set object size override apply, otherwise compute baseSize
if (manualObjectSize > 0)
{
baseSize = manualObjectSize;
}
else
{
Vector3 cachedScale = transform.root.localScale;
transform.root.localScale = Vector3.one;
var combinedBounds = new Bounds(transform.position, Vector3.zero);
var renderers = GetComponentsInChildren<Renderer>();
for (var i = 0; i < renderers.Length; i++)
{
combinedBounds.Encapsulate(renderers[i].bounds);
}
baseSize = combinedBounds.extents.magnitude;
transform.root.localScale = cachedScale;
}
if (baseSize > 0)
{
objectSize = baseSize;
}
else
{
Debug.LogWarning("ConstantViewSize: Object base size calculate was 0, defaulting to 1");
objectSize = 1f;
}
}
}
}
| |
// (c) Copyright Esri, 2010 - 2016
// This source is subject to the Apache 2.0 License.
// Please see http://www.apache.org/licenses/LICENSE-2.0.html for details.
// All other rights reserved.
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Resources;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geoprocessing;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.OSM.OSMClassExtension;
namespace ESRI.ArcGIS.OSM.GeoProcessing
{
[Guid("b0878ae8-a85d-4fee-8cce-4ed015e03e4e")]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("OSMEditor.OSMGPFeatureComparison")]
public class OSMGPFeatureComparison : ESRI.ArcGIS.Geoprocessing.IGPFunction2
{
string m_DisplayName = String.Empty;
int in_sourceFeatureClassNumber, in_sourceIntersectionFieldNumber, in_sourceRefIDsFieldNumber, in_MatchFeatureClassNumber, out_FeatureClassNumber;
ResourceManager resourceManager = null;
OSMGPFactory osmGPFactory = null;
public OSMGPFeatureComparison()
{
resourceManager = new ResourceManager("ESRI.ArcGIS.OSM.GeoProcessing.OSMGPToolsStrings", this.GetType().Assembly);
osmGPFactory = new OSMGPFactory();
}
#region "IGPFunction2 Implementations"
public ESRI.ArcGIS.esriSystem.UID DialogCLSID
{
get
{
return null;
}
}
public string DisplayName
{
get
{
if (String.IsNullOrEmpty(m_DisplayName))
{
m_DisplayName = osmGPFactory.GetFunctionName(OSMGPFactory.m_FeatureComparisonName).DisplayName;
}
return m_DisplayName;
}
}
public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message)
{
try
{
IGPUtilities3 gpUtilities3 = new GPUtilitiesClass() as IGPUtilities3;
if (TrackCancel == null)
{
TrackCancel = new CancelTrackerClass();
}
// decode in the input layers
IGPParameter in_SourceFeatureClassParameter = paramvalues.get_Element(in_sourceFeatureClassNumber) as IGPParameter;
IGPValue in_SourceFeatureGPValue = gpUtilities3.UnpackGPValue(in_SourceFeatureClassParameter) as IGPValue;
IFeatureClass sourceFeatureClass = null;
IQueryFilter queryFilter = null;
gpUtilities3.DecodeFeatureLayer((IGPValue)in_SourceFeatureGPValue, out sourceFeatureClass, out queryFilter);
if (sourceFeatureClass == null)
{
message.AddError(120027, resourceManager.GetString("GPTools_OSMGPFeatureComparison_source_nullpointer"));
return;
}
IGPParameter in_NumberOfIntersectionsFieldParameter = paramvalues.get_Element(in_sourceIntersectionFieldNumber) as IGPParameter;
IGPValue in_NumberOfIntersectionsFieldGPValue = gpUtilities3.UnpackGPValue(in_NumberOfIntersectionsFieldParameter) as IGPValue;
IGPParameter in_SourceRefIDFieldParameter = paramvalues.get_Element(in_sourceRefIDsFieldNumber) as IGPParameter;
IGPValue in_SourceRefIDFieldGPValue = gpUtilities3.UnpackGPValue(in_SourceRefIDFieldParameter) as IGPValue;
IGPParameter in_MatchFeatureClassParameter = paramvalues.get_Element(in_MatchFeatureClassNumber) as IGPParameter;
IGPValue in_MatchFeatureGPValue = gpUtilities3.UnpackGPValue(in_MatchFeatureClassParameter) as IGPValue;
IFeatureClass matchFeatureClass = null;
IQueryFilter matchQueryFilter = null;
gpUtilities3.DecodeFeatureLayer((IGPValue)in_MatchFeatureGPValue, out matchFeatureClass, out matchQueryFilter);
if (matchFeatureClass == null)
{
message.AddError(120028, resourceManager.GetString("GPTools_OSMGPFeatureComparison_match_nullpointer"));
return;
}
if (queryFilter != null)
{
if (((IGeoDataset)matchFeatureClass).SpatialReference != null)
{
queryFilter.set_OutputSpatialReference(sourceFeatureClass.ShapeFieldName, ((IGeoDataset)matchFeatureClass).SpatialReference);
}
}
IWorkspace sourceWorkspace = ((IDataset) sourceFeatureClass).Workspace;
IWorkspaceEdit sourceWorkspaceEdit = sourceWorkspace as IWorkspaceEdit;
if (sourceWorkspace.Type == esriWorkspaceType.esriRemoteDatabaseWorkspace)
{
sourceWorkspaceEdit = sourceWorkspace as IWorkspaceEdit;
sourceWorkspaceEdit.StartEditing(false);
sourceWorkspaceEdit.StartEditOperation();
}
// get an overall feature count as that determines the progress indicator
int featureCount = ((ITable)sourceFeatureClass).RowCount(queryFilter);
// set up the progress indicator
IStepProgressor stepProgressor = TrackCancel as IStepProgressor;
if (stepProgressor != null)
{
stepProgressor.MinRange = 0;
stepProgressor.MaxRange = featureCount;
stepProgressor.Position = 0;
stepProgressor.Message = resourceManager.GetString("GPTools_OSMGPFeatureComparison_progressMessage");
stepProgressor.StepValue = 1;
stepProgressor.Show();
}
int numberOfIntersectionsFieldIndex = sourceFeatureClass.FindField(in_NumberOfIntersectionsFieldGPValue.GetAsText());
int sourceRefIDFieldIndex = sourceFeatureClass.FindField(in_SourceRefIDFieldGPValue.GetAsText());
ISpatialFilter matchFCSpatialFilter = new SpatialFilter();
matchFCSpatialFilter.GeometryField = matchFeatureClass.ShapeFieldName;
matchFCSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
matchFCSpatialFilter.WhereClause = matchQueryFilter.WhereClause;
using (ComReleaser comReleaser = new ComReleaser())
{
IFeatureCursor sourceFeatureCursor = sourceFeatureClass.Search(queryFilter, false);
comReleaser.ManageLifetime(sourceFeatureCursor);
IFeature sourceFeature = null;
while ((sourceFeature = sourceFeatureCursor.NextFeature()) != null)
{
int numberOfIntersections = 0;
string intersectedFeatures = String.Empty;
IPolyline sourceLine = sourceFeature.Shape as IPolyline;
matchFCSpatialFilter.Geometry = sourceLine;
using (ComReleaser innerReleaser = new ComReleaser())
{
IFeatureCursor matchFeatureCursor = matchFeatureClass.Search(matchFCSpatialFilter, false);
innerReleaser.ManageLifetime(matchFeatureCursor);
IFeature matchFeature = null;
while ((matchFeature = matchFeatureCursor.NextFeature()) != null)
{
IPointCollection intersectionPointCollection = null;
try
{
ITopologicalOperator topoOperator = sourceLine as ITopologicalOperator;
if (topoOperator.IsSimple == false)
{
((ITopologicalOperator2)topoOperator).IsKnownSimple_2 = false;
topoOperator.Simplify();
}
IPolyline matchPolyline = matchFeature.Shape as IPolyline;
if (queryFilter != null)
{
matchPolyline.Project(sourceLine.SpatialReference);
}
if (((ITopologicalOperator)matchPolyline).IsSimple == false)
{
((ITopologicalOperator2)matchPolyline).IsKnownSimple_2 = false;
((ITopologicalOperator)matchPolyline).Simplify();
}
intersectionPointCollection = topoOperator.Intersect(matchPolyline, esriGeometryDimension.esriGeometry0Dimension) as IPointCollection;
}
catch (Exception ex)
{
message.AddWarning(ex.Message);
continue;
}
if (intersectionPointCollection != null && intersectionPointCollection.PointCount > 0)
{
numberOfIntersections = numberOfIntersections + intersectionPointCollection.PointCount;
if (String.IsNullOrEmpty(intersectedFeatures))
{
intersectedFeatures = matchFeature.OID.ToString();
}
else
{
intersectedFeatures = intersectedFeatures + "," + matchFeature.OID.ToString();
}
}
}
if (numberOfIntersectionsFieldIndex > -1)
{
sourceFeature.set_Value(numberOfIntersectionsFieldIndex, numberOfIntersections);
}
if (sourceRefIDFieldIndex > -1)
{
if (intersectedFeatures.Length > sourceFeatureClass.Fields.get_Field(sourceRefIDFieldIndex).Length)
{
sourceFeature.set_Value(sourceRefIDFieldIndex, intersectedFeatures.Substring(0, sourceFeatureClass.Fields.get_Field(sourceRefIDFieldIndex).Length));
}
else
{
sourceFeature.set_Value(sourceRefIDFieldIndex, intersectedFeatures);
}
}
}
try
{
sourceFeature.Store();
}
catch (Exception ex)
{
message.AddWarning(ex.Message);
}
if (stepProgressor != null)
{
// update the progress UI
stepProgressor.Step();
}
// check for user cancellation
if (TrackCancel.Continue() == false)
{
return;
}
}
}
if (sourceWorkspaceEdit != null)
{
sourceWorkspaceEdit.StopEditOperation();
sourceWorkspaceEdit.StopEditing(true);
}
if (stepProgressor != null)
{
stepProgressor.Hide();
}
}
catch (Exception ex)
{
message.AddAbort(ex.Message);
}
}
public ESRI.ArcGIS.esriSystem.IName FullName
{
get
{
IName fullName = null;
if (osmGPFactory != null)
{
fullName = osmGPFactory.GetFunctionName(OSMGPFactory.m_FeatureComparisonName) as IName;
}
return fullName;
}
}
public object GetRenderer(ESRI.ArcGIS.Geoprocessing.IGPParameter pParam)
{
return null;
}
public int HelpContext
{
get
{
return 0;
}
}
public string HelpFile
{
get
{
return String.Empty;
}
}
public bool IsLicensed()
{
// as an open-source tool it will also be licensed
return true;
}
public string MetadataFile
{
get
{
string metadafile = "gpfeaturecomparison.xml";
try
{
string[] languageid = System.Threading.Thread.CurrentThread.CurrentUICulture.Name.Split("-".ToCharArray());
string ArcGISInstallationLocation = OSMGPFactory.GetArcGIS10InstallLocation();
string localizedMetaDataFileShort = ArcGISInstallationLocation + System.IO.Path.DirectorySeparatorChar.ToString() + "help" + System.IO.Path.DirectorySeparatorChar.ToString() + "gp" + System.IO.Path.DirectorySeparatorChar.ToString() + "osmgpupload_" + languageid[0] + ".xml";
string localizedMetaDataFileLong = ArcGISInstallationLocation + System.IO.Path.DirectorySeparatorChar.ToString() + "help" + System.IO.Path.DirectorySeparatorChar.ToString() + "gp" + System.IO.Path.DirectorySeparatorChar.ToString() + "osmgpupload_" + System.Threading.Thread.CurrentThread.CurrentUICulture.Name + ".xml";
if (System.IO.File.Exists(localizedMetaDataFileShort))
{
metadafile = localizedMetaDataFileShort;
}
else if (System.IO.File.Exists(localizedMetaDataFileLong))
{
metadafile = localizedMetaDataFileLong;
}
}
catch { }
return metadafile;
}
}
public string Name
{
get
{
return OSMGPFactory.m_FeatureComparisonName;
}
}
public ESRI.ArcGIS.esriSystem.IArray ParameterInfo
{
get
{
IArray parameters = new ArrayClass();
// source feature class
IGPParameterEdit3 in_sourceFeaturesParameter = new GPParameterClass() as IGPParameterEdit3;
in_sourceFeaturesParameter.DataType = new GPFeatureLayerTypeClass();
in_sourceFeaturesParameter.Direction = esriGPParameterDirection.esriGPParameterDirectionInput;
in_sourceFeaturesParameter.DisplayName = resourceManager.GetString("GPTools_OSMGPFeatureComparison_inputsourcefeatures_displayname");
in_sourceFeaturesParameter.Name = "in_sourceFeatures";
in_sourceFeaturesParameter.ParameterType = esriGPParameterType.esriGPParameterTypeRequired;
IGPFeatureClassDomain sourceFeatureClassDomain = new GPFeatureClassDomainClass();
sourceFeatureClassDomain.AddType(esriGeometryType.esriGeometryPolyline);
in_sourceFeaturesParameter.Domain = (IGPDomain)sourceFeatureClassDomain;
in_sourceFeatureClassNumber = 0;
parameters.Add((IGPParameter3)in_sourceFeaturesParameter);
// input field to hold the number of intersections
IGPParameterEdit3 in_sourceIntersectionFieldParameter = new GPParameterClass() as IGPParameterEdit3;
in_sourceIntersectionFieldParameter.DataType = new FieldTypeClass();
in_sourceIntersectionFieldParameter.Direction = esriGPParameterDirection.esriGPParameterDirectionInput;
in_sourceIntersectionFieldParameter.DisplayName = resourceManager.GetString("GPTools_OSMGPFeatureComparison_inputintersectnumber_displayname");
in_sourceIntersectionFieldParameter.Name = "in_number_of_intersections_field";
in_sourceIntersectionFieldParameter.ParameterType = esriGPParameterType.esriGPParameterTypeRequired;
in_sourceIntersectionFieldParameter.AddDependency("in_sourceFeatures");
IGPFieldDomain fieldDomain = new GPFieldDomainClass();
fieldDomain.AddType(esriFieldType.esriFieldTypeInteger);
in_sourceIntersectionFieldParameter.Domain = fieldDomain as IGPDomain;
in_sourceIntersectionFieldNumber = 1;
parameters.Add((IGPParameter3)in_sourceIntersectionFieldParameter);
// input field to hold the intersected OIDs (comma separated)
IGPParameterEdit3 in_sourceRefIDsFieldParameter = new GPParameterClass() as IGPParameterEdit3;
in_sourceRefIDsFieldParameter.DataType = new FieldTypeClass();
in_sourceRefIDsFieldParameter.Direction = esriGPParameterDirection.esriGPParameterDirectionInput;
in_sourceRefIDsFieldParameter.DisplayName = resourceManager.GetString("GPTools_OSMGPFeatureComparison_inputintersectids_displayname");
in_sourceRefIDsFieldParameter.Name = "in_intersected_ids_field";
in_sourceRefIDsFieldParameter.ParameterType = esriGPParameterType.esriGPParameterTypeRequired;
in_sourceRefIDsFieldParameter.AddDependency("in_sourceFeatures");
IGPFieldDomain id_fieldDomain = new GPFieldDomainClass();
id_fieldDomain.AddType(esriFieldType.esriFieldTypeString);
in_sourceRefIDsFieldParameter.Domain = id_fieldDomain as IGPDomain;
in_sourceRefIDsFieldNumber = 2;
parameters.Add((IGPParameter3)in_sourceRefIDsFieldParameter);
// input feature class
IGPParameterEdit3 in_MatchFeatureClassParameter = new GPParameterClass() as IGPParameterEdit3;
in_MatchFeatureClassParameter.DataType = new GPFeatureLayerTypeClass();
in_MatchFeatureClassParameter.Direction = esriGPParameterDirection.esriGPParameterDirectionInput;
in_MatchFeatureClassParameter.DisplayName = resourceManager.GetString("GPTools_OSMGPFeatureComparison_inputmatchfeatures_displayname");
in_MatchFeatureClassParameter.Name = "in_matchFeatures";
in_MatchFeatureClassParameter.ParameterType = esriGPParameterType.esriGPParameterTypeRequired;
IGPFeatureClassDomain matchFeatureClassDomain = new GPFeatureClassDomainClass();
matchFeatureClassDomain.AddType(esriGeometryType.esriGeometryPolyline);
in_MatchFeatureClassParameter.Domain = (IGPDomain)matchFeatureClassDomain;
in_MatchFeatureClassNumber = 3;
parameters.Add((IGPParameter3)in_MatchFeatureClassParameter);
// output feature class
IGPParameterEdit3 out_FeatureClassParameter = new GPParameterClass() as IGPParameterEdit3;
out_FeatureClassParameter.DataType = new GPFeatureLayerTypeClass();
out_FeatureClassParameter.Direction = esriGPParameterDirection.esriGPParameterDirectionOutput;
out_FeatureClassParameter.DisplayName = resourceManager.GetString("GPTools_OSMGPFeatureComparison_outputfeatures_displayname");
out_FeatureClassParameter.Name = "out_sourceFeatures";
out_FeatureClassParameter.ParameterType = esriGPParameterType.esriGPParameterTypeDerived;
out_FeatureClassParameter.AddDependency("in_sourceFeatures");
out_FeatureClassNumber = 4;
parameters.Add((IGPParameter3)out_FeatureClassParameter);
return parameters;
}
}
public void UpdateMessages(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr, ESRI.ArcGIS.Geodatabase.IGPMessages Messages)
{
}
public void UpdateParameters(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr)
{
}
public ESRI.ArcGIS.Geodatabase.IGPMessages Validate(ESRI.ArcGIS.esriSystem.IArray paramvalues, bool updateValues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr)
{
return default(ESRI.ArcGIS.Geodatabase.IGPMessages);
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.TeamFoundation.DistributedTask.Pipelines;
using Microsoft.VisualStudio.Services.Agent.Util;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
namespace Microsoft.VisualStudio.Services.Agent.Worker.Build
{
/// <summary>
/// This class is used to keep track of which repositories are being fetched and
/// where they will be fetched to.
/// This information is tracked per definition.
/// </summary>
public sealed class TrackingConfig : TrackingConfigBase
{
public const string FileFormatVersionJsonProperty = "fileFormatVersion";
// The parameterless constructor is required for deserialization.
public TrackingConfig()
{
RepositoryTrackingInfo = new List<RepositoryTrackingInfo>();
}
public TrackingConfig(
IExecutionContext executionContext,
LegacyTrackingConfig copy,
string sourcesDirectoryNameOnly,
string repositoryType,
bool useNewArtifactsDirectoryName = false)
: this()
{
ArgUtil.NotNull(executionContext, nameof(executionContext));
ArgUtil.NotNull(copy, nameof(copy));
// Set the directories.
BuildDirectory = Path.GetFileName(copy.BuildDirectory); // Just take the portion after _work folder.
string artifactsDirectoryNameOnly =
useNewArtifactsDirectoryName ? Constants.Build.Path.ArtifactsDirectory : Constants.Build.Path.LegacyArtifactsDirectory;
ArtifactsDirectory = Path.Combine(BuildDirectory, artifactsDirectoryNameOnly);
SourcesDirectory = Path.Combine(BuildDirectory, sourcesDirectoryNameOnly);
TestResultsDirectory = Path.Combine(BuildDirectory, Constants.Build.Path.TestResultsDirectory);
// Set the other properties.
CollectionId = copy.CollectionId;
CollectionUrl = executionContext.Variables.System_TFCollectionUrl;
DefinitionId = copy.DefinitionId;
HashKey = copy.HashKey;
RepositoryType = repositoryType;
RepositoryUrl = copy.RepositoryUrl;
System = copy.System;
// Let's make sure this file gets cleaned up by the garbage collector
LastRunOn = new DateTime(1,1,1,0,0,0,DateTimeKind.Utc);
}
public TrackingConfig Clone()
{
TrackingConfig clone = this.MemberwiseClone() as TrackingConfig;
clone.RepositoryTrackingInfo = new List<RepositoryTrackingInfo>(this.RepositoryTrackingInfo);
return clone;
}
public TrackingConfig(
IExecutionContext executionContext,
IList<RepositoryResource> repositories,
int buildDirectory)
: this()
{
ArgUtil.NotNull(executionContext, nameof(executionContext));
ArgUtil.NotNull(repositories, nameof(repositories));
// Get the repo that we are going to checkout first to create the tracking info from.
var primaryRepository = RepositoryUtil.GetPrimaryRepository(repositories);
// Set the directories.
BuildDirectory = buildDirectory.ToString(CultureInfo.InvariantCulture);
ArtifactsDirectory = Path.Combine(BuildDirectory, Constants.Build.Path.ArtifactsDirectory);
SourcesDirectory = Path.Combine(BuildDirectory, Constants.Build.Path.SourcesDirectory);
TestResultsDirectory = Path.Combine(BuildDirectory, Constants.Build.Path.TestResultsDirectory);
// Set the other properties.
CollectionId = executionContext.Variables.System_CollectionId;
DefinitionId = executionContext.Variables.System_DefinitionId;
RepositoryUrl = primaryRepository?.Url.AbsoluteUri;
RepositoryType = primaryRepository?.Type;
System = BuildSystem;
UpdateJobRunProperties(executionContext);
foreach (var repo in repositories)
{
RepositoryTrackingInfo.Add(new Build.RepositoryTrackingInfo(repo, SourcesDirectory));
}
// Now that we have all the repositories set up, we can compute the config hash
HashKey = TrackingConfigHashAlgorithm.ComputeHash(CollectionId, DefinitionId, RepositoryTrackingInfo);
}
[JsonIgnore]
public string FileLocation { get; set; }
[JsonProperty("build_artifactstagingdirectory")]
public string ArtifactsDirectory { get; set; }
[JsonProperty("agent_builddirectory")]
public string BuildDirectory { get; set; }
public string CollectionUrl { get; set; }
public string DefinitionName { get; set; }
public List<RepositoryTrackingInfo> RepositoryTrackingInfo { get; set; }
// For back compat, we will ignore this property if it's null or empty
public bool ShouldSerializeRepositoryTrackingInfo()
{
return RepositoryTrackingInfo != null && RepositoryTrackingInfo.Count > 0;
}
[JsonProperty(FileFormatVersionJsonProperty)]
public int FileFormatVersion
{
get
{
// Any time this gets updated, the agent cannot be rolled back.
// Back compat is guaranteed here, forward compat is not.
return 3;
}
set
{
// Version 3 changes:
// CollectionName was removed.
// CollectionUrl was added.
switch (value)
{
case 3:
case 2:
break;
default:
// Should never reach here.
throw new NotSupportedException();
}
}
}
[JsonIgnore]
public DateTimeOffset? LastRunOn { get; set; }
[JsonProperty("lastRunOn")]
[EditorBrowsableAttribute(EditorBrowsableState.Never)]
public string LastRunOnString
{
get
{
return string.Format(CultureInfo.InvariantCulture, "{0}", LastRunOn);
}
set
{
if (string.IsNullOrEmpty(value))
{
LastRunOn = null;
return;
}
LastRunOn = DateTimeOffset.Parse(value, CultureInfo.InvariantCulture);
}
}
public string RepositoryType { get; set; }
[JsonIgnore]
public DateTimeOffset? LastMaintenanceAttemptedOn { get; set; }
[JsonProperty("lastMaintenanceAttemptedOn")]
[EditorBrowsableAttribute(EditorBrowsableState.Never)]
public string LastMaintenanceAttemptedOnString
{
get
{
return string.Format(CultureInfo.InvariantCulture, "{0}", LastMaintenanceAttemptedOn);
}
set
{
if (string.IsNullOrEmpty(value))
{
LastMaintenanceAttemptedOn = null;
return;
}
LastMaintenanceAttemptedOn = DateTimeOffset.Parse(value, CultureInfo.InvariantCulture);
}
}
[JsonIgnore]
public DateTimeOffset? LastMaintenanceCompletedOn { get; set; }
[JsonProperty("lastMaintenanceCompletedOn")]
[EditorBrowsableAttribute(EditorBrowsableState.Never)]
public string LastMaintenanceCompletedOnString
{
get
{
return string.Format(CultureInfo.InvariantCulture, "{0}", LastMaintenanceCompletedOn);
}
set
{
if (string.IsNullOrEmpty(value))
{
LastMaintenanceCompletedOn = null;
return;
}
LastMaintenanceCompletedOn = DateTimeOffset.Parse(value, CultureInfo.InvariantCulture);
}
}
[JsonProperty("build_sourcesdirectory")]
public string SourcesDirectory { get; set; }
[JsonProperty("common_testresultsdirectory")]
public string TestResultsDirectory { get; set; }
public void UpdateJobRunProperties(IExecutionContext executionContext)
{
ArgUtil.NotNull(executionContext, nameof(executionContext));
CollectionUrl = executionContext.Variables.System_TFCollectionUrl;
DefinitionName = executionContext.Variables.Build_DefinitionName;
LastRunOn = DateTimeOffset.Now;
}
}
public class RepositoryTrackingInfo
{
public RepositoryTrackingInfo(RepositoryResource repositoryResource, string sourcesDirectoryRoot)
{
if (repositoryResource != null)
{
Identifier = repositoryResource.Alias;
RepositoryType = repositoryResource.Type;
RepositoryUrl = repositoryResource.Url.AbsoluteUri;
SourcesDirectory = Path.Combine(sourcesDirectoryRoot, RepositoryUtil.GetCloneDirectory(repositoryResource));
}
}
public RepositoryTrackingInfo() { }
public string Identifier { get; set; }
public string RepositoryType { get; set; }
public string RepositoryUrl { get; set; }
public string SourcesDirectory { get; set; }
}
}
| |
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 SDammann.WebApi.Versioning.TestApi.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;
}
}
}
| |
/* ====================================================================
*/
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
namespace Oranikle.ReportDesigner
{
/// <summary>
/// Summary description for DialogNew.
/// </summary>
public class DialogNew : System.Windows.Forms.Form
{
private System.Windows.Forms.ListView listNewChoices;
private Oranikle.Studio.Controls.StyledButton btnOK;
private Oranikle.Studio.Controls.StyledButton btnCancel;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private System.Windows.Forms.Panel panel1;
private string _resultType;
public DialogNew()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
listNewChoices.Clear();
listNewChoices.BeginUpdate();
ListViewItem lvi = new ListViewItem("Blank");
listNewChoices.Items.Add(lvi);
lvi = new ListViewItem("Data Base");
listNewChoices.Items.Add(lvi);
listNewChoices.LabelWrap = true;
listNewChoices.Select();
listNewChoices.EndUpdate();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.listNewChoices = new System.Windows.Forms.ListView();
this.btnOK = new Oranikle.Studio.Controls.StyledButton();
this.btnCancel = new Oranikle.Studio.Controls.StyledButton();
this.panel1 = new System.Windows.Forms.Panel();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// listNewChoices
//
this.listNewChoices.Dock = System.Windows.Forms.DockStyle.Fill;
this.listNewChoices.HideSelection = false;
this.listNewChoices.Location = new System.Drawing.Point(0, 0);
this.listNewChoices.MultiSelect = false;
this.listNewChoices.Name = "listNewChoices";
this.listNewChoices.Size = new System.Drawing.Size(542, 403);
this.listNewChoices.TabIndex = 0;
this.listNewChoices.UseCompatibleStateImageBehavior = false;
this.listNewChoices.ItemActivate += new System.EventHandler(this.listNewChoices_ItemActivate);
this.listNewChoices.SelectedIndexChanged += new System.EventHandler(this.listNewChoices_SelectedIndexChanged);
//
// btnOK
//
this.btnOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnOK.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.btnOK.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.btnOK.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.btnOK.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.btnOK.Enabled = false;
this.btnOK.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnOK.Font = new System.Drawing.Font("Arial", 9F);
this.btnOK.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.btnOK.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnOK.Location = new System.Drawing.Point(374, 4);
this.btnOK.Name = "btnOK";
this.btnOK.OverriddenSize = null;
this.btnOK.Size = new System.Drawing.Size(75, 21);
this.btnOK.TabIndex = 1;
this.btnOK.Text = "OK";
this.btnOK.UseVisualStyleBackColor = true;
this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
//
// btnCancel
//
this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnCancel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.btnCancel.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.btnCancel.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.btnCancel.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnCancel.Font = new System.Drawing.Font("Arial", 9F);
this.btnCancel.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.btnCancel.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnCancel.Location = new System.Drawing.Point(462, 4);
this.btnCancel.Name = "btnCancel";
this.btnCancel.OverriddenSize = null;
this.btnCancel.Size = new System.Drawing.Size(75, 21);
this.btnCancel.TabIndex = 2;
this.btnCancel.Text = "Cancel";
this.btnCancel.UseVisualStyleBackColor = true;
//
// panel1
//
this.panel1.Controls.Add(this.btnOK);
this.panel1.Controls.Add(this.btnCancel);
this.panel1.Dock = System.Windows.Forms.DockStyle.Bottom;
this.panel1.Location = new System.Drawing.Point(0, 371);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(542, 32);
this.panel1.TabIndex = 3;
//
// DialogNew
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(228)))), ((int)(((byte)(241)))), ((int)(((byte)(249)))));
this.ClientSize = new System.Drawing.Size(542, 403);
this.Controls.Add(this.panel1);
this.Controls.Add(this.listNewChoices);
this.Name = "DialogNew";
this.Text = "New";
this.panel1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private void listNewChoices_ItemActivate(object sender, System.EventArgs e)
{
foreach (ListViewItem lvi in listNewChoices.SelectedItems)
{
_resultType = lvi.Text;
break;
}
DialogResult = DialogResult.OK;
this.Close();
}
private void btnOK_Click(object sender, System.EventArgs e)
{
DialogResult = DialogResult.OK;
this.Close();
}
private void listNewChoices_SelectedIndexChanged(object sender, System.EventArgs e)
{
foreach (ListViewItem lvi in listNewChoices.SelectedItems)
{
_resultType = lvi.Text;
break;
}
btnOK.Enabled = true;
}
public string ResultType
{
get {return _resultType;}
}
}
}
| |
/*
* FileVersionInfo.cs - Implementation of the
* "System.Diagnostics.FileVersionInfo" class.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Diagnostics
{
#if CONFIG_EXTENDED_DIAGNOSTICS
using System.IO;
public sealed class FileVersionInfo
{
// Internal state.
private String comments;
private String companyName;
private int fileBuildPart;
private String fileDescription;
private int fileMajorPart;
private int fileMinorPart;
private String fileName;
private int filePrivatePart;
private String internalName;
private bool isDebug;
private bool isPatched;
private bool isPreRelease;
private bool isPrivateBuild;
private bool isSpecialBuild;
private String language;
private String legalCopyright;
private String legalTrademarks;
private String originalFilename;
private String privateBuild;
private int productBuildPart;
private int productMajorPart;
private int productMinorPart;
private String productName;
private int productPrivatePart;
private String specialBuild;
// Constructor.
private FileVersionInfo(String fileName)
{
this.fileName = fileName;
}
// Properties.
public String Comments
{
get
{
return comments;
}
}
public String CompanyName
{
get
{
return companyName;
}
}
public int FileBuildPart
{
get
{
return fileBuildPart;
}
}
public String FileDescription
{
get
{
return fileDescription;
}
}
public int FileMajorPart
{
get
{
return fileMajorPart;
}
}
public int FileMinorPart
{
get
{
return fileMinorPart;
}
}
public String FileName
{
get
{
return fileName;
}
}
public int FilePrivatePart
{
get
{
return filePrivatePart;
}
}
public String FileVersion
{
get
{
return (new Version(FileMajorPart, FileMinorPart,
FileBuildPart, FilePrivatePart))
.ToString();
}
}
public String InternalName
{
get
{
return internalName;
}
}
public bool IsDebug
{
get
{
return isDebug;
}
}
public bool IsPatched
{
get
{
return isPatched;
}
}
public bool IsPreRelease
{
get
{
return isPreRelease;
}
}
public bool IsPrivateBuild
{
get
{
return isPrivateBuild;
}
}
public bool IsSpecialBuild
{
get
{
return isSpecialBuild;
}
}
public String Language
{
get
{
return language;
}
}
public String LegalCopyright
{
get
{
return legalCopyright;
}
}
public String LegalTrademarks
{
get
{
return legalTrademarks;
}
}
public String OriginalFilename
{
get
{
return originalFilename;
}
}
public String PrivateBuild
{
get
{
return privateBuild;
}
}
public int ProductBuildPart
{
get
{
return productBuildPart;
}
}
public int ProductMajorPart
{
get
{
return productMajorPart;
}
}
public int ProductMinorPart
{
get
{
return productMinorPart;
}
}
public String ProductName
{
get
{
return productName;
}
}
public int ProductPrivatePart
{
get
{
return productPrivatePart;
}
}
public String ProductVersion
{
get
{
return (new Version(ProductMajorPart, ProductMinorPart,
ProductBuildPart, ProductPrivatePart))
.ToString();
}
}
public String SpecialBuild
{
get
{
return specialBuild;
}
}
// Convert this object into a string.
public override String ToString()
{
// We don't support getting Windows version information
// in this implementation, so all we have to do is return
// the filename information.
return "File: " + fileName + Environment.NewLine;
}
// Get version information for a file.
public static FileVersionInfo GetVersionInfo(String fileName)
{
// We don't support getting Windows version information
// in this implementation, so all we have to do is return
// an object that contains the filename.
if(fileName == null)
{
throw new ArgumentNullException("fileName");
}
return new FileVersionInfo(Path.GetFullPath(fileName));
}
}; // class FileVersionInfo
#endif // CONFIG_EXTENDED_DIAGNOSTICS
}; // namespace System.Diagnostics
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
namespace Site
{
using Adxstudio.Xrm.Core.Flighting;
using System;
using System.Configuration;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Helpers;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Profile;
using System.Web.Routing;
using System.Web.Security;
using System.Web.WebPages;
using Adxstudio.Xrm;
using Adxstudio.Xrm.Core.Telemetry;
using Adxstudio.Xrm.Web;
using Adxstudio.Xrm.Web.Mvc;
using Microsoft.Xrm.Portal.Configuration;
using Adxstudio.Xrm.AspNet.Cms;
public class Global : HttpApplication
{
private static bool _setupRunning;
void Application_Start(object sender, EventArgs e)
{
AntiForgeryConfig.CookieName = "__RequestVerificationToken"; // static name as its dependent on the ajax handler.
MvcHandler.DisableMvcResponseHeader = true;
_setupRunning = SetupConfig.ApplicationStart();
if (_setupRunning) return;
var areaRegistrationState = new PortalAreaRegistrationState();
Application[typeof(IPortalAreaRegistrationState).FullName] = areaRegistrationState;
AreaRegistration.RegisterAllAreas(areaRegistrationState);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
// Set the culture of the current request's thread to the current website's language.
// This is necessary in .NET 4.6 and above because the current thread doesn't retain the
// thread culture set within the Site.Startup OWIN middleware.
// https://stackoverflow.com/questions/36455801/owinmiddleware-doesnt-preserve-culture-change-in-net-4-6
// https://connect.microsoft.com/VisualStudio/feedback/details/2455357
// https://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo(v=vs.110).aspx#Async
// https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/mitigation-culture-and-asynchronous-operations
var languageContext = Context.GetContextLanguageInfo();
if (languageContext?.ContextLanguage != null)
{
ContextLanguageInfo.SetCultureInfo(languageContext.ContextLanguage.Lcid);
}
}
protected void Session_Start(object sender, EventArgs e)
{
Session["init"] = 0;
if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.TelemetryFeatureUsage)
// ignore non-user pings
&& TelemetryState.IsTelemetryEnabledUserAgent()
// ignore requests to and referred requests from specific paths
&& TelemetryState.IsTelemetryEnabledRequestPage()
// only report this telemetry when the portal is configured
&& SetupConfig.IsPortalConfigured())
{
PortalFeatureTrace.TraceInstance.LogSessionInfo(FeatureTraceCategory.SessionStart);
}
}
void Application_Error(object sender, EventArgs e)
{
WebEventSource.Log.UnhandledException(Server.GetLastError());
}
public override string GetVaryByCustomString(HttpContext context, string arg)
{
switch (arg)
{
case "roles":
return GetVaryByRolesString(context);
case "roles;website":
return GetVaryByRolesAndWebsiteString(context);
case "user":
return GetVaryByUserString(context);
case "user;website":
return GetVaryByUserAndWebsiteString(context);
case "website":
return GetVaryByWebsiteString(context);
case "culture":
return CultureInfo.CurrentCulture.LCID.ToString();
case "user;language":
return string.Format("{0}{1}", GetVaryByUserString(context), GetVaryByLanguageString());
case "user;website;language":
return string.Format("{0}{1}", GetVaryByUserAndWebsiteString(context), GetVaryByLanguageString());
case "website;language":
return string.Format("{0}{1}", GetVaryByWebsiteString(context), GetVaryByLanguageString());
}
return base.GetVaryByCustomString(context, arg);
}
public void Profile_MigrateAnonymous(object sender, ProfileMigrateEventArgs e)
{
var portalAreaRegistrationState = Application[typeof(IPortalAreaRegistrationState).FullName] as IPortalAreaRegistrationState;
if (portalAreaRegistrationState != null)
{
portalAreaRegistrationState.OnProfile_MigrateAnonymous(sender, e);
}
}
private static string GetVaryByLanguageString()
{
var langContext = HttpContext.Current.GetContextLanguageInfo();
if (langContext.IsCrmMultiLanguageEnabled)
{
return string.Format(",{0}", langContext.ContextLanguage.Code);
}
return string.Empty;
}
private static string GetVaryByDisplayModesString(HttpContext context)
{
var availableDisplayModeIds = DisplayModeProvider.Instance
.GetAvailableDisplayModesForContext(context.Request.RequestContext.HttpContext, null)
.Select(mode => mode.DisplayModeId);
return string.Join(",", availableDisplayModeIds);
}
private static string GetVaryByRolesString(HttpContext context)
{
// If the role system is not enabled, fall back to varying cache by user.
if (!Roles.Enabled)
{
return GetVaryByUserString(context);
}
var roles = context.User != null && context.User.Identity != null && context.User.Identity.IsAuthenticated
? Roles.GetRolesForUser()
.OrderBy(role => role)
.Aggregate(new StringBuilder(), (sb, role) => sb.AppendFormat("[{0}]", role))
.ToString()
: string.Empty;
return string.Format("IsAuthenticated={0},Roles={1},DisplayModes={2}",
context.Request.IsAuthenticated,
roles.GetHashCode(),
GetVaryByDisplayModesString(context).GetHashCode());
}
private static string GetVaryByRolesAndWebsiteString(HttpContext context)
{
return string.Format("{0},{1}", GetVaryByRolesString(context), GetVaryByWebsiteString(context));
}
private static string GetVaryByUserString(HttpContext context)
{
return string.Format("IsAuthenticated={0},Identity={1},Session={2},DisplayModes={3}",
context.Request.IsAuthenticated,
GetIdentity(context),
GetSessionId(context),
GetVaryByDisplayModesString(context).GetHashCode());
}
private static object GetIdentity(HttpContext context)
{
return context.Request.IsAuthenticated && context.User != null && context.User.Identity != null
? context.User.Identity.Name
: string.Empty;
}
private static readonly SessionStateSection SessionStateConfigurationSection = ConfigurationManager.GetSection("system.web/sessionState") as SessionStateSection;
private static object GetSessionId(HttpContext context)
{
if (!context.Request.IsAuthenticated || SessionStateConfigurationSection == null)
{
return string.Empty;
}
var sessionCookie = context.Request.Cookies[SessionStateConfigurationSection.CookieName];
return sessionCookie == null ? string.Empty : sessionCookie.Value;
}
private static string GetVaryByUserAndWebsiteString(HttpContext context)
{
return string.Format("{0},{1}", GetVaryByUserString(context), GetVaryByWebsiteString(context));
}
private static string GetVaryByWebsiteString(HttpContext context)
{
var websiteId = GetWebsiteIdFromOwinContext(context) ?? GetWebsiteIdFromPortalContext(context);
return websiteId == null ? "Website=" : string.Format("Website={0}", websiteId.GetHashCode());
}
private static string GetWebsiteIdFromOwinContext(HttpContext context)
{
var owinContext = context.GetOwinContext();
if (owinContext == null)
{
return null;
}
var website = owinContext.GetWebsite();
return website == null ? null : website.Id.ToString();
}
private static string GetWebsiteIdFromPortalContext(HttpContext context)
{
var portalContext = PortalCrmConfigurationManager.CreatePortalContext(request: context.Request.RequestContext);
if (portalContext == null)
{
return null;
}
return portalContext.Website == null ? null : portalContext.Website.Id.ToString();
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Linq;
using System.Globalization;
using System.ComponentModel;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
using Newtonsoft.Json.Serialization;
namespace Newtonsoft.Json.Schema
{
/// <summary>
/// Generates a <see cref="JsonSchema"/> from a specified <see cref="Type"/>.
/// </summary>
public class JsonSchemaGenerator
{
/// <summary>
/// Gets or sets how undefined schemas are handled by the serializer.
/// </summary>
public UndefinedSchemaIdHandling UndefinedSchemaIdHandling { get; set; }
private IContractResolver _contractResolver;
/// <summary>
/// Gets or sets the contract resolver.
/// </summary>
/// <value>The contract resolver.</value>
public IContractResolver ContractResolver
{
get
{
if (_contractResolver == null)
return DefaultContractResolver.Instance;
return _contractResolver;
}
set { _contractResolver = value; }
}
private class TypeSchema
{
public Type Type { get; private set; }
public JsonSchema Schema { get; private set;}
public TypeSchema(Type type, JsonSchema schema)
{
ValidationUtils.ArgumentNotNull(type, "type");
ValidationUtils.ArgumentNotNull(schema, "schema");
Type = type;
Schema = schema;
}
}
private JsonSchemaResolver _resolver;
private readonly IList<TypeSchema> _stack = new List<TypeSchema>();
private JsonSchema _currentSchema;
private JsonSchema CurrentSchema
{
get { return _currentSchema; }
}
private void Push(TypeSchema typeSchema)
{
_currentSchema = typeSchema.Schema;
_stack.Add(typeSchema);
_resolver.LoadedSchemas.Add(typeSchema.Schema);
}
private TypeSchema Pop()
{
TypeSchema popped = _stack[_stack.Count - 1];
_stack.RemoveAt(_stack.Count - 1);
TypeSchema newValue = _stack.LastOrDefault();
if (newValue != null)
{
_currentSchema = newValue.Schema;
}
else
{
_currentSchema = null;
}
return popped;
}
/// <summary>
/// Generate a <see cref="JsonSchema"/> from the specified type.
/// </summary>
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
public JsonSchema Generate(Type type)
{
return Generate(type, new JsonSchemaResolver(), false);
}
/// <summary>
/// Generate a <see cref="JsonSchema"/> from the specified type.
/// </summary>
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
/// <param name="resolver">The <see cref="JsonSchemaResolver"/> used to resolve schema references.</param>
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
public JsonSchema Generate(Type type, JsonSchemaResolver resolver)
{
return Generate(type, resolver, false);
}
/// <summary>
/// Generate a <see cref="JsonSchema"/> from the specified type.
/// </summary>
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
/// <param name="rootSchemaNullable">Specify whether the generated root <see cref="JsonSchema"/> will be nullable.</param>
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
public JsonSchema Generate(Type type, bool rootSchemaNullable)
{
return Generate(type, new JsonSchemaResolver(), rootSchemaNullable);
}
/// <summary>
/// Generate a <see cref="JsonSchema"/> from the specified type.
/// </summary>
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
/// <param name="resolver">The <see cref="JsonSchemaResolver"/> used to resolve schema references.</param>
/// <param name="rootSchemaNullable">Specify whether the generated root <see cref="JsonSchema"/> will be nullable.</param>
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
public JsonSchema Generate(Type type, JsonSchemaResolver resolver, bool rootSchemaNullable)
{
ValidationUtils.ArgumentNotNull(type, "type");
ValidationUtils.ArgumentNotNull(resolver, "resolver");
_resolver = resolver;
return GenerateInternal(type, (!rootSchemaNullable) ? Required.Always : Required.Default, false);
}
private string GetTitle(Type type)
{
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type);
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Title))
return containerAttribute.Title;
return null;
}
private string GetDescription(Type type)
{
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type);
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Description))
return containerAttribute.Description;
#if !PocketPC
DescriptionAttribute descriptionAttribute = ReflectionUtils.GetAttribute<DescriptionAttribute>(type);
if (descriptionAttribute != null)
return descriptionAttribute.Description;
#endif
return null;
}
private string GetTypeId(Type type, bool explicitOnly)
{
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type);
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Id))
return containerAttribute.Id;
if (explicitOnly)
return null;
switch (UndefinedSchemaIdHandling)
{
case UndefinedSchemaIdHandling.UseTypeName:
return type.FullName;
case UndefinedSchemaIdHandling.UseAssemblyQualifiedName:
return type.AssemblyQualifiedName;
default:
return null;
}
}
private JsonSchema GenerateInternal(Type type, Required valueRequired, bool required)
{
ValidationUtils.ArgumentNotNull(type, "type");
string resolvedId = GetTypeId(type, false);
string explicitId = GetTypeId(type, true);
if (!string.IsNullOrEmpty(resolvedId))
{
JsonSchema resolvedSchema = _resolver.GetSchema(resolvedId);
if (resolvedSchema != null)
{
// resolved schema is not null but referencing member allows nulls
// change resolved schema to allow nulls. hacky but what are ya gonna do?
if (valueRequired != Required.Always && !HasFlag(resolvedSchema.Type, JsonSchemaType.Null))
resolvedSchema.Type |= JsonSchemaType.Null;
if (required && resolvedSchema.Required != true)
resolvedSchema.Required = true;
return resolvedSchema;
}
}
// test for unresolved circular reference
if (_stack.Any(tc => tc.Type == type))
{
throw new Exception("Unresolved circular reference for type '{0}'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.".FormatWith(CultureInfo.InvariantCulture, type));
}
JsonContract contract = ContractResolver.ResolveContract(type);
JsonConverter converter;
if ((converter = contract.Converter) != null || (converter = contract.InternalConverter) != null)
{
JsonSchema converterSchema = converter.GetSchema();
if (converterSchema != null)
return converterSchema;
}
Push(new TypeSchema(type, new JsonSchema()));
if (explicitId != null)
CurrentSchema.Id = explicitId;
if (required)
CurrentSchema.Required = true;
CurrentSchema.Title = GetTitle(type);
CurrentSchema.Description = GetDescription(type);
if (converter != null)
{
// todo: Add GetSchema to JsonConverter and use here?
CurrentSchema.Type = JsonSchemaType.Any;
}
else
{
switch (contract.ContractType)
{
case JsonContractType.Object:
CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired);
CurrentSchema.Id = GetTypeId(type, false);
GenerateObjectSchema(type, (JsonObjectContract) contract);
break;
case JsonContractType.Array:
CurrentSchema.Type = AddNullType(JsonSchemaType.Array, valueRequired);
CurrentSchema.Id = GetTypeId(type, false);
JsonArrayAttribute arrayAttribute = JsonTypeReflector.GetJsonContainerAttribute(type) as JsonArrayAttribute;
bool allowNullItem = (arrayAttribute == null || arrayAttribute.AllowNullItems);
Type collectionItemType = ReflectionUtils.GetCollectionItemType(type);
if (collectionItemType != null)
{
CurrentSchema.Items = new List<JsonSchema>();
CurrentSchema.Items.Add(GenerateInternal(collectionItemType, (!allowNullItem) ? Required.Always : Required.Default, false));
}
break;
case JsonContractType.Primitive:
CurrentSchema.Type = GetJsonSchemaType(type, valueRequired);
if (CurrentSchema.Type == JsonSchemaType.Integer && type.IsEnum && !type.IsDefined(typeof (FlagsAttribute), true))
{
CurrentSchema.Enum = new List<JToken>();
CurrentSchema.Options = new Dictionary<JToken, string>();
EnumValues<long> enumValues = EnumUtils.GetNamesAndValues<long>(type);
foreach (EnumValue<long> enumValue in enumValues)
{
JToken value = JToken.FromObject(enumValue.Value);
CurrentSchema.Enum.Add(value);
CurrentSchema.Options.Add(value, enumValue.Name);
}
}
break;
case JsonContractType.String:
JsonSchemaType schemaType = (!ReflectionUtils.IsNullable(contract.UnderlyingType))
? JsonSchemaType.String
: AddNullType(JsonSchemaType.String, valueRequired);
CurrentSchema.Type = schemaType;
break;
case JsonContractType.Dictionary:
CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired);
Type keyType;
Type valueType;
ReflectionUtils.GetDictionaryKeyValueTypes(type, out keyType, out valueType);
if (keyType != null)
{
// can be converted to a string
if (typeof (IConvertible).IsAssignableFrom(keyType))
{
CurrentSchema.AdditionalProperties = GenerateInternal(valueType, Required.Default, false);
}
}
break;
#if !SILVERLIGHT && !PocketPC
case JsonContractType.Serializable:
CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired);
CurrentSchema.Id = GetTypeId(type, false);
GenerateISerializableContract(type, (JsonISerializableContract) contract);
break;
#endif
#if !(NET35 || NET20 || WINDOWS_PHONE)
case JsonContractType.Dynamic:
#endif
case JsonContractType.Linq:
CurrentSchema.Type = JsonSchemaType.Any;
break;
default:
throw new Exception("Unexpected contract type: {0}".FormatWith(CultureInfo.InvariantCulture, contract));
}
}
return Pop().Schema;
}
private JsonSchemaType AddNullType(JsonSchemaType type, Required valueRequired)
{
if (valueRequired != Required.Always)
return type | JsonSchemaType.Null;
return type;
}
private bool HasFlag(DefaultValueHandling value, DefaultValueHandling flag)
{
return ((value & flag) == flag);
}
private void GenerateObjectSchema(Type type, JsonObjectContract contract)
{
CurrentSchema.Properties = new Dictionary<string, JsonSchema>();
foreach (JsonProperty property in contract.Properties)
{
if (!property.Ignored)
{
bool optional = property.NullValueHandling == NullValueHandling.Ignore ||
HasFlag(property.DefaultValueHandling.GetValueOrDefault(), DefaultValueHandling.Ignore) ||
property.ShouldSerialize != null ||
property.GetIsSpecified != null;
JsonSchema propertySchema = GenerateInternal(property.PropertyType, property.Required, !optional);
if (property.DefaultValue != null)
propertySchema.Default = JToken.FromObject(property.DefaultValue);
CurrentSchema.Properties.Add(property.PropertyName, propertySchema);
}
}
if (type.IsSealed)
CurrentSchema.AllowAdditionalProperties = false;
}
#if !SILVERLIGHT && !PocketPC
private void GenerateISerializableContract(Type type, JsonISerializableContract contract)
{
CurrentSchema.AllowAdditionalProperties = true;
}
#endif
internal static bool HasFlag(JsonSchemaType? value, JsonSchemaType flag)
{
// default value is Any
if (value == null)
return true;
bool match = ((value & flag) == flag);
if (match)
return true;
// integer is a subset of float
if (value == JsonSchemaType.Float && flag == JsonSchemaType.Integer)
return true;
return false;
}
private JsonSchemaType GetJsonSchemaType(Type type, Required valueRequired)
{
JsonSchemaType schemaType = JsonSchemaType.None;
if (valueRequired != Required.Always && ReflectionUtils.IsNullable(type))
{
schemaType = JsonSchemaType.Null;
if (ReflectionUtils.IsNullableType(type))
type = Nullable.GetUnderlyingType(type);
}
TypeCode typeCode = Type.GetTypeCode(type);
switch (typeCode)
{
case TypeCode.Empty:
case TypeCode.Object:
return schemaType | JsonSchemaType.String;
case TypeCode.DBNull:
return schemaType | JsonSchemaType.Null;
case TypeCode.Boolean:
return schemaType | JsonSchemaType.Boolean;
case TypeCode.Char:
return schemaType | JsonSchemaType.String;
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
return schemaType | JsonSchemaType.Integer;
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return schemaType | JsonSchemaType.Float;
// convert to string?
case TypeCode.DateTime:
return schemaType | JsonSchemaType.String;
case TypeCode.String:
return schemaType | JsonSchemaType.String;
default:
throw new Exception("Unexpected type code '{0}' for type '{1}'.".FormatWith(CultureInfo.InvariantCulture, typeCode, type));
}
}
}
}
| |
using Microsoft.TeamFoundation.TestManagement.WebApi;
using Microsoft.VisualStudio.Services.Agent.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.VisualStudio.Services.Agent.Worker.CodeCoverage
{
public sealed class CodeCoverageCommandExtension : AgentService, IWorkerCommandExtension
{
private int _buildId;
// publish code coverage inputs
private string _summaryFileLocation;
private List<string> _additionalCodeCoverageFiles;
private string _codeCoverageTool;
private string _reportDirectory;
public void ProcessCommand(IExecutionContext context, Command command)
{
if (string.Equals(command.Event, WellKnownResultsCommand.PublishCodeCoverage, StringComparison.OrdinalIgnoreCase))
{
ProcessPublishCodeCoverageCommand(context, command.Properties);
}
else if (string.Equals(command.Event, WellKnownResultsCommand.EnableCodeCoverage, StringComparison.OrdinalIgnoreCase))
{
ProcessEnableCodeCoverageCommand(context, command.Properties);
}
else
{
throw new Exception(StringUtil.Loc("CodeCoverageCommandNotFound", command.Event));
}
}
public Type ExtensionType
{
get
{
return typeof(IWorkerCommandExtension);
}
}
public string CommandArea
{
get
{
return "codecoverage";
}
}
#region enable code coverage helper methods
private void ProcessEnableCodeCoverageCommand(IExecutionContext context, Dictionary<string, string> eventProperties)
{
string codeCoverageTool;
eventProperties.TryGetValue(EnableCodeCoverageEventProperties.CodeCoverageTool, out codeCoverageTool);
if (string.IsNullOrWhiteSpace(codeCoverageTool))
{
// no code coverage tool specified. Dont enable code coverage.
return;
}
codeCoverageTool = codeCoverageTool.Trim();
string buildTool;
eventProperties.TryGetValue(EnableCodeCoverageEventProperties.BuildTool, out buildTool);
if (string.IsNullOrEmpty(buildTool))
{
throw new ArgumentException(StringUtil.Loc("ArgumentNeeded", "BuildTool"));
}
buildTool = buildTool.Trim();
var codeCoverageInputs = new CodeCoverageEnablerInputs(context, buildTool, eventProperties);
ICodeCoverageEnabler ccEnabler = GetCodeCoverageEnabler(buildTool, codeCoverageTool);
ccEnabler.EnableCodeCoverage(context, codeCoverageInputs);
}
private ICodeCoverageEnabler GetCodeCoverageEnabler(string buildTool, string codeCoverageTool)
{
var extensionManager = HostContext.GetService<IExtensionManager>();
ICodeCoverageEnabler codeCoverageEnabler = (extensionManager.GetExtensions<ICodeCoverageEnabler>()).FirstOrDefault(
x => x.Name.Equals(codeCoverageTool + "_" + buildTool, StringComparison.OrdinalIgnoreCase));
if (codeCoverageEnabler == null)
{
throw new ArgumentException(StringUtil.Loc("InvalidBuildOrCoverageTool", buildTool, codeCoverageTool));
}
return codeCoverageEnabler;
}
#endregion
#region publish code coverage helper methods
private void ProcessPublishCodeCoverageCommand(IExecutionContext context, Dictionary<string, string> eventProperties)
{
ArgUtil.NotNull(context, nameof(context));
_buildId = context.Variables.Build_BuildId ?? -1;
if (!IsHostTypeBuild(context) || _buildId < 0)
{
//In case the publishing codecoverage is not applicable for current Host type we continue without publishing
context.Warning(StringUtil.Loc("CodeCoveragePublishIsValidOnlyForBuild"));
return;
}
LoadPublishCodeCoverageInputs(eventProperties);
string project = context.Variables.System_TeamProject;
long? containerId = context.Variables.Build_ContainerId;
ArgUtil.NotNull(containerId, nameof(containerId));
Guid projectId = context.Variables.System_TeamProjectId ?? Guid.Empty;
ArgUtil.NotEmpty(projectId, nameof(projectId));
//step 1: read code coverage summary
var reader = GetCodeCoverageSummaryReader(_codeCoverageTool);
context.Output(StringUtil.Loc("ReadingCodeCoverageSummary", _summaryFileLocation));
var coverageData = reader.GetCodeCoverageSummary(context, _summaryFileLocation);
if (coverageData == null || coverageData.Count() == 0)
{
context.Warning(StringUtil.Loc("CodeCoverageDataIsNull"));
}
Client.VssConnection connection = WorkerUtilies.GetVssConnection(context);
var codeCoveragePublisher = HostContext.GetService<ICodeCoveragePublisher>();
codeCoveragePublisher.InitializePublisher(_buildId, connection);
var commandContext = HostContext.CreateService<IAsyncCommandContext>();
commandContext.InitializeCommandContext(context, StringUtil.Loc("PublishCodeCoverage"));
commandContext.Task = PublishCodeCoverageAsync(context, commandContext, codeCoveragePublisher, coverageData, project, projectId, containerId.Value, context.CancellationToken);
context.AsyncCommands.Add(commandContext);
}
private async Task PublishCodeCoverageAsync(IExecutionContext executionContext, IAsyncCommandContext commandContext, ICodeCoveragePublisher codeCoveragePublisher, IEnumerable<CodeCoverageStatistics> coverageData,
string project, Guid projectId, long containerId, CancellationToken cancellationToken)
{
//step 2: publish code coverage summary to TFS
if (coverageData != null && coverageData.Count() > 0)
{
commandContext.Output(StringUtil.Loc("PublishingCodeCoverage"));
foreach (var coverage in coverageData)
{
commandContext.Output(StringUtil.Format(" {0}- {1} of {2} covered.", coverage.Label, coverage.Covered, coverage.Total));
}
await codeCoveragePublisher.PublishCodeCoverageSummaryAsync(coverageData, project, cancellationToken);
}
// step 3: publish code coverage files as build artifacts
string additionalCodeCoverageFilePath = null;
string destinationSummaryFile = null;
var newReportDirectory = _reportDirectory;
try
{
var filesToPublish = new List<Tuple<string, string>>();
if (!Directory.Exists(newReportDirectory))
{
if (!string.IsNullOrWhiteSpace(newReportDirectory))
{
// user gave a invalid report directory. Write warning and continue.
executionContext.Warning(StringUtil.Loc("DirectoryNotFound", newReportDirectory));
}
newReportDirectory = GetCoverageDirectory(_buildId.ToString(), CodeCoverageConstants.ReportDirectory);
Directory.CreateDirectory(newReportDirectory);
}
var summaryFileName = Path.GetFileName(_summaryFileLocation);
destinationSummaryFile = Path.Combine(newReportDirectory, CodeCoverageConstants.SummaryFileDirectory + _buildId, summaryFileName);
Directory.CreateDirectory(Path.GetDirectoryName(destinationSummaryFile));
File.Copy(_summaryFileLocation, destinationSummaryFile, true);
filesToPublish.Add(new Tuple<string, string>(newReportDirectory, GetCoverageDirectoryName(_buildId.ToString(), CodeCoverageConstants.ReportDirectory)));
if (_additionalCodeCoverageFiles != null && _additionalCodeCoverageFiles.Count != 0)
{
additionalCodeCoverageFilePath = GetCoverageDirectory(_buildId.ToString(), CodeCoverageConstants.RawFilesDirectory);
CodeCoverageUtilities.CopyFilesFromFileListWithDirStructure(_additionalCodeCoverageFiles, ref additionalCodeCoverageFilePath);
filesToPublish.Add(new Tuple<string, string>(additionalCodeCoverageFilePath, GetCoverageDirectoryName(_buildId.ToString(), CodeCoverageConstants.RawFilesDirectory)));
}
commandContext.Output(StringUtil.Loc("PublishingCodeCoverageFiles"));
await codeCoveragePublisher.PublishCodeCoverageFilesAsync(commandContext, projectId, containerId, filesToPublish, File.Exists(Path.Combine(newReportDirectory, CodeCoverageConstants.DefaultIndexFile)), cancellationToken);
}
catch (IOException ex)
{
executionContext.Warning(StringUtil.Loc("ErrorOccuredWhilePublishingCCFiles", ex.Message));
}
finally
{
// clean temporary files.
if (!string.IsNullOrEmpty(additionalCodeCoverageFilePath))
{
if (Directory.Exists(additionalCodeCoverageFilePath))
{
Directory.Delete(path: additionalCodeCoverageFilePath, recursive: true);
}
}
if (!string.IsNullOrEmpty(destinationSummaryFile))
{
var summaryFileDirectory = Path.GetDirectoryName(destinationSummaryFile);
if (Directory.Exists(summaryFileDirectory))
{
Directory.Delete(path: summaryFileDirectory, recursive: true);
}
}
if (!Directory.Exists(_reportDirectory))
{
if (Directory.Exists(newReportDirectory))
{
//delete the generated report directory
Directory.Delete(path: newReportDirectory, recursive: true);
}
}
}
}
private ICodeCoverageSummaryReader GetCodeCoverageSummaryReader(string codeCoverageTool)
{
var extensionManager = HostContext.GetService<IExtensionManager>();
ICodeCoverageSummaryReader summaryReader = (extensionManager.GetExtensions<ICodeCoverageSummaryReader>()).FirstOrDefault(x => codeCoverageTool.Equals(x.Name, StringComparison.OrdinalIgnoreCase));
if (summaryReader == null)
{
throw new ArgumentException(StringUtil.Loc("UnknownCodeCoverageTool", codeCoverageTool));
}
return summaryReader;
}
private bool IsHostTypeBuild(IExecutionContext context)
{
var hostType = context.Variables.System_HostType;
if (hostType != null && String.Equals(hostType.ToString(), "build", StringComparison.OrdinalIgnoreCase))
{
return true;
}
return false;
}
private void LoadPublishCodeCoverageInputs(Dictionary<string, string> eventProperties)
{
//validate codecoverage tool input
eventProperties.TryGetValue(PublishCodeCoverageEventProperties.CodeCoverageTool, out _codeCoverageTool);
if (string.IsNullOrEmpty(_codeCoverageTool))
{
throw new ArgumentException(StringUtil.Loc("ArgumentNeeded", "CodeCoverageTool"));
}
//validate summary file input
eventProperties.TryGetValue(PublishCodeCoverageEventProperties.SummaryFile, out _summaryFileLocation);
if (string.IsNullOrEmpty(_summaryFileLocation))
{
throw new ArgumentException(StringUtil.Loc("ArgumentNeeded", "SummaryFile"));
}
eventProperties.TryGetValue(PublishCodeCoverageEventProperties.ReportDirectory, out _reportDirectory);
string additionalFilesInput;
eventProperties.TryGetValue(PublishCodeCoverageEventProperties.AdditionalCodeCoverageFiles, out additionalFilesInput);
if (!string.IsNullOrEmpty(additionalFilesInput) && additionalFilesInput.Split(',').Count() > 0)
{
_additionalCodeCoverageFiles = additionalFilesInput.Split(',').ToList<string>();
}
}
private string GetCoverageDirectory(string buildId, string directoryName)
{
return Path.Combine(Path.GetTempPath(), GetCoverageDirectoryName(buildId, directoryName));
}
private string GetCoverageDirectoryName(string buildId, string directoryName)
{
return directoryName + "_" + buildId;
}
#endregion
internal static class WellKnownResultsCommand
{
internal static readonly string PublishCodeCoverage = "publish";
internal static readonly string EnableCodeCoverage = "enable";
}
internal static class EnableCodeCoverageEventProperties
{
internal static readonly string BuildTool = "buildtool";
internal static readonly string BuildFile = "buildfile";
internal static readonly string CodeCoverageTool = "codecoveragetool";
internal static readonly string ClassFilesDirectories = "classfilesdirectories";
internal static readonly string ClassFilter = "classfilter";
internal static readonly string SourceDirectories = "sourcedirectories";
internal static readonly string SummaryFile = "summaryfile";
internal static readonly string ReportDirectory = "reportdirectory";
internal static readonly string CCReportTask = "ccreporttask";
internal static readonly string ReportBuildFile = "reportbuildfile";
internal static readonly string IsMultiModule = "ismultimodule";
}
internal static class PublishCodeCoverageEventProperties
{
internal static readonly string CodeCoverageTool = "codecoveragetool";
internal static readonly string SummaryFile = "summaryfile";
internal static readonly string ReportDirectory = "reportdirectory";
internal static readonly string AdditionalCodeCoverageFiles = "additionalcodecoveragefiles";
}
}
}
| |
using KafkaNet.Common;
using KafkaNet.Statistics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace KafkaNet.Protocol
{
public class ProduceRequest : BaseRequest, IKafkaRequest<ProduceResponse>
{
/// <summary>
/// Provide a hint to the broker call not to expect a response for requests without Acks.
/// </summary>
public override bool ExpectResponse { get { return Acks != 0; } }
/// <summary>
/// Indicates the type of kafka encoding this request is.
/// </summary>
public ApiKeyRequestType ApiKey { get { return ApiKeyRequestType.Produce; } }
/// <summary>
/// Time kafka will wait for requested ack level before returning.
/// </summary>
public int TimeoutMS = 1000;
/// <summary>
/// Level of ack required by kafka. 0 immediate, 1 written to leader, 2+ replicas synced, -1 all replicas
/// </summary>
public Int16 Acks = 1;
/// <summary>
/// Collection of payloads to post to kafka
/// </summary>
public List<Payload> Payload = new List<Payload>();
public KafkaDataPayload Encode()
{
return EncodeProduceRequest(this);
}
public IEnumerable<ProduceResponse> Decode(byte[] payload)
{
return DecodeProduceResponse(payload);
}
#region Protocol...
private KafkaDataPayload EncodeProduceRequest(ProduceRequest request)
{
int totalCompressedBytes = 0;
if (request.Payload == null) request.Payload = new List<Payload>();
var groupedPayloads = (from p in request.Payload
group p by new
{
p.Topic,
p.Partition,
p.Codec
} into tpc
select tpc).ToList();
using (var message = EncodeHeader(request)
.Pack(request.Acks)
.Pack(request.TimeoutMS)
.Pack(groupedPayloads.Count))
{
foreach (var groupedPayload in groupedPayloads)
{
var payloads = groupedPayload.ToList();
message.Pack(groupedPayload.Key.Topic, StringPrefixEncoding.Int16)
.Pack(payloads.Count)
.Pack(groupedPayload.Key.Partition);
switch (groupedPayload.Key.Codec)
{
case MessageCodec.CodecNone:
message.Pack(Message.EncodeMessageSet(payloads.SelectMany(x => x.Messages)));
break;
case MessageCodec.CodecGzip:
var compressedBytes = CreateGzipCompressedMessage(payloads.SelectMany(x => x.Messages));
Interlocked.Add(ref totalCompressedBytes, compressedBytes.CompressedAmount);
message.Pack(Message.EncodeMessageSet(new[] { compressedBytes.CompressedMessage }));
break;
default:
throw new NotSupportedException(string.Format("Codec type of {0} is not supported.", groupedPayload.Key.Codec));
}
}
var result = new KafkaDataPayload
{
Buffer = message.Payload(),
CorrelationId = request.CorrelationId,
MessageCount = request.Payload.Sum(x => x.Messages.Count)
};
StatisticsTracker.RecordProduceRequest(result.MessageCount, result.Buffer.Length, totalCompressedBytes);
return result;
}
}
private CompressedMessageResult CreateGzipCompressedMessage(IEnumerable<Message> messages)
{
var messageSet = Message.EncodeMessageSet(messages);
var gZipBytes = Compression.Zip(messageSet);
var compressedMessage = new Message
{
Attribute = (byte)(0x00 | (ProtocolConstants.AttributeCodeMask & (byte)MessageCodec.CodecGzip)),
Value = gZipBytes
};
return new CompressedMessageResult
{
CompressedAmount = messageSet.Length - compressedMessage.Value.Length,
CompressedMessage = compressedMessage
};
}
private IEnumerable<ProduceResponse> DecodeProduceResponse(byte[] data)
{
using (var stream = new BigEndianBinaryReader(data))
{
var correlationId = stream.ReadInt32();
var topicCount = stream.ReadInt32();
for (int i = 0; i < topicCount; i++)
{
var topic = stream.ReadInt16String();
var partitionCount = stream.ReadInt32();
for (int j = 0; j < partitionCount; j++)
{
var response = new ProduceResponse()
{
Topic = topic,
PartitionId = stream.ReadInt32(),
Error = stream.ReadInt16(),
Offset = stream.ReadInt64()
};
yield return response;
}
}
}
}
#endregion Protocol...
}
internal class CompressedMessageResult
{
public int CompressedAmount { get; set; }
public Message CompressedMessage { get; set; }
}
public class ProduceResponse : IBaseResponse
{
/// <summary>
/// The topic the offset came from.
/// </summary>
public string Topic { get; set; }
/// <summary>
/// The partition the offset came from.
/// </summary>
public int PartitionId { get; set; }
/// <summary>
/// Error response code. 0 is success.
/// </summary>
public Int16 Error { get; set; }
/// <summary>
/// The offset number to commit as completed.
/// </summary>
public long Offset { get; set; }
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((ProduceResponse)obj);
}
protected bool Equals(ProduceResponse other)
{
return string.Equals(Topic, other.Topic) && PartitionId == other.PartitionId && Error == other.Error && Offset == other.Offset;
}
public override int GetHashCode()
{
unchecked
{
int hashCode = (Topic != null ? Topic.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ PartitionId;
hashCode = (hashCode * 397) ^ Error.GetHashCode();
hashCode = (hashCode * 397) ^ Offset.GetHashCode();
return hashCode;
}
}
}
}
| |
// 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 System.Xml.Serialization
{
using System.Reflection;
using System.Collections;
using System.Xml.Schema;
using System;
using System.Text;
using System.ComponentModel;
using System.Xml;
using System.Xml.Serialization;
// These classes represent a mapping between classes and a particular XML format.
// There are two class of mapping information: accessors (such as elements and
// attributes), and mappings (which specify the type of an accessor).
internal abstract class Accessor
{
private string _name;
private object _defaultValue = null;
private string _ns;
private TypeMapping _mapping;
private bool _any;
private string _anyNs;
private bool _topLevelInSchema;
private bool _isFixed;
private bool _isOptional;
private XmlSchemaForm _form = XmlSchemaForm.None;
internal Accessor() { }
internal TypeMapping Mapping
{
get { return _mapping; }
set { _mapping = value; }
}
internal object Default
{
get { return _defaultValue; }
set { _defaultValue = value; }
}
internal bool HasDefault
{
get { return _defaultValue != null && _defaultValue != DBNull.Value; }
}
internal virtual string Name
{
get { return _name == null ? string.Empty : _name; }
set { _name = value; }
}
internal bool Any
{
get { return _any; }
set { _any = value; }
}
internal string AnyNamespaces
{
get { return _anyNs; }
set { _anyNs = value; }
}
internal string Namespace
{
get { return _ns; }
set { _ns = value; }
}
internal XmlSchemaForm Form
{
get { return _form; }
set { _form = value; }
}
internal bool IsFixed
{
get { return _isFixed; }
set { _isFixed = value; }
}
internal bool IsOptional
{
get { return _isOptional; }
set { _isOptional = value; }
}
internal bool IsTopLevelInSchema
{
get { return _topLevelInSchema; }
set { _topLevelInSchema = value; }
}
internal static string EscapeName(string name)
{
if (name == null || name.Length == 0) return name;
return XmlConvert.EncodeLocalName(name);
}
internal static string EscapeQName(string name)
{
if (name == null || name.Length == 0) return name;
int colon = name.LastIndexOf(':');
if (colon < 0)
return XmlConvert.EncodeLocalName(name);
else
{
if (colon == 0 || colon == name.Length - 1)
throw new ArgumentException(SR.Format(SR.Xml_InvalidNameChars, name), nameof(name));
return new XmlQualifiedName(XmlConvert.EncodeLocalName(name.Substring(colon + 1)), XmlConvert.EncodeLocalName(name.Substring(0, colon))).ToString();
}
}
internal static string UnescapeName(string name)
{
return XmlConvert.DecodeName(name);
}
internal string ToString(string defaultNs)
{
if (Any)
{
return (Namespace == null ? "##any" : Namespace) + ":" + Name;
}
else
{
return Namespace == defaultNs ? Name : Namespace + ":" + Name;
}
}
}
internal class ElementAccessor : Accessor
{
private bool _nullable;
private bool _isSoap;
private bool _unbounded = false;
internal bool IsSoap
{
get { return _isSoap; }
set { _isSoap = value; }
}
internal bool IsNullable
{
get { return _nullable; }
set { _nullable = value; }
}
internal bool IsUnbounded
{
get { return _unbounded; }
set { _unbounded = value; }
}
internal ElementAccessor Clone()
{
ElementAccessor newAccessor = new ElementAccessor();
newAccessor._nullable = _nullable;
newAccessor.IsTopLevelInSchema = this.IsTopLevelInSchema;
newAccessor.Form = this.Form;
newAccessor._isSoap = _isSoap;
newAccessor.Name = this.Name;
newAccessor.Default = this.Default;
newAccessor.Namespace = this.Namespace;
newAccessor.Mapping = this.Mapping;
newAccessor.Any = this.Any;
return newAccessor;
}
}
internal class ChoiceIdentifierAccessor : Accessor
{
private string _memberName;
private string[] _memberIds;
private MemberInfo _memberInfo;
internal string MemberName
{
get { return _memberName; }
set { _memberName = value; }
}
internal string[] MemberIds
{
get { return _memberIds; }
set { _memberIds = value; }
}
internal MemberInfo MemberInfo
{
get { return _memberInfo; }
set { _memberInfo = value; }
}
}
internal class TextAccessor : Accessor
{
}
internal class XmlnsAccessor : Accessor
{
}
internal class AttributeAccessor : Accessor
{
private bool _isSpecial;
private bool _isList;
internal bool IsSpecialXmlNamespace
{
get { return _isSpecial; }
}
internal bool IsList
{
get { return _isList; }
set { _isList = value; }
}
internal void CheckSpecial()
{
int colon = Name.LastIndexOf(':');
if (colon >= 0)
{
if (!Name.StartsWith("xml:", StringComparison.Ordinal))
{
throw new InvalidOperationException(SR.Format(SR.Xml_InvalidNameChars, Name));
}
Name = Name.Substring("xml:".Length);
Namespace = XmlReservedNs.NsXml;
_isSpecial = true;
}
else
{
if (Namespace == XmlReservedNs.NsXml)
{
_isSpecial = true;
}
else
{
_isSpecial = false;
}
}
if (_isSpecial)
{
Form = XmlSchemaForm.Qualified;
}
}
}
internal abstract class Mapping
{
private bool _isSoap;
internal Mapping() { }
protected Mapping(Mapping mapping)
{
_isSoap = mapping._isSoap;
}
internal bool IsSoap
{
get { return _isSoap; }
set { _isSoap = value; }
}
}
internal abstract class TypeMapping : Mapping
{
private TypeDesc _typeDesc;
private string _typeNs;
private string _typeName;
private bool _referencedByElement;
private bool _referencedByTopLevelElement;
private bool _includeInSchema = true;
private bool _reference = false;
internal bool ReferencedByTopLevelElement
{
get { return _referencedByTopLevelElement; }
set { _referencedByTopLevelElement = value; }
}
internal bool ReferencedByElement
{
get { return _referencedByElement || _referencedByTopLevelElement; }
set { _referencedByElement = value; }
}
internal string Namespace
{
get { return _typeNs; }
set { _typeNs = value; }
}
internal string TypeName
{
get { return _typeName; }
set { _typeName = value; }
}
internal TypeDesc TypeDesc
{
get { return _typeDesc; }
set { _typeDesc = value; }
}
internal bool IncludeInSchema
{
get { return _includeInSchema; }
set { _includeInSchema = value; }
}
internal virtual bool IsList
{
get { return false; }
set { }
}
internal bool IsReference
{
get { return _reference; }
set { _reference = value; }
}
internal bool IsAnonymousType
{
get { return _typeName == null || _typeName.Length == 0; }
}
internal virtual string DefaultElementName
{
get { return IsAnonymousType ? XmlConvert.EncodeLocalName(_typeDesc.Name) : _typeName; }
}
}
internal class PrimitiveMapping : TypeMapping
{
private bool _isList;
internal override bool IsList
{
get { return _isList; }
set { _isList = value; }
}
}
internal class NullableMapping : TypeMapping
{
private TypeMapping _baseMapping;
internal TypeMapping BaseMapping
{
get { return _baseMapping; }
set { _baseMapping = value; }
}
internal override string DefaultElementName
{
get { return BaseMapping.DefaultElementName; }
}
}
internal class ArrayMapping : TypeMapping
{
private ElementAccessor[] _elements;
private ElementAccessor[] _sortedElements;
private ArrayMapping _next;
private StructMapping _topLevelMapping;
internal ElementAccessor[] Elements
{
get { return _elements; }
set { _elements = value; _sortedElements = null; }
}
internal ElementAccessor[] ElementsSortedByDerivation
{
get
{
if (_sortedElements != null)
return _sortedElements;
if (_elements == null)
return null;
_sortedElements = new ElementAccessor[_elements.Length];
Array.Copy(_elements, 0, _sortedElements, 0, _elements.Length);
AccessorMapping.SortMostToLeastDerived(_sortedElements);
return _sortedElements;
}
}
internal ArrayMapping Next
{
get { return _next; }
set { _next = value; }
}
internal StructMapping TopLevelMapping
{
get { return _topLevelMapping; }
set { _topLevelMapping = value; }
}
}
internal class EnumMapping : PrimitiveMapping
{
private ConstantMapping[] _constants;
private bool _isFlags;
internal bool IsFlags
{
get { return _isFlags; }
set { _isFlags = value; }
}
internal ConstantMapping[] Constants
{
get { return _constants; }
set { _constants = value; }
}
}
internal class ConstantMapping : Mapping
{
private string _xmlName;
private string _name;
private long _value;
internal string XmlName
{
get { return _xmlName == null ? string.Empty : _xmlName; }
set { _xmlName = value; }
}
internal string Name
{
get { return _name == null ? string.Empty : _name; }
set { _name = value; }
}
internal long Value
{
get { return _value; }
set { _value = value; }
}
}
internal class StructMapping : TypeMapping, INameScope
{
private MemberMapping[] _members;
private StructMapping _baseMapping;
private StructMapping _derivedMappings;
private StructMapping _nextDerivedMapping;
private MemberMapping _xmlnsMember = null;
private bool _hasSimpleContent;
private bool _openModel;
private bool _isSequence;
private NameTable _elements;
private NameTable _attributes;
private CodeIdentifiers _scope;
internal StructMapping BaseMapping
{
get { return _baseMapping; }
set
{
_baseMapping = value;
if (!IsAnonymousType && _baseMapping != null)
{
_nextDerivedMapping = _baseMapping._derivedMappings;
_baseMapping._derivedMappings = this;
}
if (value._isSequence && !_isSequence)
{
_isSequence = true;
if (_baseMapping.IsSequence)
{
for (StructMapping derived = _derivedMappings; derived != null; derived = derived.NextDerivedMapping)
{
derived.SetSequence();
}
}
}
}
}
internal StructMapping DerivedMappings
{
get { return _derivedMappings; }
}
internal bool IsFullyInitialized
{
get { return _baseMapping != null && Members != null; }
}
internal NameTable LocalElements
{
get
{
if (_elements == null)
_elements = new NameTable();
return _elements;
}
}
internal NameTable LocalAttributes
{
get
{
if (_attributes == null)
_attributes = new NameTable();
return _attributes;
}
}
object INameScope.this[string name, string ns]
{
get
{
object named = LocalElements[name, ns];
if (named != null)
return named;
if (_baseMapping != null)
return ((INameScope)_baseMapping)[name, ns];
return null;
}
set
{
LocalElements[name, ns] = value;
}
}
internal StructMapping NextDerivedMapping
{
get { return _nextDerivedMapping; }
}
internal bool HasSimpleContent
{
get { return _hasSimpleContent; }
}
internal bool HasXmlnsMember
{
get
{
StructMapping mapping = this;
while (mapping != null)
{
if (mapping.XmlnsMember != null)
return true;
mapping = mapping.BaseMapping;
}
return false;
}
}
internal MemberMapping[] Members
{
get { return _members; }
set { _members = value; }
}
internal MemberMapping XmlnsMember
{
get { return _xmlnsMember; }
set { _xmlnsMember = value; }
}
internal bool IsOpenModel
{
get { return _openModel; }
set { _openModel = value; }
}
internal CodeIdentifiers Scope
{
get
{
if (_scope == null)
_scope = new CodeIdentifiers();
return _scope;
}
set { _scope = value; }
}
internal MemberMapping FindDeclaringMapping(MemberMapping member, out StructMapping declaringMapping, string parent)
{
declaringMapping = null;
if (BaseMapping != null)
{
MemberMapping baseMember = BaseMapping.FindDeclaringMapping(member, out declaringMapping, parent);
if (baseMember != null) return baseMember;
}
if (_members == null) return null;
for (int i = 0; i < _members.Length; i++)
{
if (_members[i].Name == member.Name)
{
if (_members[i].TypeDesc != member.TypeDesc)
throw new InvalidOperationException(SR.Format(SR.XmlHiddenMember, parent, member.Name, member.TypeDesc.FullName, this.TypeName, _members[i].Name, _members[i].TypeDesc.FullName));
else if (!_members[i].Match(member))
{
throw new InvalidOperationException(SR.Format(SR.XmlInvalidXmlOverride, parent, member.Name, this.TypeName, _members[i].Name));
}
declaringMapping = this;
return _members[i];
}
}
return null;
}
internal bool Declares(MemberMapping member, string parent)
{
StructMapping m;
return (FindDeclaringMapping(member, out m, parent) != null);
}
internal void SetContentModel(TextAccessor text, bool hasElements)
{
if (BaseMapping == null || BaseMapping.TypeDesc.IsRoot)
{
_hasSimpleContent = !hasElements && text != null && !text.Mapping.IsList;
}
else if (BaseMapping.HasSimpleContent)
{
if (text != null || hasElements)
{
// we can only extent a simleContent type with attributes
throw new InvalidOperationException(SR.Format(SR.XmlIllegalSimpleContentExtension, TypeDesc.FullName, BaseMapping.TypeDesc.FullName));
}
else
{
_hasSimpleContent = true;
}
}
else
{
_hasSimpleContent = false;
}
if (!_hasSimpleContent && text != null && !text.Mapping.TypeDesc.CanBeTextValue && !(BaseMapping != null && !BaseMapping.TypeDesc.IsRoot && (text.Mapping.TypeDesc.IsEnum || text.Mapping.TypeDesc.IsPrimitive)))
{
throw new InvalidOperationException(SR.Format(SR.XmlIllegalTypedTextAttribute, TypeDesc.FullName, text.Name, text.Mapping.TypeDesc.FullName));
}
}
internal bool HasExplicitSequence()
{
if (_members != null)
{
for (int i = 0; i < _members.Length; i++)
{
if (_members[i].IsParticle && _members[i].IsSequence)
{
return true;
}
}
}
return (_baseMapping != null && _baseMapping.HasExplicitSequence());
}
internal void SetSequence()
{
if (TypeDesc.IsRoot)
return;
StructMapping start = this;
// find first mapping that does not have the sequence set
while (start.BaseMapping != null && !start.BaseMapping.IsSequence && !start.BaseMapping.TypeDesc.IsRoot)
start = start.BaseMapping;
start.IsSequence = true;
for (StructMapping derived = start.DerivedMappings; derived != null; derived = derived.NextDerivedMapping)
{
derived.SetSequence();
}
}
internal bool IsSequence
{
get { return _isSequence && !TypeDesc.IsRoot; }
set { _isSequence = value; }
}
}
internal abstract class AccessorMapping : Mapping
{
private TypeDesc _typeDesc;
private AttributeAccessor _attribute;
private ElementAccessor[] _elements;
private ElementAccessor[] _sortedElements;
private TextAccessor _text;
private ChoiceIdentifierAccessor _choiceIdentifier;
private XmlnsAccessor _xmlns;
private bool _ignore;
internal AccessorMapping()
{ }
protected AccessorMapping(AccessorMapping mapping)
: base(mapping)
{
_typeDesc = mapping._typeDesc;
_attribute = mapping._attribute;
_elements = mapping._elements;
_sortedElements = mapping._sortedElements;
_text = mapping._text;
_choiceIdentifier = mapping._choiceIdentifier;
_xmlns = mapping._xmlns;
_ignore = mapping._ignore;
}
internal bool IsAttribute
{
get { return _attribute != null; }
}
internal bool IsText
{
get { return _text != null && (_elements == null || _elements.Length == 0); }
}
internal bool IsParticle
{
get { return (_elements != null && _elements.Length > 0); }
}
internal TypeDesc TypeDesc
{
get { return _typeDesc; }
set { _typeDesc = value; }
}
internal AttributeAccessor Attribute
{
get { return _attribute; }
set { _attribute = value; }
}
internal ElementAccessor[] Elements
{
get { return _elements; }
set { _elements = value; _sortedElements = null; }
}
internal static void SortMostToLeastDerived(ElementAccessor[] elements)
{
Array.Sort(elements, new AccessorComparer());
}
internal class AccessorComparer : IComparer
{
public int Compare(object o1, object o2)
{
if (o1 == o2)
return 0;
Accessor a1 = (Accessor)o1;
Accessor a2 = (Accessor)o2;
int w1 = a1.Mapping.TypeDesc.Weight;
int w2 = a2.Mapping.TypeDesc.Weight;
if (w1 == w2)
return 0;
if (w1 < w2)
return 1;
return -1;
}
}
internal ElementAccessor[] ElementsSortedByDerivation
{
get
{
if (_sortedElements != null)
return _sortedElements;
if (_elements == null)
return null;
_sortedElements = new ElementAccessor[_elements.Length];
Array.Copy(_elements, 0, _sortedElements, 0, _elements.Length);
SortMostToLeastDerived(_sortedElements);
return _sortedElements;
}
}
internal TextAccessor Text
{
get { return _text; }
set { _text = value; }
}
internal ChoiceIdentifierAccessor ChoiceIdentifier
{
get { return _choiceIdentifier; }
set { _choiceIdentifier = value; }
}
internal XmlnsAccessor Xmlns
{
get { return _xmlns; }
set { _xmlns = value; }
}
internal bool Ignore
{
get { return _ignore; }
set { _ignore = value; }
}
internal Accessor Accessor
{
get
{
if (_xmlns != null) return _xmlns;
if (_attribute != null) return _attribute;
if (_elements != null && _elements.Length > 0) return _elements[0];
return _text;
}
}
internal static bool ElementsMatch(ElementAccessor[] a, ElementAccessor[] b)
{
if (a == null)
{
if (b == null)
return true;
return false;
}
if (b == null)
return false;
if (a.Length != b.Length)
return false;
for (int i = 0; i < a.Length; i++)
{
if (a[i].Name != b[i].Name || a[i].Namespace != b[i].Namespace || a[i].Form != b[i].Form || a[i].IsNullable != b[i].IsNullable)
return false;
}
return true;
}
internal bool Match(AccessorMapping mapping)
{
if (Elements != null && Elements.Length > 0)
{
if (!ElementsMatch(Elements, mapping.Elements))
{
return false;
}
if (Text == null)
{
return (mapping.Text == null);
}
}
if (Attribute != null)
{
if (mapping.Attribute == null)
return false;
return (Attribute.Name == mapping.Attribute.Name && Attribute.Namespace == mapping.Attribute.Namespace && Attribute.Form == mapping.Attribute.Form);
}
if (Text != null)
{
return (mapping.Text != null);
}
return (mapping.Accessor == null);
}
}
internal class MemberMappingComparer : IComparer
{
public int Compare(object o1, object o2)
{
MemberMapping m1 = (MemberMapping)o1;
MemberMapping m2 = (MemberMapping)o2;
bool m1Text = m1.IsText;
if (m1Text)
{
if (m2.IsText)
return 0;
return 1;
}
else if (m2.IsText)
return -1;
if (m1.SequenceId < 0 && m2.SequenceId < 0)
return 0;
if (m1.SequenceId < 0)
return 1;
if (m2.SequenceId < 0)
return -1;
if (m1.SequenceId < m2.SequenceId)
return -1;
if (m1.SequenceId > m2.SequenceId)
return 1;
return 0;
}
}
internal class MemberMapping : AccessorMapping
{
private string _name;
private bool _checkShouldPersist;
private SpecifiedAccessor _checkSpecified;
private bool _isReturnValue;
private bool _readOnly = false;
private int _sequenceId = -1;
private MemberInfo _memberInfo;
private MemberInfo _checkSpecifiedMemberInfo;
private MethodInfo _checkShouldPersistMethodInfo;
internal MemberMapping() { }
private MemberMapping(MemberMapping mapping)
: base(mapping)
{
_name = mapping._name;
_checkShouldPersist = mapping._checkShouldPersist;
_checkSpecified = mapping._checkSpecified;
_isReturnValue = mapping._isReturnValue;
_readOnly = mapping._readOnly;
_sequenceId = mapping._sequenceId;
_memberInfo = mapping._memberInfo;
_checkSpecifiedMemberInfo = mapping._checkSpecifiedMemberInfo;
_checkShouldPersistMethodInfo = mapping._checkShouldPersistMethodInfo;
}
internal bool CheckShouldPersist
{
get { return _checkShouldPersist; }
set { _checkShouldPersist = value; }
}
internal SpecifiedAccessor CheckSpecified
{
get { return _checkSpecified; }
set { _checkSpecified = value; }
}
internal string Name
{
get { return _name == null ? string.Empty : _name; }
set { _name = value; }
}
internal MemberInfo MemberInfo
{
get { return _memberInfo; }
set { _memberInfo = value; }
}
internal MemberInfo CheckSpecifiedMemberInfo
{
get { return _checkSpecifiedMemberInfo; }
set { _checkSpecifiedMemberInfo = value; }
}
internal MethodInfo CheckShouldPersistMethodInfo
{
get { return _checkShouldPersistMethodInfo; }
set { _checkShouldPersistMethodInfo = value; }
}
internal bool IsReturnValue
{
get { return _isReturnValue; }
set { _isReturnValue = value; }
}
internal bool ReadOnly
{
get { return _readOnly; }
set { _readOnly = value; }
}
internal bool IsSequence
{
get { return _sequenceId >= 0; }
}
internal int SequenceId
{
get { return _sequenceId; }
set { _sequenceId = value; }
}
private string GetNullableType(TypeDesc td)
{
// SOAP encoded arrays not mapped to Nullable<T> since they always derive from soapenc:Array
if (td.IsMappedType || (!td.IsValueType && (Elements[0].IsSoap || td.ArrayElementTypeDesc == null)))
return td.FullName;
if (td.ArrayElementTypeDesc != null)
{
return GetNullableType(td.ArrayElementTypeDesc) + "[]";
}
return "System.Nullable`1[" + td.FullName + "]";
}
internal MemberMapping Clone()
{
return new MemberMapping(this);
}
}
internal class MembersMapping : TypeMapping
{
private MemberMapping[] _members;
private bool _hasWrapperElement = true;
private bool _validateRpcWrapperElement;
private bool _writeAccessors = true;
private MemberMapping _xmlnsMember = null;
internal MemberMapping[] Members
{
get { return _members; }
set { _members = value; }
}
internal MemberMapping XmlnsMember
{
get { return _xmlnsMember; }
set { _xmlnsMember = value; }
}
internal bool HasWrapperElement
{
get { return _hasWrapperElement; }
set { _hasWrapperElement = value; }
}
internal bool ValidateRpcWrapperElement
{
get { return _validateRpcWrapperElement; }
set { _validateRpcWrapperElement = value; }
}
internal bool WriteAccessors
{
get { return _writeAccessors; }
set { _writeAccessors = value; }
}
}
internal class SpecialMapping : TypeMapping
{
private bool _namedAny;
internal bool NamedAny
{
get { return _namedAny; }
set { _namedAny = value; }
}
}
internal class SerializableMapping : SpecialMapping
{
private XmlSchema _schema;
private Type _type;
private bool _needSchema = true;
// new implementation of the IXmlSerializable
private MethodInfo _getSchemaMethod;
private XmlQualifiedName _xsiType;
private XmlSchemaType _xsdType;
private XmlSchemaSet _schemas;
private bool _any;
private string _namespaces;
private SerializableMapping _baseMapping;
private SerializableMapping _derivedMappings;
private SerializableMapping _nextDerivedMapping;
private SerializableMapping _next; // all mappings with the same qname
internal SerializableMapping() { }
internal SerializableMapping(MethodInfo getSchemaMethod, bool any, string ns)
{
_getSchemaMethod = getSchemaMethod;
_any = any;
this.Namespace = ns;
_needSchema = getSchemaMethod != null;
}
internal SerializableMapping(XmlQualifiedName xsiType, XmlSchemaSet schemas)
{
_xsiType = xsiType;
_schemas = schemas;
this.TypeName = xsiType.Name;
this.Namespace = xsiType.Namespace;
_needSchema = false;
}
internal void SetBaseMapping(SerializableMapping mapping)
{
_baseMapping = mapping;
if (_baseMapping != null)
{
_nextDerivedMapping = _baseMapping._derivedMappings;
_baseMapping._derivedMappings = this;
if (this == _nextDerivedMapping)
{
throw new InvalidOperationException(SR.Format(SR.XmlCircularDerivation, TypeDesc.FullName));
}
}
}
internal bool IsAny
{
get
{
if (_any)
return true;
if (_getSchemaMethod == null)
return false;
if (_needSchema && typeof(XmlSchemaType).IsAssignableFrom(_getSchemaMethod.ReturnType))
return false;
RetrieveSerializableSchema();
return _any;
}
}
internal string NamespaceList
{
get
{
RetrieveSerializableSchema();
if (_namespaces == null)
{
if (_schemas != null)
{
StringBuilder anyNamespaces = new StringBuilder();
foreach (XmlSchema s in _schemas.Schemas())
{
if (s.TargetNamespace != null && s.TargetNamespace.Length > 0)
{
if (anyNamespaces.Length > 0)
anyNamespaces.Append(" ");
anyNamespaces.Append(s.TargetNamespace);
}
}
_namespaces = anyNamespaces.ToString();
}
else
{
_namespaces = string.Empty;
}
}
return _namespaces;
}
}
internal SerializableMapping DerivedMappings
{
get
{
return _derivedMappings;
}
}
internal SerializableMapping NextDerivedMapping
{
get
{
return _nextDerivedMapping;
}
}
internal SerializableMapping Next
{
get { return _next; }
set { _next = value; }
}
internal Type Type
{
get { return _type; }
set { _type = value; }
}
internal XmlSchemaSet Schemas
{
get
{
RetrieveSerializableSchema();
return _schemas;
}
}
internal XmlSchema Schema
{
get
{
RetrieveSerializableSchema();
return _schema;
}
}
internal XmlQualifiedName XsiType
{
get
{
if (!_needSchema)
return _xsiType;
if (_getSchemaMethod == null)
return null;
if (typeof(XmlSchemaType).IsAssignableFrom(_getSchemaMethod.ReturnType))
return null;
RetrieveSerializableSchema();
return _xsiType;
}
}
internal XmlSchemaType XsdType
{
get
{
RetrieveSerializableSchema();
return _xsdType;
}
}
internal static void ValidationCallbackWithErrorCode(object sender, ValidationEventArgs args)
{
// CONSIDER: need the real type name
if (args.Severity == XmlSeverityType.Error)
throw new InvalidOperationException(SR.Format(SR.XmlSerializableSchemaError, typeof(IXmlSerializable).Name, args.Message));
}
internal void CheckDuplicateElement(XmlSchemaElement element, string elementNs)
{
if (element == null)
return;
// only check duplicate definitions for top-level element
if (element.Parent == null || !(element.Parent is XmlSchema))
return;
XmlSchemaObjectTable elements = null;
if (Schema != null && Schema.TargetNamespace == elementNs)
{
XmlSchemas.Preprocess(Schema);
elements = Schema.Elements;
}
else if (Schemas != null)
{
elements = Schemas.GlobalElements;
}
else
{
return;
}
foreach (XmlSchemaElement e in elements.Values)
{
if (e.Name == element.Name && e.QualifiedName.Namespace == elementNs)
{
if (Match(e, element))
return;
// XmlSerializableRootDupName=Cannot reconcile schema for '{0}'. Please use [XmlRoot] attribute to change name or namepace of the top-level element to avoid duplicate element declarations: element name='{1} namespace='{2}'.
throw new InvalidOperationException(SR.Format(SR.XmlSerializableRootDupName, _getSchemaMethod.DeclaringType.FullName, e.Name, elementNs));
}
}
}
private bool Match(XmlSchemaElement e1, XmlSchemaElement e2)
{
if (e1.IsNillable != e2.IsNillable)
return false;
if (e1.RefName != e2.RefName)
return false;
if (e1.SchemaType != e2.SchemaType)
return false;
if (e1.SchemaTypeName != e2.SchemaTypeName)
return false;
if (e1.MinOccurs != e2.MinOccurs)
return false;
if (e1.MaxOccurs != e2.MaxOccurs)
return false;
if (e1.IsAbstract != e2.IsAbstract)
return false;
if (e1.DefaultValue != e2.DefaultValue)
return false;
if (e1.SubstitutionGroup != e2.SubstitutionGroup)
return false;
return true;
}
private void RetrieveSerializableSchema()
{
if (_needSchema)
{
_needSchema = false;
if (_getSchemaMethod != null)
{
// get the type info
if (_schemas == null)
_schemas = new XmlSchemaSet();
object typeInfo = _getSchemaMethod.Invoke(null, new object[] { _schemas });
_xsiType = XmlQualifiedName.Empty;
if (typeInfo != null)
{
if (typeof(XmlSchemaType).IsAssignableFrom(_getSchemaMethod.ReturnType))
{
_xsdType = (XmlSchemaType)typeInfo;
// check if type is named
_xsiType = _xsdType.QualifiedName;
}
else if (typeof(XmlQualifiedName).IsAssignableFrom(_getSchemaMethod.ReturnType))
{
_xsiType = (XmlQualifiedName)typeInfo;
if (_xsiType.IsEmpty)
{
throw new InvalidOperationException(SR.Format(SR.XmlGetSchemaEmptyTypeName, _type.FullName, _getSchemaMethod.Name));
}
}
else
{
throw new InvalidOperationException(SR.Format(SR.XmlGetSchemaMethodReturnType, _type.Name, _getSchemaMethod.Name, typeof(XmlSchemaProviderAttribute).Name, typeof(XmlQualifiedName).FullName));
}
}
else
{
_any = true;
}
// make sure that user-specified schemas are valid
_schemas.ValidationEventHandler += new ValidationEventHandler(ValidationCallbackWithErrorCode);
_schemas.Compile();
// at this point we verified that the information returned by the IXmlSerializable is valid
// Now check to see if the type was referenced before:
// UNDONE check for the duplcate types
if (!_xsiType.IsEmpty)
{
// try to find the type in the schemas collection
if (_xsiType.Namespace != XmlSchema.Namespace)
{
ArrayList srcSchemas = (ArrayList)_schemas.Schemas(_xsiType.Namespace);
if (srcSchemas.Count == 0)
{
throw new InvalidOperationException(SR.Format(SR.XmlMissingSchema, _xsiType.Namespace));
}
if (srcSchemas.Count > 1)
{
throw new InvalidOperationException(SR.Format(SR.XmlGetSchemaInclude, _xsiType.Namespace, _getSchemaMethod.DeclaringType.FullName, _getSchemaMethod.Name));
}
XmlSchema s = (XmlSchema)srcSchemas[0];
if (s == null)
{
throw new InvalidOperationException(SR.Format(SR.XmlMissingSchema, _xsiType.Namespace));
}
_xsdType = (XmlSchemaType)s.SchemaTypes[_xsiType];
if (_xsdType == null)
{
throw new InvalidOperationException(SR.Format(SR.XmlGetSchemaTypeMissing, _getSchemaMethod.DeclaringType.FullName, _getSchemaMethod.Name, _xsiType.Name, _xsiType.Namespace));
}
_xsdType = _xsdType.Redefined != null ? _xsdType.Redefined : _xsdType;
}
}
}
else
{
IXmlSerializable serializable = (IXmlSerializable)Activator.CreateInstance(_type);
_schema = serializable.GetSchema();
if (_schema != null)
{
if (_schema.Id == null || _schema.Id.Length == 0) throw new InvalidOperationException(SR.Format(SR.XmlSerializableNameMissing1, _type.FullName));
}
}
}
}
}
}
| |
/*
* 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 Mono.Addins;
using Nini.Config;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Services.Interfaces;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "XmlRpcGroupsServicesConnectorModule")]
public class XmlRpcGroupsServicesConnectorModule : ISharedRegionModule, IGroupsServicesConnector
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool m_debugEnabled = false;
public const GroupPowers DefaultEveryonePowers
= GroupPowers.AllowSetHome
| GroupPowers.Accountable
| GroupPowers.JoinChat
| GroupPowers.AllowVoiceChat
| GroupPowers.ReceiveNotices
| GroupPowers.StartProposal
| GroupPowers.VoteOnProposal;
// Would this be cleaner as (GroupPowers)ulong.MaxValue?
public const GroupPowers DefaultOwnerPowers
= GroupPowers.Accountable
| GroupPowers.AllowEditLand
| GroupPowers.AllowFly
| GroupPowers.AllowLandmark
| GroupPowers.AllowRez
| GroupPowers.AllowSetHome
| GroupPowers.AllowVoiceChat
| GroupPowers.AssignMember
| GroupPowers.AssignMemberLimited
| GroupPowers.ChangeActions
| GroupPowers.ChangeIdentity
| GroupPowers.ChangeMedia
| GroupPowers.ChangeOptions
| GroupPowers.CreateRole
| GroupPowers.DeedObject
| GroupPowers.DeleteRole
| GroupPowers.Eject
| GroupPowers.FindPlaces
| GroupPowers.Invite
| GroupPowers.JoinChat
| GroupPowers.LandChangeIdentity
| GroupPowers.LandDeed
| GroupPowers.LandDivideJoin
| GroupPowers.LandEdit
| GroupPowers.LandEjectAndFreeze
| GroupPowers.LandGardening
| GroupPowers.LandManageAllowed
| GroupPowers.LandManageBanned
| GroupPowers.LandManagePasses
| GroupPowers.LandOptions
| GroupPowers.LandRelease
| GroupPowers.LandSetSale
| GroupPowers.ModerateChat
| GroupPowers.ObjectManipulate
| GroupPowers.ObjectSetForSale
| GroupPowers.ReceiveNotices
| GroupPowers.RemoveMember
| GroupPowers.ReturnGroupOwned
| GroupPowers.ReturnGroupSet
| GroupPowers.ReturnNonGroup
| GroupPowers.RoleProperties
| GroupPowers.SendNotices
| GroupPowers.SetLandingPoint
| GroupPowers.StartProposal
| GroupPowers.VoteOnProposal;
private bool m_connectorEnabled = false;
private string m_groupsServerURI = string.Empty;
private bool m_disableKeepAlive = false;
private string m_groupReadKey = string.Empty;
private string m_groupWriteKey = string.Empty;
private IUserAccountService m_accountService = null;
private ThreadedClasses.ExpiringCache<string, XmlRpcResponse> m_memoryCache;
private int m_cacheTimeout = 30;
// Used to track which agents are have dropped from a group chat session
// Should be reset per agent, on logon
// TODO: move this to Flotsam XmlRpc Service
// SessionID, List<AgentID>
private Dictionary<UUID, List<UUID>> m_groupsAgentsDroppedFromChatSession = new Dictionary<UUID, List<UUID>>();
private Dictionary<UUID, List<UUID>> m_groupsAgentsInvitedToChatSession = new Dictionary<UUID, List<UUID>>();
#region Region Module interfaceBase Members
public string Name
{
get { return "XmlRpcGroupsServicesConnector"; }
}
// this module is not intended to be replaced, but there should only be 1 of them.
public Type ReplaceableInterface
{
get { return null; }
}
public void Initialise(IConfigSource config)
{
IConfig groupsConfig = config.Configs["Groups"];
if (groupsConfig == null)
{
// Do not run this module by default.
return;
}
else
{
// if groups aren't enabled, we're not needed.
// if we're not specified as the connector to use, then we're not wanted
if ((groupsConfig.GetBoolean("Enabled", false) == false)
|| (groupsConfig.GetString("ServicesConnectorModule", "XmlRpcGroupsServicesConnector") != Name))
{
m_connectorEnabled = false;
return;
}
m_log.DebugFormat("[XMLRPC-GROUPS-CONNECTOR]: Initializing {0}", this.Name);
m_groupsServerURI = groupsConfig.GetString("GroupsServerURI", string.Empty);
if (string.IsNullOrEmpty(m_groupsServerURI))
{
m_log.ErrorFormat("Please specify a valid URL for GroupsServerURI in OpenSim.ini, [Groups]");
m_connectorEnabled = false;
return;
}
m_disableKeepAlive = groupsConfig.GetBoolean("XmlRpcDisableKeepAlive", false);
m_groupReadKey = groupsConfig.GetString("XmlRpcServiceReadKey", string.Empty);
m_groupWriteKey = groupsConfig.GetString("XmlRpcServiceWriteKey", string.Empty);
m_cacheTimeout = groupsConfig.GetInt("GroupsCacheTimeout", 30);
if (m_cacheTimeout == 0)
{
m_log.WarnFormat("[XMLRPC-GROUPS-CONNECTOR]: Groups Cache Disabled.");
}
else
{
m_log.InfoFormat("[XMLRPC-GROUPS-CONNECTOR]: Groups Cache Timeout set to {0}.", m_cacheTimeout);
}
m_debugEnabled = groupsConfig.GetBoolean("DebugEnabled", false);
// If we got all the config options we need, lets start'er'up
m_memoryCache = new ThreadedClasses.ExpiringCache<string, XmlRpcResponse>(30);
m_connectorEnabled = true;
}
}
public void Close()
{
m_log.DebugFormat("[XMLRPC-GROUPS-CONNECTOR]: Closing {0}", this.Name);
}
public void AddRegion(OpenSim.Region.Framework.Scenes.Scene scene)
{
if (m_connectorEnabled)
{
if (m_accountService == null)
{
m_accountService = scene.UserAccountService;
}
scene.RegisterModuleInterface<IGroupsServicesConnector>(this);
}
}
public void RemoveRegion(OpenSim.Region.Framework.Scenes.Scene scene)
{
if (scene.RequestModuleInterface<IGroupsServicesConnector>() == this)
{
scene.UnregisterModuleInterface<IGroupsServicesConnector>(this);
}
}
public void RegionLoaded(OpenSim.Region.Framework.Scenes.Scene scene)
{
// TODO: May want to consider listenning for Agent Connections so we can pre-cache group info
// scene.EventManager.OnNewClient += OnNewClient;
}
#endregion
#region ISharedRegionModule Members
public void PostInitialise()
{
// NoOp
}
#endregion
#region IGroupsServicesConnector Members
/// <summary>
/// Create a Group, including Everyone and Owners Role, place FounderID in both groups, select Owner as selected role, and newly created group as agent's active role.
/// </summary>
public UUID CreateGroup(UUID requestingAgentID, string name, string charter, bool showInList, UUID insigniaID,
int membershipFee, bool openEnrollment, bool allowPublish,
bool maturePublish, UUID founderID)
{
UUID GroupID = UUID.Random();
UUID OwnerRoleID = UUID.Random();
Hashtable param = new Hashtable();
param["GroupID"] = GroupID.ToString();
param["Name"] = name;
param["Charter"] = charter;
param["ShowInList"] = showInList == true ? 1 : 0;
param["InsigniaID"] = insigniaID.ToString();
param["MembershipFee"] = membershipFee;
param["OpenEnrollment"] = openEnrollment == true ? 1 : 0;
param["AllowPublish"] = allowPublish == true ? 1 : 0;
param["MaturePublish"] = maturePublish == true ? 1 : 0;
param["FounderID"] = founderID.ToString();
param["EveryonePowers"] = ((ulong)DefaultEveryonePowers).ToString();
param["OwnerRoleID"] = OwnerRoleID.ToString();
param["OwnersPowers"] = ((ulong)DefaultOwnerPowers).ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.createGroup", param);
if (respData.Contains("error"))
{
// UUID is not nullable
return UUID.Zero;
}
return UUID.Parse((string)respData["GroupID"]);
}
public void UpdateGroup(UUID requestingAgentID, UUID groupID, string charter, bool showInList,
UUID insigniaID, int membershipFee, bool openEnrollment,
bool allowPublish, bool maturePublish)
{
Hashtable param = new Hashtable();
param["GroupID"] = groupID.ToString();
param["Charter"] = charter;
param["ShowInList"] = showInList == true ? 1 : 0;
param["InsigniaID"] = insigniaID.ToString();
param["MembershipFee"] = membershipFee;
param["OpenEnrollment"] = openEnrollment == true ? 1 : 0;
param["AllowPublish"] = allowPublish == true ? 1 : 0;
param["MaturePublish"] = maturePublish == true ? 1 : 0;
XmlRpcCall(requestingAgentID, "groups.updateGroup", param);
}
public void AddGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID, string name, string description,
string title, ulong powers)
{
Hashtable param = new Hashtable();
param["GroupID"] = groupID.ToString();
param["RoleID"] = roleID.ToString();
param["Name"] = name;
param["Description"] = description;
param["Title"] = title;
param["Powers"] = powers.ToString();
XmlRpcCall(requestingAgentID, "groups.addRoleToGroup", param);
}
public void RemoveGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID)
{
Hashtable param = new Hashtable();
param["GroupID"] = groupID.ToString();
param["RoleID"] = roleID.ToString();
XmlRpcCall(requestingAgentID, "groups.removeRoleFromGroup", param);
}
public void UpdateGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID, string name, string description,
string title, ulong powers)
{
Hashtable param = new Hashtable();
param["GroupID"] = groupID.ToString();
param["RoleID"] = roleID.ToString();
if (name != null)
{
param["Name"] = name;
}
if (description != null)
{
param["Description"] = description;
}
if (title != null)
{
param["Title"] = title;
}
param["Powers"] = powers.ToString();
XmlRpcCall(requestingAgentID, "groups.updateGroupRole", param);
}
public GroupRecord GetGroupRecord(UUID requestingAgentID, UUID GroupID, string GroupName)
{
Hashtable param = new Hashtable();
if (GroupID != UUID.Zero)
{
param["GroupID"] = GroupID.ToString();
}
if (!string.IsNullOrEmpty(GroupName))
{
param["Name"] = GroupName.ToString();
}
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroup", param);
if (respData.Contains("error"))
{
return null;
}
return GroupProfileHashtableToGroupRecord(respData);
}
public GroupProfileData GetMemberGroupProfile(UUID requestingAgentID, UUID GroupID, UUID AgentID)
{
Hashtable param = new Hashtable();
param["GroupID"] = GroupID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroup", param);
if (respData.Contains("error"))
{
// GroupProfileData is not nullable
return new GroupProfileData();
}
GroupMembershipData MemberInfo = GetAgentGroupMembership(requestingAgentID, AgentID, GroupID);
GroupProfileData MemberGroupProfile = GroupProfileHashtableToGroupProfileData(respData);
MemberGroupProfile.MemberTitle = MemberInfo.GroupTitle;
MemberGroupProfile.PowersMask = MemberInfo.GroupPowers;
return MemberGroupProfile;
}
public void SetAgentActiveGroup(UUID requestingAgentID, UUID AgentID, UUID GroupID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
param["GroupID"] = GroupID.ToString();
XmlRpcCall(requestingAgentID, "groups.setAgentActiveGroup", param);
}
public void SetAgentActiveGroupRole(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
param["GroupID"] = GroupID.ToString();
param["SelectedRoleID"] = RoleID.ToString();
XmlRpcCall(requestingAgentID, "groups.setAgentGroupInfo", param);
}
public void SetAgentGroupInfo(UUID requestingAgentID, UUID AgentID, UUID GroupID, bool AcceptNotices, bool ListInProfile)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
param["GroupID"] = GroupID.ToString();
param["AcceptNotices"] = AcceptNotices ? "1" : "0";
param["ListInProfile"] = ListInProfile ? "1" : "0";
XmlRpcCall(requestingAgentID, "groups.setAgentGroupInfo", param);
}
public void AddAgentToGroupInvite(UUID requestingAgentID, UUID inviteID, UUID groupID, UUID roleID, UUID agentID)
{
Hashtable param = new Hashtable();
param["InviteID"] = inviteID.ToString();
param["AgentID"] = agentID.ToString();
param["RoleID"] = roleID.ToString();
param["GroupID"] = groupID.ToString();
XmlRpcCall(requestingAgentID, "groups.addAgentToGroupInvite", param);
}
public GroupInviteInfo GetAgentToGroupInvite(UUID requestingAgentID, UUID inviteID)
{
Hashtable param = new Hashtable();
param["InviteID"] = inviteID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentToGroupInvite", param);
if (respData.Contains("error"))
{
return null;
}
GroupInviteInfo inviteInfo = new GroupInviteInfo();
inviteInfo.InviteID = inviteID;
inviteInfo.GroupID = UUID.Parse((string)respData["GroupID"]);
inviteInfo.RoleID = UUID.Parse((string)respData["RoleID"]);
inviteInfo.AgentID = UUID.Parse((string)respData["AgentID"]);
return inviteInfo;
}
public void RemoveAgentToGroupInvite(UUID requestingAgentID, UUID inviteID)
{
Hashtable param = new Hashtable();
param["InviteID"] = inviteID.ToString();
XmlRpcCall(requestingAgentID, "groups.removeAgentToGroupInvite", param);
}
public void AddAgentToGroup(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
param["GroupID"] = GroupID.ToString();
param["RoleID"] = RoleID.ToString();
XmlRpcCall(requestingAgentID, "groups.addAgentToGroup", param);
}
public void RemoveAgentFromGroup(UUID requestingAgentID, UUID AgentID, UUID GroupID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
param["GroupID"] = GroupID.ToString();
XmlRpcCall(requestingAgentID, "groups.removeAgentFromGroup", param);
}
public void AddAgentToGroupRole(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
param["GroupID"] = GroupID.ToString();
param["RoleID"] = RoleID.ToString();
XmlRpcCall(requestingAgentID, "groups.addAgentToGroupRole", param);
}
public void RemoveAgentFromGroupRole(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
param["GroupID"] = GroupID.ToString();
param["RoleID"] = RoleID.ToString();
XmlRpcCall(requestingAgentID, "groups.removeAgentFromGroupRole", param);
}
public List<DirGroupsReplyData> FindGroups(UUID requestingAgentID, string search)
{
Hashtable param = new Hashtable();
param["Search"] = search;
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.findGroups", param);
List<DirGroupsReplyData> findings = new List<DirGroupsReplyData>();
if (!respData.Contains("error"))
{
Hashtable results = (Hashtable)respData["results"];
foreach (Hashtable groupFind in results.Values)
{
DirGroupsReplyData data = new DirGroupsReplyData();
data.groupID = new UUID((string)groupFind["GroupID"]); ;
data.groupName = (string)groupFind["Name"];
data.members = int.Parse((string)groupFind["Members"]);
// data.searchOrder = order;
findings.Add(data);
}
}
return findings;
}
public GroupMembershipData GetAgentGroupMembership(UUID requestingAgentID, UUID AgentID, UUID GroupID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
param["GroupID"] = GroupID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentGroupMembership", param);
if (respData.Contains("error"))
{
return null;
}
GroupMembershipData data = HashTableToGroupMembershipData(respData);
return data;
}
public GroupMembershipData GetAgentActiveMembership(UUID requestingAgentID, UUID AgentID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentActiveMembership", param);
if (respData.Contains("error"))
{
return null;
}
return HashTableToGroupMembershipData(respData);
}
public List<GroupMembershipData> GetAgentGroupMemberships(UUID requestingAgentID, UUID AgentID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentGroupMemberships", param);
List<GroupMembershipData> memberships = new List<GroupMembershipData>();
if (!respData.Contains("error"))
{
foreach (object membership in respData.Values)
{
memberships.Add(HashTableToGroupMembershipData((Hashtable)membership));
}
}
return memberships;
}
public List<GroupRolesData> GetAgentGroupRoles(UUID requestingAgentID, UUID AgentID, UUID GroupID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
param["GroupID"] = GroupID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentRoles", param);
List<GroupRolesData> Roles = new List<GroupRolesData>();
if (respData.Contains("error"))
{
return Roles;
}
foreach (Hashtable role in respData.Values)
{
GroupRolesData data = new GroupRolesData();
data.RoleID = new UUID((string)role["RoleID"]);
data.Name = (string)role["Name"];
data.Description = (string)role["Description"];
data.Powers = ulong.Parse((string)role["Powers"]);
data.Title = (string)role["Title"];
Roles.Add(data);
}
return Roles;
}
public List<GroupRolesData> GetGroupRoles(UUID requestingAgentID, UUID GroupID)
{
Hashtable param = new Hashtable();
param["GroupID"] = GroupID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupRoles", param);
List<GroupRolesData> Roles = new List<GroupRolesData>();
if (respData.Contains("error"))
{
return Roles;
}
foreach (Hashtable role in respData.Values)
{
GroupRolesData data = new GroupRolesData();
data.Description = (string)role["Description"];
data.Members = int.Parse((string)role["Members"]);
data.Name = (string)role["Name"];
data.Powers = ulong.Parse((string)role["Powers"]);
data.RoleID = new UUID((string)role["RoleID"]);
data.Title = (string)role["Title"];
Roles.Add(data);
}
return Roles;
}
public List<GroupMembersData> GetGroupMembers(UUID requestingAgentID, UUID GroupID)
{
Hashtable param = new Hashtable();
param["GroupID"] = GroupID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupMembers", param);
List<GroupMembersData> members = new List<GroupMembersData>();
if (respData.Contains("error"))
{
return members;
}
foreach (Hashtable membership in respData.Values)
{
GroupMembersData data = new GroupMembersData();
data.AcceptNotices = ((string)membership["AcceptNotices"]) == "1";
data.AgentID = new UUID((string)membership["AgentID"]);
data.Contribution = int.Parse((string)membership["Contribution"]);
data.IsOwner = ((string)membership["IsOwner"]) == "1";
data.ListInProfile = ((string)membership["ListInProfile"]) == "1";
data.AgentPowers = ulong.Parse((string)membership["AgentPowers"]);
data.Title = (string)membership["Title"];
members.Add(data);
}
return members;
}
public List<GroupRoleMembersData> GetGroupRoleMembers(UUID requestingAgentID, UUID GroupID)
{
Hashtable param = new Hashtable();
param["GroupID"] = GroupID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupRoleMembers", param);
List<GroupRoleMembersData> members = new List<GroupRoleMembersData>();
if (!respData.Contains("error"))
{
foreach (Hashtable membership in respData.Values)
{
GroupRoleMembersData data = new GroupRoleMembersData();
data.MemberID = new UUID((string)membership["AgentID"]);
data.RoleID = new UUID((string)membership["RoleID"]);
members.Add(data);
}
}
return members;
}
public List<GroupNoticeData> GetGroupNotices(UUID requestingAgentID, UUID GroupID)
{
Hashtable param = new Hashtable();
param["GroupID"] = GroupID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupNotices", param);
List<GroupNoticeData> values = new List<GroupNoticeData>();
if (!respData.Contains("error"))
{
foreach (Hashtable value in respData.Values)
{
GroupNoticeData data = new GroupNoticeData();
data.NoticeID = UUID.Parse((string)value["NoticeID"]);
data.Timestamp = uint.Parse((string)value["Timestamp"]);
data.FromName = (string)value["FromName"];
data.Subject = (string)value["Subject"];
data.HasAttachment = false;
data.AssetType = 0;
values.Add(data);
}
}
return values;
}
public GroupNoticeInfo GetGroupNotice(UUID requestingAgentID, UUID noticeID)
{
Hashtable param = new Hashtable();
param["NoticeID"] = noticeID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupNotice", param);
if (respData.Contains("error"))
{
return null;
}
GroupNoticeInfo data = new GroupNoticeInfo();
data.GroupID = UUID.Parse((string)respData["GroupID"]);
data.Message = (string)respData["Message"];
data.BinaryBucket = Utils.HexStringToBytes((string)respData["BinaryBucket"], true);
data.noticeData.NoticeID = UUID.Parse((string)respData["NoticeID"]);
data.noticeData.Timestamp = uint.Parse((string)respData["Timestamp"]);
data.noticeData.FromName = (string)respData["FromName"];
data.noticeData.Subject = (string)respData["Subject"];
data.noticeData.HasAttachment = false;
data.noticeData.AssetType = 0;
if (data.Message == null)
{
data.Message = string.Empty;
}
return data;
}
public void AddGroupNotice(UUID requestingAgentID, UUID groupID, UUID noticeID, string fromName, string subject, string message, byte[] binaryBucket)
{
string binBucket = OpenMetaverse.Utils.BytesToHexString(binaryBucket, "");
Hashtable param = new Hashtable();
param["GroupID"] = groupID.ToString();
param["NoticeID"] = noticeID.ToString();
param["FromName"] = fromName;
param["Subject"] = subject;
param["Message"] = message;
param["BinaryBucket"] = binBucket;
param["TimeStamp"] = ((uint)Util.UnixTimeSinceEpoch()).ToString();
XmlRpcCall(requestingAgentID, "groups.addGroupNotice", param);
}
#endregion
#region GroupSessionTracking
public void ResetAgentGroupChatSessions(UUID agentID)
{
foreach (List<UUID> agentList in m_groupsAgentsDroppedFromChatSession.Values)
{
agentList.Remove(agentID);
}
}
public bool hasAgentBeenInvitedToGroupChatSession(UUID agentID, UUID groupID)
{
// If we're tracking this group, and we can find them in the tracking, then they've been invited
return m_groupsAgentsInvitedToChatSession.ContainsKey(groupID)
&& m_groupsAgentsInvitedToChatSession[groupID].Contains(agentID);
}
public bool hasAgentDroppedGroupChatSession(UUID agentID, UUID groupID)
{
// If we're tracking drops for this group,
// and we find them, well... then they've dropped
return m_groupsAgentsDroppedFromChatSession.ContainsKey(groupID)
&& m_groupsAgentsDroppedFromChatSession[groupID].Contains(agentID);
}
public void AgentDroppedFromGroupChatSession(UUID agentID, UUID groupID)
{
if (m_groupsAgentsDroppedFromChatSession.ContainsKey(groupID))
{
// If not in dropped list, add
if (!m_groupsAgentsDroppedFromChatSession[groupID].Contains(agentID))
{
m_groupsAgentsDroppedFromChatSession[groupID].Add(agentID);
}
}
}
public void AgentInvitedToGroupChatSession(UUID agentID, UUID groupID)
{
// Add Session Status if it doesn't exist for this session
CreateGroupChatSessionTracking(groupID);
// If nessesary, remove from dropped list
if (m_groupsAgentsDroppedFromChatSession[groupID].Contains(agentID))
{
m_groupsAgentsDroppedFromChatSession[groupID].Remove(agentID);
}
}
private void CreateGroupChatSessionTracking(UUID groupID)
{
if (!m_groupsAgentsDroppedFromChatSession.ContainsKey(groupID))
{
m_groupsAgentsDroppedFromChatSession.Add(groupID, new List<UUID>());
m_groupsAgentsInvitedToChatSession.Add(groupID, new List<UUID>());
}
}
#endregion
#region XmlRpcHashtableMarshalling
private GroupProfileData GroupProfileHashtableToGroupProfileData(Hashtable groupProfile)
{
GroupProfileData group = new GroupProfileData();
group.GroupID = UUID.Parse((string)groupProfile["GroupID"]);
group.Name = (string)groupProfile["Name"];
if (groupProfile["Charter"] != null)
{
group.Charter = (string)groupProfile["Charter"];
}
group.ShowInList = ((string)groupProfile["ShowInList"]) == "1";
group.InsigniaID = UUID.Parse((string)groupProfile["InsigniaID"]);
group.MembershipFee = int.Parse((string)groupProfile["MembershipFee"]);
group.OpenEnrollment = ((string)groupProfile["OpenEnrollment"]) == "1";
group.AllowPublish = ((string)groupProfile["AllowPublish"]) == "1";
group.MaturePublish = ((string)groupProfile["MaturePublish"]) == "1";
group.FounderID = UUID.Parse((string)groupProfile["FounderID"]);
group.OwnerRole = UUID.Parse((string)groupProfile["OwnerRoleID"]);
group.GroupMembershipCount = int.Parse((string)groupProfile["GroupMembershipCount"]);
group.GroupRolesCount = int.Parse((string)groupProfile["GroupRolesCount"]);
return group;
}
private GroupRecord GroupProfileHashtableToGroupRecord(Hashtable groupProfile)
{
GroupRecord group = new GroupRecord();
group.GroupID = UUID.Parse((string)groupProfile["GroupID"]);
group.GroupName = groupProfile["Name"].ToString();
if (groupProfile["Charter"] != null)
{
group.Charter = (string)groupProfile["Charter"];
}
group.ShowInList = ((string)groupProfile["ShowInList"]) == "1";
group.GroupPicture = UUID.Parse((string)groupProfile["InsigniaID"]);
group.MembershipFee = int.Parse((string)groupProfile["MembershipFee"]);
group.OpenEnrollment = ((string)groupProfile["OpenEnrollment"]) == "1";
group.AllowPublish = ((string)groupProfile["AllowPublish"]) == "1";
group.MaturePublish = ((string)groupProfile["MaturePublish"]) == "1";
group.FounderID = UUID.Parse((string)groupProfile["FounderID"]);
group.OwnerRoleID = UUID.Parse((string)groupProfile["OwnerRoleID"]);
return group;
}
private static GroupMembershipData HashTableToGroupMembershipData(Hashtable respData)
{
GroupMembershipData data = new GroupMembershipData();
data.AcceptNotices = ((string)respData["AcceptNotices"] == "1");
data.Contribution = int.Parse((string)respData["Contribution"]);
data.ListInProfile = ((string)respData["ListInProfile"] == "1");
data.ActiveRole = new UUID((string)respData["SelectedRoleID"]);
data.GroupTitle = (string)respData["Title"];
data.GroupPowers = ulong.Parse((string)respData["GroupPowers"]);
// Is this group the agent's active group
data.GroupID = new UUID((string)respData["GroupID"]);
UUID ActiveGroup = new UUID((string)respData["ActiveGroupID"]);
data.Active = data.GroupID.Equals(ActiveGroup);
data.AllowPublish = ((string)respData["AllowPublish"] == "1");
if (respData["Charter"] != null)
{
data.Charter = (string)respData["Charter"];
}
data.FounderID = new UUID((string)respData["FounderID"]);
data.GroupID = new UUID((string)respData["GroupID"]);
data.GroupName = (string)respData["GroupName"];
data.GroupPicture = new UUID((string)respData["InsigniaID"]);
data.MaturePublish = ((string)respData["MaturePublish"] == "1");
data.MembershipFee = int.Parse((string)respData["MembershipFee"]);
data.OpenEnrollment = ((string)respData["OpenEnrollment"] == "1");
data.ShowInList = ((string)respData["ShowInList"] == "1");
return data;
}
#endregion
/// <summary>
/// Encapsulate the XmlRpc call to standardize security and error handling.
/// </summary>
private Hashtable XmlRpcCall(UUID requestingAgentID, string function, Hashtable param)
{
XmlRpcResponse resp = null;
string CacheKey = null;
// Only bother with the cache if it isn't disabled.
if (m_cacheTimeout > 0)
{
if (!function.StartsWith("groups.get"))
{
// Any and all updates cause the cache to clear
m_memoryCache.Clear();
}
else
{
StringBuilder sb = new StringBuilder(requestingAgentID + function);
foreach (object key in param.Keys)
{
if (param[key] != null)
{
sb.AppendFormat(",{0}:{1}", key.ToString(), param[key].ToString());
}
}
CacheKey = sb.ToString();
m_memoryCache.TryGetValue(CacheKey, out resp);
}
}
if (resp == null)
{
if (m_debugEnabled)
m_log.DebugFormat("[XMLRPC-GROUPS-CONNECTOR]: Cache miss for key {0}", CacheKey);
string UserService;
UUID SessionID;
GetClientGroupRequestID(requestingAgentID, out UserService, out SessionID);
param.Add("RequestingAgentID", requestingAgentID.ToString());
param.Add("RequestingAgentUserService", UserService);
param.Add("RequestingSessionID", SessionID.ToString());
param.Add("ReadKey", m_groupReadKey);
param.Add("WriteKey", m_groupWriteKey);
IList parameters = new ArrayList();
parameters.Add(param);
ConfigurableKeepAliveXmlRpcRequest req;
req = new ConfigurableKeepAliveXmlRpcRequest(function, parameters, m_disableKeepAlive);
try
{
resp = req.Send(m_groupsServerURI, 10000);
if ((m_cacheTimeout > 0) && (CacheKey != null))
{
m_memoryCache.AddOrUpdate(CacheKey, resp, TimeSpan.FromSeconds(m_cacheTimeout));
}
}
catch (Exception e)
{
m_log.ErrorFormat(
"[XMLRPC-GROUPS-CONNECTOR]: An error has occured while attempting to access the XmlRpcGroups server method {0} at {1}",
function, m_groupsServerURI);
m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: {0}{1}", e.Message, e.StackTrace);
foreach (string ResponseLine in req.RequestResponse.Split(new string[] { Environment.NewLine }, StringSplitOptions.None))
{
m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: {0} ", ResponseLine);
}
foreach (string key in param.Keys)
{
m_log.WarnFormat("[XMLRPC-GROUPS-CONNECTOR]: {0} :: {1}", key, param[key].ToString());
}
Hashtable respData = new Hashtable();
respData.Add("error", e.ToString());
return respData;
}
}
if (resp.Value is Hashtable)
{
Hashtable respData = (Hashtable)resp.Value;
if (respData.Contains("error") && !respData.Contains("succeed"))
{
LogRespDataToConsoleError(requestingAgentID, function, param, respData);
}
return respData;
}
m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: The XmlRpc server returned a {1} instead of a hashtable for {0}", function, resp.Value.GetType().ToString());
if (resp.Value is ArrayList)
{
ArrayList al = (ArrayList)resp.Value;
m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: Contains {0} elements", al.Count);
foreach (object o in al)
{
m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: {0} :: {1}", o.GetType().ToString(), o.ToString());
}
}
else
{
m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: Function returned: {0}", resp.Value.ToString());
}
Hashtable error = new Hashtable();
error.Add("error", "invalid return value");
return error;
}
private void LogRespDataToConsoleError(UUID requestingAgentID, string function, Hashtable param, Hashtable respData)
{
m_log.ErrorFormat(
"[XMLRPC-GROUPS-CONNECTOR]: Error when calling {0} for {1} with params {2}. Response params are {3}",
function, requestingAgentID, Util.PrettyFormatToSingleLine(param), Util.PrettyFormatToSingleLine(respData));
}
/// <summary>
/// Group Request Tokens are an attempt to allow the groups service to authenticate
/// requests.
/// TODO: This broke after the big grid refactor, either find a better way, or discard this
/// </summary>
/// <param name="client"></param>
/// <returns></returns>
private void GetClientGroupRequestID(UUID AgentID, out string UserServiceURL, out UUID SessionID)
{
UserServiceURL = "";
SessionID = UUID.Zero;
// Need to rework this based on changes to User Services
/*
UserAccount userAccount = m_accountService.GetUserAccount(UUID.Zero,AgentID);
if (userAccount == null)
{
// This should be impossible. If I've been passed a reference to a client
// that client should be registered with the UserService. So something
// is horribly wrong somewhere.
m_log.WarnFormat("[GROUPS]: Could not find a UserServiceURL for {0}", AgentID);
}
else if (userProfile is ForeignUserProfileData)
{
// They aren't from around here
ForeignUserProfileData fupd = (ForeignUserProfileData)userProfile;
UserServiceURL = fupd.UserServerURI;
SessionID = fupd.CurrentAgent.SessionID;
}
else
{
// They're a local user, use this:
UserServiceURL = m_commManager.NetworkServersInfo.UserURL;
SessionID = userProfile.CurrentAgent.SessionID;
}
*/
}
}
}
namespace Nwc.XmlRpc
{
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Text;
using System.Xml;
/// <summary>Class supporting the request side of an XML-RPC transaction.</summary>
public class ConfigurableKeepAliveXmlRpcRequest : XmlRpcRequest
{
private XmlRpcRequestSerializer _serializer = new XmlRpcRequestSerializer();
private XmlRpcResponseDeserializer _deserializer = new XmlRpcResponseDeserializer();
private bool _disableKeepAlive = true;
public string RequestResponse = String.Empty;
/// <summary>Instantiate an <c>XmlRpcRequest</c> for a specified method and parameters.</summary>
/// <param name="methodName"><c>String</c> designating the <i>object.method</i> on the server the request
/// should be directed to.</param>
/// <param name="parameters"><c>ArrayList</c> of XML-RPC type parameters to invoke the request with.</param>
public ConfigurableKeepAliveXmlRpcRequest(String methodName, IList parameters, bool disableKeepAlive)
{
MethodName = methodName;
_params = parameters;
_disableKeepAlive = disableKeepAlive;
}
/// <summary>Send the request to the server.</summary>
/// <param name="url"><c>String</c> The url of the XML-RPC server.</param>
/// <returns><c>XmlRpcResponse</c> The response generated.</returns>
public XmlRpcResponse Send(String url)
{
ServicePointManagerTimeoutSupport.ResetHosts();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
if (request == null)
throw new XmlRpcException(XmlRpcErrorCodes.TRANSPORT_ERROR,
XmlRpcErrorCodes.TRANSPORT_ERROR_MSG + ": Could not create request with " + url);
request.Method = "POST";
request.ContentType = "text/xml";
request.AllowWriteStreamBuffering = true;
request.KeepAlive = !_disableKeepAlive;
using (Stream stream = request.GetRequestStream())
{
using (XmlTextWriter xml = new XmlTextWriter(stream, Encoding.ASCII))
{
_serializer.Serialize(xml, this);
xml.Flush();
}
}
XmlRpcResponse resp;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream s = response.GetResponseStream())
{
using (StreamReader input = new StreamReader(s))
{
string inputXml = input.ReadToEnd();
try
{
resp = (XmlRpcResponse)_deserializer.Deserialize(inputXml);
}
catch (Exception e)
{
RequestResponse = inputXml;
throw e;
}
}
}
}
return resp;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Aspose.Cells.Common.CloudHelper;
using Aspose.Cells.Common.Config;
using Aspose.Cells.Common.Controllers;
using Aspose.Cells.Common.Models;
using Aspose.Cells.Common.Services;
using Aspose.Cells.Properties;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
namespace Aspose.Cells.Metadata.Controllers
{
public class MetadataCloudApiController : CellsCloudApiControllerBase
{
private const string AppName = "Metadata";
public MetadataCloudApiController(IStorageService storage, IConfiguration configuration, ILogger<MetadataCloudApiController> logger) : base(storage, configuration, logger)
{
}
[HttpPost]
public async Task<ActionResult> Properties([FromBody] JObject obj)
{
Opts.AppName = "Metadata";
Opts.MethodName = "Properties";
Opts.FileName = Convert.ToString(obj["FileName"]);
Opts.FolderName = Convert.ToString(obj["id"]);
var interruptMonitor = new InterruptMonitor();
var thread = new Thread(InterruptMonitor);
try
{
var objectPath = $"{Configuration.SourceFolder}/{Opts.FolderName}/{Opts.FileName}";
IDictionary<string, Stream> dictStreams = new Dictionary<string, Stream> ();
dictStreams.Add(Opts.FileName, Storage.Download(objectPath).Result);
CellsCloudClient cells = new CellsCloudClient();
IList<CellsDocumentProperty> builtInDocumentProperties = cells.GetMetadata(dictStreams, "BuiltIn").Result;
IList<CellsDocumentProperty> customocumentProperties = cells.GetMetadata(dictStreams, "Custom").Result;
return Ok(new CloudPropertiesResponse { BuiltIn = toDocProperties (builtInDocumentProperties), Custom = toDocProperties( customocumentProperties) });
}
catch (Exception e)
{
var exception = e.InnerException ?? e;
var statusCode = 500;
if (exception is CellsException {Code: ExceptionType.IncorrectPassword})
{
statusCode = 403;
}
if (exception is CellsException {Code: ExceptionType.FileFormat})
{
statusCode = 415;
}
Logger.LogError("App = {App} | Method = {Method} | Message = {Message} | FileName = {FileName} | FolderName = {FolderName}",
AppName, "Properties", exception.Message, Convert.ToString(obj["FileName"]), Convert.ToString(obj["id"]));
var response = new Response
{
StatusCode = statusCode,
Status = exception.Message,
FolderName = Opts.FolderName,
Text = "Metadata Properties"
};
return BadRequest(response);
}
finally
{
thread.Interrupt();
}
}
[HttpPost]
public async Task<Response> Download([FromBody] JObject obj)
{
Opts.AppName = "Metadata";
Opts.MethodName = "Download";
var interruptMonitor = new InterruptMonitor();
var thread = new Thread(InterruptMonitor);
try
{
Opts.FileName = Convert.ToString(obj["FileName"]);
Opts.ResultFileName = Opts.FileName;
Opts.FolderName = Convert.ToString(obj["id"]);
var (_, outFilePath) = BeforeAction();
CellsCloudClient cellsCloudClient = new CellsCloudClient();
var path = $"{Configuration.SourceFolder}/{Opts.FolderName}/{Opts.FileName}";
var filenmae = $"{Opts.FileName}";
IDictionary<string, Stream> files = new Dictionary<string, Stream>();
files.Add(filenmae, Storage.Download(path).Result);
CellsCloudFilesResult cellsCloudFilesResult = cellsCloudClient.PostMetadata(files, "BuildIn", obj["properties"]["BuiltIn"]?.ToObject<List<CellsDocumentProperty>>()).Result;
cellsCloudFilesResult = cellsCloudClient.PostMetadata(cellsCloudFilesResult.Files.ToStream(), "Custom", obj["properties"]["Custom"]?.ToObject<List<CellsDocumentProperty>>()).Result;
await Storage.UpdateStatus(Common.Models.Response.Process(Opts.FolderName, Opts.ResultFileName));
var stopWatch = new Stopwatch();
stopWatch.Start();
Logger.LogWarning("AppName = {AppName} | MethodName = {MethodName} | Filename = {Filename} | Start",
AppName, Opts.MethodName, Opts.FileName);
var response = await AfterAction(outFilePath,(Dictionary<string,Stream>) cellsCloudFilesResult.Files.ToStream());
stopWatch.Stop();
Logger.LogWarning("AppName = {AppName} | MethodName = {MethodName} | Filename = {Filename} | Cost Seconds = {Seconds}s",
AppName, Opts.MethodName, Opts.FileName, stopWatch.Elapsed.TotalSeconds);
return response;
}
catch (Exception e)
{
var exception = e.InnerException ?? e;
Logger.LogError("App = {App} | Method = {Method} | Message = {Message} | FileName = {FileName} | FolderName = {FolderName}",
AppName, "", exception.Message, Convert.ToString(obj["FileName"]), Convert.ToString(obj["id"]));
return await Task.FromResult(new Response
{
StatusCode = 500,
Status = exception.Message,
FolderName = Convert.ToString(obj["id"]),
Text = "Metadata Download"
});
}
finally
{
thread.Interrupt();
}
}
[HttpPost]
public async Task<Response> Clear([FromBody] JObject obj)
{
Opts.AppName = "Metadata";
Opts.MethodName = "Clear";
var interruptMonitor = new InterruptMonitor();
var thread = new Thread(InterruptMonitor);
try
{
Opts.FileName = Convert.ToString(obj["FileName"]);
Opts.ResultFileName = Opts.FileName;
Opts.FolderName = Convert.ToString(obj["id"]);
var (_, outFilePath) = BeforeAction();
CellsCloudClient cellsCloudClient = new CellsCloudClient();
var path = $"{Configuration.SourceFolder}/{Opts.FolderName}/{Opts.FileName}";
var filenmae = $"{Opts.FileName}";
IDictionary<string, Stream> files = new Dictionary<string, Stream>();
files.Add(filenmae, Storage.Download(path).Result);
CellsCloudFilesResult cellsCloudFilesResult = cellsCloudClient.DeleteMetadata(files, "ALL").Result;
await Storage.UpdateStatus(Common.Models.Response.Process(Opts.FolderName, Opts.ResultFileName));
var stopWatch = new Stopwatch();
stopWatch.Start();
Logger.LogWarning("AppName = {AppName} | MethodName = {MethodName} | Filename = {Filename} | Start",
AppName, Opts.MethodName, Opts.FileName);
var response = await AfterAction(outFilePath, (Dictionary<string, Stream>)cellsCloudFilesResult.Files.ToStream());
stopWatch.Stop();
Logger.LogWarning("AppName = {AppName} | MethodName = {MethodName} | Filename = {Filename} | Cost Seconds = {Seconds}s",
AppName, Opts.MethodName, Opts.FileName, stopWatch.Elapsed.TotalSeconds);
return response;
}
catch (Exception e)
{
Logger.LogError("AppName = {AppName} | MethodName = {MethodName} | Message = {Message} | Filename = {Filename} | FolderName = {FolderName}",
AppName, "Clear", e.Message, Convert.ToString(obj["FileName"]), Convert.ToString(obj["id"]));
return await Task.FromResult(new Response
{
StatusCode = 500,
Status = e.Message,
FolderName = Convert.ToString(obj["id"]),
Text = "Metadata Clear"
});
}
finally
{
thread.Interrupt();
}
}
private class CloudPropertiesResponse
{
public IList<DocProperty> BuiltIn { get; set; }
public IList<DocProperty> Custom { get; set; }
}
private class DocProperty
{
public string Name { get; set; }
public object Value { get; set; }
public PropertyType Type { get; set; }
}
private IList<DocProperty> toDocProperties(IList<CellsDocumentProperty> cellsDocumentProperties)
{
IList<DocProperty> docProperties = new List<DocProperty>();
foreach(var cellsDocumentProperty in cellsDocumentProperties)
{
DocProperty docProperty = new DocProperty();
docProperty.Name = cellsDocumentProperty.Name;
docProperty.Value = cellsDocumentProperty.Value;
docProperty.Type = string.IsNullOrEmpty(cellsDocumentProperty.Type)? PropertyType.String: Enum.Parse<PropertyType>(cellsDocumentProperty.Type);
docProperties.Add(docProperty);
}
return docProperties;
}
}
}
| |
// 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.Runtime.CompilerServices;
using System.Threading.Tasks;
using Xunit;
namespace System.Threading.Channels.Tests
{
public abstract partial class ChannelTestBase : TestBase
{
protected Channel<int> CreateChannel() => CreateChannel<int>();
protected abstract Channel<T> CreateChannel<T>();
protected Channel<int> CreateFullChannel() => CreateFullChannel<int>();
protected abstract Channel<T> CreateFullChannel<T>();
protected virtual bool AllowSynchronousContinuations => false;
protected virtual bool RequiresSingleReader => false;
protected virtual bool RequiresSingleWriter => false;
protected virtual bool BuffersItems => true;
[Fact]
public void ValidateDebuggerAttributes()
{
Channel<int> c = CreateChannel();
for (int i = 1; i <= 10; i++)
{
c.Writer.WriteAsync(i);
}
DebuggerAttributes.ValidateDebuggerDisplayReferences(c);
DebuggerAttributes.InvokeDebuggerTypeProxyProperties(c);
}
[Fact]
public void Cast_MatchesInOut()
{
Channel<int> c = CreateChannel();
ChannelReader<int> rc = c;
ChannelWriter<int> wc = c;
Assert.Same(rc, c.Reader);
Assert.Same(wc, c.Writer);
}
[Fact]
public void Completion_Idempotent()
{
Channel<int> c = CreateChannel();
Task completion = c.Reader.Completion;
Assert.Equal(TaskStatus.WaitingForActivation, completion.Status);
Assert.Same(completion, c.Reader.Completion);
c.Writer.Complete();
Assert.Same(completion, c.Reader.Completion);
Assert.Equal(TaskStatus.RanToCompletion, completion.Status);
}
[Fact]
public async Task Complete_AfterEmpty_NoWaiters_TriggersCompletion()
{
Channel<int> c = CreateChannel();
c.Writer.Complete();
await c.Reader.Completion;
}
[Fact]
public async Task Complete_AfterEmpty_WaitingReader_TriggersCompletion()
{
Channel<int> c = CreateChannel();
Task<int> r = c.Reader.ReadAsync().AsTask();
c.Writer.Complete();
await c.Reader.Completion;
await Assert.ThrowsAnyAsync<InvalidOperationException>(() => r);
}
[Fact]
public async Task Complete_BeforeEmpty_WaitingReaders_TriggersCompletion()
{
Channel<int> c = CreateChannel();
ValueTask<int> read = c.Reader.ReadAsync();
c.Writer.Complete();
await c.Reader.Completion;
await Assert.ThrowsAnyAsync<InvalidOperationException>(async () => await read);
}
[Fact]
public void Complete_Twice_ThrowsInvalidOperationException()
{
Channel<int> c = CreateChannel();
c.Writer.Complete();
Assert.ThrowsAny<InvalidOperationException>(() => c.Writer.Complete());
}
[Fact]
public void TryComplete_Twice_ReturnsTrueThenFalse()
{
Channel<int> c = CreateChannel();
Assert.True(c.Writer.TryComplete());
Assert.False(c.Writer.TryComplete());
Assert.False(c.Writer.TryComplete());
}
[Fact]
public async Task TryComplete_ErrorsPropage()
{
Channel<int> c;
// Success
c = CreateChannel();
Assert.True(c.Writer.TryComplete());
await c.Reader.Completion;
// Error
c = CreateChannel();
Assert.True(c.Writer.TryComplete(new FormatException()));
await Assert.ThrowsAsync<FormatException>(() => c.Reader.Completion);
// Canceled
c = CreateChannel();
var cts = new CancellationTokenSource();
cts.Cancel();
Assert.True(c.Writer.TryComplete(new OperationCanceledException(cts.Token)));
await AssertCanceled(c.Reader.Completion, cts.Token);
}
[Fact]
public void SingleProducerConsumer_ConcurrentReadWrite_Success()
{
Channel<int> c = CreateChannel();
const int NumItems = 100000;
Task.WaitAll(
Task.Run(async () =>
{
for (int i = 0; i < NumItems; i++)
{
await c.Writer.WriteAsync(i);
}
}),
Task.Run(async () =>
{
for (int i = 0; i < NumItems; i++)
{
Assert.Equal(i, await c.Reader.ReadAsync());
}
}));
}
[Fact]
public void SingleProducerConsumer_PingPong_Success()
{
Channel<int> c1 = CreateChannel();
Channel<int> c2 = CreateChannel();
const int NumItems = 100000;
Task.WaitAll(
Task.Run(async () =>
{
for (int i = 0; i < NumItems; i++)
{
Assert.Equal(i, await c1.Reader.ReadAsync());
await c2.Writer.WriteAsync(i);
}
}),
Task.Run(async () =>
{
for (int i = 0; i < NumItems; i++)
{
await c1.Writer.WriteAsync(i);
Assert.Equal(i, await c2.Reader.ReadAsync());
}
}));
}
[Theory]
[InlineData(1, 1)]
[InlineData(1, 10)]
[InlineData(10, 1)]
[InlineData(10, 10)]
public void ManyProducerConsumer_ConcurrentReadWrite_Success(int numReaders, int numWriters)
{
if (RequiresSingleReader && numReaders > 1)
{
return;
}
if (RequiresSingleWriter && numWriters > 1)
{
return;
}
Channel<int> c = CreateChannel();
const int NumItems = 10000;
long readTotal = 0;
int remainingWriters = numWriters;
int remainingItems = NumItems;
Task[] tasks = new Task[numWriters + numReaders];
for (int i = 0; i < numReaders; i++)
{
tasks[i] = Task.Run(async () =>
{
try
{
while (await c.Reader.WaitToReadAsync())
{
if (c.Reader.TryRead(out int value))
{
Interlocked.Add(ref readTotal, value);
}
}
}
catch (ChannelClosedException) { }
});
}
for (int i = 0; i < numWriters; i++)
{
tasks[numReaders + i] = Task.Run(async () =>
{
while (true)
{
int value = Interlocked.Decrement(ref remainingItems);
if (value < 0)
{
break;
}
await c.Writer.WriteAsync(value + 1);
}
if (Interlocked.Decrement(ref remainingWriters) == 0)
{
c.Writer.Complete();
}
});
}
Task.WaitAll(tasks);
Assert.Equal((NumItems * (NumItems + 1L)) / 2, readTotal);
}
[Fact]
public void WaitToReadAsync_DataAvailableBefore_CompletesSynchronously()
{
Channel<int> c = CreateChannel();
ValueTask write = c.Writer.WriteAsync(42);
ValueTask<bool> read = c.Reader.WaitToReadAsync();
Assert.True(read.IsCompletedSuccessfully);
}
[Fact]
public void WaitToReadAsync_DataAvailableAfter_CompletesAsynchronously()
{
Channel<int> c = CreateChannel();
ValueTask<bool> read = c.Reader.WaitToReadAsync();
Assert.False(read.IsCompleted);
ValueTask write = c.Writer.WriteAsync(42);
Assert.True(read.Result);
}
[Fact]
public void WaitToReadAsync_AfterComplete_SynchronouslyCompletes()
{
Channel<int> c = CreateChannel();
c.Writer.Complete();
ValueTask<bool> read = c.Reader.WaitToReadAsync();
Assert.True(read.IsCompletedSuccessfully);
Assert.False(read.Result);
}
[Fact]
public void WaitToReadAsync_BeforeComplete_AsynchronouslyCompletes()
{
Channel<int> c = CreateChannel();
ValueTask<bool> read = c.Reader.WaitToReadAsync();
Assert.False(read.IsCompleted);
c.Writer.Complete();
Assert.False(read.Result);
}
[Fact]
public void WaitToWriteAsync_AfterComplete_SynchronouslyCompletes()
{
Channel<int> c = CreateChannel();
c.Writer.Complete();
ValueTask<bool> write = c.Writer.WaitToWriteAsync();
Assert.True(write.IsCompletedSuccessfully);
Assert.False(write.Result);
}
[Fact]
public void WaitToWriteAsync_EmptyChannel_SynchronouslyCompletes()
{
if (!BuffersItems)
{
return;
}
Channel<int> c = CreateChannel();
ValueTask<bool> write = c.Writer.WaitToWriteAsync();
Assert.True(write.IsCompletedSuccessfully);
Assert.True(write.Result);
}
[Fact]
public async Task WaitToWriteAsync_ManyConcurrent_SatisifedByReaders()
{
if (RequiresSingleReader || RequiresSingleWriter)
{
return;
}
Channel<int> c = CreateChannel();
Task[] writers = Enumerable.Range(0, 100).Select(_ => c.Writer.WaitToWriteAsync().AsTask()).ToArray();
Task[] readers = Enumerable.Range(0, 100).Select(_ => c.Reader.ReadAsync().AsTask()).ToArray();
await Task.WhenAll(writers);
}
[Fact]
public void WaitToWriteAsync_BlockedReader_ReturnsTrue()
{
Channel<int> c = CreateChannel();
ValueTask<int> reader = c.Reader.ReadAsync();
AssertSynchronousSuccess(c.Writer.WaitToWriteAsync());
}
[Fact]
public void TryRead_DataAvailable_Success()
{
Channel<int> c = CreateChannel();
ValueTask write = c.Writer.WriteAsync(42);
Assert.True(c.Reader.TryRead(out int result));
Assert.Equal(42, result);
}
[Fact]
public void TryRead_AfterComplete_ReturnsFalse()
{
Channel<int> c = CreateChannel();
c.Writer.Complete();
Assert.False(c.Reader.TryRead(out int result));
}
[Fact]
public void TryWrite_AfterComplete_ReturnsFalse()
{
Channel<int> c = CreateChannel();
c.Writer.Complete();
Assert.False(c.Writer.TryWrite(42));
}
[Fact]
public async Task WriteAsync_AfterComplete_ThrowsException()
{
Channel<int> c = CreateChannel();
c.Writer.Complete();
await Assert.ThrowsAnyAsync<InvalidOperationException>(async () => await c.Writer.WriteAsync(42));
}
[Fact]
public async Task Complete_WithException_PropagatesToCompletion()
{
Channel<int> c = CreateChannel();
var exc = new FormatException();
c.Writer.Complete(exc);
Assert.Same(exc, await Assert.ThrowsAsync<FormatException>(() => c.Reader.Completion));
}
[Fact]
public async Task Complete_WithCancellationException_PropagatesToCompletion()
{
Channel<int> c = CreateChannel();
var cts = new CancellationTokenSource();
cts.Cancel();
Exception exc = null;
try { cts.Token.ThrowIfCancellationRequested(); }
catch (Exception e) { exc = e; }
c.Writer.Complete(exc);
await AssertCanceled(c.Reader.Completion, cts.Token);
}
[Fact]
public async Task Complete_WithException_PropagatesToExistingWriter()
{
Channel<int> c = CreateFullChannel();
if (c != null)
{
ValueTask write = c.Writer.WriteAsync(42);
var exc = new FormatException();
c.Writer.Complete(exc);
Assert.Same(exc, (await Assert.ThrowsAsync<ChannelClosedException>(async () => await write)).InnerException);
}
}
[Fact]
public async Task Complete_WithException_PropagatesToNewWriter()
{
Channel<int> c = CreateChannel();
var exc = new FormatException();
c.Writer.Complete(exc);
ValueTask write = c.Writer.WriteAsync(42);
Assert.Same(exc, (await Assert.ThrowsAsync<ChannelClosedException>(async () => await write)).InnerException);
}
[Fact]
public async Task Complete_WithException_PropagatesToExistingWaitingReader()
{
Channel<int> c = CreateChannel();
ValueTask<bool> read = c.Reader.WaitToReadAsync();
var exc = new FormatException();
c.Writer.Complete(exc);
await Assert.ThrowsAsync<FormatException>(async () => await read);
}
[Fact]
public async Task Complete_WithException_PropagatesToNewWaitingReader()
{
Channel<int> c = CreateChannel();
var exc = new FormatException();
c.Writer.Complete(exc);
ValueTask<bool> read = c.Reader.WaitToReadAsync();
await Assert.ThrowsAsync<FormatException>(async () => await read);
}
[Fact]
public async Task Complete_WithException_PropagatesToNewWaitingWriter()
{
Channel<int> c = CreateChannel();
var exc = new FormatException();
c.Writer.Complete(exc);
ValueTask<bool> write = c.Writer.WaitToWriteAsync();
await Assert.ThrowsAsync<FormatException>(async () => await write);
}
[Fact]
public void ManyWriteAsync_ThenManyTryRead_Success()
{
if (RequiresSingleReader || RequiresSingleWriter)
{
return;
}
Channel<int> c = CreateChannel();
const int NumItems = 2000;
ValueTask[] writers = new ValueTask[NumItems];
for (int i = 0; i < writers.Length; i++)
{
writers[i] = c.Writer.WriteAsync(i);
}
Task<int>[] readers = new Task<int>[NumItems];
for (int i = 0; i < readers.Length; i++)
{
int result;
Assert.True(c.Reader.TryRead(out result));
Assert.Equal(i, result);
}
Assert.All(writers, w => Assert.True(w.IsCompleted));
}
[Fact]
public void Precancellation_Writing_ReturnsImmediately()
{
Channel<int> c = CreateChannel();
ValueTask writeTask = c.Writer.WriteAsync(42, new CancellationToken(true));
Assert.True(writeTask.IsCanceled);
ValueTask<bool> waitTask = c.Writer.WaitToWriteAsync(new CancellationToken(true));
Assert.True(writeTask.IsCanceled);
}
[Fact]
public void Write_WaitToReadAsync_CompletesSynchronously()
{
Channel<int> c = CreateChannel();
c.Writer.WriteAsync(42);
AssertSynchronousTrue(c.Reader.WaitToReadAsync());
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Precancellation_WaitToReadAsync_ReturnsImmediately(bool dataAvailable)
{
Channel<int> c = CreateChannel();
if (dataAvailable)
{
Assert.True(c.Writer.TryWrite(42));
}
ValueTask<bool> waitTask = c.Reader.WaitToReadAsync(new CancellationToken(true));
Assert.True(waitTask.IsCanceled);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task WaitToReadAsync_DataWritten_CompletesSuccessfully(bool cancelable)
{
Channel<int> c = CreateChannel();
CancellationToken token = cancelable ? new CancellationTokenSource().Token : default;
ValueTask<bool> read = c.Reader.WaitToReadAsync(token);
Assert.False(read.IsCompleted);
ValueTask write = c.Writer.WriteAsync(42, token);
Assert.True(await read);
}
[Fact]
public async Task WaitToReadAsync_NoDataWritten_Canceled_CompletesAsCanceled()
{
Channel<int> c = CreateChannel();
var cts = new CancellationTokenSource();
ValueTask<bool> read = c.Reader.WaitToReadAsync(cts.Token);
Assert.False(read.IsCompleted);
cts.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => await read);
}
[Fact]
public async Task ReadAsync_ThenWriteAsync_Succeeds()
{
Channel<int> c = CreateChannel();
ValueTask<int> r = c.Reader.ReadAsync();
Assert.False(r.IsCompleted);
ValueTask w = c.Writer.WriteAsync(42);
AssertSynchronousSuccess(w);
Assert.Equal(42, await r);
}
[Fact]
public async Task WriteAsync_ReadAsync_Succeeds()
{
Channel<int> c = CreateChannel();
ValueTask w = c.Writer.WriteAsync(42);
ValueTask<int> r = c.Reader.ReadAsync();
await Task.WhenAll(w.AsTask(), r.AsTask());
Assert.Equal(42, await r);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Precancellation_ReadAsync_ReturnsImmediately(bool dataAvailable)
{
Channel<int> c = CreateChannel();
if (dataAvailable)
{
Assert.True(c.Writer.TryWrite(42));
}
ValueTask<int> readTask = c.Reader.ReadAsync(new CancellationToken(true));
Assert.True(readTask.IsCanceled);
}
[Fact]
public async Task ReadAsync_Canceled_CanceledAsynchronously()
{
Channel<int> c = CreateChannel();
var cts = new CancellationTokenSource();
ValueTask<int> r = c.Reader.ReadAsync(cts.Token);
Assert.False(r.IsCompleted);
cts.Cancel();
await AssertCanceled(r.AsTask(), cts.Token);
if (c.Writer.TryWrite(42))
{
Assert.Equal(42, await c.Reader.ReadAsync());
}
}
[Fact]
public async Task ReadAsync_WriteAsync_ManyConcurrentReaders_SerializedWriters_Success()
{
if (RequiresSingleReader)
{
return;
}
Channel<int> c = CreateChannel();
const int Items = 100;
ValueTask<int>[] readers = (from i in Enumerable.Range(0, Items) select c.Reader.ReadAsync()).ToArray();
for (int i = 0; i < Items; i++)
{
await c.Writer.WriteAsync(i);
}
Assert.Equal((Items * (Items - 1)) / 2, Enumerable.Sum(await Task.WhenAll(readers.Select(r => r.AsTask()))));
}
[Fact]
public async Task ReadAsync_TryWrite_ManyConcurrentReaders_SerializedWriters_Success()
{
if (RequiresSingleReader)
{
return;
}
Channel<int> c = CreateChannel();
const int Items = 100;
Task<int>[] readers = (from i in Enumerable.Range(0, Items) select c.Reader.ReadAsync().AsTask()).ToArray();
var remainingReaders = new List<Task<int>>(readers);
for (int i = 0; i < Items; i++)
{
Assert.True(c.Writer.TryWrite(i), $"Failed to write at {i}");
Task<int> r = await Task.WhenAny(remainingReaders);
await r;
remainingReaders.Remove(r);
}
Assert.Equal((Items * (Items - 1)) / 2, Enumerable.Sum(await Task.WhenAll(readers)));
}
[Fact]
public async Task ReadAsync_AlreadyCompleted_Throws()
{
Channel<int> c = CreateChannel();
c.Writer.Complete();
await Assert.ThrowsAsync<ChannelClosedException>(() => c.Reader.ReadAsync().AsTask());
}
[Fact]
public async Task ReadAsync_SubsequentlyCompleted_Throws()
{
Channel<int> c = CreateChannel();
Task<int> r = c.Reader.ReadAsync().AsTask();
Assert.False(r.IsCompleted);
c.Writer.Complete();
await Assert.ThrowsAsync<ChannelClosedException>(() => r);
}
[Fact]
public async Task ReadAsync_AfterFaultedChannel_Throws()
{
Channel<int> c = CreateChannel();
var e = new FormatException();
c.Writer.Complete(e);
Assert.True(c.Reader.Completion.IsFaulted);
ChannelClosedException cce = await Assert.ThrowsAsync<ChannelClosedException>(() => c.Reader.ReadAsync().AsTask());
Assert.Same(e, cce.InnerException);
}
[Fact]
public async Task ReadAsync_AfterCanceledChannel_Throws()
{
Channel<int> c = CreateChannel();
var e = new OperationCanceledException();
c.Writer.Complete(e);
Assert.True(c.Reader.Completion.IsCanceled);
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => c.Reader.ReadAsync().AsTask());
}
[Fact]
public async Task ReadAsync_Canceled_WriteAsyncCompletesNextReader()
{
Channel<int> c = CreateChannel();
for (int i = 0; i < 5; i++)
{
var cts = new CancellationTokenSource();
ValueTask<int> r = c.Reader.ReadAsync(cts.Token);
cts.Cancel();
await AssertCanceled(r.AsTask(), cts.Token);
}
for (int i = 0; i < 7; i++)
{
ValueTask<int> r = c.Reader.ReadAsync();
await c.Writer.WriteAsync(i);
Assert.Equal(i, await r);
}
}
[Fact]
public async Task ReadAsync_ConsecutiveReadsSucceed()
{
Channel<int> c = CreateChannel();
for (int i = 0; i < 5; i++)
{
ValueTask<int> r = c.Reader.ReadAsync();
await c.Writer.WriteAsync(i);
Assert.Equal(i, await r);
}
}
[Fact]
public async Task WaitToReadAsync_ConsecutiveReadsSucceed()
{
Channel<int> c = CreateChannel();
for (int i = 0; i < 5; i++)
{
ValueTask<bool> r = c.Reader.WaitToReadAsync();
await c.Writer.WriteAsync(i);
Assert.True(await r);
Assert.True(c.Reader.TryRead(out int item));
Assert.Equal(i, item);
}
}
[Theory]
[InlineData(false, null)]
[InlineData(false, false)]
[InlineData(false, true)]
[InlineData(true, null)]
[InlineData(true, false)]
[InlineData(true, true)]
public void WaitToReadAsync_MultipleContinuations_Throws(bool onCompleted, bool? continueOnCapturedContext)
{
Channel<int> c = CreateChannel();
ValueTask<bool> read = c.Reader.WaitToReadAsync();
switch (continueOnCapturedContext)
{
case null:
if (onCompleted)
{
read.GetAwaiter().OnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => read.GetAwaiter().OnCompleted(() => { }));
}
else
{
read.GetAwaiter().UnsafeOnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => read.GetAwaiter().UnsafeOnCompleted(() => { }));
}
break;
default:
if (onCompleted)
{
read.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => read.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(() => { }));
}
else
{
read.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().UnsafeOnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => read.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().UnsafeOnCompleted(() => { }));
}
break;
}
}
[Theory]
[InlineData(false, null)]
[InlineData(false, false)]
[InlineData(false, true)]
[InlineData(true, null)]
[InlineData(true, false)]
[InlineData(true, true)]
public void ReadAsync_MultipleContinuations_Throws(bool onCompleted, bool? continueOnCapturedContext)
{
Channel<int> c = CreateChannel();
ValueTask<int> read = c.Reader.ReadAsync();
switch (continueOnCapturedContext)
{
case null:
if (onCompleted)
{
read.GetAwaiter().OnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => read.GetAwaiter().OnCompleted(() => { }));
}
else
{
read.GetAwaiter().UnsafeOnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => read.GetAwaiter().UnsafeOnCompleted(() => { }));
}
break;
default:
if (onCompleted)
{
read.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => read.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(() => { }));
}
else
{
read.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().UnsafeOnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => read.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().UnsafeOnCompleted(() => { }));
}
break;
}
}
[Fact]
public async Task WaitToReadAsync_AwaitThenGetResult_Throws()
{
Channel<int> c = CreateChannel();
ValueTask<bool> read = c.Reader.WaitToReadAsync();
Assert.True(c.Writer.TryWrite(42));
Assert.True(await read);
Assert.Throws<InvalidOperationException>(() => read.GetAwaiter().IsCompleted);
Assert.Throws<InvalidOperationException>(() => read.GetAwaiter().OnCompleted(() => { }));
Assert.Throws<InvalidOperationException>(() => read.GetAwaiter().GetResult());
}
[Fact]
public async Task ReadAsync_AwaitThenGetResult_Throws()
{
Channel<int> c = CreateChannel();
ValueTask<int> read = c.Reader.ReadAsync();
Assert.True(c.Writer.TryWrite(42));
Assert.Equal(42, await read);
Assert.Throws<InvalidOperationException>(() => read.GetAwaiter().IsCompleted);
Assert.Throws<InvalidOperationException>(() => read.GetAwaiter().OnCompleted(() => { }));
Assert.Throws<InvalidOperationException>(() => read.GetAwaiter().GetResult());
}
[Fact]
public async Task WaitToWriteAsync_AwaitThenGetResult_Throws()
{
Channel<int> c = CreateFullChannel();
if (c == null)
{
return;
}
ValueTask<bool> write = c.Writer.WaitToWriteAsync();
await c.Reader.ReadAsync();
Assert.True(await write);
Assert.Throws<InvalidOperationException>(() => write.GetAwaiter().IsCompleted);
Assert.Throws<InvalidOperationException>(() => write.GetAwaiter().OnCompleted(() => { }));
Assert.Throws<InvalidOperationException>(() => write.GetAwaiter().GetResult());
}
[Fact]
public async Task WriteAsync_AwaitThenGetResult_Throws()
{
Channel<int> c = CreateFullChannel();
if (c == null)
{
return;
}
ValueTask write = c.Writer.WriteAsync(42);
await c.Reader.ReadAsync();
await write;
Assert.Throws<InvalidOperationException>(() => write.GetAwaiter().IsCompleted);
Assert.Throws<InvalidOperationException>(() => write.GetAwaiter().OnCompleted(() => { }));
Assert.Throws<InvalidOperationException>(() => write.GetAwaiter().GetResult());
}
[Theory]
[InlineData(false, null)]
[InlineData(false, false)]
[InlineData(false, true)]
[InlineData(true, null)]
[InlineData(true, false)]
[InlineData(true, true)]
public void WaitToWriteAsync_MultipleContinuations_Throws(bool onCompleted, bool? continueOnCapturedContext)
{
Channel<int> c = CreateFullChannel();
if (c == null)
{
return;
}
ValueTask<bool> write = c.Writer.WaitToWriteAsync();
switch (continueOnCapturedContext)
{
case null:
if (onCompleted)
{
write.GetAwaiter().OnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => write.GetAwaiter().OnCompleted(() => { }));
}
else
{
write.GetAwaiter().UnsafeOnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => write.GetAwaiter().UnsafeOnCompleted(() => { }));
}
break;
default:
if (onCompleted)
{
write.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => write.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(() => { }));
}
else
{
write.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().UnsafeOnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => write.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().UnsafeOnCompleted(() => { }));
}
break;
}
}
[Theory]
[InlineData(false, null)]
[InlineData(false, false)]
[InlineData(false, true)]
[InlineData(true, null)]
[InlineData(true, false)]
[InlineData(true, true)]
public void WriteAsync_MultipleContinuations_Throws(bool onCompleted, bool? continueOnCapturedContext)
{
Channel<int> c = CreateFullChannel();
if (c == null)
{
return;
}
ValueTask write = c.Writer.WriteAsync(42);
switch (continueOnCapturedContext)
{
case null:
if (onCompleted)
{
write.GetAwaiter().OnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => write.GetAwaiter().OnCompleted(() => { }));
}
else
{
write.GetAwaiter().UnsafeOnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => write.GetAwaiter().UnsafeOnCompleted(() => { }));
}
break;
default:
if (onCompleted)
{
write.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => write.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(() => { }));
}
else
{
write.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().UnsafeOnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => write.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().UnsafeOnCompleted(() => { }));
}
break;
}
}
public static IEnumerable<object[]> Reader_ContinuesOnCurrentContextIfDesired_MemberData() =>
from readOrWait in new[] { true, false }
from completeBeforeOnCompleted in new[] { true, false }
from flowExecutionContext in new[] { true, false }
from continueOnCapturedContext in new bool?[] { null, false, true }
from setNonDefaultTaskScheduler in new[] { true, false }
select new object[] { readOrWait, completeBeforeOnCompleted, flowExecutionContext, continueOnCapturedContext, setNonDefaultTaskScheduler };
[Theory]
[MemberData(nameof(Reader_ContinuesOnCurrentContextIfDesired_MemberData))]
public async Task Reader_ContinuesOnCurrentSynchronizationContextIfDesired(
bool readOrWait, bool completeBeforeOnCompleted, bool flowExecutionContext, bool? continueOnCapturedContext, bool setNonDefaultTaskScheduler)
{
if (AllowSynchronousContinuations)
{
return;
}
await Task.Factory.StartNew(async () =>
{
Assert.Null(SynchronizationContext.Current);
Channel<bool> c = CreateChannel<bool>();
ValueTask<bool> vt = readOrWait ?
c.Reader.ReadAsync() :
c.Reader.WaitToReadAsync();
var continuationRan = new TaskCompletionSource<bool>();
var asyncLocal = new AsyncLocal<int>();
bool schedulerWasFlowed = false;
bool executionContextWasFlowed = false;
Action continuation = () =>
{
schedulerWasFlowed = SynchronizationContext.Current is CustomSynchronizationContext;
executionContextWasFlowed = 42 == asyncLocal.Value;
continuationRan.SetResult(true);
};
if (completeBeforeOnCompleted)
{
Assert.False(vt.IsCompleted);
Assert.False(vt.IsCompletedSuccessfully);
c.Writer.TryWrite(true);
}
SynchronizationContext.SetSynchronizationContext(new CustomSynchronizationContext());
asyncLocal.Value = 42;
switch (continueOnCapturedContext)
{
case null:
if (flowExecutionContext)
{
vt.GetAwaiter().OnCompleted(continuation);
}
else
{
vt.GetAwaiter().UnsafeOnCompleted(continuation);
}
break;
default:
if (flowExecutionContext)
{
vt.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(continuation);
}
else
{
vt.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().UnsafeOnCompleted(continuation);
}
break;
}
asyncLocal.Value = 0;
SynchronizationContext.SetSynchronizationContext(null);
if (!completeBeforeOnCompleted)
{
Assert.False(vt.IsCompleted);
Assert.False(vt.IsCompletedSuccessfully);
c.Writer.TryWrite(true);
}
await continuationRan.Task;
Assert.True(vt.IsCompleted);
Assert.True(vt.IsCompletedSuccessfully);
Assert.Equal(continueOnCapturedContext != false, schedulerWasFlowed);
if (completeBeforeOnCompleted) // OnCompleted will simply queue using a mechanism that happens to flow
{
Assert.True(executionContextWasFlowed);
}
else
{
Assert.Equal(flowExecutionContext, executionContextWasFlowed);
}
}, CancellationToken.None, TaskCreationOptions.None, setNonDefaultTaskScheduler ? new CustomTaskScheduler() : TaskScheduler.Default);
}
public static IEnumerable<object[]> Reader_ContinuesOnCurrentSchedulerIfDesired_MemberData() =>
from readOrWait in new[] { true, false }
from completeBeforeOnCompleted in new[] { true, false }
from flowExecutionContext in new[] { true, false }
from continueOnCapturedContext in new bool?[] { null, false, true }
from setDefaultSyncContext in new[] { true, false }
select new object[] { readOrWait, completeBeforeOnCompleted, flowExecutionContext, continueOnCapturedContext, setDefaultSyncContext };
[Theory]
[MemberData(nameof(Reader_ContinuesOnCurrentSchedulerIfDesired_MemberData))]
public async Task Reader_ContinuesOnCurrentTaskSchedulerIfDesired(
bool readOrWait, bool completeBeforeOnCompleted, bool flowExecutionContext, bool? continueOnCapturedContext, bool setDefaultSyncContext)
{
if (AllowSynchronousContinuations)
{
return;
}
await Task.Run(async () =>
{
Assert.Null(SynchronizationContext.Current);
Channel<bool> c = CreateChannel<bool>();
ValueTask<bool> vt = readOrWait ?
c.Reader.ReadAsync() :
c.Reader.WaitToReadAsync();
var continuationRan = new TaskCompletionSource<bool>();
var asyncLocal = new AsyncLocal<int>();
bool schedulerWasFlowed = false;
bool executionContextWasFlowed = false;
Action continuation = () =>
{
schedulerWasFlowed = TaskScheduler.Current is CustomTaskScheduler;
executionContextWasFlowed = 42 == asyncLocal.Value;
continuationRan.SetResult(true);
};
if (completeBeforeOnCompleted)
{
Assert.False(vt.IsCompleted);
Assert.False(vt.IsCompletedSuccessfully);
c.Writer.TryWrite(true);
}
await Task.Factory.StartNew(() =>
{
if (setDefaultSyncContext)
{
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
}
Assert.IsType<CustomTaskScheduler>(TaskScheduler.Current);
asyncLocal.Value = 42;
switch (continueOnCapturedContext)
{
case null:
if (flowExecutionContext)
{
vt.GetAwaiter().OnCompleted(continuation);
}
else
{
vt.GetAwaiter().UnsafeOnCompleted(continuation);
}
break;
default:
if (flowExecutionContext)
{
vt.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(continuation);
}
else
{
vt.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().UnsafeOnCompleted(continuation);
}
break;
}
asyncLocal.Value = 0;
}, CancellationToken.None, TaskCreationOptions.None, new CustomTaskScheduler());
if (!completeBeforeOnCompleted)
{
Assert.False(vt.IsCompleted);
Assert.False(vt.IsCompletedSuccessfully);
c.Writer.TryWrite(true);
}
await continuationRan.Task;
Assert.True(vt.IsCompleted);
Assert.True(vt.IsCompletedSuccessfully);
Assert.Equal(continueOnCapturedContext != false, schedulerWasFlowed);
if (completeBeforeOnCompleted) // OnCompleted will simply queue using a mechanism that happens to flow
{
Assert.True(executionContextWasFlowed);
}
else
{
Assert.Equal(flowExecutionContext, executionContextWasFlowed);
}
});
}
[Fact]
public void ValueTask_GetResultWhenNotCompleted_Throws()
{
ValueTaskAwaiter<int> readVt = CreateChannel().Reader.ReadAsync().GetAwaiter();
Assert.Throws<InvalidOperationException>(() => readVt.GetResult());
ValueTaskAwaiter<bool> waitReadVt = CreateChannel().Reader.WaitToReadAsync().GetAwaiter();
Assert.Throws<InvalidOperationException>(() => waitReadVt.GetResult());
if (CreateFullChannel() != null)
{
ValueTaskAwaiter writeVt = CreateFullChannel().Writer.WriteAsync(42).GetAwaiter();
Assert.Throws<InvalidOperationException>(() => writeVt.GetResult());
ValueTaskAwaiter<bool> waitWriteVt = CreateFullChannel().Writer.WaitToWriteAsync().GetAwaiter();
Assert.Throws<InvalidOperationException>(() => waitWriteVt.GetResult());
}
}
[Fact]
public void ValueTask_MultipleContinuations_Throws()
{
ValueTaskAwaiter<int> readVt = CreateChannel().Reader.ReadAsync().GetAwaiter();
readVt.OnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => readVt.OnCompleted(() => { }));
ValueTaskAwaiter<bool> waitReadVt = CreateChannel().Reader.WaitToReadAsync().GetAwaiter();
waitReadVt.OnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => waitReadVt.OnCompleted(() => { }));
if (CreateFullChannel() != null)
{
ValueTaskAwaiter writeVt = CreateFullChannel().Writer.WriteAsync(42).GetAwaiter();
writeVt.OnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => writeVt.OnCompleted(() => { }));
ValueTaskAwaiter<bool> waitWriteVt = CreateFullChannel().Writer.WaitToWriteAsync().GetAwaiter();
waitWriteVt.OnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => waitWriteVt.OnCompleted(() => { }));
}
}
private sealed class CustomSynchronizationContext : SynchronizationContext
{
public override void Post(SendOrPostCallback d, object state)
{
ThreadPool.QueueUserWorkItem(delegate
{
SetSynchronizationContext(this);
try
{
d(state);
}
finally
{
SetSynchronizationContext(null);
}
}, null);
}
}
private sealed class CustomTaskScheduler : TaskScheduler
{
protected override void QueueTask(Task task) => ThreadPool.QueueUserWorkItem(_ => TryExecuteTask(task));
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) => false;
protected override IEnumerable<Task> GetScheduledTasks() => null;
}
}
}
| |
//
// Klak - Utilities for creative coding with Unity
//
// Copyright (C) 2016 Keijiro Takahashi
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using UnityEngine;
using UnityEngine.Events;
using UnityEditor;
using UnityEditor.Events;
using System.Reflection;
using System;
using Graphs = UnityEditor.Graphs;
namespace Klak.Wiring.Patcher
{
public static class ConnectionTools
{
#region Public functions
// Determine data type of a given event.
public static Type GetEventDataType(Type eventType)
{
if (typeof(UnityEvent<float >).IsAssignableFrom(eventType)) return typeof(float);
if (typeof(UnityEvent<Vector3 >).IsAssignableFrom(eventType)) return typeof(Vector3);
if (typeof(UnityEvent<Quaternion>).IsAssignableFrom(eventType)) return typeof(Quaternion);
if (typeof(UnityEvent<Color >).IsAssignableFrom(eventType)) return typeof(Color);
return null;
}
// Create a connection between two slots.
public static bool ConnectSlots(Graphs.Slot fromSlot, Graphs.Slot toSlot)
{
var nodeTo = ((Node)toSlot.node).runtimeInstance;
var triggerEvent = GetEventOfOutputSlot(fromSlot);
var targetMethod = GetMethodOfInputSlot(toSlot);
// Determine the type of the target action.
var actionType = GetUnityActionToInvokeMethod(targetMethod);
if (actionType == null) return false; // invalid target method type
// Create an action that is bound to the target method.
var targetAction = Delegate.CreateDelegate(
actionType, nodeTo, targetMethod
);
if (triggerEvent is UnityEvent)
{
// The trigger event has no parameter.
// Add the action to the event with a default parameter.
if (actionType == typeof(UnityAction))
{
UnityEventTools.AddVoidPersistentListener(
triggerEvent, (UnityAction)targetAction
);
return true;
}
if (actionType == typeof(UnityAction<float>))
{
UnityEventTools.AddFloatPersistentListener(
triggerEvent, (UnityAction<float>)targetAction, 1.0f
);
return true;
}
}
else if (triggerEvent is UnityEvent<float>)
{
// The trigger event has a float parameter.
// Then the target method should have a float parameter too.
if (actionType == typeof(UnityAction<float>))
{
// Add the action to the event.
UnityEventTools.AddPersistentListener(
(UnityEvent<float>)triggerEvent,
(UnityAction<float>)targetAction
);
return true;
}
}
else if (triggerEvent is UnityEvent<Vector3>)
{
// The trigger event has a Vector3 parameter.
// Then the target method should have a Vector3 parameter too.
if (actionType == typeof(UnityAction<Vector3>))
{
// Add the action to the event.
UnityEventTools.AddPersistentListener(
(UnityEvent<Vector3>)triggerEvent,
(UnityAction<Vector3>)targetAction
);
return true;
}
}
else if (triggerEvent is UnityEvent<Quaternion>)
{
// The trigger event has a Quaternion parameter.
// Then the target method should have a Quaternion parameter too.
if (actionType == typeof(UnityAction<Quaternion>))
{
// Add the action to the event.
UnityEventTools.AddPersistentListener(
(UnityEvent<Quaternion>)triggerEvent,
(UnityAction<Quaternion>)targetAction
);
return true;
}
}
else if (triggerEvent is UnityEvent<Color>)
{
// The trigger event has a color parameter.
// Then the target method should have a color parameter too.
if (actionType == typeof(UnityAction<Color>))
{
// Add the action to the event.
UnityEventTools.AddPersistentListener(
(UnityEvent<Color>)triggerEvent,
(UnityAction<Color>)targetAction
);
return true;
}
}
return false; // trigger-target mismatch
}
// Disconnect given two slots.
public static void DisconnectSlots(Graphs.Slot fromSlot, Graphs.Slot toSlot)
{
var nodeTo = ((Node)toSlot.node).runtimeInstance;
var triggerEvent = GetEventOfOutputSlot(fromSlot);
var targetMethod = GetMethodOfInputSlot(toSlot);
var methodName = targetMethod.Name;
var eventCount = triggerEvent.GetPersistentEventCount();
for (var i = 0; i < eventCount; i++)
{
if (nodeTo == triggerEvent.GetPersistentTarget(i) &&
methodName == triggerEvent.GetPersistentMethodName(i))
{
UnityEventTools.RemovePersistentListener(triggerEvent, i);
break;
}
}
}
#endregion
#region Private functions
// Returns an event instance that is bound to a given output slot.
static UnityEventBase GetEventOfOutputSlot(Graphs.Slot slot)
{
var node = ((Node)slot.node).runtimeInstance;
var flags = BindingFlags.Instance | BindingFlags.NonPublic;
var field = node.GetType().GetField(slot.name, flags);
return (UnityEventBase)field.GetValue(node);
}
// Returns a method that is bound to a given input slot.
static MethodInfo GetMethodOfInputSlot(Graphs.Slot slot)
{
var node = ((Node)slot.node).runtimeInstance;
return node.GetType().GetMethod(slot.name);
}
// Returns a UnityAction type that can be used to call the given method.
static Type GetUnityActionToInvokeMethod(MethodInfo method)
{
var args = method.GetParameters();
// The method has no parameter: Use UnityAction.
if (args.Length == 0) return typeof(UnityAction);
// Only refer to the first parameter.
var paramType = args[0].ParameterType;
// Returns one of the corrensponding action types.
if (paramType == typeof(float )) return typeof(UnityAction<float >);
if (paramType == typeof(Vector3 )) return typeof(UnityAction<Vector3 >);
if (paramType == typeof(Quaternion)) return typeof(UnityAction<Quaternion>);
if (paramType == typeof(Color )) return typeof(UnityAction<Color >);
// No one matches the method type.
return null;
}
#endregion
}
}
| |
// Created by Paul Gonzalez Becerra
using System;
using Saserdote.Animation;
using Saserdote.DataSystems;
using Saserdote.Mathematics;
using Saserdote.Mathematics.Collision;
using Tao.OpenGl;
namespace Saserdote.Graphics
{
public abstract class BaseMesh:IDisposable,ICloneable<BaseMesh>
{
#region --- Field Variables ---
// Variables
protected Matrix pMatrix;
private Matrix tempMatrix;
protected Point3f[] vertices;
protected TexCoord[] texcoords;
protected Color[] colors;
protected ushort[] faces;
protected Bone[] bones;
protected Texture pTexture;
public bool bRenderOutline;
public string name;
public float outlineWidth;
public bool bVisible;
public static float globalOutlineWidth= 1f;
#endregion // Field Variables
#region --- Constructors ---
protected BaseMesh()
{
pMatrix= Matrix.IDENTITY;
tempMatrix= Matrix.IDENTITY;
vertices= new Point3f[0];
texcoords= new TexCoord[0];
colors= new Color[0];
faces= new ushort[0];
bones= new Bone[0];
pTexture= Texture.NULL;
bRenderOutline= false;
outlineWidth= BaseMesh.globalOutlineWidth;
name= "UMk_010010101";
bVisible= true;
}
internal BaseMesh(Matrix m, Bone[] pmBones)
{
tempMatrix= m;
bVisible= true;
bones= pmBones;
outlineWidth= BaseMesh.globalOutlineWidth;
}
#endregion // Constructors
#region --- Properties ---
// Gets and sets the position of the mesh
public Point3f position
{
get { return pMatrix.translation; }
set { setPosition(value); }
}
// Gets and sets the matrix of the mesh
public Matrix matrix
{
get { return pMatrix; }
set { applyMatrix(value); }
}
// Gets and sets the texture of the mesh
public virtual Texture texture
{
get { return pTexture; }
set { pTexture= value; }
}
#endregion // Properties
#region --- Methods ---
// Initiates the mesh
protected abstract void init();
// Draws the mesh
public abstract void render();
// Gets the vertices of the mesh
public Point3f[] getVertices()
{
return vertices;
}
// Gets the texture coordinates of the mesh
public TexCoord[] getTexCoords()
{
return texcoords;
}
// Gets the colors of the mesh
public Color[] getColors()
{
return colors;
}
// Gets the indices of the mesh
public ushort[] getIndices()
{
return faces;
}
// Gets the bones of the mesh
public Bone[] getBones()
{
return bones;
}
// Sets the bones of the mesh
public void setBones(params Bone[] pmBones)
{
bones= pmBones;
}
// Applies the matrix to all the vertices
public void applyMatrix(Matrix m)
{
// Variables
Matrix n= pMatrix.inverse();
for(int i= 0; i< vertices.Length; i++)
vertices[i]= (n*vertices[i]);
pMatrix= m;
for(int i= 0; i< vertices.Length; i++)
vertices[i]= (pMatrix*vertices[i]);
}
// Sets the position of the mesh
private void setPosition(Point3f pos)
{
// Variables
Matrix m= pMatrix;
m.translation= pos;
applyMatrix(m);
}
// Rotates the mesh with the given axis and radians
public void rotate(Vector3 axis, float radians)
{
tempMatrix.resetToIdentity();
tempMatrix.rotate(axis, radians);
tempMatrix*= pMatrix;
matrix= tempMatrix;
}
// Rotates the mesh by the x axis
public void rotateXAxis(float radians)
{
tempMatrix.resetToIdentity();
tempMatrix.rotateXAxis(radians);
tempMatrix*= pMatrix;
matrix= tempMatrix;
}
// Rotates the mesh by the y axis
public void rotateYAxis(float radians)
{
tempMatrix.resetToIdentity();
tempMatrix.rotateYAxis(radians);
tempMatrix*= pMatrix;
matrix= tempMatrix;
}
// Rotates the mesh by the z axis
public void rotateZAxis(float radians)
{
tempMatrix.resetToIdentity();
tempMatrix.rotateZAxis(radians);
tempMatrix*= pMatrix;
matrix= tempMatrix;
}
// Applies the color to all the diffuse colors
public virtual void applyColor(Color c)
{
for(int i= 0; i< colors.Length; i++)
colors[i]= c;
}
// Adds a vertex to the mesh
public void addVertex(Point3f pt)
{
// Variables
Point3f[] temp= new Point3f[vertices.Length+1];
for(int i= 0; i< vertices.Length; i++)
temp[i]= vertices[i];
temp[vertices.Length]= pt;
vertices= temp;
}
public void addVertex(float x, float y, float z) { addVertex(new Point3f(x, y, z)); }
// Adds a texcoord to the mesh
public void addTexCoord(TexCoord txcd)
{
// Variables
TexCoord[] temp= new TexCoord[texcoords.Length+1];
for(int i= 0; i< texcoords.Length; i++)
temp[i]= texcoords[i];
temp[texcoords.Length]= txcd;
texcoords= temp;
}
// Adds a color to the mesh
public void addColor(Color c)
{
// Variables
Color[] temp= new Color[colors.Length+1];
for(int i= 0; i< colors.Length; i++)
temp[i]= colors[i];
temp[colors.Length]= c;
colors= temp;
}
// Adds an index to the mesh
public void addIndex(ushort index)
{
// Variables
ushort[] temp= new ushort[faces.Length+1];
for(int i= 0; i< faces.Length; i++)
temp[i]= faces[i];
temp[faces.Length]= index;
faces= temp;
}
// Finds if the two meshes are equal to each other
public bool equals(BaseMesh mesh)
{
if((object)mesh== null)
return false;
if(vertices.Length!= mesh.vertices.Length)
return false;
if(texcoords.Length!= mesh.texcoords.Length)
return false;
if(colors.Length!= mesh.colors.Length)
return false;
if(faces.Length!= mesh.faces.Length)
return false;
// Variables
int i= 0;
for(i= 0; i< vertices.Length; i++)
{
if(vertices[i]!= mesh.vertices[i])
return false;
}
for(i= 0; i< texcoords.Length; i++)
{
if(texcoords[i]!= mesh.texcoords[i])
return false;
}
for(i= 0; i< colors.Length; i++)
{
if(colors[i]!= mesh.colors[i])
return false;
}
for(i= 0; i< faces.Length; i++)
{
if(faces[i]!= mesh.faces[i])
return false;
}
return true;
}
// Draws an outline around the mesh
public void renderOutline()
{
if(!bVisible)
return;
Gl.glLineWidth(outlineWidth);
Gl.glPolygonMode(Gl.GL_BACK, Gl.GL_LINE);
Gl.glCullFace(Gl.GL_FRONT);
Gl.glDepthFunc(Gl.GL_LEQUAL);
Gl.glColor3f(0f, 0f, 0f);
Gl.glBegin(Gl.GL_TRIANGLES);
for(int i= 0; i< faces.Length; i++)
{
Gl.glVertex3f(vertices[(int)faces[i]].x, vertices[(int)faces[i]].y, vertices[(int)faces[i]].z);
}
Gl.glEnd();
Gl.glDepthFunc(Gl.GL_LESS);
Gl.glCullFace(Gl.GL_BACK);
Gl.glPolygonMode(Gl.GL_BACK, Gl.GL_FILL);
Gl.glLineWidth(outlineWidth);
}
#endregion // Methods
#region --- Inherited Methods ---
// Clones the base mesh
public virtual BaseMesh clone()
{
// Variables
Point3f[] vtemp= new Point3f[vertices.Length];
TexCoord[] ttemp= new TexCoord[texcoords.Length];
Color[] ctemp= new Color[colors.Length];
ushort[] ftemp= new ushort[faces.Length];
Bone[] btemp= new Bone[bones.Length];
for(int i= 0; i< vtemp.Length; i++)
vtemp[i]= vertices[i];
for(int i= 0; i< ttemp.Length; i++)
ttemp[i]= texcoords[i];
for(int i= 0; i< ctemp.Length; i++)
ctemp[i]= colors[i];
for(int i= 0; i< ftemp.Length; i++)
ftemp[i]= faces[i];
for(int i= 0; i< btemp.Length; i++)
btemp[i]= bones[i];
if(this is LMesh)
return new LMesh(vtemp, ttemp, ctemp, ftemp, pMatrix, pTexture, name, btemp, bRenderOutline);
if(this is TMesh)
return new TMesh(vtemp, ttemp, ctemp, ftemp, pMatrix, pTexture, name, btemp, bRenderOutline);
if(this is QMesh)
return new QMesh(vtemp, ttemp, ctemp, ftemp, pMatrix, pTexture, name, btemp, bRenderOutline);
return null;
}
// Disposes of the mesh
public abstract void Dispose();
// Finds if the given object is equal to the mesh
public override bool Equals(object obj)
{
if(obj== null)
return false;
if(obj is BaseMesh)
return equals((BaseMesh)obj);
return false;
}
// Gets the hash code
public override int GetHashCode()
{
// Variables
int hashcode= 0;
for(int i= 0; i< vertices.Length; i++)
hashcode+= vertices.GetHashCode();
return hashcode;
}
// Prints out all the contents of the mesh
public override string ToString()
{
return "Mesh: "+name;
}
#endregion // Inherited Methods
}
}
// End of File
| |
/*
* 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;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Apache.Geode.Client;
using Apache.Geode.Client.Internal;
namespace PdxTests
{
public enum pdxEnumTest { pdx1, pdx2, pdx3};
public class Address : IPdxSerializable
{
int _aptNumber;
string _street;
string _city;
public Address()
{ }
public override string ToString()
{
return _aptNumber + " :" + _street + " : "+ _city;
}
public Address(int aptN, string street, string city)
{
_aptNumber = aptN;
_street = street;
_city = city;
}
public override bool Equals(object obj)
{
Console.WriteLine("in addredd equal");
if (obj == null)
return false;
Address other = obj as Address;
if (other == null)
return false;
Console.WriteLine("in addredd equal2 " + this.ToString() + " : : " + other.ToString());
if (_aptNumber == other._aptNumber
&& _street == other._street
&& _city == other._city)
return true;
return false;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
#region IPdxSerializable Members
public void FromData(IPdxReader reader)
{
_aptNumber = reader.ReadInt("_aptNumber");
_street = reader.ReadString("_street");
_city = reader.ReadString("_city");
}
public void ToData(IPdxWriter writer)
{
writer.WriteInt("_aptNumber", _aptNumber);
writer.WriteString("_street", _street);
writer.WriteString("_city", _city);
}
#endregion
}
[Serializable]
public class PdxType : IPdxSerializable
{
char m_char;
bool m_bool;
sbyte m_byte;
sbyte m_sbyte;
short m_int16;
short m_uint16;
Int32 m_int32;
Int32 m_uint32;
long m_long;
Int64 m_ulong;
float m_float;
double m_double;
string m_string;
bool[] m_boolArray;
byte[] m_byteArray;
byte[] m_sbyteArray;
char[] m_charArray;
DateTime m_dateTime;
Int16[] m_int16Array;
Int16[] m_uint16Array;
Int32[] m_int32Array;
Int32[] m_uint32Array;
long[] m_longArray;
Int64[] m_ulongArray;
float[] m_floatArray;
double[] m_doubleArray;
byte[][] m_byteByteArray;
string[] m_stringArray;
List<object> m_arraylist = new List<object>();
IDictionary<object, object> m_map = new Dictionary<object, object>();
Hashtable m_hashtable = new Hashtable();
ArrayList m_vector = new ArrayList();
CacheableHashSet m_chs = CacheableHashSet.Create();
CacheableLinkedHashSet m_clhs = CacheableLinkedHashSet.Create();
byte[] m_byte252 = new byte[252];
byte[] m_byte253 = new byte[253];
byte[] m_byte65535 = new byte[65535];
byte[] m_byte65536 = new byte[65536];
pdxEnumTest m_pdxEnum = pdxEnumTest.pdx2;
Address[] m_address;
List<object> m_objectArray = new List<object>();
public void Init()
{
m_char = 'C';
m_bool = true;
m_byte = 0x74;
m_sbyte = 0x67;
m_int16 = 0xab;
m_uint16 = 0x2dd5;
m_int32 = 0x2345abdc;
m_uint32 = 0x2a65c434;
m_long = 324897980;
m_ulong = 238749898;
m_float = 23324.324f;
m_double = 3243298498d;
m_string = "gfestring";
m_boolArray = new bool[] { true, false, true };
m_byteArray = new byte[] { 0x34, 0x64 };
m_sbyteArray = new byte[] { 0x34, 0x64 };
m_charArray = new char[] { 'c', 'v' };
DateTime n = new DateTime((62135596800000/*epoch*/ + 1310447869154 ) * 10000, DateTimeKind.Utc);
m_dateTime = n.ToLocalTime();
Console.WriteLine(m_dateTime.Ticks);
m_int16Array = new short[] { 0x2332, 0x4545 };
m_uint16Array = new short[] { 0x3243, 0x3232 };
m_int32Array = new int[] { 23, 676868, 34343, 2323 };
m_uint32Array = new int[] { 435, 234324, 324324, 23432432 };
m_longArray = new long[] { 324324L, 23434545L };
m_ulongArray = new Int64[] { 3245435, 3425435 };
m_floatArray = new float[] { 232.565f, 2343254.67f };
m_doubleArray = new double[] { 23423432d, 4324235435d };
m_byteByteArray = new byte[][]{new byte[] {0x23},
new byte[]{0x34, 0x55}
};
m_stringArray = new string[] { "one", "two" };
m_arraylist = new List<object>();
m_arraylist.Add(1);
m_arraylist.Add(2);
m_map = new Dictionary<object, object>();
m_map.Add(1, 1);
m_map.Add(2, 2);
m_hashtable = new Hashtable();
m_hashtable.Add(1, "1111111111111111");
m_hashtable.Add(2, "2222222222221111111111111111");
m_vector = new ArrayList();
m_vector.Add(1);
m_vector.Add(2);
m_vector.Add(3);
m_chs.Add(1);
m_clhs.Add(1);
m_clhs.Add(2);
m_pdxEnum = pdxEnumTest.pdx2;
m_address = new Address[10];
for (int i = 0; i < 10; i++)
{
m_address[i] = new Address(i + 1, "street" + i.ToString(), "city" + i.ToString());
}
m_objectArray = new List<object>();
for (int i = 0; i < 10; i++)
{
m_objectArray.Add(new Address(i + 1, "street" + i.ToString(), "city" + i.ToString()));
}
}
public PdxType()
{
Init();
}
public static IPdxSerializable CreateDeserializable()
{
return new PdxType();
}
#region IPdxSerializable Members
public static byte[][] compareByteByteArray(byte[][] baa, byte[][] baa2)
{
if (baa.Length == baa2.Length)
{
int i = 0;
while (i < baa.Length)
{
compareByteArray(baa[i], baa2[i]);
i++;
}
if (i == baa2.Length)
return baa2;
}
throw new IllegalStateException("Not got expected value for type: " + baa2.GetType().ToString());
}
bool compareBool(bool b, bool b2)
{
if (b == b2)
return b;
throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString());
}
bool[] compareBoolArray(bool[] a, bool[] a2)
{
if (a.Length == a2.Length)
{
int i = 0;
while (i < a.Length)
{
if (a[i] != a2[i])
break;
else
i++;
}
if (i == a2.Length)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString());
}
byte compareByte(byte b, byte b2)
{
if (b == b2)
return b;
throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString());
}
public static byte[] compareByteArray(byte[] a, byte[] a2)
{
Console.WriteLine("Compare byte array " + a.Length + " ; " + a2.Length);
if (a.Length == a2.Length)
{
int i = 0;
while (i < a.Length)
{
Console.WriteLine("Compare byte array " + a[i] + " : " + a2[i]);
if (a[i] != a2[i])
break;
else
i++;
}
if (i == a2.Length)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString());
}
char[] compareCharArray(char[] a, char[] a2)
{
if (a.Length == a2.Length)
{
int i = 0;
while (i < a.Length)
{
if (a[i] != a2[i])
break;
else
i++;
}
if (i == a2.Length)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString());
}
public static List<object> compareCompareCollection(List<object> a, List<object> a2)
{
if (a.Count == a2.Count)
{
int i = 0;
while (i < a.Count)
{
if (!a[i].Equals(a2[i]))
break;
else
i++;
}
if (i == a2.Count)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString());
}
/*
public static LinkedList<String> compareCompareCollection(LinkedList<String> a, LinkedList<String> a2)
{
if (a.Count == a2.Count)
{
int i = 0;
while (i < a.Count)
{
if (!a[i].Equals(a2[i]))
break;
else
i++;
}
if (i == a2.Count)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString());
}
*/
public static DateTime compareData(DateTime b, DateTime b2)
{
Console.WriteLine("date " + b.Ticks + " : " + b2.Ticks);
//TODO:
// return b;
if ((b.Ticks / 10000L) == (b2.Ticks / 10000L))
return b;
throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString());
}
Double compareDouble(Double b, Double b2)
{
if (b == b2)
return b;
throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString());
}
double[] compareDoubleArray(double[] a, double[] a2)
{
if (a.Length == a2.Length)
{
int i = 0;
while (i < a.Length)
{
if (a[i] != a2[i])
break;
else
i++;
}
if (i == a2.Length)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString());
}
float compareFloat(float b, float b2)
{
if (b == b2)
return b;
throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString());
}
float[] compareFloatArray(float[] a, float[] a2)
{
if (a.Length == a2.Length)
{
int i = 0;
while (i < a.Length)
{
if (a[i] != a2[i])
break;
else
i++;
}
if (i == a2.Length)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString());
}
Int16 compareInt16(Int16 b, Int16 b2)
{
if (b == b2)
return b;
throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString());
}
Int32 compareInt32(Int32 b, Int32 b2)
{
if (b == b2)
return b;
throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString());
}
Int64 compareInt64(Int64 b, Int64 b2)
{
if (b == b2)
return b;
throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString());
}
Int32[] compareIntArray(Int32[] a, Int32[] a2)
{
if (a.Length == a2.Length)
{
int i = 0;
while (i < a.Length)
{
if (a[i] != a2[i])
break;
else
i++;
}
if (i == a2.Length)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString());
}
long[] compareLongArray(long[] a, long[] a2)
{
if (a.Length == a2.Length)
{
int i = 0;
while (i < a.Length)
{
if (a[i] != a2[i])
break;
else
i++;
}
if (i == a2.Length)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString());
}
Int16[] compareSHortArray(Int16[] a, Int16[] a2)
{
if (a.Length == a2.Length)
{
int i = 0;
while (i < a.Length)
{
if (a[i] != a2[i])
break;
else
i++;
}
if (i == a2.Length)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString());
}
sbyte compareSByte(sbyte b, sbyte b2)
{
if (b == b2)
return b;
throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString());
}
sbyte[] compareSByteArray(sbyte[] a, sbyte[] a2)
{
if (a.Length == a2.Length)
{
int i = 0;
while (i < a.Length)
{
if (a[i] != a2[i])
break;
else
i++;
}
if (i == a2.Length)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString());
}
string[] compareStringArray(string[] a, string[] a2)
{
if (a.Length == a2.Length)
{
int i = 0;
while (i < a.Length)
{
if (a[i] != a2[i])
break;
else
i++;
}
if (i == a2.Length)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString());
}
UInt16 compareUInt16(UInt16 b, UInt16 b2)
{
if (b == b2)
return b;
throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString());
}
UInt32 compareUInt32(UInt32 b, UInt32 b2)
{
if (b == b2)
return b;
throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString());
}
UInt64 compareUint64(UInt64 b, UInt64 b2)
{
if (b == b2)
return b;
throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString());
}
UInt32[] compareUnsignedIntArray(UInt32[] a, UInt32[] a2)
{
if (a.Length == a2.Length)
{
int i = 0;
while (i < a.Length)
{
if (a[i] != a2[i])
break;
else
i++;
}
if (i == a2.Length)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString());
}
UInt64[] compareUnsignedLongArray(UInt64[] a, UInt64[] a2)
{
if (a.Length == a2.Length)
{
int i = 0;
while (i < a.Length)
{
if (a[i] != a2[i])
break;
else
i++;
}
if (i == a2.Length)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString());
}
UInt16[] compareUnsignedShortArray(UInt16[] a, UInt16[] a2)
{
if (a.Length == a2.Length)
{
int i = 0;
while (i < a.Length)
{
if (a[i] != a2[i])
break;
else
i++;
}
if (i == a2.Length)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString());
}
public static T[] GenericCompare<T>(T[] a, T[] a2)
{
if (a.Length == a2.Length)
{
int i = 0;
while (i < a.Length)
{
if (!a[i].Equals(a2[i]))
break;
else
i++;
}
if (i == a2.Length)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString());
}
public static T GenericValCompare<T>(T b, T b2)
{
if (b.Equals(b2))
return b;
throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString() + " : values " + b.ToString() + ": " + b2.ToString());
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
PdxType other = obj as PdxType;
if (other == null)
return false;
if (other == this)
return true;
compareByteByteArray(other.m_byteByteArray, m_byteByteArray);
GenericValCompare(other.m_char, m_char);
GenericValCompare(other.m_bool, m_bool);
GenericCompare(other.m_boolArray, m_boolArray);
GenericValCompare(other.m_byte, m_byte);
GenericCompare(other.m_byteArray, m_byteArray);
GenericCompare(other.m_charArray, m_charArray);
compareCompareCollection(other.m_arraylist, m_arraylist);
if (other.m_map.Count != m_map.Count)
throw new IllegalStateException("Not got expected value for type: " + m_map.GetType().ToString());
if (other.m_hashtable.Count != m_hashtable.Count)
throw new IllegalStateException("Not got expected value for type: " + m_hashtable.GetType().ToString());
if (other.m_vector.Count != m_vector.Count)
throw new IllegalStateException("Not got expected value for type: " + m_vector.GetType().ToString());
if (other.m_chs.Count != m_chs.Count)
throw new IllegalStateException("Not got expected value for type: " + m_chs.GetType().ToString());
if (other.m_clhs.Count != m_clhs.Count)
throw new IllegalStateException("Not got expected value for type: " + m_clhs.GetType().ToString());
GenericValCompare(other.m_string, m_string);
compareData(other.m_dateTime, m_dateTime);
GenericValCompare(other.m_double, m_double);
GenericCompare(other.m_doubleArray, m_doubleArray);
GenericValCompare(other.m_float, m_float);
GenericCompare(other.m_floatArray, m_floatArray);
GenericValCompare(other.m_int16, m_int16);
GenericValCompare(other.m_int32, m_int32);
GenericValCompare(other.m_long, m_long);
GenericCompare(other.m_int32Array, m_int32Array);
GenericCompare(other.m_longArray, m_longArray);
GenericCompare(other.m_int16Array, m_int16Array);
GenericValCompare(other.m_sbyte, m_sbyte);
GenericCompare(other.m_sbyteArray, m_sbyteArray);
GenericCompare(other.m_stringArray, m_stringArray);
GenericValCompare(other.m_uint16, m_uint16);
GenericValCompare(other.m_uint32, m_uint32);
GenericValCompare(other.m_ulong, m_ulong);
GenericCompare(other.m_uint32Array, m_uint32Array);
GenericCompare(other.m_ulongArray, m_ulongArray);
GenericCompare(other.m_uint16Array, m_uint16Array);
if (m_byte252.Length != 252 && other.m_byte252.Length != 252)
throw new Exception("Array len 252 not found");
if (m_byte253.Length != 253 && other.m_byte253.Length != 253)
throw new Exception("Array len 253 not found");
if (m_byte65535.Length != 65535 && other.m_byte65535.Length != 65535)
throw new Exception("Array len 65535 not found");
if (m_byte65536.Length != 65536 && other.m_byte65536.Length != 65536)
throw new Exception("Array len 65536 not found");
if(m_pdxEnum != other.m_pdxEnum)
throw new Exception("pdx enum is not equal");
{
for (int i = 0; i < m_address.Length; i++)
{
if (!m_address[i].Equals(other.m_address[i]))
throw new Exception("Address array not mateched " + i);
}
}
for (int i = 0; i < m_objectArray.Count; i++)
{
if (!m_objectArray[i].Equals(other.m_objectArray[i]))
return false;
}
return true;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public void FromData(IPdxReader reader)
{
//byte[][] baa = reader.ReadArrayOfByteArrays("m_byteByteArray");
//m_byteByteArray = compareByteByteArray(baa, m_byteByteArray);
//bool bl = reader.ReadBoolean("m_bool");
//m_bool = compareBool(bl, m_bool);
//m_boolArray = compareBoolArray(reader.ReadBooleanArray("m_boolArray"), m_boolArray);
//m_byte = compareByte(reader.ReadByte("m_byte"), m_byte);
//m_byteArray = compareByteArray(reader.ReadByteArray("m_byteArray"), m_byteArray);
//m_charArray = compareCharArray(reader.ReadCharArray("m_charArray"), m_charArray);
//List<object> tmpl = new List<object>();
//reader.ReadCollection("m_list", tmpl);
//m_list = compareCompareCollection(tmpl, m_list);
//m_dateTime = compareData(reader.ReadDate("m_dateTime"), m_dateTime);
//m_double = compareDouble(reader.ReadDouble("m_double"), m_double);
//m_doubleArray = compareDoubleArray(reader.ReadDoubleArray("m_doubleArray"), m_doubleArray);
//m_float = compareFloat(reader.ReadFloat("m_float"), m_float);
//m_floatArray = compareFloatArray(reader.ReadFloatArray("m_floatArray"), m_floatArray);
//m_int16 = compareInt16(reader.ReadInt16("m_int16"), m_int16);
//m_int32 = compareInt32(reader.ReadInt32("m_int32"), m_int32);
//m_long = compareInt64(reader.ReadInt64("m_long"), m_long);
//m_int32Array = compareIntArray(reader.ReadIntArray("m_int32Array"), m_int32Array);
//m_longArray = compareLongArray(reader.ReadLongArray("m_longArray"), m_longArray);
//m_int16Array = compareSHortArray(reader.ReadShortArray("m_int16Array"), m_int16Array);
//m_sbyte = compareSByte(reader.ReadSByte("m_sbyte"), m_sbyte);
//m_sbyteArray = compareSByteArray(reader.ReadSByteArray("m_sbyteArray"), m_sbyteArray);
//m_stringArray = compareStringArray(reader.ReadStringArray("m_stringArray"), m_stringArray);
//m_uint16 = compareUInt16(reader.ReadUInt16("m_uint16"), m_uint16);
//m_uint32 = compareUInt32(reader.ReadUInt32("m_uint32") , m_uint32);
//m_ulong = compareUint64(reader.ReadUInt64("m_ulong"), m_ulong);
//m_uint32Array = compareUnsignedIntArray(reader.ReadUnsignedIntArray("m_uint32Array"), m_uint32Array);
//m_ulongArray = compareUnsignedLongArray(reader.ReadUnsignedLongArray("m_ulongArray"), m_ulongArray);
//m_uint16Array = compareUnsignedShortArray(reader.ReadUnsignedShortArray("m_uint16Array"), m_uint16Array);
byte[][] baa = reader.ReadArrayOfByteArrays("m_byteByteArray");
m_byteByteArray = compareByteByteArray(baa, m_byteByteArray);
m_char = GenericValCompare(reader.ReadChar("m_char"), m_char);
bool bl = reader.ReadBoolean("m_bool");
m_bool = GenericValCompare(bl, m_bool);
m_boolArray = GenericCompare(reader.ReadBooleanArray("m_boolArray"), m_boolArray);
m_byte = GenericValCompare(reader.ReadByte("m_byte"), m_byte);
m_byteArray = GenericCompare(reader.ReadByteArray("m_byteArray"), m_byteArray);
m_charArray = GenericCompare(reader.ReadCharArray("m_charArray"), m_charArray);
List<object> tmpl = new List<object>();
tmpl = (List<object>)reader.ReadObject("m_arraylist");
m_arraylist = compareCompareCollection(tmpl, m_arraylist);
IDictionary<object, object> tmpM = (IDictionary<object, object>)reader.ReadObject("m_map");
if (tmpM.Count != m_map.Count)
throw new IllegalStateException("Not got expected value for type: " + m_map.GetType().ToString());
Hashtable tmpH = (Hashtable)reader.ReadObject("m_hashtable");
if (tmpH.Count != m_hashtable.Count)
throw new IllegalStateException("Not got expected value for type: " + m_hashtable.GetType().ToString());
ArrayList arrAl = (ArrayList)reader.ReadObject("m_vector");
if (arrAl.Count != m_vector.Count)
throw new IllegalStateException("Not got expected value for type: " + m_vector.GetType().ToString());
CacheableHashSet rmpChs = (CacheableHashSet)reader.ReadObject("m_chs");
if (rmpChs.Count != m_chs.Count)
throw new IllegalStateException("Not got expected value for type: " + m_chs.GetType().ToString());
CacheableLinkedHashSet rmpClhs = (CacheableLinkedHashSet)reader.ReadObject("m_clhs");
if (rmpClhs.Count != m_clhs.Count)
throw new IllegalStateException("Not got expected value for type: " + m_clhs.GetType().ToString());
m_string = GenericValCompare(reader.ReadString("m_string"), m_string);
m_dateTime = compareData(reader.ReadDate("m_dateTime"), m_dateTime);
m_double = GenericValCompare(reader.ReadDouble("m_double"), m_double);
m_doubleArray = GenericCompare(reader.ReadDoubleArray("m_doubleArray"), m_doubleArray);
m_float = GenericValCompare(reader.ReadFloat("m_float"), m_float);
m_floatArray = GenericCompare(reader.ReadFloatArray("m_floatArray"), m_floatArray);
m_int16 = GenericValCompare(reader.ReadShort("m_int16"), m_int16);
m_int32 = GenericValCompare(reader.ReadInt("m_int32"), m_int32);
m_long = GenericValCompare(reader.ReadLong("m_long"), m_long);
m_int32Array = GenericCompare(reader.ReadIntArray("m_int32Array"), m_int32Array);
m_longArray = GenericCompare(reader.ReadLongArray("m_longArray"), m_longArray);
m_int16Array = GenericCompare(reader.ReadShortArray("m_int16Array"), m_int16Array);
m_sbyte = GenericValCompare(reader.ReadByte("m_sbyte"), m_sbyte);
m_sbyteArray = GenericCompare(reader.ReadByteArray("m_sbyteArray"), m_sbyteArray);
m_stringArray = GenericCompare(reader.ReadStringArray("m_stringArray"), m_stringArray);
m_uint16 = GenericValCompare(reader.ReadShort("m_uint16"), m_uint16);
m_uint32 = GenericValCompare(reader.ReadInt("m_uint32"), m_uint32);
m_ulong = GenericValCompare(reader.ReadLong("m_ulong"), m_ulong);
m_uint32Array = GenericCompare(reader.ReadIntArray("m_uint32Array"), m_uint32Array);
m_ulongArray = GenericCompare(reader.ReadLongArray("m_ulongArray"), m_ulongArray);
m_uint16Array = GenericCompare(reader.ReadShortArray("m_uint16Array"), m_uint16Array);
byte[] ret = reader.ReadByteArray("m_byte252");
if (ret.Length != 252)
throw new Exception("Array len 252 not found");
ret = reader.ReadByteArray("m_byte253");
if (ret.Length != 253)
throw new Exception("Array len 253 not found");
ret = reader.ReadByteArray("m_byte65535");
if (ret.Length != 65535)
throw new Exception("Array len 65535 not found");
ret = reader.ReadByteArray("m_byte65536");
if (ret.Length != 65536)
throw new Exception("Array len 65536 not found");
pdxEnumTest retenum = (pdxEnumTest)reader.ReadObject("m_pdxEnum");
if (retenum != m_pdxEnum)
throw new Exception("Enum is not equal");
//byte[] m_byte252 = new byte[252];
//byte[] m_byte253 = new byte[253];
//byte[] m_byte65535 = new byte[65535];
//byte[] m_byte65536 = new byte[65536];
Address[] addressArray = (Address[])reader.ReadObject("m_address");
{
for (int i = 0; i < m_address.Length; i++)
{
if (!m_address[i].Equals(addressArray[i]))
{
Console.WriteLine(m_address[i]);
Console.WriteLine(addressArray[i]);
throw new Exception("Address array not mateched " + i);
}
}
}
List<object> retoa = reader.ReadObjectArray("m_objectArray");
for (int i = 0; i < m_objectArray.Count; i++)
{
if(!m_objectArray[i].Equals(retoa[i]))
throw new Exception("Object array not mateched " + i);
}
}
public string PString
{
get { return m_string; }
}
public void ToData(IPdxWriter writer)
{
writer.WriteArrayOfByteArrays("m_byteByteArray", m_byteByteArray);
writer.WriteChar("m_char", m_char);
writer.WriteBoolean("m_bool", m_bool);
writer.WriteBooleanArray("m_boolArray", m_boolArray);
writer.WriteByte("m_byte", m_byte);
writer.WriteByteArray("m_byteArray", m_byteArray);
writer.WriteCharArray("m_charArray", m_charArray);
//writer.WriteCollection("m_list", m_list);
writer.WriteObject("m_arraylist", m_arraylist);
writer.WriteObject("m_map", m_map);
writer.WriteObject("m_hashtable", m_hashtable);
writer.WriteObject("m_vector", m_vector);
writer.WriteObject("m_chs", m_chs);
writer.WriteObject("m_clhs", m_clhs);
writer.WriteString("m_string", m_string);
writer.WriteDate("m_dateTime", m_dateTime);
writer.WriteDouble("m_double", m_double);
writer.WriteDoubleArray("m_doubleArray", m_doubleArray);
writer.WriteFloat("m_float", m_float);
writer.WriteFloatArray("m_floatArray", m_floatArray);
writer.WriteShort("m_int16", m_int16);
writer.WriteInt("m_int32", m_int32);
writer.WriteLong("m_long", m_long);
writer.WriteIntArray("m_int32Array", m_int32Array);
writer.WriteLongArray("m_longArray", m_longArray);
writer.WriteShortArray("m_int16Array", m_int16Array);
writer.WriteByte("m_sbyte", m_sbyte);
writer.WriteByteArray("m_sbyteArray", m_sbyteArray);
writer.WriteStringArray("m_stringArray", m_stringArray);
writer.WriteShort("m_uint16", m_uint16);
writer.WriteInt("m_uint32", m_uint32);
writer.WriteLong("m_ulong", m_ulong);
writer.WriteIntArray("m_uint32Array", m_uint32Array);
writer.WriteLongArray("m_ulongArray", m_ulongArray);
writer.WriteShortArray("m_uint16Array", m_uint16Array);
writer.WriteByteArray("m_byte252", m_byte252);
writer.WriteByteArray("m_byte253", m_byte253);
writer.WriteByteArray("m_byte65535", m_byte65535);
writer.WriteByteArray("m_byte65536", m_byte65536);
writer.WriteObject("m_pdxEnum", m_pdxEnum);
writer.WriteObject("m_address", m_address);
writer.WriteObjectArray("m_objectArray", m_objectArray);
//byte[] m_byte252 = new byte[252];
//byte[] m_byte253 = new byte[253];
//byte[] m_byte65535 = new byte[65535];
//byte[] m_byte65536 = new byte[65536];
}
public char Char
{
get { return m_char; }
}
public bool Bool
{
get { return m_bool; }
}
public sbyte Byte
{
get { return m_byte; }
}
public sbyte Sbyte
{
get { return m_sbyte; }
}
public short Int16
{
get { return m_int16; }
}
public short Uint16
{
get { return m_uint16; }
}
public Int32 Int32
{
get { return m_int32; }
}
public Int32 Uint32
{
get { return m_uint32; }
}
public long Long
{
get { return m_long; }
}
public Int64 Ulong
{
get { return m_ulong; }
}
public float Float
{
get { return m_float; }
}
public double Double
{
get { return m_double; }
}
public string String
{
get { return m_string; }
}
public bool[] BoolArray
{
get { return m_boolArray; }
}
public byte[] ByteArray
{
get { return m_byteArray; }
}
public byte[] SbyteArray
{
get { return m_sbyteArray; }
}
public char[] CharArray
{
get { return m_charArray; }
}
public DateTime DateTime
{
get { return m_dateTime; }
}
public Int16[] Int16Array
{
get { return m_int16Array; }
}
public Int16[] Uint16Array
{
get { return m_uint16Array; }
}
public Int32[] Int32Array
{
get { return m_int32Array; }
}
public Int32[] Uint32Array
{
get { return m_uint32Array; }
}
public long[] LongArray
{
get { return m_longArray; }
}
public Int64[] UlongArray
{
get { return m_ulongArray; }
}
public float[] FloatArray
{
get { return m_floatArray; }
}
public double[] DoubleArray
{
get { return m_doubleArray; }
}
public byte[][] ByteByteArray
{
get { return m_byteByteArray; }
}
public string[] StringArray
{
get { return m_stringArray; }
}
public List<object> Arraylist
{
get { return m_arraylist; }
}
public IDictionary<object, object> Map
{
get { return m_map; }
}
public Hashtable Hashtable
{
get { return m_hashtable; }
}
public ArrayList Vector
{
get { return m_vector; }
}
public CacheableHashSet Chs
{
get { return m_chs; }
}
public CacheableLinkedHashSet Clhs
{
get { return m_clhs; }
}
public byte[] Byte252
{
get { return m_byte252; }
}
public byte[] Byte253
{
get { return m_byte253; }
}
public byte[] Byte65535
{
get { return m_byte65535; }
}
public byte[] Byte65536
{
get { return m_byte65536; }
}
public pdxEnumTest PdxEnum
{
get { return m_pdxEnum; }
}
public Address[] AddressArray
{
get { return m_address; }
}
public List<object> ObjectArray
{
get { return m_objectArray; }
}
#endregion
}
}
| |
// <copyright file="ImageLoader.cs" company="Anura Code">
// All rights reserved.
// </copyright>
// <author>Alberto Puyana</author>
using FFImageLoading;
using FFImageLoading.Views;
using FFImageLoading.Work;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace Anuracode.Forms.Controls.Renderers
{
/// <summary>
/// Logic for loading images in queue with FFImageLoading.
/// </summary>
public static class ImageLoader
{
/// <summary>
/// Lock for the source update.
/// </summary>
private static SemaphoreSlim lockSource;
/// <summary>
/// Lock for the source update.
/// </summary>
public static SemaphoreSlim LockSource
{
get
{
if (lockSource == null)
{
int semaphoreLimit = 2 * GetNumberOfCores();
lockSource = new SemaphoreSlim(semaphoreLimit);
}
return lockSource;
}
}
/// <summary>
/// Get the number of cores.
/// </summary>
/// <returns>Number of cores of the device.</returns>
public static int GetNumberOfCores()
{
if (((int)Android.OS.Build.VERSION.SdkInt) >= 17)
{
return Java.Lang.Runtime.GetRuntime().AvailableProcessors();
}
else
{
return 1;
}
}
/// <summary>
/// Set the lock for the images, default count depents on the cores.
/// </summary>
/// <param name="newLock">New lock to use.</param>
public static void SetLockSource(SemaphoreSlim newLock)
{
lockSource = newLock;
}
/// <summary>
/// Update image source.
/// </summary>
/// <param name="control">Control to use.</param>
/// <param name="source">Source to use.</param>
/// <param name="lastImageSource">Last image source.</param>
/// <param name="allowDownSample">Allow down sample.</param>
/// <param name="targetWidth">Target width.</param>
/// <param name="targetHeight">Target height.</param>
/// <param name="cancellationToken">Cancel token to use.</param>
/// <returns>Task to await.</returns>
public static async Task<bool> UpdateImageSource(this ImageViewAsync control, Xamarin.Forms.ImageSource source, Xamarin.Forms.ImageSource lastImageSource = null, bool allowDownSample = true, double targetWidth = 0, double targetHeight = 0, CancellationToken cancellationToken = default(CancellationToken))
{
await Task.FromResult(0);
bool controlUpdatedCorrectly = false;
IScheduledWork currentTask = null;
TaskParameter imageLoader = null;
if (control == null)
{
return false;
}
try
{
await LockSource.WaitAsync(cancellationToken);
TaskCompletionSource<bool> tc = new TaskCompletionSource<bool>();
try
{
cancellationToken.ThrowIfCancellationRequested();
var ffSource = ImageSourceBinding.GetImageSourceBinding(source);
if (ffSource == null)
{
control.SetImageResource(global::Android.Resource.Color.Transparent);
tc.SetResult(true);
}
else if (ffSource.ImageSource == FFImageLoading.Work.ImageSource.Url)
{
imageLoader = ImageService.Instance.LoadUrl(ffSource.Path, TimeSpan.FromDays(1));
}
else if (ffSource.ImageSource == FFImageLoading.Work.ImageSource.CompiledResource)
{
imageLoader = ImageService.Instance.LoadCompiledResource(ffSource.Path);
}
else if (ffSource.ImageSource == FFImageLoading.Work.ImageSource.ApplicationBundle)
{
imageLoader = ImageService.Instance.LoadFileFromApplicationBundle(ffSource.Path);
}
else if (ffSource.ImageSource == FFImageLoading.Work.ImageSource.Filepath)
{
imageLoader = ImageService.Instance.LoadFile(ffSource.Path);
}
if (imageLoader != null)
{
if (lastImageSource != null)
{
control.SetImageResource(global::Android.Resource.Color.Transparent);
}
// Downsample
if (allowDownSample && (targetHeight > 0 || targetWidth > 0))
{
if (targetHeight > targetWidth)
{
imageLoader.DownSample(height: (int)targetWidth);
}
else
{
imageLoader.DownSample(width: (int)targetHeight);
}
}
imageLoader.Retry(2, 30000);
imageLoader.Finish(
(work) =>
{
tc.TrySetResult(true);
});
imageLoader.Error(
(iex) =>
{
tc.TrySetException(iex);
});
currentTask = imageLoader.Into(control);
}
}
catch (Exception ex)
{
tc.SetException(ex);
}
controlUpdatedCorrectly = await tc.Task;
}
catch (TaskCanceledException taskCanceledException)
{
}
catch (Android.OS.OperationCanceledException operationCanceledException)
{
}
catch (IOException oException)
{
}
catch (Exception ex)
{
AC.TraceError("Android image loader", ex);
}
finally
{
if (!controlUpdatedCorrectly && (currentTask != null) && !currentTask.IsCancelled)
{
currentTask.Cancel();
}
LockSource.Release();
if (imageLoader != null)
{
imageLoader.Dispose();
}
}
return controlUpdatedCorrectly;
}
}
}
| |
//-----------------------------------------------------------------------------
// <copyright file="ContentDispositionField.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------------
namespace System.Net.Mime
{
using System;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.Text;
using System.Globalization;
using System.Net.Mail;
using System.Collections.Generic;
public class ContentDisposition
{
string dispositionType;
TrackingValidationObjectDictionary parameters;
bool isChanged;
bool isPersisted;
string disposition;
const string creationDate = "creation-date";
const string readDate = "read-date";
const string modificationDate = "modification-date";
const string size = "size";
const string fileName = "filename";
private static readonly TrackingValidationObjectDictionary.ValidateAndParseValue dateParser =
new TrackingValidationObjectDictionary.ValidateAndParseValue
((object value) =>
{
// this will throw a FormatException if the value supplied is not a valid SmtpDateTime
SmtpDateTime date = new SmtpDateTime(value.ToString());
return date;
});
private static readonly TrackingValidationObjectDictionary.ValidateAndParseValue longParser =
new TrackingValidationObjectDictionary.ValidateAndParseValue
((object value) =>
{
long longValue;
if (!long.TryParse(value.ToString(),
NumberStyles.None, CultureInfo.InvariantCulture, out longValue))
{
throw new FormatException(SR.GetString(SR.ContentDispositionInvalid));
}
return longValue;
});
private static readonly IDictionary<string, TrackingValidationObjectDictionary.ValidateAndParseValue>
validators;
static ContentDisposition()
{
validators = new Dictionary<string, TrackingValidationObjectDictionary.ValidateAndParseValue>();
validators.Add(creationDate, dateParser);
validators.Add(modificationDate, dateParser);
validators.Add(readDate, dateParser);
validators.Add(size, longParser);
}
public ContentDisposition()
{
isChanged = true;
dispositionType = "attachment";
disposition = dispositionType;
// no need to parse disposition since there's nothing to parse
}
/// <summary>
/// ctor.
/// </summary>
/// <param name="fieldValue">Unparsed header value.</param>
public ContentDisposition(string disposition)
{
if (disposition == null)
throw new ArgumentNullException("disposition");
isChanged = true;
this.disposition = disposition;
ParseValue();
}
internal DateTime GetDateParameter(string parameterName)
{
SmtpDateTime dateValue =
((TrackingValidationObjectDictionary)Parameters).InternalGet(parameterName) as SmtpDateTime;
if (dateValue == null)
{
return DateTime.MinValue;
}
return dateValue.Date;
}
/// <summary>
/// Gets the disposition type of the content.
/// </summary>
public string DispositionType
{
get
{
return dispositionType;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
if (value == string.Empty)
{
throw new ArgumentException(SR.GetString(SR.net_emptystringset), "value");
}
isChanged = true;
dispositionType = value;
}
}
public StringDictionary Parameters
{
get
{
if (parameters == null)
{
parameters = new TrackingValidationObjectDictionary(validators);
}
return parameters;
}
}
/// <summary>
/// Gets the value of the Filename parameter.
/// </summary>
public string FileName
{
get
{
return Parameters[fileName];
}
set
{
if (String.IsNullOrEmpty(value))
{
Parameters.Remove(fileName);
}
else
{
Parameters[fileName] = value;
}
}
}
/// <summary>
/// Gets the value of the Creation-Date parameter.
/// </summary>
public DateTime CreationDate
{
get
{
return GetDateParameter(creationDate);
}
set
{
SmtpDateTime date = new SmtpDateTime(value);
((TrackingValidationObjectDictionary)Parameters).InternalSet(creationDate, date);
}
}
/// <summary>
/// Gets the value of the Modification-Date parameter.
/// </summary>
public DateTime ModificationDate
{
get
{
return GetDateParameter(modificationDate);
}
set
{
SmtpDateTime date = new SmtpDateTime(value);
((TrackingValidationObjectDictionary)Parameters).InternalSet(modificationDate, date);
}
}
public bool Inline
{
get
{
return (dispositionType == DispositionTypeNames.Inline);
}
set
{
isChanged = true;
if (value)
{
dispositionType = DispositionTypeNames.Inline;
}
else
{
dispositionType = DispositionTypeNames.Attachment;
}
}
}
/// <summary>
/// Gets the value of the Read-Date parameter.
/// </summary>
public DateTime ReadDate
{
get
{
return GetDateParameter(readDate);
}
set
{
SmtpDateTime date = new SmtpDateTime(value);
((TrackingValidationObjectDictionary)Parameters).InternalSet(readDate, date);
}
}
/// <summary>
/// Gets the value of the Size parameter (-1 if unspecified).
/// </summary>
public long Size
{
get
{
object sizeValue = ((TrackingValidationObjectDictionary)Parameters).InternalGet(size);
if (sizeValue == null)
return -1;
else
return (long)sizeValue;
}
set
{
((TrackingValidationObjectDictionary)Parameters).InternalSet(size, value);
}
}
internal void Set(string contentDisposition, HeaderCollection headers)
{
// we don't set ischanged because persistence was already handled
// via the headers.
disposition = contentDisposition;
ParseValue();
headers.InternalSet(MailHeaderInfo.GetString(MailHeaderID.ContentDisposition), ToString());
isPersisted = true;
}
internal void PersistIfNeeded(HeaderCollection headers, bool forcePersist)
{
if (IsChanged || !isPersisted || forcePersist)
{
headers.InternalSet(MailHeaderInfo.GetString(MailHeaderID.ContentDisposition), ToString());
isPersisted = true;
}
}
internal bool IsChanged
{
get
{
return (isChanged || parameters != null && parameters.IsChanged);
}
}
public override string ToString()
{
if (disposition == null || isChanged || parameters != null && parameters.IsChanged)
{
disposition = Encode(false); // Legacy wire-safe format
isChanged = false;
parameters.IsChanged = false;
isPersisted = false;
}
return disposition;
}
internal string Encode(bool allowUnicode)
{
StringBuilder builder = new StringBuilder();
builder.Append(dispositionType); // Must not have unicode, already validated
// Validate and encode unicode where required
foreach (string key in Parameters.Keys)
{
builder.Append("; ");
EncodeToBuffer(key, builder, allowUnicode);
builder.Append('=');
EncodeToBuffer(parameters[key], builder, allowUnicode);
}
return builder.ToString();
}
private static void EncodeToBuffer(string value, StringBuilder builder, bool allowUnicode)
{
Encoding encoding = MimeBasePart.DecodeEncoding(value);
if (encoding != null) // Manually encoded elsewhere, pass through
{
builder.Append("\"" + value + "\"");
}
else if ((allowUnicode && !MailBnfHelper.HasCROrLF(value)) // Unicode without CL or LF's
|| MimeBasePart.IsAscii(value, false)) // Ascii
{
MailBnfHelper.GetTokenOrQuotedString(value, builder, allowUnicode);
}
else
{
// MIME Encoding required
encoding = Encoding.GetEncoding(MimeBasePart.defaultCharSet);
builder.Append("\"" + MimeBasePart.EncodeHeaderValue(value, encoding,
MimeBasePart.ShouldUseBase64Encoding(encoding)) + "\"");
}
}
public override bool Equals(object rparam)
{
if (rparam == null)
{
return false;
}
return (String.Compare(ToString(), rparam.ToString(), StringComparison.OrdinalIgnoreCase) == 0);
}
public override int GetHashCode()
{
return ToString().ToLowerInvariant().GetHashCode();
}
void ParseValue()
{
int offset = 0;
try
{
// the disposition MUST be the first parameter in the string
dispositionType = MailBnfHelper.ReadToken(disposition, ref offset, null);
// disposition MUST not be empty
if (String.IsNullOrEmpty(dispositionType))
{
throw new FormatException(SR.GetString(SR.MailHeaderFieldMalformedHeader));
}
// now we know that there are parameters so we must initialize or clear
// and parse
if (parameters == null)
{
parameters = new TrackingValidationObjectDictionary(validators);
}
else
{
parameters.Clear();
}
while (MailBnfHelper.SkipCFWS(disposition, ref offset))
{
// ensure that the separator charactor is present
if (disposition[offset++] != ';')
throw new FormatException(SR.GetString(SR.MailHeaderFieldInvalidCharacter, disposition[offset-1]));
// skip whitespace and see if there's anything left to parse or if we're done
if (!MailBnfHelper.SkipCFWS(disposition, ref offset))
break;
string paramAttribute = MailBnfHelper.ReadParameterAttribute(disposition, ref offset, null);
string paramValue;
// verify the next character after the parameter is correct
if (disposition[offset++] != '=')
{
throw new FormatException(SR.GetString(SR.MailHeaderFieldMalformedHeader));
}
if (!MailBnfHelper.SkipCFWS(disposition, ref offset))
{
// parameter was at end of string and has no value
// this is not valid
throw new FormatException(SR.GetString(SR.ContentDispositionInvalid));
}
if (disposition[offset] == '"')
{
paramValue = MailBnfHelper.ReadQuotedString(disposition, ref offset, null);
}
else
{
paramValue = MailBnfHelper.ReadToken(disposition, ref offset, null);
}
// paramValue could potentially still be empty if it was a valid quoted string that
// contained no inner value. this is invalid
if (String.IsNullOrEmpty(paramAttribute) || string.IsNullOrEmpty(paramValue))
{
throw new FormatException(SR.GetString(SR.ContentDispositionInvalid));
}
// if validation is needed, the parameters dictionary will have a validator registered
// for the parameter that is being set so no additional formatting checks are needed here
Parameters.Add(paramAttribute, paramValue);
}
}
catch (FormatException exception)
{
// it's possible that something in MailBNFHelper could throw so ensure that we catch it and wrap it
// so that the exception has the correct text
throw new FormatException(SR.GetString(SR.ContentDispositionInvalid), exception);
}
parameters.IsChanged = false;
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
namespace Microsoft.Live
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Web;
using System.Text;
using System.Threading.Tasks;
/// <summary>
/// This class is designed to help web applications developers handle user authentication/authorization process.
/// </summary>
public class LiveAuthClient : INotifyPropertyChanged
{
private readonly LiveAuthClientCore authClient;
private readonly string defaultRedirectUrl;
private LiveConnectSession session;
private string currentUserId;
private bool sessionChanged;
private bool currentUserIdChanged;
/// <summary>
/// Initializes an instance of LiveAuthClient class.
/// </summary>
/// <param name="clientId">The client Id of the app.</param>
/// <param name="clientSecret">The client secret of the app.</param>
/// <param name="defaultRedirectUrl">The default redirect URL for the site.</param>
public LiveAuthClient(
string clientId,
string clientSecret,
string defaultRedirectUrl)
: this(clientId, clientSecret, defaultRedirectUrl, null)
{
}
/// <summary>
/// Initializes an instance of LiveAuthClient class.
/// </summary>
/// <param name="clientId">The client Id of the app.</param>
/// <param name="clientSecret">The client secret of the app.</param>
/// <param name="defaultRedirectUrl">The default redirect URL for the site.</param>
/// <param name="refreshTokenHandler">An IRefreshTokenHandler instance to handle refresh token persistency and retrieval.</param>
public LiveAuthClient(
string clientId,
string clientSecret,
string defaultRedirectUrl,
IRefreshTokenHandler refreshTokenHandler)
{
LiveUtility.ValidateNotNullOrWhiteSpaceString(clientId, "clientId");
LiveUtility.ValidateNotNullOrWhiteSpaceString(clientSecret, "clientSecret");
if (!string.IsNullOrWhiteSpace(defaultRedirectUrl))
{
LiveUtility.ValidateUrl(defaultRedirectUrl, "defaultRedirectUrl");
this.defaultRedirectUrl = defaultRedirectUrl;
}
this.authClient = new LiveAuthClientCore(clientId, clientSecret, refreshTokenHandler, this);
}
/// <summary>
/// Initializes an instance of LiveAuthClient class.
/// To address security concerns, developers may wish to change their client secret. This constructor allows
/// the developer to pass in a client secret map to handle the client secret change and ensure a graceful experience
/// during the change rollover. You can create a new secret for your app on the developer portal (https://account.live.com/developers/applications)
/// site. Once a new secret is created, the site will indicate the version of each secret, new and old.
/// For example, the old secret and new secret may be shown as v0 and v1 on the developer portal site.
/// Before the new secret is activated, both secrets are accepted by the Microsoft authentication server. You should update your
/// code to provide the secret map when intializing a LiveAuthClient instance. This will ensure that the new secret
/// will be used when communicating with the Microsoft authentication server, and the LiveAuthClient instance will use the correct version of
/// the client secret to validate authentication tokens that may be signed by either old or new versions of client secret.
/// Once you activate the new secret on the developer portal site, the old secret will no longer be accepted by the Microsoft
/// authentication server, however, you may still want to keep the old secret in the map for one day, so that
/// clients with authentication tokens signed with the old secret will continue to work.
/// </summary>
/// <param name="clientId">The client Id of the app.</param>
/// <param name="clientSecretMap">The client secret map of the app.</param>
/// <param name="defaultRedirectUrl">The default redirect URL for the site.</param>
public LiveAuthClient(
string clientId,
IDictionary<int, string> clientSecretMap,
string defaultRedirectUrl)
: this(clientId, clientSecretMap, defaultRedirectUrl, null)
{
}
/// <summary>
/// Initializes an instance of LiveAuthClient class.
/// To address security concerns, developers may wish to change their client secret. This constructor allows
/// the developer to pass in a client secret map to handle the client secret change and ensure a graceful experience
/// during the change rollover. You can create a new secret for your app on the developer portal (https://account.live.com/developers/applications)
/// site. Once a new secret is created, the site will indicate the version of each secret, new and old.
/// For example, the old secret and new secret may be shown as v0 and v1 on the developer portal site.
/// Before the new secret is activated, both secrets are accepted by the Microsoft authentication server. You should update your
/// code to provide the secret map when intializing a LiveAuthClient instance. This will ensure that the new secret
/// will be used when communicating with the Microsoft authentication server, and the LiveAuthClient instance will use the correct version of
/// the client secret to validate authentication tokens that may be signed by either old or new versions of client secret.
/// Once you activate the new secret on the developer portal site, the old secret will no longer be accepted by the Microsoft
/// authentication server, however, you may still want to keep the old secret in the map for one day, so that
/// clients with authentication tokens signed with the old secret will continue to work.
/// </summary>
/// <param name="clientId">The client Id of the app.</param>
/// <param name="clientSecretMap">The client secret map of the app.</param>
/// <param name="defaultRedirectUrl">The default redirect URL for the site.</param>
/// <param name="refreshTokenHandler">An IRefreshTokenHandler instance to handle refresh token persistency and retrieval.</param>
public LiveAuthClient(
string clientId,
IDictionary<int, string> clientSecretMap,
string defaultRedirectUrl,
IRefreshTokenHandler refreshTokenHandler)
{
LiveUtility.ValidateNotNullOrWhiteSpaceString(clientId, "clientId");
LiveUtility.ValidateNotNullParameter(clientSecretMap, "clientSecretMap");
if (clientSecretMap.Count == 0)
{
throw new ArgumentException("Client secret must be provided.", "clientSecretMap");
}
if (!string.IsNullOrWhiteSpace(defaultRedirectUrl))
{
LiveUtility.ValidateUrl(defaultRedirectUrl, "defaultRedirectUrl");
this.defaultRedirectUrl = defaultRedirectUrl;
}
this.authClient = new LiveAuthClientCore(clientId, clientSecretMap, refreshTokenHandler, this);
}
/// <summary>
/// Occurs when a property value changes.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
#if DEBUG
/// <summary>
/// Allows the application to override the default auth server host name.
/// </summary>
public static string AuthEndpointOverride { get; set; }
#endif
/// <summary>
/// Gets the current session.
/// </summary>
public LiveConnectSession Session
{
get
{
return this.session;
}
internal set
{
if (this.session != value)
{
this.session = value;
this.UpdateCurrentUseId();
this.sessionChanged = true;
}
}
}
/// <summary>
/// Gets the current user's Id.
/// </summary>
public string CurrentUserId
{
get
{
return this.currentUserId;
}
private set
{
if (this.currentUserId != value)
{
this.currentUserId = value;
this.currentUserIdChanged = true;
}
}
}
/// <summary>
/// Initializes the LiveAuthClient instance for the current user.
/// If an authorization code is present, it will send a request to the auth server to exchange the token.
/// If there is an auth session in current context, it will retrieve the current auth session.
/// If the current session is expired or the current request url indicates (refresh=1) to get a new token,
/// it will try to request a new access token using refresh token that will need to be provided through
/// IRefreshTokenHandler.RetrieveRefreshTokenAsync() method.
/// Any updated session state will be saved in the auth session cookie.
/// </summary>
/// <param name="context">The HttpContextBase instance of current request.</param>
/// <returns>An async Task instance</returns>
public Task<LiveLoginResult> InitializeWebSessionAsync(
HttpContextBase context)
{
return this.InitializeWebSessionAsync(context, this.defaultRedirectUrl);
}
/// <summary>
/// Initializes the LiveAuthClient instance for the current user.
/// If an authorization code is present, it will send a request to the auth server to exchange the token.
/// If there is an auth session in current context, it will retrieve the current auth session.
/// If the current session is expired or the current request url indicates (refresh=1) to get a new token,
/// it will try to request a new access token using refresh token that will need to be provided through
/// IRefreshTokenHandler.RetrieveRefreshTokenAsync() method.
/// Any updated session state will be saved in the auth session cookie.
/// </summary>
/// <param name="context">The HttpContextBase instance of current request.</param>
/// <param name="redirectUrl">The redirect URL of the app. This must match exactly the Url that is used to
/// generate the login Url via LiveAuthClient.GetLoginUrl</param>
/// <returns>An async Task instance</returns>
public Task<LiveLoginResult> InitializeWebSessionAsync(
HttpContextBase context,
string redirectUrl)
{
return this.InitializeWebSessionAsync(context, redirectUrl, null);
}
/// <summary>
/// Initializes the LiveAuthClient instance for the current user.
/// If an authorization code is present, it will send a request to the auth server to exchange the token.
/// If there is an auth session in current context, it will retrieve the current auth session.
/// If the current session is expired or the current request url indicates (refresh=1) to get a new token,
/// it will try to request a new access token using refresh token that will need to be provided through
/// IRefreshTokenHandler.RetrieveRefreshTokenAsync() method.
/// Any updated session state will be saved in the auth session cookie.
/// </summary>
/// <param name="context">The HttpContextBase instance of current request.</param>
/// <param name="redirectUrl">The redirect URL of the app. This must match exactly the Url that is used to
/// generate the login Url via LiveAuthClient.GetLoginUrl</param>
/// <param name="scopes">A list of scopes to validate whether the user has consented. If the available session
/// does not satisfy the specified scopes, NotConnected status will be returned. However, the developer still
/// can find the available session throw the Session property.</param>
/// <returns>An async Task instance</returns>
public Task<LiveLoginResult> InitializeWebSessionAsync(
HttpContextBase context,
string redirectUrl,
IEnumerable<string> scopes)
{
LiveUtility.ValidateNotNullParameter(context, "context");
if (string.IsNullOrWhiteSpace(redirectUrl))
{
redirectUrl = LiveAuthUtility.GetCurrentRedirectUrl(context.Request.Url);
}
else
{
LiveUtility.ValidateUrl(redirectUrl, "redirectUrl");
}
return this.authClient.InitializeWebSessionAsync(redirectUrl, context, scopes);
}
/// <summary>
/// Initializes the LiveAuthClient instance.
/// This will trigger retrieving token with refresh token process.
/// </summary>
/// <returns>An async Task instance.</returns>
public Task<LiveLoginResult> InitializeSessionAsync()
{
if (this.defaultRedirectUrl == null)
{
throw new InvalidOperationException(ErrorText.DefaultRedirectUrlMissing);
}
return this.authClient.InitializeSessionAsync(this.defaultRedirectUrl, null);
}
/// <summary>
/// Initializes the LiveAuthClient instance.
/// This will trigger retrieving token with refresh token process.
/// </summary>
/// <param name="redirectUri">The redirect URL of the app.</param>
/// <returns>An async Task instance.</returns>
public Task<LiveLoginResult> InitializeSessionAsync(string redirectUrl)
{
return this.InitializeSessionAsync(redirectUrl, null);
}
/// <summary>
/// Initializes the LiveAuthClient instance.
/// This will trigger retrieving token with refresh token process.
/// </summary>
/// <param name="redirectUri">The redirect URL of the app.</param>
/// <param name="scopes">A list of scopes to validate whether the user has consented.</param>
/// <returns>An async Task instance.</returns>
public Task<LiveLoginResult> InitializeSessionAsync(string redirectUrl, IEnumerable<string> scopes)
{
LiveUtility.ValidateUrl(redirectUrl, "redirectUrl");
return this.authClient.InitializeSessionAsync(redirectUrl ,scopes);
}
/// <summary>
/// Exchange authentication code from the Http request for access token.
/// </summary>
/// <param name="context">The HttpContextBase instance</param>
/// <returns>An async Task instance.</returns>
public Task<LiveLoginResult> ExchangeAuthCodeAsync(HttpContextBase context)
{
return this.ExchangeAuthCodeAsync(context, this.defaultRedirectUrl);
}
/// <summary>
/// Exchange authentication code for access token.
/// </summary>
/// <param name="context">The HttpContextBase instance</param>
/// <param name="redirectUri">The redirect URL of the app.</param>
/// <returns>An async Task instance.</returns>
public Task<LiveLoginResult> ExchangeAuthCodeAsync(
HttpContextBase context,
string redirectUrl)
{
LiveUtility.ValidateNotNullParameter(context, "context");
if (string.IsNullOrWhiteSpace(redirectUrl))
{
redirectUrl = LiveAuthUtility.GetCurrentRedirectUrl(context.Request.Url);
}
else
{
LiveUtility.ValidateUrl(redirectUrl, "redirectUrl");
}
return this.authClient.ExchangeAuthCodeAsync(redirectUrl, context);
}
/// <summary>
/// Clear the auth state in the current session
/// </summary>
/// <param name="context">Optional</param>
public void ClearSession(HttpContextBase context)
{
LiveUtility.ValidateNotNullParameter(context, "context");
this.authClient.ClearSession(context);
}
/// <summary>
/// Generates a consent URL that includes a set of provided parameters.
/// </summary>
/// <param name="scopes">A list of scope values that the user will need to consent to.</param>
/// <returns>The generated login URL value.</returns>
public string GetLoginUrl(IEnumerable<string> scopes)
{
if (this.defaultRedirectUrl == null)
{
throw new InvalidOperationException(ErrorText.DefaultRedirectUrlMissing);
}
return this.GetLoginUrl(scopes, this.defaultRedirectUrl);
}
/// <summary>
/// Generates a consent URL that includes a set of provided parameters.
/// </summary>
/// <param name="scopes">A list of scope values that the user will need to consent to.</param>
/// <param name="redirectUri">The URL that the page will be redirected to after authorize process is completed.</param>
/// <returns>The generated login URL value.</returns>
public string GetLoginUrl(IEnumerable<string> scopes, string redirectUrl)
{
return this.GetLoginUrl(scopes, redirectUrl, null);
}
/// <summary>
/// Generates a consent URL that includes a set of provided parameters.
/// </summary>
/// <param name="scopes">A list of scope values that the user will need to authorize.</param>
/// <param name="options">Optional query string parameters.</param>
/// <returns>The generated login URL value.</returns>
public string GetLoginUrl(IEnumerable<string> scopes, IDictionary<string, string> options)
{
if (this.defaultRedirectUrl == null)
{
throw new InvalidOperationException(ErrorText.DefaultRedirectUrlMissing);
}
return this.GetLoginUrl(scopes, this.defaultRedirectUrl, options);
}
/// <summary>
/// Generates a consent URL that includes a set of provided parameters.
/// </summary>
/// <param name="scopes">A list of scope values that the user will need to authorize.</param>
/// <param name="redirectUri">The URL that the page will be redirected to after authorize process is completed.</param>
/// <param name="options">Optional query string parameters.</param>
/// <returns>The generated login URL value.</returns>
public string GetLoginUrl(IEnumerable<string> scopes, string redirectUrl, IDictionary<string, string> options)
{
LiveUtility.ValidateNotEmptyStringEnumeratorArguement(scopes, "scopes");
LiveUtility.ValidateUrl(redirectUrl, "redirectUrl");
string locale = null;
string state = null;
DisplayType display = DisplayType.Page;
if (options != null)
{
if (options.ContainsKey(AuthConstants.Locale))
{
locale = options[AuthConstants.Locale];
}
if (options.ContainsKey(AuthConstants.ClientState))
{
state = options[AuthConstants.ClientState];
}
if (options.ContainsKey(AuthConstants.Display))
{
string displayStr = options[AuthConstants.Display];
if (!Enum.TryParse<DisplayType>(displayStr, true, out display))
{
throw new ArgumentException(ErrorText.ParameterInvalidDisplayValue, "display");
}
}
}
if (locale == null)
{
locale = CultureInfo.CurrentUICulture.ToString();
}
return this.authClient.GetLoginUrl(scopes, redirectUrl, display, locale, state);
}
/// <summary>
/// Gets the logout URL.
/// </summary>
/// <param name="redirectUri">The URL that the page will be redirected to after logout is completed.</param>
/// <returns>The logout URL.</returns>
public string GetLogoutUrl(string redirectUrl)
{
LiveUtility.ValidateNotNullOrWhiteSpaceString(redirectUrl, "redirectUrl");
return this.authClient.GetLogoutUrl(redirectUrl);
}
/// <summary>
/// Decrypts the user ID from a given authentication token.
/// </summary>
/// <returns>The user ID string value</returns>
public string GetUserId(string authenticationToken)
{
LiveUtility.ValidateNotNullOrWhiteSpaceString(authenticationToken, "authenticationToken");
string userId;
LiveAuthException error;
if (this.authClient.GetUserId(authenticationToken, out userId, out error))
{
return userId;
}
else
{
throw error;
}
}
/// <summary>
/// This method is used to ensure that the property changed event is only invoked once during the execution of
/// InitUserPresentAsync and InitUserAbsentAsync methods.
/// </summary>
internal void FirePendingPropertyChangedEvents()
{
if (this.sessionChanged)
{
this.OnPropertyChanged("Session");
this.sessionChanged = false;
}
if (this.currentUserIdChanged)
{
this.OnPropertyChanged("CurrentUserId");
this.currentUserIdChanged = false;
}
}
internal bool RefreshToken(Action<LiveLoginResult> completionCallback)
{
// This scenario is not supported in the Web, because refreshing ticket
// should only happen when InitializeWebSessionAsync or InitializeSessionAsync is
// invoked.
return false;
}
private void UpdateCurrentUseId()
{
string userId = null;
if (this.session != null)
{
string authenticationToken = this.session.AuthenticationToken;
if (!string.IsNullOrEmpty(authenticationToken))
{
LiveAuthException error;
this.authClient.GetUserId(authenticationToken, out userId, out error);
}
}
this.CurrentUserId = userId;
}
private void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Binary
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache.Affinity;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Binary.Metadata;
using Apache.Ignite.Core.Impl.Cache;
using Apache.Ignite.Core.Impl.Cache.Query.Continuous;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Compute;
using Apache.Ignite.Core.Impl.Compute.Closure;
using Apache.Ignite.Core.Impl.Datastream;
using Apache.Ignite.Core.Impl.Messaging;
/// <summary>
/// Marshaller implementation.
/// </summary>
internal class Marshaller
{
/** Binary configuration. */
private readonly BinaryConfiguration _cfg;
/** Type to descriptor map. */
private readonly IDictionary<Type, IBinaryTypeDescriptor> _typeToDesc =
new Dictionary<Type, IBinaryTypeDescriptor>();
/** Type name to descriptor map. */
private readonly IDictionary<string, IBinaryTypeDescriptor> _typeNameToDesc =
new Dictionary<string, IBinaryTypeDescriptor>();
/** ID to descriptor map. */
private readonly CopyOnWriteConcurrentDictionary<long, IBinaryTypeDescriptor> _idToDesc =
new CopyOnWriteConcurrentDictionary<long, IBinaryTypeDescriptor>();
/** Cached metadatas. */
private volatile IDictionary<int, BinaryTypeHolder> _metas =
new Dictionary<int, BinaryTypeHolder>();
/// <summary>
/// Constructor.
/// </summary>
/// <param name="cfg">Configurtaion.</param>
public Marshaller(BinaryConfiguration cfg)
{
// Validation.
if (cfg == null)
cfg = new BinaryConfiguration();
CompactFooter = cfg.CompactFooter;
if (cfg.TypeConfigurations == null)
cfg.TypeConfigurations = new List<BinaryTypeConfiguration>();
foreach (BinaryTypeConfiguration typeCfg in cfg.TypeConfigurations)
{
if (string.IsNullOrEmpty(typeCfg.TypeName))
throw new BinaryObjectException("Type name cannot be null or empty: " + typeCfg);
}
// Define system types. They use internal reflective stuff, so configuration doesn't affect them.
AddSystemTypes();
// 2. Define user types.
var typeResolver = new TypeResolver();
ICollection<BinaryTypeConfiguration> typeCfgs = cfg.TypeConfigurations;
if (typeCfgs != null)
foreach (BinaryTypeConfiguration typeCfg in typeCfgs)
AddUserType(cfg, typeCfg, typeResolver);
var typeNames = cfg.Types;
if (typeNames != null)
foreach (string typeName in typeNames)
AddUserType(cfg, new BinaryTypeConfiguration(typeName), typeResolver);
_cfg = cfg;
}
/// <summary>
/// Gets or sets the backing grid.
/// </summary>
public Ignite Ignite { get; set; }
/// <summary>
/// Gets the compact footer flag.
/// </summary>
public bool CompactFooter { get; set; }
/// <summary>
/// Marshal object.
/// </summary>
/// <param name="val">Value.</param>
/// <returns>Serialized data as byte array.</returns>
public byte[] Marshal<T>(T val)
{
using (var stream = new BinaryHeapStream(128))
{
Marshal(val, stream);
return stream.GetArrayCopy();
}
}
/// <summary>
/// Marshal object.
/// </summary>
/// <param name="val">Value.</param>
/// <param name="stream">Output stream.</param>
/// <returns>Collection of metadatas (if any).</returns>
private void Marshal<T>(T val, IBinaryStream stream)
{
BinaryWriter writer = StartMarshal(stream);
writer.Write(val);
FinishMarshal(writer);
}
/// <summary>
/// Start marshal session.
/// </summary>
/// <param name="stream">Stream.</param>
/// <returns>Writer.</returns>
public BinaryWriter StartMarshal(IBinaryStream stream)
{
return new BinaryWriter(this, stream);
}
/// <summary>
/// Finish marshal session.
/// </summary>
/// <param name="writer">Writer.</param>
/// <returns>Dictionary with metadata.</returns>
public void FinishMarshal(BinaryWriter writer)
{
var metas = writer.GetBinaryTypes();
var ignite = Ignite;
if (ignite != null && metas != null && metas.Count > 0)
ignite.PutBinaryTypes(metas);
}
/// <summary>
/// Unmarshal object.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data">Data array.</param>
/// <param name="keepBinary">Whether to keep binarizable as binary.</param>
/// <returns>
/// Object.
/// </returns>
public T Unmarshal<T>(byte[] data, bool keepBinary)
{
using (var stream = new BinaryHeapStream(data))
{
return Unmarshal<T>(stream, keepBinary);
}
}
/// <summary>
/// Unmarshal object.
/// </summary>
/// <param name="data">Data array.</param>
/// <param name="mode">The mode.</param>
/// <returns>
/// Object.
/// </returns>
public T Unmarshal<T>(byte[] data, BinaryMode mode = BinaryMode.Deserialize)
{
using (var stream = new BinaryHeapStream(data))
{
return Unmarshal<T>(stream, mode);
}
}
/// <summary>
/// Unmarshal object.
/// </summary>
/// <param name="stream">Stream over underlying byte array with correct position.</param>
/// <param name="keepBinary">Whether to keep binary objects in binary form.</param>
/// <returns>
/// Object.
/// </returns>
public T Unmarshal<T>(IBinaryStream stream, bool keepBinary)
{
return Unmarshal<T>(stream, keepBinary ? BinaryMode.KeepBinary : BinaryMode.Deserialize, null);
}
/// <summary>
/// Unmarshal object.
/// </summary>
/// <param name="stream">Stream over underlying byte array with correct position.</param>
/// <param name="mode">The mode.</param>
/// <returns>
/// Object.
/// </returns>
public T Unmarshal<T>(IBinaryStream stream, BinaryMode mode = BinaryMode.Deserialize)
{
return Unmarshal<T>(stream, mode, null);
}
/// <summary>
/// Unmarshal object.
/// </summary>
/// <param name="stream">Stream over underlying byte array with correct position.</param>
/// <param name="mode">The mode.</param>
/// <param name="builder">Builder.</param>
/// <returns>
/// Object.
/// </returns>
public T Unmarshal<T>(IBinaryStream stream, BinaryMode mode, BinaryObjectBuilder builder)
{
return new BinaryReader(this, stream, mode, builder).Deserialize<T>();
}
/// <summary>
/// Start unmarshal session.
/// </summary>
/// <param name="stream">Stream.</param>
/// <param name="keepBinary">Whether to keep binarizable as binary.</param>
/// <returns>
/// Reader.
/// </returns>
public BinaryReader StartUnmarshal(IBinaryStream stream, bool keepBinary)
{
return new BinaryReader(this, stream, keepBinary ? BinaryMode.KeepBinary : BinaryMode.Deserialize, null);
}
/// <summary>
/// Start unmarshal session.
/// </summary>
/// <param name="stream">Stream.</param>
/// <param name="mode">The mode.</param>
/// <returns>Reader.</returns>
public BinaryReader StartUnmarshal(IBinaryStream stream, BinaryMode mode = BinaryMode.Deserialize)
{
return new BinaryReader(this, stream, mode, null);
}
/// <summary>
/// Gets metadata for the given type ID.
/// </summary>
/// <param name="typeId">Type ID.</param>
/// <returns>Metadata or null.</returns>
public IBinaryType GetBinaryType(int typeId)
{
if (Ignite != null)
{
IBinaryType meta = Ignite.GetBinaryType(typeId);
if (meta != null)
return meta;
}
return BinaryType.Empty;
}
/// <summary>
/// Puts the binary type metadata to Ignite.
/// </summary>
/// <param name="desc">Descriptor.</param>
public void PutBinaryType(IBinaryTypeDescriptor desc)
{
Debug.Assert(desc != null);
GetBinaryTypeHandler(desc); // ensure that handler exists
if (Ignite != null)
Ignite.PutBinaryTypes(new[] {new BinaryType(desc)});
}
/// <summary>
/// Gets binary type handler for the given type ID.
/// </summary>
/// <param name="desc">Type descriptor.</param>
/// <returns>Binary type handler.</returns>
public IBinaryTypeHandler GetBinaryTypeHandler(IBinaryTypeDescriptor desc)
{
BinaryTypeHolder holder;
if (!_metas.TryGetValue(desc.TypeId, out holder))
{
lock (this)
{
if (!_metas.TryGetValue(desc.TypeId, out holder))
{
IDictionary<int, BinaryTypeHolder> metas0 =
new Dictionary<int, BinaryTypeHolder>(_metas);
holder = new BinaryTypeHolder(desc.TypeId, desc.TypeName, desc.AffinityKeyFieldName, desc.IsEnum);
metas0[desc.TypeId] = holder;
_metas = metas0;
}
}
}
if (holder != null)
{
ICollection<int> ids = holder.GetFieldIds();
bool newType = ids.Count == 0 && !holder.Saved();
return new BinaryTypeHashsetHandler(ids, newType);
}
return null;
}
/// <summary>
/// Callback invoked when metadata has been sent to the server and acknowledged by it.
/// </summary>
/// <param name="newMetas">Binary types.</param>
public void OnBinaryTypesSent(IEnumerable<BinaryType> newMetas)
{
foreach (var meta in newMetas)
{
var mergeInfo = new Dictionary<int, Tuple<string, int>>(meta.GetFieldsMap().Count);
foreach (KeyValuePair<string, int> fieldMeta in meta.GetFieldsMap())
{
int fieldId = BinaryUtils.FieldId(meta.TypeId, fieldMeta.Key, null, null);
mergeInfo[fieldId] = new Tuple<string, int>(fieldMeta.Key, fieldMeta.Value);
}
_metas[meta.TypeId].Merge(mergeInfo);
}
}
/// <summary>
/// Gets descriptor for type.
/// </summary>
/// <param name="type">Type.</param>
/// <returns>Descriptor.</returns>
public IBinaryTypeDescriptor GetDescriptor(Type type)
{
IBinaryTypeDescriptor desc;
_typeToDesc.TryGetValue(type, out desc);
return desc;
}
/// <summary>
/// Gets descriptor for type name.
/// </summary>
/// <param name="typeName">Type name.</param>
/// <returns>Descriptor.</returns>
public IBinaryTypeDescriptor GetDescriptor(string typeName)
{
IBinaryTypeDescriptor desc;
return _typeNameToDesc.TryGetValue(typeName, out desc) ? desc :
new BinarySurrogateTypeDescriptor(_cfg, typeName);
}
/// <summary>
/// Gets descriptor for a type id.
/// </summary>
/// <param name="userType">User type flag.</param>
/// <param name="typeId">Type id.</param>
/// <returns>Descriptor.</returns>
public IBinaryTypeDescriptor GetDescriptor(bool userType, int typeId)
{
IBinaryTypeDescriptor desc;
var typeKey = BinaryUtils.TypeKey(userType, typeId);
if (_idToDesc.TryGetValue(typeKey, out desc))
return desc;
if (!userType)
return null;
var meta = GetBinaryType(typeId);
if (meta != BinaryType.Empty)
{
desc = new BinaryFullTypeDescriptor(null, meta.TypeId, meta.TypeName, true, null, null, null, false,
meta.AffinityKeyFieldName, meta.IsEnum);
_idToDesc.GetOrAdd(typeKey, _ => desc);
return desc;
}
return new BinarySurrogateTypeDescriptor(_cfg, typeId);
}
/// <summary>
/// Add user type.
/// </summary>
/// <param name="cfg">Configuration.</param>
/// <param name="typeCfg">Type configuration.</param>
/// <param name="typeResolver">The type resolver.</param>
private void AddUserType(BinaryConfiguration cfg, BinaryTypeConfiguration typeCfg,
TypeResolver typeResolver)
{
// Get converter/mapper/serializer.
IBinaryNameMapper nameMapper = typeCfg.NameMapper ?? cfg.DefaultNameMapper;
IBinaryIdMapper idMapper = typeCfg.IdMapper ?? cfg.DefaultIdMapper;
bool keepDeserialized = typeCfg.KeepDeserialized ?? cfg.DefaultKeepDeserialized;
// Try resolving type.
Type type = typeResolver.ResolveType(typeCfg.TypeName);
if (type != null)
{
if (typeCfg.IsEnum != type.IsEnum)
throw new BinaryObjectException(
string.Format(
"Invalid IsEnum flag in binary type configuration. " +
"Configuration value: IsEnum={0}, actual type: IsEnum={1}",
typeCfg.IsEnum, type.IsEnum));
// Type is found.
var typeName = BinaryUtils.GetTypeName(type);
int typeId = BinaryUtils.TypeId(typeName, nameMapper, idMapper);
var affKeyFld = typeCfg.AffinityKeyFieldName ?? GetAffinityKeyFieldNameFromAttribute(type);
var serializer = GetSerializer(cfg, typeCfg, type, typeId, nameMapper, idMapper);
AddType(type, typeId, typeName, true, keepDeserialized, nameMapper, idMapper, serializer,
affKeyFld, type.IsEnum);
}
else
{
// Type is not found.
string typeName = BinaryUtils.SimpleTypeName(typeCfg.TypeName);
int typeId = BinaryUtils.TypeId(typeName, nameMapper, idMapper);
AddType(null, typeId, typeName, true, keepDeserialized, nameMapper, idMapper, null,
typeCfg.AffinityKeyFieldName, typeCfg.IsEnum);
}
}
/// <summary>
/// Gets the serializer.
/// </summary>
private static IBinarySerializerInternal GetSerializer(BinaryConfiguration cfg, BinaryTypeConfiguration typeCfg,
Type type, int typeId, IBinaryNameMapper nameMapper, IBinaryIdMapper idMapper)
{
var serializer = typeCfg.Serializer ?? cfg.DefaultSerializer;
if (serializer == null)
{
if (type.GetInterfaces().Contains(typeof(IBinarizable)))
return BinarizableSerializer.Instance;
serializer = new BinaryReflectiveSerializer();
}
var refSerializer = serializer as BinaryReflectiveSerializer;
return refSerializer != null
? refSerializer.Register(type, typeId, nameMapper, idMapper)
: new UserSerializerProxy(serializer);
}
/// <summary>
/// Gets the affinity key field name from attribute.
/// </summary>
private static string GetAffinityKeyFieldNameFromAttribute(Type type)
{
var res = type.GetMembers()
.Where(x => x.GetCustomAttributes(false).OfType<AffinityKeyMappedAttribute>().Any())
.Select(x => x.Name).ToArray();
if (res.Length > 1)
{
throw new BinaryObjectException(string.Format("Multiple '{0}' attributes found on type '{1}'. " +
"There can be only one affinity field.", typeof (AffinityKeyMappedAttribute).Name, type));
}
return res.SingleOrDefault();
}
/// <summary>
/// Add type.
/// </summary>
/// <param name="type">Type.</param>
/// <param name="typeId">Type ID.</param>
/// <param name="typeName">Type name.</param>
/// <param name="userType">User type flag.</param>
/// <param name="keepDeserialized">Whether to cache deserialized value in IBinaryObject</param>
/// <param name="nameMapper">Name mapper.</param>
/// <param name="idMapper">ID mapper.</param>
/// <param name="serializer">Serializer.</param>
/// <param name="affKeyFieldName">Affinity key field name.</param>
/// <param name="isEnum">Enum flag.</param>
private void AddType(Type type, int typeId, string typeName, bool userType,
bool keepDeserialized, IBinaryNameMapper nameMapper, IBinaryIdMapper idMapper,
IBinarySerializerInternal serializer, string affKeyFieldName, bool isEnum)
{
long typeKey = BinaryUtils.TypeKey(userType, typeId);
IBinaryTypeDescriptor conflictingType;
if (_idToDesc.TryGetValue(typeKey, out conflictingType))
{
var type1 = conflictingType.Type != null
? conflictingType.Type.AssemblyQualifiedName
: conflictingType.TypeName;
var type2 = type != null ? type.AssemblyQualifiedName : typeName;
throw new BinaryObjectException(string.Format("Conflicting type IDs [type1='{0}', " +
"type2='{1}', typeId={2}]", type1, type2, typeId));
}
if (userType && _typeNameToDesc.ContainsKey(typeName))
throw new BinaryObjectException("Conflicting type name: " + typeName);
var descriptor = new BinaryFullTypeDescriptor(type, typeId, typeName, userType, nameMapper, idMapper,
serializer, keepDeserialized, affKeyFieldName, isEnum);
if (type != null)
_typeToDesc[type] = descriptor;
if (userType)
_typeNameToDesc[typeName] = descriptor;
_idToDesc.GetOrAdd(typeKey, _ => descriptor);
}
/// <summary>
/// Adds a predefined system type.
/// </summary>
private void AddSystemType<T>(int typeId, Func<BinaryReader, T> ctor, string affKeyFldName = null,
IBinarySerializerInternal serializer = null)
where T : IBinaryWriteAware
{
var type = typeof(T);
serializer = serializer ?? new BinarySystemTypeSerializer<T>(ctor);
if (typeId == 0)
typeId = BinaryUtils.TypeId(type.Name, null, null);
AddType(type, typeId, BinaryUtils.GetTypeName(type), false, false, null, null, serializer, affKeyFldName,
false);
}
/// <summary>
/// Adds predefined system types.
/// </summary>
private void AddSystemTypes()
{
AddSystemType(BinaryUtils.TypeNativeJobHolder, w => new ComputeJobHolder(w));
AddSystemType(BinaryUtils.TypeComputeJobWrapper, w => new ComputeJobWrapper(w));
AddSystemType(BinaryUtils.TypeIgniteProxy, w => new IgniteProxy());
AddSystemType(BinaryUtils.TypeComputeOutFuncJob, w => new ComputeOutFuncJob(w));
AddSystemType(BinaryUtils.TypeComputeOutFuncWrapper, w => new ComputeOutFuncWrapper(w));
AddSystemType(BinaryUtils.TypeComputeFuncWrapper, w => new ComputeFuncWrapper(w));
AddSystemType(BinaryUtils.TypeComputeFuncJob, w => new ComputeFuncJob(w));
AddSystemType(BinaryUtils.TypeComputeActionJob, w => new ComputeActionJob(w));
AddSystemType(BinaryUtils.TypeContinuousQueryRemoteFilterHolder, w => new ContinuousQueryFilterHolder(w));
AddSystemType(BinaryUtils.TypeSerializableHolder, w => new SerializableObjectHolder(w),
serializer: new SerializableSerializer());
AddSystemType(BinaryUtils.TypeDateTimeHolder, w => new DateTimeHolder(w),
serializer: new DateTimeSerializer());
AddSystemType(BinaryUtils.TypeCacheEntryProcessorHolder, w => new CacheEntryProcessorHolder(w));
AddSystemType(BinaryUtils.TypeCacheEntryPredicateHolder, w => new CacheEntryFilterHolder(w));
AddSystemType(BinaryUtils.TypeMessageListenerHolder, w => new MessageListenerHolder(w));
AddSystemType(BinaryUtils.TypeStreamReceiverHolder, w => new StreamReceiverHolder(w));
AddSystemType(0, w => new AffinityKey(w), "affKey");
AddSystemType(BinaryUtils.TypePlatformJavaObjectFactoryProxy, w => new PlatformJavaObjectFactoryProxy());
AddSystemType(0, w => new ObjectInfoHolder(w));
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2011 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using NUnit.Framework.Constraints;
using NUnit.Framework.Internal;
namespace NUnit.Framework
{
/// <summary>
/// The Assert class contains a collection of static methods that
/// implement the most common assertions used in NUnit.
/// </summary>
public partial class Assert
{
#region Assert.That
#region Boolean
/// <summary>
/// Asserts that a condition is true. If the condition is false the method throws
/// an <see cref="AssertionException"/>.
/// </summary>
/// <param name="condition">The evaluated condition</param>
/// <param name="message">The message to display if the condition is false</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public static void That(bool condition, string message, params object[] args)
{
Assert.That(condition, Is.True, message, args);
}
/// <summary>
/// Asserts that a condition is true. If the condition is false the method throws
/// an <see cref="AssertionException"/>.
/// </summary>
/// <param name="condition">The evaluated condition</param>
public static void That(bool condition)
{
Assert.That(condition, Is.True, null, null);
}
#if !NET_2_0
/// <summary>
/// Asserts that a condition is true. If the condition is false the method throws
/// an <see cref="AssertionException"/>.
/// </summary>
/// <param name="condition">The evaluated condition</param>
/// <param name="getExceptionMessage">A function to build the message included with the Exception</param>
public static void That(bool condition, Func<string> getExceptionMessage)
{
Assert.That(condition, Is.True, getExceptionMessage);
}
#endif
#endregion
#region Lambda returning Boolean
#if !NET_2_0
/// <summary>
/// Asserts that a condition is true. If the condition is false the method throws
/// an <see cref="AssertionException"/>.
/// </summary>
/// <param name="condition">A lambda that returns a Boolean</param>
/// <param name="message">The message to display if the condition is false</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public static void That(Func<bool> condition, string message, params object[] args)
{
Assert.That(condition.Invoke(), Is.True, message, args);
}
/// <summary>
/// Asserts that a condition is true. If the condition is false the method throws
/// an <see cref="AssertionException"/>.
/// </summary>
/// <param name="condition">A lambda that returns a Boolean</param>
public static void That(Func<bool> condition)
{
Assert.That(condition.Invoke(), Is.True, null, null);
}
/// <summary>
/// Asserts that a condition is true. If the condition is false the method throws
/// an <see cref="AssertionException"/>.
/// </summary>
/// <param name="condition">A lambda that returns a Boolean</param>
/// <param name="getExceptionMessage">A function to build the message included with the Exception</param>
public static void That(Func<bool> condition, Func<string> getExceptionMessage)
{
Assert.That(condition.Invoke(), Is.True, getExceptionMessage);
}
#endif
#endregion
#region ActualValueDelegate
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// </summary>
/// <typeparam name="TActual">The Type being compared.</typeparam>
/// <param name="del">An ActualValueDelegate returning the value to be tested</param>
/// <param name="expr">A Constraint expression to be applied</param>
public static void That<TActual>(ActualValueDelegate<TActual> del, IResolveConstraint expr)
{
Assert.That(del, expr.Resolve(), null, null);
}
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// </summary>
/// <typeparam name="TActual">The Type being compared.</typeparam>
/// <param name="del">An ActualValueDelegate returning the value to be tested</param>
/// <param name="expr">A Constraint expression to be applied</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public static void That<TActual>(ActualValueDelegate<TActual> del, IResolveConstraint expr, string message, params object[] args)
{
var constraint = expr.Resolve();
IncrementAssertCount();
var result = constraint.ApplyTo(del);
if (!result.IsSuccess)
{
MessageWriter writer = new TextMessageWriter(message, args);
result.WriteMessageTo(writer);
throw new AssertionException(writer.ToString());
}
}
#if !NET_2_0
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// </summary>
/// <typeparam name="TActual">The Type being compared.</typeparam>
/// <param name="del">An ActualValueDelegate returning the value to be tested</param>
/// <param name="expr">A Constraint expression to be applied</param>
/// <param name="getExceptionMessage">A function to build the message included with the Exception</param>
public static void That<TActual>(
ActualValueDelegate<TActual> del,
IResolveConstraint expr,
Func<string> getExceptionMessage)
{
var constraint = expr.Resolve();
IncrementAssertCount();
var result = constraint.ApplyTo(del);
if (!result.IsSuccess)
{
throw new AssertionException(getExceptionMessage());
}
}
#endif
#endregion
#region TestDelegate
/// <summary>
/// Asserts that the code represented by a delegate throws an exception
/// that satisfies the constraint provided.
/// </summary>
/// <param name="code">A TestDelegate to be executed</param>
/// <param name="constraint">A ThrowsConstraint used in the test</param>
public static void That(TestDelegate code, IResolveConstraint constraint)
{
Assert.That(code, constraint, null, null);
}
/// <summary>
/// Asserts that the code represented by a delegate throws an exception
/// that satisfies the constraint provided.
/// </summary>
/// <param name="code">A TestDelegate to be executed</param>
/// <param name="constraint">A ThrowsConstraint used in the test</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public static void That(TestDelegate code, IResolveConstraint constraint, string message, params object[] args)
{
Assert.That((object)code, constraint, message, args);
}
#if !NET_2_0
/// <summary>
/// Asserts that the code represented by a delegate throws an exception
/// that satisfies the constraint provided.
/// </summary>
/// <param name="code">A TestDelegate to be executed</param>
/// <param name="constraint">A ThrowsConstraint used in the test</param>
/// <param name="getExceptionMessage">A function to build the message included with the Exception</param>
public static void That(TestDelegate code, IResolveConstraint constraint, Func<string> getExceptionMessage)
{
Assert.That((object)code, constraint, getExceptionMessage);
}
#endif
#endregion
#endregion
#region Assert.That<TActual>
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// </summary>
/// <typeparam name="TActual">The Type being compared.</typeparam>
/// <param name="actual">The actual value to test</param>
/// <param name="expression">A Constraint to be applied</param>
public static void That<TActual>(TActual actual, IResolveConstraint expression)
{
Assert.That(actual, expression, null, null);
}
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// </summary>
/// <typeparam name="TActual">The Type being compared.</typeparam>
/// <param name="actual">The actual value to test</param>
/// <param name="expression">A Constraint expression to be applied</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public static void That<TActual>(TActual actual, IResolveConstraint expression, string message, params object[] args)
{
var constraint = expression.Resolve();
IncrementAssertCount();
var result = constraint.ApplyTo(actual);
if (!result.IsSuccess)
{
MessageWriter writer = new TextMessageWriter(message, args);
result.WriteMessageTo(writer);
throw new AssertionException(writer.ToString());
}
}
#if !NET_2_0
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// </summary>
/// <typeparam name="TActual">The Type being compared.</typeparam>
/// <param name="actual">The actual value to test</param>
/// <param name="expression">A Constraint expression to be applied</param>
/// <param name="getExceptionMessage">A function to build the message included with the Exception</param>
public static void That<TActual>(
TActual actual,
IResolveConstraint expression,
Func<string> getExceptionMessage)
{
var constraint = expression.Resolve();
IncrementAssertCount();
var result = constraint.ApplyTo(actual);
if (!result.IsSuccess)
{
throw new AssertionException(getExceptionMessage());
}
}
#endif
#endregion
#region Assert.ByVal
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// Used as a synonym for That in rare cases where a private setter
/// causes a Visual Basic compilation error.
/// </summary>
/// <param name="actual">The actual value to test</param>
/// <param name="expression">A Constraint to be applied</param>
public static void ByVal(object actual, IResolveConstraint expression)
{
Assert.That(actual, expression, null, null);
}
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// Used as a synonym for That in rare cases where a private setter
/// causes a Visual Basic compilation error.
/// </summary>
/// <remarks>
/// This method is provided for use by VB developers needing to test
/// the value of properties with private setters.
/// </remarks>
/// <param name="actual">The actual value to test</param>
/// <param name="expression">A Constraint expression to be applied</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public static void ByVal(object actual, IResolveConstraint expression, string message, params object[] args)
{
Assert.That(actual, expression, message, args);
}
#endregion
}
}
| |
using Microsoft.CodeAnalysis;
using Semmle.Extraction.CSharp.Populators;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Semmle.Extraction.Entities;
using System.IO;
using System;
namespace Semmle.Extraction.CSharp.Entities
{
internal class Parameter : CachedSymbol<IParameterSymbol>, IExpressionParentEntity
{
protected IEntity? Parent { get; set; }
protected Parameter Original { get; }
protected Parameter(Context cx, IParameterSymbol init, IEntity? parent, Parameter? original)
: base(cx, init)
{
Parent = parent;
Original = original ?? this;
}
public override Microsoft.CodeAnalysis.Location ReportingLocation => Symbol.GetSymbolLocation();
public enum Kind
{
None, Ref, Out, Params, This, In
}
protected virtual int Ordinal => Symbol.Ordinal;
private Kind ParamKind
{
get
{
switch (Symbol.RefKind)
{
case RefKind.Out:
return Kind.Out;
case RefKind.Ref:
return Kind.Ref;
case RefKind.In:
return Kind.In;
default:
if (Symbol.IsParams)
return Kind.Params;
if (Ordinal == 0)
{
if (Symbol.ContainingSymbol is IMethodSymbol method && method.IsExtensionMethod)
return Kind.This;
}
return Kind.None;
}
}
}
public static Parameter Create(Context cx, IParameterSymbol param, IEntity parent, Parameter? original = null)
{
var cachedSymbol = cx.GetPossiblyCachedParameterSymbol(param);
return ParameterFactory.Instance.CreateEntity(cx, cachedSymbol, (cachedSymbol, parent, original));
}
public static Parameter Create(Context cx, IParameterSymbol param)
{
var cachedSymbol = cx.GetPossiblyCachedParameterSymbol(param);
return ParameterFactory.Instance.CreateEntity(cx, cachedSymbol, (cachedSymbol, null, null));
}
public override void WriteId(EscapingTextWriter trapFile)
{
if (Parent is null)
Parent = Method.Create(Context, Symbol.ContainingSymbol as IMethodSymbol);
if (Parent is null)
throw new InternalError(Symbol, "Couldn't get parent of symbol.");
trapFile.WriteSubId(Parent);
trapFile.Write('_');
trapFile.Write(Ordinal);
trapFile.Write(";parameter");
}
public override bool NeedsPopulation => true;
private string Name
{
get
{
// Very rarely, two parameters have the same name according to the data model.
// This breaks our database constraints.
// Generate an impossible name to ensure that it doesn't conflict.
var conflictingCount = Symbol.ContainingSymbol.GetParameters().Count(p => p.Ordinal < Symbol.Ordinal && p.Name == Symbol.Name);
return conflictingCount > 0 ? Symbol.Name + "`" + conflictingCount : Symbol.Name;
}
}
public override void Populate(TextWriter trapFile)
{
PopulateAttributes();
PopulateNullability(trapFile, Symbol.GetAnnotatedType());
PopulateRefKind(trapFile, Symbol.RefKind);
if (Symbol.Name != Original.Symbol.Name)
Context.ModelError(Symbol, "Inconsistent parameter declaration");
var type = Type.Create(Context, Symbol.Type);
trapFile.@params(this, Name, type.TypeRef, Ordinal, ParamKind, Parent!, Original);
foreach (var l in Symbol.Locations)
trapFile.param_location(this, Context.CreateLocation(l));
if (!Symbol.Locations.Any() &&
Symbol.ContainingSymbol is IMethodSymbol ms &&
ms.Name == WellKnownMemberNames.TopLevelStatementsEntryPointMethodName &&
ms.ContainingType.Name == WellKnownMemberNames.TopLevelStatementsEntryPointTypeName)
{
trapFile.param_location(this, Context.CreateLocation());
}
if (Symbol.HasExplicitDefaultValue && Context.Defines(Symbol))
{
var defaultValueSyntax = GetDefaultValueFromSyntax(Symbol);
Action defaultValueExpressionCreation = defaultValueSyntax is not null
? () => Expression.Create(Context, defaultValueSyntax.Value, this, 0)
: () => Expression.CreateGenerated(Context, Symbol, this, 0, Location);
Context.PopulateLater(defaultValueExpressionCreation);
}
if (!IsSourceDeclaration || !Symbol.FromSource())
return;
BindComments();
if (IsSourceDeclaration)
{
foreach (var syntax in Symbol.DeclaringSyntaxReferences
.Select(d => d.GetSyntax())
.OfType<ParameterSyntax>()
.Where(s => s.Type is not null))
{
TypeMention.Create(Context, syntax.Type!, this, type);
}
}
}
private static EqualsValueClauseSyntax? GetDefaultValueFromSyntax(IParameterSymbol symbol)
{
// This is a slight bug in the dbscheme
// We should really define param_default(param, string)
// And use parameter child #0 to encode the default expression.
var defaultValue = GetParameterDefaultValue(symbol);
if (defaultValue is null)
{
// In case this parameter belongs to an accessor of an indexer, we need
// to get the default value from the corresponding parameter belonging
// to the indexer itself
if (symbol.ContainingSymbol is IMethodSymbol method)
{
var i = method.Parameters.IndexOf(symbol);
if (method.AssociatedSymbol is IPropertySymbol indexer)
defaultValue = GetParameterDefaultValue(indexer.Parameters[i]);
}
}
return defaultValue;
}
public override bool IsSourceDeclaration => Symbol.IsSourceDeclaration();
bool IExpressionParentEntity.IsTopLevelParent => true;
private static EqualsValueClauseSyntax? GetParameterDefaultValue(IParameterSymbol parameter)
{
var syntax = parameter.DeclaringSyntaxReferences.Select(@ref => @ref.GetSyntax()).OfType<ParameterSyntax>().FirstOrDefault();
return syntax?.Default;
}
private class ParameterFactory : CachedEntityFactory<(IParameterSymbol, IEntity?, Parameter?), Parameter>
{
public static ParameterFactory Instance { get; } = new ParameterFactory();
public override Parameter Create(Context cx, (IParameterSymbol, IEntity?, Parameter?) init) => new Parameter(cx, init.Item1, init.Item2, init.Item3);
}
public override TrapStackBehaviour TrapStackBehaviour => TrapStackBehaviour.OptionalLabel;
}
internal class VarargsType : Type
{
private VarargsType(Context cx)
: base(cx, null) { }
public override void Populate(TextWriter trapFile)
{
trapFile.types(this, Kinds.TypeKind.ARGLIST, "__arglist");
trapFile.parent_namespace(this, Namespace.Create(Context, Context.Compilation.GlobalNamespace));
Modifier.HasModifier(Context, trapFile, this, "public");
}
public override bool NeedsPopulation => true;
public override void WriteId(EscapingTextWriter trapFile)
{
trapFile.Write("__arglist;type");
}
public override int GetHashCode()
{
return 98735267;
}
public override bool Equals(object? obj)
{
return obj is not null && obj.GetType() == typeof(VarargsType);
}
public static VarargsType Create(Context cx) => VarargsTypeFactory.Instance.CreateEntity(cx, typeof(VarargsType), null);
private class VarargsTypeFactory : CachedEntityFactory<string?, VarargsType>
{
public static VarargsTypeFactory Instance { get; } = new VarargsTypeFactory();
public override VarargsType Create(Context cx, string? init) => new VarargsType(cx);
}
}
internal class VarargsParam : Parameter
{
#nullable disable warnings
private VarargsParam(Context cx, Method methodKey)
: base(cx, null, methodKey, null) { }
#nullable restore warnings
public override void Populate(TextWriter trapFile)
{
var typeKey = VarargsType.Create(Context);
// !! Maybe originaldefinition is wrong
trapFile.@params(this, "", typeKey, Ordinal, Kind.None, Parent!, this);
trapFile.param_location(this, GeneratedLocation.Create(Context));
}
protected override int Ordinal => ((Method)Parent!).OriginalDefinition.Symbol.Parameters.Length;
public override int GetHashCode()
{
return 9873567;
}
public override bool Equals(object? obj)
{
return obj is not null && obj.GetType() == typeof(VarargsParam);
}
public static VarargsParam Create(Context cx, Method method) => VarargsParamFactory.Instance.CreateEntity(cx, typeof(VarargsParam), method);
private class VarargsParamFactory : CachedEntityFactory<Method, VarargsParam>
{
public static VarargsParamFactory Instance { get; } = new VarargsParamFactory();
public override VarargsParam Create(Context cx, Method init) => new VarargsParam(cx, init);
}
}
}
| |
namespace Oort.AzureStorage.Mockable
{
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
public class OortTable : ICloudTable
{
private readonly CloudTable _cloudTable;
public TableResult Execute(TableOperation operation, TableRequestOptions requestOptions = null,
OperationContext operationContext = null)
{
return _cloudTable.Execute(operation, requestOptions, operationContext);
}
public ICancellableAsyncResult BeginExecute(TableOperation operation, AsyncCallback callback, object state)
{
return _cloudTable.BeginExecute(operation, callback, state);
}
public ICancellableAsyncResult BeginExecute(TableOperation operation, TableRequestOptions requestOptions,
OperationContext operationContext, AsyncCallback callback, object state)
{
return _cloudTable.BeginExecute(operation, requestOptions, operationContext, callback, state);
}
public TableResult EndExecute(IAsyncResult asyncResult)
{
return _cloudTable.EndExecute(asyncResult);
}
public Task<TableResult> ExecuteAsync(TableOperation operation)
{
return _cloudTable.ExecuteAsync(operation);
}
public Task<TableResult> ExecuteAsync(TableOperation operation, CancellationToken cancellationToken)
{
return _cloudTable.ExecuteAsync(operation, cancellationToken);
}
public Task<TableResult> ExecuteAsync(TableOperation operation, TableRequestOptions requestOptions, OperationContext operationContext)
{
return _cloudTable.ExecuteAsync(operation, requestOptions, operationContext);
}
public Task<TableResult> ExecuteAsync(TableOperation operation, TableRequestOptions requestOptions, OperationContext operationContext,
CancellationToken cancellationToken)
{
return _cloudTable.ExecuteAsync(operation, requestOptions, operationContext, cancellationToken);
}
public IList<TableResult> ExecuteBatch(TableBatchOperation batch, TableRequestOptions requestOptions = null,
OperationContext operationContext = null)
{
return _cloudTable.ExecuteBatch(batch, requestOptions, operationContext);
}
public ICancellableAsyncResult BeginExecuteBatch(TableBatchOperation batch, AsyncCallback callback, object state)
{
return _cloudTable.BeginExecuteBatch(batch, callback, state);
}
public ICancellableAsyncResult BeginExecuteBatch(TableBatchOperation batch, TableRequestOptions requestOptions,
OperationContext operationContext, AsyncCallback callback, object state)
{
return _cloudTable.BeginExecuteBatch(batch, requestOptions, operationContext, callback, state);
}
public IList<TableResult> EndExecuteBatch(IAsyncResult asyncResult)
{
return _cloudTable.EndExecuteBatch(asyncResult);
}
public Task<IList<TableResult>> ExecuteBatchAsync(TableBatchOperation batch)
{
return _cloudTable.ExecuteBatchAsync(batch);
}
public Task<IList<TableResult>> ExecuteBatchAsync(TableBatchOperation batch, CancellationToken cancellationToken)
{
return _cloudTable.ExecuteBatchAsync(batch, cancellationToken);
}
public Task<IList<TableResult>> ExecuteBatchAsync(TableBatchOperation batch, TableRequestOptions requestOptions, OperationContext operationContext)
{
return _cloudTable.ExecuteBatchAsync(batch, requestOptions, operationContext);
}
public Task<IList<TableResult>> ExecuteBatchAsync(TableBatchOperation batch, TableRequestOptions requestOptions, OperationContext operationContext,
CancellationToken cancellationToken)
{
return _cloudTable.ExecuteBatchAsync(batch, requestOptions, operationContext, cancellationToken);
}
public IEnumerable<DynamicTableEntity> ExecuteQuery(TableQuery query, TableRequestOptions requestOptions = null,
OperationContext operationContext = null)
{
return _cloudTable.ExecuteQuery(query, requestOptions, operationContext);
}
public TableQuerySegment<DynamicTableEntity> ExecuteQuerySegmented(TableQuery query, TableContinuationToken token,
TableRequestOptions requestOptions = null, OperationContext operationContext = null)
{
return _cloudTable.ExecuteQuerySegmented(query, token, requestOptions, operationContext);
}
public ICancellableAsyncResult BeginExecuteQuerySegmented(TableQuery query, TableContinuationToken token,
AsyncCallback callback, object state)
{
return _cloudTable.BeginExecuteQuerySegmented(query, token, callback, state);
}
public ICancellableAsyncResult BeginExecuteQuerySegmented(TableQuery query, TableContinuationToken token,
TableRequestOptions requestOptions, OperationContext operationContext, AsyncCallback callback, object state)
{
return _cloudTable.BeginExecuteQuerySegmented(query, token, requestOptions, operationContext, callback, state);
}
public TableQuerySegment<DynamicTableEntity> EndExecuteQuerySegmented(IAsyncResult asyncResult)
{
return _cloudTable.EndExecuteQuerySegmented(asyncResult);
}
public Task<TableQuerySegment<DynamicTableEntity>> ExecuteQuerySegmentedAsync(TableQuery query, TableContinuationToken token)
{
return _cloudTable.ExecuteQuerySegmentedAsync(query, token);
}
public Task<TableQuerySegment<DynamicTableEntity>> ExecuteQuerySegmentedAsync(TableQuery query, TableContinuationToken token, CancellationToken cancellationToken)
{
return _cloudTable.ExecuteQuerySegmentedAsync(query, token, cancellationToken);
}
public Task<TableQuerySegment<DynamicTableEntity>> ExecuteQuerySegmentedAsync(TableQuery query, TableContinuationToken token, TableRequestOptions requestOptions,
OperationContext operationContext)
{
return _cloudTable.ExecuteQuerySegmentedAsync(query, token, requestOptions, operationContext);
}
public Task<TableQuerySegment<DynamicTableEntity>> ExecuteQuerySegmentedAsync(TableQuery query, TableContinuationToken token, TableRequestOptions requestOptions,
OperationContext operationContext, CancellationToken cancellationToken)
{
return _cloudTable.ExecuteQuerySegmentedAsync(query, token, requestOptions, operationContext, cancellationToken);
}
public IEnumerable<TResult> ExecuteQuery<TResult>(TableQuery query, EntityResolver<TResult> resolver, TableRequestOptions requestOptions = null,
OperationContext operationContext = null)
{
return _cloudTable.ExecuteQuery(query, resolver, requestOptions, operationContext);
}
public TableQuerySegment<TResult> ExecuteQuerySegmented<TResult>(TableQuery query, EntityResolver<TResult> resolver, TableContinuationToken token,
TableRequestOptions requestOptions = null, OperationContext operationContext = null)
{
return _cloudTable.ExecuteQuerySegmented(query, resolver, token, requestOptions, operationContext);
}
public ICancellableAsyncResult BeginExecuteQuerySegmented<TResult>(TableQuery query, EntityResolver<TResult> resolver,
TableContinuationToken token, AsyncCallback callback, object state)
{
return _cloudTable.BeginExecuteQuerySegmented(query, resolver, token, callback, state);
}
public ICancellableAsyncResult BeginExecuteQuerySegmented<TResult>(TableQuery query, EntityResolver<TResult> resolver,
TableContinuationToken token, TableRequestOptions requestOptions, OperationContext operationContext,
AsyncCallback callback, object state)
{
return _cloudTable.BeginExecuteQuerySegmented(query, resolver, token, requestOptions, operationContext, callback, state);
}
public Task<TableQuerySegment<TResult>> ExecuteQuerySegmentedAsync<TResult>(TableQuery query, EntityResolver<TResult> resolver, TableContinuationToken token)
{
return _cloudTable.ExecuteQuerySegmentedAsync(query, resolver, token);
}
public Task<TableQuerySegment<TResult>> ExecuteQuerySegmentedAsync<TResult>(TableQuery query, EntityResolver<TResult> resolver, TableContinuationToken token,
CancellationToken cancellationToken)
{
return _cloudTable.ExecuteQuerySegmentedAsync(query, resolver, token, cancellationToken);
}
public Task<TableQuerySegment<TResult>> ExecuteQuerySegmentedAsync<TResult>(TableQuery query, EntityResolver<TResult> resolver, TableContinuationToken token,
TableRequestOptions requestOptions, OperationContext operationContext)
{
return _cloudTable.ExecuteQuerySegmentedAsync(query, resolver, token, requestOptions, operationContext);
}
public Task<TableQuerySegment<TResult>> ExecuteQuerySegmentedAsync<TResult>(TableQuery query, EntityResolver<TResult> resolver, TableContinuationToken token,
TableRequestOptions requestOptions, OperationContext operationContext, CancellationToken cancellationToken)
{
return _cloudTable.ExecuteQuerySegmentedAsync(query, resolver, token, requestOptions, operationContext, cancellationToken);
}
public TableQuery<TElement> CreateQuery<TElement>() where TElement : ITableEntity, new()
{
return _cloudTable.CreateQuery<TElement>();
}
public IEnumerable<TElement> ExecuteQuery<TElement>(TableQuery<TElement> query, TableRequestOptions requestOptions = null,
OperationContext operationContext = null) where TElement : ITableEntity, new()
{
return _cloudTable.ExecuteQuery(query, requestOptions, operationContext);
}
public TableQuerySegment<TElement> ExecuteQuerySegmented<TElement>(TableQuery<TElement> query, TableContinuationToken token,
TableRequestOptions requestOptions = null, OperationContext operationContext = null) where TElement : ITableEntity, new()
{
return _cloudTable.ExecuteQuerySegmented(query, token, requestOptions, operationContext);
}
public ICancellableAsyncResult BeginExecuteQuerySegmented<TElement>(TableQuery<TElement> query, TableContinuationToken token,
AsyncCallback callback, object state) where TElement : ITableEntity, new()
{
return _cloudTable.BeginExecuteQuerySegmented(query, token, callback, state);
}
public ICancellableAsyncResult BeginExecuteQuerySegmented<TElement>(TableQuery<TElement> query, TableContinuationToken token,
TableRequestOptions requestOptions, OperationContext operationContext, AsyncCallback callback, object state) where TElement : ITableEntity, new()
{
return _cloudTable.BeginExecuteQuerySegmented(query, token, requestOptions, operationContext, callback, state);
}
public TableQuerySegment<TResult> EndExecuteQuerySegmented<TResult>(IAsyncResult asyncResult)
{
return _cloudTable.EndExecuteQuerySegmented<TResult>(asyncResult);
}
public Task<TableQuerySegment<TElement>> ExecuteQuerySegmentedAsync<TElement>(TableQuery<TElement> query, TableContinuationToken token) where TElement : ITableEntity, new()
{
return _cloudTable.ExecuteQuerySegmentedAsync(query, token);
}
public Task<TableQuerySegment<TElement>> ExecuteQuerySegmentedAsync<TElement>(TableQuery<TElement> query, TableContinuationToken token,
CancellationToken cancellationToken) where TElement : ITableEntity, new()
{
return _cloudTable.ExecuteQuerySegmentedAsync(query, token, cancellationToken);
}
public Task<TableQuerySegment<TElement>> ExecuteQuerySegmentedAsync<TElement>(TableQuery<TElement> query, TableContinuationToken token,
TableRequestOptions requestOptions, OperationContext operationContext) where TElement : ITableEntity, new()
{
return _cloudTable.ExecuteQuerySegmentedAsync(query, token, requestOptions, operationContext);
}
public Task<TableQuerySegment<TElement>> ExecuteQuerySegmentedAsync<TElement>(TableQuery<TElement> query, TableContinuationToken token,
TableRequestOptions requestOptions, OperationContext operationContext, CancellationToken cancellationToken) where TElement : ITableEntity, new()
{
return _cloudTable.ExecuteQuerySegmentedAsync(query, token, requestOptions, operationContext, cancellationToken);
}
public IEnumerable<TResult> ExecuteQuery<TElement, TResult>(TableQuery<TElement> query, EntityResolver<TResult> resolver,
TableRequestOptions requestOptions = null, OperationContext operationContext = null) where TElement : ITableEntity, new()
{
return _cloudTable.ExecuteQuery(query, resolver, requestOptions, operationContext);
}
public TableQuerySegment<TResult> ExecuteQuerySegmented<TElement, TResult>(TableQuery<TElement> query, EntityResolver<TResult> resolver,
TableContinuationToken token, TableRequestOptions requestOptions = null, OperationContext operationContext = null) where TElement : ITableEntity, new()
{
return _cloudTable.ExecuteQuerySegmented(query, resolver, token, requestOptions, operationContext);
}
public ICancellableAsyncResult BeginExecuteQuerySegmented<TElement, TResult>(TableQuery<TElement> query, EntityResolver<TResult> resolver,
TableContinuationToken token, AsyncCallback callback, object state) where TElement : ITableEntity, new()
{
return _cloudTable.BeginExecuteQuerySegmented(query, resolver, token, callback, state);
}
public ICancellableAsyncResult BeginExecuteQuerySegmented<TElement, TResult>(TableQuery<TElement> query, EntityResolver<TResult> resolver,
TableContinuationToken token, TableRequestOptions requestOptions, OperationContext operationContext,
AsyncCallback callback, object state) where TElement : ITableEntity, new()
{
return _cloudTable.BeginExecuteQuerySegmented(query, resolver, token, requestOptions, operationContext, callback, state);
}
public TableQuerySegment<TResult> EndExecuteQuerySegmented<TElement, TResult>(IAsyncResult asyncResult) where TElement : ITableEntity, new()
{
return _cloudTable.EndExecuteQuerySegmented<TElement, TResult>(asyncResult);
}
public Task<TableQuerySegment<TResult>> ExecuteQuerySegmentedAsync<TElement, TResult>(TableQuery<TElement> query, EntityResolver<TResult> resolver,
TableContinuationToken token) where TElement : ITableEntity, new()
{
return _cloudTable.ExecuteQuerySegmentedAsync(query, resolver, token);
}
public Task<TableQuerySegment<TResult>> ExecuteQuerySegmentedAsync<TElement, TResult>(TableQuery<TElement> query, EntityResolver<TResult> resolver,
TableContinuationToken token, CancellationToken cancellationToken) where TElement : ITableEntity, new()
{
return _cloudTable.ExecuteQuerySegmentedAsync(query, resolver, token, cancellationToken);
}
public Task<TableQuerySegment<TResult>> ExecuteQuerySegmentedAsync<TElement, TResult>(TableQuery<TElement> query, EntityResolver<TResult> resolver,
TableContinuationToken token, TableRequestOptions requestOptions, OperationContext operationContext) where TElement : ITableEntity, new()
{
return _cloudTable.ExecuteQuerySegmentedAsync(query, resolver, token, requestOptions, operationContext);
}
public Task<TableQuerySegment<TResult>> ExecuteQuerySegmentedAsync<TElement, TResult>(TableQuery<TElement> query, EntityResolver<TResult> resolver,
TableContinuationToken token, TableRequestOptions requestOptions, OperationContext operationContext,
CancellationToken cancellationToken) where TElement : ITableEntity, new()
{
return _cloudTable.ExecuteQuerySegmentedAsync(query, resolver, token, requestOptions, operationContext, cancellationToken);
}
public void Create(TableRequestOptions requestOptions = null, OperationContext operationContext = null)
{
_cloudTable.Create(requestOptions, operationContext);
}
public ICancellableAsyncResult BeginCreate(AsyncCallback callback, object state)
{
return _cloudTable.BeginCreate(callback, state);
}
public ICancellableAsyncResult BeginCreate(TableRequestOptions requestOptions, OperationContext operationContext,
AsyncCallback callback, object state)
{
return _cloudTable.BeginCreate(requestOptions, operationContext, callback, state);
}
public void EndCreate(IAsyncResult asyncResult)
{
_cloudTable.EndCreate(asyncResult);
}
public Task CreateAsync()
{
return _cloudTable.CreateAsync();
}
public Task CreateAsync(CancellationToken cancellationToken)
{
return _cloudTable.CreateAsync(cancellationToken);
}
public Task CreateAsync(TableRequestOptions requestOptions, OperationContext operationContext)
{
return _cloudTable.CreateAsync(requestOptions, operationContext);
}
public Task CreateAsync(TableRequestOptions requestOptions, OperationContext operationContext,
CancellationToken cancellationToken)
{
return _cloudTable.CreateAsync(requestOptions, operationContext, cancellationToken);
}
public bool CreateIfNotExists(TableRequestOptions requestOptions = null, OperationContext operationContext = null)
{
return _cloudTable.CreateIfNotExists(requestOptions, operationContext);
}
public ICancellableAsyncResult BeginCreateIfNotExists(AsyncCallback callback, object state)
{
return _cloudTable.BeginCreateIfNotExists(callback, state);
}
public ICancellableAsyncResult BeginCreateIfNotExists(TableRequestOptions requestOptions, OperationContext operationContext,
AsyncCallback callback, object state)
{
return _cloudTable.BeginCreateIfNotExists(requestOptions, operationContext, callback, state);
}
public bool EndCreateIfNotExists(IAsyncResult asyncResult)
{
return _cloudTable.EndCreateIfNotExists(asyncResult);
}
public Task<bool> CreateIfNotExistsAsync()
{
return _cloudTable.CreateIfNotExistsAsync();
}
public Task<bool> CreateIfNotExistsAsync(CancellationToken cancellationToken)
{
return _cloudTable.CreateIfNotExistsAsync(cancellationToken);
}
public Task<bool> CreateIfNotExistsAsync(TableRequestOptions requestOptions, OperationContext operationContext)
{
return _cloudTable.CreateIfNotExistsAsync(requestOptions, operationContext);
}
public Task<bool> CreateIfNotExistsAsync(TableRequestOptions requestOptions, OperationContext operationContext,
CancellationToken cancellationToken)
{
return _cloudTable.CreateIfNotExistsAsync(requestOptions, operationContext, cancellationToken);
}
public void Delete(TableRequestOptions requestOptions = null, OperationContext operationContext = null)
{
_cloudTable.Delete(requestOptions, operationContext);
}
public ICancellableAsyncResult BeginDelete(AsyncCallback callback, object state)
{
return _cloudTable.BeginDelete(callback, state);
}
public ICancellableAsyncResult BeginDelete(TableRequestOptions requestOptions, OperationContext operationContext,
AsyncCallback callback, object state)
{
return _cloudTable.BeginDelete(requestOptions, operationContext, callback, state);
}
public void EndDelete(IAsyncResult asyncResult)
{
_cloudTable.EndDelete(asyncResult);
}
public Task DeleteAsync()
{
return _cloudTable.DeleteAsync();
}
public Task DeleteAsync(CancellationToken cancellationToken)
{
return _cloudTable.DeleteAsync(cancellationToken);
}
public Task DeleteAsync(TableRequestOptions requestOptions, OperationContext operationContext)
{
return _cloudTable.DeleteAsync(requestOptions, operationContext);
}
public Task DeleteAsync(TableRequestOptions requestOptions, OperationContext operationContext,
CancellationToken cancellationToken)
{
return _cloudTable.DeleteAsync(requestOptions, operationContext, cancellationToken);
}
public bool DeleteIfExists(TableRequestOptions requestOptions = null, OperationContext operationContext = null)
{
return _cloudTable.DeleteIfExists(requestOptions, operationContext);
}
public ICancellableAsyncResult BeginDeleteIfExists(AsyncCallback callback, object state)
{
return _cloudTable.BeginDeleteIfExists(callback, state);
}
public ICancellableAsyncResult BeginDeleteIfExists(TableRequestOptions requestOptions, OperationContext operationContext,
AsyncCallback callback, object state)
{
return _cloudTable.BeginDeleteIfExists(requestOptions, operationContext, callback, state);
}
public bool EndDeleteIfExists(IAsyncResult asyncResult)
{
return _cloudTable.EndDeleteIfExists(asyncResult);
}
public Task<bool> DeleteIfExistsAsync()
{
return _cloudTable.DeleteIfExistsAsync();
}
public Task<bool> DeleteIfExistsAsync(CancellationToken cancellationToken)
{
return _cloudTable.DeleteIfExistsAsync(cancellationToken);
}
public Task<bool> DeleteIfExistsAsync(TableRequestOptions requestOptions, OperationContext operationContext)
{
return _cloudTable.DeleteIfExistsAsync(requestOptions, operationContext);
}
public Task<bool> DeleteIfExistsAsync(TableRequestOptions requestOptions, OperationContext operationContext,
CancellationToken cancellationToken)
{
return _cloudTable.DeleteIfExistsAsync(requestOptions, operationContext, cancellationToken);
}
public bool Exists(TableRequestOptions requestOptions = null, OperationContext operationContext = null)
{
return _cloudTable.Exists(requestOptions, operationContext);
}
public ICancellableAsyncResult BeginExists(AsyncCallback callback, object state)
{
return _cloudTable.BeginExists(callback, state);
}
public ICancellableAsyncResult BeginExists(TableRequestOptions requestOptions, OperationContext operationContext,
AsyncCallback callback, object state)
{
return _cloudTable.BeginExists(requestOptions, operationContext, callback, state);
}
public bool EndExists(IAsyncResult asyncResult)
{
return _cloudTable.EndExists(asyncResult);
}
public Task<bool> ExistsAsync()
{
return _cloudTable.ExistsAsync();
}
public Task<bool> ExistsAsync(CancellationToken cancellationToken)
{
return _cloudTable.ExistsAsync(cancellationToken);
}
public Task<bool> ExistsAsync(TableRequestOptions requestOptions, OperationContext operationContext)
{
return _cloudTable.ExistsAsync(requestOptions, operationContext);
}
public Task<bool> ExistsAsync(TableRequestOptions requestOptions, OperationContext operationContext,
CancellationToken cancellationToken)
{
return _cloudTable.ExistsAsync(requestOptions, operationContext, cancellationToken);
}
public TablePermissions GetPermissions(TableRequestOptions requestOptions = null, OperationContext operationContext = null)
{
return _cloudTable.GetPermissions(requestOptions, operationContext);
}
public ICancellableAsyncResult BeginGetPermissions(AsyncCallback callback, object state)
{
return _cloudTable.BeginGetPermissions(callback, state);
}
public ICancellableAsyncResult BeginGetPermissions(TableRequestOptions requestOptions, OperationContext operationContext,
AsyncCallback callback, object state)
{
return _cloudTable.BeginGetPermissions(requestOptions, operationContext, callback, state);
}
public TablePermissions EndGetPermissions(IAsyncResult asyncResult)
{
return _cloudTable.EndGetPermissions(asyncResult);
}
public Task<TablePermissions> GetPermissionsAsync()
{
return _cloudTable.GetPermissionsAsync();
}
public Task<TablePermissions> GetPermissionsAsync(CancellationToken cancellationToken)
{
return _cloudTable.GetPermissionsAsync(cancellationToken);
}
public Task<TablePermissions> GetPermissionsAsync(TableRequestOptions requestOptions, OperationContext operationContext)
{
return _cloudTable.GetPermissionsAsync(requestOptions, operationContext);
}
public Task<TablePermissions> GetPermissionsAsync(TableRequestOptions requestOptions, OperationContext operationContext,
CancellationToken cancellationToken)
{
return _cloudTable.GetPermissionsAsync(requestOptions, operationContext, cancellationToken);
}
public void SetPermissions(TablePermissions permissions, TableRequestOptions requestOptions = null,
OperationContext operationContext = null)
{
_cloudTable.SetPermissions(permissions, requestOptions, operationContext);
}
public ICancellableAsyncResult BeginSetPermissions(TablePermissions permissions, AsyncCallback callback, object state)
{
return _cloudTable.BeginSetPermissions(permissions, callback, state);
}
public ICancellableAsyncResult BeginSetPermissions(TablePermissions permissions, TableRequestOptions requestOptions,
OperationContext operationContext, AsyncCallback callback, object state)
{
return _cloudTable.BeginSetPermissions(permissions, requestOptions, operationContext, callback, state);
}
public void EndSetPermissions(IAsyncResult asyncResult)
{
_cloudTable.EndSetPermissions(asyncResult);
}
public Task SetPermissionsAsync(TablePermissions permissions)
{
return _cloudTable.SetPermissionsAsync(permissions);
}
public Task SetPermissionsAsync(TablePermissions permissions, CancellationToken cancellationToken)
{
return _cloudTable.SetPermissionsAsync(permissions, cancellationToken);
}
public Task SetPermissionsAsync(TablePermissions permissions, TableRequestOptions requestOptions,
OperationContext operationContext)
{
return _cloudTable.SetPermissionsAsync(permissions, requestOptions, operationContext);
}
public Task SetPermissionsAsync(TablePermissions permissions, TableRequestOptions requestOptions,
OperationContext operationContext, CancellationToken cancellationToken)
{
return _cloudTable.SetPermissionsAsync(permissions, requestOptions, operationContext, cancellationToken);
}
public string GetSharedAccessSignature(SharedAccessTablePolicy policy, string accessPolicyIdentifier, string startPartitionKey,
string startRowKey, string endPartitionKey, string endRowKey)
{
return _cloudTable.GetSharedAccessSignature(policy, accessPolicyIdentifier, startPartitionKey, startRowKey, endPartitionKey, endRowKey);
}
public CloudTableClient ServiceClient
{
get { return _cloudTable.ServiceClient; }
}
public string Name
{
get { return _cloudTable.Name; }
}
public Uri Uri
{
get { return _cloudTable.Uri; }
}
public StorageUri StorageUri
{
get { return _cloudTable.StorageUri; }
}
public OortTable(CloudTable cloudTable)
{
_cloudTable = cloudTable;
}
}
}
| |
using System;
using System.Globalization;
using Avalonia.Utilities;
namespace Avalonia
{
/// <summary>
/// Represents a rectangle in device pixels.
/// </summary>
public readonly struct PixelRect : IEquatable<PixelRect>
{
/// <summary>
/// An empty rectangle.
/// </summary>
public static readonly PixelRect Empty = default;
/// <summary>
/// Initializes a new instance of the <see cref="PixelRect"/> structure.
/// </summary>
/// <param name="x">The X position.</param>
/// <param name="y">The Y position.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
public PixelRect(int x, int y, int width, int height)
{
X = x;
Y = y;
Width = width;
Height = height;
}
/// <summary>
/// Initializes a new instance of the <see cref="PixelRect"/> structure.
/// </summary>
/// <param name="size">The size of the rectangle.</param>
public PixelRect(PixelSize size)
{
X = 0;
Y = 0;
Width = size.Width;
Height = size.Height;
}
/// <summary>
/// Initializes a new instance of the <see cref="PixelRect"/> structure.
/// </summary>
/// <param name="position">The position of the rectangle.</param>
/// <param name="size">The size of the rectangle.</param>
public PixelRect(PixelPoint position, PixelSize size)
{
X = position.X;
Y = position.Y;
Width = size.Width;
Height = size.Height;
}
/// <summary>
/// Initializes a new instance of the <see cref="PixelRect"/> structure.
/// </summary>
/// <param name="topLeft">The top left position of the rectangle.</param>
/// <param name="bottomRight">The bottom right position of the rectangle.</param>
public PixelRect(PixelPoint topLeft, PixelPoint bottomRight)
{
X = topLeft.X;
Y = topLeft.Y;
Width = bottomRight.X - topLeft.X;
Height = bottomRight.Y - topLeft.Y;
}
/// <summary>
/// Gets the X position.
/// </summary>
public int X { get; }
/// <summary>
/// Gets the Y position.
/// </summary>
public int Y { get; }
/// <summary>
/// Gets the width.
/// </summary>
public int Width { get; }
/// <summary>
/// Gets the height.
/// </summary>
public int Height { get; }
/// <summary>
/// Gets the position of the rectangle.
/// </summary>
public PixelPoint Position => new PixelPoint(X, Y);
/// <summary>
/// Gets the size of the rectangle.
/// </summary>
public PixelSize Size => new PixelSize(Width, Height);
/// <summary>
/// Gets the right position of the rectangle.
/// </summary>
public int Right => X + Width;
/// <summary>
/// Gets the bottom position of the rectangle.
/// </summary>
public int Bottom => Y + Height;
/// <summary>
/// Gets the top left point of the rectangle.
/// </summary>
public PixelPoint TopLeft => new PixelPoint(X, Y);
/// <summary>
/// Gets the top right point of the rectangle.
/// </summary>
public PixelPoint TopRight => new PixelPoint(Right, Y);
/// <summary>
/// Gets the bottom left point of the rectangle.
/// </summary>
public PixelPoint BottomLeft => new PixelPoint(X, Bottom);
/// <summary>
/// Gets the bottom right point of the rectangle.
/// </summary>
public PixelPoint BottomRight => new PixelPoint(Right, Bottom);
/// <summary>
/// Gets the center point of the rectangle.
/// </summary>
public PixelPoint Center => new PixelPoint(X + (Width / 2), Y + (Height / 2));
/// <summary>
/// Gets a value that indicates whether the rectangle is empty.
/// </summary>
public bool IsEmpty => Width == 0 && Height == 0;
/// <summary>
/// Checks for equality between two <see cref="PixelRect"/>s.
/// </summary>
/// <param name="left">The first rect.</param>
/// <param name="right">The second rect.</param>
/// <returns>True if the rects are equal; otherwise false.</returns>
public static bool operator ==(PixelRect left, PixelRect right)
{
return left.Equals(right);
}
/// <summary>
/// Checks for inequality between two <see cref="PixelRect"/>s.
/// </summary>
/// <param name="left">The first rect.</param>
/// <param name="right">The second rect.</param>
/// <returns>True if the rects are unequal; otherwise false.</returns>
public static bool operator !=(PixelRect left, PixelRect right)
{
return !(left == right);
}
/// <summary>
/// Determines whether a point in in the bounds of the rectangle.
/// </summary>
/// <param name="p">The point.</param>
/// <returns>true if the point is in the bounds of the rectangle; otherwise false.</returns>
public bool Contains(PixelPoint p)
{
return p.X >= X && p.X <= Right && p.Y >= Y && p.Y <= Bottom;
}
/// <summary>
/// Determines whether the rectangle fully contains another rectangle.
/// </summary>
/// <param name="r">The rectangle.</param>
/// <returns>true if the rectangle is fully contained; otherwise false.</returns>
public bool Contains(PixelRect r)
{
return Contains(r.TopLeft) && Contains(r.BottomRight);
}
/// <summary>
/// Centers another rectangle in this rectangle.
/// </summary>
/// <param name="rect">The rectangle to center.</param>
/// <returns>The centered rectangle.</returns>
public PixelRect CenterRect(PixelRect rect)
{
return new PixelRect(
X + ((Width - rect.Width) / 2),
Y + ((Height - rect.Height) / 2),
rect.Width,
rect.Height);
}
/// <summary>
/// Returns a boolean indicating whether the rect is equal to the other given rect.
/// </summary>
/// <param name="other">The other rect to test equality against.</param>
/// <returns>True if this rect is equal to other; False otherwise.</returns>
public bool Equals(PixelRect other)
{
return Position == other.Position && Size == other.Size;
}
/// <summary>
/// Returns a boolean indicating whether the given object is equal to this rectangle.
/// </summary>
/// <param name="obj">The object to compare against.</param>
/// <returns>True if the object is equal to this rectangle; false otherwise.</returns>
public override bool Equals(object? obj) => obj is PixelRect other && Equals(other);
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
unchecked
{
int hash = 17;
hash = (hash * 23) + X.GetHashCode();
hash = (hash * 23) + Y.GetHashCode();
hash = (hash * 23) + Width.GetHashCode();
hash = (hash * 23) + Height.GetHashCode();
return hash;
}
}
/// <summary>
/// Gets the intersection of two rectangles.
/// </summary>
/// <param name="rect">The other rectangle.</param>
/// <returns>The intersection.</returns>
public PixelRect Intersect(PixelRect rect)
{
var newLeft = (rect.X > X) ? rect.X : X;
var newTop = (rect.Y > Y) ? rect.Y : Y;
var newRight = (rect.Right < Right) ? rect.Right : Right;
var newBottom = (rect.Bottom < Bottom) ? rect.Bottom : Bottom;
if ((newRight > newLeft) && (newBottom > newTop))
{
return new PixelRect(newLeft, newTop, newRight - newLeft, newBottom - newTop);
}
else
{
return Empty;
}
}
/// <summary>
/// Determines whether a rectangle intersects with this rectangle.
/// </summary>
/// <param name="rect">The other rectangle.</param>
/// <returns>
/// True if the specified rectangle intersects with this one; otherwise false.
/// </returns>
public bool Intersects(PixelRect rect)
{
return (rect.X < Right) && (X < rect.Right) && (rect.Y < Bottom) && (Y < rect.Bottom);
}
/// <summary>
/// Translates the rectangle by an offset.
/// </summary>
/// <param name="offset">The offset.</param>
/// <returns>The translated rectangle.</returns>
public PixelRect Translate(PixelVector offset)
{
return new PixelRect(Position + offset, Size);
}
/// <summary>
/// Gets the union of two rectangles.
/// </summary>
/// <param name="rect">The other rectangle.</param>
/// <returns>The union.</returns>
public PixelRect Union(PixelRect rect)
{
if (IsEmpty)
{
return rect;
}
else if (rect.IsEmpty)
{
return this;
}
else
{
var x1 = Math.Min(X, rect.X);
var x2 = Math.Max(Right, rect.Right);
var y1 = Math.Min(Y, rect.Y);
var y2 = Math.Max(Bottom, rect.Bottom);
return new PixelRect(new PixelPoint(x1, y1), new PixelPoint(x2, y2));
}
}
/// <summary>
/// Returns a new <see cref="PixelRect"/> with the specified X position.
/// </summary>
/// <param name="x">The x position.</param>
/// <returns>The new <see cref="PixelRect"/>.</returns>
public PixelRect WithX(int x)
{
return new PixelRect(x, Y, Width, Height);
}
/// <summary>
/// Returns a new <see cref="PixelRect"/> with the specified Y position.
/// </summary>
/// <param name="y">The y position.</param>
/// <returns>The new <see cref="PixelRect"/>.</returns>
public PixelRect WithY(int y)
{
return new PixelRect(X, y, Width, Height);
}
/// <summary>
/// Returns a new <see cref="PixelRect"/> with the specified width.
/// </summary>
/// <param name="width">The width.</param>
/// <returns>The new <see cref="PixelRect"/>.</returns>
public PixelRect WithWidth(int width)
{
return new PixelRect(X, Y, width, Height);
}
/// <summary>
/// Returns a new <see cref="PixelRect"/> with the specified height.
/// </summary>
/// <param name="height">The height.</param>
/// <returns>The new <see cref="PixelRect"/>.</returns>
public PixelRect WithHeight(int height)
{
return new PixelRect(X, Y, Width, Height);
}
/// <summary>
/// Converts the <see cref="PixelRect"/> to a device-independent <see cref="Rect"/> using the
/// specified scaling factor.
/// </summary>
/// <param name="scale">The scaling factor.</param>
/// <returns>The device-independent rect.</returns>
public Rect ToRect(double scale) => new Rect(Position.ToPoint(scale), Size.ToSize(scale));
/// <summary>
/// Converts the <see cref="PixelRect"/> to a device-independent <see cref="Rect"/> using the
/// specified scaling factor.
/// </summary>
/// <param name="scale">The scaling factor.</param>
/// <returns>The device-independent rect.</returns>
public Rect ToRect(Vector scale) => new Rect(Position.ToPoint(scale), Size.ToSize(scale));
/// <summary>
/// Converts the <see cref="PixelRect"/> to a device-independent <see cref="Rect"/> using the
/// specified dots per inch (DPI).
/// </summary>
/// <param name="dpi">The dots per inch of the device.</param>
/// <returns>The device-independent rect.</returns>
public Rect ToRectWithDpi(double dpi) => new Rect(Position.ToPointWithDpi(dpi), Size.ToSizeWithDpi(dpi));
/// <summary>
/// Converts the <see cref="PixelRect"/> to a device-independent <see cref="Rect"/> using the
/// specified dots per inch (DPI).
/// </summary>
/// <param name="dpi">The dots per inch of the device.</param>
/// <returns>The device-independent rect.</returns>
public Rect ToRectWithDpi(Vector dpi) => new Rect(Position.ToPointWithDpi(dpi), Size.ToSizeWithDpi(dpi));
/// <summary>
/// Converts a <see cref="Rect"/> to device pixels using the specified scaling factor.
/// </summary>
/// <param name="rect">The rect.</param>
/// <param name="scale">The scaling factor.</param>
/// <returns>The device-independent rect.</returns>
public static PixelRect FromRect(Rect rect, double scale) => new PixelRect(
PixelPoint.FromPoint(rect.Position, scale),
FromPointCeiling(rect.BottomRight, new Vector(scale, scale)));
/// <summary>
/// Converts a <see cref="Rect"/> to device pixels using the specified scaling factor.
/// </summary>
/// <param name="rect">The rect.</param>
/// <param name="scale">The scaling factor.</param>
/// <returns>The device-independent point.</returns>
public static PixelRect FromRect(Rect rect, Vector scale) => new PixelRect(
PixelPoint.FromPoint(rect.Position, scale),
FromPointCeiling(rect.BottomRight, scale));
/// <summary>
/// Converts a <see cref="Rect"/> to device pixels using the specified dots per inch (DPI).
/// </summary>
/// <param name="rect">The rect.</param>
/// <param name="dpi">The dots per inch of the device.</param>
/// <returns>The device-independent point.</returns>
public static PixelRect FromRectWithDpi(Rect rect, double dpi) => new PixelRect(
PixelPoint.FromPointWithDpi(rect.Position, dpi),
FromPointCeiling(rect.BottomRight, new Vector(dpi / 96, dpi / 96)));
/// <summary>
/// Converts a <see cref="Rect"/> to device pixels using the specified dots per inch (DPI).
/// </summary>
/// <param name="rect">The rect.</param>
/// <param name="dpi">The dots per inch of the device.</param>
/// <returns>The device-independent point.</returns>
public static PixelRect FromRectWithDpi(Rect rect, Vector dpi) => new PixelRect(
PixelPoint.FromPointWithDpi(rect.Position, dpi),
FromPointCeiling(rect.BottomRight, dpi / 96));
/// <summary>
/// Returns the string representation of the rectangle.
/// </summary>
/// <returns>The string representation of the rectangle.</returns>
public override string ToString()
{
return string.Format(
CultureInfo.InvariantCulture,
"{0}, {1}, {2}, {3}",
X,
Y,
Width,
Height);
}
/// <summary>
/// Parses a <see cref="PixelRect"/> string.
/// </summary>
/// <param name="s">The string.</param>
/// <returns>The parsed <see cref="PixelRect"/>.</returns>
public static PixelRect Parse(string s)
{
using (var tokenizer = new StringTokenizer(s, CultureInfo.InvariantCulture, exceptionMessage: "Invalid PixelRect."))
{
return new PixelRect(
tokenizer.ReadInt32(),
tokenizer.ReadInt32(),
tokenizer.ReadInt32(),
tokenizer.ReadInt32()
);
}
}
private static PixelPoint FromPointCeiling(Point point, Vector scale)
{
return new PixelPoint(
(int)Math.Ceiling(point.X * scale.X),
(int)Math.Ceiling(point.Y * scale.Y));
}
}
}
| |
using System;
using System.Diagnostics;
using System.Globalization;
using System.Net;
using System.Threading;
using Orleans.AzureUtils;
using Orleans.Runtime.Configuration;
namespace Orleans.Runtime.Host
{
/// <summary>
/// Wrapper class for an Orleans silo running in the current host process.
/// </summary>
public class AzureSilo
{
/// <summary>
/// Amount of time to pause before retrying if a secondary silo is unable to connect to the primary silo for this deployment.
/// Defaults to 5 seconds.
/// </summary>
public TimeSpan StartupRetryPause { get; set; }
/// <summary>
/// Number of times to retrying if a secondary silo is unable to connect to the primary silo for this deployment.
/// Defaults to 120 times.
/// </summary>
public int MaxRetries { get; set; }
/// <summary>
/// The name of the configuration key value for locating the DataConnectionString setting from the Azure configuration for this role.
/// Defaults to <c>DataConnectionString</c>
/// </summary>
public string DataConnectionConfigurationSettingName { get; set; }
/// <summary>
/// The name of the configuration key value for locating the OrleansSiloEndpoint setting from the Azure configuration for this role.
/// Defaults to <c>OrleansSiloEndpoint</c>
/// </summary>
public string SiloEndpointConfigurationKeyName { get; set; }
/// <summary>
/// The name of the configuration key value for locating the OrleansProxyEndpoint setting from the Azure configuration for this role.
/// Defaults to <c>OrleansProxyEndpoint</c>
/// </summary>
public string ProxyEndpointConfigurationKeyName { get; set; }
private SiloHost host;
private OrleansSiloInstanceManager siloInstanceManager;
private SiloInstanceTableEntry myEntry;
private readonly Logger logger;
private readonly IServiceRuntimeWrapper serviceRuntimeWrapper = new ServiceRuntimeWrapper();
/// <summary>
/// Constructor
/// </summary>
public AzureSilo()
{
DataConnectionConfigurationSettingName = AzureConstants.DataConnectionConfigurationSettingName;
SiloEndpointConfigurationKeyName = AzureConstants.SiloEndpointConfigurationKeyName;
ProxyEndpointConfigurationKeyName = AzureConstants.ProxyEndpointConfigurationKeyName;
StartupRetryPause = AzureConstants.STARTUP_TIME_PAUSE; // 5 seconds
MaxRetries = AzureConstants.MAX_RETRIES; // 120 x 5s = Total: 10 minutes
logger = LogManager.GetLogger("OrleansAzureSilo", LoggerType.Runtime);
}
public static ClusterConfiguration DefaultConfiguration()
{
var config = new ClusterConfiguration();
config.Globals.LivenessType = GlobalConfiguration.LivenessProviderType.AzureTable;
config.Globals.DeploymentId = AzureClient.GetDeploymentId();
config.Globals.DataConnectionString = AzureClient.GetDataConnectionString();
return config;
}
#region Azure RoleEntryPoint methods
/// <summary>
/// Initialize this Orleans silo for execution
/// </summary>
/// <returns><c>true</c> is the silo startup was successful</returns>
public bool Start()
{
return Start(null);
}
/// <summary>
/// Initialize this Orleans silo for execution with the specified Azure deploymentId
/// </summary>
/// <param name="config">If null, Config data will be read from silo config file as normal, otherwise use the specified config data.</param>
/// <param name="deploymentId">Azure DeploymentId this silo is running under</param>
/// <param name="connectionString">Azure DataConnectionString. If null, defaults to the DataConnectionString setting from the Azure configuration for this role.</param>
/// <returns><c>true</c> is the silo startup was successful</returns>
public bool Start(ClusterConfiguration config, string deploymentId = null, string connectionString = null)
{
// Program ident
Trace.TraceInformation("Starting {0} v{1}", this.GetType().FullName, RuntimeVersion.Current);
// Check if deployment id was specified
if (deploymentId == null)
deploymentId = serviceRuntimeWrapper.DeploymentId;
// Read endpoint info for this instance from Azure config
string instanceName = serviceRuntimeWrapper.InstanceName;
// Configure this Orleans silo instance
if (config == null)
{
host = new SiloHost(instanceName);
host.LoadOrleansConfig(); // Load config from file + Initializes logger configurations
}
else
{
host = new SiloHost(instanceName, config); // Use supplied config data + Initializes logger configurations
}
IPEndPoint myEndpoint = serviceRuntimeWrapper.GetIPEndpoint(SiloEndpointConfigurationKeyName);
IPEndPoint proxyEndpoint = serviceRuntimeWrapper.GetIPEndpoint(ProxyEndpointConfigurationKeyName);
host.SetSiloType(Silo.SiloType.Secondary);
int generation = SiloAddress.AllocateNewGeneration();
// Bootstrap this Orleans silo instance
myEntry = new SiloInstanceTableEntry
{
DeploymentId = deploymentId,
Address = myEndpoint.Address.ToString(),
Port = myEndpoint.Port.ToString(CultureInfo.InvariantCulture),
Generation = generation.ToString(CultureInfo.InvariantCulture),
HostName = host.Config.GetOrCreateNodeConfigurationForSilo(host.Name).DNSHostName,
ProxyPort = (proxyEndpoint != null ? proxyEndpoint.Port : 0).ToString(CultureInfo.InvariantCulture),
RoleName = serviceRuntimeWrapper.RoleName,
SiloName = instanceName,
UpdateZone = serviceRuntimeWrapper.UpdateDomain.ToString(CultureInfo.InvariantCulture),
FaultZone = serviceRuntimeWrapper.FaultDomain.ToString(CultureInfo.InvariantCulture),
StartTime = LogFormatter.PrintDate(DateTime.UtcNow),
PartitionKey = deploymentId,
RowKey = myEndpoint.Address + "-" + myEndpoint.Port + "-" + generation
};
if (connectionString == null)
connectionString = serviceRuntimeWrapper.GetConfigurationSettingValue(DataConnectionConfigurationSettingName);
try
{
siloInstanceManager = OrleansSiloInstanceManager.GetManager(
deploymentId, connectionString).WithTimeout(AzureTableDefaultPolicies.TableCreationTimeout).Result;
}
catch (Exception exc)
{
var error = String.Format("Failed to create OrleansSiloInstanceManager. This means CreateTableIfNotExist for silo instance table has failed with {0}",
LogFormatter.PrintException(exc));
Trace.TraceError(error);
logger.Error(ErrorCode.AzureTable_34, error, exc);
throw new OrleansException(error, exc);
}
// Always use Azure table for membership when running silo in Azure
host.SetSiloLivenessType(GlobalConfiguration.LivenessProviderType.AzureTable);
if (host.Config.Globals.ReminderServiceType == GlobalConfiguration.ReminderServiceProviderType.NotSpecified ||
host.Config.Globals.ReminderServiceType == GlobalConfiguration.ReminderServiceProviderType.ReminderTableGrain)
{
host.SetReminderServiceType(GlobalConfiguration.ReminderServiceProviderType.AzureTable);
}
host.SetExpectedClusterSize(serviceRuntimeWrapper.RoleInstanceCount);
siloInstanceManager.RegisterSiloInstance(myEntry);
// Initialise this Orleans silo instance
host.SetDeploymentId(deploymentId, connectionString);
host.SetSiloEndpoint(myEndpoint, generation);
host.SetProxyEndpoint(proxyEndpoint);
host.InitializeOrleansSilo();
logger.Info(ErrorCode.Runtime_Error_100288, "Successfully initialized Orleans silo '{0}' as a {1} node.", host.Name, host.Type);
return StartSilo();
}
/// <summary>
/// Makes this Orleans silo begin executing and become active.
/// Note: This method call will only return control back to the caller when the silo is shutdown.
/// </summary>
public void Run()
{
RunImpl();
}
/// <summary>
/// Makes this Orleans silo begin executing and become active.
/// Note: This method call will only return control back to the caller when the silo is shutdown or
/// an external request for cancellation has been issued.
/// </summary>
/// <param name="cancellationToken">Cancellation token.</param>
public void Run(CancellationToken cancellationToken)
{
RunImpl(cancellationToken);
}
/// <summary>
/// Stop this Orleans silo executing.
/// </summary>
public void Stop()
{
logger.Info(ErrorCode.Runtime_Error_100290, "Stopping {0}", this.GetType().FullName);
serviceRuntimeWrapper.UnsubscribeFromStoppingNotifcation(this, HandleAzureRoleStopping);
host.ShutdownOrleansSilo();
logger.Info(ErrorCode.Runtime_Error_100291, "Orleans silo '{0}' shutdown.", host.Name);
}
#endregion
private bool StartSilo()
{
logger.Info(ErrorCode.Runtime_Error_100292, "Starting Orleans silo '{0}' as a {1} node.", host.Name, host.Type);
bool ok = host.StartOrleansSilo();
if (ok)
logger.Info(ErrorCode.Runtime_Error_100293, "Successfully started Orleans silo '{0}' as a {1} node.", host.Name, host.Type);
else
logger.Error(ErrorCode.Runtime_Error_100285, string.Format("Failed to start Orleans silo '{0}' as a {1} node.", host.Name, host.Type));
return ok;
}
private void HandleAzureRoleStopping(object sender, object e)
{
// Try to perform gracefull shutdown of Silo when we detect Azure role instance is being stopped
logger.Info(ErrorCode.SiloStopping, "HandleAzureRoleStopping - starting to shutdown silo");
host.ShutdownOrleansSilo();
}
/// <summary>
/// Run method helper.
/// </summary>
/// <remarks>
/// Makes this Orleans silo begin executing and become active.
/// Note: This method call will only return control back to the caller when the silo is shutdown or
/// an external request for cancellation has been issued.
/// </remarks>
/// <param name="cancellationToken">Optional cancellation token.</param>
private void RunImpl(CancellationToken? cancellationToken = null)
{
logger.Info(ErrorCode.Runtime_Error_100289, "OrleansAzureHost entry point called");
// Hook up to receive notification of Azure role stopping events
serviceRuntimeWrapper.SubscribeForStoppingNotifcation(this, HandleAzureRoleStopping);
if (host.IsStarted)
{
if (cancellationToken.HasValue)
host.WaitForOrleansSiloShutdown(cancellationToken.Value);
else
host.WaitForOrleansSiloShutdown();
}
else
throw new Exception("Silo failed to start correctly - aborting");
}
}
}
| |
// dnlib: See LICENSE.txt for more info
using System;
using System.Collections.Generic;
using System.Diagnostics;
using dnlib.DotNet.Emit;
using dnlib.DotNet.MD;
using dnlib.DotNet.Pdb;
using dnlib.PE;
using dnlib.Threading;
using dnlib.W32Resources;
namespace dnlib.DotNet {
readonly struct ModuleLoader {
readonly ModuleDef module;
readonly ICancellationToken cancellationToken;
readonly Dictionary<object, bool> seen;
readonly Stack<object> stack;
ModuleLoader(ModuleDef module, ICancellationToken cancellationToken) {
const int CAPACITY = 0x4000;
this.module = module;
this.cancellationToken = cancellationToken;
seen = new Dictionary<object, bool>(CAPACITY);
stack = new Stack<object>(CAPACITY);
}
public static void LoadAll(ModuleDef module, ICancellationToken cancellationToken) =>
new ModuleLoader(module, cancellationToken).Load();
void Add(UTF8String a) { }
void Add(Guid? a) { }
void Add(ushort a) { }
void Add(AssemblyHashAlgorithm a) { }
void Add(Version a) { }
void Add(AssemblyAttributes a) { }
void Add(PublicKeyBase a) { }
void Add(RVA a) { }
void Add(IManagedEntryPoint a) { }
void Add(string a) { }
void Add(WinMDStatus a) { }
void Add(TypeAttributes a) { }
void Add(FieldAttributes a) { }
void Add(uint? a) { }
void Add(byte[] a) { }
void Add(MethodImplAttributes a) { }
void Add(MethodAttributes a) { }
void Add(MethodSemanticsAttributes a) { }
void Add(ParamAttributes a) { }
void Add(ElementType a) { }
void Add(SecurityAction a) { }
void Add(EventAttributes a) { }
void Add(PropertyAttributes a) { }
void Add(PInvokeAttributes a) { }
void Add(FileAttributes a) { }
void Add(ManifestResourceAttributes a) { }
void Add(GenericParamAttributes a) { }
void Add(NativeType a) { }
void Load() {
LoadAllTables();
Load(module);
Process();
}
void Process() {
while (stack.Count != 0) {
if (cancellationToken is not null)
cancellationToken.ThrowIfCancellationRequested();
var o = stack.Pop();
LoadObj(o);
}
}
void LoadAllTables() {
var resolver = module as ITokenResolver;
if (resolver is null)
return;
for (Table tbl = 0; tbl <= Table.GenericParamConstraint; tbl++) {
for (uint rid = 1; ; rid++) {
var o = resolver.ResolveToken(new MDToken(tbl, rid).Raw, new GenericParamContext());
if (o is null)
break;
Add(o);
Process();
}
}
}
void LoadObj(object o) {
if (o is TypeSig ts) {
Load(ts);
return;
}
if (o is IMDTokenProvider mdt) {
Load(mdt);
return;
}
if (o is CustomAttribute ca) {
Load(ca);
return;
}
if (o is SecurityAttribute sa) {
Load(sa);
return;
}
if (o is CANamedArgument na) {
Load(na);
return;
}
if (o is Parameter p) {
Load(p);
return;
}
if (o is PdbMethod pdbMethod) {
Load(pdbMethod);
return;
}
if (o is ResourceDirectory rd) {
Load(rd);
return;
}
if (o is ResourceData rdata) {
Load(rdata);
return;
}
Debug.Fail("Unknown type");
}
void Load(TypeSig ts) {
if (ts is null)
return;
Add(ts.Next);
switch (ts.ElementType) {
case ElementType.Void:
case ElementType.Boolean:
case ElementType.Char:
case ElementType.I1:
case ElementType.U1:
case ElementType.I2:
case ElementType.U2:
case ElementType.I4:
case ElementType.U4:
case ElementType.I8:
case ElementType.U8:
case ElementType.R4:
case ElementType.R8:
case ElementType.String:
case ElementType.ValueType:
case ElementType.Class:
case ElementType.TypedByRef:
case ElementType.I:
case ElementType.U:
case ElementType.Object:
Add(((TypeDefOrRefSig)ts).TypeDefOrRef);
break;
case ElementType.Var:
case ElementType.MVar:
var vsig = (GenericSig)ts;
Add(vsig.OwnerType);
Add(vsig.OwnerMethod);
break;
case ElementType.GenericInst:
var gis = (GenericInstSig)ts;
Add(gis.GenericType);
Add(gis.GenericArguments);
break;
case ElementType.FnPtr:
var fpsig = (FnPtrSig)ts;
Add(fpsig.Signature);
break;
case ElementType.CModReqd:
case ElementType.CModOpt:
var cmod = (ModifierSig)ts;
Add(cmod.Modifier);
break;
case ElementType.End:
case ElementType.Ptr:
case ElementType.ByRef:
case ElementType.Array:
case ElementType.ValueArray:
case ElementType.SZArray:
case ElementType.Module:
case ElementType.Pinned:
case ElementType.Sentinel:
case ElementType.R:
case ElementType.Internal:
default:
break;
}
}
void Load(IMDTokenProvider mdt) {
if (mdt is null)
return;
switch (mdt.MDToken.Table) {
case Table.Module: Load((ModuleDef)mdt); break;
case Table.TypeRef: Load((TypeRef)mdt); break;
case Table.TypeDef: Load((TypeDef)mdt); break;
case Table.Field: Load((FieldDef)mdt); break;
case Table.Method: Load((MethodDef)mdt); break;
case Table.Param: Load((ParamDef)mdt); break;
case Table.InterfaceImpl: Load((InterfaceImpl)mdt); break;
case Table.MemberRef: Load((MemberRef)mdt); break;
case Table.Constant: Load((Constant)mdt); break;
case Table.DeclSecurity: Load((DeclSecurity)mdt); break;
case Table.ClassLayout: Load((ClassLayout)mdt); break;
case Table.StandAloneSig: Load((StandAloneSig)mdt); break;
case Table.Event: Load((EventDef)mdt); break;
case Table.Property: Load((PropertyDef)mdt); break;
case Table.ModuleRef: Load((ModuleRef)mdt); break;
case Table.TypeSpec: Load((TypeSpec)mdt); break;
case Table.ImplMap: Load((ImplMap)mdt); break;
case Table.Assembly: Load((AssemblyDef)mdt); break;
case Table.AssemblyRef: Load((AssemblyRef)mdt); break;
case Table.File: Load((FileDef)mdt); break;
case Table.ExportedType: Load((ExportedType)mdt); break;
case Table.GenericParam: Load((GenericParam)mdt); break;
case Table.MethodSpec: Load((MethodSpec)mdt); break;
case Table.GenericParamConstraint: Load((GenericParamConstraint)mdt); break;
case Table.ManifestResource:
var rsrc = mdt as Resource;
if (rsrc is not null) {
Load(rsrc);
break;
}
var mr = mdt as ManifestResource;
if (mr is not null) {
Load(mr);
break;
}
Debug.Fail("Unknown ManifestResource");
break;
case Table.FieldPtr:
case Table.MethodPtr:
case Table.ParamPtr:
case Table.CustomAttribute:
case Table.FieldMarshal:
case Table.FieldLayout:
case Table.EventMap:
case Table.EventPtr:
case Table.PropertyMap:
case Table.PropertyPtr:
case Table.MethodSemantics:
case Table.MethodImpl:
case Table.FieldRVA:
case Table.ENCLog:
case Table.ENCMap:
case Table.AssemblyProcessor:
case Table.AssemblyOS:
case Table.AssemblyRefProcessor:
case Table.AssemblyRefOS:
case Table.NestedClass:
case Table.Document:
case Table.MethodDebugInformation:
case Table.LocalScope:
case Table.LocalVariable:
case Table.LocalConstant:
case Table.ImportScope:
case Table.StateMachineMethod:
case Table.CustomDebugInformation:
break;
default:
Debug.Fail("Unknown type");
break;
}
}
void Load(ModuleDef obj) {
if (obj is null || obj != module)
return;
Add(obj.Generation);
Add(obj.Name);
Add(obj.Mvid);
Add(obj.EncId);
Add(obj.EncBaseId);
Add(obj.CustomAttributes);
Add(obj.Assembly);
Add(obj.Types);
Add(obj.ExportedTypes);
Add(obj.NativeEntryPoint);
Add(obj.ManagedEntryPoint);
Add(obj.Resources);
Add(obj.VTableFixups);
Add(obj.Location);
Add(obj.Win32Resources);
Add(obj.RuntimeVersion);
Add(obj.WinMDStatus);
Add(obj.RuntimeVersionWinMD);
Add(obj.WinMDVersion);
Add(obj.PdbState);
}
void Load(TypeRef obj) {
if (obj is null)
return;
Add(obj.ResolutionScope);
Add(obj.Name);
Add(obj.Namespace);
Add(obj.CustomAttributes);
}
void Load(TypeDef obj) {
if (obj is null)
return;
Add(obj.Module2);
Add(obj.Attributes);
Add(obj.Name);
Add(obj.Namespace);
Add(obj.BaseType);
Add(obj.Fields);
Add(obj.Methods);
Add(obj.GenericParameters);
Add(obj.Interfaces);
Add(obj.DeclSecurities);
Add(obj.ClassLayout);
Add(obj.DeclaringType);
Add(obj.DeclaringType2);
Add(obj.NestedTypes);
Add(obj.Events);
Add(obj.Properties);
Add(obj.CustomAttributes);
}
void Load(FieldDef obj) {
if (obj is null)
return;
Add(obj.CustomAttributes);
Add(obj.Attributes);
Add(obj.Name);
Add(obj.Signature);
Add(obj.FieldOffset);
Add(obj.MarshalType);
Add(obj.RVA);
Add(obj.InitialValue);
Add(obj.ImplMap);
Add(obj.Constant);
Add(obj.DeclaringType);
}
void Load(MethodDef obj) {
if (obj is null)
return;
Add(obj.RVA);
Add(obj.ImplAttributes);
Add(obj.Attributes);
Add(obj.Name);
Add(obj.Signature);
Add(obj.ParamDefs);
Add(obj.GenericParameters);
Add(obj.DeclSecurities);
Add(obj.ImplMap);
Add(obj.MethodBody);
Add(obj.CustomAttributes);
Add(obj.Overrides);
Add(obj.DeclaringType);
Add(obj.Parameters);
Add(obj.SemanticsAttributes);
}
void Load(ParamDef obj) {
if (obj is null)
return;
Add(obj.DeclaringMethod);
Add(obj.Attributes);
Add(obj.Sequence);
Add(obj.Name);
Add(obj.MarshalType);
Add(obj.Constant);
Add(obj.CustomAttributes);
}
void Load(InterfaceImpl obj) {
if (obj is null)
return;
Add(obj.Interface);
Add(obj.CustomAttributes);
}
void Load(MemberRef obj) {
if (obj is null)
return;
Add(obj.Class);
Add(obj.Name);
Add(obj.Signature);
Add(obj.CustomAttributes);
}
void Load(Constant obj) {
if (obj is null)
return;
Add(obj.Type);
var o = obj.Value;
}
void Load(DeclSecurity obj) {
if (obj is null)
return;
Add(obj.Action);
Add(obj.SecurityAttributes);
Add(obj.CustomAttributes);
obj.GetBlob();
}
void Load(ClassLayout obj) {
if (obj is null)
return;
Add(obj.PackingSize);
Add(obj.ClassSize);
}
void Load(StandAloneSig obj) {
if (obj is null)
return;
Add(obj.Signature);
Add(obj.CustomAttributes);
}
void Load(EventDef obj) {
if (obj is null)
return;
Add(obj.Attributes);
Add(obj.Name);
Add(obj.EventType);
Add(obj.CustomAttributes);
Add(obj.AddMethod);
Add(obj.InvokeMethod);
Add(obj.RemoveMethod);
Add(obj.OtherMethods);
Add(obj.DeclaringType);
}
void Load(PropertyDef obj) {
if (obj is null)
return;
Add(obj.Attributes);
Add(obj.Name);
Add(obj.Type);
Add(obj.Constant);
Add(obj.CustomAttributes);
Add(obj.GetMethods);
Add(obj.SetMethods);
Add(obj.OtherMethods);
Add(obj.DeclaringType);
}
void Load(ModuleRef obj) {
if (obj is null)
return;
Add(obj.Name);
Add(obj.CustomAttributes);
}
void Load(TypeSpec obj) {
if (obj is null)
return;
Add(obj.TypeSig);
Add(obj.ExtraData);
Add(obj.CustomAttributes);
}
void Load(ImplMap obj) {
if (obj is null)
return;
Add(obj.Attributes);
Add(obj.Name);
Add(obj.Module);
}
void Load(AssemblyDef obj) {
if (obj is null)
return;
if (obj.ManifestModule != module)
return;
Add(obj.HashAlgorithm);
Add(obj.Version);
Add(obj.Attributes);
Add(obj.PublicKey);
Add(obj.Name);
Add(obj.Culture);
Add(obj.DeclSecurities);
Add(obj.Modules);
Add(obj.CustomAttributes);
}
void Load(AssemblyRef obj) {
if (obj is null)
return;
Add(obj.Version);
Add(obj.Attributes);
Add(obj.PublicKeyOrToken);
Add(obj.Name);
Add(obj.Culture);
Add(obj.Hash);
Add(obj.CustomAttributes);
}
void Load(FileDef obj) {
if (obj is null)
return;
Add(obj.Flags);
Add(obj.Name);
Add(obj.HashValue);
Add(obj.CustomAttributes);
}
void Load(ExportedType obj) {
if (obj is null)
return;
Add(obj.CustomAttributes);
Add(obj.Attributes);
Add(obj.TypeDefId);
Add(obj.TypeName);
Add(obj.TypeNamespace);
Add(obj.Implementation);
}
void Load(Resource obj) {
if (obj is null)
return;
Add(obj.Offset);
Add(obj.Name);
Add(obj.Attributes);
Add(obj.CustomAttributes);
switch (obj.ResourceType) {
case ResourceType.Embedded:
break;
case ResourceType.AssemblyLinked:
var ar = (AssemblyLinkedResource)obj;
Add(ar.Assembly);
break;
case ResourceType.Linked:
var lr = (LinkedResource)obj;
Add(lr.File);
Add(lr.Hash);
break;
default:
Debug.Fail("Unknown resource");
break;
}
}
void Load(ManifestResource obj) {
if (obj is null)
return;
Add(obj.Offset);
Add(obj.Flags);
Add(obj.Name);
Add(obj.Implementation);
Add(obj.CustomAttributes);
}
void Load(GenericParam obj) {
if (obj is null)
return;
Add(obj.Owner);
Add(obj.Number);
Add(obj.Flags);
Add(obj.Name);
Add(obj.Kind);
Add(obj.GenericParamConstraints);
Add(obj.CustomAttributes);
}
void Load(MethodSpec obj) {
if (obj is null)
return;
Add(obj.Method);
Add(obj.Instantiation);
Add(obj.CustomAttributes);
}
void Load(GenericParamConstraint obj) {
if (obj is null)
return;
Add(obj.Owner);
Add(obj.Constraint);
Add(obj.CustomAttributes);
}
void Load(CANamedArgument obj) {
if (obj is null)
return;
Add(obj.Type);
Add(obj.Name);
Load(obj.Argument);
}
void Load(Parameter obj) {
if (obj is null)
return;
Add(obj.Type);
}
void Load(SecurityAttribute obj) {
if (obj is null)
return;
Add(obj.AttributeType);
Add(obj.NamedArguments);
}
void Load(CustomAttribute obj) {
if (obj is null)
return;
Add(obj.Constructor);
Add(obj.RawData);
Add(obj.ConstructorArguments);
Add(obj.NamedArguments);
}
void Load(MethodOverride obj) {
Add(obj.MethodBody);
Add(obj.MethodDeclaration);
}
void AddCAValue(object obj) {
if (obj is CAArgument) {
Load((CAArgument)obj);
return;
}
if (obj is IList<CAArgument> list) {
Add(list);
return;
}
if (obj is IMDTokenProvider md) {
Add(md);
return;
}
}
void Load(CAArgument obj) {
Add(obj.Type);
AddCAValue(obj.Value);
}
void Load(PdbMethod obj) { }
void Load(ResourceDirectory obj) {
if (obj is null)
return;
Add(obj.Directories);
Add(obj.Data);
}
void Load(ResourceData obj) { }
void AddToStack<T>(T t) where T : class {
if (t is null)
return;
if (seen.ContainsKey(t))
return;
seen[t] = true;
stack.Push(t);
}
void Add(CustomAttribute obj) => AddToStack(obj);
void Add(SecurityAttribute obj) => AddToStack(obj);
void Add(CANamedArgument obj) => AddToStack(obj);
void Add(Parameter obj) => AddToStack(obj);
void Add(IMDTokenProvider o) => AddToStack(o);
void Add(PdbMethod pdbMethod) { }
void Add(TypeSig ts) => AddToStack(ts);
void Add(ResourceDirectory rd) => AddToStack(rd);
void Add(ResourceData rd) => AddToStack(rd);
void Add<T>(IList<T> list) where T : IMDTokenProvider {
if (list is null)
return;
foreach (var item in list)
Add(item);
}
void Add(IList<TypeSig> list) {
if (list is null)
return;
foreach (var item in list)
Add(item);
}
void Add(IList<CustomAttribute> list) {
if (list is null)
return;
foreach (var item in list)
Add(item);
}
void Add(IList<SecurityAttribute> list) {
if (list is null)
return;
foreach (var item in list)
Add(item);
}
void Add(IList<MethodOverride> list) {
if (list is null)
return;
foreach (var item in list)
Load(item);
}
void Add(IList<CAArgument> list) {
if (list is null)
return;
foreach (var item in list)
Load(item);
}
void Add(IList<CANamedArgument> list) {
if (list is null)
return;
foreach (var item in list)
Add(item);
}
void Add(ParameterList list) {
if (list is null)
return;
foreach (var item in list)
Add(item);
}
void Add(IList<Instruction> list) {
if (list is null)
return;
foreach (var item in list)
Add(item);
}
void Add(IList<ExceptionHandler> list) {
if (list is null)
return;
foreach (var item in list)
Add(item);
}
void Add(IList<Local> list) {
if (list is null)
return;
foreach (var item in list)
Add(item);
}
void Add(IList<ResourceDirectory> list) {
if (list is null)
return;
foreach (var item in list)
Add(item);
}
void Add(IList<ResourceData> list) {
if (list is null)
return;
foreach (var item in list)
Add(item);
}
void Add(VTableFixups vtf) {
if (vtf is null)
return;
foreach (var fixup in vtf) {
foreach (var method in fixup)
Add(method);
}
}
void Add(Win32Resources vtf) {
if (vtf is null)
return;
Add(vtf.Root);
}
void Add(CallingConventionSig sig) {
if (sig is MethodBaseSig msig) {
Add(msig);
return;
}
if (sig is FieldSig fsig) {
Add(fsig);
return;
}
if (sig is LocalSig lsig) {
Add(lsig);
return;
}
if (sig is GenericInstMethodSig gsig) {
Add(gsig);
return;
}
Debug.Assert(sig is null);
}
void Add(MethodBaseSig msig) {
if (msig is null)
return;
Add(msig.ExtraData);
Add(msig.RetType);
Add(msig.Params);
Add(msig.ParamsAfterSentinel);
}
void Add(FieldSig fsig) {
if (fsig is null)
return;
Add(fsig.ExtraData);
Add(fsig.Type);
}
void Add(LocalSig lsig) {
if (lsig is null)
return;
Add(lsig.ExtraData);
Add(lsig.Locals);
}
void Add(GenericInstMethodSig gsig) {
if (gsig is null)
return;
Add(gsig.ExtraData);
Add(gsig.GenericArguments);
}
void Add(MarshalType mt) {
if (mt is null)
return;
Add(mt.NativeType);
}
void Add(MethodBody mb) {
if (mb is CilBody cilBody) {
Add(cilBody);
return;
}
if (mb is NativeMethodBody nb) {
Add(nb);
return;
}
Debug.Assert(mb is null, "Unknown method body");
}
void Add(NativeMethodBody body) {
if (body is null)
return;
Add(body.RVA);
}
void Add(CilBody body) {
if (body is null)
return;
Add(body.Instructions);
Add(body.ExceptionHandlers);
Add(body.Variables);
Add(body.PdbMethod);
}
void Add(Instruction instr) {
if (instr is null)
return;
if (instr.Operand is IMDTokenProvider mdt) {
Add(mdt);
return;
}
if (instr.Operand is Parameter p) {
Add(p);
return;
}
if (instr.Operand is Local l) {
Add(l);
return;
}
if (instr.Operand is CallingConventionSig csig) {
Add(csig);
return;
}
}
void Add(ExceptionHandler eh) {
if (eh is null)
return;
Add(eh.CatchType);
}
void Add(Local local) {
if (local is null)
return;
Add(local.Type);
}
void Add(PdbState state) {
if (state is null)
return;
Add(state.UserEntryPoint);
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2009 Charlie Poole, Rob Prouse
//
// 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.Threading;
using NUnit.Compatibility;
using ActualValueDelegate = NUnit.Framework.Constraints.ActualValueDelegate<object>;
namespace NUnit.Framework.Constraints
{
[TestFixture, NonParallelizable]
public class DelayedConstraintTests : ConstraintTestBase
{
// NOTE: This class tests the functioning of the DelayConstraint,
// not the After syntax. The AfterTests class tests our syntax,
// assuring that the proper constraint is generated. Here,we
// set up constraints in the simplest way possible, often by
// constructing the constraint class, and verify that they work.
private const int DELAY = 100;
private const int AFTER = 500;
private const int POLLING = 50;
private const int MIN = AFTER - 10;
private static bool boolValue;
private static List<int> list;
private static string statusString;
[SetUp]
public void SetUp()
{
TheConstraint = new DelayedConstraint(new EqualConstraint(true), 500);
ExpectedDescription = "True after 500 milliseconds delay";
StringRepresentation = "<after 500 <equal True>>";
boolValue = false;
list = new List<int>();
statusString = null;
//SetValueTrueAfterDelay(300);
}
static object[] SuccessData = new object[] { true };
static object[] FailureData = new object[] {
new TestCaseData( false, "False" ),
new TestCaseData( 0, "0" ),
new TestCaseData( null, "null" ) };
static readonly ActualValueDelegate DelegateReturningValue;
static readonly ActualValueDelegate DelegateReturningFalse;
static readonly ActualValueDelegate DelegateReturningZero;
static ActualValueDelegate<object>[] SuccessDelegates;
static ActualValueDelegate<object>[] FailureDelegates;
// Initialize static fields that are sensitive to order of initialization.
// Most compilers would probably initialize these in lexical order but it
// may not be guaranteed in all cases so we do it directly.
static DelayedConstraintTests()
{
DelegateReturningValue = new ActualValueDelegate(MethodReturningValue);
DelegateReturningFalse = new ActualValueDelegate(MethodReturningFalse);
DelegateReturningZero = new ActualValueDelegate(MethodReturningZero);
SuccessDelegates = new ActualValueDelegate<object>[] { DelegateReturningValue };
FailureDelegates = new ActualValueDelegate<object>[] { DelegateReturningFalse, DelegateReturningZero };
}
[Test, TestCaseSource(nameof(SuccessDelegates))]
public void SucceedsWithGoodDelegates(ActualValueDelegate<object> del)
{
SetValuesAfterDelay(DELAY);
Assert.That(TheConstraint.ApplyTo(del).IsSuccess);
}
[Test, TestCaseSource(nameof(FailureDelegates))]
public void FailsWithBadDelegates(ActualValueDelegate<object> del)
{
Assert.IsFalse(TheConstraint.ApplyTo(del).IsSuccess);
}
[Test]
public void SimpleTest()
{
SetValuesAfterDelay(DELAY);
Assert.That(DelegateReturningValue, new DelayedConstraint(new EqualConstraint(true), AFTER, POLLING));
}
[Test]
public void SimpleTestUsingBoolean()
{
SetValuesAfterDelay(DELAY);
Assert.That(() => boolValue, new DelayedConstraint(new EqualConstraint(true), AFTER, POLLING));
}
[Test]
public void ThatOverload_ZeroDelayIsAllowed()
{
Assert.That(DelegateReturningZero, new DelayedConstraint(new EqualConstraint(0), 0));
}
[Test]
public void ThatOverload_DoesNotAcceptNegativeDelayValues()
{
Assert.Throws<ArgumentException>(
() => Assert.That(DelegateReturningZero, new DelayedConstraint(new EqualConstraint(0), -1)));
}
[Test]
public void CanTestContentsOfList()
{
SetValuesAfterDelay(1);
Assert.That(list, Has.Count.EqualTo(1).After(AFTER, POLLING));
}
[Test]
public void CanTestContentsOfDelegateReturningList()
{
SetValuesAfterDelay(1);
Assert.That(() => list, Has.Count.EqualTo(1).After(AFTER, POLLING));
}
[Test]
public void CanTestInitiallyNullDelegate()
{
SetValuesAfterDelay(DELAY);
Assert.That(() => statusString, Is.Not.Null.And.Length.GreaterThan(0).After(AFTER, POLLING));
}
[Test]
public void ThatBlockingDelegateWhichSucceedsWithoutPolling_ReturnsAfterDelay()
{
var watch = new Stopwatch();
watch.Start();
Assert.That(() =>
{
Delay(DELAY);
return true;
}, Is.True.After(AFTER));
watch.Stop();
Assert.That(watch.ElapsedMilliseconds, Is.GreaterThanOrEqualTo(MIN));
}
[Test]
public void ThatBlockingDelegateWhichSucceedsWithPolling_ReturnsEarly()
{
var watch = new Stopwatch();
watch.Start();
Assert.That(() =>
{
Delay(DELAY);
return true;
}, Is.True.After(AFTER, POLLING));
watch.Stop();
Assert.That(watch.ElapsedMilliseconds, Is.InRange(DELAY, AFTER));
}
[Test]
public void ThatBlockingDelegateWhichFailsWithoutPolling_FailsAfterDelay()
{
var watch = new Stopwatch();
watch.Start();
Assert.Throws<AssertionException>(() => Assert.That(() =>
{
Delay(DELAY);
return false;
}, Is.True.After(AFTER)));
watch.Stop();
Assert.That(watch.ElapsedMilliseconds, Is.GreaterThanOrEqualTo(MIN));
}
[Test]
public void ThatBlockingDelegateWhichFailsWithPolling_FailsAfterDelay()
{
var watch = new Stopwatch();
watch.Start();
Assert.Throws<AssertionException>(() => Assert.That(() =>
{
Delay(DELAY);
return false;
}, Is.True.After(AFTER, POLLING)));
watch.Stop();
Assert.That(watch.ElapsedMilliseconds, Is.GreaterThanOrEqualTo(MIN));
}
[Test]
public void ThatBlockingDelegateWhichThrowsWithoutPolling_FailsAfterDelay()
{
var watch = new Stopwatch();
watch.Start();
Assert.Throws<AssertionException>(() => Assert.That(() =>
{
Delay(DELAY);
throw new InvalidOperationException();
}, Is.True.After(AFTER)));
watch.Stop();
Assert.That(watch.ElapsedMilliseconds, Is.GreaterThanOrEqualTo(MIN));
}
[Test]
public void ThatBlockingDelegateWhichThrowsWithPolling_FailsAfterDelay()
{
var watch = new Stopwatch();
watch.Start();
Assert.Throws<AssertionException>(() => Assert.That(() =>
{
Delay(DELAY);
throw new InvalidOperationException();
}, Is.True.After(AFTER, POLLING)));
watch.Stop();
Assert.That(watch.ElapsedMilliseconds, Is.GreaterThanOrEqualTo(AFTER));
}
private static int setValuesDelay;
private static void MethodReturningVoid() { }
private static object MethodReturningValue() { return boolValue; }
private static object MethodReturningFalse() { return false; }
private static object MethodReturningZero() { return 0; }
private static readonly AutoResetEvent waitEvent = new AutoResetEvent(false);
private static void Delay(int delay)
{
waitEvent.WaitOne(delay);
}
private static void MethodSetsValues()
{
Delay(setValuesDelay);
boolValue = true;
list.Add(1);
statusString = "Finished";
}
private void SetValuesAfterDelay(int delayInMilliSeconds)
{
setValuesDelay = delayInMilliSeconds;
Thread thread = new Thread(MethodSetsValues);
thread.Start();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ResourceManager
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
public static partial class ResourceGroupsOperationsExtensions
{
/// <summary>
/// Get all of the resources under a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Query parameters. If null is passed returns all resource groups.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
public static IPage<GenericResource> ListResources(this IResourceGroupsOperations operations, string resourceGroupName, ODataQuery<GenericResourceFilter> odataQuery = default(ODataQuery<GenericResourceFilter>))
{
return Task.Factory.StartNew(s => ((IResourceGroupsOperations)s).ListResourcesAsync(resourceGroupName, odataQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get all of the resources under a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Query parameters. If null is passed returns all resource groups.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<GenericResource>> ListResourcesAsync( this IResourceGroupsOperations operations, string resourceGroupName, ODataQuery<GenericResourceFilter> odataQuery = default(ODataQuery<GenericResourceFilter>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListResourcesWithHttpMessagesAsync(resourceGroupName, odataQuery, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Checks whether resource group exists.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group to check. The name is case insensitive.
/// </param>
public static bool? CheckExistence(this IResourceGroupsOperations operations, string resourceGroupName)
{
return Task.Factory.StartNew(s => ((IResourceGroupsOperations)s).CheckExistenceAsync(resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Checks whether resource group exists.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group to check. The name is case insensitive.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<bool?> CheckExistenceAsync( this IResourceGroupsOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CheckExistenceWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Create a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group to be created or updated.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update resource group service
/// operation.
/// </param>
public static ResourceGroup CreateOrUpdate(this IResourceGroupsOperations operations, string resourceGroupName, ResourceGroup parameters)
{
return Task.Factory.StartNew(s => ((IResourceGroupsOperations)s).CreateOrUpdateAsync(resourceGroupName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group to be created or updated.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update resource group service
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ResourceGroup> CreateOrUpdateAsync( this IResourceGroupsOperations operations, string resourceGroupName, ResourceGroup parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Delete resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group to be deleted. The name is case insensitive.
/// </param>
public static void Delete(this IResourceGroupsOperations operations, string resourceGroupName)
{
Task.Factory.StartNew(s => ((IResourceGroupsOperations)s).DeleteAsync(resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group to be deleted. The name is case insensitive.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync( this IResourceGroupsOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Delete resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group to be deleted. The name is case insensitive.
/// </param>
public static void BeginDelete(this IResourceGroupsOperations operations, string resourceGroupName)
{
Task.Factory.StartNew(s => ((IResourceGroupsOperations)s).BeginDeleteAsync(resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group to be deleted. The name is case insensitive.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync( this IResourceGroupsOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group to get. The name is case insensitive.
/// </param>
public static ResourceGroup Get(this IResourceGroupsOperations operations, string resourceGroupName)
{
return Task.Factory.StartNew(s => ((IResourceGroupsOperations)s).GetAsync(resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group to get. The name is case insensitive.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ResourceGroup> GetAsync( this IResourceGroupsOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Resource groups can be updated through a simple PATCH operation to a group
/// address. The format of the request is the same as that for creating a
/// resource groups, though if a field is unspecified current value will be
/// carried over.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group to be created or updated. The name is case
/// insensitive.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the update state resource group service operation.
/// </param>
public static ResourceGroup Patch(this IResourceGroupsOperations operations, string resourceGroupName, ResourceGroup parameters)
{
return Task.Factory.StartNew(s => ((IResourceGroupsOperations)s).PatchAsync(resourceGroupName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Resource groups can be updated through a simple PATCH operation to a group
/// address. The format of the request is the same as that for creating a
/// resource groups, though if a field is unspecified current value will be
/// carried over.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group to be created or updated. The name is case
/// insensitive.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the update state resource group service operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ResourceGroup> PatchAsync( this IResourceGroupsOperations operations, string resourceGroupName, ResourceGroup parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.PatchWithHttpMessagesAsync(resourceGroupName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Captures the specified resource group as a template.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group to be created or updated.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the export template resource group operation.
/// </param>
public static ResourceGroupExportResult ExportTemplate(this IResourceGroupsOperations operations, string resourceGroupName, ExportTemplateRequest parameters)
{
return Task.Factory.StartNew(s => ((IResourceGroupsOperations)s).ExportTemplateAsync(resourceGroupName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Captures the specified resource group as a template.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group to be created or updated.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the export template resource group operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ResourceGroupExportResult> ExportTemplateAsync( this IResourceGroupsOperations operations, string resourceGroupName, ExportTemplateRequest parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ExportTemplateWithHttpMessagesAsync(resourceGroupName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a collection of resource groups.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
public static IPage<ResourceGroup> List(this IResourceGroupsOperations operations, ODataQuery<ResourceGroupFilter> odataQuery = default(ODataQuery<ResourceGroupFilter>))
{
return Task.Factory.StartNew(s => ((IResourceGroupsOperations)s).ListAsync(odataQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a collection of resource groups.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ResourceGroup>> ListAsync( this IResourceGroupsOperations operations, ODataQuery<ResourceGroupFilter> odataQuery = default(ODataQuery<ResourceGroupFilter>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(odataQuery, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get all of the resources under a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<GenericResource> ListResourcesNext(this IResourceGroupsOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IResourceGroupsOperations)s).ListResourcesNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get all of the resources under a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<GenericResource>> ListResourcesNextAsync( this IResourceGroupsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListResourcesNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a collection of resource groups.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<ResourceGroup> ListNext(this IResourceGroupsOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IResourceGroupsOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a collection of resource groups.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ResourceGroup>> ListNextAsync( this IResourceGroupsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using TestingApp.Areas.HelpPage.ModelDescriptions;
using TestingApp.Areas.HelpPage.Models;
namespace TestingApp.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// 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\General\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.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void GetAndWithElementInt321()
{
var test = new VectorGetAndWithElement__GetAndWithElementInt321();
// Validates basic functionality works
test.RunBasicScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
// Validates that invalid indices throws ArgumentOutOfRangeException
test.RunArgumentOutOfRangeScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorGetAndWithElement__GetAndWithElementInt321
{
private static readonly int LargestVectorSize = 32;
private static readonly int ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario(int imm = 1, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
Int32[] values = new Int32[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetInt32();
}
Vector256<Int32> value = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7]);
bool succeeded = !expectedOutOfRangeException;
try
{
Int32 result = value.GetElement(imm);
ValidateGetResult(result, values);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<Int32.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
Int32 insertedValue = TestLibrary.Generator.GetInt32();
try
{
Vector256<Int32> result2 = value.WithElement(imm, insertedValue);
ValidateWithResult(result2, values, insertedValue);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<Int32.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunReflectionScenario(int imm = 1, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
Int32[] values = new Int32[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetInt32();
}
Vector256<Int32> value = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7]);
bool succeeded = !expectedOutOfRangeException;
try
{
object result = typeof(Vector256)
.GetMethod(nameof(Vector256.GetElement))
.MakeGenericMethod(typeof(Int32))
.Invoke(null, new object[] { value, imm });
ValidateGetResult((Int32)(result), values);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<Int32.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
Int32 insertedValue = TestLibrary.Generator.GetInt32();
try
{
object result2 = typeof(Vector256)
.GetMethod(nameof(Vector256.WithElement))
.MakeGenericMethod(typeof(Int32))
.Invoke(null, new object[] { value, imm, insertedValue });
ValidateWithResult((Vector256<Int32>)(result2), values, insertedValue);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<Int32.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunArgumentOutOfRangeScenario()
{
RunBasicScenario(1 - ElementCount, expectedOutOfRangeException: true);
RunBasicScenario(1 + ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(1 - ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(1 + ElementCount, expectedOutOfRangeException: true);
}
private void ValidateGetResult(Int32 result, Int32[] values, [CallerMemberName] string method = "")
{
if (result != values[1])
{
Succeeded = false;
TestLibrary.TestFramework.LogInformation($"Vector256<Int32.GetElement(1): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
}
}
private void ValidateWithResult(Vector256<Int32> result, Int32[] values, Int32 insertedValue, [CallerMemberName] string method = "")
{
Int32[] resultElements = new Int32[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref resultElements[0]), result);
ValidateWithResult(resultElements, values, insertedValue, method);
}
private void ValidateWithResult(Int32[] result, Int32[] values, Int32 insertedValue, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (int i = 0; i < ElementCount; i++)
{
if ((i != 1) && (result[i] != values[i]))
{
succeeded = false;
break;
}
}
if (result[1] != insertedValue)
{
succeeded = false;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<Int32.WithElement(1): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" insert: insertedValue");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// ****************************************************************
// Copyright 2007, Charlie Poole
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org
// ****************************************************************
using System;
using System.Collections;
namespace NUnit.Constraints.Constraints
{
#region PrefixConstraint
/// <summary>
/// Abstract base class used for prefixes
/// </summary>
public abstract class PrefixConstraint : Constraint
{
/// <summary>
/// The base constraint
/// </summary>
protected Constraint baseConstraint;
/// <summary>
/// Construct given a base constraint
/// </summary>
/// <param name="resolvable"></param>
protected PrefixConstraint(IResolveConstraint resolvable) : base(resolvable)
{
if ( resolvable != null )
this.baseConstraint = resolvable.Resolve();
}
}
#endregion
#region NotConstraint
/// <summary>
/// NotConstraint negates the effect of some other constraint
/// </summary>
public class NotConstraint : PrefixConstraint
{
/// <summary>
/// Initializes a new instance of the <see cref="T:NotConstraint"/> class.
/// </summary>
/// <param name="baseConstraint">The base constraint to be negated.</param>
public NotConstraint(Constraint baseConstraint)
: base( baseConstraint ) { }
/// <summary>
/// Test whether the constraint is satisfied by a given value
/// </summary>
/// <param name="actual">The value to be tested</param>
/// <returns>True for if the base constraint fails, false if it succeeds</returns>
public override bool Matches(object actual)
{
this.actual = actual;
return !baseConstraint.Matches(actual);
}
/// <summary>
/// Write the constraint description to a MessageWriter
/// </summary>
/// <param name="writer">The writer on which the description is displayed</param>
public override void WriteDescriptionTo( MessageWriter writer )
{
writer.WritePredicate( "not" );
baseConstraint.WriteDescriptionTo( writer );
}
/// <summary>
/// Write the actual value for a failing constraint test to a MessageWriter.
/// </summary>
/// <param name="writer">The writer on which the actual value is displayed</param>
public override void WriteActualValueTo(MessageWriter writer)
{
baseConstraint.WriteActualValueTo (writer);
}
}
#endregion
#region AllItemsConstraint
/// <summary>
/// AllItemsConstraint applies another constraint to each
/// item in a collection, succeeding if they all succeed.
/// </summary>
public class AllItemsConstraint : PrefixConstraint
{
/// <summary>
/// Construct an AllItemsConstraint on top of an existing constraint
/// </summary>
/// <param name="itemConstraint"></param>
public AllItemsConstraint(Constraint itemConstraint)
: base( itemConstraint )
{
this.DisplayName = "all";
}
/// <summary>
/// Apply the item constraint to each item in the collection,
/// failing if any item fails.
/// </summary>
/// <param name="actual"></param>
/// <returns></returns>
public override bool Matches(object actual)
{
this.actual = actual;
if ( !(actual is IEnumerable) )
throw new ArgumentException( "The actual value must be an IEnumerable", "actual" );
foreach(object item in (IEnumerable)actual)
if (!baseConstraint.Matches(item))
return false;
return true;
}
/// <summary>
/// Write a description of this constraint to a MessageWriter
/// </summary>
/// <param name="writer"></param>
public override void WriteDescriptionTo(MessageWriter writer)
{
writer.WritePredicate("all items");
baseConstraint.WriteDescriptionTo(writer);
}
}
#endregion
#region SomeItemsConstraint
/// <summary>
/// SomeItemsConstraint applies another constraint to each
/// item in a collection, succeeding if any of them succeeds.
/// </summary>
public class SomeItemsConstraint : PrefixConstraint
{
/// <summary>
/// Construct a SomeItemsConstraint on top of an existing constraint
/// </summary>
/// <param name="itemConstraint"></param>
public SomeItemsConstraint(Constraint itemConstraint)
: base( itemConstraint )
{
this.DisplayName = "some";
}
/// <summary>
/// Apply the item constraint to each item in the collection,
/// succeeding if any item succeeds.
/// </summary>
/// <param name="actual"></param>
/// <returns></returns>
public override bool Matches(object actual)
{
this.actual = actual;
if ( !(actual is IEnumerable) )
throw new ArgumentException( "The actual value must be an IEnumerable", "actual" );
foreach(object item in (IEnumerable)actual)
if (baseConstraint.Matches(item))
return true;
return false;
}
/// <summary>
/// Write a description of this constraint to a MessageWriter
/// </summary>
/// <param name="writer"></param>
public override void WriteDescriptionTo(MessageWriter writer)
{
writer.WritePredicate("some item");
baseConstraint.WriteDescriptionTo(writer);
}
}
#endregion
#region NoItemConstraint
/// <summary>
/// NoItemConstraint applies another constraint to each
/// item in a collection, failing if any of them succeeds.
/// </summary>
public class NoItemConstraint : PrefixConstraint
{
/// <summary>
/// Construct a SomeItemsConstraint on top of an existing constraint
/// </summary>
/// <param name="itemConstraint"></param>
public NoItemConstraint(Constraint itemConstraint)
: base( itemConstraint )
{
this.DisplayName = "none";
}
/// <summary>
/// Apply the item constraint to each item in the collection,
/// failing if any item fails.
/// </summary>
/// <param name="actual"></param>
/// <returns></returns>
public override bool Matches(object actual)
{
this.actual = actual;
if ( !(actual is IEnumerable) )
throw new ArgumentException( "The actual value must be an IEnumerable", "actual" );
foreach(object item in (IEnumerable)actual)
if (baseConstraint.Matches(item))
return false;
return true;
}
/// <summary>
/// Write a description of this constraint to a MessageWriter
/// </summary>
/// <param name="writer"></param>
public override void WriteDescriptionTo(MessageWriter writer)
{
writer.WritePredicate("no item");
baseConstraint.WriteDescriptionTo(writer);
}
}
#endregion
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections;
using System.IO;
using System.Windows.Forms;
namespace OpenLiveWriter.FileDestinations
{
/// <summary>
/// The base class for all file destinations.
/// </summary>
abstract public class FileDestination : IDisposable
{
/// <summary>
/// File Destination constructor
/// </summary>
/// <param name="path">The path to the destination</param>
protected FileDestination(string path)
{
m_path = path;
m_retryCount = 5;
m_retryPause = 1000;
}
/// <summary>
/// File Destination constructor
/// </summary>
/// <param name="path">The path to the destination</param>
/// <param name="retryCount">The number of times to retry a file transfer that has
/// suffered a non fatal error</param>
/// <param name="retryPause">The amount of time, in milliseconds, to wait between
/// retries</param>
protected FileDestination(string path, int retryCount, int retryPause)
{
m_path = path;
m_retryCount = retryCount;
m_retryPause = retryPause;
}
/// <summary>
/// Insures that the directory we need to move an item into exists in the destination
/// </summary>
/// <param name="path">The directory that we should insure exists</param>
public void InsureDirectoryExists( string path)
{
// empty paths can just be ignored
if (path == String.Empty)
return;
// keep a hashtable of all the directories we've created, if we haven't
// already created this one
if (!m_createdDirectories.ContainsKey(path))
{
// If the path doesn't exist already, create it
if (!DirectoryExists(path))
CreateDirectory(path);
// Add this to the hashtable of created paths
m_createdDirectories.Add(path, true);
}
}
/// <summary>
/// Transfers the file from a path to a destination
/// </summary>
/// <param name="fromPath">The path from which to transfer the file</param>
/// <param name="toPath">The path to which to transfer the file</param>
/// <param name="overWrite">Whether or not to overwrite already existing files</param>
/// <param name="retryCount">How many times to retry the transfer of an individual
/// file</param>
/// <param name="retryPause">How long to pause between retry attempts</param>
/// <param name="status">An IPublisherStatus for status updates</param>
public void DoTransfer(
string fromPath,
string toPath,
bool overWrite)
{
//fully qualify the toPath
toPath = CombinePath(m_path, toPath);
int attempts = 0;
// wait and retry
while (attempts <= m_retryCount)
{
// if it worked, continue, otherwise keep trying
if (CopyFile(fromPath, toPath, overWrite))
break;
// Wait and then retry copyfile
attempts++;
// NOTE: This is not CPU optimized- need to optimize
// Pause - in case an intermittent connection or something
// gets restored and allows the retry to suceed
int startTime = Environment.TickCount;
while(Environment.TickCount < (startTime + m_retryPause) )
{
Application.DoEvents();
}
}
// If we retry and it never works, throw an exception
if (attempts > m_retryCount)
throw new SiteDestinationException(
null,
SiteDestinationException.TransferException,
GetType().Name,
0);
}
/// <summary>
/// This method is called to make a connection to the destination
/// </summary>
/// <returns>True/False - False means that a non fatal error has occurred</returns>
virtual public void Connect()
{
}
/// <summary>
/// Combines 2 paths parts together into a full path.
/// This method is overridable so that subclasses can determine the proper delimiter.
/// </summary>
/// <param name="path1"></param>
/// <param name="path2"></param>
virtual public string CombinePath(string path1, string path2)
{
return Path.Combine(path1, path2);
}
/// <summary>
/// The path delimiter for this destination.
/// This property is overridable so that subclasses can determine the proper delimiter.
/// </summary>
virtual public string PathDelimiter
{
get
{
return @"\";
}
}
/// <summary>
/// The path delimiter for this destination.
/// This property is overridable so that subclasses can determine the proper delimiter.
/// </summary>
virtual public char PathDelimiterChar
{
get
{
return '\\';
}
}
/// <summary>
/// This method is called to actually copy the files from one destination to another.
/// </summary>
/// <param name="FromPath">The path from which to copy files</param>
/// <param name="ToPath">The path to which to copy files</param>
/// <param name="overWriteFiles">Whether or not existing files should be overwritten</param>
/// <returns>True indicates success, False indicates a non fatal error</returns>
abstract public bool CopyFile(string FromPath, string ToPath, bool overWriteFiles);
/// <summary>
/// This method is called to determine whether a directory exists. This is used to
/// determine whether to create a new directory or not.
/// </summary>
/// <param name="Path">The directory</param>
/// <returns>true indicates the directory exists, false indicates it doesn't</returns>
abstract public bool DirectoryExists(string Path);
/// <summary>
/// This method is called to determine whether a file exists.
/// </summary>
/// <param name="Path">The file</param>
/// <returns>true indicates the file exists, false indicates it doesn't</returns>
abstract public bool FileExists(string Path);
/// <summary>
/// Deletes a file from the destination location.
/// </summary>
/// <param name="Path">The file</param>
abstract public void DeleteFile(string Path);
/// <summary>
/// Retrieves a file from the destination location.
/// </summary>
/// <param name="RemotePath">the path of the file on the destination to retrieve</param>
/// <param name="LocalFile">the local file path to copy the contents of the file</param>
/// <param name="isBinary">true if the remote file is binary</param>
/// <returns>true indicates the file was successfully transferred</returns>
abstract public bool GetFile(String RemotePath, string LocalFile, bool isBinary);
/// <summary>
/// Creates a directory based upon a path, not just a directory name.
/// </summary>
/// <param name="path">The path to create</param>
abstract public void CreateDirectory(string path);
/// <summary>
/// List the names of the directories in the specified path.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
abstract public string[] ListDirectories(string path);
/// <summary>
/// List the names of the files in the specified directory.
/// </summary>
/// <param name="path">the directory path</param>
/// <returns></returns>
abstract public string[] ListFiles(string path);
/// <summary>
/// This method is called to disconnect from the destination
/// </summary>
/// <returns>True indicates success, False indicates a non fatal error</returns>
virtual public void Disconnect()
{
}
/// <summary>
/// The internal representation of the file path
/// </summary>
protected string m_path;
private int m_retryCount;
private int m_retryPause;
/// <summary>
/// Stores a hash table of directories that were created during the transfer
/// to this file destination.
/// </summary>
private Hashtable m_createdDirectories = new Hashtable();
#region IDisposable Members
public void Dispose()
{
try
{
this.Disconnect();
}
catch(Exception)
{
}
}
#endregion
}
}
| |
/*
* BindingContext.cs - Implementation of the
* "System.Windows.Forms.BindingContext" class.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Windows.Forms
{
using System.Collections;
using System.ComponentModel;
#if CONFIG_COMPONENT_MODEL
[DefaultEvent("CollectionChanged")]
#endif
public class BindingContext : ICollection, IEnumerable
{
// Internal state.
private Hashtable list;
// Entry in the binding hash.
private class BindingHashEntry
{
// Internal state.
private Object dataSource;
private String dataMember;
// Constructor.
public BindingHashEntry(Object dataSource, String dataMember)
{
this.dataSource = dataSource;
this.dataMember = dataMember;
}
// Determine if two objects are equal
public override bool Equals(Object obj)
{
BindingHashEntry other = (obj as BindingHashEntry);
return (other.dataSource == dataSource &&
other.dataMember == dataMember);
}
// Get the hash code for this entry.
public override int GetHashCode()
{
int hash;
if(dataSource != null)
{
hash = dataSource.GetHashCode();
}
else
{
hash = 0;
}
return hash + dataMember.GetHashCode();
}
}; // class BindingHashEntry
// Constructor.
public BindingContext() {}
// Implement the ICollection interface.
void ICollection.CopyTo(Array array, int index)
{
list.Values.CopyTo(array, index);
}
int ICollection.Count
{
get
{
return list.Count;
}
}
bool ICollection.IsSynchronized
{
get
{
return false;
}
}
Object ICollection.SyncRoot
{
get
{
return this;
}
}
// Implement the IEnumerable interface.
IEnumerator IEnumerable.GetEnumerator()
{
return list.Values.GetEnumerator();
}
// Get the binding manager associated with a particular data source.
public BindingManagerBase this[Object dataSource]
{
get
{
return this[dataSource, String.Empty];
}
}
[TODO]
public BindingManagerBase this[Object dataSource, String dataMember]
{
get
{
// Set the default data member name if necessary.
if(dataMember == null)
{
dataMember = String.Empty;
}
// See if we already have an entry for the data source.
BindingHashEntry key = new BindingHashEntry
(dataSource, dataMember);
Object value = list[key];
if(value != null)
{
return (BindingManagerBase)value;
}
// TODO: create a new binding manager.
return null;
}
}
// Add an entry to this collection.
protected internal void Add
(Object dataSource, BindingManagerBase listManager)
{
AddCore(dataSource, listManager);
#if CONFIG_COMPONENT_MODEL
OnCollectionChanged
(new CollectionChangeEventArgs
(CollectionChangeAction.Add, dataSource));
#endif
}
protected virtual void AddCore
(Object dataSource, BindingManagerBase listManager)
{
if(dataSource == null)
{
throw new ArgumentNullException("dataSource");
}
if(listManager == null)
{
throw new ArgumentNullException("listManager");
}
list[new BindingHashEntry(dataSource, String.Empty)] =
listManager;
}
// Clear this collection.
protected internal void Clear()
{
ClearCore();
#if CONFIG_COMPONENT_MODEL
OnCollectionChanged
(new CollectionChangeEventArgs
(CollectionChangeAction.Refresh, null));
#endif
}
protected virtual void ClearCore()
{
list.Clear();
}
// Remove an entry from this collection.
protected internal void Remove(Object dataSource)
{
RemoveCore(dataSource);
#if CONFIG_COMPONENT_MODEL
OnCollectionChanged
(new CollectionChangeEventArgs
(CollectionChangeAction.Remove, dataSource));
#endif
}
protected virtual void RemoveCore(Object dataSource)
{
list.Remove(new BindingHashEntry(dataSource, String.Empty));
}
// Determine if this collection contains a particular data source.
public bool Contains(Object dataSource)
{
return Contains(dataSource, String.Empty);
}
public bool Contains(Object dataSource, String dataMember)
{
return list.Contains
(new BindingHashEntry(dataSource, dataMember));
}
// Determine if this collection is read-only.
public bool IsReadOnly
{
get
{
return false;
}
}
#if CONFIG_COMPONENT_MODEL
// Event that is raised when the collection changes.
public event CollectionChangeEventHandler CollectionChanged;
// Raise the "CollectionChanged" event.
protected virtual void OnCollectionChanged(CollectionChangeEventArgs e)
{
if(CollectionChanged != null)
{
CollectionChanged(this, e);
}
}
#endif // CONFIG_COMPONENT_MODEL
}; // class BindingContext
}; // namespace System.Windows.Forms
| |
using System;
using System.Collections.Generic;
namespace ICSimulator
{
/* a Priority Packet Pool is an abstract packet container that
* implements a priority/reordering/scheduling. Intended for use
* with injection queues, and possibly in-network buffers, that are
* nominally FIFO but could potentially reorder.
*/
public interface IPrioPktPool
{
void addPacket(Packet pkt);
void setNodeId(int id);
Packet next();
int Count { get; }
int FlitCount { get; }
Flit peekFlit();
void takeFlit();
bool FlitInterface { get; }
}
/* simple single-FIFO packet pool. */
public class FIFOPrioPktPool : IPrioPktPool
{
Queue<Packet> queue;
int flitCount = 0;
public FIFOPrioPktPool()
{
queue = new Queue<Packet>();
}
public void addPacket(Packet pkt)
{
flitCount += pkt.nrOfFlits;
queue.Enqueue(pkt);
}
public Packet next()
{
if (queue.Count > 0)
{
Packet p = queue.Dequeue();
flitCount -= p.nrOfFlits;
return p;
}
else
return null;
}
public void setNodeId(int id)
{
}
public int Count { get { return queue.Count; } }
public int FlitCount { get { return flitCount; } }
public bool FlitInterface { get { return false; } }
public Flit peekFlit() { return null; }
public void takeFlit() { }
}
/* multi-queue priority packet pool, based on Packet's notion of
* queues (Packet.numQueues and Packet.getQueue() ): currently
* Packet implements these based on the cache-coherence protocol,
* so that control, data, and writeback packets have separate queues.
*/
public class MultiQPrioPktPool : IPrioPktPool
{
Queue<Packet>[] queues;
int nqueues;
int queue_next;
int flitCount = 0;
public MultiQPrioPktPool()
{
nqueues = Packet.numQueues;
queues = new Queue<Packet>[nqueues];
for (int i = 0; i < nqueues; i++)
queues[i] = new Queue<Packet>();
queue_next = nqueues - 1;
}
public void addPacket(Packet pkt)
{
flitCount += pkt.nrOfFlits;
queues[pkt.getQueue()].Enqueue(pkt);
}
void advanceRR()
{
int tries = nqueues;
do
queue_next = (queue_next + 1) % nqueues;
while (tries-- > 0 && queues[queue_next].Count == 0);
}
public Packet next()
{
advanceRR();
if (queues[queue_next].Count > 0)
{
Packet p = queues[queue_next].Dequeue();
flitCount -= p.nrOfFlits;
return p;
}
else
return null;
}
public void setNodeId(int id)
{
}
public int Count
{
get
{
int sum = 0;
for (int i = 0; i < nqueues; i++)
sum += queues[i].Count;
return sum;
}
}
public int FlitCount { get { return flitCount; } }
public bool FlitInterface { get { return false; } }
public Flit peekFlit() { return null; }
public void takeFlit() { }
}
/**
* @brief Same as the multiqpriopktpool with throttling on request packet
* enabled.
**/
public class MultiQThrottlePktPool : IPrioPktPool
{
Queue<Packet>[] queues;
int nqueues;
int queue_next;
int node_id=-1;
int flitCount = 0;
public static IPrioPktPool construct()
{
if (Config.cluster_prios_injq)
return new ReallyNiftyPrioritizingPacketPool();
else
return new MultiQThrottlePktPool();
}
private MultiQThrottlePktPool()
{
nqueues = Packet.numQueues;
queues = new Queue<Packet>[nqueues];
for (int i = 0; i < nqueues; i++)
queues[i] = new Queue<Packet>();
queue_next = nqueues - 1;
}
public void addPacket(Packet pkt)
{
flitCount += pkt.nrOfFlits;
queues[pkt.getQueue()].Enqueue(pkt);
}
void advanceRR()
{
int tries = nqueues;
bool inject = Simulator.controller.tryInject (node_id);
do
queue_next = (queue_next + 1) % nqueues;
while ((tries-- > 0 && queues [queue_next].Count == 0) || (queue_next == 0 && !inject && Config.throttle_at_NI));
//while (tries-- > 0 && queues[queue_next].Count == 0 &&
// (queue_next==0 || !Simulator.controller.tryInject(node_id)));
}
public Packet next()
{
if(node_id==-1)
throw new Exception("Haven't configured the packet pool");
advanceRR();
if (queues [queue_next].Count > 0 ){
Packet p = queues [queue_next].Dequeue ();
flitCount -= p.nrOfFlits;
return p;
}
else
return null;
}
public void setNodeId(int id)
{
node_id=id;
}
public int Count
{
get
{
int sum = 0;
for (int i = 0; i < nqueues; i++)
sum += queues[i].Count;
return sum;
}
}
public int FlitCount { get { return flitCount; } }
public bool FlitInterface { get { return false; } }
public Flit peekFlit() { return null; }
public void takeFlit() { }
}
/** @brief the Really Nifty Prioritizing Packet Pool respects full
* priorities (i.e., by using a min-heap) and also optionally respects
* throttling.
*/
public class ReallyNiftyPrioritizingPacketPool : IPrioPktPool
{
class HeapNode : IComparable
{
public Packet pkt;
public HeapNode(Packet p) { pkt = p; }
public int CompareTo(object o)
{
if (o is HeapNode)
return Simulator.controller.rankFlits(pkt.flits[0], (o as HeapNode).pkt.flits[0]);
else
throw new ArgumentException("bad comparison");
}
}
MinHeap<HeapNode>[] heaps;
int nheaps;
int heap_next;
int flitCount = 0;
int node_id = -1;
public ReallyNiftyPrioritizingPacketPool()
{
nheaps = Packet.numQueues;
heaps = new MinHeap<HeapNode>[nheaps];
for (int i = 0; i < nheaps; i++)
heaps[i] = new MinHeap<HeapNode>();
heap_next = nheaps - 1;
}
public void addPacket(Packet pkt)
{
flitCount += pkt.nrOfFlits;
HeapNode h = new HeapNode(pkt);
heaps[pkt.getQueue()].Enqueue(h);
}
void advanceRR()
{
int tries = nheaps;
do
heap_next = (heap_next + 1) % nheaps;
// keep incrementing while we're at an empty queue or at req-queue and throttling
while (tries-- > 0 &&
((heaps[heap_next].Count == 0) ||
(heap_next == 0 && !Simulator.controller.tryInject(node_id))));
}
public Packet next()
{
advanceRR();
//only queues for non-control packets go proceed without any
//throttling constraint
if (heaps[heap_next].Count > 0 &&
(heap_next!=0 || Simulator.controller.tryInject(node_id)) )
{
HeapNode h = heaps[heap_next].Dequeue();
Packet p = h.pkt;
flitCount -= p.nrOfFlits;
return p;
}
else
return null;
}
public void setNodeId(int id)
{
node_id = id;
}
public int Count
{
get
{
int sum = 0;
for (int i = 0; i < nheaps; i++)
sum += heaps[i].Count;
return sum;
}
}
public int FlitCount { get { return flitCount; } }
public bool FlitInterface { get { return false; } }
public Flit peekFlit() { return null; }
public void takeFlit() { }
}
}
| |
using JetBrains.Annotations;
using JetBrains.Collections.Viewable;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Feature.Services.Occurrences;
using JetBrains.ReSharper.Feature.Services.Tree;
using JetBrains.ReSharper.Plugins.Unity.Core.ProjectModel;
using JetBrains.ReSharper.Plugins.Unity.Resources.Icons;
using JetBrains.ReSharper.Plugins.Unity.UnityEditorIntegration;
using JetBrains.ReSharper.Plugins.Unity.Yaml.Feature.Services.Navigation;
using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.Caches;
using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.DeferredCaches;
using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.DeferredCaches.AssetHierarchy;
using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.DeferredCaches.AssetHierarchy.Elements;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Resources.Shell;
using JetBrains.Rider.Backend.Features.Usages;
using JetBrains.Rider.Backend.Platform.Icons;
using JetBrains.Rider.Model;
using JetBrains.UI.Icons;
using JetBrains.Util;
namespace JetBrains.ReSharper.Plugins.Unity.Rider.Integration.Yaml.Feature.Usages
{
[SolutionComponent]
public class UnityYamlExtraGroupingRulesProvider : IRiderExtraGroupingRulesProvider
{
// IconHost is optional so that we don't fail if we're in tests
public UnityYamlExtraGroupingRulesProvider(MetaFileGuidCache metaFileGuidCache = null, UnitySolutionTracker unitySolutionTracker = null, IconHost iconHost = null)
{
if (unitySolutionTracker != null && unitySolutionTracker.IsUnityProject.HasValue() && unitySolutionTracker.IsUnityProject.Value
&& iconHost != null && metaFileGuidCache != null)
{
ExtraRules = new IRiderUsageGroupingRule[]
{
new GameObjectUsageGroupingRule(iconHost),
new ComponentUsageGroupingRule(metaFileGuidCache, iconHost),
new AnimationEventGroupingRule(iconHost),
new AnimatorGroupingRule(iconHost)
};
}
else
{
ExtraRules = new IRiderUsageGroupingRule[0];
}
}
public IRiderUsageGroupingRule[] ExtraRules { get; }
}
public abstract class UnityYamlUsageGroupingRuleBase : IRiderUsageGroupingRule
{
[CanBeNull] private readonly IconHost myIconHost;
protected UnityYamlUsageGroupingRuleBase(string name, IconId iconId, [CanBeNull] IconHost iconHost,
double sortingPriority)
{
Name = name;
IconId = iconId;
SortingPriority = sortingPriority;
myIconHost = iconHost;
}
protected RdUsageGroup CreateModel(string text)
{
return new RdUsageGroup(Name, text, myIconHost?.Transform(IconId));
}
protected RdUsageGroup EmptyModel()
{
return new RdUsageGroup(Name, string.Empty, null);
}
public abstract RdUsageGroup CreateModel(IOccurrence occurrence, IOccurrenceBrowserDescriptor descriptor);
public abstract void Navigate(IOccurrence occurrence);
public string Name { get; }
public IconId IconId { get; }
public bool IsSeparable => true;
public abstract bool IsNavigateable { get; }
public bool Configurable => true;
public bool PriorityDependsOnUsages => true;
public double SortingPriority { get; }
public bool DefaultValue { get; } = true;
public IDeclaredElement GetDeclaredElement(IOccurrence occurrence) => null;
public IProjectItem GetProjectItem(IOccurrence occurrence) => null;
}
public class AnimatorGroupingRule : UnityYamlUsageGroupingRuleBase
{
public AnimatorGroupingRule([NotNull] IconHost iconHost)
: base("Animator", UnityFileTypeThemedIcons.FileAnimatorController.Id, iconHost, 10.0)
{
}
public override RdUsageGroup CreateModel(IOccurrence occurrence, IOccurrenceBrowserDescriptor descriptor)
{
if (!(occurrence is UnityAnimatorScriptOccurence animationEventOccurence)) return EmptyModel();
var text = animationEventOccurence.GetDisplayText()?.Text.Split('/');
return text != null ? CreateModel(text.Join("\\")) : EmptyModel();
}
public override void Navigate(IOccurrence occurrence)
{
throw new System.NotImplementedException();
}
public override bool IsNavigateable => false;
}
public class AnimationEventGroupingRule : UnityYamlUsageGroupingRuleBase
{
public AnimationEventGroupingRule([NotNull] IconHost iconHost)
: base("AnimationEvent", UnityFileTypeThemedIcons.FileAnimationClip.Id, iconHost, 9.0)
{
}
public override RdUsageGroup CreateModel(IOccurrence occurrence, IOccurrenceBrowserDescriptor descriptor)
{
if (!(occurrence is UnityAnimationEventOccurence animationEventOccurence)) return EmptyModel();
var text = animationEventOccurence.GetDisplayText()?.Text;
return text != null ? CreateModel(text) : EmptyModel();
}
public override void Navigate(IOccurrence occurrence)
{
throw new System.NotImplementedException();
}
public override bool IsNavigateable => false;
}
// The priorities here put us after directory, file, namespace, type and member
public class GameObjectUsageGroupingRule : UnityYamlUsageGroupingRuleBase
{
// Note that the name is in CamelCase and spaces are added in the frontend
public GameObjectUsageGroupingRule([NotNull] IconHost iconHost)
: base("UnityGameObject", UnityObjectTypeThemedIcons.UnityGameObject.Id, iconHost, 7.0)
{
}
public override RdUsageGroup CreateModel(IOccurrence occurrence, IOccurrenceBrowserDescriptor descriptor)
{
using (CompilationContextCookie.GetExplicitUniversalContextIfNotSet())
{
if (occurrence is UnityAssetOccurrence assetOccurrence &&
!assetOccurrence.SourceFile.IsAsset() &&
!assetOccurrence.SourceFile.IsAnim() &&
!assetOccurrence.SourceFile.IsController())
{
using (ReadLockCookie.Create())
{
var solution = occurrence.GetSolution();
var processor = solution.GetComponent<AssetHierarchyProcessor>();
var consumer = new UnityScenePathGameObjectConsumer();
processor.ProcessSceneHierarchyFromComponentToRoot(assetOccurrence.OwningElementLocation, consumer, true, true);
string name = "...";
if (consumer.NameParts.Count > 0)
name = string.Join("\\", consumer.NameParts);
return CreateModel(name);
}
}
}
return EmptyModel();
}
public override void Navigate(IOccurrence occurrence)
{
throw new System.NotImplementedException();
}
public override bool IsNavigateable => false;
}
public class ComponentUsageGroupingRule : UnityYamlUsageGroupingRuleBase
{
private readonly MetaFileGuidCache myMetaFileGuidCache;
// Note that the name is in CamelCase and spaces are added in the frontend
public ComponentUsageGroupingRule(MetaFileGuidCache metaFileGuidCache, [NotNull] IconHost iconHost)
: base("UnityComponent", UnityObjectTypeThemedIcons.UnityComponent.Id, iconHost, 8.0)
{
myMetaFileGuidCache = metaFileGuidCache;
}
public override RdUsageGroup CreateModel(IOccurrence occurrence, IOccurrenceBrowserDescriptor descriptor)
{
using (CompilationContextCookie.GetExplicitUniversalContextIfNotSet())
{
if (occurrence is UnityAssetOccurrence assetOccurrence &&
!assetOccurrence.SourceFile.IsAsset() &&
!assetOccurrence.SourceFile.IsAnim() &&
!assetOccurrence.SourceFile.IsController())
{
var hierarchyContainer = assetOccurrence.GetSolution()?.GetComponent<AssetDocumentHierarchyElementContainer>();
var element = hierarchyContainer?.GetHierarchyElement(assetOccurrence.OwningElementLocation, true);
if (element is IComponentHierarchy componentHierarchyElement)
return CreateModel(AssetUtils.GetComponentName(myMetaFileGuidCache, componentHierarchyElement));
}
}
return EmptyModel();
}
public override void Navigate(IOccurrence occurrence)
{
throw new System.NotImplementedException();
}
public override bool IsNavigateable => false;
}
}
| |
/*
* 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 elasticloadbalancing-2012-06-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.ElasticLoadBalancing.Model
{
/// <summary>
/// Information about a load balancer.
/// </summary>
public partial class LoadBalancerDescription
{
private List<string> _availabilityZones = new List<string>();
private List<BackendServerDescription> _backendServerDescriptions = new List<BackendServerDescription>();
private string _canonicalHostedZoneName;
private string _canonicalHostedZoneNameID;
private DateTime? _createdTime;
private string _dnsName;
private HealthCheck _healthCheck;
private List<Instance> _instances = new List<Instance>();
private List<ListenerDescription> _listenerDescriptions = new List<ListenerDescription>();
private string _loadBalancerName;
private Policies _policies;
private string _scheme;
private List<string> _securityGroups = new List<string>();
private SourceSecurityGroup _sourceSecurityGroup;
private List<string> _subnets = new List<string>();
private string _vpcId;
/// <summary>
/// Empty constructor used to set properties independently even when a simple constructor is available
/// </summary>
public LoadBalancerDescription() { }
/// <summary>
/// Gets and sets the property AvailabilityZones.
/// <para>
/// The Availability Zones for the load balancer.
/// </para>
/// </summary>
public List<string> AvailabilityZones
{
get { return this._availabilityZones; }
set { this._availabilityZones = value; }
}
// Check to see if AvailabilityZones property is set
internal bool IsSetAvailabilityZones()
{
return this._availabilityZones != null && this._availabilityZones.Count > 0;
}
/// <summary>
/// Gets and sets the property BackendServerDescriptions.
/// <para>
/// Information about the back-end servers.
/// </para>
/// </summary>
public List<BackendServerDescription> BackendServerDescriptions
{
get { return this._backendServerDescriptions; }
set { this._backendServerDescriptions = value; }
}
// Check to see if BackendServerDescriptions property is set
internal bool IsSetBackendServerDescriptions()
{
return this._backendServerDescriptions != null && this._backendServerDescriptions.Count > 0;
}
/// <summary>
/// Gets and sets the property CanonicalHostedZoneName.
/// <para>
/// The Amazon Route 53 hosted zone associated with the load balancer.
/// </para>
///
/// <para>
/// For more information, see <a href="http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/using-domain-names-with-elb.html">Using
/// Domain Names With Elastic Load Balancing</a> in the <i>Elastic Load Balancing Developer
/// Guide</i>.
/// </para>
/// </summary>
public string CanonicalHostedZoneName
{
get { return this._canonicalHostedZoneName; }
set { this._canonicalHostedZoneName = value; }
}
// Check to see if CanonicalHostedZoneName property is set
internal bool IsSetCanonicalHostedZoneName()
{
return this._canonicalHostedZoneName != null;
}
/// <summary>
/// Gets and sets the property CanonicalHostedZoneNameID.
/// <para>
/// The ID of the Amazon Route 53 hosted zone name associated with the load balancer.
/// </para>
/// </summary>
public string CanonicalHostedZoneNameID
{
get { return this._canonicalHostedZoneNameID; }
set { this._canonicalHostedZoneNameID = value; }
}
// Check to see if CanonicalHostedZoneNameID property is set
internal bool IsSetCanonicalHostedZoneNameID()
{
return this._canonicalHostedZoneNameID != null;
}
/// <summary>
/// Gets and sets the property CreatedTime.
/// <para>
/// The date and time the load balancer was created.
/// </para>
/// </summary>
public DateTime CreatedTime
{
get { return this._createdTime.GetValueOrDefault(); }
set { this._createdTime = value; }
}
// Check to see if CreatedTime property is set
internal bool IsSetCreatedTime()
{
return this._createdTime.HasValue;
}
/// <summary>
/// Gets and sets the property DNSName.
/// <para>
/// The external DNS name of the load balancer.
/// </para>
/// </summary>
public string DNSName
{
get { return this._dnsName; }
set { this._dnsName = value; }
}
// Check to see if DNSName property is set
internal bool IsSetDNSName()
{
return this._dnsName != null;
}
/// <summary>
/// Gets and sets the property HealthCheck.
/// <para>
/// Information about the health checks conducted on the load balancer.
/// </para>
/// </summary>
public HealthCheck HealthCheck
{
get { return this._healthCheck; }
set { this._healthCheck = value; }
}
// Check to see if HealthCheck property is set
internal bool IsSetHealthCheck()
{
return this._healthCheck != null;
}
/// <summary>
/// Gets and sets the property Instances.
/// <para>
/// The IDs of the instances for the load balancer.
/// </para>
/// </summary>
public List<Instance> Instances
{
get { return this._instances; }
set { this._instances = value; }
}
// Check to see if Instances property is set
internal bool IsSetInstances()
{
return this._instances != null && this._instances.Count > 0;
}
/// <summary>
/// Gets and sets the property ListenerDescriptions.
/// <para>
/// The listeners for the load balancer.
/// </para>
/// </summary>
public List<ListenerDescription> ListenerDescriptions
{
get { return this._listenerDescriptions; }
set { this._listenerDescriptions = value; }
}
// Check to see if ListenerDescriptions property is set
internal bool IsSetListenerDescriptions()
{
return this._listenerDescriptions != null && this._listenerDescriptions.Count > 0;
}
/// <summary>
/// Gets and sets the property LoadBalancerName.
/// <para>
/// The name of the load balancer.
/// </para>
/// </summary>
public string LoadBalancerName
{
get { return this._loadBalancerName; }
set { this._loadBalancerName = value; }
}
// Check to see if LoadBalancerName property is set
internal bool IsSetLoadBalancerName()
{
return this._loadBalancerName != null;
}
/// <summary>
/// Gets and sets the property Policies.
/// <para>
/// The policies defined for the load balancer.
/// </para>
/// </summary>
public Policies Policies
{
get { return this._policies; }
set { this._policies = value; }
}
// Check to see if Policies property is set
internal bool IsSetPolicies()
{
return this._policies != null;
}
/// <summary>
/// Gets and sets the property Scheme.
/// <para>
/// The type of load balancer. Valid only for load balancers in a VPC.
/// </para>
///
/// <para>
/// If <code>Scheme</code> is <code>internet-facing</code>, the load balancer has a public
/// DNS name that resolves to a public IP address.
/// </para>
///
/// <para>
/// If <code>Scheme</code> is <code>internal</code>, the load balancer has a public DNS
/// name that resolves to a private IP address.
/// </para>
/// </summary>
public string Scheme
{
get { return this._scheme; }
set { this._scheme = value; }
}
// Check to see if Scheme property is set
internal bool IsSetScheme()
{
return this._scheme != null;
}
/// <summary>
/// Gets and sets the property SecurityGroups.
/// <para>
/// The security groups for the load balancer. Valid only for load balancers in a VPC.
/// </para>
/// </summary>
public List<string> SecurityGroups
{
get { return this._securityGroups; }
set { this._securityGroups = value; }
}
// Check to see if SecurityGroups property is set
internal bool IsSetSecurityGroups()
{
return this._securityGroups != null && this._securityGroups.Count > 0;
}
/// <summary>
/// Gets and sets the property SourceSecurityGroup.
/// <para>
/// The security group that you can use as part of your inbound rules for your load balancer's
/// back-end application instances. To only allow traffic from load balancers, add a security
/// group rule to your back end instance that specifies this source security group as
/// the inbound source.
/// </para>
/// </summary>
public SourceSecurityGroup SourceSecurityGroup
{
get { return this._sourceSecurityGroup; }
set { this._sourceSecurityGroup = value; }
}
// Check to see if SourceSecurityGroup property is set
internal bool IsSetSourceSecurityGroup()
{
return this._sourceSecurityGroup != null;
}
/// <summary>
/// Gets and sets the property Subnets.
/// <para>
/// The IDs of the subnets for the load balancer.
/// </para>
/// </summary>
public List<string> Subnets
{
get { return this._subnets; }
set { this._subnets = value; }
}
// Check to see if Subnets property is set
internal bool IsSetSubnets()
{
return this._subnets != null && this._subnets.Count > 0;
}
/// <summary>
/// Gets and sets the property VPCId.
/// <para>
/// The ID of the VPC for the load balancer.
/// </para>
/// </summary>
public string VPCId
{
get { return this._vpcId; }
set { this._vpcId = value; }
}
// Check to see if VPCId property is set
internal bool IsSetVPCId()
{
return this._vpcId != null;
}
}
}
| |
using System;
using NUnit.Framework;
using NServiceKit.Common.Extensions;
using NServiceKit.DataAnnotations;
using NServiceKit.Logging;
using NServiceKit.Text;
namespace NServiceKit.Common.Tests.Models
{
/// <summary>A model with fields of different types as nullables.</summary>
public class ModelWithFieldsOfDifferentTypesAsNullables
{
/// <summary>The log.</summary>
private static readonly ILog Log = LogManager.GetLogger(typeof(ModelWithFieldsOfDifferentTypesAsNullables));
/// <summary>Gets or sets the identifier.</summary>
/// <value>The identifier.</value>
public int? Id { get; set; }
/// <summary>Gets or sets the name.</summary>
/// <value>The name.</value>
public string Name { get; set; }
/// <summary>Gets or sets the identifier of the long.</summary>
/// <value>The identifier of the long.</value>
public long? LongId { get; set; }
/// <summary>Gets or sets a unique identifier.</summary>
/// <value>The identifier of the unique.</value>
public Guid? Guid { get; set; }
/// <summary>Gets or sets the. </summary>
/// <value>The bool.</value>
public bool? Bool { get; set; }
/// <summary>Gets or sets the date time.</summary>
/// <value>The date time.</value>
public DateTime? DateTime { get; set; }
/// <summary>Gets or sets the double.</summary>
/// <value>The double.</value>
public double? Double { get; set; }
/// <summary>Creates a new ModelWithFieldsOfDifferentTypesAsNullables.</summary>
/// <param name="id">The identifier.</param>
/// <returns>The ModelWithFieldsOfDifferentTypesAsNullables.</returns>
public static ModelWithFieldsOfDifferentTypesAsNullables Create(int id)
{
var row = new ModelWithFieldsOfDifferentTypesAsNullables {
Id = id,
Bool = id % 2 == 0,
DateTime = System.DateTime.Now.AddDays(id),
Double = 1.11d + id,
Guid = System.Guid.NewGuid(),
LongId = 999 + id,
Name = "Name" + id
};
return row;
}
/// <summary>Creates a constant.</summary>
/// <param name="id">The identifier.</param>
/// <returns>The new constant.</returns>
public static ModelWithFieldsOfDifferentTypesAsNullables CreateConstant(int id)
{
var row = new ModelWithFieldsOfDifferentTypesAsNullables {
Id = id,
Bool = id % 2 == 0,
DateTime = new DateTime(1979, (id % 12) + 1, (id % 28) + 1),
Double = 1.11d + id,
Guid = new Guid(((id % 240) + 16).ToString("X") + "726E3B-9983-40B4-A8CB-2F8ADA8C8760"),
LongId = 999 + id,
Name = "Name" + id
};
return row;
}
/// <summary>Assert is equal.</summary>
/// <param name="actual"> The actual.</param>
/// <param name="expected">The expected.</param>
public static void AssertIsEqual(ModelWithFieldsOfDifferentTypes actual, ModelWithFieldsOfDifferentTypesAsNullables expected)
{
Assert.That(actual.Id, Is.EqualTo(expected.Id.Value));
Assert.That(actual.Name, Is.EqualTo(expected.Name));
Assert.That(actual.Guid, Is.EqualTo(expected.Guid.Value));
Assert.That(actual.LongId, Is.EqualTo(expected.LongId.Value));
Assert.That(actual.Bool, Is.EqualTo(expected.Bool.Value));
try
{
Assert.That(actual.DateTime, Is.EqualTo(expected.DateTime.Value));
}
catch (Exception ex)
{
Log.Error("Trouble with DateTime precisions, trying Assert again with rounding to seconds", ex);
Assert.That(actual.DateTime.RoundToSecond(), Is.EqualTo(expected.DateTime.Value.RoundToSecond()));
}
try
{
Assert.That(actual.Double, Is.EqualTo(expected.Double.Value));
}
catch (Exception ex)
{
Log.Error("Trouble with double precisions, trying Assert again with rounding to 10 decimals", ex);
Assert.That(Math.Round(actual.Double, 10), Is.EqualTo(Math.Round(actual.Double, 10)));
}
}
}
/// <summary>A model with fields of different types.</summary>
public class ModelWithFieldsOfDifferentTypes
{
/// <summary>The log.</summary>
private static readonly ILog Log = LogManager.GetLogger(typeof(ModelWithFieldsOfDifferentTypes));
/// <summary>Gets or sets the identifier.</summary>
/// <value>The identifier.</value>
[AutoIncrement]
public int Id { get; set; }
/// <summary>Gets or sets the name.</summary>
/// <value>The name.</value>
public string Name { get; set; }
/// <summary>Gets or sets the identifier of the long.</summary>
/// <value>The identifier of the long.</value>
public long LongId { get; set; }
/// <summary>Gets or sets a unique identifier.</summary>
/// <value>The identifier of the unique.</value>
public Guid Guid { get; set; }
/// <summary>Gets or sets a value indicating whether the. </summary>
/// <value>true if , false if not.</value>
public bool Bool { get; set; }
/// <summary>Gets or sets the date time.</summary>
/// <value>The date time.</value>
public DateTime DateTime { get; set; }
/// <summary>Gets or sets the double.</summary>
/// <value>The double.</value>
public double Double { get; set; }
/// <summary>Creates a new ModelWithFieldsOfDifferentTypes.</summary>
/// <param name="id">The identifier.</param>
/// <returns>The ModelWithFieldsOfDifferentTypes.</returns>
public static ModelWithFieldsOfDifferentTypes Create(int id)
{
var row = new ModelWithFieldsOfDifferentTypes {
Id = id,
Bool = id % 2 == 0,
DateTime = DateTime.Now.AddDays(id),
Double = 1.11d + id,
Guid = Guid.NewGuid(),
LongId = 999 + id,
Name = "Name" + id
};
return row;
}
/// <summary>Creates a constant.</summary>
/// <param name="id">The identifier.</param>
/// <returns>The new constant.</returns>
public static ModelWithFieldsOfDifferentTypes CreateConstant(int id)
{
var row = new ModelWithFieldsOfDifferentTypes {
Id = id,
Bool = id % 2 == 0,
DateTime = new DateTime(1979, (id % 12) + 1, (id % 28) + 1),
Double = 1.11d + id,
Guid = new Guid(((id % 240) + 16).ToString("X") + "726E3B-9983-40B4-A8CB-2F8ADA8C8760"),
LongId = 999 + id,
Name = "Name" + id
};
return row;
}
/// <summary>
/// Determines whether the specified <see cref="T:System.Object" /> is equal to the current
/// <see cref="T:System.Object" />.
/// </summary>
/// <param name="obj">The object to compare with the current object.</param>
/// <returns>
/// true if the specified <see cref="T:System.Object" /> is equal to the current
/// <see cref="T:System.Object" />; otherwise, false.
/// </returns>
public override bool Equals(object obj)
{
var other = obj as ModelWithFieldsOfDifferentTypes;
if (other == null) return false;
try
{
AssertIsEqual(this, other);
return true;
}
catch (Exception)
{
return false;
}
}
/// <summary>Serves as a hash function for a particular type.</summary>
/// <returns>A hash code for the current <see cref="T:System.Object" />.</returns>
public override int GetHashCode()
{
return (Id + Guid.ToString()).GetHashCode();
}
/// <summary>Assert is equal.</summary>
/// <param name="actual"> The actual.</param>
/// <param name="expected">The expected.</param>
public static void AssertIsEqual(ModelWithFieldsOfDifferentTypes actual, ModelWithFieldsOfDifferentTypes expected)
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.Name, Is.EqualTo(expected.Name));
Assert.That(actual.Guid, Is.EqualTo(expected.Guid));
Assert.That(actual.LongId, Is.EqualTo(expected.LongId));
Assert.That(actual.Bool, Is.EqualTo(expected.Bool));
try
{
Assert.That(actual.DateTime, Is.EqualTo(expected.DateTime));
}
catch (Exception ex)
{
Log.Error("Trouble with DateTime precisions, trying Assert again with rounding to seconds", ex);
Assert.That(actual.DateTime.RoundToSecond(), Is.EqualTo(expected.DateTime.RoundToSecond()));
}
try
{
Assert.That(actual.Double, Is.EqualTo(expected.Double));
}
catch (Exception ex)
{
Log.Error("Trouble with double precisions, trying Assert again with rounding to 10 decimals", ex);
Assert.That(Math.Round(actual.Double, 10), Is.EqualTo(Math.Round(actual.Double, 10)));
}
}
}
}
| |
using System;
using Server;
using Server.Gumps;
namespace Knives.Chat3
{
public class ProfileGump : GumpPlus
{
private Mobile c_Target;
public ProfileGump(Mobile m, Mobile targ)
: base(m, 100, 100)
{
Override = true;
c_Target = targ;
}
protected override void BuildGump()
{
int width = 300;
int y = 10;
AddImage(10, y, 0x589);
Avatar av = Avatar.GetAvatar(c_Target);
if (av.Id < 100000)
AddImage(10 + av.X, y + av.Y, av.Id);
else
AddItem(10 + av.X, y + av.Y, av.Id - 100000);
AddHtml(95, y, width-95, Server.Misc.Titles.ComputeTitle(Owner, c_Target));
if (Owner.AccessLevel != AccessLevel.Player)
AddHtml(95, y += 20, width - 95, "Access: " + c_Target.AccessLevel);
else if (c_Target.AccessLevel != AccessLevel.Player)
AddHtml(95, y += 20, width - 95, "" + c_Target.AccessLevel);
else
{
if (c_Target.Guild != null)
AddHtml(95, y += 20, width - 95, "[" + c_Target.Guild.Abbreviation + "] " + c_Target.GuildTitle);
if (General.IsInFaction(c_Target))
AddHtml(95, y += 20, width - 95, General.FactionName(c_Target) + " " + General.FactionTitle(c_Target));
}
if (y < 89)
y = 89;
if (Owner == c_Target)
{
AddButton(32, y, 0x2626, 0x2627, "Avatar Down", new GumpCallback(AvatarDown));
AddButton(52, y, 0x2622, 0x2623, "Avatar Up", new GumpCallback(AvatarUp));
}
AddHtml(0, y+=20, width, "<CENTER>" + General.Local(253) + " " + Data.GetData(c_Target).Karma);
if (Owner == c_Target)
{
AddHtml(20, y += 25, 100, General.Local(247));
AddTextField(20, y+=25, width - 40, 65, 0x480, 0xBBC, "Signature", Data.GetData(c_Target).Signature);
AddHtml(width - 125, y += 65, 50, General.Local(244));
AddHtml(width - 65, y, 50, General.Local(245));
AddButton(width - 140, y + 3, 0x2716, "Clear Sig", new GumpCallback(ClearSig));
AddButton(width - 80, y + 3, 0x2716, "Submit Sig", new GumpCallback(SubmitSig));
}
else
{
AddHtml(20, y += 25, width - 40, 65, "'" + Data.GetData(c_Target).Signature + "'", false, false);
y += 65;
}
if (Owner != c_Target)
ViewOptions(width);
AddBackgroundZero(0, 0, width, y+40, Data.GetData(c_Target).DefaultBack);
}
private void ViewOptions(int x)
{
int y = 10;
int width = 150;
AddHtml(x, y += 10, width, "<CENTER>" + General.Local(0));
AddButton(x + width / 2 - 60, y, Data.GetData(Owner).Friends.Contains(c_Target) ? 0x2343 : 0x2342, "Friend", new GumpCallback(Friend));
AddButton(x + width / 2 + 40, y, Data.GetData(Owner).Friends.Contains(c_Target) ? 0x2343 : 0x2342, "Friend", new GumpCallback(Friend));
AddHtml(x, y += 20, width, "<CENTER>" + General.Local(2));
AddButton(x + width / 2 - 60, y, Data.GetData(Owner).Ignores.Contains(c_Target) ? 0x2343 : 0x2342, "Ignore", new GumpCallback(Ignore));
AddButton(x + width / 2 + 40, y, Data.GetData(Owner).Ignores.Contains(c_Target) ? 0x2343 : 0x2342, "Ignore", new GumpCallback(Ignore));
if (Chat3.Message.CanMessage(Owner, c_Target))
{
AddHtml(x, y += 20, width, "<CENTER>" + General.Local(13));
AddButton(x + width / 2 - 60, y + 3, 0x2716, "Send Message", new GumpCallback(Message));
AddButton(x + width / 2 + 50, y + 3, 0x2716, "Send Message", new GumpCallback(Message));
}
if (Owner.AccessLevel >= AccessLevel.Administrator)
{
if (Owner.AccessLevel > c_Target.AccessLevel)
{
AddHtml(x, y += 20, width, HTML.LightPurple + "<CENTER>" + General.Local(14), false);
AddButton(x + width / 2 - 60, y + 3, 0x2716, "Become User", new GumpCallback(BecomeUser));
AddButton(x + width / 2 + 50, y + 3, 0x2716, "Become User", new GumpCallback(BecomeUser));
}
if (c_Target.AccessLevel < AccessLevel.Administrator && c_Target.AccessLevel != AccessLevel.Player)
{
AddHtml(x, y += 20, width, HTML.LightPurple + "<CENTER>" + General.Local(4), false);
AddButton(x + width / 2 - 60, y, Data.GetData(c_Target).GlobalAccess ? 0x2343 : 0x2342, "Global Access", new GumpCallback(GlobalAccess));
AddButton(x + width / 2 + 40, y, Data.GetData(c_Target).GlobalAccess ? 0x2343 : 0x2342, "Global Access", new GumpCallback(GlobalAccess));
}
}
if (Owner.AccessLevel >= AccessLevel.GameMaster && c_Target.AccessLevel == AccessLevel.Player)
{
AddHtml(x, y += 20, width, HTML.Red + "<CENTER>" + General.Local(6), false);
AddButton(x + width / 2 - 60, y, Data.GetData(c_Target).Banned ? 0x2343 : 0x2342, "Ban", new GumpCallback(Ban));
AddButton(x + width / 2 + 40, y, Data.GetData(c_Target).Banned ? 0x2343 : 0x2342, "Ban", new GumpCallback(Ban));
}
if (Data.GetData(Owner).GlobalAccess)
{
y += 20;
if (Data.GetData(Owner).Global)
{
AddHtml(x, y += 20, width, HTML.Red + "<CENTER>" + General.Local(8), false);
AddButton(x + width / 2 - 60, y, Data.GetData(Owner).GIgnores.Contains(c_Target) ? 0x2343 : 0x2342, "Global Ignore", new GumpCallback(GIgnore));
AddButton(x + width / 2 + 40, y, Data.GetData(Owner).GIgnores.Contains(c_Target) ? 0x2343 : 0x2342, "Global Ignore", new GumpCallback(GIgnore));
}
else
{
AddHtml(x, y += 20, width, HTML.Red + "<CENTER>" + General.Local(10), false);
AddButton(x + width / 2 - 60, y, Data.GetData(Owner).GListens.Contains(c_Target) ? 0x2343 : 0x2342, "Global Listen", new GumpCallback(GListen));
AddButton(x + width / 2 + 40, y, Data.GetData(Owner).GListens.Contains(c_Target) ? 0x2343 : 0x2342, "Global Listen", new GumpCallback(GListen));
}
}
if (Owner.AccessLevel >= AccessLevel.GameMaster && c_Target.NetState != null)
{
AddHtml(x, y += 20, width, HTML.Red + "<CENTER>" + General.Local(15), false);
AddButton(x + width / 2 - 60, y + 3, 0x2716, "Client", new GumpCallback(Client));
AddButton(x + width / 2 + 50, y + 3, 0x2716, "Client", new GumpCallback(Client));
AddHtml(x, y += 20, width, HTML.Red + "<CENTER>" + General.Local(16), false);
AddButton(x + width / 2 - 60, y + 3, 0x2716, "Goto", new GumpCallback(Goto));
AddButton(x + width / 2 + 50, y + 3, 0x2716, "Goto", new GumpCallback(Goto));
}
if (Data.GetData(Owner).MsgSound)
{
AddHtml(x, y += 25, width, "<CENTER>" + General.Local(17));
AddImageTiled(x + width / 2 - 25, y += 25, 50, 21, 0xBBA);
AddTextField(x + width / 2 - 25, y, 50, 21, 0x480, 0xBBA, "Sound", Data.GetData(Owner).GetSound(c_Target).ToString());
AddButton(x + width / 2 + 30, y + 3, 0x15E1, 0x15E5, "Play Sound", new GumpCallback(PlaySound));
AddButton(x + width / 2 - 40, y, 0x983, "Sound Up", new GumpCallback(SoundUp));
AddButton(x + width / 2 - 40, y + 10, 0x985, "Sound Down", new GumpCallback(SoundDown));
}
AddBackgroundZero(x, 0, width, y + 40, Data.GetData(c_Target).DefaultBack, false);
}
private void ClearSig()
{
Data.GetData(Owner).Signature = "";
NewGump();
}
private void SubmitSig()
{
Data.GetData(Owner).Signature = GetTextField("Signature");
NewGump();
}
private void Friend()
{
if (Data.GetData(c_Target).ByRequest && !Data.GetData(Owner).Friends.Contains(c_Target))
{
if (!TrackSpam.LogSpam(Owner, "Request " + c_Target.Name, TimeSpan.FromHours(Data.RequestSpam)))
{
TimeSpan ts = TrackSpam.NextAllowedIn(Owner, "Request " + c_Target.Name, TimeSpan.FromHours(Data.RequestSpam));
string txt = (ts.Days != 0 ? ts.Days + " " + General.Local(170) + " " : "") + (ts.Hours != 0 ? ts.Hours + " " + General.Local(171) + " " : "") + (ts.Minutes != 0 ? ts.Minutes + " " + General.Local(172) + " " : "");
Owner.SendMessage(Data.GetData(Owner).SystemC, General.Local(96) + " " + txt);
NewGump();
return;
}
Data.GetData(c_Target).AddMessage(new Message(Owner, General.Local(84), General.Local(85), MsgType.Invite));
Owner.SendMessage(Data.GetData(Owner).SystemC, General.Local(86) + " " + c_Target.Name);
NewGump();
return;
}
if (Data.GetData(Owner).Friends.Contains(c_Target))
Data.GetData(Owner).RemoveFriend(c_Target);
else
Data.GetData(Owner).AddFriend(c_Target);
NewGump();
}
private void Ignore()
{
if (Data.GetData(Owner).Ignores.Contains(c_Target))
Data.GetData(Owner).RemoveIgnore(c_Target);
else
Data.GetData(Owner).AddIgnore(c_Target);
NewGump();
}
private void Message()
{
NewGump();
if (Chat3.Message.CanMessage(Owner, c_Target))
new SendMessageGump(Owner, c_Target, "", null, MsgType.Normal);
}
private void GlobalAccess()
{
Data.GetData(c_Target).GlobalAccess = !Data.GetData(c_Target).GlobalAccess;
if (Data.GetData(c_Target).GlobalAccess)
Owner.SendMessage(Data.GetData(Owner).SystemC, c_Target.Name + " " + General.Local(75));
else
Owner.SendMessage(Data.GetData(Owner).SystemC, c_Target.Name + " " + General.Local(76));
NewGump();
}
private void Ban()
{
if (Data.GetData(c_Target).Banned)
{
Data.GetData(c_Target).RemoveBan();
Owner.SendMessage(Data.GetData(Owner).SystemC, General.Local(78) + " " + c_Target.Name);
NewGump();
}
else
new BanGump(c_Target, this);
}
private void GIgnore()
{
if (Data.GetData(Owner).GIgnores.Contains(c_Target))
Data.GetData(Owner).RemoveGIgnore(c_Target);
else
Data.GetData(Owner).AddGIgnore(c_Target);
NewGump();
}
private void GListen()
{
if (Data.GetData(Owner).GListens.Contains(c_Target))
Data.GetData(Owner).RemoveGListen(c_Target);
else
Data.GetData(Owner).AddGListen(c_Target);
NewGump();
}
private void Client()
{
NewGump();
if (c_Target.NetState == null)
Owner.SendMessage(Data.GetData(Owner).SystemC, c_Target.Name + " " + General.Local(83));
else
Owner.SendGump(new ClientGump(Owner, c_Target.NetState));
}
private void Goto()
{
if (c_Target.NetState == null)
Owner.SendMessage(Data.GetData(Owner).SystemC, c_Target.Name + " " + General.Local(83));
else
{
Owner.Location = c_Target.Location;
Owner.Map = c_Target.Map;
}
NewGump();
}
private void BecomeUser()
{
NewGump();
General.List(Owner, c_Target);
}
private void PlaySound()
{
Data.GetData(Owner).SetSound(c_Target, GetTextFieldInt("Sound"));
Owner.SendSound(Data.GetData(Owner).GetSound(c_Target));
NewGump();
}
private void SoundUp()
{
Data.GetData(Owner).SetSound(c_Target, Data.GetData(Owner).GetSound(c_Target) + 1);
NewGump();
}
private void SoundDown()
{
Data.GetData(Owner).SetSound(c_Target, Data.GetData(Owner).GetSound(c_Target) - 1);
NewGump();
}
private void AvatarUp()
{
Data.GetData(c_Target).AvatarUp();
NewGump();
}
private void AvatarDown()
{
Data.GetData(c_Target).AvatarDown();
NewGump();
}
private class BanGump : GumpPlus
{
private GumpPlus c_Gump;
private Mobile c_Target;
public BanGump(Mobile m, GumpPlus g) : base(g.Owner, 100, 100)
{
c_Gump = g;
c_Target = m;
}
protected override void BuildGump()
{
int width = 150;
int y = 10;
AddHtml(0, y, width, "<CENTER>" + General.Local(160));
AddHtml(0, y += 20, width, "<CENTER>" + General.Local(161));
AddButton(width / 2 - 50, y + 3, 0x2716, "30 minutes", new GumpStateCallback(BanTime), TimeSpan.FromMinutes(30));
AddButton(width / 2 + 40, y + 3, 0x2716, "30 minutes", new GumpStateCallback(BanTime), TimeSpan.FromMinutes(30));
AddHtml(0, y += 20, width, "<CENTER>" + General.Local(162));
AddButton(width / 2 - 50, y + 3, 0x2716, "1 hour", new GumpStateCallback(BanTime), TimeSpan.FromHours(1));
AddButton(width / 2 + 40, y + 3, 0x2716, "1 hour", new GumpStateCallback(BanTime), TimeSpan.FromHours(1));
AddHtml(0, y += 20, width, "<CENTER>" + General.Local(163));
AddButton(width / 2 - 50, y + 3, 0x2716, "12 hours", new GumpStateCallback(BanTime), TimeSpan.FromHours(12));
AddButton(width / 2 + 40, y + 3, 0x2716, "12 hours", new GumpStateCallback(BanTime), TimeSpan.FromHours(12));
AddHtml(0, y += 20, width, "<CENTER>" + General.Local(164));
AddButton(width / 2 - 50, y + 3, 0x2716, "1 day", new GumpStateCallback(BanTime), TimeSpan.FromDays(1));
AddButton(width / 2 + 40, y + 3, 0x2716, "1 day", new GumpStateCallback(BanTime), TimeSpan.FromDays(1));
AddHtml(0, y += 20, width, "<CENTER>" + General.Local(165));
AddButton(width / 2 - 50, y + 3, 0x2716, "1 week", new GumpStateCallback(BanTime), TimeSpan.FromDays(7));
AddButton(width / 2 + 40, y + 3, 0x2716, "1 week", new GumpStateCallback(BanTime), TimeSpan.FromDays(7));
AddHtml(0, y += 20, width, "<CENTER>" + General.Local(166));
AddButton(width / 2 - 50, y + 3, 0x2716, "1 month", new GumpStateCallback(BanTime), TimeSpan.FromDays(30));
AddButton(width / 2 + 40, y + 3, 0x2716, "1 month", new GumpStateCallback(BanTime), TimeSpan.FromDays(30));
AddHtml(0, y += 20, width, "<CENTER>" + General.Local(167));
AddButton(width / 2 - 50, y + 3, 0x2716, "1 year", new GumpStateCallback(BanTime), TimeSpan.FromDays(365));
AddButton(width / 2 + 40, y + 3, 0x2716, "1 year", new GumpStateCallback(BanTime), TimeSpan.FromDays(365));
AddBackgroundZero(0, 0, width, y + 40, Data.GetData(c_Target).DefaultBack);
}
private void BanTime(object o)
{
if (!(o is TimeSpan))
return;
Data.GetData(c_Target).Ban((TimeSpan)o);
Owner.SendMessage(Data.GetData(Owner).SystemC, General.Local(77) + " " + c_Target.Name);
c_Gump.NewGump();
}
protected override void OnClose()
{
c_Gump.NewGump();
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DevTestLabs
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// UsersOperations operations.
/// </summary>
internal partial class UsersOperations : IServiceOperations<DevTestLabsClient>, IUsersOperations
{
/// <summary>
/// Initializes a new instance of the UsersOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal UsersOperations(DevTestLabsClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the DevTestLabsClient
/// </summary>
public DevTestLabsClient Client { get; private set; }
/// <summary>
/// List user profiles in a given lab.
/// </summary>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<User>>> ListWithHttpMessagesAsync(string labName, ODataQuery<User> odataQuery = default(ODataQuery<User>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ResourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("odataQuery", odataQuery);
tracingParameters.Add("labName", labName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/users").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(this.Client.ResourceGroupName));
_url = _url.Replace("{labName}", Uri.EscapeDataString(labName));
List<string> _queryParameters = new List<string>();
if (odataQuery != null)
{
var _odataFilter = odataQuery.ToString();
if (!string.IsNullOrEmpty(_odataFilter))
{
_queryParameters.Add(_odataFilter);
}
}
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<User>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<User>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get user profile.
/// </summary>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the user profile.
/// </param>
/// <param name='expand'>
/// Specify the $expand query. Example: 'properties($select=identity)'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<User>> GetWithHttpMessagesAsync(string labName, string name, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ResourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("labName", labName);
tracingParameters.Add("name", name);
tracingParameters.Add("expand", expand);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/users/{name}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(this.Client.ResourceGroupName));
_url = _url.Replace("{labName}", Uri.EscapeDataString(labName));
_url = _url.Replace("{name}", Uri.EscapeDataString(name));
List<string> _queryParameters = new List<string>();
if (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", Uri.EscapeDataString(expand)));
}
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<User>();
_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<User>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Create or replace an existing user profile.
/// </summary>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the user profile.
/// </param>
/// <param name='user'>
/// Profile of a lab user.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<User>> CreateOrUpdateWithHttpMessagesAsync(string labName, string name, User user, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ResourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
if (user == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "user");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("labName", labName);
tracingParameters.Add("name", name);
tracingParameters.Add("user", user);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/users/{name}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(this.Client.ResourceGroupName));
_url = _url.Replace("{labName}", Uri.EscapeDataString(labName));
_url = _url.Replace("{name}", Uri.EscapeDataString(name));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(user != null)
{
_requestContent = SafeJsonConvert.SerializeObject(user, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<User>();
_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<User>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<User>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Delete user profile. This operation can take a while to complete.
/// </summary>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the user profile.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string labName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(
labName, name, customHeaders, cancellationToken);
return await this.Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken);
}
/// <summary>
/// Delete user profile. This operation can take a while to complete.
/// </summary>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the user profile.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string labName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ResourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("labName", labName);
tracingParameters.Add("name", name);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/users/{name}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(this.Client.ResourceGroupName));
_url = _url.Replace("{labName}", Uri.EscapeDataString(labName));
_url = _url.Replace("{name}", Uri.EscapeDataString(name));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 202 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_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>
/// Modify properties of user profiles.
/// </summary>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the user profile.
/// </param>
/// <param name='user'>
/// Profile of a lab user.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<User>> UpdateWithHttpMessagesAsync(string labName, string name, UserFragment user, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ResourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
if (user == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "user");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("labName", labName);
tracingParameters.Add("name", name);
tracingParameters.Add("user", user);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/users/{name}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(this.Client.ResourceGroupName));
_url = _url.Replace("{labName}", Uri.EscapeDataString(labName));
_url = _url.Replace("{name}", Uri.EscapeDataString(name));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PATCH");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(user != null)
{
_requestContent = SafeJsonConvert.SerializeObject(user, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<User>();
_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<User>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// List user profiles in a given lab.
/// </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>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<User>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<User>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<User>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Microsoft.VisualStudio.Services.Agent.Util;
using Microsoft.VisualStudio.Services.Agent.Worker;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Xunit;
namespace Microsoft.VisualStudio.Services.Agent.Tests.Worker
{
public sealed class VariablesL0
{
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void Constructor_AppliesMaskHints()
{
using (TestHostContext hc = new TestHostContext(this))
{
// Arrange.
var copy = new Dictionary<string, VariableValue>
{
{ "MySecretName", new VariableValue("My secret value", true) },
{ "MyPublicVariable", "My public value" },
};
List<string> warnings;
var variables = new Variables(hc, copy, out warnings);
// Act.
KeyValuePair<string, string>[] publicVariables = variables.Public.ToArray();
// Assert.
Assert.Equal(0, warnings.Count);
Assert.Equal(1, publicVariables.Length);
Assert.Equal("MyPublicVariable", publicVariables[0].Key);
Assert.Equal("My public value", publicVariables[0].Value);
Assert.Equal("My secret value", variables.Get("MySecretName"));
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void Constructor_DetectsAdjacentCyclicalReference()
{
using (TestHostContext hc = new TestHostContext(this))
{
// Arrange.
var copy = new Dictionary<string, VariableValue>
{
{ "variable1", "1_$(variable2)" },
{ "variable2", "2_$(variable3)" },
{ "variable3", "3_$(variable2)" },
};
// Act.
List<string> warnings;
var variables = new Variables(hc, copy, out warnings);
// Assert.
Assert.Equal(3, warnings.Count);
Assert.True(warnings.Any(x => string.Equals(x, StringUtil.Loc("Variable0ContainsCyclicalReference", "variable1"))));
Assert.True(warnings.Any(x => string.Equals(x, StringUtil.Loc("Variable0ContainsCyclicalReference", "variable2"))));
Assert.True(warnings.Any(x => string.Equals(x, StringUtil.Loc("Variable0ContainsCyclicalReference", "variable3"))));
Assert.Equal("1_$(variable2)", variables.Get("variable1"));
Assert.Equal("2_$(variable3)", variables.Get("variable2"));
Assert.Equal("3_$(variable2)", variables.Get("variable3"));
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void Constructor_DetectsExcessiveDepth()
{
using (TestHostContext hc = new TestHostContext(this))
{
// Arrange.
const int MaxDepth = 50;
var copy = new Dictionary<string, VariableValue>();
copy[$"variable{MaxDepth + 1}"] = "Final value"; // Variable 51.
for (int i = 1; i <= MaxDepth; i++)
{
copy[$"variable{i}"] = $"$(variable{i + 1})"; // Variables 1-50.
}
// Act.
List<string> warnings;
var variables = new Variables(hc, copy, out warnings);
// Assert.
Assert.Equal(1, warnings.Count);
Assert.Equal(warnings[0], StringUtil.Loc("Variable0ExceedsMaxDepth1", "variable1", MaxDepth));
Assert.Equal("$(variable2)", variables.Get("variable1")); // Variable 1.
for (int i = 2; i <= MaxDepth + 1; i++)
{
Assert.Equal("Final value", variables.Get($"variable{i}")); // Variables 2-51.
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void Constructor_DetectsNonadjacentCyclicalReference()
{
using (TestHostContext hc = new TestHostContext(this))
{
// Arrange.
var copy = new Dictionary<string, VariableValue>
{
{ "variable1", "1_$(variable2)" },
{ "variable2", "2_$(variable3)" },
{ "variable3", "3_$(variable1)" },
};
// Act.
List<string> warnings;
var variables = new Variables(hc, copy, out warnings);
// Assert.
Assert.Equal(3, warnings.Count);
Assert.True(warnings.Any(x => string.Equals(x, StringUtil.Loc("Variable0ContainsCyclicalReference", "variable1"))));
Assert.True(warnings.Any(x => string.Equals(x, StringUtil.Loc("Variable0ContainsCyclicalReference", "variable2"))));
Assert.True(warnings.Any(x => string.Equals(x, StringUtil.Loc("Variable0ContainsCyclicalReference", "variable3"))));
Assert.Equal("1_$(variable2)", variables.Get("variable1"));
Assert.Equal("2_$(variable3)", variables.Get("variable2"));
Assert.Equal("3_$(variable1)", variables.Get("variable3"));
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void Constructor_InheritsSecretFlagFromDeepRecursion()
{
using (TestHostContext hc = new TestHostContext(this))
{
// Arrange.
var copy = new Dictionary<string, VariableValue>
{
{ "variable1", "before $(variable2) after" },
{ "variable2", "before2 $(variable3) after2" },
{ "variable3", new VariableValue("some variable 3 value", true) },
};
// Act.
List<string> warnings;
var variables = new Variables(hc, copy, out warnings);
// Assert.
Assert.Equal(0, warnings.Count);
Assert.Equal(0, variables.Public.Count());
Assert.Equal("before before2 some variable 3 value after2 after", variables.Get("variable1"));
Assert.Equal("before2 some variable 3 value after2", variables.Get("variable2"));
Assert.Equal("some variable 3 value", variables.Get("variable3"));
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void Constructor_InheritsSecretFlagFromRecursion()
{
using (TestHostContext hc = new TestHostContext(this))
{
// Arrange.
var copy = new Dictionary<string, VariableValue>
{
{ "variable1", "before $(variable2) after" },
{ "variable2", new VariableValue("some variable 2 value", true) },
};
// Act.
List<string> warnings;
var variables = new Variables(hc, copy, out warnings);
// Assert.
Assert.Equal(0, warnings.Count);
Assert.Equal(0, variables.Public.Count());
Assert.Equal("before some variable 2 value after", variables.Get("variable1"));
Assert.Equal("some variable 2 value", variables.Get("variable2"));
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void Constructor_ExpandsValueWithConsecutiveMacros()
{
using (TestHostContext hc = new TestHostContext(this))
{
// Arrange.
var copy = new Dictionary<string, VariableValue>
{
{ "variable1", "before$(variable2)$(variable2)after" },
{ "variable2", "some variable 2 value" },
};
// Act.
List<string> warnings;
var variables = new Variables(hc, copy, out warnings);
// Assert.
Assert.Equal(0, warnings.Count);
Assert.Equal("beforesome variable 2 valuesome variable 2 valueafter", variables.Get("variable1"));
Assert.Equal("some variable 2 value", variables.Get("variable2"));
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void Constructor_ExpandsValueWithDeepRecursion()
{
using (TestHostContext hc = new TestHostContext(this))
{
// Arrange.
var copy = new Dictionary<string, VariableValue>
{
{ "variable1", "before$(variable2)after" },
{ "variable2", "$(variable3)world" },
{ "variable3", "hello" },
};
// Act.
List<string> warnings;
var variables = new Variables(hc, copy, out warnings);
// Assert.
Assert.Equal(0, warnings.Count);
Assert.Equal("beforehelloworldafter", variables.Get("variable1"));
Assert.Equal("helloworld", variables.Get("variable2"));
Assert.Equal("hello", variables.Get("variable3"));
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void Constructor_ExpandsValueWithPreceedingPrefix()
{
using (TestHostContext hc = new TestHostContext(this))
{
// Arrange.
var copy = new Dictionary<string, VariableValue>
{
{ "variable1", "before$($(variable2)after" },
{ "variable2", "hello" },
};
// Act.
List<string> warnings;
var variables = new Variables(hc, copy, out warnings);
// Assert.
Assert.Equal(0, warnings.Count);
Assert.Equal("before$(helloafter", variables.Get("variable1"));
Assert.Equal("hello", variables.Get("variable2"));
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void Constructor_HandlesNullNestedValue()
{
using (TestHostContext hc = new TestHostContext(this))
{
// Arrange.
var copy = new Dictionary<string, VariableValue>
{
{ "variable1", "before $(variable2) after" },
{ "variable2", new VariableValue(null, false) },
};
// Act.
List<string> warnings;
var variables = new Variables(hc, copy, out warnings);
// Assert.
Assert.Equal(0, warnings.Count);
Assert.Equal("before after", variables.Get("variable1"));
Assert.Equal(string.Empty, variables.Get("variable2"));
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void Constructor_HandlesNullValue()
{
using (TestHostContext hc = new TestHostContext(this))
{
// Arrange.
var copy = new Dictionary<string, VariableValue>
{
{ "variable1", new VariableValue(null, false) },
{ "variable2", "some variable 2 value" },
};
// Act.
List<string> warnings;
var variables = new Variables(hc, copy, out warnings);
// Assert.
Assert.Equal(0, warnings.Count);
Assert.Equal(string.Empty, variables.Get("variable1"));
Assert.Equal("some variable 2 value", variables.Get("variable2"));
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void Constructor_SetsNullAsEmpty()
{
using (TestHostContext hc = new TestHostContext(this))
{
// Arrange.
List<string> warnings;
var copy = new Dictionary<string, VariableValue>
{
{ "variable1", new VariableValue(null, false) },
};
// Act.
var variables = new Variables(hc, copy, out warnings);
// Assert.
Assert.Equal(0, warnings.Count);
Assert.Equal(string.Empty, variables.Get("variable1"));
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void Constructor_SetsOrdinalIgnoreCaseComparer()
{
using (TestHostContext hc = new TestHostContext(this))
{
// Arrange.
CultureInfo currentCulture = CultureInfo.CurrentCulture;
CultureInfo currentUICulture = CultureInfo.CurrentUICulture;
try
{
CultureInfo.CurrentCulture = new CultureInfo("tr-TR");
CultureInfo.CurrentUICulture = new CultureInfo("tr-TR");
var copy = new Dictionary<string, VariableValue>
{
{ "i", "foo" },
{ "I", "foo" },
};
// Act.
List<string> warnings;
var variables = new Variables(hc, copy, out warnings);
// Assert.
Assert.Equal(1, variables.Public.Count());
}
finally
{
// Cleanup.
CultureInfo.CurrentCulture = currentCulture;
CultureInfo.CurrentUICulture = currentUICulture;
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void Constructor_SkipVariableWithEmptyName()
{
using (TestHostContext hc = new TestHostContext(this))
{
// Arrange.
var copy = new Dictionary<string, VariableValue>
{
{ "", "" },
{ " ", "" },
{ "MyPublicVariable", "My public value" },
};
List<string> warnings;
var variables = new Variables(hc, copy, out warnings);
// Act.
KeyValuePair<string, string>[] publicVariables = variables.Public.ToArray();
// Assert.
Assert.Equal(0, warnings.Count);
Assert.Equal(1, publicVariables.Length);
Assert.Equal("MyPublicVariable", publicVariables[0].Key);
Assert.Equal("My public value", publicVariables[0].Value);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void ExpandValues_DoesNotRecurse()
{
using (TestHostContext hc = new TestHostContext(this))
{
// Arrange: Setup the variables. The value of the variable1 variable
// should not get expanded since variable2 does not exist when the
// variables class is initialized (and therefore would never get expanded).
List<string> warnings;
var variableDictionary = new Dictionary<string, VariableValue>
{
{ "variable1", "$(variable2)" },
};
var variables = new Variables(hc, variableDictionary, out warnings);
variables.Set("variable2", "some variable 2 value");
// Arrange: Setup the target dictionary.
var targetDictionary = new Dictionary<string, string>();
targetDictionary["some target key"] = "before $(variable1) after";
// Act.
variables.ExpandValues(target: targetDictionary);
// Assert: The variable should only have been expanded one level.
Assert.Equal("before $(variable2) after", targetDictionary["some target key"]);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void ExpandValues_HandlesConsecutiveMacros()
{
using (TestHostContext hc = new TestHostContext(this))
{
// Arrange: Setup the variables.
List<string> warnings;
var variableDictionary = new Dictionary<string, VariableValue>
{
{ "variable1", "some variable 1 value " },
{ "variable2", "some variable 2 value" },
};
var variables = new Variables(hc, variableDictionary, out warnings);
// Arrange: Setup the target dictionary.
var targetDictionary = new Dictionary<string, string>();
targetDictionary["some target key"] = "before $(variable1)$(variable2) after";
// Act.
variables.ExpandValues(target: targetDictionary);
// Assert: The consecutive macros should both have been expanded.
Assert.Equal("before some variable 1 value some variable 2 value after", targetDictionary["some target key"]);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void ExpandValues_HandlesNullValue()
{
using (TestHostContext hc = new TestHostContext(this))
{
// Arrange: Setup the variables.
List<string> warnings;
var variableDictionary = new Dictionary<string, VariableValue>
{
{ "variable1", "some variable 1 value " },
};
var variables = new Variables(hc, variableDictionary, out warnings);
// Arrange: Setup the target dictionary.
var targetDictionary = new Dictionary<string, string>
{
{ "some target key", null },
};
// Act.
variables.ExpandValues(target: targetDictionary);
// Assert: The consecutive macros should both have been expanded.
Assert.Equal(string.Empty, targetDictionary["some target key"]);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void ExpandValues_HandlesPreceedingPrefix()
{
using (TestHostContext hc = new TestHostContext(this))
{
// Arrange: Setup the variables.
List<string> warnings;
var variableDictionary = new Dictionary<string, VariableValue>
{
{ "variable1", "some variable 1 value" },
};
var variables = new Variables(hc, variableDictionary, out warnings);
// Arrange: Setup the target dictionary.
var targetDictionary = new Dictionary<string, string>();
targetDictionary["some target key"] = "before $($(variable1) after";
// Act.
variables.ExpandValues(target: targetDictionary);
// Assert: The consecutive macros should both have been expanded.
Assert.Equal("before $(some variable 1 value after", targetDictionary["some target key"]);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void Get_ReturnsNullIfNotFound()
{
using (TestHostContext hc = new TestHostContext(this))
{
// Arrange.
List<string> warnings;
var variables = new Variables(hc, new Dictionary<string, VariableValue>(), out warnings);
// Act.
string actual = variables.Get("no such");
// Assert.
Assert.Equal(null, actual);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void GetBoolean_DoesNotThrowWhenNull()
{
using (TestHostContext hc = new TestHostContext(this))
{
// Arrange.
List<string> warnings;
var variables = new Variables(hc, new Dictionary<string, VariableValue>(), out warnings);
// Act.
bool? actual = variables.GetBoolean("no such");
// Assert.
Assert.Null(actual);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void GetEnum_DoesNotThrowWhenNull()
{
using (TestHostContext hc = new TestHostContext(this))
{
// Arrange.
List<string> warnings;
var variables = new Variables(hc, new Dictionary<string, VariableValue>(), out warnings);
// Act.
System.IO.FileShare? actual = variables.GetEnum<System.IO.FileShare>("no such");
// Assert.
Assert.Null(actual);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void RecalculateExpanded_PerformsRecalculation()
{
using (TestHostContext hc = new TestHostContext(this))
{
// Arrange.
List<string> warnings;
var original = new Dictionary<string, VariableValue>
{
{ "topLevelVariable", "$(nestedVariable1) $(nestedVariable2)" },
{ "nestedVariable1", "Some nested value 1" },
};
var variables = new Variables(hc, original, out warnings);
Assert.Equal(0, warnings.Count);
Assert.Equal(2, variables.Public.Count());
Assert.Equal("Some nested value 1 $(nestedVariable2)", variables.Get("topLevelVariable"));
Assert.Equal("Some nested value 1", variables.Get("nestedVariable1"));
// Act.
variables.Set("nestedVariable2", "Some nested value 2", secret: false);
variables.RecalculateExpanded(out warnings);
// Assert.
Assert.Equal(0, warnings.Count);
Assert.Equal(3, variables.Public.Count());
Assert.Equal("Some nested value 1 Some nested value 2", variables.Get("topLevelVariable"));
Assert.Equal("Some nested value 1", variables.Get("nestedVariable1"));
Assert.Equal("Some nested value 2", variables.Get("nestedVariable2"));
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void RecalculateExpanded_RetainsUpdatedSecretness()
{
using (TestHostContext hc = new TestHostContext(this))
{
// Arrange.
List<string> warnings;
var variables = new Variables(hc, new Dictionary<string, VariableValue>(), out warnings);
Assert.Equal(0, warnings.Count);
variables.Set("foo", "bar");
Assert.Equal(1, variables.Public.Count());
// Act.
variables.Set("foo", "baz", secret: true);
variables.RecalculateExpanded(out warnings);
// Assert.
Assert.Equal(0, warnings.Count);
Assert.Equal(0, variables.Public.Count());
Assert.Equal("baz", variables.Get("foo"));
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void RecalculateExpanded_PathTranslator()
{
using (TestHostContext hc = new TestHostContext(this))
{
// Arrange.
var copy = new Dictionary<string, VariableValue>
{
{ "variable1", "run $(variable2)" },
{ "variable2", "/path/to/something" },
};
List<string> warnings;
var variables = new Variables(hc, copy, out warnings);
variables.StringTranslator = (str) => {
if (str.StartsWith("/path/to")) {
return str.Replace("/path/to", "/another/path");
}
return str;
};;
Assert.Equal(0, warnings.Count);
// Act.
variables.RecalculateExpanded(out warnings);
// Assert.
Assert.Equal(0, warnings.Count);
Assert.Equal("run /another/path/something", variables.Get("variable1"));
Assert.Equal("/another/path/something", variables.Get("variable2"));
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void Set_CanConvertAPublicValueIntoASecretValue()
{
using (TestHostContext hc = new TestHostContext(this))
{
// Arrange.
List<string> warnings;
var variables = new Variables(hc, new Dictionary<string, VariableValue>(), out warnings);
variables.Set("foo", "bar");
Assert.Equal(1, variables.Public.Count());
// Act.
variables.Set("foo", "baz", secret: true);
// Assert.
Assert.Equal(0, variables.Public.Count());
Assert.Equal("baz", variables.Get("foo"));
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void Set_CannotConvertASecretValueIntoAPublicValue()
{
using (TestHostContext hc = new TestHostContext(this))
{
// Arrange.
List<string> warnings;
var variables = new Variables(hc, new Dictionary<string, VariableValue>(), out warnings);
variables.Set("foo", "bar", secret: true);
Assert.Equal(0, variables.Public.Count());
Assert.Equal("bar", variables.Get("foo"));
// Act.
variables.Set("foo", "baz", secret: false);
// Assert.
Assert.Equal(0, variables.Public.Count());
Assert.Equal("baz", variables.Get("foo"));
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void Set_CanStoreANewSecret()
{
using (TestHostContext hc = new TestHostContext(this))
{
// Arrange.
List<string> warnings;
var variables = new Variables(hc, new Dictionary<string, VariableValue>(), out warnings);
// Act.
variables.Set("foo", "bar", secret: true);
// Assert.
Assert.Equal(0, variables.Public.Count());
Assert.Equal("bar", variables.Get("foo"));
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void Set_CanUpdateASecret()
{
using (TestHostContext hc = new TestHostContext(this))
{
// Arrange.
List<string> warnings;
var variables = new Variables(hc, new Dictionary<string, VariableValue>(), out warnings);
// Act.
variables.Set("foo", "bar", secret: true);
variables.Set("foo", "baz", secret: true);
// Assert.
Assert.Equal(0, variables.Public.Count());
Assert.Equal("baz", variables.Get("foo"));
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void Set_StoresNullAsEmpty()
{
using (TestHostContext hc = new TestHostContext(this))
{
// Arrange.
List<string> warnings;
var variables = new Variables(hc, new Dictionary<string, VariableValue>(), out warnings);
// Act.
variables.Set("variable1", null);
// Assert.
Assert.Equal(0, warnings.Count);
Assert.Equal(string.Empty, variables.Get("variable1"));
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void Set_StoresValue()
{
using (TestHostContext hc = new TestHostContext(this))
{
// Arrange.
List<string> warnings;
var variables = new Variables(hc, new Dictionary<string, VariableValue>(), out warnings);
// Act.
variables.Set("foo", "bar");
// Assert.
Assert.Equal("bar", variables.Get("foo"));
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void IsReadOnly_RespectsSystemVariables()
{
using (TestHostContext hc = new TestHostContext(this))
{
// Arrange.
List<string> warnings;
var variables = new Variables(hc, new Dictionary<string, VariableValue>(), out warnings);
variables.Set(Constants.Variables.Agent.ReadOnlyVariables, "true");
variables.Set(Constants.Variables.System.AccessToken, "abc");
variables.Set(Constants.Variables.Agent.BuildDirectory, "abc");
variables.Set(Constants.Variables.Build.RepoClean, "abc");
variables.Set(Constants.Variables.Common.TestResultsDirectory, "abc");
// Assert.
Assert.True(variables.IsReadOnly(Constants.Variables.System.AccessToken));
Assert.True(variables.IsReadOnly(Constants.Variables.Agent.BuildDirectory));
Assert.True(variables.IsReadOnly(Constants.Variables.Build.RepoClean));
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void IsReadOnly_RespectsUserReadOnlyVariables()
{
using (TestHostContext hc = new TestHostContext(this))
{
// Arrange.
List<string> warnings;
var variables = new Variables(hc, new Dictionary<string, VariableValue>(), out warnings);
variables.Set(Constants.Variables.Agent.ReadOnlyVariables, "true");
variables.Set("var1", "abc", secret: false, readOnly: true);
variables.Set("var2", "abc", secret: false, readOnly: false);
// Assert.
Assert.True(variables.IsReadOnly("var1"));
Assert.False(variables.IsReadOnly("var2"));
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void IsReadOnly_ReturnsFalseForUnsetVariables()
{
using (TestHostContext hc = new TestHostContext(this))
{
// Arrange.
List<string> warnings;
var variables = new Variables(hc, new Dictionary<string, VariableValue>(), out warnings);
variables.Set(Constants.Variables.Agent.ReadOnlyVariables, "true");
// Assert.
Assert.False(variables.IsReadOnly("var1"));
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void IsReadOnly_ListContainsAllReadOnlyVariables()
{
using (TestHostContext hc = new TestHostContext(this))
{
// Arrange.
List<string> wellKnownSystemVariables = new List<string>();
List<System.Type> wellKnownSystemVariableClasses = new List<System.Type>()
{
typeof(Constants.Variables.Agent),
typeof(Constants.Variables.Build),
typeof(Constants.Variables.Features),
typeof(Constants.Variables.Pipeline),
typeof(Constants.Variables.Release),
typeof(Constants.Variables.System),
typeof(Constants.Variables.Task)
};
// Iterate through members of each class and add any system variables (aka prefixed with our readOnlyPrefixes)
foreach (System.Type systemVariableClass in wellKnownSystemVariableClasses)
{
var wellKnownDistributedTaskFields = systemVariableClass.GetFields();
foreach(var field in wellKnownDistributedTaskFields)
{
var fieldValue = field.GetValue(systemVariableClass);
if (fieldValue != null)
{
string value = fieldValue.ToString();
wellKnownSystemVariables.Add(value);
}
}
}
// Assert.
foreach(string systemVariable in wellKnownSystemVariables)
{
Assert.True(Constants.Variables.ReadOnlyVariables.Contains(systemVariable), "Constants.Variables.ReadOnlyVariables should contain " + systemVariable);
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void Unset()
{
using (TestHostContext hc = new TestHostContext(this))
{
List<string> warnings;
var variables = new Variables(hc, new Dictionary<string, VariableValue>(), out warnings);
variables.Set("foo", "bar");
Assert.Equal("bar", variables.Get("foo"));
variables.Unset("foo");
Assert.Equal(null, variables.Get("foo"));
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void Scope()
{
using (TestHostContext hc = new TestHostContext(this))
{
List<string> warnings;
var variables = new Variables(hc, new Dictionary<string, VariableValue>(), out warnings);
var scope = variables.CreateScope();
scope.Set("foo", "bar");
Assert.Equal("bar", variables.Get("foo"));
scope.Dispose();
Assert.Equal(null, variables.Get("foo"));
}
}
public void CopyInto_Basic()
{
using (TestHostContext hc = new TestHostContext(this))
{
// Arrange.
List<string> warnings;
var variables = new Variables(hc, new Dictionary<string, VariableValue>(), out warnings);
Dictionary<string,VariableValue> dict1 = new Dictionary<string, VariableValue>();
variables.CopyInto(dict1, Variables.DefaultStringTranslator);
Assert.Equal(0, dict1.Count);
variables.Set("foo", "bar");
variables.CopyInto(dict1, Variables.DefaultStringTranslator);
Assert.Equal(1, dict1.Count);
Assert.Equal("bar", dict1["foo"]);
variables.Set("boo", "bah", true);
variables.CopyInto(dict1, Variables.DefaultStringTranslator);
Assert.Equal(2, dict1.Count);
Assert.Equal("bar", dict1["foo"]);
Assert.Equal(new VariableValue("bah", true), dict1["boo"]);
}
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
#if !(NET20 || NET35 || SILVERLIGHT)
using System.Threading.Tasks;
#endif
using System.Xml;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Tests.Serialization;
using Newtonsoft.Json.Tests.TestObjects;
using Newtonsoft.Json.Utilities;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#endif
namespace Newtonsoft.Json.Tests
{
[TestFixture]
public class JsonConvertTest : TestFixtureBase
{
[Test]
public void DefaultSettings()
{
try
{
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Formatting = Formatting.Indented
};
string json = JsonConvert.SerializeObject(new { test = new[] { 1, 2, 3 } });
Assert.AreEqual(@"{
""test"": [
1,
2,
3
]
}", json);
}
finally
{
JsonConvert.DefaultSettings = null;
}
}
[Test]
public void DefaultSettings_Example()
{
try
{
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Formatting = Formatting.Indented,
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
Employee e = new Employee
{
FirstName = "Eric",
LastName = "Example",
BirthDate = new DateTime(1980, 4, 20, 0, 0, 0, DateTimeKind.Utc),
Department = "IT",
JobTitle = "Web Dude"
};
string json = JsonConvert.SerializeObject(e);
// {
// "firstName": "Eric",
// "lastName": "Example",
// "birthDate": "1980-04-20T00:00:00Z",
// "department": "IT",
// "jobTitle": "Web Dude"
// }
Assert.AreEqual(@"{
""firstName"": ""Eric"",
""lastName"": ""Example"",
""birthDate"": ""1980-04-20T00:00:00Z"",
""department"": ""IT"",
""jobTitle"": ""Web Dude""
}", json);
}
finally
{
JsonConvert.DefaultSettings = null;
}
}
[Test]
public void DefaultSettings_Override()
{
try
{
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Formatting = Formatting.Indented
};
string json = JsonConvert.SerializeObject(new { test = new[] { 1, 2, 3 } }, new JsonSerializerSettings
{
Formatting = Formatting.None
});
Assert.AreEqual(@"{""test"":[1,2,3]}", json);
}
finally
{
JsonConvert.DefaultSettings = null;
}
}
[Test]
public void DefaultSettings_Override_JsonConverterOrder()
{
try
{
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Formatting = Formatting.Indented,
Converters = { new IsoDateTimeConverter { DateTimeFormat = "yyyy" } }
};
string json = JsonConvert.SerializeObject(new[] { new DateTime(2000, 12, 12, 4, 2, 4, DateTimeKind.Utc) }, new JsonSerializerSettings
{
Formatting = Formatting.None,
Converters =
{
// should take precedence
new JavaScriptDateTimeConverter(),
new IsoDateTimeConverter { DateTimeFormat = "dd" }
}
});
Assert.AreEqual(@"[new Date(976593724000)]", json);
}
finally
{
JsonConvert.DefaultSettings = null;
}
}
[Test]
public void DefaultSettings_Create()
{
try
{
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Formatting = Formatting.Indented
};
IList<int> l = new List<int> { 1, 2, 3 };
StringWriter sw = new StringWriter();
JsonSerializer serializer = JsonSerializer.CreateDefault();
serializer.Serialize(sw, l);
Assert.AreEqual(@"[
1,
2,
3
]", sw.ToString());
sw = new StringWriter();
serializer.Formatting = Formatting.None;
serializer.Serialize(sw, l);
Assert.AreEqual(@"[1,2,3]", sw.ToString());
sw = new StringWriter();
serializer = new JsonSerializer();
serializer.Serialize(sw, l);
Assert.AreEqual(@"[1,2,3]", sw.ToString());
sw = new StringWriter();
serializer = JsonSerializer.Create();
serializer.Serialize(sw, l);
Assert.AreEqual(@"[1,2,3]", sw.ToString());
}
finally
{
JsonConvert.DefaultSettings = null;
}
}
[Test]
public void DefaultSettings_CreateWithSettings()
{
try
{
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Formatting = Formatting.Indented
};
IList<int> l = new List<int> { 1, 2, 3 };
StringWriter sw = new StringWriter();
JsonSerializer serializer = JsonSerializer.CreateDefault(new JsonSerializerSettings
{
Converters = { new IntConverter() }
});
serializer.Serialize(sw, l);
Assert.AreEqual(@"[
2,
4,
6
]", sw.ToString());
sw = new StringWriter();
serializer.Converters.Clear();
serializer.Serialize(sw, l);
Assert.AreEqual(@"[
1,
2,
3
]", sw.ToString());
sw = new StringWriter();
serializer = JsonSerializer.Create(new JsonSerializerSettings { Formatting = Formatting.Indented });
serializer.Serialize(sw, l);
Assert.AreEqual(@"[
1,
2,
3
]", sw.ToString());
}
finally
{
JsonConvert.DefaultSettings = null;
}
}
public class IntConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
int i = (int)value;
writer.WriteValue(i * 2);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(int);
}
}
[Test]
public void DeserializeObject_EmptyString()
{
object result = JsonConvert.DeserializeObject(string.Empty);
Assert.IsNull(result);
}
[Test]
public void DeserializeObject_Integer()
{
object result = JsonConvert.DeserializeObject("1");
Assert.AreEqual(1L, result);
}
[Test]
public void DeserializeObject_Integer_EmptyString()
{
int? value = JsonConvert.DeserializeObject<int?>("");
Assert.IsNull(value);
}
[Test]
public void DeserializeObject_Decimal_EmptyString()
{
decimal? value = JsonConvert.DeserializeObject<decimal?>("");
Assert.IsNull(value);
}
[Test]
public void DeserializeObject_DateTime_EmptyString()
{
DateTime? value = JsonConvert.DeserializeObject<DateTime?>("");
Assert.IsNull(value);
}
[Test]
public void EscapeJavaScriptString()
{
string result;
result = JavaScriptUtils.ToEscapedJavaScriptString("How now brown cow?", '"', true);
Assert.AreEqual(@"""How now brown cow?""", result);
result = JavaScriptUtils.ToEscapedJavaScriptString("How now 'brown' cow?", '"', true);
Assert.AreEqual(@"""How now 'brown' cow?""", result);
result = JavaScriptUtils.ToEscapedJavaScriptString("How now <brown> cow?", '"', true);
Assert.AreEqual(@"""How now <brown> cow?""", result);
result = JavaScriptUtils.ToEscapedJavaScriptString(@"How
now brown cow?", '"', true);
Assert.AreEqual(@"""How \r\nnow brown cow?""", result);
result = JavaScriptUtils.ToEscapedJavaScriptString("\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007", '"', true);
Assert.AreEqual(@"""\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007""", result);
result =
JavaScriptUtils.ToEscapedJavaScriptString("\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013", '"', true);
Assert.AreEqual(@"""\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013""", result);
result =
JavaScriptUtils.ToEscapedJavaScriptString(
"\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f ", '"', true);
Assert.AreEqual(@"""\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f """, result);
result =
JavaScriptUtils.ToEscapedJavaScriptString(
"!\"#$%&\u0027()*+,-./0123456789:;\u003c=\u003e?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]", '"', true);
Assert.AreEqual(@"""!\""#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]""", result);
result = JavaScriptUtils.ToEscapedJavaScriptString("^_`abcdefghijklmnopqrstuvwxyz{|}~", '"', true);
Assert.AreEqual(@"""^_`abcdefghijklmnopqrstuvwxyz{|}~""", result);
string data =
"\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&\u0027()*+,-./0123456789:;\u003c=\u003e?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
string expected =
@"""\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\""#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~""";
result = JavaScriptUtils.ToEscapedJavaScriptString(data, '"', true);
Assert.AreEqual(expected, result);
result = JavaScriptUtils.ToEscapedJavaScriptString("Fred's cat.", '\'', true);
Assert.AreEqual(result, @"'Fred\'s cat.'");
result = JavaScriptUtils.ToEscapedJavaScriptString(@"""How are you gentlemen?"" said Cats.", '"', true);
Assert.AreEqual(result, @"""\""How are you gentlemen?\"" said Cats.""");
result = JavaScriptUtils.ToEscapedJavaScriptString(@"""How are' you gentlemen?"" said Cats.", '"', true);
Assert.AreEqual(result, @"""\""How are' you gentlemen?\"" said Cats.""");
result = JavaScriptUtils.ToEscapedJavaScriptString(@"Fred's ""cat"".", '\'', true);
Assert.AreEqual(result, @"'Fred\'s ""cat"".'");
result = JavaScriptUtils.ToEscapedJavaScriptString("\u001farray\u003caddress", '"', true);
Assert.AreEqual(result, @"""\u001farray<address""");
}
[Test]
public void EscapeJavaScriptString_UnicodeLinefeeds()
{
string result;
result = JavaScriptUtils.ToEscapedJavaScriptString("before" + '\u0085' + "after", '"', true);
Assert.AreEqual(@"""before\u0085after""", result);
result = JavaScriptUtils.ToEscapedJavaScriptString("before" + '\u2028' + "after", '"', true);
Assert.AreEqual(@"""before\u2028after""", result);
result = JavaScriptUtils.ToEscapedJavaScriptString("before" + '\u2029' + "after", '"', true);
Assert.AreEqual(@"""before\u2029after""", result);
}
[Test]
public void ToStringInvalid()
{
ExceptionAssert.Throws<ArgumentException>("Unsupported type: System.Version. Use the JsonSerializer class to get the object's JSON representation.",
() =>
{
JsonConvert.ToString(new Version(1, 0));
});
}
[Test]
public void GuidToString()
{
Guid guid = new Guid("BED7F4EA-1A96-11d2-8F08-00A0C9A6186D");
string json = JsonConvert.ToString(guid);
Assert.AreEqual(@"""bed7f4ea-1a96-11d2-8f08-00a0c9a6186d""", json);
}
[Test]
public void EnumToString()
{
string json = JsonConvert.ToString(StringComparison.CurrentCultureIgnoreCase);
Assert.AreEqual("1", json);
}
[Test]
public void ObjectToString()
{
object value;
value = 1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = 1.1;
Assert.AreEqual("1.1", JsonConvert.ToString(value));
value = 1.1m;
Assert.AreEqual("1.1", JsonConvert.ToString(value));
value = (float)1.1;
Assert.AreEqual("1.1", JsonConvert.ToString(value));
value = (short)1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = (long)1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = (byte)1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = (uint)1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = (ushort)1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = (sbyte)1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = (ulong)1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc);
Assert.AreEqual(@"""1970-01-01T00:00:00Z""", JsonConvert.ToString(value));
value = new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc);
Assert.AreEqual(@"""\/Date(0)\/""", JsonConvert.ToString((DateTime)value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.RoundtripKind));
#if !NET20
value = new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, TimeSpan.Zero);
Assert.AreEqual(@"""1970-01-01T00:00:00+00:00""", JsonConvert.ToString(value));
value = new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, TimeSpan.Zero);
Assert.AreEqual(@"""\/Date(0+0000)\/""", JsonConvert.ToString((DateTimeOffset)value, DateFormatHandling.MicrosoftDateFormat));
#endif
value = null;
Assert.AreEqual("null", JsonConvert.ToString(value));
#if !(NETFX_CORE || PORTABLE || PORTABLE40)
value = DBNull.Value;
Assert.AreEqual("null", JsonConvert.ToString(value));
#endif
value = "I am a string";
Assert.AreEqual(@"""I am a string""", JsonConvert.ToString(value));
value = true;
Assert.AreEqual("true", JsonConvert.ToString(value));
value = 'c';
Assert.AreEqual(@"""c""", JsonConvert.ToString(value));
}
[Test]
public void TestInvalidStrings()
{
ExceptionAssert.Throws<JsonReaderException>("Additional text encountered after finished reading JSON content: t. Path '', line 1, position 19.",
() =>
{
string orig = @"this is a string ""that has quotes"" ";
string serialized = JsonConvert.SerializeObject(orig);
// *** Make string invalid by stripping \" \"
serialized = serialized.Replace(@"\""", "\"");
JsonConvert.DeserializeObject<string>(serialized);
});
}
[Test]
public void DeserializeValueObjects()
{
int i = JsonConvert.DeserializeObject<int>("1");
Assert.AreEqual(1, i);
#if !NET20
DateTimeOffset d = JsonConvert.DeserializeObject<DateTimeOffset>(@"""\/Date(-59011455539000+0000)\/""");
Assert.AreEqual(new DateTimeOffset(new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Utc)), d);
#endif
bool b = JsonConvert.DeserializeObject<bool>("true");
Assert.AreEqual(true, b);
object n = JsonConvert.DeserializeObject<object>("null");
Assert.AreEqual(null, n);
object u = JsonConvert.DeserializeObject<object>("undefined");
Assert.AreEqual(null, u);
}
[Test]
public void FloatToString()
{
Assert.AreEqual("1.1", JsonConvert.ToString(1.1));
Assert.AreEqual("1.11", JsonConvert.ToString(1.11));
Assert.AreEqual("1.111", JsonConvert.ToString(1.111));
Assert.AreEqual("1.1111", JsonConvert.ToString(1.1111));
Assert.AreEqual("1.11111", JsonConvert.ToString(1.11111));
Assert.AreEqual("1.111111", JsonConvert.ToString(1.111111));
Assert.AreEqual("1.0", JsonConvert.ToString(1.0));
Assert.AreEqual("1.0", JsonConvert.ToString(1d));
Assert.AreEqual("-1.0", JsonConvert.ToString(-1d));
Assert.AreEqual("1.01", JsonConvert.ToString(1.01));
Assert.AreEqual("1.001", JsonConvert.ToString(1.001));
Assert.AreEqual(JsonConvert.PositiveInfinity, JsonConvert.ToString(Double.PositiveInfinity));
Assert.AreEqual(JsonConvert.NegativeInfinity, JsonConvert.ToString(Double.NegativeInfinity));
Assert.AreEqual(JsonConvert.NaN, JsonConvert.ToString(Double.NaN));
}
[Test]
public void DecimalToString()
{
Assert.AreEqual("1.1", JsonConvert.ToString(1.1m));
Assert.AreEqual("1.11", JsonConvert.ToString(1.11m));
Assert.AreEqual("1.111", JsonConvert.ToString(1.111m));
Assert.AreEqual("1.1111", JsonConvert.ToString(1.1111m));
Assert.AreEqual("1.11111", JsonConvert.ToString(1.11111m));
Assert.AreEqual("1.111111", JsonConvert.ToString(1.111111m));
Assert.AreEqual("1.0", JsonConvert.ToString(1.0m));
Assert.AreEqual("-1.0", JsonConvert.ToString(-1.0m));
Assert.AreEqual("-1.0", JsonConvert.ToString(-1m));
Assert.AreEqual("1.0", JsonConvert.ToString(1m));
Assert.AreEqual("1.01", JsonConvert.ToString(1.01m));
Assert.AreEqual("1.001", JsonConvert.ToString(1.001m));
Assert.AreEqual("79228162514264337593543950335.0", JsonConvert.ToString(Decimal.MaxValue));
Assert.AreEqual("-79228162514264337593543950335.0", JsonConvert.ToString(Decimal.MinValue));
}
[Test]
public void StringEscaping()
{
string v = @"It's a good day
""sunshine""";
string json = JsonConvert.ToString(v);
Assert.AreEqual(@"""It's a good day\r\n\""sunshine\""""", json);
}
[Test]
public void WriteDateTime()
{
DateTimeResult result = null;
result = TestDateTime("DateTime Max", DateTime.MaxValue);
Assert.AreEqual("9999-12-31T23:59:59.9999999", result.IsoDateRoundtrip);
Assert.AreEqual("9999-12-31T23:59:59.9999999" + GetOffset(DateTime.MaxValue, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("9999-12-31T23:59:59.9999999", result.IsoDateUnspecified);
Assert.AreEqual("9999-12-31T23:59:59.9999999Z", result.IsoDateUtc);
Assert.AreEqual(@"\/Date(253402300799999)\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(253402300799999" + GetOffset(DateTime.MaxValue, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(253402300799999)\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(253402300799999)\/", result.MsDateUtc);
DateTime year2000local = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Local);
string localToUtcDate = year2000local.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFFK");
result = TestDateTime("DateTime Local", year2000local);
Assert.AreEqual("2000-01-01T01:01:01" + GetOffset(year2000local, DateFormatHandling.IsoDateFormat), result.IsoDateRoundtrip);
Assert.AreEqual("2000-01-01T01:01:01" + GetOffset(year2000local, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("2000-01-01T01:01:01", result.IsoDateUnspecified);
Assert.AreEqual(localToUtcDate, result.IsoDateUtc);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000local) + GetOffset(year2000local, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000local) + GetOffset(year2000local, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000local) + GetOffset(year2000local, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000local) + @")\/", result.MsDateUtc);
DateTime millisecondsLocal = new DateTime(2000, 1, 1, 1, 1, 1, 999, DateTimeKind.Local);
localToUtcDate = millisecondsLocal.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFFK");
result = TestDateTime("DateTime Local with milliseconds", millisecondsLocal);
Assert.AreEqual("2000-01-01T01:01:01.999" + GetOffset(millisecondsLocal, DateFormatHandling.IsoDateFormat), result.IsoDateRoundtrip);
Assert.AreEqual("2000-01-01T01:01:01.999" + GetOffset(millisecondsLocal, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("2000-01-01T01:01:01.999", result.IsoDateUnspecified);
Assert.AreEqual(localToUtcDate, result.IsoDateUtc);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + GetOffset(millisecondsLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + GetOffset(millisecondsLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + GetOffset(millisecondsLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + @")\/", result.MsDateUtc);
DateTime ticksLocal = new DateTime(634663873826822481, DateTimeKind.Local);
localToUtcDate = ticksLocal.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFFK");
result = TestDateTime("DateTime Local with ticks", ticksLocal);
Assert.AreEqual("2012-03-03T16:03:02.6822481" + GetOffset(ticksLocal, DateFormatHandling.IsoDateFormat), result.IsoDateRoundtrip);
Assert.AreEqual("2012-03-03T16:03:02.6822481" + GetOffset(ticksLocal, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("2012-03-03T16:03:02.6822481", result.IsoDateUnspecified);
Assert.AreEqual(localToUtcDate, result.IsoDateUtc);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(ticksLocal) + GetOffset(ticksLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(ticksLocal) + GetOffset(ticksLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(ticksLocal) + GetOffset(ticksLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(ticksLocal) + @")\/", result.MsDateUtc);
DateTime year2000Unspecified = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified);
result = TestDateTime("DateTime Unspecified", year2000Unspecified);
Assert.AreEqual("2000-01-01T01:01:01", result.IsoDateRoundtrip);
Assert.AreEqual("2000-01-01T01:01:01" + GetOffset(year2000Unspecified, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("2000-01-01T01:01:01", result.IsoDateUnspecified);
Assert.AreEqual("2000-01-01T01:01:01Z", result.IsoDateUtc);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000Unspecified) + GetOffset(year2000Unspecified, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000Unspecified) + GetOffset(year2000Unspecified, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000Unspecified) + GetOffset(year2000Unspecified, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000Unspecified.ToLocalTime()) + @")\/", result.MsDateUtc);
DateTime year2000Utc = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc);
string utcTolocalDate = year2000Utc.ToLocalTime().ToString("yyyy-MM-ddTHH:mm:ss");
result = TestDateTime("DateTime Utc", year2000Utc);
Assert.AreEqual("2000-01-01T01:01:01Z", result.IsoDateRoundtrip);
Assert.AreEqual(utcTolocalDate + GetOffset(year2000Utc, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("2000-01-01T01:01:01", result.IsoDateUnspecified);
Assert.AreEqual("2000-01-01T01:01:01Z", result.IsoDateUtc);
Assert.AreEqual(@"\/Date(946688461000)\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(946688461000" + GetOffset(year2000Utc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(DateTime.SpecifyKind(year2000Utc, DateTimeKind.Unspecified)) + GetOffset(year2000Utc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(946688461000)\/", result.MsDateUtc);
DateTime unixEpoc = new DateTime(621355968000000000, DateTimeKind.Utc);
utcTolocalDate = unixEpoc.ToLocalTime().ToString("yyyy-MM-ddTHH:mm:ss");
result = TestDateTime("DateTime Unix Epoc", unixEpoc);
Assert.AreEqual("1970-01-01T00:00:00Z", result.IsoDateRoundtrip);
Assert.AreEqual(utcTolocalDate + GetOffset(unixEpoc, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("1970-01-01T00:00:00", result.IsoDateUnspecified);
Assert.AreEqual("1970-01-01T00:00:00Z", result.IsoDateUtc);
Assert.AreEqual(@"\/Date(0)\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(0" + GetOffset(unixEpoc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(DateTime.SpecifyKind(unixEpoc, DateTimeKind.Unspecified)) + GetOffset(unixEpoc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(0)\/", result.MsDateUtc);
result = TestDateTime("DateTime Min", DateTime.MinValue);
Assert.AreEqual("0001-01-01T00:00:00", result.IsoDateRoundtrip);
Assert.AreEqual("0001-01-01T00:00:00" + GetOffset(DateTime.MinValue, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("0001-01-01T00:00:00", result.IsoDateUnspecified);
Assert.AreEqual("0001-01-01T00:00:00Z", result.IsoDateUtc);
Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(-62135596800000" + GetOffset(DateTime.MinValue, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateUtc);
result = TestDateTime("DateTime Default", default(DateTime));
Assert.AreEqual("0001-01-01T00:00:00", result.IsoDateRoundtrip);
Assert.AreEqual("0001-01-01T00:00:00" + GetOffset(default(DateTime), DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("0001-01-01T00:00:00", result.IsoDateUnspecified);
Assert.AreEqual("0001-01-01T00:00:00Z", result.IsoDateUtc);
Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(-62135596800000" + GetOffset(default(DateTime), DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateUtc);
#if !NET20
result = TestDateTime("DateTimeOffset TimeSpan Zero", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero));
Assert.AreEqual("2000-01-01T01:01:01+00:00", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(946688461000+0000)\/", result.MsDateRoundtrip);
result = TestDateTime("DateTimeOffset TimeSpan 1 hour", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(1)));
Assert.AreEqual("2000-01-01T01:01:01+01:00", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(946684861000+0100)\/", result.MsDateRoundtrip);
result = TestDateTime("DateTimeOffset TimeSpan 1.5 hour", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(1.5)));
Assert.AreEqual("2000-01-01T01:01:01+01:30", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(946683061000+0130)\/", result.MsDateRoundtrip);
result = TestDateTime("DateTimeOffset TimeSpan 13 hour", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(13)));
Assert.AreEqual("2000-01-01T01:01:01+13:00", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(946641661000+1300)\/", result.MsDateRoundtrip);
result = TestDateTime("DateTimeOffset TimeSpan with ticks", new DateTimeOffset(634663873826822481, TimeSpan.Zero));
Assert.AreEqual("2012-03-03T16:03:02.6822481+00:00", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(1330790582682+0000)\/", result.MsDateRoundtrip);
result = TestDateTime("DateTimeOffset Min", DateTimeOffset.MinValue);
Assert.AreEqual("0001-01-01T00:00:00+00:00", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(-62135596800000+0000)\/", result.MsDateRoundtrip);
result = TestDateTime("DateTimeOffset Max", DateTimeOffset.MaxValue);
Assert.AreEqual("9999-12-31T23:59:59.9999999+00:00", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(253402300799999+0000)\/", result.MsDateRoundtrip);
result = TestDateTime("DateTimeOffset Default", default(DateTimeOffset));
Assert.AreEqual("0001-01-01T00:00:00+00:00", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(-62135596800000+0000)\/", result.MsDateRoundtrip);
#endif
}
public class DateTimeResult
{
public string IsoDateRoundtrip { get; set; }
public string IsoDateLocal { get; set; }
public string IsoDateUnspecified { get; set; }
public string IsoDateUtc { get; set; }
public string MsDateRoundtrip { get; set; }
public string MsDateLocal { get; set; }
public string MsDateUnspecified { get; set; }
public string MsDateUtc { get; set; }
}
private DateTimeResult TestDateTime<T>(string name, T value)
{
Console.WriteLine(name);
DateTimeResult result = new DateTimeResult();
result.IsoDateRoundtrip = TestDateTimeFormat(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind);
if (value is DateTime)
{
result.IsoDateLocal = TestDateTimeFormat(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.Local);
result.IsoDateUnspecified = TestDateTimeFormat(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.Unspecified);
result.IsoDateUtc = TestDateTimeFormat(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.Utc);
}
result.MsDateRoundtrip = TestDateTimeFormat(value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.RoundtripKind);
if (value is DateTime)
{
result.MsDateLocal = TestDateTimeFormat(value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.Local);
result.MsDateUnspecified = TestDateTimeFormat(value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.Unspecified);
result.MsDateUtc = TestDateTimeFormat(value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.Utc);
}
TestDateTimeFormat(value, new IsoDateTimeConverter());
#if !NETFX_CORE
if (value is DateTime)
{
Console.WriteLine(XmlConvert.ToString((DateTime)(object)value, XmlDateTimeSerializationMode.RoundtripKind));
}
else
{
Console.WriteLine(XmlConvert.ToString((DateTimeOffset)(object)value));
}
#endif
#if !NET20
MemoryStream ms = new MemoryStream();
DataContractSerializer s = new DataContractSerializer(typeof(T));
s.WriteObject(ms, value);
string json = Encoding.UTF8.GetString(ms.ToArray(), 0, Convert.ToInt32(ms.Length));
Console.WriteLine(json);
#endif
Console.WriteLine();
return result;
}
private static string TestDateTimeFormat<T>(T value, DateFormatHandling format, DateTimeZoneHandling timeZoneHandling)
{
string date = null;
if (value is DateTime)
{
date = JsonConvert.ToString((DateTime)(object)value, format, timeZoneHandling);
}
else
{
#if !NET20
date = JsonConvert.ToString((DateTimeOffset)(object)value, format);
#endif
}
Console.WriteLine(format.ToString("g") + "-" + timeZoneHandling.ToString("g") + ": " + date);
if (timeZoneHandling == DateTimeZoneHandling.RoundtripKind)
{
T parsed = JsonConvert.DeserializeObject<T>(date);
try
{
Assert.AreEqual(value, parsed);
}
catch (Exception)
{
long valueTicks = GetTicks(value);
long parsedTicks = GetTicks(parsed);
valueTicks = (valueTicks/10000)*10000;
Assert.AreEqual(valueTicks, parsedTicks);
}
}
return date.Trim('"');
}
private static void TestDateTimeFormat<T>(T value, JsonConverter converter)
{
string date = Write(value, converter);
Console.WriteLine(converter.GetType().Name + ": " + date);
T parsed = Read<T>(date, converter);
try
{
Assert.AreEqual(value, parsed);
}
catch (Exception)
{
// JavaScript ticks aren't as precise, recheck after rounding
long valueTicks = GetTicks(value);
long parsedTicks = GetTicks(parsed);
valueTicks = (valueTicks / 10000) * 10000;
Assert.AreEqual(valueTicks, parsedTicks);
}
}
public static long GetTicks(object value)
{
return (value is DateTime) ? ((DateTime)value).Ticks : ((DateTimeOffset)value).Ticks;
}
public static string Write(object value, JsonConverter converter)
{
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
converter.WriteJson(writer, value, null);
writer.Flush();
return sw.ToString();
}
public static T Read<T>(string text, JsonConverter converter)
{
JsonTextReader reader = new JsonTextReader(new StringReader(text));
reader.ReadAsString();
return (T)converter.ReadJson(reader, typeof(T), null, null);
}
#if !(NET20 || NET35 || SILVERLIGHT || PORTABLE40)
[Test]
public void Async()
{
Task<string> task = null;
task = JsonConvert.SerializeObjectAsync(42);
task.Wait();
Assert.AreEqual("42", task.Result);
task = JsonConvert.SerializeObjectAsync(new[] {1, 2, 3, 4, 5}, Formatting.Indented);
task.Wait();
Assert.AreEqual(@"[
1,
2,
3,
4,
5
]", task.Result);
task = JsonConvert.SerializeObjectAsync(DateTime.MaxValue, Formatting.None, new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
});
task.Wait();
Assert.AreEqual(@"""\/Date(253402300799999)\/""", task.Result);
var taskObject = JsonConvert.DeserializeObjectAsync("[]");
taskObject.Wait();
CollectionAssert.AreEquivalent(new JArray(), (JArray)taskObject.Result);
Task<object> taskVersionArray = JsonConvert.DeserializeObjectAsync("['2.0']", typeof(Version[]), new JsonSerializerSettings
{
Converters = {new VersionConverter()}
});
taskVersionArray.Wait();
Version[] versionArray = (Version[])taskVersionArray.Result;
Assert.AreEqual(1, versionArray.Length);
Assert.AreEqual(2, versionArray[0].Major);
Task<int> taskInt = JsonConvert.DeserializeObjectAsync<int>("5");
taskInt.Wait();
Assert.AreEqual(5, taskInt.Result);
var taskVersion = JsonConvert.DeserializeObjectAsync<Version>("'2.0'", new JsonSerializerSettings
{
Converters = {new VersionConverter()}
});
taskVersion.Wait();
Assert.AreEqual(2, taskVersion.Result.Major);
Movie p = new Movie();
p.Name = "Existing,";
Task taskVoid = JsonConvert.PopulateObjectAsync("{'Name':'Appended'}", p, new JsonSerializerSettings
{
Converters = new List<JsonConverter> { new JsonSerializerTest.StringAppenderConverter() }
});
taskVoid.Wait();
Assert.AreEqual("Existing,Appended", p.Name);
}
#endif
[Test]
public void SerializeObjectDateTimeZoneHandling()
{
string json = JsonConvert.SerializeObject(
new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified),
new JsonSerializerSettings
{
DateTimeZoneHandling = DateTimeZoneHandling.Utc
});
Assert.AreEqual(@"""2000-01-01T01:01:01Z""", json);
}
[Test]
public void DeserializeObject()
{
string json = @"{
'Name': 'Bad Boys',
'ReleaseDate': '1995-4-7T00:00:00',
'Genres': [
'Action',
'Comedy'
]
}";
Movie m = JsonConvert.DeserializeObject<Movie>(json);
string name = m.Name;
// Bad Boys
Assert.AreEqual("Bad Boys", m.Name);
}
//[Test]
public void StackOverflowTest()
{
StringBuilder sb = new StringBuilder();
int depth = 900;
for (int i = 0; i < depth; i++)
{
sb.Append("{'A':");
}
// invalid json
sb.Append("{***}");
for (int i = 0; i < depth; i++)
{
sb.Append("}");
}
string json = sb.ToString();
JsonSerializer serializer = new JsonSerializer() { };
serializer.Deserialize<Nest>(new JsonTextReader(new StringReader(json)));
}
public class Nest
{
public Nest A { get; set; }
}
}
}
| |
using nClam;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Reflection;
using System.Text;
using Teknik.Areas.Stats.Models;
using Teknik.Areas.Upload.Models;
using Teknik.Areas.Users.Models;
using Teknik.Areas.Users.Utility;
using Teknik.Configuration;
using Teknik.Utilities;
using Teknik.Models;
using System.Threading.Tasks;
using Teknik.Utilities.Cryptography;
namespace ServerMaint
{
public class Program
{
private static string currentPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
private static string virusFile = Path.Combine(currentPath, "virusLogs.txt");
private static string errorFile = Path.Combine(currentPath, "errorLogs.txt");
private static string configPath = currentPath;
private const string TAKEDOWN_REPORTER = "Teknik Automated System";
private static readonly object dbLock = new object();
private static readonly object scanStatsLock = new object();
public static event Action<string> OutputEvent;
public static int Main(string[] args)
{
try
{
ArgumentOptions options = new ArgumentOptions();
var parser = new CommandLine.Parser(config => config.HelpWriter = Console.Out);
if (parser.ParseArguments(args, options))
{
if (!string.IsNullOrEmpty(options.Config))
configPath = options.Config;
if (Directory.Exists(configPath))
{
Config config = Config.Load(configPath);
Output(string.Format("[{0}] Started Server Maintenance Process.", DateTime.Now));
using (TeknikEntities db = new TeknikEntities())
{
// Scan all the uploads for viruses, and remove the bad ones
if (options.ScanUploads && config.UploadConfig.VirusScanEnable)
{
ScanUploads(config, db);
}
// Warns all the invalid accounts via email
if (options.WarnAccounts)
{
WarnInvalidAccounts(config, db);
}
// Cleans all inactive users
if (options.CleanUsers)
{
CleanAccounts(config, db, options.DaysBeforeDeletion);
}
// Cleans the email for unused accounts
if (options.CleanEmails)
{
CleanEmail(config, db);
}
// Cleans all the git accounts that are unused
if (options.CleanGit)
{
CleanGit(config, db);
}
// Generates a file for all of the user's last seen dates
if (options.GenerateLastSeen)
{
GenerateLastSeen(config, db, options.LastSeenFile);
}
// Generates a file for all of the invalid accounts
if (options.GenerateInvalid)
{
GenerateInvalidAccounts(config, db, options.InvalidFile);
}
// Generates a file for all of the accounts to be cleaned
if (options.GenerateCleaning)
{
GenerateCleaningList(config, db, options.CleaningFile, options.DaysBeforeDeletion);
}
}
Output(string.Format("[{0}] Finished Server Maintenance Process.", DateTime.Now));
return 0;
}
else
{
string msg = string.Format("[{0}] Config File does not exist.", DateTime.Now);
File.AppendAllLines(errorFile, new List<string> { msg });
Output(msg);
}
}
else
{
Output(options.GetUsage());
}
}
catch (Exception ex)
{
string msg = string.Format("[{0}] Exception: {1}", DateTime.Now, ex.GetFullMessage(true));
File.AppendAllLines(errorFile, new List<string> { msg });
Output(msg);
}
return -1;
}
public static void ScanUploads(Config config, TeknikEntities db)
{
Output(string.Format("[{0}] Started Virus Scan.", DateTime.Now));
List<Upload> uploads = db.Uploads.ToList();
int totalCount = uploads.Count();
int totalScans = 0;
int totalViruses = 0;
List<Task> runningTasks = new List<Task>();
foreach (Upload upload in uploads)
{
int currentScan = totalScans++;
Task scanTask = Task.Factory.StartNew(() => ScanUpload(config, db, upload, totalCount, currentScan, ref totalViruses));
if (scanTask != null)
{
runningTasks.Add(scanTask);
}
}
bool running = true;
while (running)
{
running = runningTasks.Exists(s => s != null && !s.IsCompleted && !s.IsCanceled && !s.IsFaulted);
}
Output(string.Format("Scanning Complete. {0} Scanned | {1} Viruses Found | {2} Total Files", totalScans, totalViruses, totalCount));
}
private static void ScanUpload(Config config, TeknikEntities db, Upload upload, int totalCount, int currentCount, ref int totalViruses)
{
// Initialize ClamAV
ClamClient clam = new ClamClient(config.UploadConfig.ClamServer, config.UploadConfig.ClamPort);
clam.MaxStreamSize = config.UploadConfig.MaxUploadSize;
string subDir = upload.FileName[0].ToString();
string filePath = Path.Combine(config.UploadConfig.UploadDirectory, subDir, upload.FileName);
if (File.Exists(filePath))
{
// If the IV is set, and Key is set, then scan it
if (!string.IsNullOrEmpty(upload.Key) && !string.IsNullOrEmpty(upload.IV))
{
byte[] keyBytes = Encoding.UTF8.GetBytes(upload.Key);
byte[] ivBytes = Encoding.UTF8.GetBytes(upload.IV);
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
AesCounterStream aesStream = new AesCounterStream(fs, false, keyBytes, ivBytes);
// We have the data, let's scan it
ClamScanResult scanResult = clam.SendAndScanFile(aesStream);
// Close file stream
fs.Close();
switch (scanResult.Result)
{
case ClamScanResults.Clean:
string cleanMsg = string.Format("[{0}] Clean Scan: {1}/{2} Scanned | {3} - {4}", DateTime.Now, currentCount, totalCount, upload.Url, upload.FileName);
Output(cleanMsg);
break;
case ClamScanResults.VirusDetected:
string msg = string.Format("[{0}] Virus Detected: {1} - {2} - {3}", DateTime.Now, upload.Url, upload.FileName, scanResult.InfectedFiles.First().VirusName);
Output(msg);
lock (scanStatsLock)
{
totalViruses++;
File.AppendAllLines(virusFile, new List<string> { msg });
}
lock (dbLock)
{
string urlName = upload.Url;
// Delete from the DB
db.Uploads.Remove(upload);
// Delete the File
if (File.Exists(filePath))
{
File.Delete(filePath);
}
// Add to transparency report if any were found
Takedown report = db.Takedowns.Create();
report.Requester = TAKEDOWN_REPORTER;
report.RequesterContact = config.SupportEmail;
report.DateRequested = DateTime.Now;
report.Reason = "Malware Found";
report.ActionTaken = string.Format("Upload removed: {0}", urlName);
report.DateActionTaken = DateTime.Now;
db.Takedowns.Add(report);
// Save Changes
db.SaveChanges();
}
break;
case ClamScanResults.Error:
string errorMsg = string.Format("[{0}] Scan Error: {1}", DateTime.Now, scanResult.RawResult);
File.AppendAllLines(errorFile, new List<string> { errorMsg });
Output(errorMsg);
break;
case ClamScanResults.Unknown:
string unkMsg = string.Format("[{0}] Unknown Scan Result: {1}", DateTime.Now, scanResult.RawResult);
File.AppendAllLines(errorFile, new List<string> { unkMsg });
Output(unkMsg);
break;
}
}
}
}
public static void WarnInvalidAccounts(Config config, TeknikEntities db)
{
Output(string.Format("[{0}] Started Warning of Invalid Accounts.", DateTime.Now));
List<string> invalidAccounts = GetInvalidAccounts(config, db);
foreach (string account in invalidAccounts)
{
// Let's send them an email :D
string email = UserHelper.GetUserEmailAddress(config, account);
SmtpClient client = new SmtpClient();
client.Host = config.ContactConfig.EmailAccount.Host;
client.Port = config.ContactConfig.EmailAccount.Port;
client.EnableSsl = config.ContactConfig.EmailAccount.SSL;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = true;
client.Credentials = new NetworkCredential(config.ContactConfig.EmailAccount.Username, config.ContactConfig.EmailAccount.Password);
client.Timeout = 5000;
try
{
MailMessage mail = new MailMessage(config.ContactConfig.EmailAccount.EmailAddress, email);
mail.Subject = "Invalid Account Notice";
mail.Body = string.Format(@"
The account {0} does not meet the requirements for a valid username.
The username must meet the following requirements: {1}
It must also be greater than or equal to {2} characters in length, and less than or equal to {3} characters in length.
This email is to let you know that this account will be deleted in {4} days ({5}) in order to comply with the username restrictions. If you would like to keep your data, you should create a new account and transfer the data over to the new account.
In order to make the process as easy as possible, you can reply to this email to ask for your current account to be renamed to another available account. This would keep all your data intact, and just require you to change all references to your email/git/user to the new username. If you wish to do this, please respond within {6} days ({7}) with the new username you would like to use.
Thank you for your continued use of Teknik!
- Teknik Administration", account, config.UserConfig.UsernameFilterLabel, config.UserConfig.MinUsernameLength, config.UserConfig.MaxUsernameLength, 30, DateTime.Now.AddDays(30).ToShortDateString(), 15, DateTime.Now.AddDays(15).ToShortDateString());
mail.BodyEncoding = UTF8Encoding.UTF8;
mail.DeliveryNotificationOptions = DeliveryNotificationOptions.Never;
client.Send(mail);
}
catch (Exception ex)
{
Output(string.Format("[{0}] Unable to send email to {1}. Exception: {2}", DateTime.Now, email, ex.Message));
}
}
Output(string.Format("[{0}] Finished Warning of Invalid Accounts. {1} Accounts Warned.", DateTime.Now, invalidAccounts.Count));
}
public static void CleanAccounts(Config config, TeknikEntities db, int maxDays)
{
Output(string.Format("[{0}] Started Cleaning of Inactive/Invalid Users.", DateTime.Now));
List<string> invalidAccounts = GetInvalidAccounts(config, db);
List<string> inactiveAccounts = GetInactiveAccounts(config, db, maxDays);
// Delete invalid accounts
foreach (string account in invalidAccounts)
{
UserHelper.DeleteAccount(db, config, UserHelper.GetUser(db, account));
}
if (invalidAccounts.Count > 0)
{
// Add to transparency report if any users were removed
Takedown report = db.Takedowns.Create();
report.Requester = TAKEDOWN_REPORTER;
report.RequesterContact = config.SupportEmail;
report.DateRequested = DateTime.Now;
report.Reason = "Username Invalid";
report.ActionTaken = string.Format("{0} Accounts Removed", invalidAccounts.Count);
report.DateActionTaken = DateTime.Now;
db.Takedowns.Add(report);
db.SaveChanges();
}
// Delete inactive accounts
foreach (string account in inactiveAccounts)
{
UserHelper.DeleteAccount(db, config, UserHelper.GetUser(db, account));
}
if (invalidAccounts.Count > 0)
{
// Add to transparency report if any users were removed
Takedown report = db.Takedowns.Create();
report.Requester = TAKEDOWN_REPORTER;
report.RequesterContact = config.SupportEmail;
report.DateRequested = DateTime.Now;
report.Reason = "Account Inactive";
report.ActionTaken = string.Format("{0} Accounts Removed", inactiveAccounts.Count);
report.DateActionTaken = DateTime.Now;
db.Takedowns.Add(report);
db.SaveChanges();
}
Output(string.Format("[{0}] Finished Cleaning of Inactive/Invalid Users. {1} Accounts Removed.", DateTime.Now, invalidAccounts.Count + inactiveAccounts.Count));
}
public static void CleanEmail(Config config, TeknikEntities db)
{
Output(string.Format("[{0}] Started Cleaning of Orphaned Email Accounts.", DateTime.Now));
List<string> emails = GetOrphanedEmail(config, db);
foreach (string email in emails)
{
// User doesn't exist, and it isn't reserved. Let's nuke it.
UserHelper.DeleteUserEmail(config, email);
}
if (emails.Count > 0)
{
// Add to transparency report if any users were removed
Takedown report = db.Takedowns.Create();
report.Requester = TAKEDOWN_REPORTER;
report.RequesterContact = config.SupportEmail;
report.DateRequested = DateTime.Now;
report.Reason = "Orphaned Email Account";
report.ActionTaken = string.Format("{0} Accounts Removed", emails.Count);
report.DateActionTaken = DateTime.Now;
db.Takedowns.Add(report);
db.SaveChanges();
}
Output(string.Format("[{0}] Finished Cleaning of Orphaned Email Accounts. {1} Accounts Removed.", DateTime.Now, emails.Count));
}
public static void CleanGit(Config config, TeknikEntities db)
{
Output(string.Format("[{0}] Started Cleaning of Orphaned Git Accounts.", DateTime.Now));
List<string> gitAccounts = GetOrphanedGit(config, db);
foreach (string account in gitAccounts)
{
// User doesn't exist, and it isn't reserved. Let's nuke it.
UserHelper.DeleteUserGit(config, account);
}
if (gitAccounts.Count > 0)
{
// Add to transparency report if any users were removed
Takedown report = db.Takedowns.Create();
report.Requester = TAKEDOWN_REPORTER;
report.RequesterContact = config.SupportEmail;
report.DateRequested = DateTime.Now;
report.Reason = "Orphaned Git Account";
report.ActionTaken = string.Format("{0} Accounts Removed", gitAccounts.Count);
report.DateActionTaken = DateTime.Now;
db.Takedowns.Add(report);
db.SaveChanges();
}
Output(string.Format("[{0}] Finished Cleaning of Orphaned Git Accounts. {1} Accounts Removed.", DateTime.Now, gitAccounts.Count));
}
public static void GenerateLastSeen(Config config, TeknikEntities db, string fileName)
{
Output(string.Format("[{0}] Started Generation of Last Activity List.", DateTime.Now));
List<User> curUsers = db.Users.ToList();
StringBuilder sb = new StringBuilder();
sb.AppendLine("Username,Last Activity,Creation Date,Last Website Activity,Last Email Activity,Last Git Activity");
foreach (User user in curUsers)
{
sb.AppendLine(string.Format("{0},{1},{2},{3},{4},{5}",
user.Username,
UserHelper.GetLastAccountActivity(db, config, user).ToString("g"),
user.JoinDate.ToString("g"),
user.LastSeen.ToString("g"),
UserHelper.UserEmailLastActive(config, UserHelper.GetUserEmailAddress(config, user.Username)).ToString("g"),
UserHelper.UserGitLastActive(config, user.Username).ToString("g")));
}
string dir = Path.GetDirectoryName(fileName);
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
File.WriteAllText(fileName, sb.ToString());
Output(string.Format("[{0}] Finished Generating Last Activity List.", DateTime.Now));
}
public static void GenerateInvalidAccounts(Config config, TeknikEntities db, string fileName)
{
Output(string.Format("[{0}] Started Generation of Invalid Account List.", DateTime.Now));
List<string> invalidAccounts = GetInvalidAccounts(config, db);
StringBuilder sb = new StringBuilder();
sb.AppendLine("Username,Last Activity,Creation Date,Last Website Activity,Last Email Activity,Last Git Activity");
foreach (string account in invalidAccounts)
{
User user = UserHelper.GetUser(db, account);
sb.AppendLine(string.Format("{0},{1},{2},{3},{4},{5}",
user.Username,
UserHelper.GetLastAccountActivity(db, config, user).ToString("g"),
user.JoinDate.ToString("g"),
user.LastSeen.ToString("g"),
UserHelper.UserEmailLastActive(config, UserHelper.GetUserEmailAddress(config, user.Username)).ToString("g"),
UserHelper.UserGitLastActive(config, user.Username).ToString("g")));
}
string dir = Path.GetDirectoryName(fileName);
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
File.WriteAllText(fileName, sb.ToString());
Output(string.Format("[{0}] Finished Generating Invalid Account List.", DateTime.Now));
}
public static void GenerateCleaningList(Config config, TeknikEntities db, string fileName, int maxDays)
{
Output(string.Format("[{0}] Started Generation of Accounts to Clean List.", DateTime.Now));
List<string> invalidAccounts = GetInvalidAccounts(config, db);
List<string> inactiveAccounts = GetInactiveAccounts(config, db, maxDays);
List<string> emailAccounts = GetOrphanedEmail(config, db);
List<string> gitAccounts = GetOrphanedGit(config, db);
StringBuilder sb = new StringBuilder();
sb.AppendLine("Invalid Account Cleaning");
sb.AppendLine("Username,Last Activity,Creation Date,Last Website Activity,Last Email Activity,Last Git Activity");
foreach (string account in invalidAccounts)
{
User user = UserHelper.GetUser(db, account);
sb.AppendLine(string.Format("{0},{1},{2},{3},{4},{5}",
user.Username,
UserHelper.GetLastAccountActivity(db, config, user).ToString("g"),
user.JoinDate.ToString("g"),
user.LastSeen.ToString("g"),
UserHelper.UserEmailExists(config, UserHelper.GetUserEmailAddress(config, user.Username)) ? UserHelper.UserEmailLastActive(config, UserHelper.GetUserEmailAddress(config, user.Username)).ToString("g") : null,
UserHelper.UserGitExists(config, user.Username) ? UserHelper.UserGitLastActive(config, user.Username).ToString("g") : null));
}
sb.AppendLine();
sb.AppendLine("Inactive Account Cleaning");
sb.AppendLine("Username,Last Activity,Creation Date,Last Website Activity,Last Email Activity,Last Git Activity");
foreach (string account in inactiveAccounts)
{
User user = UserHelper.GetUser(db, account);
sb.AppendLine(string.Format("{0},{1},{2},{3},{4},{5}",
user.Username,
UserHelper.GetLastAccountActivity(db, config, user).ToString("g"),
user.JoinDate.ToString("g"),
user.LastSeen.ToString("g"),
UserHelper.UserEmailExists(config, UserHelper.GetUserEmailAddress(config, user.Username)) ? UserHelper.UserEmailLastActive(config, UserHelper.GetUserEmailAddress(config, user.Username)).ToString("g") : null,
UserHelper.UserGitExists(config, user.Username) ? UserHelper.UserGitLastActive(config, user.Username).ToString("g") : null));
}
sb.AppendLine();
sb.AppendLine("Orphaned Email Cleaning");
sb.AppendLine("Email,Last Activity");
foreach (string account in emailAccounts)
{
sb.AppendLine(string.Format("{0},{1}",
account,
UserHelper.UserEmailExists(config, account) ? UserHelper.UserEmailLastActive(config, account).ToString("g") : null));
}
sb.AppendLine();
sb.AppendLine("Orphaned Git Cleaning");
sb.AppendLine("Username,Last Activity");
foreach (string account in gitAccounts)
{
sb.AppendLine(string.Format("{0},{1}",
account,
UserHelper.UserGitExists(config, account) ? UserHelper.UserGitLastActive(config, account).ToString("g") : null));
}
string dir = Path.GetDirectoryName(fileName);
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
File.WriteAllText(fileName, sb.ToString());
Output(string.Format("[{0}] Finished Generating Accounts to Clean List.", DateTime.Now));
}
public static List<string> GetInvalidAccounts(Config config, TeknikEntities db)
{
List<string> foundUsers = new List<string>();
List<User> curUsers = db.Users.ToList();
foreach (User user in curUsers)
{
// If the username is reserved, let's add it to the list
if (UserHelper.UsernameReserved(config, user.Username) && user.Username != Constants.SERVERUSER)
{
foundUsers.Add(user.Username);
continue;
}
// If the username is invalid, let's add it to the list
if (!UserHelper.ValidUsername(config, user.Username) && user.Username != Constants.SERVERUSER)
{
foundUsers.Add(user.Username);
continue;
}
}
return foundUsers;
}
public static List<string> GetInactiveAccounts(Config config, TeknikEntities db, int maxDays)
{
List<string> foundUsers = new List<string>();
List<User> curUsers = db.Users.ToList();
foreach (User user in curUsers)
{
// If the username is reserved, don't worry about it
if (UserHelper.UsernameReserved(config, user.Username) || user.Username == Constants.SERVERUSER)
{
continue;
}
// If they are Premium, don't worry about it either
if (user.AccountType == AccountType.Premium && user.AccountStatus != AccountStatus.Banned)
{
continue;
}
#region Inactivity Finding
DateTime lastActivity = DateTime.Now;
try
{
lastActivity = UserHelper.GetLastAccountActivity(db, config, user);
}
catch
{
continue;
}
TimeSpan inactiveTime = DateTime.Now.Subtract(lastActivity);
// If older than max days, check their current usage
if (inactiveTime >= new TimeSpan(maxDays, 0, 0, 0, 0))
{
// Check the user's usage of the service.
bool noData = true;
// Any blog comments?
var blogCom = db.BlogComments.Where(c => c.UserId == user.UserId);
noData &= !(blogCom != null && blogCom.Any());
// Any blog posts?
var blogPosts = db.BlogPosts.Where(p => p.Blog.UserId == user.UserId);
noData &= !(blogPosts != null && blogPosts.Any());
// Any podcast comments?
var podCom = db.PodcastComments.Where(p => p.UserId == user.UserId);
noData &= !(podCom != null && podCom.Any());
// Any email?
if (config.EmailConfig.Enabled && UserHelper.UserEmailExists(config, UserHelper.GetUserEmailAddress(config, user.Username)))
{
var app = new hMailServer.Application();
app.Connect();
app.Authenticate(config.EmailConfig.Username, config.EmailConfig.Password);
try
{
var domain = app.Domains.ItemByName[config.EmailConfig.Domain];
var account = domain.Accounts.ItemByAddress[UserHelper.GetUserEmailAddress(config, user.Username)];
noData &= ((account.Messages.Count == 0) && ((int)account.Size == 0));
}
catch { }
}
// Any git repos?
if (config.GitConfig.Enabled && UserHelper.UserGitExists(config, user.Username))
{
string email = UserHelper.GetUserEmailAddress(config, user.Username);
// We need to check the actual git database
MysqlDatabase mySQL = new MysqlDatabase(config.GitConfig.Database.Server, config.GitConfig.Database.Database, config.GitConfig.Database.Username, config.GitConfig.Database.Password, config.GitConfig.Database.Port);
string sql = @"SELECT * FROM gogs.repository
LEFT JOIN gogs.action ON gogs.user.id = gogs.action.act_user_id
WHERE gogs.user.login_name = {0}";
var results = mySQL.Query(sql, new object[] { email });
noData &= !(results != null && results.Any());
}
if (noData)
{
// They have no data, so safe to delete them.
foundUsers.Add(user.Username);
}
continue;
}
#endregion
}
return foundUsers;
}
public static List<string> GetOrphanedEmail(Config config, TeknikEntities db)
{
List<string> foundEmail = new List<string>();
if (config.EmailConfig.Enabled)
{
List<User> curUsers = db.Users.ToList();
// Connect to hmailserver COM
var app = new hMailServer.Application();
app.Connect();
app.Authenticate(config.EmailConfig.Username, config.EmailConfig.Password);
var domain = app.Domains.ItemByName[config.EmailConfig.Domain];
var accounts = domain.Accounts;
for (int i = 0; i < accounts.Count; i++)
{
var account = accounts[i];
bool userExists = curUsers.Exists(u => UserHelper.GetUserEmailAddress(config, u.Username) == account.Address);
bool isReserved = UserHelper.GetReservedUsernames(config).Exists(r => UserHelper.GetUserEmailAddress(config, r).ToLower() == account.Address.ToLower());
if (!userExists && !isReserved)
{
foundEmail.Add(account.Address);
}
}
}
return foundEmail;
}
public static List<string> GetOrphanedGit(Config config, TeknikEntities db)
{
List<string> foundGit = new List<string>();
if (config.GitConfig.Enabled)
{
List<User> curUsers = db.Users.ToList();
// We need to check the actual git database
MysqlDatabase mySQL = new MysqlDatabase(config.GitConfig.Database.Server, config.GitConfig.Database.Database, config.GitConfig.Database.Username, config.GitConfig.Database.Password, config.GitConfig.Database.Port);
string sql = @"SELECT gogs.user.login_name AS login_name, gogs.user.lower_name AS username FROM gogs.user";
var results = mySQL.Query(sql);
if (results != null && results.Any())
{
foreach (var account in results)
{
bool userExists = curUsers.Exists(u => UserHelper.GetUserEmailAddress(config, u.Username).ToLower() == account["login_name"].ToString().ToLower());
bool isReserved = UserHelper.GetReservedUsernames(config).Exists(r => UserHelper.GetUserEmailAddress(config, r) == account["login_name"].ToString().ToLower());
if (!userExists && !isReserved)
{
foundGit.Add(account["username"].ToString());
}
}
}
}
return foundGit;
}
public static void Output(string message)
{
Console.WriteLine(message);
if (OutputEvent != null)
{
OutputEvent(message);
}
}
}
}
| |
using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using RestSharp;
namespace Hook
{
public enum Order { ASCENDING, DESCENDING };
public class Collection
{
protected Client client;
protected String name;
protected string segments;
protected Dictionary<string, Object> options;
protected List<Object[]> wheres;
protected List<string[]> ordering;
protected List<string> _group;
protected Object _limit;
protected Object _offset;
protected Object _remember;
public Collection (Client client, String name)
{
if (!this.ValidateName (name)) {
throw new Exception ("Invalid Collection name.");
}
this.client = client;
this.name = name;
this.Reset ();
this.segments = "collection/" + this.name;
}
public Request Get()
{
return this.client.Get (this.segments, this.BuildQuery ());
}
public RestRequestAsyncHandle ContinueWith<TResult>(Action<TResult> callback)
{
return this.Get ().ContinueWith<TResult> (callback);
}
protected void Reset()
{
this.options = new Dictionary<string, Object>();
this.wheres = new List<Object[]>();
this.ordering = new List<string[]>();
this._group = new List<string>();
this._limit = null;
this._offset = null;
this._remember = null;
}
protected Object BuildQuery()
{
var query = new Dictionary<string, Object>();
// apply limit / offset and remember
if (this._limit != null) { query["limit"] = this._limit; }
if (this._offset != null) { query["offset"] = this._offset; }
if (this._remember != null) { query["remember"] = this._remember; }
// apply wheres
if (this.wheres.Count > 0) {
query["q"] = this.wheres;
}
// apply ordering
if (this.ordering.Count > 0) {
query["s"] = this.ordering;
}
// apply group
if (this._group.Count > 0) {
query["g"] = this._group;
}
var shortnames = new Dictionary<string, string> () {
{"paginate", "p"},
{"first", "f"},
{"aggregation", "aggr"},
{"operation", "op"},
{"data", "data"},
{"with", "with"},
{"select", "select"}
};
foreach (var f in shortnames) {
if (this.options.ContainsKey(f.Key)) {
query[f.Value] = this.options[f.Key];
}
}
// clear wheres/ordering for future calls
this.Reset();
return query;
}
protected Collection AddWhere(string field, string operation, Object value, string boolean = "and")
{
this.wheres.Add (new [] { field, operation, value, boolean });
return this;
}
public Request Create(Object data)
{
return this.client.Post (this.segments, data);
}
public Collection Where(string field, Object value)
{
return this.AddWhere (field, "=", value);
}
public Collection Where(string field, string operation, Object value)
{
return this.AddWhere (field, operation, value);
}
public Collection OrWhere(string field, Object value)
{
return this.AddWhere (field, "=", value, "or");
}
public Collection OrWhere(string field, string operation, Object value)
{
return this.AddWhere (field, operation, value, "or");
}
public Request Find(Object _id)
{
return this.client.Get (this.segments + "/" + _id.ToString (), this.BuildQuery());
}
public Collection Select(params string[] fields)
{
this.options ["select"] = fields;
return this;
}
public Collection With(params string[] relation)
{
this.options ["with"] = relation;
return this;
}
public Collection Group(params string[] relation)
{
foreach (var r in relation) {
this._group.Add (r);
}
return this;
}
public Request Count(string field = "*")
{
this.options["aggregation"] = new { method = "count", field = field };
return this.Get ();
}
public Request Max(string field)
{
this.options["aggregation"] = new {method = "max", field = field};
return this.Get ();
}
public Request Min(string field)
{
this.options["aggregation"] = new {method = "min", field = field};
return this.Get ();
}
public Request Avg(string field)
{
this.options["aggregation"] = new {method = "avg", field = field};
return this.Get ();
}
public Request Sum(string field)
{
this.options["aggregation"] = new {method = "sum", field = field};
return this.Get ();
}
public Request First()
{
this.options ["first"] = true;
return this.Get ();
}
public Request FirstOrCreate(Object data)
{
this.options ["first"] = true;
this.options ["data"] = data;
return this.client.Post (this.segments, this.BuildQuery ());
}
public Collection Sort(string field, Order direction = Order.ASCENDING)
{
string dir = (direction == Order.ASCENDING) ? "asc" : "desc";
this.ordering.Add (new [] { field, dir });
return this;
}
public Collection Limit(int i)
{
this._limit = i;
return this;
}
public Collection Offset(int i)
{
this._offset = i;
return this;
}
public Collection Remember(int minutes)
{
this._remember = minutes;
return this;
}
public Request Remove(Object _id = null)
{
var path = this.segments;
if (_id != null) {
path += "/" + _id.ToString ();
}
return this.client.Remove (path, this.BuildQuery ());
}
public Request Update(Object _id, Object data)
{
return this.client.Post (this.segments + "/" + _id.ToString (), data);
}
public Request Increment(string field, int value = 1)
{
this.options ["operation"] = new { method = "increment", field = field, value = value };
return this.client.Put(this.segments, this.BuildQuery());
}
public Request Decrement(string field, int value = 1)
{
this.options ["operation"] = new { method = "decrement", field = field, value = value };
return this.client.Put(this.segments, this.BuildQuery());
}
public Request UpdateAll(Object data)
{
this.options ["data"] = data;
return this.client.Put (this.segments, this.BuildQuery ());
}
protected bool ValidateName(string name)
{
return Regex.IsMatch(name, "^[a-z_/0-9]+$");
}
}
}
| |
/*This code is managed under the Apache v2 license.
To see an overview:
http://www.tldrlegal.com/license/apache-license-2.0-(apache-2.0)
Author: Robert Gawdzik
www.github.com/rgawdzik/
THIS CODE HAS NO FORM OF ANY WARRANTY, AND IS CONSIDERED AS-IS.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Paradox.Game.Classes.Ships;
using Paradox.Game.Classes.Cameras;
namespace Paradox.Game.Classes.Levels
{
public abstract class Objective : Collidable
{
//The main components of what an objective truely is.
public string Title { get; protected set; }
public bool IsDone { get; protected set; } //This objective does not need to call anymore events.
public bool IsFailed { get; protected set; } //This is true when the objective is failed.
public bool IsDrawable { get; protected set; }
public Vector3 Position { get; protected set; }
public Objective()
{
Title = "";
IsDone = false;
this.BoundingSphereRadius = 0;
this.BoundingSphereCenter = Vector3.Zero;
this.CollidableType = Game.Classes.CollidableType.None;
Position = Vector3.Zero;
}
//The Game can subscribe to these events and take appropriate actions.
public event EventHandler Completed;
public event EventHandler Failed;
public abstract void Update(GameTime gameTime, EnemySquadron enemySquadron, FriendSquadron friendSquadron);
public virtual void Draw(GraphicsDevice device, Camera camera) { }
protected void FailedEvent()
{
if (Failed != null)
Failed(this, EventArgs.Empty);
IsDone = true;
IsFailed = true;
}
protected void CompletedEvent()
{
if (Completed != null)
Completed(this, EventArgs.Empty);
IsDone = true;
}
}
public class ObjectiveDrawable : Objective
{
private BasicModel _model;
private Vector3 _position;
private float _rotationSpeed;
private Quaternion _rotation;
public bool _drawModel { get; protected set; }
public ObjectiveDrawable(CollidableType type, float radius, float rotationSpeed, BasicModel model, Vector3 position, Quaternion rotation)
{
_model = model;
this.CollidableType = type;
this.BoundingSphereRadius = radius;
_position = position;
Position = _position; //Update the main branched Objective position.
_rotation = rotation;
_rotationSpeed = rotationSpeed;
IsDrawable = true;
}
public override void Update(GameTime gameTime, EnemySquadron enemySquadron, FriendSquadron friendSquadron)
{
//Gets how many seconds occured after the last update.
float second = (float)gameTime.ElapsedGameTime.TotalSeconds;
//Updates the rotation on one of the axis.
_rotation *= Quaternion.CreateFromAxisAngle(new Vector3(0, 1, 0), second * _rotationSpeed);
//Updates the model while creating a world.
_model.UpdateModel(Matrix.CreateFromQuaternion(_rotation) * Matrix.CreateTranslation(_position));
this.BoundingSphereCenter = _position;
}
public override void Draw(GraphicsDevice device, Camera camera)
{
_model.DrawModel(camera);
}
}
public class ObjectiveDestroyable : ObjectiveDrawable
{
private int Life;
private TimeSpan _totalTime;
private TimeSpan _maxTime;
public ObjectiveDestroyable(CollidableType type, float radius, float rotationSpeed, BasicModel model, Vector3 position, Quaternion rotation, string description, int life, TimeSpan maxTime)
: base(type, radius, rotationSpeed, model, position, rotation)
{
this.Title = description;
this._drawModel = true;
_maxTime = maxTime;
Life = life;
}
public override void Update(GameTime gameTime, EnemySquadron enemySquadron, FriendSquadron friendSquadron)
{
if(_totalTime < _maxTime)
_totalTime += gameTime.ElapsedGameTime;
if (Life <= 0 && _drawModel && _totalTime < _maxTime)
{
_drawModel = false;
FailedEvent();
}
if (_totalTime > _maxTime && !IsDone)
{
CompletedEvent();
}
base.Update(gameTime, enemySquadron, friendSquadron);
}
public override void Draw(GraphicsDevice device, Camera camera)
{
base.Draw(device, camera);
}
public override void Collision(CollidableType objectCollidedWithType)
{
switch (objectCollidedWithType)
{
case CollidableType.EnemyBullet:
Life--;
break;
case CollidableType.FriendlyShip:
Life--;
break;
case Game.Classes.CollidableType.PlayerBullet:
Life--;
break;
}
}
}
public class ObjectiveEnemy : Objective
{
private string _titleStart;
private int _amountEnemyTotal;
private int _amountEnemy;
public ObjectiveEnemy(string titlestart, int amountEnemyTotal)
{
_titleStart = titlestart;
_amountEnemyTotal = amountEnemyTotal;
}
public override void Update(GameTime gameTime, EnemySquadron enemySquadron, FriendSquadron friendSquadron)
{
if(!IsDone)
{
_amountEnemy = enemySquadron.ShipsDestroyedPlayer;
Title = _titleStart + _amountEnemy + " / " + _amountEnemyTotal;
if (_amountEnemy >= _amountEnemyTotal)
{
CompletedEvent();
}
}
}
}
public class ObjectiveEnemyFrigate : Objective
{
private string _titleStart;
private int _amountEnemyTotal;
private int _amountEnemy;
public ObjectiveEnemyFrigate(string titlestart, int amountEnemyTotal)
{
_titleStart = titlestart;
_amountEnemyTotal = amountEnemyTotal;
}
public override void Update(GameTime gameTime, EnemySquadron enemySquadron, FriendSquadron friendSquadron)
{
if (!IsDone)
{
_amountEnemy = enemySquadron.FrigatesDestroyedPlayer;
Title = _titleStart + _amountEnemy + " / " + _amountEnemyTotal;
if (_amountEnemy >= _amountEnemyTotal)
{
CompletedEvent();
}
}
}
}
}
| |
#region License
/*---------------------------------------------------------------------------------*\
Distributed under the terms of an MIT-style license:
The MIT License
Copyright (c) 2006-2010 Stephen M. McKamey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
\*---------------------------------------------------------------------------------*/
#endregion License
using System;
using System.IO;
using JsonFx.Model;
using JsonFx.Serialization;
namespace JsonFx.Jbst
{
/// <summary>
/// Internal representation of template commands
/// </summary>
internal abstract class JbstTemplateCall : JbstCommand
{
#region Constants
public const string ControlCommand = JbstCommand.Prefix+":control";
public const string ArgName = "name"; // id
public const string ArgData = "data"; // model
public const string ArgIndex = "index"; // current
public const string ArgCount = "count"; // length
public const string ArgVisible = "visible";
public const string ArgOnInit = "oninit";
public const string ArgOnLoad = "onload";
private const string DefaultDataExpression = "this."+JbstTemplateCall.ArgData;
private const string DefaultIndexExpression = "this."+JbstTemplateCall.ArgIndex;
private const string DefaultCountExpression = "this."+JbstTemplateCall.ArgCount;
private const string FunctionEvalExpression = "({0}).call(this)";
#endregion Constants
#region Fields
private object nameExpr;
private object dataExpr;
private object indexExpr;
private object countExpr;
#endregion Fields
#region Init
/// <summary>
/// Ctor
/// </summary>
/// <param name="state"></param>
public JbstTemplateCall(CompilationState state)
{
this.State = state;
}
#endregion Init
#region Properties
public object NameExpr
{
get { return this.nameExpr; }
set { this.nameExpr = value; }
}
public object DataExpr
{
get { return (this.dataExpr ?? JbstTemplateCall.DefaultDataExpression); }
set { this.dataExpr = value; }
}
public object IndexExpr
{
get { return (this.indexExpr ?? JbstTemplateCall.DefaultIndexExpression); }
set { this.indexExpr = value; }
}
public object CountExpr
{
get { return (this.countExpr ?? JbstTemplateCall.DefaultCountExpression); }
set { this.countExpr = value; }
}
public CompilationState State
{
get;
private set;
}
#endregion Properties
#region Utility Methods
public static string FormatExpression(ITextFormatter<ModelTokenType> formatter, object argument)
{
if (argument is string)
{
// directly use as inline expression
return ((string)argument).Trim();
}
if (argument is JbstExpressionBlock)
{
// convert to inline expression
return ((JbstExpressionBlock)argument).Code.Trim();
}
if (argument is JbstCommand)
{
using (StringWriter writer = new StringWriter())
{
// render code block as function
((JbstCommand)argument).Format(formatter, writer);
// convert to anonymous function call expression
return String.Format(FunctionEvalExpression, writer.GetStringBuilder().ToString().Trim());
}
}
// convert to token sequence and allow formatter to emit as primitive
return formatter.Format(new[] { new Token<ModelTokenType>(ModelTokenType.Primitive, argument) });
}
#endregion Utility Methods
}
/// <summary>
/// Internal representation of a reference to a named template
/// </summary>
internal class JbstTemplateReference : JbstTemplateCall
{
#region Constants
private const string TemplateReferenceFormat =
@"function() {{
return JsonML.BST({0}).dataBind({1}, {2}, {3});
}}";
#endregion Constants
#region Init
/// <summary>
/// Ctor
/// </summary>
/// <param name="state"></param>
public JbstTemplateReference(CompilationState state)
: base(state)
{
}
#endregion Init
#region Properties
/// <summary>
/// Gets the command type
/// </summary>
public override JbstCommandType CommandType
{
get { return JbstCommandType.TemplateReference; }
}
#endregion Properties
#region JbstCommand Members
public override void Format(ITextFormatter<ModelTokenType> formatter, TextWriter writer)
{
writer.Write(
JbstTemplateReference.TemplateReferenceFormat,
FormatExpression(formatter, this.NameExpr),
FormatExpression(formatter, this.DataExpr),
FormatExpression(formatter, this.IndexExpr),
FormatExpression(formatter, this.CountExpr));
}
#endregion JbstCommand Members
}
/// <summary>
/// Internal representation of an anonymous inline template
/// </summary>
internal class JbstInlineTemplate : JbstTemplateCall
{
#region Constants
private const string InlineTemplateStart =
@"function() {
return JsonML.BST(";
private const string InlineTemplateEndFormat =
@").dataBind({0}, {1}, {2});
}}";
#endregion Constants
#region Init
/// <summary>
/// Ctor
/// </summary>
/// <param name="state"></param>
public JbstInlineTemplate(CompilationState state)
: base(state)
{
}
#endregion Init
#region Properties
/// <summary>
/// Gets the command type
/// </summary>
public override JbstCommandType CommandType
{
get { return JbstCommandType.InlineTemplate; }
}
#endregion Properties
#region JbstCommand Members
public override void Format(ITextFormatter<ModelTokenType> formatter, TextWriter writer)
{
writer.Write(JbstInlineTemplate.InlineTemplateStart);
if (this.State == null ||
this.State.Content == null)
{
base.Format(formatter, writer);
}
else
{
var transformed = this.State.TransformContent();
formatter.Format(transformed, writer);
}
writer.Write(
JbstInlineTemplate.InlineTemplateEndFormat,
FormatExpression(formatter, this.DataExpr),
FormatExpression(formatter, this.IndexExpr),
FormatExpression(formatter, this.CountExpr));
}
#endregion JbstCommand Members
}
/// <summary>
/// Internal representation of a wrapper control containing named or anonymous inner-templates
/// </summary>
internal class JbstWrapperTemplate : JbstTemplateCall
{
#region Constants
public const string InlineCommand = JbstCommand.Prefix+":inline";
private const string WrapperStartFormat =
@"function() {{
return JsonML.BST({0}).dataBind({1}, {2}, {3}, ";
private const string WrapperEnd =
@");
}";
#endregion Constants
#region Init
/// <summary>
/// Ctor
/// </summary>
/// <param name="state"></param>
public JbstWrapperTemplate(CompilationState state)
: base(state)
{
}
#endregion Init
#region Properties
/// <summary>
/// Gets the command type
/// </summary>
public override JbstCommandType CommandType
{
get { return JbstCommandType.WrapperTemplate; }
}
#endregion Properties
#region JbstCommand Members
public override void Format(ITextFormatter<ModelTokenType> formatter, TextWriter writer)
{
writer.Write(JbstWrapperTemplate.WrapperStartFormat,
FormatExpression(formatter, this.NameExpr),
FormatExpression(formatter, this.DataExpr),
FormatExpression(formatter, this.IndexExpr),
FormatExpression(formatter, this.CountExpr));
if (this.State == null)
{
formatter.Format(new[]
{
new Token<ModelTokenType>(ModelTokenType.ObjectBegin),
new Token<ModelTokenType>(ModelTokenType.ObjectEnd)
}, writer);
}
else
{
var namedTemplates = this.State.NamedTemplates();
formatter.Format(namedTemplates, writer);
}
writer.Write(JbstWrapperTemplate.WrapperEnd);
}
#endregion JbstCommand Members
}
/// <summary>
/// Internal representation of a placeholder control
/// </summary>
internal class JbstPlaceholder : JbstTemplateCall
{
#region Constants
public const string PlaceholderCommand = JbstCommand.Prefix+":placeholder";
public const string InlinePrefix = "$";
private const string PlaceholderStatementStart =
@"function() {
var inline = ";
private const string PlaceholderStatementEndFormat =
@",
parts = this.args;
if (parts && parts[inline]) {{
return JsonML.BST(parts[inline]).dataBind({0}, {1}, {2}, parts);
}}
}}";
#endregion Constants
#region Init
/// <summary>
/// Ctor
/// </summary>
/// <param name="state"></param>
public JbstPlaceholder()
: base(null)
{
}
#endregion Init
#region Properties
/// <summary>
/// Gets the command type
/// </summary>
public override JbstCommandType CommandType
{
get { return JbstCommandType.Placeholder; }
}
#endregion Properties
#region JbstCommand Members
public override void Format(ITextFormatter<ModelTokenType> formatter, TextWriter writer)
{
writer.Write(JbstPlaceholder.PlaceholderStatementStart);
// escape as a string literal
formatter.Format(new[] { new Token<ModelTokenType>(ModelTokenType.Primitive, JbstPlaceholder.InlinePrefix+this.NameExpr) }, writer);
writer.Write(
JbstPlaceholder.PlaceholderStatementEndFormat,
this.DataExpr,
this.IndexExpr,
this.CountExpr);
}
#endregion JbstCommand Members
}
}
| |
// 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.Data.Common;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using SysTx = System.Transactions;
namespace System.Data.ProviderBase
{
internal abstract partial class DbConnectionInternal // V1.1.3300
{
internal static readonly StateChangeEventArgs StateChangeClosed = new StateChangeEventArgs(ConnectionState.Open, ConnectionState.Closed);
internal static readonly StateChangeEventArgs StateChangeOpen = new StateChangeEventArgs(ConnectionState.Closed, ConnectionState.Open);
private readonly bool _allowSetConnectionString;
private readonly bool _hidePassword;
private readonly ConnectionState _state;
private readonly WeakReference _owningObject = new WeakReference(null, false); // [usage must be thread safe] the owning object, when not in the pool. (both Pooled and Non-Pooled connections)
private DbConnectionPool _connectionPool; // the pooler that the connection came from (Pooled connections only)
private DbConnectionPoolCounters _performanceCounters; // the performance counters we're supposed to update
private DbReferenceCollection _referenceCollection; // collection of objects that we need to notify in some way when we're being deactivated
private int _pooledCount; // [usage must be thread safe] the number of times this object has been pushed into the pool less the number of times it's been popped (0 != inPool)
private bool _connectionIsDoomed; // true when the connection should no longer be used.
private bool _cannotBePooled; // true when the connection should no longer be pooled.
private bool _isInStasis;
private DateTime _createTime; // when the connection was created.
private SysTx.Transaction _enlistedTransaction; // [usage must be thread-safe] the transaction that we're enlisted in, either manually or automatically
// _enlistedTransaction is a clone, so that transaction information can be queried even if the original transaction object is disposed.
// However, there are times when we need to know if the original transaction object was disposed, so we keep a reference to it here.
// This field should only be assigned a value at the same time _enlistedTransaction is updated.
// Also, this reference should not be disposed, since we aren't taking ownership of it.
private SysTx.Transaction _enlistedTransactionOriginal;
#if DEBUG
private int _activateCount; // debug only counter to verify activate/deactivates are in sync.
#endif //DEBUG
protected DbConnectionInternal() : this(ConnectionState.Open, true, false)
{ // V1.1.3300
}
// Constructor for internal connections
internal DbConnectionInternal(ConnectionState state, bool hidePassword, bool allowSetConnectionString)
{
_allowSetConnectionString = allowSetConnectionString;
_hidePassword = hidePassword;
_state = state;
}
internal bool AllowSetConnectionString
{
get
{
return _allowSetConnectionString;
}
}
internal bool CanBePooled
{
get
{
bool flag = (!_connectionIsDoomed && !_cannotBePooled && !_owningObject.IsAlive);
return flag;
}
}
protected internal SysTx.Transaction EnlistedTransaction
{
get
{
return _enlistedTransaction;
}
set
{
SysTx.Transaction currentEnlistedTransaction = _enlistedTransaction;
if (((null == currentEnlistedTransaction) && (null != value))
|| ((null != currentEnlistedTransaction) && !currentEnlistedTransaction.Equals(value)))
{
// Pay attention to the order here:
// 1) defect from any notifications
// 2) replace the transaction
// 3) re-enlist in notifications for the new transaction
// we need to use a clone of the transaction
// when we store it, or we'll end up keeping it past the
// duration of the using block of the TransactionScope
SysTx.Transaction valueClone = null;
SysTx.Transaction previousTransactionClone = null;
try
{
if (null != value)
{
valueClone = value.Clone();
}
// NOTE: rather than take locks around several potential round-
// trips to the server, and/or virtual function calls, we simply
// presume that you aren't doing something illegal from multiple
// threads, and check once we get around to finalizing things
// inside a lock.
lock (this)
{
// NOTE: There is still a race condition here, when we are
// called from EnlistTransaction (which cannot re-enlist)
// instead of EnlistDistributedTransaction (which can),
// however this should have been handled by the outer
// connection which checks to ensure that it's OK. The
// only case where we have the race condition is multiple
// concurrent enlist requests to the same connection, which
// is a bit out of line with something we should have to
// support.
// enlisted transaction can be nullified in Dispose call without lock
previousTransactionClone = Interlocked.Exchange(ref _enlistedTransaction, valueClone);
_enlistedTransactionOriginal = value;
value = valueClone;
valueClone = null; // we've stored it, don't dispose it.
}
}
finally
{
// we really need to dispose our clones; they may have
// native resources and GC may not happen soon enough.
// don't dispose if still holding reference in _enlistedTransaction
if (null != previousTransactionClone &&
!Object.ReferenceEquals(previousTransactionClone, _enlistedTransaction))
{
previousTransactionClone.Dispose();
}
if (null != valueClone && !Object.ReferenceEquals(valueClone, _enlistedTransaction))
{
valueClone.Dispose();
}
}
// I don't believe that we need to lock to protect the actual
// enlistment in the transaction; it would only protect us
// against multiple concurrent calls to enlist, which really
// isn't supported anyway.
}
}
}
// Is this connection in stasis, waiting for transaction to end before returning to pool?
internal bool IsTxRootWaitingForTxEnd
{
get
{
return _isInStasis;
}
}
/// <summary>
/// Get boolean that specifies whether an enlisted transaction can be unbound from
/// the connection when that transaction completes.
/// </summary>
/// <value>
/// True if the enlisted transaction can be unbound on transaction completion; otherwise false.
/// </value>
virtual protected bool UnbindOnTransactionCompletion
{
get
{
return true;
}
}
// Is this a connection that must be put in stasis (or is already in stasis) pending the end of it's transaction?
virtual protected internal bool IsNonPoolableTransactionRoot
{
get
{
return false; // if you want to have delegated transactions that are non-poolable, you better override this...
}
}
virtual internal bool IsTransactionRoot
{
get
{
return false; // if you want to have delegated transactions, you better override this...
}
}
protected internal bool IsConnectionDoomed
{
get
{
return _connectionIsDoomed;
}
}
internal bool IsEmancipated
{
get
{
// NOTE: There are race conditions between PrePush, PostPop and this
// property getter -- only use this while this object is locked;
// (DbConnectionPool.Clear and ReclaimEmancipatedObjects
// do this for us)
// Remember how this works (I keep getting confused...)
//
// _pooledCount is incremented when the connection is pushed into the pool
// _pooledCount is decremented when the connection is popped from the pool
// _pooledCount is set to -1 when the connection is not pooled (just in case...)
//
// That means that:
//
// _pooledCount > 1 connection is in the pool multiple times (this is a serious bug...)
// _pooledCount == 1 connection is in the pool
// _pooledCount == 0 connection is out of the pool
// _pooledCount == -1 connection is not a pooled connection; we shouldn't be here for non-pooled connections.
// _pooledCount < -1 connection out of the pool multiple times (not sure how this could happen...)
//
// Now, our job is to return TRUE when the connection is out
// of the pool and it's owning object is no longer around to
// return it.
bool value = !IsTxRootWaitingForTxEnd && (_pooledCount < 1) && !_owningObject.IsAlive;
return value;
}
}
protected internal object Owner
{
// We use a weak reference to the owning object so we can identify when
// it has been garbage collected without thowing exceptions.
get
{
return _owningObject.Target;
}
}
internal DbConnectionPool Pool
{
get
{
return _connectionPool;
}
}
protected DbConnectionPoolCounters PerformanceCounters
{
get
{
return _performanceCounters;
}
}
protected internal DbReferenceCollection ReferenceCollection
{
get
{
return _referenceCollection;
}
}
abstract public string ServerVersion
{
get;
}
public bool ShouldHidePassword
{
get
{
return _hidePassword;
}
}
public ConnectionState State
{
get
{
return _state;
}
}
abstract protected void Activate(SysTx.Transaction transaction);
internal void AddWeakReference(object value, int tag)
{
if (null == _referenceCollection)
{
_referenceCollection = CreateReferenceCollection();
if (null == _referenceCollection)
{
throw ADP.InternalError(ADP.InternalErrorCode.CreateReferenceCollectionReturnedNull);
}
}
_referenceCollection.Add(value, tag);
}
abstract public DbTransaction BeginTransaction(IsolationLevel il);
virtual internal void PrepareForReplaceConnection()
{
// By default, there is no preperation required
}
virtual protected void PrepareForCloseConnection()
{
// By default, there is no preperation required
}
virtual protected object ObtainAdditionalLocksForClose()
{
return null; // no additional locks in default implementation
}
virtual protected void ReleaseAdditionalLocksForClose(object lockToken)
{
// no additional locks in default implementation
}
virtual protected DbReferenceCollection CreateReferenceCollection()
{
throw ADP.InternalError(ADP.InternalErrorCode.AttemptingToConstructReferenceCollectionOnStaticObject);
}
abstract protected void Deactivate();
internal void DeactivateConnection()
{
// Internal method called from the connection pooler so we don't expose
// the Deactivate method publicly.
#if DEBUG
int activateCount = Interlocked.Decrement(ref _activateCount);
Debug.Assert(0 == activateCount, "activated multiple times?");
#endif // DEBUG
if (PerformanceCounters != null)
{ // Pool.Clear will DestroyObject that will clean performanceCounters before going here
PerformanceCounters.NumberOfActiveConnections.Decrement();
}
if (!_connectionIsDoomed && Pool.UseLoadBalancing)
{
// If we're not already doomed, check the connection's lifetime and
// doom it if it's lifetime has elapsed.
DateTime now = DateTime.UtcNow;
if ((now.Ticks - _createTime.Ticks) > Pool.LoadBalanceTimeout.Ticks)
{
DoNotPoolThisConnection();
}
}
Deactivate();
}
virtual internal void DelegatedTransactionEnded()
{
// Called by System.Transactions when the delegated transaction has
// completed. We need to make closed connections that are in stasis
// available again, or disposed closed/leaked non-pooled connections.
// IMPORTANT NOTE: You must have taken a lock on the object before
// you call this method to prevent race conditions with Clear and
// ReclaimEmancipatedObjects.
if (1 == _pooledCount)
{
// When _pooledCount is 1, it indicates a closed, pooled,
// connection so it is ready to put back into the pool for
// general use.
TerminateStasis(true);
Deactivate(); // call it one more time just in case
DbConnectionPool pool = Pool;
if (null == pool)
{
throw ADP.InternalError(ADP.InternalErrorCode.PooledObjectWithoutPool); // pooled connection does not have a pool
}
pool.PutObjectFromTransactedPool(this);
}
else if (-1 == _pooledCount && !_owningObject.IsAlive)
{
// When _pooledCount is -1 and the owning object no longer exists,
// it indicates a closed (or leaked), non-pooled connection so
// it is safe to dispose.
TerminateStasis(false);
Deactivate(); // call it one more time just in case
// it's a non-pooled connection, we need to dispose of it
// once and for all, or the server will have fits about us
// leaving connections open until the client-side GC kicks
// in.
PerformanceCounters.NumberOfNonPooledConnections.Decrement();
Dispose();
}
// When _pooledCount is 0, the connection is a pooled connection
// that is either open (if the owning object is alive) or leaked (if
// the owning object is not alive) In either case, we can't muck
// with the connection here.
}
protected internal void DoNotPoolThisConnection()
{
_cannotBePooled = true;
}
/// <devdoc>Ensure that this connection cannot be put back into the pool.</devdoc>
protected internal void DoomThisConnection()
{
_connectionIsDoomed = true;
}
abstract public void EnlistTransaction(SysTx.Transaction transaction);
virtual protected internal DataTable GetSchema(DbConnectionFactory factory, DbConnectionPoolGroup poolGroup, DbConnection outerConnection, string collectionName, string[] restrictions)
{
Debug.Assert(outerConnection != null, "outerConnection may not be null.");
DbMetaDataFactory metaDataFactory = factory.GetMetaDataFactory(poolGroup, this);
Debug.Assert(metaDataFactory != null, "metaDataFactory may not be null.");
return metaDataFactory.GetSchema(outerConnection, collectionName, restrictions);
}
internal void MakeNonPooledObject(object owningObject, DbConnectionPoolCounters performanceCounters)
{
// Used by DbConnectionFactory to indicate that this object IS NOT part of
// a connection pool.
_connectionPool = null;
_performanceCounters = performanceCounters;
_owningObject.Target = owningObject;
_pooledCount = -1;
}
internal void MakePooledConnection(DbConnectionPool connectionPool)
{
// Used by DbConnectionFactory to indicate that this object IS part of
// a connection pool.
// TODO: consider using ADP.TimerCurrent() for this.
_createTime = DateTime.UtcNow;
_connectionPool = connectionPool;
_performanceCounters = connectionPool.PerformanceCounters;
}
internal void NotifyWeakReference(int message)
{
DbReferenceCollection referenceCollection = ReferenceCollection;
if (null != referenceCollection)
{
referenceCollection.Notify(message);
}
}
internal virtual void OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
{
if (!TryOpenConnection(outerConnection, connectionFactory, null, null))
{
throw ADP.InternalError(ADP.InternalErrorCode.SynchronousConnectReturnedPending);
}
}
/// <devdoc>The default implementation is for the open connection objects, and
/// it simply throws. Our private closed-state connection objects
/// override this and do the correct thing.</devdoc>
// User code should either override DbConnectionInternal.Activate when it comes out of the pool
// or override DbConnectionFactory.CreateConnection when the connection is created for non-pooled connections
internal virtual bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions)
{
throw ADP.ConnectionAlreadyOpen(State);
}
protected bool TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions)
{
// ?->Connecting: prevent set_ConnectionString during Open
if (connectionFactory.SetInnerConnectionFrom(outerConnection, DbConnectionClosedConnecting.SingletonInstance, this))
{
DbConnectionInternal openConnection = null;
try
{
connectionFactory.PermissionDemand(outerConnection);
if (!connectionFactory.TryGetConnection(outerConnection, retry, userOptions, this, out openConnection))
{
return false;
}
}
catch
{
// This should occure for all exceptions, even ADP.UnCatchableExceptions.
connectionFactory.SetInnerConnectionTo(outerConnection, this);
throw;
}
if (null == openConnection)
{
connectionFactory.SetInnerConnectionTo(outerConnection, this);
throw ADP.InternalConnectionError(ADP.ConnectionError.GetConnectionReturnsNull);
}
connectionFactory.SetInnerConnectionEvent(outerConnection, openConnection);
}
return true;
}
internal void PrePush(object expectedOwner)
{
// Called by DbConnectionPool when we're about to be put into it's pool, we
// take this opportunity to ensure ownership and pool counts are legit.
// IMPORTANT NOTE: You must have taken a lock on the object before
// you call this method to prevent race conditions with Clear and
// ReclaimEmancipatedObjects.
//3 // The following tests are retail assertions of things we can't allow to happen.
if (null == expectedOwner)
{
if (null != _owningObject.Target)
{
throw ADP.InternalError(ADP.InternalErrorCode.UnpooledObjectHasOwner); // new unpooled object has an owner
}
}
else if (_owningObject.Target != expectedOwner)
{
throw ADP.InternalError(ADP.InternalErrorCode.UnpooledObjectHasWrongOwner); // unpooled object has incorrect owner
}
if (0 != _pooledCount)
{
throw ADP.InternalError(ADP.InternalErrorCode.PushingObjectSecondTime); // pushing object onto stack a second time
}
_pooledCount++;
_owningObject.Target = null; // NOTE: doing this and checking for InternalError.PooledObjectHasOwner degrades the close by 2%
}
internal void PostPop(object newOwner)
{
// Called by DbConnectionPool right after it pulls this from it's pool, we
// take this opportunity to ensure ownership and pool counts are legit.
Debug.Assert(!IsEmancipated, "pooled object not in pool");
// When another thread is clearing this pool, it
// will doom all connections in this pool without prejudice which
// causes the following assert to fire, which really mucks up stress
// against checked bits. The assert is benign, so we're commenting
// it out.
//Debug.Assert(CanBePooled, "pooled object is not poolable");
// IMPORTANT NOTE: You must have taken a lock on the object before
// you call this method to prevent race conditions with Clear and
// ReclaimEmancipatedObjects.
if (null != _owningObject.Target)
{
throw ADP.InternalError(ADP.InternalErrorCode.PooledObjectHasOwner); // pooled connection already has an owner!
}
_owningObject.Target = newOwner;
_pooledCount--;
//3 // The following tests are retail assertions of things we can't allow to happen.
if (null != Pool)
{
if (0 != _pooledCount)
{
throw ADP.InternalError(ADP.InternalErrorCode.PooledObjectInPoolMoreThanOnce); // popping object off stack with multiple pooledCount
}
}
else if (-1 != _pooledCount)
{
throw ADP.InternalError(ADP.InternalErrorCode.NonPooledObjectUsedMoreThanOnce); // popping object off stack with multiple pooledCount
}
}
internal void RemoveWeakReference(object value)
{
DbReferenceCollection referenceCollection = ReferenceCollection;
if (null != referenceCollection)
{
referenceCollection.Remove(value);
}
}
internal void DetachCurrentTransactionIfEnded()
{
SysTx.Transaction enlistedTransaction = EnlistedTransaction;
if (enlistedTransaction != null)
{
bool transactionIsDead;
try
{
transactionIsDead = (SysTx.TransactionStatus.Active != enlistedTransaction.TransactionInformation.Status);
}
catch (SysTx.TransactionException)
{
// If the transaction is being processed (i.e. is part way through a rollback\commit\etc then TransactionInformation.Status will throw an exception)
transactionIsDead = true;
}
if (transactionIsDead)
{
DetachTransaction(enlistedTransaction, true);
}
}
}
// Detach transaction from connection.
internal void DetachTransaction(SysTx.Transaction transaction, bool isExplicitlyReleasing)
{
// potentially a multi-threaded event, so lock the connection to make sure we don't enlist in a new
// transaction between compare and assignment. No need to short circuit outside of lock, since failed comparisons should
// be the exception, not the rule.
lock (this)
{
// Detach if detach-on-end behavior, or if outer connection was closed
DbConnection owner = (DbConnection)Owner;
if (isExplicitlyReleasing || UnbindOnTransactionCompletion || null == owner)
{
SysTx.Transaction currentEnlistedTransaction = _enlistedTransaction;
if (currentEnlistedTransaction != null && transaction.Equals(currentEnlistedTransaction))
{
EnlistedTransaction = null;
if (IsTxRootWaitingForTxEnd)
{
DelegatedTransactionEnded();
}
}
}
}
}
internal void SetInStasis()
{
_isInStasis = true;
PerformanceCounters.NumberOfStasisConnections.Increment();
}
private void TerminateStasis(bool returningToPool)
{
PerformanceCounters.NumberOfStasisConnections.Decrement();
_isInStasis = false;
}
/// <summary>
/// When overridden in a derived class, will check if the underlying connection is still actually alive
/// </summary>
/// <param name="throwOnException">If true an exception will be thrown if the connection is dead instead of returning true\false
/// (this allows the caller to have the real reason that the connection is not alive (e.g. network error, etc))</param>
/// <returns>True if the connection is still alive, otherwise false (If not overridden, then always true)</returns>
internal virtual bool IsConnectionAlive(bool throwOnException = false)
{
return true;
}
}
}
| |
/* Copyright (c) 2013, HotDocs Limited
Use, modification and redistribution of this source is subject
to the New BSD License as set out in LICENSE.TXT. */
using System;
using System.IO;
using HotDocs.Sdk.Server.Contracts;
namespace SamplePortal
{
/// <summary>
/// Global utility functions (all static methods). No need to create an instance of Util.
/// </summary>
public static class Util
{
/// <summary>
/// Takes any positive integer (up to 64-bit) and returns a string representing that number int base n (max base == 37).
/// </summary>
/// <param name="num">Number to convert to a string.</param>
/// <param name="baseN">Base to convert to.</param>
/// <returns></returns>
public static string ConvertNumToBase(ulong num, byte baseN)
{
const string alldigits = "0123456789abcdefghijklmnopqrstuvwxyz_";
if (num == 0)
return "";
return ConvertNumToBase(num / baseN, baseN) + alldigits[unchecked((int)(num % baseN))];
}
/// <summary>
/// Create a temporary file name.
/// </summary>
/// <param name="ext">The extension for the temporary file name.</param>
/// <returns></returns>
public static string MakeTempFilename(string ext)
{
string fullExt = ext[0] == '.' ? ext : "." + ext;
return Path.GetRandomFileName() + fullExt;
}
/// <summary>
/// Delete a folder. This method does some validation on the folder name.
/// </summary>
/// <param name="folder">The path of the folder to delete.</param>
public static void SafeDeleteFolder(string folder)
{
if (folder != null && folder != "" && folder[0] != '\\')
System.IO.Directory.Delete(folder, true);
}
/// <summary>
/// Save an answer collection. Also save its title and description.
/// </summary>
/// <param name="ansColl">The answer collection to save.</param>
/// <param name="newTitle">The answer collection title to save.</param>
/// <param name="newDescription">The answer collection description to save.</param>
public static void SaveAnswers(HotDocs.Sdk.AnswerCollection ansColl, string newTitle, string newDescription)
{
string answerPath = ansColl.FilePath;
string answerFileName = Path.GetFileName(answerPath);
using (SamplePortal.Data.Answers answers = new SamplePortal.Data.Answers())
{
if (!String.IsNullOrEmpty(ansColl.FilePath))//If this assembly began with an answer file on the server
{
System.Data.DataView ansData = answers.SelectFile(answerFileName);
if (ansData.Count > 0 && ansData[0]["Title"].ToString() == newTitle)//If the title did not change
{
//Update the existing entry.
ansColl.WriteFile(false);
answers.UpdateAnswerFile(answerFileName, newTitle, newDescription);
}
else
{
//Create a new entry and answer set.
string newfname = Util.MakeTempFilename(".anx");
ansColl.WriteFile(Path.Combine(Settings.AnswerPath, newfname), false);
answers.InsertNewAnswerFile(newfname, newTitle, newDescription);
}
}
else//If this assembly began with a new or uploaded answer file
{
//Create a new answer file.
string newfname = Util.MakeTempFilename(".anx");
ansColl.WriteFile(Path.Combine(Util.SafeDir(Settings.AnswerPath), newfname), false);
//Create a new entry.
answers.InsertNewAnswerFile(newfname, newTitle, newDescription);
}
}
}
/// <summary>
/// Clean up old files.
/// </summary>
public static void SweepTempDirectories()
{
SweepDirectory(Settings.DocPath, 60);
SweepDirectory(Settings.TempPath, 60);
}
/// <summary>
/// Delete old files.
/// This goes through every file in the named directory, and attempts to
/// delete all files that were created more than timeoutMinutes ago.
/// USE WITH CARE! THIS CAN DELETE ANY FILE THE USER HAS RIGHTS TO!
/// </summary>
/// <param name="dirName">The path to the folder that will be swept.</param>
/// <param name="timeoutMinutes">The minimum number of minutes that must pass since a file was created before it can be deleted during a sweep.</param>
public static void SweepDirectory(string dirName, int timeoutMinutes)
{
DirectoryInfo dInfo = new DirectoryInfo(dirName);
if (dInfo.Exists)
{
FileInfo[] fInfos = dInfo.GetFiles();
foreach (FileInfo fInfo in fInfos)
{
if (fInfo.CreationTime.AddMinutes(timeoutMinutes) < DateTime.Now)
fInfo.Delete();
}
DirectoryInfo[] subDirInfoList = dInfo.GetDirectories();
foreach (DirectoryInfo subDirInfo in subDirInfoList)
{
if (subDirInfo.CreationTime.AddMinutes(timeoutMinutes) < DateTime.Now)
subDirInfo.Delete(true);
}
}
}
/// <summary>
/// Update a data grid's column headers to reflect the current sort which may change if newSort is not null.
/// </summary>
/// <param name="grid">The grid control.</param>
/// <param name="newSort">The new sort string: column_name[ DESC]. The sort is only changed if newSort is not null.</param>
/// <param name="currentSort">The current sort string: column_name[ DESC]</param>
/// <returns></returns>
public static string ToggleSortOrder(System.Web.UI.WebControls.DataGrid grid, string newSort, string currentSort)
{
if (newSort != null)
{
//Update currentSort. Toggle the sort or sort by a new column as per newSort.
if (newSort == currentSort && !currentSort.EndsWith(" DESC"))
currentSort += " DESC";
else
currentSort = newSort;
}
//Update the column headers to reflect the new current sort by updating the triangle hint.
string sortPrefix = currentSort;
if (sortPrefix.EndsWith(" DESC"))
sortPrefix = sortPrefix.Substring(0, sortPrefix.Length - 5);
for (int i = 0; i < grid.Columns.Count; i++)
{
//strip the existing <span> tag if there is one
int tagIndex = grid.Columns[i].HeaderText.IndexOf("<span");
if (tagIndex > 0)
grid.Columns[i].HeaderText = grid.Columns[i].HeaderText.Substring(0, tagIndex - 1);
//add the character to the column that's being sorted
if (grid.Columns[i].SortExpression == sortPrefix)
{
string letter = "▾";
if (currentSort.EndsWith("DESC"))
letter = "▴";
grid.Columns[i].HeaderText += " <span>" + letter + "</span>";
}
}
return currentSort;
}
/// <summary>
/// Respond to a <c>DataGrid.ItemCreated</c> event where <c>DataGridItemEventArgs.Item.ItemType == ListItemType.Pager</c>.
/// </summary>
/// <param name="e">Event DataGridItemEventArgs.</param>
public static void CustomizePager(System.Web.UI.WebControls.DataGridItemEventArgs e)
{
System.Web.UI.WebControls.TableCell pager = (System.Web.UI.WebControls.TableCell)e.Item.Controls[0];
for (int i = 0; i < pager.Controls.Count; i++)
{
if (pager.Controls[i].ToString() == "System.Web.UI.WebControls.Label")
{
System.Web.UI.WebControls.Label lbl = (System.Web.UI.WebControls.Label)pager.Controls[i];
lbl.Text = "Page " + lbl.Text;
}
else if (pager.Controls[i].ToString() == "System.Web.UI.LiteralControl")
{
System.Web.UI.LiteralControl lit = (System.Web.UI.LiteralControl)pager.Controls[i];
lit.Text = " | ";
}
else
{
System.Web.UI.WebControls.LinkButton lnk = (System.Web.UI.WebControls.LinkButton)pager.Controls[i];
lnk.Text = "Page " + lnk.Text;
}
}
}
/// <summary>
/// Set the page size of the data grid control, updating the current page index as needed.
/// </summary>
/// <param name="dataGrid">The data grid control.</param>
/// <param name="pageSize">The new page size.</param>
/// <param name="recordCount">The new number of records.</param>
public static void SetNewPageSize(System.Web.UI.WebControls.DataGrid dataGrid, int pageSize, int recordCount)
{
if (pageSize < 1)
throw new ArgumentOutOfRangeException("The grid size must be greater than zero.");
dataGrid.PageSize = pageSize;
if (dataGrid.CurrentPageIndex > recordCount / pageSize)
dataGrid.CurrentPageIndex = recordCount / pageSize;
}
/// <summary>
/// Returns a string identifying the browser.
/// </summary>
/// <param name="request">An HttpRequest that will be used to determine the name of the browser that made the request.</param>
/// <returns>The name of the browser.</returns>
public static string GetBrowserName(System.Web.HttpRequest request)
{
//Determine what browser is being used
string browserName = "unknown";
if (request.Browser.IsBrowser("IE"))
browserName = "IE";
else if (request.Browser.IsBrowser("Safari"))
{
if (request.UserAgent.Contains("Chrome"))
browserName = "chrome";
else
browserName = "safari";
}
else if (request.Browser.IsBrowser("Opera"))
browserName = "opera";
else if (request.Browser.Browser.Contains("Firefox"))
browserName = "firefox";
return browserName;
}
/// <summary>
/// Returns non-zero if the browser supports HTML with inline images.
/// </summary>
/// <param name="req">An HttpRequest that will be used to determine whether or not the user's browser supports inline images.</param>
/// <returns></returns>
public static bool BrowserSupportsInlineImages(System.Web.HttpRequest req)
{
string inlineImages = req.Form["InlineImages"];
bool supportsInlineImages;
if (inlineImages != null)
supportsInlineImages = (inlineImages.ToLowerInvariant() == "true");
else
{
int version;
supportsInlineImages = !IsIE(req, out version) || version >= 9; // IE9 supports up to 4GB in a data uri (http://msdn.microsoft.com/en-us/ie/ff468705.aspx#_DataURI)
}
return supportsInlineImages;
}
/// <summary>
/// Returns non-zero if the browser is IE.
/// </summary>
/// <param name="req">The browser request.</param>
/// <param name="version">Returns the IE version number if it's IE. Otherwise undefined.</param>
/// <returns>Indicates whether or not the browser is Internet Explorer (IE).</returns>
public static bool IsIE(System.Web.HttpRequest req, out int version)
{
version = -1;
string browser = req.Browser.Browser.ToUpper();
if (!browser.Contains("IE"))
return false;
string type = req.Browser.Type.ToUpper();
if (string.Compare(type, 0, "IE", 0, 2) != 0)
return false;
string numStr = type.Substring(2, type.Length - 2);
try
{
version = int.Parse(numStr);
}
catch
{
//If the IE string is unexpected, we'll assume it's new. This may need updating with newer browsers.
version = 100;//Some number greater than the current version.
return true;
}
return true;
}
/// <summary>
/// Wrap a directory path in this call in order to make sure that the directory exists. (It will create the directory if it does not yet exist.)
/// </summary>
/// <param name="dirPath">The path of the folder</param>
/// <returns>The same folder path specified in the dirPath parameter.</returns>
public static string SafeDir(string dirPath)
{
Directory.CreateDirectory(dirPath);
return dirPath;
}
#region Debugging aids
/// <summary>
/// Some debugging functionality that some might find useful.
/// </summary>
public static void debugger()
{
if (System.Diagnostics.Debugger.IsAttached)
System.Diagnostics.Debugger.Break();
else
System.Diagnostics.Debugger.Launch();
}
#endregion
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using StructureMap;
namespace Sep.Git.Tfs.Core
{
public class GitHelpers : IGitHelpers
{
private readonly TextWriter realStdout;
public GitHelpers(TextWriter stdout)
{
realStdout = stdout;
}
/// <summary>
/// Runs the given git command, and returns the contents of its STDOUT.
/// </summary>
public string Command(params string[] command)
{
string retVal = null;
CommandOutputPipe(stdout => retVal = stdout.ReadToEnd(), command);
return retVal;
}
/// <summary>
/// Runs the given git command, and returns the first line of its STDOUT.
/// </summary>
public string CommandOneline(params string[] command)
{
string retVal = null;
CommandOutputPipe(stdout => retVal = stdout.ReadLine(), command);
return retVal;
}
/// <summary>
/// Runs the given git command, and passes STDOUT through to the current process's STDOUT.
/// </summary>
public void CommandNoisy(params string[] command)
{
CommandOutputPipe(stdout => realStdout.Write(stdout.ReadToEnd()), command);
}
/// <summary>
/// Runs the given git command, and redirects STDOUT to the provided action.
/// </summary>
public void CommandOutputPipe(Action<TextReader> handleOutput, params string[] command)
{
Time(command, () =>
{
AssertValidCommand(command);
var process = Start(command, RedirectStdout);
handleOutput(process.StandardOutput);
Close(process);
});
}
/// <summary>
/// Runs the given git command, and returns a reader for STDOUT. NOTE: The returned value MUST be disposed!
/// </summary>
public TextReader CommandOutputPipe(params string[] command)
{
AssertValidCommand(command);
var process = Start(command, RedirectStdout);
return new ProcessStdoutReader(this, process);
}
public class ProcessStdoutReader : TextReader
{
private readonly Process process;
private readonly GitHelpers helper;
public ProcessStdoutReader(GitHelpers helper, Process process)
{
this.helper = helper;
this.process = process;
}
public override void Close()
{
process.StandardOutput.Close();
helper.Close(process);
}
public override System.Runtime.Remoting.ObjRef CreateObjRef(Type requestedType)
{
return process.StandardOutput.CreateObjRef(requestedType);
}
protected override void Dispose(bool disposing)
{
if(disposing && process != null)
{
Close();
}
base.Dispose(disposing);
}
public override bool Equals(object obj)
{
return process.StandardOutput.Equals(obj);
}
public override int GetHashCode()
{
return process.StandardOutput.GetHashCode();
}
public override object InitializeLifetimeService()
{
return process.StandardOutput.InitializeLifetimeService();
}
public override int Peek()
{
return process.StandardOutput.Peek();
}
public override int Read()
{
return process.StandardOutput.Read();
}
public override int Read(char[] buffer, int index, int count)
{
return process.StandardOutput.Read(buffer, index, count);
}
public override int ReadBlock(char[] buffer, int index, int count)
{
return process.StandardOutput.ReadBlock(buffer, index, count);
}
public override string ReadLine()
{
return process.StandardOutput.ReadLine();
}
public override string ReadToEnd()
{
return process.StandardOutput.ReadToEnd();
}
public override string ToString()
{
return process.StandardOutput.ToString();
}
}
public void CommandInputPipe(Action<TextWriter> action, params string[] command)
{
Time(command, () =>
{
AssertValidCommand(command);
var process = Start(command, RedirectStdin);
action(process.StandardInput);
Close(process);
});
}
public void CommandInputOutputPipe(Action<TextWriter, TextReader> interact, params string[] command)
{
Time(command, () =>
{
AssertValidCommand(command);
var process = Start(command,
Ext.And<ProcessStartInfo>(RedirectStdin, RedirectStdout));
interact(process.StandardInput, process.StandardOutput);
Close(process);
});
}
private void Time(string[] command, Action action)
{
var start = DateTime.Now;
try
{
action();
}
finally
{
var end = DateTime.Now;
Trace.WriteLine(String.Format("[{0}] {1}", end - start, String.Join(" ", command)), "git command time");
}
}
private void Close(Process process)
{
if (!process.WaitForExit((int)TimeSpan.FromSeconds(10).TotalMilliseconds))
throw new GitCommandException("Command did not terminate.", process);
if(process.ExitCode != 0)
throw new GitCommandException("Command exited with error code.", process, process.ExitCode);
}
private void RedirectStdout(ProcessStartInfo startInfo)
{
startInfo.RedirectStandardOutput = true;
}
private void RedirectStdin(ProcessStartInfo startInfo)
{
startInfo.RedirectStandardInput = true;
}
private Process Start(string[] command)
{
return Start(command, x => {});
}
protected virtual Process Start(string [] command, Action<ProcessStartInfo> initialize)
{
var startInfo = new ProcessStartInfo();
startInfo.FileName = "git";
startInfo.SetArguments(command);
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardError = true;
initialize(startInfo);
Trace.WriteLine("Starting process: " + startInfo.FileName + " " + startInfo.Arguments, "git command");
var process = Process.Start(startInfo);
process.ErrorDataReceived += StdErrReceived;
process.BeginErrorReadLine();
return process;
}
private void StdErrReceived(object sender, DataReceivedEventArgs e)
{
if(e.Data != null && e.Data.Trim() != "")
{
Trace.WriteLine(e.Data.TrimEnd(), "git stderr");
}
}
/// <summary>
/// WrapGitCommandErrors the actions, and if there are any git exceptions, rethrow a new exception with the given message.
/// </summary>
/// <param name="exceptionMessage">A friendlier message to wrap the GitCommandException with. {0} is replaced with the command line and {1} is replaced with the exit code.</param>
/// <param name="action"></param>
public void WrapGitCommandErrors(string exceptionMessage, Action action)
{
try
{
action();
}
catch (GitCommandException e)
{
throw new Exception(String.Format(exceptionMessage, e.Process.StartInfo.FileName + " " + e.Process.StartInfo.Arguments, e.Process.ExitCode), e);
}
}
public IGitRepository MakeRepository(string dir)
{
return ObjectFactory
.With("gitDir").EqualTo(dir)
.GetInstance<IGitRepository>();
}
private static readonly Regex ValidCommandName = new Regex("^[a-z0-9A-Z_-]+$");
private static void AssertValidCommand(string[] command)
{
if(command.Length < 1 || !ValidCommandName.IsMatch(command[0]))
throw new Exception("bad command: " + (command.Length == 0 ? "" : command[0]));
}
}
}
| |
using System;
using Microsoft.Xna.Framework;
using System.Collections.Generic;
using System.Linq;
namespace MonoFlixel
{
/// <summary>
/// This is a simple path data container. Basically a list of points that
/// a <code>FlxObject</code> can follow. Also has code for drawing debug visuals.
/// <code>FlxTilemap.findPath()</code> returns a path object, but you can
/// also just make your own, using the <code>add()</code> functions below
/// or by creating your own array of points.
/// </summary>
public class FlxPath
{
/// <summary>
/// The list of <code>FlxPoint</code>s that make up the path data.
/// </summary>
public List<FlxPoint> Nodes { get; set; }
/// <summary>
/// Specify a debug display color for the path. Default is white.
/// </summary>
public Color DebugColor { get; set; }
/// <summary>
/// Specify a debug display scroll factor for the path. Default is (1,1).
/// NOTE: does not affect world movement! Object scroll factors take care of that.
/// </summary>
public FlxPoint DebugScrollFactor { get; set; }
/// <summary>
/// Setting this to true will prevent the object from appearing
/// when the visual debug mode in the debugger overlay is toggled on.
/// @default false
/// </summary>
public bool IgnoreDrawDebug { get; set; }
protected FlxPoint _point;
/// <summary>
/// Instantiate a new path object.
/// </summary>
/// <param name="nodes">Optional, can specify all the points for the path up front if you want.</param>
public FlxPath(IEnumerable<FlxPoint> nodes = null)
{
Nodes = (nodes == null) ? new List<FlxPoint>() : nodes.ToList();
_point = new FlxPoint();
DebugColor = Color.White;
DebugScrollFactor = new FlxPoint(1, 1);
IgnoreDrawDebug = false;
// @TODO
/*
var debugPathDisplay:DebugPathDisplay = manager;
if(debugPathDisplay != null)
debugPathDisplay.add(this);
*/
}
public void destroy()
{
DebugScrollFactor = null;
_point = null;
Nodes = null;
}
/// <summary>
/// Add a new node to the end of the path at the specified location.
/// </summary>
/// <param name="x">X position of the new path point in world coordinates.</param>
/// <param name="y">Y position of the new path point in world coordinates.</param>
public void Add(float x, float y)
{
Nodes.Add(new FlxPoint(x, y));
}
/// <summary>
/// Add a new node to the path at the specified location and index within the path.
/// </summary>
/// <param name="x">X position of the new path point in world coordinates.</param>
/// <param name="y">Y position of the new path point in world coordinates.</param>
/// <param name="index">Where within the list of path nodes to insert this new point.</param>
public void AddAt(float x, float y, int index)
{
if (index > Nodes.Count)
{
index = Nodes.Count;
}
Nodes.Insert(index, new FlxPoint(x, y));
}
/// <summary>
/// Sometimes its easier or faster to just pass a point object instead of separate X and Y coordinates.
/// This also gives you the option of not creating a new node but actually adding that specific
/// <code>FlxPoint</code> object to the path. This allows you to do neat things, like dynamic paths.
/// </summary>
/// <param name="node">The point in world coordinates you want to add to the path.</param>
/// <param name="asReference">Whether to add the point as a reference, or to create a new point with the specified values.</param>
public void AddPoint(FlxPoint node, bool asReference = false)
{
Nodes.Add(asReference ? node : new FlxPoint(node.X, node.Y));
}
/// <summary>
/// Sometimes its easier or faster to just pass a point object instead of separate X and Y coordinates.
/// This also gives you the option of not creating a new node but actually adding that specific
/// <code>FlxPoint</code> object to the path. This allows you to do neat things, like dynamic paths.
/// </summary>
/// <param name="node">The point in world coordinates you want to add to the path.</param>
/// <param name="index">Where within the list of path nodes to insert this new point.</param>
/// <param name="asReference">Whether to add the point as a reference, or to create a new point with the specified values.</param>
public void AddPointAt(FlxPoint node, int index, bool asReference = false)
{
if (index > Nodes.Count)
{
index = Nodes.Count;
}
Nodes.Insert(index, asReference ? node : new FlxPoint(node.X, node.Y));
}
/// <summary>
/// Remove a node from the path.
/// NOTE: only works with points added by reference or with references from <code>nodes</code> itself!
/// </summary>
/// <param name="node">The point object you want to remove from the path.</param>
/// <returns>The node that was excised. Returns null if the node was not found.</returns>
public FlxPoint Remove(FlxPoint node)
{
if (Nodes.Remove(node))
{
return node;
}
return null;
}
/// <summary>
/// Remove a node from the path using the specified position in the list of path nodes.
/// </summary>
/// <param name="index">Where within the list of path nodes you want to remove a node.</param>
/// <returns>The node that was excised. Returns null if there were no nodes in the path.</returns>
public FlxPoint RemoveAt(int index)
{
if (!Nodes.Any())
{
return null;
}
// @TODO: if called with wrong arguments this should crash
/*
if (index >= Nodes.Count)
{
index = Nodes.Count - 1;
}
*/
FlxPoint removedNode = Nodes[index];
Nodes.RemoveAt(index);
return removedNode;
}
/// <summary>
/// Get the first node in the list.
/// </summary>
/// <returns>The first node in the path.</returns>
public FlxPoint Head()
{
return Nodes.First();
}
/// <summary>
/// Get the last node in the list.
/// </summary>
/// <returns>The last node in the path.</returns>
public FlxPoint Tail()
{
return Nodes.Last();
}
public object DebugPathManager
{
get
{
throw new NotImplementedException();
// return FlxG.getPlugin(DebugPathDisplay) as DebugPathDisplay;
}
}
/// <summary>
/// While this doesn't override <code>FlxBasic.DrawDebug()</code>, the behavior is very similar.
/// Based on this path data, it draws a simple lines-and-boxes representation of the path
/// if the visual debug mode was toggled in the debugger overlay. You can use <code>DebugColor</code>
/// and <code>DebugScrollFactor</code> to control the path's appearance.
/// </summary>
/// <param name="camera">The camera object the path will draw to.</param>
public void drawDebug(FlxCamera camera)
{
throw new NotImplementedException();
/*
if(nodes.length <= 0)
return;
if(Camera == null)
Camera = FlxG.camera;
//Set up our global flash graphics object to draw out the path
var gfx:Graphics = FlxG.flashGfx;
gfx.clear();
//Then fill up the object with node and path graphics
var node:FlxPoint;
var nextNode:FlxPoint;
var i:uint = 0;
var l:uint = nodes.length;
while(i < l)
{
//get a reference to the current node
node = nodes[i] as FlxPoint;
//find the screen position of the node on this camera
_point.x = node.x - int(Camera.scroll.x*debugScrollFactor.x); //copied from getScreenXY()
_point.y = node.y - int(Camera.scroll.y*debugScrollFactor.y);
_point.x = int(_point.x + ((_point.x > 0)?0.0000001:-0.0000001));
_point.y = int(_point.y + ((_point.y > 0)?0.0000001:-0.0000001));
//decide what color this node should be
var nodeSize:uint = 2;
if((i == 0) || (i == l-1))
nodeSize *= 2;
var nodeColor:uint = debugColor;
if(l > 1)
{
if(i == 0)
nodeColor = FlxG.GREEN;
else if(i == l-1)
nodeColor = FlxG.RED;
}
//draw a box for the node
gfx.beginFill(nodeColor,0.5);
gfx.lineStyle();
gfx.drawRect(_point.x-nodeSize*0.5,_point.y-nodeSize*0.5,nodeSize,nodeSize);
gfx.endFill();
//then find the next node in the path
var linealpha:Number = 0.3;
if(i < l-1)
nextNode = nodes[i+1];
else
{
nextNode = nodes[0];
linealpha = 0.15;
}
//then draw a line to the next node
gfx.moveTo(_point.x,_point.y);
gfx.lineStyle(1,debugColor,linealpha);
_point.x = nextNode.x - int(Camera.scroll.x*debugScrollFactor.x); //copied from getScreenXY()
_point.y = nextNode.y - int(Camera.scroll.y*debugScrollFactor.y);
_point.x = int(_point.x + ((_point.x > 0)?0.0000001:-0.0000001));
_point.y = int(_point.y + ((_point.y > 0)?0.0000001:-0.0000001));
gfx.lineTo(_point.x,_point.y);
i++;
}
//then stamp the path down onto the game buffer
Camera.buffer.draw(FlxG.flashGfxSprite);
*/
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using Hyak.Common;
using Microsoft.WindowsAzure.Management.RemoteApp.Models;
namespace Microsoft.WindowsAzure.Management.RemoteApp.Models
{
/// <summary>
/// The parameter for collection creation request.
/// </summary>
public partial class CollectionCreationDetails
{
private ActiveDirectoryConfig _adInfo;
/// <summary>
/// Optional. Active Directory configuration details.
/// </summary>
public ActiveDirectoryConfig AdInfo
{
get { return this._adInfo; }
set { this._adInfo = value; }
}
private IList<SecurityPrincipal> _allowedPrincipals;
/// <summary>
/// Optional. The initial list of users to give access to after
/// creation of the collection.
/// </summary>
public IList<SecurityPrincipal> AllowedPrincipals
{
get { return this._allowedPrincipals; }
set { this._allowedPrincipals = value; }
}
private string _customRdpProperty;
/// <summary>
/// Optional. Customer defined Remote Desktop Protocol (RDP) properties
/// of the collection.
/// </summary>
public string CustomRdpProperty
{
get { return this._customRdpProperty; }
set { this._customRdpProperty = value; }
}
private string _description;
/// <summary>
/// Optional. The description of the collection.
/// </summary>
public string Description
{
get { return this._description; }
set { this._description = value; }
}
private IList<string> _dnsServers;
/// <summary>
/// Optional. List of the DNS Servers.
/// </summary>
public IList<string> DnsServers
{
get { return this._dnsServers; }
set { this._dnsServers = value; }
}
private CollectionMode _mode;
/// <summary>
/// Optional. The collection mode.
/// </summary>
public CollectionMode Mode
{
get { return this._mode; }
set { this._mode = value; }
}
private string _name;
/// <summary>
/// Required. The collection name.
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
}
private string _planName;
/// <summary>
/// Required. The RemoteApp plan to use.
/// </summary>
public string PlanName
{
get { return this._planName; }
set { this._planName = value; }
}
private IList<PublishedApplicationDetails> _publishedApplications;
/// <summary>
/// Optional. The list of applications to be initially published after
/// creation of the collection.
/// </summary>
public IList<PublishedApplicationDetails> PublishedApplications
{
get { return this._publishedApplications; }
set { this._publishedApplications = value; }
}
private bool _readyForPublishing;
/// <summary>
/// Optional. A flag denoting if this collection is ready for
/// publishing operations.
/// </summary>
public bool ReadyForPublishing
{
get { return this._readyForPublishing; }
set { this._readyForPublishing = value; }
}
private string _region;
/// <summary>
/// Optional. The location of the collection (required for cloud-only
/// collections, optional for hybrid collections)
/// </summary>
public string Region
{
get { return this._region; }
set { this._region = value; }
}
private string _subnetName;
/// <summary>
/// Optional. The subnet name of the customer created Azure VNet.
/// </summary>
public string SubnetName
{
get { return this._subnetName; }
set { this._subnetName = value; }
}
private string _templateImageName;
/// <summary>
/// Optional. The name of the template image to be used to create this
/// collection.
/// </summary>
public string TemplateImageName
{
get { return this._templateImageName; }
set { this._templateImageName = value; }
}
private string _vNetName;
/// <summary>
/// Optional. The VNet name associated with this collection.
/// </summary>
public string VNetName
{
get { return this._vNetName; }
set { this._vNetName = value; }
}
/// <summary>
/// Initializes a new instance of the CollectionCreationDetails class.
/// </summary>
public CollectionCreationDetails()
{
this.AllowedPrincipals = new LazyList<SecurityPrincipal>();
this.DnsServers = new LazyList<string>();
this.PublishedApplications = new LazyList<PublishedApplicationDetails>();
}
/// <summary>
/// Initializes a new instance of the CollectionCreationDetails class
/// with required arguments.
/// </summary>
public CollectionCreationDetails(string name, string planName)
: this()
{
if (name == null)
{
throw new ArgumentNullException("name");
}
if (planName == null)
{
throw new ArgumentNullException("planName");
}
this.Name = name;
this.PlanName = planName;
}
}
}
| |
// 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.Threading.Tasks;
using Xunit;
namespace Microsoft.AspNetCore.Components
{
public class EventCallbackFactoryTest
{
[Fact]
public void Create_EventCallback_ReturnsInput()
{
// Arrange
var component = new EventComponent();
var @delegate = (Action)component.SomeAction;
var input = new EventCallback(component, @delegate);
var anotherComponent = new EventComponent();
// Act
var callback = EventCallback.Factory.Create(anotherComponent, input);
// Assert
Assert.Same(@delegate, callback.Delegate);
Assert.Same(component, callback.Receiver);
Assert.False(callback.RequiresExplicitReceiver);
}
[Fact]
public void Create_Action_AlreadyBoundToReceiver()
{
// Arrange
var component = new EventComponent();
var @delegate = (Action)component.SomeAction;
// Act
var callback = EventCallback.Factory.Create(component, @delegate);
// Assert
Assert.Same(@delegate, callback.Delegate);
Assert.Same(component, callback.Receiver);
Assert.False(callback.RequiresExplicitReceiver);
}
[Fact]
public void Create_Action_DifferentReceiver()
{
// Arrange
var component = new EventComponent();
var @delegate = (Action)component.SomeAction;
var anotherComponent = new EventComponent();
// Act
var callback = EventCallback.Factory.Create(anotherComponent, @delegate);
// Assert
Assert.Same(@delegate, callback.Delegate);
Assert.Same(component, callback.Receiver);
Assert.False(callback.RequiresExplicitReceiver);
}
[Fact]
public void Create_Action_Unbound()
{
// Arrange
var component = new EventComponent();
var @delegate = (Action)(() => { });
var anotherComponent = new EventComponent();
// Act
var callback = EventCallback.Factory.Create(anotherComponent, @delegate);
// Assert
Assert.Same(@delegate, callback.Delegate);
Assert.Same(anotherComponent, callback.Receiver);
Assert.True(callback.RequiresExplicitReceiver);
}
[Fact]
public void Create_Action_Null()
{
// Arrange
var component = new EventComponent();
// Act
var callback = EventCallback.Factory.Create(component, (Action)null);
// Assert
Assert.Null(callback.Delegate);
Assert.Same(component, callback.Receiver);
Assert.True(callback.RequiresExplicitReceiver);
}
[Fact]
public void Create_ActionT_AlreadyBoundToReceiver()
{
// Arrange
var component = new EventComponent();
var @delegate = (Action<string>)component.SomeActionOfT;
// Act
var callback = EventCallback.Factory.Create(component, @delegate);
// Assert
Assert.Same(@delegate, callback.Delegate);
Assert.Same(component, callback.Receiver);
Assert.False(callback.RequiresExplicitReceiver);
}
[Fact]
public void Create_ActionT_DifferentReceiver()
{
// Arrange
var component = new EventComponent();
var @delegate = (Action<string>)component.SomeActionOfT;
var anotherComponent = new EventComponent();
// Act
var callback = EventCallback.Factory.Create(anotherComponent, @delegate);
// Assert
Assert.Same(@delegate, callback.Delegate);
Assert.Same(component, callback.Receiver);
Assert.False(callback.RequiresExplicitReceiver);
}
[Fact]
public void Create_ActionT_Unbound()
{
// Arrange
var component = new EventComponent();
var @delegate = (Action<string>)((s) => { });
var anotherComponent = new EventComponent();
// Act
var callback = EventCallback.Factory.Create(anotherComponent, @delegate);
// Assert
Assert.Same(@delegate, callback.Delegate);
Assert.Same(anotherComponent, callback.Receiver);
Assert.True(callback.RequiresExplicitReceiver);
}
[Fact]
public void Create_ActionT_Null()
{
// Arrange
var component = new EventComponent();
// Act
var callback = EventCallback.Factory.Create(component, (Action<string>)null);
// Assert
Assert.Null(callback.Delegate);
Assert.Same(component, callback.Receiver);
Assert.True(callback.RequiresExplicitReceiver);
}
[Fact]
public void Create_FuncTask_AlreadyBoundToReceiver()
{
// Arrange
var component = new EventComponent();
var @delegate = (Func<Task>)component.SomeFuncTask;
// Act
var callback = EventCallback.Factory.Create(component, @delegate);
// Assert
Assert.Same(@delegate, callback.Delegate);
Assert.Same(component, callback.Receiver);
Assert.False(callback.RequiresExplicitReceiver);
}
[Fact]
public void Create_FuncTask_DifferentReceiver()
{
// Arrange
var component = new EventComponent();
var @delegate = (Func<Task>)component.SomeFuncTask;
var anotherComponent = new EventComponent();
// Act
var callback = EventCallback.Factory.Create(anotherComponent, @delegate);
// Assert
Assert.Same(@delegate, callback.Delegate);
Assert.Same(component, callback.Receiver);
Assert.False(callback.RequiresExplicitReceiver);
}
[Fact]
public void Create_FuncTask_Unbound()
{
// Arrange
var component = new EventComponent();
var @delegate = (Func<Task>)(() => Task.CompletedTask);
var anotherComponent = new EventComponent();
// Act
var callback = EventCallback.Factory.Create(anotherComponent, @delegate);
// Assert
Assert.Same(@delegate, callback.Delegate);
Assert.Same(anotherComponent, callback.Receiver);
Assert.True(callback.RequiresExplicitReceiver);
}
[Fact]
public void Create_FuncTTask_AlreadyBoundToReceiver()
{
// Arrange
var component = new EventComponent();
var @delegate = (Func<string, Task>)component.SomeFuncTTask;
// Act
var callback = EventCallback.Factory.Create(component, @delegate);
// Assert
Assert.Same(@delegate, callback.Delegate);
Assert.Same(component, callback.Receiver);
Assert.False(callback.RequiresExplicitReceiver);
}
[Fact]
public void Create_FuncTask_Null()
{
// Arrange
var component = new EventComponent();
// Act
var callback = EventCallback.Factory.Create(component, (Func<Task>)null);
// Assert
Assert.Null(callback.Delegate);
Assert.Same(component, callback.Receiver);
Assert.True(callback.RequiresExplicitReceiver);
}
[Fact]
public void Create_FuncTTask_DifferentReceiver()
{
// Arrange
var component = new EventComponent();
var @delegate = (Func<string, Task>)component.SomeFuncTTask;
var anotherComponent = new EventComponent();
// Act
var callback = EventCallback.Factory.Create(anotherComponent, @delegate);
// Assert
Assert.Same(@delegate, callback.Delegate);
Assert.Same(component, callback.Receiver);
Assert.False(callback.RequiresExplicitReceiver);
}
[Fact]
public void Create_FuncTTask_Unbound()
{
// Arrange
var component = new EventComponent();
var @delegate = (Func<string, Task>)((s) => Task.CompletedTask);
var anotherComponent = new EventComponent();
// Act
var callback = EventCallback.Factory.Create(anotherComponent, @delegate);
// Assert
Assert.Same(@delegate, callback.Delegate);
Assert.Same(anotherComponent, callback.Receiver);
Assert.True(callback.RequiresExplicitReceiver);
}
[Fact]
public void Create_FuncTTask_Null()
{
// Arrange
var component = new EventComponent();
// Act
var callback = EventCallback.Factory.Create(component, (Func<string, Task>)null);
// Assert
Assert.Null(callback.Delegate);
Assert.Same(component, callback.Receiver);
Assert.True(callback.RequiresExplicitReceiver);
}
[Fact]
public void CreateT_EventCallback_ReturnsInput()
{
// Arrange
var component = new EventComponent();
var @delegate = (Action)component.SomeAction;
var input = new EventCallback<string>(component, @delegate);
var anotherComponent = new EventComponent();
// Act
var callback = EventCallback.Factory.Create<string>(anotherComponent, input);
// Assert
Assert.Same(@delegate, callback.Delegate);
Assert.Same(component, callback.Receiver);
Assert.False(callback.RequiresExplicitReceiver);
}
[Fact]
public void CreateT_Action_AlreadyBoundToReceiver()
{
// Arrange
var component = new EventComponent();
var @delegate = (Action)component.SomeAction;
// Act
var callback = EventCallback.Factory.Create<string>(component, @delegate);
// Assert
Assert.Same(@delegate, callback.Delegate);
Assert.Same(component, callback.Receiver);
Assert.False(callback.RequiresExplicitReceiver);
}
[Fact]
public void CreateT_Action_DifferentReceiver()
{
// Arrange
var component = new EventComponent();
var @delegate = (Action)component.SomeAction;
var anotherComponent = new EventComponent();
// Act
var callback = EventCallback.Factory.Create<string>(anotherComponent, @delegate);
// Assert
Assert.Same(@delegate, callback.Delegate);
Assert.Same(component, callback.Receiver);
Assert.False(callback.RequiresExplicitReceiver);
}
[Fact]
public void CreateT_Action_Unbound()
{
// Arrange
var component = new EventComponent();
var @delegate = (Action)(() => { });
var anotherComponent = new EventComponent();
// Act
var callback = EventCallback.Factory.Create<string>(anotherComponent, @delegate);
// Assert
Assert.Same(@delegate, callback.Delegate);
Assert.Same(anotherComponent, callback.Receiver);
Assert.True(callback.RequiresExplicitReceiver);
}
[Fact]
public void CreateT_Action_Null()
{
// Arrange
var component = new EventComponent();
// Act
var callback = EventCallback.Factory.Create<string>(component, (Action)null);
// Assert
Assert.Null(callback.Delegate);
Assert.Same(component, callback.Receiver);
Assert.True(callback.RequiresExplicitReceiver);
}
[Fact]
public void CreateT_ActionT_AlreadyBoundToReceiver()
{
// Arrange
var component = new EventComponent();
var @delegate = (Action<string>)component.SomeActionOfT;
// Act
var callback = EventCallback.Factory.Create<string>(component, @delegate);
// Assert
Assert.Same(@delegate, callback.Delegate);
Assert.Same(component, callback.Receiver);
Assert.False(callback.RequiresExplicitReceiver);
}
[Fact]
public void CreateT_ActionT_DifferentReceiver()
{
// Arrange
var component = new EventComponent();
var @delegate = (Action<string>)component.SomeActionOfT;
var anotherComponent = new EventComponent();
// Act
var callback = EventCallback.Factory.Create<string>(anotherComponent, @delegate);
// Assert
Assert.Same(@delegate, callback.Delegate);
Assert.Same(component, callback.Receiver);
Assert.False(callback.RequiresExplicitReceiver);
}
[Fact]
public void CreateT_ActionT_Null()
{
// Arrange
var component = new EventComponent();
// Act
var callback = EventCallback.Factory.Create<string>(component, (Action<string>)null);
// Assert
Assert.Null(callback.Delegate);
Assert.Same(component, callback.Receiver);
Assert.True(callback.RequiresExplicitReceiver);
}
[Fact]
public void CreateT_ActionT_Unbound()
{
// Arrange
var component = new EventComponent();
var @delegate = (Action<string>)((s) => { });
var anotherComponent = new EventComponent();
// Act
var callback = EventCallback.Factory.Create<string>(anotherComponent, @delegate);
// Assert
Assert.Same(@delegate, callback.Delegate);
Assert.Same(anotherComponent, callback.Receiver);
Assert.True(callback.RequiresExplicitReceiver);
}
[Fact]
public void CreateT_FuncTask_AlreadyBoundToReceiver()
{
// Arrange
var component = new EventComponent();
var @delegate = (Func<Task>)component.SomeFuncTask;
// Act
var callback = EventCallback.Factory.Create<string>(component, @delegate);
// Assert
Assert.Same(@delegate, callback.Delegate);
Assert.Same(component, callback.Receiver);
Assert.False(callback.RequiresExplicitReceiver);
}
[Fact]
public void CreateT_FuncTask_DifferentReceiver()
{
// Arrange
var component = new EventComponent();
var @delegate = (Func<Task>)component.SomeFuncTask;
var anotherComponent = new EventComponent();
// Act
var callback = EventCallback.Factory.Create<string>(anotherComponent, @delegate);
// Assert
Assert.Same(@delegate, callback.Delegate);
Assert.Same(component, callback.Receiver);
Assert.False(callback.RequiresExplicitReceiver);
}
[Fact]
public void CreateT_FuncTask_Unbound()
{
// Arrange
var component = new EventComponent();
var @delegate = (Func<Task>)(() => Task.CompletedTask);
var anotherComponent = new EventComponent();
// Act
var callback = EventCallback.Factory.Create<string>(anotherComponent, @delegate);
// Assert
Assert.Same(@delegate, callback.Delegate);
Assert.Same(anotherComponent, callback.Receiver);
Assert.True(callback.RequiresExplicitReceiver);
}
[Fact]
public void CreateT_FuncTask_Null()
{
// Arrange
var component = new EventComponent();
// Act
var callback = EventCallback.Factory.Create<string>(component, (Func<Task>)null);
// Assert
Assert.Null(callback.Delegate);
Assert.Same(component, callback.Receiver);
Assert.True(callback.RequiresExplicitReceiver);
}
[Fact]
public void CreateT_FuncTTask_AlreadyBoundToReceiver()
{
// Arrange
var component = new EventComponent();
var @delegate = (Func<string, Task>)component.SomeFuncTTask;
// Act
var callback = EventCallback.Factory.Create<string>(component, @delegate);
// Assert
Assert.Same(@delegate, callback.Delegate);
Assert.Same(component, callback.Receiver);
Assert.False(callback.RequiresExplicitReceiver);
}
[Fact]
public void CreateT_FuncTTask_DifferentReceiver()
{
// Arrange
var component = new EventComponent();
var @delegate = (Func<string, Task>)component.SomeFuncTTask;
var anotherComponent = new EventComponent();
// Act
var callback = EventCallback.Factory.Create<string>(anotherComponent, @delegate);
// Assert
Assert.Same(@delegate, callback.Delegate);
Assert.Same(component, callback.Receiver);
Assert.False(callback.RequiresExplicitReceiver);
}
[Fact]
public void CreateT_FuncTTask_Unbound()
{
// Arrange
var component = new EventComponent();
var @delegate = (Func<string, Task>)((s) => Task.CompletedTask);
var anotherComponent = new EventComponent();
// Act
var callback = EventCallback.Factory.Create<string>(anotherComponent, @delegate);
// Assert
Assert.Same(@delegate, callback.Delegate);
Assert.Same(anotherComponent, callback.Receiver);
Assert.True(callback.RequiresExplicitReceiver);
}
[Fact]
public void CreateT_FuncTTask_Null()
{
// Arrange
var component = new EventComponent();
// Act
var callback = EventCallback.Factory.Create<string>(component, (Func<string, Task>)null);
// Assert
Assert.Null(callback.Delegate);
Assert.Same(component, callback.Receiver);
Assert.True(callback.RequiresExplicitReceiver);
}
[Fact]
public void CreateInferred_ActionT()
{
// Arrange
var component = new EventComponent();
var @delegate = (Action<string>)((s) => { });
// Act
var callback = EventCallback.Factory.CreateInferred<string>(component, @delegate, "hi");
// Assert
Assert.Same(@delegate, callback.Delegate);
Assert.Same(component, callback.Receiver);
Assert.True(callback.RequiresExplicitReceiver);
}
[Fact]
public void CreateInferred_FuncTTask()
{
// Arrange
var component = new EventComponent();
var @delegate = (Func<string, Task>)((s) => Task.CompletedTask);
// Act
var callback = EventCallback.Factory.CreateInferred<string>(component, @delegate, "hi");
// Assert
Assert.Same(@delegate, callback.Delegate);
Assert.Same(component, callback.Receiver);
Assert.True(callback.RequiresExplicitReceiver);
}
private class EventComponent : IComponent, IHandleEvent
{
public void SomeAction()
{
}
public void SomeActionOfT(string e)
{
}
public Task SomeFuncTask()
{
return Task.CompletedTask;
}
public Task SomeFuncTTask(string s)
{
return Task.CompletedTask;
}
public void Attach(RenderHandle renderHandle)
{
throw new NotImplementedException();
}
public Task HandleEventAsync(EventCallbackWorkItem item, object arg)
{
throw new NotImplementedException();
}
public Task SetParametersAsync(ParameterView parameters)
{
throw new NotImplementedException();
}
}
}
}
| |
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 Budgy.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Globalization;
using System.Threading;
namespace System.Transactions
{
internal interface IPromotedEnlistment
{
void EnlistmentDone();
void Prepared();
void ForceRollback();
void ForceRollback(Exception e);
void Committed();
void Aborted();
void Aborted(Exception e);
void InDoubt();
void InDoubt(Exception e);
byte[] GetRecoveryInformation();
InternalEnlistment InternalEnlistment
{
get;
set;
}
}
//
// InternalEnlistment by itself can support a Phase0 volatile enlistment.
// There are derived classes to support durable, phase1 volatile & PSPE
// enlistments.
//
internal class InternalEnlistment : ISinglePhaseNotificationInternal
{
// Storage for the state of the enlistment.
internal EnlistmentState _twoPhaseState;
// Interface implemented by the enlistment owner for notifications
protected IEnlistmentNotification _twoPhaseNotifications;
// Store a reference to the single phase notification interface in case
// the enlisment supports it.
protected ISinglePhaseNotification _singlePhaseNotifications;
// Reference to the containing transaction.
protected InternalTransaction _transaction;
// Reference to the lightweight transaction.
private Transaction _atomicTransaction;
// The EnlistmentTraceIdentifier for this enlistment.
private EnlistmentTraceIdentifier _traceIdentifier;
// Unique value amongst all enlistments for a given internal transaction.
private int _enlistmentId;
internal Guid DistributedTxId
{
get
{
Guid returnValue = Guid.Empty;
if (Transaction != null)
{
returnValue = Transaction.DistributedTxId;
}
return returnValue;
}
}
// Parent Enlistment Object
private Enlistment _enlistment;
private PreparingEnlistment _preparingEnlistment;
private SinglePhaseEnlistment _singlePhaseEnlistment;
// If this enlistment is promoted store the object it delegates to.
private IPromotedEnlistment _promotedEnlistment;
// For Recovering Enlistments
protected InternalEnlistment(Enlistment enlistment, IEnlistmentNotification twoPhaseNotifications)
{
Debug.Assert(this is RecoveringInternalEnlistment, "this is RecoveringInternalEnlistment");
_enlistment = enlistment;
_twoPhaseNotifications = twoPhaseNotifications;
_enlistmentId = 1;
_traceIdentifier = EnlistmentTraceIdentifier.Empty;
}
// For Promotable Enlistments
protected InternalEnlistment(Enlistment enlistment, InternalTransaction transaction, Transaction atomicTransaction)
{
Debug.Assert(this is PromotableInternalEnlistment, "this is PromotableInternalEnlistment");
_enlistment = enlistment;
_transaction = transaction;
_atomicTransaction = atomicTransaction;
_enlistmentId = transaction._enlistmentCount++;
_traceIdentifier = EnlistmentTraceIdentifier.Empty;
}
internal InternalEnlistment(
Enlistment enlistment,
InternalTransaction transaction,
IEnlistmentNotification twoPhaseNotifications,
ISinglePhaseNotification singlePhaseNotifications,
Transaction atomicTransaction)
{
_enlistment = enlistment;
_transaction = transaction;
_twoPhaseNotifications = twoPhaseNotifications;
_singlePhaseNotifications = singlePhaseNotifications;
_atomicTransaction = atomicTransaction;
_enlistmentId = transaction._enlistmentCount++;
_traceIdentifier = EnlistmentTraceIdentifier.Empty;
}
internal InternalEnlistment(
Enlistment enlistment,
IEnlistmentNotification twoPhaseNotifications,
InternalTransaction transaction,
Transaction atomicTransaction)
{
_enlistment = enlistment;
_twoPhaseNotifications = twoPhaseNotifications;
_transaction = transaction;
_atomicTransaction = atomicTransaction;
}
internal EnlistmentState State
{
get { return _twoPhaseState; }
set { _twoPhaseState = value; }
}
internal Enlistment Enlistment => _enlistment;
internal PreparingEnlistment PreparingEnlistment
{
get
{
if (_preparingEnlistment == null)
{
// If there is a race here one of the objects would simply be garbage collected.
_preparingEnlistment = new PreparingEnlistment(this);
}
return _preparingEnlistment;
}
}
internal SinglePhaseEnlistment SinglePhaseEnlistment
{
get
{
if (_singlePhaseEnlistment == null)
{
// If there is a race here one of the objects would simply be garbage collected.
_singlePhaseEnlistment = new SinglePhaseEnlistment(this);
}
return _singlePhaseEnlistment;
}
}
internal InternalTransaction Transaction => _transaction;
internal virtual object SyncRoot
{
get
{
Debug.Assert(_transaction != null, "this.transaction != null");
return _transaction;
}
}
internal IEnlistmentNotification EnlistmentNotification => _twoPhaseNotifications;
internal ISinglePhaseNotification SinglePhaseNotification => _singlePhaseNotifications;
internal virtual IPromotableSinglePhaseNotification PromotableSinglePhaseNotification
{
get
{
Debug.Fail("PromotableSinglePhaseNotification called for a non promotable enlistment.");
throw new NotImplementedException();
}
}
internal IPromotedEnlistment PromotedEnlistment
{
get { return _promotedEnlistment; }
set { _promotedEnlistment = value; }
}
internal EnlistmentTraceIdentifier EnlistmentTraceId
{
get
{
if (_traceIdentifier == EnlistmentTraceIdentifier.Empty)
{
lock (SyncRoot)
{
if (_traceIdentifier == EnlistmentTraceIdentifier.Empty)
{
EnlistmentTraceIdentifier temp;
if (null != _atomicTransaction)
{
temp = new EnlistmentTraceIdentifier(
Guid.Empty,
_atomicTransaction.TransactionTraceId,
_enlistmentId);
}
else
{
temp = new EnlistmentTraceIdentifier(
Guid.Empty,
new TransactionTraceIdentifier(
InternalTransaction.InstanceIdentifier +
Convert.ToString(Interlocked.Increment(ref InternalTransaction._nextHash), CultureInfo.InvariantCulture),
0),
_enlistmentId);
}
Interlocked.MemoryBarrier();
_traceIdentifier = temp;
}
}
}
return _traceIdentifier;
}
}
internal virtual void FinishEnlistment()
{
// Note another enlistment finished.
Transaction._phase0Volatiles._preparedVolatileEnlistments++;
CheckComplete();
}
internal virtual void CheckComplete()
{
// Make certain we increment the right list.
Debug.Assert(Transaction._phase0Volatiles._preparedVolatileEnlistments <=
Transaction._phase0Volatiles._volatileEnlistmentCount + Transaction._phase0Volatiles._dependentClones);
// Check to see if all of the volatile enlistments are done.
if (Transaction._phase0Volatiles._preparedVolatileEnlistments ==
Transaction._phase0VolatileWaveCount + Transaction._phase0Volatiles._dependentClones)
{
Transaction.State.Phase0VolatilePrepareDone(Transaction);
}
}
internal virtual Guid ResourceManagerIdentifier
{
get
{
Debug.Fail("ResourceManagerIdentifier called for non durable enlistment");
throw new NotImplementedException();
}
}
void ISinglePhaseNotificationInternal.SinglePhaseCommit(IPromotedEnlistment singlePhaseEnlistment)
{
bool spcCommitted = false;
_promotedEnlistment = singlePhaseEnlistment;
try
{
_singlePhaseNotifications.SinglePhaseCommit(SinglePhaseEnlistment);
spcCommitted = true;
}
finally
{
if (!spcCommitted)
{
SinglePhaseEnlistment.InDoubt();
}
}
}
void IEnlistmentNotificationInternal.Prepare(
IPromotedEnlistment preparingEnlistment
)
{
_promotedEnlistment = preparingEnlistment;
_twoPhaseNotifications.Prepare(PreparingEnlistment);
}
void IEnlistmentNotificationInternal.Commit(
IPromotedEnlistment enlistment
)
{
_promotedEnlistment = enlistment;
_twoPhaseNotifications.Commit(Enlistment);
}
void IEnlistmentNotificationInternal.Rollback(
IPromotedEnlistment enlistment
)
{
_promotedEnlistment = enlistment;
_twoPhaseNotifications.Rollback(Enlistment);
}
void IEnlistmentNotificationInternal.InDoubt(
IPromotedEnlistment enlistment
)
{
_promotedEnlistment = enlistment;
_twoPhaseNotifications.InDoubt(Enlistment);
}
}
internal class DurableInternalEnlistment : InternalEnlistment
{
// Resource Manager Identifier for this enlistment if it is durable
internal Guid _resourceManagerIdentifier;
internal DurableInternalEnlistment(
Enlistment enlistment,
Guid resourceManagerIdentifier,
InternalTransaction transaction,
IEnlistmentNotification twoPhaseNotifications,
ISinglePhaseNotification singlePhaseNotifications,
Transaction atomicTransaction) :
base(enlistment, transaction, twoPhaseNotifications, singlePhaseNotifications, atomicTransaction)
{
_resourceManagerIdentifier = resourceManagerIdentifier;
}
protected DurableInternalEnlistment(Enlistment enlistment, IEnlistmentNotification twoPhaseNotifications) :
base(enlistment, twoPhaseNotifications)
{
}
internal override Guid ResourceManagerIdentifier => _resourceManagerIdentifier;
}
//
// Since RecoveringInternalEnlistment does not have a transaction it must take
// a separate object as its sync root.
//
internal class RecoveringInternalEnlistment : DurableInternalEnlistment
{
private object _syncRoot;
internal RecoveringInternalEnlistment(Enlistment enlistment, IEnlistmentNotification twoPhaseNotifications, object syncRoot) :
base(enlistment, twoPhaseNotifications)
{
_syncRoot = syncRoot;
}
internal override object SyncRoot => _syncRoot;
}
internal class PromotableInternalEnlistment : InternalEnlistment
{
// This class acts as the durable single phase enlistment for a
// promotable single phase enlistment.
private IPromotableSinglePhaseNotification _promotableNotificationInterface;
internal PromotableInternalEnlistment(
Enlistment enlistment,
InternalTransaction transaction,
IPromotableSinglePhaseNotification promotableSinglePhaseNotification,
Transaction atomicTransaction) :
base(enlistment, transaction, atomicTransaction)
{
_promotableNotificationInterface = promotableSinglePhaseNotification;
}
internal override IPromotableSinglePhaseNotification PromotableSinglePhaseNotification => _promotableNotificationInterface;
}
// This class supports volatile enlistments
//
internal class Phase1VolatileEnlistment : InternalEnlistment
{
public Phase1VolatileEnlistment(
Enlistment enlistment,
InternalTransaction transaction,
IEnlistmentNotification twoPhaseNotifications,
ISinglePhaseNotification singlePhaseNotifications,
Transaction atomicTransaction)
: base(enlistment, transaction, twoPhaseNotifications, singlePhaseNotifications, atomicTransaction)
{
}
internal override void FinishEnlistment()
{
// Note another enlistment finished.
_transaction._phase1Volatiles._preparedVolatileEnlistments++;
CheckComplete();
}
internal override void CheckComplete()
{
// Make certain we increment the right list.
Debug.Assert(_transaction._phase1Volatiles._preparedVolatileEnlistments <=
_transaction._phase1Volatiles._volatileEnlistmentCount +
_transaction._phase1Volatiles._dependentClones);
// Check to see if all of the volatile enlistments are done.
if (_transaction._phase1Volatiles._preparedVolatileEnlistments ==
_transaction._phase1Volatiles._volatileEnlistmentCount +
_transaction._phase1Volatiles._dependentClones)
{
_transaction.State.Phase1VolatilePrepareDone(_transaction);
}
}
}
public class Enlistment
{
// Interface for communicating with the state machine.
internal InternalEnlistment _internalEnlistment;
internal Enlistment(InternalEnlistment internalEnlistment)
{
_internalEnlistment = internalEnlistment;
}
internal Enlistment(
Guid resourceManagerIdentifier,
InternalTransaction transaction,
IEnlistmentNotification twoPhaseNotifications,
ISinglePhaseNotification singlePhaseNotifications,
Transaction atomicTransaction)
{
_internalEnlistment = new DurableInternalEnlistment(
this,
resourceManagerIdentifier,
transaction,
twoPhaseNotifications,
singlePhaseNotifications,
atomicTransaction
);
}
internal Enlistment(
InternalTransaction transaction,
IEnlistmentNotification twoPhaseNotifications,
ISinglePhaseNotification singlePhaseNotifications,
Transaction atomicTransaction,
EnlistmentOptions enlistmentOptions)
{
if ((enlistmentOptions & EnlistmentOptions.EnlistDuringPrepareRequired) != 0)
{
_internalEnlistment = new InternalEnlistment(
this,
transaction,
twoPhaseNotifications,
singlePhaseNotifications,
atomicTransaction
);
}
else
{
_internalEnlistment = new Phase1VolatileEnlistment(
this,
transaction,
twoPhaseNotifications,
singlePhaseNotifications,
atomicTransaction
);
}
}
// This constructor is for a promotable single phase enlistment.
internal Enlistment(
InternalTransaction transaction,
IPromotableSinglePhaseNotification promotableSinglePhaseNotification,
Transaction atomicTransaction)
{
_internalEnlistment = new PromotableInternalEnlistment(
this,
transaction,
promotableSinglePhaseNotification,
atomicTransaction
);
}
internal Enlistment(
IEnlistmentNotification twoPhaseNotifications,
InternalTransaction transaction,
Transaction atomicTransaction)
{
_internalEnlistment = new InternalEnlistment(
this,
twoPhaseNotifications,
transaction,
atomicTransaction
);
}
internal Enlistment(IEnlistmentNotification twoPhaseNotifications, object syncRoot)
{
_internalEnlistment = new RecoveringInternalEnlistment(
this,
twoPhaseNotifications,
syncRoot
);
}
public void Done()
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
etwLog.EnlistmentDone(_internalEnlistment);
}
lock (_internalEnlistment.SyncRoot)
{
_internalEnlistment.State.EnlistmentDone(_internalEnlistment);
}
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
}
internal InternalEnlistment InternalEnlistment => _internalEnlistment;
}
}
|