context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Batch { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// ApplicationOperations operations. /// </summary> internal partial class ApplicationOperations : Microsoft.Rest.IServiceOperations<BatchManagementClient>, IApplicationOperations { /// <summary> /// Initializes a new instance of the ApplicationOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ApplicationOperations(BatchManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the BatchManagementClient /// </summary> public BatchManagementClient Client { get; private set; } /// <summary> /// Adds an application to the specified Batch account. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the Batch account. /// </param> /// <param name='accountName'> /// The name of the Batch account. /// </param> /// <param name='applicationId'> /// The id of the application. /// </param> /// <param name='parameters'> /// The parameters for the request. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Application>> CreateWithHttpMessagesAsync(string resourceGroupName, string accountName, string applicationId, AddApplicationParameters parameters = default(AddApplicationParameters), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$")) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$"); } } if (accountName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "accountName"); } if (accountName != null) { if (accountName.Length > 24) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MaxLength, "accountName", 24); } if (accountName.Length < 3) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "accountName", 3); } if (!System.Text.RegularExpressions.Regex.IsMatch(accountName, "^[-\\w\\._]+$")) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "accountName", "^[-\\w\\._]+$"); } } if (applicationId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "applicationId"); } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("accountName", accountName); tracingParameters.Add("applicationId", applicationId); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Create", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationId}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName)); _url = _url.Replace("{applicationId}", System.Uri.EscapeDataString(applicationId)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.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(parameters != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.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) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 201) { var ex = new Microsoft.Rest.Azure.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, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Application>(); _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 == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Application>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes an application. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the Batch account. /// </param> /// <param name='accountName'> /// The name of the Batch account. /// </param> /// <param name='applicationId'> /// The id of the application. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string accountName, string applicationId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$")) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$"); } } if (accountName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "accountName"); } if (accountName != null) { if (accountName.Length > 24) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MaxLength, "accountName", 24); } if (accountName.Length < 3) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "accountName", 3); } if (!System.Text.RegularExpressions.Regex.IsMatch(accountName, "^[-\\w\\._]+$")) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "accountName", "^[-\\w\\._]+$"); } } if (applicationId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "applicationId"); } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("accountName", accountName); tracingParameters.Add("applicationId", applicationId); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationId}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName)); _url = _url.Replace("{applicationId}", System.Uri.EscapeDataString(applicationId)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.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) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.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) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets information about the specified application. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the Batch account. /// </param> /// <param name='accountName'> /// The name of the Batch account. /// </param> /// <param name='applicationId'> /// The id of the application. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Application>> GetWithHttpMessagesAsync(string resourceGroupName, string accountName, string applicationId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$")) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$"); } } if (accountName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "accountName"); } if (accountName != null) { if (accountName.Length > 24) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MaxLength, "accountName", 24); } if (accountName.Length < 3) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "accountName", 3); } if (!System.Text.RegularExpressions.Regex.IsMatch(accountName, "^[-\\w\\._]+$")) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "accountName", "^[-\\w\\._]+$"); } } if (applicationId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "applicationId"); } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("accountName", accountName); tracingParameters.Add("applicationId", applicationId); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationId}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName)); _url = _url.Replace("{applicationId}", System.Uri.EscapeDataString(applicationId)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.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) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.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, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Application>(); _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<Application>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Updates settings for the specified application. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the Batch account. /// </param> /// <param name='accountName'> /// The name of the Batch account. /// </param> /// <param name='applicationId'> /// The id of the application. /// </param> /// <param name='parameters'> /// The parameters for the request. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> UpdateWithHttpMessagesAsync(string resourceGroupName, string accountName, string applicationId, UpdateApplicationParameters parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$")) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$"); } } if (accountName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "accountName"); } if (accountName != null) { if (accountName.Length > 24) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MaxLength, "accountName", 24); } if (accountName.Length < 3) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "accountName", 3); } if (!System.Text.RegularExpressions.Regex.IsMatch(accountName, "^[-\\w\\._]+$")) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "accountName", "^[-\\w\\._]+$"); } } if (applicationId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "applicationId"); } if (parameters == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "parameters"); } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("accountName", accountName); tracingParameters.Add("applicationId", applicationId); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationId}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName)); _url = _url.Replace("{applicationId}", System.Uri.EscapeDataString(applicationId)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PATCH"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.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(parameters != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.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) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.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) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Lists all of the applications in the specified account. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the Batch account. /// </param> /// <param name='accountName'> /// The name of the Batch account. /// </param> /// <param name='maxresults'> /// The maximum number of items to return in the response. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Application>>> ListWithHttpMessagesAsync(string resourceGroupName, string accountName, int? maxresults = default(int?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$")) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$"); } } if (accountName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "accountName"); } if (accountName != null) { if (accountName.Length > 24) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MaxLength, "accountName", 24); } if (accountName.Length < 3) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "accountName", 3); } if (!System.Text.RegularExpressions.Regex.IsMatch(accountName, "^[-\\w\\._]+$")) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "accountName", "^[-\\w\\._]+$"); } } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("accountName", accountName); tracingParameters.Add("maxresults", maxresults); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (maxresults != null) { _queryParameters.Add(string.Format("maxresults={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(maxresults, this.Client.SerializationSettings).Trim('"')))); } if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.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) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.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, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Application>>(); _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<Application>>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Lists all of the applications in the specified account. /// </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="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Application>>> ListNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (nextPageLink == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.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) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.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, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Application>>(); _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<Application>>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using Xunit; using System; using System.Xml; namespace XmlDocumentTests.XmlNodeTests { public class RemoveChildTests { private static readonly XmlNodeType[] XmlNodeTypes = new XmlNodeType[] { XmlNodeType.Whitespace, XmlNodeType.SignificantWhitespace, XmlNodeType.CDATA, XmlNodeType.Text, XmlNodeType.Comment }; private enum InsertType { InsertBefore, InsertAfter } [Fact] public static void IterativelyRemoveAllChildNodes() { var xml = @"<root> text node one <elem1 child1="""" child2=""duu"" child3=""e1;e2;"" child4=""a1"" child5=""goody""> text node two e1; text node three </elem1><!-- comment3 --><?PI3 processing instruction?>e2;<foo /><![CDATA[ <opentag> without an </endtag> and & <! are all ok here ]]><elem2 att1=""id1"" att2=""up"" att3=""attribute3""><a /></elem2><elem2> elem2-text1 <a> this-is-a </a> elem2-text2 e3;e4;<!-- elem2-comment1--> elem2-text3 <b> this-is-b </b> elem2-text4 <?elem2_PI elem2-PI?> elem2-text5 </elem2></root>"; var xmlDocument = new XmlDocument(); xmlDocument.LoadXml(xml); var count = xmlDocument.DocumentElement.ChildNodes.Count; for (int idx = 0; idx < count; idx++) xmlDocument.DocumentElement.RemoveChild(xmlDocument.DocumentElement.ChildNodes[0]); Assert.Equal(0, xmlDocument.DocumentElement.ChildNodes.Count); } [Fact] public static void RemoveDocumentElement() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<?PI pi1?><root><child1/><child2/><child3/></root><!--comment-->"); var root = xmlDocument.DocumentElement; Assert.Equal(3, xmlDocument.ChildNodes.Count); xmlDocument.RemoveChild(root); Assert.Equal(2, xmlDocument.ChildNodes.Count); Assert.Equal(XmlNodeType.ProcessingInstruction, xmlDocument.ChildNodes[0].NodeType); Assert.Equal(XmlNodeType.Comment, xmlDocument.ChildNodes[1].NodeType); } [Fact] public static void OldChildIsNull() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<root><child/></root>"); Assert.Throws<NullReferenceException>(() => xmlDocument.DocumentElement.RemoveChild(null)); } [Fact] public static void OldChildIsFirstChild() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<root><child1/><child2/></root>"); var child1 = xmlDocument.DocumentElement.ChildNodes[0]; var child2 = xmlDocument.DocumentElement.ChildNodes[1]; Assert.Equal(2, xmlDocument.DocumentElement.ChildNodes.Count); Assert.Equal(child1, xmlDocument.DocumentElement.FirstChild); xmlDocument.DocumentElement.RemoveChild(child1); Assert.Equal(1, xmlDocument.DocumentElement.ChildNodes.Count); Assert.Equal(child2, xmlDocument.DocumentElement.FirstChild); } [Fact] public static void NotChildNode() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<root><child1><gchild1/></child1><child2/></root>"); var child1 = xmlDocument.DocumentElement.ChildNodes[0]; var child2 = xmlDocument.DocumentElement.ChildNodes[1]; Assert.Throws<ArgumentException>(() => child1.RemoveChild(child2)); } [Fact] public static void AccessRemovedChildByReference() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<root>child1</root>"); var child1 = xmlDocument.DocumentElement.ChildNodes[0]; Assert.Equal("child1", child1.Value); Assert.Equal(1, xmlDocument.DocumentElement.ChildNodes.Count); xmlDocument.DocumentElement.RemoveChild(child1); Assert.Equal("child1", child1.Value); Assert.Equal(0, xmlDocument.DocumentElement.ChildNodes.Count); } [Fact] public static void RepeatedRemoveInsert() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<root/>"); var element = xmlDocument.CreateElement("elem"); for (int i = 0; i < 100; i++) { Assert.False(xmlDocument.DocumentElement.HasChildNodes); xmlDocument.DocumentElement.AppendChild(element); Assert.True(xmlDocument.DocumentElement.HasChildNodes); xmlDocument.DocumentElement.RemoveChild(element); } Assert.False(xmlDocument.DocumentElement.HasChildNodes); Assert.Null(element.ParentNode); } [Fact] public static void FromNodesThatCannotContainChildren() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<root><?PI pi node?>some test<!--comment--><![CDATA[some data]]></root>"); var piNode = xmlDocument.DocumentElement.ChildNodes[0]; var textNode = xmlDocument.DocumentElement.ChildNodes[1]; var commentNode = xmlDocument.DocumentElement.ChildNodes[2]; var cdataNode = xmlDocument.DocumentElement.ChildNodes[3]; Assert.Equal(XmlNodeType.ProcessingInstruction, piNode.NodeType); Assert.Throws<InvalidOperationException>(() => piNode.RemoveChild(null)); Assert.Equal(XmlNodeType.Text, textNode.NodeType); Assert.Throws<InvalidOperationException>(() => textNode.RemoveChild(null)); Assert.Equal(XmlNodeType.Comment, commentNode.NodeType); Assert.Throws<InvalidOperationException>(() => commentNode.RemoveChild(null)); Assert.Equal(XmlNodeType.CDATA, cdataNode.NodeType); Assert.Throws<InvalidOperationException>(() => cdataNode.RemoveChild(null)); } [Fact] public static void Text_Text_Text() { RemoveChildTestBase(new[] { XmlNodeType.Text, XmlNodeType.Text, XmlNodeType.Text }); } [Fact] public static void Whitespace_Whitespace_Whitespace() { RemoveChildTestBase(new XmlNodeType[] { XmlNodeType.Whitespace, XmlNodeType.Whitespace, XmlNodeType.Whitespace }); } [Fact] public static void SignificantWhitespace_SignificantWhitespace_SignificantWhitespace() { RemoveChildTestBase(new XmlNodeType[] { XmlNodeType.SignificantWhitespace, XmlNodeType.SignificantWhitespace, XmlNodeType.SignificantWhitespace }); } [Fact] public static void CDATA_CDATA_CDATA() { RemoveChildTestBase(new XmlNodeType[] { XmlNodeType.CDATA, XmlNodeType.CDATA, XmlNodeType.CDATA }); } [Fact] public static void Whitespace_Text_Text_CDATA_SignificantWhitespace_SignificantWhitespace() { RemoveChildTestBase(new XmlNodeType[] { XmlNodeType.Whitespace, XmlNodeType.Text, XmlNodeType.Text, XmlNodeType.CDATA, XmlNodeType.SignificantWhitespace, XmlNodeType.SignificantWhitespace }); } [Fact] public static void Text_Comment_CDATA() { var xml = @"<TMC>text<!-- comments --><![CDATA[ &lt; &amp; <tag> < ! > & </tag> ]]></TMC>"; foreach (var nodeType in XmlNodeTypes) DeleteNonTextNodeBase(xml, InsertType.InsertBefore, nodeType); } [Fact] public static void Text_Comment_SignificantWhitespace() { var xml = @"<TCS xml:space=""preserve"">text<!-- comments --> </TCS>"; foreach (var nodeType in XmlNodeTypes) DeleteNonTextNodeBase(xml, InsertType.InsertBefore, nodeType); } [Fact] public static void Whitespace_Comment_Text() { var xml = @"<WMT> <!-- comments -->text</WMT>"; foreach (var nodeType in XmlNodeTypes) DeleteNonTextNodeBase(xml, InsertType.InsertBefore, nodeType); } [Fact] public static void Whitespace_Element_Whitespace() { var xml = @"<WEW> <E/> </WEW>"; foreach (var nodeType in XmlNodeTypes) DeleteNonTextNodeBase(xml, InsertType.InsertAfter, nodeType); } [Fact] public static void Text_Element_Text() { var xml = @"<TET>text1<E/>text2</TET>"; foreach (var nodeType in XmlNodeTypes) DeleteNonTextNodeBase(xml, InsertType.InsertAfter, nodeType); } [Fact] public static void SignificantWhitespace_Element_SignificantWhitespace() { var xml = @" <SES xml:space=""preserve""> <E/> </SES>"; foreach (var nodeType in XmlNodeTypes) DeleteNonTextNodeBase(xml, InsertType.InsertAfter, nodeType); } [Fact] public static void CDATA_Element_CDATA() { var xml = @"<CEC><![CDATA[ &lt; &amp; <tag> < ! > & </tag> ]]><E/><![CDATA[ &lt; &amp; <tag> < ! > & </tag> ]]></CEC>"; foreach (var nodeType in XmlNodeTypes) DeleteNonTextNodeBase(xml, InsertType.InsertAfter, nodeType); } private static void RemoveChildTestBase(XmlNodeType[] nodeTypes) { for (int i = 0; i < nodeTypes.Length; i++) RemoveChildTestBase(nodeTypes, i); } private static void DeleteNonTextNodeBase(string xml, InsertType insertType, XmlNodeType nodeType) { string[] expected = new string[3]; var xmlDocument = new XmlDocument { PreserveWhitespace = true }; xmlDocument.LoadXml(xml); XmlNode parent = xmlDocument.DocumentElement; XmlNode firstChild = parent.FirstChild; XmlNode lastChild = parent.LastChild; XmlNode nodeToRemove = parent.FirstChild.NextSibling; expected[0] = firstChild.OuterXml + lastChild.OuterXml; // deletion parent.RemoveChild(nodeToRemove); // verify Assert.Equal(2, parent.ChildNodes.Count); Assert.Equal(expected[0], parent.InnerXml); Assert.Equal(firstChild.ParentNode, parent); Assert.Equal(lastChild.ParentNode, parent); VerifySiblings(firstChild, lastChild, InsertType.InsertAfter); // now, parent contains two textnodes only XmlNode newChild = CreateNode(xmlDocument, nodeType); XmlNode refChild = (insertType == InsertType.InsertBefore) ? lastChild : firstChild; expected[1] = firstChild.OuterXml + newChild.OuterXml + lastChild.OuterXml; expected[2] = parent.InnerXml; // insertion var insertDelegate = CreateInsertBeforeOrAfter(insertType); insertDelegate(parent, newChild, refChild); // verify Assert.Equal(3, parent.ChildNodes.Count); Assert.Equal(expected[1], parent.InnerXml); Assert.Equal(newChild.ParentNode, parent); Assert.Equal(lastChild.ParentNode, parent); Assert.Equal(firstChild.ParentNode, parent); VerifySiblings(firstChild, newChild, InsertType.InsertAfter); VerifySiblings(newChild, lastChild, InsertType.InsertAfter); // delete the newChild parent.RemoveChild(newChild); // verify Assert.Equal(2, parent.ChildNodes.Count); Assert.Equal(expected[2], parent.InnerXml); Assert.Equal(firstChild.ParentNode, parent); Assert.Equal(lastChild.ParentNode, parent); VerifySiblings(firstChild, lastChild, InsertType.InsertAfter); } private static void RemoveChildTestBase(XmlNodeType[] nodeTypes, int ithNodeToRemove) { int total = nodeTypes.Length; XmlDocument doc = new XmlDocument { PreserveWhitespace = true }; var parent = doc.CreateElement("root"); doc.AppendChild(parent); var newChildren = new XmlNode[total]; string expected = string.Empty; for (int i = 0; i < total; i++) { newChildren[i] = CreateNode(doc, nodeTypes[i]); parent.AppendChild(newChildren[i]); expected += newChildren[i].OuterXml; } Assert.Equal(total, parent.ChildNodes.Count); Assert.Equal(expected, parent.InnerXml); for (int i = 0; i < total - 1; i++) { Verify(parent, newChildren[i], newChildren[i + 1]); VerifySiblings(newChildren[i], newChildren[i + 1]); } expected = string.Empty; for (int i = 0; i < total; i++) if (i != ithNodeToRemove) expected += newChildren[i].OuterXml; // remove either the FirstChild or LastChild according to the value of ithNodeToRemove parent.RemoveChild(newChildren[ithNodeToRemove]); Assert.Equal(total - 1, parent.ChildNodes.Count); Assert.Equal(expected, parent.InnerXml); } private static void VerifySiblings(XmlNode refChild, XmlNode newChild) { Assert.Equal(newChild, refChild.NextSibling); Assert.Equal(refChild, newChild.PreviousSibling); } private static void VerifySiblings(XmlNode refChild, XmlNode newChild, InsertType insertType) { switch (insertType) { case InsertType.InsertBefore: VerifySiblings(newChild, refChild); break; case InsertType.InsertAfter: VerifySiblings(refChild, newChild); break; default: Assert.True(false, "Wrong InsertType: '" + insertType + "'"); break; } } private static void Verify(XmlNode parent, XmlNode child, XmlNode newChild) { Assert.Equal(child.ParentNode, parent); Assert.Equal(newChild.ParentNode, parent); } private static XmlNode CreateNode(XmlDocument doc, XmlNodeType nodeType) { Assert.NotNull(doc); switch (nodeType) { case XmlNodeType.CDATA: return doc.CreateCDataSection(@"&lt; &amp; <tag> < ! > & </tag> "); case XmlNodeType.Comment: return doc.CreateComment(@"comment"); case XmlNodeType.Element: return doc.CreateElement("E"); case XmlNodeType.Text: return doc.CreateTextNode("text"); case XmlNodeType.Whitespace: return doc.CreateWhitespace(@" "); case XmlNodeType.SignificantWhitespace: return doc.CreateSignificantWhitespace(" "); default: Assert.True(false, "Wrong XmlNodeType: '" + nodeType + "'"); return null; } } private static XmlNode InsertBefore(XmlNode parent, XmlNode newChild, XmlNode refChild) { Assert.NotNull(parent); Assert.NotNull(newChild); return parent.InsertBefore(newChild, refChild); } private static XmlNode InsertAfter(XmlNode parent, XmlNode newChild, XmlNode refChild) { Assert.NotNull(parent); Assert.NotNull(newChild); return parent.InsertAfter(newChild, refChild); } private static Func<XmlNode, XmlNode, XmlNode, XmlNode> CreateInsertBeforeOrAfter(InsertType insertType) { switch (insertType) { case InsertType.InsertBefore: return InsertBefore; case InsertType.InsertAfter: return InsertAfter; } Assert.True(false, "Unknown type"); return null; } } }
// Copyright 2017 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. using Android.App; using Android.Graphics; using Android.OS; using Android.Views; using Android.Widget; using ArcGISRuntime.Samples.Managers; using Esri.ArcGISRuntime.Data; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.UI; using Esri.ArcGISRuntime.UI.Controls; using System; using ContextThemeWrapper = AndroidX.AppCompat.View.ContextThemeWrapper; namespace ArcGISRuntime.Samples.ReadShapefileMetadata { [Activity(ConfigurationChanges = Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)] [ArcGISRuntime.Samples.Shared.Attributes.OfflineData("d98b3e5293834c5f852f13c569930caa")] [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "Read shapefile metadata", category: "Data", description: "Read a shapefile and display its metadata.", instructions: "The shapefile's metadata will be displayed when you open the sample.", tags: new[] { "credits", "description", "metadata", "package", "shape file", "shapefile", "summary", "symbology", "tags", "visualization" })] public class ReadShapefileMetadata : Activity { // Store the app's map view private MapView _myMapView; // Store the object that holds the shapefile metadata private ShapefileInfo _shapefileMetadata; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); Title = "Read shapefile metadata"; CreateLayout(); // Download (if necessary) and add a local shapefile dataset to the map Initialize(); } private async void Initialize() { // Create a new map to display in the map view with a streets basemap Map streetMap = new Map(BasemapStyle.ArcGISStreets); // Get the path to the downloaded shapefile string filepath = GetShapefilePath(); try { // Open the shapefile ShapefileFeatureTable myShapefile = await ShapefileFeatureTable.OpenAsync(filepath); // Read metadata about the shapefile and display it in the UI _shapefileMetadata = myShapefile.Info; // Create a feature layer to display the shapefile FeatureLayer newFeatureLayer = new FeatureLayer(myShapefile); await newFeatureLayer.LoadAsync(); // Zoom the map to the extent of the shapefile _myMapView.SpatialReferenceChanged += async (s, e) => { await _myMapView.SetViewpointGeometryAsync(newFeatureLayer.FullExtent); }; // Add the feature layer to the map streetMap.OperationalLayers.Add(newFeatureLayer); // Show the map in the MapView _myMapView.Map = streetMap; } catch (Exception e) { new AlertDialog.Builder(this).SetMessage(e.ToString()).SetTitle("Error").Show(); } } private static string GetShapefilePath() { return DataManager.GetDataFolder("d98b3e5293834c5f852f13c569930caa", "TrailBikeNetwork.shp"); } private void CreateLayout() { // Create a new vertical layout for the app LinearLayout layout = new LinearLayout(this) { Orientation = Orientation.Vertical }; // Add a button to show the metadata Button showMetadataButton = new Button(this) { Text = "Show Metadata" }; showMetadataButton.Click += ShowMetadataDialog; layout.AddView(showMetadataButton); // Add the map view to the layout _myMapView = new MapView(this); layout.AddView(_myMapView); // Show the layout in the app SetContentView(layout); } private void ShowMetadataDialog(object sender, System.EventArgs e) { MetadataDialogFragment metadataDialog = new MetadataDialogFragment(_shapefileMetadata); // Begin a transaction to show a UI fragment (the metadata dialog) FragmentTransaction trans = FragmentManager.BeginTransaction(); metadataDialog.Show(trans, "metadata"); } } // A custom DialogFragment class to show shapefile metadata public class MetadataDialogFragment : DialogFragment { private ShapefileInfo _metadata; private ImageView _thumbnailImageView; public MetadataDialogFragment(ShapefileInfo metadata) { _metadata = metadata; } public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { base.OnCreateView(inflater, container, savedInstanceState); // Dialog to display LinearLayout dialogView = null; // Get the context for creating the dialog controls Android.Content.Context ctx = Activity.ApplicationContext; AndroidX.AppCompat.View.ContextThemeWrapper ctxWrapper = new ContextThemeWrapper(ctx, Android.Resource.Style.ThemeMaterialLight); // Set a dialog title Dialog.SetTitle(_metadata.Credits); // The container for the dialog is a vertical linear layout dialogView = new LinearLayout(ctxWrapper) { Orientation = Orientation.Vertical }; dialogView.SetPadding(20, 20, 20, 20); // Add a text box for showing metadata summary TextView summaryTextView = new TextView(ctxWrapper) { Text = _metadata.Summary }; dialogView.AddView(summaryTextView); // Add an image to show the thumbnail _thumbnailImageView = new ImageView(ctxWrapper); _thumbnailImageView.SetMinimumHeight(200); _thumbnailImageView.SetMinimumWidth(200); dialogView.AddView(_thumbnailImageView); // Call a function to load the thumbnail image from the metadata LoadThumbnail(); // Add a text box for showing metadata tags TextView tagsTextView = new TextView(ctxWrapper) { Text = string.Join(",", _metadata.Tags) }; dialogView.AddView(tagsTextView); // Add a button to close the dialog Button dismissButton = new Button(ctxWrapper) { Text = "OK" }; dismissButton.Click += (s, e) => Dismiss(); dialogView.AddView(dismissButton); // Return the new view for display return dialogView; } private async void LoadThumbnail() { try { Bitmap img = await _metadata.Thumbnail.ToImageSourceAsync(); _thumbnailImageView.SetImageBitmap(img); } catch (Exception e) { new AlertDialog.Builder(Context).SetMessage(e.ToString()).SetTitle("Error").Show(); } } } }
// *********************************************************************** // Copyright (c) 2015 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.Collections; using NUnit.Framework; using NUnit.Framework.Internal; using System; using System.Collections.Generic; using System.Linq; namespace NUnit.TestData.TestFixtureSourceData { public abstract class TestFixtureSourceTest { private readonly string Arg; private readonly string Expected; public TestFixtureSourceTest(string arg, string expected) { Arg = arg; Expected = expected; } [Test] public void CheckSource() { Assert.That(Arg, Is.EqualTo(Expected)); } } public abstract class TestFixtureSourceDivideTest { private readonly int X; private readonly int Y; private readonly int Z; public TestFixtureSourceDivideTest(int x, int y, int z) { X = x; Y = y; Z = z; } [Test] public void CheckSource() { Assert.That(X / Y, Is.EqualTo(Z)); } } [TestFixtureSource("StaticField")] public class StaticField_SameClass : TestFixtureSourceTest { public StaticField_SameClass(string arg) : base(arg, "StaticFieldInClass") { } #pragma warning disable 414 static object[] StaticField = new object[] { "StaticFieldInClass" }; #pragma warning restore 414 } [TestFixtureSource("StaticProperty")] public class StaticProperty_SameClass : TestFixtureSourceTest { public StaticProperty_SameClass(string arg) : base(arg, "StaticPropertyInClass") { } public StaticProperty_SameClass(string arg, string expected) : base(arg, expected) { } public static object[] StaticProperty { get { return new object[] { new object[] { "StaticPropertyInClass" } }; } } } [TestFixtureSource("StaticProperty")] public class StaticProperty_InheritedClass : StaticProperty_SameClass { public StaticProperty_InheritedClass (string arg) : base(arg, "StaticPropertyInClass") { } } [TestFixtureSource("StaticMethod")] public class StaticMethod_SameClass : TestFixtureSourceTest { public StaticMethod_SameClass(string arg) : base(arg, "StaticMethodInClass") { } static object[] StaticMethod() { return new object[] { new object[] { "StaticMethodInClass" } }; } } [TestFixtureSource("InstanceField")] public class InstanceField_SameClass : TestFixtureSourceTest { public InstanceField_SameClass(string arg) : base(arg, "InstanceFieldInClass") { } #pragma warning disable 414 object[] InstanceField = new object[] { "InstanceFieldInClass" }; #pragma warning restore 414 } [TestFixtureSource("InstanceProperty")] public class InstanceProperty_SameClass : TestFixtureSourceTest { public InstanceProperty_SameClass(string arg) : base(arg, "InstancePropertyInClass") { } object[] InstanceProperty { get { return new object[] { new object[] { "InstancePropertyInClass" } }; } } } [TestFixtureSource("InstanceMethod")] public class InstanceMethod_SameClass : TestFixtureSourceTest { public InstanceMethod_SameClass(string arg) : base(arg, "InstanceMethodInClass") { } object[] InstanceMethod() { return new object[] { new object[] { "InstanceMethodInClass" } }; } } [TestFixtureSource(typeof(SourceData), "StaticField")] public class StaticField_DifferentClass : TestFixtureSourceTest { public StaticField_DifferentClass(string arg) : base(arg, "StaticField") { } } [TestFixtureSource(typeof(SourceData), "StaticProperty")] public class StaticProperty_DifferentClass : TestFixtureSourceTest { public StaticProperty_DifferentClass(string arg) : base(arg, "StaticProperty") { } } [TestFixtureSource(typeof(SourceData), "StaticMethod")] public class StaticMethod_DifferentClass : TestFixtureSourceTest { public StaticMethod_DifferentClass(string arg) : base(arg, "StaticMethod") { } } [TestFixtureSource(typeof(SourceData_IEnumerable))] public class IEnumerableSource : TestFixtureSourceTest { public IEnumerableSource(string arg) : base(arg, "SourceData_IEnumerable") { } } [TestFixtureSource("MyData")] public class SourceReturnsObjectArray : TestFixtureSourceDivideTest { public SourceReturnsObjectArray(int x, int y, int z) : base(x, y, z) { } static IEnumerable MyData() { yield return new object[] { 12, 4, 3 }; yield return new object[] { 12, 3, 4 }; yield return new object[] { 12, 6, 2 }; } } [TestFixtureSource("MyData")] public class SourceReturnsFixtureParameters : TestFixtureSourceDivideTest { public SourceReturnsFixtureParameters(int x, int y, int z) : base(x, y, z) { } static IEnumerable MyData() { yield return new TestFixtureParameters(12, 4, 3); yield return new TestFixtureParameters(12, 3, 4); yield return new TestFixtureParameters(12, 6, 2); } } [TestFixture] [TestFixtureSource("MyData")] public class ExtraTestFixtureAttributeIsIgnored : TestFixtureSourceDivideTest { public ExtraTestFixtureAttributeIsIgnored(int x, int y, int z) : base(x, y, z) { } static IEnumerable MyData() { yield return new object[] { 12, 4, 3 }; yield return new object[] { 12, 3, 4 }; yield return new object[] { 12, 6, 2 }; } } [TestFixture] [TestFixtureSource("MyData")] [TestFixtureSource("MoreData", Category = "Extra")] [TestFixture(12, 12, 1)] public class TestFixtureMayUseMultipleSourceAttributes : TestFixtureSourceDivideTest { public TestFixtureMayUseMultipleSourceAttributes(int n, int d, int q) : base(n, d, q) { } static IEnumerable MyData() { yield return new object[] { 12, 4, 3 }; yield return new object[] { 12, 3, 4 }; yield return new object[] { 12, 6, 2 }; } #pragma warning disable 414 static object[] MoreData = new object[] { new object[] { 12, 1, 12 }, new object[] { 12, 2, 6 } }; #pragma warning restore 414 } [TestFixtureSource("IgnoredData")] public class IndividualInstancesMayBeIgnored : TestFixtureSourceTest { public IndividualInstancesMayBeIgnored(string arg) : base(arg, "IgnoredData") { } static IEnumerable IgnoredData() { yield return new TestFixtureData("GoodData"); yield return new TestFixtureData("IgnoredData").Ignore("There must be a reason"); yield return new TestFixtureData("MoreGoodData"); } } [TestFixtureSource("ExplicitData")] public class IndividualInstancesMayBeExplicit : TestFixtureSourceTest { public IndividualInstancesMayBeExplicit(string arg) : base(arg, "ExplicitData") { } static IEnumerable ExplicitData() { yield return new TestFixtureData("GoodData"); yield return new TestFixtureData("ExplicitData").Explicit("Runs long"); yield return new TestFixtureData("MoreExplicitData").Explicit(); } } #region Test name tests [TestFixtureSource(nameof(IndividualInstanceNameTestDataSource))] public sealed class IndividualInstanceNameTestDataFixture { public IndividualInstanceNameTestDataFixture(params object[] args) { } [Test] public void Test() { } public static IEnumerable<TestFixtureData> IndividualInstanceNameTestDataSource() => from spec in TestDataSpec.Specs select new TestFixtureData(spec.Arguments) { Properties = // SetProperty does not exist { ["ExpectedTestName"] = { spec.GetFixtureName(nameof(IndividualInstanceNameTestDataFixture)) } } } .SetArgDisplayNames(spec.ArgDisplayNames); } #endregion [TestFixture] public abstract class Issue1118_Root { protected readonly string Browser; protected Issue1118_Root(string browser) { Browser = browser; } [SetUp] public void Setup() { } } [TestFixtureSource(typeof(Issue1118_SourceData))] public class Issue1118_Base : Issue1118_Root { public Issue1118_Base(string browser) : base(browser) { } [TearDown] public void Cleanup() { } } public class Issue1118_Fixture : Issue1118_Base { public Issue1118_Fixture(string browser) : base(browser) { } [Test] public void DoSomethingOnAWebPageWithSelenium() { } [Test] public void DoSomethingElseOnAWebPageWithSelenium() { } } public class Issue1118_SourceData : IEnumerable { public IEnumerator GetEnumerator() { yield return "Firefox"; yield return "Chrome"; yield return "Internet Explorer"; } } public class GenericFixtureSource { public static readonly Type[] Source = new Type[] { typeof(short), typeof(int), typeof(long) }; } [TestFixtureSource(typeof(GenericFixtureSource), "Source")] public class GenericFixtureSourceWithProperArgsProvided<T> { [Test] public void SomeTest() { } } #region Source Data Classes class SourceData_IEnumerable : IEnumerable { public SourceData_IEnumerable() { } public IEnumerator GetEnumerator() { yield return "SourceData_IEnumerable"; } } class SourceData { public static object[] InheritedStaticProperty { get { return new object[] { new object[] { "StaticProperty" } }; } } #pragma warning disable 414 static object[] StaticField = new object[] { "StaticField" }; #pragma warning restore 414 static object[] StaticProperty { get { return new object[] { new object[] { "StaticProperty" } }; } } static object[] StaticMethod() { return new object[] { new object[] { "StaticMethod" } }; } } #endregion } [TestFixtureSource("MyData")] public class NoNamespaceTestFixtureSourceWithTwoValues { public NoNamespaceTestFixtureSourceWithTwoValues(int i) { } [Test] public void Test() { } #pragma warning disable 414 static object[] MyData = { 1, 2 }; #pragma warning restore 414 } [TestFixtureSource("MyData")] public class NoNamespaceTestFixtureSourceWithSingleValue { public NoNamespaceTestFixtureSourceWithSingleValue(int i) { } [Test] public void Test() { } #pragma warning disable 414 static object[] MyData = { 1 }; #pragma warning restore 414 }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using Microsoft.Build.Collections; using System; using Microsoft.Build.Evaluation; using Microsoft.Build.UnitTests; using Microsoft.Build.Framework; using System.Collections; using Microsoft.Build.Execution; using Microsoft.Build.Shared; using Microsoft.Build.Construction; using System.Xml; using System.IO; using System.Linq; using System.Reflection; using Xunit; namespace Microsoft.Build.UnitTests.Construction { /// <summary> /// Tests for the ElementLocation class /// </summary> public class ElementLocationPublic_Tests { /// <summary> /// Check that we can get the file name off an element and attribute, even if /// it wouldn't normally have got one because the project wasn't /// loaded from disk, or has been edited since. /// This is really a test of our XmlDocumentWithLocation. /// </summary> [Fact] public void ShouldHaveFilePathLocationEvenIfNotLoadedNorSavedYet() { ProjectRootElement project = ProjectRootElement.Create(); project.FullPath = "c:\\x"; ProjectTargetElement target = project.CreateTargetElement("t"); target.Outputs = "o"; project.AppendChild(target); Assert.Equal(project.FullPath, target.Location.File); Assert.Equal(project.FullPath, target.OutputsLocation.File); } /// <summary> /// Element location should reflect rename. /// This is really a test of our XmlXXXXWithLocation. /// </summary> [Fact] public void XmlLocationReflectsRename() { ProjectRootElement project = ProjectRootElement.Create(); project.FullPath = "c:\\x"; ProjectTargetElement target = project.CreateTargetElement("t"); target.Outputs = "o"; project.AppendChild(target); Assert.Equal(project.FullPath, target.Location.File); Assert.Equal(project.FullPath, target.OutputsLocation.File); project.FullPath = "c:\\y"; Assert.Equal(project.FullPath, target.Location.File); Assert.Equal(project.FullPath, target.OutputsLocation.File); } /// <summary> /// We should cache ElementLocation objects for perf. /// </summary> [Fact] public void XmlLocationsAreCached() { ProjectRootElement project = ProjectRootElement.Create(); project.FullPath = "c:\\x"; ProjectTargetElement target = project.CreateTargetElement("t"); target.Outputs = "o"; project.AppendChild(target); ElementLocation e1 = target.Location; ElementLocation e2 = target.OutputsLocation; Assert.True(Object.ReferenceEquals(e1, target.Location)); Assert.True(Object.ReferenceEquals(e2, target.OutputsLocation)); } /// <summary> /// Test many of the getters /// </summary> [Fact] public void LocationStringsMedley() { string content = @" <Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`> <UsingTask TaskName='t' AssemblyName='a' Condition='true'/> <UsingTask TaskName='t' AssemblyFile='a' Condition='true'/> <ItemDefinitionGroup Condition='true' Label='l'> <m Condition='true'/> </ItemDefinitionGroup> <ItemGroup> <i Include='i' Condition='true' Exclude='r'> <m Condition='true'/> </i> </ItemGroup> <PropertyGroup> <p Condition='true'/> </PropertyGroup> <Target Name='Build' Condition='true' Inputs='i' Outputs='o'> <ItemGroup> <i Include='i' Condition='true' Exclude='r'> <m Condition='true'/> </i> <i Remove='r'/> </ItemGroup> <PropertyGroup> <p Condition='true'/> </PropertyGroup> <Error Text='xyz' ContinueOnError='true' Importance='high'/> </Target> <Import Project='p' Condition='false'/> </Project> "; var project = ObjectModelHelpers.CreateInMemoryProject(content); string locations = project.Xml.Location.LocationString + "\r\n"; foreach (var element in project.Xml.AllChildren) { foreach (var property in element.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) { if (!property.Name.Equals("ImplicitImportLocation") && property.Name.Contains("Location")) { if (property.Name == "ParameterLocations") { var values = new List<KeyValuePair<string, ElementLocation>>(((ICollection<KeyValuePair<string, ElementLocation>>)property.GetValue(element, null))); values.ForEach((value) => locations += value.Key + ":" + value.Value.LocationString + "\r\n"); } else { var value = ((ElementLocation)property.GetValue(element, null)); if (value != null) // null means attribute is not present { locations += value.LocationString + "\r\n"; } } } } } locations = locations.Replace(project.FullPath, "c:\\foo\\bar.csproj"); string expected = @"c:\foo\bar.csproj (2,13) c:\foo\bar.csproj (3,32) c:\foo\bar.csproj (3,45) c:\foo\bar.csproj (3,62) c:\foo\bar.csproj (3,21) c:\foo\bar.csproj (4,32) c:\foo\bar.csproj (4,45) c:\foo\bar.csproj (4,62) c:\foo\bar.csproj (4,21) c:\foo\bar.csproj (5,42) c:\foo\bar.csproj (5,59) c:\foo\bar.csproj (5,21) c:\foo\bar.csproj (6,28) c:\foo\bar.csproj (6,25) c:\foo\bar.csproj (8,21) c:\foo\bar.csproj (9,28) c:\foo\bar.csproj (9,57) c:\foo\bar.csproj (9,40) c:\foo\bar.csproj (9,25) c:\foo\bar.csproj (10,32) c:\foo\bar.csproj (10,29) c:\foo\bar.csproj (13,21) c:\foo\bar.csproj (14,28) c:\foo\bar.csproj (14,25) c:\foo\bar.csproj (16,29) c:\foo\bar.csproj (16,59) c:\foo\bar.csproj (16,70) c:\foo\bar.csproj (16,29) c:\foo\bar.csproj (16,42) c:\foo\bar.csproj (16,21) c:\foo\bar.csproj (17,25) c:\foo\bar.csproj (18,32) c:\foo\bar.csproj (18,61) c:\foo\bar.csproj (18,44) c:\foo\bar.csproj (18,29) c:\foo\bar.csproj (19,36) c:\foo\bar.csproj (19,33) c:\foo\bar.csproj (21,32) c:\foo\bar.csproj (21,29) c:\foo\bar.csproj (23,25) c:\foo\bar.csproj (24,32) c:\foo\bar.csproj (24,29) Text: (26,32) Importance: (26,66) c:\foo\bar.csproj (26,43) c:\foo\bar.csproj (26,25) c:\foo\bar.csproj (28,29) c:\foo\bar.csproj (28,41) c:\foo\bar.csproj (28,21) "; Helpers.VerifyAssertLineByLine(expected, locations); } } }
// This file is part of the re-linq project (relinq.codeplex.com) // Copyright (C) 2005-2009 rubicon informationstechnologie gmbh, www.rubicon.eu // // re-linq is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License as published by the // Free Software Foundation; either version 2.1 of the License, // or (at your option) any later version. // // re-linq is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with re-linq; if not, see http://www.gnu.org/licenses. // using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Remotion.Linq.Parsing.ExpressionTreeVisitors; using Remotion.Linq.Parsing.ExpressionTreeVisitors.Transformation; using Remotion.Linq.Parsing.Structure.ExpressionTreeProcessors; using Remotion.Linq.Parsing.Structure.IntermediateModel; using Remotion.Linq.Parsing.Structure.NodeTypeProviders; using Remotion.Linq.Utilities; namespace Remotion.Linq.Parsing.Structure { /// <summary> /// Parses an expression tree into a chain of <see cref="IExpressionNode"/> objects after executing a sequence of /// <see cref="IExpressionTreeProcessor"/> objects. /// </summary> public class ExpressionTreeParser { private static readonly MethodInfo s_getArrayLengthMethod = typeof (Array).GetMethod ("get_Length"); [Obsolete ( "This method has been removed. Use QueryParser.CreateDefault, or create a customized ExpressionTreeParser using the constructor. (1.13.93)", true)] public static ExpressionTreeParser CreateDefault () { throw new NotImplementedException(); } /// <summary> /// Creates a default <see cref="CompoundNodeTypeProvider"/> that already has all expression node parser defined by the re-linq assembly /// registered. Users can add inner providers to register their own expression node parsers. /// </summary> /// <returns>A default <see cref="CompoundNodeTypeProvider"/> that already has all expression node parser defined by the re-linq assembly /// registered.</returns> public static CompoundNodeTypeProvider CreateDefaultNodeTypeProvider () { var searchedTypes = typeof (MethodInfoBasedNodeTypeRegistry).Assembly.GetTypes (); var innerProviders = new INodeTypeProvider[] { MethodInfoBasedNodeTypeRegistry.CreateFromTypes (searchedTypes), MethodNameBasedNodeTypeRegistry.CreateFromTypes(searchedTypes) }; return new CompoundNodeTypeProvider (innerProviders); } /// <summary> /// Creates a default <see cref="CompoundExpressionTreeProcessor"/> that already has the expression tree processing steps defined by the re-linq assembly /// registered. Users can insert additional processing steps. /// </summary> /// <param name="tranformationProvider">The tranformation provider to be used by the <see cref="TransformingExpressionTreeProcessor"/> included /// in the result set. Use <see cref="ExpressionTransformerRegistry.CreateDefault"/> to create a default provider.</param> /// <returns> /// A default <see cref="CompoundExpressionTreeProcessor"/> that already has all expression tree processing steps defined by the re-linq assembly /// registered. /// </returns> /// <remarks> /// The following steps are included: /// <list type="bullet"> /// <item><see cref="PartialEvaluatingExpressionTreeProcessor"/></item> /// <item><see cref="TransformingExpressionTreeProcessor"/> (parameterized with <paramref name="tranformationProvider"/>)</item> /// </list> /// </remarks> public static CompoundExpressionTreeProcessor CreateDefaultProcessor (IExpressionTranformationProvider tranformationProvider) { ArgumentUtility.CheckNotNull ("tranformationProvider", tranformationProvider); return new CompoundExpressionTreeProcessor (new IExpressionTreeProcessor[] { new PartialEvaluatingExpressionTreeProcessor(), new TransformingExpressionTreeProcessor (tranformationProvider) }); } private readonly UniqueIdentifierGenerator _identifierGenerator = new UniqueIdentifierGenerator (); private readonly INodeTypeProvider _nodeTypeProvider; private readonly IExpressionTreeProcessor _processor; private readonly MethodCallExpressionParser _methodCallExpressionParser; /// <summary> /// Initializes a new instance of the <see cref="ExpressionTreeParser"/> class with a custom <see cref="INodeTypeProvider"/> and /// <see cref="IExpressionTreeProcessor"/> implementation. /// </summary> /// <param name="nodeTypeProvider">The <see cref="INodeTypeProvider"/> to use when parsing <see cref="Expression"/> trees. Use /// <see cref="CreateDefaultNodeTypeProvider"/> to create an instance of <see cref="CompoundNodeTypeProvider"/> that already includes all /// default node types. (The <see cref="CompoundNodeTypeProvider"/> can be customized as needed by adding or removing /// <see cref="CompoundNodeTypeProvider.InnerProviders"/>).</param> /// <param name="processor">The <see cref="IExpressionTreeProcessor"/> to apply to <see cref="Expression"/> trees before parsing their nodes. Use /// <see cref="CreateDefaultProcessor"/> to create an instance of <see cref="CompoundExpressionTreeProcessor"/> that already includes /// the default steps. (The <see cref="CompoundExpressionTreeProcessor"/> can be customized as needed by adding or removing /// <see cref="CompoundExpressionTreeProcessor.InnerProcessors"/>).</param> public ExpressionTreeParser (INodeTypeProvider nodeTypeProvider, IExpressionTreeProcessor processor) { ArgumentUtility.CheckNotNull ("nodeTypeProvider", nodeTypeProvider); ArgumentUtility.CheckNotNull ("processor", processor); _nodeTypeProvider = nodeTypeProvider; _processor = processor; _methodCallExpressionParser = new MethodCallExpressionParser (_nodeTypeProvider); } /// <summary> /// Gets the node type provider used to parse <see cref="MethodCallExpression"/> instances in <see cref="ParseTree"/>. /// </summary> /// <value>The node type provider.</value> public INodeTypeProvider NodeTypeProvider { get { return _nodeTypeProvider; } } /// <summary> /// Gets the processing steps used by <see cref="ParseTree"/> to process the <see cref="Expression"/> tree before analyzing its structure. /// </summary> /// <value>The processing steps.</value> public IExpressionTreeProcessor Processor { get { return _processor; } } /// <summary> /// Parses the given <paramref name="expressionTree"/> into a chain of <see cref="IExpressionNode"/> instances, using /// <see cref="MethodInfoBasedNodeTypeRegistry"/> to convert expressions to nodes. /// </summary> /// <param name="expressionTree">The expression tree to parse.</param> /// <returns>A chain of <see cref="IExpressionNode"/> instances representing the <paramref name="expressionTree"/>.</returns> public IExpressionNode ParseTree (Expression expressionTree) { ArgumentUtility.CheckNotNull ("expressionTree", expressionTree); if (expressionTree.Type == typeof (void)) throw new ParserException (String.Format ("Expressions of type void ('{0}') are not supported.", expressionTree)); var processedExpressionTree = _processor.Process (expressionTree); return ParseNode (processedExpressionTree, null); } /// <summary> /// Gets the query operator <see cref="MethodCallExpression"/> represented by <paramref name="expression"/>. If <paramref name="expression"/> /// is already a <see cref="MethodCallExpression"/>, that is the assumed query operator. If <paramref name="expression"/> is a /// <see cref="MemberExpression"/> and the member's getter is registered with <see cref="NodeTypeProvider"/>, a corresponding /// <see cref="MethodCallExpression"/> is constructed and returned. Otherwise, <see langword="null" /> is returned. /// </summary> /// <param name="expression">The expression to get a query operator expression for.</param> /// <returns>A <see cref="MethodCallExpression"/> to be parsed as a query operator, or <see langword="null"/> if the expression does not represent /// a query operator.</returns> public MethodCallExpression GetQueryOperatorExpression (Expression expression) { var methodCallExpression = expression as MethodCallExpression; if (methodCallExpression != null) return methodCallExpression; var memberExpression = expression as MemberExpression; if (memberExpression != null) { var propertyInfo = memberExpression.Member as PropertyInfo; if (propertyInfo == null) return null; var getterMethod = propertyInfo.GetGetMethod (); if (getterMethod == null || !_nodeTypeProvider.IsRegistered (getterMethod)) return null; return Expression.Call (memberExpression.Expression, getterMethod); } var unaryExpression = expression as UnaryExpression; if (unaryExpression != null) { if (unaryExpression.NodeType == ExpressionType.ArrayLength && _nodeTypeProvider.IsRegistered (s_getArrayLengthMethod)) return Expression.Call (unaryExpression.Operand, s_getArrayLengthMethod); } return null; } private IExpressionNode ParseNode (Expression expression, string associatedIdentifier) { if (associatedIdentifier == null) associatedIdentifier = _identifierGenerator.GetUniqueIdentifier ("<generated>_"); var methodCallExpression = GetQueryOperatorExpression(expression); if (methodCallExpression != null) return ParseMethodCallExpression (methodCallExpression, associatedIdentifier); else return ParseNonQueryOperatorExpression(expression, associatedIdentifier); } private IExpressionNode ParseMethodCallExpression (MethodCallExpression methodCallExpression, string associatedIdentifier) { string associatedIdentifierForSource = InferAssociatedIdentifierForSource (methodCallExpression); Expression sourceExpression; IEnumerable<Expression> arguments; if (methodCallExpression.Object != null) { sourceExpression = methodCallExpression.Object; arguments = methodCallExpression.Arguments; } else { sourceExpression = methodCallExpression.Arguments[0]; arguments = methodCallExpression.Arguments.Skip (1); } var source = ParseNode (sourceExpression, associatedIdentifierForSource); return _methodCallExpressionParser.Parse (associatedIdentifier, source, arguments, methodCallExpression); } private IExpressionNode ParseNonQueryOperatorExpression (Expression expression, string associatedIdentifier) { var preprocessedExpression = SubQueryFindingExpressionTreeVisitor.Process (expression, _nodeTypeProvider); try { return new MainSourceExpressionNode (associatedIdentifier, preprocessedExpression); } catch (ArgumentTypeException ex) { var message = String.Format ( "Cannot parse expression '{0}' as it has an unsupported type. Only query sources (that is, expressions that implement IEnumerable) " + "and query operators can be parsed.", preprocessedExpression); throw new ParserException (message, ex); } } /// <summary> /// Infers the associated identifier for the source expression node contained in methodCallExpression.Arguments[0]. For example, for the /// call chain "<c>source.Where (i => i > 5)</c>" (which actually reads "<c>Where (source, i => i > 5</c>"), the identifier "i" is associated /// with the node generated for "source". If no identifier can be inferred, <see langword="null"/> is returned. /// </summary> private string InferAssociatedIdentifierForSource (MethodCallExpression methodCallExpression) { var lambdaExpression = GetLambdaArgument (methodCallExpression); if (lambdaExpression != null && lambdaExpression.Parameters.Count == 1) return lambdaExpression.Parameters[0].Name; else return null; } private LambdaExpression GetLambdaArgument (MethodCallExpression methodCallExpression) { return methodCallExpression.Arguments .Select (argument => GetLambdaExpression (argument)) .FirstOrDefault (lambdaExpression => lambdaExpression != null); } private LambdaExpression GetLambdaExpression (Expression expression) { var lambdaExpression = expression as LambdaExpression; if (lambdaExpression != null) return lambdaExpression; else { var unaryExpression = expression as UnaryExpression; if (unaryExpression != null) return unaryExpression.Operand as LambdaExpression; else return null; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Globalization; namespace System.Numerics { /// <summary> /// A structure encapsulating a 3x2 matrix. /// </summary> public struct Matrix3x2 : IEquatable<Matrix3x2> { #region Public Fields /// <summary> /// The first element of the first row /// </summary> public float M11; /// <summary> /// The second element of the first row /// </summary> public float M12; /// <summary> /// The first element of the second row /// </summary> public float M21; /// <summary> /// The second element of the second row /// </summary> public float M22; /// <summary> /// The first element of the third row /// </summary> public float M31; /// <summary> /// The second element of the third row /// </summary> public float M32; #endregion Public Fields private static readonly Matrix3x2 _identity = new Matrix3x2 ( 1f, 0f, 0f, 1f, 0f, 0f ); /// <summary> /// Returns the multiplicative identity matrix. /// </summary> public static Matrix3x2 Identity { get { return _identity; } } /// <summary> /// Returns whether the matrix is the identity matrix. /// </summary> public bool IsIdentity { get { return M11 == 1f && M22 == 1f && // Check diagonal element first for early out. M12 == 0f && M21 == 0f && M31 == 0f && M32 == 0f; } } /// <summary> /// Gets or sets the translation component of this matrix. /// </summary> public Vector2 Translation { get { return new Vector2(M31, M32); } set { M31 = value.X; M32 = value.Y; } } /// <summary> /// Constructs a Matrix3x2 from the given components. /// </summary> public Matrix3x2(float m11, float m12, float m21, float m22, float m31, float m32) { this.M11 = m11; this.M12 = m12; this.M21 = m21; this.M22 = m22; this.M31 = m31; this.M32 = m32; } /// <summary> /// Creates a translation matrix from the given vector. /// </summary> /// <param name="position">The translation position.</param> /// <returns>A translation matrix.</returns> public static Matrix3x2 CreateTranslation(Vector2 position) { Matrix3x2 result; result.M11 = 1.0f; result.M12 = 0.0f; result.M21 = 0.0f; result.M22 = 1.0f; result.M31 = position.X; result.M32 = position.Y; return result; } /// <summary> /// Creates a translation matrix from the given X and Y components. /// </summary> /// <param name="xPosition">The X position.</param> /// <param name="yPosition">The Y position.</param> /// <returns>A translation matrix.</returns> public static Matrix3x2 CreateTranslation(float xPosition, float yPosition) { Matrix3x2 result; result.M11 = 1.0f; result.M12 = 0.0f; result.M21 = 0.0f; result.M22 = 1.0f; result.M31 = xPosition; result.M32 = yPosition; return result; } /// <summary> /// Creates a scale matrix from the given X and Y components. /// </summary> /// <param name="xScale">Value to scale by on the X-axis.</param> /// <param name="yScale">Value to scale by on the Y-axis.</param> /// <returns>A scaling matrix.</returns> public static Matrix3x2 CreateScale(float xScale, float yScale) { Matrix3x2 result; result.M11 = xScale; result.M12 = 0.0f; result.M21 = 0.0f; result.M22 = yScale; result.M31 = 0.0f; result.M32 = 0.0f; return result; } /// <summary> /// Creates a scale matrix that is offset by a given center point. /// </summary> /// <param name="xScale">Value to scale by on the X-axis.</param> /// <param name="yScale">Value to scale by on the Y-axis.</param> /// <param name="centerPoint">The center point.</param> /// <returns>A scaling matrix.</returns> public static Matrix3x2 CreateScale(float xScale, float yScale, Vector2 centerPoint) { Matrix3x2 result; float tx = centerPoint.X * (1 - xScale); float ty = centerPoint.Y * (1 - yScale); result.M11 = xScale; result.M12 = 0.0f; result.M21 = 0.0f; result.M22 = yScale; result.M31 = tx; result.M32 = ty; return result; } /// <summary> /// Creates a scale matrix from the given vector scale. /// </summary> /// <param name="scales">The scale to use.</param> /// <returns>A scaling matrix.</returns> public static Matrix3x2 CreateScale(Vector2 scales) { Matrix3x2 result; result.M11 = scales.X; result.M12 = 0.0f; result.M21 = 0.0f; result.M22 = scales.Y; result.M31 = 0.0f; result.M32 = 0.0f; return result; } /// <summary> /// Creates a scale matrix from the given vector scale with an offset from the given center point. /// </summary> /// <param name="scales">The scale to use.</param> /// <param name="centerPoint">The center offset.</param> /// <returns>A scaling matrix.</returns> public static Matrix3x2 CreateScale(Vector2 scales, Vector2 centerPoint) { Matrix3x2 result; float tx = centerPoint.X * (1 - scales.X); float ty = centerPoint.Y * (1 - scales.Y); result.M11 = scales.X; result.M12 = 0.0f; result.M21 = 0.0f; result.M22 = scales.Y; result.M31 = tx; result.M32 = ty; return result; } /// <summary> /// Creates a scale matrix that scales uniformly with the given scale. /// </summary> /// <param name="scale">The uniform scale to use.</param> /// <returns>A scaling matrix.</returns> public static Matrix3x2 CreateScale(float scale) { Matrix3x2 result; result.M11 = scale; result.M12 = 0.0f; result.M21 = 0.0f; result.M22 = scale; result.M31 = 0.0f; result.M32 = 0.0f; return result; } /// <summary> /// Creates a scale matrix that scales uniformly with the given scale with an offset from the given center. /// </summary> /// <param name="scale">The uniform scale to use.</param> /// <param name="centerPoint">The center offset.</param> /// <returns>A scaling matrix.</returns> public static Matrix3x2 CreateScale(float scale, Vector2 centerPoint) { Matrix3x2 result; float tx = centerPoint.X * (1 - scale); float ty = centerPoint.Y * (1 - scale); result.M11 = scale; result.M12 = 0.0f; result.M21 = 0.0f; result.M22 = scale; result.M31 = tx; result.M32 = ty; return result; } /// <summary> /// Creates a skew matrix from the given angles in radians. /// </summary> /// <param name="radiansX">The X angle, in radians.</param> /// <param name="radiansY">The Y angle, in radians.</param> /// <returns>A skew matrix.</returns> public static Matrix3x2 CreateSkew(float radiansX, float radiansY) { Matrix3x2 result; float xTan = (float)Math.Tan(radiansX); float yTan = (float)Math.Tan(radiansY); result.M11 = 1.0f; result.M12 = yTan; result.M21 = xTan; result.M22 = 1.0f; result.M31 = 0.0f; result.M32 = 0.0f; return result; } /// <summary> /// Creates a skew matrix from the given angles in radians and a center point. /// </summary> /// <param name="radiansX">The X angle, in radians.</param> /// <param name="radiansY">The Y angle, in radians.</param> /// <param name="centerPoint">The center point.</param> /// <returns>A skew matrix.</returns> public static Matrix3x2 CreateSkew(float radiansX, float radiansY, Vector2 centerPoint) { Matrix3x2 result; float xTan = (float)Math.Tan(radiansX); float yTan = (float)Math.Tan(radiansY); float tx = -centerPoint.Y * xTan; float ty = -centerPoint.X * yTan; result.M11 = 1.0f; result.M12 = yTan; result.M21 = xTan; result.M22 = 1.0f; result.M31 = tx; result.M32 = ty; return result; } /// <summary> /// Creates a rotation matrix using the given rotation in radians. /// </summary> /// <param name="radians">The amount of rotation, in radians.</param> /// <returns>A rotation matrix.</returns> public static Matrix3x2 CreateRotation(float radians) { Matrix3x2 result; radians = (float)Math.IEEERemainder(radians, Math.PI * 2); float c, s; const float epsilon = 0.001f * (float)Math.PI / 180f; // 0.1% of a degree if (radians > -epsilon && radians < epsilon) { // Exact case for zero rotation. c = 1; s = 0; } else if (radians > Math.PI / 2 - epsilon && radians < Math.PI / 2 + epsilon) { // Exact case for 90 degree rotation. c = 0; s = 1; } else if (radians < -Math.PI + epsilon || radians > Math.PI - epsilon) { // Exact case for 180 degree rotation. c = -1; s = 0; } else if (radians > -Math.PI / 2 - epsilon && radians < -Math.PI / 2 + epsilon) { // Exact case for 270 degree rotation. c = 0; s = -1; } else { // Arbitrary rotation. c = (float)Math.Cos(radians); s = (float)Math.Sin(radians); } // [ c s ] // [ -s c ] // [ 0 0 ] result.M11 = c; result.M12 = s; result.M21 = -s; result.M22 = c; result.M31 = 0.0f; result.M32 = 0.0f; return result; } /// <summary> /// Creates a rotation matrix using the given rotation in radians and a center point. /// </summary> /// <param name="radians">The amount of rotation, in radians.</param> /// <param name="centerPoint">The center point.</param> /// <returns>A rotation matrix.</returns> public static Matrix3x2 CreateRotation(float radians, Vector2 centerPoint) { Matrix3x2 result; radians = (float)Math.IEEERemainder(radians, Math.PI * 2); float c, s; const float epsilon = 0.001f * (float)Math.PI / 180f; // 0.1% of a degree if (radians > -epsilon && radians < epsilon) { // Exact case for zero rotation. c = 1; s = 0; } else if (radians > Math.PI / 2 - epsilon && radians < Math.PI / 2 + epsilon) { // Exact case for 90 degree rotation. c = 0; s = 1; } else if (radians < -Math.PI + epsilon || radians > Math.PI - epsilon) { // Exact case for 180 degree rotation. c = -1; s = 0; } else if (radians > -Math.PI / 2 - epsilon && radians < -Math.PI / 2 + epsilon) { // Exact case for 270 degree rotation. c = 0; s = -1; } else { // Arbitrary rotation. c = (float)Math.Cos(radians); s = (float)Math.Sin(radians); } float x = centerPoint.X * (1 - c) + centerPoint.Y * s; float y = centerPoint.Y * (1 - c) - centerPoint.X * s; // [ c s ] // [ -s c ] // [ x y ] result.M11 = c; result.M12 = s; result.M21 = -s; result.M22 = c; result.M31 = x; result.M32 = y; return result; } /// <summary> /// Calculates the determinant for this matrix. /// The determinant is calculated by expanding the matrix with a third column whose values are (0,0,1). /// </summary> /// <returns>The determinant.</returns> public float GetDeterminant() { // There isn't actually any such thing as a determinant for a non-square matrix, // but this 3x2 type is really just an optimization of a 3x3 where we happen to // know the rightmost column is always (0, 0, 1). So we expand to 3x3 format: // // [ M11, M12, 0 ] // [ M21, M22, 0 ] // [ M31, M32, 1 ] // // Sum the diagonal products: // (M11 * M22 * 1) + (M12 * 0 * M31) + (0 * M21 * M32) // // Subtract the opposite diagonal products: // (M31 * M22 * 0) + (M32 * 0 * M11) + (1 * M21 * M12) // // Collapse out the constants and oh look, this is just a 2x2 determinant! return (M11 * M22) - (M21 * M12); } /// <summary> /// Attempts to invert the given matrix. If the operation succeeds, the inverted matrix is stored in the result parameter. /// </summary> /// <param name="matrix">The source matrix.</param> /// <param name="result">The output matrix.</param> /// <returns>True if the operation succeeded, False otherwise.</returns> public static bool Invert(Matrix3x2 matrix, out Matrix3x2 result) { float det = (matrix.M11 * matrix.M22) - (matrix.M21 * matrix.M12); if (Math.Abs(det) < float.Epsilon) { result = new Matrix3x2(float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN); return false; } float invDet = 1.0f / det; result.M11 = matrix.M22 * invDet; result.M12 = -matrix.M12 * invDet; result.M21 = -matrix.M21 * invDet; result.M22 = matrix.M11 * invDet; result.M31 = (matrix.M21 * matrix.M32 - matrix.M31 * matrix.M22) * invDet; result.M32 = (matrix.M31 * matrix.M12 - matrix.M11 * matrix.M32) * invDet; return true; } /// <summary> /// Linearly interpolates from matrix1 to matrix2, based on the third parameter. /// </summary> /// <param name="matrix1">The first source matrix.</param> /// <param name="matrix2">The second source matrix.</param> /// <param name="amount">The relative weighting of matrix2.</param> /// <returns>The interpolated matrix.</returns> public static Matrix3x2 Lerp(Matrix3x2 matrix1, Matrix3x2 matrix2, float amount) { Matrix3x2 result; // First row result.M11 = matrix1.M11 + (matrix2.M11 - matrix1.M11) * amount; result.M12 = matrix1.M12 + (matrix2.M12 - matrix1.M12) * amount; // Second row result.M21 = matrix1.M21 + (matrix2.M21 - matrix1.M21) * amount; result.M22 = matrix1.M22 + (matrix2.M22 - matrix1.M22) * amount; // Third row result.M31 = matrix1.M31 + (matrix2.M31 - matrix1.M31) * amount; result.M32 = matrix1.M32 + (matrix2.M32 - matrix1.M32) * amount; return result; } /// <summary> /// Negates the given matrix by multiplying all values by -1. /// </summary> /// <param name="value">The source matrix.</param> /// <returns>The negated matrix.</returns> public static Matrix3x2 Negate(Matrix3x2 value) { Matrix3x2 result; result.M11 = -value.M11; result.M12 = -value.M12; result.M21 = -value.M21; result.M22 = -value.M22; result.M31 = -value.M31; result.M32 = -value.M32; return result; } /// <summary> /// Adds each matrix element in value1 with its corresponding element in value2. /// </summary> /// <param name="value1">The first source matrix.</param> /// <param name="value2">The second source matrix.</param> /// <returns>The matrix containing the summed values.</returns> public static Matrix3x2 Add(Matrix3x2 value1, Matrix3x2 value2) { Matrix3x2 result; result.M11 = value1.M11 + value2.M11; result.M12 = value1.M12 + value2.M12; result.M21 = value1.M21 + value2.M21; result.M22 = value1.M22 + value2.M22; result.M31 = value1.M31 + value2.M31; result.M32 = value1.M32 + value2.M32; return result; } /// <summary> /// Subtracts each matrix element in value2 from its corresponding element in value1. /// </summary> /// <param name="value1">The first source matrix.</param> /// <param name="value2">The second source matrix.</param> /// <returns>The matrix containing the resulting values.</returns> public static Matrix3x2 Subtract(Matrix3x2 value1, Matrix3x2 value2) { Matrix3x2 result; result.M11 = value1.M11 - value2.M11; result.M12 = value1.M12 - value2.M12; result.M21 = value1.M21 - value2.M21; result.M22 = value1.M22 - value2.M22; result.M31 = value1.M31 - value2.M31; result.M32 = value1.M32 - value2.M32; return result; } /// <summary> /// Multiplies two matrices together and returns the resulting matrix. /// </summary> /// <param name="value1">The first source matrix.</param> /// <param name="value2">The second source matrix.</param> /// <returns>The product matrix.</returns> public static Matrix3x2 Multiply(Matrix3x2 value1, Matrix3x2 value2) { Matrix3x2 result; // First row result.M11 = value1.M11 * value2.M11 + value1.M12 * value2.M21; result.M12 = value1.M11 * value2.M12 + value1.M12 * value2.M22; // Second row result.M21 = value1.M21 * value2.M11 + value1.M22 * value2.M21; result.M22 = value1.M21 * value2.M12 + value1.M22 * value2.M22; // Third row result.M31 = value1.M31 * value2.M11 + value1.M32 * value2.M21 + value2.M31; result.M32 = value1.M31 * value2.M12 + value1.M32 * value2.M22 + value2.M32; return result; } /// <summary> /// Scales all elements in a matrix by the given scalar factor. /// </summary> /// <param name="value1">The source matrix.</param> /// <param name="value2">The scaling value to use.</param> /// <returns>The resulting matrix.</returns> public static Matrix3x2 Multiply(Matrix3x2 value1, float value2) { Matrix3x2 result; result.M11 = value1.M11 * value2; result.M12 = value1.M12 * value2; result.M21 = value1.M21 * value2; result.M22 = value1.M22 * value2; result.M31 = value1.M31 * value2; result.M32 = value1.M32 * value2; return result; } /// <summary> /// Negates the given matrix by multiplying all values by -1. /// </summary> /// <param name="value">The source matrix.</param> /// <returns>The negated matrix.</returns> public static Matrix3x2 operator -(Matrix3x2 value) { Matrix3x2 m; m.M11 = -value.M11; m.M12 = -value.M12; m.M21 = -value.M21; m.M22 = -value.M22; m.M31 = -value.M31; m.M32 = -value.M32; return m; } /// <summary> /// Adds each matrix element in value1 with its corresponding element in value2. /// </summary> /// <param name="value1">The first source matrix.</param> /// <param name="value2">The second source matrix.</param> /// <returns>The matrix containing the summed values.</returns> public static Matrix3x2 operator +(Matrix3x2 value1, Matrix3x2 value2) { Matrix3x2 m; m.M11 = value1.M11 + value2.M11; m.M12 = value1.M12 + value2.M12; m.M21 = value1.M21 + value2.M21; m.M22 = value1.M22 + value2.M22; m.M31 = value1.M31 + value2.M31; m.M32 = value1.M32 + value2.M32; return m; } /// <summary> /// Subtracts each matrix element in value2 from its corresponding element in value1. /// </summary> /// <param name="value1">The first source matrix.</param> /// <param name="value2">The second source matrix.</param> /// <returns>The matrix containing the resulting values.</returns> public static Matrix3x2 operator -(Matrix3x2 value1, Matrix3x2 value2) { Matrix3x2 m; m.M11 = value1.M11 - value2.M11; m.M12 = value1.M12 - value2.M12; m.M21 = value1.M21 - value2.M21; m.M22 = value1.M22 - value2.M22; m.M31 = value1.M31 - value2.M31; m.M32 = value1.M32 - value2.M32; return m; } /// <summary> /// Multiplies two matrices together and returns the resulting matrix. /// </summary> /// <param name="value1">The first source matrix.</param> /// <param name="value2">The second source matrix.</param> /// <returns>The product matrix.</returns> public static Matrix3x2 operator *(Matrix3x2 value1, Matrix3x2 value2) { Matrix3x2 m; // First row m.M11 = value1.M11 * value2.M11 + value1.M12 * value2.M21; m.M12 = value1.M11 * value2.M12 + value1.M12 * value2.M22; // Second row m.M21 = value1.M21 * value2.M11 + value1.M22 * value2.M21; m.M22 = value1.M21 * value2.M12 + value1.M22 * value2.M22; // Third row m.M31 = value1.M31 * value2.M11 + value1.M32 * value2.M21 + value2.M31; m.M32 = value1.M31 * value2.M12 + value1.M32 * value2.M22 + value2.M32; return m; } /// <summary> /// Scales all elements in a matrix by the given scalar factor. /// </summary> /// <param name="value1">The source matrix.</param> /// <param name="value2">The scaling value to use.</param> /// <returns>The resulting matrix.</returns> public static Matrix3x2 operator *(Matrix3x2 value1, float value2) { Matrix3x2 m; m.M11 = value1.M11 * value2; m.M12 = value1.M12 * value2; m.M21 = value1.M21 * value2; m.M22 = value1.M22 * value2; m.M31 = value1.M31 * value2; m.M32 = value1.M32 * value2; return m; } /// <summary> /// Returns a boolean indicating whether the given matrices are equal. /// </summary> /// <param name="value1">The first source matrix.</param> /// <param name="value2">The second source matrix.</param> /// <returns>True if the matrices are equal; False otherwise.</returns> public static bool operator ==(Matrix3x2 value1, Matrix3x2 value2) { return (value1.M11 == value2.M11 && value1.M22 == value2.M22 && // Check diagonal element first for early out. value1.M12 == value2.M12 && value1.M21 == value2.M21 && value1.M31 == value2.M31 && value1.M32 == value2.M32); } /// <summary> /// Returns a boolean indicating whether the given matrices are not equal. /// </summary> /// <param name="value1">The first source matrix.</param> /// <param name="value2">The second source matrix.</param> /// <returns>True if the matrices are not equal; False if they are equal.</returns> public static bool operator !=(Matrix3x2 value1, Matrix3x2 value2) { return (value1.M11 != value2.M11 || value1.M12 != value2.M12 || value1.M21 != value2.M21 || value1.M22 != value2.M22 || value1.M31 != value2.M31 || value1.M32 != value2.M32); } /// <summary> /// Returns a boolean indicating whether the matrix is equal to the other given matrix. /// </summary> /// <param name="other">The other matrix to test equality against.</param> /// <returns>True if this matrix is equal to other; False otherwise.</returns> public bool Equals(Matrix3x2 other) { return (M11 == other.M11 && M22 == other.M22 && // Check diagonal element first for early out. M12 == other.M12 && M21 == other.M21 && M31 == other.M31 && M32 == other.M32); } /// <summary> /// Returns a boolean indicating whether the given Object is equal to this matrix instance. /// </summary> /// <param name="obj">The Object to compare against.</param> /// <returns>True if the Object is equal to this matrix; False otherwise.</returns> public override bool Equals(object obj) { if (obj is Matrix3x2) { return Equals((Matrix3x2)obj); } return false; } /// <summary> /// Returns a String representing this matrix instance. /// </summary> /// <returns>The string representation.</returns> public override string ToString() { CultureInfo ci = CultureInfo.CurrentCulture; return String.Format(ci, "{{ {{M11:{0} M12:{1}}} {{M21:{2} M22:{3}}} {{M31:{4} M32:{5}}} }}", M11.ToString(ci), M12.ToString(ci), M21.ToString(ci), M22.ToString(ci), M31.ToString(ci), M32.ToString(ci)); } /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { return M11.GetHashCode() + M12.GetHashCode() + M21.GetHashCode() + M22.GetHashCode() + M31.GetHashCode() + M32.GetHashCode(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.Remoting.Messaging; using System.Runtime.Serialization; using PSycheTest.Runners.Framework.Utilities.Reflection; using Xunit; using Xunit.Sdk; namespace Tests.Support { /// <summary> /// Contains custom assertions. /// </summary> public static class AssertThat { /// <summary> /// Verifies that the provided object raised INotifyPropertyChanged.PropertyChanged as a result of executing the given /// test code. /// </summary> /// <typeparam name="TDeclaring">The type of object declaring the property</typeparam> /// <typeparam name="TValue">The value of the property</typeparam> /// <param name="object">The object declaring the property</param> /// <param name="property">The property</param> /// <param name="testCode">The code that should change the property</param> public static void PropertyChanged<TDeclaring, TValue>(TDeclaring @object, Expression<Func<TDeclaring, TValue>> property, Assert.PropertyChangedDelegate testCode) where TDeclaring : INotifyPropertyChanged { Assert.PropertyChanged(@object, Reflect.PropertyOf(property).Name, testCode); } /// <summary> /// Verifies that the provided object did not raise INotifyPropertyChanged.PropertyChanged as a result of executing the given /// test code. /// </summary> /// <typeparam name="TDeclaring">The type of object declaring the property</typeparam> /// <typeparam name="TValue">The value of the property</typeparam> /// <param name="object">The object declaring the property</param> /// <param name="property">The property</param> /// <param name="testCode">The code that should not change the property</param> public static void PropertyDoesNotChange<TDeclaring, TValue>(TDeclaring @object, Expression<Func<TDeclaring, TValue>> property, Assert.PropertyChangedDelegate testCode) where TDeclaring : INotifyPropertyChanged { object sender = null; PropertyChangedEventArgs args = null; PropertyChangedEventHandler handler = (o, e) => { sender = o; args = e; }; try { @object.PropertyChanged += handler; testCode(); } finally { @object.PropertyChanged -= handler; } if (args != null && ReferenceEquals(sender, @object)) { string propertyName = Reflect.PropertyOf(property).Name; if (args.PropertyName == propertyName) { throw new PropertyDoesNotChangeException(propertyName); } } } /// <summary> /// Determines whether two sequences are equal by comparing length and element equality. /// The type of element's default equality comparer is used. /// </summary> /// <typeparam name="T">The type of elements in the sequences</typeparam> /// <param name="expected">The expected sequence</param> /// <param name="actual">The actual sequence</param> public static void SequenceEqual<T>(IEnumerable<T> expected, IEnumerable<T> actual) { SequenceEqual(expected, actual, EqualityComparer<T>.Default); } /// <summary> /// Determines whether two sequences are equal by comparing length and element equality. /// </summary> /// <typeparam name="T">The type of elements in the sequences</typeparam> /// <param name="expected">The expected sequence</param> /// <param name="actual">The actual sequence</param> /// <param name="equalityComparer">The equality comparer to use for element equality. If null, the default for the type is used</param> public static void SequenceEqual<T>(IEnumerable<T> expected, IEnumerable<T> actual, IEqualityComparer<T> equalityComparer) { IEqualityComparer<T> actualComparer = equalityComparer ?? EqualityComparer<T>.Default; // Cache the sequences so that they are not re-evaluated. ICollection<T> expectedBuffer = new List<T>(); ICollection<T> actualBuffer = new List<T>(); using (var expectedEnumerator = expected.GetEnumerator()) using (var actualEnumerator = actual.GetEnumerator()) { while (true) { bool expectedHasNext = expectedEnumerator.MoveNext(); T expectedElement = default(T); if (expectedHasNext) { expectedElement = expectedEnumerator.Current; expectedBuffer.Add(expectedElement); } bool actualHasNext = actualEnumerator.MoveNext(); T actualElement = default(T); if (actualHasNext) { actualElement = actualEnumerator.Current; actualBuffer.Add(actualElement); } if (expectedHasNext != actualHasNext) throw new SequenceEqualException(expectedBuffer, !expectedEnumerator.MoveNext(), actualBuffer, !actualEnumerator.MoveNext()); if (!actualHasNext || !expectedHasNext) break; if (!actualComparer.Equals(actualElement, expectedElement)) throw new SequenceEqualException(expectedBuffer, !expectedEnumerator.MoveNext(), actualBuffer, !actualEnumerator.MoveNext()); } } } /// <summary> /// Asserts that the given event is raised. /// </summary> /// <param name="target">The object raising the event</param> /// <param name="subscriber">An action adding or removing a null handler from the target event</param> /// <param name="eventDelegate">The delegate to invoke which should trigger the event</param> public static void Raises<T>(T target, Action<T> subscriber, EventDelegate eventDelegate) { Raises(target, subscriber, eventDelegate, true); } /// <summary> /// Asserts that the given event is not raised. /// </summary> /// <param name="target">The object raising the event</param> /// <param name="subscriber">An action adding or removing a null handler from the target event</param> /// <param name="eventDelegate">The delegate to invoke which shouldn't trigger the event</param> public static void DoesNotRaise<T>(T target, Action<T> subscriber, EventDelegate eventDelegate) { Raises(target, subscriber, eventDelegate, false); } /// <summary> /// Asserts that an event is raised and returns the event arguments. /// </summary> /// <typeparam name="TTarget">The type of the target object</typeparam> /// <typeparam name="TArgs">The event argument type, must be of type EventArgs</typeparam> /// <param name="target">The object raising the event</param> /// <param name="subscriber">An action adding or removing a null handler from the target event</param> /// <param name="eventDelegate">The delegate to invoke which should trigger the event</param> /// <returns>The captured event args of the event if it is successfully raised</returns> public static TArgs RaisesWithEventArgs<TTarget, TArgs>(TTarget target, Action<TTarget> subscriber, EventDelegate eventDelegate) where TArgs : EventArgs { EventProxy proxy = Raises(target, subscriber, eventDelegate, true); return (TArgs)proxy.ArgsReceived; } private static EventProxy Raises<T>(T target, Action<T> subscriber, EventDelegate eventDelegate, bool expectEventReceived) { EventInfo eventInfo = ExtractEvent(subscriber, target); EventProxy proxy = InternalRaises(target, eventInfo, eventDelegate); if (expectEventReceived != proxy.EventReceived) throw new RaisesException(typeof(T), eventInfo.Name, expectEventReceived, proxy.EventReceived); return proxy; } private static EventInfo ExtractEvent<T>(Action<T> eventAccessor, T target) { var recorder = new MethodRecorder<T>(); eventAccessor(recorder.Proxy); IMethodCallMessage eventMember = recorder.LastInvocation; if (!(eventMember.MethodName.StartsWith("add_") || eventMember.MethodName.StartsWith("remove_"))) throw new ArgumentException(@"Invocation must be an event subscription or unsubscription", "eventAccessor"); string eventName = eventMember.MethodName.Replace("add_", string.Empty).Replace("remove_", string.Empty); EventInfo eventInfo = typeof(T).GetEvent(eventName); return eventInfo; } /// <summary> /// Asserts that the given event is raised. /// </summary> /// <param name="target">The object raising the event</param> /// <param name="eventName">The name of the event</param> /// <param name="eventDelegate">The delegate to invoke which should trigger the event</param> public static void Raises(object target, string eventName, EventDelegate eventDelegate) { Raises(target, eventName, eventDelegate, true); } /// <summary> /// Asserts that the given event is not raised. /// </summary> /// <param name="target">The object raising the event</param> /// <param name="eventName">The name of the event</param> /// <param name="eventDelegate">The delegate to invoke which shouldn't trigger the event</param> public static void DoesNotRaise(object target, string eventName, EventDelegate eventDelegate) { Raises(target, eventName, eventDelegate, false); } /// <summary> /// Asserts that an event is raised and returns the event arguments. /// </summary> /// <typeparam name="TArgs">The event argument type, must be of type EventArgs</typeparam> /// <param name="target">The object raising the event</param> /// <param name="eventName">The name of the event</param> /// <param name="eventDelegate">The delegate to invoke which should trigger the event</param> /// <returns>The captured event args of the event if it is successfully raised</returns> public static TArgs RaisesWithEventArgs<TArgs>(object target, string eventName, EventDelegate eventDelegate) where TArgs : EventArgs { EventProxy proxy = Raises(target, eventName, eventDelegate, true); return (TArgs)proxy.ArgsReceived; } private static EventProxy Raises(object target, string eventName, EventDelegate eventDelegate, bool expectEventReceived) { Type targetType = target.GetType(); EventInfo eventInfo = targetType.GetEvent(eventName); EventProxy proxy = InternalRaises(target, eventInfo, eventDelegate); if (expectEventReceived != proxy.EventReceived) throw new RaisesException(targetType, eventName, expectEventReceived, proxy.EventReceived); return proxy; } private static EventProxy InternalRaises<T>(T target, EventInfo eventInfo, EventDelegate eventDelegate) { // this method to dynamically subscribe for events was taken from // http://www.codeproject.com/KB/cs/eventtracingviareflection.aspx EventProxy proxy = new EventProxy(); Delegate d = Delegate.CreateDelegate(eventInfo.EventHandlerType, proxy, EventProxy.Handler); eventInfo.AddEventHandler(target, d); eventDelegate.DynamicInvoke(); eventInfo.RemoveEventHandler(target, d); return proxy; } public delegate void EventDelegate(); private class EventProxy { public void OnEvent(object sender, EventArgs e) { EventReceived = true; ArgsReceived = e; } public bool EventReceived { get; private set; } public EventArgs ArgsReceived { get; private set; } public static readonly MethodInfo Handler = Reflect.MethodOf<EventProxy>(ep => ep.OnEvent(null, null)); } } /// <summary> /// Exception raised when an assertion about the raising of an event is not met. /// </summary> public class RaisesException : AssertException { /// <summary> /// Creates a new instance of the <see cref="RaisesException"/> class. /// </summary> /// <param name="eventOwner">The type of object owning the event</param> /// <param name="eventName">The name of the event</param> /// <param name="shouldHaveBeenRaised">Whether the event should have been raised</param> /// <param name="wasRaised">Whether the event was raised</param> public RaisesException(Type eventOwner, string eventName, bool shouldHaveBeenRaised, bool wasRaised) : base(typeof(RaisesException).Name + " : Event Assertion Failure") { EventOwner = eventOwner; EventName = eventName; ShouldHaveBeenRaised = shouldHaveBeenRaised; WasRaised = wasRaised; } /// <summary> /// The type of object owning the event. /// </summary> public Type EventOwner { get; private set; } /// <summary> /// The name of the event. /// </summary> public string EventName { get; private set; } /// <summary> /// Whether the event should have been raised. /// </summary> public bool ShouldHaveBeenRaised { get; private set; } /// <summary> /// Whether the event was raised. /// </summary> public bool WasRaised { get; private set; } /// <summary> /// Gets a message that describes the current exception. /// </summary> /// <returns>The error message that explains the reason for the exception, or an empty string("").</returns> public override string Message { get { return String.Format("{0}{1}The event {2} {3} when {4}.", base.Message, Environment.NewLine, EventName, WasRaised ? "was raised" : "was not raised", ShouldHaveBeenRaised ? "expected" : "not expected"); } } } /// <summary> /// Exceptions thrown when a SequenceEqual assertion fails. /// </summary> public class SequenceEqualException : AssertException { /// <summary> /// Creates a new instance of the <see cref="SequenceEqualException"/> class. /// </summary> /// <param name="expected">The expected sequence</param> /// <param name="expectedFullyDrained">Whether the entirety of the expected sequence was evaluated</param> /// <param name="actual">The actual sequence</param> /// <param name="actualFullyDrained">Whether the entirety of the actual sequence was evaluated</param> public SequenceEqualException(IEnumerable expected, bool expectedFullyDrained, IEnumerable actual, bool actualFullyDrained) : base(typeof(SequenceEqualException).Name + " : SequenceEqual Assertion Failure") { _expected = expected; _actual = actual; _expectedFullyDrained = expectedFullyDrained; _actualFullyDrained = actualFullyDrained; Actual = String.Join(",", _actual.Cast<object>()); Expected = String.Join(",", _expected.Cast<object>()); } /// <summary> /// Gets the actual sequence. /// </summary> public string Actual { get; private set; } /// <summary> /// Gets the expected sequence. /// </summary> public string Expected { get; private set; } /// <summary> /// Gets a message that describes the current exception. /// </summary> /// <returns>The error message that explains the reason for the exception, or an empty string("").</returns> public override string Message { get { return String.Format("{0}{1}Expected: {2}{3}{1}Actual: {4}{5}", base.Message, Environment.NewLine, Expected == string.Empty ? EMPTY_COLLECTION_MESSAGE : Expected, _expectedFullyDrained ? string.Empty : ",...", Actual == string.Empty ? EMPTY_COLLECTION_MESSAGE : Actual, _actualFullyDrained ? string.Empty : ",..."); } } private readonly IEnumerable _expected; private readonly IEnumerable _actual; private readonly bool _expectedFullyDrained; private readonly bool _actualFullyDrained; private const string EMPTY_COLLECTION_MESSAGE = "Empty Sequence"; } /// <summary> /// Exception thrown when code unexpectedly changes a property. /// </summary> [Serializable] public class PropertyDoesNotChangeException : AssertException { /// <summary> /// Creates a new instance of the <see cref="T:Tests.Support.PropertyDoesNotChangeException"/> class. /// </summary> /// <param name="propertyName">The name of the property that should not have changed.</param> public PropertyDoesNotChangeException(string propertyName) : base(String.Format("PropertyDoesNotChange assertion failure: PropertyChanged event for property {0} was raised", propertyName)) { } /// <inheritdoc/> protected PropertyDoesNotChangeException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
namespace ZetaResourceEditor.UI.Main.LeftTree { partial class ProjectFilesUserControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose( bool disposing ) { if ( disposing && (components != null) ) { components.Dispose(); } base.Dispose( disposing ); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ProjectFilesUserControl)); this.treeView = new ZetaResourceEditor.UI.Helper.ZetaResourceEditorTreeListControl(); this.treeListColumn1 = new DevExpress.XtraTreeList.Columns.TreeListColumn(); this.treeImageList = new DevExpress.Utils.ImageCollection(this.components); this.stateImageList = new DevExpress.Utils.ImageCollection(this.components); this.toolTipController1 = new DevExpress.Utils.ToolTipController(this.components); this.barDockControlTop = new DevExpress.XtraBars.BarDockControl(); this.barManager = new DevExpress.XtraBars.BarManager(this.components); this.barDockControlBottom = new DevExpress.XtraBars.BarDockControl(); this.barDockControlLeft = new DevExpress.XtraBars.BarDockControl(); this.barDockControlRight = new DevExpress.XtraBars.BarDockControl(); this.buttonMenuProjectEditResourceFiles = new DevExpress.XtraBars.BarButtonItem(); this.buttonMenuProjectAutomaticallyAddMultipleFileGroupsToProject = new DevExpress.XtraBars.BarButtonItem(); this.buttonMenuProjectAddFileGroupToProject = new DevExpress.XtraBars.BarButtonItem(); this.buttonMenuProjectRemoveFileGroupFromProject = new DevExpress.XtraBars.BarButtonItem(); this.buttonMenuProjectEditFileGroupSettings = new DevExpress.XtraBars.BarButtonItem(); this.buttonMenuProjectAddFilesToFileGroup = new DevExpress.XtraBars.BarButtonItem(); this.buttonMenuProjectRemoveFileFromFileGroup = new DevExpress.XtraBars.BarButtonItem(); this.buttonMenuProjectEditProjectSettings = new DevExpress.XtraBars.BarButtonItem(); this.buttonMenuProjectAddProjectFolder = new DevExpress.XtraBars.BarButtonItem(); this.buttonMenuProjectRemoveProjectFolder = new DevExpress.XtraBars.BarButtonItem(); this.buttonMenuProjectEditProjectFolder = new DevExpress.XtraBars.BarButtonItem(); this.buttonMenuProjectMoveUp = new DevExpress.XtraBars.BarButtonItem(); this.buttonMenuProjectMoveDown = new DevExpress.XtraBars.BarButtonItem(); this.buttonMenuProjectCreateNewFile = new DevExpress.XtraBars.BarButtonItem(); this.buttonMenuProjectCreateNewFiles = new DevExpress.XtraBars.BarButtonItem(); this.buttonMenuProjectAutomaticallyAddFileGroupsFromVisualStudioSolution = new DevExpress.XtraBars.BarButtonItem(); this.buttonOpenProjectMenuItem = new DevExpress.XtraBars.BarButtonItem(); this.buttonSortProjectFolderChildrenAscendingAZ = new DevExpress.XtraBars.BarButtonItem(); this.buttonSortChildrenProjectAZ = new DevExpress.XtraBars.BarButtonItem(); this.buttonMenuProjectFolderAddFileGroupToProject = new DevExpress.XtraBars.BarButtonItem(); this.buttonMenuProjectAddNewFileGroupToProject = new DevExpress.XtraBars.BarButtonItem(); this.buttonMenuProjectDeleteExistingLanguage = new DevExpress.XtraBars.BarButtonItem(); this.buttonMenuProjectDeleteLanguages = new DevExpress.XtraBars.BarButtonItem(); this.buttonMergeIntoFileGroup = new DevExpress.XtraBars.BarButtonItem(); this.guiRefreshTimer = new System.Windows.Forms.Timer(this.components); this.popupMenuProject = new DevExpress.XtraBars.PopupMenu(this.components); this.popupMenuProjectFolder = new DevExpress.XtraBars.PopupMenu(this.components); this.popupMenuFileGroup = new DevExpress.XtraBars.PopupMenu(this.components); this.popupMenuFile = new DevExpress.XtraBars.PopupMenu(this.components); this.popupMenuNone = new DevExpress.XtraBars.PopupMenu(this.components); this.updateNodeStateImageBackgroundworker = new System.ComponentModel.BackgroundWorker(); ((System.ComponentModel.ISupportInitialize)(this.treeView)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.treeImageList)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.stateImageList)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.barManager)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.popupMenuProject)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.popupMenuProjectFolder)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.popupMenuFileGroup)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.popupMenuFile)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.popupMenuNone)).BeginInit(); this.SuspendLayout(); // // treeView // this.treeView.Columns.AddRange(new DevExpress.XtraTreeList.Columns.TreeListColumn[] { this.treeListColumn1}); this.treeView.Dock = System.Windows.Forms.DockStyle.Fill; this.treeView.EmptyText = "No items"; this.treeView.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel); this.treeView.Location = new System.Drawing.Point(0, 0); this.treeView.Name = "treeView"; this.treeView.OptionsBehavior.AllowExpandOnDblClick = false; this.treeView.OptionsBehavior.AllowIncrementalSearch = true; this.treeView.OptionsBehavior.ImmediateEditor = false; this.treeView.OptionsDragAndDrop.DragNodesMode = DevExpress.XtraTreeList.DragNodesMode.Single; this.treeView.OptionsSelection.EnableAppearanceFocusedCell = false; this.treeView.OptionsView.FocusRectStyle = DevExpress.XtraTreeList.DrawFocusRectStyle.None; this.treeView.OptionsView.ShowColumns = false; this.treeView.OptionsView.ShowHorzLines = false; this.treeView.OptionsView.ShowIndicator = false; this.treeView.OptionsView.ShowRoot = false; this.treeView.OptionsView.ShowVertLines = false; this.treeView.SelectedNode = null; this.treeView.SelectImageList = this.treeImageList; this.treeView.Size = new System.Drawing.Size(201, 434); this.treeView.StateImageList = this.stateImageList; this.treeView.TabIndex = 1; this.treeView.ToolTipController = this.toolTipController1; this.treeView.WasDoubleClick = false; this.treeView.NodeCellStyle += new DevExpress.XtraTreeList.GetCustomNodeCellStyleEventHandler(this.treeView_NodeCellStyle); this.treeView.BeforeExpand += new DevExpress.XtraTreeList.BeforeExpandEventHandler(this.treeView_BeforeExpand); this.treeView.BeforeCollapse += new DevExpress.XtraTreeList.BeforeCollapseEventHandler(this.treeView_BeforeCollapse); this.treeView.CompareNodeValues += new DevExpress.XtraTreeList.CompareNodeValuesEventHandler(this.treeView_CompareNodeValues); this.treeView.CalcNodeDragImageIndex += new DevExpress.XtraTreeList.CalcNodeDragImageIndexEventHandler(this.treeView_CalcNodeDragImageIndex); this.treeView.DragDrop += new System.Windows.Forms.DragEventHandler(this.treeView_DragDrop); this.treeView.DragOver += new System.Windows.Forms.DragEventHandler(this.treeView_DragOver); this.treeView.DoubleClick += new System.EventHandler(this.treeView_DoubleClick); this.treeView.KeyDown += new System.Windows.Forms.KeyEventHandler(this.treeView_KeyDown); this.treeView.MouseUp += new System.Windows.Forms.MouseEventHandler(this.treeView_MouseUp); // // treeListColumn1 // this.treeListColumn1.Caption = "Name"; this.treeListColumn1.FieldName = "Name"; this.treeListColumn1.MinWidth = 52; this.treeListColumn1.Name = "treeListColumn1"; this.treeListColumn1.OptionsColumn.AllowEdit = false; this.treeListColumn1.OptionsColumn.AllowMove = false; this.treeListColumn1.OptionsColumn.AllowSort = false; this.treeListColumn1.OptionsColumn.ReadOnly = true; this.treeListColumn1.Visible = true; this.treeListColumn1.VisibleIndex = 0; this.treeListColumn1.Width = 108; // // treeImageList // this.treeImageList.ImageStream = ((DevExpress.Utils.ImageCollectionStreamer)(resources.GetObject("treeImageList.ImageStream"))); this.treeImageList.Images.SetKeyName(0, "root"); this.treeImageList.Images.SetKeyName(1, "group"); this.treeImageList.Images.SetKeyName(2, "file"); this.treeImageList.Images.SetKeyName(3, "projectfolder"); // // stateImageList // this.stateImageList.ImageStream = ((DevExpress.Utils.ImageCollectionStreamer)(resources.GetObject("stateImageList.ImageStream"))); this.stateImageList.Images.SetKeyName(0, "grey"); this.stateImageList.Images.SetKeyName(1, "green"); this.stateImageList.Images.SetKeyName(2, "yellow"); this.stateImageList.Images.SetKeyName(3, "red"); this.stateImageList.Images.SetKeyName(4, "blue"); // // toolTipController1 // this.toolTipController1.GetActiveObjectInfo += new DevExpress.Utils.ToolTipControllerGetActiveObjectInfoEventHandler(this.toolTipController1_GetActiveObjectInfo); // // barDockControlTop // this.barDockControlTop.CausesValidation = false; this.barDockControlTop.Dock = System.Windows.Forms.DockStyle.Top; this.barDockControlTop.Location = new System.Drawing.Point(0, 0); this.barDockControlTop.Manager = this.barManager; this.barDockControlTop.Size = new System.Drawing.Size(201, 0); // // barManager // this.barManager.DockControls.Add(this.barDockControlTop); this.barManager.DockControls.Add(this.barDockControlBottom); this.barManager.DockControls.Add(this.barDockControlLeft); this.barManager.DockControls.Add(this.barDockControlRight); this.barManager.Form = this; this.barManager.Items.AddRange(new DevExpress.XtraBars.BarItem[] { this.buttonMenuProjectEditResourceFiles, this.buttonMenuProjectAutomaticallyAddMultipleFileGroupsToProject, this.buttonMenuProjectAddFileGroupToProject, this.buttonMenuProjectRemoveFileGroupFromProject, this.buttonMenuProjectEditFileGroupSettings, this.buttonMenuProjectAddFilesToFileGroup, this.buttonMenuProjectRemoveFileFromFileGroup, this.buttonMenuProjectEditProjectSettings, this.buttonMenuProjectAddProjectFolder, this.buttonMenuProjectRemoveProjectFolder, this.buttonMenuProjectEditProjectFolder, this.buttonMenuProjectMoveUp, this.buttonMenuProjectMoveDown, this.buttonMenuProjectCreateNewFile, this.buttonMenuProjectCreateNewFiles, this.buttonMenuProjectAutomaticallyAddFileGroupsFromVisualStudioSolution, this.buttonOpenProjectMenuItem, this.buttonSortProjectFolderChildrenAscendingAZ, this.buttonSortChildrenProjectAZ, this.buttonMenuProjectFolderAddFileGroupToProject, this.buttonMenuProjectAddNewFileGroupToProject, this.buttonMenuProjectDeleteExistingLanguage, this.buttonMenuProjectDeleteLanguages, this.buttonMergeIntoFileGroup}); this.barManager.MaxItemId = 27; // // barDockControlBottom // this.barDockControlBottom.CausesValidation = false; this.barDockControlBottom.Dock = System.Windows.Forms.DockStyle.Bottom; this.barDockControlBottom.Location = new System.Drawing.Point(0, 434); this.barDockControlBottom.Manager = this.barManager; this.barDockControlBottom.Size = new System.Drawing.Size(201, 0); // // barDockControlLeft // this.barDockControlLeft.CausesValidation = false; this.barDockControlLeft.Dock = System.Windows.Forms.DockStyle.Left; this.barDockControlLeft.Location = new System.Drawing.Point(0, 0); this.barDockControlLeft.Manager = this.barManager; this.barDockControlLeft.Size = new System.Drawing.Size(0, 434); // // barDockControlRight // this.barDockControlRight.CausesValidation = false; this.barDockControlRight.Dock = System.Windows.Forms.DockStyle.Right; this.barDockControlRight.Location = new System.Drawing.Point(201, 0); this.barDockControlRight.Manager = this.barManager; this.barDockControlRight.Size = new System.Drawing.Size(0, 434); // // buttonMenuProjectEditResourceFiles // this.buttonMenuProjectEditResourceFiles.Caption = "Edit resource files"; this.buttonMenuProjectEditResourceFiles.Id = 3; this.buttonMenuProjectEditResourceFiles.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonMenuProjectEditResourceFiles.ImageOptions.Image"))); this.buttonMenuProjectEditResourceFiles.Name = "buttonMenuProjectEditResourceFiles"; this.buttonMenuProjectEditResourceFiles.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonEditResourceFiles_ItemClick); // // buttonMenuProjectAutomaticallyAddMultipleFileGroupsToProject // this.buttonMenuProjectAutomaticallyAddMultipleFileGroupsToProject.Caption = "Automatically add multiple file groups to project"; this.buttonMenuProjectAutomaticallyAddMultipleFileGroupsToProject.Id = 4; this.buttonMenuProjectAutomaticallyAddMultipleFileGroupsToProject.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonMenuProjectAutomaticallyAddMultipleFileGroupsToProject.ImageOptions.Image"))); this.buttonMenuProjectAutomaticallyAddMultipleFileGroupsToProject.Name = "buttonMenuProjectAutomaticallyAddMultipleFileGroupsToProject"; this.buttonMenuProjectAutomaticallyAddMultipleFileGroupsToProject.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonAutomaticallyAddMultipleFileGroupsToProject_ItemClick); // // buttonMenuProjectAddFileGroupToProject // this.buttonMenuProjectAddFileGroupToProject.Caption = "Add existing file group to project"; this.buttonMenuProjectAddFileGroupToProject.Id = 5; this.buttonMenuProjectAddFileGroupToProject.Name = "buttonMenuProjectAddFileGroupToProject"; this.buttonMenuProjectAddFileGroupToProject.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonAddFileGroupToProject_ItemClick); // // buttonMenuProjectRemoveFileGroupFromProject // this.buttonMenuProjectRemoveFileGroupFromProject.Caption = "Remove file group from project"; this.buttonMenuProjectRemoveFileGroupFromProject.Id = 6; this.buttonMenuProjectRemoveFileGroupFromProject.Name = "buttonMenuProjectRemoveFileGroupFromProject"; this.buttonMenuProjectRemoveFileGroupFromProject.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonRemoveFileGroupFromProject_ItemClick); // // buttonMenuProjectEditFileGroupSettings // this.buttonMenuProjectEditFileGroupSettings.Caption = "Edit file group settings"; this.buttonMenuProjectEditFileGroupSettings.Id = 7; this.buttonMenuProjectEditFileGroupSettings.Name = "buttonMenuProjectEditFileGroupSettings"; this.buttonMenuProjectEditFileGroupSettings.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonEditFileGroupSettings_ItemClick); // // buttonMenuProjectAddFilesToFileGroup // this.buttonMenuProjectAddFilesToFileGroup.Caption = "Add files to file group"; this.buttonMenuProjectAddFilesToFileGroup.Id = 8; this.buttonMenuProjectAddFilesToFileGroup.Name = "buttonMenuProjectAddFilesToFileGroup"; this.buttonMenuProjectAddFilesToFileGroup.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonAddFilesToFileGroup_ItemClick); // // buttonMenuProjectRemoveFileFromFileGroup // this.buttonMenuProjectRemoveFileFromFileGroup.Caption = "Remove file from file group"; this.buttonMenuProjectRemoveFileFromFileGroup.Id = 9; this.buttonMenuProjectRemoveFileFromFileGroup.Name = "buttonMenuProjectRemoveFileFromFileGroup"; this.buttonMenuProjectRemoveFileFromFileGroup.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonRemoveFileFromFileGroup_ItemClick); // // buttonMenuProjectEditProjectSettings // this.buttonMenuProjectEditProjectSettings.Caption = "Edit project settings"; this.buttonMenuProjectEditProjectSettings.Id = 10; this.buttonMenuProjectEditProjectSettings.Name = "buttonMenuProjectEditProjectSettings"; this.buttonMenuProjectEditProjectSettings.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonEditProjectSettings_ItemClick); // // buttonMenuProjectAddProjectFolder // this.buttonMenuProjectAddProjectFolder.Caption = "Add new project folder"; this.buttonMenuProjectAddProjectFolder.Id = 11; this.buttonMenuProjectAddProjectFolder.Name = "buttonMenuProjectAddProjectFolder"; this.buttonMenuProjectAddProjectFolder.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonAddProjectFolder_ItemClick); // // buttonMenuProjectRemoveProjectFolder // this.buttonMenuProjectRemoveProjectFolder.Caption = "Remove project folder"; this.buttonMenuProjectRemoveProjectFolder.Id = 12; this.buttonMenuProjectRemoveProjectFolder.Name = "buttonMenuProjectRemoveProjectFolder"; this.buttonMenuProjectRemoveProjectFolder.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonRemoveProjectFolder_ItemClick); // // buttonMenuProjectEditProjectFolder // this.buttonMenuProjectEditProjectFolder.Caption = "Edit project folder"; this.buttonMenuProjectEditProjectFolder.Id = 13; this.buttonMenuProjectEditProjectFolder.Name = "buttonMenuProjectEditProjectFolder"; this.buttonMenuProjectEditProjectFolder.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonEditProjectFolder_ItemClick); // // buttonMenuProjectMoveUp // this.buttonMenuProjectMoveUp.Caption = "Move up"; this.buttonMenuProjectMoveUp.Id = 14; this.buttonMenuProjectMoveUp.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonMenuProjectMoveUp.ImageOptions.Image"))); this.buttonMenuProjectMoveUp.Name = "buttonMenuProjectMoveUp"; this.buttonMenuProjectMoveUp.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonMoveUp_ItemClick); // // buttonMenuProjectMoveDown // this.buttonMenuProjectMoveDown.Caption = "Move down"; this.buttonMenuProjectMoveDown.Id = 15; this.buttonMenuProjectMoveDown.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonMenuProjectMoveDown.ImageOptions.Image"))); this.buttonMenuProjectMoveDown.Name = "buttonMenuProjectMoveDown"; this.buttonMenuProjectMoveDown.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonMoveDown_ItemClick); // // buttonMenuProjectCreateNewFile // this.buttonMenuProjectCreateNewFile.Caption = "Create new file for language"; this.buttonMenuProjectCreateNewFile.Id = 16; this.buttonMenuProjectCreateNewFile.Name = "buttonMenuProjectCreateNewFile"; this.buttonMenuProjectCreateNewFile.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonCreateNewFile_ItemClick); // // buttonMenuProjectCreateNewFiles // this.buttonMenuProjectCreateNewFiles.Caption = "Create new files for language"; this.buttonMenuProjectCreateNewFiles.Id = 17; this.buttonMenuProjectCreateNewFiles.Name = "buttonMenuProjectCreateNewFiles"; this.buttonMenuProjectCreateNewFiles.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonCreateNewFiles_ItemClick); // // buttonMenuProjectAutomaticallyAddFileGroupsFromVisualStudioSolution // this.buttonMenuProjectAutomaticallyAddFileGroupsFromVisualStudioSolution.Caption = "Automatically add file groups from Visual Studio solution"; this.buttonMenuProjectAutomaticallyAddFileGroupsFromVisualStudioSolution.Id = 18; this.buttonMenuProjectAutomaticallyAddFileGroupsFromVisualStudioSolution.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonMenuProjectAutomaticallyAddFileGroupsFromVisualStudioSolution.ImageOptions." + "Image"))); this.buttonMenuProjectAutomaticallyAddFileGroupsFromVisualStudioSolution.Name = "buttonMenuProjectAutomaticallyAddFileGroupsFromVisualStudioSolution"; this.buttonMenuProjectAutomaticallyAddFileGroupsFromVisualStudioSolution.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonAutomaticallyAddFileGroupsFromVisualStudioSolution_ItemClick); // // buttonOpenProjectMenuItem // this.buttonOpenProjectMenuItem.Caption = "Open project file"; this.buttonOpenProjectMenuItem.Id = 19; this.buttonOpenProjectMenuItem.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonOpenProjectMenuItem.ImageOptions.Image"))); this.buttonOpenProjectMenuItem.Name = "buttonOpenProjectMenuItem"; this.buttonOpenProjectMenuItem.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonOpenProjectMenuItem_ItemClick); // // buttonSortProjectFolderChildrenAscendingAZ // this.buttonSortProjectFolderChildrenAscendingAZ.Caption = "Sort children alphabetically"; this.buttonSortProjectFolderChildrenAscendingAZ.Id = 20; this.buttonSortProjectFolderChildrenAscendingAZ.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonSortProjectFolderChildrenAscendingAZ.ImageOptions.Image"))); this.buttonSortProjectFolderChildrenAscendingAZ.Name = "buttonSortProjectFolderChildrenAscendingAZ"; this.buttonSortProjectFolderChildrenAscendingAZ.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonSortAscendingAZ_ItemClick); // // buttonSortChildrenProjectAZ // this.buttonSortChildrenProjectAZ.Caption = "Sort children alphabetically"; this.buttonSortChildrenProjectAZ.Id = 21; this.buttonSortChildrenProjectAZ.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonSortChildrenProjectAZ.ImageOptions.Image"))); this.buttonSortChildrenProjectAZ.Name = "buttonSortChildrenProjectAZ"; this.buttonSortChildrenProjectAZ.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonSortChildrenProjectAZ_ItemClick); // // buttonMenuProjectFolderAddFileGroupToProject // this.buttonMenuProjectFolderAddFileGroupToProject.Caption = "Add new file group to project"; this.buttonMenuProjectFolderAddFileGroupToProject.Id = 22; this.buttonMenuProjectFolderAddFileGroupToProject.Name = "buttonMenuProjectFolderAddFileGroupToProject"; this.buttonMenuProjectFolderAddFileGroupToProject.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonMenuProjectFolderAddFileGroupToProject_ItemClick); // // buttonMenuProjectAddNewFileGroupToProject // this.buttonMenuProjectAddNewFileGroupToProject.Caption = "Add new file group to project"; this.buttonMenuProjectAddNewFileGroupToProject.Id = 23; this.buttonMenuProjectAddNewFileGroupToProject.Name = "buttonMenuProjectAddNewFileGroupToProject"; this.buttonMenuProjectAddNewFileGroupToProject.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonMenuProjectAddNewFileGroupToProject_ItemClick); // // buttonMenuProjectDeleteExistingLanguage // this.buttonMenuProjectDeleteExistingLanguage.Caption = "Delete language"; this.buttonMenuProjectDeleteExistingLanguage.Id = 24; this.buttonMenuProjectDeleteExistingLanguage.Name = "buttonMenuProjectDeleteExistingLanguage"; this.buttonMenuProjectDeleteExistingLanguage.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonMenuProjectDeleteExistingLanguage_ItemClick); // // buttonMenuProjectDeleteLanguages // this.buttonMenuProjectDeleteLanguages.Caption = "Delete language"; this.buttonMenuProjectDeleteLanguages.Id = 25; this.buttonMenuProjectDeleteLanguages.Name = "buttonMenuProjectDeleteLanguages"; this.buttonMenuProjectDeleteLanguages.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonMenuProjectDeleteLanguages_ItemClick); // // buttonMergeIntoFileGroup // this.buttonMergeIntoFileGroup.Caption = "Merge into this file group"; this.buttonMergeIntoFileGroup.Id = 26; this.buttonMergeIntoFileGroup.ImageOptions.Image = ((System.Drawing.Image)(resources.GetObject("buttonMergeIntoFileGroup.ImageOptions.Image"))); this.buttonMergeIntoFileGroup.Name = "buttonMergeIntoFileGroup"; this.buttonMergeIntoFileGroup.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonMergeIntoFileGroup_ItemClick); // // guiRefreshTimer // this.guiRefreshTimer.Interval = 500; this.guiRefreshTimer.Tick += new System.EventHandler(this.guiRefreshTimer_Tick); // // popupMenuProject // this.popupMenuProject.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.buttonMenuProjectEditResourceFiles), new DevExpress.XtraBars.LinkPersistInfo(this.buttonMenuProjectAutomaticallyAddMultipleFileGroupsToProject, true), new DevExpress.XtraBars.LinkPersistInfo(this.buttonMenuProjectAutomaticallyAddFileGroupsFromVisualStudioSolution), new DevExpress.XtraBars.LinkPersistInfo(this.buttonMenuProjectAddFileGroupToProject, true), new DevExpress.XtraBars.LinkPersistInfo(this.buttonMenuProjectAddNewFileGroupToProject), new DevExpress.XtraBars.LinkPersistInfo(this.buttonMenuProjectCreateNewFiles), new DevExpress.XtraBars.LinkPersistInfo(this.buttonMenuProjectDeleteLanguages), new DevExpress.XtraBars.LinkPersistInfo(this.buttonMenuProjectAddProjectFolder, true), new DevExpress.XtraBars.LinkPersistInfo(this.buttonMenuProjectEditProjectSettings, true), new DevExpress.XtraBars.LinkPersistInfo(this.buttonSortChildrenProjectAZ, true)}); this.popupMenuProject.Manager = this.barManager; this.popupMenuProject.Name = "popupMenuProject"; this.popupMenuProject.BeforePopup += new System.ComponentModel.CancelEventHandler(this.optionsPopupMenu_BeforePopup); // // popupMenuProjectFolder // this.popupMenuProjectFolder.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.buttonMenuProjectEditResourceFiles), new DevExpress.XtraBars.LinkPersistInfo(this.buttonMenuProjectAutomaticallyAddMultipleFileGroupsToProject, true), new DevExpress.XtraBars.LinkPersistInfo(this.buttonMenuProjectAutomaticallyAddFileGroupsFromVisualStudioSolution), new DevExpress.XtraBars.LinkPersistInfo(this.buttonMenuProjectAddFileGroupToProject, true), new DevExpress.XtraBars.LinkPersistInfo(this.buttonMenuProjectFolderAddFileGroupToProject), new DevExpress.XtraBars.LinkPersistInfo(this.buttonMenuProjectCreateNewFiles), new DevExpress.XtraBars.LinkPersistInfo(this.buttonMenuProjectDeleteExistingLanguage), new DevExpress.XtraBars.LinkPersistInfo(this.buttonMenuProjectAddProjectFolder, true), new DevExpress.XtraBars.LinkPersistInfo(this.buttonMenuProjectRemoveProjectFolder), new DevExpress.XtraBars.LinkPersistInfo(this.buttonMenuProjectEditProjectFolder), new DevExpress.XtraBars.LinkPersistInfo(this.buttonMenuProjectEditProjectSettings, true), new DevExpress.XtraBars.LinkPersistInfo(this.buttonMenuProjectMoveUp, true), new DevExpress.XtraBars.LinkPersistInfo(this.buttonMenuProjectMoveDown), new DevExpress.XtraBars.LinkPersistInfo(this.buttonSortProjectFolderChildrenAscendingAZ)}); this.popupMenuProjectFolder.Manager = this.barManager; this.popupMenuProjectFolder.Name = "popupMenuProjectFolder"; // // popupMenuFileGroup // this.popupMenuFileGroup.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.buttonMenuProjectEditResourceFiles), new DevExpress.XtraBars.LinkPersistInfo(this.buttonMenuProjectRemoveFileGroupFromProject), new DevExpress.XtraBars.LinkPersistInfo(this.buttonMenuProjectEditFileGroupSettings), new DevExpress.XtraBars.LinkPersistInfo(this.buttonMergeIntoFileGroup), new DevExpress.XtraBars.LinkPersistInfo(this.buttonMenuProjectAddFilesToFileGroup, true), new DevExpress.XtraBars.LinkPersistInfo(this.buttonMenuProjectCreateNewFile), new DevExpress.XtraBars.LinkPersistInfo(this.buttonMenuProjectEditProjectSettings, true), new DevExpress.XtraBars.LinkPersistInfo(this.buttonMenuProjectMoveUp, true), new DevExpress.XtraBars.LinkPersistInfo(this.buttonMenuProjectMoveDown)}); this.popupMenuFileGroup.Manager = this.barManager; this.popupMenuFileGroup.Name = "popupMenuFileGroup"; // // popupMenuFile // this.popupMenuFile.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.buttonMenuProjectRemoveFileFromFileGroup), new DevExpress.XtraBars.LinkPersistInfo(this.buttonMenuProjectEditProjectSettings, true)}); this.popupMenuFile.Manager = this.barManager; this.popupMenuFile.Name = "popupMenuFile"; // // popupMenuNone // this.popupMenuNone.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.buttonOpenProjectMenuItem)}); this.popupMenuNone.Manager = this.barManager; this.popupMenuNone.Name = "popupMenuNone"; // // updateNodeStateImageBackgroundworker // this.updateNodeStateImageBackgroundworker.WorkerReportsProgress = true; this.updateNodeStateImageBackgroundworker.WorkerSupportsCancellation = true; this.updateNodeStateImageBackgroundworker.DoWork += new System.ComponentModel.DoWorkEventHandler(this.updateNodeStateImageBackgroundworker_DoWork); this.updateNodeStateImageBackgroundworker.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.updateNodeStateImageBackgroundworker_ProgressChanged); this.updateNodeStateImageBackgroundworker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.updateNodeStateImageBackgroundworker_RunWorkerCompleted); // // ProjectFilesUserControl // this.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel); this.Appearance.Options.UseFont = true; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None; this.Controls.Add(this.treeView); this.Controls.Add(this.barDockControlLeft); this.Controls.Add(this.barDockControlRight); this.Controls.Add(this.barDockControlBottom); this.Controls.Add(this.barDockControlTop); this.Name = "ProjectFilesUserControl"; this.Size = new System.Drawing.Size(201, 434); this.Load += new System.EventHandler(this.projectFilesUserControlNew_Load); ((System.ComponentModel.ISupportInitialize)(this.treeView)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.treeImageList)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.stateImageList)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.barManager)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.popupMenuProject)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.popupMenuProjectFolder)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.popupMenuFileGroup)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.popupMenuFile)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.popupMenuNone)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Timer guiRefreshTimer; private DevExpress.Utils.ImageCollection treeImageList; private DevExpress.Utils.ImageCollection stateImageList; private ZetaResourceEditor.UI.Helper.ZetaResourceEditorTreeListControl treeView; private DevExpress.XtraBars.BarManager barManager; private DevExpress.XtraBars.BarDockControl barDockControlTop; private DevExpress.XtraBars.BarDockControl barDockControlBottom; private DevExpress.XtraBars.BarDockControl barDockControlLeft; private DevExpress.XtraBars.BarDockControl barDockControlRight; private DevExpress.XtraBars.PopupMenu popupMenuProject; private DevExpress.XtraBars.BarButtonItem buttonMenuProjectEditResourceFiles; private DevExpress.XtraBars.BarButtonItem buttonMenuProjectAutomaticallyAddMultipleFileGroupsToProject; private DevExpress.XtraBars.BarButtonItem buttonMenuProjectAddFileGroupToProject; private DevExpress.XtraBars.BarButtonItem buttonMenuProjectRemoveFileGroupFromProject; private DevExpress.XtraBars.BarButtonItem buttonMenuProjectEditFileGroupSettings; private DevExpress.XtraBars.BarButtonItem buttonMenuProjectAddFilesToFileGroup; private DevExpress.XtraBars.BarButtonItem buttonMenuProjectRemoveFileFromFileGroup; private DevExpress.XtraBars.BarButtonItem buttonMenuProjectEditProjectSettings; private DevExpress.XtraTreeList.Columns.TreeListColumn treeListColumn1; private DevExpress.Utils.ToolTipController toolTipController1; private DevExpress.XtraBars.BarButtonItem buttonMenuProjectAddProjectFolder; private DevExpress.XtraBars.BarButtonItem buttonMenuProjectRemoveProjectFolder; private DevExpress.XtraBars.BarButtonItem buttonMenuProjectEditProjectFolder; private DevExpress.XtraBars.BarButtonItem buttonMenuProjectMoveUp; private DevExpress.XtraBars.BarButtonItem buttonMenuProjectMoveDown; private DevExpress.XtraBars.BarButtonItem buttonMenuProjectCreateNewFile; private DevExpress.XtraBars.BarButtonItem buttonMenuProjectCreateNewFiles; private DevExpress.XtraBars.BarButtonItem buttonMenuProjectAutomaticallyAddFileGroupsFromVisualStudioSolution; private DevExpress.XtraBars.PopupMenu popupMenuProjectFolder; private DevExpress.XtraBars.PopupMenu popupMenuFileGroup; private DevExpress.XtraBars.PopupMenu popupMenuFile; private DevExpress.XtraBars.PopupMenu popupMenuNone; private DevExpress.XtraBars.BarButtonItem buttonOpenProjectMenuItem; private System.ComponentModel.BackgroundWorker updateNodeStateImageBackgroundworker; private DevExpress.XtraBars.BarButtonItem buttonSortProjectFolderChildrenAscendingAZ; private DevExpress.XtraBars.BarButtonItem buttonSortChildrenProjectAZ; private DevExpress.XtraBars.BarButtonItem buttonMenuProjectFolderAddFileGroupToProject; private DevExpress.XtraBars.BarButtonItem buttonMenuProjectAddNewFileGroupToProject; private DevExpress.XtraBars.BarButtonItem buttonMenuProjectDeleteExistingLanguage; private DevExpress.XtraBars.BarButtonItem buttonMenuProjectDeleteLanguages; private DevExpress.XtraBars.BarButtonItem buttonMergeIntoFileGroup; } }
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using IdentityModel; using IdentityServer4.Events; using IdentityServer4.Extensions; using IdentityServer4.Models; using IdentityServer4.Services; using IdentityServer4.Stores; using IdentityServer4.Test; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Linq; using System.Threading.Tasks; namespace IdentityServer4.Quickstart.UI { /// <summary> /// This sample controller implements a typical login/logout/provision workflow for local and external accounts. /// The login service encapsulates the interactions with the user data store. This data store is in-memory only and cannot be used for production! /// The interaction service provides a way for the UI to communicate with identityserver for validation and context retrieval /// </summary> [SecurityHeaders] [AllowAnonymous] public class AccountController : Controller { private readonly TestUserStore _users; private readonly IIdentityServerInteractionService _interaction; private readonly IClientStore _clientStore; private readonly IAuthenticationSchemeProvider _schemeProvider; private readonly IEventService _events; public AccountController( IIdentityServerInteractionService interaction, IClientStore clientStore, IAuthenticationSchemeProvider schemeProvider, IEventService events, TestUserStore users = null) { // if the TestUserStore is not in DI, then we'll just use the global users collection // this is where you would plug in your own custom identity management library (e.g. ASP.NET Identity) _users = users ?? new TestUserStore(TestUsers.Users); _interaction = interaction; _clientStore = clientStore; _schemeProvider = schemeProvider; _events = events; } /// <summary> /// Entry point into the login workflow /// </summary> [HttpGet] public async Task<IActionResult> Login(string returnUrl) { // build a model so we know what to show on the login page var vm = await BuildLoginViewModelAsync(returnUrl); if (vm.IsExternalLoginOnly) { // we only have one option for logging in and it's an external provider return RedirectToAction("Challenge", "External", new { provider = vm.ExternalLoginScheme, returnUrl }); } return View(vm); } /// <summary> /// Handle postback from username/password login /// </summary> [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Login(LoginInputModel model, string button) { // check if we are in the context of an authorization request var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl); // the user clicked the "cancel" button if (button != "login") { if (context != null) { // if the user cancels, send a result back into IdentityServer as if they // denied the consent (even if this client does not require consent). // this will send back an access denied OIDC error response to the client. await _interaction.GrantConsentAsync(context, ConsentResponse.Denied); // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null if (await _clientStore.IsPkceClientAsync(context.ClientId)) { // if the client is PKCE then we assume it's native, so this change in how to // return the response is for better UX for the end user. return View("Redirect", new RedirectViewModel { RedirectUrl = model.ReturnUrl }); } return Redirect(model.ReturnUrl); } else { // since we don't have a valid context, then we just go back to the home page return Redirect("~/"); } } if (ModelState.IsValid) { // validate username/password against in-memory store if (_users.ValidateCredentials(model.Username, model.Password)) { var user = _users.FindByUsername(model.Username); await _events.RaiseAsync(new UserLoginSuccessEvent(user.Username, user.SubjectId, user.Username, clientId: context?.ClientId)); // only set explicit expiration here if user chooses "remember me". // otherwise we rely upon expiration configured in cookie middleware. AuthenticationProperties props = null; if (AccountOptions.AllowRememberLogin && model.RememberLogin) { props = new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration) }; }; // issue authentication cookie with subject ID and username await HttpContext.SignInAsync(user.SubjectId, user.Username, props); if (context != null) { if (await _clientStore.IsPkceClientAsync(context.ClientId)) { // if the client is PKCE then we assume it's native, so this change in how to // return the response is for better UX for the end user. return View("Redirect", new RedirectViewModel { RedirectUrl = model.ReturnUrl }); } // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null return Redirect(model.ReturnUrl); } // request for a local page if (Url.IsLocalUrl(model.ReturnUrl)) { return Redirect(model.ReturnUrl); } else if (string.IsNullOrEmpty(model.ReturnUrl)) { return Redirect("~/"); } else { // user might have clicked on a malicious link - should be logged throw new Exception("invalid return URL"); } } await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials", clientId:context?.ClientId)); ModelState.AddModelError(string.Empty, AccountOptions.InvalidCredentialsErrorMessage); } // something went wrong, show form with error var vm = await BuildLoginViewModelAsync(model); return View(vm); } /// <summary> /// Show logout page /// </summary> [HttpGet] public async Task<IActionResult> Logout(string logoutId) { // build a model so the logout page knows what to display var vm = await BuildLogoutViewModelAsync(logoutId); if (vm.ShowLogoutPrompt == false) { // if the request for logout was properly authenticated from IdentityServer, then // we don't need to show the prompt and can just log the user out directly. return await Logout(vm); } return View(vm); } /// <summary> /// Handle logout page postback /// </summary> [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Logout(LogoutInputModel model) { // build a model so the logged out page knows what to display var vm = await BuildLoggedOutViewModelAsync(model.LogoutId); if (User?.Identity.IsAuthenticated == true) { // delete local authentication cookie await HttpContext.SignOutAsync(); // raise the logout event await _events.RaiseAsync(new UserLogoutSuccessEvent(User.GetSubjectId(), User.GetDisplayName())); } // check if we need to trigger sign-out at an upstream identity provider if (vm.TriggerExternalSignout) { // build a return URL so the upstream provider will redirect back // to us after the user has logged out. this allows us to then // complete our single sign-out processing. string url = Url.Action("Logout", new { logoutId = vm.LogoutId }); // this triggers a redirect to the external provider for sign-out return SignOut(new AuthenticationProperties { RedirectUri = url }, vm.ExternalAuthenticationScheme); } return View("LoggedOut", vm); } [HttpGet] public IActionResult AccessDenied() { return View(); } /*****************************************/ /* helper APIs for the AccountController */ /*****************************************/ private async Task<LoginViewModel> BuildLoginViewModelAsync(string returnUrl) { var context = await _interaction.GetAuthorizationContextAsync(returnUrl); if (context?.IdP != null && await _schemeProvider.GetSchemeAsync(context.IdP) != null) { var local = context.IdP == IdentityServer4.IdentityServerConstants.LocalIdentityProvider; // this is meant to short circuit the UI and only trigger the one external IdP var vm = new LoginViewModel { EnableLocalLogin = local, ReturnUrl = returnUrl, Username = context?.LoginHint, }; if (!local) { vm.ExternalProviders = new[] { new ExternalProvider { AuthenticationScheme = context.IdP } }; } return vm; } var schemes = await _schemeProvider.GetAllSchemesAsync(); var providers = schemes .Where(x => x.DisplayName != null || (x.Name.Equals(AccountOptions.WindowsAuthenticationSchemeName, StringComparison.OrdinalIgnoreCase)) ) .Select(x => new ExternalProvider { DisplayName = x.DisplayName, AuthenticationScheme = x.Name }).ToList(); var allowLocal = true; if (context?.ClientId != null) { var client = await _clientStore.FindEnabledClientByIdAsync(context.ClientId); if (client != null) { allowLocal = client.EnableLocalLogin; if (client.IdentityProviderRestrictions != null && client.IdentityProviderRestrictions.Any()) { providers = providers.Where(provider => client.IdentityProviderRestrictions.Contains(provider.AuthenticationScheme)).ToList(); } } } return new LoginViewModel { AllowRememberLogin = AccountOptions.AllowRememberLogin, EnableLocalLogin = allowLocal && AccountOptions.AllowLocalLogin, ReturnUrl = returnUrl, Username = context?.LoginHint, ExternalProviders = providers.ToArray() }; } private async Task<LoginViewModel> BuildLoginViewModelAsync(LoginInputModel model) { var vm = await BuildLoginViewModelAsync(model.ReturnUrl); vm.Username = model.Username; vm.RememberLogin = model.RememberLogin; return vm; } private async Task<LogoutViewModel> BuildLogoutViewModelAsync(string logoutId) { var vm = new LogoutViewModel { LogoutId = logoutId, ShowLogoutPrompt = AccountOptions.ShowLogoutPrompt }; if (User?.Identity.IsAuthenticated != true) { // if the user is not authenticated, then just show logged out page vm.ShowLogoutPrompt = false; return vm; } var context = await _interaction.GetLogoutContextAsync(logoutId); if (context?.ShowSignoutPrompt == false) { // it's safe to automatically sign-out vm.ShowLogoutPrompt = false; return vm; } // show the logout prompt. this prevents attacks where the user // is automatically signed out by another malicious web page. return vm; } private async Task<LoggedOutViewModel> BuildLoggedOutViewModelAsync(string logoutId) { // get context information (client name, post logout redirect URI and iframe for federated signout) var logout = await _interaction.GetLogoutContextAsync(logoutId); var vm = new LoggedOutViewModel { AutomaticRedirectAfterSignOut = AccountOptions.AutomaticRedirectAfterSignOut, PostLogoutRedirectUri = logout?.PostLogoutRedirectUri, ClientName = string.IsNullOrEmpty(logout?.ClientName) ? logout?.ClientId : logout?.ClientName, SignOutIframeUrl = logout?.SignOutIFrameUrl, LogoutId = logoutId }; if (User?.Identity.IsAuthenticated == true) { var idp = User.FindFirst(JwtClaimTypes.IdentityProvider)?.Value; if (idp != null && idp != IdentityServer4.IdentityServerConstants.LocalIdentityProvider) { var providerSupportsSignout = await HttpContext.GetSchemeSupportsSignOutAsync(idp); if (providerSupportsSignout) { if (vm.LogoutId == null) { // if there's no current logout context, we need to create one // this captures necessary info from the current logged in user // before we signout and redirect away to the external IdP for signout vm.LogoutId = await _interaction.CreateLogoutContextAsync(); } vm.ExternalAuthenticationScheme = idp; } } } return vm; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Differencing; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Text.Projection; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Venus { /// <summary> /// An IVisualStudioDocument which represents the secondary buffer to the workspace API. /// </summary> internal sealed class ContainedDocument : ForegroundThreadAffinitizedObject, IVisualStudioHostDocument { private const string ReturnReplacementString = @"{|r|}"; private const string NewLineReplacementString = @"{|n|}"; private const string HTML = nameof(HTML); private const string HTMLX = nameof(HTMLX); private const string Razor = nameof(Razor); private const string XOML = nameof(XOML); private const char RazorExplicit = '@'; private const string CSharpRazorBlock = "{"; private const string VBRazorBlock = "code"; private const string HelperRazor = "helper"; private const string FunctionsRazor = "functions"; private static readonly EditOptions s_venusEditOptions = new EditOptions(new StringDifferenceOptions { DifferenceType = StringDifferenceTypes.Character, IgnoreTrimWhiteSpace = false }); private readonly AbstractContainedLanguage _containedLanguage; private readonly SourceCodeKind _sourceCodeKind; private readonly IComponentModel _componentModel; private readonly Workspace _workspace; private readonly ITextDifferencingSelectorService _differenceSelectorService; private readonly HostType _hostType; private readonly ReiteratedVersionSnapshotTracker _snapshotTracker; private readonly IFormattingRule _vbHelperFormattingRule; private readonly string _itemMoniker; public AbstractProject Project { get { return _containedLanguage.Project; } } public bool SupportsRename { get { return _hostType == HostType.Razor; } } public DocumentId Id { get; } public IReadOnlyList<string> Folders { get; } public TextLoader Loader { get; } public DocumentKey Key { get; } public ContainedDocument( AbstractContainedLanguage containedLanguage, SourceCodeKind sourceCodeKind, Workspace workspace, IVsHierarchy hierarchy, uint itemId, IComponentModel componentModel, IFormattingRule vbHelperFormattingRule) { Contract.ThrowIfNull(containedLanguage); _containedLanguage = containedLanguage; _sourceCodeKind = sourceCodeKind; _componentModel = componentModel; _workspace = workspace; _hostType = GetHostType(); if (!ErrorHandler.Succeeded(((IVsProject)hierarchy).GetMkDocument(itemId, out var filePath))) { // we couldn't look up the document moniker from an hierarchy for an itemid. // Since we only use this moniker as a key, we could fall back to something else, like the document name. Debug.Assert(false, "Could not get the document moniker for an item from its hierarchy."); if (!hierarchy.TryGetItemName(itemId, out filePath)) { Environment.FailFast("Failed to get document moniker for a contained document"); } } if (Project.Hierarchy != null) { Project.Hierarchy.GetCanonicalName(itemId, out var moniker); _itemMoniker = moniker; } this.Key = new DocumentKey(Project, filePath); this.Id = DocumentId.CreateNewId(Project.Id, filePath); this.Folders = containedLanguage.Project.GetFolderNamesFromHierarchy(itemId); this.Loader = TextLoader.From(containedLanguage.SubjectBuffer.AsTextContainer(), VersionStamp.Create(), filePath); _differenceSelectorService = componentModel.GetService<ITextDifferencingSelectorService>(); _snapshotTracker = new ReiteratedVersionSnapshotTracker(_containedLanguage.SubjectBuffer); _vbHelperFormattingRule = vbHelperFormattingRule; } private HostType GetHostType() { var projectionBuffer = _containedLanguage.DataBuffer as IProjectionBuffer; if (projectionBuffer != null) { // RazorCSharp has an HTMLX base type but should not be associated with // the HTML host type, so we check for it first. if (projectionBuffer.SourceBuffers.Any(b => b.ContentType.IsOfType(Razor))) { return HostType.Razor; } // For TypeScript hosted in HTML the source buffers will have type names // HTMLX and TypeScript. if (projectionBuffer.SourceBuffers.Any(b => b.ContentType.IsOfType(HTML) || b.ContentType.IsOfType(HTMLX))) { return HostType.HTML; } } else { // XOML is set up differently. For XOML, the secondary buffer (i.e. SubjectBuffer) // is a projection buffer, while the primary buffer (i.e. DataBuffer) is not. Instead, // the primary buffer is a regular unprojected ITextBuffer with the HTML content type. if (_containedLanguage.DataBuffer.CurrentSnapshot.ContentType.IsOfType(HTML)) { return HostType.XOML; } } throw ExceptionUtilities.Unreachable; } public DocumentInfo GetInitialState() { return DocumentInfo.Create( this.Id, this.Name, folders: this.Folders, sourceCodeKind: _sourceCodeKind, loader: this.Loader, filePath: this.Key.Moniker); } public bool IsOpen { get { return true; } } #pragma warning disable 67 public event EventHandler UpdatedOnDisk; public event EventHandler<bool> Opened; public event EventHandler<bool> Closing; #pragma warning restore 67 IVisualStudioHostProject IVisualStudioHostDocument.Project { get { return this.Project; } } public ITextBuffer GetOpenTextBuffer() { return _containedLanguage.SubjectBuffer; } public SourceTextContainer GetOpenTextContainer() { return this.GetOpenTextBuffer().AsTextContainer(); } public IContentType ContentType { get { return _containedLanguage.SubjectBuffer.ContentType; } } public string Name { get { try { return Path.GetFileName(this.FilePath); } catch (ArgumentException) { return this.FilePath; } } } public SourceCodeKind SourceCodeKind { get { return _sourceCodeKind; } } public string FilePath { get { return Key.Moniker; } } public AbstractContainedLanguage ContainedLanguage { get { return _containedLanguage; } } public void Dispose() { _snapshotTracker.StopTracking(_containedLanguage.SubjectBuffer); this.ContainedLanguage.Dispose(); } public DocumentId FindProjectDocumentIdWithItemId(uint itemidInsertionPoint) { return Project.GetCurrentDocuments().SingleOrDefault(d => d.GetItemId() == itemidInsertionPoint).Id; } public uint FindItemIdOfDocument(Document document) { return Project.GetDocumentOrAdditionalDocument(document.Id).GetItemId(); } public void UpdateText(SourceText newText) { var subjectBuffer = (IProjectionBuffer)this.GetOpenTextBuffer(); var originalSnapshot = subjectBuffer.CurrentSnapshot; var originalText = originalSnapshot.AsText(); var changes = newText.GetTextChanges(originalText); IEnumerable<int> affectedVisibleSpanIndices = null; var editorVisibleSpansInOriginal = SharedPools.Default<List<TextSpan>>().AllocateAndClear(); try { var originalDocument = _workspace.CurrentSolution.GetDocument(this.Id); editorVisibleSpansInOriginal.AddRange(GetEditorVisibleSpans()); var newChanges = FilterTextChanges(originalText, editorVisibleSpansInOriginal, changes).ToList(); if (newChanges.Count == 0) { // no change to apply return; } ApplyChanges(subjectBuffer, newChanges, editorVisibleSpansInOriginal, out affectedVisibleSpanIndices); AdjustIndentation(subjectBuffer, affectedVisibleSpanIndices); } finally { SharedPools.Default<HashSet<int>>().ClearAndFree((HashSet<int>)affectedVisibleSpanIndices); SharedPools.Default<List<TextSpan>>().ClearAndFree(editorVisibleSpansInOriginal); } } private IEnumerable<TextChange> FilterTextChanges(SourceText originalText, List<TextSpan> editorVisibleSpansInOriginal, IReadOnlyList<TextChange> changes) { // no visible spans or changes if (editorVisibleSpansInOriginal.Count == 0 || changes.Count == 0) { // return empty one yield break; } using (var pooledObject = SharedPools.Default<List<TextChange>>().GetPooledObject()) { var changeQueue = pooledObject.Object; changeQueue.AddRange(changes); var spanIndex = 0; var changeIndex = 0; for (; spanIndex < editorVisibleSpansInOriginal.Count; spanIndex++) { var visibleSpan = editorVisibleSpansInOriginal[spanIndex]; var visibleTextSpan = GetVisibleTextSpan(originalText, visibleSpan, uptoFirstAndLastLine: true); for (; changeIndex < changeQueue.Count; changeIndex++) { var change = changeQueue[changeIndex]; // easy case first if (change.Span.End < visibleSpan.Start) { // move to next change continue; } if (visibleSpan.End < change.Span.Start) { // move to next visible span break; } // make sure we are not replacing whitespace around start and at the end of visible span if (WhitespaceOnEdges(originalText, visibleTextSpan, change)) { continue; } if (visibleSpan.Contains(change.Span)) { yield return change; continue; } // now it is complex case where things are intersecting each other var subChanges = GetSubTextChanges(originalText, change, visibleSpan).ToList(); if (subChanges.Count > 0) { if (subChanges.Count == 1 && subChanges[0] == change) { // we can't break it. not much we can do here. just don't touch and ignore this change continue; } changeQueue.InsertRange(changeIndex + 1, subChanges); continue; } } } } } private bool WhitespaceOnEdges(SourceText text, TextSpan visibleTextSpan, TextChange change) { if (!string.IsNullOrWhiteSpace(change.NewText)) { return false; } if (change.Span.End <= visibleTextSpan.Start) { return true; } if (visibleTextSpan.End <= change.Span.Start) { return true; } return false; } private IEnumerable<TextChange> GetSubTextChanges(SourceText originalText, TextChange changeInOriginalText, TextSpan visibleSpanInOriginalText) { using (var changes = SharedPools.Default<List<TextChange>>().GetPooledObject()) { var leftText = originalText.ToString(changeInOriginalText.Span); var rightText = changeInOriginalText.NewText; var offsetInOriginalText = changeInOriginalText.Span.Start; if (TryGetSubTextChanges(originalText, visibleSpanInOriginalText, leftText, rightText, offsetInOriginalText, changes.Object)) { return changes.Object.ToList(); } return GetSubTextChanges(originalText, visibleSpanInOriginalText, leftText, rightText, offsetInOriginalText); } } private bool TryGetSubTextChanges( SourceText originalText, TextSpan visibleSpanInOriginalText, string leftText, string rightText, int offsetInOriginalText, List<TextChange> changes) { // these are expensive. but hopefully we don't hit this as much except the boundary cases. using (var leftPool = SharedPools.Default<List<TextSpan>>().GetPooledObject()) using (var rightPool = SharedPools.Default<List<TextSpan>>().GetPooledObject()) { var spansInLeftText = leftPool.Object; var spansInRightText = rightPool.Object; if (TryGetWhitespaceOnlyChanges(leftText, rightText, spansInLeftText, spansInRightText)) { for (var i = 0; i < spansInLeftText.Count; i++) { var spanInLeftText = spansInLeftText[i]; var spanInRightText = spansInRightText[i]; if (spanInLeftText.IsEmpty && spanInRightText.IsEmpty) { continue; } var spanInOriginalText = new TextSpan(offsetInOriginalText + spanInLeftText.Start, spanInLeftText.Length); if (TryGetSubTextChange(originalText, visibleSpanInOriginalText, rightText, spanInOriginalText, spanInRightText, out var textChange)) { changes.Add(textChange); } } return true; } return false; } } private IEnumerable<TextChange> GetSubTextChanges( SourceText originalText, TextSpan visibleSpanInOriginalText, string leftText, string rightText, int offsetInOriginalText) { // these are expensive. but hopefully we don't hit this as much except the boundary cases. using (var leftPool = SharedPools.Default<List<ValueTuple<int, int>>>().GetPooledObject()) using (var rightPool = SharedPools.Default<List<ValueTuple<int, int>>>().GetPooledObject()) { var leftReplacementMap = leftPool.Object; var rightReplacementMap = rightPool.Object; GetTextWithReplacements(leftText, rightText, leftReplacementMap, rightReplacementMap, out var leftTextWithReplacement, out var rightTextWithReplacement); var diffResult = DiffStrings(leftTextWithReplacement, rightTextWithReplacement); foreach (var difference in diffResult) { var spanInLeftText = AdjustSpan(diffResult.LeftDecomposition.GetSpanInOriginal(difference.Left), leftReplacementMap); var spanInRightText = AdjustSpan(diffResult.RightDecomposition.GetSpanInOriginal(difference.Right), rightReplacementMap); var spanInOriginalText = new TextSpan(offsetInOriginalText + spanInLeftText.Start, spanInLeftText.Length); if (TryGetSubTextChange(originalText, visibleSpanInOriginalText, rightText, spanInOriginalText, spanInRightText.ToTextSpan(), out var textChange)) { yield return textChange; } } } } private bool TryGetWhitespaceOnlyChanges(string leftText, string rightText, List<TextSpan> spansInLeftText, List<TextSpan> spansInRightText) { return TryGetWhitespaceGroup(leftText, spansInLeftText) && TryGetWhitespaceGroup(rightText, spansInRightText) && spansInLeftText.Count == spansInRightText.Count; } private bool TryGetWhitespaceGroup(string text, List<TextSpan> groups) { if (text.Length == 0) { groups.Add(new TextSpan(0, 0)); return true; } var start = 0; for (var i = 0; i < text.Length; i++) { var ch = text[i]; switch (ch) { case ' ': if (!TextAt(text, i - 1, ' ')) { start = i; } break; case '\r': case '\n': if (i == 0) { groups.Add(TextSpan.FromBounds(0, 0)); } else if (TextAt(text, i - 1, ' ')) { groups.Add(TextSpan.FromBounds(start, i)); } else if (TextAt(text, i - 1, '\n')) { groups.Add(TextSpan.FromBounds(start, i)); } start = i + 1; break; default: return false; } } if (start <= text.Length) { groups.Add(TextSpan.FromBounds(start, text.Length)); } return true; } private bool TextAt(string text, int index, char ch) { if (index < 0 || text.Length <= index) { return false; } return text[index] == ch; } private bool TryGetSubTextChange( SourceText originalText, TextSpan visibleSpanInOriginalText, string rightText, TextSpan spanInOriginalText, TextSpan spanInRightText, out TextChange textChange) { textChange = default(TextChange); var visibleFirstLineInOriginalText = originalText.Lines.GetLineFromPosition(visibleSpanInOriginalText.Start); var visibleLastLineInOriginalText = originalText.Lines.GetLineFromPosition(visibleSpanInOriginalText.End); // skip easy case // 1. things are out of visible span if (!visibleSpanInOriginalText.IntersectsWith(spanInOriginalText)) { return false; } // 2. there are no intersects var snippetInRightText = rightText.Substring(spanInRightText.Start, spanInRightText.Length); if (visibleSpanInOriginalText.Contains(spanInOriginalText) && visibleSpanInOriginalText.End != spanInOriginalText.End) { textChange = new TextChange(spanInOriginalText, snippetInRightText); return true; } // okay, more complex case. things are intersecting boundaries. var firstLineOfRightTextSnippet = snippetInRightText.GetFirstLineText(); var lastLineOfRightTextSnippet = snippetInRightText.GetLastLineText(); // there are 4 complex cases - these are all heuristic. not sure what better way I have. and the heuristic is heavily based on // text differ's behavior. // 1. it is a single line if (visibleFirstLineInOriginalText.LineNumber == visibleLastLineInOriginalText.LineNumber) { // don't do anything return false; } // 2. replacement contains visible spans if (spanInOriginalText.Contains(visibleSpanInOriginalText)) { // header // don't do anything // body textChange = new TextChange( TextSpan.FromBounds(visibleFirstLineInOriginalText.EndIncludingLineBreak, visibleLastLineInOriginalText.Start), snippetInRightText.Substring(firstLineOfRightTextSnippet.Length, snippetInRightText.Length - firstLineOfRightTextSnippet.Length - lastLineOfRightTextSnippet.Length)); // footer // don't do anything return true; } // 3. replacement intersects with start if (spanInOriginalText.Start < visibleSpanInOriginalText.Start && visibleSpanInOriginalText.Start <= spanInOriginalText.End && spanInOriginalText.End < visibleSpanInOriginalText.End) { // header // don't do anything // body if (visibleFirstLineInOriginalText.EndIncludingLineBreak <= spanInOriginalText.End) { textChange = new TextChange( TextSpan.FromBounds(visibleFirstLineInOriginalText.EndIncludingLineBreak, spanInOriginalText.End), snippetInRightText.Substring(firstLineOfRightTextSnippet.Length)); return true; } return false; } // 4. replacement intersects with end if (visibleSpanInOriginalText.Start < spanInOriginalText.Start && spanInOriginalText.Start <= visibleSpanInOriginalText.End && visibleSpanInOriginalText.End <= spanInOriginalText.End) { // body if (spanInOriginalText.Start <= visibleLastLineInOriginalText.Start) { textChange = new TextChange( TextSpan.FromBounds(spanInOriginalText.Start, visibleLastLineInOriginalText.Start), snippetInRightText.Substring(0, snippetInRightText.Length - lastLineOfRightTextSnippet.Length)); return true; } // footer // don't do anything return false; } // if it got hit, then it means there is a missing case throw ExceptionUtilities.Unreachable; } private IHierarchicalDifferenceCollection DiffStrings(string leftTextWithReplacement, string rightTextWithReplacement) { var diffService = _differenceSelectorService.GetTextDifferencingService( _workspace.Services.GetLanguageServices(this.Project.Language).GetService<IContentTypeLanguageService>().GetDefaultContentType()); diffService = diffService ?? _differenceSelectorService.DefaultTextDifferencingService; return diffService.DiffStrings(leftTextWithReplacement, rightTextWithReplacement, s_venusEditOptions.DifferenceOptions); } private void GetTextWithReplacements( string leftText, string rightText, List<ValueTuple<int, int>> leftReplacementMap, List<ValueTuple<int, int>> rightReplacementMap, out string leftTextWithReplacement, out string rightTextWithReplacement) { // to make diff works better, we choose replacement strings that don't appear in both texts. var returnReplacement = GetReplacementStrings(leftText, rightText, ReturnReplacementString); var newLineReplacement = GetReplacementStrings(leftText, rightText, NewLineReplacementString); leftTextWithReplacement = GetTextWithReplacementMap(leftText, returnReplacement, newLineReplacement, leftReplacementMap); rightTextWithReplacement = GetTextWithReplacementMap(rightText, returnReplacement, newLineReplacement, rightReplacementMap); } private static string GetReplacementStrings(string leftText, string rightText, string initialReplacement) { if (leftText.IndexOf(initialReplacement, StringComparison.Ordinal) < 0 && rightText.IndexOf(initialReplacement, StringComparison.Ordinal) < 0) { return initialReplacement; } // okay, there is already one in the given text. const string format = "{{|{0}|{1}|{0}|}}"; for (var i = 0; true; i++) { var replacement = string.Format(format, i.ToString(), initialReplacement); if (leftText.IndexOf(replacement, StringComparison.Ordinal) < 0 && rightText.IndexOf(replacement, StringComparison.Ordinal) < 0) { return replacement; } } } private string GetTextWithReplacementMap(string text, string returnReplacement, string newLineReplacement, List<ValueTuple<int, int>> replacementMap) { var delta = 0; var returnLength = returnReplacement.Length; var newLineLength = newLineReplacement.Length; var sb = StringBuilderPool.Allocate(); for (var i = 0; i < text.Length; i++) { var ch = text[i]; if (ch == '\r') { sb.Append(returnReplacement); delta += returnLength - 1; replacementMap.Add(ValueTuple.Create(i + delta, delta)); continue; } else if (ch == '\n') { sb.Append(newLineReplacement); delta += newLineLength - 1; replacementMap.Add(ValueTuple.Create(i + delta, delta)); continue; } sb.Append(ch); } return StringBuilderPool.ReturnAndFree(sb); } private Span AdjustSpan(Span span, List<ValueTuple<int, int>> replacementMap) { var start = span.Start; var end = span.End; for (var i = 0; i < replacementMap.Count; i++) { var positionAndDelta = replacementMap[i]; if (positionAndDelta.Item1 <= span.Start) { start = span.Start - positionAndDelta.Item2; } if (positionAndDelta.Item1 <= span.End) { end = span.End - positionAndDelta.Item2; } if (positionAndDelta.Item1 > span.End) { break; } } return Span.FromBounds(start, end); } public IEnumerable<TextSpan> GetEditorVisibleSpans() { var subjectBuffer = (IProjectionBuffer)this.GetOpenTextBuffer(); var projectionDataBuffer = _containedLanguage.DataBuffer as IProjectionBuffer; if (projectionDataBuffer != null) { return projectionDataBuffer.CurrentSnapshot .GetSourceSpans() .Where(ss => ss.Snapshot.TextBuffer == subjectBuffer) .Select(s => s.Span.ToTextSpan()) .OrderBy(s => s.Start); } else { return SpecializedCollections.EmptyEnumerable<TextSpan>(); } } private static void ApplyChanges( IProjectionBuffer subjectBuffer, IEnumerable<TextChange> changes, IList<TextSpan> visibleSpansInOriginal, out IEnumerable<int> affectedVisibleSpansInNew) { using (var edit = subjectBuffer.CreateEdit(s_venusEditOptions, reiteratedVersionNumber: null, editTag: null)) { var affectedSpans = SharedPools.Default<HashSet<int>>().AllocateAndClear(); affectedVisibleSpansInNew = affectedSpans; var currentVisibleSpanIndex = 0; foreach (var change in changes) { // Find the next visible span that either overlaps or intersects with while (currentVisibleSpanIndex < visibleSpansInOriginal.Count && visibleSpansInOriginal[currentVisibleSpanIndex].End < change.Span.Start) { currentVisibleSpanIndex++; } // no more place to apply text changes if (currentVisibleSpanIndex >= visibleSpansInOriginal.Count) { break; } var newText = change.NewText; var span = change.Span.ToSpan(); edit.Replace(span, newText); affectedSpans.Add(currentVisibleSpanIndex); } edit.Apply(); } } private void AdjustIndentation(IProjectionBuffer subjectBuffer, IEnumerable<int> visibleSpanIndex) { if (!visibleSpanIndex.Any()) { return; } var snapshot = subjectBuffer.CurrentSnapshot; var document = _workspace.CurrentSolution.GetDocument(this.Id); if (!document.SupportsSyntaxTree) { return; } var originalText = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None); Contract.Requires(object.ReferenceEquals(originalText, snapshot.AsText())); var root = document.GetSyntaxRootSynchronously(CancellationToken.None); var editorOptionsFactory = _componentModel.GetService<IEditorOptionsFactoryService>(); var editorOptions = editorOptionsFactory.GetOptions(_containedLanguage.DataBuffer); var options = _workspace.Options .WithChangedOption(FormattingOptions.UseTabs, root.Language, !editorOptions.IsConvertTabsToSpacesEnabled()) .WithChangedOption(FormattingOptions.TabSize, root.Language, editorOptions.GetTabSize()) .WithChangedOption(FormattingOptions.IndentationSize, root.Language, editorOptions.GetIndentSize()); using (var pooledObject = SharedPools.Default<List<TextSpan>>().GetPooledObject()) { var spans = pooledObject.Object; spans.AddRange(this.GetEditorVisibleSpans()); using (var edit = subjectBuffer.CreateEdit(s_venusEditOptions, reiteratedVersionNumber: null, editTag: null)) { foreach (var spanIndex in visibleSpanIndex) { var rule = GetBaseIndentationRule(root, originalText, spans, spanIndex); var visibleSpan = spans[spanIndex]; AdjustIndentationForSpan(document, edit, visibleSpan, rule, options); } edit.Apply(); } } } private void AdjustIndentationForSpan( Document document, ITextEdit edit, TextSpan visibleSpan, IFormattingRule baseIndentationRule, OptionSet options) { var root = document.GetSyntaxRootSynchronously(CancellationToken.None); using (var rulePool = SharedPools.Default<List<IFormattingRule>>().GetPooledObject()) using (var spanPool = SharedPools.Default<List<TextSpan>>().GetPooledObject()) { var venusFormattingRules = rulePool.Object; var visibleSpans = spanPool.Object; venusFormattingRules.Add(baseIndentationRule); venusFormattingRules.Add(ContainedDocumentPreserveFormattingRule.Instance); var formattingRules = venusFormattingRules.Concat(Formatter.GetDefaultFormattingRules(document)); var workspace = document.Project.Solution.Workspace; var changes = Formatter.GetFormattedTextChanges( root, new TextSpan[] { CommonFormattingHelpers.GetFormattingSpan(root, visibleSpan) }, workspace, options, formattingRules, CancellationToken.None); visibleSpans.Add(visibleSpan); var newChanges = FilterTextChanges(document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None), visibleSpans, changes.ToReadOnlyCollection()).Where(t => visibleSpan.Contains(t.Span)); foreach (var change in newChanges) { edit.Replace(change.Span.ToSpan(), change.NewText); } } } public BaseIndentationFormattingRule GetBaseIndentationRule(SyntaxNode root, SourceText text, List<TextSpan> spans, int spanIndex) { if (_hostType == HostType.Razor) { var currentSpanIndex = spanIndex; GetVisibleAndTextSpan(text, spans, currentSpanIndex, out var visibleSpan, out var visibleTextSpan); var end = visibleSpan.End; var current = root.FindToken(visibleTextSpan.Start).Parent; while (current != null) { if (current.Span.Start == visibleTextSpan.Start) { var blockType = GetRazorCodeBlockType(visibleSpan.Start); if (blockType == RazorCodeBlockType.Explicit) { var baseIndentation = GetBaseIndentation(root, text, visibleSpan); return new BaseIndentationFormattingRule(root, TextSpan.FromBounds(visibleSpan.Start, end), baseIndentation, _vbHelperFormattingRule); } } if (current.Span.Start < visibleSpan.Start) { var blockType = GetRazorCodeBlockType(visibleSpan.Start); if (blockType == RazorCodeBlockType.Block || blockType == RazorCodeBlockType.Helper) { var baseIndentation = GetBaseIndentation(root, text, visibleSpan); return new BaseIndentationFormattingRule(root, TextSpan.FromBounds(visibleSpan.Start, end), baseIndentation, _vbHelperFormattingRule); } if (currentSpanIndex == 0) { break; } GetVisibleAndTextSpan(text, spans, --currentSpanIndex, out visibleSpan, out visibleTextSpan); continue; } current = current.Parent; } } var span = spans[spanIndex]; var indentation = GetBaseIndentation(root, text, span); return new BaseIndentationFormattingRule(root, span, indentation, _vbHelperFormattingRule); } private void GetVisibleAndTextSpan(SourceText text, List<TextSpan> spans, int spanIndex, out TextSpan visibleSpan, out TextSpan visibleTextSpan) { visibleSpan = spans[spanIndex]; visibleTextSpan = GetVisibleTextSpan(text, visibleSpan); if (visibleTextSpan.IsEmpty) { // span has no text in them visibleTextSpan = visibleSpan; } } private int GetBaseIndentation(SyntaxNode root, SourceText text, TextSpan span) { // Is this right? We should probably get this from the IVsContainedLanguageHost instead. var editorOptionsFactory = _componentModel.GetService<IEditorOptionsFactoryService>(); var editorOptions = editorOptionsFactory.GetOptions(_containedLanguage.DataBuffer); var additionalIndentation = GetAdditionalIndentation(root, text, span); int useTabs = 0, tabSize = 0; // Skip over the first line, since it's in "Venus space" anyway. var startingLine = text.Lines.GetLineFromPosition(span.Start); for (var line = startingLine; line.Start < span.End; line = text.Lines[line.LineNumber + 1]) { Marshal.ThrowExceptionForHR( this.ContainedLanguage.ContainedLanguageHost.GetLineIndent( line.LineNumber, out var baseIndentationString, out var parent, out var indentSize, out useTabs, out tabSize)); if (!string.IsNullOrEmpty(baseIndentationString)) { return baseIndentationString.GetColumnFromLineOffset(baseIndentationString.Length, editorOptions.GetTabSize()) + additionalIndentation; } } return additionalIndentation; } private TextSpan GetVisibleTextSpan(SourceText text, TextSpan visibleSpan, bool uptoFirstAndLastLine = false) { var start = visibleSpan.Start; for (; start < visibleSpan.End; start++) { if (!char.IsWhiteSpace(text[start])) { break; } } var end = visibleSpan.End - 1; if (start <= end) { for (; start <= end; end--) { if (!char.IsWhiteSpace(text[end])) { break; } } } if (uptoFirstAndLastLine) { var firstLine = text.Lines.GetLineFromPosition(visibleSpan.Start); var lastLine = text.Lines.GetLineFromPosition(visibleSpan.End); if (firstLine.LineNumber < lastLine.LineNumber) { start = (start < firstLine.End) ? start : firstLine.End; end = (lastLine.Start < end + 1) ? end : lastLine.Start - 1; } } return (start <= end) ? TextSpan.FromBounds(start, end + 1) : default(TextSpan); } private int GetAdditionalIndentation(SyntaxNode root, SourceText text, TextSpan span) { if (_hostType == HostType.HTML) { return _workspace.Options.GetOption(FormattingOptions.IndentationSize, this.Project.Language); } if (_hostType == HostType.Razor) { var type = GetRazorCodeBlockType(span.Start); // razor block if (type == RazorCodeBlockType.Block) { // more workaround for csharp razor case. when } for csharp razor code block is just typed, "}" exist // in both subject and surface buffer and there is no easy way to figure out who owns } just typed. // in this case, we let razor owns it. later razor will remove } from subject buffer if it is something // razor owns. if (this.Project.Language == LanguageNames.CSharp) { var textSpan = GetVisibleTextSpan(text, span); var end = textSpan.End - 1; if (end >= 0 && text[end] == '}') { var token = root.FindToken(end); var syntaxFact = _workspace.Services.GetLanguageServices(Project.Language).GetService<ISyntaxFactsService>(); if (token.Span.Start == end && syntaxFact != null) { if (syntaxFact.TryGetCorrespondingOpenBrace(token, out var openBrace) && !textSpan.Contains(openBrace.Span)) { return 0; } } } } // same as C#, but different text is in the buffer if (this.Project.Language == LanguageNames.VisualBasic) { var textSpan = GetVisibleTextSpan(text, span); var subjectSnapshot = _containedLanguage.SubjectBuffer.CurrentSnapshot; var end = textSpan.End - 1; if (end >= 0) { var ch = subjectSnapshot[end]; if (CheckCode(subjectSnapshot, textSpan.End, ch, VBRazorBlock, checkAt: false) || CheckCode(subjectSnapshot, textSpan.End, ch, FunctionsRazor, checkAt: false)) { var token = root.FindToken(end, findInsideTrivia: true); var syntaxFact = _workspace.Services.GetLanguageServices(Project.Language).GetService<ISyntaxFactsService>(); if (token.Span.End == textSpan.End && syntaxFact != null) { if (syntaxFact.IsSkippedTokensTrivia(token.Parent)) { return 0; } } } } } return _workspace.Options.GetOption(FormattingOptions.IndentationSize, this.Project.Language); } } return 0; } private RazorCodeBlockType GetRazorCodeBlockType(int position) { Debug.Assert(_hostType == HostType.Razor); var subjectBuffer = (IProjectionBuffer)this.GetOpenTextBuffer(); var subjectSnapshot = subjectBuffer.CurrentSnapshot; var surfaceSnapshot = ((IProjectionBuffer)_containedLanguage.DataBuffer).CurrentSnapshot; var surfacePoint = surfaceSnapshot.MapFromSourceSnapshot(new SnapshotPoint(subjectSnapshot, position), PositionAffinity.Predecessor); if (!surfacePoint.HasValue) { // how this can happen? return RazorCodeBlockType.Implicit; } var ch = char.ToLower(surfaceSnapshot[Math.Max(surfacePoint.Value - 1, 0)]); // razor block if (IsCodeBlock(surfaceSnapshot, surfacePoint.Value, ch)) { return RazorCodeBlockType.Block; } if (ch == RazorExplicit) { return RazorCodeBlockType.Explicit; } if (CheckCode(surfaceSnapshot, surfacePoint.Value, HelperRazor)) { return RazorCodeBlockType.Helper; } return RazorCodeBlockType.Implicit; } private bool IsCodeBlock(ITextSnapshot surfaceSnapshot, int position, char ch) { if (this.Project.Language == LanguageNames.CSharp) { return CheckCode(surfaceSnapshot, position, ch, CSharpRazorBlock) || CheckCode(surfaceSnapshot, position, ch, FunctionsRazor, CSharpRazorBlock); } if (this.Project.Language == LanguageNames.VisualBasic) { return CheckCode(surfaceSnapshot, position, ch, VBRazorBlock) || CheckCode(surfaceSnapshot, position, ch, FunctionsRazor); } return false; } private bool CheckCode(ITextSnapshot snapshot, int position, char ch, string tag, bool checkAt = true) { if (ch != tag[tag.Length - 1] || position < tag.Length) { return false; } var start = position - tag.Length; var razorTag = snapshot.GetText(start, tag.Length); return string.Equals(razorTag, tag, StringComparison.OrdinalIgnoreCase) && (!checkAt || snapshot[start - 1] == RazorExplicit); } private bool CheckCode(ITextSnapshot snapshot, int position, string tag) { int i = position - 1; if (i < 0) { return false; } for (; i >= 0; i--) { if (!char.IsWhiteSpace(snapshot[i])) { break; } } var ch = snapshot[i]; position = i + 1; return CheckCode(snapshot, position, ch, tag); } private bool CheckCode(ITextSnapshot snapshot, int position, char ch, string tag1, string tag2) { if (!CheckCode(snapshot, position, ch, tag2, checkAt: false)) { return false; } return CheckCode(snapshot, position - tag2.Length, tag1); } public ITextUndoHistory GetTextUndoHistory() { // In Venus scenarios, the undo history is associated with the data buffer return _componentModel.GetService<ITextUndoHistoryRegistry>().GetHistory(_containedLanguage.DataBuffer); } public uint GetItemId() { AssertIsForeground(); if (_itemMoniker == null) { return (uint)VSConstants.VSITEMID.Nil; } return Project.Hierarchy.ParseCanonicalName(_itemMoniker, out var itemId) == VSConstants.S_OK ? itemId : (uint)VSConstants.VSITEMID.Nil; } private enum RazorCodeBlockType { Block, Explicit, Implicit, Helper } private enum HostType { HTML, Razor, XOML } } }
// 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.Contracts; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace System.Threading { /// <summary> /// Stores the hash code and the Monitor synchronization object for all managed objects used /// with the Monitor.Enter/TryEnter/Exit methods. /// </summary> /// <remarks> /// This implementation is faster than ConditionalWeakTable for two reasons: /// 1) We store the synchronization entry index in the object header, which avoids a hash table /// lookup. /// 2) We store a strong reference to the synchronization object, which allows retrieving it /// much faster than going through a DependentHandle. /// /// SyncTable assigns a unique table entry to each object it is asked for. The assigned entry /// index is stored in the object header and preserved during table expansion (we never shrink /// the table). Each table entry contains a long weak GC handle representing the owner object /// of that entry and may be in one of the three states: /// 1) Free (IsAllocated == false). These entries have been either never used or used and /// freed/recycled after their owners died. We keep a linked list of recycled entries and /// use it to dispense entries to new objects. /// 2) Live (Target != null). These entries store the hash code and the Monitor synchronization /// object assigned to Target. /// 3) Dead (Target == null). These entries lost their owners and are ready to be freed/recycled. /// /// Here is the state diagram for an entry: /// Free --{AssignEntry}--> Live --{GC}--> Dead --{(Recycle|Free)DeadEntries} --> Free /// /// Dead entries are freed/recycled when there are no free entries available (in this case they /// are recycled and added to the free list) or periodically from the finalizer thread (in this /// case they are freed without adding to the free list). That small difference in behavior /// allows using a more fine-grained locking when freeing is done on the finalizer thread. /// /// Thread safety is ensured by two locks: s_freeEntriesLock and s_usedEntriesLock. The former /// protects everything related to free entries: s_freeEntryList, s_unusedEntryIndex, and the /// content of free entries in the s_entries array. The latter protects the content of used /// entries in the s_entries array. Growing the table and updating the s_entries reference is /// protected by both locks. Having two locks is not required for correctness, they may be /// merged into a single coarser lock. /// /// The public methods operates on live entries only and acquire the following locks: /// * GetLockObject : Lock-free. We always allocate a Monitor synchronization object before /// the entry goes live. The returned object may be used as normal; no /// additional synchronization required. /// * GetHashCode : Lock-free. A stale zero value may be returned. /// * SetHashCode : Acquires s_usedEntriesLock. /// * AssignEntry : Acquires s_freeEntriesLock if at least one free entry is available; /// otherwise also acquires s_usedEntriesLock to recycle dead entries /// and/or grow the table. /// /// The important part here is that all read operations are lock-free and fast, and write /// operations are expected to be much less frequent than read ones. /// /// One possible future optimization is recycling Monitor synchronization objects from dead /// entries. /// </remarks> [EagerStaticClassConstruction] internal static class SyncTable { /// <summary> /// The initial size of the table. Must be positive and not greater than /// ObjectHeader.MASK_HASHCODE_INDEX + 1. /// </summary> /// <remarks> /// CLR uses 250 as the initial table size. In contrast to CoreRT, CLR creates sync /// entries less frequently since uncontended Monitor synchronization employs a thin lock /// stored in the object header. /// </remarks> #if DEBUG // Exercise table expansion more frequently in debug builds private const int InitialSize = 1; #else private const int InitialSize = 1 << 7; #endif /// <summary> /// The table size threshold for doubling in size. Must be positive. /// </summary> private const int DoublingSizeThreshold = 1 << 20; /// <summary> /// Protects everything related to free entries: s_freeEntryList, s_unusedEntryIndex, and the /// content of free entries in the s_entries array. Also protects growing the table. /// </summary> internal static Lock s_freeEntriesLock = new Lock(); /// <summary> /// The dynamically growing array of sync entries. /// </summary> private static Entry[] s_entries = new Entry[InitialSize]; /// <summary> /// The head of the list of freed entries linked using the Next property. /// </summary> private static int s_freeEntryList = 0; /// <summary> /// The index of the lowest never used entry. We skip the 0th entry and start with 1. /// If all entries have been used, s_unusedEntryIndex == s_entries.Length. This counter /// never decreases. /// </summary> private static int s_unusedEntryIndex = 1; /// <summary> /// Protects the content of used entries in the s_entries array. Also protects growing /// the table. /// </summary> private static Lock s_usedEntriesLock = new Lock(); /// <summary> /// Creates the initial array of entries and the dead entries collector. /// </summary> static SyncTable() { // Create only one collector instance and do not store any references to it, so it may // be finalized. Use GC.KeepAlive to ensure the allocation will not be optimized out. GC.KeepAlive(new DeadEntryCollector()); } /// <summary> /// Assigns a sync table entry to the object in a thread-safe way. /// </summary> public static unsafe int AssignEntry(object obj, int* pHeader) { // Allocate the synchronization object outside the lock Lock lck = new Lock(); using (LockHolder.Hold(s_freeEntriesLock)) { // After acquiring the lock check whether another thread already assigned the sync entry int hashOrIndex; if (ObjectHeader.GetSyncEntryIndex(*pHeader, out hashOrIndex)) { return hashOrIndex; } // Allocate a new sync entry. First, make sure all data is ready. This call may OOM. GCHandle owner = GCHandle.Alloc(obj, GCHandleType.WeakTrackResurrection); try { // Now find a free entry in the table int syncIndex; if (s_freeEntryList != 0) { // Grab a free entry from the list syncIndex = s_freeEntryList; s_freeEntryList = s_entries[syncIndex].Next; s_entries[syncIndex].Next = 0; } else if (s_unusedEntryIndex < s_entries.Length) { // Grab the next unused entry syncIndex = s_unusedEntryIndex++; } else { // No free entries, use the slow path. This call may OOM. syncIndex = EnsureFreeEntry(); } // Found a free entry to assign Contract.Assert(!s_entries[syncIndex].Owner.IsAllocated); Contract.Assert(s_entries[syncIndex].Lock == null); Contract.Assert(s_entries[syncIndex].HashCode == 0); // Set up the new entry. We should not fail after this point. s_entries[syncIndex].Lock = lck; // The hash code will be set by the SetSyncEntryIndex call below s_entries[syncIndex].Owner = owner; owner = default(GCHandle); // Finally, store the entry index in the object header ObjectHeader.SetSyncEntryIndex(pHeader, syncIndex); return syncIndex; } finally { if (owner.IsAllocated) { owner.Free(); } } } } /// <summary> /// Creates a free entry by either freeing dead entries or growing the sync table. /// This method either returns an index of a free entry or throws an OOM exception /// keeping the state valid. /// </summary> private static int EnsureFreeEntry() { Contract.Assert(s_freeEntriesLock.IsAcquired); Contract.Assert((s_freeEntryList == 0) && (s_unusedEntryIndex == s_entries.Length)); int syncIndex; // Scan for dead and freed entries and put them into s_freeEntryList int recycledEntries = RecycleDeadEntries(); if (s_freeEntryList != 0) { // If the table is almost full (less than 1/8 of free entries), try growing it // to avoid frequent RecycleDeadEntries scans, which may degrade performance. if (recycledEntries < (s_entries.Length >> 3)) { try { Grow(); } catch (OutOfMemoryException) { // Since we still have free entries, ignore memory shortage } } syncIndex = s_freeEntryList; s_freeEntryList = s_entries[syncIndex].Next; s_entries[syncIndex].Next = 0; } else { // No entries were recycled; must grow the table. // This call may throw OOM; keep the state valid. Grow(); Contract.Assert(s_unusedEntryIndex < s_entries.Length); syncIndex = s_unusedEntryIndex++; } return syncIndex; } /// <summary> /// Scans the table and recycles all dead and freed entries adding them to the free entry /// list. Returns the number of recycled entries. /// </summary> private static int RecycleDeadEntries() { Contract.Assert(s_freeEntriesLock.IsAcquired); using (LockHolder.Hold(s_usedEntriesLock)) { int recycledEntries = 0; for (int idx = s_unusedEntryIndex; --idx > 0;) { bool freed = !s_entries[idx].Owner.IsAllocated; if (freed || (s_entries[idx].Owner.Target == null)) { s_entries[idx].Lock = null; s_entries[idx].Next = s_freeEntryList; if (!freed) { s_entries[idx].Owner.Free(); } s_freeEntryList = idx; recycledEntries++; } } return recycledEntries; } } /// <summary> /// Scans the table and frees all dead entries without adding them to the free entry list. /// Runs on the finalizer thread. /// </summary> private static void FreeDeadEntries() { // Be cautious as this method may run in parallel with grabbing a free entry in the // AssignEntry method. The potential race is checking IsAllocated && (Target == null) // while a new non-zero (allocated) GCHandle is being assigned to the Owner field // containing a zero (non-allocated) GCHandle. That must be safe as a GCHandle is // just an IntPtr, which is assigned atomically, and Target has load dependency on it. using (LockHolder.Hold(s_usedEntriesLock)) { // We do not care if the s_unusedEntryIndex value is stale here; it suffices that // the s_entries reference is locked and s_unusedEntryIndex points within that array. Contract.Assert(s_unusedEntryIndex <= s_entries.Length); for (int idx = s_unusedEntryIndex; --idx > 0;) { bool allocated = s_entries[idx].Owner.IsAllocated; if (allocated && (s_entries[idx].Owner.Target == null)) { s_entries[idx].Lock = null; s_entries[idx].Next = 0; s_entries[idx].Owner.Free(); } } } } /// <summary> /// Grows the sync table. If memory is not available, it throws an OOM exception keeping /// the state valid. /// </summary> private static void Grow() { Contract.Assert(s_freeEntriesLock.IsAcquired); int oldSize = s_entries.Length; int newSize = CalculateNewSize(oldSize); Entry[] newEntries = new Entry[newSize]; using (LockHolder.Hold(s_usedEntriesLock)) { // Copy the shallow content of the table Array.Copy(s_entries, newEntries, oldSize); // Publish the new table. Lock-free reader threads must not see the new value of // s_entries until all the content is copied to the new table. Volatile.Write(ref s_entries, newEntries); } } /// <summary> /// Calculates the new size of the sync table if it needs to grow. Throws an OOM exception /// in case of size overflow. /// </summary> private static int CalculateNewSize(int oldSize) { Contract.Assert(oldSize > 0); Contract.Assert(ObjectHeader.MASK_HASHCODE_INDEX < int.MaxValue); int newSize; if (oldSize <= DoublingSizeThreshold) { // Double in size; overflow is checked below newSize = unchecked(oldSize * 2); } else { // For bigger tables use a smaller factor 1.5 Contract.Assert(oldSize > 1); newSize = unchecked(oldSize + (oldSize >> 1)); } // All indices must fit in the mask, limit the size accordingly newSize = Math.Min(newSize, ObjectHeader.MASK_HASHCODE_INDEX + 1); // Make sure the new size has not overflowed and is actually bigger if (newSize <= oldSize) { throw new OutOfMemoryException(); } return newSize; } /// <summary> /// Returns the stored hash code. The zero value indicates the hash code has not yet been /// assigned or visible to this thread. /// </summary> public static int GetHashCode(int syncIndex) { // This thread may be looking at an old version of s_entries. If the old version had // no hash code stored, GetHashCode returns zero and the subsequent SetHashCode call // will resolve the potential race. return s_entries[syncIndex].HashCode; } /// <summary> /// Sets the hash code in a thread-safe way. /// </summary> public static int SetHashCode(int syncIndex, int hashCode) { Contract.Assert((0 < syncIndex) && (syncIndex < s_unusedEntryIndex)); // Acquire the lock to ensure we are updating the latest version of s_entries. This // lock may be avoided if we store the hash code and Monitor synchronization data in // the same object accessed by a reference. using (LockHolder.Hold(s_usedEntriesLock)) { int currentHash = s_entries[syncIndex].HashCode; if (currentHash != 0) { return currentHash; } s_entries[syncIndex].HashCode = hashCode; return hashCode; } } /// <summary> /// Sets the hash code assuming the caller holds s_freeEntriesLock. Use for not yet /// published entries only. /// </summary> public static void MoveHashCodeToNewEntry(int syncIndex, int hashCode) { Contract.Assert(s_freeEntriesLock.IsAcquired); Contract.Assert((0 < syncIndex) && (syncIndex < s_unusedEntryIndex)); s_entries[syncIndex].HashCode = hashCode; } /// <summary> /// Returns the Monitor synchronization object. The return value is never null. /// </summary> public static Lock GetLockObject(int syncIndex) { // Note that we do not take a lock here. When we replace s_entries, we preserve all // indices and Lock references. return s_entries[syncIndex].Lock; } /// <summary> /// Periodically scans the SyncTable and frees dead entries. It runs on the finalizer /// thread roughly every full (i.e. generation 2) garbage collection. /// </summary> private sealed class DeadEntryCollector { ~DeadEntryCollector() { if (!Environment.HasShutdownStarted) { SyncTable.FreeDeadEntries(); // Resurrect itself by re-registering for finalization GC.ReRegisterForFinalize(this); } } } /// <summary> /// Stores the Monitor synchronization object and the hash code for an arbitrary object. /// </summary> private struct Entry { /// <summary> /// The Monitor synchronization object. /// </summary> public Lock Lock; /// <summary> /// Contains either the hash code or the index of the next freed entry. /// </summary> private int _hashOrNext; /// <summary> /// The long weak GC handle representing the owner object of this sync entry. /// </summary> public GCHandle Owner; /// <summary> /// For entries in use, this property gets or sets the hash code of the owner object. /// The zero value indicates the hash code has not yet been assigned. /// </summary> public int HashCode { get { return _hashOrNext; } set { _hashOrNext = value; } } /// <summary> /// For freed entries, this property gets or sets the index of the next freed entry. /// The zero value indicates the end of the list. /// </summary> public int Next { get { return _hashOrNext; } set { _hashOrNext = value; } } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; namespace NuGet { // REVIEW: Do we need this class? Should this logic be moved to ProjectManager? public static class ProjectSystemExtensions { public static void AddFiles(this IProjectSystem project, IEnumerable<IPackageFile> files, IDictionary<string, IPackageFileTransformer> fileTransformers) { // Convert files to a list List<IPackageFile> fileList = files.ToList(); // See if the project system knows how to sort the files var fileComparer = project as IComparer<IPackageFile>; if (fileComparer != null) { fileList.Sort(fileComparer); } var batchProcessor = project as IBatchProcessor<string>; try { if (batchProcessor != null) { var paths = fileList.Select(file => ResolvePath(fileTransformers, file.EffectivePath)); batchProcessor.BeginProcessing(paths, PackageAction.Install); } foreach (IPackageFile file in fileList) { if (file.IsEmptyFolder()) { continue; } IPackageFileTransformer transformer; // Resolve the target path string path = ResolveTargetPath(project, fileTransformers, file.EffectivePath, out transformer); if (project.IsSupportedFile(path)) { // Try to get the package file modifier for the extension if (transformer != null) { // If the transform was done then continue transformer.TransformFile(file, path, project); } else { project.AddFileWithCheck(path, file.GetStream); } } } } finally { if (batchProcessor != null) { batchProcessor.EndProcessing(); } } } [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We want delete to be robust, when exceptions occur we log then and move on")] public static void DeleteFiles(this IProjectSystem project, IEnumerable<IPackageFile> files, IEnumerable<IPackage> otherPackages, IDictionary<string, IPackageFileTransformer> fileTransformers) { IPackageFileTransformer transformer; // First get all directories that contain files var directoryLookup = files.ToLookup(p => Path.GetDirectoryName(ResolveTargetPath(project, fileTransformers, p.EffectivePath, out transformer))); // Get all directories that this package may have added var directories = from grouping in directoryLookup from directory in FileSystemExtensions.GetDirectories(grouping.Key) orderby directory.Length descending select directory; // Remove files from every directory foreach (var directory in directories) { var directoryFiles = directoryLookup.Contains(directory) ? directoryLookup[directory] : Enumerable.Empty<IPackageFile>(); if (!project.DirectoryExists(directory)) { continue; } var batchProcessor = project as IBatchProcessor<string>; try { if (batchProcessor != null) { var paths = directoryFiles.Select(file => ResolvePath(fileTransformers, file.EffectivePath)); batchProcessor.BeginProcessing(paths, PackageAction.Uninstall); } foreach (var file in directoryFiles) { if (file.IsEmptyFolder()) { continue; } // Resolve the path string path = ResolveTargetPath(project, fileTransformers, file.EffectivePath, out transformer); if (project.IsSupportedFile(path)) { if (transformer != null) { var matchingFiles = from p in otherPackages from otherFile in project.GetCompatibleItemsCore(p.GetContentFiles()) where otherFile.EffectivePath.Equals(file.EffectivePath, StringComparison.OrdinalIgnoreCase) select otherFile; try { transformer.RevertFile(file, path, matchingFiles, project); } catch (Exception e) { // Report a warning and move on project.Logger.Log(MessageLevel.Warning, e.Message); } } else { project.DeleteFileSafe(path, file.GetStream); } } } // If the directory is empty then delete it if (!project.GetFilesSafe(directory).Any() && !project.GetDirectoriesSafe(directory).Any()) { project.DeleteDirectorySafe(directory, recursive: false); } } finally { if (batchProcessor != null) { batchProcessor.EndProcessing(); } } } } public static bool TryGetCompatibleItems<T>(this IProjectSystem projectSystem, IEnumerable<T> items, out IEnumerable<T> compatibleItems) where T : IFrameworkTargetable { if (projectSystem == null) { throw new ArgumentNullException("projectSystem"); } if (items == null) { throw new ArgumentNullException("items"); } return VersionUtility.TryGetCompatibleItems<T>(projectSystem.TargetFramework, items, out compatibleItems); } internal static IEnumerable<T> GetCompatibleItemsCore<T>(this IProjectSystem projectSystem, IEnumerable<T> items) where T : IFrameworkTargetable { IEnumerable<T> compatibleItems; if (VersionUtility.TryGetCompatibleItems(projectSystem.TargetFramework, items, out compatibleItems)) { return compatibleItems; } return Enumerable.Empty<T>(); } private static string ResolvePath(IDictionary<string, IPackageFileTransformer> fileTransformers, string effectivePath) { // Try to get the package file modifier for the extension string extension = Path.GetExtension(effectivePath); IPackageFileTransformer transformer; if (fileTransformers.TryGetValue(extension, out transformer)) { // Remove the transformer extension (e.g. .pp, .transform) string truncatedPath = RemoveExtension(effectivePath); // Bug 1686: Don't allow transforming packages.config.transform string fileName = Path.GetFileName(truncatedPath); if (!Constants.PackageReferenceFile.Equals(fileName, StringComparison.OrdinalIgnoreCase)) { effectivePath = truncatedPath; } } return effectivePath; } private static string ResolveTargetPath(IProjectSystem projectSystem, IDictionary<string, IPackageFileTransformer> fileTransformers, string effectivePath, out IPackageFileTransformer transformer) { // Try to get the package file modifier for the extension string extension = Path.GetExtension(effectivePath); if (fileTransformers.TryGetValue(extension, out transformer)) { // Remove the transformer extension (e.g. .pp, .transform) string truncatedPath = RemoveExtension(effectivePath); // Bug 1686: Don't allow transforming packages.config.transform, // but we still want to copy packages.config.transform as-is into the project. string fileName = Path.GetFileName(truncatedPath); if (Constants.PackageReferenceFile.Equals(fileName, StringComparison.OrdinalIgnoreCase)) { // setting to null means no pre-processing of this file transformer = null; } else { effectivePath = truncatedPath; } } return projectSystem.ResolvePath(effectivePath); } private static string RemoveExtension(string path) { // Remove the extension from the file name, preserving the directory return Path.Combine(Path.GetDirectoryName(path), Path.GetFileNameWithoutExtension(path)); } } }
//------------------------------------------------------------------------------ // <copyright file="ObjectListItem.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System; using System.Collections; using System.ComponentModel; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Security.Permissions; namespace System.Web.UI.MobileControls { /* * Object List Item class. * * Copyright (c) 2000 Microsoft Corporation */ /// <include file='doc\ObjectListItem.uex' path='docs/doc[@for="ObjectListItem"]/*' /> [ ToolboxItem(false) ] [AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)] [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal)] [Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")] public class ObjectListItem : MobileListItem { private String[] _fields; private bool _dirty; private ObjectList _owner; internal ObjectListItem(ObjectList owner) : this(owner, null) { } internal ObjectListItem(ObjectList owner, Object dataItem) : base(dataItem, null, null) { _owner = owner; _fields = new String[owner.AllFields.Count]; } private int FieldIndexFromKey(String key) { int index = _owner.AllFields.IndexOf (key); if (index == -1) { throw new ArgumentException( SR.GetString(SR.ObjectList_FieldNotFound, key)); } return index; } /// <include file='doc\ObjectListItem.uex' path='docs/doc[@for="ObjectListItem.this"]/*' /> public String this[String key] { get { return this[FieldIndexFromKey (key)]; } set { this[FieldIndexFromKey (key)] = value; } } /// <include file='doc\ObjectListItem.uex' path='docs/doc[@for="ObjectListItem.this1"]/*' /> public String this[int index] { get { String s = _fields[index]; return (s != null) ? s : String.Empty; } set { _fields[index] = value; if (IsTrackingViewState) { _dirty = true; } } } /// <include file='doc\ObjectListItem.uex' path='docs/doc[@for="ObjectListItem.Equals"]/*' /> public override bool Equals(Object obj) { ObjectListItem other = obj as ObjectListItem; if (other == null) { return false; } if (_fields == null && other._fields == null) { return true; } else if (_fields == null || other._fields == null) { return false; } if (_fields.Length != other._fields.Length) { return false; } for (int i = 0; i < _fields.Length; i++) { if (this[i] != other[i]) { return false; } } if(!Value.Equals(other.Value) || !Text.Equals(other.Text)) { return false; } return true; } /// <include file='doc\ObjectListItem.uex' path='docs/doc[@for="ObjectListItem.GetHashCode"]/*' /> public override int GetHashCode() { if (_fields.Length > 0) { return _fields[0].GetHashCode(); } else { return Value.GetHashCode(); } } ///////////////////////////////////////////////////////////////////////// // STATE MANAGEMENT, FOR ITEM'S DATA (NON-CONTROL) STATE. ///////////////////////////////////////////////////////////////////////// internal override Object SaveDataState() { Object baseState = base.SaveDataState (); if (_dirty && _fields != null) { int fieldCount = _fields.Length; Object[] itemState = new Object[fieldCount + 1]; itemState[0] = baseState; for (int i = 0; i < fieldCount; i++) { itemState[i + 1] = _fields[i]; } return itemState; } else if (baseState != null) { return new Object[1] { baseState }; } else { return null; } } internal override void LoadDataState(Object state) { if (state != null) { Object[] itemState = (Object[])state; int fieldCount = itemState.Length; base.LoadDataState (itemState[0]); _fields = new String[fieldCount - 1]; for (int i = 1; i < fieldCount; i++) { _fields[i - 1] = (String)itemState[i]; } } } internal override bool Dirty { get { return _dirty || base.Dirty; } set { _dirty = true; base.Dirty = value; } } ///////////////////////////////////////////////////////////////////////// // EVENT BUBBLING ///////////////////////////////////////////////////////////////////////// /// <include file='doc\ObjectListItem.uex' path='docs/doc[@for="ObjectListItem.OnBubbleEvent"]/*' /> protected override bool OnBubbleEvent(Object source, EventArgs e) { if (e is CommandEventArgs) { ObjectListCommandEventArgs args = new ObjectListCommandEventArgs(this, source, (CommandEventArgs)e); RaiseBubbleEvent (this, args); return true; } return false; } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Compute.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedRegionInstanceGroupManagersClientTest { [xunit::FactAttribute] public void GetRequestObject() { moq::Mock<RegionInstanceGroupManagers.RegionInstanceGroupManagersClient> mockGrpcClient = new moq::Mock<RegionInstanceGroupManagers.RegionInstanceGroupManagersClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRegionInstanceGroupManagerRequest request = new GetRegionInstanceGroupManagerRequest { Region = "regionedb20d96", Project = "projectaa6ff846", InstanceGroupManager = "instance_group_manager71b45dfc", }; InstanceGroupManager expectedResponse = new InstanceGroupManager { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Zone = "zone255f4ea8", CreationTimestamp = "creation_timestamp235e59a1", StatefulPolicy = new StatefulPolicy(), TargetSize = -93132225, InstanceGroup = "instance_group6bf5a5ef", Region = "regionedb20d96", Versions = { new InstanceGroupManagerVersion(), }, CurrentActions = new InstanceGroupManagerActionsSummary(), UpdatePolicy = new InstanceGroupManagerUpdatePolicy(), Status = new InstanceGroupManagerStatus(), Fingerprint = "fingerprint009e6052", InstanceTemplate = "instance_template6cae3083", TargetPools = { "target_pools6fc69e1f", }, BaseInstanceName = "base_instance_name7c1f304c", Description = "description2cf9da67", NamedPorts = { new NamedPort(), }, SelfLink = "self_link7e87f12d", AutoHealingPolicies = { new InstanceGroupManagerAutoHealingPolicy(), }, DistributionPolicy = new DistributionPolicy(), }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); RegionInstanceGroupManagersClient client = new RegionInstanceGroupManagersClientImpl(mockGrpcClient.Object, null); InstanceGroupManager response = client.Get(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRequestObjectAsync() { moq::Mock<RegionInstanceGroupManagers.RegionInstanceGroupManagersClient> mockGrpcClient = new moq::Mock<RegionInstanceGroupManagers.RegionInstanceGroupManagersClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRegionInstanceGroupManagerRequest request = new GetRegionInstanceGroupManagerRequest { Region = "regionedb20d96", Project = "projectaa6ff846", InstanceGroupManager = "instance_group_manager71b45dfc", }; InstanceGroupManager expectedResponse = new InstanceGroupManager { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Zone = "zone255f4ea8", CreationTimestamp = "creation_timestamp235e59a1", StatefulPolicy = new StatefulPolicy(), TargetSize = -93132225, InstanceGroup = "instance_group6bf5a5ef", Region = "regionedb20d96", Versions = { new InstanceGroupManagerVersion(), }, CurrentActions = new InstanceGroupManagerActionsSummary(), UpdatePolicy = new InstanceGroupManagerUpdatePolicy(), Status = new InstanceGroupManagerStatus(), Fingerprint = "fingerprint009e6052", InstanceTemplate = "instance_template6cae3083", TargetPools = { "target_pools6fc69e1f", }, BaseInstanceName = "base_instance_name7c1f304c", Description = "description2cf9da67", NamedPorts = { new NamedPort(), }, SelfLink = "self_link7e87f12d", AutoHealingPolicies = { new InstanceGroupManagerAutoHealingPolicy(), }, DistributionPolicy = new DistributionPolicy(), }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<InstanceGroupManager>(stt::Task.FromResult(expectedResponse), null, null, null, null)); RegionInstanceGroupManagersClient client = new RegionInstanceGroupManagersClientImpl(mockGrpcClient.Object, null); InstanceGroupManager responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); InstanceGroupManager responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void Get() { moq::Mock<RegionInstanceGroupManagers.RegionInstanceGroupManagersClient> mockGrpcClient = new moq::Mock<RegionInstanceGroupManagers.RegionInstanceGroupManagersClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRegionInstanceGroupManagerRequest request = new GetRegionInstanceGroupManagerRequest { Region = "regionedb20d96", Project = "projectaa6ff846", InstanceGroupManager = "instance_group_manager71b45dfc", }; InstanceGroupManager expectedResponse = new InstanceGroupManager { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Zone = "zone255f4ea8", CreationTimestamp = "creation_timestamp235e59a1", StatefulPolicy = new StatefulPolicy(), TargetSize = -93132225, InstanceGroup = "instance_group6bf5a5ef", Region = "regionedb20d96", Versions = { new InstanceGroupManagerVersion(), }, CurrentActions = new InstanceGroupManagerActionsSummary(), UpdatePolicy = new InstanceGroupManagerUpdatePolicy(), Status = new InstanceGroupManagerStatus(), Fingerprint = "fingerprint009e6052", InstanceTemplate = "instance_template6cae3083", TargetPools = { "target_pools6fc69e1f", }, BaseInstanceName = "base_instance_name7c1f304c", Description = "description2cf9da67", NamedPorts = { new NamedPort(), }, SelfLink = "self_link7e87f12d", AutoHealingPolicies = { new InstanceGroupManagerAutoHealingPolicy(), }, DistributionPolicy = new DistributionPolicy(), }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); RegionInstanceGroupManagersClient client = new RegionInstanceGroupManagersClientImpl(mockGrpcClient.Object, null); InstanceGroupManager response = client.Get(request.Project, request.Region, request.InstanceGroupManager); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAsync() { moq::Mock<RegionInstanceGroupManagers.RegionInstanceGroupManagersClient> mockGrpcClient = new moq::Mock<RegionInstanceGroupManagers.RegionInstanceGroupManagersClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRegionInstanceGroupManagerRequest request = new GetRegionInstanceGroupManagerRequest { Region = "regionedb20d96", Project = "projectaa6ff846", InstanceGroupManager = "instance_group_manager71b45dfc", }; InstanceGroupManager expectedResponse = new InstanceGroupManager { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Zone = "zone255f4ea8", CreationTimestamp = "creation_timestamp235e59a1", StatefulPolicy = new StatefulPolicy(), TargetSize = -93132225, InstanceGroup = "instance_group6bf5a5ef", Region = "regionedb20d96", Versions = { new InstanceGroupManagerVersion(), }, CurrentActions = new InstanceGroupManagerActionsSummary(), UpdatePolicy = new InstanceGroupManagerUpdatePolicy(), Status = new InstanceGroupManagerStatus(), Fingerprint = "fingerprint009e6052", InstanceTemplate = "instance_template6cae3083", TargetPools = { "target_pools6fc69e1f", }, BaseInstanceName = "base_instance_name7c1f304c", Description = "description2cf9da67", NamedPorts = { new NamedPort(), }, SelfLink = "self_link7e87f12d", AutoHealingPolicies = { new InstanceGroupManagerAutoHealingPolicy(), }, DistributionPolicy = new DistributionPolicy(), }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<InstanceGroupManager>(stt::Task.FromResult(expectedResponse), null, null, null, null)); RegionInstanceGroupManagersClient client = new RegionInstanceGroupManagersClientImpl(mockGrpcClient.Object, null); InstanceGroupManager responseCallSettings = await client.GetAsync(request.Project, request.Region, request.InstanceGroupManager, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); InstanceGroupManager responseCancellationToken = await client.GetAsync(request.Project, request.Region, request.InstanceGroupManager, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using Qwack.Math.Extensions; using static System.Math; namespace Qwack.Math { public static class Integration { public static double TrapezoidRule(Func<double, double> f, double a, double b, int nSteps) { //bounds check if (a >= b) return 0; var iSum = 0.0; var step = (b - a) / nSteps; double vA, vU; vA = f(a); while (a < b) { vU = f(a + step); iSum += 0.5 * (vU + vA) * (step); a += step; vA = vU; } return iSum; } //https://en.wikipedia.org/wiki/Simpson%27s_rule public static double SimpsonsRule(Func<double, double> f, double a, double b, int nSteps) { if (nSteps % 2 != 0) throw new Exception("nSteps must be even"); //bounds check if (a >= b) return 0; var iSum = f(a); var step = (b - a) / nSteps; var x = a; for (var i = 1; i < nSteps; i++) { x += step; iSum += ((i % 2 == 0) ? 2.0 : 4.0) * f(x); } iSum += f(b); return iSum * step / 3.0; } public static double SimpsonsRuleExtended(Func<double, double> f, double a, double b, int nSteps) { if (nSteps % 2 != 0 || nSteps <= 8) throw new Exception("nSteps must be even and > 8"); //bounds check if (a >= b) return 0; var h = (b - a) / nSteps; var iSum = 17 * f(a) + 59 * f(a + h) + 43 * f(a + h + h) + 49 * f(a + h + h + h); var x = a + h * 3; for (var i = 4; i <= nSteps - 4; i++) { x += h; iSum += 48 * f(x); } iSum += 49 * f(b - h - h - h) + 43 * f(b - h - h) + 59 * f(b - h) + 17 * f(b); return iSum * h / 48.0; } public static double LegendrePolynomial(double x, int n) { if (n <= 0) return 1.0; if (n == 1) return x; return ((2 * (n-1) + 1) * x * LegendrePolynomial(x, n - 1) - (n - 1) * LegendrePolynomial(x, n - 2)) / n; } public static double[] LegendrePolynomialRoots(int n) { switch(n) { case 1: return new[] { 0.0 }; case 2: var r2 = Sqrt(1.0 / 3.0); return new[] { -r2, r2 }; case 3: var r3 = Sqrt(3.0 / 5.0); return new[] { -r3, 0.0, r3 }; case 4: var r4a = Sqrt(3.0 / 7.0 - 2.0 / 7.0 * Sqrt(6.0 / 5.0)); var r4b = Sqrt(3.0 / 7.0 + 2.0 / 7.0 * Sqrt(6.0 / 5.0)); return new[] { -r4b, -r4a, r4a, r4b }; case 5: var r5a = Sqrt(5.0 - 2.0 * Sqrt(10.0 / 7.0)) / 3.0; var r5b = Sqrt(5.0 + 2.0 * Sqrt(10.0 / 7.0)) / 3.0; return new[] { -r5b, -r5a, 0.0, r5a, r5b }; case 6: var x6a = 0.238619186083197; var x6b = 0.661209386466265; var x6c = 0.932469514203152; return new[] { -x6a, -x6b, -x6c, x6a, x6b, x6c }; case 7: var x7a = 0.405845151377397; var x7b = 0.741531185599394; var x7c = 0.949107912342759; return new[] { -x7a, -x7b, -x7c, 0.0, x7a, x7b, x7c }; case 8: var x8a = 0.183434642495650; var x8b = 0.525532409916329; var x8c = 0.796666477413627; var x8d = 0.960289856497536; return new[] { -x8a, -x8b, -x8c, -x8d, x8a, x8b, x8c, x8d }; case 9: var x9a = 0.324253423403809; var x9b = 0.613371432700590; var x9c = 0.836031107326636; var x9d = 0.968160239507626; return new[] { -x9a, -x9b, -x9c, -x9d, 0.0, x9a, x9b, x9c, x9d }; case 10: var x10a = 0.148874338981631; var x10b = 0.433395394129247; var x10c = 0.679409568299024; var x10d = 0.865063366688985; var x10e = 0.973906528517172; return new[] { -x10a, -x10b, -x10c, -x10d, -x10e, x10a, x10b, x10c, x10d, x10e }; case 11: var x11a = 0.269543155952345; var x11b = 0.519096129110681; var x11c = 0.730152005574049; var x11d = 0.887062599768095; var x11e = 0.978228658146057; return new[] { -x11a, -x11b, -x11c, -x11d, -x11e, 0.0, x11a, x11b, x11c, x11d, x11e }; case 12: var x12a = 0.125333408511469; var x12b = 0.367831498918180; var x12c = 0.587317954286617; var x12d = 0.769902674194305; var x12e = 0.904117256370475; var x12f = 0.981560634246719; return new[] { -x12a, -x12b, -x12c, -x12d, -x12e, -x12f, x12a, x12b, x12c, x12d, x12e, x12f }; case 13: var x13a = 0.230458315955135; var x13b = 0.448492751036447; var x13c = 0.642349339440340; var x13d = 0.801578090733310; var x13e = 0.917598399222978; var x13f = 0.984183054718588; return new[] { -x13a, -x13b, -x13c, -x13d, -x13e, -x13f, 0.0, x13a, x13b, x13c, x13d, x13e, x13f }; case 14: var x14a = 0.108054948707344; var x14b = 0.319112368927890; var x14c = 0.515248636358154; var x14d = 0.687292904811685; var x14e = 0.827201315069765; var x14f = 0.928434883663574; var x14g = 0.986283808696812; return new[] { -x14a, -x14b, -x14c, -x14d, -x14e, -x14f, -x14g, x14a, x14b, x14c, x14d, x14e, x14f, x14g }; case 15: var x15a = 0.201194093997435; var x15b = 0.394151347077563; var x15c = 0.570972172608539; var x15d = 0.724417731360170; var x15e = 0.848206583410427; var x15f = 0.937273392400706; var x15g = 0.987992518020485; return new[] { -x15a, -x15b, -x15c, -x15d, -x15e, -x15f, -x15g,0.0, x15a, x15b, x15c, x15d, x15e, x15f, x15g }; case 16: var x16a = 0.095012509837637; var x16b = 0.281603550779259; var x16c = 0.458016777657227; var x16d = 0.617876244402644; var x16e = 0.755404408355003; var x16f = 0.865631202387832; var x16g = 0.944575023073233; var x16h = 0.989400934991650; return new[] { -x16a, -x16b, -x16c, -x16d, -x16e, -x16f, -x16g, -x16h, x16a, x16b, x16c, x16d, x16e, x16f, x16g, x16h }; default: throw new Exception("Only n<=16 supported"); } } public static double GaussLegendre(Func<double, double> f, double a, double b, int nPoints) { var q1 = (b - a) / 2; var q2 = (a + b) / 2; var xi = LegendrePolynomialRoots(nPoints); var wi = xi.Select(x => 2.0 * (1 - x * x) / ((nPoints + 1) * (nPoints + 1) * LegendrePolynomial(x, nPoints + 1).IntPow(2))).ToArray(); var iSum = xi.Select((x, ix) => wi[ix] * f(q1*x+q2)); return q1*iSum.Sum(); } public static double TwoDimensionalGaussLegendre(Func<double, double, double> fxy, double ax, double bx, double ay, double by, int nPoints) { var q1x = (bx - ax) / 2; var q2x = (ax + bx) / 2; var q1y = (by - ay) / 2; var q2y = (ay + by) / 2; var xi = LegendrePolynomialRoots(nPoints); var wi = xi.Select(x => 2.0 * (1 - x * x) / ((nPoints + 1) * (nPoints + 1) * LegendrePolynomial(x, nPoints + 1).IntPow(2))).ToArray(); var iSum = 0.0; for (var i = 0; i < wi.Length; i++) { for (var j = 0; j < wi.Length; j++) { iSum += wi[i] * wi[j] * fxy(q1x * xi[i] + q2x, q1y * xi[j] + q2y); } } return q1x * q1y * iSum; } //http://mathfaculty.fullerton.edu/mathews/n2003/SimpsonsRule2DMod.html public static double TwoDimensionalSimpsons(Func<double, double, double> fxy, double ax, double bx, double ay, double by, int nSteps) { if (nSteps % 2 != 0) throw new Exception("nSteps must be even"); //bounds check if (ax >= bx || ay >= by) return 0; var hx = (bx - ax) / nSteps / 2.0; var hy = (by - ay) / nSteps / 2.0; var ys = new Func<double, double>(ix => ay + ix * hy); var xs = new Func<double, double>(ix => ax + ix * hx); var iSum = fxy(ax, ay) + fxy(bx, ay) + fxy(ax, by) + fxy(bx, by); for (var i = 1; i <= nSteps; i++) { iSum += 4 * fxy(ax, ys(2 * i - 1)); iSum += 4 * fxy(bx, ys(2 * i - 1)); iSum += 4 * fxy(xs(2 * i - 1), ay); iSum += 4 * fxy(xs(2 * i - 1), by); if (i < nSteps) { iSum += 2 * fxy(ax, ys(2 * i)); iSum += 2 * fxy(bx, ys(2 * i)); iSum += 2 * fxy(xs(2 * i), ay); iSum += 2 * fxy(xs(2 * i), by); } for (var j = 1; j <= nSteps; j++) { iSum += 16 * fxy(xs(2 * i-1), ys(2 * j - 1)); if (i < nSteps) { iSum += 8 * fxy(xs(2 * i), ys(2 * j - 1)); } } for (var j = 1; j < nSteps; j++) { iSum += 8 * fxy(xs(2 * i-1), ys(2 * j)); if (i < nSteps) { iSum += 4 * fxy(xs(2 * i), ys(2 * j)); } } } iSum *= hx * hy / 9.0; return iSum; } public static double TwoDimensionalTrapezoid(Func<double, double, double> fxy, double ax, double bx, double ay, double by, int nSteps) { //bounds check if (ax >= bx || ay >= by) return 0; var hx = (bx - ax) / nSteps; var hy = (by - ay) / nSteps; var ys = Enumerable.Range(0, nSteps + 1) .Select(ix => ay + ix * hy) .ToArray(); var xs = Enumerable.Range(0, nSteps + 1) .Select(ix => ax + ix * hx) .ToArray(); var iSum = fxy(ax, ay) + fxy(bx, ay) + fxy(ax, by) + fxy(bx, by); for (var i = 1; i < nSteps; i++) { iSum += 2 * fxy(xs[i], ay); iSum += 2 * fxy(xs[i], by); iSum += 2 * fxy(ax, ys[i]); iSum += 2 * fxy(bx, ys[i]); for (var j = 1; j < nSteps; j++) { iSum += 4 * fxy(xs[i], ys[j]); } } iSum *= hx * hy / 4.0; return iSum; } } }
using System; using System.Xml; using System.Collections; using System.Collections.Generic; using System.Data; using System.Data.OleDb; namespace MyMeta { #if ENTERPRISE using System.Runtime.InteropServices; [ComVisible(false), ClassInterface(ClassInterfaceType.AutoDual)] #endif public class Procedures : Collection, IProcedures, IEnumerable, ICollection { public Procedures() { } #region XML User Data #if ENTERPRISE [ComVisible(false)] #endif override public string UserDataXPath { get { return Database.UserDataXPath + @"/Procedures"; } } #if ENTERPRISE [ComVisible(false)] #endif override internal bool GetXmlNode(out XmlNode node, bool forceCreate) { node = null; bool success = false; if(null == _xmlNode) { // Get the parent node XmlNode parentNode = null; if(this.Database.GetXmlNode(out parentNode, forceCreate)) { // See if our user data already exists string xPath = @"./Procedures"; if(!GetUserData(xPath, parentNode, out _xmlNode) && forceCreate) { // Create it, and try again this.CreateUserMetaData(parentNode); GetUserData(xPath, parentNode, out _xmlNode); } } } if(null != _xmlNode) { node = _xmlNode; success = true; } return success; } #if ENTERPRISE [ComVisible(false)] #endif override public void CreateUserMetaData(XmlNode parentNode) { XmlNode myNode = parentNode.OwnerDocument.CreateNode(XmlNodeType.Element, "Procedures", null); parentNode.AppendChild(myNode); } #endregion internal DataColumn f_Catalog = null; internal DataColumn f_Schema = null; internal DataColumn f_Name = null; internal DataColumn f_Type = null; internal DataColumn f_ProcedureDefinition = null; internal DataColumn f_Description = null; internal DataColumn f_DateCreated = null; internal DataColumn f_DateModified = null; private void BindToColumns(DataTable metaData) { if(false == _fieldsBound) { if(metaData.Columns.Contains("PROCEDURE_CATALOG")) f_Catalog = metaData.Columns["PROCEDURE_CATALOG"]; if(metaData.Columns.Contains("PROCEDURE_SCHEMA")) f_Schema = metaData.Columns["PROCEDURE_SCHEMA"]; if(metaData.Columns.Contains("PROCEDURE_NAME")) f_Name = metaData.Columns["PROCEDURE_NAME"]; if(metaData.Columns.Contains("PROCEDURE_TYPE")) f_Type = metaData.Columns["PROCEDURE_TYPE"]; if(metaData.Columns.Contains("PROCEDURE_DEFINITION")) f_ProcedureDefinition = metaData.Columns["PROCEDURE_DEFINITION"]; if(metaData.Columns.Contains("DESCRIPTION")) f_Description = metaData.Columns["DESCRIPTION"]; if(metaData.Columns.Contains("DATE_CREATED")) f_DateCreated = metaData.Columns["DATE_CREATED"]; if(metaData.Columns.Contains("DATE_MODIFIED")) f_DateModified = metaData.Columns["DATE_MODIFIED"]; } } internal virtual void LoadAll() { } internal void PopulateArray(DataTable metaData) { BindToColumns(metaData); Procedure procedure = null; int count = metaData.Rows.Count; for(int i = 0; i < count; i++) { procedure = (Procedure)this.dbRoot.ClassFactory.CreateProcedure(); procedure.dbRoot = this.dbRoot; procedure.Procedures = this; procedure.Row = metaData.Rows[i]; this._array.Add(procedure); } } internal void AddProcedure(Procedure procedure) { this._array.Add(procedure); } #region indexers virtual public IProcedure this[object index] { get { if(index.GetType() == Type.GetType("System.String")) { return GetByPhysicalName(index as String); } else { int idx = Convert.ToInt32(index); return this._array[idx] as Procedure; } } } #if ENTERPRISE [ComVisible(false)] #endif public Procedure GetByName(string name) { Procedure obj = null; Procedure tmp = null; int count = this._array.Count; for(int i = 0; i < count; i++) { tmp = this._array[i] as Procedure; if(this.CompareStrings(name,tmp.Name)) { obj = tmp; break; } } return obj; } #if ENTERPRISE [ComVisible(false)] #endif public Procedure GetByPhysicalName(string name) { Procedure obj = null; Procedure tmp = null; int count = this._array.Count; for(int i = 0; i < count; i++) { tmp = this._array[i] as Procedure; if(this.CompareStrings(name,tmp.Name)) { obj = tmp; break; } } return obj; } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion #region IEnumerable<IProcedure> Members public IEnumerator<IProcedure> GetEnumerator() { foreach (object item in _array) yield return item as IProcedure; } #endregion #region IList Members object System.Collections.IList.this[int index] { get { return this[index];} set { } } #endregion internal Database Database = null; } }
using System; using System.IO; using System.Reflection; using ToolKit.Cryptography; using Xunit; namespace UnitTests.Cryptography { [System.Diagnostics.CodeAnalysis.SuppressMessage( "StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Test Suites do not need XML Documentation.")] public class SHA512Tests { private static readonly string _assemblyPath = Path.GetDirectoryName(Assembly.GetAssembly(typeof(SHA512Tests)).Location) + Path.DirectorySeparatorChar; [Fact] public void SHA512Hash_Should_CalculateCorrectHash() { // Arrange var expected = "EA0B57CBECB912E69EFCC662D979D432D22590BF9782B1F8238C87F5C3F1F83E" + "31C2476BF0F7C0DD4F4DBAA565A72127DF4D10611E2A9D49667DE861E5BD4A94"; // Act var actual = SHA512Hash.Create().Compute("This is a Test of the Hash Function"); // Assert Assert.Equal(expected, actual); } [Fact] public void SHA512Hash_Should_CalculateCorrectHash_When_ProvidedEncryptionData() { // Arrange var data = new EncryptionData("This is a Test of the Hash Function"); var expected = "EA0B57CBECB912E69EFCC662D979D432D22590BF9782B1F8238C87F5C3F1F83E" + "31C2476BF0F7C0DD4F4DBAA565A72127DF4D10611E2A9D49667DE861E5BD4A94"; // Act var actual = SHA512Hash.Create().Compute(data); // Assert Assert.Equal(expected, actual); } [Fact] public void SHA512Hash_Should_CalculateCorrectHash_When_ProvidedStream() { // Arrange var expected = "92D11A96C22A0D346219F41D96906DD7A97872B782E1B9596A26D9FF1F540C23" + "86AD6E0E35641458BFD86862B63599F77103B38FADA89F2DB93BFF62CB82BE30"; var actual = String.Empty; // Act using (var sr = new StreamReader($"{_assemblyPath}gettysburg.txt")) { actual = SHA512Hash.Create().Compute(sr.BaseStream); } // Assert Assert.Equal(expected, actual); } [Fact] public void SHA512Hash_Should_CalculateCorrectHash_When_ProvidedWithBytes() { // Arrange var data = new byte[] { 0x55, 0x6e, 0x69, 0x74, 0x54, 0x65, 0x73, 0x74 }; var expected = "E67958D980D4534131BA29EE59DEF22DF37656D8D433F7AF5667E7E88BC38282" + "325EE4BD278827BC5376466A5F753E0CB8ABF7768EF8B4B819F32A64AA585EBB"; // Act var actual = SHA512Hash.Create().Compute(data); // Assert Assert.Equal(expected, actual); } [Fact] public void SHA512Hash_Should_CalculateCorrectHash_When_Salted() { // Arrange var data = new EncryptionData("This is a Test of the Hash Function"); var salt = new EncryptionData("Salty!"); var expected = "95688DA4EEA5DF0AB4330A785FFBF9B4FE16B7A661A48935CE864C92CC28B587" + "91F258F94AD745563D26752A2B7D5B2ABC6B0B5F87B2C602CF6BF1B485507C88"; // Act var actual = SHA512Hash.Create().Compute(data, salt); // Assert Assert.Equal(expected, actual); } [Fact] public void SHA512Hash_Should_CalculateCorrectHashBytes() { // Arrange var expected = new byte[] { 0xea, 0x0b, 0x57, 0xcb, 0xec, 0xb9, 0x12, 0xe6, 0x9e, 0xfc, 0xc6, 0x62, 0xd9, 0x79, 0xd4, 0x32, 0xd2, 0x25, 0x90, 0xbf, 0x97, 0x82, 0xb1, 0xf8, 0x23, 0x8c, 0x87, 0xf5, 0xc3, 0xf1, 0xf8, 0x3e, 0x31, 0xc2, 0x47, 0x6b, 0xf0, 0xf7, 0xc0, 0xdd, 0x4f, 0x4d, 0xba, 0xa5, 0x65, 0xa7, 0x21, 0x27, 0xdf, 0x4d, 0x10, 0x61, 0x1e, 0x2a, 0x9d, 0x49, 0x66, 0x7d, 0xe8, 0x61, 0xe5, 0xbd, 0x4a, 0x94 }; // Act var actual = SHA512Hash.Create().ComputeToBytes("This is a Test of the Hash Function"); // Assert Assert.Equal(expected, actual); } [Fact] public void SHA512Hash_Should_CalculateCorrectHashBytes_When_ProvidedEncryptionData() { // Arrange var data = new EncryptionData("This is a Test of the Hash Function"); var expected = new byte[] { 0xea, 0x0b, 0x57, 0xcb, 0xec, 0xb9, 0x12, 0xe6, 0x9e, 0xfc, 0xc6, 0x62, 0xd9, 0x79, 0xd4, 0x32, 0xd2, 0x25, 0x90, 0xbf, 0x97, 0x82, 0xb1, 0xf8, 0x23, 0x8c, 0x87, 0xf5, 0xc3, 0xf1, 0xf8, 0x3e, 0x31, 0xc2, 0x47, 0x6b, 0xf0, 0xf7, 0xc0, 0xdd, 0x4f, 0x4d, 0xba, 0xa5, 0x65, 0xa7, 0x21, 0x27, 0xdf, 0x4d, 0x10, 0x61, 0x1e, 0x2a, 0x9d, 0x49, 0x66, 0x7d, 0xe8, 0x61, 0xe5, 0xbd, 0x4a, 0x94 }; // Act var actual = SHA512Hash.Create().ComputeToBytes(data); // Assert Assert.Equal(expected, actual); } [Fact] public void SHA512Hash_Should_CalculateCorrectHashBytes_When_ProvidedStream() { // Arrange var expected = new byte[] { 0x92, 0xd1, 0x1a, 0x96, 0xc2, 0x2a, 0x0d, 0x34, 0x62, 0x19, 0xf4, 0x1d, 0x96, 0x90, 0x6d, 0xd7, 0xa9, 0x78, 0x72, 0xb7, 0x82, 0xe1, 0xb9, 0x59, 0x6a, 0x26, 0xd9, 0xff, 0x1f, 0x54, 0x0c, 0x23, 0x86, 0xad, 0x6e, 0x0e, 0x35, 0x64, 0x14, 0x58, 0xbf, 0xd8, 0x68, 0x62, 0xb6, 0x35, 0x99, 0xf7, 0x71, 0x03, 0xb3, 0x8f, 0xad, 0xa8, 0x9f, 0x2d, 0xb9, 0x3b, 0xff, 0x62, 0xcb, 0x82, 0xbe, 0x30 }; byte[] actual; // Act using (var sr = new StreamReader($"{_assemblyPath}gettysburg.txt")) { actual = SHA512Hash.Create().ComputeToBytes(sr.BaseStream); } // Assert Assert.Equal(expected, actual); } [Fact] public void SHA512Hash_Should_CalculateCorrectHashBytes_When_ProvidedWithBytes() { // Arrange var data = new byte[] { 0x55, 0x6e, 0x69, 0x74, 0x54, 0x65, 0x73, 0x74 }; var expected = new byte[] { 0xe6, 0x79, 0x58, 0xd9, 0x80, 0xd4, 0x53, 0x41, 0x31, 0xba, 0x29, 0xee, 0x59, 0xde, 0xf2, 0x2d, 0xf3, 0x76, 0x56, 0xd8, 0xd4, 0x33, 0xf7, 0xaf, 0x56, 0x67, 0xe7, 0xe8, 0x8b, 0xc3, 0x82, 0x82, 0x32, 0x5e, 0xe4, 0xbd, 0x27, 0x88, 0x27, 0xbc, 0x53, 0x76, 0x46, 0x6a, 0x5f, 0x75, 0x3e, 0x0c, 0xb8, 0xab, 0xf7, 0x76, 0x8e, 0xf8, 0xb4, 0xb8, 0x19, 0xf3, 0x2a, 0x64, 0xaa, 0x58, 0x5e, 0xbb }; // Act var actual = SHA512Hash.Create().ComputeToBytes(data); // Assert Assert.Equal(expected, actual); } [Fact] public void SHA512Hash_Should_CalculateCorrectHashBytes_When_Salted() { // Arrange var data = new EncryptionData("This is a Test of the Hash Function"); var salt = new EncryptionData("Salty!"); var expected = new byte[] { 0x95, 0x68, 0x8d, 0xa4, 0xee, 0xa5, 0xdf, 0x0a, 0xb4, 0x33, 0x0a, 0x78, 0x5f, 0xfb, 0xf9, 0xb4, 0xfe, 0x16, 0xb7, 0xa6, 0x61, 0xa4, 0x89, 0x35, 0xce, 0x86, 0x4c, 0x92, 0xcc, 0x28, 0xb5, 0x87, 0x91, 0xf2, 0x58, 0xf9, 0x4a, 0xd7, 0x45, 0x56, 0x3d, 0x26, 0x75, 0x2a, 0x2b, 0x7d, 0x5b, 0x2a, 0xbc, 0x6b, 0x0b, 0x5f, 0x87, 0xb2, 0xc6, 0x02, 0xcf, 0x6b, 0xf1, 0xb4, 0x85, 0x50, 0x7c, 0x88 }; // Act var actual = SHA512Hash.Create().ComputeToBytes(data, salt); // Assert Assert.Equal(expected, actual); } } }
// 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.Drawing { public sealed class Pens { private static readonly object s_transparentKey = new object(); private static readonly object s_aliceBlueKey = new object(); private static readonly object s_antiqueWhiteKey = new object(); private static readonly object s_aquaKey = new object(); private static readonly object s_aquamarineKey = new object(); private static readonly object s_azureKey = new object(); private static readonly object s_beigeKey = new object(); private static readonly object s_bisqueKey = new object(); private static readonly object s_blackKey = new object(); private static readonly object s_blanchedAlmondKey = new object(); private static readonly object s_blueKey = new object(); private static readonly object s_blueVioletKey = new object(); private static readonly object s_brownKey = new object(); private static readonly object s_burlyWoodKey = new object(); private static readonly object s_cadetBlueKey = new object(); private static readonly object s_chartreuseKey = new object(); private static readonly object s_chocolateKey = new object(); private static readonly object s_coralKey = new object(); private static readonly object s_cornflowerBlueKey = new object(); private static readonly object s_cornsilkKey = new object(); private static readonly object s_crimsonKey = new object(); private static readonly object s_cyanKey = new object(); private static readonly object s_darkBlueKey = new object(); private static readonly object s_darkCyanKey = new object(); private static readonly object s_darkGoldenrodKey = new object(); private static readonly object s_darkGrayKey = new object(); private static readonly object s_darkGreenKey = new object(); private static readonly object s_darkKhakiKey = new object(); private static readonly object s_darkMagentaKey = new object(); private static readonly object s_darkOliveGreenKey = new object(); private static readonly object s_darkOrangeKey = new object(); private static readonly object s_darkOrchidKey = new object(); private static readonly object s_darkRedKey = new object(); private static readonly object s_darkSalmonKey = new object(); private static readonly object s_darkSeaGreenKey = new object(); private static readonly object s_darkSlateBlueKey = new object(); private static readonly object s_darkSlateGrayKey = new object(); private static readonly object s_darkTurquoiseKey = new object(); private static readonly object s_darkVioletKey = new object(); private static readonly object s_deepPinkKey = new object(); private static readonly object s_deepSkyBlueKey = new object(); private static readonly object s_dimGrayKey = new object(); private static readonly object s_dodgerBlueKey = new object(); private static readonly object s_firebrickKey = new object(); private static readonly object s_floralWhiteKey = new object(); private static readonly object s_forestGreenKey = new object(); private static readonly object s_fuchsiaKey = new object(); private static readonly object s_gainsboroKey = new object(); private static readonly object s_ghostWhiteKey = new object(); private static readonly object s_goldKey = new object(); private static readonly object s_goldenrodKey = new object(); private static readonly object s_grayKey = new object(); private static readonly object s_greenKey = new object(); private static readonly object s_greenYellowKey = new object(); private static readonly object s_honeydewKey = new object(); private static readonly object s_hotPinkKey = new object(); private static readonly object s_indianRedKey = new object(); private static readonly object s_indigoKey = new object(); private static readonly object s_ivoryKey = new object(); private static readonly object s_khakiKey = new object(); private static readonly object s_lavenderKey = new object(); private static readonly object s_lavenderBlushKey = new object(); private static readonly object s_lawnGreenKey = new object(); private static readonly object s_lemonChiffonKey = new object(); private static readonly object s_lightBlueKey = new object(); private static readonly object s_lightCoralKey = new object(); private static readonly object s_lightCyanKey = new object(); private static readonly object s_lightGoldenrodYellowKey = new object(); private static readonly object s_lightGreenKey = new object(); private static readonly object s_lightGrayKey = new object(); private static readonly object s_lightPinkKey = new object(); private static readonly object s_lightSalmonKey = new object(); private static readonly object s_lightSeaGreenKey = new object(); private static readonly object s_lightSkyBlueKey = new object(); private static readonly object s_lightSlateGrayKey = new object(); private static readonly object s_lightSteelBlueKey = new object(); private static readonly object s_lightYellowKey = new object(); private static readonly object s_limeKey = new object(); private static readonly object s_limeGreenKey = new object(); private static readonly object s_linenKey = new object(); private static readonly object s_magentaKey = new object(); private static readonly object s_maroonKey = new object(); private static readonly object s_mediumAquamarineKey = new object(); private static readonly object s_mediumBlueKey = new object(); private static readonly object s_mediumOrchidKey = new object(); private static readonly object s_mediumPurpleKey = new object(); private static readonly object s_mediumSeaGreenKey = new object(); private static readonly object s_mediumSlateBlueKey = new object(); private static readonly object s_mediumSpringGreenKey = new object(); private static readonly object s_mediumTurquoiseKey = new object(); private static readonly object s_mediumVioletRedKey = new object(); private static readonly object s_midnightBlueKey = new object(); private static readonly object s_mintCreamKey = new object(); private static readonly object s_mistyRoseKey = new object(); private static readonly object s_moccasinKey = new object(); private static readonly object s_navajoWhiteKey = new object(); private static readonly object s_navyKey = new object(); private static readonly object s_oldLaceKey = new object(); private static readonly object s_oliveKey = new object(); private static readonly object s_oliveDrabKey = new object(); private static readonly object s_orangeKey = new object(); private static readonly object s_orangeRedKey = new object(); private static readonly object s_orchidKey = new object(); private static readonly object s_paleGoldenrodKey = new object(); private static readonly object s_paleGreenKey = new object(); private static readonly object s_paleTurquoiseKey = new object(); private static readonly object s_paleVioletRedKey = new object(); private static readonly object s_papayaWhipKey = new object(); private static readonly object s_peachPuffKey = new object(); private static readonly object s_peruKey = new object(); private static readonly object s_pinkKey = new object(); private static readonly object s_plumKey = new object(); private static readonly object s_powderBlueKey = new object(); private static readonly object s_purpleKey = new object(); private static readonly object s_redKey = new object(); private static readonly object s_rosyBrownKey = new object(); private static readonly object s_royalBlueKey = new object(); private static readonly object s_saddleBrownKey = new object(); private static readonly object s_salmonKey = new object(); private static readonly object s_sandyBrownKey = new object(); private static readonly object s_seaGreenKey = new object(); private static readonly object s_seaShellKey = new object(); private static readonly object s_siennaKey = new object(); private static readonly object s_silverKey = new object(); private static readonly object s_skyBlueKey = new object(); private static readonly object s_slateBlueKey = new object(); private static readonly object s_slateGrayKey = new object(); private static readonly object s_snowKey = new object(); private static readonly object s_springGreenKey = new object(); private static readonly object s_steelBlueKey = new object(); private static readonly object s_tanKey = new object(); private static readonly object s_tealKey = new object(); private static readonly object s_thistleKey = new object(); private static readonly object s_tomatoKey = new object(); private static readonly object s_turquoiseKey = new object(); private static readonly object s_violetKey = new object(); private static readonly object s_wheatKey = new object(); private static readonly object s_whiteKey = new object(); private static readonly object s_whiteSmokeKey = new object(); private static readonly object s_yellowKey = new object(); private static readonly object s_yellowGreenKey = new object(); public static Pen Transparent => GetPen(s_transparentKey, Color.Transparent); public static Pen AliceBlue => GetPen(s_aliceBlueKey, Color.AliceBlue); public static Pen AntiqueWhite => GetPen(s_antiqueWhiteKey, Color.AntiqueWhite); public static Pen Aqua => GetPen(s_aquaKey, Color.Aqua); public static Pen Aquamarine => GetPen(s_aquamarineKey, Color.Aquamarine); public static Pen Azure => GetPen(s_azureKey, Color.Azure); public static Pen Beige => GetPen(s_beigeKey, Color.Beige); public static Pen Bisque => GetPen(s_bisqueKey, Color.Bisque); public static Pen Black => GetPen(s_blackKey, Color.Black); public static Pen BlanchedAlmond => GetPen(s_blanchedAlmondKey, Color.BlanchedAlmond); public static Pen Blue => GetPen(s_blueKey, Color.Blue); public static Pen BlueViolet => GetPen(s_blueVioletKey, Color.BlueViolet); public static Pen Brown => GetPen(s_brownKey, Color.Brown); public static Pen BurlyWood => GetPen(s_burlyWoodKey, Color.BurlyWood); public static Pen CadetBlue => GetPen(s_cadetBlueKey, Color.CadetBlue); public static Pen Chartreuse => GetPen(s_chartreuseKey, Color.Chartreuse); public static Pen Chocolate => GetPen(s_chocolateKey, Color.Chocolate); public static Pen Coral => GetPen(s_coralKey, Color.Coral); public static Pen CornflowerBlue => GetPen(s_cornflowerBlueKey, Color.CornflowerBlue); public static Pen Cornsilk => GetPen(s_cornsilkKey, Color.Cornsilk); public static Pen Crimson => GetPen(s_crimsonKey, Color.Crimson); public static Pen Cyan => GetPen(s_cyanKey, Color.Cyan); public static Pen DarkBlue => GetPen(s_darkBlueKey, Color.DarkBlue); public static Pen DarkCyan => GetPen(s_darkCyanKey, Color.DarkCyan); public static Pen DarkGoldenrod => GetPen(s_darkGoldenrodKey, Color.DarkGoldenrod); public static Pen DarkGray => GetPen(s_darkGrayKey, Color.DarkGray); public static Pen DarkGreen => GetPen(s_darkGreenKey, Color.DarkGreen); public static Pen DarkKhaki => GetPen(s_darkKhakiKey, Color.DarkKhaki); public static Pen DarkMagenta => GetPen(s_darkMagentaKey, Color.DarkMagenta); public static Pen DarkOliveGreen => GetPen(s_darkOliveGreenKey, Color.DarkOliveGreen); public static Pen DarkOrange => GetPen(s_darkOrangeKey, Color.DarkOrange); public static Pen DarkOrchid => GetPen(s_darkOrchidKey, Color.DarkOrchid); public static Pen DarkRed => GetPen(s_darkRedKey, Color.DarkRed); public static Pen DarkSalmon => GetPen(s_darkSalmonKey, Color.DarkSalmon); public static Pen DarkSeaGreen => GetPen(s_darkSeaGreenKey, Color.DarkSeaGreen); public static Pen DarkSlateBlue => GetPen(s_darkSlateBlueKey, Color.DarkSlateBlue); public static Pen DarkSlateGray => GetPen(s_darkSlateGrayKey, Color.DarkSlateGray); public static Pen DarkTurquoise => GetPen(s_darkTurquoiseKey, Color.DarkTurquoise); public static Pen DarkViolet => GetPen(s_darkVioletKey, Color.DarkViolet); public static Pen DeepPink => GetPen(s_deepPinkKey, Color.DeepPink); public static Pen DeepSkyBlue => GetPen(s_deepSkyBlueKey, Color.DeepSkyBlue); public static Pen DimGray => GetPen(s_dimGrayKey, Color.DimGray); public static Pen DodgerBlue => GetPen(s_dodgerBlueKey, Color.DodgerBlue); public static Pen Firebrick => GetPen(s_firebrickKey, Color.Firebrick); public static Pen FloralWhite => GetPen(s_floralWhiteKey, Color.FloralWhite); public static Pen ForestGreen => GetPen(s_forestGreenKey, Color.ForestGreen); public static Pen Fuchsia => GetPen(s_fuchsiaKey, Color.Fuchsia); public static Pen Gainsboro => GetPen(s_gainsboroKey, Color.Gainsboro); public static Pen GhostWhite => GetPen(s_ghostWhiteKey, Color.GhostWhite); public static Pen Gold => GetPen(s_goldKey, Color.Gold); public static Pen Goldenrod => GetPen(s_goldenrodKey, Color.Goldenrod); public static Pen Gray => GetPen(s_grayKey, Color.Gray); public static Pen Green => GetPen(s_greenKey, Color.Green); public static Pen GreenYellow => GetPen(s_greenYellowKey, Color.GreenYellow); public static Pen Honeydew => GetPen(s_honeydewKey, Color.Honeydew); public static Pen HotPink => GetPen(s_hotPinkKey, Color.HotPink); public static Pen IndianRed => GetPen(s_indianRedKey, Color.IndianRed); public static Pen Indigo => GetPen(s_indigoKey, Color.Indigo); public static Pen Ivory => GetPen(s_ivoryKey, Color.Ivory); public static Pen Khaki => GetPen(s_khakiKey, Color.Khaki); public static Pen Lavender => GetPen(s_lavenderKey, Color.Lavender); public static Pen LavenderBlush => GetPen(s_lavenderBlushKey, Color.LavenderBlush); public static Pen LawnGreen => GetPen(s_lawnGreenKey, Color.LawnGreen); public static Pen LemonChiffon => GetPen(s_lemonChiffonKey, Color.LemonChiffon); public static Pen LightBlue => GetPen(s_lightBlueKey, Color.LightBlue); public static Pen LightCoral => GetPen(s_lightCoralKey, Color.LightCoral); public static Pen LightCyan => GetPen(s_lightCyanKey, Color.LightCyan); public static Pen LightGoldenrodYellow => GetPen(s_lightGoldenrodYellowKey, Color.LightGoldenrodYellow); public static Pen LightGreen => GetPen(s_lightGreenKey, Color.LightGreen); public static Pen LightGray => GetPen(s_lightGrayKey, Color.LightGray); public static Pen LightPink => GetPen(s_lightPinkKey, Color.LightPink); public static Pen LightSalmon => GetPen(s_lightSalmonKey, Color.LightSalmon); public static Pen LightSeaGreen => GetPen(s_lightSeaGreenKey, Color.LightSeaGreen); public static Pen LightSkyBlue => GetPen(s_lightSkyBlueKey, Color.LightSkyBlue); public static Pen LightSlateGray => GetPen(s_lightSlateGrayKey, Color.LightSlateGray); public static Pen LightSteelBlue => GetPen(s_lightSteelBlueKey, Color.LightSteelBlue); public static Pen LightYellow => GetPen(s_lightYellowKey, Color.LightYellow); public static Pen Lime => GetPen(s_limeKey, Color.Lime); public static Pen LimeGreen => GetPen(s_limeGreenKey, Color.LimeGreen); public static Pen Linen => GetPen(s_linenKey, Color.Linen); public static Pen Magenta => GetPen(s_magentaKey, Color.Magenta); public static Pen Maroon => GetPen(s_maroonKey, Color.Maroon); public static Pen MediumAquamarine => GetPen(s_mediumAquamarineKey, Color.MediumAquamarine); public static Pen MediumBlue => GetPen(s_mediumBlueKey, Color.MediumBlue); public static Pen MediumOrchid => GetPen(s_mediumOrchidKey, Color.MediumOrchid); public static Pen MediumPurple => GetPen(s_mediumPurpleKey, Color.MediumPurple); public static Pen MediumSeaGreen => GetPen(s_mediumSeaGreenKey, Color.MediumSeaGreen); public static Pen MediumSlateBlue => GetPen(s_mediumSlateBlueKey, Color.MediumSlateBlue); public static Pen MediumSpringGreen => GetPen(s_mediumSpringGreenKey, Color.MediumSpringGreen); public static Pen MediumTurquoise => GetPen(s_mediumTurquoiseKey, Color.MediumTurquoise); public static Pen MediumVioletRed => GetPen(s_mediumVioletRedKey, Color.MediumVioletRed); public static Pen MidnightBlue => GetPen(s_midnightBlueKey, Color.MidnightBlue); public static Pen MintCream => GetPen(s_mintCreamKey, Color.MintCream); public static Pen MistyRose => GetPen(s_mistyRoseKey, Color.MistyRose); public static Pen Moccasin => GetPen(s_moccasinKey, Color.Moccasin); public static Pen NavajoWhite => GetPen(s_navajoWhiteKey, Color.NavajoWhite); public static Pen Navy => GetPen(s_navyKey, Color.Navy); public static Pen OldLace => GetPen(s_oldLaceKey, Color.OldLace); public static Pen Olive => GetPen(s_oliveKey, Color.Olive); public static Pen OliveDrab => GetPen(s_oliveDrabKey, Color.OliveDrab); public static Pen Orange => GetPen(s_orangeKey, Color.Orange); public static Pen OrangeRed => GetPen(s_orangeRedKey, Color.OrangeRed); public static Pen Orchid => GetPen(s_orchidKey, Color.Orchid); public static Pen PaleGoldenrod => GetPen(s_paleGoldenrodKey, Color.PaleGoldenrod); public static Pen PaleGreen => GetPen(s_paleGreenKey, Color.PaleGreen); public static Pen PaleTurquoise => GetPen(s_paleTurquoiseKey, Color.PaleTurquoise); public static Pen PaleVioletRed => GetPen(s_paleVioletRedKey, Color.PaleVioletRed); public static Pen PapayaWhip => GetPen(s_papayaWhipKey, Color.PapayaWhip); public static Pen PeachPuff => GetPen(s_peachPuffKey, Color.PeachPuff); public static Pen Peru => GetPen(s_peruKey, Color.Peru); public static Pen Pink => GetPen(s_pinkKey, Color.Pink); public static Pen Plum => GetPen(s_plumKey, Color.Plum); public static Pen PowderBlue => GetPen(s_powderBlueKey, Color.PowderBlue); public static Pen Purple => GetPen(s_purpleKey, Color.Purple); public static Pen Red => GetPen(s_redKey, Color.Red); public static Pen RosyBrown => GetPen(s_rosyBrownKey, Color.RosyBrown); public static Pen RoyalBlue => GetPen(s_royalBlueKey, Color.RoyalBlue); public static Pen SaddleBrown => GetPen(s_saddleBrownKey, Color.SaddleBrown); public static Pen Salmon => GetPen(s_salmonKey, Color.Salmon); public static Pen SandyBrown => GetPen(s_sandyBrownKey, Color.SandyBrown); public static Pen SeaGreen => GetPen(s_seaGreenKey, Color.SeaGreen); public static Pen SeaShell => GetPen(s_seaShellKey, Color.SeaShell); public static Pen Sienna => GetPen(s_siennaKey, Color.Sienna); public static Pen Silver => GetPen(s_silverKey, Color.Silver); public static Pen SkyBlue => GetPen(s_skyBlueKey, Color.SkyBlue); public static Pen SlateBlue => GetPen(s_slateBlueKey, Color.SlateBlue); public static Pen SlateGray => GetPen(s_slateGrayKey, Color.SlateGray); public static Pen Snow => GetPen(s_snowKey, Color.Snow); public static Pen SpringGreen => GetPen(s_springGreenKey, Color.SpringGreen); public static Pen SteelBlue => GetPen(s_steelBlueKey, Color.SteelBlue); public static Pen Tan => GetPen(s_tanKey, Color.Tan); public static Pen Teal => GetPen(s_tealKey, Color.Teal); public static Pen Thistle => GetPen(s_thistleKey, Color.Thistle); public static Pen Tomato => GetPen(s_tomatoKey, Color.Tomato); public static Pen Turquoise => GetPen(s_turquoiseKey, Color.Turquoise); public static Pen Violet => GetPen(s_violetKey, Color.Violet); public static Pen Wheat => GetPen(s_wheatKey, Color.Wheat); public static Pen White => GetPen(s_whiteKey, Color.White); public static Pen WhiteSmoke => GetPen(s_whiteSmokeKey, Color.WhiteSmoke); public static Pen Yellow => GetPen(s_yellowKey, Color.Yellow); public static Pen YellowGreen => GetPen(s_yellowGreenKey, Color.YellowGreen); private static Pen GetPen(object key, Color color) { Pen Pen = (Pen)SafeNativeMethods.Gdip.ThreadData[key]; if (Pen == null) { Pen = new Pen(color, true); SafeNativeMethods.Gdip.ThreadData[key] = Pen; } return Pen; } } }
#region File Description //----------------------------------------------------------------------------- // InputState.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Input.Touch; using System.Collections.Generic; #endregion namespace UserInterfaceSample { /// <summary> /// Helper for reading input from keyboard, gamepad, and touch input. This class /// tracks both the current and previous state of the input devices, and implements /// query methods for high level input actions such as "move up through the menu" /// or "pause the game". /// </summary> public class InputState { #region Fields public const int MaxInputs = 4; public readonly KeyboardState[] CurrentKeyboardStates; public readonly GamePadState[] CurrentGamePadStates; public readonly KeyboardState[] LastKeyboardStates; public readonly GamePadState[] LastGamePadStates; public readonly bool[] GamePadWasConnected; public TouchCollection TouchState; public readonly List<GestureSample> Gestures = new List<GestureSample>(); #endregion #region Initialization /// <summary> /// Constructs a new input state. /// </summary> public InputState() { CurrentKeyboardStates = new KeyboardState[MaxInputs]; CurrentGamePadStates = new GamePadState[MaxInputs]; LastKeyboardStates = new KeyboardState[MaxInputs]; LastGamePadStates = new GamePadState[MaxInputs]; GamePadWasConnected = new bool[MaxInputs]; } #endregion #region Public Methods /// <summary> /// Reads the latest state of the keyboard and gamepad. /// </summary> public void Update() { for (int i = 0; i < MaxInputs; i++) { LastKeyboardStates[i] = CurrentKeyboardStates[i]; LastGamePadStates[i] = CurrentGamePadStates[i]; CurrentKeyboardStates[i] = Keyboard.GetState((PlayerIndex)i); CurrentGamePadStates[i] = GamePad.GetState((PlayerIndex)i); // Keep track of whether a gamepad has ever been // connected, so we can detect if it is unplugged. if (CurrentGamePadStates[i].IsConnected) { GamePadWasConnected[i] = true; } } TouchState = TouchPanel.GetState(); Gestures.Clear(); while (TouchPanel.IsGestureAvailable) { Gestures.Add(TouchPanel.ReadGesture()); } } /// <summary> /// Helper for checking if a key was newly pressed during this update. The /// controllingPlayer parameter specifies which player to read input for. /// If this is null, it will accept input from any player. When a keypress /// is detected, the output playerIndex reports which player pressed it. /// </summary> public bool IsNewKeyPress(Keys key, PlayerIndex? controllingPlayer, out PlayerIndex playerIndex) { if (controllingPlayer.HasValue) { // Read input from the specified player. playerIndex = controllingPlayer.Value; int i = (int)playerIndex; return (CurrentKeyboardStates[i].IsKeyDown(key) && LastKeyboardStates[i].IsKeyUp(key)); } else { // Accept input from any player. return (IsNewKeyPress(key, PlayerIndex.One, out playerIndex) || IsNewKeyPress(key, PlayerIndex.Two, out playerIndex) || IsNewKeyPress(key, PlayerIndex.Three, out playerIndex) || IsNewKeyPress(key, PlayerIndex.Four, out playerIndex)); } } /// <summary> /// Helper for checking if a button was newly pressed during this update. /// The controllingPlayer parameter specifies which player to read input for. /// If this is null, it will accept input from any player. When a button press /// is detected, the output playerIndex reports which player pressed it. /// </summary> public bool IsNewButtonPress(Buttons button, PlayerIndex? controllingPlayer, out PlayerIndex playerIndex) { if (controllingPlayer.HasValue) { // Read input from the specified player. playerIndex = controllingPlayer.Value; int i = (int)playerIndex; return (CurrentGamePadStates[i].IsButtonDown(button) && LastGamePadStates[i].IsButtonUp(button)); } else { // Accept input from any player. return (IsNewButtonPress(button, PlayerIndex.One, out playerIndex) || IsNewButtonPress(button, PlayerIndex.Two, out playerIndex) || IsNewButtonPress(button, PlayerIndex.Three, out playerIndex) || IsNewButtonPress(button, PlayerIndex.Four, out playerIndex)); } } /// <summary> /// Checks for a "menu select" input action. /// The controllingPlayer parameter specifies which player to read input for. /// If this is null, it will accept input from any player. When the action /// is detected, the output playerIndex reports which player pressed it. /// </summary> public bool IsMenuSelect(PlayerIndex? controllingPlayer, out PlayerIndex playerIndex) { return IsNewKeyPress(Keys.Space, controllingPlayer, out playerIndex) || IsNewKeyPress(Keys.Enter, controllingPlayer, out playerIndex) || IsNewButtonPress(Buttons.A, controllingPlayer, out playerIndex) || IsNewButtonPress(Buttons.Start, controllingPlayer, out playerIndex); } /// <summary> /// Checks for a "menu cancel" input action. /// The controllingPlayer parameter specifies which player to read input for. /// If this is null, it will accept input from any player. When the action /// is detected, the output playerIndex reports which player pressed it. /// </summary> public bool IsMenuCancel(PlayerIndex? controllingPlayer, out PlayerIndex playerIndex) { return IsNewKeyPress(Keys.Escape, controllingPlayer, out playerIndex) || IsNewButtonPress(Buttons.B, controllingPlayer, out playerIndex) || IsNewButtonPress(Buttons.Back, controllingPlayer, out playerIndex); } /// <summary> /// Checks for a "menu up" input action. /// The controllingPlayer parameter specifies which player to read /// input for. If this is null, it will accept input from any player. /// </summary> public bool IsMenuUp(PlayerIndex? controllingPlayer) { PlayerIndex playerIndex; return IsNewKeyPress(Keys.Up, controllingPlayer, out playerIndex) || IsNewButtonPress(Buttons.DPadUp, controllingPlayer, out playerIndex) || IsNewButtonPress(Buttons.LeftThumbstickUp, controllingPlayer, out playerIndex); } /// <summary> /// Checks for a "menu down" input action. /// The controllingPlayer parameter specifies which player to read /// input for. If this is null, it will accept input from any player. /// </summary> public bool IsMenuDown(PlayerIndex? controllingPlayer) { PlayerIndex playerIndex; return IsNewKeyPress(Keys.Down, controllingPlayer, out playerIndex) || IsNewButtonPress(Buttons.DPadDown, controllingPlayer, out playerIndex) || IsNewButtonPress(Buttons.LeftThumbstickDown, controllingPlayer, out playerIndex); } /// <summary> /// Checks for a "pause the game" input action. /// The controllingPlayer parameter specifies which player to read /// input for. If this is null, it will accept input from any player. /// </summary> public bool IsPauseGame(PlayerIndex? controllingPlayer) { PlayerIndex playerIndex; return IsNewKeyPress(Keys.Escape, controllingPlayer, out playerIndex) || IsNewButtonPress(Buttons.Back, controllingPlayer, out playerIndex) || IsNewButtonPress(Buttons.Start, controllingPlayer, out playerIndex); } #endregion } }
using System; using System.Text.RegularExpressions; using Platform.Text; namespace Platform.VirtualFileSystem.Providers.Local { [Serializable] public class LocalNodeAddress : AbstractNodeAddressWithRootPart { private static readonly Regex localFileNameRegEx; public const string LowerAlphabet = "abcdefghijklmnopqrstuvwxyz"; public const string UpperAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; private static readonly char[] validFileNameChars; private static readonly string validFileNameString; public static bool IsValidFileNameChar(char c) { return Array.BinarySearch<char>(validFileNameChars, c) >= 0; } static LocalNodeAddress() { string exp; validFileNameChars = (@"\-+,;=\[\].$%_@~`!(){}^#&-" + UpperAlphabet + LowerAlphabet).ToCharArray(); Array.Sort<char>(validFileNameChars); validFileNameString = validFileNameChars.ToString(); exp = @" # The optional file:// part [ ]* ^(((?<scheme>[a-z]*)\:[\\/]{2,2})?) ( # UNC paths ( ([\\/]{2,2}) (?<uncserver>(([a-zA-Z\-\.0-9]*)|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))) #(?<path1>([ \\/][\-+,;=\[\].$%_@~`!(){}^#&a-zA-Z0-9\\/]*)*) (\?(?<query>(.*)))?$ #(?<path1>([^\?\""\<\>\|\/\\\*:]*)*) (\?(?<query>(.*)))?$ (?<path1>([/\\] [^\?\""\<\>\|\/\*:\\]+)+[/\\]? | [/\\]?) (\?(?<query>(.*)))?$ ) | # Windows paths ( (?<root>([a-zA-Z]\:)) (?<path2>([/\\] [^\?\""\<\>\|\/\*:\\]+)+[/\\]? | [/\\]?) #(?<path2>[/\\]? | ([/\\] [ \-\+,;=\[\].$%_@~`!(){}^#&\p{N}\p{L}]+)+[/\\]?) (\?(?<query>(.*)))?$ ) | # UNIX paths ( #(?<path3>/ | /([ \-\+,;=\[\].$%_@~`!(){}^#&a-zA-Z0-9]+)+/?) (\?(?<query>(.*)))?$ #(?<path3>/ | /([^\?\""\<\>\|\/\\\*:]+)+/?) (\?(?<query>(.*)))?$ (?<path3>([/] [^\?\""\<\>\|\/\*:]+)+[/]? | [/\\]?) (\?(?<query>(.*)))?$ ) | # Relative Paths ( (?<path4>([/\\]? | (([\.]{1,2}[/\\]?)|([\.]{1,2}[/\\])+) (([/] [^\?\""\<\>\|\/\*:]+)+[/]? | [/\\]?)? )) (\?(?<query>(.*)))?$ ) ) [ ]* "; localFileNameRegEx = new Regex ( exp, RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled | RegexOptions.CultureInvariant ); } private readonly bool includeRootPartInUri; public LocalNodeAddress(string scheme, string rootPart, bool includeRootPartInUri, string path) : this(scheme, rootPart, includeRootPartInUri, path, "") { } public LocalNodeAddress(string scheme, string rootPart, bool includeRootPartInUri, string path, string query) : base(scheme, rootPart, path, query) { this.includeRootPartInUri = includeRootPartInUri; } [ThreadStatic] private static string lastCanParseUri; [ThreadStatic] private static Match lastCanParseMatch; public static bool CanParse(string uri) { return CanParse(uri, "file"); } public static bool CanParse(string uri, string scheme) { if (!((uri.Length >= 2 && Char.IsLetter(uri[0]) && uri[1] == ':') || (uri == null || (uri != null && uri.StartsWith(scheme, StringComparison.CurrentCultureIgnoreCase))) || uri.StartsWith("/") || uri.StartsWith(@"\") || uri == "." || uri == ".." || uri.StartsWith("./") || uri.StartsWith("../") || uri.StartsWith(".\\") || uri.StartsWith("..\\"))) { // Fast fail path out. return false; } if (lastCanParseUri == uri && lastCanParseMatch != null && lastCanParseMatch.Success) { return true; } // Use regular expression to totally verify. lastCanParseUri = uri; lastCanParseMatch = localFileNameRegEx.Match(uri); return lastCanParseMatch.Success; } public static LocalNodeAddress Parse(string uri) { Group group; Match match = null; string root, scheme, query; // Often Parse will be called with the exact same URI reference that was last passed // to CanParse. If this is the case then use the results cached by the last call to // CanParse from this thread. if ((object)uri == (object)lastCanParseUri) { match = lastCanParseMatch; } while (true) { if (match == null) { match = localFileNameRegEx.Match(uri); } if (!match.Success) { throw new MalformedUriException(uri); } bool schemeExplicitlyProvided; group = match.Groups["scheme"]; if (group.Value == "") { scheme = "file"; schemeExplicitlyProvided = false; } else { scheme = group.Value; schemeExplicitlyProvided = true; } group = match.Groups["uncserver"]; if (group.Success) { string path; Pair<string, string> result; path = match.Groups["path1"].Value; result = path.SplitAroundCharFromLeft(1, PredicateUtils.ObjectEqualsAny('\\', '/')); root = "//" + group.Value + result.Left.Replace('\\', '/'); path = "/" + result.Right; if (path == "") { path = "/"; } query = match.Groups["query"].Value; return new LocalNodeAddress(scheme, root, true, StringUriUtils.NormalizePath(path), query); } else { string path; group = match.Groups["root"]; if (group.Captures.Count > 0) { // // Windows path specification // root = group.Value; path = match.Groups["path2"].Value; if (path.Length == 0) { path = FileSystemManager.SeperatorString; } query = match.Groups["query"].Value; path = StringUriUtils.NormalizePath(path); if (schemeExplicitlyProvided) { // // Explicitly provided scheme means // special characters are hexcoded // path = TextConversion.FromEscapedHexString(path); query = TextConversion.FromEscapedHexString(query); } return new LocalNodeAddress(scheme, root, true, path, query); } else if (match.Groups["path3"].Value != "") { // // Unix path specification // path = match.Groups["path3"].Value; query = match.Groups["query"].Value; path = StringUriUtils.NormalizePath(path); if (schemeExplicitlyProvided) { // // Explicitly provided scheme means // special characters are hexcoded // path = TextConversion.FromEscapedHexString(path); query = TextConversion.FromEscapedHexString(query); } return new LocalNodeAddress(scheme, "", true, path, query); } else { // // Relative path specification // path = match.Groups["path4"].Value; query = match.Groups["query"].Value; path = StringUriUtils.Combine(Environment.CurrentDirectory, path); path = StringUriUtils.NormalizePath(path); if (!string.IsNullOrEmpty(query)) { query = "?" + query; } else { query = ""; } if (schemeExplicitlyProvided) { uri = scheme + "://" + path + "query"; } else { uri = path + query; } match = null; } } } } protected override INodeAddress CreateAddress(string path, string query) { if (this.GetType() == typeof(LocalNodeAddress)) { return new LocalNodeAddress(this.Scheme, this.RootPart, this.includeRootPartInUri, path, query); } else { return (LocalNodeAddress)Activator.CreateInstance(GetType(), this.Scheme, this.RootPart, this.includeRootPartInUri, path, query); } } protected override string GetRootUri() { if (this.includeRootPartInUri) { return this.Scheme + "://" + this.RootPart; } else { return this.Scheme + "://"; } } public override INodeAddress CreateAsRoot(string scheme) { if (this.AbsolutePath == FileSystemManager.RootPath) { return new LocalNodeAddress(scheme, this.RootPart, false, "/"); } else { return new LocalNodeAddress(scheme, this.RootPart + this.AbsolutePath, false, "/"); } } public virtual string AbsoluteNativePath { get { string s; s = this.RootPart + TextConversion.FromEscapedHexString(this.AbsolutePath); if (System.IO.Path.DirectorySeparatorChar != '/') { s = s.Replace(System.IO.Path.DirectorySeparatorChar, '/'); } s = System.IO.Path.GetFullPath(s); return s; } } } }
using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security.Cryptography; using Common.Logging; using ToolKit.Validation; namespace ToolKit.Cryptography { /// <summary> /// Hash functions are fundamental to modern cryptography. These functions map binary strings of /// an arbitrary length to small binary strings of a fixed length, known as hash values. A /// cryptographic hash function has the property that it is computationally infeasible to find /// two distinct inputs that hash to the same value. Hash functions are commonly used with /// digital signatures and for data integrity. /// </summary> public class Hash : DisposableObject { private static readonly ILog _log = LogManager.GetLogger<Hash>(); private HashAlgorithm _hashAlgorithm; /// <summary> /// Initializes a new instance of the <see cref="Hash"/> class. /// </summary> /// <param name="provider">The Hash Algorithm Provider.</param> [SuppressMessage( "Security", "CA5351:Do Not Use Broken Cryptographic Algorithms", Justification = "While I wouldn't use broken algorithms, I don't want to break backward-compatibility.")] [SuppressMessage( "Security", "CA5350:Do Not Use Weak Cryptographic Algorithms", Justification = "While I wouldn't use weak algorithms, I don't want to break backward-compatibility.")] public Hash(Provider provider) { switch (provider) { case Provider.CRC32: _log.Debug("Using CRC32 provider..."); _hashAlgorithm = new Crc32Algorithm(); break; case Provider.MD5: _log.Debug("Using MD5 provider..."); _hashAlgorithm = new MD5CryptoServiceProvider(); break; case Provider.SHA1: _log.Debug("Using SHA1 provider..."); _hashAlgorithm = new SHA1Managed(); break; case Provider.SHA256: _log.Debug("Using SHA256 provider..."); _hashAlgorithm = new SHA256Managed(); break; case Provider.SHA384: _log.Debug("Using SHA384 provider..."); _hashAlgorithm = new SHA384Managed(); break; case Provider.SHA512: _log.Debug("Using SHA512 provider..."); _hashAlgorithm = new SHA512Managed(); break; default: _log.Error("Invalid Provider Provided!"); throw new ArgumentException("Invalid Provider Provided!"); } } /// <summary> /// Prevents a default instance of the <see cref="Hash"/> class from being created. /// </summary> [ExcludeFromCodeCoverage] private Hash() { } /// <summary> /// Type of hash; some are security oriented, others are fast and simple. /// </summary> public enum Provider { /// <summary> /// Cyclic Redundancy Check provider, 32-bit /// </summary> CRC32, /// <summary> /// Message Digest algorithm 5, 128-bit /// </summary> MD5, /// <summary> /// Secure Hashing Algorithm provider, SHA-1 variant, 160-bit /// </summary> SHA1, /// <summary> /// Secure Hashing Algorithm provider, SHA-2 variant, 256-bit /// </summary> SHA256, /// <summary> /// Secure Hashing Algorithm provider, SHA-2 variant, 384-bit /// </summary> SHA384, /// <summary> /// Secure Hashing Algorithm provider, SHA-2 variant, 512-bit /// </summary> SHA512 } /// <summary> /// Gets the previously calculated hash. /// </summary> public EncryptionData Value { get; } = new EncryptionData(); /// <summary> /// Calculates hash on a stream of arbitrary length. /// </summary> /// <param name="stream">The stream of data to read.</param> /// <returns>the hash of the data provided.</returns> public EncryptionData Calculate(Stream stream) { Value.Bytes = _hashAlgorithm.ComputeHash(stream); return Value; } /// <summary> /// Calculates hash for fixed length <see cref="EncryptionData"/>. /// </summary> /// <param name="data">The data to be used to hash.</param> /// <returns>the hash of the data provided.</returns> public EncryptionData Calculate(EncryptionData data) { Value.Bytes = _hashAlgorithm.ComputeHash(Check.NotNull(data, nameof(data)).Bytes); return Value; } /// <summary> /// Calculates hash for a string with a prefixed salt value. A "salt" is random data prefixed /// to every hashed value to prevent common dictionary attacks. /// </summary> /// <param name="data">The data to be used to hash.</param> /// <param name="salt">The salt to use during the hash.</param> /// <returns>the hash of the data provided.</returns> public EncryptionData Calculate(EncryptionData data, EncryptionData salt) { data = Check.NotNull(data, nameof(data)); salt = Check.NotNull(salt, nameof(salt)); var nb = new byte[data.Bytes.Length + salt.Bytes.Length]; salt.Bytes.CopyTo(nb, 0); data.Bytes.CopyTo(nb, salt.Bytes.Length); Value.Bytes = _hashAlgorithm.ComputeHash(nb); return Value; } /// <summary>Disposes the resources used by the inherited class.</summary> /// <param name="disposing"> /// <c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only /// unmanaged resources.</param> protected override void DisposeResources(bool disposing) { if (_hashAlgorithm != null) { _hashAlgorithm.Dispose(); _hashAlgorithm = null; } } /// <summary> /// Implements a cyclic redundancy check (CRC) hash algorithm. /// </summary> private sealed class Crc32Algorithm : HashAlgorithm { private uint _hash; private uint[] _table; /// <summary> /// Initializes a new instance of the <see cref="Crc32Algorithm"/> class. /// </summary> public Crc32Algorithm() { Initialize(); } /// <inheritdoc/> /// <summary> /// Initializes an implementation of the <see cref="HashAlgorithm"/> class. /// </summary> public override void Initialize() { if (_table != null) { return; } _table = new uint[256]; for (var i = 0; i < 256; i++) { var entry = (uint)i; for (var j = 0; j < 8; j++) { entry = (entry & 1) == 1 ? (entry >> 1) ^ 0xEDB88320 : entry >> 1; } _table[i] = entry; } _hash = 0xFFFFFFFF; } #pragma warning disable S927 // parameter names should match base declaration and other partial definitions /// <summary> /// Called by the base class to implement the hash algorithm. /// </summary> /// <param name="buffer">The buffer containing the data to calculate the CRC hash.</param> /// <param name="start">The start index of the buffer.</param> /// <param name="length">The length of the buffer.</param> protected override void HashCore(byte[] buffer, int start, int length) #pragma warning restore S927 // parameter names should match base declaration and other partial definitions { _hash = CalculateHash(_table, _hash, buffer, start, length); } /// <summary> /// When overridden in a derived class, finalizes the hash computation after the last /// data is processed by the cryptographic stream object. /// </summary> /// <returns>The computed hash code.</returns> protected override byte[] HashFinal() { var hashBuffer = ToBigEndianBytes(~_hash); HashValue = hashBuffer; return hashBuffer; } private static uint CalculateHash(uint[] table, uint seed, byte[] buffer, int start, int size) { var crc = seed; for (var i = start; i < size; i++) { unchecked { crc = (crc >> 8) ^ table[buffer[i] ^ (crc & 0xff)]; } } return crc; } private static byte[] ToBigEndianBytes(uint x) { return new[] { (byte)(x >> 24 & 0xff), (byte)(x >> 16 & 0xff), (byte)(x >> 8 & 0xff), (byte)(x & 0xff) }; } } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // AsynchronousOneToOneChannel.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Threading; using System.Diagnostics; namespace System.Linq.Parallel { /// <summary> /// This is a bounded channel meant for single-producer/single-consumer scenarios. /// </summary> /// <typeparam name="T">Specifies the type of data in the channel.</typeparam> internal sealed class AsynchronousChannel<T> : IDisposable { // The producer will be blocked once the channel reaches a capacity, and unblocked // as soon as a consumer makes room. A consumer can block waiting until a producer // enqueues a new element. We use a chunking scheme to adjust the granularity and // frequency of synchronization, e.g. by enqueueing/dequeueing N elements at a time. // Because there is only ever a single producer and consumer, we are able to achieve // efficient and low-overhead synchronization. // // In general, the buffer has four logical states: // FULL <--> OPEN <--> EMPTY <--> DONE // // Here is a summary of the state transitions and what they mean: // * OPEN: // A buffer starts in the OPEN state. When the buffer is in the READY state, // a consumer and producer can dequeue and enqueue new elements. // * OPEN->FULL: // A producer transitions the buffer from OPEN->FULL when it enqueues a chunk // that causes the buffer to reach capacity; a producer can no longer enqueue // new chunks when this happens, causing it to block. // * FULL->OPEN: // When the consumer takes a chunk from a FULL buffer, it transitions back from // FULL->OPEN and the producer is woken up. // * OPEN->EMPTY: // When the consumer takes the last chunk from a buffer, the buffer is // transitioned from OPEN->EMPTY; a consumer can no longer take new chunks, // causing it to block. // * EMPTY->OPEN: // Lastly, when the producer enqueues an item into an EMPTY buffer, it // transitions to the OPEN state. This causes any waiting consumers to wake up. // * EMPTY->DONE: // If the buffer is empty, and the producer is done enqueueing new // items, the buffer is DONE. There will be no more consumption or production. // // Assumptions: // There is only ever one producer and one consumer operating on this channel // concurrently. The internal synchronization cannot handle anything else. // // ** WARNING ** WARNING ** WARNING ** WARNING ** WARNING ** WARNING ** WARNING ** // VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV // // There... got your attention now... just in case you didn't read the comments // very carefully above, this channel will deadlock, become corrupt, and generally // make you an unhappy camper if you try to use more than 1 producer or more than // 1 consumer thread to access this thing concurrently. It's been carefully designed // to avoid locking, but only because of this restriction... private readonly T[][] _buffer; // The buffer of chunks. private readonly int _index; // Index of this channel private volatile int _producerBufferIndex; // Producer's current index, i.e. where to put the next chunk. private volatile int _consumerBufferIndex; // Consumer's current index, i.e. where to get the next chunk. private volatile bool _done; // Set to true once the producer is done. private T[] _producerChunk; // The temporary chunk being generated by the producer. private int _producerChunkIndex; // A producer's index into its temporary chunk. private T[] _consumerChunk; // The temporary chunk being enumerated by the consumer. private int _consumerChunkIndex; // A consumer's index into its temporary chunk. private readonly int _chunkSize; // The number of elements that comprise a chunk. // These events are used to signal a waiting producer when the consumer dequeues, and to signal a // waiting consumer when the producer enqueues. private ManualResetEventSlim _producerEvent; private IntValueEvent _consumerEvent; // These two-valued ints track whether a producer or consumer _might_ be waiting. They are marked // volatile because they are used in synchronization critical regions of code (see usage below). private volatile int _producerIsWaiting; private volatile int _consumerIsWaiting; private readonly CancellationToken _cancellationToken; //----------------------------------------------------------------------------------- // Initializes a new channel with the specific capacity and chunk size. // // Arguments: // orderingHelper - the ordering helper to use for order preservation // capacity - the maximum number of elements before a producer blocks // chunkSize - the granularity of chunking on enqueue/dequeue. 0 means default size. // // Notes: // The capacity represents the maximum number of chunks a channel can hold. That // means producers will actually block after enqueueing capacity*chunkSize // individual elements. // internal AsynchronousChannel(int index, int chunkSize, CancellationToken cancellationToken, IntValueEvent consumerEvent) : this(index, Scheduling.DEFAULT_BOUNDED_BUFFER_CAPACITY, chunkSize, cancellationToken, consumerEvent) { } internal AsynchronousChannel(int index, int capacity, int chunkSize, CancellationToken cancellationToken, IntValueEvent consumerEvent) { if (chunkSize == 0) chunkSize = Scheduling.GetDefaultChunkSize<T>(); Debug.Assert(chunkSize > 0, "chunk size must be greater than 0"); Debug.Assert(capacity > 1, "this impl doesn't support capacity of 1 or 0"); // Initialize a buffer with enough space to hold 'capacity' elements. // We need one extra unused element as a sentinel to detect a full buffer, // thus we add one to the capacity requested. _index = index; _buffer = new T[capacity + 1][]; _producerBufferIndex = 0; _consumerBufferIndex = 0; _producerEvent = new ManualResetEventSlim(); _consumerEvent = consumerEvent; _chunkSize = chunkSize; _producerChunk = new T[chunkSize]; _producerChunkIndex = 0; _cancellationToken = cancellationToken; } //----------------------------------------------------------------------------------- // Checks whether the buffer is full. If the consumer is calling this, they can be // assured that a true value won't change before the consumer has a chance to dequeue // elements. That's because only one consumer can run at once. A producer might see // a true value, however, and then a consumer might transition to non-full, so it's // not stable for them. Lastly, it's of course possible to see a false value when // there really is a full queue, it's all dependent on small race conditions. // internal bool IsFull { get { // Read the fields once. One of these is always stable, since the only threads // that call this are the 1 producer/1 consumer threads. int producerIndex = _producerBufferIndex; int consumerIndex = _consumerBufferIndex; // Two cases: // 1) Is the producer index one less than the consumer? // 2) The producer is at the end of the buffer and the consumer at the beginning. return (producerIndex == consumerIndex - 1) || (consumerIndex == 0 && producerIndex == _buffer.Length - 1); // Note to readers: you might have expected us to consider the case where // _producerBufferIndex == _buffer.Length && _consumerBufferIndex == 1. // That is, a producer has gone off the end of the array, but is about to // wrap around to the 0th element again. We don't need this for a subtle // reason. It is SAFE for a consumer to think we are non-full when we // actually are full; it is NOT for a producer; but thankfully, there is // only one producer, and hence the producer will never see this seemingly // invalid state. Hence, we're fine producing a false negative. It's all // based on a race condition we have to deal with anyway. } } //----------------------------------------------------------------------------------- // Checks whether the buffer is empty. If the producer is calling this, they can be // assured that a true value won't change before the producer has a chance to enqueue // an item. That's because only one producer can run at once. A consumer might see // a true value, however, and then a producer might transition to non-empty. // internal bool IsChunkBufferEmpty { get { // The queue is empty when the producer and consumer are at the same index. return _producerBufferIndex == _consumerBufferIndex; } } //----------------------------------------------------------------------------------- // Checks whether the producer is done enqueueing new elements. // internal bool IsDone { get { return _done; } } //----------------------------------------------------------------------------------- // Used by a producer to flush out any internal buffers that have been accumulating // data, but which hasn't yet been published to the consumer. internal void FlushBuffers() { TraceHelpers.TraceInfo("tid {0}: AsynchronousChannel<T>::FlushBuffers() called", Environment.CurrentManagedThreadId); // Ensure that a partially filled chunk is made available to the consumer. FlushCachedChunk(); } //----------------------------------------------------------------------------------- // Used by a producer to signal that it is done producing new elements. This will // also wake up any consumers that have gone to sleep. // internal void SetDone() { TraceHelpers.TraceInfo("tid {0}: AsynchronousChannel<T>::SetDone() called", Environment.CurrentManagedThreadId); // This is set with a volatile write to ensure that, after the consumer // sees done, they can re-read the enqueued chunks and see the last one we // enqueued just above. _done = true; // We set the event to ensure consumers that may have waited or are // considering waiting will notice that the producer is done. This is done // after setting the done flag to facilitate a Dekker-style check/recheck. // // Because we can race with threads trying to Dispose of the event, we must // acquire a lock around our setting, and double-check that the event isn't null. // // Update 8/2/2011: Dispose() should never be called with SetDone() concurrently, // but in order to reduce churn late in the product cycle, we decided not to // remove the lock. lock (this) { if (_consumerEvent != null) { _consumerEvent.Set(_index); } } } //----------------------------------------------------------------------------------- // Enqueues a new element to the buffer, possibly blocking in the process. // // Arguments: // item - the new element to enqueue // timeoutMilliseconds - a timeout (or -1 for no timeout) used in case the buffer // is full; we return false if it expires // // Notes: // This API will block until the buffer is non-full. This internally buffers // elements up into chunks, so elements are not immediately available to consumers. // internal void Enqueue(T item) { // Store the element into our current chunk. int producerChunkIndex = _producerChunkIndex; _producerChunk[producerChunkIndex] = item; // And lastly, if we have filled a chunk, make it visible to consumers. if (producerChunkIndex == _chunkSize - 1) { EnqueueChunk(_producerChunk); _producerChunk = new T[_chunkSize]; } _producerChunkIndex = (producerChunkIndex + 1) % _chunkSize; } //----------------------------------------------------------------------------------- // Internal helper to queue a real chunk, not just an element. // // Arguments: // chunk - the chunk to make visible to consumers // timeoutMilliseconds - an optional timeout; we return false if it expires // // Notes: // This API will block if the buffer is full. A chunk must contain only valid // elements; if the chunk wasn't filled, it should be trimmed to size before // enqueueing it for consumers to observe. // private void EnqueueChunk(T[] chunk) { Debug.Assert(chunk != null); Debug.Assert(!_done, "can't continue producing after the production is over"); if (IsFull) WaitUntilNonFull(); Debug.Assert(!IsFull, "expected a non-full buffer"); // We can safely store into the current producer index because we know no consumers // will be reading from it concurrently. int bufferIndex = _producerBufferIndex; _buffer[bufferIndex] = chunk; // Increment the producer index, taking into count wrapping back to 0. This is a shared // write; the CLR 2.0 memory model ensures the write won't move before the write to the // corresponding element, so a consumer won't see the new index but the corresponding // element in the array as empty. Interlocked.Exchange(ref _producerBufferIndex, (bufferIndex + 1) % _buffer.Length); // (If there is a consumer waiting, we have to ensure to signal the event. Unfortunately, // this requires that we issue a memory barrier: We need to guarantee that the write to // our producer index doesn't pass the read of the consumer waiting flags; the CLR memory // model unfortunately permits this reordering. That is handled by using a CAS above.) if (_consumerIsWaiting == 1 && !IsChunkBufferEmpty) { TraceHelpers.TraceInfo("AsynchronousChannel::EnqueueChunk - producer waking consumer"); _consumerIsWaiting = 0; _consumerEvent.Set(_index); } } //----------------------------------------------------------------------------------- // Just waits until the queue is non-full. // private void WaitUntilNonFull() { // We must loop; sometimes the producer event will have been set // prematurely due to the way waiting flags are managed. By looping, // we will only return from this method when space is truly available. do { // If the queue is full, we have to wait for a consumer to make room. // Reset the event to unsignaled state before waiting. _producerEvent.Reset(); // We have to handle the case where a producer and consumer are racing to // wait simultaneously. For instance, a producer might see a full queue (by // reading IsFull just above), but meanwhile a consumer might drain the queue // very quickly, suddenly seeing an empty queue. This would lead to deadlock // if we aren't careful. Therefore we check the empty/full state AGAIN after // setting our flag to see if a real wait is warranted. Interlocked.Exchange(ref _producerIsWaiting, 1); // (We have to prevent the reads that go into determining whether the buffer // is full from moving before the write to the producer-wait flag. Hence the CAS.) // Because we might be racing with a consumer that is transitioning the // buffer from full to non-full, we must check that the queue is full once // more. Otherwise, we might decide to wait and never be woken up (since // we just reset the event). if (IsFull) { // Assuming a consumer didn't make room for us, we can wait on the event. TraceHelpers.TraceInfo("AsynchronousChannel::EnqueueChunk - producer waiting, buffer full"); _producerEvent.Wait(_cancellationToken); } else { // Reset the flags, we don't actually have to wait after all. _producerIsWaiting = 0; } } while (IsFull); } //----------------------------------------------------------------------------------- // Flushes any built up elements that haven't been made available to a consumer yet. // Only safe to be called by a producer. // // Notes: // This API can block if the channel is currently full. // private void FlushCachedChunk() { // If the producer didn't fill their temporary working chunk, flushing forces an enqueue // so that a consumer will see the partially filled chunk of elements. if (_producerChunk != null && _producerChunkIndex != 0) { // Trim the partially-full chunk to an array just big enough to hold it. Debug.Assert(1 <= _producerChunkIndex && _producerChunkIndex <= _chunkSize); T[] leftOverChunk = new T[_producerChunkIndex]; Array.Copy(_producerChunk, 0, leftOverChunk, 0, _producerChunkIndex); // And enqueue the right-sized temporary chunk, possibly blocking if it's full. EnqueueChunk(leftOverChunk); _producerChunk = null; } } //----------------------------------------------------------------------------------- // Dequeues the next element in the queue. // // Arguments: // item - a byref to the location into which we'll store the dequeued element // // Return Value: // True if an item was found, false otherwise. // internal bool TryDequeue(ref T item) { // Ensure we have a chunk to work with. if (_consumerChunk == null) { if (!TryDequeueChunk(ref _consumerChunk)) { Debug.Assert(_consumerChunk == null); return false; } _consumerChunkIndex = 0; } // Retrieve the current item in the chunk. Debug.Assert(_consumerChunk != null, "consumer chunk is null"); Debug.Assert(0 <= _consumerChunkIndex && _consumerChunkIndex < _consumerChunk.Length, "chunk index out of bounds"); item = _consumerChunk[_consumerChunkIndex]; // And lastly, if we have consumed the chunk, null it out so we'll get the // next one when dequeue is called again. ++_consumerChunkIndex; if (_consumerChunkIndex == _consumerChunk.Length) { _consumerChunk = null; } return true; } //----------------------------------------------------------------------------------- // Internal helper method to dequeue a whole chunk. // // Arguments: // chunk - a byref to the location into which we'll store the chunk // // Return Value: // True if a chunk was found, false otherwise. // private bool TryDequeueChunk(ref T[] chunk) { // This is the non-blocking version of dequeue. We first check to see // if the queue is empty. If the caller chooses to wait later, they can // call the overload with an event. if (IsChunkBufferEmpty) { return false; } chunk = InternalDequeueChunk(); return true; } //----------------------------------------------------------------------------------- // Blocking dequeue for the next element. This version of the API is used when the // caller will possibly wait for a new chunk to be enqueued. // // Arguments: // item - a byref for the returned element // waitEvent - a byref for the event used to signal blocked consumers // // Return Value: // True if an element was found, false otherwise. // // Notes: // If the return value is false, it doesn't always mean waitEvent will be non- // null. If the producer is done enqueueing, the return will be false and the // event will remain null. A caller must check for this condition. // // If the return value is false and an event is returned, there have been // side-effects on the channel. Namely, the flag telling producers a consumer // might be waiting will have been set. DequeueEndAfterWait _must_ be called // eventually regardless of whether the caller actually waits or not. // internal bool TryDequeue(ref T item, ref bool isDone) { isDone = false; // Ensure we have a buffer to work with. if (_consumerChunk == null) { if (!TryDequeueChunk(ref _consumerChunk, ref isDone)) { Debug.Assert(_consumerChunk == null); return false; } _consumerChunkIndex = 0; } // Retrieve the current item in the chunk. Debug.Assert(_consumerChunk != null, "consumer chunk is null"); Debug.Assert(0 <= _consumerChunkIndex && _consumerChunkIndex < _consumerChunk.Length, "chunk index out of bounds"); item = _consumerChunk[_consumerChunkIndex]; // And lastly, if we have consumed the chunk, null it out. ++_consumerChunkIndex; if (_consumerChunkIndex == _consumerChunk.Length) { _consumerChunk = null; } return true; } //----------------------------------------------------------------------------------- // Internal helper method to dequeue a whole chunk. This version of the API is used // when the caller will wait for a new chunk to be enqueued. // // Arguments: // chunk - a byref for the dequeued chunk // waitEvent - a byref for the event used to signal blocked consumers // // Return Value: // True if a chunk was found, false otherwise. // // Notes: // If the return value is false, it doesn't always mean waitEvent will be non- // null. If the producer is done enqueueing, the return will be false and the // event will remain null. A caller must check for this condition. // // If the return value is false and an event is returned, there have been // side-effects on the channel. Namely, the flag telling producers a consumer // might be waiting will have been set. DequeueEndAfterWait _must_ be called // eventually regardless of whether the caller actually waits or not. // private bool TryDequeueChunk(ref T[] chunk, ref bool isDone) { isDone = false; // We will register our interest in waiting, and then return an event // that the caller can use to wait. while (IsChunkBufferEmpty) { // If the producer is done and we've drained the queue, we can bail right away. if (IsDone) { // We have to see if the buffer is empty AFTER we've seen that it's done. // Otherwise, we would possibly miss the elements enqueued before the // producer signaled that it's done. This is done with a volatile load so // that the read of empty doesn't move before the read of done. if (IsChunkBufferEmpty) { // Return isDone=true so callers know not to wait isDone = true; return false; } } // We have to handle the case where a producer and consumer are racing to // wait simultaneously. For instance, a consumer might see an empty queue (by // reading IsChunkBufferEmpty just above), but meanwhile a producer might fill the queue // very quickly, suddenly seeing a full queue. This would lead to deadlock // if we aren't careful. Therefore we check the empty/full state AGAIN after // setting our flag to see if a real wait is warranted. Interlocked.Exchange(ref _consumerIsWaiting, 1); // (We have to prevent the reads that go into determining whether the buffer // is full from moving before the write to the producer-wait flag. Hence the CAS.) // Because we might be racing with a producer that is transitioning the // buffer from empty to non-full, we must check that the queue is empty once // more. Similarly, if the queue has been marked as done, we must not wait // because we just reset the event, possibly losing as signal. In both cases, // we would otherwise decide to wait and never be woken up (i.e. deadlock). if (IsChunkBufferEmpty && !IsDone) { // Note that the caller must eventually call DequeueEndAfterWait to set the // flags back to a state where no consumer is waiting, whether they choose // to wait or not. TraceHelpers.TraceInfo("AsynchronousChannel::DequeueChunk - consumer possibly waiting"); return false; } else { // Reset the wait flags, we don't need to wait after all. We loop back around // and recheck that the queue isn't empty, done, etc. _consumerIsWaiting = 0; } } Debug.Assert(!IsChunkBufferEmpty, "single-consumer should never witness an empty queue here"); chunk = InternalDequeueChunk(); return true; } //----------------------------------------------------------------------------------- // Internal helper method that dequeues a chunk after we've verified that there is // a chunk available to dequeue. // // Return Value: // The dequeued chunk. // // Assumptions: // The caller has verified that a chunk is available, i.e. the queue is non-empty. // private T[] InternalDequeueChunk() { Debug.Assert(!IsChunkBufferEmpty); // We can safely read from the consumer index because we know no producers // will write concurrently. int consumerBufferIndex = _consumerBufferIndex; T[] chunk = _buffer[consumerBufferIndex]; // Zero out contents to avoid holding on to memory for longer than necessary. This // ensures the entire chunk is eligible for GC sooner. (More important for big chunks.) _buffer[consumerBufferIndex] = null; // Increment the consumer index, taking into count wrapping back to 0. This is a shared // write; the CLR 2.0 memory model ensures the write won't move before the write to the // corresponding element, so a consumer won't see the new index but the corresponding // element in the array as empty. Interlocked.Exchange(ref _consumerBufferIndex, (consumerBufferIndex + 1) % _buffer.Length); // (Unfortunately, this whole sequence requires a memory barrier: We need to guarantee // that the write to _consumerBufferIndex doesn't pass the read of the wait-flags; the CLR memory // model sadly permits this reordering. Hence the CAS above.) if (_producerIsWaiting == 1 && !IsFull) { TraceHelpers.TraceInfo("BoundedSingleLockFreeChannel::DequeueChunk - consumer waking producer"); _producerIsWaiting = 0; _producerEvent.Set(); } return chunk; } //----------------------------------------------------------------------------------- // Clears the flag set when a blocking Dequeue is called, letting producers know // the consumer is no longer waiting. // internal void DoneWithDequeueWait() { // On our way out, be sure to reset the flags. _consumerIsWaiting = 0; } //----------------------------------------------------------------------------------- // Closes Win32 events possibly allocated during execution. // public void Dispose() { // We need to take a lock to deal with consumer threads racing to call Dispose // and producer threads racing inside of SetDone. // // Update 8/2/2011: Dispose() should never be called with SetDone() concurrently, // but in order to reduce churn late in the product cycle, we decided not to // remove the lock. lock (this) { Debug.Assert(_done, "Expected channel to be done before disposing"); Debug.Assert(_producerEvent != null); Debug.Assert(_consumerEvent != null); _producerEvent.Dispose(); _producerEvent = null; _consumerEvent = null; } } } }
//--------------------------------------------------------------------- // This file is part of the CLR Managed Debugger (mdbg) Sample. // // Copyright (C) Microsoft Corporation. All rights reserved. // // Part of managed wrappers for native debugging APIs. // NativeImports.cs: raw definitions of native methods and structures // for native debugging API. // Also includes some useful utility methods. //--------------------------------------------------------------------- using Microsoft.Samples.Debugging.NativeApi; using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security.Permissions; // Native structures used for the implementation of the pipeline. namespace Microsoft.Samples.Debugging.NativeApi { #region Structures for CreateProcess [StructLayout(LayoutKind.Sequential, Pack = 8), ComVisible(false)] public class PROCESS_INFORMATION { public IntPtr hProcess; public IntPtr hThread; public int dwProcessId; public int dwThreadId; public PROCESS_INFORMATION() { } } [StructLayout(LayoutKind.Sequential, Pack = 8), ComVisible(false)] public class SECURITY_ATTRIBUTES { public int nLength; public IntPtr lpSecurityDescriptor; public bool bInheritHandle; public SECURITY_ATTRIBUTES() { } } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 8), ComVisible(false)] public class STARTUPINFO { public int cb; public string lpReserved; public string lpDesktop; public string lpTitle; public int dwX; public int dwY; public int dwXSize; public int dwYSize; public int dwXCountChars; public int dwYCountChars; public int dwFillAttribute; public int dwFlags; public short wShowWindow; public short cbReserved2; public IntPtr lpReserved2; public SafeFileHandle hStdInput; public SafeFileHandle hStdOutput; public SafeFileHandle hStdError; public STARTUPINFO() { // Initialize size field. cb = Marshal.SizeOf(this); // initialize safe handles hStdInput = new Microsoft.Win32.SafeHandles.SafeFileHandle(new IntPtr(0), false); hStdOutput = new Microsoft.Win32.SafeHandles.SafeFileHandle(new IntPtr(0), false); hStdError = new Microsoft.Win32.SafeHandles.SafeFileHandle(new IntPtr(0), false); } } #endregion // Structures for CreateProcess } // Microsoft.Samples.Debugging.CorDebug.NativeApi namespace Microsoft.Samples.Debugging.Native { #region Interfaces /// <summary> /// Thrown when failing to read memory from a target. /// </summary> [Serializable()] public class ReadMemoryFailureException : InvalidOperationException { /// <summary> /// Initialize a new exception /// </summary> /// <param name="address">address where read failed</param> /// <param name="countBytes">size of read attempted</param> public ReadMemoryFailureException(IntPtr address, int countBytes) : base(MessageHelper(address, countBytes)) { } public ReadMemoryFailureException(IntPtr address, int countBytes, Exception innerException) : base(MessageHelper(address, countBytes), innerException) { } // Internal helper to get the message string for the ctor. private static string MessageHelper(IntPtr address, int countBytes) { return String.Format("Failed to read memory at 0x" + address.ToString("x") + " of " + countBytes + " bytes."); } #region Standard Ctors /// <summary> /// Initializes a new instance of the ReadMemoryFailureException. /// </summary> public ReadMemoryFailureException() { } /// <summary> /// Initializes a new instance of the ReadMemoryFailureException with the specified error message. /// </summary> /// <param name="message">The message that describes the error.</param> public ReadMemoryFailureException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the ReadMemoryFailureException with the specified error message and inner Exception. /// </summary> /// <param name="message">The message that describes the error.</param> /// <param name="innerException">The exception that is the cause of the current exception.</param> public ReadMemoryFailureException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Initializes a new instance of the ReadMemoryFailureException class with serialized data. /// </summary> /// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param> protected ReadMemoryFailureException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endregion } // <strip>This may evolve into a data-target</strip> /// <summary> /// Interface to provide access to target /// </summary> public interface IMemoryReader { /// <summary> /// Read memory from the target process. Either reads all memory or throws. /// </summary> /// <param name="address">target address to read memory from</param> /// <param name="buffer">buffer to fill with memory</param> /// <exception cref="ReadMemoryFailureException">Throws if can't read all the memory</exception> void ReadMemory(IntPtr address, byte[] buffer); } #endregion #region Native Structures /// <summary> /// Platform agnostic flags used to extract platform-specific context flag values /// </summary> [Flags] public enum AgnosticContextFlags : int { //using a seperate bit for each flag will allow logical operations of flags // i.e ContextControl | ContextInteger | ContextSegments, etc ContextControl = 0x1, ContextInteger = 0x2, ContextFloatingPoint = 0x4, ContextDebugRegisters = 0x10, //on IA64, this will be equivalent to ContextDebug ContextAll = 0x3F, None = 0x0 } [Flags] public enum ContextFlags { None = 0, X86Context = 0x10000, X86ContextControl = X86Context | 0x1, X86ContextInteger = X86Context | 0x2, X86ContextSegments = X86Context | 0x4, X86ContextFloatingPoint = X86Context | 0x8, X86ContextDebugRegisters = X86Context | 0x10, X86ContextExtendedRegisters = X86Context | 0x20, X86ContextFull = X86Context | X86ContextControl | X86ContextInteger | X86ContextSegments, X86ContextAll = X86Context | X86ContextControl | X86ContextInteger | X86ContextSegments | X86ContextFloatingPoint | X86ContextDebugRegisters | X86ContextExtendedRegisters, AMD64Context = 0x100000, AMD64ContextControl = AMD64Context | 0x1, AMD64ContextInteger = AMD64Context | 0x2, AMD64ContextSegments = AMD64Context | 0x4, AMD64ContextFloatingPoint = AMD64Context | 0x8, AMD64ContextDebugRegisters = AMD64Context | 0x10, AMD64ContextFull = AMD64Context | AMD64ContextControl | AMD64ContextInteger | AMD64ContextFloatingPoint, AMD64ContextAll = AMD64Context | AMD64ContextControl | AMD64ContextInteger | AMD64ContextSegments | AMD64ContextFloatingPoint | AMD64ContextDebugRegisters, IA64Context = 0x80000, IA64ContextControl = IA64Context | 0x1, IA64ContextLowerFloatingPoint = IA64Context | 0x2, IA64ContextHigherFloatingPoint = IA64Context | 0x4, IA64ContextInteger = IA64Context | 0x8, IA64ContextDebug = IA64Context | 0x10, IA64ContextIA32Control = IA64Context | 0x20, IA64ContextFloatingPoint = IA64Context | IA64ContextLowerFloatingPoint | IA64ContextHigherFloatingPoint, IA64ContextFull = IA64Context | IA64ContextControl | IA64ContextFloatingPoint | IA64ContextInteger | IA64ContextIA32Control, IA64ContextAll = IA64Context | IA64ContextControl | IA64ContextFloatingPoint | IA64ContextInteger | IA64ContextDebug | IA64ContextIA32Control, ARMContext = 0x200000, ARMContextControl = ARMContext | 0x1, ARMContextInteger = ARMContext | 0x2, ARMContextFloatingPoint = ARMContext | 0x4, ARMContextDebugRegisters = ARMContext | 0x8, ARMContextFull = ARMContext | ARMContextControl | ARMContextInteger, ARMContextAll = ARMContext | ARMContextControl | ARMContextInteger | ARMContextDebugRegisters, } public enum ContextSize : int { None = 0, X86 = 716, AMD64 = 1232, IA64 = 2672, ARM = 416, } [Flags] public enum X86Offsets : int { ContextFlags = 0x0, // This section is specified/returned if CONTEXT_DEBUG_REGISTERS is // set in ContextFlags. Note that CONTEXT_DEBUG_REGISTERS is NOT // included in CONTEXT_FULL. Dr0 = 0x4, Dr1 = 0x8, Dr2 = 0xC, Dr3 = 0x10, Dr6 = 0x14, Dr7 = 0x18, // This section is specified/returned if the // ContextFlags word contians the flag CONTEXT_FLOATING_POINT. FloatSave = 0x1C, // This section is specified/returned if the // ContextFlags word contians the flag CONTEXT_SEGMENTS. SegGs = 0x8C, SegFs = 0x90, SegEs = 0x94, SegDs = 0x98, // This section is specified/returned if the // ContextFlags word contians the flag CONTEXT_INTEGER. Edi = 0x9C, Esi = 0xA0, Ebx = 0xA4, Edx = 0xA8, Ecx = 0xAC, Eax = 0xB0, // This section is specified/returned if the // ContextFlags word contians the flag CONTEXT_CONTROL. Ebp = 0xB4, Eip = 0xB8, SegCs = 0xBC, EFlags = 0xC0, Esp = 0xC4, SegSs = 0xC8, // This section is specified/returned if the ContextFlags word // contains the flag CONTEXT_EXTENDED_REGISTERS. // The format and contexts are processor specific ExtendedRegisters = 0xCB, //512 } [Flags] public enum X86Flags : int { SINGLE_STEP_FLAG = 0x100, } [Flags] public enum AMD64Offsets : int { // Register Parameter Home Addresses P1Home = 0x000, P2Home = 0x008, P3Home = 0x010, P4Home = 0x018, P5Home = 0x020, P6Home = 0x028, // Control Flags ContextFlags = 0x030, MxCsr = 0x034, // Segment Registers and Processor Flags SegCs = 0x038, SegDs = 0x03a, SegEs = 0x03c, SegFs = 0x03e, SegGs = 0x040, SegSs = 0x042, EFlags = 0x044, // Debug Registers Dr0 = 0x048, Dr1 = 0x050, Dr2 = 0x058, Dr3 = 0x060, Dr6 = 0x068, Dr7 = 0x070, // Integer Registers Rax = 0x078, Rcx = 0x080, Rdx = 0x088, Rbx = 0x090, Rsp = 0x098, Rbp = 0x0a0, Rsi = 0x0a8, Rdi = 0x0b0, R8 = 0x0b8, R9 = 0x0c0, R10 = 0x0c8, R11 = 0x0d0, R12 = 0x0d8, R13 = 0x0e0, R14 = 0x0e8, R15 = 0x0f0, // Program Counter Rip = 0x0f8, // Floating Point State FltSave = 0x100, Legacy = 0x120, Xmm0 = 0x1a0, Xmm1 = 0x1b0, Xmm2 = 0x1c0, Xmm3 = 0x1d0, Xmm4 = 0x1e0, Xmm5 = 0x1f0, Xmm6 = 0x200, Xmm7 = 0x210, Xmm8 = 0x220, Xmm9 = 0x230, Xmm10 = 0x240, Xmm11 = 0x250, Xmm12 = 0x260, Xmm13 = 0x270, Xmm14 = 0x280, Xmm15 = 0x290, // Vector Registers VectorRegister = 0x300, VectorControl = 0x4a0, // Special Debug Control Registers DebugControl = 0x4a8, LastBranchToRip = 0x4b0, LastBranchFromRip = 0x4b8, LastExceptionToRip = 0x4c0, LastExceptionFromRip = 0x4c8, } [Flags] public enum AMD64Flags : int { SINGLE_STEP_FLAG = 0x100, } [Flags] public enum IA64Offsets : int { ContextFlags = 0x0, // This section is specified/returned if the ContextFlags word contains // the flag CONTEXT_DEBUG. DbI0 = 0x010, DbI1 = 0x018, DbI2 = 0x020, DbI3 = 0x028, DbI4 = 0x030, DbI5 = 0x038, DbI6 = 0x040, DbI7 = 0x048, DbD0 = 0x050, DbD1 = 0x058, DbD2 = 0x060, DbD3 = 0x068, DbD4 = 0x070, DbD5 = 0x078, DbD6 = 0x080, DbD7 = 0x088, // This section is specified/returned if the ContextFlags word contains // the flag CONTEXT_LOWER_FLOATING_POINT. FltS0 = 0x090, FltS1 = 0x0a0, FltS2 = 0x0b0, FltS3 = 0x0c0, FltT0 = 0x0d0, FltT1 = 0x0e0, FltT2 = 0x0f0, FltT3 = 0x100, FltT4 = 0x110, FltT5 = 0x120, FltT6 = 0x130, FltT7 = 0x140, FltT8 = 0x150, FltT9 = 0x160, // This section is specified/returned if the ContextFlags word contains // the flag CONTEXT_HIGHER_FLOATING_POINT. FltS4 = 0x170, FltS5 = 0x180, FltS6 = 0x190, FltS7 = 0x1a0, FltS8 = 0x1b0, FltS9 = 0x1c0, FltS10 = 0x1d0, FltS11 = 0x1e0, FltS12 = 0x1f0, FltS13 = 0x200, FltS14 = 0x210, FltS15 = 0x220, FltS16 = 0x230, FltS17 = 0x240, FltS18 = 0x250, FltS19 = 0x260, FltF32 = 0x270, FltF33 = 0x280, FltF34 = 0x290, FltF35 = 0x2a0, FltF36 = 0x2b0, FltF37 = 0x2c0, FltF38 = 0x2d0, FltF39 = 0x2e0, FltF40 = 0x2f0, FltF41 = 0x300, FltF42 = 0x310, FltF43 = 0x320, FltF44 = 0x330, FltF45 = 0x340, FltF46 = 0x350, FltF47 = 0x360, FltF48 = 0x370, FltF49 = 0x380, FltF50 = 0x390, FltF51 = 0x3a0, FltF52 = 0x3b0, FltF53 = 0x3c0, FltF54 = 0x3d0, FltF55 = 0x3e0, FltF56 = 0x3f0, FltF57 = 0x400, FltF58 = 0x410, FltF59 = 0x420, FltF60 = 0x430, FltF61 = 0x440, FltF62 = 0x450, FltF63 = 0x460, FltF64 = 0x470, FltF65 = 0x480, FltF66 = 0x490, FltF67 = 0x4a0, FltF68 = 0x4b0, FltF69 = 0x4c0, FltF70 = 0x4d0, FltF71 = 0x4e0, FltF72 = 0x4f0, FltF73 = 0x500, FltF74 = 0x510, FltF75 = 0x520, FltF76 = 0x530, FltF77 = 0x540, FltF78 = 0x550, FltF79 = 0x560, FltF80 = 0x570, FltF81 = 0x580, FltF82 = 0x590, FltF83 = 0x5a0, FltF84 = 0x5b0, FltF85 = 0x5c0, FltF86 = 0x5d0, FltF87 = 0x5e0, FltF88 = 0x5f0, FltF89 = 0x600, FltF90 = 0x610, FltF91 = 0x620, FltF92 = 0x630, FltF93 = 0x640, FltF94 = 0x650, FltF95 = 0x660, FltF96 = 0x670, FltF97 = 0x680, FltF98 = 0x690, FltF99 = 0x6a0, FltF100 = 0x6b0, FltF101 = 0x6c0, FltF102 = 0x6d0, FltF103 = 0x6e0, FltF104 = 0x6f0, FltF105 = 0x700, FltF106 = 0x710, FltF107 = 0x720, FltF108 = 0x730, FltF109 = 0x740, FltF110 = 0x750, FltF111 = 0x760, FltF112 = 0x770, FltF113 = 0x780, FltF114 = 0x790, FltF115 = 0x7a0, FltF116 = 0x7b0, FltF117 = 0x7c0, FltF118 = 0x7d0, FltF119 = 0x7e0, FltF120 = 0x7f0, FltF121 = 0x800, FltF122 = 0x810, FltF123 = 0x820, FltF124 = 0x830, FltF125 = 0x840, FltF126 = 0x850, FltF127 = 0x860, // This section is specified/returned if the ContextFlags word contains // the flag CONTEXT_LOWER_FLOATING_POINT | CONTEXT_HIGHER_FLOATING_POINT | CONTEXT_CONTROL. StFPSR = 0x870, // FP status // This section is specified/returned if the ContextFlags word contains // the flag CONTEXT_INTEGER. IntGp = 0x878, // r1 = 0x, volatile IntT0 = 0x880, // r2-r3 = 0x, volatile IntT1 = 0x888, // IntS0 = 0x890, // r4-r7 = 0x, preserved IntS1 = 0x898, IntS2 = 0x8a0, IntS3 = 0x8a8, IntV0 = 0x8b0, // r8 = 0x, volatile IntT2 = 0x8b8, // r9-r11 = 0x, volatile IntT3 = 0x8c0, IntT4 = 0x8c8, IntSp = 0x8d0, // stack pointer (r12) = 0x, special IntTeb = 0x8d8, // teb (r13) = 0x, special IntT5 = 0x8e0, // r14-r31 = 0x, volatile IntT6 = 0x8e8, IntT7 = 0x8f0, IntT8 = 0x8f8, IntT9 = 0x900, IntT10 = 0x908, IntT11 = 0x910, IntT12 = 0x918, IntT13 = 0x920, IntT14 = 0x928, IntT15 = 0x930, IntT16 = 0x938, IntT17 = 0x940, IntT18 = 0x948, IntT19 = 0x950, IntT20 = 0x958, IntT21 = 0x960, IntT22 = 0x968, IntNats = 0x970, // Nat bits for r1-r31 // r1-r31 in bits 1 thru 31. Preds = 0x978, // predicates = 0x, preserved BrRp = 0x980, // return pointer = 0x, b0 = 0x, preserved BrS0 = 0x988, // b1-b5 = 0x, preserved BrS1 = 0x990, BrS2 = 0x998, BrS3 = 0x9a0, BrS4 = 0x9a8, BrT0 = 0x9b0, // b6-b7 = 0x, volatile BrT1 = 0x9b8, // This section is specified/returned if the ContextFlags word contains // the flag CONTEXT_CONTROL. // Other application registers ApUNAT = 0x9c0, // User Nat collection register = 0x, preserved ApLC = 0x9c8, // Loop counter register = 0x, preserved ApEC = 0x9d0, // Epilog counter register = 0x, preserved ApCCV = 0x9d8, // CMPXCHG value register = 0x, volatile ApDCR = 0x9e0, // Default control register (TBD) // Register stack info RsPFS = 0x9e8, // Previous function state = 0x, preserved RsBSP = 0x9f0, // Backing store pointer = 0x, preserved RsBSPSTORE = 0x9f8, RsRSC = 0xa00, // RSE configuration = 0x, volatile RsRNAT = 0xa08, // RSE Nat collection register = 0x, preserved // Trap Status Information StIPSR = 0xa10, // Interruption Processor Status StIIP = 0xa18, // Interruption IP StIFS = 0xa20, // Interruption Function State // iA32 related control registers StFCR = 0xa28, // copy of Ar21 Eflag = 0xa30, // Eflag copy of Ar24 SegCSD = 0xa38, // iA32 CSDescriptor (Ar25) SegSSD = 0xa40, // iA32 SSDescriptor (Ar26) Cflag = 0xa48, // Cr0+Cr4 copy of Ar27 StFSR = 0xa50, // x86 FP status (copy of AR28) StFIR = 0xa58, // x86 FP status (copy of AR29) StFDR = 0xa60, // x86 FP status (copy of AR30) UNUSEDPACK = 0xa68, // alignment padding } [Flags] public enum IA64Flags : long { PSR_RI = 41, IA64_BUNDLE_SIZE = 16, SINGLE_STEP_FLAG = 0x1000000000, } [Flags] public enum ARMOffsets : int { ContextFlags = 0x0, // Integer registers Dr0 = 0x4, Dr1 = 0x8, Dr2 = 0xC, Dr3 = 0x10, Dr4 = 0x14, Dr5 = 0x18, Dr6 = 0x1C, Dr7 = 0x20, Dr8 = 0x24, Dr9 = 0x28, Dr10 = 0x2C, Dr11 = 0x30, Dr12 = 0x34, // Control Registers Sp = 0x38, Lr = 0x3C, Pc = 0x40, Cpsr = 0x44, // Floating Point/NEON Registers // Fpscr = 0x48, /* union { M128A Q[16]; --> Quad) 16 items that are 16 byte aligned. Total size is 256 decimal or 100 hex ULONGLONG D[32]; --> Double) 32 items that are 8 bytes in size. Total size is 256 decimal or 100 hex DWORD S[32]; --> Single) 32 items that are 4 bytes in size. Total size is 128 decimal or 80 hex } DUMMYUNIONNAME; // size of the union = largest size which is 256 deciman or 100 hex...From dumping the context in Windbg // it appears that the union is aligned to start at the next 0x10 boundary which is 0x5C which // means the next item will start at 0x15C */ Q = 0x50, D = 0x50, S = 0x50, // // Debug registers // /* // ARM_MAX_BREAKPOINTS = 8 // ARM_MAX_WATCHPOINTS = 1 DWORD Bvr[ARM_MAX_BREAKPOINTS]; DWORD Bcr[ARM_MAX_BREAKPOINTS]; DWORD Wvr[ARM_MAX_WATCHPOINTS]; DWORD Wcr[ARM_MAX_WATCHPOINTS]; */ Bvr = 0x150, Bcr = 0x170, Wvr = 0x190, Wcr = 0x194, } [Flags] public enum ARMFlags : int { // There is no single step flag for arm that is implemented or recognized // on all arm devices. Single stepping was implemented by the CLR team for // managed debuging and this flag is just a place holder SINGLE_STEP_FLAG = 0x000, } [Flags] public enum ImageFileMachine : int { X86 = 0x014c, AMD64 = 0x8664, IA64 = 0x0200, ARM = 0x01c4, // IMAGE_FILE_MACHINE_ARMNT } public enum Platform { None = 0, X86 = 1, AMD64 = 2, IA64 = 3, ARM = 4, } /// <summary> /// Native debug event Codes that are returned through NativeStop event /// </summary> public enum NativeDebugEventCode { None = 0, EXCEPTION_DEBUG_EVENT = 1, CREATE_THREAD_DEBUG_EVENT = 2, CREATE_PROCESS_DEBUG_EVENT = 3, EXIT_THREAD_DEBUG_EVENT = 4, EXIT_PROCESS_DEBUG_EVENT = 5, LOAD_DLL_DEBUG_EVENT = 6, UNLOAD_DLL_DEBUG_EVENT = 7, OUTPUT_DEBUG_STRING_EVENT = 8, RIP_EVENT = 9, } // Debug header for debug events. [StructLayout(LayoutKind.Sequential)] public struct DebugEventHeader { public NativeDebugEventCode dwDebugEventCode; public UInt32 dwProcessId; public UInt32 dwThreadId; }; public enum ThreadAccess : int { None = 0, THREAD_ALL_ACCESS = (0x1F03FF), THREAD_DIRECT_IMPERSONATION = (0x0200), THREAD_GET_CONTEXT = (0x0008), THREAD_IMPERSONATE = (0x0100), THREAD_QUERY_INFORMATION = (0x0040), THREAD_QUERY_LIMITED_INFORMATION = (0x0800), THREAD_SET_CONTEXT = (0x0010), THREAD_SET_INFORMATION = (0x0020), THREAD_SET_LIMITED_INFORMATION = (0x0400), THREAD_SET_THREAD_TOKEN = (0x0080), THREAD_SUSPEND_RESUME = (0x0002), THREAD_TERMINATE = (0x0001), } #region Exception events /// <summary> /// Common Exception codes /// </summary> /// <remarks>Users can define their own exception codes, so the code could be any value. /// The OS reserves bit 28 and may clear that for its own purposes</remarks> public enum ExceptionCode : uint { None = 0x0, // included for completeness sake STATUS_BREAKPOINT = 0x80000003, STATUS_SINGLESTEP = 0x80000004, EXCEPTION_INT_DIVIDE_BY_ZERO = 0xC0000094, /// <summary> /// Fired when debuggee gets a Control-C. /// </summary> DBG_CONTROL_C = 0x40010005, EXCEPTION_STACK_OVERFLOW = 0xC00000FD, EXCEPTION_NONCONTINUABLE_EXCEPTION = 0xC0000025, EXCEPTION_ACCESS_VIOLATION = 0xc0000005, } /// <summary> /// Flags for <see cref="EXCEPTION_RECORD"/> /// </summary> [Flags] public enum ExceptionRecordFlags : uint { /// <summary> /// No flags. /// </summary> None = 0x0, /// <summary> /// Exception can not be continued. Debugging services can still override this to continue the exception, but recommended to warn the user in this case. /// </summary> EXCEPTION_NONCONTINUABLE = 0x1, } /// <summary> /// Information about an exception /// </summary> /// <remarks>This will default to the correct caller's platform</remarks> [StructLayout(LayoutKind.Sequential)] public struct EXCEPTION_RECORD { public ExceptionCode ExceptionCode; public ExceptionRecordFlags ExceptionFlags; /// <summary> /// Based off ExceptionFlags, is the exception Non-continuable? /// </summary> public bool IsNotContinuable { get { return (ExceptionFlags & ExceptionRecordFlags.EXCEPTION_NONCONTINUABLE) != 0; } } public IntPtr ExceptionRecord; /// <summary> /// Address in the debuggee that the exception occured at. /// </summary> public IntPtr ExceptionAddress; /// <summary> /// Number of parameters used in ExceptionInformation array. /// </summary> public UInt32 NumberParameters; private const int EXCEPTION_MAXIMUM_PARAMETERS = 15; // We'd like to marshal this as a ByValArray, but that's not supported yet. // We get an alignment error / TypeLoadException for DebugEventUnion //[MarshalAs(UnmanagedType.ByValArray, SizeConst = EXCEPTION_MAXIMUM_PARAMETERS)] //public IntPtr [] ExceptionInformation; // Instead, mashal manually. public IntPtr ExceptionInformation0; public IntPtr ExceptionInformation1; public IntPtr ExceptionInformation2; public IntPtr ExceptionInformation3; public IntPtr ExceptionInformation4; public IntPtr ExceptionInformation5; public IntPtr ExceptionInformation6; public IntPtr ExceptionInformation7; public IntPtr ExceptionInformation8; public IntPtr ExceptionInformation9; public IntPtr ExceptionInformation10; public IntPtr ExceptionInformation11; public IntPtr ExceptionInformation12; public IntPtr ExceptionInformation13; public IntPtr ExceptionInformation14; } // end of class EXCEPTION_RECORD /// <summary> /// Information about an exception debug event. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct EXCEPTION_DEBUG_INFO { public EXCEPTION_RECORD ExceptionRecord; public UInt32 dwFirstChance; } // end of class EXCEPTION_DEBUG_INFO #endregion // Exception events // MODULEINFO declared in psapi.h [StructLayout(LayoutKind.Sequential)] public struct ModuleInfo { public IntPtr lpBaseOfDll; public uint SizeOfImage; public IntPtr EntryPoint; } [StructLayout(LayoutKind.Sequential)] public struct CREATE_PROCESS_DEBUG_INFO { public IntPtr hFile; public IntPtr hProcess; public IntPtr hThread; public IntPtr lpBaseOfImage; public UInt32 dwDebugInfoFileOffset; public UInt32 nDebugInfoSize; public IntPtr lpThreadLocalBase; public IntPtr lpStartAddress; public IntPtr lpImageName; public UInt16 fUnicode; } // end of class CREATE_PROCESS_DEBUG_INFO [StructLayout(LayoutKind.Sequential)] public struct CREATE_THREAD_DEBUG_INFO { public IntPtr hThread; public IntPtr lpThreadLocalBase; public IntPtr lpStartAddress; } // end of class CREATE_THREAD_DEBUG_INFO [StructLayout(LayoutKind.Sequential)] public struct EXIT_THREAD_DEBUG_INFO { public UInt32 dwExitCode; } // end of class EXIT_THREAD_DEBUG_INFO [StructLayout(LayoutKind.Sequential)] public struct EXIT_PROCESS_DEBUG_INFO { public UInt32 dwExitCode; } // end of class EXIT_PROCESS_DEBUG_INFO [StructLayout(LayoutKind.Sequential)] public struct LOAD_DLL_DEBUG_INFO { public IntPtr hFile; public IntPtr lpBaseOfDll; public UInt32 dwDebugInfoFileOffset; public UInt32 nDebugInfoSize; public IntPtr lpImageName; public UInt16 fUnicode; // Helper to read an IntPtr from the target private IntPtr ReadIntPtrFromTarget(IMemoryReader reader, IntPtr ptr) { // This is not cross-platform: it assumes host and target are the same size. byte[] buffer = new byte[IntPtr.Size]; reader.ReadMemory(ptr, buffer); System.UInt64 val = 0; // Note: this is dependent on endienness. for (int i = buffer.Length - 1; i >= 0; i--) { val <<= 8; val += buffer[i]; } IntPtr newptr = new IntPtr(unchecked((long)val)); return newptr; } /// <summary> /// Read the image name from the target. /// </summary> /// <param name="reader">access to target's memory</param> /// <returns>String for full path to image. Null if name not available</returns> /// <remarks>MSDN says this will never be provided for during Attach scenarios; nor for the first 1 or 2 dlls.</remarks> public string ReadImageNameFromTarget(IMemoryReader reader) { string moduleName; bool bUnicode = (fUnicode != 0); if (lpImageName == IntPtr.Zero) { return null; } else { try { IntPtr newptr = ReadIntPtrFromTarget(reader, lpImageName); if (newptr == IntPtr.Zero) { return null; } else { int charSize = (bUnicode) ? 2 : 1; byte[] buffer = new byte[charSize]; System.Text.StringBuilder sb = new System.Text.StringBuilder(); while (true) { // Read 1 character at a time. This is extremely inefficient, // but we don't know the whole length of the string and it ensures we don't // read off a page. reader.ReadMemory(newptr, buffer); int b; if (bUnicode) { b = (int)buffer[0] + ((int)buffer[1] << 8); } else { b = (int)buffer[0]; } if (b == 0) // string is null-terminated { break; } sb.Append((char)b); newptr = new IntPtr(newptr.ToInt64() + charSize); // move to next character } moduleName = sb.ToString(); } } catch (System.DataMisalignedException) { return null; } catch (InvalidOperationException) // ignore failures to read { return null; } catch (COMException e) { // 0x80131c49 is CORDBG_E_READVIRTUAL_FAILURE, but because of the way MDbg is built I can't // reference Microsoft.Samples.Debugging.CorDebug.HResult.CORDBG_E_READVIRTUAL_FAILURE here. // // On Win8, for some reason the name of the module is not available at the module load debug // event, even though the address is stored by the OS in the DEBUG_EVENT struct. if (e.ErrorCode == unchecked((int)0x80131c49)) { return null; } else { throw; } } } return moduleName; } } // end of class LOAD_DLL_DEBUG_INFO [StructLayout(LayoutKind.Sequential)] public struct UNLOAD_DLL_DEBUG_INFO { public IntPtr lpBaseOfDll; } // end of class UNLOAD_DLL_DEBUG_INFO [StructLayout(LayoutKind.Sequential)] public struct OUTPUT_DEBUG_STRING_INFO { public IntPtr lpDebugStringData; public UInt16 fUnicode; public UInt16 nDebugStringLength; // /// <summary> /// Read the log message from the target. /// </summary> /// <param name="reader">interface to access debuggee memory</param> /// <returns>string containing message or null if not available</returns> public string ReadMessageFromTarget(IMemoryReader reader) { try { bool isUnicode = (fUnicode != 0); int cbCharSize = (isUnicode) ? 2 : 1; byte[] buffer = new byte[nDebugStringLength * cbCharSize]; reader.ReadMemory(lpDebugStringData, buffer); System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int i = 0; i < buffer.Length; i += cbCharSize) { int val; if (isUnicode) { val = (int)buffer[i] + ((int)buffer[i + 1] << 8); } else { val = buffer[i]; } sb.Append((char)val); } return sb.ToString(); } catch (InvalidOperationException) { return null; } } } // end of class OUTPUT_DEBUG_STRING_INFO [StructLayout(LayoutKind.Explicit)] public struct DebugEventUnion { [FieldOffset(0)] public CREATE_PROCESS_DEBUG_INFO CreateProcess; [FieldOffset(0)] public EXCEPTION_DEBUG_INFO Exception; [FieldOffset(0)] public CREATE_THREAD_DEBUG_INFO CreateThread; [FieldOffset(0)] public EXIT_THREAD_DEBUG_INFO ExitThread; [FieldOffset(0)] public EXIT_PROCESS_DEBUG_INFO ExitProcess; [FieldOffset(0)] public LOAD_DLL_DEBUG_INFO LoadDll; [FieldOffset(0)] public UNLOAD_DLL_DEBUG_INFO UnloadDll; [FieldOffset(0)] public OUTPUT_DEBUG_STRING_INFO OutputDebugString; } // 32-bit and 64-bit have sufficiently different alignment that we need // two different debug event structures. /// <summary> /// Matches DEBUG_EVENT layout on 32-bit architecture /// </summary> [StructLayout(LayoutKind.Explicit)] public struct DebugEvent32 { [FieldOffset(0)] public DebugEventHeader header; [FieldOffset(12)] public DebugEventUnion union; } /// <summary> /// Matches DEBUG_EVENT layout on 64-bit architecture /// </summary> [StructLayout(LayoutKind.Explicit)] public struct DebugEvent64 { [FieldOffset(0)] public DebugEventHeader header; [FieldOffset(16)] public DebugEventUnion union; } #endregion Native Structures // SafeHandle to call CloseHandle [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)] public sealed class SafeWin32Handle : SafeHandleZeroOrMinusOneIsInvalid { public SafeWin32Handle() : base(true) { } public SafeWin32Handle(IntPtr handle) : base(true) { SetHandle(handle); } protected override bool ReleaseHandle() { return NativeMethods.CloseHandle(handle); } } // These extend the Mdbg native definitions. public static class NativeMethods { private const string Kernel32LibraryName = "kernel32.dll"; private const string PsapiLibraryName = "psapi.dll"; // // These should be sharable with other pinvokes // [DllImport(Kernel32LibraryName, SetLastError = true, PreserveSig = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool CloseHandle(IntPtr handle); [DllImport(Kernel32LibraryName, SetLastError = true, PreserveSig = true)] public static extern int WaitForSingleObject(IntPtr hHandle, uint dwMilliseconds); [DllImport(Kernel32LibraryName)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetThreadContext(IntPtr hThread, IntPtr lpContext); [DllImport(Kernel32LibraryName)] public static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, uint dwThreadId); [DllImport(Kernel32LibraryName)] public static extern SafeWin32Handle OpenProcess(Int32 dwDesiredAccess, bool bInheritHandle, Int32 dwProcessId); [DllImport(Kernel32LibraryName)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetThreadContext(IntPtr hThread, IntPtr lpContext); // This gets the raw OS thread ID. This is not fiber aware. [DllImport(Kernel32LibraryName)] public static extern int GetCurrentThreadId(); [DllImport(Kernel32LibraryName)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool IsWow64Process(SafeWin32Handle hProcess, ref bool isWow); [Flags] public enum PageProtection : uint { NoAccess = 0x01, Readonly = 0x02, ReadWrite = 0x04, WriteCopy = 0x08, Execute = 0x10, ExecuteRead = 0x20, ExecuteReadWrite = 0x40, ExecuteWriteCopy = 0x80, Guard = 0x100, NoCache = 0x200, WriteCombine = 0x400, } // Call BOOL UnmapViewOfFile(void*) to clean up. [DllImport(Kernel32LibraryName, SetLastError = true)] public static extern SafeMemoryMappedViewHandle MapViewOfFile(SafeMemoryMappedFileHandle hFileMappingObject, uint dwDesiredAccess, uint dwFileOffsetHigh, uint dwFileOffsetLow, IntPtr dwNumberOfBytesToMap); [Flags] public enum LoadLibraryFlags : uint { NoFlags = 0x00000000, DontResolveDllReferences = 0x00000001, LoadIgnoreCodeAuthzLevel = 0x00000010, LoadLibraryAsDatafile = 0x00000002, LoadLibraryAsDatafileExclusive = 0x00000040, LoadLibraryAsImageResource = 0x00000020, LoadWithAlteredSearchPath = 0x00000008 } // SafeHandle to call FreeLibrary [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)] public sealed class SafeLoadLibraryHandle : SafeHandleZeroOrMinusOneIsInvalid { private SafeLoadLibraryHandle() : base(true) { } public SafeLoadLibraryHandle(IntPtr handle) : base(true) { SetHandle(handle); } protected override bool ReleaseHandle() { return FreeLibrary(handle); } // This is technically equivalent to DangerousGetHandle, but it's safer for loaded // libraries where the HMODULE is also the base address the module is loaded at. public IntPtr BaseAddress { get { return handle; } } } [DllImportAttribute(Kernel32LibraryName)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool FreeLibrary(IntPtr hModule); [DllImportAttribute(Kernel32LibraryName)] internal static extern IntPtr LoadLibraryEx(String fileName, int hFile, LoadLibraryFlags dwFlags); // Filesize can be used as a approximation of module size in memory. // In memory size will be larger because of alignment issues. [DllImport(Kernel32LibraryName)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetFileSizeEx(IntPtr hFile, out System.Int64 lpFileSize); // Get the module's size. // This can not be called during the actual dll-load debug event. // (The debug event is sent before the information is initialized) [DllImport(PsapiLibraryName, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetModuleInformation(IntPtr hProcess, IntPtr hModule, out ModuleInfo lpmodinfo, uint countBytes); // Read memory from live, local process. [DllImport(Kernel32LibraryName, SetLastError = true, PreserveSig = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, UIntPtr nSize, out int lpNumberOfBytesRead); // Requires Windows XP / Win2k03 [DllImport(Kernel32LibraryName, SetLastError = true, PreserveSig = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool DebugSetProcessKillOnExit( [MarshalAs(UnmanagedType.Bool)] bool KillOnExit ); // Requires WinXp/Win2k03 [DllImport(Kernel32LibraryName, SetLastError = true, PreserveSig = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool DebugBreakProcess(IntPtr hProcess); [DllImport(Kernel32LibraryName, SetLastError = true, PreserveSig = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetEvent(SafeWin32Handle eventHandle); #region Attach / Detach APIS // constants used in CreateProcess functions public enum CreateProcessFlags { CREATE_NEW_CONSOLE = 0x00000010, // This will include child processes. DEBUG_PROCESS = 1, // This will be just the target process. DEBUG_ONLY_THIS_PROCESS = 2, } [DllImport(Kernel32LibraryName, CharSet = CharSet.Unicode, SetLastError = true, PreserveSig = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool CreateProcess( string lpApplicationName, string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandles, CreateProcessFlags dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, STARTUPINFO lpStartupInfo,// class PROCESS_INFORMATION lpProcessInformation // class ); // Attach to a process [DllImport(Kernel32LibraryName, SetLastError = true, PreserveSig = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool DebugActiveProcess(uint dwProcessId); // Detach from a process // Requires WinXp/Win2k03 [DllImport(Kernel32LibraryName, SetLastError = true, PreserveSig = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool DebugActiveProcessStop(uint dwProcessId); [DllImport(Kernel32LibraryName, SetLastError = true, PreserveSig = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool TerminateProcess(IntPtr hProcess, uint uExitCode); #endregion // Attach / Detach APIS #region Stop-Go APIs // We have two separate versions of kernel32!WaitForDebugEvent to cope with different structure // layout on each platform. [DllImport(Kernel32LibraryName, EntryPoint = "WaitForDebugEvent", SetLastError = true, PreserveSig = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WaitForDebugEvent32(ref DebugEvent32 pDebugEvent, int dwMilliseconds); [DllImport(Kernel32LibraryName, EntryPoint = "WaitForDebugEvent", SetLastError = true, PreserveSig = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WaitForDebugEvent64(ref DebugEvent64 pDebugEvent, int dwMilliseconds); /// <summary> /// Values to pass to ContinueDebugEvent for ContinueStatus /// </summary> public enum ContinueStatus : uint { /// <summary> /// This is our own "empty" value /// </summary> CONTINUED = 0, /// <summary> /// Debugger consumes exceptions. Debuggee will never see the exception. Like "gh" in Windbg. /// </summary> DBG_CONTINUE = 0x00010002, /// <summary> /// Debugger does not interfere with exception processing, this passes the exception onto the debuggee. /// Like "gn" in Windbg. /// </summary> DBG_EXCEPTION_NOT_HANDLED = 0x80010001, } [DllImport(Kernel32LibraryName, SetLastError = true, PreserveSig = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool ContinueDebugEvent(uint dwProcessId, uint dwThreadId, ContinueStatus dwContinueStatus); #endregion // Stop-Go [DllImport("kernel32.dll")] public static extern void GetSystemInfo([MarshalAs(UnmanagedType.Struct)] out SYSTEM_INFO lpSystemInfo); [StructLayout(LayoutKind.Sequential)] public struct SYSTEM_INFO { // Don't marshal dwOemId since that's obsolete and lets // us avoid marshalling a union. internal ProcessorArchitecture wProcessorArchitecture; internal ushort wReserved; public uint dwPageSize; public IntPtr lpMinimumApplicationAddress; public IntPtr lpMaximumApplicationAddress; public IntPtr dwActiveProcessorMask; public uint dwNumberOfProcessors; public uint dwProcessorType; // obsolete public uint dwAllocationGranularity; public ushort dwProcessorLevel; public ushort dwProcessorRevision; } } // NativeMethods }
using System; using System.Collections; namespace Greatbone { /// <summary> /// A JSON array model. /// </summary> public class JArr : ISource, IEnumerable { // array elements JMbr[] elements; int count; int current; public JArr(int capacity = 16) { elements = new JMbr[capacity]; count = 0; current = -1; } public JMbr this[int index] => elements[index]; public int Count => count; /// <summary> /// This add can be used in initialzier /// </summary> /// <param name="elem"></param> internal void Add(JMbr elem) { int len = elements.Length; if (count >= len) { JMbr[] alloc = new JMbr[len * 4]; Array.Copy(elements, 0, alloc, 0, len); elements = alloc; } elements[count++] = elem; } public void Add(JObj elem) { Add(new JMbr(elem)); } public void Add(JArr elem) { Add(new JMbr(elem)); } public void Add(bool elem) { Add(new JMbr(elem)); } public void Add(JNumber elem) { Add(new JMbr(elem)); } public bool Get(string name, ref bool v) { JObj jo = elements[current]; return jo != null && jo.Get(name, ref v); } public bool Get(string name, ref char v) { JObj jo = elements[current]; return jo != null && jo.Get(name, ref v); } public bool Get(string name, ref short v) { JObj jo = elements[current]; return jo != null && jo.Get(name, ref v); } public bool Get(string name, ref int v) { JObj jo = elements[current]; return jo != null && jo.Get(name, ref v); } public bool Get(string name, ref long v) { JObj jo = elements[current]; return jo != null && jo.Get(name, ref v); } public bool Get(string name, ref double v) { JObj jo = elements[current]; return jo != null && jo.Get(name, ref v); } public bool Get(string name, ref decimal v) { JObj jo = elements[current]; return jo != null && jo.Get(name, ref v); } public bool Get(string name, ref DateTime v) { JObj jo = elements[current]; return jo != null && jo.Get(name, ref v); } public bool Get(string name, ref string v) { JObj jo = elements[current]; return jo != null && jo.Get(name, ref v); } public bool Get(string name, ref ArraySegment<byte> v) { JObj jo = elements[current]; return jo != null && jo.Get(name, ref v); } public bool Get(string name, ref byte[] v) { JObj jo = elements[current]; return jo != null && jo.Get(name, ref v); } public bool Get<D>(string name, ref D v, byte proj = 0x0f) where D : IData, new() { JObj jo = elements[current]; return jo != null && jo.Get(name, ref v, proj); } public bool Get(string name, ref short[] v) { JObj jo = elements[current]; return jo != null && jo.Get(name, ref v); } public bool Get(string name, ref int[] v) { JObj jo = elements[current]; return jo != null && jo.Get(name, ref v); } public bool Get(string name, ref long[] v) { JObj jo = elements[current]; return jo != null && jo.Get(name, ref v); } public bool Get(string name, ref string[] v) { JObj jo = elements[current]; return jo != null && jo.Get(name, ref v); } public bool Get(string name, ref JObj v) { throw new NotImplementedException(); } public bool Get(string name, ref JArr v) { throw new NotImplementedException(); } public bool Get<D>(string name, ref D[] v, byte proj = 0x0f) where D : IData, new() { JObj jo = elements[current]; return jo != null && jo.Get(name, ref v); } // // LET // public ISource Let(out bool v) { v = elements[current]; return this; } public ISource Let(out char v) { v = elements[current]; return this; } public ISource Let(out short v) { v = elements[current]; return this; } public ISource Let(out int v) { v = elements[current]; return this; } public ISource Let(out long v) { v = elements[current]; return this; } public ISource Let(out double v) { v = elements[current]; return this; } public ISource Let(out decimal v) { v = elements[current]; return this; } public ISource Let(out DateTime v) { v = elements[current]; return this; } public ISource Let(out string v) { v = elements[current]; return this; } public ISource Let(out ArraySegment<byte> v) { throw new NotImplementedException(); } public ISource Let(out short[] v) { throw new NotImplementedException(); } public ISource Let(out int[] v) { throw new NotImplementedException(); } public ISource Let(out long[] v) { throw new NotImplementedException(); } public ISource Let(out string[] v) { throw new NotImplementedException(); } public ISource Let(out JObj v) { throw new NotImplementedException(); } public ISource Let(out JArr v) { throw new NotImplementedException(); } public ISource Let<D>(out D v, byte proj = 0x0f) where D : IData, new() { throw new NotImplementedException(); } public ISource Let<D>(out D[] v, byte proj = 0x0f) where D : IData, new() { throw new NotImplementedException(); } // // ENTIRITY // public D ToObject<D>(byte proj = 0x0f) where D : IData, new() { D obj = new D(); obj.Read(this, proj); return obj; } public D[] ToArray<D>(byte proj = 0x0f) where D : IData, new() { D[] arr = new D[count]; for (int i = 0; i < arr.Length; i++) { D obj = new D(); obj.Read((JObj) elements[i], proj); arr[i] = obj; } return arr; } public Map<K, D> ToMap<K, D>(byte proj = 0x0f, Func<D, K> keyer = null, Predicate<K> toper = null) where D : IData, new() { Map<K, D> map = new Map<K, D>(); for (int i = 0; i < count; i++) { D obj = new D(); obj.Read((JObj) elements[i], proj); K key = default; if (keyer != null) { key = keyer(obj); } else if (obj is IKeyable<K> mappable) { key = mappable.Key; } map.Add(key, obj); } return map; } public bool DataSet => true; public bool Next() { return ++current < count; } public void Write<C>(C cnt) where C : IContent, ISink { for (int i = 0; i < count; i++) { JMbr e = elements[i]; JType t = e.type; if (t == JType.Array) { cnt.Put(null, (JArr) e); } else if (t == JType.Object) { cnt.Put(null, (JObj) e); } else if (t == JType.String) { cnt.Put(null, (string) e); } else if (t == JType.Number) { cnt.Put(null, (JNumber) e); } else if (t == JType.True) { cnt.Put(null, true); } else if (t == JType.False) { cnt.Put(null, false); } else if (t == JType.Null) { cnt.PutNull(null); } } } public IContent Dump() { var cnt = new JsonContent(true, 4096); cnt.PutFrom(this); return cnt; } public override string ToString() { JsonContent cnt = new JsonContent(false, 4096); try { cnt.PutFrom(this); return cnt.ToString(); } finally { BufferUtility.Return(cnt); } } public IEnumerator GetEnumerator() { throw new NotImplementedException(); } public static implicit operator string[](JArr v) { string[] arr = new string[v.count]; for (int i = 0; i < v.count; i++) { arr[i] = v[i]; } return arr; } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/type.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Protobuf.WellKnownTypes { /// <summary>Holder for reflection information generated from google/protobuf/type.proto</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class TypeReflection { #region Descriptor /// <summary>File descriptor for google/protobuf/type.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static TypeReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Chpnb29nbGUvcHJvdG9idWYvdHlwZS5wcm90bxIPZ29vZ2xlLnByb3RvYnVm", "Ghlnb29nbGUvcHJvdG9idWYvYW55LnByb3RvGiRnb29nbGUvcHJvdG9idWYv", "c291cmNlX2NvbnRleHQucHJvdG8i1wEKBFR5cGUSDAoEbmFtZRgBIAEoCRIm", "CgZmaWVsZHMYAiADKAsyFi5nb29nbGUucHJvdG9idWYuRmllbGQSDgoGb25l", "b2ZzGAMgAygJEigKB29wdGlvbnMYBCADKAsyFy5nb29nbGUucHJvdG9idWYu", "T3B0aW9uEjYKDnNvdXJjZV9jb250ZXh0GAUgASgLMh4uZ29vZ2xlLnByb3Rv", "YnVmLlNvdXJjZUNvbnRleHQSJwoGc3ludGF4GAYgASgOMhcuZ29vZ2xlLnBy", "b3RvYnVmLlN5bnRheCK+BQoFRmllbGQSKQoEa2luZBgBIAEoDjIbLmdvb2ds", "ZS5wcm90b2J1Zi5GaWVsZC5LaW5kEjcKC2NhcmRpbmFsaXR5GAIgASgOMiIu", "Z29vZ2xlLnByb3RvYnVmLkZpZWxkLkNhcmRpbmFsaXR5Eg4KBm51bWJlchgD", "IAEoBRIMCgRuYW1lGAQgASgJEhAKCHR5cGVfdXJsGAYgASgJEhMKC29uZW9m", "X2luZGV4GAcgASgFEg4KBnBhY2tlZBgIIAEoCBIoCgdvcHRpb25zGAkgAygL", "MhcuZ29vZ2xlLnByb3RvYnVmLk9wdGlvbhIRCglqc29uX25hbWUYCiABKAki", "yAIKBEtpbmQSEAoMVFlQRV9VTktOT1dOEAASDwoLVFlQRV9ET1VCTEUQARIO", "CgpUWVBFX0ZMT0FUEAISDgoKVFlQRV9JTlQ2NBADEg8KC1RZUEVfVUlOVDY0", "EAQSDgoKVFlQRV9JTlQzMhAFEhAKDFRZUEVfRklYRUQ2NBAGEhAKDFRZUEVf", "RklYRUQzMhAHEg0KCVRZUEVfQk9PTBAIEg8KC1RZUEVfU1RSSU5HEAkSDgoK", "VFlQRV9HUk9VUBAKEhAKDFRZUEVfTUVTU0FHRRALEg4KClRZUEVfQllURVMQ", "DBIPCgtUWVBFX1VJTlQzMhANEg0KCVRZUEVfRU5VTRAOEhEKDVRZUEVfU0ZJ", "WEVEMzIQDxIRCg1UWVBFX1NGSVhFRDY0EBASDwoLVFlQRV9TSU5UMzIQERIP", "CgtUWVBFX1NJTlQ2NBASInQKC0NhcmRpbmFsaXR5EhcKE0NBUkRJTkFMSVRZ", "X1VOS05PV04QABIYChRDQVJESU5BTElUWV9PUFRJT05BTBABEhgKFENBUkRJ", "TkFMSVRZX1JFUVVJUkVEEAISGAoUQ0FSRElOQUxJVFlfUkVQRUFURUQQAyLO", "AQoERW51bRIMCgRuYW1lGAEgASgJEi0KCWVudW12YWx1ZRgCIAMoCzIaLmdv", "b2dsZS5wcm90b2J1Zi5FbnVtVmFsdWUSKAoHb3B0aW9ucxgDIAMoCzIXLmdv", "b2dsZS5wcm90b2J1Zi5PcHRpb24SNgoOc291cmNlX2NvbnRleHQYBCABKAsy", "Hi5nb29nbGUucHJvdG9idWYuU291cmNlQ29udGV4dBInCgZzeW50YXgYBSAB", "KA4yFy5nb29nbGUucHJvdG9idWYuU3ludGF4IlMKCUVudW1WYWx1ZRIMCgRu", "YW1lGAEgASgJEg4KBm51bWJlchgCIAEoBRIoCgdvcHRpb25zGAMgAygLMhcu", "Z29vZ2xlLnByb3RvYnVmLk9wdGlvbiI7CgZPcHRpb24SDAoEbmFtZRgBIAEo", "CRIjCgV2YWx1ZRgCIAEoCzIULmdvb2dsZS5wcm90b2J1Zi5BbnkqLgoGU3lu", "dGF4EhEKDVNZTlRBWF9QUk9UTzIQABIRCg1TWU5UQVhfUFJPVE8zEAFCTAoT", "Y29tLmdvb2dsZS5wcm90b2J1ZkIJVHlwZVByb3RvUAGgAQGiAgNHUEKqAh5H", "b29nbGUuUHJvdG9idWYuV2VsbEtub3duVHlwZXNiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.AnyReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.SourceContextReflection.Descriptor, }, new pbr::GeneratedCodeInfo(new[] {typeof(global::Google.Protobuf.WellKnownTypes.Syntax), }, new pbr::GeneratedCodeInfo[] { new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Type), global::Google.Protobuf.WellKnownTypes.Type.Parser, new[]{ "Name", "Fields", "Oneofs", "Options", "SourceContext", "Syntax" }, null, null, null), new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Field), global::Google.Protobuf.WellKnownTypes.Field.Parser, new[]{ "Kind", "Cardinality", "Number", "Name", "TypeUrl", "OneofIndex", "Packed", "Options", "JsonName" }, null, new[]{ typeof(global::Google.Protobuf.WellKnownTypes.Field.Types.Kind), typeof(global::Google.Protobuf.WellKnownTypes.Field.Types.Cardinality) }, null), new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Enum), global::Google.Protobuf.WellKnownTypes.Enum.Parser, new[]{ "Name", "Enumvalue", "Options", "SourceContext", "Syntax" }, null, null, null), new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.WellKnownTypes.EnumValue), global::Google.Protobuf.WellKnownTypes.EnumValue.Parser, new[]{ "Name", "Number", "Options" }, null, null, null), new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Option), global::Google.Protobuf.WellKnownTypes.Option.Parser, new[]{ "Name", "Value" }, null, null, null) })); } #endregion } #region Enums /// <summary> /// Syntax specifies the syntax in which a service element was defined. /// </summary> public enum Syntax { /// <summary> /// Syntax "proto2" /// </summary> SYNTAX_PROTO2 = 0, /// <summary> /// Syntax "proto3" /// </summary> SYNTAX_PROTO3 = 1, } #endregion #region Messages /// <summary> /// A light-weight descriptor for a proto message type. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Type : pb::IMessage<Type> { private static readonly pb::MessageParser<Type> _parser = new pb::MessageParser<Type>(() => new Type()); public static pb::MessageParser<Type> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.WellKnownTypes.TypeReflection.Descriptor.MessageTypes[0]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public Type() { OnConstruction(); } partial void OnConstruction(); public Type(Type other) : this() { name_ = other.name_; fields_ = other.fields_.Clone(); oneofs_ = other.oneofs_.Clone(); options_ = other.options_.Clone(); SourceContext = other.sourceContext_ != null ? other.SourceContext.Clone() : null; syntax_ = other.syntax_; } public Type Clone() { return new Type(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// The fully qualified message name. /// </summary> public string Name { get { return name_; } set { name_ = pb::Preconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "fields" field.</summary> public const int FieldsFieldNumber = 2; private static readonly pb::FieldCodec<global::Google.Protobuf.WellKnownTypes.Field> _repeated_fields_codec = pb::FieldCodec.ForMessage(18, global::Google.Protobuf.WellKnownTypes.Field.Parser); private readonly pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Field> fields_ = new pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Field>(); /// <summary> /// The list of fields. /// </summary> public pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Field> Fields { get { return fields_; } } /// <summary>Field number for the "oneofs" field.</summary> public const int OneofsFieldNumber = 3; private static readonly pb::FieldCodec<string> _repeated_oneofs_codec = pb::FieldCodec.ForString(26); private readonly pbc::RepeatedField<string> oneofs_ = new pbc::RepeatedField<string>(); /// <summary> /// The list of oneof definitions. /// </summary> public pbc::RepeatedField<string> Oneofs { get { return oneofs_; } } /// <summary>Field number for the "options" field.</summary> public const int OptionsFieldNumber = 4; private static readonly pb::FieldCodec<global::Google.Protobuf.WellKnownTypes.Option> _repeated_options_codec = pb::FieldCodec.ForMessage(34, global::Google.Protobuf.WellKnownTypes.Option.Parser); private readonly pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Option> options_ = new pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Option>(); /// <summary> /// The proto options. /// </summary> public pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Option> Options { get { return options_; } } /// <summary>Field number for the "source_context" field.</summary> public const int SourceContextFieldNumber = 5; private global::Google.Protobuf.WellKnownTypes.SourceContext sourceContext_; /// <summary> /// The source context. /// </summary> public global::Google.Protobuf.WellKnownTypes.SourceContext SourceContext { get { return sourceContext_; } set { sourceContext_ = value; } } /// <summary>Field number for the "syntax" field.</summary> public const int SyntaxFieldNumber = 6; private global::Google.Protobuf.WellKnownTypes.Syntax syntax_ = global::Google.Protobuf.WellKnownTypes.Syntax.SYNTAX_PROTO2; /// <summary> /// The source syntax. /// </summary> public global::Google.Protobuf.WellKnownTypes.Syntax Syntax { get { return syntax_; } set { syntax_ = value; } } public override bool Equals(object other) { return Equals(other as Type); } public bool Equals(Type other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if(!fields_.Equals(other.fields_)) return false; if(!oneofs_.Equals(other.oneofs_)) return false; if(!options_.Equals(other.options_)) return false; if (!object.Equals(SourceContext, other.SourceContext)) return false; if (Syntax != other.Syntax) return false; return true; } public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); hash ^= fields_.GetHashCode(); hash ^= oneofs_.GetHashCode(); hash ^= options_.GetHashCode(); if (sourceContext_ != null) hash ^= SourceContext.GetHashCode(); if (Syntax != global::Google.Protobuf.WellKnownTypes.Syntax.SYNTAX_PROTO2) hash ^= Syntax.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } fields_.WriteTo(output, _repeated_fields_codec); oneofs_.WriteTo(output, _repeated_oneofs_codec); options_.WriteTo(output, _repeated_options_codec); if (sourceContext_ != null) { output.WriteRawTag(42); output.WriteMessage(SourceContext); } if (Syntax != global::Google.Protobuf.WellKnownTypes.Syntax.SYNTAX_PROTO2) { output.WriteRawTag(48); output.WriteEnum((int) Syntax); } } public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } size += fields_.CalculateSize(_repeated_fields_codec); size += oneofs_.CalculateSize(_repeated_oneofs_codec); size += options_.CalculateSize(_repeated_options_codec); if (sourceContext_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(SourceContext); } if (Syntax != global::Google.Protobuf.WellKnownTypes.Syntax.SYNTAX_PROTO2) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Syntax); } return size; } public void MergeFrom(Type other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } fields_.Add(other.fields_); oneofs_.Add(other.oneofs_); options_.Add(other.options_); if (other.sourceContext_ != null) { if (sourceContext_ == null) { sourceContext_ = new global::Google.Protobuf.WellKnownTypes.SourceContext(); } SourceContext.MergeFrom(other.SourceContext); } if (other.Syntax != global::Google.Protobuf.WellKnownTypes.Syntax.SYNTAX_PROTO2) { Syntax = other.Syntax; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 18: { fields_.AddEntriesFrom(input, _repeated_fields_codec); break; } case 26: { oneofs_.AddEntriesFrom(input, _repeated_oneofs_codec); break; } case 34: { options_.AddEntriesFrom(input, _repeated_options_codec); break; } case 42: { if (sourceContext_ == null) { sourceContext_ = new global::Google.Protobuf.WellKnownTypes.SourceContext(); } input.ReadMessage(sourceContext_); break; } case 48: { syntax_ = (global::Google.Protobuf.WellKnownTypes.Syntax) input.ReadEnum(); break; } } } } } /// <summary> /// Field represents a single field of a message type. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Field : pb::IMessage<Field> { private static readonly pb::MessageParser<Field> _parser = new pb::MessageParser<Field>(() => new Field()); public static pb::MessageParser<Field> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.WellKnownTypes.TypeReflection.Descriptor.MessageTypes[1]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public Field() { OnConstruction(); } partial void OnConstruction(); public Field(Field other) : this() { kind_ = other.kind_; cardinality_ = other.cardinality_; number_ = other.number_; name_ = other.name_; typeUrl_ = other.typeUrl_; oneofIndex_ = other.oneofIndex_; packed_ = other.packed_; options_ = other.options_.Clone(); jsonName_ = other.jsonName_; } public Field Clone() { return new Field(this); } /// <summary>Field number for the "kind" field.</summary> public const int KindFieldNumber = 1; private global::Google.Protobuf.WellKnownTypes.Field.Types.Kind kind_ = global::Google.Protobuf.WellKnownTypes.Field.Types.Kind.TYPE_UNKNOWN; /// <summary> /// The field kind. /// </summary> public global::Google.Protobuf.WellKnownTypes.Field.Types.Kind Kind { get { return kind_; } set { kind_ = value; } } /// <summary>Field number for the "cardinality" field.</summary> public const int CardinalityFieldNumber = 2; private global::Google.Protobuf.WellKnownTypes.Field.Types.Cardinality cardinality_ = global::Google.Protobuf.WellKnownTypes.Field.Types.Cardinality.CARDINALITY_UNKNOWN; /// <summary> /// The field cardinality, i.e. optional/required/repeated. /// </summary> public global::Google.Protobuf.WellKnownTypes.Field.Types.Cardinality Cardinality { get { return cardinality_; } set { cardinality_ = value; } } /// <summary>Field number for the "number" field.</summary> public const int NumberFieldNumber = 3; private int number_; /// <summary> /// The proto field number. /// </summary> public int Number { get { return number_; } set { number_ = value; } } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 4; private string name_ = ""; /// <summary> /// The field name. /// </summary> public string Name { get { return name_; } set { name_ = pb::Preconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "type_url" field.</summary> public const int TypeUrlFieldNumber = 6; private string typeUrl_ = ""; /// <summary> /// The type URL (without the scheme) when the type is MESSAGE or ENUM, /// such as `type.googleapis.com/google.protobuf.Empty`. /// </summary> public string TypeUrl { get { return typeUrl_; } set { typeUrl_ = pb::Preconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "oneof_index" field.</summary> public const int OneofIndexFieldNumber = 7; private int oneofIndex_; /// <summary> /// Index in Type.oneofs. Starts at 1. Zero means no oneof mapping. /// </summary> public int OneofIndex { get { return oneofIndex_; } set { oneofIndex_ = value; } } /// <summary>Field number for the "packed" field.</summary> public const int PackedFieldNumber = 8; private bool packed_; /// <summary> /// Whether to use alternative packed wire representation. /// </summary> public bool Packed { get { return packed_; } set { packed_ = value; } } /// <summary>Field number for the "options" field.</summary> public const int OptionsFieldNumber = 9; private static readonly pb::FieldCodec<global::Google.Protobuf.WellKnownTypes.Option> _repeated_options_codec = pb::FieldCodec.ForMessage(74, global::Google.Protobuf.WellKnownTypes.Option.Parser); private readonly pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Option> options_ = new pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Option>(); /// <summary> /// The proto options. /// </summary> public pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Option> Options { get { return options_; } } /// <summary>Field number for the "json_name" field.</summary> public const int JsonNameFieldNumber = 10; private string jsonName_ = ""; /// <summary> /// The JSON name for this field. /// </summary> public string JsonName { get { return jsonName_; } set { jsonName_ = pb::Preconditions.CheckNotNull(value, "value"); } } public override bool Equals(object other) { return Equals(other as Field); } public bool Equals(Field other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Kind != other.Kind) return false; if (Cardinality != other.Cardinality) return false; if (Number != other.Number) return false; if (Name != other.Name) return false; if (TypeUrl != other.TypeUrl) return false; if (OneofIndex != other.OneofIndex) return false; if (Packed != other.Packed) return false; if(!options_.Equals(other.options_)) return false; if (JsonName != other.JsonName) return false; return true; } public override int GetHashCode() { int hash = 1; if (Kind != global::Google.Protobuf.WellKnownTypes.Field.Types.Kind.TYPE_UNKNOWN) hash ^= Kind.GetHashCode(); if (Cardinality != global::Google.Protobuf.WellKnownTypes.Field.Types.Cardinality.CARDINALITY_UNKNOWN) hash ^= Cardinality.GetHashCode(); if (Number != 0) hash ^= Number.GetHashCode(); if (Name.Length != 0) hash ^= Name.GetHashCode(); if (TypeUrl.Length != 0) hash ^= TypeUrl.GetHashCode(); if (OneofIndex != 0) hash ^= OneofIndex.GetHashCode(); if (Packed != false) hash ^= Packed.GetHashCode(); hash ^= options_.GetHashCode(); if (JsonName.Length != 0) hash ^= JsonName.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { if (Kind != global::Google.Protobuf.WellKnownTypes.Field.Types.Kind.TYPE_UNKNOWN) { output.WriteRawTag(8); output.WriteEnum((int) Kind); } if (Cardinality != global::Google.Protobuf.WellKnownTypes.Field.Types.Cardinality.CARDINALITY_UNKNOWN) { output.WriteRawTag(16); output.WriteEnum((int) Cardinality); } if (Number != 0) { output.WriteRawTag(24); output.WriteInt32(Number); } if (Name.Length != 0) { output.WriteRawTag(34); output.WriteString(Name); } if (TypeUrl.Length != 0) { output.WriteRawTag(50); output.WriteString(TypeUrl); } if (OneofIndex != 0) { output.WriteRawTag(56); output.WriteInt32(OneofIndex); } if (Packed != false) { output.WriteRawTag(64); output.WriteBool(Packed); } options_.WriteTo(output, _repeated_options_codec); if (JsonName.Length != 0) { output.WriteRawTag(82); output.WriteString(JsonName); } } public int CalculateSize() { int size = 0; if (Kind != global::Google.Protobuf.WellKnownTypes.Field.Types.Kind.TYPE_UNKNOWN) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Kind); } if (Cardinality != global::Google.Protobuf.WellKnownTypes.Field.Types.Cardinality.CARDINALITY_UNKNOWN) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Cardinality); } if (Number != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Number); } if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (TypeUrl.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(TypeUrl); } if (OneofIndex != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(OneofIndex); } if (Packed != false) { size += 1 + 1; } size += options_.CalculateSize(_repeated_options_codec); if (JsonName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(JsonName); } return size; } public void MergeFrom(Field other) { if (other == null) { return; } if (other.Kind != global::Google.Protobuf.WellKnownTypes.Field.Types.Kind.TYPE_UNKNOWN) { Kind = other.Kind; } if (other.Cardinality != global::Google.Protobuf.WellKnownTypes.Field.Types.Cardinality.CARDINALITY_UNKNOWN) { Cardinality = other.Cardinality; } if (other.Number != 0) { Number = other.Number; } if (other.Name.Length != 0) { Name = other.Name; } if (other.TypeUrl.Length != 0) { TypeUrl = other.TypeUrl; } if (other.OneofIndex != 0) { OneofIndex = other.OneofIndex; } if (other.Packed != false) { Packed = other.Packed; } options_.Add(other.options_); if (other.JsonName.Length != 0) { JsonName = other.JsonName; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { kind_ = (global::Google.Protobuf.WellKnownTypes.Field.Types.Kind) input.ReadEnum(); break; } case 16: { cardinality_ = (global::Google.Protobuf.WellKnownTypes.Field.Types.Cardinality) input.ReadEnum(); break; } case 24: { Number = input.ReadInt32(); break; } case 34: { Name = input.ReadString(); break; } case 50: { TypeUrl = input.ReadString(); break; } case 56: { OneofIndex = input.ReadInt32(); break; } case 64: { Packed = input.ReadBool(); break; } case 74: { options_.AddEntriesFrom(input, _repeated_options_codec); break; } case 82: { JsonName = input.ReadString(); break; } } } } #region Nested types /// <summary>Container for nested types declared in the Field message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class Types { /// <summary> /// Kind represents a basic field type. /// </summary> public enum Kind { /// <summary> /// Field type unknown. /// </summary> TYPE_UNKNOWN = 0, /// <summary> /// Field type double. /// </summary> TYPE_DOUBLE = 1, /// <summary> /// Field type float. /// </summary> TYPE_FLOAT = 2, /// <summary> /// Field type int64. /// </summary> TYPE_INT64 = 3, /// <summary> /// Field type uint64. /// </summary> TYPE_UINT64 = 4, /// <summary> /// Field type int32. /// </summary> TYPE_INT32 = 5, /// <summary> /// Field type fixed64. /// </summary> TYPE_FIXED64 = 6, /// <summary> /// Field type fixed32. /// </summary> TYPE_FIXED32 = 7, /// <summary> /// Field type bool. /// </summary> TYPE_BOOL = 8, /// <summary> /// Field type string. /// </summary> TYPE_STRING = 9, /// <summary> /// Field type group (deprecated proto2 type) /// </summary> TYPE_GROUP = 10, /// <summary> /// Field type message. /// </summary> TYPE_MESSAGE = 11, /// <summary> /// Field type bytes. /// </summary> TYPE_BYTES = 12, /// <summary> /// Field type uint32. /// </summary> TYPE_UINT32 = 13, /// <summary> /// Field type enum. /// </summary> TYPE_ENUM = 14, /// <summary> /// Field type sfixed32. /// </summary> TYPE_SFIXED32 = 15, /// <summary> /// Field type sfixed64. /// </summary> TYPE_SFIXED64 = 16, /// <summary> /// Field type sint32. /// </summary> TYPE_SINT32 = 17, /// <summary> /// Field type sint64. /// </summary> TYPE_SINT64 = 18, } /// <summary> /// Cardinality represents whether a field is optional, required, or /// repeated. /// </summary> public enum Cardinality { /// <summary> /// The field cardinality is unknown. Typically an error condition. /// </summary> CARDINALITY_UNKNOWN = 0, /// <summary> /// For optional fields. /// </summary> CARDINALITY_OPTIONAL = 1, /// <summary> /// For required fields. Not used for proto3. /// </summary> CARDINALITY_REQUIRED = 2, /// <summary> /// For repeated fields. /// </summary> CARDINALITY_REPEATED = 3, } } #endregion } /// <summary> /// Enum type definition. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Enum : pb::IMessage<Enum> { private static readonly pb::MessageParser<Enum> _parser = new pb::MessageParser<Enum>(() => new Enum()); public static pb::MessageParser<Enum> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.WellKnownTypes.TypeReflection.Descriptor.MessageTypes[2]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public Enum() { OnConstruction(); } partial void OnConstruction(); public Enum(Enum other) : this() { name_ = other.name_; enumvalue_ = other.enumvalue_.Clone(); options_ = other.options_.Clone(); SourceContext = other.sourceContext_ != null ? other.SourceContext.Clone() : null; syntax_ = other.syntax_; } public Enum Clone() { return new Enum(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// Enum type name. /// </summary> public string Name { get { return name_; } set { name_ = pb::Preconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "enumvalue" field.</summary> public const int EnumvalueFieldNumber = 2; private static readonly pb::FieldCodec<global::Google.Protobuf.WellKnownTypes.EnumValue> _repeated_enumvalue_codec = pb::FieldCodec.ForMessage(18, global::Google.Protobuf.WellKnownTypes.EnumValue.Parser); private readonly pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.EnumValue> enumvalue_ = new pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.EnumValue>(); /// <summary> /// Enum value definitions. /// </summary> public pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.EnumValue> Enumvalue { get { return enumvalue_; } } /// <summary>Field number for the "options" field.</summary> public const int OptionsFieldNumber = 3; private static readonly pb::FieldCodec<global::Google.Protobuf.WellKnownTypes.Option> _repeated_options_codec = pb::FieldCodec.ForMessage(26, global::Google.Protobuf.WellKnownTypes.Option.Parser); private readonly pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Option> options_ = new pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Option>(); /// <summary> /// Proto options for the enum type. /// </summary> public pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Option> Options { get { return options_; } } /// <summary>Field number for the "source_context" field.</summary> public const int SourceContextFieldNumber = 4; private global::Google.Protobuf.WellKnownTypes.SourceContext sourceContext_; /// <summary> /// The source context. /// </summary> public global::Google.Protobuf.WellKnownTypes.SourceContext SourceContext { get { return sourceContext_; } set { sourceContext_ = value; } } /// <summary>Field number for the "syntax" field.</summary> public const int SyntaxFieldNumber = 5; private global::Google.Protobuf.WellKnownTypes.Syntax syntax_ = global::Google.Protobuf.WellKnownTypes.Syntax.SYNTAX_PROTO2; /// <summary> /// The source syntax. /// </summary> public global::Google.Protobuf.WellKnownTypes.Syntax Syntax { get { return syntax_; } set { syntax_ = value; } } public override bool Equals(object other) { return Equals(other as Enum); } public bool Equals(Enum other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if(!enumvalue_.Equals(other.enumvalue_)) return false; if(!options_.Equals(other.options_)) return false; if (!object.Equals(SourceContext, other.SourceContext)) return false; if (Syntax != other.Syntax) return false; return true; } public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); hash ^= enumvalue_.GetHashCode(); hash ^= options_.GetHashCode(); if (sourceContext_ != null) hash ^= SourceContext.GetHashCode(); if (Syntax != global::Google.Protobuf.WellKnownTypes.Syntax.SYNTAX_PROTO2) hash ^= Syntax.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } enumvalue_.WriteTo(output, _repeated_enumvalue_codec); options_.WriteTo(output, _repeated_options_codec); if (sourceContext_ != null) { output.WriteRawTag(34); output.WriteMessage(SourceContext); } if (Syntax != global::Google.Protobuf.WellKnownTypes.Syntax.SYNTAX_PROTO2) { output.WriteRawTag(40); output.WriteEnum((int) Syntax); } } public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } size += enumvalue_.CalculateSize(_repeated_enumvalue_codec); size += options_.CalculateSize(_repeated_options_codec); if (sourceContext_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(SourceContext); } if (Syntax != global::Google.Protobuf.WellKnownTypes.Syntax.SYNTAX_PROTO2) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Syntax); } return size; } public void MergeFrom(Enum other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } enumvalue_.Add(other.enumvalue_); options_.Add(other.options_); if (other.sourceContext_ != null) { if (sourceContext_ == null) { sourceContext_ = new global::Google.Protobuf.WellKnownTypes.SourceContext(); } SourceContext.MergeFrom(other.SourceContext); } if (other.Syntax != global::Google.Protobuf.WellKnownTypes.Syntax.SYNTAX_PROTO2) { Syntax = other.Syntax; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 18: { enumvalue_.AddEntriesFrom(input, _repeated_enumvalue_codec); break; } case 26: { options_.AddEntriesFrom(input, _repeated_options_codec); break; } case 34: { if (sourceContext_ == null) { sourceContext_ = new global::Google.Protobuf.WellKnownTypes.SourceContext(); } input.ReadMessage(sourceContext_); break; } case 40: { syntax_ = (global::Google.Protobuf.WellKnownTypes.Syntax) input.ReadEnum(); break; } } } } } /// <summary> /// Enum value definition. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class EnumValue : pb::IMessage<EnumValue> { private static readonly pb::MessageParser<EnumValue> _parser = new pb::MessageParser<EnumValue>(() => new EnumValue()); public static pb::MessageParser<EnumValue> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.WellKnownTypes.TypeReflection.Descriptor.MessageTypes[3]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public EnumValue() { OnConstruction(); } partial void OnConstruction(); public EnumValue(EnumValue other) : this() { name_ = other.name_; number_ = other.number_; options_ = other.options_.Clone(); } public EnumValue Clone() { return new EnumValue(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// Enum value name. /// </summary> public string Name { get { return name_; } set { name_ = pb::Preconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "number" field.</summary> public const int NumberFieldNumber = 2; private int number_; /// <summary> /// Enum value number. /// </summary> public int Number { get { return number_; } set { number_ = value; } } /// <summary>Field number for the "options" field.</summary> public const int OptionsFieldNumber = 3; private static readonly pb::FieldCodec<global::Google.Protobuf.WellKnownTypes.Option> _repeated_options_codec = pb::FieldCodec.ForMessage(26, global::Google.Protobuf.WellKnownTypes.Option.Parser); private readonly pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Option> options_ = new pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Option>(); /// <summary> /// Proto options for the enum value. /// </summary> public pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Option> Options { get { return options_; } } public override bool Equals(object other) { return Equals(other as EnumValue); } public bool Equals(EnumValue other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (Number != other.Number) return false; if(!options_.Equals(other.options_)) return false; return true; } public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (Number != 0) hash ^= Number.GetHashCode(); hash ^= options_.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (Number != 0) { output.WriteRawTag(16); output.WriteInt32(Number); } options_.WriteTo(output, _repeated_options_codec); } public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (Number != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Number); } size += options_.CalculateSize(_repeated_options_codec); return size; } public void MergeFrom(EnumValue other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.Number != 0) { Number = other.Number; } options_.Add(other.options_); } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 16: { Number = input.ReadInt32(); break; } case 26: { options_.AddEntriesFrom(input, _repeated_options_codec); break; } } } } } /// <summary> /// Proto option attached to messages/fields/enums etc. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Option : pb::IMessage<Option> { private static readonly pb::MessageParser<Option> _parser = new pb::MessageParser<Option>(() => new Option()); public static pb::MessageParser<Option> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.WellKnownTypes.TypeReflection.Descriptor.MessageTypes[4]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public Option() { OnConstruction(); } partial void OnConstruction(); public Option(Option other) : this() { name_ = other.name_; Value = other.value_ != null ? other.Value.Clone() : null; } public Option Clone() { return new Option(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// Proto option name. /// </summary> public string Name { get { return name_; } set { name_ = pb::Preconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "value" field.</summary> public const int ValueFieldNumber = 2; private global::Google.Protobuf.WellKnownTypes.Any value_; /// <summary> /// Proto option value. /// </summary> public global::Google.Protobuf.WellKnownTypes.Any Value { get { return value_; } set { value_ = value; } } public override bool Equals(object other) { return Equals(other as Option); } public bool Equals(Option other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (!object.Equals(Value, other.Value)) return false; return true; } public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (value_ != null) hash ^= Value.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (value_ != null) { output.WriteRawTag(18); output.WriteMessage(Value); } } public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (value_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Value); } return size; } public void MergeFrom(Option other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.value_ != null) { if (value_ == null) { value_ = new global::Google.Protobuf.WellKnownTypes.Any(); } Value.MergeFrom(other.Value); } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 18: { if (value_ == null) { value_ = new global::Google.Protobuf.WellKnownTypes.Any(); } input.ReadMessage(value_); break; } } } } } #endregion } #endregion Designer generated code
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.ServiceModel.Channels { using System.Runtime; using System.Threading; enum LifetimeState { Opened, Closing, Closed } class LifetimeManager { #if DEBUG_EXPENSIVE StackTrace closeStack; #endif bool aborted; int busyCount; ICommunicationWaiter busyWaiter; int busyWaiterCount; object mutex; LifetimeState state; public LifetimeManager(object mutex) { this.mutex = mutex; this.state = LifetimeState.Opened; } public int BusyCount { get { return this.busyCount; } } protected LifetimeState State { get { return this.state; } } protected object ThisLock { get { return this.mutex; } } public void Abort() { lock (this.ThisLock) { if (this.State == LifetimeState.Closed || this.aborted) return; #if DEBUG_EXPENSIVE if (closeStack == null) closeStack = new StackTrace(); #endif this.aborted = true; this.state = LifetimeState.Closing; } this.OnAbort(); this.state = LifetimeState.Closed; } void ThrowIfNotOpened() { if (!this.aborted && this.state != LifetimeState.Opened) { #if DEBUG_EXPENSIVE String originalStack = closeStack.ToString().Replace("\r\n", "\r\n "); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(this.GetType().ToString() + ", Object already closed:\r\n " + originalStack)); #else throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(this.GetType().ToString())); #endif } } public IAsyncResult BeginClose(TimeSpan timeout, AsyncCallback callback, object state) { lock (this.ThisLock) { this.ThrowIfNotOpened(); #if DEBUG_EXPENSIVE if (closeStack == null) closeStack = new StackTrace(); #endif this.state = LifetimeState.Closing; } return this.OnBeginClose(timeout, callback, state); } public void Close(TimeSpan timeout) { lock (this.ThisLock) { this.ThrowIfNotOpened(); #if DEBUG_EXPENSIVE if (closeStack == null) closeStack = new StackTrace(); #endif this.state = LifetimeState.Closing; } this.OnClose(timeout); this.state = LifetimeState.Closed; } CommunicationWaitResult CloseCore(TimeSpan timeout, bool aborting) { ICommunicationWaiter busyWaiter = null; CommunicationWaitResult result = CommunicationWaitResult.Succeeded; lock (this.ThisLock) { if (this.busyCount > 0) { if (this.busyWaiter != null) { if (!aborting && this.aborted) return CommunicationWaitResult.Aborted; busyWaiter = this.busyWaiter; } else { busyWaiter = new SyncCommunicationWaiter(this.ThisLock); this.busyWaiter = busyWaiter; } Interlocked.Increment(ref busyWaiterCount); } } if (busyWaiter != null) { result = busyWaiter.Wait(timeout, aborting); if (Interlocked.Decrement(ref busyWaiterCount) == 0) { busyWaiter.Dispose(); this.busyWaiter = null; } } return result; } protected void DecrementBusyCount() { ICommunicationWaiter busyWaiter = null; bool empty = false; lock (this.ThisLock) { if (this.busyCount <= 0) { throw Fx.AssertAndThrow("LifetimeManager.DecrementBusyCount: (this.busyCount > 0)"); } if (--this.busyCount == 0) { if (this.busyWaiter != null) { busyWaiter = this.busyWaiter; Interlocked.Increment(ref this.busyWaiterCount); } empty = true; } } if (busyWaiter != null) { busyWaiter.Signal(); if (Interlocked.Decrement(ref this.busyWaiterCount) == 0) { busyWaiter.Dispose(); this.busyWaiter = null; } } if (empty && this.State == LifetimeState.Opened) OnEmpty(); } public void EndClose(IAsyncResult result) { this.OnEndClose(result); this.state = LifetimeState.Closed; } protected virtual void IncrementBusyCount() { lock (this.ThisLock) { Fx.Assert(this.State == LifetimeState.Opened, "LifetimeManager.IncrementBusyCount: (this.State == LifetimeState.Opened)"); this.busyCount++; } } protected virtual void IncrementBusyCountWithoutLock() { Fx.Assert(this.State == LifetimeState.Opened, "LifetimeManager.IncrementBusyCountWithoutLock: (this.State == LifetimeState.Opened)"); this.busyCount++; } protected virtual void OnAbort() { // We have decided not to make this configurable CloseCore(TimeSpan.FromSeconds(1), true); } protected virtual IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { CloseCommunicationAsyncResult closeResult = null; lock (this.ThisLock) { if (this.busyCount > 0) { if (this.busyWaiter != null) { Fx.Assert(this.aborted, "LifetimeManager.OnBeginClose: (this.aborted == true)"); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(this.GetType().ToString())); } else { closeResult = new CloseCommunicationAsyncResult(timeout, callback, state, this.ThisLock); Fx.Assert(this.busyWaiter == null, "LifetimeManager.OnBeginClose: (this.busyWaiter == null)"); this.busyWaiter = closeResult; Interlocked.Increment(ref this.busyWaiterCount); } } } if (closeResult != null) { return closeResult; } else { return new CompletedAsyncResult(callback, state); } } protected virtual void OnClose(TimeSpan timeout) { switch (CloseCore(timeout, false)) { case CommunicationWaitResult.Expired: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(SR.GetString(SR.SFxCloseTimedOut1, timeout))); case CommunicationWaitResult.Aborted: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(this.GetType().ToString())); } } protected virtual void OnEmpty() { } protected virtual void OnEndClose(IAsyncResult result) { if (result is CloseCommunicationAsyncResult) { CloseCommunicationAsyncResult.End(result); if (Interlocked.Decrement(ref this.busyWaiterCount) == 0) { this.busyWaiter.Dispose(); this.busyWaiter = null; } } else CompletedAsyncResult.End(result); } } enum CommunicationWaitResult { Waiting, Succeeded, Expired, Aborted } interface ICommunicationWaiter : IDisposable { void Signal(); CommunicationWaitResult Wait(TimeSpan timeout, bool aborting); } class CloseCommunicationAsyncResult : AsyncResult, ICommunicationWaiter { object mutex; CommunicationWaitResult result; IOThreadTimer timer; TimeoutHelper timeoutHelper; TimeSpan timeout; public CloseCommunicationAsyncResult(TimeSpan timeout, AsyncCallback callback, object state, object mutex) : base(callback, state) { this.timeout = timeout; this.timeoutHelper = new TimeoutHelper(timeout); this.mutex = mutex; if (timeout < TimeSpan.Zero) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(SR.GetString(SR.SFxCloseTimedOut1, timeout))); this.timer = new IOThreadTimer(new Action<object>(TimeoutCallback), this, true); this.timer.Set(timeout); } object ThisLock { get { return mutex; } } public void Dispose() { } public static void End(IAsyncResult result) { AsyncResult.End<CloseCommunicationAsyncResult>(result); } public void Signal() { lock (this.ThisLock) { if (this.result != CommunicationWaitResult.Waiting) return; this.result = CommunicationWaitResult.Succeeded; } this.timer.Cancel(); this.Complete(false); } void Timeout() { lock (this.ThisLock) { if (this.result != CommunicationWaitResult.Waiting) return; this.result = CommunicationWaitResult.Expired; } this.Complete(false, new TimeoutException(SR.GetString(SR.SFxCloseTimedOut1, this.timeout))); } static void TimeoutCallback(object state) { CloseCommunicationAsyncResult closeResult = (CloseCommunicationAsyncResult)state; closeResult.Timeout(); } public CommunicationWaitResult Wait(TimeSpan timeout, bool aborting) { if (timeout < TimeSpan.Zero) { return CommunicationWaitResult.Expired; } // Synchronous Wait on AsyncResult should only be called in Abort code-path Fx.Assert(aborting, "CloseCommunicationAsyncResult.Wait: (aborting == true)"); lock (this.ThisLock) { if (this.result != CommunicationWaitResult.Waiting) { return this.result; } this.result = CommunicationWaitResult.Aborted; } this.timer.Cancel(); TimeoutHelper.WaitOne(this.AsyncWaitHandle, timeout); this.Complete(false, new ObjectDisposedException(this.GetType().ToString())); return this.result; } } internal class SyncCommunicationWaiter : ICommunicationWaiter { bool closed; object mutex; CommunicationWaitResult result; ManualResetEvent waitHandle; public SyncCommunicationWaiter(object mutex) { this.mutex = mutex; this.waitHandle = new ManualResetEvent(false); } object ThisLock { get { return this.mutex; } } public void Dispose() { lock (this.ThisLock) { if (this.closed) return; this.closed = true; this.waitHandle.Close(); } } public void Signal() { lock (this.ThisLock) { if (this.closed) return; this.waitHandle.Set(); } } public CommunicationWaitResult Wait(TimeSpan timeout, bool aborting) { if (this.closed) { return CommunicationWaitResult.Aborted; } if (timeout < TimeSpan.Zero) { return CommunicationWaitResult.Expired; } if (aborting) { this.result = CommunicationWaitResult.Aborted; } bool expired = !TimeoutHelper.WaitOne(this.waitHandle, timeout); lock (this.ThisLock) { if (this.result == CommunicationWaitResult.Waiting) { this.result = (expired ? CommunicationWaitResult.Expired : CommunicationWaitResult.Succeeded); } } lock (this.ThisLock) { if (!this.closed) this.waitHandle.Set(); // unblock other waiters if there are any } return this.result; } } }
//------------------------------------------------------------------------------ // <copyright file="StringUtil.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* * StringUtil class * * Copyright (c) 1999 Microsoft Corporation */ namespace System.Web.Util { using System.Text; using System.Globalization; using System.Runtime.InteropServices; using System.Web.Hosting; /* * Various string handling utilities */ internal static class StringUtil { internal static string CheckAndTrimString(string paramValue, string paramName) { return CheckAndTrimString(paramValue, paramName, true); } internal static string CheckAndTrimString(string paramValue, string paramName, bool throwIfNull) { return CheckAndTrimString(paramValue, paramName, throwIfNull, -1); } internal static string CheckAndTrimString(string paramValue, string paramName, bool throwIfNull, int lengthToCheck) { if (paramValue == null) { if (throwIfNull) { throw new ArgumentNullException(paramName); } return null; } string trimmedValue = paramValue.Trim(); if (trimmedValue.Length == 0) { throw new ArgumentException( SR.GetString(SR.PersonalizationProviderHelper_TrimmedEmptyString, paramName)); } if (lengthToCheck > -1 && trimmedValue.Length > lengthToCheck) { throw new ArgumentException( SR.GetString(SR.StringUtil_Trimmed_String_Exceed_Maximum_Length, paramValue, paramName, lengthToCheck.ToString(CultureInfo.InvariantCulture))); } return trimmedValue; } internal static bool Equals(string s1, string s2) { if (s1 == s2) { return true; } if (String.IsNullOrEmpty(s1) && String.IsNullOrEmpty(s2)) { return true; } return false; } unsafe internal static bool Equals(string s1, int offset1, string s2, int offset2, int length) { if (offset1 < 0) throw new ArgumentOutOfRangeException("offset1"); if (offset2 < 0) throw new ArgumentOutOfRangeException("offset2"); if (length < 0) throw new ArgumentOutOfRangeException("length"); if ((s1 == null ? 0 : s1.Length) - offset1 < length) throw new ArgumentOutOfRangeException(SR.GetString(SR.InvalidOffsetOrCount, "offset1", "length")); if ((s2 == null ? 0 : s2.Length) - offset2 < length) throw new ArgumentOutOfRangeException(SR.GetString(SR.InvalidOffsetOrCount, "offset2", "length")); if (String.IsNullOrEmpty(s1) || String.IsNullOrEmpty(s2)) return true; fixed (char * pch1 = s1, pch2 = s2) { char * p1 = pch1 + offset1, p2 = pch2 + offset2; int c = length; while (c-- > 0) { if (*p1++ != *p2++) return false; } } return true; } internal static bool EqualsIgnoreCase(string s1, string s2) { if (String.IsNullOrEmpty(s1) && String.IsNullOrEmpty(s2)) { return true; } if (String.IsNullOrEmpty(s1) || String.IsNullOrEmpty(s2)) { return false; } if(s2.Length != s1.Length) { return false; } return 0 == string.Compare(s1, 0, s2, 0, s2.Length, StringComparison.OrdinalIgnoreCase); } internal static bool EqualsIgnoreCase(string s1, int index1, string s2, int index2, int length) { return String.Compare(s1, index1, s2, index2, length, StringComparison.OrdinalIgnoreCase) == 0; } internal static string StringFromWCharPtr(IntPtr ip, int length) { unsafe { return new string((char *) ip, 0, length); } } internal static string StringFromCharPtr(IntPtr ip, int length) { return Marshal.PtrToStringAnsi(ip, length); } /* * Determines if the string ends with the specified character. * Fast, non-culture aware. */ internal static bool StringEndsWith(string s, char c) { int len = s.Length; return len != 0 && s[len - 1] == c; } /* * Determines if the first string ends with the second string. * Fast, non-culture aware. */ unsafe internal static bool StringEndsWith(string s1, string s2) { int offset = s1.Length - s2.Length; if (offset < 0) { return false; } fixed (char * pch1=s1, pch2=s2) { char * p1 = pch1 + offset, p2=pch2; int c = s2.Length; while (c-- > 0) { if (*p1++ != *p2++) return false; } } return true; } /* * Determines if the first string ends with the second string, ignoring case. * Fast, non-culture aware. */ internal static bool StringEndsWithIgnoreCase(string s1, string s2) { int offset = s1.Length - s2.Length; if (offset < 0) { return false; } return 0 == string.Compare(s1, offset, s2, 0, s2.Length, StringComparison.OrdinalIgnoreCase); } /* * Determines if the string starts with the specified character. * Fast, non-culture aware. */ internal static bool StringStartsWith(string s, char c) { return s.Length != 0 && (s[0] == c); } /* * Determines if the first string starts with the second string. * Fast, non-culture aware. */ unsafe internal static bool StringStartsWith(string s1, string s2) { if (s2.Length > s1.Length) { return false; } fixed (char * pch1=s1, pch2=s2) { char * p1 = pch1, p2=pch2; int c = s2.Length; while (c-- > 0) { if (*p1++ != *p2++) return false; } } return true; } /* * Determines if the first string starts with the second string, ignoring case. * Fast, non-culture aware. */ internal static bool StringStartsWithIgnoreCase(string s1, string s2) { if (String.IsNullOrEmpty(s1) || String.IsNullOrEmpty(s2)) { return false; } if (s2.Length > s1.Length) { return false; } return 0 == string.Compare(s1, 0, s2, 0, s2.Length, StringComparison.OrdinalIgnoreCase); } internal unsafe static void UnsafeStringCopy(string src, int srcIndex, char[] dest, int destIndex, int len) { // We do not verify the parameters in this function, as the callers are assumed // to have done so. This is important for users such as HttpWriter that already // do the argument checking, and are called several times per request. Debug.Assert(len >= 0, "len >= 0"); Debug.Assert(src != null, "src != null"); Debug.Assert(srcIndex >= 0, "srcIndex >= 0"); Debug.Assert(srcIndex + len <= src.Length, "src"); Debug.Assert(dest != null, "dest != null"); Debug.Assert(destIndex >= 0, "destIndex >= 0"); Debug.Assert(destIndex + len <= dest.Length, "dest"); int cb = len * sizeof(char); fixed (char * pchSrc = src, pchDest = dest) { byte* pbSrc = (byte *) (pchSrc + srcIndex); byte* pbDest = (byte*) (pchDest + destIndex); memcpyimpl(pbSrc, pbDest, cb); } } internal static bool StringArrayEquals(string[] a, string [] b) { if ((a == null) != (b == null)) { return false; } if (a == null) { return true; } int n = a.Length; if (n != b.Length) { return false; } for (int i = 0; i < n; i++) { if (a[i] != b[i]) { return false; } } return true; } // This is copied from String.GetHashCode. We want our own copy, because the result of // String.GetHashCode is not guaranteed to be the same from build to build. But we want a // stable hash, since we persist things to disk (e.g. precomp scenario). VSWhidbey 399279. internal static int GetStringHashCode(string s) { unsafe { fixed (char* src = s) { int hash1 = (5381 << 16) + 5381; int hash2 = hash1; // 32bit machines. int* pint = (int*)src; int len = s.Length; while (len > 0) { hash1 = ((hash1 << 5) + hash1 + (hash1 >> 27)) ^ pint[0]; if (len <= 2) { break; } hash2 = ((hash2 << 5) + hash2 + (hash2 >> 27)) ^ pint[1]; pint += 2; len -= 4; } return hash1 + (hash2 * 1566083941); } } } internal static int GetNonRandomizedHashCode(string s, bool ignoreCase = false) { // Preserve the default behavior when string hash randomization is off if (!AppSettings.UseRandomizedStringHashAlgorithm) { return ignoreCase ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(s) : s.GetHashCode(); } if (ignoreCase) { s = s.ToLower(CultureInfo.InvariantCulture); } // Use our stable hash algorithm implementation return GetStringHashCode(s); } // Need StringComparer implementation. It's very expensive to port the actual BCL code here // Instead use the default AppDomain, because it doesn't have string hash randomization enabled. // Marshal the call to reuse the default StringComparer behavior. // PERF isn't optimal, so apply consideration! internal static int GetNonRandomizedStringComparerHashCode(string s) { // Preserve the default behavior when string hash randomization is off if (!AppSettings.UseRandomizedStringHashAlgorithm) { return StringComparer.InvariantCultureIgnoreCase.GetHashCode(s); } ApplicationManager appManager = HostingEnvironment.GetApplicationManager(); if (appManager != null) { // Cross AppDomain call may cause marshaling of IPrincipal to fail. So strip out the exectuion context int hashCode = 0; ExecutionContextUtil.RunInNullExecutionContext(delegate { hashCode = appManager.GetNonRandomizedStringComparerHashCode(s, ignoreCase:true); }); return hashCode; } // Fall back to non-compat result return GetStringHashCode(s.ToLower(CultureInfo.InvariantCulture)); } internal static int GetNullTerminatedByteArray(Encoding enc, string s, out byte[] bytes) { bytes = null; if (s == null) return 0; // Encoding.GetMaxByteCount is faster than GetByteCount, but will probably allocate more // memory than needed. Working with small short-lived strings here, so that's probably ok. bytes = new byte[enc.GetMaxByteCount(s.Length) + 1]; return enc.GetBytes(s, 0, s.Length, bytes, 0); } internal unsafe static void memcpyimpl(byte* src, byte* dest, int len) { Debug.Assert(len >= 0, "Negative length in memcpyimpl!"); #if FEATURE_PAL // Portable naive implementation while (len-- > 0) *dest++ = *src++; #else #if IA64 long dstAlign = (7 & (8 - (((long)dest) & 7))); // number of bytes to copy before dest is 8-byte aligned while ((dstAlign > 0) && (len > 0)) { // < *dest++ = *src++; len--; dstAlign--; } if (len > 0) { long srcAlign = 8 - (((long)src) & 7); if (srcAlign != 8) { if (4 == srcAlign) { while (len >= 4) { ((int*)dest)[0] = ((int*)src)[0]; dest += 4; src += 4; len -= 4; } srcAlign = 2; // fall through to 2-byte copies } if ((2 == srcAlign) || (6 == srcAlign)) { while (len >= 2) { ((short*)dest)[0] = ((short*)src)[0]; dest += 2; src += 2; len -= 2; } } while (len-- > 0) { *dest++ = *src++; } } else { if (len >= 16) { do { ((long*)dest)[0] = ((long*)src)[0]; ((long*)dest)[1] = ((long*)src)[1]; dest += 16; src += 16; } while ((len -= 16) >= 16); } if(len > 0) // protection against negative len and optimization for len==16*N { if ((len & 8) != 0) { ((long*)dest)[0] = ((long*)src)[0]; dest += 8; src += 8; } if ((len & 4) != 0) { ((int*)dest)[0] = ((int*)src)[0]; dest += 4; src += 4; } if ((len & 2) != 0) { ((short*)dest)[0] = ((short*)src)[0]; dest += 2; src += 2; } if ((len & 1) != 0) { *dest++ = *src++; } } } } #else // <STRIP>This is Peter Sollich's faster memcpy implementation, from // COMString.cpp. For our strings, this beat the processor's // repeat & move single byte instruction, which memcpy expands into. // (You read that correctly.) // This is 3x faster than a simple while loop copying byte by byte, // for large copies.</STRIP> if (len >= 16) { do { #if AMD64 ((long*)dest)[0] = ((long*)src)[0]; ((long*)dest)[1] = ((long*)src)[1]; #else ((int*)dest)[0] = ((int*)src)[0]; ((int*)dest)[1] = ((int*)src)[1]; ((int*)dest)[2] = ((int*)src)[2]; ((int*)dest)[3] = ((int*)src)[3]; #endif dest += 16; src += 16; } while ((len -= 16) >= 16); } if(len > 0) // protection against negative len and optimization for len==16*N { if ((len & 8) != 0) { #if AMD64 ((long*)dest)[0] = ((long*)src)[0]; #else ((int*)dest)[0] = ((int*)src)[0]; ((int*)dest)[1] = ((int*)src)[1]; #endif dest += 8; src += 8; } if ((len & 4) != 0) { ((int*)dest)[0] = ((int*)src)[0]; dest += 4; src += 4; } if ((len & 2) != 0) { ((short*)dest)[0] = ((short*)src)[0]; dest += 2; src += 2; } if ((len & 1) != 0) *dest++ = *src++; } #endif #endif // FEATURE_PAL } internal static string[] ObjectArrayToStringArray(object[] objectArray) { String[] stringKeys = new String[objectArray.Length]; objectArray.CopyTo(stringKeys, 0); return stringKeys; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading; using System.Threading.Tasks; using Abp.Authorization.Users; using Abp.Dependency; using Abp.Domain.Repositories; using Abp.Domain.Uow; using Abp.Extensions; using Abp.Zero; using Castle.Core.Logging; using JetBrains.Annotations; using Microsoft.AspNetCore.Identity; namespace Abp.Authorization.Roles { /// <summary> /// Creates a new instance of a persistence store for roles. /// </summary> public class AbpRoleStore<TRole, TUser> : IRoleStore<TRole>, IRoleClaimStore<TRole>, IRolePermissionStore<TRole>, IQueryableRoleStore<TRole>, ITransientDependency where TRole : AbpRole<TUser> where TUser : AbpUser<TUser> { public ILogger Logger { get; set; } /// <summary> /// Gets or sets the <see cref="IdentityErrorDescriber"/> for any error that occurred with the current operation. /// </summary> public IdentityErrorDescriber ErrorDescriber { get; set; } /// <summary> /// Gets or sets a flag indicating if changes should be persisted after CreateAsync, UpdateAsync and DeleteAsync are called. /// </summary> /// <value> /// True if changes should be automatically persisted, otherwise false. /// </value> public bool AutoSaveChanges { get; set; } = true; public IQueryable<TRole> Roles => _roleRepository.GetAll(); private readonly IRepository<TRole> _roleRepository; private readonly IUnitOfWorkManager _unitOfWorkManager; private readonly IRepository<RolePermissionSetting, long> _rolePermissionSettingRepository; public AbpRoleStore( IUnitOfWorkManager unitOfWorkManager, IRepository<TRole> roleRepository, IRepository<RolePermissionSetting, long> rolePermissionSettingRepository) { _unitOfWorkManager = unitOfWorkManager; _roleRepository = roleRepository; _rolePermissionSettingRepository = rolePermissionSettingRepository; ErrorDescriber = new IdentityErrorDescriber(); Logger = NullLogger.Instance; } /// <summary>Saves the current store.</summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> protected Task SaveChanges(CancellationToken cancellationToken) { if (!AutoSaveChanges || _unitOfWorkManager.Current == null) { return Task.CompletedTask; } return _unitOfWorkManager.Current.SaveChangesAsync(); } /// <summary> /// Creates a new role in a store as an asynchronous operation. /// </summary> /// <param name="role">The role to create in the store.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that represents the <see cref="IdentityResult"/> of the asynchronous query.</returns> public virtual async Task<IdentityResult> CreateAsync([NotNull] TRole role, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(role, nameof(role)); await _roleRepository.InsertAsync(role); await SaveChanges(cancellationToken); return IdentityResult.Success; } /// <summary> /// Updates a role in a store as an asynchronous operation. /// </summary> /// <param name="role">The role to update in the store.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that represents the <see cref="IdentityResult"/> of the asynchronous query.</returns> public virtual async Task<IdentityResult> UpdateAsync([NotNull] TRole role, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(role, nameof(role)); role.ConcurrencyStamp = Guid.NewGuid().ToString(); await _roleRepository.UpdateAsync(role); try { await SaveChanges(cancellationToken); } catch (AbpDbConcurrencyException ex) { Logger.Warn(ex.ToString(), ex); return IdentityResult.Failed(ErrorDescriber.ConcurrencyFailure()); } await SaveChanges(cancellationToken); return IdentityResult.Success; } /// <summary> /// Deletes a role from the store as an asynchronous operation. /// </summary> /// <param name="role">The role to delete from the store.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that represents the <see cref="IdentityResult"/> of the asynchronous query.</returns> public virtual async Task<IdentityResult> DeleteAsync([NotNull] TRole role, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(role, nameof(role)); await _roleRepository.DeleteAsync(role); try { await SaveChanges(cancellationToken); } catch (AbpDbConcurrencyException ex) { Logger.Warn(ex.ToString(), ex); return IdentityResult.Failed(ErrorDescriber.ConcurrencyFailure()); } await SaveChanges(cancellationToken); return IdentityResult.Success; } /// <summary> /// Gets the ID for a role from the store as an asynchronous operation. /// </summary> /// <param name="role">The role whose ID should be returned.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that contains the ID of the role.</returns> public Task<string> GetRoleIdAsync([NotNull] TRole role, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(role, nameof(role)); return Task.FromResult(role.Id.ToString()); } /// <summary> /// Gets the name of a role from the store as an asynchronous operation. /// </summary> /// <param name="role">The role whose name should be returned.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that contains the name of the role.</returns> public Task<string> GetRoleNameAsync([NotNull] TRole role, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(role, nameof(role)); return Task.FromResult(role.Name); } /// <summary> /// Sets the name of a role in the store as an asynchronous operation. /// </summary> /// <param name="role">The role whose name should be set.</param> /// <param name="roleName">The name of the role.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public Task SetRoleNameAsync([NotNull] TRole role, string roleName, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(role, nameof(role)); role.Name = roleName; return Task.CompletedTask; } /// <summary> /// Finds the role who has the specified ID as an asynchronous operation. /// </summary> /// <param name="id">The role ID to look for.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that result of the look up.</returns> public virtual Task<TRole> FindByIdAsync(string id, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); return _roleRepository.GetAsync(id.To<int>()); } /// <summary> /// Finds the role who has the specified normalized name as an asynchronous operation. /// </summary> /// <param name="normalizedName">The normalized role name to look for.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that result of the look up.</returns> public virtual Task<TRole> FindByNameAsync([NotNull] string normalizedName, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(normalizedName, nameof(normalizedName)); return _roleRepository.FirstOrDefaultAsync(r => r.NormalizedName == normalizedName); } /// <summary> /// Get a role's normalized name as an asynchronous operation. /// </summary> /// <param name="role">The role whose normalized name should be retrieved.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that contains the name of the role.</returns> public virtual Task<string> GetNormalizedRoleNameAsync([NotNull] TRole role, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(role, nameof(role)); return Task.FromResult(role.NormalizedName); } /// <summary> /// Set a role's normalized name as an asynchronous operation. /// </summary> /// <param name="role">The role whose normalized name should be set.</param> /// <param name="normalizedName">The normalized name to set</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public virtual Task SetNormalizedRoleNameAsync([NotNull] TRole role, string normalizedName, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(role, nameof(role)); role.NormalizedName = normalizedName; return Task.CompletedTask; } /// <summary> /// Dispose the stores /// </summary> public void Dispose() { } /// <summary> /// Get the claims associated with the specified <paramref name="role"/> as an asynchronous operation. /// </summary> /// <param name="role">The role whose claims should be retrieved.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that contains the claims granted to a role.</returns> public virtual async Task<IList<Claim>> GetClaimsAsync([NotNull] TRole role, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(role, nameof(role)); await _roleRepository.EnsureCollectionLoadedAsync(role, u => u.Claims, cancellationToken); return role.Claims.Select(c => new Claim(c.ClaimType, c.ClaimValue)).ToList(); } /// <summary> /// Adds the <paramref name="claim"/> given to the specified <paramref name="role"/>. /// </summary> /// <param name="role">The role to add the claim to.</param> /// <param name="claim">The claim to add to the role.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public async Task AddClaimAsync([NotNull] TRole role, [NotNull] Claim claim, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); Check.NotNull(role, nameof(role)); Check.NotNull(claim, nameof(claim)); await _roleRepository.EnsureCollectionLoadedAsync(role, u => u.Claims, cancellationToken); role.Claims.Add(new RoleClaim(role, claim)); } /// <summary> /// Removes the <paramref name="claim"/> given from the specified <paramref name="role"/>. /// </summary> /// <param name="role">The role to remove the claim from.</param> /// <param name="claim">The claim to remove from the role.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public async Task RemoveClaimAsync([NotNull] TRole role, [NotNull] Claim claim, CancellationToken cancellationToken = default(CancellationToken)) { Check.NotNull(role, nameof(role)); Check.NotNull(claim, nameof(claim)); await _roleRepository.EnsureCollectionLoadedAsync(role, u => u.Claims, cancellationToken); role.Claims.RemoveAll(c => c.ClaimValue == claim.Value && c.ClaimType == claim.Type); } public virtual async Task<TRole> FindByDisplayNameAsync(string displayName) { return await _roleRepository.FirstOrDefaultAsync( role => role.DisplayName == displayName ); } public virtual async Task AddPermissionAsync(TRole role, PermissionGrantInfo permissionGrant) { if (await HasPermissionAsync(role.Id, permissionGrant)) { return; } await _rolePermissionSettingRepository.InsertAsync( new RolePermissionSetting { TenantId = role.TenantId, RoleId = role.Id, Name = permissionGrant.Name, IsGranted = permissionGrant.IsGranted }); } /// <inheritdoc/> public virtual async Task RemovePermissionAsync(TRole role, PermissionGrantInfo permissionGrant) { await _rolePermissionSettingRepository.DeleteAsync( permissionSetting => permissionSetting.RoleId == role.Id && permissionSetting.Name == permissionGrant.Name && permissionSetting.IsGranted == permissionGrant.IsGranted ); } /// <inheritdoc/> public virtual Task<IList<PermissionGrantInfo>> GetPermissionsAsync(TRole role) { return GetPermissionsAsync(role.Id); } public async Task<IList<PermissionGrantInfo>> GetPermissionsAsync(int roleId) { return (await _rolePermissionSettingRepository.GetAllListAsync(p => p.RoleId == roleId)) .Select(p => new PermissionGrantInfo(p.Name, p.IsGranted)) .ToList(); } /// <inheritdoc/> public virtual async Task<bool> HasPermissionAsync(int roleId, PermissionGrantInfo permissionGrant) { return await _rolePermissionSettingRepository.FirstOrDefaultAsync( p => p.RoleId == roleId && p.Name == permissionGrant.Name && p.IsGranted == permissionGrant.IsGranted ) != null; } /// <inheritdoc/> public virtual async Task RemoveAllPermissionSettingsAsync(TRole role) { await _rolePermissionSettingRepository.DeleteAsync(s => s.RoleId == role.Id); } } }
using System; using System.Diagnostics; using System.Collections.Generic; using System.Drawing; using Microsoft.DirectX; using Microsoft.DirectX.Direct3D; namespace Simbiosis { /// <summary> /// A 3D sphere for debugging /// </summary> public class Marker { //---------- STATIC MEMBERS = list of markers ------------- private static List<Marker> list = new List<Marker>(); public enum Type { Sphere, Cone }; /// <summary> /// Create a new SPHERE marker /// </summary> /// <param name="color">ARGB value (use A for transparency)</param> /// <param name="posn">World coordinates for position</param> /// <param name="radius">Radius of sphere</param> /// <returns></returns> public static Marker CreateSphere(Color color, Vector3 posn, float radius) { Marker m = new Marker(color, posn, radius); list.Add(m); return m; } /// <summary> /// Create a new SPHERE marker /// </summary> /// <param name="color">ARGB value (use A for transparency)</param> /// <param name="posn">World coordinates of TIP</param> /// <param name="size">Radius of base</param> /// <returns></returns> public static Marker CreateCone(Color color, Vector3 posn, Orientation orientation, float angle, float height) { Marker m = new Marker(color, posn, orientation, angle, height); list.Add(m); return m; } /// <summary> /// A new D3D device has been created. /// if Engine.IsFirstDevice==true, create those once-only things that require a Device to be available /// Otherwise, rebuild all those resources that get lost when a device is destroyed during a windowing change etc. /// </summary> public static void OnDeviceCreated() { Debug.WriteLine("Marker.OnDeviceCreated()"); Debug.WriteLine("(does nothing)"); } /// <summary> /// Called immediately after the D3D device has been destroyed, /// which generally happens as a result of application termination or /// windowed/full screen toggles. Resources created in OnSubsequentDevices() /// should be released here, which generally includes all Pool.Managed resources. /// </summary> public static void OnDeviceLost() { Debug.WriteLine("Marker.OnDeviceLost()"); Debug.WriteLine("(does nothing)"); } /// <summary> /// Device has been reset - rebuild unmanaged resources /// </summary> public static void OnReset() { Debug.WriteLine("Marker.OnReset()"); Debug.WriteLine("(does nothing)"); } /// <summary> /// Render all markers /// </summary> public static void Render() { // --------------------- Set Renderstate ------------------ Fx.SetTexture(null); // Use no texture at all (material-only objects) Engine.Device.RenderState.ZBufferEnable = true; // enabled Fx.SetMarkerTechnique(); // -------------------------------------------------------- foreach (Marker m in list) { // Set world matrix Fx.SetWorldMatrix(m.matrix); // Define the material for lighting Fx.SetMaterial(m.material); // draw the mesh Fx.DrawMeshSubset(m.mesh, 0); } } /// <summary> /// Move a marker by index number /// </summary> /// <param name="index"></param> /// <param name="posn"></param> public static void Goto(int index, Vector3 posn) { ((Marker)list[index]).Goto(posn); } /// <summary> /// Delete a marker by index (will change all other indices!!!) /// </summary> /// <param name="index"></param> public static void Delete(int index) { list.RemoveAt(index); } // ---------- DYNAMIC MEMBERS private Mesh mesh = null; private Material material = new Material(); private Vector3 location = new Vector3(); private float scale = 1.0f; private Orientation orientation = new Orientation(0,0,0); private Matrix matrix = Matrix.Identity; /// <summary> /// Create a SPHERE marker /// </summary> /// <param name="color"></param> /// <param name="posn"></param> /// <param name="radius"></param> private Marker(Color color, Vector3 posn, float radius) { // Create the mesh mesh = Mesh.Sphere(Engine.Device,1.0f,16,16); // create the material // material.Ambient = color; material.Diffuse = color; // material.Specular = color; material.Emissive = color; Goto(posn); Scale(radius); } /// <summary> /// Create a CONE marker, with the tip at posn /// </summary> /// <param name="color"></param> /// <param name="posn"></param> /// <param name="angle"></param> /// <param name="height"></param> /// <param name="orientation"></param> private Marker(Color color, Vector3 posn, Orientation orientation, float angle, float height) { // Work out the width of the base from the angle float radius = (float)Math.Tan(angle) * height; // Create the mesh, centred at 0,0,0 mesh = Mesh.Cylinder(Engine.Device,0,radius,height,16,1); // Shift the cone so that the tip is at 0,0,0 // and orient it to be aligned with the Y axis (which is how Truespace objects come out when at a YPR of 0,0,0) Matrix mat = Matrix.Translation(0,0,height/2) * Matrix.RotationYawPitchRoll(0,-(float)Math.PI/2,0); VertexBuffer vb = mesh.VertexBuffer; // Retrieve the vertex buffer data CustomVertex.PositionNormal[] vert; // get the input vertices as an array (in case I want to modify them) vert = (CustomVertex.PositionNormal[])vb.Lock(0, typeof(CustomVertex.PositionNormal), 0, mesh.NumberVertices); for (int i=0; i<mesh.NumberVertices; i++) { //vert[i].Z = vert[i].Z + height / 2; vert[i].Position = Vector3.TransformCoordinate(vert[i].Position,mat); vert[i].Normal = Vector3.TransformNormal(vert[i].Normal, mat); } vb.Unlock(); // create the material material.Ambient = color; material.Diffuse = color; material.Specular = color; material.Emissive = color; Goto(posn, orientation); } /// <summary> /// Move this marker /// </summary> /// <param name="locn"></param> public void Goto(Vector3 locn) { location = locn; SetMatrix(); } /// <summary> /// Move and orient this marker /// </summary> /// <param name="locn"></param> /// <param name="orient"></param> public void Goto(Vector3 locn, Orientation orient) { location = locn; orientation = orient; SetMatrix(); } /// <summary> /// Move and orient this marker using a matrix (e.g. for showing sensor Cones) /// </summary> /// <param name="locn"></param> /// <param name="orient"></param> public void Goto(Matrix mat) { matrix = mat; } public void Scale(float size) { scale = size; SetMatrix(); } private void SetMatrix() { matrix = Matrix.Scaling(new Vector3(scale,scale,scale)) * Matrix.RotationYawPitchRoll(orientation.Yaw, orientation.Pitch, orientation.Roll) * Matrix.Translation(location); } /// <summary> /// Remove this marker from the list /// </summary> public void Delete() { mesh.Dispose(); list.Remove(this); } } }
namespace DwarfFortressMapCompressor { partial class MapViewer { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MapViewer)); this.panel1 = new System.Windows.Forms.Panel(); this.label1 = new System.Windows.Forms.Label(); this.actionTimer = new System.Windows.Forms.Timer(this.components); this.mouseDraggingRepelsMapRadioButton = new System.Windows.Forms.RadioButton(); this.panel2 = new System.Windows.Forms.Panel(); this.mouseDragsMapRadioButton = new System.Windows.Forms.RadioButton(); this.panel3 = new System.Windows.Forms.Panel(); this.zoomOnCenterRadioButton = new System.Windows.Forms.RadioButton(); this.zoomOnMouseRadioButton = new System.Windows.Forms.RadioButton(); this.zLevelChooser = new DomainUpDownIgnoringMousewheel(); this.zLevelLabel = new System.Windows.Forms.Label(); this.mapBox = new DwarfFortressMapCompressor.WindowBox(); this.panel1.SuspendLayout(); this.panel2.SuspendLayout(); this.panel3.SuspendLayout(); ((System.ComponentModel.ISupportInitialize) (this.mapBox)).BeginInit(); this.SuspendLayout(); // // panel1 // this.panel1.Controls.Add(this.mapBox); this.panel1.Cursor = System.Windows.Forms.Cursors.Default; this.panel1.Location = new System.Drawing.Point(12, 12); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(913, 572); this.panel1.TabIndex = 1; this.panel1.MouseWheel += new System.Windows.Forms.MouseEventHandler(this.panel1_MouseWheel); // // label1 // this.label1.AutoSize = true; this.label1.Cursor = System.Windows.Forms.Cursors.Default; this.label1.Location = new System.Drawing.Point(12, 597); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(359, 13); this.label1.TabIndex = 2; this.label1.Text = "Use the mousewheel to zoom, and click and drag to scroll around the map."; // // actionTimer // this.actionTimer.Tick += new System.EventHandler(this.actionTimer_Tick); // // mouseDraggingRepelsMapRadioButton // this.mouseDraggingRepelsMapRadioButton.AutoSize = true; this.mouseDraggingRepelsMapRadioButton.Cursor = System.Windows.Forms.Cursors.Default; this.mouseDraggingRepelsMapRadioButton.Dock = System.Windows.Forms.DockStyle.Bottom; this.mouseDraggingRepelsMapRadioButton.Location = new System.Drawing.Point(0, 23); this.mouseDraggingRepelsMapRadioButton.Name = "mouseDraggingRepelsMapRadioButton"; this.mouseDraggingRepelsMapRadioButton.Size = new System.Drawing.Size(175, 17); this.mouseDraggingRepelsMapRadioButton.TabIndex = 4; this.mouseDraggingRepelsMapRadioButton.Text = "Mouse dragging repels map"; this.mouseDraggingRepelsMapRadioButton.UseVisualStyleBackColor = true; this.mouseDraggingRepelsMapRadioButton.CheckedChanged += new System.EventHandler(this.mouseDraggingRepelsMapRadioButton_CheckedChanged); // // panel2 // this.panel2.Controls.Add(this.mouseDragsMapRadioButton); this.panel2.Controls.Add(this.mouseDraggingRepelsMapRadioButton); this.panel2.Cursor = System.Windows.Forms.Cursors.Default; this.panel2.Location = new System.Drawing.Point(377, 597); this.panel2.Name = "panel2"; this.panel2.Size = new System.Drawing.Size(175, 40); this.panel2.TabIndex = 7; // // mouseDragsMapRadioButton // this.mouseDragsMapRadioButton.AutoSize = true; this.mouseDragsMapRadioButton.Checked = true; this.mouseDragsMapRadioButton.Cursor = System.Windows.Forms.Cursors.Default; this.mouseDragsMapRadioButton.Dock = System.Windows.Forms.DockStyle.Top; this.mouseDragsMapRadioButton.Location = new System.Drawing.Point(0, 0); this.mouseDragsMapRadioButton.Name = "mouseDragsMapRadioButton"; this.mouseDragsMapRadioButton.Size = new System.Drawing.Size(175, 17); this.mouseDragsMapRadioButton.TabIndex = 3; this.mouseDragsMapRadioButton.TabStop = true; this.mouseDragsMapRadioButton.Text = "Mouse drags map"; this.mouseDragsMapRadioButton.UseVisualStyleBackColor = true; this.mouseDragsMapRadioButton.CheckedChanged += new System.EventHandler(this.mouseDragsMapRadioButton_CheckedChanged); // // panel3 // this.panel3.Controls.Add(this.zoomOnCenterRadioButton); this.panel3.Controls.Add(this.zoomOnMouseRadioButton); this.panel3.Cursor = System.Windows.Forms.Cursors.Default; this.panel3.Location = new System.Drawing.Point(558, 597); this.panel3.Name = "panel3"; this.panel3.Size = new System.Drawing.Size(179, 40); this.panel3.TabIndex = 8; this.panel3.Visible = false; // // zoomOnCenterRadioButton // this.zoomOnCenterRadioButton.AutoSize = true; this.zoomOnCenterRadioButton.Checked = true; this.zoomOnCenterRadioButton.Cursor = System.Windows.Forms.Cursors.Default; this.zoomOnCenterRadioButton.Dock = System.Windows.Forms.DockStyle.Top; this.zoomOnCenterRadioButton.Location = new System.Drawing.Point(0, 0); this.zoomOnCenterRadioButton.Name = "zoomOnCenterRadioButton"; this.zoomOnCenterRadioButton.Size = new System.Drawing.Size(179, 17); this.zoomOnCenterRadioButton.TabIndex = 3; this.zoomOnCenterRadioButton.TabStop = true; this.zoomOnCenterRadioButton.Text = "Zoom on center"; this.zoomOnCenterRadioButton.UseVisualStyleBackColor = true; this.zoomOnCenterRadioButton.Visible = false; // // zoomOnMouseRadioButton // this.zoomOnMouseRadioButton.AutoSize = true; this.zoomOnMouseRadioButton.Cursor = System.Windows.Forms.Cursors.Default; this.zoomOnMouseRadioButton.Dock = System.Windows.Forms.DockStyle.Bottom; this.zoomOnMouseRadioButton.Location = new System.Drawing.Point(0, 23); this.zoomOnMouseRadioButton.Name = "zoomOnMouseRadioButton"; this.zoomOnMouseRadioButton.Size = new System.Drawing.Size(179, 17); this.zoomOnMouseRadioButton.TabIndex = 4; this.zoomOnMouseRadioButton.Text = "Zoom on mouse"; this.zoomOnMouseRadioButton.UseVisualStyleBackColor = true; this.zoomOnMouseRadioButton.Visible = false; // // zLevelChooser // this.zLevelChooser.InterceptArrowKeys = false; this.zLevelChooser.Location = new System.Drawing.Point(759, 616); this.zLevelChooser.Name = "zLevelChooser"; this.zLevelChooser.Size = new System.Drawing.Size(43, 20); this.zLevelChooser.TabIndex = 9; this.zLevelChooser.TabStop = false; this.zLevelChooser.Text = "0"; this.zLevelChooser.SelectedItemChanged += new System.EventHandler(this.zLevelChooser_SelectedItemChanged); this.zLevelChooser.MouseWheel += new System.Windows.Forms.MouseEventHandler(this.zLevelChooser_MouseWheel); // // zLevelLabel // this.zLevelLabel.AutoSize = true; this.zLevelLabel.Location = new System.Drawing.Point(756, 597); this.zLevelLabel.Name = "zLevelLabel"; this.zLevelLabel.Size = new System.Drawing.Size(169, 13); this.zLevelLabel.TabIndex = 10; this.zLevelLabel.Text = "Z Level: (negative is underground)"; // // mapBox // this.mapBox.Cursor = System.Windows.Forms.Cursors.Default; this.mapBox.Dock = System.Windows.Forms.DockStyle.Fill; this.mapBox.Location = new System.Drawing.Point(0, 0); this.mapBox.Name = "mapBox"; this.mapBox.Size = new System.Drawing.Size(913, 572); this.mapBox.TabIndex = 0; this.mapBox.TabStop = false; this.mapBox.MouseWheel += new System.Windows.Forms.MouseEventHandler(this.mapBox_MouseWheel); this.mapBox.Click += new System.EventHandler(this.mapBox_Click); this.mapBox.MouseDown += new System.Windows.Forms.MouseEventHandler(this.mapBox_MouseDown); this.mapBox.MouseMove += new System.Windows.Forms.MouseEventHandler(this.mapBox_MouseMove); this.mapBox.MouseUp += new System.Windows.Forms.MouseEventHandler(this.mapBox_MouseUp); // // MapViewer // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(937, 648); this.Controls.Add(this.zLevelLabel); this.Controls.Add(this.zLevelChooser); this.Controls.Add(this.panel3); this.Controls.Add(this.panel2); this.Controls.Add(this.label1); this.Controls.Add(this.panel1); this.Cursor = System.Windows.Forms.Cursors.Default; this.Icon = ((System.Drawing.Icon) (resources.GetObject("$this.Icon"))); this.Name = "MapViewer"; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Show; this.Text = "DF Map Compressor\'s Map Viewer"; this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.MapViewer_FormClosed); this.MouseWheel += new System.Windows.Forms.MouseEventHandler(this.form_MouseWheel); this.Resize += new System.EventHandler(this.mapViewer_Resize); this.panel1.ResumeLayout(false); this.panel2.ResumeLayout(false); this.panel2.PerformLayout(); this.panel3.ResumeLayout(false); this.panel3.PerformLayout(); ((System.ComponentModel.ISupportInitialize) (this.mapBox)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Panel panel1; private WindowBox mapBox; private System.Windows.Forms.Label label1; private System.Windows.Forms.Timer actionTimer; private System.Windows.Forms.RadioButton mouseDraggingRepelsMapRadioButton; private System.Windows.Forms.Panel panel2; private System.Windows.Forms.RadioButton mouseDragsMapRadioButton; private System.Windows.Forms.Panel panel3; private System.Windows.Forms.RadioButton zoomOnCenterRadioButton; private System.Windows.Forms.RadioButton zoomOnMouseRadioButton; private DomainUpDownIgnoringMousewheel zLevelChooser; private System.Windows.Forms.Label zLevelLabel; } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Text; using log4net; using Nini.Config; using NUnit.Framework; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.CoreModules.Scripting.ScriptModuleComms; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.ScriptEngine.Shared; using OpenSim.Region.ScriptEngine.Shared.Api; using OpenSim.Services.Interfaces; using OpenSim.Tests.Common; using OpenSim.Tests.Common.Mock; namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests { /// <summary> /// Tests for inventory functions in LSL /// </summary> [TestFixture] public class JsonStoreScriptModuleTests : OpenSimTestCase { private Scene m_scene; private MockScriptEngine m_engine; private ScriptModuleCommsModule m_smcm; private JsonStoreScriptModule m_jssm; [TestFixtureSetUp] public void FixtureInit() { // Don't allow tests to be bamboozled by asynchronous events. Execute everything on the same thread. Util.FireAndForgetMethod = FireAndForgetMethod.RegressionTest; } [TestFixtureTearDown] public void TearDown() { // We must set this back afterwards, otherwise later tests will fail since they're expecting multiple // threads. Possibly, later tests should be rewritten so none of them require async stuff (which regression // tests really shouldn't). Util.FireAndForgetMethod = Util.DefaultFireAndForgetMethod; } [SetUp] public override void SetUp() { base.SetUp(); IConfigSource configSource = new IniConfigSource(); IConfig jsonStoreConfig = configSource.AddConfig("JsonStore"); jsonStoreConfig.Set("Enabled", "true"); m_engine = new MockScriptEngine(); m_smcm = new ScriptModuleCommsModule(); JsonStoreModule jsm = new JsonStoreModule(); m_jssm = new JsonStoreScriptModule(); m_scene = new SceneHelpers().SetupScene(); SceneHelpers.SetupSceneModules(m_scene, configSource, m_engine, m_smcm, jsm, m_jssm); try { m_smcm.RegisterScriptInvocation(this, "DummyTestMethod"); } catch (ArgumentException) { Assert.Ignore("Ignoring test since running on .NET 3.5 or earlier."); } // XXX: Unfortunately, ICommsModule currently has no way of deregistering methods. } private object InvokeOp(string name, params object[] args) { return InvokeOpOnHost(name, UUID.Zero, args); } private object InvokeOpOnHost(string name, UUID hostId, params object[] args) { return m_smcm.InvokeOperation(hostId, UUID.Zero, name, args); } [Test] public void TestJsonCreateStore() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); // Test blank store { UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); Assert.That(storeId, Is.Not.EqualTo(UUID.Zero)); } // Test single element store { UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : 'World' }"); Assert.That(storeId, Is.Not.EqualTo(UUID.Zero)); } // Test with an integer value { UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : 42.15 }"); Assert.That(storeId, Is.Not.EqualTo(UUID.Zero)); string value = (string)InvokeOp("JsonGetValue", storeId, "Hello"); Assert.That(value, Is.EqualTo("42.15")); } // Test with an array as the root node { UUID storeId = (UUID)InvokeOp("JsonCreateStore", "[ 'one', 'two', 'three' ]"); Assert.That(storeId, Is.Not.EqualTo(UUID.Zero)); string value = (string)InvokeOp("JsonGetValue", storeId, "[1]"); Assert.That(value, Is.EqualTo("two")); } } [Test] public void TestJsonDestroyStore() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : 'World' }"); int dsrv = (int)InvokeOp("JsonDestroyStore", storeId); Assert.That(dsrv, Is.EqualTo(1)); int tprv = (int)InvokeOp("JsonGetNodeType", storeId, "Hello"); Assert.That(tprv, Is.EqualTo(JsonStoreScriptModule.JSON_NODETYPE_UNDEF)); } [Test] public void TestJsonDestroyStoreNotExists() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); UUID fakeStoreId = TestHelpers.ParseTail(0x500); int dsrv = (int)InvokeOp("JsonDestroyStore", fakeStoreId); Assert.That(dsrv, Is.EqualTo(0)); } [Test] public void TestJsonGetValue() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : { 'World' : 'Two' } }"); { string value = (string)InvokeOp("JsonGetValue", storeId, "Hello.World"); Assert.That(value, Is.EqualTo("Two")); } // Test get of path section instead of leaf { string value = (string)InvokeOp("JsonGetValue", storeId, "Hello"); Assert.That(value, Is.EqualTo("")); } // Test get of non-existing value { string fakeValueGet = (string)InvokeOp("JsonGetValue", storeId, "foo"); Assert.That(fakeValueGet, Is.EqualTo("")); } // Test get from non-existing store { UUID fakeStoreId = TestHelpers.ParseTail(0x500); string fakeStoreValueGet = (string)InvokeOp("JsonGetValue", fakeStoreId, "Hello"); Assert.That(fakeStoreValueGet, Is.EqualTo("")); } } [Test] public void TestJsonGetJson() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : { 'World' : 'Two' } }"); { string value = (string)InvokeOp("JsonGetJson", storeId, "Hello.World"); Assert.That(value, Is.EqualTo("'Two'")); } // Test get of path section instead of leaf { string value = (string)InvokeOp("JsonGetJson", storeId, "Hello"); Assert.That(value, Is.EqualTo("{\"World\":\"Two\"}")); } // Test get of non-existing value { string fakeValueGet = (string)InvokeOp("JsonGetJson", storeId, "foo"); Assert.That(fakeValueGet, Is.EqualTo("")); } // Test get from non-existing store { UUID fakeStoreId = TestHelpers.ParseTail(0x500); string fakeStoreValueGet = (string)InvokeOp("JsonGetJson", fakeStoreId, "Hello"); Assert.That(fakeStoreValueGet, Is.EqualTo("")); } } // [Test] // public void TestJsonTakeValue() // { // TestHelpers.InMethod(); //// TestHelpers.EnableLogging(); // // UUID storeId // = (UUID)m_smcm.InvokeOperation( // UUID.Zero, UUID.Zero, "JsonCreateStore", new object[] { "{ 'Hello' : 'World' }" }); // // string value // = (string)m_smcm.InvokeOperation( // UUID.Zero, UUID.Zero, "JsonTakeValue", new object[] { storeId, "Hello" }); // // Assert.That(value, Is.EqualTo("World")); // // string value2 // = (string)m_smcm.InvokeOperation( // UUID.Zero, UUID.Zero, "JsonGetValue", new object[] { storeId, "Hello" }); // // Assert.That(value, Is.Null); // } [Test] public void TestJsonRemoveValue() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); // Test remove of node in object pointing to a string { UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : 'World' }"); int returnValue = (int)InvokeOp( "JsonRemoveValue", storeId, "Hello"); Assert.That(returnValue, Is.EqualTo(1)); int result = (int)InvokeOp("JsonGetNodeType", storeId, "Hello"); Assert.That(result, Is.EqualTo(JsonStoreScriptModule.JSON_NODETYPE_UNDEF)); string returnValue2 = (string)InvokeOp("JsonGetValue", storeId, "Hello"); Assert.That(returnValue2, Is.EqualTo("")); } // Test remove of node in object pointing to another object { UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : { 'World' : 'Wally' } }"); int returnValue = (int)InvokeOp( "JsonRemoveValue", storeId, "Hello"); Assert.That(returnValue, Is.EqualTo(1)); int result = (int)InvokeOp("JsonGetNodeType", storeId, "Hello"); Assert.That(result, Is.EqualTo(JsonStoreScriptModule.JSON_NODETYPE_UNDEF)); string returnValue2 = (string)InvokeOp("JsonGetJson", storeId, "Hello"); Assert.That(returnValue2, Is.EqualTo("")); } // Test remove of node in an array { UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : [ 'value1', 'value2' ] }"); int returnValue = (int)InvokeOp( "JsonRemoveValue", storeId, "Hello[0]"); Assert.That(returnValue, Is.EqualTo(1)); int result = (int)InvokeOp("JsonGetNodeType", storeId, "Hello[0]"); Assert.That(result, Is.EqualTo(JsonStoreScriptModule.JSON_NODETYPE_VALUE)); result = (int)InvokeOp("JsonGetNodeType", storeId, "Hello[1]"); Assert.That(result, Is.EqualTo(JsonStoreScriptModule.JSON_NODETYPE_UNDEF)); string stringReturnValue = (string)InvokeOp("JsonGetValue", storeId, "Hello[0]"); Assert.That(stringReturnValue, Is.EqualTo("value2")); stringReturnValue = (string)InvokeOp("JsonGetJson", storeId, "Hello[1]"); Assert.That(stringReturnValue, Is.EqualTo("")); } // Test remove of non-existing value { UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : 'World' }"); int fakeValueRemove = (int)InvokeOp("JsonRemoveValue", storeId, "Cheese"); Assert.That(fakeValueRemove, Is.EqualTo(0)); } { // Test get from non-existing store UUID fakeStoreId = TestHelpers.ParseTail(0x500); int fakeStoreValueRemove = (int)InvokeOp("JsonRemoveValue", fakeStoreId, "Hello"); Assert.That(fakeStoreValueRemove, Is.EqualTo(0)); } } // [Test] // public void TestJsonTestPath() // { // TestHelpers.InMethod(); //// TestHelpers.EnableLogging(); // // UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : { 'World' : 'One' } }"); // // { // int result = (int)InvokeOp("JsonTestPath", storeId, "Hello.World"); // Assert.That(result, Is.EqualTo(1)); // } // // // Test for path which does not resolve to a value. // { // int result = (int)InvokeOp("JsonTestPath", storeId, "Hello"); // Assert.That(result, Is.EqualTo(0)); // } // // { // int result2 = (int)InvokeOp("JsonTestPath", storeId, "foo"); // Assert.That(result2, Is.EqualTo(0)); // } // // // Test with fake store // { // UUID fakeStoreId = TestHelpers.ParseTail(0x500); // int fakeStoreValueRemove = (int)InvokeOp("JsonTestPath", fakeStoreId, "Hello"); // Assert.That(fakeStoreValueRemove, Is.EqualTo(0)); // } // } // [Test] // public void TestJsonTestPathJson() // { // TestHelpers.InMethod(); //// TestHelpers.EnableLogging(); // // UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : { 'World' : 'One' } }"); // // { // int result = (int)InvokeOp("JsonTestPathJson", storeId, "Hello.World"); // Assert.That(result, Is.EqualTo(1)); // } // // // Test for path which does not resolve to a value. // { // int result = (int)InvokeOp("JsonTestPathJson", storeId, "Hello"); // Assert.That(result, Is.EqualTo(1)); // } // // { // int result2 = (int)InvokeOp("JsonTestPathJson", storeId, "foo"); // Assert.That(result2, Is.EqualTo(0)); // } // // // Test with fake store // { // UUID fakeStoreId = TestHelpers.ParseTail(0x500); // int fakeStoreValueRemove = (int)InvokeOp("JsonTestPathJson", fakeStoreId, "Hello"); // Assert.That(fakeStoreValueRemove, Is.EqualTo(0)); // } // } [Test] public void TestJsonGetArrayLength() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : { 'World' : [ 'one', 2 ] } }"); { int result = (int)InvokeOp("JsonGetArrayLength", storeId, "Hello.World"); Assert.That(result, Is.EqualTo(2)); } // Test path which is not an array { int result = (int)InvokeOp("JsonGetArrayLength", storeId, "Hello"); Assert.That(result, Is.EqualTo(-1)); } // Test fake path { int result = (int)InvokeOp("JsonGetArrayLength", storeId, "foo"); Assert.That(result, Is.EqualTo(-1)); } // Test fake store { UUID fakeStoreId = TestHelpers.ParseTail(0x500); int result = (int)InvokeOp("JsonGetArrayLength", fakeStoreId, "Hello.World"); Assert.That(result, Is.EqualTo(-1)); } } [Test] public void TestJsonGetNodeType() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : { 'World' : [ 'one', 2 ] } }"); { int result = (int)InvokeOp("JsonGetNodeType", storeId, "."); Assert.That(result, Is.EqualTo(JsonStoreScriptModule.JSON_NODETYPE_OBJECT)); } { int result = (int)InvokeOp("JsonGetNodeType", storeId, "Hello"); Assert.That(result, Is.EqualTo(JsonStoreScriptModule.JSON_NODETYPE_OBJECT)); } { int result = (int)InvokeOp("JsonGetNodeType", storeId, "Hello.World"); Assert.That(result, Is.EqualTo(JsonStoreScriptModule.JSON_NODETYPE_ARRAY)); } { int result = (int)InvokeOp("JsonGetNodeType", storeId, "Hello.World[0]"); Assert.That(result, Is.EqualTo(JsonStoreScriptModule.JSON_NODETYPE_VALUE)); } { int result = (int)InvokeOp("JsonGetNodeType", storeId, "Hello.World[1]"); Assert.That(result, Is.EqualTo(JsonStoreScriptModule.JSON_NODETYPE_VALUE)); } // Test for non-existent path { int result = (int)InvokeOp("JsonGetNodeType", storeId, "foo"); Assert.That(result, Is.EqualTo(JsonStoreScriptModule.JSON_NODETYPE_UNDEF)); } // Test for non-existent store { UUID fakeStoreId = TestHelpers.ParseTail(0x500); int result = (int)InvokeOp("JsonGetNodeType", fakeStoreId, "."); Assert.That(result, Is.EqualTo(JsonStoreScriptModule.JSON_NODETYPE_UNDEF)); } } [Test] public void TestJsonList2Path() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); // Invoking these methods directly since I just couldn't get comms module invocation to work for some reason // - some confusion with the methods that take a params object[] invocation. { string result = m_jssm.JsonList2Path(UUID.Zero, UUID.Zero, new object[] { "foo" }); Assert.That(result, Is.EqualTo("{foo}")); } { string result = m_jssm.JsonList2Path(UUID.Zero, UUID.Zero, new object[] { "foo", "bar" }); Assert.That(result, Is.EqualTo("{foo}.{bar}")); } { string result = m_jssm.JsonList2Path(UUID.Zero, UUID.Zero, new object[] { "foo", 1, "bar" }); Assert.That(result, Is.EqualTo("{foo}.[1].{bar}")); } } [Test] public void TestJsonSetValue() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); { UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); int result = (int)InvokeOp("JsonSetValue", storeId, "Fun", "Times"); Assert.That(result, Is.EqualTo(1)); string value = (string)InvokeOp("JsonGetValue", storeId, "Fun"); Assert.That(value, Is.EqualTo("Times")); } // Test setting a key containing periods with delineation { UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); int result = (int)InvokeOp("JsonSetValue", storeId, "{Fun.Circus}", "Times"); Assert.That(result, Is.EqualTo(1)); string value = (string)InvokeOp("JsonGetValue", storeId, "{Fun.Circus}"); Assert.That(value, Is.EqualTo("Times")); } // *** Test [] *** // Test setting a key containing unbalanced ] without delineation. Expecting failure { UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); int result = (int)InvokeOp("JsonSetValue", storeId, "Fun]Circus", "Times"); Assert.That(result, Is.EqualTo(0)); string value = (string)InvokeOp("JsonGetValue", storeId, "Fun]Circus"); Assert.That(value, Is.EqualTo("")); } // Test setting a key containing unbalanced [ without delineation. Expecting failure { UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); int result = (int)InvokeOp("JsonSetValue", storeId, "Fun[Circus", "Times"); Assert.That(result, Is.EqualTo(0)); string value = (string)InvokeOp("JsonGetValue", storeId, "Fun[Circus"); Assert.That(value, Is.EqualTo("")); } // Test setting a key containing unbalanced [] without delineation. Expecting failure { UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); int result = (int)InvokeOp("JsonSetValue", storeId, "Fun[]Circus", "Times"); Assert.That(result, Is.EqualTo(0)); string value = (string)InvokeOp("JsonGetValue", storeId, "Fun[]Circus"); Assert.That(value, Is.EqualTo("")); } // Test setting a key containing unbalanced ] with delineation { UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); int result = (int)InvokeOp("JsonSetValue", storeId, "{Fun]Circus}", "Times"); Assert.That(result, Is.EqualTo(1)); string value = (string)InvokeOp("JsonGetValue", storeId, "{Fun]Circus}"); Assert.That(value, Is.EqualTo("Times")); } // Test setting a key containing unbalanced [ with delineation { UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); int result = (int)InvokeOp("JsonSetValue", storeId, "{Fun[Circus}", "Times"); Assert.That(result, Is.EqualTo(1)); string value = (string)InvokeOp("JsonGetValue", storeId, "{Fun[Circus}"); Assert.That(value, Is.EqualTo("Times")); } // Test setting a key containing empty balanced [] with delineation { UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); int result = (int)InvokeOp("JsonSetValue", storeId, "{Fun[]Circus}", "Times"); Assert.That(result, Is.EqualTo(1)); string value = (string)InvokeOp("JsonGetValue", storeId, "{Fun[]Circus}"); Assert.That(value, Is.EqualTo("Times")); } // // Commented out as this currently unexpectedly fails. // // Test setting a key containing brackets around an integer with delineation // { // UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); // // int result = (int)InvokeOp("JsonSetValue", storeId, "{Fun[0]Circus}", "Times"); // Assert.That(result, Is.EqualTo(1)); // // string value = (string)InvokeOp("JsonGetValue", storeId, "{Fun[0]Circus}"); // Assert.That(value, Is.EqualTo("Times")); // } // *** Test {} *** // Test setting a key containing unbalanced } without delineation. Expecting failure (?) { UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); int result = (int)InvokeOp("JsonSetValue", storeId, "Fun}Circus", "Times"); Assert.That(result, Is.EqualTo(0)); string value = (string)InvokeOp("JsonGetValue", storeId, "Fun}Circus"); Assert.That(value, Is.EqualTo("")); } // Test setting a key containing unbalanced { without delineation. Expecting failure (?) { UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); int result = (int)InvokeOp("JsonSetValue", storeId, "Fun{Circus", "Times"); Assert.That(result, Is.EqualTo(0)); string value = (string)InvokeOp("JsonGetValue", storeId, "Fun}Circus"); Assert.That(value, Is.EqualTo("")); } // // Commented out as this currently unexpectedly fails. // // Test setting a key containing unbalanced } // { // UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); // // int result = (int)InvokeOp("JsonSetValue", storeId, "{Fun}Circus}", "Times"); // Assert.That(result, Is.EqualTo(0)); // } // Test setting a key containing unbalanced { with delineation { UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); int result = (int)InvokeOp("JsonSetValue", storeId, "{Fun{Circus}", "Times"); Assert.That(result, Is.EqualTo(1)); string value = (string)InvokeOp("JsonGetValue", storeId, "{Fun{Circus}"); Assert.That(value, Is.EqualTo("Times")); } // Test setting a key containing balanced {} with delineation. This should fail. { UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); int result = (int)InvokeOp("JsonSetValue", storeId, "{Fun{Filled}Circus}", "Times"); Assert.That(result, Is.EqualTo(0)); string value = (string)InvokeOp("JsonGetValue", storeId, "{Fun{Filled}Circus}"); Assert.That(value, Is.EqualTo("")); } // Test setting to location that does not exist. This should fail. { UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); int result = (int)InvokeOp("JsonSetValue", storeId, "Fun.Circus", "Times"); Assert.That(result, Is.EqualTo(0)); string value = (string)InvokeOp("JsonGetValue", storeId, "Fun.Circus"); Assert.That(value, Is.EqualTo("")); } // Test with fake store { UUID fakeStoreId = TestHelpers.ParseTail(0x500); int fakeStoreValueSet = (int)InvokeOp("JsonSetValue", fakeStoreId, "Hello", "World"); Assert.That(fakeStoreValueSet, Is.EqualTo(0)); } } [Test] public void TestJsonSetJson() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); // Single quoted token case { UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ }"); int result = (int)InvokeOp("JsonSetJson", storeId, "Fun", "'Times'"); Assert.That(result, Is.EqualTo(1)); string value = (string)InvokeOp("JsonGetValue", storeId, "Fun"); Assert.That(value, Is.EqualTo("Times")); } // Sub-tree case { UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ }"); int result = (int)InvokeOp("JsonSetJson", storeId, "Fun", "{ 'Filled' : 'Times' }"); Assert.That(result, Is.EqualTo(1)); string value = (string)InvokeOp("JsonGetValue", storeId, "Fun.Filled"); Assert.That(value, Is.EqualTo("Times")); } // If setting single strings in JsonSetValueJson, these must be single quoted tokens, not bare strings. { UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ }"); int result = (int)InvokeOp("JsonSetJson", storeId, "Fun", "Times"); Assert.That(result, Is.EqualTo(0)); string value = (string)InvokeOp("JsonGetValue", storeId, "Fun"); Assert.That(value, Is.EqualTo("")); } // Test setting to location that does not exist. This should fail. { UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ }"); int result = (int)InvokeOp("JsonSetJson", storeId, "Fun.Circus", "'Times'"); Assert.That(result, Is.EqualTo(0)); string value = (string)InvokeOp("JsonGetValue", storeId, "Fun.Circus"); Assert.That(value, Is.EqualTo("")); } // Test with fake store { UUID fakeStoreId = TestHelpers.ParseTail(0x500); int fakeStoreValueSet = (int)InvokeOp("JsonSetJson", fakeStoreId, "Hello", "'World'"); Assert.That(fakeStoreValueSet, Is.EqualTo(0)); } } /// <summary> /// Test for writing json to a notecard /// </summary> /// <remarks> /// TODO: Really needs to test correct receipt of the link_message event. Could do this by directly fetching /// it via the MockScriptEngine or perhaps by a dummy script instance. /// </remarks> [Test] public void TestJsonWriteNotecard() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); SceneObjectGroup so = SceneHelpers.CreateSceneObject(1, TestHelpers.ParseTail(0x1)); m_scene.AddSceneObject(so); UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello':'World' }"); { string notecardName = "nc1"; // Write notecard UUID writeNotecardRequestId = (UUID)InvokeOpOnHost("JsonWriteNotecard", so.UUID, storeId, "", notecardName); Assert.That(writeNotecardRequestId, Is.Not.EqualTo(UUID.Zero)); TaskInventoryItem nc1Item = so.RootPart.Inventory.GetInventoryItem(notecardName); Assert.That(nc1Item, Is.Not.Null); // TODO: Should independently check the contents. } // TODO: Write partial test { // Try to write notecard for a bad path // In this case we do get a request id but no notecard is written. string badPathNotecardName = "badPathNotecardName"; UUID writeNotecardBadPathRequestId = (UUID)InvokeOpOnHost("JsonWriteNotecard", so.UUID, storeId, "flibble", badPathNotecardName); Assert.That(writeNotecardBadPathRequestId, Is.Not.EqualTo(UUID.Zero)); TaskInventoryItem badPathItem = so.RootPart.Inventory.GetInventoryItem(badPathNotecardName); Assert.That(badPathItem, Is.Null); } { // Test with fake store // In this case we do get a request id but no notecard is written. string fakeStoreNotecardName = "fakeStoreNotecardName"; UUID fakeStoreId = TestHelpers.ParseTail(0x500); UUID fakeStoreWriteNotecardValue = (UUID)InvokeOpOnHost("JsonWriteNotecard", so.UUID, fakeStoreId, "", fakeStoreNotecardName); Assert.That(fakeStoreWriteNotecardValue, Is.Not.EqualTo(UUID.Zero)); TaskInventoryItem fakeStoreItem = so.RootPart.Inventory.GetInventoryItem(fakeStoreNotecardName); Assert.That(fakeStoreItem, Is.Null); } } /// <summary> /// Test for reading json from a notecard /// </summary> /// <remarks> /// TODO: Really needs to test correct receipt of the link_message event. Could do this by directly fetching /// it via the MockScriptEngine or perhaps by a dummy script instance. /// </remarks> [Test] public void TestJsonReadNotecard() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); string notecardName = "nc1"; SceneObjectGroup so = SceneHelpers.CreateSceneObject(1, TestHelpers.ParseTail(0x1)); m_scene.AddSceneObject(so); UUID creatingStoreId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello':'World' }"); // Write notecard InvokeOpOnHost("JsonWriteNotecard", so.UUID, creatingStoreId, "", notecardName); { // Read notecard UUID receivingStoreId = (UUID)InvokeOp("JsonCreateStore", "{}"); UUID readNotecardRequestId = (UUID)InvokeOpOnHost("JsonReadNotecard", so.UUID, receivingStoreId, "", notecardName); Assert.That(readNotecardRequestId, Is.Not.EqualTo(UUID.Zero)); string value = (string)InvokeOp("JsonGetValue", receivingStoreId, "Hello"); Assert.That(value, Is.EqualTo("World")); } { // Read notecard to new single component path UUID receivingStoreId = (UUID)InvokeOp("JsonCreateStore", "{}"); UUID readNotecardRequestId = (UUID)InvokeOpOnHost("JsonReadNotecard", so.UUID, receivingStoreId, "make", notecardName); Assert.That(readNotecardRequestId, Is.Not.EqualTo(UUID.Zero)); string value = (string)InvokeOp("JsonGetValue", receivingStoreId, "Hello"); Assert.That(value, Is.EqualTo("")); value = (string)InvokeOp("JsonGetValue", receivingStoreId, "make.Hello"); Assert.That(value, Is.EqualTo("World")); } { // Read notecard to new multi-component path. This should not work. UUID receivingStoreId = (UUID)InvokeOp("JsonCreateStore", "{}"); UUID readNotecardRequestId = (UUID)InvokeOpOnHost("JsonReadNotecard", so.UUID, receivingStoreId, "make.it", notecardName); Assert.That(readNotecardRequestId, Is.Not.EqualTo(UUID.Zero)); string value = (string)InvokeOp("JsonGetValue", receivingStoreId, "Hello"); Assert.That(value, Is.EqualTo("")); value = (string)InvokeOp("JsonGetValue", receivingStoreId, "make.it.Hello"); Assert.That(value, Is.EqualTo("")); } { // Read notecard to existing multi-component path. This should work UUID receivingStoreId = (UUID)InvokeOp("JsonCreateStore", "{ 'make' : { 'it' : 'so' } }"); UUID readNotecardRequestId = (UUID)InvokeOpOnHost("JsonReadNotecard", so.UUID, receivingStoreId, "make.it", notecardName); Assert.That(readNotecardRequestId, Is.Not.EqualTo(UUID.Zero)); string value = (string)InvokeOp("JsonGetValue", receivingStoreId, "Hello"); Assert.That(value, Is.EqualTo("")); value = (string)InvokeOp("JsonGetValue", receivingStoreId, "make.it.Hello"); Assert.That(value, Is.EqualTo("World")); } { // Read notecard to invalid path. This should not work. UUID receivingStoreId = (UUID)InvokeOp("JsonCreateStore", "{ 'make' : { 'it' : 'so' } }"); UUID readNotecardRequestId = (UUID)InvokeOpOnHost("JsonReadNotecard", so.UUID, receivingStoreId, "/", notecardName); Assert.That(readNotecardRequestId, Is.Not.EqualTo(UUID.Zero)); string value = (string)InvokeOp("JsonGetValue", receivingStoreId, "Hello"); Assert.That(value, Is.EqualTo("")); } { // Try read notecard to fake store. UUID fakeStoreId = TestHelpers.ParseTail(0x500); UUID readNotecardRequestId = (UUID)InvokeOpOnHost("JsonReadNotecard", so.UUID, fakeStoreId, "", notecardName); Assert.That(readNotecardRequestId, Is.Not.EqualTo(UUID.Zero)); string value = (string)InvokeOp("JsonGetValue", fakeStoreId, "Hello"); Assert.That(value, Is.EqualTo("")); } } public object DummyTestMethod(object o1, object o2, object o3, object o4, object o5) { return null; } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type DriveItemRequest. /// </summary> public partial class DriveItemRequest : BaseRequest, IDriveItemRequest { /// <summary> /// Constructs a new DriveItemRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public DriveItemRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified DriveItem using POST. /// </summary> /// <param name="driveItemToCreate">The DriveItem to create.</param> /// <returns>The created DriveItem.</returns> public System.Threading.Tasks.Task<DriveItem> CreateAsync(DriveItem driveItemToCreate) { return this.CreateAsync(driveItemToCreate, CancellationToken.None); } /// <summary> /// Creates the specified DriveItem using POST. /// </summary> /// <param name="driveItemToCreate">The DriveItem to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created DriveItem.</returns> public async System.Threading.Tasks.Task<DriveItem> CreateAsync(DriveItem driveItemToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<DriveItem>(driveItemToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified DriveItem. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified DriveItem. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken) { this.Method = "DELETE"; await this.SendAsync<DriveItem>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified DriveItem. /// </summary> /// <returns>The DriveItem.</returns> public System.Threading.Tasks.Task<DriveItem> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified DriveItem. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The DriveItem.</returns> public async System.Threading.Tasks.Task<DriveItem> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<DriveItem>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified DriveItem using PATCH. /// </summary> /// <param name="driveItemToUpdate">The DriveItem to update.</param> /// <returns>The updated DriveItem.</returns> public System.Threading.Tasks.Task<DriveItem> UpdateAsync(DriveItem driveItemToUpdate) { return this.UpdateAsync(driveItemToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified DriveItem using PATCH. /// </summary> /// <param name="driveItemToUpdate">The DriveItem to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated DriveItem.</returns> public async System.Threading.Tasks.Task<DriveItem> UpdateAsync(DriveItem driveItemToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<DriveItem>(driveItemToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IDriveItemRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IDriveItemRequest Expand(Expression<Func<DriveItem, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IDriveItemRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IDriveItemRequest Select(Expression<Func<DriveItem, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="driveItemToInitialize">The <see cref="DriveItem"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(DriveItem driveItemToInitialize) { if (driveItemToInitialize != null && driveItemToInitialize.AdditionalData != null) { if (driveItemToInitialize.Children != null && driveItemToInitialize.Children.CurrentPage != null) { driveItemToInitialize.Children.AdditionalData = driveItemToInitialize.AdditionalData; object nextPageLink; driveItemToInitialize.AdditionalData.TryGetValue("[email protected]", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { driveItemToInitialize.Children.InitializeNextPageRequest( this.Client, nextPageLinkString); } } if (driveItemToInitialize.Permissions != null && driveItemToInitialize.Permissions.CurrentPage != null) { driveItemToInitialize.Permissions.AdditionalData = driveItemToInitialize.AdditionalData; object nextPageLink; driveItemToInitialize.AdditionalData.TryGetValue("[email protected]", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { driveItemToInitialize.Permissions.InitializeNextPageRequest( this.Client, nextPageLinkString); } } if (driveItemToInitialize.Thumbnails != null && driveItemToInitialize.Thumbnails.CurrentPage != null) { driveItemToInitialize.Thumbnails.AdditionalData = driveItemToInitialize.AdditionalData; object nextPageLink; driveItemToInitialize.AdditionalData.TryGetValue("[email protected]", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { driveItemToInitialize.Thumbnails.InitializeNextPageRequest( this.Client, nextPageLinkString); } } } } } }
// 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.Buffers; using System.IO.Pipelines; using System.Linq; using System.Net.WebSockets; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Connections; using Microsoft.AspNetCore.Http.Connections.Internal; using Microsoft.AspNetCore.Http.Connections.Internal.Transports; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.SignalR.Tests; using Microsoft.AspNetCore.Testing; using Microsoft.Net.Http.Headers; using Xunit; namespace Microsoft.AspNetCore.Http.Connections.Tests { public class WebSocketsTests : VerifiableLoggedTest { // Using nameof with WebSocketMessageType because it is a GACed type and xunit can't serialize it [Theory] [InlineData(nameof(WebSocketMessageType.Text))] [InlineData(nameof(WebSocketMessageType.Binary))] public async Task ReceivedFramesAreWrittenToChannel(string webSocketMessageType) { using (StartVerifiableLog()) { var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default); var connection = new HttpConnectionContext("foo", connectionToken: null, LoggerFactory.CreateLogger("HttpConnectionContext1"), pair.Transport, pair.Application, new()); using (var feature = new TestWebSocketConnectionFeature()) { var ws = new WebSocketsServerTransport(new WebSocketOptions(), connection.Application, connection, LoggerFactory); // Give the server socket to the transport and run it var transport = ws.ProcessSocketAsync(await feature.AcceptAsync()); // Run the client socket var client = feature.Client.ExecuteAndCaptureFramesAsync(); // Send a frame, then close await feature.Client.SendAsync( buffer: new ArraySegment<byte>(Encoding.UTF8.GetBytes("Hello")), messageType: (WebSocketMessageType)Enum.Parse(typeof(WebSocketMessageType), webSocketMessageType), endOfMessage: true, cancellationToken: CancellationToken.None); await feature.Client.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None); var result = await connection.Transport.Input.ReadAsync(); var buffer = result.Buffer; Assert.Equal("Hello", Encoding.UTF8.GetString(buffer.ToArray())); connection.Transport.Input.AdvanceTo(buffer.End); connection.Transport.Output.Complete(); // The transport should finish now await transport; // The connection should close after this, which means the client will get a close frame. var clientSummary = await client; Assert.Equal(WebSocketCloseStatus.NormalClosure, clientSummary.CloseResult.CloseStatus); } } } // Using nameof with WebSocketMessageType because it is a GACed type and xunit can't serialize it [Theory] [InlineData(TransferFormat.Text, nameof(WebSocketMessageType.Text))] [InlineData(TransferFormat.Binary, nameof(WebSocketMessageType.Binary))] public async Task WebSocketTransportSetsMessageTypeBasedOnTransferFormatFeature(TransferFormat transferFormat, string expectedMessageType) { using (StartVerifiableLog()) { var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default); var connection = new HttpConnectionContext("foo", connectionToken: null, LoggerFactory.CreateLogger("HttpConnectionContext1"), pair.Transport, pair.Application, new()); using (var feature = new TestWebSocketConnectionFeature()) { connection.ActiveFormat = transferFormat; var ws = new WebSocketsServerTransport(new WebSocketOptions(), connection.Application, connection, LoggerFactory); // Give the server socket to the transport and run it var transport = ws.ProcessSocketAsync(await feature.AcceptAsync()); // Run the client socket var client = feature.Client.ExecuteAndCaptureFramesAsync(); // Write to the output channel, and then complete it await connection.Transport.Output.WriteAsync(Encoding.UTF8.GetBytes("Hello")); connection.Transport.Output.Complete(); // The client should finish now, as should the server var clientSummary = await client; await feature.Client.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None); await transport; Assert.Equal(1, clientSummary.Received.Count); Assert.True(clientSummary.Received[0].EndOfMessage); Assert.Equal((WebSocketMessageType)Enum.Parse(typeof(WebSocketMessageType), expectedMessageType), clientSummary.Received[0].MessageType); Assert.Equal("Hello", Encoding.UTF8.GetString(clientSummary.Received[0].Buffer)); } } } [Fact] public async Task TransportCommunicatesErrorToApplicationWhenClientDisconnectsAbnormally() { using (StartVerifiableLog()) { var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default); var connection = new HttpConnectionContext("foo", connectionToken: null, LoggerFactory.CreateLogger("HttpConnectionContext1"), pair.Transport, pair.Application, new()); using (var feature = new TestWebSocketConnectionFeature()) { async Task CompleteApplicationAfterTransportCompletes() { try { // Wait until the transport completes so that we can end the application var result = await connection.Transport.Input.ReadAsync(); connection.Transport.Input.AdvanceTo(result.Buffer.End); } catch (Exception ex) { Assert.IsType<WebSocketError>(ex); } finally { // Complete the application so that the connection unwinds without aborting connection.Transport.Output.Complete(); } } var ws = new WebSocketsServerTransport(new WebSocketOptions(), connection.Application, connection, LoggerFactory); // Give the server socket to the transport and run it var transport = ws.ProcessSocketAsync(await feature.AcceptAsync()); // Run the client socket var client = feature.Client.ExecuteAndCaptureFramesAsync(); // When the close frame is received, we complete the application so the send // loop unwinds _ = CompleteApplicationAfterTransportCompletes(); // Terminate the client to server channel with an exception feature.Client.SendAbort(); // Wait for the transport await transport.DefaultTimeout(); await client.DefaultTimeout(); } } } [Fact] public async Task ClientReceivesInternalServerErrorWhenTheApplicationFails() { using (StartVerifiableLog()) { var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default); var connection = new HttpConnectionContext("foo", connectionToken: null, LoggerFactory.CreateLogger(nameof(HttpConnectionContext)), pair.Transport, pair.Application, new()); using (var feature = new TestWebSocketConnectionFeature()) { var ws = new WebSocketsServerTransport(new WebSocketOptions(), connection.Application, connection, LoggerFactory); // Give the server socket to the transport and run it var transport = ws.ProcessSocketAsync(await feature.AcceptAsync()); // Run the client socket var client = feature.Client.ExecuteAndCaptureFramesAsync(); // Fail in the app connection.Transport.Output.Complete(new InvalidOperationException("Catastrophic failure.")); var clientSummary = await client.DefaultTimeout(); Assert.Equal(WebSocketCloseStatus.InternalServerError, clientSummary.CloseResult.CloseStatus); // Close from the client await feature.Client.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None); await transport.DefaultTimeout(); } } } [Fact] public async Task TransportClosesOnCloseTimeoutIfClientDoesNotSendCloseFrame() { using (StartVerifiableLog()) { var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default); var connection = new HttpConnectionContext("foo", connectionToken: null, LoggerFactory.CreateLogger(nameof(HttpConnectionContext)), pair.Transport, pair.Application, new()); using (var feature = new TestWebSocketConnectionFeature()) { var options = new WebSocketOptions() { CloseTimeout = TimeSpan.FromSeconds(1) }; var ws = new WebSocketsServerTransport(options, connection.Application, connection, LoggerFactory); var serverSocket = await feature.AcceptAsync(); // Give the server socket to the transport and run it var transport = ws.ProcessSocketAsync(serverSocket); // End the app connection.Transport.Output.Complete(); await transport.DefaultTimeout(TimeSpan.FromSeconds(10)); // Now we're closed Assert.Equal(WebSocketState.Aborted, serverSocket.State); serverSocket.Dispose(); } } } [Fact] public async Task TransportFailsOnTimeoutWithErrorWhenApplicationFailsAndClientDoesNotSendCloseFrame() { using (StartVerifiableLog()) { var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default); var connection = new HttpConnectionContext("foo", connectionToken: null, LoggerFactory.CreateLogger(nameof(HttpConnectionContext)), pair.Transport, pair.Application, new()); using (var feature = new TestWebSocketConnectionFeature()) { var options = new WebSocketOptions { CloseTimeout = TimeSpan.FromSeconds(1) }; var ws = new WebSocketsServerTransport(options, connection.Application, connection, LoggerFactory); var serverSocket = await feature.AcceptAsync(); // Give the server socket to the transport and run it var transport = ws.ProcessSocketAsync(serverSocket); // Run the client socket var client = feature.Client.ExecuteAndCaptureFramesAsync(); // fail the client to server channel connection.Transport.Output.Complete(new Exception()); await transport.DefaultTimeout(); Assert.Equal(WebSocketState.Aborted, serverSocket.State); } } } [Fact] public async Task ServerGracefullyClosesWhenApplicationEndsThenClientSendsCloseFrame() { using (StartVerifiableLog()) { var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default); var connection = new HttpConnectionContext("foo", connectionToken: null, LoggerFactory.CreateLogger(nameof(HttpConnectionContext)), pair.Transport, pair.Application, new()); using (var feature = new TestWebSocketConnectionFeature()) { var options = new WebSocketOptions { // We want to verify behavior without timeout affecting it CloseTimeout = TimeSpan.FromSeconds(20) }; var ws = new WebSocketsServerTransport(options, connection.Application, connection, LoggerFactory); var serverSocket = await feature.AcceptAsync(); // Give the server socket to the transport and run it var transport = ws.ProcessSocketAsync(serverSocket); // Run the client socket var client = feature.Client.ExecuteAndCaptureFramesAsync(); // close the client to server channel connection.Transport.Output.Complete(); _ = await client.DefaultTimeout(); await feature.Client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None).DefaultTimeout(); await transport.DefaultTimeout(); Assert.Equal(WebSocketCloseStatus.NormalClosure, serverSocket.CloseStatus); } } } [Fact] public async Task ServerGracefullyClosesWhenClientSendsCloseFrameThenApplicationEnds() { using (StartVerifiableLog()) { var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default); var connection = new HttpConnectionContext("foo", connectionToken: null, LoggerFactory.CreateLogger(nameof(HttpConnectionContext)), pair.Transport, pair.Application, new()); using (var feature = new TestWebSocketConnectionFeature()) { var options = new WebSocketOptions { // We want to verify behavior without timeout affecting it CloseTimeout = TimeSpan.FromSeconds(20) }; var ws = new WebSocketsServerTransport(options, connection.Application, connection, LoggerFactory); var serverSocket = await feature.AcceptAsync(); // Give the server socket to the transport and run it var transport = ws.ProcessSocketAsync(serverSocket); // Run the client socket var client = feature.Client.ExecuteAndCaptureFramesAsync(); await feature.Client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None).DefaultTimeout(); // close the client to server channel connection.Transport.Output.Complete(); _ = await client.DefaultTimeout(); await transport.DefaultTimeout(); Assert.Equal(WebSocketCloseStatus.NormalClosure, serverSocket.CloseStatus); } } } [Fact] public async Task SubProtocolSelectorIsUsedToSelectSubProtocol() { const string ExpectedSubProtocol = "expected"; var providedSubProtocols = new[] {"provided1", "provided2"}; using (StartVerifiableLog()) { var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default); var connection = new HttpConnectionContext("foo", connectionToken: null, LoggerFactory.CreateLogger(nameof(HttpConnectionContext)), pair.Transport, pair.Application, new()); using (var feature = new TestWebSocketConnectionFeature()) { var options = new WebSocketOptions { // We want to verify behavior without timeout affecting it CloseTimeout = TimeSpan.FromSeconds(20), SubProtocolSelector = protocols => { Assert.Equal(providedSubProtocols, protocols.ToArray()); return ExpectedSubProtocol; }, }; var ws = new WebSocketsServerTransport(options, connection.Application, connection, LoggerFactory); // Create an HttpContext var context = new DefaultHttpContext(); context.Request.Headers.Add(HeaderNames.WebSocketSubProtocols, providedSubProtocols.ToArray()); context.Features.Set<IHttpWebSocketFeature>(feature); var transport = ws.ProcessRequestAsync(context, CancellationToken.None); await feature.Accepted.OrThrowIfOtherFails(transport); // Assert the feature got the right subprotocol Assert.Equal(ExpectedSubProtocol, feature.SubProtocol); // Run the client socket var client = feature.Client.ExecuteAndCaptureFramesAsync(); await feature.Client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None).DefaultTimeout(); // close the client to server channel connection.Transport.Output.Complete(); _ = await client.DefaultTimeout(); await transport.DefaultTimeout(); } } } [Fact] public async Task MultiSegmentSendWillNotSendEmptyEndOfMessageFrame() { using (var feature = new TestWebSocketConnectionFeature()) { var serverSocket = await feature.AcceptAsync(); var sequence = ReadOnlySequenceFactory.CreateSegments(new byte[] { 1 }, new byte[] { 15 }); Assert.False(sequence.IsSingleSegment); await serverSocket.SendAsync(sequence, WebSocketMessageType.Text); // Run the client socket var client = feature.Client.ExecuteAndCaptureFramesAsync(); await serverSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", default); var messages = await client.DefaultTimeout(); Assert.Equal(2, messages.Received.Count); // First message: 1 byte, endOfMessage false Assert.Single(messages.Received[0].Buffer); Assert.Equal(1, messages.Received[0].Buffer[0]); Assert.False(messages.Received[0].EndOfMessage); // Second message: 1 byte, endOfMessage true Assert.Single(messages.Received[1].Buffer); Assert.Equal(15, messages.Received[1].Buffer[0]); Assert.True(messages.Received[1].EndOfMessage); } } } }
using System; using System.Collections.Concurrent; using System.Data.Common; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using NServiceBus.Persistence.Sql.ScriptBuilder; using NServiceBus.Unicast.Subscriptions; using NServiceBus.Unicast.Subscriptions.MessageDrivenSubscriptions; using NUnit.Framework; using Particular.Approvals; public abstract class SubscriptionPersisterTests { BuildSqlDialect sqlDialect; string schema; Func<string, DbConnection> dbConnection; protected abstract Func<string, DbConnection> GetConnection(); protected virtual bool SupportsSchemas() => true; string tablePrefix; public SubscriptionPersisterTests(BuildSqlDialect sqlDialect, string schema) { this.sqlDialect = sqlDialect; this.schema = schema; } SubscriptionPersister Setup(string theSchema) { dbConnection = GetConnection(); tablePrefix = GetTablePrefix(); var persister = new SubscriptionPersister( connectionManager: new ConnectionManager(() => dbConnection(theSchema)), tablePrefix: $"{tablePrefix}_", sqlDialect: sqlDialect.Convert(theSchema), cacheFor: TimeSpan.FromSeconds(10) ); using (var connection = dbConnection(theSchema)) { connection.Open(); connection.ExecuteCommand(SubscriptionScriptBuilder.BuildDropScript(sqlDialect), tablePrefix, schema: theSchema); connection.ExecuteCommand(SubscriptionScriptBuilder.BuildCreateScript(sqlDialect), tablePrefix, schema: theSchema); } return persister; } protected virtual string GetTablePrefix() { return nameof(SubscriptionPersisterTests); } [TearDown] public void TearDown() { using (var connection = dbConnection(null)) { connection.Open(); connection.ExecuteCommand(SubscriptionScriptBuilder.BuildDropScript(sqlDialect), tablePrefix, schema: null); } using (var connection = dbConnection(schema)) { connection.Open(); connection.ExecuteCommand(SubscriptionScriptBuilder.BuildDropScript(sqlDialect), tablePrefix, schema: schema); } } [Test] public void ExecuteCreateTwice() { using (var connection = dbConnection(schema)) { connection.Open(); connection.ExecuteCommand(SubscriptionScriptBuilder.BuildCreateScript(sqlDialect), GetTablePrefix(), schema: schema); connection.ExecuteCommand(SubscriptionScriptBuilder.BuildCreateScript(sqlDialect), GetTablePrefix(), schema: schema); } } [Test] public void Subscribe() { var persister = Setup(schema); var type1 = new MessageType("type1", new Version(0, 0, 0, 0)); var type2 = new MessageType("type2", new Version(0, 0, 0, 0)); persister.Subscribe(new Subscriber("e@machine1", "endpoint"), type1, null).Await(); persister.Subscribe(new Subscriber("e@machine1", "endpoint"), type2, null).Await(); persister.Subscribe(new Subscriber("e@machine2", "endpoint"), type1, null).Await(); persister.Subscribe(new Subscriber("e@machine2", "endpoint"), type2, null).Await(); persister.Subscribe(new Subscriber("e@machine3", null), type2, null).Await(); var result = persister.GetSubscribers(type1,type2).Result.OrderBy(s => s.TransportAddress); Assert.IsNotEmpty(result); Approver.Verify(result); } [Test] public void Subscribe_multiple_with_no_endpoint() { var persister = Setup(schema); var type = new MessageType("type", new Version(0, 0, 0, 0)); persister.Subscribe(new Subscriber("e@machine1", null), type, null).Await(); // Ensuring that MSSQL's handling of = null vs. is null doesn't cause a PK violation here persister.Subscribe(new Subscriber("e@machine1", null), type, null).Await(); var result = persister.GetSubscribers(type).Result.OrderBy(s => s.TransportAddress); Assert.AreEqual(1, result.Count()); } [Test] public async Task Cached_get_should_be_faster() { var persister = Setup(schema); var type = new MessageType("type1", new Version(0, 0, 0, 0)); persister.Subscribe(new Subscriber("e@machine1", "endpoint"), type, null).Await(); var first = Stopwatch.StartNew(); var subscribersFirst = await persister.GetSubscribers(type) .ConfigureAwait(false); var firstTime = first.ElapsedMilliseconds; var second = Stopwatch.StartNew(); var subscribersSecond = await persister.GetSubscribers(type) .ConfigureAwait(false); var secondTime = second.ElapsedMilliseconds; Assert.IsTrue(secondTime * 1000 < firstTime); Assert.AreEqual(subscribersFirst.Count(), subscribersSecond.Count()); } [Test] public void Should_be_cached() { var persister = Setup(schema); var type = new MessageType("type1", new Version(0, 0, 0, 0)); persister.Subscribe(new Subscriber("e@machine1", "endpoint"), type, null).Await(); persister.GetSubscribers(type).Await(); VerifyCache(persister.Cache); } static void VerifyCache(ConcurrentDictionary<string, SubscriptionPersister.CacheItem> cache) { var items = cache .OrderBy(_ => _.Key) .ToDictionary(_ => _.Key, elementSelector: item => { return item.Value.Subscribers.Result .OrderBy(_ => _.Endpoint) .ThenBy(_ => _.TransportAddress); }); Approver.Verify(items); } [Test] public void Subscribe_with_same_type_should_clear_cache() { var persister = Setup(schema); var matchingType = new MessageType("matchingType", new Version(0, 0, 0, 0)); persister.Subscribe(new Subscriber("e@machine1", "endpoint"), matchingType, null).Await(); persister.GetSubscribers(matchingType).Await(); persister.Subscribe(new Subscriber("e@machine1", "endpoint"), matchingType, null).Await(); VerifyCache(persister.Cache); } [Test] public void Unsubscribe_with_same_type_should_clear_cache() { var persister = Setup(schema); var matchingType = new MessageType("matchingType", new Version(0, 0, 0, 0)); persister.Subscribe(new Subscriber("e@machine1", "endpoint"), matchingType, null).Await(); persister.GetSubscribers(matchingType).Await(); persister.Unsubscribe(new Subscriber("e@machine1", "endpoint"), matchingType, null).Await(); VerifyCache(persister.Cache); } [Test] public void Unsubscribe_with_part_type_should_partially_clear_cache() { var persister = Setup(schema); var version = new Version(0, 0, 0, 0); var type1 = new MessageType("type1", version); var type2 = new MessageType("type2", version); var type3 = new MessageType("type3", version); persister.Subscribe(new Subscriber("e@machine1", "endpoint"), type1, null).Await(); persister.Subscribe(new Subscriber("e@machine1", "endpoint"), type2, null).Await(); persister.Subscribe(new Subscriber("e@machine1", "endpoint"), type3, null).Await(); persister.GetSubscribers(type1).Await(); persister.GetSubscribers(type2).Await(); persister.GetSubscribers(type3).Await(); persister.GetSubscribers(type1, type2).Await(); persister.GetSubscribers(type2, type3).Await(); persister.GetSubscribers(type1, type3).Await(); persister.GetSubscribers(type1, type2, type3).Await(); persister.Unsubscribe(new Subscriber("e@machine1", "endpoint"), type2, null).Await(); VerifyCache(persister.Cache); } [Test] public void Subscribe_duplicate_add() { var persister = Setup(schema); var type1 = new MessageType("type1", new Version(0, 0, 0, 0)); var type2 = new MessageType("type2", new Version(0, 0, 0, 0)); persister.Subscribe(new Subscriber("e@machine1", "endpoint"), type1, null).Await(); persister.Subscribe(new Subscriber("e@machine1", "endpoint"), type2, null).Await(); persister.Subscribe(new Subscriber("e@machine1", "endpoint"), type1, null).Await(); persister.Subscribe(new Subscriber("e@machine1", "endpoint"), type2, null).Await(); var result = persister.GetSubscribers(type1, type2).Result.ToList(); Assert.IsNotEmpty(result); Approver.Verify(result); } [Test] public void Subscribe_version_migration() { var persister = Setup(schema); var type1 = new MessageType("type1", new Version(0, 0, 0, 0)); //NSB 5.x: endpoint is null persister.Subscribe(new Subscriber("e@machine1", null), type1, null).Await(); //NSB 6.x: same subscriber now mentions endpoint persister.Subscribe(new Subscriber("e@machine1", "endpoint"), type1, null).Await(); var result = persister.GetSubscribers(type1).Result.ToList(); Assert.IsNotEmpty(result); Approver.Verify(result); } [Test] public void Subscribe_different_endpoint_name() { var persister = Setup(schema); var type1 = new MessageType("type1", new Version(0, 0, 0, 0)); //NSB 6.x: old endpoint value persister.Subscribe(new Subscriber("e@machine1", "e1"), type1, null).Await(); //NSB 6.x: same address, new endpoint value persister.Subscribe(new Subscriber("e@machine1", "e2"), type1, null).Await(); var result = persister.GetSubscribers(type1).Result.ToList(); Assert.IsNotEmpty(result); Approver.Verify(result); } [Test] public void Subscribe_should_not_downgrade() { var persister = Setup(schema); var type1 = new MessageType("type1", new Version(0, 0, 0, 0)); //NSB 6.x: subscriber contains endpoint persister.Subscribe(new Subscriber("e@machine1", "endpoint"), type1, null).Await(); //NSB 5.x: endpoint is null, don't want to remove endpoint value from table though persister.Subscribe(new Subscriber("e@machine1", null), type1, null).Await(); var result = persister.GetSubscribers(type1).Result.ToList(); Assert.IsNotEmpty(result); Approver.Verify(result); } [Test] public void Unsubscribe() { var persister = Setup(schema); var message2 = new MessageType("type2", new Version(0, 0)); var message1 = new MessageType("type1", new Version(0, 0)); var address1 = new Subscriber("address1@machine1", "endpoint"); persister.Subscribe(address1, message2, null).Await(); persister.Subscribe(address1, message1, null).Await(); var address2 = new Subscriber("address2@machine2", "endpoint"); persister.Subscribe(address2, message2, null).Await(); persister.Subscribe(address2, message1, null).Await(); persister.Unsubscribe(address1, message2, null).Await(); var result = persister.GetSubscribers(message2, message1).Result.ToList(); Assert.IsNotEmpty(result); Approver.Verify(result); } [Test] public void UseConfiguredSchema() { if (!SupportsSchemas()) { Assert.Ignore(); } var defaultSchemaPersister = Setup(null); var schemaPersister = Setup(schema); var type1 = new MessageType("type1", new Version(0, 0, 0, 0)); defaultSchemaPersister.Subscribe(new Subscriber("e@machine1", "endpoint"), type1, null).Await(); var result = schemaPersister.GetSubscribers(type1).Result.OrderBy(s => s.TransportAddress); Assert.IsEmpty(result); } }
using Microsoft.TeamFoundation.Build.WebApi; using Microsoft.TeamFoundation.DistributedTask.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.Build { public sealed class BuildJobExtension : AgentService, IJobExtension { public Type ExtensionType => typeof(IJobExtension); public string HostType => "build"; public IStep PrepareStep { get; private set; } public IStep FinallyStep { get; private set; } private ServiceEndpoint SourceEndpoint { set; get; } private ISourceProvider SourceProvider { set; get; } public BuildJobExtension() { PrepareStep = new JobExtensionRunner( runAsync: PrepareAsync, alwaysRun: false, continueOnError: false, critical: true, displayName: StringUtil.Loc("GetSources"), enabled: true, @finally: false); FinallyStep = new JobExtensionRunner( runAsync: FinallyAsync, alwaysRun: false, continueOnError: false, critical: false, displayName: StringUtil.Loc("Cleanup"), enabled: true, @finally: true); } // 1. use source provide to solve path, if solved result is rooted, return full path. // 2. prefix default path root (build.sourcesDirectory), if result is rooted, return full path. public string GetRootedPath(IExecutionContext context, string path) { string rootedPath = null; if (SourceProvider != null && SourceEndpoint != null) { path = SourceProvider.GetLocalPath(context, SourceEndpoint, path) ?? string.Empty; Trace.Info($"Build JobExtension resolving path use source provide: {path}"); if (!string.IsNullOrEmpty(path) && path.IndexOfAny(Path.GetInvalidPathChars()) < 0 && Path.IsPathRooted(path)) { try { rootedPath = Path.GetFullPath(path); Trace.Info($"Path resolved by source provider is a rooted path, return absolute path: {rootedPath}"); return rootedPath; } catch (Exception ex) { Trace.Info($"Path resolved by source provider is a rooted path, but it is not a full qualified path: {path}"); Trace.Error(ex); } } } string defaultPathRoot = context.Variables.Get(Constants.Variables.Build.SourcesDirectory) ?? string.Empty; Trace.Info($"The Default Path Root of Build JobExtension is build.sourcesDirectory: {defaultPathRoot}"); if (defaultPathRoot != null && defaultPathRoot.IndexOfAny(Path.GetInvalidPathChars()) < 0 && path != null && path.IndexOfAny(Path.GetInvalidPathChars()) < 0) { path = Path.Combine(defaultPathRoot, path); Trace.Info($"After prefix Default Path Root provide by JobExtension: {path}"); if (Path.IsPathRooted(path)) { try { rootedPath = Path.GetFullPath(path); Trace.Info($"Return absolute path after prefix DefaultPathRoot: {rootedPath}"); return rootedPath; } catch (Exception ex) { Trace.Error(ex); Trace.Info($"After prefix Default Path Root provide by JobExtension, the Path is a rooted path, but it is not full qualified, return the path: {path}."); return path; } } } return rootedPath; } public void ConvertLocalPath(IExecutionContext context, string localPath, out string repoName, out string sourcePath) { repoName = ""; // If no repo was found, send back an empty repo with original path. sourcePath = localPath; if (!string.IsNullOrEmpty(localPath) && File.Exists(localPath) && SourceEndpoint != null && SourceProvider != null) { // If we found a repo, calculate the relative path to the file repoName = SourceEndpoint.Name; sourcePath = IOUtil.MakeRelative(localPath, context.Variables.Get(Constants.Variables.Build.SourcesDirectory)); } } private async Task PrepareAsync() { // Validate args. Trace.Entering(); ArgUtil.NotNull(PrepareStep, nameof(PrepareStep)); ArgUtil.NotNull(PrepareStep.ExecutionContext, nameof(PrepareStep.ExecutionContext)); IExecutionContext executionContext = PrepareStep.ExecutionContext; var directoryManager = HostContext.GetService<IBuildDirectoryManager>(); // This flag can be false for jobs like cleanup artifacts. // If syncSources = false, we will not set source related build variable, not create build folder, not sync source. bool syncSources = executionContext.Variables.Build_SyncSources ?? true; if (!syncSources) { Trace.Info($"{Constants.Variables.Build.SyncSources} = false, we will not set source related build variable, not create build folder and not sync source"); return; } // Get the repo endpoint and source provider. if (!TrySetPrimaryEndpointAndProviderInfo(executionContext)) { throw new Exception(StringUtil.Loc("SupportedRepositoryEndpointNotFound")); } executionContext.Debug($"Primary repository: {SourceEndpoint.Name}. repository type: {SourceProvider.RepositoryType}"); // Prepare the build directory. executionContext.Debug("Preparing build directory."); TrackingConfig trackingConfig = directoryManager.PrepareDirectory( executionContext, SourceEndpoint, SourceProvider); executionContext.Debug("Set build variables."); string _workDirectory = IOUtil.GetWorkPath(HostContext); executionContext.Variables.Set(Constants.Variables.Agent.BuildDirectory, Path.Combine(_workDirectory, trackingConfig.BuildDirectory)); executionContext.Variables.Set(Constants.Variables.System.ArtifactsDirectory, Path.Combine(_workDirectory, trackingConfig.ArtifactsDirectory)); executionContext.Variables.Set(Constants.Variables.System.DefaultWorkingDirectory, Path.Combine(_workDirectory, trackingConfig.SourcesDirectory)); executionContext.Variables.Set(Constants.Variables.Common.TestResultsDirectory, Path.Combine(_workDirectory, trackingConfig.TestResultsDirectory)); executionContext.Variables.Set(Constants.Variables.Build.BinariesDirectory, Path.Combine(_workDirectory, trackingConfig.BuildDirectory, Constants.Build.Path.BinariesDirectory)); executionContext.Variables.Set(Constants.Variables.Build.SourcesDirectory, Path.Combine(_workDirectory, trackingConfig.SourcesDirectory)); executionContext.Variables.Set(Constants.Variables.Build.StagingDirectory, Path.Combine(_workDirectory, trackingConfig.ArtifactsDirectory)); executionContext.Variables.Set(Constants.Variables.Build.ArtifactStagingDirectory, Path.Combine(_workDirectory, trackingConfig.ArtifactsDirectory)); executionContext.Variables.Set(Constants.Variables.Build.RepoId, SourceEndpoint.Id.ToString("D")); // TODO: This is getting set to the empty guid. executionContext.Variables.Set(Constants.Variables.Build.RepoName, SourceEndpoint.Name); executionContext.Variables.Set(Constants.Variables.Build.RepoProvider, SourceEndpoint.Type); executionContext.Variables.Set(Constants.Variables.Build.RepoUri, SourceEndpoint.Url?.AbsoluteUri); executionContext.Variables.Set(Constants.Variables.Build.RepoLocalPath, Path.Combine(_workDirectory, trackingConfig.SourcesDirectory)); string checkoutSubmoduleText; if (SourceEndpoint.Data.TryGetValue(WellKnownEndpointData.CheckoutSubmodules, out checkoutSubmoduleText)) { executionContext.Variables.Set(Constants.Variables.Build.RepoGitSubmoduleCheckout, checkoutSubmoduleText); } // overwrite primary repository's clean value if build.repository.clean is sent from server. this is used by tfvc gated check-in bool? repoClean = executionContext.Variables.GetBoolean(Constants.Variables.Build.RepoClean); if (repoClean != null) { SourceEndpoint.Data[WellKnownEndpointData.Clean] = repoClean.Value.ToString(); } else { string cleanRepoText; if (SourceEndpoint.Data.TryGetValue(WellKnownEndpointData.Clean, out cleanRepoText)) { executionContext.Variables.Set(Constants.Variables.Build.RepoClean, cleanRepoText); } } executionContext.Debug($"Sync source for endpoint: {SourceEndpoint.Name}"); await SourceProvider.GetSourceAsync(executionContext, SourceEndpoint, executionContext.CancellationToken); } private async Task FinallyAsync() { // Validate args. Trace.Entering(); ArgUtil.NotNull(FinallyStep, nameof(FinallyStep)); ArgUtil.NotNull(FinallyStep.ExecutionContext, nameof(FinallyStep.ExecutionContext)); IExecutionContext executionContext = FinallyStep.ExecutionContext; // If syncSources = false, we will not reset repository. bool syncSources = executionContext.Variables.Build_SyncSources ?? true; if (!syncSources) { Trace.Verbose($"{Constants.Variables.Build.SyncSources} = false, we will not run post job cleanup for this repository"); return; } await SourceProvider.PostJobCleanupAsync(executionContext, SourceEndpoint); } private bool TrySetPrimaryEndpointAndProviderInfo(IExecutionContext executionContext) { // Return the first service endpoint that contains a supported source provider. Trace.Entering(); var extensionManager = HostContext.GetService<IExtensionManager>(); List<ISourceProvider> sourceProviders = extensionManager.GetExtensions<ISourceProvider>(); foreach (ServiceEndpoint ep in executionContext.Endpoints) { SourceProvider = sourceProviders .FirstOrDefault(x => string.Equals(x.RepositoryType, ep.Type, StringComparison.OrdinalIgnoreCase)); if (SourceProvider != null) { SourceEndpoint = ep; return true; } } return false; } } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; using System.Drawing; namespace Microsoft.MultiverseInterfaceStudio.FrameXml.Serialization { public class PropertyBag { #region inner dictionary implementation private SortedDictionary<string, object> dictionary = new SortedDictionary<string, object>(); private LayoutFrameType owner = null; public PropertyBag(LayoutFrameType owner) { this.owner = owner; } #endregion #region public interface public object this[string name] { get { if (dictionary.ContainsKey(name)) return dictionary[name]; if (!IsSerializing) { if (owner != null && owner.InheritedObject != null) return owner.InheritedObject.Properties[name]; } return owner.GetDefaultValue(name); } set { // TODO: solve issue: inherited property value cannot be set back to default if (IsEmpty(value) || (value.Equals(owner.GetDefaultValue(name)))) dictionary.Remove(name); else dictionary[name] = value; } } public T GetValue<T>(string name) { object value = this[name]; if (value == null) value = default(T); return (T)value; } public bool HasValue(string name) { return dictionary.ContainsKey(name) && !IsEmpty(dictionary[name]); } public bool HasInheritedValue(string name) { if (owner != null) { LayoutFrameType layoutFrame = owner.InheritedObject; while (layoutFrame != null) { if (layoutFrame.Properties.HasValue(name)) return true; layoutFrame = layoutFrame.InheritedObject; } } return false; } #endregion #region array handling public T[] GetArray<T>(string name) { return this.HasValue(name) ? new T[] { this.GetValue<T>(name) } : new T[] { }; } public void SetArray<T>(string name, T[] values) { if (values != null && values.Length > 0) this[name] = values[0]; else this.Remove(name); } #endregion #region list handling - obsolete //public List<T> GetList<T>(string name) //{ // List<T> value; // if (!dictionary.ContainsKey(name)) // { // value = new List<T>(); // dictionary.Add(name, value); // } // else // { // value = dictionary[name] as List<T>; // } // if (value.Count > 0) // return value; // if (!IsSerializing) // { // if (owner != null && owner.InheritedObject != null) // return owner.InheritedObject.Properties.GetList<T>(name); // } // return value; //} //public void SetList<T>(string name, List<T> value) //{ // if (value == null) // value = new List<T>(); // dictionary[name] = value; //} #endregion #region helper methods private bool IsEmpty(object value) { if (value == null) return true; if (value is string) return String.IsNullOrEmpty(value as string); if (value is IList) return (value as IList).Count == 0; if (value is Color) return ((Color)value).IsEmpty; return false; } private bool IsSerializing { get { FrameXmlDesignerLoader activeDesignerLoader = FrameXmlDesignerLoader.ActiveDesignerLoader; if (activeDesignerLoader == null) return true; return activeDesignerLoader.IsSerializing; } } #endregion internal void Remove(string name) { dictionary.Remove(name); } } }
//CPOL, 2010, Stan Kirk //MIT, 2015-present, EngineKit using System; using System.IO; using System.Net; namespace SharpConnect { #if DEBUG static class dbugLOG { //object that will be used to lock the listOfDataHolders static readonly object lockerForList = new object(); //If you make this true, then the IncomingDataPreparer will not write to // a List<T>, and you will not see the printout of the data at the end //of the log. public static readonly bool runLongTest = false; //If you make this true, then info about threads will print to log. public static readonly bool watchThreads = false; //If you make this true, then the above "watch-" variables will print to //both Console and log, instead of just to log. I suggest only using this if //you are having a problem with an application that is crashing. public static readonly bool consoleWatch = false; //static List<DataHolder> dbugDataHolderList; //This is for logging during testing. //You can change the path in the TestFileWriter class if you need to. //If you make this a positive value, it will simulate some delay on the //receive/send SAEA object after doing a receive operation. //That would be where you would do some work on the received data, //before responding to the client. //This is in milliseconds. So a value of 1000 = 1 second delay. public static readonly Int32 msDelayAfterGettingMessage = -1; public static bool enableDebugLog = false; //If this is true, then info about which method the program is in //will print to log. public static bool watchProgramFlow = true; //If you make this true, then connect/disconnect info will print to log. public static readonly bool watchConnectAndDisconnect = true; //If you make this true, then data will print to log. //public static readonly bool watchData = true; static dbugTestFileWriter testWriter; // To keep a record of maximum number of simultaneous connections // that occur while the server is running. This can be limited by operating // system and hardware. It will not be higher than the value that you set // for maxNumberOfConnections. public static Int32 maxSimultaneousClientsThatWereConnected = 0; //These strings are just for console interaction. public const string checkString = "C"; public const string closeString = "Z"; public const string wpf = "T"; public const string wpfNo = "F"; public static string wpfTrueString = ""; public static string wpfFalseString = ""; static object lockStart = new object(); static bool isInit = false; internal static void StartLog() { //lock (lockStart) //{ // if (!isInit) // { // //init once // BuildStringsForServerConsole(); // testWriter = new dbugTestFileWriter(); // isInit = true; // } //} } ///// <summary> ///// /Display thread info.,Use this one in method where AcceptOpUserToken is available. ///// </summary> ///// <param name="methodName"></param> ///// <param name="acceptToken"></param> //public static void dbugDealWithThreadsForTesting(SocketServer socketServer, string methodName, dbugAcceptOpUserToken acceptToken) //{ // StringBuilder sb = new StringBuilder(); // string hString = hString = ". Socket handle " + acceptToken.dbugSocketHandleNumber; // sb.Append(" In " + methodName + ", acceptToken id " + acceptToken.dbugTokenId + ". Thread id " + Thread.CurrentThread.ManagedThreadId + hString + "."); // sb.Append(socketServer.dbugDealWithNewThreads()); // dbugLOG.WriteLine(sb.ToString()); //} [System.Diagnostics.Conditional("DEBUG")] public static void dbugLog(string msg) { //if (dbugLOG.enableDebugLog && dbugLOG.watchProgramFlow) //for testing //{ // dbugLOG.WriteLine(msg); //} } internal static void WriteLine(string str) { //testWriter.WriteLine(str); } static void BuildStringsForServerConsole() { //if (dbugLOG.enableDebugLog) //{ // StringBuilder sb = new StringBuilder(); // // Make the string to write. // sb.Append("\r\n"); // sb.Append("\r\n"); // sb.Append("To take any of the following actions type the \r\ncorresponding letter below and press Enter.\r\n"); // sb.Append(closeString); // sb.Append(") to close the program\r\n"); // sb.Append(checkString); // sb.Append(") to check current status\r\n"); // string tempString = sb.ToString(); // sb.Length = 0; // // string when watchProgramFlow == true // sb.Append(wpfNo); // sb.Append(") to quit writing program flow. (ProgramFlow is being logged now.)\r\n"); // wpfTrueString = tempString + sb.ToString(); // sb.Length = 0; // // string when watchProgramFlow == false // sb.Append(wpf); // sb.Append(") to start writing program flow. (ProgramFlow is NOT being logged.)\r\n"); // wpfFalseString = tempString + sb.ToString(); //} } internal static void WriteSetupInfo(IPEndPoint localEndPoint) { //Console.WriteLine("The following options can be changed in Program.cs file."); //Console.WriteLine("server buffer size = " + testBufferSize); //Console.WriteLine("max connections = " + maxNumberOfConnections); //Console.WriteLine("backlog variable value = " + backlog); //Console.WriteLine("watchProgramFlow = " + dbugWatchProgramFlow); //Console.WriteLine("watchConnectAndDisconnect = " + watchConnectAndDisconnect); //Console.WriteLine("watchThreads = " + dbugWatchThreads); //Console.WriteLine("msDelayAfterGettingMessage = " + dbugMsDelayAfterGettingMessage); //if (dbugLOG.enableDebugLog) //{ // Console.WriteLine(); // Console.WriteLine(); // Console.WriteLine("local endpoint = " + IPAddress.Parse(((IPEndPoint)localEndPoint).Address.ToString()) + ": " + ((IPEndPoint)localEndPoint).Port.ToString()); // Console.WriteLine("server machine name = " + Environment.MachineName); // Console.WriteLine(); // Console.WriteLine("Client and server should be on separate machines for best results."); // Console.WriteLine("And your firewalls on both client and server will need to allow the connection."); // Console.WriteLine(); //} } static void WriteLogData() { //if ((watchData) && (runLongTest)) //{ // Program.testWriter.WriteLine("\r\n\r\nData from DataHolders in listOfDataHolders follows:\r\n"); // int listCount = dbugDataHolderList.Count; // for (int i = 0; i < listCount; i++) // { // //DataHolder dataHolder = dbugDataHolderList[i]; // //Program.testWriter.WriteLine(IPAddress.Parse(((IPEndPoint)dataHolder.remoteEndpoint).Address.ToString()) + ": " + // // ((IPEndPoint)dataHolder.remoteEndpoint).Port.ToString() + ", " + dataHolder.receivedTransMissionId + ", " + // // Encoding.ASCII.GetString(dataHolder.dataMessageReceived)); // } //} //testWriter.WriteLine("\r\nHighest # of simultaneous connections was " + maxSimultaneousClientsThatWereConnected); //testWriter.WriteLine("# of transmissions received was " + (mainTransMissionId - startingTid)); } } #endif #if DEBUG static class dbugConsole { static LogWriter _logWriter; static dbugConsole() { //set _logWriter = new LogWriter(null);//not write anything to disk //logWriter = new LogWriter("d:\\WImageTest\\log1.txt"); } [System.Diagnostics.Conditional("DEBUG")] public static void WriteLine(string str) { _logWriter.Write(str); _logWriter.Write("\r\n"); } [System.Diagnostics.Conditional("DEBUG")] public static void Write(string str) { _logWriter.Write(str); } class LogWriter : IDisposable { string filename; FileStream fs; StreamWriter writer; public LogWriter(string logFilename) { filename = logFilename; if (!string.IsNullOrEmpty(logFilename)) { fs = new FileStream(logFilename, FileMode.Create); writer = new StreamWriter(fs); } } public void Dispose() { if (writer != null) { writer.Flush(); writer.Dispose(); writer = null; } if (fs != null) { fs.Dispose(); fs = null; } } public void Write(string data) { if (writer != null) { writer.Write(data); writer.Flush(); } } } } #endif //-------------------------------------------------- }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void AlignRightByte0() { var test = new ImmBinaryOpTest__AlignRightByte0(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmBinaryOpTest__AlignRightByte0 { private struct TestStruct { public Vector128<Byte> _fld1; public Vector128<Byte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); return testStruct; } public void RunStructFldScenario(ImmBinaryOpTest__AlignRightByte0 testClass) { var result = Ssse3.AlignRight(_fld1, _fld2, 0); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector128<Byte> _clsVar1; private static Vector128<Byte> _clsVar2; private Vector128<Byte> _fld1; private Vector128<Byte> _fld2; private SimpleBinaryOpTest__DataTable<Byte, Byte, Byte> _dataTable; static ImmBinaryOpTest__AlignRightByte0() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); } public ImmBinaryOpTest__AlignRightByte0() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } _dataTable = new SimpleBinaryOpTest__DataTable<Byte, Byte, Byte>(_data1, _data2, new Byte[RetElementCount], LargestVectorSize); } public bool IsSupported => Ssse3.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Ssse3.AlignRight( Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr), 0 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Ssse3.AlignRight( Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)), 0 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Ssse3.AlignRight( Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)), 0 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Ssse3).GetMethod(nameof(Ssse3.AlignRight), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr), (byte)0 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Ssse3).GetMethod(nameof(Ssse3.AlignRight), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)), (byte)0 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Ssse3).GetMethod(nameof(Ssse3.AlignRight), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)), (byte)0 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Ssse3.AlignRight( _clsVar1, _clsVar2, 0 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr); var result = Ssse3.AlignRight(left, right, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)); var result = Ssse3.AlignRight(left, right, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)); var result = Ssse3.AlignRight(left, right, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__AlignRightByte0(); var result = Ssse3.AlignRight(test._fld1, test._fld2, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Ssse3.AlignRight(_fld1, _fld2, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Ssse3.AlignRight(test._fld1, test._fld2, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Byte> left, Vector128<Byte> right, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), left); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != right[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != right[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Ssse3)}.{nameof(Ssse3.AlignRight)}<Byte>(Vector128<Byte>.0, Vector128<Byte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Threading; using System.Collections; using System.IO; using System.Data; using System.Data.SqlClient; using System.Messaging; using System.Runtime.InteropServices; using klServiceCore; namespace klServiceCore { public class klDLLImports { //[DllImport("kldll.dll", EntryPoint="#3",CharSet=CharSet.Auto,CallingConvention=CallingConvention.Cdecl)] public static extern void klMatlabWrapper(String xmlFile); [DllImport("kldll.dll", EntryPoint="#3",CharSet=CharSet.Auto,CallingConvention=CallingConvention.Cdecl)] public static extern void klRunWorkFlow(); //[DllImport("kldll.dll", EntryPoint="#3",CharSet=CharSet.Auto,CallingConvention=CallingConvention.Cdecl)] public static extern String klRunWorkFlow2(String xmlFile); //[DllImport("klqldll.dll", EntryPoint="#3",CharSet=CharSet.Auto,CallingConvention=CallingConvention.Cdecl)] public static extern void klQuantlibWrapper(string xmlFile); } public class klDataHost { public Hashtable m_HostIdMapping; public Hashtable m_DBMappings; //public Hashtable m_uidMapping; //public Hashtable m_PwdMapping; public klDataHost() { m_HostIdMapping=new Hashtable(); m_DBMappings=new Hashtable(); //m_uidMapping=new Hashtable(); //m_PwdMapping=new Hashtable(); } public SqlConnection getSQLClientConnection(Object key) { String connectionString=""; System.Data.SqlClient.SqlConnection DBConnection=new SqlConnection(connectionString); return DBConnection; } } public class klMessageHost { public Hashtable m_HostIdMapping; public Hashtable m_MessageQueueMappings; //public Hashtable m_uidMapping; //public Hashtable m_PwdMapping; public klMessageHost() { m_HostIdMapping=new Hashtable(); m_MessageQueueMappings=new Hashtable(); //m_uidMapping=new Hashtable(); //m_PwdMapping=new Hashtable(); } MessageQueue getMessageQueue(Object key) { MessageQueue messageQueue= new System.Messaging.MessageQueue(); return messageQueue; } } //An analysis has resources, an algorithm graph, and a run method which renders the graph public class klAnalysis :MarshalByRefObject { //All of HostID's in the data host container must be represented in the messaging resources. public klMessageHost m_messageHostResources; public klAlgorithmGraph m_AlgoGraph; public virtual void run() { } } //Representes an analysis contained entirely on a single machine running SQL Server public class klSQLServerAnalysis : klAnalysis { public klDataHost m_dataHostResources; public new void run() { } } //Represents an analysis on one of the grid resources public class klMQAnalysis : klAnalysis { public new void run() { } } //Data Descriptors describe the data inside a rendered item. They are used //as keys in the rendering and caching mechanisms. Data descriptors contain symbol, //time, and scale parameters for all rendered items [ flat files, blobs, reports, movies, ... etc] public class klDataDesc { } public class klBufferDesc: klDataDesc { } public class klMRTimeDesc : klDataDesc { } public class klModelParamDesc :klDataDesc { } [Serializable] public class klModel :MarshalByRefObject { public klAnalysis m_analysis; public klDataDesc m_dataDesc; //Analysis results - blobs,reports, movies, flat files, RI's are //further rendered in the model. This includes realtime algorithmmics, //running a classifier trainined in the analysis, aggregating several analysis //and UI output public virtual void run() { //Default behvaior - typically this is overridden in a derived class //where model parameters are used to run in realtime or classification mode // } } //Represents distributed analysis resources. //This object gets used by driver classes //One analysis object gets created by the user, and the //drivers are resposible for calling render on the parts of the //analysis chain that it can render. public class klDTCAnalysisResources { //Deploys the workflow elements {server,grid} on the Cluster public ArrayList m_Servers;//klSQLServerAnalysis public ArrayList m_GridElements;//klMQAnalysis public String m_xmlFile;//workflow graph public klDTCAnalysisResources() { m_Servers= new ArrayList(); m_GridElements=new ArrayList(); } } public class klAlgorithmGraph { public Hashtable m_Sources; public Hashtable m_Sinks; public Hashtable m_Transforms; public klAlgorithmGraph() { m_Sources=new Hashtable(); m_Sinks=new Hashtable(); m_Transforms=new Hashtable(); } } public abstract class klTransform :MarshalByRefObject { public abstract RenderedItem getData(Object key); public string persist() { return ""; } private string m_Name; public string getName() { return m_Name; } public void setName(string name) { m_Name=name; } } [Serializable] public class RenderedItem { protected string m_Key; public RenderedItem() { m_Key=""; } public string getKey() { return m_Key; } } public class ICP { public OCP m_OCP; public RenderedItem getData(object key) { return m_OCP.getData( key); } public void connect (OCP src) { m_OCP=src; } } public class OCP { //Rendered item container. private Hashtable m_Cache; public void setCache(string key) { RenderedItem ri=new RenderedItem(); m_Cache.Add(key,ri);//ri is filled later. } private klTransform m_xform; public void setTransform(klTransform xform) { m_xform=xform; } public RenderedItem getData(object key) { RenderedItem ri=m_xform.getData(key); String lkey=ri.getKey(); if(m_Cache[lkey]!=null) m_Cache[lkey]=ri; return ri; } public OCP() { m_Cache=new Hashtable(); } } public class klAlgorithmDataSource :klTransform { public OCP m_OCP; public klAlgorithmDataSource() { m_OCP=new OCP(); m_OCP.setTransform(this); } public override RenderedItem getData(object key) { //The beginning of all real algorithmics. RenderedItem ri=new RenderedItem(); return ri; } } public class klAlgorithmDataSink : klTransform { public ICP m_ICP; public klAlgorithmDataSink() { m_ICP=new ICP(); } //Fills the RenderItems. public void generateDependencies() { } public override RenderedItem getData(object key) { //Sink get data RenderedItem ri= m_ICP.getData(key); return ri; } public virtual void render() { string key=""; RenderedItem ri = getData(key); } public void MultiThreadedRender() { } //a priority list of all the renderables required to generate output. private Hashtable RenderItems; } public class klAlgorithmTransform : klTransform { public ICP m_ICP; public OCP m_OCP; public klAlgorithmTransform() { m_ICP=new ICP(); m_OCP=new OCP(); m_OCP.setTransform(this); } public override RenderedItem getData(object key) { RenderedItem ri=m_ICP.getData(key); return ri; } } public class klMatlabAlgorithm : klAlgorithmTransform { public string m_script; void runScript(string script) { //klDLLImports.klMatlabWrapper(m_script); } public override RenderedItem getData(object key) { RenderedItem ri=m_ICP.getData(key); return ri; } } public class klRAlgorithm : klAlgorithmTransform { public override RenderedItem getData(object key) { RenderedItem ri=m_ICP.getData(key); return ri; } } public class klLocalTransform : klAlgorithmTransform { //Secondary ICP - public ICP m_ICP2; public klLocalTransform() :base() { m_ICP2=new ICP(); m_OCP2=new OCP(); m_OCP2.setTransform(this); } //Secondary OCP public OCP m_OCP2; public override RenderedItem getData(object key) { //We need to know which ocp was used to make this call if multiple outputs are allowed! //Get inputs RenderedItem ri1=m_ICP2.getData(key); RenderedItem ri2=m_ICP.getData(key); //Do our stuff RenderedItem ri=new RenderedItem(); return ri; } } public class klADOSource :klAlgorithmDataSource { public System.Data.DataSet m_DataSet; public System.Data.SqlClient.SqlDataAdapter m_DataAdapter; public System.Data.SqlClient.SqlConnection m_sqlConnection; public override RenderedItem getData(object key) { // System.Console.WriteLine("GET DATA:"); RenderedItem ri =new RenderedItem(); return ri; } } public class klFileSource : klAlgorithmDataSource { public klFileSource() { } public void setFileName(string name) { m_FileName=name; } public klFileSource(string name) { m_FileName=name; } public override RenderedItem getData(object key) { // System.Console.WriteLine("GET DATA:"); RenderedItem ri =new RenderedItem(); return ri; } protected string m_FileName; } public class klFileListSource : klAlgorithmDataSource { public klFileListSource() { } public override RenderedItem getData(object key) { klFileListRI ri =new klFileListRI(); return ri; } } public class klADOSink : klAlgorithmDataSink { public System.Data.DataSet m_DataSet; public System.Data.SqlClient.SqlDataAdapter m_DataAdapter; } public class klFileSink : klAlgorithmDataSink { public klFileSink(String filename) { m_fileName=filename; } private String m_fileName; } public class klEquityInstance :RenderedItem { } [Serializable] public class klDLLXMLRI :RenderedItem { public string m_xmlResults; } [Serializable] public class klFileListRI :RenderedItem { public string m_baseFileName; public ArrayList m_files; } [Serializable] public class klUnitTestFn : klAlgorithmTransform { public string m_xmlFile; klUnitTestFn(string xmlFile) { m_xmlFile = xmlFile; } //makes a call into kldll - runs portfolio analysis on single flat blob - public override RenderedItem getData(object key) { klDLLXMLRI ri = new klDLLXMLRI(); ri.m_xmlResults = null; //Just call main driver for now klDLLImports.klRunWorkFlow(); return ri; } } [Serializable] public class klDFTAggTransform : klAlgorithmTransform { //Aggs FFT sec data in basic windows. Corr calculated by inner prod. alg. public string m_xmlFile; klDFTAggTransform(string xmlFile) { m_xmlFile=xmlFile; } //makes a call into kldll - runs portfolio analysis on single flat blob - public override RenderedItem getData(object key) { klDLLXMLRI ri=new klDLLXMLRI(); //ri.m_xmlResults=klDLLImports.klRunWorkFlow2(m_xmlFile); return ri; } } [Serializable] public class klCorrelationMovieTransform : klMatlabAlgorithm { } //For Realtime algorithms - see klTownsendAnalytics } namespace testWorkflow { /// <summary> /// Summary description for Class1. /// </summary> public class klWorkFlowFactory { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] public static void runTestWorkflow(string[] args) { klMessageHost klmh=new klMessageHost(); klmh.m_HostIdMapping.Add(0,"grid00"); klmh.m_MessageQueueMappings.Add(0,"grid00_MQ"); klmh.m_HostIdMapping.Add(1,"grid01"); klmh.m_MessageQueueMappings.Add(1,"grid00_MQ"); klmh.m_HostIdMapping.Add(2,"grid02"); klmh.m_MessageQueueMappings.Add(2,"grid02_MQ"); klmh.m_HostIdMapping.Add(3,"IWM"); klmh.m_MessageQueueMappings.Add(3,"IWM_MQ"); klmh.m_HostIdMapping.Add(4,"SPY"); klmh.m_MessageQueueMappings.Add(4,"SPY_MQ"); klmh.m_HostIdMapping.Add(5,"OIH"); klmh.m_MessageQueueMappings.Add(5,"OIH_MQ"); klmh.m_HostIdMapping.Add(6,"tickerplant"); klmh.m_MessageQueueMappings.Add(6,"tickerplant_MQ"); klmh.m_HostIdMapping.Add(7,"dtchost"); klmh.m_MessageQueueMappings.Add(7,"dtchost_MQ"); klDataHost kldh=new klDataHost(); kldh.m_DBMappings.Add(0,"OIH"); kldh.m_HostIdMapping.Add(0,"OIH"); kldh.m_DBMappings.Add(1,"IWM"); kldh.m_HostIdMapping.Add(1,"IWM"); kldh.m_DBMappings.Add(2,"SPY"); kldh.m_HostIdMapping.Add(2,"SPY"); klMQAnalysis kla=new klMQAnalysis(); kla.m_messageHostResources=klmh; //Something on grid03 klSQLServerAnalysis klssa=new klSQLServerAnalysis(); klssa.m_dataHostResources=kldh; //something on shuttle klDTCAnalysisResources kldtc=new klDTCAnalysisResources(); kldtc.m_GridElements.Add(klmh); kldtc.m_Servers.Add(kldh); //Algorithm Graph klAlgorithmGraph klag=new klAlgorithmGraph(); //sources klADOSource kladosrc=new klADOSource(); kladosrc.setName(kladosrc.GetType().FullName); klFileSource klfsrc=new klFileSource("in.txt"); klfsrc.setName(klfsrc.GetType().FullName); //transforms klMatlabAlgorithm klma =new klMatlabAlgorithm(); klma.setName(klma.GetType().FullName); klRAlgorithm klra=new klRAlgorithm(); klra.setName(klra.GetType().FullName); //sinks klFileSink klfsnk=new klFileSink("moo.txt"); klfsnk.setName(klfsnk.GetType().FullName); klADOSink kladosnk=new klADOSink(); kladosnk.setName(kladosnk.GetType().FullName); klLocalTransform kllt=new klLocalTransform(); kllt.setName(kllt.GetType().FullName); klag.m_Sources.Add(0,klfsrc); klag.m_Sources.Add(1,kladosrc); klag.m_Transforms.Add(0,klma); klag.m_Transforms.Add(1,klra); klag.m_Transforms.Add(2,kllt); klag.m_Sinks.Add(0,klfsnk); klag.m_Sinks.Add(1,kladosnk); //Make Connections klma.m_ICP.connect(kladosrc.m_OCP); klra.m_ICP.connect(klfsrc.m_OCP); kllt.m_ICP.connect(klma.m_OCP); kllt.m_ICP2.connect(klra.m_OCP); kladosnk.m_ICP.connect(kllt.m_OCP2); klfsnk.m_ICP.connect(kllt.m_OCP); kladosnk.render(); klfsnk.render(); kladosnk.persist(); klfsnk.persist(); // ADOSRC-------matlab--------| |----------FILESINK // | | // |---------MYLocalTransform -------------| // | | // | |----------ADOSINK // FILESRC--------R-----------| } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace NinjectWebApi.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V9.Resources { /// <summary>Resource name for the <c>HotelGroupView</c> resource.</summary> public sealed partial class HotelGroupViewName : gax::IResourceName, sys::IEquatable<HotelGroupViewName> { /// <summary>The possible contents of <see cref="HotelGroupViewName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>customers/{customer_id}/hotelGroupViews/{ad_group_id}~{criterion_id}</c> /// . /// </summary> CustomerAdGroupCriterion = 1, } private static gax::PathTemplate s_customerAdGroupCriterion = new gax::PathTemplate("customers/{customer_id}/hotelGroupViews/{ad_group_id_criterion_id}"); /// <summary>Creates a <see cref="HotelGroupViewName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="HotelGroupViewName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static HotelGroupViewName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new HotelGroupViewName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="HotelGroupViewName"/> with the pattern /// <c>customers/{customer_id}/hotelGroupViews/{ad_group_id}~{criterion_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="HotelGroupViewName"/> constructed from the provided ids.</returns> public static HotelGroupViewName FromCustomerAdGroupCriterion(string customerId, string adGroupId, string criterionId) => new HotelGroupViewName(ResourceNameType.CustomerAdGroupCriterion, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="HotelGroupViewName"/> with pattern /// <c>customers/{customer_id}/hotelGroupViews/{ad_group_id}~{criterion_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="HotelGroupViewName"/> with pattern /// <c>customers/{customer_id}/hotelGroupViews/{ad_group_id}~{criterion_id}</c>. /// </returns> public static string Format(string customerId, string adGroupId, string criterionId) => FormatCustomerAdGroupCriterion(customerId, adGroupId, criterionId); /// <summary> /// Formats the IDs into the string representation of this <see cref="HotelGroupViewName"/> with pattern /// <c>customers/{customer_id}/hotelGroupViews/{ad_group_id}~{criterion_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="HotelGroupViewName"/> with pattern /// <c>customers/{customer_id}/hotelGroupViews/{ad_group_id}~{criterion_id}</c>. /// </returns> public static string FormatCustomerAdGroupCriterion(string customerId, string adGroupId, string criterionId) => s_customerAdGroupCriterion.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)))}"); /// <summary> /// Parses the given resource name string into a new <see cref="HotelGroupViewName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/hotelGroupViews/{ad_group_id}~{criterion_id}</c></description> /// </item> /// </list> /// </remarks> /// <param name="hotelGroupViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="HotelGroupViewName"/> if successful.</returns> public static HotelGroupViewName Parse(string hotelGroupViewName) => Parse(hotelGroupViewName, false); /// <summary> /// Parses the given resource name string into a new <see cref="HotelGroupViewName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/hotelGroupViews/{ad_group_id}~{criterion_id}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="hotelGroupViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="HotelGroupViewName"/> if successful.</returns> public static HotelGroupViewName Parse(string hotelGroupViewName, bool allowUnparsed) => TryParse(hotelGroupViewName, allowUnparsed, out HotelGroupViewName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="HotelGroupViewName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/hotelGroupViews/{ad_group_id}~{criterion_id}</c></description> /// </item> /// </list> /// </remarks> /// <param name="hotelGroupViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="HotelGroupViewName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string hotelGroupViewName, out HotelGroupViewName result) => TryParse(hotelGroupViewName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="HotelGroupViewName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/hotelGroupViews/{ad_group_id}~{criterion_id}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="hotelGroupViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="HotelGroupViewName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string hotelGroupViewName, bool allowUnparsed, out HotelGroupViewName result) { gax::GaxPreconditions.CheckNotNull(hotelGroupViewName, nameof(hotelGroupViewName)); gax::TemplatedResourceName resourceName; if (s_customerAdGroupCriterion.TryParseName(hotelGroupViewName, out resourceName)) { string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', }); if (split1 == null) { result = null; return false; } result = FromCustomerAdGroupCriterion(resourceName[0], split1[0], split1[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(hotelGroupViewName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private static string[] ParseSplitHelper(string s, char[] separators) { string[] result = new string[separators.Length + 1]; int i0 = 0; for (int i = 0; i <= separators.Length; i++) { int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length; if (i1 < 0 || i1 == i0) { return null; } result[i] = s.Substring(i0, i1 - i0); i0 = i1 + 1; } return result; } private HotelGroupViewName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string adGroupId = null, string criterionId = null, string customerId = null) { Type = type; UnparsedResource = unparsedResourceName; AdGroupId = adGroupId; CriterionId = criterionId; CustomerId = customerId; } /// <summary> /// Constructs a new instance of a <see cref="HotelGroupViewName"/> class from the component parts of pattern /// <c>customers/{customer_id}/hotelGroupViews/{ad_group_id}~{criterion_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> public HotelGroupViewName(string customerId, string adGroupId, string criterionId) : this(ResourceNameType.CustomerAdGroupCriterion, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>AdGroup</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string AdGroupId { get; } /// <summary> /// The <c>Criterion</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CriterionId { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerAdGroupCriterion: return s_customerAdGroupCriterion.Expand(CustomerId, $"{AdGroupId}~{CriterionId}"); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as HotelGroupViewName); /// <inheritdoc/> public bool Equals(HotelGroupViewName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(HotelGroupViewName a, HotelGroupViewName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(HotelGroupViewName a, HotelGroupViewName b) => !(a == b); } public partial class HotelGroupView { /// <summary> /// <see cref="HotelGroupViewName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal HotelGroupViewName ResourceNameAsHotelGroupViewName { get => string.IsNullOrEmpty(ResourceName) ? null : HotelGroupViewName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } } }
using System; using UnityEngine; namespace UnityEditor { internal class MK_StandardShaderGUI : ShaderGUI { private enum WorkflowMode { Specular, Metallic, Dielectric } public enum BlendMode { Opaque, Cutout, Fade, // Old school alpha-blending mode, fresnel does not affect amount of transparency Transparent // Physically plausible transparency mode, implemented as alpha pre-multiply } private static class Styles { public static GUIStyle optionsButton = "PaneOptions"; public static GUIContent uvSetLabel = new GUIContent("UV Set"); public static GUIContent[] uvSetOptions = new GUIContent[] { new GUIContent("UV channel 0"), new GUIContent("UV channel 1") }; public static string emptyTootip = ""; public static GUIContent albedoText = new GUIContent("Albedo", "Albedo (RGB) and Transparency (A)"); public static GUIContent alphaCutoffText = new GUIContent("Alpha Cutoff", "Threshold for alpha cutoff"); public static GUIContent specularMapText = new GUIContent("Specular", "Specular (RGB) and Smoothness (A)"); public static GUIContent metallicMapText = new GUIContent("Metallic", "Metallic (R) and Smoothness (A)"); public static GUIContent smoothnessText = new GUIContent("Smoothness", ""); public static GUIContent normalMapText = new GUIContent("Normal Map", "Normal Map"); public static GUIContent heightMapText = new GUIContent("Height Map", "Height Map (G)"); public static GUIContent occlusionText = new GUIContent("Occlusion", "Occlusion (G)"); public static GUIContent emissionText = new GUIContent("Emission", "Emission (RGB)"); public static GUIContent detailMaskText = new GUIContent("Detail Mask", "Mask for Secondary Maps (A)"); public static GUIContent detailAlbedoText = new GUIContent("Detail Albedo x2", "Albedo (RGB) multiplied by 2"); public static GUIContent detailNormalMapText = new GUIContent("Normal Map", "Normal Map"); public static string whiteSpaceString = " "; public static string primaryMapsText = "Main Maps"; public static string secondaryMapsText = "Secondary Maps"; public static string renderingMode = "Rendering Mode"; public static GUIContent emissiveWarning = new GUIContent ("Emissive value is animated but the material has not been configured to support emissive. Please make sure the material itself has some amount of emissive."); public static GUIContent emissiveColorWarning = new GUIContent ("Ensure emissive color is non-black for emission to have effect."); public static readonly string[] blendNames = Enum.GetNames (typeof (BlendMode)); public static string mk_glow_system = "MK Glow System"; public static GUIContent mk_glow_color = new GUIContent("Glow Color"); } MaterialProperty mk_glow_system_material_color = null; MaterialProperty mk_glow_system_material_glowPower = null; MaterialProperty mk_glow_system_material_glowtex = null; MaterialProperty mk_glow_system_material_glowtexColor = null; MaterialProperty mk_glow_system_material_glowtexColorStrength = null; MaterialProperty mk_glow_system_material_glowOffset = null; MaterialProperty blendMode = null; MaterialProperty albedoMap = null; MaterialProperty albedoColor = null; MaterialProperty alphaCutoff = null; MaterialProperty specularMap = null; MaterialProperty specularColor = null; MaterialProperty metallicMap = null; MaterialProperty metallic = null; MaterialProperty smoothness = null; MaterialProperty bumpScale = null; MaterialProperty bumpMap = null; MaterialProperty occlusionStrength = null; MaterialProperty occlusionMap = null; MaterialProperty heigtMapScale = null; MaterialProperty heightMap = null; MaterialProperty emissionColorForRendering = null; MaterialProperty emissionMap = null; MaterialProperty detailMask = null; MaterialProperty detailAlbedoMap = null; MaterialProperty detailNormalMapScale = null; MaterialProperty detailNormalMap = null; MaterialProperty uvSetSecondary = null; MaterialEditor m_MaterialEditor; WorkflowMode m_WorkflowMode = WorkflowMode.Specular; ColorPickerHDRConfig m_ColorPickerHDRConfig = new ColorPickerHDRConfig(0f, 99f, 1/99f, 3f); bool m_FirstTimeApply = true; public void FindProperties (MaterialProperty[] props) { mk_glow_system_material_color = FindProperty ("_MKGlowColor", props); mk_glow_system_material_glowPower = FindProperty ("_MKGlowPower", props); mk_glow_system_material_glowtex = FindProperty ("_MKGlowTex", props); mk_glow_system_material_glowtexColor = FindProperty ("_MKGlowTexColor", props); mk_glow_system_material_glowtexColorStrength = FindProperty ("_MKGlowTexStrength", props); mk_glow_system_material_glowOffset = FindProperty ("_MKGlowOffSet", props); blendMode = FindProperty ("_Mode", props); albedoMap = FindProperty ("_MainTex", props); albedoColor = FindProperty ("_Color", props); alphaCutoff = FindProperty ("_Cutoff", props); specularMap = FindProperty ("_SpecGlossMap", props, false); specularColor = FindProperty ("_SpecColor", props, false); metallicMap = FindProperty ("_MetallicGlossMap", props, false); metallic = FindProperty ("_Metallic", props, false); if (specularMap != null && specularColor != null) m_WorkflowMode = WorkflowMode.Specular; else if (metallicMap != null && metallic != null) m_WorkflowMode = WorkflowMode.Metallic; else m_WorkflowMode = WorkflowMode.Dielectric; smoothness = FindProperty ("_Glossiness", props); bumpScale = FindProperty ("_BumpScale", props); bumpMap = FindProperty ("_BumpMap", props); heigtMapScale = FindProperty ("_Parallax", props); heightMap = FindProperty("_ParallaxMap", props); occlusionStrength = FindProperty ("_OcclusionStrength", props); occlusionMap = FindProperty ("_OcclusionMap", props); emissionColorForRendering = FindProperty ("_EmissionColor", props); emissionMap = FindProperty ("_EmissionMap", props); detailMask = FindProperty ("_DetailMask", props); detailAlbedoMap = FindProperty ("_DetailAlbedoMap", props); detailNormalMapScale = FindProperty ("_DetailNormalMapScale", props); detailNormalMap = FindProperty ("_DetailNormalMap", props); uvSetSecondary = FindProperty ("_UVSec", props); } void DoMKGlowArea(Material material) { m_MaterialEditor.ColorProperty(mk_glow_system_material_color, "Glow Color"); m_MaterialEditor.ShaderProperty(mk_glow_system_material_glowPower, "Glow Power"); m_MaterialEditor.TextureProperty(mk_glow_system_material_glowtex, "Glow Texture"); m_MaterialEditor.ColorProperty(mk_glow_system_material_glowtexColor, "Glow Texture Color"); m_MaterialEditor.ShaderProperty(mk_glow_system_material_glowtexColorStrength, "Glow Texture Strength"); m_MaterialEditor.ShaderProperty(mk_glow_system_material_glowOffset, "Glow Width"); if (((BlendMode)material.GetFloat("_Mode") == BlendMode.Cutout)) { m_MaterialEditor.ShaderProperty(alphaCutoff, Styles.alphaCutoffText.text, MaterialEditor.kMiniTextureFieldLabelIndentLevel+1); } } public override void OnGUI (MaterialEditor materialEditor, MaterialProperty[] props) { FindProperties (props); // MaterialProperties can be animated so we do not cache them but fetch them every event to ensure animated values are updated correctly m_MaterialEditor = materialEditor; Material material = materialEditor.target as Material; ShaderPropertiesGUI (material); // Make sure that needed keywords are set up if we're switching some existing // material to a standard shader. if (m_FirstTimeApply) { SetMaterialKeywords (material, m_WorkflowMode); m_FirstTimeApply = false; } } public void ShaderPropertiesGUI (Material material) { // Use default labelWidth EditorGUIUtility.labelWidth = 0f; // Detect any changes to the material EditorGUI.BeginChangeCheck(); { BlendModePopup(); // Primary properties GUILayout.Label (Styles.primaryMapsText, EditorStyles.boldLabel); DoAlbedoArea(material); DoSpecularMetallicArea(); m_MaterialEditor.TexturePropertySingleLine(Styles.normalMapText, bumpMap, bumpMap.textureValue != null ? bumpScale : null); m_MaterialEditor.TexturePropertySingleLine(Styles.heightMapText, heightMap, heightMap.textureValue != null ? heigtMapScale : null); m_MaterialEditor.TexturePropertySingleLine(Styles.occlusionText, occlusionMap, occlusionMap.textureValue != null ? occlusionStrength : null); DoEmissionArea(material); m_MaterialEditor.TexturePropertySingleLine(Styles.detailMaskText, detailMask); EditorGUI.BeginChangeCheck(); m_MaterialEditor.TextureScaleOffsetProperty(albedoMap); if (EditorGUI.EndChangeCheck()) emissionMap.textureScaleAndOffset = albedoMap.textureScaleAndOffset; // Apply the main texture scale and offset to the emission texture as well, for Enlighten's sake EditorGUILayout.Space(); // Secondary properties GUILayout.Label(Styles.secondaryMapsText, EditorStyles.boldLabel); m_MaterialEditor.TexturePropertySingleLine(Styles.detailAlbedoText, detailAlbedoMap); m_MaterialEditor.TexturePropertySingleLine(Styles.detailNormalMapText, detailNormalMap, detailNormalMapScale); m_MaterialEditor.TextureScaleOffsetProperty(detailAlbedoMap); m_MaterialEditor.ShaderProperty(uvSetSecondary, Styles.uvSetLabel.text); GUILayout.Label(Styles.mk_glow_system, EditorStyles.boldLabel); DoMKGlowArea(material); } if (EditorGUI.EndChangeCheck()) { foreach (var obj in blendMode.targets) MaterialChanged((Material)obj, m_WorkflowMode); } } internal void DetermineWorkflow(MaterialProperty[] props) { if (FindProperty("_SpecGlossMap", props, false) != null && FindProperty("_SpecColor", props, false) != null) m_WorkflowMode = WorkflowMode.Specular; else if (FindProperty("_MetallicGlossMap", props, false) != null && FindProperty("_Metallic", props, false) != null) m_WorkflowMode = WorkflowMode.Metallic; else m_WorkflowMode = WorkflowMode.Dielectric; } public override void AssignNewShaderToMaterial (Material material, Shader oldShader, Shader newShader) { // _Emission property is lost after assigning Standard shader to the material // thus transfer it before assigning the new shader if (material.HasProperty("_Emission")) { material.SetColor("_EmissionColor", material.GetColor("_Emission")); } base.AssignNewShaderToMaterial(material, oldShader, newShader); if (oldShader == null || !oldShader.name.Contains("Legacy Shaders/")) return; BlendMode blendMode = BlendMode.Opaque; if (oldShader.name.Contains("/Transparent/Cutout/")) { blendMode = BlendMode.Cutout; } else if (oldShader.name.Contains("/Transparent/")) { // NOTE: legacy shaders did not provide physically based transparency // therefore Fade mode blendMode = BlendMode.Fade; } material.SetFloat("_Mode", (float)blendMode); DetermineWorkflow( MaterialEditor.GetMaterialProperties (new Material[] { material }) ); MaterialChanged(material, m_WorkflowMode); } void BlendModePopup() { EditorGUI.showMixedValue = blendMode.hasMixedValue; var mode = (BlendMode)blendMode.floatValue; EditorGUI.BeginChangeCheck(); mode = (BlendMode)EditorGUILayout.Popup(Styles.renderingMode, (int)mode, Styles.blendNames); if (EditorGUI.EndChangeCheck()) { m_MaterialEditor.RegisterPropertyChangeUndo("Rendering Mode"); blendMode.floatValue = (float)mode; } EditorGUI.showMixedValue = false; } void DoAlbedoArea(Material material) { m_MaterialEditor.TexturePropertySingleLine(Styles.albedoText, albedoMap, albedoColor); if (((BlendMode)material.GetFloat("_Mode") == BlendMode.Cutout)) { m_MaterialEditor.ShaderProperty(alphaCutoff, Styles.alphaCutoffText.text, MaterialEditor.kMiniTextureFieldLabelIndentLevel+1); } } void DoEmissionArea(Material material) { float brightness = emissionColorForRendering.colorValue.maxColorComponent; bool showHelpBox = !HasValidEmissiveKeyword(material); bool showEmissionColorAndGIControls = brightness > 0.0f; bool hadEmissionTexture = emissionMap.textureValue != null; // Texture and HDR color controls m_MaterialEditor.TexturePropertyWithHDRColor(Styles.emissionText, emissionMap, emissionColorForRendering, m_ColorPickerHDRConfig, false); // If texture was assigned and color was black set color to white if (emissionMap.textureValue != null && !hadEmissionTexture && brightness <= 0f) emissionColorForRendering.colorValue = Color.white; // Dynamic Lightmapping mode if (showEmissionColorAndGIControls) { bool shouldEmissionBeEnabled = ShouldEmissionBeEnabled(emissionColorForRendering.colorValue); EditorGUI.BeginDisabledGroup(!shouldEmissionBeEnabled); m_MaterialEditor.LightmapEmissionProperty (MaterialEditor.kMiniTextureFieldLabelIndentLevel + 1); EditorGUI.EndDisabledGroup(); } if (showHelpBox) { EditorGUILayout.HelpBox(Styles.emissiveWarning.text, MessageType.Warning); } } void DoSpecularMetallicArea() { if (m_WorkflowMode == WorkflowMode.Specular) { if (specularMap.textureValue == null) m_MaterialEditor.TexturePropertyTwoLines(Styles.specularMapText, specularMap, specularColor, Styles.smoothnessText, smoothness); else m_MaterialEditor.TexturePropertySingleLine(Styles.specularMapText, specularMap); } else if (m_WorkflowMode == WorkflowMode.Metallic) { if (metallicMap.textureValue == null) m_MaterialEditor.TexturePropertyTwoLines(Styles.metallicMapText, metallicMap, metallic, Styles.smoothnessText, smoothness); else m_MaterialEditor.TexturePropertySingleLine(Styles.metallicMapText, metallicMap); } } public static void SetupMaterialWithBlendMode(Material material, BlendMode blendMode) { switch (blendMode) { case BlendMode.Opaque: material.SetOverrideTag("RenderType", ""); material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); material.SetInt("_ZWrite", 1); material.DisableKeyword("_ALPHATEST_ON"); material.DisableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = -1; break; case BlendMode.Cutout: material.SetOverrideTag("RenderType", "TransparentCutout"); material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); material.SetInt("_ZWrite", 1); material.EnableKeyword("_ALPHATEST_ON"); material.DisableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = 2450; break; case BlendMode.Fade: material.SetOverrideTag("RenderType", "Transparent"); material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); material.SetInt("_ZWrite", 0); material.DisableKeyword("_ALPHATEST_ON"); material.EnableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = 3000; break; case BlendMode.Transparent: material.SetOverrideTag("RenderType", "Transparent"); material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); material.SetInt("_ZWrite", 0); material.DisableKeyword("_ALPHATEST_ON"); material.DisableKeyword("_ALPHABLEND_ON"); material.EnableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = 3000; break; } } static bool ShouldEmissionBeEnabled (Color color) { return color.maxColorComponent > (0.1f / 255.0f); } static void SetMaterialKeywords(Material material, WorkflowMode workflowMode) { // Note: keywords must be based on Material value not on MaterialProperty due to multi-edit & material animation // (MaterialProperty value might come from renderer material property block) SetKeyword (material, "_NORMALMAP", material.GetTexture ("_BumpMap") || material.GetTexture ("_DetailNormalMap")); if (workflowMode == WorkflowMode.Specular) SetKeyword (material, "_SPECGLOSSMAP", material.GetTexture ("_SpecGlossMap")); else if (workflowMode == WorkflowMode.Metallic) SetKeyword (material, "_METALLICGLOSSMAP", material.GetTexture ("_MetallicGlossMap")); SetKeyword (material, "_PARALLAXMAP", material.GetTexture ("_ParallaxMap")); SetKeyword (material, "_DETAIL_MULX2", material.GetTexture ("_DetailAlbedoMap") || material.GetTexture ("_DetailNormalMap")); bool shouldEmissionBeEnabled = ShouldEmissionBeEnabled (material.GetColor("_EmissionColor")); SetKeyword (material, "_EMISSION", shouldEmissionBeEnabled); // Setup lightmap emissive flags MaterialGlobalIlluminationFlags flags = material.globalIlluminationFlags; if ((flags & (MaterialGlobalIlluminationFlags.BakedEmissive | MaterialGlobalIlluminationFlags.RealtimeEmissive)) != 0) { flags &= ~MaterialGlobalIlluminationFlags.EmissiveIsBlack; if (!shouldEmissionBeEnabled) flags |= MaterialGlobalIlluminationFlags.EmissiveIsBlack; material.globalIlluminationFlags = flags; } } bool HasValidEmissiveKeyword (Material material) { // Material animation might be out of sync with the material keyword. // So if the emission support is disabled on the material, but the property blocks have a value that requires it, then we need to show a warning. // (note: (Renderer MaterialPropertyBlock applies its values to emissionColorForRendering)) bool hasEmissionKeyword = material.IsKeywordEnabled ("_EMISSION"); if (!hasEmissionKeyword && ShouldEmissionBeEnabled (emissionColorForRendering.colorValue)) return false; else return true; } static void MaterialChanged(Material material, WorkflowMode workflowMode) { SetupMaterialWithBlendMode(material, (BlendMode)material.GetFloat("_Mode")); SetMaterialKeywords(material, workflowMode); } static void SetKeyword(Material m, string keyword, bool state) { if (state) m.EnableKeyword (keyword); else m.DisableKeyword (keyword); } } } // namespace UnityEditor
using System; using System.Collections.Generic; using System.Linq; using Nop.Core; using Nop.Core.Caching; using Nop.Core.Data; using Nop.Core.Domain.Catalog; using Nop.Services.Events; namespace Nop.Services.Catalog { /// <summary> /// Product attribute service /// </summary> public partial class ProductAttributeService : IProductAttributeService { #region Constants /// <summary> /// Key for caching /// </summary> /// <remarks> /// {0} : page index /// {1} : page size /// </remarks> private const string PRODUCTATTRIBUTES_ALL_KEY = "Nop.productattribute.all-{0}-{1}"; /// <summary> /// Key for caching /// </summary> /// <remarks> /// {0} : product attribute ID /// </remarks> private const string PRODUCTATTRIBUTES_BY_ID_KEY = "Nop.productattribute.id-{0}"; /// <summary> /// Key for caching /// </summary> /// <remarks> /// {0} : product ID /// </remarks> private const string PRODUCTATTRIBUTEMAPPINGS_ALL_KEY = "Nop.productattributemapping.all-{0}"; /// <summary> /// Key for caching /// </summary> /// <remarks> /// {0} : product attribute mapping ID /// </remarks> private const string PRODUCTATTRIBUTEMAPPINGS_BY_ID_KEY = "Nop.productattributemapping.id-{0}"; /// <summary> /// Key for caching /// </summary> /// <remarks> /// {0} : product attribute mapping ID /// </remarks> private const string PRODUCTATTRIBUTEVALUES_ALL_KEY = "Nop.productattributevalue.all-{0}"; /// <summary> /// Key for caching /// </summary> /// <remarks> /// {0} : product attribute value ID /// </remarks> private const string PRODUCTATTRIBUTEVALUES_BY_ID_KEY = "Nop.productattributevalue.id-{0}"; /// <summary> /// Key for caching /// </summary> /// <remarks> /// {0} : product ID /// </remarks> private const string PRODUCTATTRIBUTECOMBINATIONS_ALL_KEY = "Nop.productattributecombination.all-{0}"; /// <summary> /// Key pattern to clear cache /// </summary> private const string PRODUCTATTRIBUTES_PATTERN_KEY = "Nop.productattribute."; /// <summary> /// Key pattern to clear cache /// </summary> private const string PRODUCTATTRIBUTEMAPPINGS_PATTERN_KEY = "Nop.productattributemapping."; /// <summary> /// Key pattern to clear cache /// </summary> private const string PRODUCTATTRIBUTEVALUES_PATTERN_KEY = "Nop.productattributevalue."; /// <summary> /// Key pattern to clear cache /// </summary> private const string PRODUCTATTRIBUTECOMBINATIONS_PATTERN_KEY = "Nop.productattributecombination."; #endregion #region Fields private readonly IRepository<ProductAttribute> _productAttributeRepository; private readonly IRepository<ProductAttributeMapping> _productAttributeMappingRepository; private readonly IRepository<ProductAttributeCombination> _productAttributeCombinationRepository; private readonly IRepository<ProductAttributeValue> _productAttributeValueRepository; private readonly IEventPublisher _eventPublisher; private readonly ICacheManager _cacheManager; #endregion #region Ctor /// <summary> /// Ctor /// </summary> /// <param name="cacheManager">Cache manager</param> /// <param name="productAttributeRepository">Product attribute repository</param> /// <param name="productAttributeMappingRepository">Product attribute mapping repository</param> /// <param name="productAttributeCombinationRepository">Product attribute combination repository</param> /// <param name="productAttributeValueRepository">Product attribute value repository</param> /// <param name="eventPublisher">Event published</param> public ProductAttributeService(ICacheManager cacheManager, IRepository<ProductAttribute> productAttributeRepository, IRepository<ProductAttributeMapping> productAttributeMappingRepository, IRepository<ProductAttributeCombination> productAttributeCombinationRepository, IRepository<ProductAttributeValue> productAttributeValueRepository, IEventPublisher eventPublisher ) { this._cacheManager = cacheManager; this._productAttributeRepository = productAttributeRepository; this._productAttributeMappingRepository = productAttributeMappingRepository; this._productAttributeCombinationRepository = productAttributeCombinationRepository; this._productAttributeValueRepository = productAttributeValueRepository; this._eventPublisher = eventPublisher; } #endregion #region Methods #region Product attributes /// <summary> /// Deletes a product attribute /// </summary> /// <param name="productAttribute">Product attribute</param> public virtual void DeleteProductAttribute(ProductAttribute productAttribute) { if (productAttribute == null) throw new ArgumentNullException("productAttribute"); _productAttributeRepository.Delete(productAttribute); //cache _cacheManager.RemoveByPattern(PRODUCTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTATTRIBUTEMAPPINGS_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTATTRIBUTEVALUES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTATTRIBUTECOMBINATIONS_PATTERN_KEY); //event notification _eventPublisher.EntityDeleted(productAttribute); } /// <summary> /// Gets all product attributes /// </summary> /// <param name="pageIndex">Page index</param> /// <param name="pageSize">Page size</param> /// <returns>Product attribute collection</returns> public virtual IPagedList<ProductAttribute> GetAllProductAttributes(int pageIndex = 0, int pageSize = int.MaxValue) { string key = string.Format(PRODUCTATTRIBUTES_ALL_KEY, pageIndex, pageSize); return _cacheManager.Get(key, () => { var query = from pa in _productAttributeRepository.Table orderby pa.Name select pa; var productAttributes = new PagedList<ProductAttribute>(query, pageIndex, pageSize); return productAttributes; }); } /// <summary> /// Gets a product attribute /// </summary> /// <param name="productAttributeId">Product attribute identifier</param> /// <returns>Product attribute </returns> public virtual ProductAttribute GetProductAttributeById(int productAttributeId) { if (productAttributeId == 0) return null; string key = string.Format(PRODUCTATTRIBUTES_BY_ID_KEY, productAttributeId); return _cacheManager.Get(key, () => _productAttributeRepository.GetById(productAttributeId)); } /// <summary> /// Inserts a product attribute /// </summary> /// <param name="productAttribute">Product attribute</param> public virtual void InsertProductAttribute(ProductAttribute productAttribute) { if (productAttribute == null) throw new ArgumentNullException("productAttribute"); _productAttributeRepository.Insert(productAttribute); //cache _cacheManager.RemoveByPattern(PRODUCTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTATTRIBUTEMAPPINGS_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTATTRIBUTEVALUES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTATTRIBUTECOMBINATIONS_PATTERN_KEY); //event notification _eventPublisher.EntityInserted(productAttribute); } /// <summary> /// Updates the product attribute /// </summary> /// <param name="productAttribute">Product attribute</param> public virtual void UpdateProductAttribute(ProductAttribute productAttribute) { if (productAttribute == null) throw new ArgumentNullException("productAttribute"); _productAttributeRepository.Update(productAttribute); //cache _cacheManager.RemoveByPattern(PRODUCTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTATTRIBUTEMAPPINGS_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTATTRIBUTEVALUES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTATTRIBUTECOMBINATIONS_PATTERN_KEY); //event notification _eventPublisher.EntityUpdated(productAttribute); } #endregion #region Product attributes mappings /// <summary> /// Deletes a product attribute mapping /// </summary> /// <param name="productAttributeMapping">Product attribute mapping</param> public virtual void DeleteProductAttributeMapping(ProductAttributeMapping productAttributeMapping) { if (productAttributeMapping == null) throw new ArgumentNullException("productAttributeMapping"); _productAttributeMappingRepository.Delete(productAttributeMapping); //cache _cacheManager.RemoveByPattern(PRODUCTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTATTRIBUTEMAPPINGS_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTATTRIBUTEVALUES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTATTRIBUTECOMBINATIONS_PATTERN_KEY); //event notification _eventPublisher.EntityDeleted(productAttributeMapping); } /// <summary> /// Gets product attribute mappings by product identifier /// </summary> /// <param name="productId">The product identifier</param> /// <returns>Product attribute mapping collection</returns> public virtual IList<ProductAttributeMapping> GetProductAttributeMappingsByProductId(int productId) { string key = string.Format(PRODUCTATTRIBUTEMAPPINGS_ALL_KEY, productId); return _cacheManager.Get(key, () => { var query = from pam in _productAttributeMappingRepository.Table orderby pam.DisplayOrder where pam.ProductId == productId select pam; var productAttributeMappings = query.ToList(); return productAttributeMappings; }); } /// <summary> /// Gets a product attribute mapping /// </summary> /// <param name="productAttributeMappingId">Product attribute mapping identifier</param> /// <returns>Product attribute mapping</returns> public virtual ProductAttributeMapping GetProductAttributeMappingById(int productAttributeMappingId) { if (productAttributeMappingId == 0) return null; string key = string.Format(PRODUCTATTRIBUTEMAPPINGS_BY_ID_KEY, productAttributeMappingId); return _cacheManager.Get(key, () => _productAttributeMappingRepository.GetById(productAttributeMappingId)); } /// <summary> /// Inserts a product attribute mapping /// </summary> /// <param name="productAttributeMapping">The product attribute mapping</param> public virtual void InsertProductAttributeMapping(ProductAttributeMapping productAttributeMapping) { if (productAttributeMapping == null) throw new ArgumentNullException("productAttributeMapping"); _productAttributeMappingRepository.Insert(productAttributeMapping); //cache _cacheManager.RemoveByPattern(PRODUCTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTATTRIBUTEMAPPINGS_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTATTRIBUTEVALUES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTATTRIBUTECOMBINATIONS_PATTERN_KEY); //event notification _eventPublisher.EntityInserted(productAttributeMapping); } /// <summary> /// Updates the product attribute mapping /// </summary> /// <param name="productAttributeMapping">The product attribute mapping</param> public virtual void UpdateProductAttributeMapping(ProductAttributeMapping productAttributeMapping) { if (productAttributeMapping == null) throw new ArgumentNullException("productAttributeMapping"); _productAttributeMappingRepository.Update(productAttributeMapping); //cache _cacheManager.RemoveByPattern(PRODUCTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTATTRIBUTEMAPPINGS_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTATTRIBUTEVALUES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTATTRIBUTECOMBINATIONS_PATTERN_KEY); //event notification _eventPublisher.EntityUpdated(productAttributeMapping); } #endregion #region Product attribute values /// <summary> /// Deletes a product attribute value /// </summary> /// <param name="productAttributeValue">Product attribute value</param> public virtual void DeleteProductAttributeValue(ProductAttributeValue productAttributeValue) { if (productAttributeValue == null) throw new ArgumentNullException("productAttributeValue"); _productAttributeValueRepository.Delete(productAttributeValue); //cache _cacheManager.RemoveByPattern(PRODUCTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTATTRIBUTEMAPPINGS_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTATTRIBUTEVALUES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTATTRIBUTECOMBINATIONS_PATTERN_KEY); //event notification _eventPublisher.EntityDeleted(productAttributeValue); } /// <summary> /// Gets product attribute values by product attribute mapping identifier /// </summary> /// <param name="productAttributeMappingId">The product attribute mapping identifier</param> /// <returns>Product attribute mapping collection</returns> public virtual IList<ProductAttributeValue> GetProductAttributeValues(int productAttributeMappingId) { string key = string.Format(PRODUCTATTRIBUTEVALUES_ALL_KEY, productAttributeMappingId); return _cacheManager.Get(key, () => { var query = from pav in _productAttributeValueRepository.Table orderby pav.DisplayOrder where pav.ProductAttributeMappingId == productAttributeMappingId select pav; var productAttributeValues = query.ToList(); return productAttributeValues; }); } /// <summary> /// Gets a product attribute value /// </summary> /// <param name="productAttributeValueId">Product attribute value identifier</param> /// <returns>Product attribute value</returns> public virtual ProductAttributeValue GetProductAttributeValueById(int productAttributeValueId) { if (productAttributeValueId == 0) return null; string key = string.Format(PRODUCTATTRIBUTEVALUES_BY_ID_KEY, productAttributeValueId); return _cacheManager.Get(key, () => _productAttributeValueRepository.GetById(productAttributeValueId)); } /// <summary> /// Inserts a product attribute value /// </summary> /// <param name="productAttributeValue">The product attribute value</param> public virtual void InsertProductAttributeValue(ProductAttributeValue productAttributeValue) { if (productAttributeValue == null) throw new ArgumentNullException("productAttributeValue"); _productAttributeValueRepository.Insert(productAttributeValue); //cache _cacheManager.RemoveByPattern(PRODUCTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTATTRIBUTEMAPPINGS_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTATTRIBUTEVALUES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTATTRIBUTECOMBINATIONS_PATTERN_KEY); //event notification _eventPublisher.EntityInserted(productAttributeValue); } /// <summary> /// Updates the product attribute value /// </summary> /// <param name="productAttributeValue">The product attribute value</param> public virtual void UpdateProductAttributeValue(ProductAttributeValue productAttributeValue) { if (productAttributeValue == null) throw new ArgumentNullException("productAttributeValue"); _productAttributeValueRepository.Update(productAttributeValue); //cache _cacheManager.RemoveByPattern(PRODUCTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTATTRIBUTEMAPPINGS_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTATTRIBUTEVALUES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTATTRIBUTECOMBINATIONS_PATTERN_KEY); //event notification _eventPublisher.EntityUpdated(productAttributeValue); } #endregion #region Product attribute combinations /// <summary> /// Deletes a product attribute combination /// </summary> /// <param name="combination">Product attribute combination</param> public virtual void DeleteProductAttributeCombination(ProductAttributeCombination combination) { if (combination == null) throw new ArgumentNullException("combination"); _productAttributeCombinationRepository.Delete(combination); //cache _cacheManager.RemoveByPattern(PRODUCTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTATTRIBUTEMAPPINGS_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTATTRIBUTEVALUES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTATTRIBUTECOMBINATIONS_PATTERN_KEY); //event notification _eventPublisher.EntityDeleted(combination); } /// <summary> /// Gets all product attribute combinations /// </summary> /// <param name="productId">Product identifier</param> /// <returns>Product attribute combination collection</returns> public virtual IList<ProductAttributeCombination> GetAllProductAttributeCombinations(int productId) { if (productId == 0) return new List<ProductAttributeCombination>(); string key = string.Format(PRODUCTATTRIBUTECOMBINATIONS_ALL_KEY, productId); return _cacheManager.Get(key, () => { var query = from c in _productAttributeCombinationRepository.Table orderby c.Id where c.ProductId == productId select c; var combinations = query.ToList(); return combinations; }); } /// <summary> /// Gets a product attribute combination /// </summary> /// <param name="productAttributeCombinationId">Product attribute combination identifier</param> /// <returns>Product attribute combination</returns> public virtual ProductAttributeCombination GetProductAttributeCombinationById(int productAttributeCombinationId) { if (productAttributeCombinationId == 0) return null; return _productAttributeCombinationRepository.GetById(productAttributeCombinationId); } /// <summary> /// Inserts a product attribute combination /// </summary> /// <param name="combination">Product attribute combination</param> public virtual void InsertProductAttributeCombination(ProductAttributeCombination combination) { if (combination == null) throw new ArgumentNullException("combination"); _productAttributeCombinationRepository.Insert(combination); //cache _cacheManager.RemoveByPattern(PRODUCTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTATTRIBUTEMAPPINGS_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTATTRIBUTEVALUES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTATTRIBUTECOMBINATIONS_PATTERN_KEY); //event notification _eventPublisher.EntityInserted(combination); } /// <summary> /// Updates a product attribute combination /// </summary> /// <param name="combination">Product attribute combination</param> public virtual void UpdateProductAttributeCombination(ProductAttributeCombination combination) { if (combination == null) throw new ArgumentNullException("combination"); _productAttributeCombinationRepository.Update(combination); //cache _cacheManager.RemoveByPattern(PRODUCTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTATTRIBUTEMAPPINGS_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTATTRIBUTEVALUES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTATTRIBUTECOMBINATIONS_PATTERN_KEY); //event notification _eventPublisher.EntityUpdated(combination); } #endregion #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Dynamic.Utils; using System.Reflection; namespace System.Linq.Expressions { /// <summary> /// Creates a <see cref="LambdaExpression"/> node. /// This captures a block of code that is similar to a .NET method body. /// </summary> /// <remarks> /// Lambda expressions take input through parameters and are expected to be fully bound. /// </remarks> [DebuggerTypeProxy(typeof(LambdaExpressionProxy))] public abstract partial class LambdaExpression : Expression, IParameterProvider { private readonly Expression _body; internal LambdaExpression(Expression body) { _body = body; } /// <summary> /// Gets the static type of the expression that this <see cref="Expression"/> represents. (Inherited from <see cref="Expression"/>.) /// </summary> /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns> public sealed override Type Type => TypeCore; internal abstract Type TypeCore { get; } internal abstract Type PublicType { get; } /// <summary> /// Returns the node type of this <see cref="Expression"/>. (Inherited from <see cref="Expression"/>.) /// </summary> /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns> public sealed override ExpressionType NodeType => ExpressionType.Lambda; /// <summary> /// Gets the parameters of the lambda expression. /// </summary> public ReadOnlyCollection<ParameterExpression> Parameters => GetOrMakeParameters(); /// <summary> /// Gets the name of the lambda expression. /// </summary> /// <remarks>Used for debugging purposes.</remarks> public string Name => NameCore; internal virtual string NameCore => null; /// <summary> /// Gets the body of the lambda expression. /// </summary> public Expression Body => _body; /// <summary> /// Gets the return type of the lambda expression. /// </summary> public Type ReturnType => Type.GetMethod("Invoke").ReturnType; /// <summary> /// Gets the value that indicates if the lambda expression will be compiled with /// tail call optimization. /// </summary> public bool TailCall => TailCallCore; internal virtual bool TailCallCore => false; [ExcludeFromCodeCoverage] // Unreachable internal virtual ReadOnlyCollection<ParameterExpression> GetOrMakeParameters() { throw ContractUtils.Unreachable; } [ExcludeFromCodeCoverage] // Unreachable ParameterExpression IParameterProvider.GetParameter(int index) => GetParameter(index); [ExcludeFromCodeCoverage] // Unreachable internal virtual ParameterExpression GetParameter(int index) { throw ContractUtils.Unreachable; } [ExcludeFromCodeCoverage] // Unreachable int IParameterProvider.ParameterCount => ParameterCount; [ExcludeFromCodeCoverage] // Unreachable internal virtual int ParameterCount { get { throw ContractUtils.Unreachable; } } /// <summary> /// Produces a delegate that represents the lambda expression. /// </summary> /// <returns>A delegate containing the compiled version of the lambda.</returns> public Delegate Compile() { return Compile(preferInterpretation: false); } /// <summary> /// Produces a delegate that represents the lambda expression. /// </summary> /// <param name="preferInterpretation">A <see cref="bool"/> that indicates if the expression should be compiled to an interpreted form, if available.</param> /// <returns>A delegate containing the compiled version of the lambda.</returns> public Delegate Compile(bool preferInterpretation) { #if FEATURE_COMPILE #if FEATURE_INTERPRET if (preferInterpretation) { return new Interpreter.LightCompiler().CompileTop(this).CreateDelegate(); } #endif return Compiler.LambdaCompiler.Compile(this); #else return new Interpreter.LightCompiler().CompileTop(this).CreateDelegate(); #endif } #if FEATURE_COMPILE_TO_METHODBUILDER /// <summary> /// Compiles the lambda into a method definition. /// </summary> /// <param name="method">A <see cref="Emit.MethodBuilder"/> which will be used to hold the lambda's IL.</param> public void CompileToMethod(System.Reflection.Emit.MethodBuilder method) { ContractUtils.RequiresNotNull(method, nameof(method)); ContractUtils.Requires(method.IsStatic, nameof(method)); var type = method.DeclaringType as System.Reflection.Emit.TypeBuilder; if (type == null) throw Error.MethodBuilderDoesNotHaveTypeBuilder(); Compiler.LambdaCompiler.Compile(this, method); } #endif #if FEATURE_COMPILE internal abstract LambdaExpression Accept(Compiler.StackSpiller spiller); #endif } /// <summary> /// Defines a <see cref="Expression{TDelegate}"/> node. /// This captures a block of code that is similar to a .NET method body. /// </summary> /// <typeparam name="TDelegate">The type of the delegate.</typeparam> /// <remarks> /// Lambda expressions take input through parameters and are expected to be fully bound. /// </remarks> public partial class Expression<TDelegate> : LambdaExpression { internal Expression(Expression body) : base(body) { } internal sealed override Type TypeCore => typeof(TDelegate); internal override Type PublicType => typeof(Expression<TDelegate>); /// <summary> /// Produces a delegate that represents the lambda expression. /// </summary> /// <returns>A delegate containing the compiled version of the lambda.</returns> public new TDelegate Compile() { return Compile(preferInterpretation: false); } /// <summary> /// Produces a delegate that represents the lambda expression. /// </summary> /// <param name="preferInterpretation">A <see cref="bool"/> that indicates if the expression should be compiled to an interpreted form, if available.</param> /// <returns>A delegate containing the compiled version of the lambda.</returns> public new TDelegate Compile(bool preferInterpretation) { #if FEATURE_COMPILE #if FEATURE_INTERPRET if (preferInterpretation) { return (TDelegate)(object)new Interpreter.LightCompiler().CompileTop(this).CreateDelegate(); } #endif return (TDelegate)(object)Compiler.LambdaCompiler.Compile(this); #else return (TDelegate)(object)new Interpreter.LightCompiler().CompileTop(this).CreateDelegate(); #endif } /// <summary> /// Creates a new expression that is like this one, but using the /// supplied children. If all of the children are the same, it will /// return this expression. /// </summary> /// <param name="body">The <see cref="LambdaExpression.Body" /> property of the result.</param> /// <param name="parameters">The <see cref="LambdaExpression.Parameters" /> property of the result.</param> /// <returns>This expression if no children changed, or an expression with the updated children.</returns> public Expression<TDelegate> Update(Expression body, IEnumerable<ParameterExpression> parameters) { if (body == Body) { // Ensure parameters is safe to enumerate twice. // (If this means a second call to ToReadOnly it will return quickly). ICollection<ParameterExpression> pars; if (parameters == null) { pars = null; } else { pars = parameters as ICollection<ParameterExpression>; if (pars == null) { parameters = pars = parameters.ToReadOnly(); } } if (SameParameters(pars)) { return this; } } return Lambda<TDelegate>(body, Name, TailCall, parameters); } [ExcludeFromCodeCoverage] // Unreachable internal virtual bool SameParameters(ICollection<ParameterExpression> parameters) { throw ContractUtils.Unreachable; } [ExcludeFromCodeCoverage] // Unreachable internal virtual Expression<TDelegate> Rewrite(Expression body, ParameterExpression[] parameters) { throw ContractUtils.Unreachable; } /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitLambda(this); } #if FEATURE_COMPILE internal override LambdaExpression Accept(Compiler.StackSpiller spiller) { return spiller.Rewrite(this); } internal static Expression<TDelegate> Create(Expression body, string name, bool tailCall, IReadOnlyList<ParameterExpression> parameters) { if (name == null && !tailCall) { switch (parameters.Count) { case 0: return new Expression0<TDelegate>(body); case 1: return new Expression1<TDelegate>(body, parameters[0]); case 2: return new Expression2<TDelegate>(body, parameters[0], parameters[1]); case 3: return new Expression3<TDelegate>(body, parameters[0], parameters[1], parameters[2]); default: return new ExpressionN<TDelegate>(body, parameters); } } return new FullExpression<TDelegate>(body, name, tailCall, parameters); } #endif } #if !FEATURE_COMPILE // Separate expression creation class to hide the CreateExpressionFunc function from users reflecting on Expression<T> public class ExpressionCreator<TDelegate> { public static LambdaExpression CreateExpressionFunc(Expression body, string name, bool tailCall, ReadOnlyCollection<ParameterExpression> parameters) { if (name == null && !tailCall) { switch (parameters.Count) { case 0: return new Expression0<TDelegate>(body); case 1: return new Expression1<TDelegate>(body, parameters[0]); case 2: return new Expression2<TDelegate>(body, parameters[0], parameters[1]); case 3: return new Expression3<TDelegate>(body, parameters[0], parameters[1], parameters[2]); default: return new ExpressionN<TDelegate>(body, parameters); } } return new FullExpression<TDelegate>(body, name, tailCall, parameters); } } #endif internal sealed class Expression0<TDelegate> : Expression<TDelegate> { public Expression0(Expression body) : base(body) { } internal override int ParameterCount => 0; internal override bool SameParameters(ICollection<ParameterExpression> parameters) => parameters == null || parameters.Count == 0; internal override ParameterExpression GetParameter(int index) { throw Error.ArgumentOutOfRange(nameof(index)); } internal override ReadOnlyCollection<ParameterExpression> GetOrMakeParameters() => EmptyReadOnlyCollection<ParameterExpression>.Instance; internal override Expression<TDelegate> Rewrite(Expression body, ParameterExpression[] parameters) { Debug.Assert(body != null); Debug.Assert(parameters == null || parameters.Length == 0); return Expression.Lambda<TDelegate>(body, parameters); } } internal sealed class Expression1<TDelegate> : Expression<TDelegate> { private object _par0; public Expression1(Expression body, ParameterExpression par0) : base(body) { _par0 = par0; } internal override int ParameterCount => 1; internal override ParameterExpression GetParameter(int index) { switch (index) { case 0: return ExpressionUtils.ReturnObject<ParameterExpression>(_par0); default: throw Error.ArgumentOutOfRange(nameof(index)); } } internal override bool SameParameters(ICollection<ParameterExpression> parameters) { if (parameters != null && parameters.Count == 1) { using (IEnumerator<ParameterExpression> en = parameters.GetEnumerator()) { en.MoveNext(); return en.Current == ExpressionUtils.ReturnObject<ParameterExpression>(_par0); } } return false; } internal override ReadOnlyCollection<ParameterExpression> GetOrMakeParameters() => ExpressionUtils.ReturnReadOnly(this, ref _par0); internal override Expression<TDelegate> Rewrite(Expression body, ParameterExpression[] parameters) { Debug.Assert(body != null); Debug.Assert(parameters == null || parameters.Length == 1); if (parameters != null) { return Expression.Lambda<TDelegate>(body, parameters); } return Expression.Lambda<TDelegate>(body, ExpressionUtils.ReturnObject<ParameterExpression>(_par0)); } } internal sealed class Expression2<TDelegate> : Expression<TDelegate> { private object _par0; private readonly ParameterExpression _par1; public Expression2(Expression body, ParameterExpression par0, ParameterExpression par1) : base(body) { _par0 = par0; _par1 = par1; } internal override int ParameterCount => 2; internal override ParameterExpression GetParameter(int index) { switch (index) { case 0: return ExpressionUtils.ReturnObject<ParameterExpression>(_par0); case 1: return _par1; default: throw Error.ArgumentOutOfRange(nameof(index)); } } internal override bool SameParameters(ICollection<ParameterExpression> parameters) { if (parameters != null && parameters.Count == 2) { ReadOnlyCollection<ParameterExpression> alreadyCollection = _par0 as ReadOnlyCollection<ParameterExpression>; if (alreadyCollection != null) { return ExpressionUtils.SameElements(parameters, alreadyCollection); } using (IEnumerator<ParameterExpression> en = parameters.GetEnumerator()) { en.MoveNext(); if (en.Current == _par0) { en.MoveNext(); return en.Current == _par1; } } } return false; } internal override ReadOnlyCollection<ParameterExpression> GetOrMakeParameters() => ExpressionUtils.ReturnReadOnly(this, ref _par0); internal override Expression<TDelegate> Rewrite(Expression body, ParameterExpression[] parameters) { Debug.Assert(body != null); Debug.Assert(parameters == null || parameters.Length == 2); if (parameters != null) { return Expression.Lambda<TDelegate>(body, parameters); } return Expression.Lambda<TDelegate>(body, ExpressionUtils.ReturnObject<ParameterExpression>(_par0), _par1); } } internal sealed class Expression3<TDelegate> : Expression<TDelegate> { private object _par0; private readonly ParameterExpression _par1; private readonly ParameterExpression _par2; public Expression3(Expression body, ParameterExpression par0, ParameterExpression par1, ParameterExpression par2) : base(body) { _par0 = par0; _par1 = par1; _par2 = par2; } internal override int ParameterCount => 3; internal override ParameterExpression GetParameter(int index) { switch (index) { case 0: return ExpressionUtils.ReturnObject<ParameterExpression>(_par0); case 1: return _par1; case 2: return _par2; default: throw Error.ArgumentOutOfRange(nameof(index)); } } internal override bool SameParameters(ICollection<ParameterExpression> parameters) { if (parameters != null && parameters.Count == 3) { ReadOnlyCollection<ParameterExpression> alreadyCollection = _par0 as ReadOnlyCollection<ParameterExpression>; if (alreadyCollection != null) { return ExpressionUtils.SameElements(parameters, alreadyCollection); } using (IEnumerator<ParameterExpression> en = parameters.GetEnumerator()) { en.MoveNext(); if (en.Current == _par0) { en.MoveNext(); if (en.Current == _par1) { en.MoveNext(); return en.Current == _par2; } } } } return false; } internal override ReadOnlyCollection<ParameterExpression> GetOrMakeParameters() => ExpressionUtils.ReturnReadOnly(this, ref _par0); internal override Expression<TDelegate> Rewrite(Expression body, ParameterExpression[] parameters) { Debug.Assert(body != null); Debug.Assert(parameters == null || parameters.Length == 3); if (parameters != null) { return Expression.Lambda<TDelegate>(body, parameters); } return Expression.Lambda<TDelegate>(body, ExpressionUtils.ReturnObject<ParameterExpression>(_par0), _par1, _par2); } } internal class ExpressionN<TDelegate> : Expression<TDelegate> { private IReadOnlyList<ParameterExpression> _parameters; public ExpressionN(Expression body, IReadOnlyList<ParameterExpression> parameters) : base(body) { _parameters = parameters; } internal override int ParameterCount => _parameters.Count; internal override ParameterExpression GetParameter(int index) => _parameters[index]; internal override bool SameParameters(ICollection<ParameterExpression> parameters) => ExpressionUtils.SameElements(parameters, _parameters); internal override ReadOnlyCollection<ParameterExpression> GetOrMakeParameters() => ExpressionUtils.ReturnReadOnly(ref _parameters); internal override Expression<TDelegate> Rewrite(Expression body, ParameterExpression[] parameters) { Debug.Assert(body != null); Debug.Assert(parameters == null || parameters.Length == _parameters.Count); return Expression.Lambda<TDelegate>(body, Name, TailCall, parameters ?? _parameters); } } internal sealed class FullExpression<TDelegate> : ExpressionN<TDelegate> { public FullExpression(Expression body, string name, bool tailCall, IReadOnlyList<ParameterExpression> parameters) : base(body, parameters) { NameCore = name; TailCallCore = tailCall; } internal override string NameCore { get; } internal override bool TailCallCore { get; } } public partial class Expression { /// <summary> /// Creates an Expression{T} given the delegate type. Caches the /// factory method to speed up repeated creations for the same T. /// </summary> internal static LambdaExpression CreateLambda(Type delegateType, Expression body, string name, bool tailCall, ReadOnlyCollection<ParameterExpression> parameters) { // Get or create a delegate to the public Expression.Lambda<T> // method and call that will be used for creating instances of this // delegate type Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression> fastPath; CacheDict<Type, Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>> factories = s_lambdaFactories; if (factories == null) { s_lambdaFactories = factories = new CacheDict<Type, Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>>(50); } MethodInfo create = null; if (!factories.TryGetValue(delegateType, out fastPath)) { #if FEATURE_COMPILE create = typeof(Expression<>).MakeGenericType(delegateType).GetMethod("Create", BindingFlags.Static | BindingFlags.NonPublic); #else create = typeof(ExpressionCreator<>).MakeGenericType(delegateType).GetMethod("CreateExpressionFunc", BindingFlags.Static | BindingFlags.Public); #endif if (delegateType.CanCache()) { factories[delegateType] = fastPath = (Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>)create.CreateDelegate(typeof(Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>)); } } if (fastPath != null) { return fastPath(body, name, tailCall, parameters); } Debug.Assert(create != null); return (LambdaExpression)create.Invoke(null, new object[] { body, name, tailCall, parameters }); } /// <summary> /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time. /// </summary> /// <typeparam name="TDelegate">The delegate type.</typeparam> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static Expression<TDelegate> Lambda<TDelegate>(Expression body, params ParameterExpression[] parameters) { return Lambda<TDelegate>(body, false, (IEnumerable<ParameterExpression>)parameters); } /// <summary> /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time. /// </summary> /// <typeparam name="TDelegate">The delegate type.</typeparam> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="tailCall">A <see cref="bool"/> that indicates if tail call optimization will be applied when compiling the created expression.</param> /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static Expression<TDelegate> Lambda<TDelegate>(Expression body, bool tailCall, params ParameterExpression[] parameters) { return Lambda<TDelegate>(body, tailCall, (IEnumerable<ParameterExpression>)parameters); } /// <summary> /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time. /// </summary> /// <typeparam name="TDelegate">The delegate type.</typeparam> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static Expression<TDelegate> Lambda<TDelegate>(Expression body, IEnumerable<ParameterExpression> parameters) { return Lambda<TDelegate>(body, null, false, parameters); } /// <summary> /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time. /// </summary> /// <typeparam name="TDelegate">The delegate type.</typeparam> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="tailCall">A <see cref="bool"/> that indicates if tail call optimization will be applied when compiling the created expression.</param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static Expression<TDelegate> Lambda<TDelegate>(Expression body, bool tailCall, IEnumerable<ParameterExpression> parameters) { return Lambda<TDelegate>(body, null, tailCall, parameters); } /// <summary> /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time. /// </summary> /// <typeparam name="TDelegate">The delegate type.</typeparam> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <param name="name">The name of the lambda. Used for generating debugging info.</param> /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static Expression<TDelegate> Lambda<TDelegate>(Expression body, string name, IEnumerable<ParameterExpression> parameters) { return Lambda<TDelegate>(body, name, false, parameters); } /// <summary> /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time. /// </summary> /// <typeparam name="TDelegate">The delegate type.</typeparam> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="name">The name of the lambda. Used for generating debugging info.</param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <param name="tailCall">A <see cref="bool"/> that indicates if tail call optimization will be applied when compiling the created expression.</param> /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static Expression<TDelegate> Lambda<TDelegate>(Expression body, string name, bool tailCall, IEnumerable<ParameterExpression> parameters) { ReadOnlyCollection<ParameterExpression> parameterList = parameters.ToReadOnly(); ValidateLambdaArgs(typeof(TDelegate), ref body, parameterList, nameof(TDelegate)); return (Expression<TDelegate>)CreateLambda(typeof(TDelegate), body, name, tailCall, parameterList); } /// <summary> /// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Expression body, params ParameterExpression[] parameters) { return Lambda(body, false, (IEnumerable<ParameterExpression>)parameters); } /// <summary> /// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="tailCall">A <see cref="bool"/> that indicates if tail call optimization will be applied when compiling the created expression.</param> /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Expression body, bool tailCall, params ParameterExpression[] parameters) { return Lambda(body, tailCall, (IEnumerable<ParameterExpression>)parameters); } /// <summary> /// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Expression body, IEnumerable<ParameterExpression> parameters) { return Lambda(body, null, false, parameters); } /// <summary> /// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="tailCall">A <see cref="bool"/> that indicates if tail call optimization will be applied when compiling the created expression.</param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Expression body, bool tailCall, IEnumerable<ParameterExpression> parameters) { return Lambda(body, null, tailCall, parameters); } /// <summary> /// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Type delegateType, Expression body, params ParameterExpression[] parameters) { return Lambda(delegateType, body, null, false, parameters); } /// <summary> /// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="tailCall">A <see cref="bool"/> that indicates if tail call optimization will be applied when compiling the created expression.</param> /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Type delegateType, Expression body, bool tailCall, params ParameterExpression[] parameters) { return Lambda(delegateType, body, null, tailCall, parameters); } /// <summary> /// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Type delegateType, Expression body, IEnumerable<ParameterExpression> parameters) { return Lambda(delegateType, body, null, false, parameters); } /// <summary> /// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="tailCall">A <see cref="bool"/> that indicates if tail call optimization will be applied when compiling the created expression.</param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Type delegateType, Expression body, bool tailCall, IEnumerable<ParameterExpression> parameters) { return Lambda(delegateType, body, null, tailCall, parameters); } /// <summary> /// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <param name="name">The name for the lambda. Used for emitting debug information.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Expression body, string name, IEnumerable<ParameterExpression> parameters) { return Lambda(body, name, false, parameters); } /// <summary> /// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="name">The name for the lambda. Used for emitting debug information.</param> /// <param name="tailCall">A <see cref="bool"/> that indicates if tail call optimization will be applied when compiling the created expression.</param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Expression body, string name, bool tailCall, IEnumerable<ParameterExpression> parameters) { ContractUtils.RequiresNotNull(body, nameof(body)); ReadOnlyCollection<ParameterExpression> parameterList = parameters.ToReadOnly(); int paramCount = parameterList.Count; Type[] typeArgs = new Type[paramCount + 1]; if (paramCount > 0) { var set = new HashSet<ParameterExpression>(); for (int i = 0; i < paramCount; i++) { ParameterExpression param = parameterList[i]; ContractUtils.RequiresNotNull(param, "parameter"); typeArgs[i] = param.IsByRef ? param.Type.MakeByRefType() : param.Type; if (!set.Add(param)) { throw Error.DuplicateVariable(param, nameof(parameters), i); } } } typeArgs[paramCount] = body.Type; Type delegateType = Compiler.DelegateHelpers.MakeDelegateType(typeArgs); return CreateLambda(delegateType, body, name, tailCall, parameterList); } /// <summary> /// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <param name="name">The name for the lambda. Used for emitting debug information.</param> /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Type delegateType, Expression body, string name, IEnumerable<ParameterExpression> parameters) { ReadOnlyCollection<ParameterExpression> paramList = parameters.ToReadOnly(); ValidateLambdaArgs(delegateType, ref body, paramList, nameof(delegateType)); return CreateLambda(delegateType, body, name, false, paramList); } /// <summary> /// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type. /// </summary> /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="name">The name for the lambda. Used for emitting debug information.</param> /// <param name="tailCall">A <see cref="bool"/> that indicates if tail call optimization will be applied when compiling the created expression.</param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Type delegateType, Expression body, string name, bool tailCall, IEnumerable<ParameterExpression> parameters) { ReadOnlyCollection<ParameterExpression> paramList = parameters.ToReadOnly(); ValidateLambdaArgs(delegateType, ref body, paramList, nameof(delegateType)); return CreateLambda(delegateType, body, name, tailCall, paramList); } private static void ValidateLambdaArgs(Type delegateType, ref Expression body, ReadOnlyCollection<ParameterExpression> parameters, string paramName) { ContractUtils.RequiresNotNull(delegateType, nameof(delegateType)); ExpressionUtils.RequiresCanRead(body, nameof(body)); if (!typeof(MulticastDelegate).IsAssignableFrom(delegateType) || delegateType == typeof(MulticastDelegate)) { throw Error.LambdaTypeMustBeDerivedFromSystemDelegate(paramName); } TypeUtils.ValidateType(delegateType, nameof(delegateType)); MethodInfo mi; CacheDict<Type, MethodInfo> ldc = s_lambdaDelegateCache; if (!ldc.TryGetValue(delegateType, out mi)) { mi = delegateType.GetMethod("Invoke"); if (delegateType.CanCache()) { ldc[delegateType] = mi; } } ParameterInfo[] pis = mi.GetParametersCached(); if (pis.Length > 0) { if (pis.Length != parameters.Count) { throw Error.IncorrectNumberOfLambdaDeclarationParameters(); } var set = new HashSet<ParameterExpression>(); for (int i = 0, n = pis.Length; i < n; i++) { ParameterExpression pex = parameters[i]; ParameterInfo pi = pis[i]; ExpressionUtils.RequiresCanRead(pex, nameof(parameters), i); Type pType = pi.ParameterType; if (pex.IsByRef) { if (!pType.IsByRef) { //We cannot pass a parameter of T& to a delegate that takes T or any non-ByRef type. throw Error.ParameterExpressionNotValidAsDelegate(pex.Type.MakeByRefType(), pType); } pType = pType.GetElementType(); } if (!TypeUtils.AreReferenceAssignable(pex.Type, pType)) { throw Error.ParameterExpressionNotValidAsDelegate(pex.Type, pType); } if (!set.Add(pex)) { throw Error.DuplicateVariable(pex, nameof(parameters), i); } } } else if (parameters.Count > 0) { throw Error.IncorrectNumberOfLambdaDeclarationParameters(); } if (mi.ReturnType != typeof(void) && !TypeUtils.AreReferenceAssignable(mi.ReturnType, body.Type)) { if (!TryQuote(mi.ReturnType, ref body)) { throw Error.ExpressionTypeDoesNotMatchReturn(body.Type, mi.ReturnType); } } } private enum TryGetFuncActionArgsResult { Valid, ArgumentNull, ByRef, PointerOrVoid } private static TryGetFuncActionArgsResult ValidateTryGetFuncActionArgs(Type[] typeArgs) { if (typeArgs == null) { return TryGetFuncActionArgsResult.ArgumentNull; } for (int i = 0; i < typeArgs.Length; i++) { Type a = typeArgs[i]; if (a == null) { return TryGetFuncActionArgsResult.ArgumentNull; } if (a.IsByRef) { return TryGetFuncActionArgsResult.ByRef; } if (a == typeof(void) || a.IsPointer) { return TryGetFuncActionArgsResult.PointerOrVoid; } } return TryGetFuncActionArgsResult.Valid; } /// <summary> /// Creates a <see cref="System.Type"/> object that represents a generic System.Func delegate type that has specific type arguments. /// The last type argument specifies the return type of the created delegate. /// </summary> /// <param name="typeArgs">An array of <see cref="System.Type"/> objects that specify the type arguments for the System.Func delegate type.</param> /// <returns>The type of a System.Func delegate that has the specified type arguments.</returns> public static Type GetFuncType(params Type[] typeArgs) { switch (ValidateTryGetFuncActionArgs(typeArgs)) { case TryGetFuncActionArgsResult.ArgumentNull: throw new ArgumentNullException(nameof(typeArgs)); case TryGetFuncActionArgsResult.ByRef: throw Error.TypeMustNotBeByRef(nameof(typeArgs)); default: // This includes pointers or void. We allow the exception that comes // from trying to use them as generic arguments to pass through. Type result = Compiler.DelegateHelpers.GetFuncType(typeArgs); if (result == null) { throw Error.IncorrectNumberOfTypeArgsForFunc(nameof(typeArgs)); } return result; } } /// <summary> /// Creates a <see cref="System.Type"/> object that represents a generic System.Func delegate type that has specific type arguments. /// The last type argument specifies the return type of the created delegate. /// </summary> /// <param name="typeArgs">An array of <see cref="System.Type"/> objects that specify the type arguments for the System.Func delegate type.</param> /// <param name="funcType">When this method returns, contains the generic System.Func delegate type that has specific type arguments. Contains null if there is no generic System.Func delegate that matches the <paramref name="typeArgs"/>.This parameter is passed uninitialized.</param> /// <returns>true if generic System.Func delegate type was created for specific <paramref name="typeArgs"/>; false otherwise.</returns> public static bool TryGetFuncType(Type[] typeArgs, out Type funcType) { if (ValidateTryGetFuncActionArgs(typeArgs) == TryGetFuncActionArgsResult.Valid) { return (funcType = Compiler.DelegateHelpers.GetFuncType(typeArgs)) != null; } funcType = null; return false; } /// <summary> /// Creates a <see cref="System.Type"/> object that represents a generic System.Action delegate type that has specific type arguments. /// </summary> /// <param name="typeArgs">An array of <see cref="System.Type"/> objects that specify the type arguments for the System.Action delegate type.</param> /// <returns>The type of a System.Action delegate that has the specified type arguments.</returns> public static Type GetActionType(params Type[] typeArgs) { switch (ValidateTryGetFuncActionArgs(typeArgs)) { case TryGetFuncActionArgsResult.ArgumentNull: throw new ArgumentNullException(nameof(typeArgs)); case TryGetFuncActionArgsResult.ByRef: throw Error.TypeMustNotBeByRef(nameof(typeArgs)); default: // This includes pointers or void. We allow the exception that comes // from trying to use them as generic arguments to pass through. Type result = Compiler.DelegateHelpers.GetActionType(typeArgs); if (result == null) { throw Error.IncorrectNumberOfTypeArgsForAction(nameof(typeArgs)); } return result; } } /// <summary> /// Creates a <see cref="System.Type"/> object that represents a generic System.Action delegate type that has specific type arguments. /// </summary> /// <param name="typeArgs">An array of <see cref="System.Type"/> objects that specify the type arguments for the System.Action delegate type.</param> /// <param name="actionType">When this method returns, contains the generic System.Action delegate type that has specific type arguments. Contains null if there is no generic System.Action delegate that matches the <paramref name="typeArgs"/>.This parameter is passed uninitialized.</param> /// <returns>true if generic System.Action delegate type was created for specific <paramref name="typeArgs"/>; false otherwise.</returns> public static bool TryGetActionType(Type[] typeArgs, out Type actionType) { if (ValidateTryGetFuncActionArgs(typeArgs) == TryGetFuncActionArgsResult.Valid) { return (actionType = Compiler.DelegateHelpers.GetActionType(typeArgs)) != null; } actionType = null; return false; } /// <summary> /// Gets a <see cref="System.Type"/> object that represents a generic System.Func or System.Action delegate type that has specific type arguments. /// The last type argument determines the return type of the delegate. If no Func or Action is large enough, it will generate a custom /// delegate type. /// </summary> /// <param name="typeArgs">An array of <see cref="System.Type"/> objects that specify the type arguments of the delegate type.</param> /// <returns>The delegate type.</returns> /// <remarks> /// As with Func, the last argument is the return type. It can be set /// to <see cref="System.Void"/> to produce an Action.</remarks> public static Type GetDelegateType(params Type[] typeArgs) { ContractUtils.RequiresNotEmpty(typeArgs, nameof(typeArgs)); ContractUtils.RequiresNotNullItems(typeArgs, nameof(typeArgs)); return Compiler.DelegateHelpers.MakeDelegateType(typeArgs); } } }
// 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.Buffers.Binary; using System.Text; using System.Threading; using System.Threading.Tasks; using Thrift.Protocol.Entities; using Thrift.Transport; namespace Thrift.Protocol { // ReSharper disable once InconsistentNaming public class TBinaryProtocol : TProtocol { protected const uint VersionMask = 0xffff0000; protected const uint Version1 = 0x80010000; protected bool StrictRead; protected bool StrictWrite; // minimize memory allocations by means of an preallocated bytes buffer // The value of 128 is arbitrarily chosen, the required minimum size must be sizeof(long) private readonly byte[] PreAllocatedBuffer = new byte[128]; public TBinaryProtocol(TTransport trans) : this(trans, false, true) { } public TBinaryProtocol(TTransport trans, bool strictRead, bool strictWrite) : base(trans) { StrictRead = strictRead; StrictWrite = strictWrite; } public override async Task WriteMessageBeginAsync(TMessage message, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (StrictWrite) { var version = Version1 | (uint) message.Type; await WriteI32Async((int) version, cancellationToken); await WriteStringAsync(message.Name, cancellationToken); await WriteI32Async(message.SeqID, cancellationToken); } else { await WriteStringAsync(message.Name, cancellationToken); await WriteByteAsync((sbyte) message.Type, cancellationToken); await WriteI32Async(message.SeqID, cancellationToken); } } public override Task WriteMessageEndAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return Task.CompletedTask; } public override Task WriteStructBeginAsync(TStruct @struct, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return Task.CompletedTask; } public override Task WriteStructEndAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return Task.CompletedTask; } public override async Task WriteFieldBeginAsync(TField field, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); await WriteByteAsync((sbyte) field.Type, cancellationToken); await WriteI16Async(field.ID, cancellationToken); } public override Task WriteFieldEndAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return Task.CompletedTask; } public override async Task WriteFieldStopAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); await WriteByteAsync((sbyte) TType.Stop, cancellationToken); } public override async Task WriteMapBeginAsync(TMap map, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); PreAllocatedBuffer[0] = (byte)map.KeyType; PreAllocatedBuffer[1] = (byte)map.ValueType; await Trans.WriteAsync(PreAllocatedBuffer, 0, 2, cancellationToken); await WriteI32Async(map.Count, cancellationToken); } public override Task WriteMapEndAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return Task.CompletedTask; } public override async Task WriteListBeginAsync(TList list, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); await WriteByteAsync((sbyte) list.ElementType, cancellationToken); await WriteI32Async(list.Count, cancellationToken); } public override Task WriteListEndAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return Task.CompletedTask; } public override async Task WriteSetBeginAsync(TSet set, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); await WriteByteAsync((sbyte) set.ElementType, cancellationToken); await WriteI32Async(set.Count, cancellationToken); } public override Task WriteSetEndAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return Task.CompletedTask; } public override async Task WriteBoolAsync(bool b, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); await WriteByteAsync(b ? (sbyte) 1 : (sbyte) 0, cancellationToken); } public override async Task WriteByteAsync(sbyte b, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); PreAllocatedBuffer[0] = (byte)b; await Trans.WriteAsync(PreAllocatedBuffer, 0, 1, cancellationToken); } public override async Task WriteI16Async(short i16, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); BinaryPrimitives.WriteInt16BigEndian(PreAllocatedBuffer, i16); await Trans.WriteAsync(PreAllocatedBuffer, 0, 2, cancellationToken); } public override async Task WriteI32Async(int i32, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); BinaryPrimitives.WriteInt32BigEndian(PreAllocatedBuffer, i32); await Trans.WriteAsync(PreAllocatedBuffer, 0, 4, cancellationToken); } public override async Task WriteI64Async(long i64, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); BinaryPrimitives.WriteInt64BigEndian(PreAllocatedBuffer, i64); await Trans.WriteAsync(PreAllocatedBuffer, 0, 8, cancellationToken); } public override async Task WriteDoubleAsync(double d, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); await WriteI64Async(BitConverter.DoubleToInt64Bits(d), cancellationToken); } public override async Task WriteBinaryAsync(byte[] bytes, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); await WriteI32Async(bytes.Length, cancellationToken); await Trans.WriteAsync(bytes, 0, bytes.Length, cancellationToken); } public override async ValueTask<TMessage> ReadMessageBeginAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var message = new TMessage(); var size = await ReadI32Async(cancellationToken); if (size < 0) { var version = (uint) size & VersionMask; if (version != Version1) { throw new TProtocolException(TProtocolException.BAD_VERSION, $"Bad version in ReadMessageBegin: {version}"); } message.Type = (TMessageType) (size & 0x000000ff); message.Name = await ReadStringAsync(cancellationToken); message.SeqID = await ReadI32Async(cancellationToken); } else { if (StrictRead) { throw new TProtocolException(TProtocolException.BAD_VERSION, "Missing version in ReadMessageBegin, old client?"); } message.Name = (size > 0) ? await ReadStringBodyAsync(size, cancellationToken) : string.Empty; message.Type = (TMessageType) await ReadByteAsync(cancellationToken); message.SeqID = await ReadI32Async(cancellationToken); } return message; } public override Task ReadMessageEndAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return Task.CompletedTask; } public override ValueTask<TStruct> ReadStructBeginAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return new ValueTask<TStruct>(AnonymousStruct); } public override Task ReadStructEndAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return Task.CompletedTask; } public override async ValueTask<TField> ReadFieldBeginAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var type = (TType)await ReadByteAsync(cancellationToken); if (type == TType.Stop) { return StopField; } return new TField { Type = type, ID = await ReadI16Async(cancellationToken) }; } public override Task ReadFieldEndAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return Task.CompletedTask; } public override async ValueTask<TMap> ReadMapBeginAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var map = new TMap { KeyType = (TType) await ReadByteAsync(cancellationToken), ValueType = (TType) await ReadByteAsync(cancellationToken), Count = await ReadI32Async(cancellationToken) }; CheckReadBytesAvailable(map); return map; } public override Task ReadMapEndAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return Task.CompletedTask; } public override async ValueTask<TList> ReadListBeginAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var list = new TList { ElementType = (TType) await ReadByteAsync(cancellationToken), Count = await ReadI32Async(cancellationToken) }; CheckReadBytesAvailable(list); return list; } public override Task ReadListEndAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return Task.CompletedTask; } public override async ValueTask<TSet> ReadSetBeginAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var set = new TSet { ElementType = (TType) await ReadByteAsync(cancellationToken), Count = await ReadI32Async(cancellationToken) }; CheckReadBytesAvailable(set); return set; } public override Task ReadSetEndAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return Task.CompletedTask; } public override async ValueTask<bool> ReadBoolAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return await ReadByteAsync(cancellationToken) == 1; } public override async ValueTask<sbyte> ReadByteAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); await Trans.ReadAllAsync(PreAllocatedBuffer, 0, 1, cancellationToken); return (sbyte)PreAllocatedBuffer[0]; } public override async ValueTask<short> ReadI16Async(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); await Trans.ReadAllAsync(PreAllocatedBuffer, 0, 2, cancellationToken); var result = BinaryPrimitives.ReadInt16BigEndian(PreAllocatedBuffer); return result; } public override async ValueTask<int> ReadI32Async(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); await Trans.ReadAllAsync(PreAllocatedBuffer, 0, 4, cancellationToken); var result = BinaryPrimitives.ReadInt32BigEndian(PreAllocatedBuffer); return result; } public override async ValueTask<long> ReadI64Async(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); await Trans.ReadAllAsync(PreAllocatedBuffer, 0, 8, cancellationToken); return BinaryPrimitives.ReadInt64BigEndian(PreAllocatedBuffer); } public override async ValueTask<double> ReadDoubleAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var d = await ReadI64Async(cancellationToken); return BitConverter.Int64BitsToDouble(d); } public override async ValueTask<byte[]> ReadBinaryAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var size = await ReadI32Async(cancellationToken); Transport.CheckReadBytesAvailable(size); var buf = new byte[size]; await Trans.ReadAllAsync(buf, 0, size, cancellationToken); return buf; } public override async ValueTask<string> ReadStringAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var size = await ReadI32Async(cancellationToken); return size > 0 ? await ReadStringBodyAsync(size, cancellationToken) : string.Empty; } private async ValueTask<string> ReadStringBodyAsync(int size, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (size <= PreAllocatedBuffer.Length) { await Trans.ReadAllAsync(PreAllocatedBuffer, 0, size, cancellationToken); return Encoding.UTF8.GetString(PreAllocatedBuffer, 0, size); } Transport.CheckReadBytesAvailable(size); var buf = new byte[size]; await Trans.ReadAllAsync(buf, 0, size, cancellationToken); return Encoding.UTF8.GetString(buf, 0, buf.Length); } // Return the minimum number of bytes a type will consume on the wire public override int GetMinSerializedSize(TType type) { switch (type) { case TType.Stop: return 0; case TType.Void: return 0; case TType.Bool: return sizeof(byte); case TType.Byte: return sizeof(byte); case TType.Double: return sizeof(double); case TType.I16: return sizeof(short); case TType.I32: return sizeof(int); case TType.I64: return sizeof(long); case TType.String: return sizeof(int); // string length case TType.Struct: return 0; // empty struct case TType.Map: return sizeof(int); // element count case TType.Set: return sizeof(int); // element count case TType.List: return sizeof(int); // element count default: throw new TProtocolException(TProtocolException.NOT_IMPLEMENTED, "unrecognized type code"); } } public class Factory : TProtocolFactory { protected bool StrictRead; protected bool StrictWrite; public Factory() : this(false, true) { } public Factory(bool strictRead, bool strictWrite) { StrictRead = strictRead; StrictWrite = strictWrite; } public override TProtocol GetProtocol(TTransport trans) { return new TBinaryProtocol(trans, StrictRead, StrictWrite); } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Threading; using log4net; using Mono.Addins; using Nini.Config; using Nwc.XmlRpc; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Servers; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.CoreModules.Avatar.Chat; namespace OpenSim.Region.OptionalModules.Avatar.Concierge { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "ConciergeModule")] public class ConciergeModule : ChatModule, ISharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // private const int DEBUG_CHANNEL = 2147483647; use base value private new List<IScene> m_scenes = new List<IScene>(); private List<IScene> m_conciergedScenes = new List<IScene>(); private bool m_replacingChatModule = false; private string m_whoami = "conferencier"; private Regex m_regions = null; private string m_welcomes = null; private int m_conciergeChannel = 42; private string m_announceEntering = "{0} enters {1} (now {2} visitors in this region)"; private string m_announceLeaving = "{0} leaves {1} (back to {2} visitors in this region)"; private string m_xmlRpcPassword = String.Empty; private string m_brokerURI = String.Empty; private int m_brokerUpdateTimeout = 300; internal new object m_syncy = new object(); internal new bool m_enabled = false; #region ISharedRegionModule Members public override void Initialise(IConfigSource configSource) { IConfig config = configSource.Configs["Concierge"]; if (config == null) return; if (!config.GetBoolean("enabled", false)) return; m_enabled = true; // check whether ChatModule has been disabled: if yes, // then we'll "stand in" try { if (configSource.Configs["Chat"] == null) { // if Chat module has not been configured it's // enabled by default, so we are not going to // replace it. m_replacingChatModule = false; } else { m_replacingChatModule = !configSource.Configs["Chat"].GetBoolean("enabled", true); } } catch (Exception) { m_replacingChatModule = false; } m_log.InfoFormat("[Concierge] {0} ChatModule", m_replacingChatModule ? "replacing" : "not replacing"); // take note of concierge channel and of identity m_conciergeChannel = configSource.Configs["Concierge"].GetInt("concierge_channel", m_conciergeChannel); m_whoami = config.GetString("whoami", "conferencier"); m_welcomes = config.GetString("welcomes", m_welcomes); m_announceEntering = config.GetString("announce_entering", m_announceEntering); m_announceLeaving = config.GetString("announce_leaving", m_announceLeaving); m_xmlRpcPassword = config.GetString("password", m_xmlRpcPassword); m_brokerURI = config.GetString("broker", m_brokerURI); m_brokerUpdateTimeout = config.GetInt("broker_timeout", m_brokerUpdateTimeout); m_log.InfoFormat("[Concierge] reporting as \"{0}\" to our users", m_whoami); // calculate regions Regex if (m_regions == null) { string regions = config.GetString("regions", String.Empty); if (!String.IsNullOrEmpty(regions)) { m_regions = new Regex(@regions, RegexOptions.Compiled | RegexOptions.IgnoreCase); } } } public override void AddRegion(Scene scene) { if (!m_enabled) return; MainServer.Instance.AddXmlRPCHandler("concierge_update_welcome", XmlRpcUpdateWelcomeMethod, false); lock (m_syncy) { if (!m_scenes.Contains(scene)) { m_scenes.Add(scene); if (m_regions == null || m_regions.IsMatch(scene.RegionInfo.RegionName)) m_conciergedScenes.Add(scene); // subscribe to NewClient events scene.EventManager.OnNewClient += OnNewClient; // subscribe to *Chat events scene.EventManager.OnChatFromWorld += OnChatFromWorld; if (!m_replacingChatModule) scene.EventManager.OnChatFromClient += OnChatFromClient; scene.EventManager.OnChatBroadcast += OnChatBroadcast; // subscribe to agent change events scene.EventManager.OnMakeRootAgent += OnMakeRootAgent; scene.EventManager.OnMakeChildAgent += OnMakeChildAgent; } } m_log.InfoFormat("[Concierge]: initialized for {0}", scene.RegionInfo.RegionName); } public override void RemoveRegion(Scene scene) { if (!m_enabled) return; MainServer.Instance.RemoveXmlRPCHandler("concierge_update_welcome"); lock (m_syncy) { // unsubscribe from NewClient events scene.EventManager.OnNewClient -= OnNewClient; // unsubscribe from *Chat events scene.EventManager.OnChatFromWorld -= OnChatFromWorld; if (!m_replacingChatModule) scene.EventManager.OnChatFromClient -= OnChatFromClient; scene.EventManager.OnChatBroadcast -= OnChatBroadcast; // unsubscribe from agent change events scene.EventManager.OnMakeRootAgent -= OnMakeRootAgent; scene.EventManager.OnMakeChildAgent -= OnMakeChildAgent; if (m_scenes.Contains(scene)) { m_scenes.Remove(scene); } if (m_conciergedScenes.Contains(scene)) { m_conciergedScenes.Remove(scene); } } m_log.InfoFormat("[Concierge]: removed {0}", scene.RegionInfo.RegionName); } public override void PostInitialise() { } public override void Close() { } new public Type ReplaceableInterface { get { return null; } } public override string Name { get { return "ConciergeModule"; } } #endregion #region ISimChat Members public override void OnChatBroadcast(Object sender, OSChatMessage c) { if (m_replacingChatModule) { // distribute chat message to each and every avatar in // the region base.OnChatBroadcast(sender, c); } // TODO: capture logic return; } public override void OnChatFromClient(Object sender, OSChatMessage c) { if (m_replacingChatModule) { // replacing ChatModule: need to redistribute // ChatFromClient to interested subscribers c = FixPositionOfChatMessage(c); Scene scene = (Scene)c.Scene; scene.EventManager.TriggerOnChatFromClient(sender, c); if (m_conciergedScenes.Contains(c.Scene)) { // when we are replacing ChatModule, we treat // OnChatFromClient like OnChatBroadcast for // concierged regions, effectively extending the // range of chat to cover the whole // region. however, we don't do this for whisper // (got to have some privacy) if (c.Type != ChatTypeEnum.Whisper) { base.OnChatBroadcast(sender, c); return; } } // redistribution will be done by base class base.OnChatFromClient(sender, c); } // TODO: capture chat return; } public override void OnChatFromWorld(Object sender, OSChatMessage c) { if (m_replacingChatModule) { if (m_conciergedScenes.Contains(c.Scene)) { // when we are replacing ChatModule, we treat // OnChatFromClient like OnChatBroadcast for // concierged regions, effectively extending the // range of chat to cover the whole // region. however, we don't do this for whisper // (got to have some privacy) if (c.Type != ChatTypeEnum.Whisper) { base.OnChatBroadcast(sender, c); return; } } base.OnChatFromWorld(sender, c); } return; } #endregion public override void OnNewClient(IClientAPI client) { client.OnLogout += OnClientLoggedOut; if (m_replacingChatModule) client.OnChatFromClient += OnChatFromClient; } public void OnClientLoggedOut(IClientAPI client) { client.OnLogout -= OnClientLoggedOut; client.OnConnectionClosed -= OnClientLoggedOut; if (m_conciergedScenes.Contains(client.Scene)) { Scene scene = client.Scene as Scene; m_log.DebugFormat("[Concierge]: {0} logs off from {1}", client.Name, scene.RegionInfo.RegionName); AnnounceToAgentsRegion(scene, String.Format(m_announceLeaving, client.Name, scene.RegionInfo.RegionName, scene.GetRootAgentCount())); UpdateBroker(scene); } } public void OnMakeRootAgent(ScenePresence agent) { if (m_conciergedScenes.Contains(agent.Scene)) { Scene scene = agent.Scene; m_log.DebugFormat("[Concierge]: {0} enters {1}", agent.Name, scene.RegionInfo.RegionName); WelcomeAvatar(agent, scene); AnnounceToAgentsRegion(scene, String.Format(m_announceEntering, agent.Name, scene.RegionInfo.RegionName, scene.GetRootAgentCount())); UpdateBroker(scene); } } public void OnMakeChildAgent(ScenePresence agent) { if (m_conciergedScenes.Contains(agent.Scene)) { Scene scene = agent.Scene; m_log.DebugFormat("[Concierge]: {0} leaves {1}", agent.Name, scene.RegionInfo.RegionName); AnnounceToAgentsRegion(scene, String.Format(m_announceLeaving, agent.Name, scene.RegionInfo.RegionName, scene.GetRootAgentCount())); UpdateBroker(scene); } } internal class BrokerState { public string Uri; public string Payload; public HttpWebRequest Poster; public Timer Timer; public BrokerState(string uri, string payload, HttpWebRequest poster) { Uri = uri; Payload = payload; Poster = poster; } } protected void UpdateBroker(Scene scene) { if (String.IsNullOrEmpty(m_brokerURI)) return; string uri = String.Format(m_brokerURI, scene.RegionInfo.RegionName, scene.RegionInfo.RegionID); // create XML sniplet StringBuilder list = new StringBuilder(); list.Append(String.Format("<avatars count=\"{0}\" region_name=\"{1}\" region_uuid=\"{2}\" timestamp=\"{3}\">\n", scene.GetRootAgentCount(), scene.RegionInfo.RegionName, scene.RegionInfo.RegionID, DateTime.UtcNow.ToString("s"))); scene.ForEachRootScenePresence(delegate(ScenePresence sp) { list.Append(String.Format(" <avatar name=\"{0}\" uuid=\"{1}\" />\n", sp.Name, sp.UUID)); }); list.Append("</avatars>"); string payload = list.ToString(); // post via REST to broker HttpWebRequest updatePost = WebRequest.Create(uri) as HttpWebRequest; updatePost.Method = "POST"; updatePost.ContentType = "text/xml"; updatePost.ContentLength = payload.Length; updatePost.UserAgent = "OpenSim.Concierge"; BrokerState bs = new BrokerState(uri, payload, updatePost); bs.Timer = new Timer(delegate(object state) { BrokerState b = state as BrokerState; b.Poster.Abort(); b.Timer.Dispose(); m_log.Debug("[Concierge]: async broker POST abort due to timeout"); }, bs, m_brokerUpdateTimeout * 1000, Timeout.Infinite); try { updatePost.BeginGetRequestStream(UpdateBrokerSend, bs); m_log.DebugFormat("[Concierge] async broker POST to {0} started", uri); } catch (WebException we) { m_log.ErrorFormat("[Concierge] async broker POST to {0} failed: {1}", uri, we.Status); } } private void UpdateBrokerSend(IAsyncResult result) { BrokerState bs = null; try { bs = result.AsyncState as BrokerState; string payload = bs.Payload; HttpWebRequest updatePost = bs.Poster; using (StreamWriter payloadStream = new StreamWriter(updatePost.EndGetRequestStream(result))) { payloadStream.Write(payload); payloadStream.Close(); } updatePost.BeginGetResponse(UpdateBrokerDone, bs); } catch (WebException we) { m_log.DebugFormat("[Concierge]: async broker POST to {0} failed: {1}", bs.Uri, we.Status); } catch (Exception) { m_log.DebugFormat("[Concierge]: async broker POST to {0} failed", bs.Uri); } } private void UpdateBrokerDone(IAsyncResult result) { BrokerState bs = null; try { bs = result.AsyncState as BrokerState; HttpWebRequest updatePost = bs.Poster; using (HttpWebResponse response = updatePost.EndGetResponse(result) as HttpWebResponse) { m_log.DebugFormat("[Concierge] broker update: status {0}", response.StatusCode); } bs.Timer.Dispose(); } catch (WebException we) { m_log.ErrorFormat("[Concierge] broker update to {0} failed with status {1}", bs.Uri, we.Status); if (null != we.Response) { using (HttpWebResponse resp = we.Response as HttpWebResponse) { m_log.ErrorFormat("[Concierge] response from {0} status code: {1}", bs.Uri, resp.StatusCode); m_log.ErrorFormat("[Concierge] response from {0} status desc: {1}", bs.Uri, resp.StatusDescription); m_log.ErrorFormat("[Concierge] response from {0} server: {1}", bs.Uri, resp.Server); if (resp.ContentLength > 0) { using(StreamReader content = new StreamReader(resp.GetResponseStream())) m_log.ErrorFormat("[Concierge] response from {0} content: {1}", bs.Uri, content.ReadToEnd()); } } } } } protected void WelcomeAvatar(ScenePresence agent, Scene scene) { // welcome mechanics: check whether we have a welcomes // directory set and wether there is a region specific // welcome file there: if yes, send it to the agent if (!String.IsNullOrEmpty(m_welcomes)) { string[] welcomes = new string[] { Path.Combine(m_welcomes, agent.Scene.RegionInfo.RegionName), Path.Combine(m_welcomes, "DEFAULT")}; foreach (string welcome in welcomes) { if (File.Exists(welcome)) { try { string[] welcomeLines = File.ReadAllLines(welcome); foreach (string l in welcomeLines) { AnnounceToAgent(agent, String.Format(l, agent.Name, scene.RegionInfo.RegionName, m_whoami)); } } catch (IOException ioe) { m_log.ErrorFormat("[Concierge]: run into trouble reading welcome file {0} for region {1} for avatar {2}: {3}", welcome, scene.RegionInfo.RegionName, agent.Name, ioe); } catch (FormatException fe) { m_log.ErrorFormat("[Concierge]: welcome file {0} is malformed: {1}", welcome, fe); } } return; } m_log.DebugFormat("[Concierge]: no welcome message for region {0}", scene.RegionInfo.RegionName); } } static private Vector3 PosOfGod = new Vector3(128, 128, 9999); // protected void AnnounceToAgentsRegion(Scene scene, string msg) // { // ScenePresence agent = null; // if ((client.Scene is Scene) && (client.Scene as Scene).TryGetScenePresence(client.AgentId, out agent)) // AnnounceToAgentsRegion(agent, msg); // else // m_log.DebugFormat("[Concierge]: could not find an agent for client {0}", client.Name); // } protected void AnnounceToAgentsRegion(IScene scene, string msg) { OSChatMessage c = new OSChatMessage(); c.Message = msg; c.Type = ChatTypeEnum.Say; c.Channel = 0; c.Position = PosOfGod; c.From = m_whoami; c.Sender = null; c.SenderUUID = UUID.Zero; c.Scene = scene; if (scene is Scene) (scene as Scene).EventManager.TriggerOnChatBroadcast(this, c); } protected void AnnounceToAgent(ScenePresence agent, string msg) { OSChatMessage c = new OSChatMessage(); c.Message = msg; c.Type = ChatTypeEnum.Say; c.Channel = 0; c.Position = PosOfGod; c.From = m_whoami; c.Sender = null; c.SenderUUID = UUID.Zero; c.Scene = agent.Scene; agent.ControllingClient.SendChatMessage( msg, (byte) ChatTypeEnum.Say, PosOfGod, m_whoami, UUID.Zero, UUID.Zero, (byte)ChatSourceType.Object, (byte)ChatAudibleLevel.Fully); } private static void checkStringParameters(XmlRpcRequest request, string[] param) { Hashtable requestData = (Hashtable) request.Params[0]; foreach (string p in param) { if (!requestData.Contains(p)) throw new Exception(String.Format("missing string parameter {0}", p)); if (String.IsNullOrEmpty((string)requestData[p])) throw new Exception(String.Format("parameter {0} is empty", p)); } } public XmlRpcResponse XmlRpcUpdateWelcomeMethod(XmlRpcRequest request, IPEndPoint remoteClient) { m_log.Info("[Concierge]: processing UpdateWelcome request"); XmlRpcResponse response = new XmlRpcResponse(); Hashtable responseData = new Hashtable(); try { Hashtable requestData = (Hashtable)request.Params[0]; checkStringParameters(request, new string[] { "password", "region", "welcome" }); // check password if (!String.IsNullOrEmpty(m_xmlRpcPassword) && (string)requestData["password"] != m_xmlRpcPassword) throw new Exception("wrong password"); if (String.IsNullOrEmpty(m_welcomes)) throw new Exception("welcome templates are not enabled, ask your OpenSim operator to set the \"welcomes\" option in the [Concierge] section of OpenSim.ini"); string msg = (string)requestData["welcome"]; if (String.IsNullOrEmpty(msg)) throw new Exception("empty parameter \"welcome\""); string regionName = (string)requestData["region"]; IScene scene = m_scenes.Find(delegate(IScene s) { return s.RegionInfo.RegionName == regionName; }); if (scene == null) throw new Exception(String.Format("unknown region \"{0}\"", regionName)); if (!m_conciergedScenes.Contains(scene)) throw new Exception(String.Format("region \"{0}\" is not a concierged region.", regionName)); string welcome = Path.Combine(m_welcomes, regionName); if (File.Exists(welcome)) { m_log.InfoFormat("[Concierge]: UpdateWelcome: updating existing template \"{0}\"", welcome); string welcomeBackup = String.Format("{0}~", welcome); if (File.Exists(welcomeBackup)) File.Delete(welcomeBackup); File.Move(welcome, welcomeBackup); } File.WriteAllText(welcome, msg); responseData["success"] = "true"; response.Value = responseData; } catch (Exception e) { m_log.InfoFormat("[Concierge]: UpdateWelcome failed: {0}", e.Message); responseData["success"] = "false"; responseData["error"] = e.Message; response.Value = responseData; } m_log.Debug("[Concierge]: done processing UpdateWelcome request"); return response; } } }
using Lucene.Net.Attributes; using Lucene.Net.Documents; namespace Lucene.Net.Search { using NUnit.Framework; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using BinaryDocValuesField = BinaryDocValuesField; using BytesRef = Lucene.Net.Util.BytesRef; using Directory = Lucene.Net.Store.Directory; using Document = Documents.Document; using DoubleDocValuesField = DoubleDocValuesField; using Field = Field; using SingleDocValuesField = SingleDocValuesField; using IndexReader = Lucene.Net.Index.IndexReader; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using NumericDocValuesField = NumericDocValuesField; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; using SortedDocValuesField = SortedDocValuesField; /// <summary> /// Tests basic sorting on docvalues fields. /// These are mostly like TestSort's tests, except each test /// indexes the field up-front as docvalues, and checks no fieldcaches were made /// </summary> [SuppressCodecs("Lucene3x", "Appending", "Lucene40", "Lucene41", "Lucene42")] // avoid codecs that don't support "missing" [TestFixture] public class TestSortDocValues : LuceneTestCase { [SetUp] public override void SetUp() { base.SetUp(); // ensure there is nothing in fieldcache before test starts FieldCache.DEFAULT.PurgeAllCaches(); } private void AssertNoFieldCaches() { // docvalues sorting should NOT create any fieldcache entries! Assert.AreEqual(0, FieldCache.DEFAULT.GetCacheEntries().Length); } /// <summary> /// Tests sorting on type string </summary> [Test] public virtual void TestString() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, Similarity, TimeZone); Document doc = new Document(); doc.Add(new SortedDocValuesField("value", new BytesRef("foo"))); doc.Add(NewStringField("value", "foo", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new SortedDocValuesField("value", new BytesRef("bar"))); doc.Add(NewStringField("value", "bar", Field.Store.YES)); writer.AddDocument(doc); IndexReader ir = writer.Reader; writer.Dispose(); IndexSearcher searcher = NewSearcher(ir); Sort sort = new Sort(new SortField("value", SortFieldType.STRING)); TopDocs td = searcher.Search(new MatchAllDocsQuery(), 10, sort); Assert.AreEqual(2, td.TotalHits); // 'bar' comes before 'foo' Assert.AreEqual("bar", searcher.Doc(td.ScoreDocs[0].Doc).Get("value")); Assert.AreEqual("foo", searcher.Doc(td.ScoreDocs[1].Doc).Get("value")); AssertNoFieldCaches(); ir.Dispose(); dir.Dispose(); } /// <summary> /// Tests reverse sorting on type string </summary> [Test] public virtual void TestStringReverse() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, Similarity, TimeZone); Document doc = new Document(); doc.Add(new SortedDocValuesField("value", new BytesRef("bar"))); doc.Add(NewStringField("value", "bar", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new SortedDocValuesField("value", new BytesRef("foo"))); doc.Add(NewStringField("value", "foo", Field.Store.YES)); writer.AddDocument(doc); IndexReader ir = writer.Reader; writer.Dispose(); IndexSearcher searcher = NewSearcher(ir); Sort sort = new Sort(new SortField("value", SortFieldType.STRING, true)); TopDocs td = searcher.Search(new MatchAllDocsQuery(), 10, sort); Assert.AreEqual(2, td.TotalHits); // 'foo' comes after 'bar' in reverse order Assert.AreEqual("foo", searcher.Doc(td.ScoreDocs[0].Doc).Get("value")); Assert.AreEqual("bar", searcher.Doc(td.ScoreDocs[1].Doc).Get("value")); AssertNoFieldCaches(); ir.Dispose(); dir.Dispose(); } /// <summary> /// Tests sorting on type string_val </summary> [Test] public virtual void TestStringVal() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, Similarity, TimeZone); Document doc = new Document(); doc.Add(new BinaryDocValuesField("value", new BytesRef("foo"))); doc.Add(NewStringField("value", "foo", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new BinaryDocValuesField("value", new BytesRef("bar"))); doc.Add(NewStringField("value", "bar", Field.Store.YES)); writer.AddDocument(doc); IndexReader ir = writer.Reader; writer.Dispose(); IndexSearcher searcher = NewSearcher(ir); Sort sort = new Sort(new SortField("value", SortFieldType.STRING_VAL)); TopDocs td = searcher.Search(new MatchAllDocsQuery(), 10, sort); Assert.AreEqual(2, td.TotalHits); // 'bar' comes before 'foo' Assert.AreEqual("bar", searcher.Doc(td.ScoreDocs[0].Doc).Get("value")); Assert.AreEqual("foo", searcher.Doc(td.ScoreDocs[1].Doc).Get("value")); AssertNoFieldCaches(); ir.Dispose(); dir.Dispose(); } /// <summary> /// Tests reverse sorting on type string_val </summary> [Test] public virtual void TestStringValReverse() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, Similarity, TimeZone); Document doc = new Document(); doc.Add(new BinaryDocValuesField("value", new BytesRef("bar"))); doc.Add(NewStringField("value", "bar", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new BinaryDocValuesField("value", new BytesRef("foo"))); doc.Add(NewStringField("value", "foo", Field.Store.YES)); writer.AddDocument(doc); IndexReader ir = writer.Reader; writer.Dispose(); IndexSearcher searcher = NewSearcher(ir); Sort sort = new Sort(new SortField("value", SortFieldType.STRING_VAL, true)); TopDocs td = searcher.Search(new MatchAllDocsQuery(), 10, sort); Assert.AreEqual(2, td.TotalHits); // 'foo' comes after 'bar' in reverse order Assert.AreEqual("foo", searcher.Doc(td.ScoreDocs[0].Doc).Get("value")); Assert.AreEqual("bar", searcher.Doc(td.ScoreDocs[1].Doc).Get("value")); AssertNoFieldCaches(); ir.Dispose(); dir.Dispose(); } /// <summary> /// Tests sorting on type string_val, but with a SortedDocValuesField </summary> [Test] public virtual void TestStringValSorted() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, Similarity, TimeZone); Document doc = new Document(); doc.Add(new SortedDocValuesField("value", new BytesRef("foo"))); doc.Add(NewStringField("value", "foo", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new SortedDocValuesField("value", new BytesRef("bar"))); doc.Add(NewStringField("value", "bar", Field.Store.YES)); writer.AddDocument(doc); IndexReader ir = writer.Reader; writer.Dispose(); IndexSearcher searcher = NewSearcher(ir); Sort sort = new Sort(new SortField("value", SortFieldType.STRING_VAL)); TopDocs td = searcher.Search(new MatchAllDocsQuery(), 10, sort); Assert.AreEqual(2, td.TotalHits); // 'bar' comes before 'foo' Assert.AreEqual("bar", searcher.Doc(td.ScoreDocs[0].Doc).Get("value")); Assert.AreEqual("foo", searcher.Doc(td.ScoreDocs[1].Doc).Get("value")); AssertNoFieldCaches(); ir.Dispose(); dir.Dispose(); } /// <summary> /// Tests reverse sorting on type string_val, but with a SortedDocValuesField </summary> [Test] public virtual void TestStringValReverseSorted() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, Similarity, TimeZone); Document doc = new Document(); doc.Add(new SortedDocValuesField("value", new BytesRef("bar"))); doc.Add(NewStringField("value", "bar", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new SortedDocValuesField("value", new BytesRef("foo"))); doc.Add(NewStringField("value", "foo", Field.Store.YES)); writer.AddDocument(doc); IndexReader ir = writer.Reader; writer.Dispose(); IndexSearcher searcher = NewSearcher(ir); Sort sort = new Sort(new SortField("value", SortFieldType.STRING_VAL, true)); TopDocs td = searcher.Search(new MatchAllDocsQuery(), 10, sort); Assert.AreEqual(2, td.TotalHits); // 'foo' comes after 'bar' in reverse order Assert.AreEqual("foo", searcher.Doc(td.ScoreDocs[0].Doc).Get("value")); Assert.AreEqual("bar", searcher.Doc(td.ScoreDocs[1].Doc).Get("value")); AssertNoFieldCaches(); ir.Dispose(); dir.Dispose(); } /// <summary> /// Tests sorting on type byte </summary> [Test] public virtual void TestByte() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, Similarity, TimeZone); Document doc = new Document(); doc.Add(new NumericDocValuesField("value", 23)); doc.Add(NewStringField("value", "23", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new NumericDocValuesField("value", -1)); doc.Add(NewStringField("value", "-1", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new NumericDocValuesField("value", 4)); doc.Add(NewStringField("value", "4", Field.Store.YES)); writer.AddDocument(doc); IndexReader ir = writer.Reader; writer.Dispose(); IndexSearcher searcher = NewSearcher(ir); #pragma warning disable 612, 618 Sort sort = new Sort(new SortField("value", SortFieldType.BYTE)); #pragma warning restore 612, 618 TopDocs td = searcher.Search(new MatchAllDocsQuery(), 10, sort); Assert.AreEqual(3, td.TotalHits); // numeric order Assert.AreEqual("-1", searcher.Doc(td.ScoreDocs[0].Doc).Get("value")); Assert.AreEqual("4", searcher.Doc(td.ScoreDocs[1].Doc).Get("value")); Assert.AreEqual("23", searcher.Doc(td.ScoreDocs[2].Doc).Get("value")); AssertNoFieldCaches(); ir.Dispose(); dir.Dispose(); } /// <summary> /// Tests sorting on type byte in reverse </summary> [Test] public virtual void TestByteReverse() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, Similarity, TimeZone); Document doc = new Document(); doc.Add(new NumericDocValuesField("value", 23)); doc.Add(NewStringField("value", "23", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new NumericDocValuesField("value", -1)); doc.Add(NewStringField("value", "-1", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new NumericDocValuesField("value", 4)); doc.Add(NewStringField("value", "4", Field.Store.YES)); writer.AddDocument(doc); IndexReader ir = writer.Reader; writer.Dispose(); IndexSearcher searcher = NewSearcher(ir); #pragma warning disable 612, 618 Sort sort = new Sort(new SortField("value", SortFieldType.BYTE, true)); #pragma warning restore 612, 618 TopDocs td = searcher.Search(new MatchAllDocsQuery(), 10, sort); Assert.AreEqual(3, td.TotalHits); // reverse numeric order Assert.AreEqual("23", searcher.Doc(td.ScoreDocs[0].Doc).Get("value")); Assert.AreEqual("4", searcher.Doc(td.ScoreDocs[1].Doc).Get("value")); Assert.AreEqual("-1", searcher.Doc(td.ScoreDocs[2].Doc).Get("value")); AssertNoFieldCaches(); ir.Dispose(); dir.Dispose(); } /// <summary> /// Tests sorting on type short </summary> [Test] public virtual void TestShort() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, Similarity, TimeZone); Document doc = new Document(); doc.Add(new NumericDocValuesField("value", 300)); doc.Add(NewStringField("value", "300", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new NumericDocValuesField("value", -1)); doc.Add(NewStringField("value", "-1", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new NumericDocValuesField("value", 4)); doc.Add(NewStringField("value", "4", Field.Store.YES)); writer.AddDocument(doc); IndexReader ir = writer.Reader; writer.Dispose(); IndexSearcher searcher = NewSearcher(ir); #pragma warning disable 612, 618 Sort sort = new Sort(new SortField("value", SortFieldType.INT16)); #pragma warning restore 612, 618 TopDocs td = searcher.Search(new MatchAllDocsQuery(), 10, sort); Assert.AreEqual(3, td.TotalHits); // numeric order Assert.AreEqual("-1", searcher.Doc(td.ScoreDocs[0].Doc).Get("value")); Assert.AreEqual("4", searcher.Doc(td.ScoreDocs[1].Doc).Get("value")); Assert.AreEqual("300", searcher.Doc(td.ScoreDocs[2].Doc).Get("value")); AssertNoFieldCaches(); ir.Dispose(); dir.Dispose(); } /// <summary> /// Tests sorting on type short in reverse </summary> [Test] public virtual void TestShortReverse() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, Similarity, TimeZone); Document doc = new Document(); doc.Add(new NumericDocValuesField("value", 300)); doc.Add(NewStringField("value", "300", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new NumericDocValuesField("value", -1)); doc.Add(NewStringField("value", "-1", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new NumericDocValuesField("value", 4)); doc.Add(NewStringField("value", "4", Field.Store.YES)); writer.AddDocument(doc); IndexReader ir = writer.Reader; writer.Dispose(); IndexSearcher searcher = NewSearcher(ir); #pragma warning disable 612, 618 Sort sort = new Sort(new SortField("value", SortFieldType.INT16, true)); #pragma warning restore 612, 618 TopDocs td = searcher.Search(new MatchAllDocsQuery(), 10, sort); Assert.AreEqual(3, td.TotalHits); // reverse numeric order Assert.AreEqual("300", searcher.Doc(td.ScoreDocs[0].Doc).Get("value")); Assert.AreEqual("4", searcher.Doc(td.ScoreDocs[1].Doc).Get("value")); Assert.AreEqual("-1", searcher.Doc(td.ScoreDocs[2].Doc).Get("value")); AssertNoFieldCaches(); ir.Dispose(); dir.Dispose(); } /// <summary> /// Tests sorting on type int </summary> [Test] public virtual void TestInt() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, Similarity, TimeZone); Document doc = new Document(); doc.Add(new NumericDocValuesField("value", 300000)); doc.Add(NewStringField("value", "300000", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new NumericDocValuesField("value", -1)); doc.Add(NewStringField("value", "-1", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new NumericDocValuesField("value", 4)); doc.Add(NewStringField("value", "4", Field.Store.YES)); writer.AddDocument(doc); IndexReader ir = writer.Reader; writer.Dispose(); IndexSearcher searcher = NewSearcher(ir); Sort sort = new Sort(new SortField("value", SortFieldType.INT32)); TopDocs td = searcher.Search(new MatchAllDocsQuery(), 10, sort); Assert.AreEqual(3, td.TotalHits); // numeric order Assert.AreEqual("-1", searcher.Doc(td.ScoreDocs[0].Doc).Get("value")); Assert.AreEqual("4", searcher.Doc(td.ScoreDocs[1].Doc).Get("value")); Assert.AreEqual("300000", searcher.Doc(td.ScoreDocs[2].Doc).Get("value")); AssertNoFieldCaches(); ir.Dispose(); dir.Dispose(); } /// <summary> /// Tests sorting on type int in reverse </summary> [Test] public virtual void TestIntReverse() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, Similarity, TimeZone); Document doc = new Document(); doc.Add(new NumericDocValuesField("value", 300000)); doc.Add(NewStringField("value", "300000", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new NumericDocValuesField("value", -1)); doc.Add(NewStringField("value", "-1", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new NumericDocValuesField("value", 4)); doc.Add(NewStringField("value", "4", Field.Store.YES)); writer.AddDocument(doc); IndexReader ir = writer.Reader; writer.Dispose(); IndexSearcher searcher = NewSearcher(ir); Sort sort = new Sort(new SortField("value", SortFieldType.INT32, true)); TopDocs td = searcher.Search(new MatchAllDocsQuery(), 10, sort); Assert.AreEqual(3, td.TotalHits); // reverse numeric order Assert.AreEqual("300000", searcher.Doc(td.ScoreDocs[0].Doc).Get("value")); Assert.AreEqual("4", searcher.Doc(td.ScoreDocs[1].Doc).Get("value")); Assert.AreEqual("-1", searcher.Doc(td.ScoreDocs[2].Doc).Get("value")); AssertNoFieldCaches(); ir.Dispose(); dir.Dispose(); } /// <summary> /// Tests sorting on type int with a missing value </summary> [Test] public virtual void TestIntMissing() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, Similarity, TimeZone); Document doc = new Document(); writer.AddDocument(doc); doc = new Document(); doc.Add(new NumericDocValuesField("value", -1)); doc.Add(NewStringField("value", "-1", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new NumericDocValuesField("value", 4)); doc.Add(NewStringField("value", "4", Field.Store.YES)); writer.AddDocument(doc); IndexReader ir = writer.Reader; writer.Dispose(); IndexSearcher searcher = NewSearcher(ir); Sort sort = new Sort(new SortField("value", SortFieldType.INT32)); TopDocs td = searcher.Search(new MatchAllDocsQuery(), 10, sort); Assert.AreEqual(3, td.TotalHits); // null is treated as a 0 Assert.AreEqual("-1", searcher.Doc(td.ScoreDocs[0].Doc).Get("value")); Assert.IsNull(searcher.Doc(td.ScoreDocs[1].Doc).Get("value")); Assert.AreEqual("4", searcher.Doc(td.ScoreDocs[2].Doc).Get("value")); ir.Dispose(); dir.Dispose(); } /// <summary> /// Tests sorting on type int, specifying the missing value should be treated as Integer.MAX_VALUE </summary> [Test] public virtual void TestIntMissingLast() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, Similarity, TimeZone); Document doc = new Document(); writer.AddDocument(doc); doc = new Document(); doc.Add(new NumericDocValuesField("value", -1)); doc.Add(NewStringField("value", "-1", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new NumericDocValuesField("value", 4)); doc.Add(NewStringField("value", "4", Field.Store.YES)); writer.AddDocument(doc); IndexReader ir = writer.Reader; writer.Dispose(); IndexSearcher searcher = NewSearcher(ir); SortField sortField = new SortField("value", SortFieldType.INT32); sortField.MissingValue = int.MaxValue; Sort sort = new Sort(sortField); TopDocs td = searcher.Search(new MatchAllDocsQuery(), 10, sort); Assert.AreEqual(3, td.TotalHits); // null is treated as a Integer.MAX_VALUE Assert.AreEqual("-1", searcher.Doc(td.ScoreDocs[0].Doc).Get("value")); Assert.AreEqual("4", searcher.Doc(td.ScoreDocs[1].Doc).Get("value")); Assert.IsNull(searcher.Doc(td.ScoreDocs[2].Doc).Get("value")); ir.Dispose(); dir.Dispose(); } /// <summary> /// Tests sorting on type long </summary> [Test] public virtual void TestLong() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, Similarity, TimeZone); Document doc = new Document(); doc.Add(new NumericDocValuesField("value", 3000000000L)); doc.Add(NewStringField("value", "3000000000", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new NumericDocValuesField("value", -1)); doc.Add(NewStringField("value", "-1", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new NumericDocValuesField("value", 4)); doc.Add(NewStringField("value", "4", Field.Store.YES)); writer.AddDocument(doc); IndexReader ir = writer.Reader; writer.Dispose(); IndexSearcher searcher = NewSearcher(ir); Sort sort = new Sort(new SortField("value", SortFieldType.INT64)); TopDocs td = searcher.Search(new MatchAllDocsQuery(), 10, sort); Assert.AreEqual(3, td.TotalHits); // numeric order Assert.AreEqual("-1", searcher.Doc(td.ScoreDocs[0].Doc).Get("value")); Assert.AreEqual("4", searcher.Doc(td.ScoreDocs[1].Doc).Get("value")); Assert.AreEqual("3000000000", searcher.Doc(td.ScoreDocs[2].Doc).Get("value")); AssertNoFieldCaches(); ir.Dispose(); dir.Dispose(); } /// <summary> /// Tests sorting on type long in reverse </summary> [Test] public virtual void TestLongReverse() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, Similarity, TimeZone); Document doc = new Document(); doc.Add(new NumericDocValuesField("value", 3000000000L)); doc.Add(NewStringField("value", "3000000000", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new NumericDocValuesField("value", -1)); doc.Add(NewStringField("value", "-1", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new NumericDocValuesField("value", 4)); doc.Add(NewStringField("value", "4", Field.Store.YES)); writer.AddDocument(doc); IndexReader ir = writer.Reader; writer.Dispose(); IndexSearcher searcher = NewSearcher(ir); Sort sort = new Sort(new SortField("value", SortFieldType.INT64, true)); TopDocs td = searcher.Search(new MatchAllDocsQuery(), 10, sort); Assert.AreEqual(3, td.TotalHits); // reverse numeric order Assert.AreEqual("3000000000", searcher.Doc(td.ScoreDocs[0].Doc).Get("value")); Assert.AreEqual("4", searcher.Doc(td.ScoreDocs[1].Doc).Get("value")); Assert.AreEqual("-1", searcher.Doc(td.ScoreDocs[2].Doc).Get("value")); AssertNoFieldCaches(); ir.Dispose(); dir.Dispose(); } /// <summary> /// Tests sorting on type long with a missing value </summary> [Test] public virtual void TestLongMissing() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, Similarity, TimeZone); Document doc = new Document(); writer.AddDocument(doc); doc = new Document(); doc.Add(new NumericDocValuesField("value", -1)); doc.Add(NewStringField("value", "-1", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new NumericDocValuesField("value", 4)); doc.Add(NewStringField("value", "4", Field.Store.YES)); writer.AddDocument(doc); IndexReader ir = writer.Reader; writer.Dispose(); IndexSearcher searcher = NewSearcher(ir); Sort sort = new Sort(new SortField("value", SortFieldType.INT64)); TopDocs td = searcher.Search(new MatchAllDocsQuery(), 10, sort); Assert.AreEqual(3, td.TotalHits); // null is treated as 0 Assert.AreEqual("-1", searcher.Doc(td.ScoreDocs[0].Doc).Get("value")); Assert.IsNull(searcher.Doc(td.ScoreDocs[1].Doc).Get("value")); Assert.AreEqual("4", searcher.Doc(td.ScoreDocs[2].Doc).Get("value")); ir.Dispose(); dir.Dispose(); } /// <summary> /// Tests sorting on type long, specifying the missing value should be treated as Long.MAX_VALUE </summary> [Test] public virtual void TestLongMissingLast() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, Similarity, TimeZone); Document doc = new Document(); writer.AddDocument(doc); doc = new Document(); doc.Add(new NumericDocValuesField("value", -1)); doc.Add(NewStringField("value", "-1", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new NumericDocValuesField("value", 4)); doc.Add(NewStringField("value", "4", Field.Store.YES)); writer.AddDocument(doc); IndexReader ir = writer.Reader; writer.Dispose(); IndexSearcher searcher = NewSearcher(ir); SortField sortField = new SortField("value", SortFieldType.INT64); sortField.MissingValue = long.MaxValue; Sort sort = new Sort(sortField); TopDocs td = searcher.Search(new MatchAllDocsQuery(), 10, sort); Assert.AreEqual(3, td.TotalHits); // null is treated as Long.MAX_VALUE Assert.AreEqual("-1", searcher.Doc(td.ScoreDocs[0].Doc).Get("value")); Assert.AreEqual("4", searcher.Doc(td.ScoreDocs[1].Doc).Get("value")); Assert.IsNull(searcher.Doc(td.ScoreDocs[2].Doc).Get("value")); ir.Dispose(); dir.Dispose(); } /// <summary> /// Tests sorting on type float </summary> [Test] public virtual void TestFloat() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, Similarity, TimeZone); Document doc = new Document(); doc.Add(new SingleDocValuesField("value", 30.1F)); doc.Add(NewStringField("value", "30.1", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new SingleDocValuesField("value", -1.3F)); doc.Add(NewStringField("value", "-1.3", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new SingleDocValuesField("value", 4.2F)); doc.Add(NewStringField("value", "4.2", Field.Store.YES)); writer.AddDocument(doc); IndexReader ir = writer.Reader; writer.Dispose(); IndexSearcher searcher = NewSearcher(ir); Sort sort = new Sort(new SortField("value", SortFieldType.SINGLE)); TopDocs td = searcher.Search(new MatchAllDocsQuery(), 10, sort); Assert.AreEqual(3, td.TotalHits); // numeric order Assert.AreEqual("-1.3", searcher.Doc(td.ScoreDocs[0].Doc).Get("value")); Assert.AreEqual("4.2", searcher.Doc(td.ScoreDocs[1].Doc).Get("value")); Assert.AreEqual("30.1", searcher.Doc(td.ScoreDocs[2].Doc).Get("value")); AssertNoFieldCaches(); ir.Dispose(); dir.Dispose(); } /// <summary> /// Tests sorting on type double with +/- zero </summary> [Test, LuceneNetSpecific] public virtual void TestFloatSignedZero() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, Similarity, TimeZone); Document doc = new Document(); doc.Add(new SingleDocValuesField("value", +0f)); doc.Add(NewStringField("value", "+0", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new SingleDocValuesField("value", -0f)); doc.Add(NewStringField("value", "-0", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); IndexReader ir = writer.Reader; writer.Dispose(); IndexSearcher searcher = NewSearcher(ir); Sort sort = new Sort(new SortField("value", SortFieldType.SINGLE)); TopDocs td = searcher.Search(new MatchAllDocsQuery(), 10, sort); Assert.AreEqual(2, td.TotalHits); // numeric order Assert.AreEqual("-0", searcher.Doc(td.ScoreDocs[0].Doc).Get("value")); Assert.AreEqual("+0", searcher.Doc(td.ScoreDocs[1].Doc).Get("value")); ir.Dispose(); dir.Dispose(); } /// <summary> /// Tests sorting on type float in reverse </summary> [Test] public virtual void TestFloatReverse() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, Similarity, TimeZone); Document doc = new Document(); doc.Add(new SingleDocValuesField("value", 30.1F)); doc.Add(NewStringField("value", "30.1", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new SingleDocValuesField("value", -1.3F)); doc.Add(NewStringField("value", "-1.3", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new SingleDocValuesField("value", 4.2F)); doc.Add(NewStringField("value", "4.2", Field.Store.YES)); writer.AddDocument(doc); IndexReader ir = writer.Reader; writer.Dispose(); IndexSearcher searcher = NewSearcher(ir); Sort sort = new Sort(new SortField("value", SortFieldType.SINGLE, true)); TopDocs td = searcher.Search(new MatchAllDocsQuery(), 10, sort); Assert.AreEqual(3, td.TotalHits); // reverse numeric order Assert.AreEqual("30.1", searcher.Doc(td.ScoreDocs[0].Doc).Get("value")); Assert.AreEqual("4.2", searcher.Doc(td.ScoreDocs[1].Doc).Get("value")); Assert.AreEqual("-1.3", searcher.Doc(td.ScoreDocs[2].Doc).Get("value")); AssertNoFieldCaches(); ir.Dispose(); dir.Dispose(); } /// <summary> /// Tests sorting on type float with a missing value </summary> [Test] public virtual void TestFloatMissing() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, Similarity, TimeZone); Document doc = new Document(); writer.AddDocument(doc); doc = new Document(); doc.Add(new SingleDocValuesField("value", -1.3F)); doc.Add(NewStringField("value", "-1.3", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new SingleDocValuesField("value", 4.2F)); doc.Add(NewStringField("value", "4.2", Field.Store.YES)); writer.AddDocument(doc); IndexReader ir = writer.Reader; writer.Dispose(); IndexSearcher searcher = NewSearcher(ir); Sort sort = new Sort(new SortField("value", SortFieldType.SINGLE)); TopDocs td = searcher.Search(new MatchAllDocsQuery(), 10, sort); Assert.AreEqual(3, td.TotalHits); // null is treated as 0 Assert.AreEqual("-1.3", searcher.Doc(td.ScoreDocs[0].Doc).Get("value")); Assert.IsNull(searcher.Doc(td.ScoreDocs[1].Doc).Get("value")); Assert.AreEqual("4.2", searcher.Doc(td.ScoreDocs[2].Doc).Get("value")); ir.Dispose(); dir.Dispose(); } /// <summary> /// Tests sorting on type float, specifying the missing value should be treated as Float.MAX_VALUE </summary> [Test] public virtual void TestFloatMissingLast() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, Similarity, TimeZone); Document doc = new Document(); writer.AddDocument(doc); doc = new Document(); doc.Add(new SingleDocValuesField("value", -1.3F)); doc.Add(NewStringField("value", "-1.3", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new SingleDocValuesField("value", 4.2F)); doc.Add(NewStringField("value", "4.2", Field.Store.YES)); writer.AddDocument(doc); IndexReader ir = writer.Reader; writer.Dispose(); IndexSearcher searcher = NewSearcher(ir); SortField sortField = new SortField("value", SortFieldType.SINGLE); sortField.MissingValue = float.MaxValue; Sort sort = new Sort(sortField); TopDocs td = searcher.Search(new MatchAllDocsQuery(), 10, sort); Assert.AreEqual(3, td.TotalHits); // null is treated as Float.MAX_VALUE Assert.AreEqual("-1.3", searcher.Doc(td.ScoreDocs[0].Doc).Get("value")); Assert.AreEqual("4.2", searcher.Doc(td.ScoreDocs[1].Doc).Get("value")); Assert.IsNull(searcher.Doc(td.ScoreDocs[2].Doc).Get("value")); ir.Dispose(); dir.Dispose(); } /// <summary> /// Tests sorting on type double </summary> [Test] public virtual void TestDouble() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, Similarity, TimeZone); Document doc = new Document(); doc.Add(new DoubleDocValuesField("value", 30.1)); doc.Add(NewStringField("value", "30.1", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new DoubleDocValuesField("value", -1.3)); doc.Add(NewStringField("value", "-1.3", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new DoubleDocValuesField("value", 4.2333333333333)); doc.Add(NewStringField("value", "4.2333333333333", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new DoubleDocValuesField("value", 4.2333333333332)); doc.Add(NewStringField("value", "4.2333333333332", Field.Store.YES)); writer.AddDocument(doc); IndexReader ir = writer.Reader; writer.Dispose(); IndexSearcher searcher = NewSearcher(ir); Sort sort = new Sort(new SortField("value", SortFieldType.DOUBLE)); TopDocs td = searcher.Search(new MatchAllDocsQuery(), 10, sort); Assert.AreEqual(4, td.TotalHits); // numeric order Assert.AreEqual("-1.3", searcher.Doc(td.ScoreDocs[0].Doc).Get("value")); Assert.AreEqual("4.2333333333332", searcher.Doc(td.ScoreDocs[1].Doc).Get("value")); Assert.AreEqual("4.2333333333333", searcher.Doc(td.ScoreDocs[2].Doc).Get("value")); Assert.AreEqual("30.1", searcher.Doc(td.ScoreDocs[3].Doc).Get("value")); AssertNoFieldCaches(); ir.Dispose(); dir.Dispose(); } /// <summary> /// Tests sorting on type double with +/- zero </summary> [Test] public virtual void TestDoubleSignedZero() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, Similarity, TimeZone); Document doc = new Document(); doc.Add(new DoubleDocValuesField("value", +0D)); doc.Add(NewStringField("value", "+0", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new DoubleDocValuesField("value", -0D)); doc.Add(NewStringField("value", "-0", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); IndexReader ir = writer.Reader; writer.Dispose(); IndexSearcher searcher = NewSearcher(ir); Sort sort = new Sort(new SortField("value", SortFieldType.DOUBLE)); TopDocs td = searcher.Search(new MatchAllDocsQuery(), 10, sort); Assert.AreEqual(2, td.TotalHits); // numeric order Assert.AreEqual("-0", searcher.Doc(td.ScoreDocs[0].Doc).Get("value")); Assert.AreEqual("+0", searcher.Doc(td.ScoreDocs[1].Doc).Get("value")); ir.Dispose(); dir.Dispose(); } /// <summary> /// Tests sorting on type double in reverse </summary> [Test] public virtual void TestDoubleReverse() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, Similarity, TimeZone); Document doc = new Document(); doc.Add(new DoubleDocValuesField("value", 30.1)); doc.Add(NewStringField("value", "30.1", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new DoubleDocValuesField("value", -1.3)); doc.Add(NewStringField("value", "-1.3", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new DoubleDocValuesField("value", 4.2333333333333)); doc.Add(NewStringField("value", "4.2333333333333", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new DoubleDocValuesField("value", 4.2333333333332)); doc.Add(NewStringField("value", "4.2333333333332", Field.Store.YES)); writer.AddDocument(doc); IndexReader ir = writer.Reader; writer.Dispose(); IndexSearcher searcher = NewSearcher(ir); Sort sort = new Sort(new SortField("value", SortFieldType.DOUBLE, true)); TopDocs td = searcher.Search(new MatchAllDocsQuery(), 10, sort); Assert.AreEqual(4, td.TotalHits); // numeric order Assert.AreEqual("30.1", searcher.Doc(td.ScoreDocs[0].Doc).Get("value")); Assert.AreEqual("4.2333333333333", searcher.Doc(td.ScoreDocs[1].Doc).Get("value")); Assert.AreEqual("4.2333333333332", searcher.Doc(td.ScoreDocs[2].Doc).Get("value")); Assert.AreEqual("-1.3", searcher.Doc(td.ScoreDocs[3].Doc).Get("value")); AssertNoFieldCaches(); ir.Dispose(); dir.Dispose(); } /// <summary> /// Tests sorting on type double with a missing value </summary> [Test] public virtual void TestDoubleMissing() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, Similarity, TimeZone); Document doc = new Document(); writer.AddDocument(doc); doc = new Document(); doc.Add(new DoubleDocValuesField("value", -1.3)); doc.Add(NewStringField("value", "-1.3", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new DoubleDocValuesField("value", 4.2333333333333)); doc.Add(NewStringField("value", "4.2333333333333", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new DoubleDocValuesField("value", 4.2333333333332)); doc.Add(NewStringField("value", "4.2333333333332", Field.Store.YES)); writer.AddDocument(doc); IndexReader ir = writer.Reader; writer.Dispose(); IndexSearcher searcher = NewSearcher(ir); Sort sort = new Sort(new SortField("value", SortFieldType.DOUBLE)); TopDocs td = searcher.Search(new MatchAllDocsQuery(), 10, sort); Assert.AreEqual(4, td.TotalHits); // null treated as a 0 Assert.AreEqual("-1.3", searcher.Doc(td.ScoreDocs[0].Doc).Get("value")); Assert.IsNull(searcher.Doc(td.ScoreDocs[1].Doc).Get("value")); Assert.AreEqual("4.2333333333332", searcher.Doc(td.ScoreDocs[2].Doc).Get("value")); Assert.AreEqual("4.2333333333333", searcher.Doc(td.ScoreDocs[3].Doc).Get("value")); ir.Dispose(); dir.Dispose(); } /// <summary> /// Tests sorting on type double, specifying the missing value should be treated as Double.MAX_VALUE </summary> [Test] public virtual void TestDoubleMissingLast() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, Similarity, TimeZone); Document doc = new Document(); writer.AddDocument(doc); doc = new Document(); doc.Add(new DoubleDocValuesField("value", -1.3)); doc.Add(NewStringField("value", "-1.3", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new DoubleDocValuesField("value", 4.2333333333333)); doc.Add(NewStringField("value", "4.2333333333333", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(new DoubleDocValuesField("value", 4.2333333333332)); doc.Add(NewStringField("value", "4.2333333333332", Field.Store.YES)); writer.AddDocument(doc); IndexReader ir = writer.Reader; writer.Dispose(); IndexSearcher searcher = NewSearcher(ir); SortField sortField = new SortField("value", SortFieldType.DOUBLE); sortField.MissingValue = double.MaxValue; Sort sort = new Sort(sortField); TopDocs td = searcher.Search(new MatchAllDocsQuery(), 10, sort); Assert.AreEqual(4, td.TotalHits); // null treated as Double.MAX_VALUE Assert.AreEqual("-1.3", searcher.Doc(td.ScoreDocs[0].Doc).Get("value")); Assert.AreEqual("4.2333333333332", searcher.Doc(td.ScoreDocs[1].Doc).Get("value")); Assert.AreEqual("4.2333333333333", searcher.Doc(td.ScoreDocs[2].Doc).Get("value")); Assert.IsNull(searcher.Doc(td.ScoreDocs[3].Doc).Get("value")); ir.Dispose(); dir.Dispose(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #region Using directives using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Management.Automation; #endregion namespace Microsoft.Management.Infrastructure.CimCmdlets { /// <summary> /// This cmdlet enables the user to invoke a static method on a CIM class using /// the arguments passed as a list of name value pair dictionary. /// </summary> [Cmdlet( "Invoke", "CimMethod", SupportsShouldProcess = true, DefaultParameterSetName = CimBaseCommand.ClassNameComputerSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=227965")] public class InvokeCimMethodCommand : CimBaseCommand { #region constructor /// <summary> /// Constructor. /// </summary> public InvokeCimMethodCommand() : base(parameters, parameterSets) { DebugHelper.WriteLogEx(); } #endregion #region parameters /// <summary> /// The following is the definition of the input parameter "ClassName". /// Specifies the Class Name, on which to invoke static method. /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true, ParameterSetName = CimBaseCommand.ClassNameComputerSet)] [Parameter(Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true, ParameterSetName = CimBaseCommand.ClassNameSessionSet)] [Alias("Class")] public string ClassName { get { return className; } set { className = value; base.SetParameter(value, nameClassName); } } private string className; /// <summary> /// <para> /// The following is the definition of the input parameter "ResourceUri". /// Define the Resource Uri for which the instances are retrieved. /// </para> /// </summary> [Parameter(ValueFromPipelineByPropertyName = true, ParameterSetName = CimBaseCommand.CimInstanceComputerSet)] [Parameter(ValueFromPipelineByPropertyName = true, ParameterSetName = CimBaseCommand.CimInstanceSessionSet)] [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = CimBaseCommand.ResourceUriComputerSet)] [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = CimBaseCommand.ResourceUriSessionSet)] public Uri ResourceUri { get { return resourceUri; } set { this.resourceUri = value; base.SetParameter(value, nameResourceUri); } } private Uri resourceUri; /// <summary> /// The following is the definition of the input parameter "CimClass". /// Specifies the <see cref="CimClass"/> object, on which to invoke static method. /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ParameterSetName = CimClassComputerSet)] [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ParameterSetName = CimClassSessionSet)] public CimClass CimClass { get { return cimClass; } set { cimClass = value; base.SetParameter(value, nameCimClass); } } private CimClass cimClass; /// <summary> /// The following is the definition of the input parameter "Query". /// Specifies the <see cref="CimClass"/> object, on which to invoke static method. /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = CimBaseCommand.QueryComputerSet)] [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = CimBaseCommand.QuerySessionSet)] public string Query { get { return query; } set { query = value; base.SetParameter(value, nameQuery); } } private string query; /// <summary> /// <para> /// The following is the definition of the input parameter "QueryDialect". /// Specifies the dialect used by the query Engine that interprets the Query /// string. /// </para> /// </summary> [Parameter(ValueFromPipelineByPropertyName = true, ParameterSetName = CimBaseCommand.QueryComputerSet)] [Parameter(ValueFromPipelineByPropertyName = true, ParameterSetName = CimBaseCommand.QuerySessionSet)] public string QueryDialect { get { return queryDialect; } set { queryDialect = value; base.SetParameter(value, nameQueryDialect); } } private string queryDialect; /// <summary> /// The following is the definition of the input parameter "InputObject". /// Takes a CimInstance object retrieved by a Get-CimInstance call. /// Invoke the method against the given instance. /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ParameterSetName = CimBaseCommand.CimInstanceComputerSet)] [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ParameterSetName = CimBaseCommand.CimInstanceSessionSet)] [Alias(CimBaseCommand.AliasCimInstance)] public CimInstance InputObject { get { return cimInstance; } set { cimInstance = value; base.SetParameter(value, nameCimInstance); } } /// <summary> /// Property for internal usage purpose. /// </summary> internal CimInstance CimInstance { get { return cimInstance; } } private CimInstance cimInstance; /// <summary> /// <para>The following is the definition of the input parameter "ComputerName". /// Provides the name of the computer from which to invoke the method. The /// ComputerName is used to create a temporary CimSession with default parameter /// values, which is then used to retrieve the instances. /// </para> /// <para> /// If no ComputerName is specified the default value is "localhost" /// </para> /// </summary> [Alias(AliasCN, AliasServerName)] [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = CimBaseCommand.ClassNameComputerSet)] [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = CimBaseCommand.QueryComputerSet)] [Parameter( ParameterSetName = CimBaseCommand.CimInstanceComputerSet)] [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = CimBaseCommand.CimClassComputerSet)] [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = CimBaseCommand.ResourceUriComputerSet)] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] ComputerName { get { return computerName; } set { DebugHelper.WriteLogEx(); computerName = value; base.SetParameter(value, nameComputerName); } } private string[] computerName; /// <summary> /// <para> /// The following is the definition of the input parameter "CimSession". /// Identifies the CimSession which is to be used to retrieve the instances. /// </para> /// </summary> [Parameter( Mandatory = true, ValueFromPipeline = true, ParameterSetName = CimBaseCommand.CimInstanceSessionSet)] [Parameter( Mandatory = true, ValueFromPipeline = true, ParameterSetName = CimBaseCommand.QuerySessionSet)] [Parameter( Mandatory = true, ValueFromPipeline = true, ParameterSetName = CimBaseCommand.ClassNameSessionSet)] [Parameter( Mandatory = true, ValueFromPipeline = true, ParameterSetName = CimClassSessionSet)] [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = CimBaseCommand.ResourceUriSessionSet)] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public CimSession[] CimSession { get { return cimSession; } set { cimSession = value; base.SetParameter(value, nameCimSession); } } private CimSession[] cimSession; /// <summary> /// The following is the definition of the input parameter "Arguments". /// Specifies the parameter arguments for the static method using a name value /// pair. /// </summary> [Parameter(Position = 1, ValueFromPipelineByPropertyName = true)] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public IDictionary Arguments { get { return arguments; } set { arguments = value; } } private IDictionary arguments; /// <summary> /// The following is the definition of the input parameter "MethodName". /// Name of the Static Method to use. /// </summary> [Parameter(Mandatory = true, Position = 2, ValueFromPipelineByPropertyName = true)] [Alias("Name")] public string MethodName { get { return methodName; } set { methodName = value; base.SetParameter(value, nameMethodName); } } private string methodName; /// <summary> /// The following is the definition of the input parameter "Namespace". /// Specifies the NameSpace in which the class or instance lives under. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true, ParameterSetName = CimBaseCommand.ClassNameComputerSet)] [Parameter(ValueFromPipelineByPropertyName = true, ParameterSetName = CimBaseCommand.ClassNameSessionSet)] [Parameter(ValueFromPipelineByPropertyName = true, ParameterSetName = CimBaseCommand.QueryComputerSet)] [Parameter(ValueFromPipelineByPropertyName = true, ParameterSetName = CimBaseCommand.QuerySessionSet)] [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = CimBaseCommand.ResourceUriComputerSet)] [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = CimBaseCommand.ResourceUriSessionSet)] public string Namespace { get { return nameSpace; } set { nameSpace = value; base.SetParameter(value, nameNamespace); } } private string nameSpace; /// <summary> /// The following is the definition of the input parameter "OperationTimeoutSec". /// Enables the user to specify the operation timeout in Seconds. This value /// overwrites the value specified by the CimSession Operation timeout. /// </summary> [Alias(AliasOT)] [Parameter] public UInt32 OperationTimeoutSec { get { return operationTimeout; } set { operationTimeout = value; } } private UInt32 operationTimeout; #endregion #region cmdlet methods /// <summary> /// BeginProcessing method. /// </summary> protected override void BeginProcessing() { CimInvokeCimMethod cimInvokeMethod = this.GetOperationAgent(); if (cimInvokeMethod == null) { cimInvokeMethod = CreateOperationAgent(); } this.CmdletOperation = new CmdletOperationInvokeCimMethod(this, cimInvokeMethod); this.AtBeginProcess = false; } /// <summary> /// ProcessRecord method. /// </summary> protected override void ProcessRecord() { base.CheckParameterSet(); this.CheckArgument(); CimInvokeCimMethod cimInvokeMethod = this.GetOperationAgent(); cimInvokeMethod.InvokeCimMethod(this); cimInvokeMethod.ProcessActions(this.CmdletOperation); } /// <summary> /// EndProcessing method. /// </summary> protected override void EndProcessing() { CimInvokeCimMethod cimInvokeMethod = this.GetOperationAgent(); if (cimInvokeMethod != null) { cimInvokeMethod.ProcessRemainActions(this.CmdletOperation); } } #endregion #region helper methods /// <summary> /// <para> /// Get <see cref="CimInvokeCimMethod"/> object, which is /// used to delegate all Invoke-CimMethod operations. /// </para> /// </summary> CimInvokeCimMethod GetOperationAgent() { return this.AsyncOperation as CimInvokeCimMethod; } /// <summary> /// <para> /// Create <see cref="CimInvokeCimMethod"/> object, which is /// used to delegate all Invoke-CimMethod operations. /// </para> /// </summary> /// <returns></returns> CimInvokeCimMethod CreateOperationAgent() { CimInvokeCimMethod cimInvokeMethod = new CimInvokeCimMethod(); this.AsyncOperation = cimInvokeMethod; return cimInvokeMethod; } /// <summary> /// Check argument value. /// </summary> private void CheckArgument() { switch (this.ParameterSetName) { case CimBaseCommand.ClassNameComputerSet: case CimBaseCommand.ClassNameSessionSet: // validate the classname this.className = ValidationHelper.ValidateArgumentIsValidName(nameClassName, this.className); break; default: break; } } #endregion #region private members #region const string of parameter names internal const string nameClassName = "ClassName"; internal const string nameCimClass = "CimClass"; internal const string nameQuery = "Query"; internal const string nameResourceUri = "ResourceUri"; internal const string nameQueryDialect = "QueryDialect"; internal const string nameCimInstance = "InputObject"; internal const string nameComputerName = "ComputerName"; internal const string nameCimSession = "CimSession"; internal const string nameArguments = "Arguments"; internal const string nameMethodName = "MethodName"; internal const string nameNamespace = "Namespace"; #endregion /// <summary> /// Static parameter definition entries. /// </summary> static Dictionary<string, HashSet<ParameterDefinitionEntry>> parameters = new Dictionary<string, HashSet<ParameterDefinitionEntry>> { { nameClassName, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, true), new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, true), } }, { nameCimClass, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.CimClassComputerSet, true), new ParameterDefinitionEntry(CimBaseCommand.CimClassSessionSet, true), } }, { nameQuery, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, true), new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, true), } }, { nameQueryDialect, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, false), new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, false), } }, { nameCimInstance, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.CimInstanceComputerSet, true), new ParameterDefinitionEntry(CimBaseCommand.CimInstanceSessionSet, true), } }, { nameComputerName, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false), new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, false), new ParameterDefinitionEntry(CimBaseCommand.CimInstanceComputerSet, false), new ParameterDefinitionEntry(CimBaseCommand.CimClassComputerSet, false), new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, false), } }, { nameCimSession, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.CimInstanceSessionSet, true), new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, true), new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, true), new ParameterDefinitionEntry(CimBaseCommand.CimClassSessionSet, true), new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, true), } }, { nameMethodName, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, true), new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, true), new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, true), new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, true), new ParameterDefinitionEntry(CimBaseCommand.CimInstanceComputerSet, true), new ParameterDefinitionEntry(CimBaseCommand.CimInstanceSessionSet, true), new ParameterDefinitionEntry(CimBaseCommand.CimClassComputerSet, true), new ParameterDefinitionEntry(CimBaseCommand.CimClassSessionSet, true), new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, true), new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, true), } }, { nameNamespace, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false), new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, false), new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, false), new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, false), new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, false), new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, false), } }, { nameResourceUri, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.CimInstanceComputerSet, false), new ParameterDefinitionEntry(CimBaseCommand.CimInstanceSessionSet, false), new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, true), new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, true), } }, }; /// <summary> /// Static parameter set entries. /// </summary> static Dictionary<string, ParameterSetEntry> parameterSets = new Dictionary<string, ParameterSetEntry> { { CimBaseCommand.ClassNameComputerSet, new ParameterSetEntry(2, true) }, { CimBaseCommand.ResourceUriSessionSet, new ParameterSetEntry(3) }, { CimBaseCommand.ResourceUriComputerSet, new ParameterSetEntry(2) }, { CimBaseCommand.ClassNameSessionSet, new ParameterSetEntry(3) }, { CimBaseCommand.QueryComputerSet, new ParameterSetEntry(2) }, { CimBaseCommand.QuerySessionSet, new ParameterSetEntry(3) }, { CimBaseCommand.CimInstanceComputerSet, new ParameterSetEntry(2) }, { CimBaseCommand.CimInstanceSessionSet, new ParameterSetEntry(3) }, { CimBaseCommand.CimClassComputerSet, new ParameterSetEntry(2) }, { CimBaseCommand.CimClassSessionSet, new ParameterSetEntry(3) }, }; #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; namespace System.Net.Sockets { partial class SafeSocketHandle { private ThreadPoolBoundHandle _iocpBoundHandle; private bool _skipCompletionPortOnSuccess; private object _iocpBindingLock = new object(); internal void SetExposed() { /* nop */ } internal ThreadPoolBoundHandle IOCPBoundHandle { get { return _iocpBoundHandle; } } internal ThreadPoolBoundHandle GetThreadPoolBoundHandle() => !_released ? _iocpBoundHandle : null; // Binds the Socket Win32 Handle to the ThreadPool's CompletionPort. internal ThreadPoolBoundHandle GetOrAllocateThreadPoolBoundHandle(bool trySkipCompletionPortOnSuccess) { if (_released) { // Keep the exception message pointing at the external type. throw new ObjectDisposedException(typeof(Socket).FullName); } if (_iocpBoundHandle != null) { return _iocpBoundHandle; } lock (_iocpBindingLock) { ThreadPoolBoundHandle boundHandle = _iocpBoundHandle; if (boundHandle == null) { // Bind the socket native _handle to the ThreadPool. if (NetEventSource.IsEnabled) NetEventSource.Info(this, "calling ThreadPool.BindHandle()"); try { // The handle (this) may have been already released: // E.g.: The socket has been disposed in the main thread. A completion callback may // attempt starting another operation. boundHandle = ThreadPoolBoundHandle.BindHandle(this); } catch (Exception exception) when (!ExceptionCheck.IsFatal(exception)) { bool closed = IsClosed; CloseAsIs(); if (closed) { // If the handle was closed just before the call to BindHandle, // we could end up getting an ArgumentException, which we should // instead propagate as an ObjectDisposedException. throw new ObjectDisposedException(typeof(Socket).FullName, exception); } throw; } // Try to disable completions for synchronous success, if requested if (trySkipCompletionPortOnSuccess && CompletionPortHelper.SkipCompletionPortOnSuccess(boundHandle.Handle)) { _skipCompletionPortOnSuccess = true; } // Don't set this until after we've configured the handle above (if we did) Volatile.Write(ref _iocpBoundHandle, boundHandle); } return boundHandle; } } internal bool SkipCompletionPortOnSuccess { get { Debug.Assert(_iocpBoundHandle != null); return _skipCompletionPortOnSuccess; } } internal static SafeSocketHandle CreateWSASocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) { return CreateSocket(InnerSafeCloseSocket.CreateWSASocket(addressFamily, socketType, protocolType)); } internal static SafeSocketHandle Accept( SafeSocketHandle socketHandle, byte[] socketAddress, ref int socketAddressSize) { return CreateSocket(InnerSafeCloseSocket.Accept(socketHandle, socketAddress, ref socketAddressSize)); } private void InnerReleaseHandle() { // Keep m_IocpBoundHandle around after disposing it to allow freeing NativeOverlapped. // ThreadPoolBoundHandle allows FreeNativeOverlapped even after it has been disposed. if (_iocpBoundHandle != null) { _iocpBoundHandle.Dispose(); } } internal sealed partial class InnerSafeCloseSocket : SafeHandleMinusOneIsInvalid { private SocketError InnerReleaseHandle() { SocketError errorCode; // If _blockable was set in BlockingRelease, it's safe to block here, which means // we can honor the linger options set on the socket. It also means closesocket() might return WSAEWOULDBLOCK, in which // case we need to do some recovery. if (_blockable) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, Following 'blockable' branch"); errorCode = Interop.Winsock.closesocket(handle); #if DEBUG _closeSocketHandle = handle; _closeSocketResult = errorCode; #endif if (errorCode == SocketError.SocketError) errorCode = (SocketError)Marshal.GetLastWin32Error(); if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, closesocket()#1:{errorCode}"); // If it's not WSAEWOULDBLOCK, there's no more recourse - we either succeeded or failed. if (errorCode != SocketError.WouldBlock) { return errorCode; } // The socket must be non-blocking with a linger timeout set. // We have to set the socket to blocking. int nonBlockCmd = 0; errorCode = Interop.Winsock.ioctlsocket( handle, Interop.Winsock.IoctlSocketConstants.FIONBIO, ref nonBlockCmd); if (errorCode == SocketError.SocketError) errorCode = (SocketError)Marshal.GetLastWin32Error(); if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, ioctlsocket()#1:{errorCode}"); // If that succeeded, try again. if (errorCode == SocketError.Success) { errorCode = Interop.Winsock.closesocket(handle); #if DEBUG _closeSocketHandle = handle; _closeSocketResult = errorCode; #endif if (errorCode == SocketError.SocketError) errorCode = (SocketError)Marshal.GetLastWin32Error(); if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, closesocket#2():{errorCode}"); // If it's not WSAEWOULDBLOCK, there's no more recourse - we either succeeded or failed. if (errorCode != SocketError.WouldBlock) { return errorCode; } } // It failed. Fall through to the regular abortive close. } // By default or if CloseAsIs() path failed, set linger timeout to zero to get an abortive close (RST). Interop.Winsock.Linger lingerStruct; lingerStruct.OnOff = 1; lingerStruct.Time = 0; errorCode = Interop.Winsock.setsockopt( handle, SocketOptionLevel.Socket, SocketOptionName.Linger, ref lingerStruct, 4); #if DEBUG _closeSocketLinger = errorCode; #endif if (errorCode == SocketError.SocketError) errorCode = (SocketError)Marshal.GetLastWin32Error(); if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, setsockopt():{errorCode}"); if (errorCode != SocketError.Success && errorCode != SocketError.InvalidArgument && errorCode != SocketError.ProtocolOption) { // Too dangerous to try closesocket() - it might block! return errorCode; } errorCode = Interop.Winsock.closesocket(handle); #if DEBUG _closeSocketHandle = handle; _closeSocketResult = errorCode; #endif if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, closesocket#3():{(errorCode == SocketError.SocketError ? (SocketError)Marshal.GetLastWin32Error() : errorCode)}"); return errorCode; } internal static InnerSafeCloseSocket CreateWSASocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) { InnerSafeCloseSocket result = Interop.Winsock.WSASocketW(addressFamily, socketType, protocolType, IntPtr.Zero, 0, Interop.Winsock.SocketConstructorFlags.WSA_FLAG_OVERLAPPED | Interop.Winsock.SocketConstructorFlags.WSA_FLAG_NO_HANDLE_INHERIT); if (result.IsInvalid) { result.SetHandleAsInvalid(); } return result; } internal static InnerSafeCloseSocket Accept(SafeSocketHandle socketHandle, byte[] socketAddress, ref int socketAddressSize) { InnerSafeCloseSocket result = Interop.Winsock.accept(socketHandle.DangerousGetHandle(), socketAddress, ref socketAddressSize); if (result.IsInvalid) { result.SetHandleAsInvalid(); } return result; } } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.HSSF.Record.Aggregates { using NPOI.HSSF.Model; using NPOI.HSSF.Record; using NPOI.Util; using System; /** * Groups the sheet protection records for a worksheet. * <p/> * * See OOO excelfileformat.pdf sec 4.18.2 'Sheet Protection in a Workbook * (BIFF5-BIFF8)' * * @author Josh Micich */ public class WorksheetProtectionBlock : RecordAggregate { // Every one of these component records is optional // (The whole WorksheetProtectionBlock may not be present) private ProtectRecord _protectRecord; private ObjectProtectRecord _objectProtectRecord; private ScenarioProtectRecord _scenarioProtectRecord; private PasswordRecord _passwordRecord; /** * Creates an empty WorksheetProtectionBlock */ public WorksheetProtectionBlock() { // all fields emptyv } /** * @return <c>true</c> if the specified Record sid is one belonging to * the 'Page Settings Block'. */ public static bool IsComponentRecord(int sid) { switch (sid) { case ProtectRecord.sid: case ObjectProtectRecord.sid: case ScenarioProtectRecord.sid: case PasswordRecord.sid: return true; } return false; } private bool ReadARecord(RecordStream rs) { switch (rs.PeekNextSid()) { case ProtectRecord.sid: CheckNotPresent(_protectRecord); _protectRecord = rs.GetNext() as ProtectRecord; break; case ObjectProtectRecord.sid: CheckNotPresent(_objectProtectRecord); _objectProtectRecord = rs.GetNext() as ObjectProtectRecord; break; case ScenarioProtectRecord.sid: CheckNotPresent(_scenarioProtectRecord); _scenarioProtectRecord = rs.GetNext() as ScenarioProtectRecord; break; case PasswordRecord.sid: CheckNotPresent(_passwordRecord); _passwordRecord = rs.GetNext() as PasswordRecord; break; default: // all other record types are not part of the PageSettingsBlock return false; } return true; } private void CheckNotPresent(Record rec) { if (rec != null) { throw new RecordFormatException("Duplicate WorksheetProtectionBlock record (sid=0x" + StringUtil.ToHexString(rec.Sid) + ")"); } } public override void VisitContainedRecords(RecordVisitor rv) { // Replicates record order from Excel 2007, though this is not critical VisitIfPresent(_protectRecord, rv); VisitIfPresent(_objectProtectRecord, rv); VisitIfPresent(_scenarioProtectRecord, rv); VisitIfPresent(_passwordRecord, rv); } private static void VisitIfPresent(Record r, RecordVisitor rv) { if (r != null) { rv.VisitRecord(r); } } public PasswordRecord GetPasswordRecord() { return _passwordRecord; } public ScenarioProtectRecord GetHCenter() { return _scenarioProtectRecord; } /** * This method Reads {@link WorksheetProtectionBlock} records from the supplied RecordStream * until the first non-WorksheetProtectionBlock record is encountered. As each record is Read, * it is incorporated into this WorksheetProtectionBlock. * <p/> * As per the OOO documentation, the protection block records can be expected to be written * toGether (with no intervening records), but earlier versions of POI (prior to Jun 2009) * didn't do this. Workbooks with sheet protection Created by those earlier POI versions * seemed to be valid (Excel opens them OK). So PO allows continues to support Reading of files * with non continuous worksheet protection blocks. * * <p/> * <b>Note</b> - when POI Writes out this WorksheetProtectionBlock, the records will always be * written in one consolidated block (in the standard ordering) regardless of how scattered the * records were when they were originally Read. */ public void AddRecords(RecordStream rs) { while (true) { if (!ReadARecord(rs)) { break; } } } /// <summary> /// the ProtectRecord. If one is not contained in the sheet, then one is created. /// </summary> private ProtectRecord Protect { get { if (_protectRecord == null) { _protectRecord = new ProtectRecord(false); } return _protectRecord; } } /// <summary> /// the PasswordRecord. If one is not Contained in the sheet, then one is Created. /// </summary> public PasswordRecord Password { get { if (_passwordRecord == null) { _passwordRecord = CreatePassword(); } return _passwordRecord; } } /// <summary> /// protect a spreadsheet with a password (not encrypted, just sets protect flags and the password.) /// </summary> /// <param name="password">password to set;Pass <code>null</code> to remove all protection</param> /// <param name="shouldProtectObjects">shouldProtectObjects are protected</param> /// <param name="shouldProtectScenarios">shouldProtectScenarios are protected</param> public void ProtectSheet(String password, bool shouldProtectObjects, bool shouldProtectScenarios) { if (password == null) { _passwordRecord = null; _protectRecord = null; _objectProtectRecord = null; _scenarioProtectRecord = null; return; } ProtectRecord prec = this.Protect; PasswordRecord pass = this.Password; prec.Protect = true; pass.Password = (PasswordRecord.HashPassword(password)); if (_objectProtectRecord == null && shouldProtectObjects) { ObjectProtectRecord rec = CreateObjectProtect(); rec.Protect = (true); _objectProtectRecord = rec; } if (_scenarioProtectRecord == null && shouldProtectScenarios) { ScenarioProtectRecord srec = CreateScenarioProtect(); srec.Protect = (true); _scenarioProtectRecord = srec; } } public bool IsSheetProtected { get { return _protectRecord != null && _protectRecord.Protect; } } public bool IsObjectProtected { get{ return _objectProtectRecord != null && _objectProtectRecord.Protect; } } public bool IsScenarioProtected { get { return _scenarioProtectRecord != null && _scenarioProtectRecord.Protect; } } /// <summary> /// Creates an ObjectProtect record with protect set to false. /// </summary> /// <returns></returns> private static ObjectProtectRecord CreateObjectProtect() { ObjectProtectRecord retval = new ObjectProtectRecord(); retval.Protect = (false); return retval; } /// <summary> /// Creates a ScenarioProtect record with protect set to false. /// </summary> /// <returns></returns> private static ScenarioProtectRecord CreateScenarioProtect() { ScenarioProtectRecord retval = new ScenarioProtectRecord(); retval.Protect = (false); return retval; } /// <summary> ///Creates a Password record with password set to 0x0000. /// </summary> /// <returns></returns> private static PasswordRecord CreatePassword() { return new PasswordRecord(0x0000); } public int PasswordHash { get { if (_passwordRecord == null) { return 0; } return _passwordRecord.Password; } } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Data.Forms.dll // Description: A dynamically loaded extension with a toolkit. // ******************************************************************************************************** // The contents of this file are subject to the MIT License (MIT) // you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://dotspatial.codeplex.com/license // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either expressed or implied. See the License for the specific language governing rights and // limitations under the License. // // The Initial Developer of this Original Code is Ted Dunsford. Created during refactoring 2010. // ******************************************************************************************************** using System; using System.Windows.Forms; namespace DotSpatial.Data.Forms { /// <summary> /// This handles the methodology of progress messaging in one place to make it easier to update. /// </summary> public class TimedProgressMeter { private readonly TimeSpan _timeSpan; private readonly Timer _timer; private string _baseMessage; private double _endValue = 100; private int _oldProg; // the previous progress level private int _prog; // the current progress level private IProgressHandler _progressHandler; private bool _silent; private double _startValue; private int _stepPercent = 1; private double _value; #region Constructors /// <summary> /// Constructs a Time-Based progress meter that shows progress against an expected time. /// </summary> /// <param name="progressHandler"></param> /// <param name="baseMessage"></param> /// <param name="estimatedTime"></param> public TimedProgressMeter(IProgressHandler progressHandler, string baseMessage, TimeSpan estimatedTime) { _progressHandler = progressHandler; _baseMessage = baseMessage; _timeSpan = estimatedTime; _endValue = estimatedTime.TotalSeconds * 1000; _timer = new Timer(); _timer.Interval = Convert.ToInt32(_timeSpan.TotalSeconds * 10); // Attempt to have a tick once during each estimated percentile //_timer.Interval = 100; _timer.Tick += TimerTick; _timer.Start(); // Timers should be on another thread... } /// <summary> /// Intializes a new progress meter, but doesn't support the IProgressHandler unless one is specified. /// </summary> public TimedProgressMeter() : this(null, "Calculating values.", 100) { } /// <summary> /// A progress meter can't actually do anything without a progressHandler, which actually displays the status. /// </summary> /// <param name="progressHandler">An IProgressHandler that will actually handle the status messages sent by this meter.</param> public TimedProgressMeter(IProgressHandler progressHandler) : this(progressHandler, "Calculating values.", 100) { } /// <summary> /// A progress meter that simply keeps track of progress and is capable of sending progress messages. /// This assumes a MaxValue of 100 unless it is changed later. /// </summary> /// <param name="progressHandler">Any valid IProgressHandler that will display progress messages</param> /// <param name="baseMessage">A base message to use as the basic status for this progress handler.</param> public TimedProgressMeter(IProgressHandler progressHandler, string baseMessage) : this(progressHandler, baseMessage, 100) { } /// <summary> /// A progress meter that simply keeps track of progress and is capable of sending progress messages. /// </summary> /// <param name="progressHandler">Any valid implementation if IProgressHandler that will handle the progress function</param> /// <param name="baseMessage">The message without any progress information.</param> /// <param name="endValue">Percent shoudl show a range between the MinValue and MaxValue. MinValue is assumed to be 0.</param> public TimedProgressMeter(IProgressHandler progressHandler, string baseMessage, object endValue) { _endValue = Convert.ToDouble(endValue); _progressHandler = progressHandler; Reset(); _baseMessage = baseMessage; } private void TimerTick(object sender, EventArgs e) { CurrentPercent++; } #endregion #region Methods /// <summary> /// Resets the progress meter to the 0 value. This sets the status message to "Ready.". /// </summary> public void Reset() { _prog = 0; _oldProg = 0; _baseMessage = "Ready."; if (_timer != null) _timer.Stop(); if (_silent) return; if (_progressHandler == null) return; _progressHandler.Progress(_baseMessage, _prog, _baseMessage); Application.DoEvents(); // Allow the form to update a status bar if necessary. } #endregion #region Properties /// <summary> /// Gets or sets the string that does not include any mention of progress percentage, but specifies what is occuring. /// </summary> public string Key { get { return _baseMessage; } set { _baseMessage = value; } } /// <summary> /// Gets or sets the current integer progress level from 0 to 100. If a new update is less than or equal to the previous /// value, then no progress will be displayed by the ProgressMeter. Values less than 0 are set to 0. Values greater than /// 100 are set to 100. /// </summary> public int CurrentPercent { get { return _prog; } set { int val = value; if (val < 0) val = 0; if (val > 100) { if (_timer != null) _timer.Stop(); val = 100; } _prog = val; if (_prog >= _oldProg + _stepPercent) { SendProgress(); _oldProg = _prog; } } } /// <summary> /// Gets or sets the current value relative to the specified MaxValue in order to update the progress. /// Setting this will also update OldProgress if there is an integer change in the percentage, and send /// a progress message to the IProgressHandler interface. /// </summary> public object CurrentValue { get { return _value; } set { _value = Convert.ToDouble(value); if (_startValue < _endValue) { CurrentPercent = Convert.ToInt32(Math.Round(100 * (_value - _startValue) / (_endValue - _startValue))); } else { CurrentPercent = Convert.ToInt32(Math.Round(100 * (_startValue - _value) / (_startValue - _endValue))); } } } /// <summary> /// The value that defines when the meter should show as 100% complete. /// EndValue can be less than StartValue, but values closer to EndValue /// will show as being closer to 100%. /// </summary> public object EndValue { get { return _endValue; } set { _endValue = Convert.ToDouble(value); } } /// <summary> /// Gets or sets whether the progress meter should send messages to the IProgressHandler. /// By default Silent is false, but setting this to true will disable the messaging portion. /// </summary> public bool Silent { get { return _silent; } set { _silent = value; } } /// <summary> /// The minimum value defines when the meter should show as 0% complete. /// </summary> public object StartValue { get { return _startValue; } set { _startValue = Convert.ToDouble(value); } } /// <summary> /// An integer value that is 1 by default. Ordinarilly this will send a progress message only when the integer progress /// has changed by 1 percentage point. For example, if StepPercent were set to 5, then a progress update would only /// be sent out at 5%, 10% and so on. This helps reduce overhead in cases where showing status messages is actually /// the majority of the processing time for the function. /// </summary> public int StepPercent { get { return _stepPercent; } set { _stepPercent = value; if (_stepPercent < 1) _stepPercent = 1; if (_stepPercent > 100) _stepPercent = 100; } } /// <summary> /// Gets or sets the previous integer progress level from 0 to 100. If a new update is less than or equal to the previous /// value, then no progress will be displayed by the ProgressMeter. Values less than 0 are set to 0. Values greater than /// 100 are set to 100. /// </summary> public int PreviousPercent { get { return _oldProg; } set { int val = value; if (val < 0) val = 0; if (val > 100) val = 100; _oldProg = val; } } /// <summary> /// Gets or sets the progress handler for this meter /// </summary> public IProgressHandler ProgressHandler { get { return _progressHandler; } set { _progressHandler = value; } } /// <summary> /// Sends a progress message to the IProgressHandler interface with the current message and progres /// </summary> public void SendProgress() { if (_silent) return; if (_progressHandler == null) return; _progressHandler.Progress(_baseMessage, _prog, _baseMessage + ", " + _prog + "% Complete."); Application.DoEvents(); // Allow the form to update a status bar if necessary. } #endregion } }
// // CodeWriter.cs // // Author: // Jb Evain ([email protected]) // // (C) 2005 - 2007 Jb Evain // // 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 Mono.Cecil.Cil { using System; using System.Collections; using Mono.Cecil; using Mono.Cecil.Binary; using Mono.Cecil.Metadata; using Mono.Cecil.Signatures; class CodeWriter : BaseCodeVisitor { ReflectionWriter m_reflectWriter; MemoryBinaryWriter m_binaryWriter; MemoryBinaryWriter m_codeWriter; IDictionary m_localSigCache; IDictionary m_standaloneSigCache; public CodeWriter (ReflectionWriter reflectWriter, MemoryBinaryWriter writer) { m_reflectWriter = reflectWriter; m_binaryWriter = writer; m_codeWriter = new MemoryBinaryWriter (); m_localSigCache = new Hashtable (); m_standaloneSigCache = new Hashtable (); } public RVA WriteMethodBody (MethodDefinition meth) { if (meth.Body == null) return RVA.Zero; RVA ret = m_reflectWriter.MetadataWriter.GetDataCursor (); meth.Body.Accept (this); return ret; } public override void VisitMethodBody (MethodBody body) { m_codeWriter.Empty (); } void WriteToken (MetadataToken token) { if (token.RID == 0) m_codeWriter.Write (0); else m_codeWriter.Write (token.ToUInt ()); } static int GetParameterIndex (MethodBody body, ParameterDefinition p) { int idx = body.Method.Parameters.IndexOf (p); if (idx == -1 && p == body.Method.This) return 0; if (body.Method.HasThis) idx++; return idx; } public override void VisitInstructionCollection (InstructionCollection instructions) { MethodBody body = instructions.Container; long start = m_codeWriter.BaseStream.Position; ComputeMaxStack (instructions); foreach (Instruction instr in instructions) { instr.Offset = (int) (m_codeWriter.BaseStream.Position - start); if (instr.OpCode.Size == 1) m_codeWriter.Write (instr.OpCode.Op2); else { m_codeWriter.Write (instr.OpCode.Op1); m_codeWriter.Write (instr.OpCode.Op2); } if (instr.OpCode.OperandType != OperandType.InlineNone && instr.Operand == null) throw new ReflectionException ("OpCode {0} have null operand", instr.OpCode.Name); switch (instr.OpCode.OperandType) { case OperandType.InlineNone : break; case OperandType.InlineSwitch : Instruction [] targets = (Instruction []) instr.Operand; for (int i = 0; i < targets.Length + 1; i++) m_codeWriter.Write ((uint) 0); break; case OperandType.ShortInlineBrTarget : m_codeWriter.Write ((byte) 0); break; case OperandType.InlineBrTarget : m_codeWriter.Write (0); break; case OperandType.ShortInlineI : if (instr.OpCode == OpCodes.Ldc_I4_S) m_codeWriter.Write ((sbyte) instr.Operand); else m_codeWriter.Write ((byte) instr.Operand); break; case OperandType.ShortInlineVar : m_codeWriter.Write ((byte) body.Variables.IndexOf ( (VariableDefinition) instr.Operand)); break; case OperandType.ShortInlineParam : m_codeWriter.Write ((byte) GetParameterIndex (body, (ParameterDefinition) instr.Operand)); break; case OperandType.InlineSig : WriteToken (GetCallSiteToken ((CallSite) instr.Operand)); break; case OperandType.InlineI : m_codeWriter.Write ((int) instr.Operand); break; case OperandType.InlineVar : m_codeWriter.Write ((short) body.Variables.IndexOf ( (VariableDefinition) instr.Operand)); break; case OperandType.InlineParam : m_codeWriter.Write ((short) GetParameterIndex ( body, (ParameterDefinition) instr.Operand)); break; case OperandType.InlineI8 : m_codeWriter.Write ((long) instr.Operand); break; case OperandType.ShortInlineR : m_codeWriter.Write ((float) instr.Operand); break; case OperandType.InlineR : m_codeWriter.Write ((double) instr.Operand); break; case OperandType.InlineString : WriteToken (new MetadataToken (TokenType.String, m_reflectWriter.MetadataWriter.AddUserString (instr.Operand as string))); break; case OperandType.InlineField : case OperandType.InlineMethod : case OperandType.InlineType : case OperandType.InlineTok : if (instr.Operand is TypeReference) WriteToken (m_reflectWriter.GetTypeDefOrRefToken ( instr.Operand as TypeReference)); else if (instr.Operand is GenericInstanceMethod) WriteToken (m_reflectWriter.GetMethodSpecToken (instr.Operand as GenericInstanceMethod)); else if (instr.Operand is MemberReference) WriteToken (m_reflectWriter.GetMemberRefToken ((MemberReference) instr.Operand)); else if (instr.Operand is IMetadataTokenProvider) WriteToken (((IMetadataTokenProvider) instr.Operand).MetadataToken); else throw new ReflectionException ( string.Format ("Wrong operand for {0} OpCode: {1}", instr.OpCode.OperandType, instr.Operand.GetType ().FullName)); break; } } // patch branches long pos = m_codeWriter.BaseStream.Position; foreach (Instruction instr in instructions) { switch (instr.OpCode.OperandType) { case OperandType.InlineSwitch : m_codeWriter.BaseStream.Position = instr.Offset + instr.OpCode.Size; Instruction [] targets = (Instruction []) instr.Operand; m_codeWriter.Write ((uint) targets.Length); foreach (Instruction tgt in targets) m_codeWriter.Write ((tgt.Offset - (instr.Offset + instr.OpCode.Size + (4 * (targets.Length + 1))))); break; case OperandType.ShortInlineBrTarget : m_codeWriter.BaseStream.Position = instr.Offset + instr.OpCode.Size; m_codeWriter.Write ((byte) (((Instruction) instr.Operand).Offset - (instr.Offset + instr.OpCode.Size + 1))); break; case OperandType.InlineBrTarget : m_codeWriter.BaseStream.Position = instr.Offset + instr.OpCode.Size; m_codeWriter.Write(((Instruction) instr.Operand).Offset - (instr.Offset + instr.OpCode.Size + 4)); break; } } m_codeWriter.BaseStream.Position = pos; } MetadataToken GetCallSiteToken (CallSite cs) { uint sig; int sentinel = cs.GetSentinel (); if (sentinel > 0) sig = m_reflectWriter.SignatureWriter.AddMethodDefSig ( m_reflectWriter.GetMethodDefSig (cs)); else sig = m_reflectWriter.SignatureWriter.AddMethodRefSig ( m_reflectWriter.GetMethodRefSig (cs)); if (m_standaloneSigCache.Contains (sig)) return (MetadataToken) m_standaloneSigCache [sig]; StandAloneSigTable sasTable = m_reflectWriter.MetadataTableWriter.GetStandAloneSigTable (); StandAloneSigRow sasRow = m_reflectWriter.MetadataRowWriter.CreateStandAloneSigRow (sig); sasTable.Rows.Add(sasRow); MetadataToken token = new MetadataToken (TokenType.Signature, (uint) sasTable.Rows.Count); m_standaloneSigCache [sig] = token; return token; } static int GetLength (Instruction start, Instruction end, InstructionCollection instructions) { Instruction last = instructions [instructions.Count - 1]; return (end == instructions.Outside ? last.Offset + GetSize (last) : end.Offset) - start.Offset; } static int GetSize (Instruction i) { int size = i.OpCode.Size; switch (i.OpCode.OperandType) { case OperandType.InlineSwitch: size += ((Instruction []) i.Operand).Length * 4; break; case OperandType.InlineI8: case OperandType.InlineR: size += 8; break; case OperandType.InlineBrTarget: case OperandType.InlineField: case OperandType.InlineI: case OperandType.InlineMethod: case OperandType.InlineString: case OperandType.InlineTok: case OperandType.InlineType: case OperandType.ShortInlineR: size += 4; break; case OperandType.InlineParam: case OperandType.InlineVar: size += 2; break; case OperandType.ShortInlineBrTarget: case OperandType.ShortInlineI: case OperandType.ShortInlineParam: case OperandType.ShortInlineVar: size += 1; break; } return size; } static bool IsRangeFat (Instruction start, Instruction end, InstructionCollection instructions) { return GetLength (start, end, instructions) >= 256 || start.Offset >= 65536; } static bool IsFat (ExceptionHandlerCollection seh) { for (int i = 0; i < seh.Count; i++) { ExceptionHandler eh = seh [i]; if (IsRangeFat (eh.TryStart, eh.TryEnd, seh.Container.Instructions)) return true; if (IsRangeFat (eh.HandlerStart, eh.HandlerEnd, seh.Container.Instructions)) return true; switch (eh.Type) { case ExceptionHandlerType.Filter : if (IsRangeFat (eh.FilterStart, eh.FilterEnd, seh.Container.Instructions)) return true; break; } } return false; } void WriteExceptionHandlerCollection (ExceptionHandlerCollection seh) { m_codeWriter.QuadAlign (); if (seh.Count < 0x15 && !IsFat (seh)) { m_codeWriter.Write ((byte) MethodDataSection.EHTable); m_codeWriter.Write ((byte) (seh.Count * 12 + 4)); m_codeWriter.Write (new byte [2]); foreach (ExceptionHandler eh in seh) { m_codeWriter.Write ((ushort) eh.Type); m_codeWriter.Write ((ushort) eh.TryStart.Offset); m_codeWriter.Write ((byte) (eh.TryEnd.Offset - eh.TryStart.Offset)); m_codeWriter.Write ((ushort) eh.HandlerStart.Offset); m_codeWriter.Write ((byte) GetLength (eh.HandlerStart, eh.HandlerEnd, seh.Container.Instructions)); WriteHandlerSpecific (eh); } } else { m_codeWriter.Write ((byte) (MethodDataSection.FatFormat | MethodDataSection.EHTable)); WriteFatBlockSize (seh); foreach (ExceptionHandler eh in seh) { m_codeWriter.Write ((uint) eh.Type); m_codeWriter.Write ((uint) eh.TryStart.Offset); m_codeWriter.Write ((uint) (eh.TryEnd.Offset - eh.TryStart.Offset)); m_codeWriter.Write ((uint) eh.HandlerStart.Offset); m_codeWriter.Write ((uint) GetLength (eh.HandlerStart, eh.HandlerEnd, seh.Container.Instructions)); WriteHandlerSpecific (eh); } } } void WriteFatBlockSize (ExceptionHandlerCollection seh) { int size = seh.Count * 24 + 4; m_codeWriter.Write ((byte) (size & 0xff)); m_codeWriter.Write ((byte) ((size >> 8) & 0xff)); m_codeWriter.Write ((byte) ((size >> 16) & 0xff)); } void WriteHandlerSpecific (ExceptionHandler eh) { switch (eh.Type) { case ExceptionHandlerType.Catch : WriteToken (eh.CatchType.MetadataToken); break; case ExceptionHandlerType.Filter : m_codeWriter.Write ((uint) eh.FilterStart.Offset); break; default : m_codeWriter.Write (0); break; } } public override void VisitVariableDefinitionCollection (VariableDefinitionCollection variables) { MethodBody body = variables.Container as MethodBody; if (body == null) return; uint sig = m_reflectWriter.SignatureWriter.AddLocalVarSig ( GetLocalVarSig (variables)); if (m_localSigCache.Contains (sig)) { body.LocalVarToken = (int) m_localSigCache [sig]; return; } StandAloneSigTable sasTable = m_reflectWriter.MetadataTableWriter.GetStandAloneSigTable (); StandAloneSigRow sasRow = m_reflectWriter.MetadataRowWriter.CreateStandAloneSigRow ( sig); sasTable.Rows.Add (sasRow); body.LocalVarToken = sasTable.Rows.Count; m_localSigCache [sig] = body.LocalVarToken; } public override void TerminateMethodBody (MethodBody body) { long pos = m_binaryWriter.BaseStream.Position; if (body.Variables.Count > 0 || body.ExceptionHandlers.Count > 0 || m_codeWriter.BaseStream.Length >= 64 || body.MaxStack > 8) { MethodHeader header = MethodHeader.FatFormat; if (body.InitLocals) header |= MethodHeader.InitLocals; if (body.ExceptionHandlers.Count > 0) header |= MethodHeader.MoreSects; m_binaryWriter.Write ((byte) header); m_binaryWriter.Write ((byte) 0x30); // (header size / 4) << 4 m_binaryWriter.Write ((short) body.MaxStack); m_binaryWriter.Write ((int) m_codeWriter.BaseStream.Length); m_binaryWriter.Write (((int) TokenType.Signature | body.LocalVarToken)); WriteExceptionHandlerCollection (body.ExceptionHandlers); } else m_binaryWriter.Write ((byte) ((byte) MethodHeader.TinyFormat | m_codeWriter.BaseStream.Length << 2)); m_binaryWriter.Write (m_codeWriter); m_binaryWriter.QuadAlign (); m_reflectWriter.MetadataWriter.AddData ( (int) (m_binaryWriter.BaseStream.Position - pos)); } public LocalVarSig.LocalVariable GetLocalVariableSig (VariableDefinition var) { LocalVarSig.LocalVariable lv = new LocalVarSig.LocalVariable (); TypeReference type = var.VariableType; lv.CustomMods = m_reflectWriter.GetCustomMods (type); if (type is PinnedType) { lv.Constraint |= Constraint.Pinned; type = (type as PinnedType).ElementType; } if (type is ReferenceType) { lv.ByRef = true; type = (type as ReferenceType).ElementType; } lv.Type = m_reflectWriter.GetSigType (type); return lv; } public LocalVarSig GetLocalVarSig (VariableDefinitionCollection vars) { LocalVarSig lvs = new LocalVarSig (); lvs.CallingConvention |= 0x7; lvs.Count = vars.Count; lvs.LocalVariables = new LocalVarSig.LocalVariable [lvs.Count]; for (int i = 0; i < lvs.Count; i++) { lvs.LocalVariables [i] = GetLocalVariableSig (vars [i]); } return lvs; } static void ComputeMaxStack (InstructionCollection instructions) { InstructionCollection ehs = new InstructionCollection (null); foreach (ExceptionHandler eh in instructions.Container.ExceptionHandlers) { switch (eh.Type) { case ExceptionHandlerType.Catch : ehs.Add (eh.HandlerStart); break; case ExceptionHandlerType.Filter : ehs.Add (eh.FilterStart); break; } } int max = 0, current = 0; foreach (Instruction instr in instructions) { if (ehs.Contains (instr)) current++; switch (instr.OpCode.StackBehaviourPush) { case StackBehaviour.Push1: case StackBehaviour.Pushi: case StackBehaviour.Pushi8: case StackBehaviour.Pushr4: case StackBehaviour.Pushr8: case StackBehaviour.Pushref: case StackBehaviour.Varpush: current++; break; case StackBehaviour.Push1_push1: current += 2; break; } if (max < current) max = current; switch (instr.OpCode.StackBehaviourPop) { case StackBehaviour.Varpop: break; case StackBehaviour.Pop1: case StackBehaviour.Popi: case StackBehaviour.Popref: current--; break; case StackBehaviour.Pop1_pop1: case StackBehaviour.Popi_pop1: case StackBehaviour.Popi_popi: case StackBehaviour.Popi_popi8: case StackBehaviour.Popi_popr4: case StackBehaviour.Popi_popr8: case StackBehaviour.Popref_pop1: case StackBehaviour.Popref_popi: current -= 2; break; case StackBehaviour.Popi_popi_popi: case StackBehaviour.Popref_popi_popi: case StackBehaviour.Popref_popi_popi8: case StackBehaviour.Popref_popi_popr4: case StackBehaviour.Popref_popi_popr8: case StackBehaviour.Popref_popi_popref: current -= 3; break; } if (current < 0) current = 0; } instructions.Container.MaxStack = max; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Xml.XPath; namespace MS.Internal.Xml.Cache { /// <summary> /// Implementation of a Node in the XPath/XQuery data model. /// 1. All nodes are stored in variable-size pages (max 65536 nodes/page) of XPathNode structures. /// 2. Pages are sequentially numbered. Nodes are allocated in strict document order. /// 3. Node references take the form of a (page, index) pair. /// 4. Each node explicitly stores a parent and a sibling reference. /// 5. If a node has one or more attributes and/or non-collapsed content children, then its first /// child is stored in the next slot. If the node is in the last slot of a page, then its first /// child is stored in the first slot of the next page. /// 6. Attributes are linked together at the start of the child list. /// 7. Namespaces are allocated in totally separate pages. Elements are associated with /// declared namespaces via a hashtable map in the document. /// 8. Name parts are always non-null (string.Empty for nodes without names) /// 9. XPathNodeInfoAtom contains all information that is common to many nodes in a /// document, and therefore is atomized to save space. This includes the document, the name, /// the child, sibling, parent, and value pages, and the schema type. /// 10. The node structure is 20 bytes in length. Out-of-line overhead is typically 2-4 bytes per node. /// </summary> internal struct XPathNode { private XPathNodeInfoAtom _info; // Atomized node information private ushort _idxSibling; // Page index of sibling node private ushort _idxParent; // Page index of parent node private ushort _idxSimilar; // Page index of next node in document order that has local name with same hashcode private ushort _posOffset; // Line position offset of node (added to LinePositionBase) private uint _props; // Node properties (broken down into bits below) private string _value; // String value of node private const uint NodeTypeMask = 0xF; private const uint HasAttributeBit = 0x10; private const uint HasContentChildBit = 0x20; private const uint HasElementChildBit = 0x40; private const uint HasCollapsedTextBit = 0x80; private const uint AllowShortcutTagBit = 0x100; // True if this is an element that allows shortcut tag syntax private const uint HasNmspDeclsBit = 0x200; // True if this is an element with namespace declarations declared on it private const uint LineNumberMask = 0x00FFFC00; // 14 bits for line number offset (0 - 16K) private const int LineNumberShift = 10; private const int CollapsedPositionShift = 24; // 8 bits for collapsed text position offset (0 - 256) #if DEBUG public const int MaxLineNumberOffset = 0x20; public const int MaxLinePositionOffset = 0x20; public const int MaxCollapsedPositionOffset = 0x10; #else public const int MaxLineNumberOffset = 0x3FFF; public const int MaxLinePositionOffset = 0xFFFF; public const int MaxCollapsedPositionOffset = 0xFF; #endif /// <summary> /// Returns the type of this node /// </summary> public XPathNodeType NodeType { get { return (XPathNodeType)(_props & NodeTypeMask); } } /// <summary> /// Returns the namespace prefix of this node. If this node has no prefix, then the empty string /// will be returned (never null). /// </summary> public string Prefix { get { return _info.Prefix; } } /// <summary> /// Returns the local name of this node. If this node has no name, then the empty string /// will be returned (never null). /// </summary> public string LocalName { get { return _info.LocalName; } } /// <summary> /// Returns the name of this node. If this node has no name, then the empty string /// will be returned (never null). /// </summary> public string Name { get { if (Prefix.Length == 0) { return LocalName; } else { return string.Concat(Prefix, ":", LocalName); } } } /// <summary> /// Returns the namespace part of this node's name. If this node has no name, then the empty string /// will be returned (never null). /// </summary> public string NamespaceUri { get { return _info.NamespaceUri; } } /// <summary> /// Returns this node's document. /// </summary> public XPathDocument Document { get { return _info.Document; } } /// <summary> /// Returns this node's base Uri. This is string.Empty for all node kinds except Element, Root, and PI. /// </summary> public string BaseUri { get { return _info.BaseUri; } } /// <summary> /// Returns this node's source line number. /// </summary> public int LineNumber { get { return _info.LineNumberBase + (int)((_props & LineNumberMask) >> LineNumberShift); } } /// <summary> /// Return this node's source line position. /// </summary> public int LinePosition { get { return _info.LinePositionBase + (int)_posOffset; } } /// <summary> /// If this node is an element with collapsed text, then return the source line position of the node (the /// source line number is the same as LineNumber). /// </summary> public int CollapsedLinePosition { get { Debug.Assert(HasCollapsedText, "Do not call CollapsedLinePosition unless HasCollapsedText is true."); return LinePosition + (int)(_props >> CollapsedPositionShift); } } /// <summary> /// Returns information about the node page. Only the 0th node on each page has this property defined. /// </summary> public XPathNodePageInfo PageInfo { get { return _info.PageInfo; } } /// <summary> /// Returns the root node of the current document. This always succeeds. /// </summary> public int GetRoot(out XPathNode[] pageNode) { return _info.Document.GetRootNode(out pageNode); } /// <summary> /// Returns the parent of this node. If this node has no parent, then 0 is returned. /// </summary> public int GetParent(out XPathNode[] pageNode) { pageNode = _info.ParentPage; return _idxParent; } /// <summary> /// Returns the next sibling of this node. If this node has no next sibling, then 0 is returned. /// </summary> public int GetSibling(out XPathNode[] pageNode) { pageNode = _info.SiblingPage; return _idxSibling; } /// <summary> /// Returns the next element in document order that has the same local name hashcode as this element. /// If there are no similar elements, then 0 is returned. /// </summary> public int GetSimilarElement(out XPathNode[] pageNode) { pageNode = _info.SimilarElementPage; return _idxSimilar; } /// <summary> /// Returns true if this node's name matches the specified localName and namespaceName. Assume /// that localName has been atomized, but namespaceName has not. /// </summary> public bool NameMatch(string localName, string namespaceName) { Debug.Assert(localName == null || (object)Document.NameTable.Get(localName) == (object)localName, "localName must be atomized."); return (object)_info.LocalName == (object)localName && _info.NamespaceUri == namespaceName; } /// <summary> /// Returns true if this is an Element node with a name that matches the specified localName and /// namespaceName. Assume that localName has been atomized, but namespaceName has not. /// </summary> public bool ElementMatch(string localName, string namespaceName) { Debug.Assert(localName == null || (object)Document.NameTable.Get(localName) == (object)localName, "localName must be atomized."); return NodeType == XPathNodeType.Element && (object)_info.LocalName == (object)localName && _info.NamespaceUri == namespaceName; } /// <summary> /// Return true if this node is an xmlns:xml node. /// </summary> public bool IsXmlNamespaceNode { get { string localName = _info.LocalName; return NodeType == XPathNodeType.Namespace && localName.Length == 3 && localName == "xml"; } } /// <summary> /// Returns true if this node has a sibling. /// </summary> public bool HasSibling { get { return _idxSibling != 0; } } /// <summary> /// Returns true if this node has a collapsed text node as its only content-typed child. /// </summary> public bool HasCollapsedText { get { return (_props & HasCollapsedTextBit) != 0; } } /// <summary> /// Returns true if this node has at least one attribute. /// </summary> public bool HasAttribute { get { return (_props & HasAttributeBit) != 0; } } /// <summary> /// Returns true if this node has at least one content-typed child (attributes and namespaces /// don't count). /// </summary> public bool HasContentChild { get { return (_props & HasContentChildBit) != 0; } } /// <summary> /// Returns true if this node has at least one element child. /// </summary> public bool HasElementChild { get { return (_props & HasElementChildBit) != 0; } } /// <summary> /// Returns true if this is an attribute or namespace node. /// </summary> public bool IsAttrNmsp { get { XPathNodeType xptyp = NodeType; return xptyp == XPathNodeType.Attribute || xptyp == XPathNodeType.Namespace; } } /// <summary> /// Returns true if this is a text or whitespace node. /// </summary> public bool IsText { get { return XPathNavigator.IsText(NodeType); } } /// <summary> /// Returns true if this node has local namespace declarations associated with it. Since all /// namespace declarations are stored out-of-line in the owner Document, this property /// can be consulted in order to avoid a lookup in the common case where this node has no /// local namespace declarations. /// </summary> public bool HasNamespaceDecls { get { return (_props & HasNmspDeclsBit) != 0; } set { if (value) _props |= HasNmspDeclsBit; else unchecked { _props &= (byte)~((uint)HasNmspDeclsBit); } } } /// <summary> /// Returns true if this node is an empty element that allows shortcut tag syntax. /// </summary> public bool AllowShortcutTag { get { return (_props & AllowShortcutTagBit) != 0; } } /// <summary> /// Cached hashcode computed over the local name of this element. /// </summary> public int LocalNameHashCode { get { return _info.LocalNameHashCode; } } /// <summary> /// Return the precomputed String value of this node (null if no value exists, i.e. document node, element node with complex content, etc). /// </summary> public string Value { get { return _value; } } //----------------------------------------------- // Node construction //----------------------------------------------- /// <summary> /// Constructs the 0th XPathNode in each page, which contains only page information. /// </summary> public void Create(XPathNodePageInfo pageInfo) { _info = new XPathNodeInfoAtom(pageInfo); } /// <summary> /// Constructs a XPathNode. Later, the idxSibling and value fields may be fixed up. /// </summary> public void Create(XPathNodeInfoAtom info, XPathNodeType xptyp, int idxParent) { Debug.Assert(info != null && idxParent <= UInt16.MaxValue); _info = info; _props = (uint)xptyp; _idxParent = (ushort)idxParent; } /// <summary> /// Set this node's line number information. /// </summary> public void SetLineInfoOffsets(int lineNumOffset, int linePosOffset) { Debug.Assert(lineNumOffset >= 0 && lineNumOffset <= MaxLineNumberOffset, "Line number offset too large or small: " + lineNumOffset); Debug.Assert(linePosOffset >= 0 && linePosOffset <= MaxLinePositionOffset, "Line position offset too large or small: " + linePosOffset); _props |= ((uint)lineNumOffset << LineNumberShift); _posOffset = (ushort)linePosOffset; } /// <summary> /// Set the position offset of this element's collapsed text. /// </summary> public void SetCollapsedLineInfoOffset(int posOffset) { Debug.Assert(posOffset >= 0 && posOffset <= MaxCollapsedPositionOffset, "Collapsed text line position offset too large or small: " + posOffset); _props |= ((uint)posOffset << CollapsedPositionShift); } /// <summary> /// Set this node's value. /// </summary> public void SetValue(string value) { _value = value; } /// <summary> /// Create an empty element value. /// </summary> public void SetEmptyValue(bool allowShortcutTag) { Debug.Assert(NodeType == XPathNodeType.Element); _value = string.Empty; if (allowShortcutTag) _props |= AllowShortcutTagBit; } /// <summary> /// Create a collapsed text node on this element having the specified value. /// </summary> public void SetCollapsedValue(string value) { Debug.Assert(NodeType == XPathNodeType.Element); _value = value; _props |= HasContentChildBit | HasCollapsedTextBit; } /// <summary> /// This method is called when a new child is appended to this node's list of attributes and children. /// The type of the new child is used to determine how various parent properties should be set. /// </summary> public void SetParentProperties(XPathNodeType xptyp) { if (xptyp == XPathNodeType.Attribute) { _props |= HasAttributeBit; } else { _props |= HasContentChildBit; if (xptyp == XPathNodeType.Element) _props |= HasElementChildBit; } } /// <summary> /// Link this node to its next sibling. If "pageSibling" is different than the one stored in the InfoAtom, re-atomize. /// </summary> public void SetSibling(XPathNodeInfoTable infoTable, XPathNode[] pageSibling, int idxSibling) { Debug.Assert(pageSibling != null && idxSibling != 0 && idxSibling <= UInt16.MaxValue, "Bad argument"); Debug.Assert(_idxSibling == 0, "SetSibling should not be called more than once."); _idxSibling = (ushort)idxSibling; if (pageSibling != _info.SiblingPage) { // Re-atomize the InfoAtom _info = infoTable.Create(_info.LocalName, _info.NamespaceUri, _info.Prefix, _info.BaseUri, _info.ParentPage, pageSibling, _info.SimilarElementPage, _info.Document, _info.LineNumberBase, _info.LinePositionBase); } } /// <summary> /// Link this element to the next element in document order that shares a local name having the same hash code. /// If "pageSimilar" is different than the one stored in the InfoAtom, re-atomize. /// </summary> public void SetSimilarElement(XPathNodeInfoTable infoTable, XPathNode[] pageSimilar, int idxSimilar) { Debug.Assert(pageSimilar != null && idxSimilar != 0 && idxSimilar <= UInt16.MaxValue, "Bad argument"); Debug.Assert(_idxSimilar == 0, "SetSimilarElement should not be called more than once."); _idxSimilar = (ushort)idxSimilar; if (pageSimilar != _info.SimilarElementPage) { // Re-atomize the InfoAtom _info = infoTable.Create(_info.LocalName, _info.NamespaceUri, _info.Prefix, _info.BaseUri, _info.ParentPage, _info.SiblingPage, pageSimilar, _info.Document, _info.LineNumberBase, _info.LinePositionBase); } } } /// <summary> /// A reference to a XPathNode is composed of two values: the page on which the node is located, and the node's /// index in the page. /// </summary> internal struct XPathNodeRef { private XPathNode[] _page; private int _idx; public XPathNodeRef(XPathNode[] page, int idx) { _page = page; _idx = idx; } public XPathNode[] Page { get { return _page; } } public int Index { get { return _idx; } } public override int GetHashCode() { return XPathNodeHelper.GetLocation(_page, _idx); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a source code document that is part of a project. /// It provides access to the source text, parsed syntax tree and the corresponding semantic model. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] public partial class Document : TextDocument { private WeakReference<SemanticModel> _model; private Task<SyntaxTree> _syntaxTreeResultTask; internal Document(Project project, DocumentState state) : base(project, state) { } private DocumentState DocumentState => (DocumentState)State; /// <summary> /// The kind of source code this document contains. /// </summary> public SourceCodeKind SourceCodeKind => DocumentState.SourceCodeKind; /// <summary> /// True if the info of the document change (name, folders, file path; not the content) /// </summary> internal bool HasInfoChanged(Document otherDocument) { return DocumentState.Info != otherDocument.DocumentState.Info || DocumentState.SourceCodeKind != otherDocument.SourceCodeKind; } /// <summary> /// Gets a <see cref="DocumentInfo"/> for this document w/o the content. /// </summary> internal DocumentInfo GetDocumentInfoWithoutContent() { return DocumentState.Info.WithSourceCodeKind(DocumentState.SourceCodeKind); } /// <summary> /// True if the document content has potentially changed. /// Does not compare actual text. /// </summary> internal bool HasContentChanged(Document otherDocument) { return DocumentState.HasContentChanged(otherDocument.DocumentState); } /// <summary> /// Get the current syntax tree for the document if the text is already loaded and the tree is already parsed. /// In almost all cases, you should call <see cref="GetSyntaxTreeAsync"/> to fetch the tree, which will parse the tree /// if it's not already parsed. /// </summary> public bool TryGetSyntaxTree(out SyntaxTree syntaxTree) { // if we already have cache, use it if (_syntaxTreeResultTask != null) { syntaxTree = _syntaxTreeResultTask.Result; return true; } if (!DocumentState.TryGetSyntaxTree(out syntaxTree)) { return false; } // cache the result if it is not already cached if (_syntaxTreeResultTask == null) { var result = Task.FromResult(syntaxTree); Interlocked.CompareExchange(ref _syntaxTreeResultTask, result, null); } return true; } /// <summary> /// Get the current syntax tree version for the document if the text is already loaded and the tree is already parsed. /// In almost all cases, you should call <see cref="GetSyntaxVersionAsync"/> to fetch the version, which will load the tree /// if it's not already available. /// </summary> public bool TryGetSyntaxVersion(out VersionStamp version) { version = default(VersionStamp); if (!this.TryGetTextVersion(out var textVersion)) { return false; } var projectVersion = this.Project.Version; version = textVersion.GetNewerVersion(projectVersion); return true; } /// <summary> /// Gets the version of the document's top level signature if it is already loaded and available. /// </summary> internal bool TryGetTopLevelChangeTextVersion(out VersionStamp version) { return DocumentState.TryGetTopLevelChangeTextVersion(out version); } /// <summary> /// Gets the version of the syntax tree. This is generally the newer of the text version and the project's version. /// </summary> public async Task<VersionStamp> GetSyntaxVersionAsync(CancellationToken cancellationToken = default(CancellationToken)) { var textVersion = await this.GetTextVersionAsync(cancellationToken).ConfigureAwait(false); var projectVersion = this.Project.Version; return textVersion.GetNewerVersion(projectVersion); } /// <summary> /// <code>true</code> if this Document supports providing data through the /// <see cref="GetSyntaxTreeAsync"/> and <see cref="GetSyntaxRootAsync"/> methods. /// /// If <code>false</code> then these methods will return <code>null</code> instead. /// </summary> public bool SupportsSyntaxTree => DocumentState.SupportsSyntaxTree; /// <summary> /// <code>true</code> if this Document supports providing data through the /// <see cref="GetSemanticModelAsync"/> method. /// /// If <code>false</code> then this method will return <code>null</code> instead. /// </summary> public bool SupportsSemanticModel { get { return this.SupportsSyntaxTree && this.Project.SupportsCompilation; } } /// <summary> /// Gets the <see cref="SyntaxTree" /> for this document asynchronously. /// </summary> public Task<SyntaxTree> GetSyntaxTreeAsync(CancellationToken cancellationToken = default(CancellationToken)) { // If the language doesn't support getting syntax trees for a document, then bail out immediately. if (!this.SupportsSyntaxTree) { return SpecializedTasks.Default<SyntaxTree>(); } // if we have a cached result task use it if (_syntaxTreeResultTask != null) { return _syntaxTreeResultTask; } // check to see if we already have the tree before actually going async if (TryGetSyntaxTree(out var tree)) { // stash a completed result task for this value for the next request (to reduce extraneous allocations of tasks) // don't use the actual async task because it depends on a specific cancellation token // its okay to cache the task and hold onto the SyntaxTree, because the DocumentState already keeps the SyntaxTree alive. Interlocked.CompareExchange(ref _syntaxTreeResultTask, Task.FromResult(tree), null); return _syntaxTreeResultTask; } // do it async for real. return DocumentState.GetSyntaxTreeAsync(cancellationToken); } internal SyntaxTree GetSyntaxTreeSynchronously(CancellationToken cancellationToken) { if (!this.SupportsSyntaxTree) { return null; } return DocumentState.GetSyntaxTree(cancellationToken); } /// <summary> /// Gets the root node of the current syntax tree if the syntax tree has already been parsed and the tree is still cached. /// In almost all cases, you should call <see cref="GetSyntaxRootAsync"/> to fetch the root node, which will parse /// the document if necessary. /// </summary> public bool TryGetSyntaxRoot(out SyntaxNode root) { root = null; return this.TryGetSyntaxTree(out var tree) && tree.TryGetRoot(out root) && root != null; } /// <summary> /// Gets the root node of the syntax tree asynchronously. /// </summary> public async Task<SyntaxNode> GetSyntaxRootAsync(CancellationToken cancellationToken = default(CancellationToken)) { if (!this.SupportsSyntaxTree) { return null; } var tree = await this.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); return await tree.GetRootAsync(cancellationToken).ConfigureAwait(false); } /// <summary> /// Only for features that absolutely must run synchronously (probably because they're /// on the UI thread). Right now, the only feature this is for is Outlining as VS will /// block on that feature from the UI thread when a document is opened. /// </summary> internal SyntaxNode GetSyntaxRootSynchronously(CancellationToken cancellationToken) { if (!this.SupportsSyntaxTree) { return null; } var tree = this.GetSyntaxTreeSynchronously(cancellationToken); return tree.GetRoot(cancellationToken); } /// <summary> /// Gets the current semantic model for this document if the model is already computed and still cached. /// In almost all cases, you should call <see cref="GetSemanticModelAsync"/>, which will compute the semantic model /// if necessary. /// </summary> public bool TryGetSemanticModel(out SemanticModel semanticModel) { semanticModel = null; return _model != null && _model.TryGetTarget(out semanticModel); } /// <summary> /// Gets the semantic model for this document asynchronously. /// </summary> public async Task<SemanticModel> GetSemanticModelAsync(CancellationToken cancellationToken = default(CancellationToken)) { try { if (!this.SupportsSemanticModel) { return null; } if (this.TryGetSemanticModel(out var semanticModel)) { return semanticModel; } var syntaxTree = await this.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var compilation = await this.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var result = compilation.GetSemanticModel(syntaxTree); Contract.ThrowIfNull(result); // first try set the cache if it has not been set var original = Interlocked.CompareExchange(ref _model, new WeakReference<SemanticModel>(result), null); // okay, it is first time. if (original == null) { return result; } // it looks like someone has set it. try to reuse same semantic model if (original.TryGetTarget(out semanticModel)) { return semanticModel; } // it looks like cache is gone. reset the cache. original.SetTarget(result); return result; } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Creates a new instance of this document updated to have the source code kind specified. /// </summary> public Document WithSourceCodeKind(SourceCodeKind kind) { return this.Project.Solution.WithDocumentSourceCodeKind(this.Id, kind).GetDocument(this.Id); } /// <summary> /// Creates a new instance of this document updated to have the text specified. /// </summary> public Document WithText(SourceText text) { return this.Project.Solution.WithDocumentText(this.Id, text, PreservationMode.PreserveIdentity).GetDocument(this.Id); } /// <summary> /// Creates a new instance of this document updated to have a syntax tree rooted by the specified syntax node. /// </summary> public Document WithSyntaxRoot(SyntaxNode root) { return this.Project.Solution.WithDocumentSyntaxRoot(this.Id, root, PreservationMode.PreserveIdentity).GetDocument(this.Id); } /// <summary> /// Creates a new instance of this document updated to have the specified name. /// </summary> public Document WithName(string name) { return this.Project.Solution.WithDocumentName(this.Id, name).GetDocument(this.Id); } /// <summary> /// Creates a new instance of this document updated to have the specified folders. /// </summary> public Document WithFolders(IEnumerable<string> folders) { return this.Project.Solution.WithDocumentFolders(this.Id, folders).GetDocument(this.Id); } /// <summary> /// Creates a new instance of this document updated to have the specified file path. /// </summary> /// <param name="filePath"></param> public Document WithFilePath(string filePath) { return this.Project.Solution.WithDocumentFilePath(this.Id, filePath).GetDocument(this.Id); } /// <summary> /// Get the text changes between this document and a prior version of the same document. /// The changes, when applied to the text of the old document, will produce the text of the current document. /// </summary> public async Task<IEnumerable<TextChange>> GetTextChangesAsync(Document oldDocument, CancellationToken cancellationToken = default(CancellationToken)) { try { using (Logger.LogBlock(FunctionId.Workspace_Document_GetTextChanges, this.Name, cancellationToken)) { if (oldDocument == this) { // no changes return SpecializedCollections.EmptyEnumerable<TextChange>(); } if (this.Id != oldDocument.Id) { throw new ArgumentException(WorkspacesResources.The_specified_document_is_not_a_version_of_this_document); } // first try to see if text already knows its changes IList<TextChange> textChanges = null; if (this.TryGetText(out var text) && oldDocument.TryGetText(out var oldText)) { if (text == oldText) { return SpecializedCollections.EmptyEnumerable<TextChange>(); } var container = text.Container; if (container != null) { textChanges = text.GetTextChanges(oldText).ToList(); // if changes are significant (not the whole document being replaced) then use these changes if (textChanges.Count > 1 || (textChanges.Count == 1 && textChanges[0].Span != new TextSpan(0, oldText.Length))) { return textChanges; } } } // get changes by diffing the trees if (this.SupportsSyntaxTree) { var tree = await this.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var oldTree = await oldDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); return tree.GetChanges(oldTree); } text = await this.GetTextAsync(cancellationToken).ConfigureAwait(false); oldText = await oldDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); return text.GetTextChanges(oldText).ToList(); } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Gets the list of <see cref="DocumentId"/>s that are linked to this /// <see cref="Document" />. <see cref="Document"/>s are considered to be linked if they /// share the same <see cref="TextDocument.FilePath" />. This <see cref="DocumentId"/> is excluded from the /// result. /// </summary> public ImmutableArray<DocumentId> GetLinkedDocumentIds() { var documentIdsWithPath = this.Project.Solution.GetDocumentIdsWithFilePath(this.FilePath); var filteredDocumentIds = this.Project.Solution.FilterDocumentIdsByLanguage(documentIdsWithPath, this.Project.Language).ToImmutableArray(); return filteredDocumentIds.Remove(this.Id); } /// <summary> /// Creates a branched version of this document that has its semantic model frozen in whatever state it is available at the time, /// assuming a background process is constructing the semantics asynchronously. Repeated calls to this method may return /// documents with increasingly more complete semantics. /// /// Use this method to gain access to potentially incomplete semantics quickly. /// </summary> internal async Task<Document> WithFrozenPartialSemanticsAsync(CancellationToken cancellationToken) { var solution = this.Project.Solution; var workspace = solution.Workspace; // only produce doc with frozen semantics if this document is part of the workspace's // primary branch and there is actual background compilation going on, since w/o // background compilation the semantics won't be moving toward completeness. Also, // ensure that the project that this document is part of actually supports compilations, // as partial semantics don't make sense otherwise. if (solution.BranchId == workspace.PrimaryBranchId && workspace.PartialSemanticsEnabled && this.Project.SupportsCompilation) { var newSolution = await this.Project.Solution.WithFrozenPartialCompilationIncludingSpecificDocumentAsync(this.Id, cancellationToken).ConfigureAwait(false); return newSolution.GetDocument(this.Id); } else { return this; } } private string GetDebuggerDisplay() { return this.Name; } private AsyncLazy<DocumentOptionSet> _cachedOptions; /// <summary> /// Returns the options that should be applied to this document. This consists of global options from <see cref="Solution.Options"/>, /// merged with any settings the user has specified at the document levels. /// </summary> /// <remarks> /// This method is async because this may require reading other files. In files that are already open, this is expected to be cheap and complete synchronously. /// </remarks> public Task<DocumentOptionSet> GetOptionsAsync(CancellationToken cancellationToken = default(CancellationToken)) { if (_cachedOptions == null) { var newAsyncLazy = new AsyncLazy<DocumentOptionSet>(async c => { var optionsService = Project.Solution.Workspace.Services.GetRequiredService<IOptionService>(); var optionSet = await optionsService.GetUpdatedOptionSetForDocumentAsync(this, Project.Solution.Options, c).ConfigureAwait(false); return new DocumentOptionSet(optionSet, Project.Language); }, cacheResult: true); Interlocked.CompareExchange(ref _cachedOptions, newAsyncLazy, comparand: null); } return _cachedOptions.GetValueAsync(cancellationToken); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Net.Http; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using Azure.Core.Pipeline; using NUnit.Framework; namespace Azure.Core.TestFramework { /// <summary> /// Encapsulates a process running an instance of the Test Proxy as well as providing access to the Test Proxy administration actions /// via the TestProxyRestClient. /// <seealso href="https://github.com/Azure/azure-sdk-tools/tree/main/tools/test-proxy"/> /// </summary> public class TestProxy { private static readonly string s_dotNetExe; // for some reason using localhost instead of the ip address causes slowness when combined with SSL callback being specified public const string IpAddress = "127.0.0.1"; public int? ProxyPortHttp => _proxyPortHttp; public int? ProxyPortHttps => _proxyPortHttps; private readonly int? _proxyPortHttp; private readonly int? _proxyPortHttps; private readonly Process _testProxyProcess; internal TestProxyRestClient Client { get; } private readonly StringBuilder _errorBuffer = new(); private static readonly object _lock = new(); private static TestProxy _shared; static TestProxy() { string installDir = Environment.GetEnvironmentVariable("DOTNET_INSTALL_DIR"); var dotNetExeName = "dotnet" + (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ".exe" : ""); if (!HasDotNetExe(installDir)) { installDir = Environment.GetEnvironmentVariable("PATH")?.Split(Path.PathSeparator).FirstOrDefault(HasDotNetExe); } if (installDir == null) { throw new InvalidOperationException("DOTNET install directory was not found"); } s_dotNetExe = Path.Combine(installDir, dotNetExeName); bool HasDotNetExe(string dotnetDir) => dotnetDir != null && File.Exists(Path.Combine(dotnetDir, dotNetExeName)); } private TestProxy(string proxyPath) { ProcessStartInfo testProxyProcessInfo = new ProcessStartInfo( s_dotNetExe, proxyPath) { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, EnvironmentVariables = { ["ASPNETCORE_URLS"] = $"http://{IpAddress}:0;https://{IpAddress}:0", ["Logging__LogLevel__Default"] = "Error", ["Logging__LogLevel__Microsoft.Hosting.Lifetime"] = "Information", ["ASPNETCORE_Kestrel__Certificates__Default__Path"] = TestEnvironment.DevCertPath, ["ASPNETCORE_Kestrel__Certificates__Default__Password"] = TestEnvironment.DevCertPassword } }; _testProxyProcess = Process.Start(testProxyProcessInfo); ProcessTracker.Add(_testProxyProcess); _ = Task.Run( () => { while (!_testProxyProcess.HasExited && !_testProxyProcess.StandardError.EndOfStream) { var error = _testProxyProcess.StandardError.ReadLine(); // output to console in case another error in the test causes the exception to not be propagated TestContext.Progress.WriteLine(error); _errorBuffer.AppendLine(error); } }); int lines = 0; while ((_proxyPortHttp == null || _proxyPortHttps == null) && lines++ < 50) { string outputLine = _testProxyProcess.StandardOutput.ReadLine(); // useful for debugging TestContext.Progress.WriteLine(outputLine); if (ProxyPortHttp == null && TryParsePort(outputLine, "http", out _proxyPortHttp)) { continue; } if (_proxyPortHttps == null && TryParsePort(outputLine, "https", out _proxyPortHttps)) { continue; } } if (_proxyPortHttp == null || _proxyPortHttps == null) { CheckForErrors(); // if no errors, fallback to this exception throw new InvalidOperationException("Failed to start the test proxy. One or both of the ports was not populated." + Environment.NewLine + $"http: {_proxyPortHttp}" + Environment.NewLine + $"https: {_proxyPortHttps}"); } var options = new TestProxyClientOptions(); Client = new TestProxyRestClient( new ClientDiagnostics(new TestProxyClientOptions()), HttpPipelineBuilder.Build(options), new Uri($"http://{IpAddress}:{_proxyPortHttp}")); // For some reason draining the standard output stream is necessary to keep the test-proxy process healthy. Otherwise requests // start timing out. This only seems to happen when not specifying a port. _ = Task.Run( () => { while (!_testProxyProcess.HasExited && !_testProxyProcess.StandardOutput.EndOfStream) { _testProxyProcess.StandardOutput.ReadLine(); } }); } public static TestProxy Start() { if (_shared != null) { return _shared; } lock (_lock) { var shared = _shared; if (shared == null) { shared = new TestProxy(typeof(TestProxy) .Assembly .GetCustomAttributes<AssemblyMetadataAttribute>() .Single(a => a.Key == "TestProxyPath") .Value); AppDomain.CurrentDomain.DomainUnload += (_, _) => { shared._testProxyProcess?.Kill(); }; _shared = shared; } return shared; } } private static bool TryParsePort(string output, string scheme, out int? port) { if (output == null) { TestContext.Progress.WriteLine("output was null"); port = null; return false; } string nowListeningOn = "Now listening on: "; int nowListeningOnLength = nowListeningOn.Length; var index = output.IndexOf($"{nowListeningOn}{scheme}:", StringComparison.CurrentCultureIgnoreCase); if (index > -1) { var start = index + nowListeningOnLength; var uri = output.Substring(start, output.Length - start).Trim(); port = new Uri(uri).Port; return true; } port = null; return false; } public void CheckForErrors() { if (_errorBuffer.Length > 0) { var error = _errorBuffer.ToString(); _errorBuffer.Clear(); throw new InvalidOperationException($"An error occurred in the test proxy: {error}"); } } } }
using System; using System.IO; using System.Reflection; using System.Text; using System.Linq; namespace SpecUnit.Report { public interface IReportGenerator { void WriteReport(Assembly assemblyUnderTest); } public class ReportGenerator : IReportGenerator { public virtual void WriteReport(Assembly assemblyUnderTest) { SpecificationDataset specificationDataset = SpecificationDataset.Build(assemblyUnderTest); string generatedReport = Render(specificationDataset); string reportFilePath = assemblyUnderTest.GetName().Name + ".html"; if (File.Exists(reportFilePath)) { File.Delete(reportFilePath); } TextWriter tw = new StreamWriter(reportFilePath); tw.Write(generatedReport); tw.Close(); } public static string Render(SpecificationDataset specificationDataset) { StringBuilder reportBuilder = new StringBuilder(); RenderTitle(specificationDataset, reportBuilder); RenderHR(reportBuilder); Concern[] concerns = (from c in specificationDataset.Concerns orderby c.Name select c).ToArray(); RenderConcerns(concerns, reportBuilder); string reportBody = reportBuilder.ToString(); return String.Format(GetTemplate(), specificationDataset.Name, reportBody); } private static void RenderTitle(SpecificationDataset specificationDataset, StringBuilder reportBuilder) { string concernsCaption = ConcernsCaption(specificationDataset.Concerns); string contextsCaption = ContextsCaption(specificationDataset.Concerns); string specificationsCaption = SpecificationsCaption(specificationDataset.Concerns); string title = String.Format("<h1>{0}&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"count\">{1}, {2}, {3}</span></h1>", specificationDataset.Name, concernsCaption, contextsCaption, specificationsCaption); reportBuilder.Append(title); } public static string RenderTitle(SpecificationDataset specificationDataset) { StringBuilder reportBuilder = new StringBuilder(); RenderTitle(specificationDataset, reportBuilder); return reportBuilder.ToString(); } private static void RenderConcerns(Concern[] concerns, StringBuilder reportBuilder) { foreach (Concern concern in concerns) { RenderConcern(concern, reportBuilder); } } private static void RenderConcern(Concern concern, StringBuilder reportBuilder) { string concernText = RenderConcern(concern); reportBuilder.Append(concernText); } public static string RenderConcern(Concern concern) { StringBuilder reportBuilder = new StringBuilder(); string concernHeader = RenderConcernHeader(concern); concernHeader = String.Format("{0}\n\n", concernHeader); reportBuilder.Append(concernHeader); RenderContexts(concern.Contexts, reportBuilder); RenderHR(reportBuilder); return reportBuilder.ToString(); } public static string RenderConcernHeader(Concern concern) { string contextsCaption = ContextsCaption(concern); string specificationsCaption = SpecificationsCaption(concern); return String.Format("<h2 class=\"concern\">{0} specifications&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"count\">{1}, {2}</span></h2>", concern.Name, contextsCaption, specificationsCaption); } private static void RenderContexts(Context[] contexts, StringBuilder reportBuilder) { foreach (Context context in contexts) { reportBuilder.Append(RenderContext(context)); } } public static string RenderContext(Context context) { StringBuilder reportBuilder = new StringBuilder(); reportBuilder.Append("\n"); string contextHeader = RenderContextHeader(context); reportBuilder.Append(contextHeader); string behavesLike = context.BehavesLike; if (behavesLike != null) { reportBuilder.Append(RenderBehavesLike(behavesLike)); reportBuilder.Append("\n\n"); } string specificationList = RenderSpecificationList(context.Specifications); reportBuilder.Append(specificationList); reportBuilder.Append("\n\n"); return reportBuilder.ToString(); } private static string RenderBehavesLike(string behavesLike) { return String.Format("<p class=\"behaves_like\">behaves like: {0}</p>", behavesLike); } public static string RenderContextHeader(Context context) { string specificationsCaption = SpecificationsCaption(context); return String.Format("<h3 class=\"context\">{0}&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"count\">{1}</span></h3>", context.Name, specificationsCaption); } public static string RenderSpecificationList(Specification[] specifications) { StringBuilder specificationListBuilder = new StringBuilder(); foreach (Specification specification in specifications) { string specificationListItem = String.Format("\t<li>{0}</li>\n", specification.Name); specificationListBuilder.Append(specificationListItem); } return String.Format("<ul>\n{0}</ul>", specificationListBuilder); } private static void RenderHR(StringBuilder reportBuilder) { string hr = "<hr>\n\n"; reportBuilder.Append(hr); } private static string GetTemplate() { string template = @"<html> <head> <title>Specification Report for {0}</title> <style type=""text/css""> body {{ font-family: Arial,Helvetica,sans-serif; font-size: .9em; }} .count {{ color: LightGrey; }} .behaves_like {{ color: DarkGrey; font-weight: bold; margin-left: 20px; margin-top: -10px; }} hr {{ color: LightGrey; border: 1px solid LightGrey; height: 1px; }} </style> </head> <body> {1} </body> </html>"; return template; } public static string Pluralize(string caption, int count) { if (count > 1 || count == 0) { caption += "s"; } return caption; } private static string ConcernsCaption(Concern[] concerns) { int concernsCount = concerns.Length; string concernsCaption = String.Format("{0} {1}", concernsCount, Pluralize("concern", concernsCount)); return concernsCaption; } private static string ContextsCaption(Concern[] concerns) { int contextCount = concerns.Sum(c => c.Contexts.Length); return ContextsCaption(contextCount); } private static string ContextsCaption(Concern concern) { int contextCount = concern.Contexts.Length; return ContextsCaption(contextCount); } private static string ContextsCaption(int contextCount) { string contextCaption = String.Format("{0} {1}", contextCount, Pluralize("context", contextCount)); return contextCaption; } private static string SpecificationsCaption(int specificationCount) { string specificationCaption = String.Format("{0} {1}", specificationCount, Pluralize("specification", specificationCount)); return specificationCaption; } private static string SpecificationsCaption(Concern[] concerns) { int specificationCount = concerns.Sum(c => c.Contexts.Sum(ctx => ctx.Specifications.Length)); return SpecificationsCaption(specificationCount); } private static string SpecificationsCaption(Concern concern) { int specificationCount = concern.Contexts.Sum(c => c.Specifications.Length); return SpecificationsCaption(specificationCount); } private static string SpecificationsCaption(Context context) { int specificationCount = context.Specifications.Length; return SpecificationsCaption(specificationCount); } } }
namespace Epi.Data.SqlServer.Forms { partial class ConnectionStringDialog { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ConnectionStringDialog)); this.lblInstructions = new System.Windows.Forms.Label(); this.lblServerName = new System.Windows.Forms.Label(); this.groupBoxAuthentication = new System.Windows.Forms.GroupBox(); this.rdbSqlAuthentication = new System.Windows.Forms.RadioButton(); this.rdbWindowsAuthentication = new System.Windows.Forms.RadioButton(); this.lblPassword = new System.Windows.Forms.Label(); this.txtPassword = new System.Windows.Forms.TextBox(); this.txtUserName = new System.Windows.Forms.TextBox(); this.lblUserName = new System.Windows.Forms.Label(); this.btnOK = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.lblDatabaseName = new System.Windows.Forms.Label(); this.cmbServerName = new System.Windows.Forms.ComboBox(); this.btnTest = new System.Windows.Forms.Button(); this.cmbDatabaseName = new System.Windows.Forms.ComboBox(); this.groupBoxAuthentication.SuspendLayout(); this.SuspendLayout(); // // lblInstructions // resources.ApplyResources(this.lblInstructions, "lblInstructions"); this.lblInstructions.Name = "lblInstructions"; // // lblServerName // resources.ApplyResources(this.lblServerName, "lblServerName"); this.lblServerName.Name = "lblServerName"; // // groupBoxAuthentication // this.groupBoxAuthentication.Controls.Add(this.rdbSqlAuthentication); this.groupBoxAuthentication.Controls.Add(this.rdbWindowsAuthentication); this.groupBoxAuthentication.Controls.Add(this.lblPassword); this.groupBoxAuthentication.Controls.Add(this.txtPassword); this.groupBoxAuthentication.Controls.Add(this.txtUserName); this.groupBoxAuthentication.Controls.Add(this.lblUserName); resources.ApplyResources(this.groupBoxAuthentication, "groupBoxAuthentication"); this.groupBoxAuthentication.Name = "groupBoxAuthentication"; this.groupBoxAuthentication.TabStop = false; // // rdbSqlAuthentication // resources.ApplyResources(this.rdbSqlAuthentication, "rdbSqlAuthentication"); this.rdbSqlAuthentication.Name = "rdbSqlAuthentication"; this.rdbSqlAuthentication.UseVisualStyleBackColor = true; this.rdbSqlAuthentication.CheckedChanged += new System.EventHandler(this.rdbAuthentication_CheckedChanged); // // rdbWindowsAuthentication // resources.ApplyResources(this.rdbWindowsAuthentication, "rdbWindowsAuthentication"); this.rdbWindowsAuthentication.Checked = true; this.rdbWindowsAuthentication.Name = "rdbWindowsAuthentication"; this.rdbWindowsAuthentication.TabStop = true; this.rdbWindowsAuthentication.UseVisualStyleBackColor = true; this.rdbWindowsAuthentication.CheckedChanged += new System.EventHandler(this.rdbAuthentication_CheckedChanged); // // lblPassword // resources.ApplyResources(this.lblPassword, "lblPassword"); this.lblPassword.Name = "lblPassword"; // // txtPassword // resources.ApplyResources(this.txtPassword, "txtPassword"); this.txtPassword.Name = "txtPassword"; this.txtPassword.UseSystemPasswordChar = true; // // txtUserName // resources.ApplyResources(this.txtUserName, "txtUserName"); this.txtUserName.Name = "txtUserName"; // // lblUserName // resources.ApplyResources(this.lblUserName, "lblUserName"); this.lblUserName.Name = "lblUserName"; // // btnOK // resources.ApplyResources(this.btnOK, "btnOK"); this.btnOK.Name = "btnOK"; this.btnOK.UseVisualStyleBackColor = true; this.btnOK.Click += new System.EventHandler(this.btnOK_Click); // // btnCancel // resources.ApplyResources(this.btnCancel, "btnCancel"); this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.Name = "btnCancel"; this.btnCancel.UseVisualStyleBackColor = true; this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // lblDatabaseName // resources.ApplyResources(this.lblDatabaseName, "lblDatabaseName"); this.lblDatabaseName.Name = "lblDatabaseName"; // // cmbServerName // this.cmbServerName.FormattingEnabled = true; resources.ApplyResources(this.cmbServerName, "cmbServerName"); this.cmbServerName.Name = "cmbServerName"; this.cmbServerName.SelectedIndexChanged += new System.EventHandler(this.cmbServerName_SelectedIndexChanged); // // btnTest // resources.ApplyResources(this.btnTest, "btnTest"); this.btnTest.Name = "btnTest"; this.btnTest.UseVisualStyleBackColor = true; this.btnTest.Click += new System.EventHandler(this.btnTest_Click); // // cmbDatabaseName // this.cmbDatabaseName.FormattingEnabled = true; resources.ApplyResources(this.cmbDatabaseName, "cmbDatabaseName"); this.cmbDatabaseName.Name = "cmbDatabaseName"; this.cmbDatabaseName.SelectedIndexChanged += new System.EventHandler(this.cmbDatabaseName_SelectedIndexChanged); // // ConnectionStringDialog // this.AcceptButton = this.btnOK; resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.btnCancel; this.Controls.Add(this.cmbDatabaseName); this.Controls.Add(this.btnTest); this.Controls.Add(this.cmbServerName); this.Controls.Add(this.lblDatabaseName); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnOK); this.Controls.Add(this.groupBoxAuthentication); this.Controls.Add(this.lblServerName); this.Controls.Add(this.lblInstructions); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "ConnectionStringDialog"; this.ShowIcon = false; this.groupBoxAuthentication.ResumeLayout(false); this.groupBoxAuthentication.PerformLayout(); this.ResumeLayout(false); } #endregion /// <summary> /// Control exposed to derived class for UI inheritance /// </summary> protected System.Windows.Forms.Label lblInstructions; /// <summary> /// Control exposed to derived class for UI inheritance /// </summary> protected System.Windows.Forms.Label lblServerName; /// <summary> /// Control exposed to derived class for UI inheritance /// </summary> protected System.Windows.Forms.GroupBox groupBoxAuthentication; /// <summary> /// Control exposed to derived class for UI inheritance /// </summary> protected System.Windows.Forms.Label lblUserName; /// <summary> /// Control exposed to derived class for UI inheritance /// </summary> protected System.Windows.Forms.Label lblPassword; /// <summary> /// Control exposed to derived class for UI inheritance /// </summary> protected System.Windows.Forms.TextBox txtPassword; /// <summary> /// Control exposed to derived class for UI inheritance /// </summary> protected System.Windows.Forms.TextBox txtUserName; /// <summary> /// Control exposed to derived class for UI inheritance /// </summary> protected System.Windows.Forms.Button btnOK; /// <summary> /// Control exposed to derived class for UI inheritance /// </summary> protected System.Windows.Forms.Button btnCancel; /// <summary> /// Control exposed to derived class for UI inheritance /// </summary> protected System.Windows.Forms.RadioButton rdbSqlAuthentication; /// <summary> /// Control exposed to derived class for UI inheritance /// </summary> protected System.Windows.Forms.RadioButton rdbWindowsAuthentication; /// <summary> /// Control exposed to derived class for UI inheritance /// </summary> protected System.Windows.Forms.Label lblDatabaseName; /// <summary> /// Control exposed to derived class for UI inheritance /// </summary> protected System.Windows.Forms.ComboBox cmbServerName; /// <summary> /// Control exposed to derived class for UI inheritance /// </summary> protected System.Windows.Forms.Button btnTest; /// <summary> /// Control exposed to derived class for UI inheritance /// </summary> protected System.Windows.Forms.ComboBox cmbDatabaseName; } }
//------------------------------------------------------------------------------- // <copyright file="StateMachineTest.cs" company="Appccelerate"> // Copyright (c) 2008-2019 Appccelerate // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> //------------------------------------------------------------------------------- namespace Appccelerate.StateMachine.Facts.Machine { using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using FluentAssertions; using StateMachine.Infrastructure; using StateMachine.Machine; using Xunit; /// <summary> /// Tests state machine initialization and state switching. /// </summary> public class StateMachineTest { private readonly IStateDefinitionDictionary<States, Events> stateDefinitions; /// <summary> /// The list of recorded actions. /// </summary> private readonly List<Record> records = new List<Record>(); /// <summary> /// Initializes a new instance of the <see cref="StateMachineTest"/> class. /// </summary> public StateMachineTest() { var stateDefinitionBuilder = new StateDefinitionsBuilder<States, Events>(); stateDefinitionBuilder .DefineHierarchyOn(States.B) .WithHistoryType(HistoryType.None) .WithInitialSubState(States.B1) .WithSubState(States.B2); stateDefinitionBuilder .DefineHierarchyOn(States.C) .WithHistoryType(HistoryType.Shallow) .WithInitialSubState(States.C2) .WithSubState(States.C1); stateDefinitionBuilder .DefineHierarchyOn(States.C1) .WithHistoryType(HistoryType.Shallow) .WithInitialSubState(States.C1A) .WithSubState(States.C1B); stateDefinitionBuilder .DefineHierarchyOn(States.D) .WithHistoryType(HistoryType.Deep) .WithInitialSubState(States.D1) .WithSubState(States.D2); stateDefinitionBuilder .DefineHierarchyOn(States.D1) .WithHistoryType(HistoryType.Deep) .WithInitialSubState(States.D1A) .WithSubState(States.D1B); stateDefinitionBuilder .In(States.A) .ExecuteOnEntry(() => this.RecordEntry(States.A)) .ExecuteOnExit(() => this.RecordExit(States.A)) .On(Events.B).Goto(States.B) .On(Events.C).Goto(States.C) .On(Events.D).Goto(States.D) .On(Events.A); stateDefinitionBuilder .In(States.B) .ExecuteOnEntry(() => this.RecordEntry(States.B)) .ExecuteOnExit(() => this.RecordExit(States.B)) .On(Events.D).Goto(States.D); stateDefinitionBuilder .In(States.B1) .ExecuteOnEntry(() => this.RecordEntry(States.B1)) .ExecuteOnExit(() => this.RecordExit(States.B1)) .On(Events.B2).Goto(States.B2); stateDefinitionBuilder .In(States.B2) .ExecuteOnEntry(() => this.RecordEntry(States.B2)) .ExecuteOnExit(() => this.RecordExit(States.B2)) .On(Events.A).Goto(States.A) .On(Events.C1B).Goto(States.C1B); stateDefinitionBuilder .In(States.C) .ExecuteOnEntry(() => this.RecordEntry(States.C)) .ExecuteOnExit(() => this.RecordExit(States.C)) .On(Events.A).Goto(States.A); stateDefinitionBuilder .In(States.C1) .ExecuteOnEntry(() => this.RecordEntry(States.C1)) .ExecuteOnExit(() => this.RecordExit(States.C1)) .On(Events.C1B).Goto(States.C1B); stateDefinitionBuilder .In(States.C2) .ExecuteOnEntry(() => this.RecordEntry(States.C2)) .ExecuteOnExit(() => this.RecordExit(States.C2)); stateDefinitionBuilder .In(States.C1A) .ExecuteOnEntry(() => this.RecordEntry(States.C1A)) .ExecuteOnExit(() => this.RecordExit(States.C1A)); stateDefinitionBuilder .In(States.C1B) .ExecuteOnEntry(() => this.RecordEntry(States.C1B)) .ExecuteOnExit(() => this.RecordExit(States.C1B)); stateDefinitionBuilder .In(States.D) .ExecuteOnEntry(() => this.RecordEntry(States.D)) .ExecuteOnExit(() => this.RecordExit(States.D)); stateDefinitionBuilder .In(States.D1) .ExecuteOnEntry(() => this.RecordEntry(States.D1)) .ExecuteOnExit(() => this.RecordExit(States.D1)); stateDefinitionBuilder .In(States.D1A) .ExecuteOnEntry(() => this.RecordEntry(States.D1A)) .ExecuteOnExit(() => this.RecordExit(States.D1A)); stateDefinitionBuilder .In(States.D1B) .ExecuteOnEntry(() => this.RecordEntry(States.D1B)) .ExecuteOnExit(() => this.RecordExit(States.D1B)) .On(Events.A).Goto(States.A) .On(Events.B1).Goto(States.B1); stateDefinitionBuilder .In(States.D2) .ExecuteOnEntry(() => this.RecordEntry(States.D2)) .ExecuteOnExit(() => this.RecordExit(States.D2)) .On(Events.A).Goto(States.A); stateDefinitionBuilder .In(States.E) .ExecuteOnEntry(() => this.RecordEntry(States.E)) .ExecuteOnExit(() => this.RecordExit(States.E)) .On(Events.A).Goto(States.A) .On(Events.E).Goto(States.E); this.stateDefinitions = stateDefinitionBuilder.Build(); } [Fact] public void CurrentStateShouldBeUninitializedWhenInitialStateWasNotYetEntered() { var stateContainer = new StateContainer<States, Events>(); new StateMachineBuilder<States, Events>() .WithStateContainer(stateContainer) .Build(); stateContainer .CurrentStateId .Should() .Match<Initializable<States>>(x => x.IsInitialized == false); this.CheckNoRemainingRecords(); } /// <summary> /// After initialization the state machine is in the initial state and the initial state is entered. /// </summary> [Fact] public void InitializeToTopLevelState() { var stateContainer = new StateContainer<States, Events>(); var testee = new StateMachineBuilder<States, Events>() .WithStateContainer(stateContainer) .Build(); testee.EnterInitialState(stateContainer, this.stateDefinitions, States.A); stateContainer .CurrentStateId .Should() .BeEquivalentTo(Initializable<States>.Initialized(States.A)); this.CheckRecord<EntryRecord>(States.A); this.CheckNoRemainingRecords(); } /// <summary> /// After initialization the state machine is in the initial state and the initial state is entered. /// All states up in the hierarchy of the initial state are entered, too. /// </summary> [Fact] public void InitializeToNestedState() { var stateContainer = new StateContainer<States, Events>(); var testee = new StateMachineBuilder<States, Events>() .WithStateContainer(stateContainer) .Build(); testee.EnterInitialState(stateContainer, this.stateDefinitions, States.D1B); stateContainer .CurrentStateId .Should() .BeEquivalentTo(Initializable<States>.Initialized(States.D1B)); this.CheckRecord<EntryRecord>(States.D); this.CheckRecord<EntryRecord>(States.D1); this.CheckRecord<EntryRecord>(States.D1B); this.CheckNoRemainingRecords(); } /// <summary> /// When the state machine is initializes to a state with sub-states then the hierarchy is recursively /// traversed to the most nested state along the chain of initial states. /// </summary> [Fact] public void InitializeStateWithSubStates() { var stateContainer = new StateContainer<States, Events>(); var testee = new StateMachineBuilder<States, Events>() .WithStateContainer(stateContainer) .Build(); stateContainer.SetLastActiveStateFor(States.D, States.D1); stateContainer.SetLastActiveStateFor(States.D1, States.D1A); testee.EnterInitialState(stateContainer, this.stateDefinitions, States.D); stateContainer .CurrentStateId .Should() .BeEquivalentTo(Initializable<States>.Initialized(States.D1A)); this.CheckRecord<EntryRecord>(States.D); this.CheckRecord<EntryRecord>(States.D1); this.CheckRecord<EntryRecord>(States.D1A); this.CheckNoRemainingRecords(); } /// <summary> /// When a transition between two states at the top level then the /// exit action of the source state is executed, then the action is performed /// and the entry action of the target state is executed. /// Finally, the current state is the target state. /// </summary> [Fact] public void ExecuteTransition() { var stateContainer = new StateContainer<States, Events>(); var testee = new StateMachineBuilder<States, Events>() .WithStateContainer(stateContainer) .Build(); testee.EnterInitialState(stateContainer, this.stateDefinitions, States.E); this.ClearRecords(); testee.Fire(Events.A, stateContainer, stateContainer, this.stateDefinitions); stateContainer .CurrentStateId .Should() .BeEquivalentTo(Initializable<States>.Initialized(States.A)); this.CheckRecord<ExitRecord>(States.E); this.CheckRecord<EntryRecord>(States.A); this.CheckNoRemainingRecords(); } /// <summary> /// When a transition between two states with the same super state is executed then /// the exit action of source state, the transition action and the entry action of /// the target state are executed. /// </summary> [Fact] public void ExecuteTransitionBetweenStatesWithSameSuperState() { var stateContainer = new StateContainer<States, Events>(); var testee = new StateMachineBuilder<States, Events>() .WithStateContainer(stateContainer) .Build(); testee.EnterInitialState(stateContainer, this.stateDefinitions, States.B1); this.ClearRecords(); testee.Fire(Events.B2, stateContainer, stateContainer, this.stateDefinitions); stateContainer .CurrentStateId .Should() .BeEquivalentTo(Initializable<States>.Initialized(States.B2)); this.CheckRecord<ExitRecord>(States.B1); this.CheckRecord<EntryRecord>(States.B2); this.CheckNoRemainingRecords(); } /// <summary> /// When a transition between two states in different super states on different levels is executed /// then all states from the source up to the common super-state are exited and all states down to /// the target state are entered. In this case the target state is lower than the source state. /// </summary> [Fact] public void ExecuteTransitionBetweenStatesOnDifferentLevelsDownwards() { var stateContainer = new StateContainer<States, Events>(); var testee = new StateMachineBuilder<States, Events>() .WithStateContainer(stateContainer) .Build(); testee.EnterInitialState(stateContainer, this.stateDefinitions, States.B2); this.ClearRecords(); testee.Fire(Events.C1B, stateContainer, stateContainer, this.stateDefinitions); stateContainer .CurrentStateId .Should() .BeEquivalentTo(Initializable<States>.Initialized(States.C1B)); this.CheckRecord<ExitRecord>(States.B2); this.CheckRecord<ExitRecord>(States.B); this.CheckRecord<EntryRecord>(States.C); this.CheckRecord<EntryRecord>(States.C1); this.CheckRecord<EntryRecord>(States.C1B); this.CheckNoRemainingRecords(); } /// <summary> /// When a transition between two states in different super states on different levels is executed /// then all states from the source up to the common super-state are exited and all states down to /// the target state are entered. In this case the target state is higher than the source state. /// </summary> [Fact] public void ExecuteTransitionBetweenStatesOnDifferentLevelsUpwards() { var stateContainer = new StateContainer<States, Events>(); var testee = new StateMachineBuilder<States, Events>() .WithStateContainer(stateContainer) .Build(); testee.EnterInitialState(stateContainer, this.stateDefinitions, States.D1B); this.ClearRecords(); testee.Fire(Events.B1, stateContainer, stateContainer, this.stateDefinitions); stateContainer .CurrentStateId .Should() .BeEquivalentTo(Initializable<States>.Initialized(States.B1)); this.CheckRecord<ExitRecord>(States.D1B); this.CheckRecord<ExitRecord>(States.D1); this.CheckRecord<ExitRecord>(States.D); this.CheckRecord<EntryRecord>(States.B); this.CheckRecord<EntryRecord>(States.B1); this.CheckNoRemainingRecords(); } /// <summary> /// When a transition targets a super-state then the initial-state of this super-state is entered recursively /// down to the most nested state. /// No history here. /// </summary> [Fact] public void ExecuteTransitionWithInitialSubState() { var stateContainer = new StateContainer<States, Events>(); var testee = new StateMachineBuilder<States, Events>() .WithStateContainer(stateContainer) .Build(); testee.EnterInitialState(stateContainer, this.stateDefinitions, States.A); this.ClearRecords(); testee.Fire(Events.B, stateContainer, stateContainer, this.stateDefinitions); stateContainer .CurrentStateId .Should() .BeEquivalentTo(Initializable<States>.Initialized(States.B1)); this.CheckRecord<ExitRecord>(States.A); this.CheckRecord<EntryRecord>(States.B); this.CheckRecord<EntryRecord>(States.B1); this.CheckNoRemainingRecords(); } /// <summary> /// When a transition targets a super-state with <see cref="HistoryType.None"/> then the initial /// sub-state is entered whatever sub.state was last active. /// </summary> [Fact] public void ExecuteTransitionWithHistoryTypeNone() { var stateContainer = new StateContainer<States, Events>(); var testee = new StateMachineBuilder<States, Events>() .WithStateContainer(stateContainer) .Build(); testee.EnterInitialState(stateContainer, this.stateDefinitions, States.B2); testee.Fire(Events.A, stateContainer, stateContainer, this.stateDefinitions); this.ClearRecords(); testee.Fire(Events.B, stateContainer, stateContainer, this.stateDefinitions); this.CheckRecord<ExitRecord>(States.A); this.CheckRecord<EntryRecord>(States.B); this.CheckRecord<EntryRecord>(States.B1); this.CheckNoRemainingRecords(); } /// <summary> /// When a transition targets a super-state with <see cref="HistoryType.Shallow"/> then the last /// active sub-state is entered and the initial-state of the entered sub-state is entered (no recursive history). /// </summary> [Fact] public void ExecuteTransitionWithHistoryTypeShallow() { var stateContainer = new StateContainer<States, Events>(); var testee = new StateMachineBuilder<States, Events>() .WithStateContainer(stateContainer) .Build(); testee.EnterInitialState(stateContainer, this.stateDefinitions, States.C1B); testee.Fire(Events.A, stateContainer, stateContainer, this.stateDefinitions); this.ClearRecords(); testee.Fire(Events.C, stateContainer, stateContainer, this.stateDefinitions); stateContainer .CurrentStateId .Should() .BeEquivalentTo(Initializable<States>.Initialized(States.C1A)); this.CheckRecord<ExitRecord>(States.A); this.CheckRecord<EntryRecord>(States.C); this.CheckRecord<EntryRecord>(States.C1); this.CheckRecord<EntryRecord>(States.C1A); this.CheckNoRemainingRecords(); } /// <summary> /// When a transition targets a super-state with <see cref="HistoryType.Deep"/> then the last /// active sub-state is entered recursively down to the most nested state. /// </summary> [Fact] public void ExecuteTransitionWithHistoryTypeDeep() { var stateContainer = new StateContainer<States, Events>(); var testee = new StateMachineBuilder<States, Events>() .WithStateContainer(stateContainer) .Build(); testee.EnterInitialState(stateContainer, this.stateDefinitions, States.D1B); testee.Fire(Events.A, stateContainer, stateContainer, this.stateDefinitions); this.ClearRecords(); testee.Fire(Events.D, stateContainer, stateContainer, this.stateDefinitions); stateContainer .CurrentStateId .Should() .BeEquivalentTo(Initializable<States>.Initialized(States.D1B)); this.CheckRecord<ExitRecord>(States.A); this.CheckRecord<EntryRecord>(States.D); this.CheckRecord<EntryRecord>(States.D1); this.CheckRecord<EntryRecord>(States.D1B); this.CheckNoRemainingRecords(); } /// <summary> /// The state hierarchy is recursively walked up until a state can handle the event. /// </summary> [Fact] public void ExecuteTransitionHandledBySuperState() { var stateContainer = new StateContainer<States, Events>(); var testee = new StateMachineBuilder<States, Events>() .WithStateContainer(stateContainer) .Build(); testee.EnterInitialState(stateContainer, this.stateDefinitions, States.C1B); this.ClearRecords(); testee.Fire(Events.A, stateContainer, stateContainer, this.stateDefinitions); stateContainer .CurrentStateId .Should() .BeEquivalentTo(Initializable<States>.Initialized(States.A)); this.CheckRecord<ExitRecord>(States.C1B); this.CheckRecord<ExitRecord>(States.C1); this.CheckRecord<ExitRecord>(States.C); this.CheckRecord<EntryRecord>(States.A); this.CheckNoRemainingRecords(); } /// <summary> /// Internal transitions do not trigger any exit or entry actions and the state machine remains in the same state. /// </summary> [Fact] public void InternalTransition() { var stateContainer = new StateContainer<States, Events>(); var testee = new StateMachineBuilder<States, Events>() .WithStateContainer(stateContainer) .Build(); testee.EnterInitialState(stateContainer, this.stateDefinitions, States.A); this.ClearRecords(); testee.Fire(Events.A, stateContainer, stateContainer, this.stateDefinitions); stateContainer .CurrentStateId .Should() .BeEquivalentTo(Initializable<States>.Initialized(States.A)); } [Fact] public void ExecuteSelfTransition() { var stateContainer = new StateContainer<States, Events>(); var testee = new StateMachineBuilder<States, Events>() .WithStateContainer(stateContainer) .Build(); testee.EnterInitialState(stateContainer, this.stateDefinitions, States.E); this.ClearRecords(); testee.Fire(Events.E, stateContainer, stateContainer, this.stateDefinitions); stateContainer .CurrentStateId .Should() .BeEquivalentTo(Initializable<States>.Initialized(States.E)); this.CheckRecord<ExitRecord>(States.E); this.CheckRecord<EntryRecord>(States.E); this.CheckNoRemainingRecords(); } [Fact] public void ExecuteTransitionToNephew() { var stateContainer = new StateContainer<States, Events>(); var testee = new StateMachineBuilder<States, Events>() .WithStateContainer(stateContainer) .Build(); testee.EnterInitialState(stateContainer, this.stateDefinitions, States.C1A); this.ClearRecords(); testee.Fire(Events.C1B, stateContainer, stateContainer, this.stateDefinitions); stateContainer .CurrentStateId .Should() .BeEquivalentTo(Initializable<States>.Initialized(States.C1B)); this.CheckRecord<ExitRecord>(States.C1A); this.CheckRecord<EntryRecord>(States.C1B); this.CheckNoRemainingRecords(); } /// <summary> /// Records the entry into a state. /// </summary> /// <param name="state">The state.</param> private void RecordEntry(States state) { this.records.Add(new EntryRecord { State = state }); } /// <summary> /// Records the exit out of a state. /// </summary> /// <param name="state">The state.</param> private void RecordExit(States state) { this.records.Add(new ExitRecord { State = state }); } /// <summary> /// Clears the records. /// </summary> private void ClearRecords() { this.records.Clear(); } /// <summary> /// Checks that the first record in the list of records is of type <typeparamref name="T"/> and involves the specified state. /// The record is removed after the check. /// </summary> /// <typeparam name="T">Type of the record.</typeparam> /// <param name="state">The state.</param> private void CheckRecord<T>(States state) where T : Record { Record record = this.records.FirstOrDefault(); record.Should().NotBeNull(); record.Should().BeAssignableTo<T>(); //// ReSharper disable once PossibleNullReferenceException record.State.Should().Be(state, record.Message); this.records.RemoveAt(0); } /// <summary> /// Checks that no remaining records are present. /// </summary> private void CheckNoRemainingRecords() { if (this.records.Count == 0) { return; } var sb = new StringBuilder("there are additional records:"); foreach (var s in from record in this.records select record.GetType().Name + "-" + record.State) { sb.AppendLine(); sb.Append(s); } this.records.Should().BeEmpty(sb.ToString()); } /// <summary> /// A record of something that happened. /// </summary> [DebuggerDisplay("Message = {Message}")] private abstract class Record { /// <summary> /// Gets or sets the state. /// </summary> /// <value>The state.</value> public States State { get; set; } /// <summary> /// Gets the message. /// </summary> /// <value>The message.</value> public abstract string Message { get; } } /// <summary> /// Record of a state entry. /// </summary> private class EntryRecord : Record { /// <summary> /// Gets the message. /// </summary> /// <value>The message.</value> public override string Message => "State " + this.State + " not entered."; } /// <summary> /// Record of a state exit. /// </summary> private class ExitRecord : Record { /// <summary> /// Gets the message. /// </summary> /// <value>The message.</value> public override string Message => "State " + this.State + " not exited."; } } }
#region Copyright //////////////////////////////////////////////////////////////////////////////// // The following FIT Protocol software provided may be used with FIT protocol // devices only and remains the copyrighted property of Dynastream Innovations Inc. // The software is being provided on an "as-is" basis and as an accommodation, // and therefore all warranties, representations, or guarantees of any kind // (whether express, implied or statutory) including, without limitation, // warranties of merchantability, non-infringement, or fitness for a particular // purpose, are specifically disclaimed. // // Copyright 2015 Dynastream Innovations Inc. //////////////////////////////////////////////////////////////////////////////// // ****WARNING**** This file is auto-generated! Do NOT edit this file. // Profile Version = 16.10Release // Tag = development-akw-16.10.00-0 //////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.IO; namespace FickleFrostbite.FIT { /// <summary> /// Implements the MonitoringInfo profile message. /// </summary> public class MonitoringInfoMesg : Mesg { #region Fields #endregion #region Constructors public MonitoringInfoMesg() : base(Profile.mesgs[Profile.MonitoringInfoIndex]) { } public MonitoringInfoMesg(Mesg mesg) : base(mesg) { } #endregion // Constructors #region Methods ///<summary> /// Retrieves the Timestamp field /// Units: s</summary> /// <returns>Returns DateTime representing the Timestamp field</returns> public DateTime GetTimestamp() { return TimestampToDateTime((uint?)GetFieldValue(253, 0, Fit.SubfieldIndexMainField)); } /// <summary> /// Set Timestamp field /// Units: s</summary> /// <param name="timestamp_">Nullable field value to be set</param> public void SetTimestamp(DateTime timestamp_) { SetFieldValue(253, 0, timestamp_.GetTimeStamp(), Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the LocalTimestamp field /// Units: s /// Comment: Use to convert activity timestamps to local time if device does not support time zone and daylight savings time correction.</summary> /// <returns>Returns nullable uint representing the LocalTimestamp field</returns> public uint? GetLocalTimestamp() { return (uint?)GetFieldValue(0, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set LocalTimestamp field /// Units: s /// Comment: Use to convert activity timestamps to local time if device does not support time zone and daylight savings time correction.</summary> /// <param name="localTimestamp_">Nullable field value to be set</param> public void SetLocalTimestamp(uint? localTimestamp_) { SetFieldValue(0, 0, localTimestamp_, Fit.SubfieldIndexMainField); } /// <summary> /// /// </summary> /// <returns>returns number of elements in field ActivityType</returns> public int GetNumActivityType() { return GetNumFieldValues(1, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the ActivityType field</summary> /// <param name="index">0 based index of ActivityType element to retrieve</param> /// <returns>Returns nullable ActivityType enum representing the ActivityType field</returns> public ActivityType? GetActivityType(int index) { object obj = GetFieldValue(1, index, Fit.SubfieldIndexMainField); ActivityType? value = obj == null ? (ActivityType?)null : (ActivityType)obj; return value; } /// <summary> /// Set ActivityType field</summary> /// <param name="index">0 based index of activity_type</param> /// <param name="activityType_">Nullable field value to be set</param> public void SetActivityType(int index, ActivityType? activityType_) { SetFieldValue(1, index, activityType_, Fit.SubfieldIndexMainField); } /// <summary> /// /// </summary> /// <returns>returns number of elements in field CyclesToDistance</returns> public int GetNumCyclesToDistance() { return GetNumFieldValues(3, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the CyclesToDistance field /// Units: m/cycle /// Comment: Indexed by activity_type</summary> /// <param name="index">0 based index of CyclesToDistance element to retrieve</param> /// <returns>Returns nullable float representing the CyclesToDistance field</returns> public float? GetCyclesToDistance(int index) { return (float?)GetFieldValue(3, index, Fit.SubfieldIndexMainField); } /// <summary> /// Set CyclesToDistance field /// Units: m/cycle /// Comment: Indexed by activity_type</summary> /// <param name="index">0 based index of cycles_to_distance</param> /// <param name="cyclesToDistance_">Nullable field value to be set</param> public void SetCyclesToDistance(int index, float? cyclesToDistance_) { SetFieldValue(3, index, cyclesToDistance_, Fit.SubfieldIndexMainField); } /// <summary> /// /// </summary> /// <returns>returns number of elements in field CyclesToCalories</returns> public int GetNumCyclesToCalories() { return GetNumFieldValues(4, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the CyclesToCalories field /// Units: kcal/cycle /// Comment: Indexed by activity_type</summary> /// <param name="index">0 based index of CyclesToCalories element to retrieve</param> /// <returns>Returns nullable float representing the CyclesToCalories field</returns> public float? GetCyclesToCalories(int index) { return (float?)GetFieldValue(4, index, Fit.SubfieldIndexMainField); } /// <summary> /// Set CyclesToCalories field /// Units: kcal/cycle /// Comment: Indexed by activity_type</summary> /// <param name="index">0 based index of cycles_to_calories</param> /// <param name="cyclesToCalories_">Nullable field value to be set</param> public void SetCyclesToCalories(int index, float? cyclesToCalories_) { SetFieldValue(4, index, cyclesToCalories_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the RestingMetabolicRate field /// Units: kcal / day</summary> /// <returns>Returns nullable ushort representing the RestingMetabolicRate field</returns> public ushort? GetRestingMetabolicRate() { return (ushort?)GetFieldValue(5, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set RestingMetabolicRate field /// Units: kcal / day</summary> /// <param name="restingMetabolicRate_">Nullable field value to be set</param> public void SetRestingMetabolicRate(ushort? restingMetabolicRate_) { SetFieldValue(5, 0, restingMetabolicRate_, Fit.SubfieldIndexMainField); } #endregion // Methods } // Class } // namespace
namespace StockSharp.Algo.Storages.Binary { using System; using System.Collections.Generic; using System.IO; using System.Linq; using Ecng.Collections; using Ecng.Common; using StockSharp.Localization; using StockSharp.Messages; class PositionMetaInfo : BinaryMetaInfo { public PositionMetaInfo(DateTime date) : base(date) { BeginValue = new RefPair<decimal, decimal>(); CurrentValue = new RefPair<decimal, decimal>(); BlockedValue = new RefPair<decimal, decimal>(); CurrentPrice = new RefPair<decimal, decimal>(); AveragePrice = new RefPair<decimal, decimal>(); UnrealizedPnL = new RefPair<decimal, decimal>(); RealizedPnL = new RefPair<decimal, decimal>(); VariationMargin = new RefPair<decimal, decimal>(); Leverage = new RefPair<decimal, decimal>(); Commission = new RefPair<decimal, decimal>(); CurrentValueInLots = new RefPair<decimal, decimal>(); SettlementPrice = new RefPair<decimal, decimal>(); Portfolios = new List<string>(); ClientCodes = new List<string>(); DepoNames = new List<string>(); } public RefPair<decimal, decimal> BeginValue { get; private set; } public RefPair<decimal, decimal> CurrentValue { get; private set; } public RefPair<decimal, decimal> BlockedValue { get; private set; } public RefPair<decimal, decimal> CurrentPrice { get; private set; } public RefPair<decimal, decimal> AveragePrice { get; private set; } public RefPair<decimal, decimal> UnrealizedPnL { get; private set; } public RefPair<decimal, decimal> RealizedPnL { get; private set; } public RefPair<decimal, decimal> VariationMargin { get; private set; } public RefPair<decimal, decimal> Leverage { get; private set; } public RefPair<decimal, decimal> Commission { get; private set; } public RefPair<decimal, decimal> CurrentValueInLots { get; private set; } public RefPair<decimal, decimal> SettlementPrice { get; private set; } public IList<string> Portfolios { get; } public IList<string> ClientCodes { get; } public IList<string> DepoNames { get; } public DateTime FirstFieldTime { get; set; } public DateTime LastFieldTime { get; set; } public override void Write(Stream stream) { base.Write(stream); Write(stream, BeginValue); Write(stream, CurrentValue); Write(stream, BlockedValue); Write(stream, CurrentPrice); Write(stream, AveragePrice); Write(stream, UnrealizedPnL); Write(stream, RealizedPnL); Write(stream, VariationMargin); Write(stream, Leverage); Write(stream, Commission); Write(stream, CurrentValueInLots); stream.WriteEx(Portfolios.Count); foreach (var portfolio in Portfolios) stream.WriteEx(portfolio); stream.WriteEx(ClientCodes.Count); foreach (var clientCode in ClientCodes) stream.WriteEx(clientCode); stream.WriteEx(DepoNames.Count); foreach (var depoName in DepoNames) stream.WriteEx(depoName); if (Version < MarketDataVersions.Version33) return; Write(stream, SettlementPrice); } public override void Read(Stream stream) { base.Read(stream); BeginValue = ReadInfo(stream); CurrentValue = ReadInfo(stream); BlockedValue = ReadInfo(stream); CurrentPrice = ReadInfo(stream); AveragePrice = ReadInfo(stream); UnrealizedPnL = ReadInfo(stream); RealizedPnL = ReadInfo(stream); VariationMargin = ReadInfo(stream); Leverage = ReadInfo(stream); Commission = ReadInfo(stream); CurrentValueInLots = ReadInfo(stream); var pfCount = stream.Read<int>(); for (var i = 0; i < pfCount; i++) Portfolios.Add(stream.Read<string>()); var ccCount = stream.Read<int>(); for (var i = 0; i < ccCount; i++) ClientCodes.Add(stream.Read<string>()); var dnCount = stream.Read<int>(); for (var i = 0; i < dnCount; i++) DepoNames.Add(stream.Read<string>()); if (Version < MarketDataVersions.Version33) return; SettlementPrice = ReadInfo(stream); } private static void Write(Stream stream, RefPair<decimal, decimal> info) { stream.WriteEx(info.First); stream.WriteEx(info.Second); } private static RefPair<decimal, decimal> ReadInfo(Stream stream) { return RefTuple.Create(stream.Read<decimal>(), stream.Read<decimal>()); } public override void CopyFrom(BinaryMetaInfo src) { base.CopyFrom(src); var posInfo = (PositionMetaInfo)src; BeginValue = Clone(posInfo.BeginValue); CurrentValue = Clone(posInfo.CurrentValue); BlockedValue = Clone(posInfo.BlockedValue); CurrentPrice = Clone(posInfo.CurrentPrice); AveragePrice = Clone(posInfo.AveragePrice); UnrealizedPnL = Clone(posInfo.UnrealizedPnL); RealizedPnL = Clone(posInfo.RealizedPnL); VariationMargin = Clone(posInfo.VariationMargin); Leverage = Clone(posInfo.Leverage); Commission = Clone(posInfo.Commission); CurrentValueInLots = Clone(posInfo.CurrentValueInLots); Portfolios.Clear(); Portfolios.AddRange(posInfo.Portfolios); ClientCodes.Clear(); ClientCodes.AddRange(posInfo.ClientCodes); DepoNames.Clear(); DepoNames.AddRange(posInfo.DepoNames); SettlementPrice = Clone(posInfo.SettlementPrice); } private static RefPair<decimal, decimal> Clone(RefPair<decimal, decimal> info) { return RefTuple.Create(info.First, info.Second); } } class PositionBinarySerializer : BinaryMarketDataSerializer<PositionChangeMessage, PositionMetaInfo> { public PositionBinarySerializer(SecurityId securityId, IExchangeInfoProvider exchangeInfoProvider) : base(securityId, null, 20, MarketDataVersions.Version36, exchangeInfoProvider) { } protected override void OnSave(BitArrayWriter writer, IEnumerable<PositionChangeMessage> messages, PositionMetaInfo metaInfo) { if (metaInfo.IsEmpty()) { var msg = messages.First(); metaInfo.ServerOffset = msg.ServerTime.Offset; } writer.WriteInt(messages.Count()); var buildFrom = metaInfo.Version >= MarketDataVersions.Version35; var side = metaInfo.Version >= MarketDataVersions.Version36; foreach (var message in messages) { var lastOffset = metaInfo.LastServerOffset; metaInfo.LastTime = writer.WriteTime(message.ServerTime, metaInfo.LastTime, "level1", true, true, metaInfo.ServerOffset, true, true, ref lastOffset); metaInfo.LastServerOffset = lastOffset; var hasLocalTime = message.HasLocalTime(message.ServerTime); writer.Write(hasLocalTime); if (hasLocalTime) { lastOffset = metaInfo.LastLocalOffset; metaInfo.LastLocalTime = writer.WriteTime(message.LocalTime, metaInfo.LastLocalTime, LocalizedStrings.Str919, true, true, metaInfo.LocalOffset, true, true, ref lastOffset, true); metaInfo.LastLocalOffset = lastOffset; } metaInfo.Portfolios.TryAdd(message.PortfolioName); writer.WriteInt(metaInfo.Portfolios.IndexOf(message.PortfolioName)); if (message.ClientCode.IsEmpty()) writer.Write(false); else { writer.Write(true); metaInfo.ClientCodes.TryAdd(message.ClientCode); writer.WriteInt(metaInfo.ClientCodes.IndexOf(message.ClientCode)); } if (message.DepoName.IsEmpty()) writer.Write(false); else { writer.Write(true); metaInfo.DepoNames.TryAdd(message.DepoName); writer.WriteInt(metaInfo.DepoNames.IndexOf(message.DepoName)); } writer.Write(message.LimitType != null); if (message.LimitType != null) writer.WriteInt((int)message.LimitType.Value); var count = message.Changes.Count; if (count == 0) throw new ArgumentException(LocalizedStrings.Str920, nameof(messages)); writer.WriteInt(count); foreach (var change in message.Changes) { writer.WriteInt((int)change.Key); switch (change.Key) { case PositionChangeTypes.BeginValue: SerializeChange(writer, metaInfo.BeginValue, (decimal)change.Value); break; case PositionChangeTypes.CurrentValue: SerializeChange(writer, metaInfo.CurrentValue, (decimal)change.Value); break; case PositionChangeTypes.BlockedValue: SerializeChange(writer, metaInfo.BlockedValue, (decimal)change.Value); break; case PositionChangeTypes.CurrentPrice: SerializeChange(writer, metaInfo.CurrentPrice, (decimal)change.Value); break; case PositionChangeTypes.AveragePrice: SerializeChange(writer, metaInfo.AveragePrice, (decimal)change.Value); break; case PositionChangeTypes.UnrealizedPnL: SerializeChange(writer, metaInfo.UnrealizedPnL, (decimal)change.Value); break; case PositionChangeTypes.RealizedPnL: SerializeChange(writer, metaInfo.RealizedPnL, (decimal)change.Value); break; case PositionChangeTypes.VariationMargin: SerializeChange(writer, metaInfo.VariationMargin, (decimal)change.Value); break; case PositionChangeTypes.Currency: writer.WriteInt((int)(CurrencyTypes)change.Value); break; case PositionChangeTypes.Leverage: SerializeChange(writer, metaInfo.Leverage, (decimal)change.Value); break; case PositionChangeTypes.Commission: SerializeChange(writer, metaInfo.Commission, (decimal)change.Value); break; case PositionChangeTypes.CurrentValueInLots: SerializeChange(writer, metaInfo.CurrentValueInLots, (decimal)change.Value); break; case PositionChangeTypes.State: writer.WriteInt((int)(PortfolioStates)change.Value); break; case PositionChangeTypes.ExpirationDate: writer.WriteDto((DateTimeOffset)change.Value); break; case PositionChangeTypes.CommissionMaker: case PositionChangeTypes.CommissionTaker: case PositionChangeTypes.BuyOrdersMargin: case PositionChangeTypes.SellOrdersMargin: case PositionChangeTypes.OrdersMargin: writer.WriteDecimal((decimal)change.Value, 0); break; case PositionChangeTypes.SettlementPrice: SerializeChange(writer, metaInfo.SettlementPrice, (decimal)change.Value); break; case PositionChangeTypes.BuyOrdersCount: case PositionChangeTypes.SellOrdersCount: case PositionChangeTypes.OrdersCount: case PositionChangeTypes.TradesCount: writer.WriteInt((int)change.Value); break; default: throw new InvalidOperationException(change.Key.To<string>()); } } if (metaInfo.Version < MarketDataVersions.Version34) continue; writer.WriteStringEx(message.Description); writer.WriteStringEx(message.StrategyId); if (!buildFrom) continue; writer.WriteBuildFrom(message.BuildFrom); if (!side) continue; writer.WriteNullableSide(message.Side); } } public override PositionChangeMessage MoveNext(MarketDataEnumerator enumerator) { var reader = enumerator.Reader; var metaInfo = enumerator.MetaInfo; var buildFrom = metaInfo.Version >= MarketDataVersions.Version35; var side = metaInfo.Version >= MarketDataVersions.Version36; var posMsg = new PositionChangeMessage { SecurityId = SecurityId }; var prevTime = metaInfo.FirstTime; var lastOffset = metaInfo.FirstServerOffset; posMsg.ServerTime = reader.ReadTime(ref prevTime, true, true, metaInfo.GetTimeZone(true, SecurityId, ExchangeInfoProvider), true, true, ref lastOffset); metaInfo.FirstTime = prevTime; metaInfo.FirstServerOffset = lastOffset; if (reader.Read()) { prevTime = metaInfo.FirstLocalTime; lastOffset = metaInfo.FirstLocalOffset; posMsg.LocalTime = reader.ReadTime(ref prevTime, true, true, metaInfo.LocalOffset, true, true, ref lastOffset); metaInfo.FirstLocalTime = prevTime; metaInfo.FirstLocalOffset = lastOffset; } posMsg.PortfolioName = metaInfo.Portfolios[reader.ReadInt()]; if (reader.Read()) { posMsg.ClientCode = metaInfo.ClientCodes[reader.ReadInt()]; } if (reader.Read()) { posMsg.DepoName = metaInfo.DepoNames[reader.ReadInt()]; } if (reader.Read()) posMsg.LimitType = (TPlusLimits)reader.ReadInt(); var changeCount = reader.ReadInt(); for (var i = 0; i < changeCount; i++) { var type = (PositionChangeTypes)reader.ReadInt(); switch (type) { case PositionChangeTypes.BeginValue: posMsg.Add(type, DeserializeChange(reader, metaInfo.BeginValue)); break; case PositionChangeTypes.CurrentValue: posMsg.Add(type, DeserializeChange(reader, metaInfo.CurrentValue)); break; case PositionChangeTypes.BlockedValue: posMsg.Add(type, DeserializeChange(reader, metaInfo.BlockedValue)); break; case PositionChangeTypes.CurrentPrice: posMsg.Add(type, DeserializeChange(reader, metaInfo.CurrentPrice)); break; case PositionChangeTypes.AveragePrice: posMsg.Add(type, DeserializeChange(reader, metaInfo.AveragePrice)); break; case PositionChangeTypes.UnrealizedPnL: posMsg.Add(type, DeserializeChange(reader, metaInfo.UnrealizedPnL)); break; case PositionChangeTypes.RealizedPnL: posMsg.Add(type, DeserializeChange(reader, metaInfo.RealizedPnL)); break; case PositionChangeTypes.VariationMargin: posMsg.Add(type, DeserializeChange(reader, metaInfo.VariationMargin)); break; case PositionChangeTypes.Currency: posMsg.Add(type, (CurrencyTypes)reader.ReadInt()); break; case PositionChangeTypes.Leverage: posMsg.Add(type, DeserializeChange(reader, metaInfo.Leverage)); break; case PositionChangeTypes.Commission: posMsg.Add(type, DeserializeChange(reader, metaInfo.Commission)); break; case PositionChangeTypes.CurrentValueInLots: posMsg.Add(type, DeserializeChange(reader, metaInfo.CurrentValueInLots)); break; case PositionChangeTypes.State: posMsg.Add(type, (PortfolioStates)reader.ReadInt()); break; case PositionChangeTypes.ExpirationDate: posMsg.Add(type, reader.ReadDto().Value); break; case PositionChangeTypes.CommissionMaker: case PositionChangeTypes.CommissionTaker: case PositionChangeTypes.BuyOrdersMargin: case PositionChangeTypes.SellOrdersMargin: case PositionChangeTypes.OrdersMargin: posMsg.Add(type, reader.ReadDecimal(0)); break; case PositionChangeTypes.SettlementPrice: posMsg.Add(type, DeserializeChange(reader, metaInfo.SettlementPrice)); break; case PositionChangeTypes.BuyOrdersCount: case PositionChangeTypes.SellOrdersCount: case PositionChangeTypes.OrdersCount: case PositionChangeTypes.TradesCount: posMsg.Add(type, reader.ReadInt()); break; default: throw new InvalidOperationException(type.To<string>()); } } if (metaInfo.Version < MarketDataVersions.Version34) return posMsg; posMsg.Description = reader.ReadStringEx(); posMsg.StrategyId = reader.ReadStringEx(); if (!buildFrom) return posMsg; posMsg.BuildFrom = reader.ReadBuildFrom(); if (!side) return posMsg; posMsg.Side = reader.ReadNullableSide(); return posMsg; } private static void SerializeChange(BitArrayWriter writer, RefPair<decimal, decimal> info, decimal price) { //if (price == 0) // throw new ArgumentOutOfRangeException(nameof(price)); if (info.First == 0) info.First = info.Second = price; info.Second = writer.WriteDecimal(price, info.Second); } private static decimal DeserializeChange(BitArrayReader reader, RefPair<decimal, decimal> info) { info.First = reader.ReadDecimal(info.First); return info.First; } } }
using System; using System.Collections.Generic; using System.Reactive; using System.Reactive.Linq; using System.Reactive.Subjects; using Microsoft.Reactive.Testing; using Avalonia.Data; using Avalonia.Data.Core; using Avalonia.UnitTests; using Xunit; using System.Threading.Tasks; using Avalonia.Markup.Parsers; using Avalonia.Threading; namespace Avalonia.Base.UnitTests.Data.Core { public class ExpressionObserverTests_Property { [Fact] public async Task Should_Get_Simple_Property_Value() { var data = new { Foo = "foo" }; var target = ExpressionObserver.Create(data, o => o.Foo); var result = await target.Take(1); Assert.Equal("foo", result); GC.KeepAlive(data); } [Fact] public void Should_Get_Simple_Property_Value_Type() { var data = new { Foo = "foo" }; var target = ExpressionObserver.Create(data, o => o.Foo); target.Subscribe(_ => { }); Assert.Equal(typeof(string), target.ResultType); GC.KeepAlive(data); } [Fact] public async Task Should_Get_Simple_Property_Value_Null() { var data = new { Foo = (string)null }; var target = ExpressionObserver.Create(data, o => o.Foo); var result = await target.Take(1); Assert.Null(result); GC.KeepAlive(data); } [Fact] public async Task Should_Get_Simple_Property_From_Base_Class() { var data = new Class3 { Foo = "foo" }; var target = ExpressionObserver.Create(data, o => o.Foo); var result = await target.Take(1); Assert.Equal("foo", result); GC.KeepAlive(data); } [Fact] public async Task Should_Return_BindingNotification_Error_For_Root_Null() { var target = ExpressionObserver.Create(default(Class3), o => o.Foo); var result = await target.Take(1); Assert.Equal( new BindingNotification( new MarkupBindingChainException("Null value", "o => o.Foo", string.Empty), BindingErrorType.Error, AvaloniaProperty.UnsetValue), result); } [Fact] public async Task Should_Return_BindingNotification_Error_For_Root_UnsetValue() { var target = ExpressionObserver.Create(AvaloniaProperty.UnsetValue, o => (o as Class3).Foo); var result = await target.Take(1); Assert.Equal( new BindingNotification( new MarkupBindingChainException("Null value", "o => (o As Class3).Foo", string.Empty), BindingErrorType.Error, AvaloniaProperty.UnsetValue), result); } [Fact] public async Task Should_Return_BindingNotification_Error_For_Observable_Root_Null() { var target = ExpressionObserver.Create(Observable.Return(default(Class3)), o => o.Foo); var result = await target.Take(1); Assert.Equal( new BindingNotification( new MarkupBindingChainException("Null value", "o => o.Foo", string.Empty), BindingErrorType.Error, AvaloniaProperty.UnsetValue), result); } [Fact] public async void Should_Return_BindingNotification_Error_For_Observable_Root_UnsetValue() { var target = ExpressionObserver.Create<object, string>(Observable.Return(AvaloniaProperty.UnsetValue), o => (o as Class3).Foo); var result = await target.Take(1); Assert.Equal( new BindingNotification( new MarkupBindingChainException("Null value", "o => (o As Class3).Foo", string.Empty), BindingErrorType.Error, AvaloniaProperty.UnsetValue), result); } [Fact] public async Task Should_Get_Simple_Property_Chain() { var data = new { Foo = new { Bar = new { Baz = "baz" } } }; var target = ExpressionObserver.Create(data, o => o.Foo.Bar.Baz); var result = await target.Take(1); Assert.Equal("baz", result); GC.KeepAlive(data); } [Fact] public void Should_Get_Simple_Property_Chain_Type() { var data = new { Foo = new { Bar = new { Baz = "baz" } } }; var target = ExpressionObserver.Create(data, o => o.Foo.Bar.Baz); target.Subscribe(_ => { }); Assert.Equal(typeof(string), target.ResultType); GC.KeepAlive(data); } [Fact] public void Should_Return_BindingNotification_Error_For_Chain_With_Null_Value() { var data = new { Foo = default(Class1) }; var target = ExpressionObserver.Create(data, o => o.Foo.Foo.Length); var result = new List<object>(); target.Subscribe(x => result.Add(x)); Assert.Equal( new[] { new BindingNotification( new MarkupBindingChainException("Null value", "o => o.Foo.Foo.Length", "Foo"), BindingErrorType.Error, AvaloniaProperty.UnsetValue), }, result); GC.KeepAlive(data); } [Fact] public void Should_Track_Simple_Property_Value() { var data = new Class1 { Foo = "foo" }; var target = ExpressionObserver.Create(data, o => o.Foo); var result = new List<object>(); var sub = target.Subscribe(x => result.Add(x)); data.Foo = "bar"; Assert.Equal(new[] { "foo", "bar" }, result); sub.Dispose(); // Forces WeakEvent compact Dispatcher.UIThread.RunJobs(); Assert.Equal(0, data.PropertyChangedSubscriptionCount); GC.KeepAlive(data); } [Fact] public void Should_Trigger_PropertyChanged_On_Null_Or_Empty_String() { var data = new Class1 { Bar = "foo" }; var target = ExpressionObserver.Create(data, o => o.Bar); var result = new List<object>(); var sub = target.Subscribe(x => result.Add(x)); Assert.Equal(new[] { "foo" }, result); data.Bar = "bar"; Assert.Equal(new[] { "foo" }, result); data.RaisePropertyChanged(string.Empty); Assert.Equal(new[] { "foo", "bar" }, result); data.RaisePropertyChanged(null); Assert.Equal(new[] { "foo", "bar", "bar" }, result); sub.Dispose(); // Forces WeakEvent compact Dispatcher.UIThread.RunJobs(); Assert.Equal(0, data.PropertyChangedSubscriptionCount); GC.KeepAlive(data); } [Fact] public void Should_Track_End_Of_Property_Chain_Changing() { var data = new Class1 { Next = new Class2 { Bar = "bar" } }; var target = ExpressionObserver.Create(data, o => (o.Next as Class2).Bar); var result = new List<object>(); var sub = target.Subscribe(x => result.Add(x)); ((Class2)data.Next).Bar = "baz"; ((Class2)data.Next).Bar = null; Assert.Equal(new[] { "bar", "baz", null }, result); sub.Dispose(); // Forces WeakEvent compact Dispatcher.UIThread.RunJobs(); Assert.Equal(0, data.PropertyChangedSubscriptionCount); Assert.Equal(0, data.Next.PropertyChangedSubscriptionCount); GC.KeepAlive(data); } [Fact] public void Should_Track_Property_Chain_Changing() { var data = new Class1 { Next = new Class2 { Bar = "bar" } }; var target = ExpressionObserver.Create(data, o => (o.Next as Class2).Bar); var result = new List<object>(); var sub = target.Subscribe(x => result.Add(x)); var old = data.Next; data.Next = new Class2 { Bar = "baz" }; data.Next = new Class2 { Bar = null }; Assert.Equal(new[] { "bar", "baz", null }, result); sub.Dispose(); // Forces WeakEvent compact Dispatcher.UIThread.RunJobs(); Assert.Equal(0, data.PropertyChangedSubscriptionCount); Assert.Equal(0, data.Next.PropertyChangedSubscriptionCount); Assert.Equal(0, old.PropertyChangedSubscriptionCount); GC.KeepAlive(data); } [Fact] public void Should_Track_Property_Chain_Breaking_With_Null_Then_Mending() { var data = new Class1 { Next = new Class2 { Next = new Class2 { Bar = "bar" } } }; var target = ExpressionObserver.Create(data, o => ((o.Next as Class2).Next as Class2).Bar); var result = new List<object>(); var sub = target.Subscribe(x => result.Add(x)); var old = data.Next; data.Next = new Class2 { Bar = "baz" }; data.Next = old; Assert.Equal( new object[] { "bar", new BindingNotification( new MarkupBindingChainException("Null value", "o => ((o.Next As Class2).Next As Class2).Bar", "Next.Next"), BindingErrorType.Error, AvaloniaProperty.UnsetValue), "bar" }, result); sub.Dispose(); // Forces WeakEvent compact Dispatcher.UIThread.RunJobs(); Assert.Equal(0, data.PropertyChangedSubscriptionCount); Assert.Equal(0, data.Next.PropertyChangedSubscriptionCount); Assert.Equal(0, old.PropertyChangedSubscriptionCount); GC.KeepAlive(data); } [Fact] public void Should_Track_Property_Chain_Breaking_With_Missing_Member_Then_Mending() { var data = new Class1 { Next = new Class2 { Bar = "bar" } }; var target = ExpressionObserver.Create(data, o => (o.Next as Class2).Bar); var result = new List<object>(); var sub = target.Subscribe(x => result.Add(x)); var old = data.Next; var breaking = new WithoutBar(); data.Next = breaking; data.Next = new Class2 { Bar = "baz" }; Assert.Equal( new object[] { "bar", new BindingNotification( new MissingMemberException("Could not find a matching property accessor for 'Bar' on 'Avalonia.Base.UnitTests.Data.Core.ExpressionObserverTests_Property+WithoutBar'"), BindingErrorType.Error), "baz", }, result); sub.Dispose(); // Forces WeakEvent compact Dispatcher.UIThread.RunJobs(); Assert.Equal(0, data.PropertyChangedSubscriptionCount); Assert.Equal(0, data.Next.PropertyChangedSubscriptionCount); Assert.Equal(0, breaking.PropertyChangedSubscriptionCount); Assert.Equal(0, old.PropertyChangedSubscriptionCount); GC.KeepAlive(data); } [Fact] public void Empty_Expression_Should_Track_Root() { var data = new Class1 { Foo = "foo" }; var update = new Subject<Unit>(); var target = ExpressionObserver.Create(() => data.Foo, o => o, update); var result = new List<object>(); target.Subscribe(x => result.Add(x)); data.Foo = "bar"; update.OnNext(Unit.Default); Assert.Equal(new[] { "foo", "bar" }, result); GC.KeepAlive(data); } [Fact] public void Should_Track_Property_Value_From_Observable_Root() { var scheduler = new TestScheduler(); var source = scheduler.CreateColdObservable( OnNext(1, new Class1 { Foo = "foo" }), OnNext(2, new Class1 { Foo = "bar" })); var target = ExpressionObserver.Create(source, o => o.Foo); var result = new List<object>(); using (target.Subscribe(x => result.Add(x))) { scheduler.Start(); } Assert.Equal(new[] { "foo", "bar" }, result); Assert.All(source.Subscriptions, x => Assert.NotEqual(Subscription.Infinite, x.Unsubscribe)); } [Fact] public void Subscribing_Multiple_Times_Should_Return_Values_To_All() { var data = new Class1 { Foo = "foo" }; var target = ExpressionObserver.Create(data, o => o.Foo); var result1 = new List<object>(); var result2 = new List<object>(); var result3 = new List<object>(); target.Subscribe(x => result1.Add(x)); target.Subscribe(x => result2.Add(x)); data.Foo = "bar"; target.Subscribe(x => result3.Add(x)); Assert.Equal(new[] { "foo", "bar" }, result1); Assert.Equal(new[] { "foo", "bar" }, result2); Assert.Equal(new[] { "bar" }, result3); GC.KeepAlive(data); } [Fact] public void Subscribing_Multiple_Times_Should_Only_Add_PropertyChanged_Handlers_Once() { var data = new Class1 { Foo = "foo" }; var target = ExpressionObserver.Create(data, o => o.Foo); var sub1 = target.Subscribe(x => { }); var sub2 = target.Subscribe(x => { }); Assert.Equal(1, data.PropertyChangedSubscriptionCount); sub1.Dispose(); sub2.Dispose(); // Forces WeakEvent compact Dispatcher.UIThread.RunJobs(); Assert.Equal(0, data.PropertyChangedSubscriptionCount); GC.KeepAlive(data); } [Fact] public void SetValue_Should_Set_Simple_Property_Value() { var data = new Class1 { Foo = "foo" }; var target = ExpressionObserver.Create(data, o => o.Foo); using (target.Subscribe(_ => { })) { Assert.True(target.SetValue("bar")); } Assert.Equal("bar", data.Foo); GC.KeepAlive(data); } [Fact] public void SetValue_Should_Set_Property_At_The_End_Of_Chain() { var data = new Class1 { Next = new Class2 { Bar = "bar" } }; var target = ExpressionObserver.Create(data, o => (o.Next as Class2).Bar); using (target.Subscribe(_ => { })) { Assert.True(target.SetValue("baz")); } Assert.Equal("baz", ((Class2)data.Next).Bar); GC.KeepAlive(data); } [Fact] public void SetValue_Should_Return_False_For_Missing_Property() { var data = new Class1 { Next = new WithoutBar() }; var target = ExpressionObserver.Create(data, o => (o.Next as Class2).Bar); using (target.Subscribe(_ => { })) { Assert.False(target.SetValue("baz")); } GC.KeepAlive(data); } [Fact] public void SetValue_Should_Notify_New_Value_With_Inpc() { var data = new Class1(); var target = ExpressionObserver.Create(data, o => o.Foo); var result = new List<object>(); target.Subscribe(x => result.Add(x)); target.SetValue("bar"); Assert.Equal(new[] { null, "bar" }, result); GC.KeepAlive(data); } [Fact] public void SetValue_Should_Notify_New_Value_Without_Inpc() { var data = new Class1(); var target = ExpressionObserver.Create(data, o => o.Bar); var result = new List<object>(); target.Subscribe(x => result.Add(x)); target.SetValue("bar"); Assert.Equal(new[] { null, "bar" }, result); GC.KeepAlive(data); } [Fact] public void SetValue_Should_Return_False_For_Missing_Object() { var data = new Class1(); var target = ExpressionObserver.Create(data, o => (o.Next as Class2).Bar); using (target.Subscribe(_ => { })) { Assert.False(target.SetValue("baz")); } GC.KeepAlive(data); } [Fact] public void Can_Replace_Root() { var first = new Class1 { Foo = "foo" }; var second = new Class1 { Foo = "bar" }; var root = first; var update = new Subject<Unit>(); var target = ExpressionObserver.Create(() => root, o => o.Foo, update); var result = new List<object>(); var sub = target.Subscribe(x => result.Add(x)); root = second; update.OnNext(Unit.Default); root = null; update.OnNext(Unit.Default); Assert.Equal( new object[] { "foo", "bar", new BindingNotification( new MarkupBindingChainException("Null value", "o => o.Foo", string.Empty), BindingErrorType.Error, AvaloniaProperty.UnsetValue) }, result); // Forces WeakEvent compact Dispatcher.UIThread.RunJobs(); Assert.Equal(0, first.PropertyChangedSubscriptionCount); Assert.Equal(0, second.PropertyChangedSubscriptionCount); GC.KeepAlive(first); GC.KeepAlive(second); } [Fact] public void Should_Not_Keep_Source_Alive() { Func<Tuple<ExpressionObserver, WeakReference>> run = () => { var source = new Class1 { Foo = "foo" }; var target = ExpressionObserver.Create(source, o => o.Foo); return Tuple.Create(target, new WeakReference(source)); }; var result = run(); result.Item1.Subscribe(x => { }); // Mono trickery GC.Collect(2); GC.WaitForPendingFinalizers(); GC.WaitForPendingFinalizers(); GC.Collect(2); Assert.Null(result.Item2.Target); } [Fact] public void Should_Not_Throw_Exception_On_Unsubscribe_When_Already_Unsubscribed() { var source = new Class1 { Foo = "foo" }; var target = new PropertyAccessorNode("Foo", false); Assert.NotNull(target); target.Target = new WeakReference<object>(source); target.Subscribe(_ => { }); target.Unsubscribe(); target.Unsubscribe(); Assert.True(true); } [Fact] public void Should_Not_Throw_Exception_When_Enabling_Data_Validation_On_Missing_Member() { var source = new Class1(); var target = new PropertyAccessorNode("NotFound", true); target.Target = new WeakReference<object>(source); var result = new List<object>(); target.Subscribe(x => result.Add(x)); Assert.Equal( new object[] { new BindingNotification( new MissingMemberException("Could not find a matching property accessor for 'NotFound' on 'Avalonia.Base.UnitTests.Data.Core.ExpressionObserverTests_Property+Class1'"), BindingErrorType.Error), }, result); } [Fact] public void Should_Not_Throw_Exception_On_Duplicate_Properties() { // Repro of https://github.com/AvaloniaUI/Avalonia/issues/4733. var source = new MyViewModel(); var target = new PropertyAccessorNode("Name", false); target.Target = new WeakReference<object>(source); var result = new List<object>(); target.Subscribe(x => result.Add(x)); } public class MyViewModelBase { public object Name => "Name"; } public class MyViewModel : MyViewModelBase { public new string Name => "NewName"; } private interface INext { int PropertyChangedSubscriptionCount { get; } } private class Class1 : NotifyingBase { private string _foo; private INext _next; public string Foo { get { return _foo; } set { _foo = value; RaisePropertyChanged(nameof(Foo)); } } private string _bar; public string Bar { get { return _bar; } set { _bar = value; } } public INext Next { get { return _next; } set { _next = value; RaisePropertyChanged(nameof(Next)); } } } private class Class2 : NotifyingBase, INext { private string _bar; private INext _next; public string Bar { get { return _bar; } set { _bar = value; RaisePropertyChanged(nameof(Bar)); } } public INext Next { get { return _next; } set { _next = value; RaisePropertyChanged(nameof(Next)); } } } private class Class3 : Class1 { } private class WithoutBar : NotifyingBase, INext { } private Recorded<Notification<T>> OnNext<T>(long time, T value) { return new Recorded<Notification<T>>(time, Notification.CreateOnNext<T>(value)); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using Microsoft.Rest.Azure; using Microsoft.Azure.Management.ResourceManager; using Microsoft.Azure.Management.ResourceManager.Models; using Microsoft.Rest; using Newtonsoft.Json.Linq; using Xunit; using Microsoft.Rest.Azure.OData; namespace ResourceGroups.Tests { public class InMemoryResourceGroupTests { public ResourceManagementClient GetResourceManagementClient(RecordedDelegatingHandler handler) { var subscriptionId = Guid.NewGuid().ToString(); var token = new TokenCredentials(subscriptionId, "abc123"); handler.IsPassThrough = false; var client = new ResourceManagementClient(token, handler); client.SubscriptionId = subscriptionId; return client; } [Fact] public void ResourceGroupCreateOrUpdateValidateMessage() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'id': '/subscriptions/abc123/resourcegroups/csmrgr5mfggio', 'name': 'foo', 'location': 'WestEurope', 'tags' : { 'department':'finance', 'tagname':'tagvalue' }, 'properties': { 'provisioningState': 'Succeeded' } }") }; var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(handler); var result = client.ResourceGroups.CreateOrUpdate("foo", new ResourceGroup { Location = "WestEurope", Tags = new Dictionary<string, string>() { { "department", "finance" }, { "tagname", "tagvalue" } }, }); JObject json = JObject.Parse(handler.Request); // Validate headers Assert.Equal("application/json; charset=utf-8", handler.ContentHeaders.GetValues("Content-Type").First()); Assert.Equal(HttpMethod.Put, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("Authorization")); // Validate payload Assert.Equal("WestEurope", json["location"].Value<string>()); Assert.Equal("finance", json["tags"]["department"].Value<string>()); Assert.Equal("tagvalue", json["tags"]["tagname"].Value<string>()); // Validate response Assert.Equal("/subscriptions/abc123/resourcegroups/csmrgr5mfggio", result.Id); Assert.Equal("Succeeded", result.Properties.ProvisioningState); Assert.Equal("foo", result.Name); Assert.Equal("finance", result.Tags["department"]); Assert.Equal("tagvalue", result.Tags["tagname"]); Assert.Equal("WestEurope", result.Location); } [Fact] public void ResourceGroupCreateOrUpdateThrowsExceptions() { var handler = new RecordedDelegatingHandler(); var client = GetResourceManagementClient(handler); Assert.Throws<Microsoft.Rest.ValidationException>(() => client.ResourceGroups.CreateOrUpdate(null, new ResourceGroup())); Assert.Throws<Microsoft.Rest.ValidationException>(() => client.ResourceGroups.CreateOrUpdate("foo", null)); } [Fact] public void ResourceGroupExistsReturnsTrue() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.NoContent }; var client = GetResourceManagementClient(handler); var result = client.ResourceGroups.CheckExistence("foo"); // Validate payload Assert.Empty(handler.Request); // Validate response Assert.True(result); } [Fact] public void ResourceGroupExistsReturnsFalse() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.NotFound }; var client = GetResourceManagementClient(handler); var result = client.ResourceGroups.CheckExistence(Guid.NewGuid().ToString()); // Validate payload Assert.Empty(handler.Request); // Validate response Assert.False(result); } [Fact()] public void ResourceGroupExistsThrowsException() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.BadRequest }; var client = GetResourceManagementClient(handler); Assert.Throws<CloudException>(() => client.ResourceGroups.CheckExistence("foo")); } [Fact] public void ResourceGroupPatchValidateMessage() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'subscriptionId': '123456', 'name': 'foo', 'location': 'WestEurope', 'id': '/subscriptions/abc123/resourcegroups/csmrgr5mfggio', 'properties': { 'provisioningState': 'Succeeded' } }") }; var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(handler); var result = client.ResourceGroups.Update("foo", new ResourceGroupPatchable { Name = "foo", }); JObject json = JObject.Parse(handler.Request); // Validate headers Assert.Equal("application/json; charset=utf-8", handler.ContentHeaders.GetValues("Content-Type").First()); Assert.Equal("patch", handler.Method.Method.Trim().ToLower()); Assert.NotNull(handler.RequestHeaders.GetValues("Authorization")); // Validate payload Assert.Equal("foo", json["name"].Value<string>()); // Validate response Assert.Equal("/subscriptions/abc123/resourcegroups/csmrgr5mfggio", result.Id); Assert.Equal("Succeeded", result.Properties.ProvisioningState); Assert.Equal("foo", result.Name); Assert.Equal("WestEurope", result.Location); } [Fact(Skip = "Parameter validation using pattern match is not supported yet at code-gen, the work is on-going.")] public void ResourceGroupUpdateStateThrowsExceptions() { var handler = new RecordedDelegatingHandler(); var client = GetResourceManagementClient(handler); Assert.Throws<ArgumentNullException>(() => client.ResourceGroups.Update(null, new ResourceGroupPatchable())); Assert.Throws<ArgumentNullException>(() => client.ResourceGroups.Update("foo", null)); Assert.Throws<ArgumentOutOfRangeException>(() => client.ResourceGroups.Update("~`123", new ResourceGroupPatchable())); } [Fact] public void ResourceGroupGetValidateMessage() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'id': '/subscriptions/abc123/resourcegroups/csmrgr5mfggio', 'name': 'foo', 'location': 'WestEurope', 'properties': { 'provisioningState': 'Succeeded' } }") }; response.Headers.Add("x-ms-request-id", "1"); var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(handler); var result = client.ResourceGroups.Get("foo"); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("Authorization")); // Validate result Assert.Equal("/subscriptions/abc123/resourcegroups/csmrgr5mfggio", result.Id); Assert.Equal("WestEurope", result.Location); Assert.Equal("foo", result.Name); Assert.Equal("Succeeded", result.Properties.ProvisioningState); Assert.True(result.Properties.ProvisioningState == "Succeeded"); } [Fact] public void ResourceGroupNameAcceptsAllAllowableCharacters() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'id': '/subscriptions/abc123/resourcegroups/csmrgr5mfggio', 'name': 'foo', 'location': 'WestEurope', 'properties': { 'provisioningState': 'Succeeded' } }") }; response.Headers.Add("x-ms-request-id", "1"); var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(handler); client.ResourceGroups.Get("foo-123_(bar)"); } [Fact(Skip = "Parameter validation using pattern match is not supported yet at code-gen, the work is on-going.")] public void ResourceGroupGetThrowsExceptions() { var handler = new RecordedDelegatingHandler(); var client = GetResourceManagementClient(handler); Assert.Throws<ArgumentNullException>(() => client.ResourceGroups.Get(null)); Assert.Throws<ArgumentOutOfRangeException>(() => client.ResourceGroups.Get("~`123")); } [Fact] public void ResourceGroupListAllValidateMessage() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'value': [{ 'id': '/subscriptions/abc123/resourcegroups/csmrgr5mfggio', 'name': 'myresourcegroup1', 'location': 'westus', 'properties': { 'provisioningState': 'Succeeded' } }, { 'id': '/subscriptions/abc123/resourcegroups/fdfdsdsf', 'name': 'myresourcegroup2', 'location': 'eastus', 'properties': { 'provisioningState': 'Succeeded' } } ], 'nextLink': 'https://wa/subscriptions/subId/resourcegroups?api-version=1.0&$skiptoken=662idk', }") }; response.Headers.Add("x-ms-request-id", "1"); var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(handler); var result = client.ResourceGroups.List(null); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("Authorization")); // Validate result Assert.Equal(2, result.Count()); Assert.Equal("myresourcegroup1", result.First().Name); Assert.Equal("Succeeded", result.First().Properties.ProvisioningState); Assert.Equal("/subscriptions/abc123/resourcegroups/csmrgr5mfggio", result.First().Id); Assert.Equal("https://wa/subscriptions/subId/resourcegroups?api-version=1.0&$skiptoken=662idk", result.NextPageLink); } [Fact] public void ResourceGroupListAllWorksForEmptyLists() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{'value': []}") }; response.Headers.Add("x-ms-request-id", "1"); var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(handler); var result = client.ResourceGroups.List(null); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("Authorization")); // Validate result Assert.Equal(0, result.Count()); } [Fact] public void ResourceGroupListValidateMessage() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'value': [{ 'name': 'myresourcegroup1', 'location': 'westus', 'locked': 'true' }, { 'name': 'myresourcegroup2', 'location': 'eastus', 'locked': 'false' } ], 'nextLink': 'https://wa/subscriptions/subId/resourcegroups?api-version=1.0&$skiptoken=662idk', }") }; response.Headers.Add("x-ms-request-id", "1"); var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(handler); var result = client.ResourceGroups.List(new ODataQuery<ResourceGroupFilter> { Top = 5 }); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("Authorization")); Assert.True(handler.Uri.ToString().Contains("$top=5")); // Validate result Assert.Equal(2, result.Count()); Assert.Equal("myresourcegroup1", result.First().Name); Assert.Equal("https://wa/subscriptions/subId/resourcegroups?api-version=1.0&$skiptoken=662idk", result.NextPageLink); } [Fact] public void ResourceGroupDeleteValidateMessage() { var response = new HttpResponseMessage(HttpStatusCode.Accepted); response.Headers.Add("Location", "http://foo"); var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.Accepted, SubsequentStatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(handler); client.LongRunningOperationRetryTimeout = 0; client.ResourceGroups.Delete("foo"); } [Fact] public void ResourceGroupDeleteThrowsExceptions() { var handler = new RecordedDelegatingHandler(); var client = GetResourceManagementClient(handler); Assert.Throws<ValidationException>(() => client.ResourceGroups.Delete(null)); Assert.Throws<ValidationException>(() => client.ResourceGroups.Delete("~`123")); } } }
//------------------------------------------------------------------------------ // <copyright file="PerformanceCounterCategory.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Diagnostics { using System.Runtime.Serialization.Formatters; using System.ComponentModel; using System.Diagnostics; using System; using System.Threading; using System.Security; using System.Security.Permissions; using System.Collections; using Microsoft.Win32; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.Versioning; /// <devdoc> /// A Performance counter category object. /// </devdoc> [ HostProtection(Synchronization=true, SharedState=true) ] public sealed class PerformanceCounterCategory { private string categoryName; private string categoryHelp; private string machineName; internal const int MaxCategoryNameLength = 80; internal const int MaxCounterNameLength = 32767; internal const int MaxHelpLength = 32767; private const string perfMutexName = "netfxperf.1.0"; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public PerformanceCounterCategory() { machineName = "."; } /// <devdoc> /// Creates a PerformanceCounterCategory object for given category. /// Uses the local machine. /// </devdoc> public PerformanceCounterCategory(string categoryName) : this(categoryName, ".") { } /// <devdoc> /// Creates a PerformanceCounterCategory object for given category. /// Uses the given machine name. /// </devdoc> public PerformanceCounterCategory(string categoryName, string machineName) { if (categoryName == null) throw new ArgumentNullException("categoryName"); if (categoryName.Length == 0) throw new ArgumentException(SR.GetString(SR.InvalidParameter, "categoryName", categoryName)); if (!SyntaxCheck.CheckMachineName(machineName)) throw new ArgumentException(SR.GetString(SR.InvalidParameter, "machineName", machineName)); PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, machineName, categoryName); permission.Demand(); this.categoryName = categoryName; this.machineName = machineName; } /// <devdoc> /// Gets/sets the Category name /// </devdoc> public string CategoryName { get { return categoryName; } set { if (value == null) throw new ArgumentNullException("value"); if (value.Length == 0) throw new ArgumentException(SR.GetString(SR.InvalidProperty, "CategoryName", value)); // there lock prevents a ---- between setting CategoryName and MachineName, since this permission // checks depend on both pieces of info. lock (this) { PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, machineName, value); permission.Demand(); this.categoryName = value; } } } /// <devdoc> /// Gets/sets the Category help /// </devdoc> public string CategoryHelp { get { if (this.categoryName == null) throw new InvalidOperationException(SR.GetString(SR.CategoryNameNotSet)); if (categoryHelp == null) categoryHelp = PerformanceCounterLib.GetCategoryHelp(this.machineName, this.categoryName); return categoryHelp; } } public PerformanceCounterCategoryType CategoryType{ get { CategorySample categorySample = PerformanceCounterLib.GetCategorySample(machineName, categoryName); // If we get MultiInstance, we can be confident it is correct. If it is single instance, though // we need to check if is a custom category and if the IsMultiInstance value is set in the registry. // If not we return Unknown if (categorySample.IsMultiInstance) return PerformanceCounterCategoryType.MultiInstance; else { if (PerformanceCounterLib.IsCustomCategory(".", categoryName)) return PerformanceCounterLib.GetCategoryType(".", categoryName); else return PerformanceCounterCategoryType.SingleInstance; } } } /// <devdoc> /// Gets/sets the Machine name /// </devdoc> public string MachineName { get { return machineName; } set { if (!SyntaxCheck.CheckMachineName(value)) throw new ArgumentException(SR.GetString(SR.InvalidProperty, "MachineName", value)); // there lock prevents a ---- between setting CategoryName and MachineName, since this permission // checks depend on both pieces of info. lock (this) { if (categoryName != null) { PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, value, categoryName); permission.Demand(); } machineName = value; } } } /// <devdoc> /// Returns true if the counter is registered for this category /// </devdoc> public bool CounterExists(string counterName) { if (counterName == null) throw new ArgumentNullException("counterName"); if (this.categoryName == null) throw new InvalidOperationException(SR.GetString(SR.CategoryNameNotSet)); return PerformanceCounterLib.CounterExists(machineName, categoryName, counterName); } /// <devdoc> /// Returns true if the counter is registered for this category on the current machine. /// </devdoc> public static bool CounterExists(string counterName, string categoryName) { return CounterExists(counterName, categoryName, "."); } /// <devdoc> /// Returns true if the counter is registered for this category on a particular machine. /// </devdoc> public static bool CounterExists(string counterName, string categoryName, string machineName) { if (counterName == null) throw new ArgumentNullException("counterName"); if (categoryName == null) throw new ArgumentNullException("categoryName"); if (categoryName.Length == 0) throw new ArgumentException(SR.GetString(SR.InvalidParameter, "categoryName", categoryName)); if (!SyntaxCheck.CheckMachineName(machineName)) throw new ArgumentException(SR.GetString(SR.InvalidParameter, "machineName", machineName)); PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, machineName, categoryName); permission.Demand(); return PerformanceCounterLib.CounterExists(machineName, categoryName, counterName); } /// <devdoc> /// Registers one extensible performance category of type NumberOfItems32 with the system /// </devdoc> [Obsolete("This method has been deprecated. Please use System.Diagnostics.PerformanceCounterCategory.Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, string counterName, string counterHelp) instead. http://go.microsoft.com/fwlink/?linkid=14202")] [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public static PerformanceCounterCategory Create(string categoryName, string categoryHelp, string counterName, string counterHelp) { CounterCreationData customData = new CounterCreationData(counterName, counterHelp, PerformanceCounterType.NumberOfItems32); return Create(categoryName, categoryHelp, PerformanceCounterCategoryType.Unknown, new CounterCreationDataCollection(new CounterCreationData [] {customData})); } [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public static PerformanceCounterCategory Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, string counterName, string counterHelp) { CounterCreationData customData = new CounterCreationData(counterName, counterHelp, PerformanceCounterType.NumberOfItems32); return Create(categoryName, categoryHelp, categoryType, new CounterCreationDataCollection(new CounterCreationData [] {customData})); } /// <devdoc> /// Registers the extensible performance category with the system on the local machine /// </devdoc> [Obsolete("This method has been deprecated. Please use System.Diagnostics.PerformanceCounterCategory.Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, CounterCreationDataCollection counterData) instead. http://go.microsoft.com/fwlink/?linkid=14202")] [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public static PerformanceCounterCategory Create(string categoryName, string categoryHelp, CounterCreationDataCollection counterData) { return Create(categoryName, categoryHelp, PerformanceCounterCategoryType.Unknown, counterData); } [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public static PerformanceCounterCategory Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, CounterCreationDataCollection counterData) { if (categoryType < PerformanceCounterCategoryType.Unknown || categoryType > PerformanceCounterCategoryType.MultiInstance) throw new ArgumentOutOfRangeException("categoryType"); if (counterData == null) throw new ArgumentNullException("counterData"); CheckValidCategory(categoryName); if (categoryHelp != null) { // null categoryHelp is a valid option - it gets set to "Help Not Available" later on. CheckValidHelp(categoryHelp); } string machineName = "."; PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Administer, machineName, categoryName); permission.Demand(); SharedUtils.CheckNtEnvironment(); Mutex mutex = null; RuntimeHelpers.PrepareConstrainedRegions(); try { SharedUtils.EnterMutex(perfMutexName, ref mutex); if (PerformanceCounterLib.IsCustomCategory(machineName, categoryName) || PerformanceCounterLib.CategoryExists(machineName , categoryName)) throw new InvalidOperationException(SR.GetString(SR.PerformanceCategoryExists, categoryName)); CheckValidCounterLayout(counterData); PerformanceCounterLib.RegisterCategory(categoryName, categoryType, categoryHelp, counterData); return new PerformanceCounterCategory(categoryName, machineName); } finally { if (mutex != null) { mutex.ReleaseMutex(); mutex.Close(); } } } // there is an idential copy of CheckValidCategory in PerformnaceCounterInstaller internal static void CheckValidCategory(string categoryName) { if (categoryName == null) throw new ArgumentNullException("categoryName"); if (!CheckValidId(categoryName, MaxCategoryNameLength)) throw new ArgumentException(SR.GetString(SR.PerfInvalidCategoryName, 1, MaxCategoryNameLength)); // 1026 chars is the size of the buffer used in perfcounter.dll to get this name. // If the categoryname plus prefix is too long, we won't be able to read the category properly. if (categoryName.Length > (1024 - SharedPerformanceCounter.DefaultFileMappingName.Length)) throw new ArgumentException(SR.GetString(SR.CategoryNameTooLong)); } internal static void CheckValidCounter(string counterName) { if (counterName == null) throw new ArgumentNullException("counterName"); if (!CheckValidId(counterName, MaxCounterNameLength)) throw new ArgumentException(SR.GetString(SR.PerfInvalidCounterName, 1, MaxCounterNameLength)); } // there is an idential copy of CheckValidId in PerformnaceCounterInstaller internal static bool CheckValidId(string id, int maxLength) { if (id.Length == 0 || id.Length > maxLength) return false; for (int index = 0; index < id.Length; ++index) { char current = id[index]; if ((index == 0 || index == (id.Length -1)) && current == ' ') return false; if (current == '\"') return false; if (char.IsControl(current)) return false; } return true; } internal static void CheckValidHelp(string help) { if (help == null) throw new ArgumentNullException("help"); if (help.Length > MaxHelpLength) throw new ArgumentException(SR.GetString(SR.PerfInvalidHelp, 0, MaxHelpLength)); } internal static void CheckValidCounterLayout(CounterCreationDataCollection counterData) { // Ensure that there are no duplicate counter names being created Hashtable h = new Hashtable(); for (int i = 0; i < counterData.Count; i++) { if (counterData[i].CounterName == null || counterData[i].CounterName.Length == 0) { throw new ArgumentException(SR.GetString(SR.InvalidCounterName)); } int currentSampleType = (int)counterData[i].CounterType; if ( (currentSampleType == NativeMethods.PERF_AVERAGE_BULK) || (currentSampleType == NativeMethods.PERF_100NSEC_MULTI_TIMER) || (currentSampleType == NativeMethods.PERF_100NSEC_MULTI_TIMER_INV) || (currentSampleType == NativeMethods.PERF_COUNTER_MULTI_TIMER) || (currentSampleType == NativeMethods.PERF_COUNTER_MULTI_TIMER_INV) || (currentSampleType == NativeMethods.PERF_RAW_FRACTION) || (currentSampleType == NativeMethods.PERF_SAMPLE_FRACTION) || (currentSampleType == NativeMethods.PERF_AVERAGE_TIMER)) { if (counterData.Count <= (i + 1)) throw new InvalidOperationException(SR.GetString(SR.CounterLayout)); else { currentSampleType = (int)counterData[i + 1].CounterType; if (!PerformanceCounterLib.IsBaseCounter(currentSampleType)) throw new InvalidOperationException(SR.GetString(SR.CounterLayout)); } } else if (PerformanceCounterLib.IsBaseCounter(currentSampleType)) { if (i == 0) throw new InvalidOperationException(SR.GetString(SR.CounterLayout)); else { currentSampleType = (int)counterData[i - 1].CounterType; if ( (currentSampleType != NativeMethods.PERF_AVERAGE_BULK) && (currentSampleType != NativeMethods.PERF_100NSEC_MULTI_TIMER) && (currentSampleType != NativeMethods.PERF_100NSEC_MULTI_TIMER_INV) && (currentSampleType != NativeMethods.PERF_COUNTER_MULTI_TIMER) && (currentSampleType != NativeMethods.PERF_COUNTER_MULTI_TIMER_INV) && (currentSampleType != NativeMethods.PERF_RAW_FRACTION) && (currentSampleType != NativeMethods.PERF_SAMPLE_FRACTION) && (currentSampleType != NativeMethods.PERF_AVERAGE_TIMER)) throw new InvalidOperationException(SR.GetString(SR.CounterLayout)); } } if (h.ContainsKey(counterData[i].CounterName)) { throw new ArgumentException(SR.GetString(SR.DuplicateCounterName, counterData[i].CounterName)); } else { h.Add(counterData[i].CounterName, String.Empty); // Ensure that all counter help strings aren't null or empty if (counterData[i].CounterHelp == null || counterData[i].CounterHelp.Length == 0) { counterData[i].CounterHelp = counterData[i].CounterName; } } } } /// <devdoc> /// Removes the counter (category) from the system /// </devdoc> [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public static void Delete(string categoryName) { CheckValidCategory(categoryName); string machineName = "."; PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Administer, machineName, categoryName); permission.Demand(); SharedUtils.CheckNtEnvironment(); categoryName = categoryName.ToLower(CultureInfo.InvariantCulture); Mutex mutex = null; RuntimeHelpers.PrepareConstrainedRegions(); try { SharedUtils.EnterMutex(perfMutexName, ref mutex); if (!PerformanceCounterLib.IsCustomCategory(machineName, categoryName)) throw new InvalidOperationException(SR.GetString(SR.CantDeleteCategory)); SharedPerformanceCounter.RemoveAllInstances(categoryName); PerformanceCounterLib.UnregisterCategory(categoryName); PerformanceCounterLib.CloseAllLibraries(); } finally { if (mutex != null) { mutex.ReleaseMutex(); mutex.Close(); } } } /// <devdoc> /// Returns true if the category is registered on the current machine. /// </devdoc> public static bool Exists(string categoryName) { return Exists(categoryName, "."); } /// <devdoc> /// Returns true if the category is registered in the machine. /// </devdoc> public static bool Exists(string categoryName, string machineName) { if (categoryName == null) throw new ArgumentNullException("categoryName"); if (categoryName.Length == 0) throw new ArgumentException(SR.GetString(SR.InvalidParameter, "categoryName", categoryName)); if (!SyntaxCheck.CheckMachineName(machineName)) throw new ArgumentException(SR.GetString(SR.InvalidParameter, "machineName", machineName)); PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, machineName, categoryName); permission.Demand(); if (PerformanceCounterLib.IsCustomCategory(machineName , categoryName)) return true; return PerformanceCounterLib.CategoryExists(machineName , categoryName); } /// <devdoc> /// Returns the instance names for a given category /// </devdoc> /// <internalonly/> internal static string[] GetCounterInstances(string categoryName, string machineName) { PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, machineName, categoryName); permission.Demand(); CategorySample categorySample = PerformanceCounterLib.GetCategorySample(machineName, categoryName); if (categorySample.InstanceNameTable.Count == 0) return new string[0]; string[] instanceNames = new string[categorySample.InstanceNameTable.Count]; categorySample.InstanceNameTable.Keys.CopyTo(instanceNames, 0); if (instanceNames.Length == 1 && instanceNames[0].CompareTo(PerformanceCounterLib.SingleInstanceName) == 0) return new string[0]; return instanceNames; } /// <devdoc> /// Returns an array of counters in this category. The counter must have only one instance. /// </devdoc> public PerformanceCounter[] GetCounters() { if (GetInstanceNames().Length != 0) throw new ArgumentException(SR.GetString(SR.InstanceNameRequired)); return GetCounters(""); } /// <devdoc> /// Returns an array of counters in this category for the given instance. /// </devdoc> public PerformanceCounter[] GetCounters(string instanceName) { if (instanceName == null) throw new ArgumentNullException("instanceName"); if (this.categoryName == null) throw new InvalidOperationException(SR.GetString(SR.CategoryNameNotSet)); if (instanceName.Length != 0 && !InstanceExists(instanceName)) throw new InvalidOperationException(SR.GetString(SR.MissingInstance, instanceName, categoryName)); string[] counterNames = PerformanceCounterLib.GetCounters(machineName, categoryName); PerformanceCounter[] counters = new PerformanceCounter[counterNames.Length]; for (int index = 0; index < counters.Length; index++) counters[index] = new PerformanceCounter(categoryName, counterNames[index], instanceName, machineName, true); return counters; } /// <devdoc> /// Returns an array of performance counter categories for the current machine. /// </devdoc> public static PerformanceCounterCategory[] GetCategories() { return GetCategories("."); } /// <devdoc> /// Returns an array of performance counter categories for a particular machine. /// </devdoc> public static PerformanceCounterCategory[] GetCategories(string machineName) { if (!SyntaxCheck.CheckMachineName(machineName)) throw new ArgumentException(SR.GetString(SR.InvalidParameter, "machineName", machineName)); PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, machineName, "*"); permission.Demand(); string[] categoryNames = PerformanceCounterLib.GetCategories(machineName); PerformanceCounterCategory[] categories = new PerformanceCounterCategory[categoryNames.Length]; for (int index = 0; index < categories.Length; index++) categories[index] = new PerformanceCounterCategory(categoryNames[index], machineName); return categories; } /// <devdoc> /// Returns an array of instances for this category /// </devdoc> public string[] GetInstanceNames() { if (this.categoryName == null) throw new InvalidOperationException(SR.GetString(SR.CategoryNameNotSet)); return GetCounterInstances(categoryName, machineName); } /// <devdoc> /// Returns true if the instance already exists for this category. /// </devdoc> public bool InstanceExists(string instanceName) { if (instanceName == null) throw new ArgumentNullException("instanceName"); if (this.categoryName == null) throw new InvalidOperationException(SR.GetString(SR.CategoryNameNotSet)); CategorySample categorySample = PerformanceCounterLib.GetCategorySample(machineName, categoryName); return categorySample.InstanceNameTable.ContainsKey(instanceName); } /// <devdoc> /// Returns true if the instance already exists for the category specified. /// </devdoc> public static bool InstanceExists(string instanceName, string categoryName) { return InstanceExists(instanceName, categoryName, "."); } /// <devdoc> /// Returns true if the instance already exists for this category and machine specified. /// </devdoc> public static bool InstanceExists(string instanceName, string categoryName, string machineName) { if (instanceName == null) throw new ArgumentNullException("instanceName"); if (categoryName == null) throw new ArgumentNullException("categoryName"); if (categoryName.Length == 0) throw new ArgumentException(SR.GetString(SR.InvalidParameter, "categoryName", categoryName)); if (!SyntaxCheck.CheckMachineName(machineName)) throw new ArgumentException(SR.GetString(SR.InvalidParameter, "machineName", machineName)); PerformanceCounterCategory category = new PerformanceCounterCategory(categoryName, machineName); return category.InstanceExists(instanceName); } /// <devdoc> /// Reads all the counter and instance data of this performance category. Note that reading the entire category /// at once can be as efficient as reading a single counter because of the way the system provides the data. /// </devdoc> public InstanceDataCollectionCollection ReadCategory() { if (this.categoryName == null) throw new InvalidOperationException(SR.GetString(SR.CategoryNameNotSet)); CategorySample categorySample = PerformanceCounterLib.GetCategorySample(this.machineName, this.categoryName); return categorySample.ReadCategory(); } } [Flags] internal enum PerformanceCounterCategoryOptions { EnableReuse = 0x1, UseUniqueSharedMemory = 0x2, } }
using System; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; using NSubstitute; using Xunit; namespace Octokit.Tests.Clients { /// <summary> /// Client tests mostly just need to make sure they call the IApiConnection with the correct /// relative Uri. No need to fake up the response. All *those* tests are in ApiConnectionTests.cs. /// </summary> public class RepositoryBranchesClientTests { public class TheCtor { [Fact] public void EnsuresNonNullArguments() { Assert.Throws<ArgumentNullException>(() => new RepositoryBranchesClient(null)); } } public class TheGetAllMethod { [Fact] public async Task RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); await client.GetAll("owner", "name"); connection.Received() .GetAll<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/branches"), null, "application/vnd.github.loki-preview+json", Args.ApiOptions); } [Fact] public async Task RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); await client.GetAll(1); connection.Received() .GetAll<Branch>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches"), null, "application/vnd.github.loki-preview+json", Args.ApiOptions); } [Fact] public async Task RequestsTheCorrectUrlWithApiOptions() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); var options = new ApiOptions { PageCount = 1, StartPage = 1, PageSize = 1 }; await client.GetAll("owner", "name", options); connection.Received() .GetAll<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/branches"), null, "application/vnd.github.loki-preview+json", options); } [Fact] public async Task RequestsTheCorrectUrlWithRepositoryIdWithApiOptions() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); var options = new ApiOptions { PageCount = 1, StartPage = 1, PageSize = 1 }; await client.GetAll(1, options); connection.Received() .GetAll<Branch>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches"), null, "application/vnd.github.loki-preview+json", options); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll(null, "name")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll("owner", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll(null, "name", ApiOptions.None)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll("owner", null, ApiOptions.None)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll("owner", "name", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll(1, null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAll("", "name")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAll("owner", "")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAll("", "name", ApiOptions.None)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAll("owner", "", ApiOptions.None)); } } public class TheGetMethod { [Fact] public async Task RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); await client.Get("owner", "repo", "branch"); connection.Received() .Get<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch"), null, "application/vnd.github.loki-preview+json"); } [Fact] public async Task RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); await client.Get(1, "branch"); connection.Received() .Get<Branch>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch"), null, "application/vnd.github.loki-preview+json"); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get(null, "repo", "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get("owner", null, "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get("owner", "repo", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get(1, null)); await Assert.ThrowsAsync<ArgumentException>(() => client.Get("", "repo", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.Get("owner", "", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.Get("owner", "repo", "")); } } public class TheEditMethod { [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); var update = new BranchUpdate(); const string previewAcceptsHeader = "application/vnd.github.loki-preview+json"; client.Edit("owner", "repo", "branch", update); connection.Received() .Patch<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch"), Arg.Any<BranchUpdate>(), previewAcceptsHeader); } [Fact] public void RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); var update = new BranchUpdate(); const string previewAcceptsHeader = "application/vnd.github.loki-preview+json"; client.Edit(1, "branch", update); connection.Received() .Patch<Branch>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch"), Arg.Any<BranchUpdate>(), previewAcceptsHeader); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>()); var update = new BranchUpdate(); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Edit(null, "repo", "branch", update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Edit("owner", null, "branch", update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Edit("owner", "repo", null, update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Edit("owner", "repo", "branch", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Edit(1, null, update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Edit(1, "branch", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.Edit("", "repo", "branch", update)); await Assert.ThrowsAsync<ArgumentException>(() => client.Edit("owner", "", "branch", update)); await Assert.ThrowsAsync<ArgumentException>(() => client.Edit("owner", "repo", "", update)); await Assert.ThrowsAsync<ArgumentException>(() => client.Edit(1, "", update)); } } public class TheGetBranchProtectectionMethod { [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); const string previewAcceptsHeader = "application/vnd.github.loki-preview+json"; client.GetBranchProtection("owner", "repo", "branch"); connection.Received() .Get<BranchProtectionSettings>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection"), null, previewAcceptsHeader); } [Fact] public void RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); const string previewAcceptsHeader = "application/vnd.github.loki-preview+json"; client.GetBranchProtection(1, "branch"); connection.Received() .Get<BranchProtectionSettings>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection"), null, previewAcceptsHeader); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranchProtection(null, "repo", "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranchProtection("owner", null, "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranchProtection("owner", "repo", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranchProtection(1, null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetBranchProtection("", "repo", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetBranchProtection("owner", "", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetBranchProtection("owner", "repo", "")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetBranchProtection(1, "")); } } public class TheUpdateBranchProtectionMethod { [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); var update = new BranchProtectionSettingsUpdate( new BranchProtectionRequiredStatusChecksUpdate(true, true, new[] { "test" })); const string previewAcceptsHeader = "application/vnd.github.loki-preview+json"; client.UpdateBranchProtection("owner", "repo", "branch", update); connection.Received() .Put<BranchProtectionSettings>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection"), Arg.Any<BranchProtectionSettingsUpdate>(), null, previewAcceptsHeader); } [Fact] public void RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); var update = new BranchProtectionSettingsUpdate( new BranchProtectionRequiredStatusChecksUpdate(true, true, new[] { "test" })); const string previewAcceptsHeader = "application/vnd.github.loki-preview+json"; client.UpdateBranchProtection(1, "branch", update); connection.Received() .Put<BranchProtectionSettings>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection"), Arg.Any<BranchProtectionSettingsUpdate>(), null, previewAcceptsHeader); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>()); var update = new BranchProtectionSettingsUpdate( new BranchProtectionRequiredStatusChecksUpdate(true, true, new[] { "test" })); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateBranchProtection(null, "repo", "branch", update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateBranchProtection("owner", null, "branch", update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateBranchProtection("owner", "repo", null, update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateBranchProtection("owner", "repo", "branch", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateBranchProtection(1, null, update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateBranchProtection(1, "branch", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateBranchProtection("", "repo", "branch", update)); await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateBranchProtection("owner", "", "branch", update)); await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateBranchProtection("owner", "repo", "", update)); await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateBranchProtection(1, "", update)); } } public class TheDeleteBranchProtectectionMethod { [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); const string previewAcceptsHeader = "application/vnd.github.loki-preview+json"; client.DeleteBranchProtection("owner", "repo", "branch"); connection.Connection.Received() .Delete(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection"), Arg.Any<object>(), previewAcceptsHeader); } [Fact] public void RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); const string previewAcceptsHeader = "application/vnd.github.loki-preview+json"; client.DeleteBranchProtection(1, "branch"); connection.Connection.Received() .Delete(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection"), Arg.Any<object>(), previewAcceptsHeader); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteBranchProtection(null, "repo", "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteBranchProtection("owner", null, "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteBranchProtection("owner", "repo", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteBranchProtection(1, null)); await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteBranchProtection("", "repo", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteBranchProtection("owner", "", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteBranchProtection("owner", "repo", "")); await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteBranchProtection(1, "")); } } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using NonSilo.Tests.Utilities; using NSubstitute; using Orleans; using Orleans.Configuration; using Orleans.Runtime; using Orleans.Runtime.MembershipService; using TestExtensions; using Xunit; using Xunit.Abstractions; namespace NonSilo.Tests.Membership { [TestCategory("BVT"), TestCategory("Membership")] public class MembershipAgentTests { private readonly ITestOutputHelper output; private readonly LoggerFactory loggerFactory; private readonly ILocalSiloDetails localSiloDetails; private readonly SiloAddress localSilo; private readonly IFatalErrorHandler fatalErrorHandler; private readonly IMembershipGossiper membershipGossiper; private readonly SiloLifecycleSubject lifecycle; private readonly List<DelegateAsyncTimer> timers; private readonly ConcurrentDictionary<string, ConcurrentQueue<(TimeSpan? DelayOverride, TaskCompletionSource<bool> Completion)>> timerCalls; private readonly DelegateAsyncTimerFactory timerFactory; private readonly InMemoryMembershipTable membershipTable; private readonly IOptions<ClusterMembershipOptions> clusterMembershipOptions; private readonly MembershipTableManager manager; private readonly ClusterHealthMonitor clusterHealthMonitor; private readonly MembershipAgent agent; public MembershipAgentTests(ITestOutputHelper output) { this.output = output; this.loggerFactory = new LoggerFactory(new[] { new XunitLoggerProvider(this.output) }); this.localSiloDetails = Substitute.For<ILocalSiloDetails>(); this.localSilo = SiloAddress.FromParsableString("127.0.0.1:100@100"); this.localSiloDetails.SiloAddress.Returns(this.localSilo); this.localSiloDetails.DnsHostName.Returns("MyServer11"); this.localSiloDetails.Name.Returns(Guid.NewGuid().ToString("N")); this.fatalErrorHandler = Substitute.For<IFatalErrorHandler>(); this.fatalErrorHandler.IsUnexpected(default).ReturnsForAnyArgs(true); this.membershipGossiper = Substitute.For<IMembershipGossiper>(); this.lifecycle = new SiloLifecycleSubject(this.loggerFactory.CreateLogger<SiloLifecycleSubject>()); this.timers = new List<DelegateAsyncTimer>(); this.timerCalls = new ConcurrentDictionary<string, ConcurrentQueue<(TimeSpan? DelayOverride, TaskCompletionSource<bool> Completion)>>(); this.timerFactory = new DelegateAsyncTimerFactory( (period, name) => { var t = new DelegateAsyncTimer( overridePeriod => { var queue = this.timerCalls.GetOrAdd(name, n => new ConcurrentQueue<(TimeSpan? DelayOverride, TaskCompletionSource<bool> Completion)>()); var task = new TaskCompletionSource<bool>(); queue.Enqueue((overridePeriod, task)); return task.Task; }); this.timers.Add(t); return t; }); this.membershipTable = new InMemoryMembershipTable(new TableVersion(1, "1")); this.clusterMembershipOptions = Options.Create(new ClusterMembershipOptions()); this.manager = new MembershipTableManager( localSiloDetails: this.localSiloDetails, clusterMembershipOptions: Options.Create(new ClusterMembershipOptions()), membershipTable: membershipTable, fatalErrorHandler: this.fatalErrorHandler, gossiper: this.membershipGossiper, log: this.loggerFactory.CreateLogger<MembershipTableManager>(), timerFactory: new AsyncTimerFactory(this.loggerFactory), this.lifecycle); ((ILifecycleParticipant<ISiloLifecycle>)this.manager).Participate(this.lifecycle); this.clusterHealthMonitor = new ClusterHealthMonitor( this.localSiloDetails, this.manager, this.loggerFactory.CreateLogger<ClusterHealthMonitor>(), this.clusterMembershipOptions, this.fatalErrorHandler, null, this.timerFactory); this.agent = new MembershipAgent( this.manager, this.clusterHealthMonitor, this.localSiloDetails, this.fatalErrorHandler, this.clusterMembershipOptions, this.loggerFactory.CreateLogger<MembershipAgent>(), this.timerFactory); ((ILifecycleParticipant<ISiloLifecycle>)this.agent).Participate(this.lifecycle); } [Fact] public async Task MembershipAgent_LifecycleStages_GracefulShutdown() { var levels = new ConcurrentDictionary<int, SiloStatus>(); Func<CancellationToken, Task> Callback(int level) => ct => { levels[level] = this.manager.CurrentStatus; return Task.CompletedTask; }; Func<CancellationToken, Task> NoOp = ct => Task.CompletedTask; foreach (var l in new[] { ServiceLifecycleStage.RuntimeInitialize, ServiceLifecycleStage.AfterRuntimeGrainServices, ServiceLifecycleStage.BecomeActive}) { // After start this.lifecycle.Subscribe( "x", l + 1, Callback(l + 1), NoOp); // After stop this.lifecycle.Subscribe( "x", l - 1, NoOp, Callback(l - 1)); } await this.lifecycle.OnStart(); Assert.Equal(SiloStatus.Created, levels[ServiceLifecycleStage.RuntimeInitialize + 1]); Assert.Equal(SiloStatus.Joining, levels[ServiceLifecycleStage.AfterRuntimeGrainServices + 1]); Assert.Equal(SiloStatus.Active, levels[ServiceLifecycleStage.BecomeActive + 1]); await StopLifecycle(); Assert.Equal(SiloStatus.ShuttingDown, levels[ServiceLifecycleStage.BecomeActive - 1]); Assert.Equal(SiloStatus.ShuttingDown, levels[ServiceLifecycleStage.AfterRuntimeGrainServices - 1]); Assert.Equal(SiloStatus.Dead, levels[ServiceLifecycleStage.RuntimeInitialize - 1]); } [Fact] public async Task MembershipAgent_LifecycleStages_UngracefulShutdown() { var levels = new ConcurrentDictionary<int, SiloStatus>(); Func<CancellationToken, Task> Callback(int level) => ct => { levels[level] = this.manager.CurrentStatus; return Task.CompletedTask; }; Func<CancellationToken, Task> NoOp = ct => Task.CompletedTask; foreach (var l in new[] { ServiceLifecycleStage.RuntimeInitialize, ServiceLifecycleStage.AfterRuntimeGrainServices, ServiceLifecycleStage.BecomeActive}) { // After start this.lifecycle.Subscribe( "x", l + 1, Callback(l + 1), NoOp); // After stop this.lifecycle.Subscribe( "x", l - 1, NoOp, Callback(l - 1)); } await this.lifecycle.OnStart(); Assert.Equal(SiloStatus.Created, levels[ServiceLifecycleStage.RuntimeInitialize + 1]); Assert.Equal(SiloStatus.Joining, levels[ServiceLifecycleStage.AfterRuntimeGrainServices + 1]); Assert.Equal(SiloStatus.Active, levels[ServiceLifecycleStage.BecomeActive + 1]); var cancellation = new CancellationTokenSource(); cancellation.Cancel(); await StopLifecycle(cancellation.Token); Assert.Equal(SiloStatus.Stopping, levels[ServiceLifecycleStage.BecomeActive - 1]); Assert.Equal(SiloStatus.Stopping, levels[ServiceLifecycleStage.AfterRuntimeGrainServices - 1]); Assert.Equal(SiloStatus.Dead, levels[ServiceLifecycleStage.RuntimeInitialize - 1]); } [Fact] public async Task MembershipAgent_UpdateIAmAlive() { await this.lifecycle.OnStart(); await Until(() => this.timerCalls.ContainsKey("UpdateIAmAlive")); var updateCounter = 0; var testAccessor = (MembershipAgent.ITestAccessor)this.agent; testAccessor.OnUpdateIAmAlive = () => ++updateCounter; (TimeSpan? DelayOverride, TaskCompletionSource<bool> Completion) timer = (default, default); while (!this.timerCalls["UpdateIAmAlive"].TryDequeue(out timer)) await Task.Delay(1); timer.Completion.TrySetResult(true); await Until(() => updateCounter == 1); testAccessor.OnUpdateIAmAlive = () => { ++updateCounter; throw new Exception("no"); }; while (!this.timerCalls["UpdateIAmAlive"].TryDequeue(out timer)) await Task.Delay(1); timer.Completion.TrySetResult(true); Assert.False(timer.DelayOverride.HasValue); await Until(() => updateCounter == 2); testAccessor.OnUpdateIAmAlive = () => ++updateCounter; while (!this.timerCalls["UpdateIAmAlive"].TryDequeue(out timer)) await Task.Delay(1); Assert.True(timer.DelayOverride.HasValue); timer.Completion.TrySetResult(true); await Until(() => updateCounter == 3); Assert.Equal(3, updateCounter); // When something goes horribly awry (eg, the timer throws an exception), the silo should fault. this.fatalErrorHandler.DidNotReceiveWithAnyArgs().OnFatalException(default, default, default); while (!this.timerCalls["UpdateIAmAlive"].TryDequeue(out timer)) await Task.Delay(1); timer.Completion.TrySetException(new Exception("no")); Assert.False(timer.DelayOverride.HasValue); await Until(() => this.fatalErrorHandler.ReceivedCalls().Any()); this.fatalErrorHandler.ReceivedWithAnyArgs().OnFatalException(default, default, default); // Stop & cancel all timers. await StopLifecycle(); } [Fact] public async Task MembershipAgent_LifecycleStages_ValidateInitialConnectivity_Success() { MessagingStatisticsGroup.Init(); var otherSilos = new[] { Entry(Silo("127.0.0.200:100@100"), SiloStatus.Active), Entry(Silo("127.0.0.200:200@100"), SiloStatus.Active), Entry(Silo("127.0.0.200:300@100"), SiloStatus.Active), Entry(Silo("127.0.0.200:400@100"), SiloStatus.Active), Entry(Silo("127.0.0.200:500@100"), SiloStatus.Active), Entry(Silo("127.0.0.200:600@100"), SiloStatus.Active), Entry(Silo("127.0.0.200:700@100"), SiloStatus.Active), Entry(Silo("127.0.0.200:800@100"), SiloStatus.Active), Entry(Silo("127.0.0.200:900@100"), SiloStatus.Active) }; // Add the new silos foreach (var entry in otherSilos) { var table = await this.membershipTable.ReadAll(); Assert.True(await this.membershipTable.InsertRow(entry, table.Version.Next())); } var prober = Substitute.For<IRemoteSiloProber>(); prober.Probe(default, default).ReturnsForAnyArgs(Task.CompletedTask); var clusterHealthMonitorTestAccessor = (ClusterHealthMonitor.ITestAccessor)this.clusterHealthMonitor; clusterHealthMonitorTestAccessor.CreateMonitor = silo => new SiloHealthMonitor(silo, this.loggerFactory, prober); var started = this.lifecycle.OnStart(); await Until(() => prober.ReceivedCalls().Count() < otherSilos.Length); await Until(() => started.IsCompleted); await started; await StopLifecycle(); } [Fact] public async Task MembershipAgent_LifecycleStages_ValidateInitialConnectivity_Failure() { MessagingStatisticsGroup.Init(); this.timerFactory.CreateDelegate = (period, name) => new DelegateAsyncTimer(_ => Task.FromResult(false)); var otherSilos = new[] { Entry(Silo("127.0.0.200:100@100"), SiloStatus.Active), Entry(Silo("127.0.0.200:200@100"), SiloStatus.Active), Entry(Silo("127.0.0.200:300@100"), SiloStatus.Active), Entry(Silo("127.0.0.200:400@100"), SiloStatus.Active), Entry(Silo("127.0.0.200:500@100"), SiloStatus.Active), Entry(Silo("127.0.0.200:600@100"), SiloStatus.Active), Entry(Silo("127.0.0.200:700@100"), SiloStatus.Active), Entry(Silo("127.0.0.200:800@100"), SiloStatus.Active), Entry(Silo("127.0.0.200:900@100"), SiloStatus.Active) }; // Add the new silos foreach (var entry in otherSilos) { var table = await this.membershipTable.ReadAll(); Assert.True(await this.membershipTable.InsertRow(entry, table.Version.Next())); } var prober = Substitute.For<IRemoteSiloProber>(); prober.Probe(default, default).ReturnsForAnyArgs(Task.FromException(new Exception("no"))); var dateTimeIndex = 0; var dateTimes = new DateTime[] { DateTime.UtcNow, DateTime.UtcNow.AddMinutes(8) }; var membershipAgentTestAccessor = ((MembershipAgent.ITestAccessor)this.agent).GetDateTime = () => dateTimes[dateTimeIndex++]; var clusterHealthMonitorTestAccessor = (ClusterHealthMonitor.ITestAccessor)this.clusterHealthMonitor; clusterHealthMonitorTestAccessor.CreateMonitor = silo => new SiloHealthMonitor(silo, this.loggerFactory, prober); var started = this.lifecycle.OnStart(); await Until(() => prober.ReceivedCalls().Count() < otherSilos.Length); await Until(() => started.IsCompleted); // Startup should have faulted. Assert.True(started.IsFaulted); await StopLifecycle(); } private static SiloAddress Silo(string value) => SiloAddress.FromParsableString(value); private static MembershipEntry Entry(SiloAddress address, SiloStatus status) => new MembershipEntry { SiloAddress = address, Status = status, StartTime = DateTime.UtcNow, IAmAliveTime = DateTime.UtcNow }; private static async Task Until(Func<bool> condition) { var maxTimeout = 40_000; while (!condition() && (maxTimeout -= 10) > 0) await Task.Delay(10); Assert.True(maxTimeout > 0); } private async Task StopLifecycle(CancellationToken cancellation = default) { var stopped = this.lifecycle.OnStop(cancellation); while (!stopped.IsCompleted) { foreach (var pair in this.timerCalls) while (pair.Value.TryDequeue(out var call)) call.Completion.TrySetResult(false); await Task.Delay(15); } await stopped; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime; using System.Runtime.CompilerServices; #if BIT64 using nuint = System.UInt64; #else using nuint = System.UInt32; #endif namespace System { /// <summary> /// Extension methods and non-generic helpers for Span and ReadOnlySpan /// </summary> public static class Span { /// <summary> /// Casts a Span of one primitive type <typeparamref name="T"/> to Span of bytes. /// That type may not contain pointers or references. This is checked at runtime in order to preserve type safety. /// </summary> /// <param name="source">The source slice, of type <typeparamref name="T"/>.</param> /// <exception cref="System.ArgumentException"> /// Thrown when <typeparamref name="T"/> contains pointers. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<byte> AsBytes<T>(this Span<T> source) where T : struct { if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); return new Span<byte>( ref Unsafe.As<T, byte>(ref source.DangerousGetPinnableReference()), checked(source.Length * Unsafe.SizeOf<T>())); } /// <summary> /// Casts a ReadOnlySpan of one primitive type <typeparamref name="T"/> to ReadOnlySpan of bytes. /// That type may not contain pointers or references. This is checked at runtime in order to preserve type safety. /// </summary> /// <param name="source">The source slice, of type <typeparamref name="T"/>.</param> /// <exception cref="System.ArgumentException"> /// Thrown when <typeparamref name="T"/> contains pointers. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan<byte> AsBytes<T>(this ReadOnlySpan<T> source) where T : struct { if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); return new ReadOnlySpan<byte>( ref Unsafe.As<T, byte>(ref source.DangerousGetPinnableReference()), checked(source.Length * Unsafe.SizeOf<T>())); } /// <summary> /// Casts a Span of one primitive type <typeparamref name="TFrom"/> to another primitive type <typeparamref name="TTo"/>. /// These types may not contain pointers or references. This is checked at runtime in order to preserve type safety. /// </summary> /// <remarks> /// Supported only for platforms that support misaligned memory access. /// </remarks> /// <param name="source">The source slice, of type <typeparamref name="TFrom"/>.</param> /// <exception cref="System.ArgumentException"> /// Thrown when <typeparamref name="TFrom"/> or <typeparamref name="TTo"/> contains pointers. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<TTo> NonPortableCast<TFrom, TTo>(this Span<TFrom> source) where TFrom : struct where TTo : struct { if (RuntimeHelpers.IsReferenceOrContainsReferences<TFrom>()) ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(TFrom)); if (RuntimeHelpers.IsReferenceOrContainsReferences<TTo>()) ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(TTo)); return new Span<TTo>( ref Unsafe.As<TFrom, TTo>(ref source.DangerousGetPinnableReference()), checked((int)((long)source.Length * Unsafe.SizeOf<TFrom>() / Unsafe.SizeOf<TTo>()))); } /// <summary> /// Casts a ReadOnlySpan of one primitive type <typeparamref name="TFrom"/> to another primitive type <typeparamref name="TTo"/>. /// These types may not contain pointers or references. This is checked at runtime in order to preserve type safety. /// </summary> /// <remarks> /// Supported only for platforms that support misaligned memory access. /// </remarks> /// <param name="source">The source slice, of type <typeparamref name="TFrom"/>.</param> /// <exception cref="System.ArgumentException"> /// Thrown when <typeparamref name="TFrom"/> or <typeparamref name="TTo"/> contains pointers. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan<TTo> NonPortableCast<TFrom, TTo>(this ReadOnlySpan<TFrom> source) where TFrom : struct where TTo : struct { if (RuntimeHelpers.IsReferenceOrContainsReferences<TFrom>()) ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(TFrom)); if (RuntimeHelpers.IsReferenceOrContainsReferences<TTo>()) ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(TTo)); return new ReadOnlySpan<TTo>( ref Unsafe.As<TFrom, TTo>(ref source.DangerousGetPinnableReference()), checked((int)((long)source.Length * Unsafe.SizeOf<TFrom>() / Unsafe.SizeOf<TTo>()))); } [Obsolete("This method is obsolete. Use AsReadOnlySpan instead.", false)] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan<char> AsSpan(this string text) => AsReadOnlySpan(text); /// <summary> /// Creates a new readonly span over the portion of the target string. /// </summary> /// <param name="text">The target string.</param> /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="text"/> is a null /// reference (Nothing in Visual Basic).</exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan<char> AsReadOnlySpan(this string text) { if (text == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text); return new ReadOnlySpan<char>(ref text.GetRawStringData(), text.Length); } internal static unsafe void CopyTo<T>(ref T destination, ref T source, int elementsCount) { if (Unsafe.AreSame(ref destination, ref source)) return; if (elementsCount <= 1) { if (elementsCount == 1) { destination = source; } return; } nuint byteCount = (nuint)elementsCount * (nuint)Unsafe.SizeOf<T>(); if (!RuntimeHelpers.IsReferenceOrContainsReferences<T>()) { fixed (byte* pDestination = &Unsafe.As<T, byte>(ref destination)) { fixed (byte* pSource = &Unsafe.As<T, byte>(ref source)) { Buffer.Memmove(pDestination, pSource, byteCount); } } } else { RuntimeImports.RhBulkMoveWithWriteBarrier( ref Unsafe.As<T, byte>(ref destination), ref Unsafe.As<T, byte>(ref source), byteCount); } } internal static unsafe void ClearWithoutReferences(ref byte b, nuint byteLength) { if (byteLength == 0) return; #if CORECLR && (AMD64 || ARM64) if (byteLength > 4096) goto PInvoke; Unsafe.InitBlockUnaligned(ref b, 0, (uint)byteLength); return; #else // TODO: Optimize other platforms to be on par with AMD64 CoreCLR // Note: It's important that this switch handles lengths at least up to 22. // See notes below near the main loop for why. // The switch will be very fast since it can be implemented using a jump // table in assembly. See http://stackoverflow.com/a/449297/4077294 for more info. switch (byteLength) { case 1: b = 0; return; case 2: Unsafe.As<byte, short>(ref b) = 0; return; case 3: Unsafe.As<byte, short>(ref b) = 0; Unsafe.Add<byte>(ref b, 2) = 0; return; case 4: Unsafe.As<byte, int>(ref b) = 0; return; case 5: Unsafe.As<byte, int>(ref b) = 0; Unsafe.Add<byte>(ref b, 4) = 0; return; case 6: Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 4)) = 0; return; case 7: Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 4)) = 0; Unsafe.Add<byte>(ref b, 6) = 0; return; case 8: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; #endif return; case 9: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; #endif Unsafe.Add<byte>(ref b, 8) = 0; return; case 10: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; #endif Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 8)) = 0; return; case 11: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; #endif Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.Add<byte>(ref b, 10) = 0; return; case 12: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; #endif Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; return; case 13: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; #endif Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.Add<byte>(ref b, 12) = 0; return; case 14: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; #endif Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 12)) = 0; return; case 15: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; #endif Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 12)) = 0; Unsafe.Add<byte>(ref b, 14) = 0; return; case 16: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0; #endif return; case 17: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0; #endif Unsafe.Add<byte>(ref b, 16) = 0; return; case 18: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0; #endif Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 16)) = 0; return; case 19: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0; #endif Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 16)) = 0; Unsafe.Add<byte>(ref b, 18) = 0; return; case 20: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0; #endif Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 16)) = 0; return; case 21: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0; #endif Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 16)) = 0; Unsafe.Add<byte>(ref b, 20) = 0; return; case 22: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0; #endif Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 16)) = 0; Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 20)) = 0; return; } // P/Invoke into the native version for large lengths if (byteLength >= 512) goto PInvoke; nuint i = 0; // byte offset at which we're copying if ((Unsafe.As<byte, int>(ref b) & 3) != 0) { if ((Unsafe.As<byte, int>(ref b) & 1) != 0) { Unsafe.AddByteOffset<byte>(ref b, i) = 0; i += 1; if ((Unsafe.As<byte, int>(ref b) & 2) != 0) goto IntAligned; } Unsafe.As<byte, short>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0; i += 2; } IntAligned: // On 64-bit IntPtr.Size == 8, so we want to advance to the next 8-aligned address. If // (int)b % 8 is 0, 5, 6, or 7, we will already have advanced by 0, 3, 2, or 1 // bytes to the next aligned address (respectively), so do nothing. On the other hand, // if it is 1, 2, 3, or 4 we will want to copy-and-advance another 4 bytes until // we're aligned. // The thing 1, 2, 3, and 4 have in common that the others don't is that if you // subtract one from them, their 3rd lsb will not be set. Hence, the below check. if (((Unsafe.As<byte, int>(ref b) - 1) & 4) == 0) { Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0; i += 4; } nuint end = byteLength - 16; byteLength -= i; // lower 4 bits of byteLength represent how many bytes are left *after* the unrolled loop // We know due to the above switch-case that this loop will always run 1 iteration; max // bytes we clear before checking is 23 (7 to align the pointers, 16 for 1 iteration) so // the switch handles lengths 0-22. Debug.Assert(end >= 7 && i <= end); // This is separated out into a different variable, so the i + 16 addition can be // performed at the start of the pipeline and the loop condition does not have // a dependency on the writes. nuint counter; do { counter = i + 16; // This loop looks very costly since there appear to be a bunch of temporary values // being created with the adds, but the jit (for x86 anyways) will convert each of // these to use memory addressing operands. // So the only cost is a bit of code size, which is made up for by the fact that // we save on writes to b. #if BIT64 Unsafe.As<byte, long>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0; Unsafe.As<byte, long>(ref Unsafe.AddByteOffset<byte>(ref b, i + 8)) = 0; #else Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0; Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i + 4)) = 0; Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i + 8)) = 0; Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i + 12)) = 0; #endif i = counter; // See notes above for why this wasn't used instead // i += 16; } while (counter <= end); if ((byteLength & 8) != 0) { #if BIT64 Unsafe.As<byte, long>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0; #else Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0; Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i + 4)) = 0; #endif i += 8; } if ((byteLength & 4) != 0) { Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0; i += 4; } if ((byteLength & 2) != 0) { Unsafe.As<byte, short>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0; i += 2; } if ((byteLength & 1) != 0) { Unsafe.AddByteOffset<byte>(ref b, i) = 0; // We're not using i after this, so not needed // i += 1; } return; #endif PInvoke: RuntimeImports.RhZeroMemory(ref b, byteLength); } internal static unsafe void ClearWithReferences(ref IntPtr ip, nuint pointerSizeLength) { if (pointerSizeLength == 0) return; // TODO: Perhaps do switch casing to improve small size perf nuint i = 0; nuint n = 0; while ((n = i + 8) <= (pointerSizeLength)) { Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 0) * (nuint)sizeof(IntPtr)) = default(IntPtr); Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 1) * (nuint)sizeof(IntPtr)) = default(IntPtr); Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 2) * (nuint)sizeof(IntPtr)) = default(IntPtr); Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 3) * (nuint)sizeof(IntPtr)) = default(IntPtr); Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 4) * (nuint)sizeof(IntPtr)) = default(IntPtr); Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 5) * (nuint)sizeof(IntPtr)) = default(IntPtr); Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 6) * (nuint)sizeof(IntPtr)) = default(IntPtr); Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 7) * (nuint)sizeof(IntPtr)) = default(IntPtr); i = n; } if ((n = i + 4) <= (pointerSizeLength)) { Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 0) * (nuint)sizeof(IntPtr)) = default(IntPtr); Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 1) * (nuint)sizeof(IntPtr)) = default(IntPtr); Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 2) * (nuint)sizeof(IntPtr)) = default(IntPtr); Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 3) * (nuint)sizeof(IntPtr)) = default(IntPtr); i = n; } if ((n = i + 2) <= (pointerSizeLength)) { Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 0) * (nuint)sizeof(IntPtr)) = default(IntPtr); Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 1) * (nuint)sizeof(IntPtr)) = default(IntPtr); i = n; } if ((i + 1) <= (pointerSizeLength)) { Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 0) * (nuint)sizeof(IntPtr)) = default(IntPtr); } } } }
// // SubSonic - http://subsonicproject.com // // The contents of this file are subject to the New BSD // License (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.opensource.org/licenses/bsd-license.php // // Software distributed under the License is distributed on an // "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or // implied. See the License for the specific language governing // rights and limitations under the License. // using System; namespace SubSonic.Extensions { /// <summary> /// Summary for the Dates class /// </summary> public static class Dates { public const string AGO = "ago"; public const string DAY = "day"; public const string HOUR = "hour"; public const string MINUTE = "minute"; public const string MONTH = "month"; public const string SECOND = "second"; public const string SPACE = " "; public const string YEAR = "year"; #region Date Math /// <summary> /// Returns a date in the past by days. /// </summary> /// <param name="days">The days.</param> /// <returns></returns> public static DateTime DaysAgo(this int days) { TimeSpan t = new TimeSpan(days, 0, 0, 0); return DateTime.Now.Subtract(t); } /// <summary> /// Returns a date in the future by days. /// </summary> /// <param name="days">The days.</param> /// <returns></returns> public static DateTime DaysFromNow(this int days) { TimeSpan t = new TimeSpan(days, 0, 0, 0); return DateTime.Now.Add(t); } /// <summary> /// Returns a date in the past by hours. /// </summary> /// <param name="hours">The hours.</param> /// <returns></returns> public static DateTime HoursAgo(this int hours) { TimeSpan t = new TimeSpan(hours, 0, 0); return DateTime.Now.Subtract(t); } /// <summary> /// Returns a date in the future by hours. /// </summary> /// <param name="hours">The hours.</param> /// <returns></returns> public static DateTime HoursFromNow(this int hours) { TimeSpan t = new TimeSpan(hours, 0, 0); return DateTime.Now.Add(t); } /// <summary> /// Returns a date in the past by minutes /// </summary> /// <param name="minutes">The minutes.</param> /// <returns></returns> public static DateTime MinutesAgo(this int minutes) { TimeSpan t = new TimeSpan(0, minutes, 0); return DateTime.Now.Subtract(t); } /// <summary> /// Returns a date in the future by minutes. /// </summary> /// <param name="minutes">The minutes.</param> /// <returns></returns> public static DateTime MinutesFromNow(this int minutes) { TimeSpan t = new TimeSpan(0, minutes, 0); return DateTime.Now.Add(t); } /// <summary> /// Gets a date in the past according to seconds /// </summary> /// <param name="seconds">The seconds.</param> /// <returns></returns> public static DateTime SecondsAgo(this int seconds) { TimeSpan t = new TimeSpan(0, 0, seconds); return DateTime.Now.Subtract(t); } /// <summary> /// Gets a date in the future by seconds. /// </summary> /// <param name="seconds">The seconds.</param> /// <returns></returns> public static DateTime SecondsFromNow(this int seconds) { TimeSpan t = new TimeSpan(0, 0, seconds); return DateTime.Now.Add(t); } #endregion #region Diffs /// <summary> /// Diffs the specified date. /// </summary> /// <param name="dateOne">The date one.</param> /// <param name="dateTwo">The date two.</param> /// <returns></returns> public static TimeSpan Diff(this DateTime dateOne, DateTime dateTwo) { TimeSpan t = dateOne.Subtract(dateTwo); return t; } /// <summary> /// Returns a double indicating the number of days between two dates (past is negative) /// </summary> /// <param name="dateOne">The date one.</param> /// <param name="dateTwo">The date two.</param> /// <returns></returns> public static double DiffDays(this string dateOne, string dateTwo) { DateTime dtOne; DateTime dtTwo; if(DateTime.TryParse(dateOne, out dtOne) && DateTime.TryParse(dateTwo, out dtTwo)) return Diff(dtOne, dtTwo).TotalDays; return 0; } /// <summary> /// Returns a double indicating the number of days between two dates (past is negative) /// </summary> /// <param name="dateOne">The date one.</param> /// <param name="dateTwo">The date two.</param> /// <returns></returns> public static double DiffDays(this DateTime dateOne, DateTime dateTwo) { return Diff(dateOne, dateTwo).TotalDays; } /// <summary> /// Returns a double indicating the number of days between two dates (past is negative) /// </summary> /// <param name="dateOne">The date one.</param> /// <param name="dateTwo">The date two.</param> /// <returns></returns> public static double DiffHours(this string dateOne, string dateTwo) { DateTime dtOne; DateTime dtTwo; if(DateTime.TryParse(dateOne, out dtOne) && DateTime.TryParse(dateTwo, out dtTwo)) return Diff(dtOne, dtTwo).TotalHours; return 0; } /// <summary> /// Returns a double indicating the number of days between two dates (past is negative) /// </summary> /// <param name="dateOne">The date one.</param> /// <param name="dateTwo">The date two.</param> /// <returns></returns> public static double DiffHours(this DateTime dateOne, DateTime dateTwo) { return Diff(dateOne, dateTwo).TotalHours; } /// <summary> /// Returns a double indicating the number of days between two dates (past is negative) /// </summary> /// <param name="dateOne">The date one.</param> /// <param name="dateTwo">The date two.</param> /// <returns></returns> public static double DiffMinutes(this string dateOne, string dateTwo) { DateTime dtOne; DateTime dtTwo; if(DateTime.TryParse(dateOne, out dtOne) && DateTime.TryParse(dateTwo, out dtTwo)) return Diff(dtOne, dtTwo).TotalMinutes; return 0; } /// <summary> /// Returns a double indicating the number of days between two dates (past is negative) /// </summary> /// <param name="dateOne">The date one.</param> /// <param name="dateTwo">The date two.</param> /// <returns></returns> public static double DiffMinutes(this DateTime dateOne, DateTime dateTwo) { return Diff(dateOne, dateTwo).TotalMinutes; } /// <summary> /// Displays the difference in time between the two dates. Return example is "12 years 4 months 24 days 8 hours 33 minutes 5 seconds" /// </summary> /// <param name="startTime">The start time.</param> /// <param name="endTime">The end time.</param> /// <returns></returns> public static string ReadableDiff(this DateTime startTime, DateTime endTime) { string result; int seconds = endTime.Second - startTime.Second; int minutes = endTime.Minute - startTime.Minute; int hours = endTime.Hour - startTime.Hour; int days = endTime.Day - startTime.Day; int months = endTime.Month - startTime.Month; int years = endTime.Year - startTime.Year; if(seconds < 0) { minutes--; seconds += 60; } if(minutes < 0) { hours--; minutes += 60; } if(hours < 0) { days--; hours += 24; } if(days < 0) { months--; int previousMonth = (endTime.Month == 1) ? 12 : endTime.Month - 1; int year = (previousMonth == 12) ? endTime.Year - 1 : endTime.Year; days += DateTime.DaysInMonth(year, previousMonth); } if(months < 0) { years--; months += 12; } //put this in a readable format if(years > 0) { result = years.Pluralize(YEAR); if(months != 0) result += ", " + months.Pluralize(MONTH); result += " ago"; } else if(months > 0) { result = months.Pluralize(MONTH); if(days != 0) result += ", " + days.Pluralize(DAY); result += " ago"; } else if(days > 0) { result = days.Pluralize(DAY); if(hours != 0) result += ", " + hours.Pluralize(HOUR); result += " ago"; } else if(hours > 0) { result = hours.Pluralize(HOUR); if(minutes != 0) result += ", " + minutes.Pluralize(MINUTE); result += " ago"; } else if(minutes > 0) result = minutes.Pluralize(MINUTE) + " ago"; else result = seconds.Pluralize(SECOND) + " ago"; return result; } #endregion // many thanks to ASP Alliance for the code below // http://authors.aspalliance.com/olson/methods/ /// <summary> /// Counts the number of weekdays between two dates. /// </summary> /// <param name="startTime">The start time.</param> /// <param name="endTime">The end time.</param> /// <returns></returns> public static int CountWeekdays(this DateTime startTime, DateTime endTime) { TimeSpan ts = endTime - startTime; Console.WriteLine(ts.Days); int cnt = 0; for(int i = 0; i < ts.Days; i++) { DateTime dt = startTime.AddDays(i); if(IsWeekDay(dt)) cnt++; } return cnt; } /// <summary> /// Counts the number of weekends between two dates. /// </summary> /// <param name="startTime">The start time.</param> /// <param name="endTime">The end time.</param> /// <returns></returns> public static int CountWeekends(this DateTime startTime, DateTime endTime) { TimeSpan ts = endTime - startTime; Console.WriteLine(ts.Days); int cnt = 0; for(int i = 0; i < ts.Days; i++) { DateTime dt = startTime.AddDays(i); if(IsWeekEnd(dt)) cnt++; } return cnt; } /// <summary> /// Verifies if the object is a date /// </summary> /// <param name="dt">The dt.</param> /// <returns> /// <c>true</c> if the specified dt is date; otherwise, <c>false</c>. /// </returns> public static bool IsDate(this object dt) { DateTime newDate; return DateTime.TryParse(dt.ToString(), out newDate); } /// <summary> /// Checks to see if the date is a week day (Mon - Fri) /// </summary> /// <param name="dt">The dt.</param> /// <returns> /// <c>true</c> if [is week day] [the specified dt]; otherwise, <c>false</c>. /// </returns> public static bool IsWeekDay(this DateTime dt) { return (dt.DayOfWeek != DayOfWeek.Saturday && dt.DayOfWeek != DayOfWeek.Sunday); } /// <summary> /// Checks to see if the date is Saturday or Sunday /// </summary> /// <param name="dt">The dt.</param> /// <returns> /// <c>true</c> if [is week end] [the specified dt]; otherwise, <c>false</c>. /// </returns> public static bool IsWeekEnd(this DateTime dt) { return (dt.DayOfWeek == DayOfWeek.Saturday || dt.DayOfWeek == DayOfWeek.Sunday); } /// <summary> /// Displays the difference in time between the two dates. Return example is "12 years 4 months 24 days 8 hours 33 minutes 5 seconds" /// </summary> /// <param name="startTime">The start time.</param> /// <param name="endTime">The end time.</param> /// <returns></returns> public static string TimeDiff(this DateTime startTime, DateTime endTime) { int seconds = endTime.Second - startTime.Second; int minutes = endTime.Minute - startTime.Minute; int hours = endTime.Hour - startTime.Hour; int days = endTime.Day - startTime.Day; int months = endTime.Month - startTime.Month; int years = endTime.Year - startTime.Year; if(seconds < 0) { minutes--; seconds += 60; } if(minutes < 0) { hours--; minutes += 60; } if(hours < 0) { days--; hours += 24; } if(days < 0) { months--; int previousMonth = (endTime.Month == 1) ? 12 : endTime.Month - 1; int year = (previousMonth == 12) ? endTime.Year - 1 : endTime.Year; days += DateTime.DaysInMonth(year, previousMonth); } if(months < 0) { years--; months += 12; } string sYears = FormatString(YEAR, String.Empty, years); string sMonths = FormatString(MONTH, sYears, months); string sDays = FormatString(DAY, sMonths, days); string sHours = FormatString(HOUR, sDays, hours); string sMinutes = FormatString(MINUTE, sHours, minutes); string sSeconds = FormatString(SECOND, sMinutes, seconds); return String.Concat(sYears, sMonths, sDays, sHours, sMinutes, sSeconds); } /// <summary> /// Given a datetime object, returns the formatted month and day, i.e. "April 15th" /// </summary> /// <param name="date">The date to extract the string from</param> /// <returns></returns> public static string GetFormattedMonthAndDay(this DateTime date) { return String.Concat(String.Format("{0:MMMM}", date), " ", GetDateDayWithSuffix(date)); } /// <summary> /// Given a datetime object, returns the formatted day, "15th" /// </summary> /// <param name="date">The date to extract the string from</param> /// <returns></returns> public static string GetDateDayWithSuffix(this DateTime date) { int dayNumber = date.Day; string suffix = "th"; if(dayNumber == 1 || dayNumber == 21 || dayNumber == 31) suffix = "st"; else if(dayNumber == 2 || dayNumber == 22) suffix = "nd"; else if(dayNumber == 3 || dayNumber == 23) suffix = "rd"; return String.Concat(dayNumber, suffix); } /// <summary> /// Remove leading strings with zeros and adjust for singular/plural /// </summary> /// <param name="str">The STR.</param> /// <param name="previousStr">The previous STR.</param> /// <param name="t">The t.</param> /// <returns></returns> private static string FormatString(this string str, string previousStr, int t) { if((t == 0) && (previousStr.Length == 0)) return String.Empty; string suffix = (t == 1) ? String.Empty : "s"; return String.Concat(t, SPACE, str, suffix, SPACE); } } }
// $ANTLR 2.7.5 (20050128): "CppHeader.g" -> "CppHeader.cs"$ using antlr; // Generate header specific to lexer CSharp file using System; using Stream = System.IO.Stream; using TextReader = System.IO.TextReader; using Hashtable = System.Collections.Hashtable; using Comparer = System.Collections.Comparer; using TokenStreamException = antlr.TokenStreamException; using TokenStreamIOException = antlr.TokenStreamIOException; using TokenStreamRecognitionException = antlr.TokenStreamRecognitionException; using CharStreamException = antlr.CharStreamException; using CharStreamIOException = antlr.CharStreamIOException; using ANTLRException = antlr.ANTLRException; using CharScanner = antlr.CharScanner; using InputBuffer = antlr.InputBuffer; using ByteBuffer = antlr.ByteBuffer; using CharBuffer = antlr.CharBuffer; using Token = antlr.Token; using IToken = antlr.IToken; using CommonToken = antlr.CommonToken; using SemanticException = antlr.SemanticException; using RecognitionException = antlr.RecognitionException; using NoViableAltForCharException = antlr.NoViableAltForCharException; using MismatchedCharException = antlr.MismatchedCharException; using TokenStream = antlr.TokenStream; using LexerSharedInputState = antlr.LexerSharedInputState; using BitSet = antlr.collections.impl.BitSet; public class CppHeader : antlr.CharScanner , TokenStream { public const int EOF = 1; public const int NULL_TREE_LOOKAHEAD = 3; public const int NULL_NODE = 4; public const int PROG_LIST = 5; public const int FUNC = 6; public const int STRUCT = 7; public const int STRUCTLIST = 8; public const int GLOBA = 9; public const int GLOBD = 10; public const int DECLA = 11; public const int FUNC_HEAD = 12; public const int FUNC_APP = 13; public const int FORMAL_LIST = 14; public const int DECL = 15; public const int ARRAY_DEF = 16; public const int TYPE_DEF = 17; public const int VAR = 18; public const int VAL_INTEGER = 19; public const int ABS = 20; public const int SQRT = 21; public const int ROOT = 22; public const int BLOCK = 23; public const int IDENT = 24; public const int LPAREN = 25; public const int RPAREN = 26; public const int LITERAL_abs = 27; public const int LITERAL_sqrt = 28; public const int LITERAL_root = 29; public const int COMMA = 30; public const int MINUS = 31; public const int POWER = 32; public const int TIMES = 33; public const int DIVIDE = 34; public const int MOD = 35; public const int PLUS = 36; public const int LITERAL_class = 37; public const int SEMICOLON = 38; public const int ICON = 39; public const int WS_ = 40; public const int ESC = 41; public const int CHCON = 42; public const int STCON = 43; public const int LBRACKET = 44; public const int RBRACKET = 45; public const int LCURL = 46; public const int RCURL = 47; public const int DOT = 48; public const int ASSIGN = 49; public const int EQ = 50; public const int NEQ = 51; public const int LTHAN = 52; public const int GTHAN = 53; public const int LEQ = 54; public const int GEQ = 55; public const int SHIFT_LEFT = 56; public const int SHIFT_RIGHT = 57; public CppHeader(Stream ins) : this(new ByteBuffer(ins)) { } public CppHeader(TextReader r) : this(new CharBuffer(r)) { } public CppHeader(InputBuffer ib) : this(new LexerSharedInputState(ib)) { } public CppHeader(LexerSharedInputState state) : base(state) { initialize(); } private void initialize() { caseSensitiveLiterals = true; setCaseSensitive(true); literals = new Hashtable(100, (float) 0.4, null, Comparer.Default); literals.Add("sqrt", 28); literals.Add("class", 37); literals.Add("abs", 27); literals.Add("root", 29); } override public IToken nextToken() //throws TokenStreamException { IToken theRetToken = null; tryAgain: for (;;) { IToken _token = null; int _ttype = Token.INVALID_TYPE; resetText(); try // for char stream error handling { try // for lexical error handling { switch ( cached_LA1 ) { case '\t': case '\n': case '\r': case ' ': { mWS_(true); theRetToken = returnToken_; break; } case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': { mIDENT(true); theRetToken = returnToken_; break; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { mICON(true); theRetToken = returnToken_; break; } case '\\': { mESC(true); theRetToken = returnToken_; break; } case '\'': { mCHCON(true); theRetToken = returnToken_; break; } case '"': { mSTCON(true); theRetToken = returnToken_; break; } case ',': { mCOMMA(true); theRetToken = returnToken_; break; } case ';': { mSEMICOLON(true); theRetToken = returnToken_; break; } case '(': { mLPAREN(true); theRetToken = returnToken_; break; } case '[': { mLBRACKET(true); theRetToken = returnToken_; break; } case ']': { mRBRACKET(true); theRetToken = returnToken_; break; } case ')': { mRPAREN(true); theRetToken = returnToken_; break; } case '{': { mLCURL(true); theRetToken = returnToken_; break; } case '}': { mRCURL(true); theRetToken = returnToken_; break; } case '+': { mPLUS(true); theRetToken = returnToken_; break; } case '-': { mMINUS(true); theRetToken = returnToken_; break; } case '*': { mTIMES(true); theRetToken = returnToken_; break; } case '.': { mDOT(true); theRetToken = returnToken_; break; } case '/': { mDIVIDE(true); theRetToken = returnToken_; break; } case '%': { mMOD(true); theRetToken = returnToken_; break; } case '^': { mPOWER(true); theRetToken = returnToken_; break; } case '!': { mNEQ(true); theRetToken = returnToken_; break; } default: if ((cached_LA1=='=') && (cached_LA2=='=')) { mEQ(true); theRetToken = returnToken_; } else if ((cached_LA1=='<') && (cached_LA2=='=')) { mLEQ(true); theRetToken = returnToken_; } else if ((cached_LA1=='>') && (cached_LA2=='=')) { mGEQ(true); theRetToken = returnToken_; } else if ((cached_LA1=='<') && (cached_LA2=='<')) { mSHIFT_LEFT(true); theRetToken = returnToken_; } else if ((cached_LA1=='>') && (cached_LA2=='>')) { mSHIFT_RIGHT(true); theRetToken = returnToken_; } else if ((cached_LA1=='=') && (true)) { mASSIGN(true); theRetToken = returnToken_; } else if ((cached_LA1=='<') && (true)) { mLTHAN(true); theRetToken = returnToken_; } else if ((cached_LA1=='>') && (true)) { mGTHAN(true); theRetToken = returnToken_; } else { if (cached_LA1==EOF_CHAR) { uponEOF(); returnToken_ = makeToken(Token.EOF_TYPE); } else {throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());} } break; } if ( null==returnToken_ ) goto tryAgain; // found SKIP token _ttype = returnToken_.Type; _ttype = testLiteralsTable(_ttype); returnToken_.Type = _ttype; return returnToken_; } catch (RecognitionException e) { throw new TokenStreamRecognitionException(e); } } catch (CharStreamException cse) { if ( cse is CharStreamIOException ) { throw new TokenStreamIOException(((CharStreamIOException)cse).io); } else { throw new TokenStreamException(cse.Message); } } } } public void mWS_(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = WS_; { switch ( cached_LA1 ) { case ' ': { match(' '); break; } case '\t': { match('\t'); break; } case '\n': { match('\n'); newline(); break; } case '\r': { match('\r'); break; } default: { throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); } } } _ttype = Token.SKIP; if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mIDENT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = IDENT; { switch ( cached_LA1 ) { case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': { matchRange('a','z'); break; } case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': { matchRange('A','Z'); break; } case '_': { match('_'); break; } default: { throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); } } } { // ( ... )* for (;;) { switch ( cached_LA1 ) { case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': { { switch ( cached_LA1 ) { case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': { matchRange('a','z'); break; } case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': { matchRange('A','Z'); break; } case '_': { match('_'); break; } default: { throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); } } } break; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { { matchRange('0','9'); } break; } default: { goto _loop40_breakloop; } } } _loop40_breakloop: ; } // ( ... )* if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mICON(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = ICON; matchRange('0','9'); { // ( ... )* for (;;) { if (((cached_LA1 >= '0' && cached_LA1 <= '9'))) { matchRange('0','9'); } else { goto _loop43_breakloop; } } _loop43_breakloop: ; } // ( ... )* if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mESC(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = ESC; match('\\'); { switch ( cached_LA1 ) { case 'n': { match('n'); break; } case 'r': { match('r'); break; } case 't': { match('t'); break; } case 'b': { match('b'); break; } case 'f': { match('f'); break; } case '"': { match('"'); break; } case '\'': { match('\''); break; } case '\\': { match('\\'); break; } default: { throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); } } } if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mCHCON(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = CHCON; int _saveIndex = 0; _saveIndex = text.Length; match("'"); text.Length = _saveIndex; { switch ( cached_LA1 ) { case '\\': { mESC(false); break; } case '\u0000': case '\u0001': case '\u0002': case '\u0003': case '\u0004': case '\u0005': case '\u0006': case '\u0007': case '\u0008': case '\t': case '\n': case '\u000b': case '\u000c': case '\r': case '\u000e': case '\u000f': case '\u0010': case '\u0011': case '\u0012': case '\u0013': case '\u0014': case '\u0015': case '\u0016': case '\u0017': case '\u0018': case '\u0019': case '\u001a': case '\u001b': case '\u001c': case '\u001d': case '\u001e': case '\u001f': case ' ': case '!': case '"': case '#': case '$': case '%': case '&': case '(': case ')': case '*': case '+': case ',': case '-': case '.': case '/': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case ':': case ';': case '<': case '=': case '>': case '?': case '@': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '[': case ']': case '^': case '_': case '`': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case '{': case '|': case '}': case '~': case '\u007f': { matchNot('\''); break; } default: { throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); } } } _saveIndex = text.Length; match("'"); text.Length = _saveIndex; if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mSTCON(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = STCON; match('"'); { // ( ... )* for (;;) { switch ( cached_LA1 ) { case '\\': { mESC(false); break; } case '\u0000': case '\u0001': case '\u0002': case '\u0003': case '\u0004': case '\u0005': case '\u0006': case '\u0007': case '\u0008': case '\t': case '\n': case '\u000b': case '\u000c': case '\r': case '\u000e': case '\u000f': case '\u0010': case '\u0011': case '\u0012': case '\u0013': case '\u0014': case '\u0015': case '\u0016': case '\u0017': case '\u0018': case '\u0019': case '\u001a': case '\u001b': case '\u001c': case '\u001d': case '\u001e': case '\u001f': case ' ': case '!': case '#': case '$': case '%': case '&': case '\'': case '(': case ')': case '*': case '+': case ',': case '-': case '.': case '/': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case ':': case ';': case '<': case '=': case '>': case '?': case '@': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '[': case ']': case '^': case '_': case '`': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case '{': case '|': case '}': case '~': case '\u007f': { matchNot('"'); break; } default: { goto _loop50_breakloop; } } } _loop50_breakloop: ; } // ( ... )* match('"'); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mCOMMA(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = COMMA; match(','); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mSEMICOLON(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = SEMICOLON; match(';'); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mLPAREN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = LPAREN; match('('); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mLBRACKET(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = LBRACKET; match('['); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mRBRACKET(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = RBRACKET; match(']'); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mRPAREN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = RPAREN; match(')'); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mLCURL(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = LCURL; match('{'); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mRCURL(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = RCURL; match('}'); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mPLUS(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = PLUS; match('+'); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mMINUS(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = MINUS; match('-'); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mTIMES(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = TIMES; match('*'); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mDOT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = DOT; match('.'); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mDIVIDE(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = DIVIDE; match('/'); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mMOD(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = MOD; match('%'); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mPOWER(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = POWER; match('^'); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mASSIGN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = ASSIGN; match('='); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mEQ(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = EQ; match("=="); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mNEQ(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = NEQ; match("!="); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mLTHAN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = LTHAN; match('<'); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mGTHAN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = GTHAN; match('>'); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mLEQ(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = LEQ; match("<="); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mGEQ(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = GEQ; match(">="); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mSHIFT_LEFT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = SHIFT_LEFT; match("<<"); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mSHIFT_RIGHT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = SHIFT_RIGHT; match(">>"); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } }
#region Header // // Copyright 2003-2019 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // #endregion // Header using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Xml; using System.Windows.Forms; using Autodesk.Revit.DB; using RevitLookup.ModelStats; namespace RevitLookup.ModelStats { /// <summary> /// Summary description for Report. /// </summary> public class Report { // data members private ArrayList m_rawObjCounts = new ArrayList(); private ArrayList m_categoryCounts = new ArrayList(); private ArrayList m_symRefCounts = new ArrayList(); public Report() { } /// <summary> /// Find a RawObjCount node for the the given type of object. /// </summary> /// <param name="obj"></param> /// <returns></returns> private RawObjCount FindRawObjNode( System.Type objType ) { foreach( RawObjCount tmpNode in m_rawObjCounts ) { if( tmpNode.m_classType == objType ) return tmpNode; } return null; } private void RawObjStats( System.Object obj ) { RawObjCount tmpNode = FindRawObjNode( obj.GetType() ); if( tmpNode == null ) { tmpNode = new RawObjCount(); tmpNode.m_classType = obj.GetType(); m_rawObjCounts.Add( tmpNode ); } tmpNode.m_objs.Add( obj ); } private CategoryCount FindCategoryNode( Category cat ) { Debug.Assert( cat != null ); // don't call unless you've already checked this foreach( CategoryCount tmpNode in m_categoryCounts ) { if( tmpNode.m_category == cat ) return tmpNode; } return null; } private void CategoryStats( Element elem ) { if( elem.Category == null ) // some elements don't belong to a category return; CategoryCount tmpNode = FindCategoryNode( elem.Category ); if( tmpNode == null ) { tmpNode = new CategoryCount(); tmpNode.m_category = elem.Category; m_categoryCounts.Add( tmpNode ); } tmpNode.m_objs.Add( elem ); } private SymbolCount FindSymbolNode( ElementType sym ) { foreach( SymbolCount tmpNode in m_symRefCounts ) { if( tmpNode.m_symbol.Id.IntegerValue == sym.Id.IntegerValue ) // TBD: directly comparing Symbol objects doesn't work return tmpNode; } return null; } private ElementType GetSymbolRef( Element elem ) { FamilyInstance famInst = elem as FamilyInstance; if( famInst != null ) return famInst.Symbol; Floor floor = elem as Floor; if( floor != null ) return floor.FloorType; Group group = elem as Group; if( group != null ) return group.GroupType; Wall wall = elem as Wall; if( wall != null ) return wall.WallType; return null; // nothing we know about } private void SymbolRefStats( Element elem ) { // if it is a Symbol element, just make an entry in our map // and get out. ElementType sym = elem as ElementType; if( sym != null ) { SymbolCount tmpNode = FindSymbolNode( sym ); if( tmpNode == null ) { tmpNode = new SymbolCount(); tmpNode.m_symbol = sym; m_symRefCounts.Add( tmpNode ); } return; } // it isn't a Symbol, so we need to check if it is something that // references a Symbol. sym = GetSymbolRef( elem ); if( sym != null ) { SymbolCount tmpNode = FindSymbolNode( sym ); if( tmpNode == null ) { tmpNode = new SymbolCount(); tmpNode.m_symbol = sym; m_symRefCounts.Add( tmpNode ); } tmpNode.m_refs.Add( elem ); } } private void ProcessElements( Document doc ) { FilteredElementCollector fec = new FilteredElementCollector( doc ); ElementClassFilter elementsAreWanted = new ElementClassFilter( typeof( Element ) ); fec.WherePasses( elementsAreWanted ); List<Element> elements = fec.ToElements() as List<Element>; foreach( Element element in elements ) { RawObjStats( element ); if( element != null ) { SymbolRefStats( element ); CategoryStats( element ); } } } /// <summary> /// Create the XML Report for this document /// </summary> /// <param name="reportPath"></param> /// <param name="elemIter"></param> public void XmlReport( string reportPath, Document doc ) { ProcessElements( doc ); // index all of the elements XmlTextWriter stream = new XmlTextWriter( reportPath, System.Text.Encoding.UTF8 ); stream.Formatting = Formatting.Indented; stream.IndentChar = '\t'; stream.Indentation = 1; stream.WriteStartDocument(); stream.WriteStartElement( "Project" ); stream.WriteAttributeString( "title", doc.Title ); stream.WriteAttributeString( "path", doc.PathName ); XmlReportRawCounts( stream ); XmlReportCategoryCounts( stream ); XmlReportSymbolRefCounts( stream ); stream.WriteEndElement(); // "Project" stream.WriteEndDocument(); stream.Close(); } private void XmlReportRawCounts( XmlTextWriter stream ) { stream.WriteStartElement( "RawCounts" ); foreach( RawObjCount tmpNode in m_rawObjCounts ) { // write summary stats for this class type stream.WriteStartElement( "ClassType" ); stream.WriteAttributeString( "name", tmpNode.m_classType.Name ); stream.WriteAttributeString( "fullName", tmpNode.m_classType.FullName ); stream.WriteAttributeString( "count", tmpNode.m_objs.Count.ToString() ); // list a reference to each element of this type foreach( System.Object tmpObj in tmpNode.m_objs ) { Element tmpElem = tmpObj as Element; if( tmpElem != null ) { stream.WriteStartElement( "ElementRef" ); stream.WriteAttributeString( "idRef", tmpElem.Id.IntegerValue.ToString() ); stream.WriteEndElement(); // ElementRef } } stream.WriteEndElement(); // ClassType } stream.WriteEndElement(); // RawCounts } private void XmlReportCategoryCounts( XmlTextWriter stream ) { stream.WriteStartElement( "Categories" ); foreach( CategoryCount tmpNode in m_categoryCounts ) { // write summary stats for this category stream.WriteStartElement( "Category" ); stream.WriteAttributeString( "name", tmpNode.m_category.Name ); stream.WriteAttributeString( "count", tmpNode.m_objs.Count.ToString() ); // list a reference to each element of this type foreach( Element tmpElem in tmpNode.m_objs ) { stream.WriteStartElement( "ElementRef" ); stream.WriteAttributeString( "idRef", tmpElem.Id.IntegerValue.ToString() ); stream.WriteEndElement(); // ElementRef } stream.WriteEndElement(); // Category } stream.WriteEndElement(); // Categories } private void XmlReportSymbolRefCounts( XmlTextWriter stream ) { stream.WriteStartElement( "Symbols" ); foreach( SymbolCount tmpNode in m_symRefCounts ) { // write summary stats for this Symbol stream.WriteStartElement( "Symbol" ); stream.WriteAttributeString( "name", tmpNode.m_symbol.Name ); stream.WriteAttributeString( "symbolType", tmpNode.m_symbol.GetType().Name ); stream.WriteAttributeString( "refCount", tmpNode.m_refs.Count.ToString() ); // list a reference to each element of this type foreach( Element tmpElem in tmpNode.m_refs ) { stream.WriteStartElement( "ElementRef" ); stream.WriteAttributeString( "idRef", tmpElem.Id.IntegerValue.ToString() ); stream.WriteEndElement(); // ElementRef } stream.WriteEndElement(); // Symbol } stream.WriteEndElement(); // Symbols } private void XmlReportWriteElement( XmlTextWriter stream, Element elem ) { if( elem.Category == null ) return; stream.WriteStartElement( "BldgElement" ); stream.WriteAttributeString( "category", elem.Category.Name ); stream.WriteAttributeString( "id", elem.Id.IntegerValue.ToString() ); stream.WriteAttributeString( "name", elem.Name ); ParameterSet paramSet = elem.Parameters; foreach( Parameter tmpObj in paramSet ) { stream.WriteStartElement( "Param" ); stream.WriteAttributeString( "name", tmpObj.Definition.Name ); if( tmpObj.StorageType == StorageType.Double ) { stream.WriteAttributeString( "dataType", "double" ); stream.WriteAttributeString( "value", tmpObj.AsDouble().ToString() ); } else if( tmpObj.StorageType == StorageType.ElementId ) { stream.WriteAttributeString( "dataType", "elemId" ); stream.WriteAttributeString( "value", tmpObj.AsElementId().IntegerValue.ToString() ); } else if( tmpObj.StorageType == StorageType.Integer ) { stream.WriteAttributeString( "dataType", "int" ); stream.WriteAttributeString( "value", tmpObj.AsInteger().ToString() ); } else if( tmpObj.StorageType == StorageType.String ) { stream.WriteAttributeString( "dataType", "string" ); stream.WriteAttributeString( "value", tmpObj.AsString() ); } else if( tmpObj.StorageType == StorageType.None ) { stream.WriteAttributeString( "dataType", "none" ); stream.WriteAttributeString( "value", "???" ); } stream.WriteEndElement(); // "Param" } stream.WriteEndElement(); // "BldgElement" } } }
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 _05cTokenBasedAuthentication.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// // Copyright 2012-2013, Xamarin Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Linq; using System.Net; using Android.App; using Android.Net.Http; using Android.Webkit; using Android.OS; using System.Threading.Tasks; using SimpleAuth.Droid; namespace SimpleAuth { [Activity(Label = "Web Authenticator")] public class WebAuthenticatorActivity : Activity { WebView webView; public static string UserAgent = ""; public class State : Java.Lang.Object { public WebAuthenticator Authenticator; } public static readonly ActivityStateRepository<State> StateRepo = new ActivityStateRepository<State>(); State state; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // // Load the state either from a configuration change or from the intent. // state = LastNonConfigurationInstance as State; if (state == null && Intent.HasExtra("StateKey")) { var stateKey = Intent.GetStringExtra("StateKey"); state = StateRepo.Remove(stateKey); } if (state == null) { Finish(); return; } MonitorAuthenticator(); Title = state.Authenticator.Title; // // Build the UI // webView = new WebView(this) { Id = 42, }; if (!string.IsNullOrWhiteSpace(UserAgent)) { webView.Settings.UserAgentString = UserAgent; webView.Settings.LoadWithOverviewMode = true; } webView.Settings.JavaScriptEnabled = true; webView.SetWebViewClient(new Client(this)); SetContentView(webView); // // Restore the UI state or start over // if (savedInstanceState != null) { webView.RestoreState(savedInstanceState); } else { if (Intent.GetBooleanExtra("ClearCookies", true)) ClearCookies(); BeginLoadingInitialUrl(); } } async Task MonitorAuthenticator() { try { await state.Authenticator.GetAuthCode(); if (state.Authenticator.HasCompleted) { SetResult(Result.Ok); Finish(); } } catch (Exception ex) { Console.WriteLine(ex); } } Task loadingTask; async Task BeginLoadingInitialUrl() { if (loadingTask == null || loadingTask.IsCompleted) { loadingTask = RealLoading(); } await loadingTask; } async Task RealLoading() { ClearCookies (); if (!this.state.Authenticator.ClearCookiesBeforeLogin) LoadCookies(); // // Begin displaying the page // try { var url = await state.Authenticator.GetInitialUrl(); if (url == null) return; webView.LoadUrl(url.AbsoluteUri); } catch (Exception ex) { Console.WriteLine(ex); return; } } void LoadCookies () { this.state.Authenticator?.Cookies?.ToList ()?.ForEach (c => CookieManager.Instance.SetCookie(c.Domain, $"{c.Name}={c.Value}; path={c.Path}")); } public void ClearCookies() { CookieSyncManager.CreateInstance(Android.App.Application.Context); Android.Webkit.CookieManager.Instance.RemoveAllCookie(); } public override void OnBackPressed() { Finish(); state.Authenticator.OnCancelled(); } public override Java.Lang.Object OnRetainNonConfigurationInstance() { return state; } protected override void OnSaveInstanceState(Bundle outState) { base.OnSaveInstanceState(outState); webView.SaveState(outState); } void BeginProgress(string message) { webView.Enabled = false; } void EndProgress() { webView.Enabled = true; } class Client : WebViewClient { WebAuthenticatorActivity activity; HashSet<SslCertificate> sslContinue; Dictionary<SslCertificate, List<SslErrorHandler>> inProgress; public Client(WebAuthenticatorActivity activity) { this.activity = activity; } [Obsolete] public override bool ShouldOverrideUrlLoading(WebView view, string url) { Console.WriteLine(url); return false; } // TODO: Matt Hidinger confirm this should be removed? //public override bool ShouldOverrideUrlLoading (WebView view, IWebResourceRequest request) //{ // return false; //} public override void OnPageStarted(WebView view, string url, Android.Graphics.Bitmap favicon) { var uri = new Uri(url); activity.state.Authenticator.CheckUrl(uri, GetCookies(url)); activity.BeginProgress(uri.Authority); } public override void OnPageFinished(WebView view, string url) { var uri = new Uri(url); activity.state.Authenticator.CheckUrl(uri,GetCookies(url)); activity.EndProgress(); } System.Net.Cookie[] GetCookies(string url) { Android.Webkit.CookieSyncManager.CreateInstance(this.activity); var cookies = CookieManager.Instance.GetCookie (url); var cookiePairs = cookies?.Split('!') ?? new string[0]; return cookiePairs.Select(x => { var parts = x.Split('='); if (parts[0].Contains(":")) parts[0] = parts[0].Substring(0, parts[0].IndexOf(":")); try{ return new Cookie { Name = parts[0]?.Trim(), Value = parts[1]?.Trim(), }; } catch(Exception ex) { Console.WriteLine(ex); return null; } })?.Where(x=> x != null).ToArray() ?? new Cookie[0]; } class SslCertificateEqualityComparer : IEqualityComparer<SslCertificate> { public bool Equals(SslCertificate x, SslCertificate y) { return Equals(x.IssuedTo, y.IssuedTo) && Equals(x.IssuedBy, y.IssuedBy) && x.ValidNotBeforeDate.Equals(y.ValidNotBeforeDate) && x.ValidNotAfterDate.Equals(y.ValidNotAfterDate); } bool Equals(SslCertificate.DName x, SslCertificate.DName y) { if (ReferenceEquals(x, y)) return true; if (ReferenceEquals(x, y) || ReferenceEquals(null, y)) return false; return x.GetDName().Equals(y.GetDName()); } public int GetHashCode(SslCertificate obj) { unchecked { int hashCode = GetHashCode(obj.IssuedTo); hashCode = (hashCode * 397) ^ GetHashCode(obj.IssuedBy); hashCode = (hashCode * 397) ^ obj.ValidNotBeforeDate.GetHashCode(); hashCode = (hashCode * 397) ^ obj.ValidNotAfterDate.GetHashCode(); return hashCode; } } int GetHashCode(SslCertificate.DName dname) { return dname.GetDName().GetHashCode(); } } public override void OnReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { if (sslContinue == null) { var certComparer = new SslCertificateEqualityComparer(); sslContinue = new HashSet<SslCertificate>(certComparer); inProgress = new Dictionary<SslCertificate, List<SslErrorHandler>>(certComparer); } List<SslErrorHandler> handlers; if (inProgress.TryGetValue(error.Certificate, out handlers)) { handlers.Add(handler); return; } if (sslContinue.Contains(error.Certificate)) { handler.Proceed(); return; } inProgress[error.Certificate] = new List<SslErrorHandler>(); AlertDialog.Builder builder = new AlertDialog.Builder(this.activity); builder.SetTitle("Security warning"); builder.SetIcon(Android.Resource.Drawable.IcDialogAlert); builder.SetMessage("There are problems with the security certificate for this site."); builder.SetNegativeButton("Go back", (sender, args) => { UpdateInProgressHandlers(error.Certificate, h => h.Cancel()); handler.Cancel(); }); builder.SetPositiveButton("Continue", (sender, args) => { sslContinue.Add(error.Certificate); UpdateInProgressHandlers(error.Certificate, h => h.Proceed()); handler.Proceed(); }); builder.Create().Show(); } void UpdateInProgressHandlers(SslCertificate certificate, Action<SslErrorHandler> update) { List<SslErrorHandler> inProgressHandlers; if (!this.inProgress.TryGetValue(certificate, out inProgressHandlers)) return; foreach (SslErrorHandler sslErrorHandler in inProgressHandlers) update(sslErrorHandler); inProgressHandlers.Clear(); } } } }
using Aardvark.Base; using System; using System.Collections.Generic; using System.Xml.Linq; namespace Aardvark.Base.Coder { // AUTO GENERATED CODE - DO NOT CHANGE! //# var directlyCodeableTypes = Meta.DirectlyCodeableTypes.Map(t =>t.Name); //# var geometryTypes = Meta.GeometryTypes.Map(t => t.Name); //# var specialSimpleTypes = new[] { "bool", "char", "string", "Type", "Guid", "Symbol" }; //# { //# var structTypes = new List<string>(); //# var tensorTypes = new List<string>(); public partial class NewXmlWritingCoder { #region Vectors //# foreach (var t in Meta.VecTypes) { structTypes.Add(t.Name); //# var name = Meta.GetXmlTypeName(t.Name); public void Code__name__(ref __t.Name__ v) { throw new NotImplementedException(); } //# } #endregion #region Matrices //# foreach (var t in Meta.MatTypes) { structTypes.Add(t.Name); //# var name = Meta.GetXmlTypeName(t.Name); public void Code__name__(ref __t.Name__ v) { throw new NotImplementedException(); } //# } #endregion #region Ranges and Boxes //# foreach (var t in Meta.RangeAndBoxTypes) { structTypes.Add(t.Name); //# var name = Meta.GetXmlTypeName(t.Name); public void Code__name__(ref __t.Name__ v) { throw new NotImplementedException(); } //# } #endregion #region Colors //# foreach (var t in Meta.ColorTypes) { structTypes.Add(t.Name); //# var name = Meta.GetXmlTypeName(t.Name); public void Code__name__(ref __t.Name__ v) { throw new NotImplementedException(); } //# } #endregion #region Trafos //# foreach (var t in Meta.TrafoTypes) { structTypes.Add(t.Name); //# var name = Meta.GetXmlTypeName(t.Name); public void Code__name__(ref __t.Name__ v) { throw new NotImplementedException(); } //# } #endregion #region Tensors //# foreach (var t in geometryTypes) structTypes.Add(t); //# var simpleTypes = directlyCodeableTypes.Concat(specialSimpleTypes).Concat(geometryTypes); //# var genericTensorTypes = new[] { "Vector", "Matrix", "Volume", "Tensor" }; //# genericTensorTypes.ForEach(tt => { //# simpleTypes.ForEach(t => { //# var type = tt + "<" + t + ">"; //# tensorTypes.Add(type); //# var name = Meta.GetXmlTypeName(type); public void Code__name__(ref __type__ value) { throw new NotImplementedException(); } //# }); //# }); #endregion #region Arrays //# structTypes.ForEach(t => { //# var name = Meta.GetXmlTypeName(t + "[]"); public void Code__name__(ref __t__[] v) { throw new NotImplementedException(); } //# }); #endregion #region Multi-Dimensional Arrays //# directlyCodeableTypes.ForEach(t => { //# var name2d = Meta.GetXmlTypeName(t + "[,]"); public void Code__name2d__(ref __t__[,] v) { throw new NotImplementedException(); } //# var name3d = Meta.GetXmlTypeName(t + "[,,]"); public void Code__name3d__(ref __t__[, ,] v) { throw new NotImplementedException(); } //# }); #endregion #region Jagged Multi-Dimensional Arrays //# directlyCodeableTypes.ForEach(t => { //# var name2d = Meta.GetXmlTypeName(t + "[][]"); public void Code__name2d__(ref __t__[][] v) { throw new NotImplementedException(); } //# var name3d = Meta.GetXmlTypeName(t + "[][][]"); public void Code__name3d__(ref __t__[][][] v) { throw new NotImplementedException(); } //# }); #endregion #region Lists //# structTypes.ForEach(t => { //# var name = Meta.GetXmlTypeName("List<" + t + ">"); public void Code__name__(ref List<__t__> v) { throw new NotImplementedException(); } //# }); #endregion #region Arrays of Tensors //# tensorTypes.ForEach(t => { //# var name = Meta.GetXmlTypeName(t + "[]"); public void Code__name__(ref __t__[] v) { throw new NotImplementedException(); } //# }); #endregion #region Lists of Tensors //# tensorTypes.ForEach(t => { //# var name = Meta.GetXmlTypeName("List<" + t + ">"); public void Code__name__(ref List<__t__> v) { throw new NotImplementedException(); } //# }); #endregion } //# } { //# var structTypes = new List<string>(); //# var tensorTypes = new List<string>(); public partial class XmlWritingCoder { #region Vectors //# foreach (var t in Meta.VecTypes) { structTypes.Add(t.Name); //# var name = Meta.GetXmlTypeName(t.Name); public void Code__name__(ref __t.Name__ v) { AddValue(v.ToString()); } //# } #endregion #region Matrices //# foreach (var t in Meta.MatTypes) { structTypes.Add(t.Name); //# var name = Meta.GetXmlTypeName(t.Name); public void Code__name__(ref __t.Name__ v) { AddValue(v.ToString()); } //# } #endregion #region Ranges and Boxes //# foreach (var t in Meta.RangeAndBoxTypes) { structTypes.Add(t.Name); //# var name = Meta.GetXmlTypeName(t.Name); public void Code__name__(ref __t.Name__ v) { AddValue(v.ToString()); } //# } #endregion #region Colors //# foreach (var t in Meta.ColorTypes) { structTypes.Add(t.Name); //# var name = Meta.GetXmlTypeName(t.Name); public void Code__name__(ref __t.Name__ v) { AddValue(v.ToString()); } //# } #endregion #region Trafos //# foreach (var t in Meta.TrafoTypes) { structTypes.Add(t.Name); //# var name = Meta.GetXmlTypeName(t.Name); public void Code__name__(ref __t.Name__ v) { AddValue(v.ToString()); } //# } #endregion #region Tensors //# foreach (var t in geometryTypes) structTypes.Add(t); //# var simpleTypes = directlyCodeableTypes.Concat(specialSimpleTypes).Concat(geometryTypes); //# var genericTensorTypes = new[] { "Vector", "Matrix", "Volume", "Tensor" }; //# var genericTensorSizes = new[] { "long", "V2l", "V3l", "long[]" }; //# genericTensorTypes.ForEach((tt, ti) => { //# var ts = genericTensorSizes[ti]; var tsn = Meta.GetXmlTypeName(ts); //# simpleTypes.ForEach(t => { //# var type = tt + "<" + t + ">"; //# tensorTypes.Add(type); //# var dname = Meta.GetXmlTypeName(t + "[]"); //# var name = Meta.GetXmlTypeName(type); public void Code__name__(ref __type__ value) { var item = new XElement("__tt__"); m_elementStack.Push(m_element); m_element = item; var element = new XElement("Data"); m_elementStack.Push(m_element); m_element = element; var data = value.Data; Code__dname__(ref data); m_element = m_elementStack.Pop(); m_element.Add(element); element = new XElement("Origin"); m_elementStack.Push(m_element); m_element = element; var origin = value.Origin; CodeLong(ref origin); m_element = m_elementStack.Pop(); m_element.Add(element); element = new XElement("Length"); m_elementStack.Push(m_element); m_element = element; var size = value.Size; Code__tsn__(ref size); m_element = m_elementStack.Pop(); m_element.Add(element); element = new XElement("Delta"); m_elementStack.Push(m_element); m_element = element; var delta = value.Delta; Code__tsn__(ref delta); m_element = m_elementStack.Pop(); m_element.Add(element); m_element = m_elementStack.Pop(); AddValue(item); } //# }); //# }); #endregion #region Arrays //# structTypes.ForEach(t => { //# var name = Meta.GetXmlTypeName(t + "[]"); public void Code__name__(ref __t__[] v) { CodeArrayOfStruct(v); } //# }); #endregion #region Multi-Dimensional Arrays //# directlyCodeableTypes.ForEach(t => { //# var name2d = Meta.GetXmlTypeName(t + "[,]"); public void Code__name2d__(ref __t__[,] v) { throw new NotImplementedException(); } //# var name3d = Meta.GetXmlTypeName(t + "[,,]"); public void Code__name3d__(ref __t__[, ,] v) { throw new NotImplementedException(); } //# }); #endregion #region Multi-Dimensional Arrays //# directlyCodeableTypes.ForEach(t => { //# var name2d = Meta.GetXmlTypeName(t + "[][]"); public void Code__name2d__(ref __t__[][] v) { throw new NotImplementedException(); } //# var name3d = Meta.GetXmlTypeName(t + "[][][]"); public void Code__name3d__(ref __t__[][][] v) { throw new NotImplementedException(); } //# }); #endregion #region Lists //# structTypes.ForEach(t => { //# var name = Meta.GetXmlTypeName("List<" + t + ">"); public void Code__name__(ref List<__t__> v) { CodeListOfStruct(v); } //# }); #endregion #region Arrays of Tensors //# tensorTypes.ForEach(t => { //# var name = Meta.GetXmlTypeName(t + "[]"); public void Code__name__(ref __t__[] v) { CodeArrayOf(v); } //# }); #endregion #region Lists of Tensors //# tensorTypes.ForEach(t => { //# var name = Meta.GetXmlTypeName("List<" + t + ">"); public void Code__name__(ref List<__t__> v) { CodeListOf(v); } //# }); #endregion } //# } }
// Copyright (c) Alexandre Mutel. All rights reserved. // Licensed under the BSD-Clause 2 license. // See license.txt file in the project root for full license information. #nullable disable using System; using System.Collections.Generic; using Scriban.Parsing; using Scriban.Runtime; using Scriban.Syntax; namespace Scriban.Functions { /// <summary> /// The include function available through the function 'include' in scriban. /// </summary> #if SCRIBAN_PUBLIC public #else internal #endif sealed partial class IncludeFunction : IScriptCustomFunction { public IncludeFunction() { } public object Invoke(TemplateContext context, ScriptNode callerContext, ScriptArray arguments, ScriptBlockStatement blockStatement) { if (arguments.Count == 0) { throw new ScriptRuntimeException(callerContext.Span, "Expecting at least the name of the template to include for the <include> function"); } var templateName = context.ObjectToString(arguments[0]); // If template name is empty, throw an exception if (string.IsNullOrEmpty(templateName)) { // In a liquid template context, we let an include to continue without failing if (context is LiquidTemplateContext) { return null; } throw new ScriptRuntimeException(callerContext.Span, $"Include template name cannot be null or empty"); } var templateLoader = context.TemplateLoader; if (templateLoader == null) { throw new ScriptRuntimeException(callerContext.Span, $"Unable to include <{templateName}>. No TemplateLoader registered in TemplateContext.TemplateLoader"); } string templatePath; try { templatePath = templateLoader.GetPath(context, callerContext.Span, templateName); } catch (Exception ex) when (!(ex is ScriptRuntimeException)) { throw new ScriptRuntimeException(callerContext.Span, $"Unexpected exception while getting the path for the include name `{templateName}`", ex); } // If template path is empty (probably because template doesn't exist), throw an exception if (templatePath == null) { throw new ScriptRuntimeException(callerContext.Span, $"Include template path is null for `{templateName}"); } string indent = null; // Handle indent if (context.IndentWithInclude) { // Find the statement for the include var current = callerContext.Parent; while (current != null && !(current is ScriptStatement)) { current = current.Parent; } // Find the RawStatement preceding this include ScriptNode childNode = null; bool shouldContinue = true; while (shouldContinue && current != null) { if (current is ScriptList<ScriptStatement> statementList && childNode is ScriptStatement childStatement) { var indexOf = statementList.IndexOf(childStatement); // Case for first indent, if it is not the first statement in the doc // it's not a valid indent if (indent != null && indexOf > 0) { indent = null; break; } for (int i = indexOf - 1; i >= 0; i--) { var previousStatement = statementList[i]; if (previousStatement is ScriptEscapeStatement escapeStatement && escapeStatement.IsEntering) { if (i > 0 && statementList[i - 1] is ScriptRawStatement rawStatement) { var text = rawStatement.Text; for (int j = text.Length - 1; j >= 0; j--) { var c = text[j]; if (c == '\n') { shouldContinue = false; indent = text.Substring(j + 1); break; } if (!char.IsWhiteSpace(c)) { shouldContinue = false; break; } if (j == 0) { // We have a raw statement that has only white spaces // It could be the first raw statement of the document // so we continue but we handle it later indent = text.ToString(); } } } else { shouldContinue = false; } break; } } } childNode = current; current = childNode.Parent; } if (string.IsNullOrEmpty(indent)) { indent = null; } } Template template; if (!context.CachedTemplates.TryGetValue(templatePath, out template)) { string templateText; try { templateText = templateLoader.Load(context, callerContext.Span, templatePath); } catch (Exception ex) when (!(ex is ScriptRuntimeException)) { throw new ScriptRuntimeException(callerContext.Span, $"Unexpected exception while loading the include `{templateName}` from path `{templatePath}`", ex); } if (templateText == null) { throw new ScriptRuntimeException(callerContext.Span, $"The result of including `{templateName}->{templatePath}` cannot be null"); } // Clone parser options var parserOptions = context.TemplateLoaderParserOptions; var lexerOptions = context.TemplateLoaderLexerOptions; template = Template.Parse(templateText, templatePath, parserOptions, lexerOptions); // If the template has any errors, throw an exception if (template.HasErrors) { throw new ScriptParserRuntimeException(callerContext.Span, $"Error while parsing template `{templateName}` from `{templatePath}`", template.Messages); } context.CachedTemplates.Add(templatePath, template); } // Make sure that we cannot recursively include a template object result = null; context.EnterRecursive(callerContext); var previousIndent = context.CurrentIndent; context.CurrentIndent = indent; context.PushOutput(); var previousArguments = context.GetValue(ScriptVariable.Arguments); try { context.SetValue(ScriptVariable.Arguments, arguments, true, true); if (indent != null) { // We reset before and after the fact that we have a new line context.ResetPreviousNewLine(); } result = template.Render(context); if (indent != null) { context.ResetPreviousNewLine(); } } finally { context.PopOutput(); context.CurrentIndent = previousIndent; context.ExitRecursive(callerContext); // Remove the arguments context.DeleteValue(ScriptVariable.Arguments); if (previousArguments != null) { // Restore them if necessary context.SetValue(ScriptVariable.Arguments, previousArguments, true); } } return result; } public int RequiredParameterCount => 1; public int ParameterCount => 1; public ScriptVarParamKind VarParamKind => ScriptVarParamKind.Direct; public Type ReturnType => typeof(object); public ScriptParameterInfo GetParameterInfo(int index) { if (index == 0) return new ScriptParameterInfo(typeof(string), "template_name"); return new ScriptParameterInfo(typeof(object), "value"); } public int GetParameterIndexByName(string name) { throw new NotImplementedException(); } } }
using AutoMapper; using FizzWare.NBuilder; using Moq; using NUnit.Framework; using ReMi.BusinessEntities.Api; using ReMi.DataAccess.BusinessEntityGateways.Auth; using System; using System.Collections.Generic; using System.Linq; using ReMi.Common.Utils.Repository; using ReMi.Contracts.Plugins.Data; using ReMi.TestUtils.UnitTests; using ReMi.DataAccess.Exceptions; using ReMi.DataEntities.Auth; using ReMi.DataEntities.Plugins; using DataCommand = ReMi.DataEntities.Api.Command; using DataCommandPermission = ReMi.DataEntities.Auth.CommandPermission; using DataRole = ReMi.DataEntities.Auth.Role; namespace ReMi.DataAccess.Tests.Auth { [TestFixture] public class CommandPermissionsGatewayTests : TestClassFor<CommandPermissionsGateway> { private Mock<IRepository<DataCommand>> _commandRepositoryMock; private Mock<IRepository<DataCommandPermission>> _commandPermissionRepositoryMock; private Mock<IRepository<DataRole>> _roleRepositoryMock; private Mock<IRepository<Account>> _accountRepositoryMock; private Mock<IRepository<PluginConfiguration>> _pluginConfigurationRepositoryMock; private Mock<IMappingEngine> _mapperMock; protected override CommandPermissionsGateway ConstructSystemUnderTest() { return new CommandPermissionsGateway { CommandRepository = _commandRepositoryMock.Object, CommandPermissionRepository = _commandPermissionRepositoryMock.Object, RoleRepository = _roleRepositoryMock.Object, AccountRepository = _accountRepositoryMock.Object, PluginConfigurationRepository = _pluginConfigurationRepositoryMock.Object, Mapper = _mapperMock.Object }; } protected override void TestInitialize() { _commandRepositoryMock = new Mock<IRepository<DataCommand>>(MockBehavior.Strict); _commandPermissionRepositoryMock = new Mock<IRepository<DataCommandPermission>>(MockBehavior.Strict); _roleRepositoryMock = new Mock<IRepository<DataRole>>(MockBehavior.Strict); _accountRepositoryMock = new Mock<IRepository<Account>>(MockBehavior.Strict); _pluginConfigurationRepositoryMock = new Mock<IRepository<PluginConfiguration>>(MockBehavior.Strict); _mapperMock = new Mock<IMappingEngine>(MockBehavior.Strict); base.TestInitialize(); } [Test] public void Dispose_ShouldDisposeAllRepositories_WhenInvoked() { _commandRepositoryMock.Setup(x => x.Dispose()); _commandPermissionRepositoryMock.Setup(x => x.Dispose()); _roleRepositoryMock.Setup(x => x.Dispose()); _accountRepositoryMock.Setup(x => x.Dispose()); _pluginConfigurationRepositoryMock.Setup(x => x.Dispose()); Sut.Dispose(); _commandRepositoryMock.Verify(x => x.Dispose(), Times.Once); _commandPermissionRepositoryMock.Verify(x => x.Dispose(), Times.Once); _roleRepositoryMock.Verify(x => x.Dispose(), Times.Once); _accountRepositoryMock.Verify(x => x.Dispose(), Times.Once); _pluginConfigurationRepositoryMock.Verify(x => x.Dispose(), Times.Once); } [Test] public void GetCommands_ShouldReturnAllNotBackgroundCommands_WhenCalledWithoutParameter() { var commands = BuildCommandEntities(); var notBackgroundCount = commands.Count(x => !x.IsBackground); _commandRepositoryMock.SetupEntities(commands); _mapperMock.Setup(x => x.Map<DataCommand, Command>(It.IsAny<DataCommand>())) .Returns(new Command()); var result = Sut.GetCommands(); Assert.AreEqual(notBackgroundCount, result.Count()); _mapperMock.Verify(x => x.Map<DataCommand, Command>(It.IsAny<DataCommand>()), Times.Exactly(notBackgroundCount)); } [Test] public void GetCommands_ShouldReturnAllCommands_WhenCalledWithoutTrueParameter() { var commands = BuildCommandEntities(); var count = commands.Count(); _commandRepositoryMock.SetupEntities(commands); _mapperMock.Setup(x => x.Map<DataCommand, Command>(It.IsAny<DataCommand>())) .Returns(new Command()); var result = Sut.GetCommands(true); Assert.AreEqual(count, result.Count()); _mapperMock.Verify(x => x.Map<DataCommand, Command>(It.IsAny<DataCommand>()), Times.Exactly(count)); } [Test] public void AddCommandPermission_ShouldAddNewCommandToRoleRelation_WhenCommandAndRoleExist() { var roles = BuildRoleEntities(); var commands = BuildCommandEntities(); var startPermissionCount = commands.First().CommandPermissions.Count; _commandRepositoryMock.SetupEntities(commands); _roleRepositoryMock.SetupEntities(roles); _commandRepositoryMock.Setup(x => x.Update(commands.First())) .Returns((ChangedFields<DataCommand>)null); Sut.AddCommandPermission(commands.First().CommandId, roles.First().ExternalId); Assert.IsTrue(commands.First().CommandPermissions.Any(x => x.RoleId == roles.First().Id)); Assert.AreEqual(startPermissionCount + 1, commands.First().CommandPermissions.Count); _commandRepositoryMock.Verify(x => x.Update(commands.First()), Times.Once()); } [Test] [ExpectedException(typeof(CommandNotFoundException))] public void AddCommandPermission_ShouldThrowException_WhenCommandNotExists() { var roles = BuildRoleEntities(); var commands = BuildCommandEntities(); _commandRepositoryMock.SetupEntities(commands); Sut.AddCommandPermission(-1, roles.First().ExternalId); } [Test] [ExpectedException(typeof(RoleNotFoundException))] public void AddCommandPermission_ShouldThrowException_WhenRoleNotExists() { var roles = BuildRoleEntities(); var commands = BuildCommandEntities(); _commandRepositoryMock.SetupEntities(commands); _roleRepositoryMock.SetupEntities(roles); Sut.AddCommandPermission(commands.First().CommandId, Guid.Empty); } [Test] public void AddCommandPermission_ShouldDoNothing_WhenPermissionExists() { var roles = BuildRoleEntities(); var commands = BuildCommandEntities(); commands.First().CommandPermissions.Add(new DataCommandPermission { CommandId = commands.First().CommandId, RoleId = roles.First().Id, Role = roles.First() }); var startPermissionCount = commands.First().CommandPermissions.Count; _commandRepositoryMock.SetupEntities(commands); _roleRepositoryMock.SetupEntities(roles); Sut.AddCommandPermission(commands.First().CommandId, roles.First().ExternalId); Assert.AreEqual(startPermissionCount, commands.First().CommandPermissions.Count); _commandRepositoryMock.Verify(x => x.Update(It.IsAny<DataCommand>()), Times.Never); } [Test] public void RemoveCommandPermission_ShouldRemoveCommandToRoleRelation_WhenCommandAndRoleExist() { var roles = BuildRoleEntities(); var commands = BuildCommandEntities(); commands.First().CommandPermissions.Add(new DataCommandPermission { CommandId = commands.First().CommandId, RoleId = roles.First().Id, Role = roles.First() }); _commandRepositoryMock.SetupEntities(commands); _roleRepositoryMock.SetupEntities(roles); _commandPermissionRepositoryMock.SetupEntities(commands.First().CommandPermissions); _commandPermissionRepositoryMock.Setup(x =>x.Delete(It.Is<DataCommandPermission>( r => r.CommandId == commands.First().CommandId && r.RoleId == roles.First().Id))); Sut.RemoveCommandPermission(commands.First().CommandId, roles.First().ExternalId); Assert.IsTrue(commands.First().CommandPermissions.Any(x => x.RoleId == roles.First().Id)); _commandPermissionRepositoryMock.Verify(x => x.Delete(It.Is<DataCommandPermission>( r => r.CommandId == commands.First().CommandId && r.RoleId == roles.First().Id)), Times.Once()); } [Test] [ExpectedException(typeof(CommandNotFoundException))] public void RemoveCommandPermission_ShouldThrowException_WhenCommandNotExists() { var roles = BuildRoleEntities(); var commands = BuildCommandEntities(); _commandRepositoryMock.SetupEntities(commands); Sut.RemoveCommandPermission(-1, roles.First().ExternalId); } [Test] [ExpectedException(typeof(RoleNotFoundException))] public void RemoveCommandPermission_ShouldThrowException_WhenRoleNotExists() { var roles = BuildRoleEntities(); var commands = BuildCommandEntities(); _commandRepositoryMock.SetupEntities(commands); _roleRepositoryMock.SetupEntities(roles); Sut.RemoveCommandPermission(commands.First().CommandId, Guid.Empty); } [Test] public void RemoveCommandPermission_ShouldDoNothing_WhenPermissionExists() { var roles = BuildRoleEntities(); var commands = BuildCommandEntities(); var startPermissionCount = commands.First().CommandPermissions.Count; _commandRepositoryMock.SetupEntities(commands); _roleRepositoryMock.SetupEntities(roles); Sut.RemoveCommandPermission(commands.First().CommandId, roles.First().ExternalId); _commandPermissionRepositoryMock.Verify(x => x.Delete(It.IsAny<DataCommandPermission>()), Times.Never); } [Test] public void GetAllowedCommands_ShouldReturnCorrectValue() { var commandPermissions = new List<DataCommandPermission> { new DataCommandPermission { Command = new DataCommand{Name = RandomData.RandomString(15,20)}, Role = new DataRole { ExternalId = Guid.NewGuid() } } }; _roleRepositoryMock.SetupEntities(commandPermissions.Select(x => x.Role).ToArray()); _commandPermissionRepositoryMock.SetupEntities(commandPermissions); var result = Sut.GetAllowedCommands(commandPermissions[0].Role.ExternalId); Assert.AreEqual(commandPermissions[0].Command.Name, result.First()); } [Test] public void GetAllowedCommands_ShouldReturnEmptyCollection_WhenRoleIsEmptyAndAuthenticationMethodDefined() { var commands = Builder<DataCommand>.CreateListOfSize(5).Build(); var accounts = Builder<Account>.CreateListOfSize(5).Build(); var pluginsConfig = Builder<PluginConfiguration>.CreateListOfSize(5) .Random(1) .With(x => x.PluginType, PluginType.Authentication) .With(x => x.PluginId, RandomData.RandomInt(int.MaxValue)) .Build(); _accountRepositoryMock.SetupEntities(accounts); _pluginConfigurationRepositoryMock.SetupEntities(pluginsConfig); _commandRepositoryMock.SetupEntities(commands); var result = Sut.GetAllowedCommands(null); CollectionAssert.IsEmpty(result); } [Test] public void GetAllowedCommands_ShouldReturnAllCommands_WhenRoleIsEmptyAndNoAuthenticationMethodDefined() { var commands = Builder<DataCommand>.CreateListOfSize(5).Build(); _accountRepositoryMock.SetupEntities(Enumerable.Empty<Account>()); _pluginConfigurationRepositoryMock.SetupEntities(Enumerable.Empty<PluginConfiguration>()); _commandRepositoryMock.SetupEntities(commands); var result = Sut.GetAllowedCommands(null); CollectionAssert.AreEquivalent(commands.Select(x => x.Name), result); } [Test] public void GetAllowedCommands_ShouldReturnAllCommands_WhenRoleIsAdmin() { var role = new DataRole { ExternalId = Guid.NewGuid(), Name = "Admin" }; var commands = Builder<DataCommand>.CreateListOfSize(5).Build(); _roleRepositoryMock.SetupEntities(new[] { role }); _commandRepositoryMock.SetupEntities(commands); var result = Sut.GetAllowedCommands(role.ExternalId); CollectionAssert.AreEquivalent(commands.Select(x => x.Name), result); } private static IList<DataCommand> BuildCommandEntities() { var i = 1000; return Builder<DataCommand>.CreateListOfSize(5) .All() .Do(x => x.CommandId = i++) .Do(x => x.Description = RandomData.RandomString(10)) .Do(x => x.Group = RandomData.RandomString(10)) .Do(x => x.Name = RandomData.RandomString(10)) .Do(x => x.IsBackground = RandomData.RandomBool()) .Do(x => x.CommandPermissions = RandomData.RandomBool() ? new List<DataCommandPermission>() : Builder<DataCommandPermission>.CreateListOfSize(RandomData.RandomInt(1, 5)) .All() .Do(cp => cp.Role = new DataRole { ExternalId = Guid.NewGuid(), Description = RandomData.RandomString(10), Name = RandomData.RandomString(10), Id = RandomData.RandomInt(10000) }) .Build()) .Build(); } private static IList<DataRole> BuildRoleEntities() { var i = 1000; return Builder<DataRole>.CreateListOfSize(5) .All() .Do(x => x.Id = i++) .Do(x => x.Description = RandomData.RandomString(10)) .Do(x => x.Name = RandomData.RandomString(10)) .Do(x => x.ExternalId = Guid.NewGuid()) .Build(); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; namespace SineSignal.Ottoman.Serialization { public sealed class JsonWriter { private static NumberFormatInfo numberFormatInfo; private StringBuilder internalStringBuilder; private TextWriter writer; private Stack<Scope> scopes; static JsonWriter () { numberFormatInfo = NumberFormatInfo.InvariantInfo; } public JsonWriter() { internalStringBuilder = new StringBuilder(); writer = new StringWriter(internalStringBuilder); scopes = new Stack<Scope>(); } public void BeginObject() { BeginObjectScope(); } public void BeginArray() { BeginArrayScope(); } public void WriteMember(string name) { PutComma(ScopeType.Object); PutStringValue(name); PutNameSeparator(); } public void WriteBoolean(bool boolean) { PutValue(boolean ? "true" : "false"); } public void WriteString(string text) { if (text != null) { PutStringValue(text); } else { PutValue("null"); } } public void WriteNumber(int number) { PutValue(Convert.ToString(number, numberFormatInfo)); } public void WriteNumber(long number) { PutValue(Convert.ToString(number, numberFormatInfo)); } // This makes us not CLS Compliant public void WriteNumber(ulong number) { PutValue(Convert.ToString(number, numberFormatInfo)); } public void WriteNumber(float number) { PutValue(Convert.ToString(number, numberFormatInfo)); } public void WriteNumber(double number) { PutValue(Convert.ToString(number, numberFormatInfo)); } public void WriteNumber(decimal number) { PutValue(Convert.ToString(number, numberFormatInfo)); } public void EndObject() { EndScope(); } public void EndArray() { EndScope(); } public void Reset() { if (internalStringBuilder != null) { internalStringBuilder.Remove(0, internalStringBuilder.Length); } } public override string ToString() { if (internalStringBuilder != null) { return internalStringBuilder.ToString(); } return String.Empty; } private void PutValue(string text) { PutComma(ScopeType.Array); writer.Write(text); } private void PutStringValue(string text) { PutValue(String.Format("\"{0}\"", EscapeString(text))); } private string EscapeString(string text) { var stringBuilder = new StringBuilder(); for (int index = 0; index < text.Length; index++) { char character = text[index]; // Special Character, need to escape switch (character) { case '\n': stringBuilder.Append("\\n"); continue; case '\r': stringBuilder.Append("\\r"); continue; case '\t': stringBuilder.Append("\\t"); continue; case '"': case '\\': stringBuilder.Append('\\'); stringBuilder.Append(character); continue; case '\f': stringBuilder.Append("\\f"); continue; case '\b': stringBuilder.Append("\\b"); continue; } // Unicode Character if (character < ' ' || character > 0x7F) { stringBuilder.AppendFormat(CultureInfo.InvariantCulture, "\\u{0:X4}", (int)character); continue; } // ASCII Character stringBuilder.Append(character); } return stringBuilder.ToString(); } private void BeginObjectScope() { BeginScope(ScopeType.Object); } private void BeginArrayScope() { BeginScope(ScopeType.Array); } private void BeginScope(ScopeType scopeType) { PutComma(ScopeType.Array); var scope = new Scope(scopeType); scopes.Push(scope); if (scopeType == ScopeType.Object) { writer.Write('{'); } else if (scope.Type == ScopeType.Array) { writer.Write('['); } } private void EndScope() { Scope scope = scopes.Pop(); if (scope.Type == ScopeType.Object) { writer.Write('}'); } else if (scope.Type == ScopeType.Array) { writer.Write(']'); } } private void PutNameSeparator() { writer.Write(':'); } private void PutComma(ScopeType scopeType) { if (scopes.Count != 0) { Scope currentScope = scopes.Peek(); if (currentScope.Type == scopeType && currentScope.ObjectCount != 0) { writer.Write(','); } currentScope.ObjectCount++; } } private enum ScopeType { Object = 0, Array = 1 } private sealed class Scope { public ScopeType Type { get; private set; } public int ObjectCount { get; set; } public Scope(ScopeType scopeType) { Type = scopeType; } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Xml; using Nop.Core.Domain.Catalog; namespace Nop.Services.Catalog { /// <summary> /// Product attribute parser /// </summary> public partial class ProductAttributeParser : IProductAttributeParser { #region Fields private readonly IProductAttributeService _productAttributeService; #endregion #region Ctor public ProductAttributeParser(IProductAttributeService productAttributeService) { this._productAttributeService = productAttributeService; } #endregion #region Product attributes /// <summary> /// Gets selected product attribute mapping identifiers /// </summary> /// <param name="attributesXml">Attributes in XML format</param> /// <returns>Selected product attribute mapping identifiers</returns> protected virtual IList<int> ParseProductAttributeMappingIds(string attributesXml) { var ids = new List<int>(); if (String.IsNullOrEmpty(attributesXml)) return ids; try { var xmlDoc = new XmlDocument(); xmlDoc.LoadXml(attributesXml); var nodeList1 = xmlDoc.SelectNodes(@"//Attributes/ProductAttribute"); foreach (XmlNode node1 in nodeList1) { if (node1.Attributes != null && node1.Attributes["ID"] != null) { string str1 = node1.Attributes["ID"].InnerText.Trim(); int id; if (int.TryParse(str1, out id)) { ids.Add(id); } } } } catch (Exception exc) { Debug.Write(exc.ToString()); } return ids; } /// <summary> /// Gets selected product attribute mappings /// </summary> /// <param name="attributesXml">Attributes in XML format</param> /// <returns>Selected product attribute mappings</returns> public virtual IList<ProductAttributeMapping> ParseProductAttributeMappings(string attributesXml) { var result = new List<ProductAttributeMapping>(); var ids = ParseProductAttributeMappingIds(attributesXml); foreach (int id in ids) { var attribute = _productAttributeService.GetProductAttributeMappingById(id); if (attribute != null) { result.Add(attribute); } } return result; } /// <summary> /// Get product attribute values /// </summary> /// <param name="attributesXml">Attributes in XML format</param> /// <returns>Product attribute values</returns> public virtual IList<ProductAttributeValue> ParseProductAttributeValues(string attributesXml) { var values = new List<ProductAttributeValue>(); var attributes = ParseProductAttributeMappings(attributesXml); foreach (var attribute in attributes) { if (!attribute.ShouldHaveValues()) continue; var valuesStr = ParseValues(attributesXml, attribute.Id); foreach (string valueStr in valuesStr) { if (!String.IsNullOrEmpty(valueStr)) { int id; if (int.TryParse(valueStr, out id)) { var value = _productAttributeService.GetProductAttributeValueById(id); if (value != null) values.Add(value); } } } } return values; } /// <summary> /// Gets selected product attribute values /// </summary> /// <param name="attributesXml">Attributes in XML format</param> /// <param name="productAttributeMappingId">Product attribute mapping identifier</param> /// <returns>Product attribute values</returns> public virtual IList<string> ParseValues(string attributesXml, int productAttributeMappingId) { var selectedValues = new List<string>(); try { var xmlDoc = new XmlDocument(); xmlDoc.LoadXml(attributesXml); var nodeList1 = xmlDoc.SelectNodes(@"//Attributes/ProductAttribute"); foreach (XmlNode node1 in nodeList1) { if (node1.Attributes != null && node1.Attributes["ID"] != null) { string str1 =node1.Attributes["ID"].InnerText.Trim(); int id; if (int.TryParse(str1, out id)) { if (id == productAttributeMappingId) { var nodeList2 = node1.SelectNodes(@"ProductAttributeValue/Value"); foreach (XmlNode node2 in nodeList2) { string value = node2.InnerText.Trim(); selectedValues.Add(value); } } } } } } catch (Exception exc) { Debug.Write(exc.ToString()); } return selectedValues; } /// <summary> /// Adds an attribute /// </summary> /// <param name="attributesXml">Attributes in XML format</param> /// <param name="productAttributeMapping">Product attribute mapping</param> /// <param name="value">Value</param> /// <returns>Updated result (XML format)</returns> public virtual string AddProductAttribute(string attributesXml, ProductAttributeMapping productAttributeMapping, string value) { string result = string.Empty; try { var xmlDoc = new XmlDocument(); if (String.IsNullOrEmpty(attributesXml)) { var element1 = xmlDoc.CreateElement("Attributes"); xmlDoc.AppendChild(element1); } else { xmlDoc.LoadXml(attributesXml); } var rootElement = (XmlElement)xmlDoc.SelectSingleNode(@"//Attributes"); XmlElement attributeElement = null; //find existing var nodeList1 = xmlDoc.SelectNodes(@"//Attributes/ProductAttribute"); foreach (XmlNode node1 in nodeList1) { if (node1.Attributes != null && node1.Attributes["ID"] != null) { string str1 =node1.Attributes["ID"].InnerText.Trim(); int id; if (int.TryParse(str1, out id)) { if (id == productAttributeMapping.Id) { attributeElement = (XmlElement)node1; break; } } } } //create new one if not found if (attributeElement == null) { attributeElement = xmlDoc.CreateElement("ProductAttribute"); attributeElement.SetAttribute("ID", productAttributeMapping.Id.ToString()); rootElement.AppendChild(attributeElement); } var attributeValueElement = xmlDoc.CreateElement("ProductAttributeValue"); attributeElement.AppendChild(attributeValueElement); var attributeValueValueElement = xmlDoc.CreateElement("Value"); attributeValueValueElement.InnerText = value; attributeValueElement.AppendChild(attributeValueValueElement); result = xmlDoc.OuterXml; } catch (Exception exc) { Debug.Write(exc.ToString()); } return result; } /// <summary> /// Remove an attribute /// </summary> /// <param name="attributesXml">Attributes in XML format</param> /// <param name="productAttributeMapping">Product attribute mapping</param> /// <returns>Updated result (XML format)</returns> public virtual string RemoveProductAttribute(string attributesXml, ProductAttributeMapping productAttributeMapping) { string result = string.Empty; try { var xmlDoc = new XmlDocument(); if (String.IsNullOrEmpty(attributesXml)) { var element1 = xmlDoc.CreateElement("Attributes"); xmlDoc.AppendChild(element1); } else { xmlDoc.LoadXml(attributesXml); } var rootElement = (XmlElement)xmlDoc.SelectSingleNode(@"//Attributes"); XmlElement attributeElement = null; //find existing var nodeList1 = xmlDoc.SelectNodes(@"//Attributes/ProductAttribute"); foreach (XmlNode node1 in nodeList1) { if (node1.Attributes != null && node1.Attributes["ID"] != null) { string str1 = node1.Attributes["ID"].InnerText.Trim(); int id; if (int.TryParse(str1, out id)) { if (id == productAttributeMapping.Id) { attributeElement = (XmlElement)node1; break; } } } } //found if (attributeElement != null) { rootElement.RemoveChild(attributeElement); } result = xmlDoc.OuterXml; } catch (Exception exc) { Debug.Write(exc.ToString()); } return result; } /// <summary> /// Are attributes equal /// </summary> /// <param name="attributesXml1">The attributes of the first product</param> /// <param name="attributesXml2">The attributes of the second product</param> /// <param name="ignoreNonCombinableAttributes">A value indicating whether we should ignore non-combinable attributes</param> /// <returns>Result</returns> public virtual bool AreProductAttributesEqual(string attributesXml1, string attributesXml2, bool ignoreNonCombinableAttributes) { var attributes1 = ParseProductAttributeMappings(attributesXml1); if (ignoreNonCombinableAttributes) { attributes1 = attributes1.Where(x => !x.IsNonCombinable()).ToList(); } var attributes2 = ParseProductAttributeMappings(attributesXml2); if (ignoreNonCombinableAttributes) { attributes2 = attributes2.Where(x => !x.IsNonCombinable()).ToList(); } if (attributes1.Count != attributes2.Count) return false; bool attributesEqual = true; foreach (var a1 in attributes1) { bool hasAttribute = false; foreach (var a2 in attributes2) { if (a1.Id == a2.Id) { hasAttribute = true; var values1Str = ParseValues(attributesXml1, a1.Id); var values2Str = ParseValues(attributesXml2, a2.Id); if (values1Str.Count == values2Str.Count) { foreach (string str1 in values1Str) { bool hasValue = false; foreach (string str2 in values2Str) { //case insensitive? //if (str1.Trim().ToLower() == str2.Trim().ToLower()) if (str1.Trim() == str2.Trim()) { hasValue = true; break; } } if (!hasValue) { attributesEqual = false; break; } } } else { attributesEqual = false; break; } } } if (hasAttribute == false) { attributesEqual = false; break; } } return attributesEqual; } /// <summary> /// Check whether condition of some attribute is met (if specified). Return "null" if not condition is specified /// </summary> /// <param name="pam">Product attribute</param> /// <param name="selectedAttributesXml">Selected attributes (XML format)</param> /// <returns>Result</returns> public virtual bool? IsConditionMet(ProductAttributeMapping pam, string selectedAttributesXml) { if (pam == null) throw new ArgumentNullException("pam"); var conditionAttributeXml = pam.ConditionAttributeXml; if (String.IsNullOrEmpty(conditionAttributeXml)) //no condition return null; //load an attribute this one depends on var dependOnAttribute = ParseProductAttributeMappings(conditionAttributeXml).FirstOrDefault(); if (dependOnAttribute == null) return true; var valuesThatShouldBeSelected = ParseValues(conditionAttributeXml, dependOnAttribute.Id) //a workaround here: //ConditionAttributeXml can contain "empty" values (nothing is selected) //but in other cases (like below) we do not store empty values //that's why we remove empty values here .Where(x => !String.IsNullOrEmpty(x)) .ToList(); var selectedValues = ParseValues(selectedAttributesXml, dependOnAttribute.Id); if (valuesThatShouldBeSelected.Count != selectedValues.Count) return false; //compare values var allFound = true; foreach (var t1 in valuesThatShouldBeSelected) { bool found = false; foreach (var t2 in selectedValues) if (t1 == t2) found = true; if (!found) allFound = false; } return allFound; } /// <summary> /// Finds a product attribute combination by attributes stored in XML /// </summary> /// <param name="product">Product</param> /// <param name="attributesXml">Attributes in XML format</param> /// <param name="ignoreNonCombinableAttributes">A value indicating whether we should ignore non-combinable attributes</param> /// <returns>Found product attribute combination</returns> public virtual ProductAttributeCombination FindProductAttributeCombination(Product product, string attributesXml, bool ignoreNonCombinableAttributes = true) { if (product == null) throw new ArgumentNullException("product"); var combinations = _productAttributeService.GetAllProductAttributeCombinations(product.Id); return combinations.FirstOrDefault(x => AreProductAttributesEqual(x.AttributesXml, attributesXml, ignoreNonCombinableAttributes)); } /// <summary> /// Generate all combinations /// </summary> /// <param name="product">Product</param> /// <param name="ignoreNonCombinableAttributes">A value indicating whether we should ignore non-combinable attributes</param> /// <returns>Attribute combinations in XML format</returns> public virtual IList<string> GenerateAllCombinations(Product product, bool ignoreNonCombinableAttributes = false) { if (product == null) throw new ArgumentNullException("product"); var allProductAttributMappings = _productAttributeService.GetProductAttributeMappingsByProductId(product.Id); if (ignoreNonCombinableAttributes) { allProductAttributMappings = allProductAttributMappings.Where(x => !x.IsNonCombinable()).ToList(); } var allPossibleAttributeCombinations = new List<List<ProductAttributeMapping>>(); for (int counter = 0; counter < (1 << allProductAttributMappings.Count); ++counter) { var combination = new List<ProductAttributeMapping>(); for (int i = 0; i < allProductAttributMappings.Count; ++i) { if ((counter & (1 << i)) == 0) { combination.Add(allProductAttributMappings[i]); } } allPossibleAttributeCombinations.Add(combination); } var allAttributesXml = new List<string>(); foreach (var combination in allPossibleAttributeCombinations) { var attributesXml = new List<string>(); foreach (var pam in combination) { if (!pam.ShouldHaveValues()) continue; var attributeValues = _productAttributeService.GetProductAttributeValues(pam.Id); if (attributeValues.Count == 0) continue; //checkboxes could have several values ticked var allPossibleCheckboxCombinations = new List<List<ProductAttributeValue>>(); if (pam.AttributeControlType == AttributeControlType.Checkboxes || pam.AttributeControlType == AttributeControlType.ReadonlyCheckboxes) { for (int counter = 0; counter < (1 << attributeValues.Count); ++counter) { var checkboxCombination = new List<ProductAttributeValue>(); for (int i = 0; i < attributeValues.Count; ++i) { if ((counter & (1 << i)) == 0) { checkboxCombination.Add(attributeValues[i]); } } allPossibleCheckboxCombinations.Add(checkboxCombination); } } if (attributesXml.Count == 0) { //first set of values if (pam.AttributeControlType == AttributeControlType.Checkboxes || pam.AttributeControlType == AttributeControlType.ReadonlyCheckboxes) { //checkboxes could have several values ticked foreach (var checkboxCombination in allPossibleCheckboxCombinations) { var tmp1 = ""; foreach (var checkboxValue in checkboxCombination) { tmp1 = AddProductAttribute(tmp1, pam, checkboxValue.Id.ToString()); } if (!String.IsNullOrEmpty(tmp1)) { attributesXml.Add(tmp1); } } } else { //other attribute types (dropdownlist, radiobutton, color squares) foreach (var attributeValue in attributeValues) { var tmp1 = AddProductAttribute("", pam, attributeValue.Id.ToString()); attributesXml.Add(tmp1); } } } else { //next values. let's "append" them to already generated attribute combinations in XML format var attributesXmlTmp = new List<string>(); if (pam.AttributeControlType == AttributeControlType.Checkboxes || pam.AttributeControlType == AttributeControlType.ReadonlyCheckboxes) { //checkboxes could have several values ticked foreach (var str1 in attributesXml) { foreach (var checkboxCombination in allPossibleCheckboxCombinations) { var tmp1 = str1; foreach (var checkboxValue in checkboxCombination) { tmp1 = AddProductAttribute(tmp1, pam, checkboxValue.Id.ToString()); } if (!String.IsNullOrEmpty(tmp1)) { attributesXmlTmp.Add(tmp1); } } } } else { //other attribute types (dropdownlist, radiobutton, color squares) foreach (var attributeValue in attributeValues) { foreach (var str1 in attributesXml) { var tmp1 = AddProductAttribute(str1, pam, attributeValue.Id.ToString()); attributesXmlTmp.Add(tmp1); } } } attributesXml.Clear(); attributesXml.AddRange(attributesXmlTmp); } } allAttributesXml.AddRange(attributesXml); } return allAttributesXml; } #endregion #region Gift card attributes /// <summary> /// Add gift card attrbibutes /// </summary> /// <param name="attributesXml">Attributes in XML format</param> /// <param name="recipientName">Recipient name</param> /// <param name="recipientEmail">Recipient email</param> /// <param name="senderName">Sender name</param> /// <param name="senderEmail">Sender email</param> /// <param name="giftCardMessage">Message</param> /// <returns>Attributes</returns> public string AddGiftCardAttribute(string attributesXml, string recipientName, string recipientEmail, string senderName, string senderEmail, string giftCardMessage) { string result = string.Empty; try { recipientName = recipientName.Trim(); recipientEmail = recipientEmail.Trim(); senderName = senderName.Trim(); senderEmail = senderEmail.Trim(); var xmlDoc = new XmlDocument(); if (String.IsNullOrEmpty(attributesXml)) { var element1 = xmlDoc.CreateElement("Attributes"); xmlDoc.AppendChild(element1); } else { xmlDoc.LoadXml(attributesXml); } var rootElement = (XmlElement)xmlDoc.SelectSingleNode(@"//Attributes"); var giftCardElement = (XmlElement)xmlDoc.SelectSingleNode(@"//Attributes/GiftCardInfo"); if (giftCardElement == null) { giftCardElement = xmlDoc.CreateElement("GiftCardInfo"); rootElement.AppendChild(giftCardElement); } var recipientNameElement = xmlDoc.CreateElement("RecipientName"); recipientNameElement.InnerText = recipientName; giftCardElement.AppendChild(recipientNameElement); var recipientEmailElement = xmlDoc.CreateElement("RecipientEmail"); recipientEmailElement.InnerText = recipientEmail; giftCardElement.AppendChild(recipientEmailElement); var senderNameElement = xmlDoc.CreateElement("SenderName"); senderNameElement.InnerText = senderName; giftCardElement.AppendChild(senderNameElement); var senderEmailElement = xmlDoc.CreateElement("SenderEmail"); senderEmailElement.InnerText = senderEmail; giftCardElement.AppendChild(senderEmailElement); var messageElement = xmlDoc.CreateElement("Message"); messageElement.InnerText = giftCardMessage; giftCardElement.AppendChild(messageElement); result = xmlDoc.OuterXml; } catch (Exception exc) { Debug.Write(exc.ToString()); } return result; } /// <summary> /// Get gift card attrbibutes /// </summary> /// <param name="attributesXml">Attributes</param> /// <param name="recipientName">Recipient name</param> /// <param name="recipientEmail">Recipient email</param> /// <param name="senderName">Sender name</param> /// <param name="senderEmail">Sender email</param> /// <param name="giftCardMessage">Message</param> public void GetGiftCardAttribute(string attributesXml, out string recipientName, out string recipientEmail, out string senderName, out string senderEmail, out string giftCardMessage) { recipientName = string.Empty; recipientEmail = string.Empty; senderName = string.Empty; senderEmail = string.Empty; giftCardMessage = string.Empty; try { var xmlDoc = new XmlDocument(); xmlDoc.LoadXml(attributesXml); var recipientNameElement = (XmlElement)xmlDoc.SelectSingleNode(@"//Attributes/GiftCardInfo/RecipientName"); var recipientEmailElement = (XmlElement)xmlDoc.SelectSingleNode(@"//Attributes/GiftCardInfo/RecipientEmail"); var senderNameElement = (XmlElement)xmlDoc.SelectSingleNode(@"//Attributes/GiftCardInfo/SenderName"); var senderEmailElement = (XmlElement)xmlDoc.SelectSingleNode(@"//Attributes/GiftCardInfo/SenderEmail"); var messageElement = (XmlElement)xmlDoc.SelectSingleNode(@"//Attributes/GiftCardInfo/Message"); if (recipientNameElement != null) recipientName = recipientNameElement.InnerText; if (recipientEmailElement != null) recipientEmail = recipientEmailElement.InnerText; if (senderNameElement != null) senderName = senderNameElement.InnerText; if (senderEmailElement != null) senderEmail = senderEmailElement.InnerText; if (messageElement != null) giftCardMessage = messageElement.InnerText; } catch (Exception exc) { Debug.Write(exc.ToString()); } } #endregion } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using NLog.Config; #if !MONO && !NETSTANDARD namespace NLog.UnitTests.Targets { using System.Collections.Generic; using System.Messaging; using NLog.Targets; using Xunit; public class MessageQueueTargetTests : NLogTestBase { [Fact] public void QueueExists_Write_MessageIsWritten() { var messageQueueTestProxy = new MessageQueueTestProxy { QueueExists = true, }; var target = CreateTarget(messageQueueTestProxy, false); target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(_ => { })); Assert.Equal(1, messageQueueTestProxy.SentMessages.Count); } [Fact] public void QueueDoesNotExistsAndDoNotCreate_Write_NothingIsWritten() { var messageQueueTestProxy = new MessageQueueTestProxy { QueueExists = false, }; var target = CreateTarget(messageQueueTestProxy, false); target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(_ => { })); Assert.Equal(0, messageQueueTestProxy.SentMessages.Count); } [Fact] public void QueueDoesNotExistsAndCreatedQueue_Write_QueueIsCreated() { var messageQueueTestProxy = new MessageQueueTestProxy { QueueExists = false, }; var target = CreateTarget(messageQueueTestProxy, true); target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(_ => { })); Assert.True(messageQueueTestProxy.QueueCreated); } [Fact] public void QueueDoesNotExistsAndCreatedQueue_Write_MessageIsWritten() { var messageQueueTestProxy = new MessageQueueTestProxy { QueueExists = false, }; var target = CreateTarget(messageQueueTestProxy, true); target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(_ => { })); Assert.Equal(1, messageQueueTestProxy.SentMessages.Count); } [Fact] public void FormatQueueName_Write_DoesNotCheckIfQueueExists() { var messageQueueTestProxy = new MessageQueueTestProxy(); var target = CreateTarget(messageQueueTestProxy, false, "DIRECT=http://test.com/MSMQ/queue"); target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(_ => { })); Assert.False(messageQueueTestProxy.QueueExistsCalled); } [Fact] public void DoNotCheckIfQueueExists_Write_DoesNotCheckIfQueueExists() { var messageQueueTestProxy = new MessageQueueTestProxy(); var target = CreateTarget(messageQueueTestProxy, false, checkIfQueueExists: false); target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(_ => { })); Assert.False(messageQueueTestProxy.QueueExistsCalled); } /// <summary> /// Checks if setting the CheckIfQueueExists is working /// </summary> [Fact] public void MessageQueueTarget_CheckIfQueueExists_setting_should_work() { var configuration = XmlLoggingConfiguration.CreateFromXmlString(string.Format(@" <nlog throwExceptions='true' > <targets> <target type='MSMQ' name='q' checkIfQueueExists='False' queue='queue1' > </target> </targets> <rules> <logger name='*' writeTo='q'> </logger> </rules> </nlog>")); LogManager.Configuration = configuration; var messageQueueTarget = configuration.FindTargetByName("q") as MessageQueueTarget; Assert.NotNull(messageQueueTarget); Assert.False(messageQueueTarget.CheckIfQueueExists); } private static MessageQueueTarget CreateTarget(MessageQueueProxy messageQueueTestProxy, bool createQueue, string queueName = "Test", bool checkIfQueueExists = true) { var target = new MessageQueueTarget { MessageQueueProxy = messageQueueTestProxy, Queue = queueName, CreateQueueIfNotExists = createQueue, CheckIfQueueExists = checkIfQueueExists, }; target.Initialize(null); return target; } internal class MessageQueueTestProxy : MessageQueueProxy { public IList<Message> SentMessages { get; private set; } public bool QueueExists { get; set; } public bool QueueCreated { get; private set; } public bool QueueExistsCalled { get; private set; } public MessageQueueTestProxy() { SentMessages = new List<Message>(); } public override bool Exists(string queue) { QueueExistsCalled = true; return QueueExists; } public override void Create(string queue) { QueueCreated = true; } public override void Send(string queue, Message message) { SentMessages.Add(message); } } } } #endif
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsAzureParameterGrouping { using Fixtures.Azure; 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> /// ParameterGroupingOperations operations. /// </summary> internal partial class ParameterGroupingOperations : IServiceOperations<AutoRestParameterGroupingTestService>, IParameterGroupingOperations { /// <summary> /// Initializes a new instance of the ParameterGroupingOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ParameterGroupingOperations(AutoRestParameterGroupingTestService client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the AutoRestParameterGroupingTestService /// </summary> public AutoRestParameterGroupingTestService Client { get; private set; } /// <summary> /// Post a bunch of required parameters grouped /// </summary> /// <param name='parameterGroupingPostRequiredParameters'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <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> PostRequiredWithHttpMessagesAsync(ParameterGroupingPostRequiredParametersInner parameterGroupingPostRequiredParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (parameterGroupingPostRequiredParameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameterGroupingPostRequiredParameters"); } if (parameterGroupingPostRequiredParameters != null) { parameterGroupingPostRequiredParameters.Validate(); } int body = default(int); if (parameterGroupingPostRequiredParameters != null) { body = parameterGroupingPostRequiredParameters.Body; } string customHeader = default(string); if (parameterGroupingPostRequiredParameters != null) { customHeader = parameterGroupingPostRequiredParameters.CustomHeader; } int? query = default(int?); if (parameterGroupingPostRequiredParameters != null) { query = parameterGroupingPostRequiredParameters.Query; } string path = default(string); if (parameterGroupingPostRequiredParameters != null) { path = parameterGroupingPostRequiredParameters.Path; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("body", body); tracingParameters.Add("customHeader", customHeader); tracingParameters.Add("query", query); tracingParameters.Add("path", path); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PostRequired", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "parameterGrouping/postRequired/{path}").ToString(); _url = _url.Replace("{path}", System.Uri.EscapeDataString(path)); List<string> _queryParameters = new List<string>(); if (query != null) { _queryParameters.Add(string.Format("query={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(query, Client.SerializationSettings).Trim('"')))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeader != null) { if (_httpRequest.Headers.Contains("customHeader")) { _httpRequest.Headers.Remove("customHeader"); } _httpRequest.Headers.TryAddWithoutValidation("customHeader", customHeader); } 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; _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _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> /// Post a bunch of optional parameters grouped /// </summary> /// <param name='parameterGroupingPostOptionalParameters'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> PostOptionalWithHttpMessagesAsync(ParameterGroupingPostOptionalParametersInner parameterGroupingPostOptionalParameters = default(ParameterGroupingPostOptionalParametersInner), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { string customHeader = default(string); if (parameterGroupingPostOptionalParameters != null) { customHeader = parameterGroupingPostOptionalParameters.CustomHeader; } int? query = default(int?); if (parameterGroupingPostOptionalParameters != null) { query = parameterGroupingPostOptionalParameters.Query; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("customHeader", customHeader); tracingParameters.Add("query", query); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PostOptional", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "parameterGrouping/postOptional").ToString(); List<string> _queryParameters = new List<string>(); if (query != null) { _queryParameters.Add(string.Format("query={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(query, Client.SerializationSettings).Trim('"')))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeader != null) { if (_httpRequest.Headers.Contains("customHeader")) { _httpRequest.Headers.Remove("customHeader"); } _httpRequest.Headers.TryAddWithoutValidation("customHeader", customHeader); } 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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _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> /// Post parameters from multiple different parameter groups /// </summary> /// <param name='firstParameterGroup'> /// Additional parameters for the operation /// </param> /// <param name='parameterGroupingPostMultiParamGroupsSecondParamGroup'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> PostMultiParamGroupsWithHttpMessagesAsync(FirstParameterGroupInner firstParameterGroup = default(FirstParameterGroupInner), ParameterGroupingPostMultiParamGroupsSecondParamGroupInner parameterGroupingPostMultiParamGroupsSecondParamGroup = default(ParameterGroupingPostMultiParamGroupsSecondParamGroupInner), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { string headerOne = default(string); if (firstParameterGroup != null) { headerOne = firstParameterGroup.HeaderOne; } int? queryOne = default(int?); if (firstParameterGroup != null) { queryOne = firstParameterGroup.QueryOne; } string headerTwo = default(string); if (parameterGroupingPostMultiParamGroupsSecondParamGroup != null) { headerTwo = parameterGroupingPostMultiParamGroupsSecondParamGroup.HeaderTwo; } int? queryTwo = default(int?); if (parameterGroupingPostMultiParamGroupsSecondParamGroup != null) { queryTwo = parameterGroupingPostMultiParamGroupsSecondParamGroup.QueryTwo; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("headerOne", headerOne); tracingParameters.Add("queryOne", queryOne); tracingParameters.Add("headerTwo", headerTwo); tracingParameters.Add("queryTwo", queryTwo); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PostMultiParamGroups", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "parameterGrouping/postMultipleParameterGroups").ToString(); List<string> _queryParameters = new List<string>(); if (queryOne != null) { _queryParameters.Add(string.Format("query-one={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(queryOne, Client.SerializationSettings).Trim('"')))); } if (queryTwo != null) { _queryParameters.Add(string.Format("query-two={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(queryTwo, Client.SerializationSettings).Trim('"')))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (headerOne != null) { if (_httpRequest.Headers.Contains("header-one")) { _httpRequest.Headers.Remove("header-one"); } _httpRequest.Headers.TryAddWithoutValidation("header-one", headerOne); } if (headerTwo != null) { if (_httpRequest.Headers.Contains("header-two")) { _httpRequest.Headers.Remove("header-two"); } _httpRequest.Headers.TryAddWithoutValidation("header-two", headerTwo); } 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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _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> /// Post parameters with a shared parameter group object /// </summary> /// <param name='firstParameterGroup'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> PostSharedParameterGroupObjectWithHttpMessagesAsync(FirstParameterGroupInner firstParameterGroup = default(FirstParameterGroupInner), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { string headerOne = default(string); if (firstParameterGroup != null) { headerOne = firstParameterGroup.HeaderOne; } int? queryOne = default(int?); if (firstParameterGroup != null) { queryOne = firstParameterGroup.QueryOne; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("headerOne", headerOne); tracingParameters.Add("queryOne", queryOne); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PostSharedParameterGroupObject", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "parameterGrouping/sharedParameterGroupObject").ToString(); List<string> _queryParameters = new List<string>(); if (queryOne != null) { _queryParameters.Add(string.Format("query-one={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(queryOne, Client.SerializationSettings).Trim('"')))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (headerOne != null) { if (_httpRequest.Headers.Contains("header-one")) { _httpRequest.Headers.Remove("header-one"); } _httpRequest.Headers.TryAddWithoutValidation("header-one", headerOne); } 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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _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; } } }
// 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.IO; using System.Xml; using System.Collections; using OLEDB.Test.ModuleCore; using XmlCoreTest.Common; namespace XmlReaderTest.Common { ///////////////////////////////////////////////////////////////////////// // TestCase ReadOuterXml // ///////////////////////////////////////////////////////////////////////// [InheritRequired()] public abstract partial class TCReadToDescendant : TCXMLReaderBaseGeneral { #region XMLSTR private string _xmlStr = @"<?xml version='1.0'?> <root><!--Comment--> <elem><!-- Comment --> <child1 att='1'><?pi target?> <child2 xmlns='child2'> <child3/> blahblahblah<![CDATA[ blah ]]> <child4/> </child2> <?pi target1?> </child1> </elem> <elem att='1'> <child1 att='1'> <child2 xmlns='child2'> <child3/> blahblahblah <child4/> </child2> <?pi target1?> </child1> </elem> <elem xmlns='elem'> <child1 att='1'> <child2 xmlns='child2'> <child3/> blahblahblah2 <child4/> </child2> </child1> </elem> <elem xmlns='elem' att='1'> <child1 att='1'> <child2 xmlns='child2'> <child3/> blahblahblah2 <child4/> </child2> </child1> </elem> <e:elem xmlns:e='elem2'> <e:child1 att='1'> <e:child2 xmlns='child2'> <e:child3/> blahblahblah2 <e:child4/> </e:child2> </e:child1> </e:elem> <e:elem xmlns:e='elem2' att='1'> <e:child1 att='1'> <e:child2 xmlns='child2'> <e:child3/> blahblahblah2 <e:child4/> </e:child2> </e:child1> </e:elem> </root>"; #endregion //[Variation("Simple positive test", Pri = 0, Params = new object[] { "NNS" })] //[Variation("Simple positive test", Pri = 0, Params = new object[] { "DNS" })] //[Variation("Simple positive test", Pri = 0, Params = new object[] { "NS" })] public int v() { string type = CurVariation.Params[0].ToString(); CError.WriteLine("Test Type : " + type); ReloadSource(new StringReader(_xmlStr)); DataReader.PositionOnElement("root"); switch (type) { case "NNS": DataReader.ReadToDescendant("elem"); if (DataReader.HasAttributes) { CError.WriteLine("Positioned on wrong element"); CError.WriteIgnore(DataReader.ReadInnerXml() + "\n"); return TEST_FAIL; } while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; case "DNS": DataReader.ReadToDescendant("elem", "elem"); if (DataReader.HasAttributes) { if (DataReader.GetAttribute("xmlns") == null) { CError.WriteLine("Positioned on wrong element, not on DNS"); return TEST_FAIL; } } while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; case "NS": DataReader.ReadToDescendant("e:elem"); if (DataReader.HasAttributes) { if (DataReader.GetAttribute("xmlns:e") == null) { CError.WriteLine("Positioned on wrong element, not on NS"); return TEST_FAIL; } } while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; default: throw new CTestFailedException("Error in Test type"); } } [Variation("Read on a deep tree atleast more than 4K boundary", Pri = 2)] public int v2() { ManagedNodeWriter mnw = new ManagedNodeWriter(); mnw.PutPattern("X"); int count = 0; do { mnw.PutPattern("E/"); count++; } while (mnw.GetNodes().Length < 4096); mnw.PutText("<a/>"); mnw.Finish(); CError.WriteIgnore(mnw.GetNodes() + "\n"); ReloadSource(new StringReader(mnw.GetNodes())); DataReader.PositionOnElement("ELEMENT_1"); CError.WriteLine("Reading to : " + "a"); DataReader.ReadToDescendant("a"); CError.Compare(DataReader.Depth, count, "Depth is not correct"); CError.Compare(DataReader.NodeType, XmlNodeType.Element, "Nodetype is not correct"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } [Variation("Read on a deep tree atleast more than 65535 boundary", Pri = 2)] public int v2_1() { ManagedNodeWriter mnw = new ManagedNodeWriter(); mnw.PutPattern("X"); int count = 0; do { mnw.PutPattern("E/"); count++; } while (count < 65536); mnw.PutText("<a/>"); mnw.Finish(); ReloadSource(new StringReader(mnw.GetNodes())); DataReader.PositionOnElement("ELEMENT_1"); CError.WriteLine("Reading to : a"); DataReader.ReadToDescendant("a"); CError.Compare(DataReader.Depth, 65536, "Depth is not correct"); CError.Compare(DataReader.NodeType, XmlNodeType.Element, "Nodetype is not correct"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } //[Variation("Read on descendant with same names", Pri = 1, Params = new object[] { "NNS" })] //[Variation("Read on descendant with same names", Pri = 1, Params = new object[] { "DNS" })] //[Variation("Read on descendant with same names", Pri = 1, Params = new object[] { "NS" })] public int v3() { string type = CurVariation.Params[0].ToString(); CError.WriteLine("Test Type : " + type); ReloadSource(new StringReader(_xmlStr)); DataReader.PositionOnElement("root"); //Doing a sequential read. switch (type) { case "NNS": DataReader.ReadToDescendant("elem"); int depth = DataReader.Depth; if (DataReader.HasAttributes) { CError.WriteLine("Positioned on wrong element"); return TEST_FAIL; } CError.Compare(DataReader.ReadToDescendant("elem"), false, "There are no more descendants"); CError.Compare(DataReader.NodeType, XmlNodeType.EndElement, "Wrong node type"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; case "DNS": DataReader.ReadToDescendant("elem", "elem"); if (DataReader.HasAttributes) { if (DataReader.GetAttribute("xmlns") == null) { CError.WriteLine("Positioned on wrong element, not on DNS"); return TEST_FAIL; } } CError.Compare(DataReader.ReadToDescendant("elem", "elem"), false, "There are no more descendants"); CError.Compare(DataReader.NodeType, XmlNodeType.EndElement, "Wrong node type"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; case "NS": DataReader.ReadToDescendant("e:elem"); if (DataReader.HasAttributes) { if (DataReader.GetAttribute("xmlns:e") == null) { CError.WriteLine("Positioned on wrong element, not on DNS"); return TEST_FAIL; } } CError.Compare(DataReader.ReadToDescendant("e:elem"), false, "There are no more descendants"); CError.Compare(DataReader.NodeType, XmlNodeType.EndElement, "Wrong node type"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; default: throw new CTestFailedException("Error in Test type"); } } [Variation("If name not found, stop at end element of the subtree", Pri = 1)] public int v4() { ReloadSource(new StringReader(_xmlStr)); DataReader.PositionOnElement("elem"); CError.Compare(DataReader.ReadToDescendant("abc"), false, "Reader returned true for an invalid name"); CError.Compare(DataReader.NodeType, XmlNodeType.EndElement, "Wrong node type"); DataReader.Read(); CError.Compare(DataReader.ReadToDescendant("abc", "elem"), false, "reader returned true for an invalid name,ns combination"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } [Variation("Positioning on a level and try to find the name which is on a level higher", Pri = 1)] public int v5() { ReloadSource(new StringReader(_xmlStr)); DataReader.PositionOnElement("child3"); CError.Compare(DataReader.ReadToDescendant("child1"), false, "Reader returned true for an invalid name"); CError.Compare(DataReader.NodeType, XmlNodeType.Element, "Wrong node type"); CError.Compare(DataReader.LocalName, "child3", "Wrong name"); DataReader.PositionOnElement("child3"); CError.Compare(DataReader.ReadToDescendant("child2", "child2"), false, "Reader returned true for an invalid name,ns"); CError.Compare(DataReader.NodeType, XmlNodeType.Element, "Wrong node type for name,ns"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } [Variation("Read to Descendant on one level and again to level below it", Pri = 1)] public int v6() { ReloadSource(new StringReader(_xmlStr)); DataReader.PositionOnElement("root"); CError.Compare(DataReader.ReadToDescendant("elem"), true, "Cant find elem"); CError.Compare(DataReader.ReadToDescendant("child1"), true, "Cant find child1"); CError.Compare(DataReader.ReadToDescendant("child2"), true, "Cant find child2"); CError.Compare(DataReader.ReadToDescendant("child3"), true, "Cant find child3"); CError.Compare(DataReader.ReadToDescendant("child4"), false, "shouldnt find child4"); CError.Compare(DataReader.NodeType, XmlNodeType.Element, "Not on EndElement"); DataReader.Read(); CError.Compare(DataReader.NodeType, XmlNodeType.Text, "Not on Element"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } [Variation("Read to Descendant on one level and again to level below it, with namespace", Pri = 1)] public int v7() { ReloadSource(new StringReader(_xmlStr)); DataReader.PositionOnElement("root"); CError.Compare(DataReader.ReadToDescendant("elem", "elem"), true, "Cant find elem"); CError.Compare(DataReader.ReadToDescendant("child1", "elem"), true, "Cant find child1"); CError.Compare(DataReader.ReadToDescendant("child2", "child2"), true, "Cant find child2"); CError.Compare(DataReader.ReadToDescendant("child3", "child2"), true, "Cant find child3"); CError.Compare(DataReader.ReadToDescendant("child4", "child2"), false, "shouldnt find child4"); CError.Compare(DataReader.NodeType, XmlNodeType.Element, "Not on EndElement"); DataReader.Read(); CError.Compare(DataReader.NodeType, XmlNodeType.Text, "Not on Element"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } [Variation("Read to Descendant on one level and again to level below it, with prefix", Pri = 1)] public int v8() { ReloadSource(new StringReader(_xmlStr)); DataReader.PositionOnElement("root"); CError.Compare(DataReader.ReadToDescendant("e:elem"), true, "Cant find elem"); CError.Compare(DataReader.ReadToDescendant("e:child1"), true, "Cant find child1"); CError.Compare(DataReader.ReadToDescendant("e:child2"), true, "Cant find child2"); CError.Compare(DataReader.ReadToDescendant("e:child3"), true, "Cant find child3"); CError.Compare(DataReader.ReadToDescendant("e:child4"), false, "shouldnt find child4"); CError.Compare(DataReader.NodeType, XmlNodeType.Element, "Not on EndElement"); DataReader.Read(); CError.Compare(DataReader.NodeType, XmlNodeType.Text, "Not on Element"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } [Variation("Multiple Reads to children and then next siblings, NNS", Pri = 2)] public int v9() { ReloadSource(new StringReader(_xmlStr)); DataReader.PositionOnElement("root"); CError.Compare(DataReader.ReadToDescendant("elem"), true, "Read fails elem"); CError.Compare(DataReader.ReadToDescendant("child3"), true, "Read fails child3"); CError.Compare(DataReader.ReadToNextSibling("child4"), true, "Read fails child4"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } [Variation("Multiple Reads to children and then next siblings, DNS", Pri = 2)] public int v10() { ReloadSource(new StringReader(_xmlStr)); DataReader.PositionOnElement("root"); CError.Compare(DataReader.ReadToDescendant("elem", "elem"), true, "Read fails elem"); CError.Compare(DataReader.ReadToDescendant("child3", "child2"), true, "Read fails child3"); CError.Compare(DataReader.ReadToNextSibling("child4", "child2"), true, "Read fails child4"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } [Variation("Multiple Reads to children and then next siblings, NS", Pri = 2)] public int v11() { ReloadSource(new StringReader(_xmlStr)); DataReader.PositionOnElement("root"); CError.Compare(DataReader.ReadToDescendant("e:elem"), true, "Read fails elem"); CError.Compare(DataReader.ReadToDescendant("e:child3"), true, "Read fails child3"); CError.Compare(DataReader.ReadToNextSibling("e:child4"), true, "Read fails child4"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } [Variation("Call from different nodetypes", Pri = 1)] public int v12() { ReloadSource(new StringReader(_xmlStr)); while (DataReader.Read()) { if (DataReader.NodeType != XmlNodeType.Element) { CError.WriteLine(DataReader.NodeType.ToString()); CError.Compare(DataReader.ReadToDescendant("child1"), false, "Fails on node"); } else { if (DataReader.HasAttributes) { while (DataReader.MoveToNextAttribute()) { CError.Compare(DataReader.ReadToDescendant("abc"), false, "Fails on attribute node"); } } } } DataReader.Close(); return TEST_PASS; } [Variation("Interaction with MoveToContent", Pri = 2)] public int v13() { return TEST_SKIPPED; } [Variation("Only child has namespaces and read to it", Pri = 2)] public int v14() { ReloadSource(new StringReader(_xmlStr)); DataReader.PositionOnElement("root"); CError.Compare(DataReader.ReadToDescendant("child2", "child2"), true, "Fails on attribute node"); DataReader.Close(); return TEST_PASS; } [Variation("Pass null to both arguments throws ArgumentException", Pri = 2)] public int v15() { ReloadSource(new StringReader("<root><b/></root>")); DataReader.Read(); if (IsBinaryReader()) DataReader.Read(); try { DataReader.ReadToDescendant(null); } catch (ArgumentNullException) { CError.WriteLine("Caught for single param"); } try { DataReader.ReadToDescendant("b", null); } catch (ArgumentNullException) { CError.WriteLine("Caught for single param"); } while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } [Variation("Different names, same uri works correctly", Pri = 2)] public int v17() { ReloadSource(new StringReader("<root><child1 xmlns='foo'/>blah<child1 xmlns='bar'>blah</child1></root>")); DataReader.Read(); if (IsBinaryReader()) DataReader.Read(); DataReader.ReadToDescendant("child1", "bar"); CError.Compare(DataReader.IsEmptyElement, false, "Not on the correct node"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } //[Variation("On Root Node", Pri = 0, Params = new object[] { "NNS" })] //[Variation("On Root Node", Pri = 0, Params = new object[] { "DNS" })] //[Variation("On Root Node", Pri = 0, Params = new object[] { "NS" })] public int v18() { string type = CurVariation.Params[0].ToString(); CError.WriteLine("Test Type : " + type); ReloadSource(new StringReader(_xmlStr)); switch (type) { case "NNS": DataReader.ReadToDescendant("elem"); if (DataReader.HasAttributes) { CError.WriteLine("Positioned on wrong element"); CError.WriteIgnore(DataReader.ReadInnerXml() + "\n"); return TEST_FAIL; } while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; case "DNS": DataReader.ReadToDescendant("elem", "elem"); if (DataReader.HasAttributes) { if (DataReader.GetAttribute("xmlns") == null) { CError.WriteLine("Positioned on wrong element, not on DNS"); return TEST_FAIL; } } while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; case "NS": DataReader.ReadToDescendant("e:elem"); if (DataReader.HasAttributes) { if (DataReader.GetAttribute("xmlns:e") == null) { CError.WriteLine("Positioned on wrong element, not on NS"); return TEST_FAIL; } } while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; default: throw new CTestFailedException("Error in Test type"); } } [Variation("Assertion failed when call XmlReader.ReadToDescendant() for non-existing node", Pri = 1)] public int v19() { ReloadSource(new StringReader("<a>b</a>")); CError.Compare(DataReader.ReadToDescendant("foo"), false, "Should fail without assert"); DataReader.Close(); return TEST_PASS; } } }
using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.Runtime.InteropServices; using System.Security.Permissions; using System.Diagnostics.CodeAnalysis; namespace WeifenLuo.WinFormsUI.Docking { [ToolboxItem(false)] public partial class DockPane : UserControl, IDockDragSource { public enum AppearanceStyle { ToolWindow, Document } private enum HitTestArea { Caption, TabStrip, Content, None } private struct HitTestResult { public HitTestArea HitArea; public int Index; public HitTestResult(HitTestArea hitTestArea, int index) { HitArea = hitTestArea; Index = index; } } private DockPaneCaptionBase m_captionControl; private DockPaneCaptionBase CaptionControl { get { return m_captionControl; } } private DockPaneStripBase m_tabStripControl; public DockPaneStripBase TabStripControl { get { return m_tabStripControl; } } internal protected DockPane(IDockContent content, DockState visibleState, bool show) { InternalConstruct(content, visibleState, false, Rectangle.Empty, null, DockAlignment.Right, 0.5, show); } [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", MessageId = "1#")] internal protected DockPane(IDockContent content, FloatWindow floatWindow, bool show) { if (floatWindow == null) throw new ArgumentNullException("floatWindow"); InternalConstruct(content, DockState.Float, false, Rectangle.Empty, floatWindow.NestedPanes.GetDefaultPreviousPane(this), DockAlignment.Right, 0.5, show); } internal protected DockPane(IDockContent content, DockPane previousPane, DockAlignment alignment, double proportion, bool show) { if (previousPane == null) throw (new ArgumentNullException("previousPane")); InternalConstruct(content, previousPane.DockState, false, Rectangle.Empty, previousPane, alignment, proportion, show); } [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", MessageId = "1#")] internal protected DockPane(IDockContent content, Rectangle floatWindowBounds, bool show) { InternalConstruct(content, DockState.Float, true, floatWindowBounds, null, DockAlignment.Right, 0.5, show); } private void InternalConstruct(IDockContent content, DockState dockState, bool flagBounds, Rectangle floatWindowBounds, DockPane prevPane, DockAlignment alignment, double proportion, bool show) { if (dockState == DockState.Hidden || dockState == DockState.Unknown) throw new ArgumentException(Strings.DockPane_SetDockState_InvalidState); if (content == null) throw new ArgumentNullException(Strings.DockPane_Constructor_NullContent); if (content.DockHandler.DockPanel == null) throw new ArgumentException(Strings.DockPane_Constructor_NullDockPanel); SuspendLayout(); SetStyle(ControlStyles.Selectable, false); m_isFloat = (dockState == DockState.Float); m_contents = new DockContentCollection(); m_displayingContents = new DockContentCollection(this); m_dockPanel = content.DockHandler.DockPanel; m_dockPanel.AddPane(this); m_splitter = content.DockHandler.DockPanel.Extender.DockPaneSplitterControlFactory.CreateSplitterControl(this); m_nestedDockingStatus = new NestedDockingStatus(this); m_captionControl = DockPanel.DockPaneCaptionFactory.CreateDockPaneCaption(this); m_tabStripControl = DockPanel.DockPaneStripFactory.CreateDockPaneStrip(this); Controls.AddRange(new Control[] { m_captionControl, m_tabStripControl }); DockPanel.SuspendLayout(true); if (flagBounds) FloatWindow = DockPanel.FloatWindowFactory.CreateFloatWindow(DockPanel, this, floatWindowBounds); else if (prevPane != null) DockTo(prevPane.NestedPanesContainer, prevPane, alignment, proportion); SetDockState(dockState); if (show) content.DockHandler.Pane = this; else if (this.IsFloat) content.DockHandler.FloatPane = this; else content.DockHandler.PanelPane = this; ResumeLayout(); DockPanel.ResumeLayout(true, true); } private bool m_isDisposing; protected override void Dispose(bool disposing) { if (disposing) { // IMPORTANT: avoid nested call into this method on Mono. // https://github.com/dockpanelsuite/dockpanelsuite/issues/16 if (Win32Helper.IsRunningOnMono) { if (m_isDisposing) return; m_isDisposing = true; } m_dockState = DockState.Unknown; if (NestedPanesContainer != null) NestedPanesContainer.NestedPanes.Remove(this); if (DockPanel != null) { DockPanel.RemovePane(this); m_dockPanel = null; } Splitter.Dispose(); if (m_autoHidePane != null) m_autoHidePane.Dispose(); } base.Dispose(disposing); } private IDockContent m_activeContent = null; public virtual IDockContent ActiveContent { get { return m_activeContent; } set { if (ActiveContent == value) return; if (value != null) { if (!DisplayingContents.Contains(value)) throw (new InvalidOperationException(Strings.DockPane_ActiveContent_InvalidValue)); } else { if (DisplayingContents.Count != 0) throw (new InvalidOperationException(Strings.DockPane_ActiveContent_InvalidValue)); } IDockContent oldValue = m_activeContent; if (DockPanel.ActiveAutoHideContent == oldValue) DockPanel.ActiveAutoHideContent = null; m_activeContent = value; if (DockPanel.DocumentStyle == DocumentStyle.DockingMdi && DockState == DockState.Document) { if (m_activeContent != null) m_activeContent.DockHandler.Form.BringToFront(); } else { if (m_activeContent != null) m_activeContent.DockHandler.SetVisible(); if (oldValue != null && DisplayingContents.Contains(oldValue)) oldValue.DockHandler.SetVisible(); if (IsActivated && m_activeContent != null) m_activeContent.DockHandler.Activate(); } if (FloatWindow != null) FloatWindow.SetText(); if (DockPanel.DocumentStyle == DocumentStyle.DockingMdi && DockState == DockState.Document) RefreshChanges(false); // delayed layout to reduce screen flicker else RefreshChanges(); if (m_activeContent != null) TabStripControl.EnsureTabVisible(m_activeContent); } } private bool m_allowDockDragAndDrop = true; public virtual bool AllowDockDragAndDrop { get { return m_allowDockDragAndDrop; } set { m_allowDockDragAndDrop = value; } } private IDisposable m_autoHidePane = null; internal IDisposable AutoHidePane { get { return m_autoHidePane; } set { m_autoHidePane = value; } } private object m_autoHideTabs = null; internal object AutoHideTabs { get { return m_autoHideTabs; } set { m_autoHideTabs = value; } } private object TabPageContextMenu { get { IDockContent content = ActiveContent; if (content == null) return null; if (content.DockHandler.TabPageContextMenuStrip != null) return content.DockHandler.TabPageContextMenuStrip; else if (content.DockHandler.TabPageContextMenu != null) return content.DockHandler.TabPageContextMenu; else return null; } } internal bool HasTabPageContextMenu { get { return TabPageContextMenu != null; } } internal void ShowTabPageContextMenu(Control control, Point position) { object menu = TabPageContextMenu; if (menu == null) return; ContextMenuStrip contextMenuStrip = menu as ContextMenuStrip; if (contextMenuStrip != null) { contextMenuStrip.Show(control, position); return; } ContextMenu contextMenu = menu as ContextMenu; if (contextMenu != null) contextMenu.Show(this, position); } private Rectangle CaptionRectangle { get { if (!HasCaption) return Rectangle.Empty; Rectangle rectWindow = DisplayingRectangle; int x, y, width; x = rectWindow.X; y = rectWindow.Y; width = rectWindow.Width; int height = CaptionControl.MeasureHeight(); return new Rectangle(x, y, width, height); } } internal Rectangle ContentRectangle { get { Rectangle rectWindow = DisplayingRectangle; Rectangle rectCaption = CaptionRectangle; Rectangle rectTabStrip = TabStripRectangle; int x = rectWindow.X; int y = rectWindow.Y + (rectCaption.IsEmpty ? 0 : rectCaption.Height); if (DockState == DockState.Document && DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Top) y += rectTabStrip.Height; int width = rectWindow.Width; int height = rectWindow.Height - rectCaption.Height - rectTabStrip.Height; return new Rectangle(x, y, width, height); } } internal Rectangle TabStripRectangle { get { if (Appearance == AppearanceStyle.ToolWindow) return TabStripRectangle_ToolWindow; else return TabStripRectangle_Document; } } private Rectangle TabStripRectangle_ToolWindow { get { if (DisplayingContents.Count <= 1 || IsAutoHide) return Rectangle.Empty; Rectangle rectWindow = DisplayingRectangle; int width = rectWindow.Width; int height = TabStripControl.MeasureHeight(); int x = rectWindow.X; int y = rectWindow.Bottom - height; Rectangle rectCaption = CaptionRectangle; if (rectCaption.Contains(x, y)) y = rectCaption.Y + rectCaption.Height; return new Rectangle(x, y, width, height); } } private Rectangle TabStripRectangle_Document { get { if (DisplayingContents.Count == 0) return Rectangle.Empty; if (DisplayingContents.Count == 1 && DockPanel.DocumentStyle == DocumentStyle.DockingSdi) return Rectangle.Empty; Rectangle rectWindow = DisplayingRectangle; int x = rectWindow.X; int width = rectWindow.Width; int height = TabStripControl.MeasureHeight(); int y = 0; if (DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) y = rectWindow.Height - height; else y = rectWindow.Y; return new Rectangle(x, y, width, height); } } public virtual string CaptionText { get { return ActiveContent == null ? string.Empty : ActiveContent.DockHandler.TabText; } } private DockContentCollection m_contents; public DockContentCollection Contents { get { return m_contents; } } private DockContentCollection m_displayingContents; public DockContentCollection DisplayingContents { get { return m_displayingContents; } } private DockPanel m_dockPanel; public DockPanel DockPanel { get { return m_dockPanel; } } private bool HasCaption { get { if (DockState == DockState.Document || DockState == DockState.Hidden || DockState == DockState.Unknown || (DockState == DockState.Float && FloatWindow.VisibleNestedPanes.Count <= 1)) return false; else return true; } } private bool m_isActivated = false; public bool IsActivated { get { return m_isActivated; } } internal void SetIsActivated(bool value) { if (m_isActivated == value) return; m_isActivated = value; if (DockState != DockState.Document) RefreshChanges(false); OnIsActivatedChanged(EventArgs.Empty); } private bool m_isActiveDocumentPane = false; public bool IsActiveDocumentPane { get { return m_isActiveDocumentPane; } } internal void SetIsActiveDocumentPane(bool value) { if (m_isActiveDocumentPane == value) return; m_isActiveDocumentPane = value; if (DockState == DockState.Document) RefreshChanges(); OnIsActiveDocumentPaneChanged(EventArgs.Empty); } public bool IsDockStateValid(DockState dockState) { foreach (IDockContent content in Contents) if (!content.DockHandler.IsDockStateValid(dockState)) return false; return true; } public bool IsAutoHide { get { return DockHelper.IsDockStateAutoHide(DockState); } } public AppearanceStyle Appearance { get { return (DockState == DockState.Document) ? AppearanceStyle.Document : AppearanceStyle.ToolWindow; } } public Rectangle DisplayingRectangle { get { return ClientRectangle; } } public void Activate() { if (DockHelper.IsDockStateAutoHide(DockState) && DockPanel.ActiveAutoHideContent != ActiveContent) DockPanel.ActiveAutoHideContent = ActiveContent; else if (!IsActivated && ActiveContent != null) ActiveContent.DockHandler.Activate(); //System.Diagnostics.Debug.WriteLine( "Activated: " + this.CaptionText ); } internal void AddContent(IDockContent content) { if (Contents.Contains(content)) return; Contents.Add(content); } internal void Close() { Dispose(); } public void CloseActiveContent() { CloseContent(ActiveContent); } internal void CloseContent(IDockContent content) { if (content == null) return; if (!content.DockHandler.CloseButton) return; DockPanel dockPanel = DockPanel; if ( !dockPanel.AllowChangeLayout ) return; dockPanel.SuspendLayout(true); try { if (content.DockHandler.HideOnClose) { content.DockHandler.Hide(); NestedDockingStatus.NestedPanes.SwitchPaneWithFirstChild(this); } else content.DockHandler.Close(); } finally { dockPanel.ResumeLayout(true, true); } } private HitTestResult GetHitTest(Point ptMouse) { Point ptMouseClient = PointToClient(ptMouse); Rectangle rectCaption = CaptionRectangle; if (rectCaption.Contains(ptMouseClient)) return new HitTestResult(HitTestArea.Caption, -1); Rectangle rectContent = ContentRectangle; if (rectContent.Contains(ptMouseClient)) return new HitTestResult(HitTestArea.Content, -1); Rectangle rectTabStrip = TabStripRectangle; if (rectTabStrip.Contains(ptMouseClient)) return new HitTestResult(HitTestArea.TabStrip, TabStripControl.HitTest(TabStripControl.PointToClient(ptMouse))); return new HitTestResult(HitTestArea.None, -1); } private bool m_isHidden = true; public bool IsHidden { get { return m_isHidden; } } private void SetIsHidden(bool value) { if (m_isHidden == value) return; m_isHidden = value; if (DockHelper.IsDockStateAutoHide(DockState)) { DockPanel.RefreshAutoHideStrip(); DockPanel.PerformLayout(); } else if (NestedPanesContainer != null) ((Control)NestedPanesContainer).PerformLayout(); } protected override void OnLayout(LayoutEventArgs levent) { SetIsHidden(DisplayingContents.Count == 0); if (!IsHidden) { CaptionControl.Bounds = CaptionRectangle; TabStripControl.Bounds = TabStripRectangle; SetContentBounds(); foreach (IDockContent content in Contents) { if (DisplayingContents.Contains(content)) if (content.DockHandler.FlagClipWindow && content.DockHandler.Form.Visible) content.DockHandler.FlagClipWindow = false; } } base.OnLayout(levent); } internal void SetContentBounds() { Rectangle rectContent = ContentRectangle; if (DockState == DockState.Document && DockPanel.DocumentStyle == DocumentStyle.DockingMdi) rectContent = DockPanel.RectangleToMdiClient(RectangleToScreen(rectContent)); Rectangle rectInactive = new Rectangle(-rectContent.Width, rectContent.Y, rectContent.Width, rectContent.Height); foreach (IDockContent content in Contents) if (content.DockHandler.Pane == this) { if (content == ActiveContent) content.DockHandler.Form.Bounds = rectContent; else content.DockHandler.Form.Bounds = rectInactive; } } internal void RefreshChanges() { RefreshChanges(true); } private void RefreshChanges(bool performLayout) { if (IsDisposed) return; CaptionControl.RefreshChanges(); TabStripControl.RefreshChanges(); if (DockState == DockState.Float && FloatWindow != null) FloatWindow.RefreshChanges(); if (DockHelper.IsDockStateAutoHide(DockState) && DockPanel != null) { DockPanel.RefreshAutoHideStrip(); DockPanel.PerformLayout(); } if (performLayout) PerformLayout(); } internal void RemoveContent(IDockContent content) { if (!Contents.Contains(content)) return; Contents.Remove(content); } public void SetContentIndex(IDockContent content, int index) { int oldIndex = Contents.IndexOf(content); if (oldIndex == -1) throw (new ArgumentException(Strings.DockPane_SetContentIndex_InvalidContent)); if (index < 0 || index > Contents.Count - 1) if (index != -1) throw (new ArgumentOutOfRangeException(Strings.DockPane_SetContentIndex_InvalidIndex)); if (oldIndex == index) return; if (oldIndex == Contents.Count - 1 && index == -1) return; Contents.Remove(content); if (index == -1) Contents.Add(content); else if (oldIndex < index) Contents.AddAt(content, index - 1); else Contents.AddAt(content, index); RefreshChanges(); } private void SetParent() { if (DockState == DockState.Unknown || DockState == DockState.Hidden) { SetParent(null); Splitter.Parent = null; } else if (DockState == DockState.Float) { SetParent(FloatWindow); Splitter.Parent = FloatWindow; } else if (DockHelper.IsDockStateAutoHide(DockState)) { SetParent(DockPanel.AutoHideControl); Splitter.Parent = null; } else { SetParent(DockPanel.DockWindows[DockState]); Splitter.Parent = Parent; } } private void SetParent(Control value) { if (Parent == value) return; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Workaround of .Net Framework bug: // Change the parent of a control with focus may result in the first // MDI child form get activated. //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! IDockContent contentFocused = GetFocusedContent(); if (contentFocused != null) DockPanel.SaveFocus(); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Parent = value; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Workaround of .Net Framework bug: // Change the parent of a control with focus may result in the first // MDI child form get activated. //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! if (contentFocused != null) contentFocused.DockHandler.Activate(); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! } public new void Show() { Activate(); } internal void TestDrop( DockHelper.CursorPoint info, DockOutlineBase dockOutline ) { if ( !info.DragSource.CanDockTo( this ) ) return; HitTestResult hitTestResult = GetHitTest( info.Cursor); if (hitTestResult.HitArea == HitTestArea.Caption) dockOutline.Show(this, -1); else if (hitTestResult.HitArea == HitTestArea.TabStrip && hitTestResult.Index != -1) dockOutline.Show(this, hitTestResult.Index); } internal void ValidateActiveContent() { if (ActiveContent == null) { if (DisplayingContents.Count != 0) ActiveContent = DisplayingContents[0]; return; } if (DisplayingContents.IndexOf(ActiveContent) >= 0) return; IDockContent prevVisible = null; for (int i = Contents.IndexOf(ActiveContent) - 1; i >= 0; i--) if (Contents[i].DockHandler.DockState == DockState) { prevVisible = Contents[i]; break; } IDockContent nextVisible = null; for (int i = Contents.IndexOf(ActiveContent) + 1; i < Contents.Count; i++) if (Contents[i].DockHandler.DockState == DockState) { nextVisible = Contents[i]; break; } if (prevVisible != null) ActiveContent = prevVisible; else if (nextVisible != null) ActiveContent = nextVisible; else ActiveContent = null; } private static readonly object DockStateChangedEvent = new object(); public event EventHandler DockStateChanged { add { Events.AddHandler(DockStateChangedEvent, value); } remove { Events.RemoveHandler(DockStateChangedEvent, value); } } protected virtual void OnDockStateChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[DockStateChangedEvent]; if (handler != null) handler(this, e); } private static readonly object IsActivatedChangedEvent = new object(); public event EventHandler IsActivatedChanged { add { Events.AddHandler(IsActivatedChangedEvent, value); } remove { Events.RemoveHandler(IsActivatedChangedEvent, value); } } protected virtual void OnIsActivatedChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[IsActivatedChangedEvent]; if (handler != null) handler(this, e); } private static readonly object IsActiveDocumentPaneChangedEvent = new object(); public event EventHandler IsActiveDocumentPaneChanged { add { Events.AddHandler(IsActiveDocumentPaneChangedEvent, value); } remove { Events.RemoveHandler(IsActiveDocumentPaneChangedEvent, value); } } protected virtual void OnIsActiveDocumentPaneChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[IsActiveDocumentPaneChangedEvent]; if (handler != null) handler(this, e); } public DockWindow DockWindow { get { return (m_nestedDockingStatus.NestedPanes == null) ? null : m_nestedDockingStatus.NestedPanes.Container as DockWindow; } set { DockWindow oldValue = DockWindow; if (oldValue == value) return; DockTo(value); } } public FloatWindow FloatWindow { get { return (m_nestedDockingStatus.NestedPanes == null) ? null : m_nestedDockingStatus.NestedPanes.Container as FloatWindow; } set { FloatWindow oldValue = FloatWindow; if (oldValue == value) return; DockTo(value); } } private NestedDockingStatus m_nestedDockingStatus; public NestedDockingStatus NestedDockingStatus { get { return m_nestedDockingStatus; } } private bool m_isFloat; public bool IsFloat { get { return m_isFloat; } } public INestedPanesContainer NestedPanesContainer { get { if (NestedDockingStatus.NestedPanes == null) return null; else return NestedDockingStatus.NestedPanes.Container; } } private DockState m_dockState = DockState.Unknown; public DockState DockState { get { return m_dockState; } set { SetDockState(value); } } public DockPane SetDockState(DockState value) { if (value == DockState.Unknown || value == DockState.Hidden) throw new InvalidOperationException(Strings.DockPane_SetDockState_InvalidState); if ((value == DockState.Float) == this.IsFloat) { InternalSetDockState(value); return this; } if (DisplayingContents.Count == 0) return null; IDockContent firstContent = null; for (int i = 0; i < DisplayingContents.Count; i++) { IDockContent content = DisplayingContents[i]; if (content.DockHandler.IsDockStateValid(value)) { firstContent = content; break; } } if (firstContent == null) return null; firstContent.DockHandler.DockState = value; DockPane pane = firstContent.DockHandler.Pane; DockPanel.SuspendLayout(true); for (int i = 0; i < DisplayingContents.Count; i++) { IDockContent content = DisplayingContents[i]; if (content.DockHandler.IsDockStateValid(value)) content.DockHandler.Pane = pane; } DockPanel.ResumeLayout(true, true); return pane; } private void InternalSetDockState(DockState value) { if (m_dockState == value) return; DockState oldDockState = m_dockState; INestedPanesContainer oldContainer = NestedPanesContainer; m_dockState = value; SuspendRefreshStateChange(); IDockContent contentFocused = GetFocusedContent(); if (contentFocused != null) DockPanel.SaveFocus(); if (!IsFloat) DockWindow = DockPanel.DockWindows[DockState]; else if (FloatWindow == null) FloatWindow = DockPanel.FloatWindowFactory.CreateFloatWindow(DockPanel, this); if (contentFocused != null) { if (!Win32Helper.IsRunningOnMono) { DockPanel.ContentFocusManager.Activate(contentFocused); } } ResumeRefreshStateChange(oldContainer, oldDockState); } private int m_countRefreshStateChange = 0; private void SuspendRefreshStateChange() { m_countRefreshStateChange++; DockPanel.SuspendLayout(true); } private void ResumeRefreshStateChange() { m_countRefreshStateChange--; System.Diagnostics.Debug.Assert(m_countRefreshStateChange >= 0); DockPanel.ResumeLayout(true, true); } private bool IsRefreshStateChangeSuspended { get { return m_countRefreshStateChange != 0; } } private void ResumeRefreshStateChange(INestedPanesContainer oldContainer, DockState oldDockState) { ResumeRefreshStateChange(); RefreshStateChange(oldContainer, oldDockState); } private void RefreshStateChange(INestedPanesContainer oldContainer, DockState oldDockState) { if (IsRefreshStateChangeSuspended) return; SuspendRefreshStateChange(); DockPanel.SuspendLayout(true); IDockContent contentFocused = GetFocusedContent(); if (contentFocused != null) DockPanel.SaveFocus(); SetParent(); if (ActiveContent != null) ActiveContent.DockHandler.SetDockState(ActiveContent.DockHandler.IsHidden, DockState, ActiveContent.DockHandler.Pane); foreach (IDockContent content in Contents) { if (content.DockHandler.Pane == this) content.DockHandler.SetDockState(content.DockHandler.IsHidden, DockState, content.DockHandler.Pane); } if (oldContainer != null) { Control oldContainerControl = (Control)oldContainer; if (oldContainer.DockState == oldDockState && !oldContainerControl.IsDisposed) oldContainerControl.PerformLayout(); } if (DockHelper.IsDockStateAutoHide(oldDockState)) DockPanel.RefreshActiveAutoHideContent(); if (NestedPanesContainer.DockState == DockState) ((Control)NestedPanesContainer).PerformLayout(); if (DockHelper.IsDockStateAutoHide(DockState)) DockPanel.RefreshActiveAutoHideContent(); if (DockHelper.IsDockStateAutoHide(oldDockState) || DockHelper.IsDockStateAutoHide(DockState)) { DockPanel.RefreshAutoHideStrip(); DockPanel.PerformLayout(); } ResumeRefreshStateChange(); if (contentFocused != null) contentFocused.DockHandler.Activate(); DockPanel.ResumeLayout(true, true); if (oldDockState != DockState) OnDockStateChanged(EventArgs.Empty); } private IDockContent GetFocusedContent() { IDockContent contentFocused = null; foreach (IDockContent content in Contents) { if (content.DockHandler.Form.ContainsFocus) { contentFocused = content; break; } } return contentFocused; } public DockPane DockTo(INestedPanesContainer container) { if (container == null) throw new InvalidOperationException(Strings.DockPane_DockTo_NullContainer); DockAlignment alignment; if (container.DockState == DockState.DockLeft || container.DockState == DockState.DockRight) alignment = DockAlignment.Bottom; else alignment = DockAlignment.Right; return DockTo(container, container.NestedPanes.GetDefaultPreviousPane(this), alignment, 0.5); } public DockPane DockTo(INestedPanesContainer container, DockPane previousPane, DockAlignment alignment, double proportion) { if (container == null) throw new InvalidOperationException(Strings.DockPane_DockTo_NullContainer); if (container.IsFloat == this.IsFloat) { InternalAddToDockList(container, previousPane, alignment, proportion); return this; } IDockContent firstContent = GetFirstContent(container.DockState); if (firstContent == null) return null; DockPane pane; DockPanel.DummyContent.DockPanel = DockPanel; if (container.IsFloat) pane = DockPanel.DockPaneFactory.CreateDockPane(DockPanel.DummyContent, (FloatWindow)container, true); else pane = DockPanel.DockPaneFactory.CreateDockPane(DockPanel.DummyContent, container.DockState, true); pane.DockTo(container, previousPane, alignment, proportion); SetVisibleContentsToPane(pane); DockPanel.DummyContent.DockPanel = null; return pane; } private void SetVisibleContentsToPane(DockPane pane) { SetVisibleContentsToPane(pane, ActiveContent); } private void SetVisibleContentsToPane(DockPane pane, IDockContent activeContent) { for (int i = 0; i < DisplayingContents.Count; i++) { IDockContent content = DisplayingContents[i]; if (content.DockHandler.IsDockStateValid(pane.DockState)) { content.DockHandler.Pane = pane; i--; } } if (activeContent.DockHandler.Pane == pane) pane.ActiveContent = activeContent; } private void InternalAddToDockList(INestedPanesContainer container, DockPane prevPane, DockAlignment alignment, double proportion) { if ((container.DockState == DockState.Float) != IsFloat) throw new InvalidOperationException(Strings.DockPane_DockTo_InvalidContainer); int count = container.NestedPanes.Count; if (container.NestedPanes.Contains(this)) count--; if (prevPane == null && count > 0) throw new InvalidOperationException(Strings.DockPane_DockTo_NullPrevPane); if (prevPane != null && !container.NestedPanes.Contains(prevPane)) throw new InvalidOperationException(Strings.DockPane_DockTo_NoPrevPane); if (prevPane == this) throw new InvalidOperationException(Strings.DockPane_DockTo_SelfPrevPane); INestedPanesContainer oldContainer = NestedPanesContainer; DockState oldDockState = DockState; container.NestedPanes.Add(this); NestedDockingStatus.SetStatus(container.NestedPanes, prevPane, alignment, proportion); if (DockHelper.IsDockWindowState(DockState)) m_dockState = container.DockState; RefreshStateChange(oldContainer, oldDockState); } public void SetNestedDockingProportion(double proportion) { NestedDockingStatus.SetStatus(NestedDockingStatus.NestedPanes, NestedDockingStatus.PreviousPane, NestedDockingStatus.Alignment, proportion); if (NestedPanesContainer != null) ((Control)NestedPanesContainer).PerformLayout(); } public DockPane Float() { DockPanel.SuspendLayout(true); IDockContent activeContent = ActiveContent; DockPane floatPane = GetFloatPaneFromContents(); if (floatPane == null) { IDockContent firstContent = GetFirstContent(DockState.Float); if (firstContent == null) { DockPanel.ResumeLayout(true, true); return null; } floatPane = DockPanel.DockPaneFactory.CreateDockPane(firstContent, DockState.Float, true); } SetVisibleContentsToPane(floatPane, activeContent); DockPanel.ResumeLayout(true, true); return floatPane; } private DockPane GetFloatPaneFromContents() { DockPane floatPane = null; for (int i = 0; i < DisplayingContents.Count; i++) { IDockContent content = DisplayingContents[i]; if (!content.DockHandler.IsDockStateValid(DockState.Float)) continue; if (floatPane != null && content.DockHandler.FloatPane != floatPane) return null; else floatPane = content.DockHandler.FloatPane; } return floatPane; } private IDockContent GetFirstContent(DockState dockState) { for (int i = 0; i < DisplayingContents.Count; i++) { IDockContent content = DisplayingContents[i]; if (content.DockHandler.IsDockStateValid(dockState)) return content; } return null; } public void RestoreToPanel() { DockPanel.SuspendLayout(true); IDockContent activeContent = DockPanel.ActiveContent; for (int i = DisplayingContents.Count - 1; i >= 0; i--) { IDockContent content = DisplayingContents[i]; if (content.DockHandler.CheckDockState(false) != DockState.Unknown) content.DockHandler.IsFloat = false; } DockPanel.ResumeLayout(true, true); } [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] protected override void WndProc(ref Message m) { if (m.Msg == (int)Win32.Msgs.WM_MOUSEACTIVATE) Activate(); base.WndProc(ref m); } #region IDockDragSource Members #region IDragSource Members Control IDragSource.DragControl { get { return this; } } public IDockContent MouseOverTab { get; set; } void IDockDragSource.OnDragging( Point ptMouse ) { } #endregion bool IDockDragSource.IsDockStateValid(DockState dockState) { return IsDockStateValid(dockState); } bool IDockDragSource.CanDockTo(DockPane pane) { if (!IsDockStateValid(pane.DockState)) return false; if (pane == this) return false; return true; } Rectangle IDockDragSource.BeginDrag(Point ptMouse) { Point location = PointToScreen(new Point(0, 0)); Size size; DockPane floatPane = ActiveContent.DockHandler.FloatPane; if (DockState == DockState.Float || floatPane == null || floatPane.FloatWindow.NestedPanes.Count != 1) size = DockPanel.DefaultFloatWindowSize; else size = floatPane.FloatWindow.Size; if (ptMouse.X > location.X + size.Width) location.X += ptMouse.X - (location.X + size.Width) + Measures.SplitterSize; return new Rectangle(location, size); } void IDockDragSource.EndDrag() { } public void FloatAt(Rectangle floatWindowBounds) { if (FloatWindow == null || FloatWindow.NestedPanes.Count != 1) FloatWindow = DockPanel.FloatWindowFactory.CreateFloatWindow(DockPanel, this, floatWindowBounds); else FloatWindow.Bounds = floatWindowBounds; DockState = DockState.Float; NestedDockingStatus.NestedPanes.SwitchPaneWithFirstChild(this); } public void DockTo(DockPane pane, DockStyle dockStyle, int contentIndex) { if (dockStyle == DockStyle.Fill) { IDockContent activeContent = ActiveContent; for (int i = Contents.Count - 1; i >= 0; i--) { IDockContent c = Contents[i]; if (c.DockHandler.DockState == DockState) { c.DockHandler.Pane = pane; if (contentIndex != -1) pane.SetContentIndex(c, contentIndex); } } pane.ActiveContent = activeContent; } else { if (dockStyle == DockStyle.Left) DockTo(pane.NestedPanesContainer, pane, DockAlignment.Left, 0.5); else if (dockStyle == DockStyle.Right) DockTo(pane.NestedPanesContainer, pane, DockAlignment.Right, 0.5); else if (dockStyle == DockStyle.Top) DockTo(pane.NestedPanesContainer, pane, DockAlignment.Top, 0.5); else if (dockStyle == DockStyle.Bottom) DockTo(pane.NestedPanesContainer, pane, DockAlignment.Bottom, 0.5); DockState = pane.DockState; } } public void DockTo(DockPanel panel, DockStyle dockStyle) { if (panel != DockPanel) throw new ArgumentException(Strings.IDockDragSource_DockTo_InvalidPanel, "panel"); if (dockStyle == DockStyle.Top) DockState = DockState.DockTop; else if (dockStyle == DockStyle.Bottom) DockState = DockState.DockBottom; else if (dockStyle == DockStyle.Left) DockState = DockState.DockLeft; else if (dockStyle == DockStyle.Right) DockState = DockState.DockRight; else if (dockStyle == DockStyle.Fill) DockState = DockState.Document; } #endregion #region cachedLayoutArgs leak workaround /// <summary> /// There's a bug in the WinForms layout engine /// that can result in a deferred layout to not /// properly clear out the cached layout args after /// the layout operation is performed. /// Specifically, this bug is hit when the bounds of /// the Pane change, initiating a layout on the parent /// (DockWindow) which is where the bug hits. /// To work around it, when a pane loses the DockWindow /// as its parent, that parent DockWindow needs to /// perform a layout to flush the cached args, if they exist. /// </summary> private DockWindow _lastParentWindow; protected override void OnParentChanged(EventArgs e) { base.OnParentChanged(e); var newParent = Parent as DockWindow; if (newParent != _lastParentWindow) { if (_lastParentWindow != null) _lastParentWindow.PerformLayout(); _lastParentWindow = newParent; } } #endregion } }
// <copyright file="TurnBasedMatch.cs" company="Google Inc."> // Copyright (C) 2014 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> #if UNITY_ANDROID namespace GooglePlayGames.BasicApi.Multiplayer { using System.Collections.Generic; using System.Linq; using GooglePlayGames.OurUtils; /// <summary> /// Represents a turn-based match. /// </summary> public class TurnBasedMatch { public enum MatchStatus { Active, AutoMatching, Cancelled, Complete, Expired, Unknown, Deleted } public enum MatchTurnStatus { Complete, Invited, MyTurn, TheirTurn, Unknown } private string mMatchId; private byte[] mData; private bool mCanRematch; private uint mAvailableAutomatchSlots; private string mSelfParticipantId; private List<Participant> mParticipants; private string mPendingParticipantId; private MatchTurnStatus mTurnStatus; private MatchStatus mMatchStatus; private uint mVariant; private uint mVersion; internal TurnBasedMatch(string matchId, byte[] data, bool canRematch, string selfParticipantId, List<Participant> participants, uint availableAutomatchSlots, string pendingParticipantId, MatchTurnStatus turnStatus, MatchStatus matchStatus, uint variant, uint version) { mMatchId = matchId; mData = data; mCanRematch = canRematch; mSelfParticipantId = selfParticipantId; mParticipants = participants; // participant list is always sorted! mParticipants.Sort(); mAvailableAutomatchSlots = availableAutomatchSlots; mPendingParticipantId = pendingParticipantId; mTurnStatus = turnStatus; mMatchStatus = matchStatus; mVariant = variant; mVersion = version; } /// Match ID. public string MatchId { get { return mMatchId; } } /// The data associated with the match. The meaning of this data is defined by the game. public byte[] Data { get { return mData; } } /// If true, this match can be rematched. public bool CanRematch { get { return mCanRematch; } } /// The participant ID that represents the current player. public string SelfParticipantId { get { return mSelfParticipantId; } } /// The participant that represents the current player in the match. public Participant Self { get { return GetParticipant(mSelfParticipantId); } } /// Gets a participant by ID. Returns null if not found. public Participant GetParticipant(string participantId) { foreach (Participant p in mParticipants) { if (p.ParticipantId.Equals(participantId)) { return p; } } Logger.w("Participant not found in turn-based match: " + participantId); return null; } /// Returns the list of participants. Guaranteed to be sorted by participant ID. public List<Participant> Participants { get { return mParticipants; } } /// Returns the pending participant ID (whose turn it is). public string PendingParticipantId { get { return mPendingParticipantId; } } /// Returns the pending participant (whose turn it is). public Participant PendingParticipant { get { return mPendingParticipantId == null ? null : GetParticipant(mPendingParticipantId); } } /// Returns the turn status (whether it's my turn). public MatchTurnStatus TurnStatus { get { return mTurnStatus; } } /// Returns the status of the match. public MatchStatus Status { get { return mMatchStatus; } } /// Returns the match variant being played. 0 for default. public uint Variant { get { return mVariant; } } /// Returns the version for the contained match. public uint Version { get { return mVersion; } } // Returns how many automatch slots are still open in the match. public uint AvailableAutomatchSlots { get { return mAvailableAutomatchSlots; } } public override string ToString() { return string.Format("[TurnBasedMatch: mMatchId={0}, mData={1}, mCanRematch={2}, " + "mSelfParticipantId={3}, mParticipants={4}, mPendingParticipantId={5}, " + "mTurnStatus={6}, mMatchStatus={7}, mVariant={8}, mVersion={9}]", mMatchId, mData, mCanRematch, mSelfParticipantId, string.Join(",", mParticipants.Select(p => p.ToString()).ToArray()), mPendingParticipantId, mTurnStatus, mMatchStatus, mVariant, mVersion); } } } #endif
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.ComponentModel; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.ComponentModel.EventBasedAsync { public class AsyncOperationTests { private const int SpinTimeoutSeconds = 30; [Fact] public static void Noop() { // Test that a simple AsyncOperation can be dispatched and completed via AsyncOperationManager Task.Run(() => { var operation = new TestAsyncOperation(op => { }); operation.Wait(); Assert.True(operation.Completed); Assert.False(operation.Cancelled); Assert.Null(operation.Exception); }).Wait(); } [Fact] public static void ThrowAfterAsyncComplete() { Task.Run(() => { var operation = new TestAsyncOperation(op => { }); operation.Wait(); SendOrPostCallback noopCallback = state => { }; Assert.Throws<InvalidOperationException>(() => operation.AsyncOperation.Post(noopCallback, null)); Assert.Throws<InvalidOperationException>(() => operation.AsyncOperation.PostOperationCompleted(noopCallback, null)); Assert.Throws<InvalidOperationException>(() => operation.AsyncOperation.OperationCompleted()); }).Wait(); } [Fact] public static void ThrowAfterSynchronousComplete() { Task.Run(() => { var operation = AsyncOperationManager.CreateOperation(null); operation.OperationCompleted(); SendOrPostCallback noopCallback = state => { }; Assert.Throws<InvalidOperationException>(() => operation.Post(noopCallback, null)); Assert.Throws<InvalidOperationException>(() => operation.PostOperationCompleted(noopCallback, null)); Assert.Throws<InvalidOperationException>(() => operation.OperationCompleted()); }).Wait(); } [Fact] public static void Cancel() { // Test that cancellation gets passed all the way through PostOperationCompleted(callback, AsyncCompletedEventArgs) Task.Run(() => { var cancelEvent = new ManualResetEventSlim(); var operation = new TestAsyncOperation(op => { var ret = cancelEvent.Wait(SpinTimeoutSeconds*1000); Assert.True(ret); }, cancelEvent: cancelEvent); operation.Cancel(); operation.Wait(); Assert.True(operation.Completed); Assert.True(operation.Cancelled); Assert.Null(operation.Exception); }).Wait(); } [Fact] public static void Throw() { // Test that exceptions get passed all the way through PostOperationCompleted(callback, AsyncCompletedEventArgs) Task.Run(() => { var operation = new TestAsyncOperation(op => { throw new TestException("Test throw"); }); Assert.Throws<TestException>(() => operation.Wait()); }).Wait(); } [Fact] public static void PostNullDelegate() { // the xUnit SynchronizationContext - AysncTestSyncContext interferes with the current SynchronizationContext // used by AsyncOperation when there is exception thrown -> the SC.OperationCompleted() is not called. // use new SC here to avoid this issue var orignal = SynchronizationContext.Current; try { SynchronizationContext.SetSynchronizationContext(null); // Pass a non-null state just to emphasize we're only testing passing a null delegate var state = new object(); var operation = AsyncOperationManager.CreateOperation(state); Assert.Throws<ArgumentNullException>(() => operation.Post(null, state)); Assert.Throws<ArgumentNullException>(() => operation.PostOperationCompleted(null, state)); } finally { SynchronizationContext.SetSynchronizationContext(orignal); } } // A simple wrapper for AsyncOperation which executes the specified delegate and a completion handler asynchronously. public class TestAsyncOperation { private object _operationId; private Action<TestAsyncOperation> _executeDelegate; private ManualResetEventSlim _cancelEvent, _completeEvent; public AsyncOperation AsyncOperation { get; private set; } public bool Completed { get { return _completeEvent.IsSet; } } public bool Cancelled { get { return _cancelEvent.IsSet; } } public Exception Exception { get; private set; } public TestAsyncOperation(Action<TestAsyncOperation> executeDelegate, ManualResetEventSlim cancelEvent = null) { // Create an async operation passing an object as the state so we can // verify that state is passed properly. _operationId = new object(); AsyncOperation = AsyncOperationManager.CreateOperation(_operationId); Assert.Equal(AsyncOperation.SynchronizationContext, AsyncOperationManager.SynchronizationContext); _completeEvent = new ManualResetEventSlim(false); _cancelEvent = cancelEvent ?? new ManualResetEventSlim(false); // Post work to the wrapped synchronization context _executeDelegate = executeDelegate; AsyncOperation.Post((SendOrPostCallback)ExecuteWorker, _operationId); } public void Wait() { var ret = _completeEvent.Wait(SpinTimeoutSeconds*1000); Assert.True(ret); if (this.Exception != null) { throw this.Exception; } } public void Cancel() { CompleteOperationAsync(cancelled: true); } private void ExecuteWorker(object operationId) { Assert.True(_operationId == operationId, "AsyncOperationManager did not pass UserSuppliedState through to the operation."); Exception exception = null; try { _executeDelegate(this); } catch (Exception e) { exception = e; } finally { CompleteOperationAsync(exception: exception); } } private void CompleteOperationAsync(Exception exception = null, bool cancelled = false) { if (!(Completed || Cancelled)) { AsyncOperation.PostOperationCompleted( (SendOrPostCallback)OnOperationCompleted, new AsyncCompletedEventArgs( exception, cancelled, _operationId)); } } private void OnOperationCompleted(object state) { var e = state as AsyncCompletedEventArgs; Assert.True(e != null, "The state passed to this operation must be of type AsyncCompletedEventArgs"); Assert.Equal(_operationId, e.UserState); Exception = e.Error; // Make sure to set _cancelEvent before _completeEvent so that anyone waiting on // _completeEvent will not be at risk of reading Cancelled before it is set. if (e.Cancelled) _cancelEvent.Set(); _completeEvent.Set(); } } public class TestException : Exception { public TestException(string message) : base(message) { } } public class TestTimeoutException : Exception { } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.DataLake.Store { using Azure; using DataLake; using Management; using Azure; using Management; using DataLake; using Models; using Newtonsoft.Json; using Rest; using Rest.Azure; 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> /// TrustedIdProvidersOperations operations. /// </summary> internal partial class TrustedIdProvidersOperations : IServiceOperations<DataLakeStoreAccountManagementClient>, ITrustedIdProvidersOperations { /// <summary> /// Initializes a new instance of the TrustedIdProvidersOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal TrustedIdProvidersOperations(DataLakeStoreAccountManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the DataLakeStoreAccountManagementClient /// </summary> public DataLakeStoreAccountManagementClient Client { get; private set; } /// <summary> /// Creates or updates the specified trusted identity provider. During update, /// the trusted identity provider with the specified name will be replaced with /// this new provider /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account to add or replace the trusted /// identity provider. /// </param> /// <param name='trustedIdProviderName'> /// The name of the trusted identity provider. This is used for differentiation /// of providers in the account. /// </param> /// <param name='parameters'> /// Parameters supplied to create or replace the trusted identity provider. /// </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<TrustedIdProvider>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string accountName, string trustedIdProviderName, TrustedIdProvider parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (trustedIdProviderName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "trustedIdProviderName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("accountName", accountName); tracingParameters.Add("trustedIdProviderName", trustedIdProviderName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeStore/accounts/{accountName}/trustedIdProviders/{trustedIdProviderName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName)); _url = _url.Replace("{trustedIdProviderName}", System.Uri.EscapeDataString(trustedIdProviderName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.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(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.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<TrustedIdProvider>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<TrustedIdProvider>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Updates the specified trusted identity provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account to which to update the trusted /// identity provider. /// </param> /// <param name='trustedIdProviderName'> /// The name of the trusted identity provider. This is used for differentiation /// of providers in the account. /// </param> /// <param name='parameters'> /// Parameters supplied to update the trusted identity provider. /// </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<TrustedIdProvider>> UpdateWithHttpMessagesAsync(string resourceGroupName, string accountName, string trustedIdProviderName, UpdateTrustedIdProviderParameters parameters = default(UpdateTrustedIdProviderParameters), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (trustedIdProviderName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "trustedIdProviderName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("accountName", accountName); tracingParameters.Add("trustedIdProviderName", trustedIdProviderName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Update", 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.DataLakeStore/accounts/{accountName}/trustedIdProviders/{trustedIdProviderName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName)); _url = _url.Replace("{trustedIdProviderName}", System.Uri.EscapeDataString(trustedIdProviderName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PATCH"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.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<TrustedIdProvider>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<TrustedIdProvider>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.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 trusted identity provider from the specified Data /// Lake Store account /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to delete the trusted /// identity provider. /// </param> /// <param name='trustedIdProviderName'> /// The name of the trusted identity provider to delete. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string accountName, string trustedIdProviderName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (trustedIdProviderName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "trustedIdProviderName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("accountName", accountName); tracingParameters.Add("trustedIdProviderName", trustedIdProviderName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeStore/accounts/{accountName}/trustedIdProviders/{trustedIdProviderName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName)); _url = _url.Replace("{trustedIdProviderName}", System.Uri.EscapeDataString(trustedIdProviderName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 204) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } 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> /// Gets the specified Data Lake Store trusted identity provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to get the trusted /// identity provider. /// </param> /// <param name='trustedIdProviderName'> /// The name of the trusted identity provider to retrieve. /// </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<TrustedIdProvider>> GetWithHttpMessagesAsync(string resourceGroupName, string accountName, string trustedIdProviderName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (trustedIdProviderName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "trustedIdProviderName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("accountName", accountName); tracingParameters.Add("trustedIdProviderName", trustedIdProviderName); 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.DataLakeStore/accounts/{accountName}/trustedIdProviders/{trustedIdProviderName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName)); _url = _url.Replace("{trustedIdProviderName}", System.Uri.EscapeDataString(trustedIdProviderName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.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<TrustedIdProvider>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<TrustedIdProvider>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Lists the Data Lake Store trusted identity providers within the specified /// Data Lake Store account. /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to get the trusted /// identity providers. /// </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<TrustedIdProvider>>> ListByAccountWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("accountName", accountName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByAccount", 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.DataLakeStore/accounts/{accountName}/trustedIdProviders").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.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<TrustedIdProvider>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<TrustedIdProvider>>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Lists the Data Lake Store trusted identity providers within the specified /// Data Lake Store account. /// </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<TrustedIdProvider>>> ListByAccountNextWithHttpMessagesAsync(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, "ListByAccountNext", 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 System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.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<TrustedIdProvider>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<TrustedIdProvider>>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.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. All rights reserved. // // Description: Impelementation of ArcSegment // // History: // //-------------------------------------------------------------------------------------------------- using MS.Internal; using MS.Internal.PresentationCore; using System; using System.Collections; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Text; using System.Security; using System.Security.Permissions; using System.Text.RegularExpressions; using System.Windows.Media; using System.Windows; using System.Windows.Media.Composition; using System.Windows.Media.Animation; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; namespace System.Windows.Media { /// <summary> /// ArcSegment /// </summary> public sealed partial class ArcSegment : PathSegment { #region Constructors /// <summary> /// /// </summary> public ArcSegment() { } /// <summary> /// /// </summary> public ArcSegment( Point point, Size size, double rotationAngle, bool isLargeArc, SweepDirection sweepDirection, bool isStroked) { Size = size; RotationAngle = rotationAngle; IsLargeArc = isLargeArc; SweepDirection = sweepDirection; Point = point; IsStroked = isStroked; } #endregion #region AddToFigure /// <SecurityNote> /// Critical: This code calls into MilUtility_ArcToBezier which has an unmanaged code elevation /// TreatAsSafe: Adding a figure is considered safe in partial trust. /// </SecurityNote> [SecurityCritical,SecurityTreatAsSafe] internal override void AddToFigure( Matrix matrix, // The transformation matrid PathFigure figure, // The figure to add to ref Point current) // In: Segment start point, Out: Segment endpoint, neither transformed { Point endPoint = Point; if (matrix.IsIdentity) { figure.Segments.Add(this); } else { // The arc segment is approximated by up to 4 Bezier segments unsafe { int count; Point* points = stackalloc Point[12]; Size size = Size; Double rotation = RotationAngle; MilMatrix3x2D mat3X2 = CompositionResourceManager.MatrixToMilMatrix3x2D(ref matrix); Composition.MilCoreApi.MilUtility_ArcToBezier( current, // =start point size, rotation, IsLargeArc, SweepDirection, endPoint, &mat3X2, points, out count); // = number of Bezier segments Invariant.Assert(count <= 4); // To ensure no buffer overflows count = Math.Min(count, 4); bool isStroked = IsStroked; bool isSmoothJoin = IsSmoothJoin; // Add the segments if (count > 0) { for (int i = 0; i < count; i++) { figure.Segments.Add(new BezierSegment( points[3*i], points[3*i + 1], points[3*i + 2], isStroked, (i < count - 1) || isSmoothJoin)); // Smooth join between arc pieces } } else if (count == 0) { figure.Segments.Add(new LineSegment(points[0], isStroked, isSmoothJoin)); } } // Update the last point current = endPoint; } } #endregion /// <summary> /// SerializeData - Serialize the contents of this Segment to the provided context. /// </summary> internal override void SerializeData(StreamGeometryContext ctx) { ctx.ArcTo(Point, Size, RotationAngle, IsLargeArc, SweepDirection, IsStroked, IsSmoothJoin); } internal override bool IsCurved() { return true; } /// <summary> /// Creates a string representation of this object based on the format string /// and IFormatProvider passed in. /// If the provider is null, the CurrentCulture is used. /// See the documentation for IFormattable for more information. /// </summary> /// <returns> /// A string representation of this object. /// </returns> internal override string ConvertToString(string format, IFormatProvider provider) { // Helper to get the numeric list separator for a given culture. char separator = MS.Internal.TokenizerHelper.GetNumericListSeparator(provider); return String.Format(provider, "A{1:" + format + "}{0}{2:" + format + "}{0}{3}{0}{4}{0}{5:" + format + "}", separator, Size, RotationAngle, IsLargeArc ? "1" : "0", SweepDirection == SweepDirection.Clockwise ? "1" : "0", Point); } // // This property // 1. Finds the correct initial size for the _effectiveValues store on the current DependencyObject // 2. This is a performance optimization // internal override int EffectiveValuesInitialSize { get { return 6; } } /// <summary> /// For the purposes of this class, Size.Empty should be treated as if it were Size(0,0). /// </summary> private static object CoerceSize(DependencyObject d, object value) { if (((Size)value).IsEmpty) { return new Size(0,0); } else { return value; } } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; // ERROR: Not supported in C#: OptionDeclaration namespace _4PosBackOffice.NET { internal partial class frmIncrementQuantity : System.Windows.Forms.Form { int gIncrementID; int gQuantity; private void loadLanguage() { //frmIncrementQuantity = No Code [Edit Increment Quantity] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then frmIncrementQuantity.Caption = rsLang("LanguageLayoutLnk_Description"): frmIncrementQuantity.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1004; //Exit|Checked if (modRecordSet.rsLang.RecordCount){cmdClose.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdClose.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} //_lbl_1 = No Code [Increment Name] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then _lbl_1.Caption = rsLang("LanguageLayoutLnk_Description"): _lbl_1.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2145; //Shrink Size|Checked if (modRecordSet.rsLang.RecordCount){_lblLabels_9.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_9.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1151; //Price|Checked if (modRecordSet.rsLang.RecordCount){_LBL_3.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_LBL_3.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'"; //UPGRADE_ISSUE: Form property frmIncrementQuantity.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"' if (modRecordSet.rsHelp.RecordCount) this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value; } private void loadData() { ADODB.Recordset rs = default(ADODB.Recordset); if (gQuantity) { rs = modRecordSet.getRS(ref "SELECT IncrementQuantity.*, Increment.Increment_Name FROM Increment INNER JOIN IncrementQuantity ON Increment.IncrementID = IncrementQuantity.IncrementQuantity_IncrementID WHERE (((IncrementQuantity.IncrementQuantity_IncrementID)=" + gIncrementID + ") AND ((IncrementQuantity.IncrementQuantity_Quantity)=" + gQuantity + "));"); if (rs.RecordCount) { lblStockItem.Text = rs.Fields("Increment_Name").Value; txtPrice.Text = Convert.ToString(rs.Fields("IncrementQuantity_Price").Value * 100); txtPrice_Leave(txtPrice, new System.EventArgs()); txtQuantity.Text = Convert.ToString(gQuantity); txtQuantity_Leave(txtQuantity, new System.EventArgs()); } else { this.Close(); return; } } else { rs = modRecordSet.getRS(ref "SELECT Increment.* From Increment WHERE (((Increment.IncrementID)=" + gIncrementID + "));"); if (rs.RecordCount) { lblStockItem.Text = rs.Fields("Increment_Name").Value; txtPrice.Text = Convert.ToString(0); txtPrice_Leave(txtPrice, new System.EventArgs()); txtQuantity.Text = Convert.ToString(gQuantity); txtQuantity_Leave(txtQuantity, new System.EventArgs()); } else { this.Close(); return; } } } public void loadItem(ref int incrementID, ref int quantity) { gIncrementID = incrementID; gQuantity = quantity; loadData(); loadLanguage(); ShowDialog(); } private void frmIncrementQuantity_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs) { short KeyAscii = Strings.Asc(eventArgs.KeyChar); bool mbAddNewFlag = false; bool mbEditFlag = false; if (mbEditFlag | mbAddNewFlag) goto EventExitSub; switch (KeyAscii) { case System.Windows.Forms.Keys.Escape: KeyAscii = 0; cmdClose.Focus(); System.Windows.Forms.Application.DoEvents(); cmdClose_Click(cmdClose, new System.EventArgs()); break; } EventExitSub: eventArgs.KeyChar = Strings.Chr(KeyAscii); if (KeyAscii == 0) { eventArgs.Handled = true; } } private void cmdCancel_Click() { bool mbDataChanged = false; int mvBookMark = 0; ADODB.Recordset adoPrimaryRS = default(ADODB.Recordset); bool mbAddNewFlag = false; bool mbEditFlag = false; // ERROR: Not supported in C#: OnErrorStatement if (mbAddNewFlag) { this.Close(); } else { mbEditFlag = false; mbAddNewFlag = false; adoPrimaryRS.CancelUpdate(); if (mvBookMark > 0) { adoPrimaryRS.Bookmark = mvBookMark; } else { adoPrimaryRS.MoveFirst(); } mbDataChanged = false; } } private bool update_Renamed() { bool functionReturnValue = false; // ERROR: Not supported in C#: OnErrorStatement short lBit = 0; functionReturnValue = true; this.cmdClose.Focus(); System.Windows.Forms.Application.DoEvents(); modRecordSet.cnnDB.Execute("DELETE IncrementQuantity.* From IncrementQuantity WHERE (((IncrementQuantity.IncrementQuantity_IncrementID)=" + gIncrementID + ") AND ((IncrementQuantity.IncrementQuantity_Quantity)=" + gQuantity + "));"); modRecordSet.cnnDB.Execute("DELETE IncrementQuantity.* From IncrementQuantity WHERE (((IncrementQuantity.IncrementQuantity_IncrementID)=" + gIncrementID + ") AND ((IncrementQuantity.IncrementQuantity_Quantity)=" + txtQuantity.Text + "));"); if (Convert.ToInt16(txtQuantity.Text) > 1) { modRecordSet.cnnDB.Execute("INSERT INTO IncrementQuantity ( IncrementQuantity_IncrementID, IncrementQuantity_Quantity, IncrementQuantity_Price ) SELECT " + gIncrementID + ", " + txtQuantity.Text + ", " + txtPrice.Text + ";"); } return functionReturnValue; UpdateErr: Interaction.MsgBox(Err().Description); functionReturnValue = true; return functionReturnValue; } private void cmdClose_Click(System.Object eventSender, System.EventArgs eventArgs) { cmdClose.Focus(); System.Windows.Forms.Application.DoEvents(); if (update_Renamed()) { this.Close(); } } private void txtPrice_Enter(System.Object eventSender, System.EventArgs eventArgs) { modUtilities.MyGotFocusNumeric(ref txtPrice); } private void txtPrice_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs) { short KeyAscii = Strings.Asc(eventArgs.KeyChar); modUtilities.MyKeyPressNegative(ref txtPrice, ref KeyAscii); eventArgs.KeyChar = Strings.Chr(KeyAscii); if (KeyAscii == 0) { eventArgs.Handled = true; } } private void txtPrice_Leave(System.Object eventSender, System.EventArgs eventArgs) { modUtilities.MyLostFocus(ref txtPrice, ref 2); } private void txtQuantity_Enter(System.Object eventSender, System.EventArgs eventArgs) { modUtilities.MyGotFocusNumeric(ref txtQuantity); } private void txtQuantity_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs) { short KeyAscii = Strings.Asc(eventArgs.KeyChar); modUtilities.MyKeyPressNegative(ref txtQuantity, ref KeyAscii); eventArgs.KeyChar = Strings.Chr(KeyAscii); if (KeyAscii == 0) { eventArgs.Handled = true; } } private void txtQuantity_Leave(System.Object eventSender, System.EventArgs eventArgs) { modUtilities.MyLostFocus(ref txtQuantity, ref 0); } } }
using UnityEditor; using UnityEngine; using System.Collections.Generic; using System.IO; [InitializeOnLoad] public static class tk2dEditorUtility { public static double version = 2.3; public static int releaseId = 3; // < -10001 = alpha 1, other negative = beta release, 0 = final, positive = final hotfix static tk2dEditorUtility() { #if UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2 System.Reflection.FieldInfo undoCallback = typeof(EditorApplication).GetField("undoRedoPerformed", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static); if (undoCallback != null) { undoCallback.SetValue(null, (EditorApplication.CallbackFunction)OnUndoRedo); } else { Debug.LogError("tk2d Undo/Redo callback failed. Undo/Redo not supported in this version of Unity."); } #else Undo.undoRedoPerformed += OnUndoRedo; #endif } static void OnUndoRedo() { foreach (GameObject go in Selection.gameObjects) { tk2dSpriteFromTexture sft = go.GetComponent<tk2dSpriteFromTexture>(); tk2dBaseSprite spr = go.GetComponent<tk2dBaseSprite>(); tk2dTextMesh tm = go.GetComponent<tk2dTextMesh>(); if (sft != null) { sft.ForceBuild(); } else if (spr != null) { spr.ForceBuild(); } else if (tm != null) { tm.ForceBuild(); } } } public static string ReleaseStringIdentifier(double _version, int _releaseId) { string id = _version.ToString("0.0"); if (_releaseId == 0) id += ".0"; else if (_releaseId > 0) id += "." + _releaseId.ToString(); else if (_releaseId < -10000) id += " alpha " + (-_releaseId - 10000).ToString(); else if (_releaseId < 0) id += " beta " + (-_releaseId).ToString(); return id; } /// <summary> /// Release filename for the current version /// </summary> public static string CurrentReleaseFileName(string product, double _version, int _releaseId) { string id = product + _version.ToString("0.0"); if (_releaseId == 0) id += ".0"; else if (_releaseId > 0) id += "." + _releaseId.ToString(); else if (_releaseId < -10000) id += "alpha" + (-_releaseId - 10000).ToString(); else if (_releaseId < 0) id += "beta" + (-_releaseId).ToString(); return id; } [MenuItem(tk2dMenu.root + "About", false, 10300)] public static void About2DToolkit() { EditorUtility.DisplayDialog("About 2D Toolkit", "2D Toolkit Version " + ReleaseStringIdentifier(version, releaseId) + "\n" + "Copyright (c) Unikron Software Ltd", "Ok"); } [MenuItem(tk2dMenu.root + "Documentation", false, 10098)] public static void LaunchDocumentation() { Application.OpenURL(string.Format("http://www.2dtoolkit.com/docs/{0:0.0}", version)); } [MenuItem(tk2dMenu.root + "Support/Forum", false, 10103)] public static void LaunchForum() { Application.OpenURL("http://www.2dtoolkit.com/forum"); } [MenuItem(tk2dMenu.root + "Support/Email", false, 10103)] public static void LaunchEmail() { Application.OpenURL(string.Format("mailto:[email protected]?subject=2D%20Toolkit%20{0:0.0}{1}%20Support", version, (releaseId!=0)?releaseId.ToString():"" )); } [MenuItem(tk2dMenu.root + "Rebuild Index", false, 1)] public static void RebuildIndex() { AssetDatabase.DeleteAsset(indexPath); AssetDatabase.Refresh(); CreateIndex(); // Now rebuild system object tk2dSystemUtility.RebuildResources(); } [MenuItem(tk2dMenu.root + "Preferences...", false, 1)] public static void ShowPreferences() { EditorWindow.GetWindow( typeof(tk2dPreferencesEditor), true, "2D Toolkit Preferences" ); } public static string CreateNewPrefab(string name) // name is the filename of the prefab EXCLUDING .prefab { Object obj = Selection.activeObject; string assetPath = AssetDatabase.GetAssetPath(obj); if (assetPath.Length == 0) { assetPath = tk2dGuiUtility.SaveFileInProject("Create...", "Assets/", name, "prefab"); } else { // is a directory string path = System.IO.Directory.Exists(assetPath) ? assetPath : System.IO.Path.GetDirectoryName(assetPath); assetPath = AssetDatabase.GenerateUniqueAssetPath(path + "/" + name + ".prefab"); } return assetPath; } const string indexPath = "Assets/-tk2d.asset"; static tk2dIndex index = null; public static tk2dIndex GetExistingIndex() { if (index == null) { index = Resources.LoadAssetAtPath(indexPath, typeof(tk2dIndex)) as tk2dIndex; } return index; } public static tk2dIndex ForceCreateIndex() { CreateIndex(); return GetExistingIndex(); } public static tk2dIndex GetOrCreateIndex() { tk2dIndex thisIndex = GetExistingIndex(); if (thisIndex == null || thisIndex.version != tk2dIndex.CURRENT_VERSION) { CreateIndex(); thisIndex = GetExistingIndex(); } return thisIndex; } public static void CommitIndex() { if (index) { EditorUtility.SetDirty(index); tk2dSpriteGuiUtility.ResetCache(); } } static void CreateIndex() { tk2dIndex newIndex = ScriptableObject.CreateInstance<tk2dIndex>(); newIndex.version = tk2dIndex.CURRENT_VERSION; newIndex.hideFlags = HideFlags.DontSave; // get this to not be destroyed in Unity 4.1 List<string> rebuildSpriteCollectionPaths = new List<string>(); // check all prefabs to see if we can find any objects we are interested in List<string> allPrefabPaths = new List<string>(); Stack<string> paths = new Stack<string>(); paths.Push(Application.dataPath); while (paths.Count != 0) { string path = paths.Pop(); string[] files = Directory.GetFiles(path, "*.prefab"); foreach (var file in files) { allPrefabPaths.Add(file.Substring(Application.dataPath.Length - 6)); } foreach (string subdirs in Directory.GetDirectories(path)) paths.Push(subdirs); } // Check all prefabs int currPrefabCount = 1; foreach (string prefabPath in allPrefabPaths) { EditorUtility.DisplayProgressBar("Rebuilding Index", "Scanning project folder...", (float)currPrefabCount / (float)(allPrefabPaths.Count)); GameObject iterGo = AssetDatabase.LoadAssetAtPath( prefabPath, typeof(GameObject) ) as GameObject; if (!iterGo) continue; tk2dSpriteCollection spriteCollection = iterGo.GetComponent<tk2dSpriteCollection>(); tk2dSpriteCollectionData spriteCollectionData = iterGo.GetComponent<tk2dSpriteCollectionData>(); tk2dFont font = iterGo.GetComponent<tk2dFont>(); tk2dSpriteAnimation anim = iterGo.GetComponent<tk2dSpriteAnimation>(); if (spriteCollection) { tk2dSpriteCollectionData thisSpriteCollectionData = spriteCollection.spriteCollection; if (thisSpriteCollectionData) { if (thisSpriteCollectionData.version < 1) { rebuildSpriteCollectionPaths.Add( AssetDatabase.GetAssetPath(spriteCollection )); } newIndex.AddSpriteCollectionData( thisSpriteCollectionData ); } } else if (spriteCollectionData) { string guid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(spriteCollectionData)); bool present = false; foreach (var v in newIndex.GetSpriteCollectionIndex()) { if (v.spriteCollectionDataGUID == guid) { present = true; break; } } if (!present && guid != "") newIndex.AddSpriteCollectionData(spriteCollectionData); } else if (font) { newIndex.AddOrUpdateFont(font); // unfortunate but necessary } else if (anim) { newIndex.AddSpriteAnimation(anim); } else { iterGo = null; System.GC.Collect(); } tk2dEditorUtility.UnloadUnusedAssets(); ++currPrefabCount; } EditorUtility.ClearProgressBar(); // Create index newIndex.hideFlags = 0; // to save it AssetDatabase.CreateAsset(newIndex, indexPath); AssetDatabase.SaveAssets(); // unload all unused assets tk2dEditorUtility.UnloadUnusedAssets(); // Rebuild invalid sprite collections if (rebuildSpriteCollectionPaths.Count > 0) { EditorUtility.DisplayDialog("Upgrade required", "Please wait while your sprite collection is upgraded.", "Ok"); int count = 1; foreach (var scPath in rebuildSpriteCollectionPaths) { tk2dSpriteCollection sc = AssetDatabase.LoadAssetAtPath(scPath, typeof(tk2dSpriteCollection)) as tk2dSpriteCollection; EditorUtility.DisplayProgressBar("Rebuilding Sprite Collections", "Rebuilding Sprite Collection: " + sc.name, (float)count / (float)(rebuildSpriteCollectionPaths.Count)); tk2dSpriteCollectionBuilder.Rebuild(sc); sc = null; tk2dEditorUtility.UnloadUnusedAssets(); ++count; } EditorUtility.ClearProgressBar(); } index = newIndex; tk2dSpriteGuiUtility.ResetCache(); } [System.ObsoleteAttribute] static T[] FindPrefabsInProjectWithComponent<T>() where T : Component // returns null if nothing is found { List<T> allGens = new List<T>(); Stack<string> paths = new Stack<string>(); paths.Push(Application.dataPath); while (paths.Count != 0) { string path = paths.Pop(); string[] files = Directory.GetFiles(path, "*.prefab"); foreach (var file in files) { GameObject go = AssetDatabase.LoadAssetAtPath( file.Substring(Application.dataPath.Length - 6), typeof(GameObject) ) as GameObject; if (!go) continue; T gen = go.GetComponent<T>(); if (gen) { allGens.Add(gen); } } foreach (string subdirs in Directory.GetDirectories(path)) paths.Push(subdirs); } if (allGens.Count == 0) return null; T[] allGensArray = new T[allGens.Count]; for (int i = 0; i < allGens.Count; ++i) allGensArray[i] = allGens[i]; return allGensArray; } public static GameObject CreateGameObjectInScene(string name) { string realName = name; int counter = 0; while (GameObject.Find(realName) != null) { realName = name + counter++; } GameObject go = new GameObject(realName); if (Selection.activeGameObject != null) { string assetPath = AssetDatabase.GetAssetPath(Selection.activeGameObject); if (assetPath.Length == 0) { go.transform.parent = Selection.activeGameObject.transform; go.layer = Selection.activeGameObject.layer; } } go.transform.localPosition = Vector3.zero; go.transform.localRotation = Quaternion.identity; go.transform.localScale = Vector3.one; return go; } public static void DrawMeshBounds(Mesh mesh, Transform transform, Color c) { var e = mesh.bounds.extents; Vector3[] boundPoints = new Vector3[] { mesh.bounds.center + new Vector3(-e.x, e.y, 0.0f), mesh.bounds.center + new Vector3( e.x, e.y, 0.0f), mesh.bounds.center + new Vector3( e.x,-e.y, 0.0f), mesh.bounds.center + new Vector3(-e.x,-e.y, 0.0f), mesh.bounds.center + new Vector3(-e.x, e.y, 0.0f) }; for (int i = 0; i < boundPoints.Length; ++i) boundPoints[i] = transform.TransformPoint(boundPoints[i]); Handles.color = c; Handles.DrawPolyLine(boundPoints); } public static void UnloadUnusedAssets() { Object[] previousSelectedObjects = Selection.objects; Selection.objects = new Object[0]; System.GC.Collect(); EditorUtility.UnloadUnusedAssets(); index = null; Selection.objects = previousSelectedObjects; } public static void CollectAndUnloadUnusedAssets() { System.GC.Collect(); System.GC.WaitForPendingFinalizers(); EditorUtility.UnloadUnusedAssets(); } public static void DeleteAsset(UnityEngine.Object obj) { if (obj == null) return; UnityEditor.AssetDatabase.DeleteAsset(UnityEditor.AssetDatabase.GetAssetPath(obj)); } public static bool IsPrefab(Object obj) { return (PrefabUtility.GetPrefabType(obj) == PrefabType.Prefab); } public static void SetGameObjectActive(GameObject go, bool active) { #if UNITY_3_5 go.SetActiveRecursively(active); #else go.SetActive(active); #endif } public static bool IsGameObjectActive(GameObject go) { #if UNITY_3_5 return go.active; #else return go.activeSelf; #endif } #if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2) private static System.Reflection.PropertyInfo sortingLayerNamesPropInfo = null; private static bool sortingLayerNamesChecked = false; private static string[] GetSortingLayerNames() { if (sortingLayerNamesPropInfo == null && !sortingLayerNamesChecked) { sortingLayerNamesChecked = true; try { System.Type IEU = System.Type.GetType("UnityEditorInternal.InternalEditorUtility,UnityEditor"); if (IEU != null) { sortingLayerNamesPropInfo = IEU.GetProperty("sortingLayerNames", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public); } } catch { } if (sortingLayerNamesPropInfo == null) { Debug.Log("tk2dEditorUtility - Unable to get sorting layer names."); } } if (sortingLayerNamesPropInfo != null) { return sortingLayerNamesPropInfo.GetValue(null, null) as string[]; } else { return new string[0]; } } public static string SortingLayerNamePopup( string label, string value ) { string[] names = GetSortingLayerNames(); if (names.Length == 0) { return EditorGUILayout.TextField(label, value); } else { int sel = 0; for (int i = 0; i < names.Length; ++i) { if (names[i] == value) { sel = i; break; } } sel = EditorGUILayout.Popup(label, sel, names); return names[sel]; } } #endif [MenuItem("GameObject/Create Other/tk2d/Empty GameObject", false, 55000)] static void DoCreateEmptyGameObject() { GameObject go = tk2dEditorUtility.CreateGameObjectInScene("GameObject"); Selection.activeGameObject = go; Undo.RegisterCreatedObjectUndo(go, "Create Empty GameObject"); } }
using System; using System.Runtime.InteropServices; using Clutter; public static class TestCoglVertexBuffer { // Defines the size and resolution of the quad mesh we morph: const int MESH_WIDTH = 100; // number of quads along x axis const int MESH_HEIGHT = 100; // number of quads along y axis const float QUAD_WIDTH = 5.0f; // width in pixels of a single quad const float QUAD_HEIGHT = 5.0f; // height in pixels of a single quad // Defines a sine wave that sweeps across the mesh: const float WAVE_DEPTH = ((MESH_WIDTH * QUAD_WIDTH) / 16.0f); // peak amplitude const float WAVE_PERIODS = 4.0f; const float WAVE_SPEED = 10.0f; // Defines a rippling sine wave emitted from a point: const float RIPPLE_CENTER_X = ((MESH_WIDTH / 2.0f) * QUAD_WIDTH); const float RIPPLE_CENTER_Y = ((MESH_HEIGHT / 2.0f) * QUAD_HEIGHT); const float RIPPLE_RADIUS = (MESH_WIDTH * QUAD_WIDTH); const float RIPPLE_DEPTH = ((MESH_WIDTH * QUAD_WIDTH) / 16.0f); // peak amplitude const float RIPPLE_PERIODS = 4.0f; const float RIPPLE_SPEED = -10.0f; // Defines the width of the gaussian bell used to fade out the alpha // towards the edges of the mesh (starting from the ripple center): const float GAUSSIAN_RADIUS = ((MESH_WIDTH * QUAD_WIDTH) / 6.0f); // Our hues lie in the range [0, 1], and this defines how we map amplitude // to hues (before scaling by {WAVE,RIPPLE}_DEPTH) // As we are interferring two sine waves together; amplitudes lie in the // range [-2, 2] const float HSL_OFFSET = 0.5f; // the hue that we map an amplitude of 0 too const float HSL_SCALE = 0.25f; static Actor dummy; static Timeline timeline; static IntPtr buffer; static unsafe float *quad_mesh_verts; static unsafe byte *quad_mesh_colors; static unsafe ushort *static_indices; static uint n_static_indices; public static unsafe void Main () { Application.Init (); var stage = Stage.Default; var stage_geom = stage.Geometry; var dummy_width = (int)(MESH_WIDTH * QUAD_WIDTH); var dummy_height = (int)(MESH_HEIGHT * QUAD_HEIGHT); dummy = CreateDummyActor (dummy_width, dummy_height); dummy.SetPosition ( (int)((stage_geom.Width / 2.0) - (dummy_width / 2.0)), (int)((stage_geom.Height / 2.0) - (dummy_height / 2.0))); dummy.Painted += (o, e) => { Cogl.General.SetSourceColor4ub (0xff, 0x00, 0x00, 0xff); Cogl.VertexBuffer.DrawElements (buffer, Cogl.GL.GL_TRIANGLE_STRIP, 0, (MESH_WIDTH + 1) * (MESH_HEIGHT + 1), (int)n_static_indices, Cogl.GL.GL_UNSIGNED_SHORT, new IntPtr (static_indices)); }; timeline = new Timeline () { FrameCount = 360, Speed = 60, Loop = true }; timeline.NewFrame += OnNewFrame; GLib.Idle.Add (() => { stage.QueueRedraw (); return true; }); InitQuadMesh (); stage.Color = new Color (0, 0, 0, 0xff); stage.Add (dummy); stage.ShowAll (); timeline.Start (); Application.Run (); } static Actor CreateDummyActor (int width, int height) { var rect = new Rectangle (new Color (0, 0, 0, 0)); rect.SetSize (width, height); return rect; } static float Gaussian (float x, float y) { // Bell width float c = GAUSSIAN_RADIUS; // Peak amplitude float a = 1.0f; // float a = 1.0 / (c * sqrtf (2.0 * G_PI)); // Center offset float b = 0.0f; x = x - RIPPLE_CENTER_X; y = y - RIPPLE_CENTER_Y; float dist = (float)Math.Sqrt (x*x + y*y); return a * (float)Math.Exp ((- ((dist - b) * (dist - b))) / (2.0f * c * c)); } static unsafe void InitQuadMesh () { // Note: we maintain the minimum number of vertices possible. This minimizes // the work required when we come to morph the geometry. // // We use static indices into our mesh so that we can treat the data like a // single triangle list and drawing can be done in one operation (Note: We // are using degenerate triangles at the edges to link to the next row) quad_mesh_verts = (float *)Marshal.AllocHGlobal (sizeof (float) * 3 * (MESH_WIDTH + 1) * (MESH_HEIGHT + 1)); quad_mesh_colors = (byte *)Marshal.AllocHGlobal (sizeof (byte) * 4 * (MESH_WIDTH + 1) * (MESH_HEIGHT + 1)); float *vert = quad_mesh_verts; byte *color = quad_mesh_colors; for (int y = 0; y <= MESH_HEIGHT; y++) { for (int x = 0; x <= MESH_WIDTH; x++) { vert[0] = x * QUAD_WIDTH; vert[1] = y * QUAD_HEIGHT; vert += 3; color[3] = (byte)(Gaussian (x * QUAD_WIDTH, y * QUAD_HEIGHT) * 255.0); color += 4; } } buffer = Cogl.VertexBuffer.New ((MESH_WIDTH + 1) * (MESH_HEIGHT + 1)); Cogl.VertexBuffer.Add (buffer, "gl_Vertex", 3, // n components Cogl.GL.GL_FLOAT, false, // normalized 0, // stride new IntPtr (quad_mesh_verts)); Cogl.VertexBuffer.Add (buffer, "gl_Color", 4, //n components Cogl.GL.GL_UNSIGNED_BYTE, false, // normalized 0, // stride new IntPtr (quad_mesh_colors)); Cogl.VertexBuffer.Submit (buffer); InitStaticIndexArrays (); } static ushort MeshIndex (int x, int y) { return (ushort)(y * (MESH_WIDTH + 1) + x); } static unsafe void InitStaticIndexArrays () { // - Each row takes (2 + 2 * MESH_WIDTH indices) // - Thats 2 to start the triangle strip then 2 indices to add 2 triangles // per mesh quad. // - We have MESH_HEIGHT rows // - It takes one extra index for linking between rows (MESH_HEIGHT - 1) // - A 2 x 3 mesh == 20 indices... n_static_indices = (uint)((2 + 2 * MESH_WIDTH) * MESH_HEIGHT + (MESH_HEIGHT - 1)); static_indices = (ushort *)Marshal.AllocHGlobal ((int)(sizeof (ushort) * n_static_indices)); ushort *i = static_indices; // NB: front facing == anti-clockwise winding i[0] = MeshIndex (0, 0); i[1] = MeshIndex (0, 1); i += 2; bool right_dir = true; for (int y = 0; y < MESH_HEIGHT; y++) { for (int x = 0; x < MESH_WIDTH; x++) { // Add 2 triangles per mesh quad... if (right_dir) { i[0] = MeshIndex (x + 1, y); i[1] = MeshIndex (x + 1, y + 1); } else { i[0] = MeshIndex (MESH_WIDTH - x - 1, y); i[1] = MeshIndex (MESH_WIDTH - x - 1, y + 1); } i += 2; } // Link rows... if (y == (MESH_HEIGHT - 1)) { break; } if (right_dir) { i[0] = MeshIndex (MESH_WIDTH, y + 1); i[1] = MeshIndex (MESH_WIDTH, y + 1); i[2] = MeshIndex (MESH_WIDTH, y + 2); } else { i[0] = MeshIndex (0, y + 1); i[1] = MeshIndex (0, y + 1); i[2] = MeshIndex (0, y + 2); } i += 3; right_dir = !right_dir; } } static unsafe void OnNewFrame (object o, NewFrameArgs args) { Color color = Color.Zero; uint n_frames = timeline.FrameCount; int frame_num = args.FrameNum; float period_progress = ((float)frame_num / (float)n_frames) * 2.0f * (float)Math.PI; float period_progress_sin = (float)Math.Sin (period_progress); float wave_shift = period_progress * WAVE_SPEED; float ripple_shift = period_progress * RIPPLE_SPEED; for (uint y = 0; y <= MESH_HEIGHT; y++) { for (uint x = 0; x <= MESH_WIDTH; x++) { uint vert_index = (MESH_WIDTH + 1) * y + x; float *vert = &quad_mesh_verts[3 * vert_index]; float real_x = x * QUAD_WIDTH; float real_y = y * QUAD_HEIGHT; float wave_offset = (float)x / (MESH_WIDTH + 1); float wave_angle = (WAVE_PERIODS * 2 * (float)Math.PI * wave_offset) + wave_shift; float wave_sin = (float)Math.Sin (wave_angle); float a_sqr = (RIPPLE_CENTER_X - real_x) * (RIPPLE_CENTER_X - real_x); float b_sqr = (RIPPLE_CENTER_Y - real_y) * (RIPPLE_CENTER_Y - real_y); float ripple_offset = (float)Math.Sqrt (a_sqr + b_sqr) / RIPPLE_RADIUS; float ripple_angle = (RIPPLE_PERIODS * 2 * (float)Math.PI * ripple_offset) + ripple_shift; float ripple_sin = (float)Math.Sin (ripple_angle); vert[2] = (wave_sin * WAVE_DEPTH) + (ripple_sin * RIPPLE_DEPTH); // Burn some CPU time picking a pretty color... float h = (HSL_OFFSET + wave_sin + ripple_sin + period_progress_sin) * HSL_SCALE; float s = 0.5f; float l = 0.25f + (period_progress_sin + 1.0f) / 4.0f; color.FromHls (h * 360.0f, l, s); byte *c = &quad_mesh_colors[4 * vert_index]; c[0] = color.R; c[1] = color.G; c[2] = color.B; } } Cogl.VertexBuffer.Add (buffer, "gl_Vertex", 3, // n components Cogl.GL.GL_FLOAT, false, // normalized 0, // stride new IntPtr (quad_mesh_verts)); Cogl.VertexBuffer.Add (buffer, "gl_Color", 4, // n components Cogl.GL.GL_UNSIGNED_BYTE, false, // normalized 0, // stride new IntPtr (quad_mesh_colors)); Cogl.VertexBuffer.Submit (buffer); dummy.SetRotation (RotateAxis.Z, frame_num, (int)((MESH_WIDTH * QUAD_WIDTH) / 2), (int)((MESH_HEIGHT * QUAD_HEIGHT) / 2), 0); dummy.SetRotation (RotateAxis.X, frame_num, (int)((MESH_WIDTH * QUAD_WIDTH) / 2), (int)((MESH_HEIGHT * QUAD_HEIGHT) / 2), 0); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void SignInt32() { var test = new SimpleBinaryOpTest__SignInt32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__SignInt32 { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Int32); private const int Op2ElementCount = VectorSize / sizeof(Int32); private const int RetElementCount = VectorSize / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector128<Int32> _clsVar1; private static Vector128<Int32> _clsVar2; private Vector128<Int32> _fld1; private Vector128<Int32> _fld2; private SimpleBinaryOpTest__DataTable<Int32, Int32, Int32> _dataTable; static SimpleBinaryOpTest__SignInt32() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue + 1, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__SignInt32() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue + 1, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue + 1, int.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<Int32, Int32, Int32>(_data1, _data2, new Int32[RetElementCount], VectorSize); } public bool IsSupported => Ssse3.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Ssse3.Sign( Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Ssse3.Sign( Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Ssse3.Sign( Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Ssse3).GetMethod(nameof(Ssse3.Sign), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Ssse3).GetMethod(nameof(Ssse3.Sign), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Ssse3).GetMethod(nameof(Ssse3.Sign), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Ssse3.Sign( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr); var result = Ssse3.Sign(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)); var result = Ssse3.Sign(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)); var result = Ssse3.Sign(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__SignInt32(); var result = Ssse3.Sign(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Ssse3.Sign(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Int32> left, Vector128<Int32> right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { if (result[0] != (right[0] < 0 ? (int)(-left[0]) : (right[0] > 0 ? left[0] : 0))) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (right[i] < 0 ? (int)(-left[i]) : (right[i] > 0 ? left[i] : 0))) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Ssse3)}.{nameof(Ssse3.Sign)}<Int32>(Vector128<Int32>, Vector128<Int32>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
using System; using Orleans.Runtime.Scheduler; using Orleans.Runtime.Versions; using Orleans.Runtime.Versions.Compatibility; namespace Orleans.Runtime { /// <summary> /// Responsible for scheduling incoming messages for an activation. /// </summary> internal class ActivationMessageScheduler { private readonly Dispatcher _dispatcher; private readonly IncomingRequestMonitor _incomingRequestMonitor; private readonly Catalog _catalog; private readonly GrainVersionManifest _versionManifest; private readonly RuntimeMessagingTrace _messagingTrace; private readonly ActivationCollector _activationCollector; private readonly CompatibilityDirectorManager _compatibilityDirectorManager; private readonly OrleansTaskScheduler _scheduler; public ActivationMessageScheduler( Catalog catalog, Dispatcher dispatcher, GrainVersionManifest versionManifest, RuntimeMessagingTrace messagingTrace, ActivationCollector activationCollector, OrleansTaskScheduler scheduler, CompatibilityDirectorManager compatibilityDirectorManager, IncomingRequestMonitor incomingRequestMonitor) { _incomingRequestMonitor = incomingRequestMonitor; _catalog = catalog; _versionManifest = versionManifest; _messagingTrace = messagingTrace; _activationCollector = activationCollector; _scheduler = scheduler; _compatibilityDirectorManager = compatibilityDirectorManager; _dispatcher = dispatcher; } /// <summary> /// Receive a new message: /// - validate order constraints, queue (or possibly redirect) if out of order /// - validate transactions constraints /// - invoke handler if ready, otherwise enqueue for later invocation /// </summary> public void ReceiveMessage(IGrainContext target, Message message) { var activation = (ActivationData)target; _messagingTrace.OnDispatcherReceiveMessage(message); // Don't process messages that have already timed out if (message.IsExpired) { MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message); _messagingTrace.OnDropExpiredMessage(message, MessagingStatisticsGroup.Phase.Dispatch); return; } if (message.Direction == Message.Directions.Response) { ReceiveResponse(message, activation); } else // Request or OneWay { if (activation.State == ActivationState.Valid) { _activationCollector.TryRescheduleCollection(activation); } // Silo is always capable to accept a new request. It's up to the activation to handle its internal state. // If activation is shutting down, it will queue and later forward this request. ReceiveRequest(message, activation); } } /// <summary> /// Invoked when an activation has finished a transaction and may be ready for additional transactions /// </summary> /// <param name="activation">The activation that has just completed processing this message</param> /// <param name="message">The message that has just completed processing. /// This will be <c>null</c> for the case of completion of Activate/Deactivate calls.</param> internal void OnActivationCompletedRequest(ActivationData activation, Message message) { lock (activation) { activation.ResetRunning(message); // ensure inactive callbacks get run even with transactions disabled if (!activation.IsCurrentlyExecuting) activation.RunOnInactive(); // Run message pump to see if there is a new request arrived to be processed RunMessagePump(activation); } } internal void RunMessagePump(ActivationData activation) { // Note: this method must be called while holding lock (activation) // don't run any messages if activation is not ready or deactivating if (activation.State != ActivationState.Valid) return; bool runLoop; do { runLoop = false; var nextMessage = activation.PeekNextWaitingMessage(); if (nextMessage == null) continue; if (!ActivationMayAcceptRequest(activation, nextMessage)) continue; activation.DequeueNextWaitingMessage(); // we might be over-writing an already running read only request. HandleIncomingRequest(nextMessage, activation); runLoop = true; } while (runLoop); } /// <summary> /// Enqueue message for local handling after transaction completes /// </summary> /// <param name="message"></param> /// <param name="targetActivation"></param> private void EnqueueRequest(Message message, ActivationData targetActivation) { var overloadException = targetActivation.CheckOverloaded(); if (overloadException != null) { MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message); _dispatcher.RejectMessage(message, Message.RejectionTypes.Overloaded, overloadException, "Target activation is overloaded " + targetActivation); return; } switch (targetActivation.EnqueueMessage(message)) { case ActivationData.EnqueueMessageResult.Success: // Great, nothing to do break; case ActivationData.EnqueueMessageResult.ErrorInvalidActivation: _dispatcher.ProcessRequestToInvalidActivation(message, targetActivation.Address, targetActivation.ForwardingAddress, "EnqueueRequest"); break; case ActivationData.EnqueueMessageResult.ErrorActivateFailed: _dispatcher.ProcessRequestToInvalidActivation(message, targetActivation.Address, targetActivation.ForwardingAddress, "EnqueueRequest", rejectMessages: true); break; case ActivationData.EnqueueMessageResult.ErrorStuckActivation: // Avoid any new call to this activation _dispatcher.ProcessRequestToStuckActivation(message, targetActivation, "EnqueueRequest - blocked grain"); break; default: throw new ArgumentOutOfRangeException(); } // Dont count this as end of processing. The message will come back after queueing via HandleIncomingRequest. } private void ReceiveResponse(Message message, ActivationData targetActivation) { lock (targetActivation) { if (targetActivation.State == ActivationState.Invalid || targetActivation.State == ActivationState.FailedToActivate) { _messagingTrace.OnDispatcherReceiveInvalidActivation(message, targetActivation.State); return; } MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedOk(message); _catalog.RuntimeClient.ReceiveResponse(message); } } /// <summary> /// Check if we can locally accept this message. /// Redirects if it can't be accepted. /// </summary> /// <param name="message"></param> /// <param name="targetActivation"></param> private void ReceiveRequest(Message message, ActivationData targetActivation) { lock (targetActivation) { // If the grain was previously inactive, schedule it for workload analysis if (targetActivation.IsInactive) { _incomingRequestMonitor.MarkRecentlyUsed(targetActivation); } if (!ActivationMayAcceptRequest(targetActivation, message)) { EnqueueRequest(message, targetActivation); } else { HandleIncomingRequest(message, targetActivation); } } } /// <summary> /// Determine if the activation is able to currently accept the given message /// - always accept responses /// For other messages, require that: /// - activation is properly initialized /// - the message would not cause a reentrancy conflict /// </summary> /// <param name="targetActivation"></param> /// <param name="incoming"></param> /// <returns></returns> private bool ActivationMayAcceptRequest(ActivationData targetActivation, Message incoming) { if (targetActivation.State != ActivationState.Valid) return false; if (!targetActivation.IsCurrentlyExecuting) return true; return CanInterleave(targetActivation, incoming); } /// <summary> /// Whether an incoming message can interleave /// </summary> /// <param name="targetActivation"></param> /// <param name="incoming"></param> /// <returns></returns> public bool CanInterleave(ActivationData targetActivation, Message incoming) { if (incoming.IsAlwaysInterleave) { return true; } if (targetActivation.Blocking is null) { return true; } if (targetActivation.Blocking.IsReadOnly && incoming.IsReadOnly) { return true; } if (targetActivation.GetComponent<GrainCanInterleave>() is GrainCanInterleave canInterleave) { return canInterleave.MayInterleave(incoming); } return false; } /// <summary> /// Handle an incoming message and queue/invoke appropriate handler /// </summary> /// <param name="message"></param> /// <param name="targetActivation"></param> public void HandleIncomingRequest(Message message, ActivationData targetActivation) { lock (targetActivation) { if (targetActivation.State == ActivationState.Invalid || targetActivation.State == ActivationState.FailedToActivate) { _dispatcher.ProcessRequestToInvalidActivation( message, targetActivation.Address, targetActivation.ForwardingAddress, "HandleIncomingRequest", rejectMessages: targetActivation.State == ActivationState.FailedToActivate); return; } if (message.InterfaceVersion > 0) { var compatibilityDirector = _compatibilityDirectorManager.GetDirector(message.InterfaceType); var currentVersion = _versionManifest.GetLocalVersion(message.InterfaceType); if (!compatibilityDirector.IsCompatible(message.InterfaceVersion, currentVersion)) { _catalog.DeactivateActivationOnIdle(targetActivation); _dispatcher.ProcessRequestToInvalidActivation( message, targetActivation.Address, targetActivation.ForwardingAddress, "HandleIncomingRequest - Incompatible request"); return; } } // Now we can actually scheduler processing of this request targetActivation.RecordRunning(message, message.IsAlwaysInterleave); MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedOk(message); _messagingTrace.OnScheduleMessage(message); _scheduler.QueueWorkItem(new InvokeWorkItem(targetActivation, message, _dispatcher.RuntimeClient, this)); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.VisualStudio.Shell; [assembly: ProvideBindingRedirection( AssemblyName = "Microsoft.Build.Tasks.CodeAnalysis", OldVersionLowerBound = Constants.OldVersionLowerBound, OldVersionUpperBound = Constants.OldVersionUpperBound, NewVersion = Constants.NewVersion, PublicKeyToken = Constants.PublicKeyToken, GenerateCodeBase = false)] [assembly: ProvideBindingRedirection( AssemblyName = "Microsoft.CodeAnalysis.CSharp", OldVersionLowerBound = Constants.OldVersionLowerBound, OldVersionUpperBound = Constants.OldVersionUpperBound, NewVersion = Constants.NewVersion, PublicKeyToken = Constants.PublicKeyToken, GenerateCodeBase = false)] [assembly: ProvideBindingRedirection( AssemblyName = "Microsoft.CodeAnalysis.CSharp.EditorFeatures", OldVersionLowerBound = Constants.OldVersionLowerBound, OldVersionUpperBound = Constants.OldVersionUpperBound, NewVersion = Constants.NewVersion, PublicKeyToken = Constants.PublicKeyToken, GenerateCodeBase = false)] [assembly: ProvideBindingRedirection( AssemblyName = "Microsoft.CodeAnalysis.CSharp.Features", OldVersionLowerBound = Constants.OldVersionLowerBound, OldVersionUpperBound = Constants.OldVersionUpperBound, NewVersion = Constants.NewVersion, PublicKeyToken = Constants.PublicKeyToken, GenerateCodeBase = false)] [assembly: ProvideBindingRedirection( AssemblyName = "Microsoft.CodeAnalysis.CSharp.Workspaces", OldVersionLowerBound = Constants.OldVersionLowerBound, OldVersionUpperBound = Constants.OldVersionUpperBound, NewVersion = Constants.NewVersion, PublicKeyToken = Constants.PublicKeyToken, GenerateCodeBase = false)] [assembly: ProvideBindingRedirection( AssemblyName = "Microsoft.CodeAnalysis", OldVersionLowerBound = Constants.OldVersionLowerBound, OldVersionUpperBound = Constants.OldVersionUpperBound, NewVersion = Constants.NewVersion, PublicKeyToken = Constants.PublicKeyToken, GenerateCodeBase = false)] [assembly: ProvideBindingRedirection( AssemblyName = "Microsoft.CodeAnalysis.EditorFeatures", OldVersionLowerBound = Constants.OldVersionLowerBound, OldVersionUpperBound = Constants.OldVersionUpperBound, NewVersion = Constants.NewVersion, PublicKeyToken = Constants.PublicKeyToken, GenerateCodeBase = false)] [assembly: ProvideBindingRedirection( AssemblyName = "Microsoft.CodeAnalysis.EditorFeatures.Text", OldVersionLowerBound = Constants.OldVersionLowerBound, OldVersionUpperBound = Constants.OldVersionUpperBound, NewVersion = Constants.NewVersion, PublicKeyToken = Constants.PublicKeyToken, GenerateCodeBase = false)] [assembly: ProvideBindingRedirection( AssemblyName = "Microsoft.CodeAnalysis.Features", OldVersionLowerBound = Constants.OldVersionLowerBound, OldVersionUpperBound = Constants.OldVersionUpperBound, NewVersion = Constants.NewVersion, PublicKeyToken = Constants.PublicKeyToken, GenerateCodeBase = false)] [assembly: ProvideBindingRedirection( AssemblyName = "Microsoft.CodeAnalysis.VisualBasic", OldVersionLowerBound = Constants.OldVersionLowerBound, OldVersionUpperBound = Constants.OldVersionUpperBound, NewVersion = Constants.NewVersion, PublicKeyToken = Constants.PublicKeyToken, GenerateCodeBase = false)] [assembly: ProvideBindingRedirection( AssemblyName = "Microsoft.CodeAnalysis.VisualBasic.EditorFeatures", OldVersionLowerBound = Constants.OldVersionLowerBound, OldVersionUpperBound = Constants.OldVersionUpperBound, NewVersion = Constants.NewVersion, PublicKeyToken = Constants.PublicKeyToken, GenerateCodeBase = false)] [assembly: ProvideBindingRedirection( AssemblyName = "Microsoft.CodeAnalysis.VisualBasic.Features", OldVersionLowerBound = Constants.OldVersionLowerBound, OldVersionUpperBound = Constants.OldVersionUpperBound, NewVersion = Constants.NewVersion, PublicKeyToken = Constants.PublicKeyToken, GenerateCodeBase = false)] [assembly: ProvideBindingRedirection( AssemblyName = "Microsoft.CodeAnalysis.VisualBasic.Workspaces", OldVersionLowerBound = Constants.OldVersionLowerBound, OldVersionUpperBound = Constants.OldVersionUpperBound, NewVersion = Constants.NewVersion, PublicKeyToken = Constants.PublicKeyToken, GenerateCodeBase = false)] [assembly: ProvideBindingRedirection( AssemblyName = "Microsoft.CodeAnalysis.Workspaces.Desktop", OldVersionLowerBound = Constants.OldVersionLowerBound, OldVersionUpperBound = Constants.OldVersionUpperBound, NewVersion = Constants.NewVersion, PublicKeyToken = Constants.PublicKeyToken, GenerateCodeBase = false)] [assembly: ProvideBindingRedirection( AssemblyName = "Microsoft.CodeAnalysis.Workspaces", OldVersionLowerBound = Constants.OldVersionLowerBound, OldVersionUpperBound = Constants.OldVersionUpperBound, NewVersion = Constants.NewVersion, PublicKeyToken = Constants.PublicKeyToken, GenerateCodeBase = false)] [assembly: ProvideBindingRedirection( AssemblyName = "Microsoft.VisualStudio.LanguageServices", OldVersionLowerBound = Constants.OldVersionLowerBound, OldVersionUpperBound = Constants.OldVersionUpperBound, NewVersion = Constants.NewVersion, PublicKeyToken = Constants.PublicKeyToken, GenerateCodeBase = false)] [assembly: ProvideBindingRedirection( AssemblyName = "Microsoft.VisualStudio.LanguageServices.Implementation", OldVersionLowerBound = Constants.OldVersionLowerBound, OldVersionUpperBound = Constants.OldVersionUpperBound, NewVersion = Constants.NewVersion, PublicKeyToken = Constants.PublicKeyToken, GenerateCodeBase = false)] [assembly: ProvideBindingRedirection( AssemblyName = "Microsoft.VisualStudio.LanguageServices.VisualBasic", OldVersionLowerBound = Constants.OldVersionLowerBound, OldVersionUpperBound = Constants.OldVersionUpperBound, NewVersion = Constants.NewVersion, PublicKeyToken = Constants.PublicKeyToken, GenerateCodeBase = false)] [assembly: ProvideBindingRedirection( AssemblyName = "Microsoft.VisualStudio.LanguageServices.CSharp", OldVersionLowerBound = Constants.OldVersionLowerBound, OldVersionUpperBound = Constants.OldVersionUpperBound, NewVersion = Constants.NewVersion, PublicKeyToken = Constants.PublicKeyToken, GenerateCodeBase = false)] [assembly: ProvideBindingRedirection( AssemblyName = "Microsoft.VisualStudio.LanguageServices.SolutionExplorer", OldVersionLowerBound = Constants.OldVersionLowerBound, OldVersionUpperBound = Constants.OldVersionUpperBound, NewVersion = Constants.NewVersion, PublicKeyToken = Constants.PublicKeyToken, GenerateCodeBase = false)] [assembly: ProvideBindingRedirection( AssemblyName = "System.Reflection.Metadata", OldVersionLowerBound = "1.0.0.0", OldVersionUpperBound = "1.0.99.0", NewVersion = "1.1.0.0", PublicKeyToken = "b03f5f7f11d50a3a", GenerateCodeBase = false)] #if !OFFICIAL_BUILD [assembly: ProvideBindingRedirection( AssemblyName = "Microsoft.VisualStudio.InteractiveWindow", OldVersionLowerBound = Constants.OldVersionLowerBound, OldVersionUpperBound = Constants.OldVersionUpperBound, NewVersion = Constants.NewVersion, PublicKeyToken = Constants.PublicKeyToken, GenerateCodeBase = false)] [assembly: ProvideBindingRedirection( AssemblyName = "Microsoft.VisualStudio.VsInteractiveWindow", OldVersionLowerBound = Constants.OldVersionLowerBound, OldVersionUpperBound = Constants.OldVersionUpperBound, NewVersion = Constants.NewVersion, PublicKeyToken = Constants.PublicKeyToken, GenerateCodeBase = false)] #endif internal class Constants { public const string OldVersionLowerBound = "0.7.0.0"; public const string OldVersionUpperBound = "1.1.0.0"; #if OFFICIAL_BUILD // If this is an official build we want to generate binding // redirects from our old versions to the release version public const string NewVersion = "1.1.0.0"; #else // Non-official builds get redirects to local 42.42.42.42, // which will only be built locally public const string NewVersion = "42.42.42.42"; #endif public const string PublicKeyToken = "31BF3856AD364E35"; }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the PnExpediente class. /// </summary> [Serializable] public partial class PnExpedienteCollection : ActiveList<PnExpediente, PnExpedienteCollection> { public PnExpedienteCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>PnExpedienteCollection</returns> public PnExpedienteCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { PnExpediente o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the PN_expediente table. /// </summary> [Serializable] public partial class PnExpediente : ActiveRecord<PnExpediente>, IActiveRecord { #region .ctors and Default Settings public PnExpediente() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public PnExpediente(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public PnExpediente(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public PnExpediente(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("PN_expediente", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdExpediente = new TableSchema.TableColumn(schema); colvarIdExpediente.ColumnName = "id_expediente"; colvarIdExpediente.DataType = DbType.Int32; colvarIdExpediente.MaxLength = 0; colvarIdExpediente.AutoIncrement = true; colvarIdExpediente.IsNullable = false; colvarIdExpediente.IsPrimaryKey = true; colvarIdExpediente.IsForeignKey = false; colvarIdExpediente.IsReadOnly = false; colvarIdExpediente.DefaultSetting = @""; colvarIdExpediente.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdExpediente); TableSchema.TableColumn colvarIdEfeConv = new TableSchema.TableColumn(schema); colvarIdEfeConv.ColumnName = "id_efe_conv"; colvarIdEfeConv.DataType = DbType.Int32; colvarIdEfeConv.MaxLength = 0; colvarIdEfeConv.AutoIncrement = false; colvarIdEfeConv.IsNullable = false; colvarIdEfeConv.IsPrimaryKey = false; colvarIdEfeConv.IsForeignKey = false; colvarIdEfeConv.IsReadOnly = false; colvarIdEfeConv.DefaultSetting = @""; colvarIdEfeConv.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdEfeConv); TableSchema.TableColumn colvarNroExp = new TableSchema.TableColumn(schema); colvarNroExp.ColumnName = "nro_exp"; colvarNroExp.DataType = DbType.AnsiString; colvarNroExp.MaxLength = -1; colvarNroExp.AutoIncrement = false; colvarNroExp.IsNullable = true; colvarNroExp.IsPrimaryKey = false; colvarNroExp.IsForeignKey = false; colvarNroExp.IsReadOnly = false; colvarNroExp.DefaultSetting = @""; colvarNroExp.ForeignKeyTableName = ""; schema.Columns.Add(colvarNroExp); TableSchema.TableColumn colvarFechaIng = new TableSchema.TableColumn(schema); colvarFechaIng.ColumnName = "fecha_ing"; colvarFechaIng.DataType = DbType.DateTime; colvarFechaIng.MaxLength = 0; colvarFechaIng.AutoIncrement = false; colvarFechaIng.IsNullable = true; colvarFechaIng.IsPrimaryKey = false; colvarFechaIng.IsForeignKey = false; colvarFechaIng.IsReadOnly = false; colvarFechaIng.DefaultSetting = @""; colvarFechaIng.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaIng); TableSchema.TableColumn colvarMonto = new TableSchema.TableColumn(schema); colvarMonto.ColumnName = "monto"; colvarMonto.DataType = DbType.Int32; colvarMonto.MaxLength = 0; colvarMonto.AutoIncrement = false; colvarMonto.IsNullable = true; colvarMonto.IsPrimaryKey = false; colvarMonto.IsForeignKey = false; colvarMonto.IsReadOnly = false; colvarMonto.DefaultSetting = @""; colvarMonto.ForeignKeyTableName = ""; schema.Columns.Add(colvarMonto); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("PN_expediente",schema); } } #endregion #region Props [XmlAttribute("IdExpediente")] [Bindable(true)] public int IdExpediente { get { return GetColumnValue<int>(Columns.IdExpediente); } set { SetColumnValue(Columns.IdExpediente, value); } } [XmlAttribute("IdEfeConv")] [Bindable(true)] public int IdEfeConv { get { return GetColumnValue<int>(Columns.IdEfeConv); } set { SetColumnValue(Columns.IdEfeConv, value); } } [XmlAttribute("NroExp")] [Bindable(true)] public string NroExp { get { return GetColumnValue<string>(Columns.NroExp); } set { SetColumnValue(Columns.NroExp, value); } } [XmlAttribute("FechaIng")] [Bindable(true)] public DateTime? FechaIng { get { return GetColumnValue<DateTime?>(Columns.FechaIng); } set { SetColumnValue(Columns.FechaIng, value); } } [XmlAttribute("Monto")] [Bindable(true)] public int? Monto { get { return GetColumnValue<int?>(Columns.Monto); } set { SetColumnValue(Columns.Monto, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varIdEfeConv,string varNroExp,DateTime? varFechaIng,int? varMonto) { PnExpediente item = new PnExpediente(); item.IdEfeConv = varIdEfeConv; item.NroExp = varNroExp; item.FechaIng = varFechaIng; item.Monto = varMonto; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdExpediente,int varIdEfeConv,string varNroExp,DateTime? varFechaIng,int? varMonto) { PnExpediente item = new PnExpediente(); item.IdExpediente = varIdExpediente; item.IdEfeConv = varIdEfeConv; item.NroExp = varNroExp; item.FechaIng = varFechaIng; item.Monto = varMonto; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdExpedienteColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdEfeConvColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn NroExpColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn FechaIngColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn MontoColumn { get { return Schema.Columns[4]; } } #endregion #region Columns Struct public struct Columns { public static string IdExpediente = @"id_expediente"; public static string IdEfeConv = @"id_efe_conv"; public static string NroExp = @"nro_exp"; public static string FechaIng = @"fecha_ing"; public static string Monto = @"monto"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
using System; using System.Text; using System.Threading.Tasks; using System.Xml; using AspNetCore.XmlRpc.Extensions; namespace AspNetCore.XmlRpc { public class XmlRpcHandler : IXmlRpcHandler { public XmlRpcHandler() { } public bool CanProcess(XmlRpcContext context) { return context.HttpContext.Request.Path.StartsWithSegments(context.Options.Endpoint); } public Task ProcessRequestAsync(XmlRpcContext context) { var request = context.HttpContext.Request; if (!request.Method.Equals( HttpVerbs.Post.ToString(), StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException(); } var requestInfo = XmlRpcRequestParser.GetRequestInformation( request.Body); if (string.IsNullOrWhiteSpace(requestInfo.MethodName)) { throw new InvalidOperationException( "XmlRpc call does not contain a method."); } var methodInfo = XmlRpcRequestParser.GetRequestedMethod(requestInfo, context.Services); if (methodInfo == null) { throw new InvalidOperationException( string.Concat( "There was no implementation of IXmlRpcService ", "found, that containins a method decorated with ", " the XmlRpcMethodAttribute value'", requestInfo.MethodName, "'.")); } var result = XmlRpcRequestParser.ExecuteRequestedMethod( requestInfo, methodInfo, context); var response = context.HttpContext.Response; response.ContentType = "text/xml"; var settings = new XmlWriterSettings { OmitXmlDeclaration = false, Encoding = new UTF8Encoding(false), // Get rid of BOM Indent = true, }; using (var writer = XmlWriter.Create(response.Body, settings)) { if (methodInfo.ResponseType == XmlRpcResponseType.Wrapped) { WriteWrappedResponse(writer, result); return Task.CompletedTask; } WriteRawResponse(writer, result); return Task.CompletedTask; } } private bool _generateServiceOverview = true; public bool GenerateServiceOverview { get { return _generateServiceOverview; } set { _generateServiceOverview = value; } } private static void WriteRawResponse( XmlWriter output, dynamic result) { output.WriteStartDocument(); { output.WriteStartElement("response"); { WriteObject(output, result); } output.WriteEndElement(); } output.WriteEndDocument(); } private static void WriteWrappedResponse( XmlWriter output, dynamic result) { output.WriteStartDocument(); { output.WriteStartElement("methodResponse"); { output.WriteStartElement("params"); { output.WriteStartElement("param"); { output.WriteStartElement("value"); { WriteObject(output, result); } output.WriteEndElement(); } output.WriteEndElement(); } output.WriteEndElement(); } output.WriteEndElement(); } output.WriteEndDocument(); } private static void WriteObject( XmlWriter xmlWriter, dynamic result) { Type type = result.GetType(); if (type.IsPrimitive()) { xmlWriter.WrapOutgoingType((object)result); } else if (type.IsArray) { WriteArray(xmlWriter, result); } else if (!type.IsPrimitive && type.IsClass) { WriteClass(xmlWriter, type, result); } } private static void WriteClass( XmlWriter xmlWriter, Type type, object obj) { xmlWriter.WriteStartElement("struct"); foreach (var property in type.GetProperties()) { var value = property.GetValue(obj, null); if (value == null) continue; xmlWriter.WriteStartElement("member"); { xmlWriter.WriteStartElement("name"); { xmlWriter.WriteString(property.GetSerializationName()); } xmlWriter.WriteEndElement(); xmlWriter.WriteStartElement("value"); { WriteObject(xmlWriter, value); } xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } // struct xmlWriter.WriteEndElement(); } private static void WriteArray(XmlWriter xmlWriter, dynamic obj) { xmlWriter.WriteStartElement("array"); { xmlWriter.WriteStartElement("data"); { foreach (var resultEntry in obj) { xmlWriter.WriteStartElement("value"); { WriteObject(xmlWriter, resultEntry); } xmlWriter.WriteEndElement(); } } xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } } }
using System; using System.Collections.Generic; using System.Text; using CodeEditor.Text.Data; using UnityEngine; namespace CodeEditor.Text.UI.Unity.Engine.Implementation { /* Plain text [PT] (the actual text document state). Used for: Inserting/deleting char at caret position/selection in document RenderText with whitespaced tabs [RT] Used for mapping between logical caret and visual caret pos RenderColoredText [RCT]: Rich text with whitespaced tabs. Used for rendering CaretPosition state is in PT space Selection state is in PT space On rendering selection get rect by mapping caret from PT pos to RT pos and get Rect from style using RT positions On mouse clicked get PT pos by mapping from RT pos to PT pos */ class TextView : ITextView { float TopMargin = 6; float LeftMargin; readonly ITextViewDocument _document; readonly ITextViewAppearance _appearance; readonly ITextViewAdornments _adornments; readonly ITextViewWhitespace _whitespace; readonly IFontManager _fontManager; readonly Selection _selection; readonly IMouseCursors _mouseCursors; readonly IMouseCursorRegions _mouseCursorsRegions; readonly ISettings _settings; public Action<int, int, int> Clicked {get; set;} public Action TextViewEvent { get; set; } public bool ShowCursor { get; set; } public TextView( ITextViewDocument document, ITextViewAppearance appearance, ITextViewAdornments adornments, IMouseCursors mouseCursors, IMouseCursorRegions mouseCursorRegions, ITextViewWhitespace whitespace, ISettings settings, IFontManager fontManager) { _appearance = appearance; _adornments = adornments; _document = document; _mouseCursors = mouseCursors; _mouseCursorsRegions = mouseCursorRegions; _whitespace = whitespace; _settings = settings; _fontManager = fontManager; _selection = new Selection(document.Caret); _document.Caret.Moved += EnsureCursorIsVisible; } public ITextViewMargins Margins { get; set; } public Rect ViewPort { get; set; } public ITextViewWhitespace Whitespace { get { return _whitespace; } } public IFontManager FontManager { get { return _fontManager; } } public ISettings Settings { get { return _settings; } } public Vector2 ScrollOffset { get; set; } public ITextViewDocument Document { get { return _document; } } public ITextViewAppearance Appearance { get { return _appearance; } } public IMouseCursors MouseCursors { get { return _mouseCursors; } } public IMouseCursorRegions MouseCursorsRegions { get { return _mouseCursorsRegions;} } public float LineHeight { get { return _appearance.Text.lineHeight; } } public bool HasSelection { get {return _selection.HasSelection();}} public Position SelectionAnchor { get {return _selection.Anchor;} set {_selection.Anchor = value;} } public bool GetSelectionStart (out int row, out int column) { row = column = 0; if (!HasSelection) return false; row = _selection.BeginDrawPos.Row; column = _selection.BeginDrawPos.Column; return true; } public bool GetSelectionEnd (out int row, out int column) { row = column = 0; if (!HasSelection) return false; row = _selection.EndDrawPos.Row; column = _selection.EndDrawPos.Column; return true; } public bool GetSelectionInDocument (out int pos, out int length) { pos = length = 0; if (!HasSelection) return false; Position begin = _selection.BeginDrawPos; Position end = _selection.EndDrawPos; int startPos = _document.Line (begin.Row).Start + begin.Column; int endPos = _document.Line (end.Row).Start + end.Column; pos = startPos; length = endPos - startPos; return true; } public void OnGUI() { if (Repainting) EraseBackground(); LeftMargin = LineHeight * 0.5f; // Make left margin proportional with font size ScrollOffset = GUI.BeginScrollView(ViewPort, ScrollOffset, ContentRect); { if (ScrollOffset.y < 0) ScrollOffset = new Vector2(ScrollOffset.x, 0f); DoGUIOnElements(); HandleMouseDragSelection (); if (TextViewEvent != null) TextViewEvent(); } GUI.EndScrollView(); HandleMouseCursorImage(); } private bool VerticalScrollbarVisible { get { return ContentRect.height > ViewPort.height; } } private bool HorizontalScrollbarVisible { get { return ContentRect.height > ViewPort.height; } } private void HandleMouseCursorImage() { Rect textAreaRect = ViewPort; textAreaRect.x += Margins.TotalWidth; textAreaRect.width -= Margins.TotalWidth; const float kScrollbarWidth = 17f; if (VerticalScrollbarVisible) textAreaRect.width -= kScrollbarWidth; if (HorizontalScrollbarVisible) textAreaRect.height -= kScrollbarWidth; _mouseCursorsRegions.AddMouseCursorRegion(textAreaRect, _mouseCursors.Text); } private void EraseBackground() { GUIUtils.DrawRect(ViewPort, Appearance.BackgroundColor); if (BackgroundStyle != null) GUI.Label(ViewPort, GUIContent.none, BackgroundStyle); } void DoGUIOnElements() { int firstRow, lastRow; GetFirstAndLastRowVisible(LineCount, ScrollOffset.y, ViewPort.height, out firstRow, out lastRow); DrawSelection (firstRow, lastRow); for (var row = firstRow; row <= lastRow; ++row) { var lineRect = GetLineRect (row); var line = Line(row); if (Repainting) Margins.Repaint(line, lineRect); else Margins.HandleInputEvent(line, lineRect); lineRect.x += CodeOffset; if (Repainting) DrawLine(lineRect, row, row + 110101010); } } float CodeOffset { get { return Margins.TotalWidth + LeftMargin; } } void HandleMouseDragSelection () { int controlID = 666666; Event evt = Event.current; switch (evt.type) { case EventType.mouseDown: // If dragging outside window and releasing mousedown we do not get a MouseUp event so we // can clear the hotcontrol. We therefore check if we already have hotcontrol and allow mouse down action if so. bool alreadyHotcontrol = GUIUtility.hotControl == controlID; if ((GUIUtility.hotControl == 0 || alreadyHotcontrol) && evt.button == 0) { Position pos = GetCaretPositionUnderMouseCursor(Event.current.mousePosition); if (evt.clickCount == 1) { GUIUtility.hotControl = controlID; // Grab mouse focus _selection.Clear(); if (pos.Column >= 0) { _selection.Anchor = pos; _document.Caret.SetPosition(pos.Row, pos.Column); } } if (evt.clickCount == 2) { _selection.Clear (); } if (Clicked != null) Clicked(pos.Row, pos.Column, evt.clickCount); evt.Use(); } break; case EventType.mouseDrag: if (GUIUtility.hotControl == controlID) { var cursorPosition = Event.current.mousePosition; cursorPosition.x = Mathf.Clamp (cursorPosition.x, ViewPort.xMin, ViewPort.xMax); // clamp in x so we drag select while having cursor outside view rect Position pos = GetCaretPositionUnderMouseCursor (cursorPosition); if (pos.Column >= 0) { if (_selection.Anchor.Row < 0) _selection.Anchor = pos; // init if dragging from outside into the text _document.Caret.SetPosition(pos.Row, pos.Column); evt.Use(); } } break; case EventType.mouseUp: if (GUIUtility.hotControl == controlID && evt.button == 0) { Position pos = GetCaretPositionUnderMouseCursor(Event.current.mousePosition); if (_selection.Anchor == pos) _selection.Clear (); GUIUtility.hotControl = 0; evt.Use(); } break; } } void DrawSelection (int firstRowVisible, int lastRowVisible) { if (!_selection.HasSelection()) return; Color selectionColor = _appearance.SelectionColor; int startRow = _selection.BeginDrawPos.Row; int endRow = _selection.EndDrawPos.Row; int startCol = _selection.BeginDrawPos.Column; int endCol = _selection.EndDrawPos.Column; if (endRow < firstRowVisible || startRow > lastRowVisible) return; // Selection outside view int startColumn = Whitespace.ConvertToGraphicalCaretColumn(startCol, Line(startRow)); int endColumn = Whitespace.ConvertToGraphicalCaretColumn(endCol, Line(endRow)); int loopBegin = firstRowVisible > startRow ? firstRowVisible : startRow; int loopEnd = lastRowVisible < endRow ? lastRowVisible : endRow; if (loopBegin > loopEnd) { Debug.LogError("Invalid loop data " + loopBegin + " " + loopEnd); return; } for (int row = loopBegin; row<=loopEnd; row++) { var line = Line(row); string renderText = Whitespace.FormatBaseText(line.Text); Rect rowRect = GetLineRect(row); Rect textSpanRect; if (row == startRow && row == endRow) { textSpanRect = GetTextSpanRect(rowRect, renderText, startColumn, endColumn - startColumn); } else if (row == startRow) { int len = renderText.Length - startColumn; if (len > 0) { textSpanRect = GetTextSpanRect(rowRect, renderText, startColumn, len); } else { // We are at end of line so we get the span for the previous character and // use xMax from that character as startpos. textSpanRect = GetTextSpanRect(rowRect, renderText, Mathf.Max(0, startColumn - 1), 1); textSpanRect.x = textSpanRect.xMax; textSpanRect.width = 0; } } else if (row == endRow) { textSpanRect = GetTextSpanRect(rowRect, renderText, 0, endColumn); } else { textSpanRect = GetTextSpanRect(rowRect, renderText, 0, renderText.Length); } float extraWidth = (row != endRow) ? LineHeight*0.5f : 0f; // add extra width for all rows except the last to enhance selection rowRect.x = textSpanRect.x + CodeOffset; rowRect.width = textSpanRect.width + extraWidth; GUIUtils.DrawRect (rowRect, selectionColor); } } private static bool Repainting { get { return Event.current.type == EventType.repaint; } } void DrawLine(Rect lineRect, int row, int controlID) { var line = Line(row); DrawAdornments(line, lineRect); List<int> tabSizes; string baseTextFormatted = Whitespace.FormatBaseText(line.Text, out tabSizes); string renderText = Whitespace.FormatRichText(line.RichText, tabSizes); LineStyle.Draw(lineRect, MissingEngineAPI.GUIContent_Temp(renderText), controlID); if (ShowCursor && row == CaretRow) { int graphicalCaretPos = Whitespace.ConvertToGraphicalCaretColumn(CaretColumn, line, tabSizes); LineStyle.DrawCursor(lineRect, MissingEngineAPI.GUIContent_Temp(baseTextFormatted), controlID, graphicalCaretPos); } } private void DrawAdornments(ITextViewLine line, Rect lineRect) { _adornments.Draw(line, lineRect); } Rect ContentRect { get { return new Rect(0, 0, 1000, LineCount * LineHeight + 2 * TopMargin); } } void GetFirstAndLastRowVisible(int numRows, float topPixel, float heightInPixels, out int firstRowVisible, out int lastRowVisible) { firstRowVisible = (int)Mathf.Floor(topPixel / LineHeight); lastRowVisible = Mathf.Min(firstRowVisible + (int)Mathf.Ceil(heightInPixels / LineHeight), numRows - 1); } public Position GetCaretPositionUnderMouseCursor (Vector2 cursorPosition) { if (cursorPosition.x < ViewPort.x || cursorPosition.x > ViewPort.xMax) return new Position(-1,-1); var row = GetRow(cursorPosition.y); if (row >= LineCount) row = LineCount-1; var rect = GetLineRect(row); rect.x += CodeOffset; List<int> tabSizes; string renderText = Whitespace.FormatBaseText(Line(row).Text, out tabSizes); GUIContent guiContent = new GUIContent(renderText); cursorPosition.y = (rect.yMin + rect.yMax)*0.5f; // use center of row to fix issue with incorrect string index between rows var renderColumn = LineStyle.GetCursorStringIndex(rect, guiContent, cursorPosition); var column = Whitespace.ConvertToLogicalCaretColumn(renderColumn, Line(row), tabSizes); return new Position(row, column); } public void EnsureCursorIsVisible() { Vector2 scrollOffset = ScrollOffset; var topPixelOfRow = LineHeight * CaretRow; var scrollBottom = topPixelOfRow - ViewPort.height + 2 * LineHeight + 2 * TopMargin; scrollOffset.y = Mathf.Clamp(scrollOffset.y, scrollBottom, topPixelOfRow); var lineRect = GetLineRect(CaretRow); var cursorRect = GetTextSpanRect(lineRect, CurrentLine.Text, Mathf.Max(CaretColumn - 2, 0), 1); var scrollRight = Mathf.Max(cursorRect.x - ViewPort.width + 40f, 0f); scrollOffset.x = Mathf.Clamp(scrollOffset.x, scrollRight, 1000); const float distToScroll = 20f; if (cursorRect.x > ViewPort.width + scrollOffset.x) scrollOffset.x = Mathf.Min(cursorRect.x - ViewPort.width + distToScroll, 1000f); if (cursorRect.x < scrollOffset.x + distToScroll) scrollOffset.x = Mathf.Max(cursorRect.x - distToScroll, 0f); ScrollOffset = scrollOffset; } public Rect GetCurrentCharacterRect() { return GetSubstringRect(CaretRow, Math.Max(0, CaretColumn - 1), 1); } // Input data in document text values public Rect GetSubstringRect(int row, int column, int length) { if (column < 0 || row < 0 || length < 0) { Debug.LogError("GetSubstringRect: Invalid input: (column " + column + ", length " + length + ", row " + row + ")"); return new Rect(); } var line = Line(row); string renderText = Whitespace.FormatBaseText(line.Text); if (renderText.Length == 0) { length = 0; column = 0; } int startColumn = Whitespace.ConvertToGraphicalCaretColumn(column, line); Rect textRect = GetTextSpanRect(GetLineRect(row), renderText, startColumn, length); textRect.x += CodeOffset; return textRect; } // Input data in render text values Rect GetTextSpanRect(Rect lineRect, string renderText, int startPosition, int length) { if (startPosition < 0) startPosition = 0; if (startPosition >= renderText.Length - 1) startPosition = renderText.Length - 1; if (startPosition + length >= renderText.Length) length = Mathf.Max(1, renderText.Length - startPosition); var start = LineStyle.GetCursorPixelPosition(lineRect, MissingEngineAPI.GUIContent_Temp(renderText), startPosition); var end = LineStyle.GetCursorPixelPosition(lineRect, MissingEngineAPI.GUIContent_Temp(renderText), startPosition + length); return new Rect(start.x, start.y, end.x - start.x, LineHeight); } int GetRow(float yPos) { return Mathf.Max(0, Mathf.FloorToInt( (yPos - TopMargin) / LineHeight)); } Rect GetLineRect(int row) { return new Rect(0, row * LineHeight + TopMargin, 1000000, LineHeight); } private void DebugDrawRowRect(int row) { if (row >= 0 && Event.current.type == EventType.repaint) GUIUtils.DrawRect(GetLineRect(row), new Color(0.8f, 0.1f, 0.1f, 0.5f)); } int CaretColumn { get { return _document.Caret.Column; } } int CaretRow { get { return _document.Caret.Row; } } ITextViewLine CurrentLine { get { return _document.CurrentLine; } } private int LineCount { get { return _document.LineCount; } } private ITextViewLine Line(int row) { return _document.Line(row); } GUIStyle BackgroundStyle { get { return _appearance.Background; } } GUIStyle LineStyle { get { return _appearance.Text; } } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Threading; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using HetsApi.Authorization; using HetsApi.Helpers; using HetsApi.Model; using HetsData.Helpers; using HetsData.Entities; using HetsReport; using HetsData.Dtos; using HetsData.Repositories; using AutoMapper; namespace HetsApi.Controllers { /// <summary> /// Rental Agreement Controller /// </summary> [Route("/api/rentalAgreements")] [ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)] public class RentalAgreementController : ControllerBase { private readonly DbAppContext _context; private readonly IConfiguration _configuration; private readonly HttpContext _httpContext; private readonly IRentalAgreementRepository _rentalAgreementRepo; private readonly IMapper _mapper; private readonly ILogger<RentalAgreementController> _logger; public RentalAgreementController(DbAppContext context, IConfiguration configuration, IHttpContextAccessor httpContextAccessor, IRentalAgreementRepository rentalAgreementRepo, IMapper mapper, ILogger<RentalAgreementController> logger) { _context = context; _configuration = configuration; _httpContext = httpContextAccessor.HttpContext; _rentalAgreementRepo = rentalAgreementRepo; _mapper = mapper; _logger = logger; } /// <summary> /// Get rental agreement by id /// </summary> /// <param name="id">id of RentalAgreement to fetch</param> [HttpGet] [Route("{id}")] [RequiresPermission(HetPermission.Login)] public virtual ActionResult<RentalAgreementDto> RentalAgreementsIdGet([FromRoute] int id) { return new ObjectResult(new HetsResponse(_rentalAgreementRepo.GetRecord(id))); } /// <summary> /// Update rental agreement /// </summary> /// <param name="id">id of RentalAgreement to update</param> /// <param name="item"></param> [HttpPut] [Route("{id}")] [RequiresPermission(HetPermission.Login, HetPermission.WriteAccess)] public virtual ActionResult<RentalAgreementDto> RentalAgreementsIdPut([FromRoute] int id, [FromBody] RentalAgreementDto item) { if (item == null || id != item.RentalAgreementId) { // not found return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); } bool exists = _context.HetRentalAgreements.Any(a => a.RentalAgreementId == id); // not found if (!exists) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // get record HetRentalAgreement agreement = _context.HetRentalAgreements .Include(a => a.HetRentalAgreementRates) .First(a => a.RentalAgreementId == id); int? statusId = StatusHelper.GetStatusId(item.Status, "rentalAgreementStatus", _context); if (statusId == null) return new BadRequestObjectResult(new HetsResponse("HETS-23", ErrorViewModel.GetDescription("HETS-23", _configuration))); // get overtime records List<HetProvincialRateType> overtime = _context.HetProvincialRateTypes.AsNoTracking() .Where(x => x.Overtime) .ToList(); // get rate period type for the agreement int? rateTypeId = StatusHelper.GetRatePeriodId(item.RatePeriod, _context); if (rateTypeId == null) { throw new DataException("Rate Period Id cannot be null"); } string city = item.AgreementCity; if (!string.IsNullOrEmpty(city)) { city = city.Trim(); } // update the agreement record agreement.ConcurrencyControlNumber = item.ConcurrencyControlNumber; agreement.DatedOn = item.DatedOn; agreement.AgreementCity = city; agreement.EquipmentRate = item.EquipmentRate; agreement.EstimateHours = item.EstimateHours; agreement.EstimateStartWork = item.EstimateStartWork; agreement.Note = item.Note; agreement.Number = item.Number; agreement.RateComment = item.RateComment; agreement.RatePeriod = item.RatePeriod; agreement.RatePeriodTypeId = (int)rateTypeId; agreement.RentalAgreementStatusTypeId = (int)statusId; agreement.ProjectId = item.ProjectId; agreement.EquipmentId = item.EquipmentId; // update the rate period for all included rates and attachments foreach (HetRentalAgreementRate agreementRate in agreement.HetRentalAgreementRates.Where(x => !(x.Overtime ?? false) && x.IsIncludedInTotal)) { agreementRate.RatePeriod = agreement.RatePeriod; agreementRate.RatePeriodTypeId = agreement.RatePeriodTypeId; } // update the agreement overtime records (default overtime flag) if (item.OvertimeRates != null) { foreach (var rate in item.OvertimeRates) { bool found = false; foreach (HetRentalAgreementRate agreementRate in agreement.HetRentalAgreementRates) { if (agreementRate.RentalAgreementRateId == rate.RentalAgreementRateId) { agreementRate.ConcurrencyControlNumber = rate.ConcurrencyControlNumber; agreementRate.Comment = rate.Comment; agreementRate.Overtime = true; agreementRate.Active = rate.Active; agreementRate.IsIncludedInTotal = rate.IsIncludedInTotal; agreementRate.Rate = rate.Rate; found = true; break; } } if (!found) { // add the rate HetRentalAgreementRate newAgreementRate = new HetRentalAgreementRate { ConcurrencyControlNumber = rate.ConcurrencyControlNumber, Comment = rate.Comment, ComponentName = rate.ComponentName, Overtime = true, Active = true, IsIncludedInTotal = rate.IsIncludedInTotal, Rate = rate.Rate }; HetProvincialRateType overtimeRate = overtime.FirstOrDefault(x => x.Description == rate.Comment); if (overtimeRate != null) { newAgreementRate.ComponentName = overtimeRate.RateType; } if (agreement.HetRentalAgreementRates == null) { agreement.HetRentalAgreementRates = new List<HetRentalAgreementRate>(); } agreement.HetRentalAgreementRates.Add(newAgreementRate); } } } // save the changes _context.SaveChanges(); // retrieve updated rental agreement to return to ui return new ObjectResult(new HetsResponse(_rentalAgreementRepo.GetRecord(id))); } /// <summary> /// Create rental agreement /// </summary> /// <param name="item"></param> [HttpPost] [Route("")] [RequiresPermission(HetPermission.Login, HetPermission.WriteAccess)] public virtual ActionResult<RentalAgreementDto> RentalAgreementsPost([FromBody] RentalAgreementDto item) { // not found if (item == null) return new BadRequestObjectResult(new HetsResponse("HETS-04", ErrorViewModel.GetDescription("HETS-04", _configuration))); // set the rate period type id int? rateTypeId = StatusHelper.GetRatePeriodId(item.RatePeriod, _context); if (rateTypeId == null) { throw new DataException("Rate Period Id cannot be null"); } // get overtime records List<HetProvincialRateType> overtime = _context.HetProvincialRateTypes.AsNoTracking() .Where(x => x.Overtime) .ToList(); // get status for new agreement int? statusId = StatusHelper.GetStatusId(item.Status, "rentalAgreementStatus", _context); if (statusId == null) return new BadRequestObjectResult(new HetsResponse("HETS-23", ErrorViewModel.GetDescription("HETS-23", _configuration))); // get user info - agreement city CurrentUserDto user = UserAccountHelper.GetUser(_context, _httpContext); string agreementCity = user.AgreementCity; // create agreement HetRentalAgreement agreement = new HetRentalAgreement { Number = RentalAgreementHelper.GetRentalAgreementNumber(item.Equipment?.LocalAreaId, _context), DatedOn = item.DatedOn, AgreementCity = agreementCity, EquipmentRate = item.EquipmentRate, EstimateHours = item.EstimateHours, EstimateStartWork = item.EstimateStartWork, Note = item.Note, RateComment = item.RateComment, RatePeriodTypeId = (int)rateTypeId, RentalAgreementStatusTypeId = (int)statusId, EquipmentId = item.EquipmentId, ProjectId = item.ProjectId }; // agreement overtime records (default overtime flag) if (item.OvertimeRates != null) { foreach (var rate in item.OvertimeRates) { // add the rate HetRentalAgreementRate newAgreementRate = new HetRentalAgreementRate { ConcurrencyControlNumber = rate.ConcurrencyControlNumber, Comment = rate.Comment, ComponentName = rate.ComponentName, Overtime = true, Active = true, IsIncludedInTotal = rate.IsIncludedInTotal, Rate = rate.Rate }; HetProvincialRateType overtimeRate = overtime.FirstOrDefault(x => x.Description == rate.Comment); if (overtimeRate != null) { newAgreementRate.ComponentName = overtimeRate.RateType; } if (agreement.HetRentalAgreementRates == null) { agreement.HetRentalAgreementRates = new List<HetRentalAgreementRate>(); } agreement.HetRentalAgreementRates.Add(newAgreementRate); } } // save the changes _context.SaveChanges(); int id = agreement.RentalAgreementId; // retrieve updated rental agreement to return to ui return new ObjectResult(new HetsResponse(_rentalAgreementRepo.GetRecord(id))); } /// <summary> /// Release (terminate) a rental agreement /// </summary> /// <param name="id">id of RentalAgreement to release</param> [HttpPost] [Route("{id}/release")] [RequiresPermission(HetPermission.Login, HetPermission.WriteAccess)] public virtual ActionResult<RentalAgreementDto> RentalAgreementsIdReleasePost([FromRoute] int id) { bool exists = _context.HetRentalAgreements.Any(a => a.RentalAgreementId == id); // not found if (!exists) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // get record HetRentalAgreement agreement = _context.HetRentalAgreements.First(a => a.RentalAgreementId == id); // release (terminate) rental agreement int? statusIdComplete = StatusHelper.GetStatusId(HetRentalAgreement.StatusComplete, "rentalAgreementStatus", _context); if (statusIdComplete == null) return new BadRequestObjectResult(new HetsResponse("HETS-23", ErrorViewModel.GetDescription("HETS-23", _configuration))); agreement.RentalAgreementStatusTypeId = (int)statusIdComplete; agreement.Status = "Complete"; // save the changes _context.SaveChanges(); // retrieve updated rental agreement to return to ui return new ObjectResult(new HetsResponse(_rentalAgreementRepo.GetRecord(id))); } #region Rental Agreement Document /// <summary> /// Get an OpenXML version of a rental agreement /// </summary> /// <remarks>Returns an OpenXML version of the specified rental agreement</remarks> /// <param name="id">id of RentalAgreement to get</param> [HttpGet] [Route("{id}/doc")] [RequiresPermission(HetPermission.Login)] public virtual IActionResult RentalAgreementsIdDocGet([FromRoute] int id) { // get user info - agreement city CurrentUserDto user = UserAccountHelper.GetUser(_context, _httpContext); string agreementCity = user.AgreementCity; HetRentalAgreement rentalAgreement = _context.HetRentalAgreements.AsNoTracking() .Include(x => x.RatePeriodType) .Include(x => x.RentalAgreementStatusType) .Include(x => x.Equipment) .ThenInclude(y => y.Owner) .ThenInclude(z => z.PrimaryContact) .Include(x => x.Equipment) .ThenInclude(y => y.DistrictEquipmentType) .Include(x => x.Equipment) .ThenInclude(y => y.HetEquipmentAttachments) .Include(x => x.Equipment) .ThenInclude(y => y.LocalArea.ServiceArea.District.Region) .Include(x => x.Project) .ThenInclude(p => p.District.Region) .Include(x => x.HetRentalAgreementConditions) .Include(x => x.HetRentalAgreementRates) .ThenInclude(x => x.RatePeriodType) .FirstOrDefault(a => a.RentalAgreementId == id); if (rentalAgreement == null) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // construct the view model RentalAgreementDocViewModel reportModel = _rentalAgreementRepo .GetRentalAgreementReportModel(_mapper.Map<RentalAgreementDto>(rentalAgreement), agreementCity); string ownerName = rentalAgreement.Equipment?.Owner?.OrganizationName?.Trim().ToLower(); ownerName = CleanName(ownerName); ownerName = ownerName.Replace(" ", ""); ownerName = Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(ownerName); string fileName = rentalAgreement.Number + "_" + ownerName; // convert to open xml document string documentName = $"{fileName}.docx"; byte[] document = RentalAgreement.GetRentalAgreement(reportModel, documentName); // return document FileContentResult result = new FileContentResult(document, "application/vnd.openxmlformats-officedocument.wordprocessingml.document") { FileDownloadName = documentName }; Response.Headers.Add("Content-Disposition", "inline; filename=" + documentName); return result; } private static string CleanName(string name) { if (name == null) return ""; name = name.Replace("'", ""); name = name.Replace("<", ""); name = name.Replace(">", ""); name = name.Replace("\"", ""); name = name.Replace("|", ""); name = name.Replace("?", ""); name = name.Replace("*", ""); name = name.Replace(":", ""); name = name.Replace("/", ""); name = name.Replace("\\", ""); return name; } #endregion #region Rental Agreement Time Records /// <summary> /// Get time records associated with a rental agreement /// </summary> /// <remarks>Gets a Rental Agreements Time Records</remarks> /// <param name="id">id of Rental Agreement to fetch Time Records for</param> [HttpGet] [Route("{id}/timeRecords")] [RequiresPermission(HetPermission.Login)] public virtual ActionResult<TimeRecordLite> RentalAgreementsIdTimeRecordsGet([FromRoute] int id) { bool exists = _context.HetRentalAgreements.Any(a => a.RentalAgreementId == id); // not found if (!exists) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // get current district int? districtId = UserAccountHelper.GetUsersDistrictId(_context); // return time records return new ObjectResult(new HetsResponse(_rentalAgreementRepo.GetTimeRecords(id, districtId))); } /// <summary> /// Add or update a rental agreement time record /// </summary> /// <remarks>Adds Rental Agreement Time Records</remarks> /// <param name="id">id of Rental Agreement to add a time record for</param> /// <param name="item">Adds to Rental Agreement Time Records</param> [HttpPost] [Route("{id}/timeRecord")] [RequiresPermission(HetPermission.Login, HetPermission.WriteAccess)] public virtual ActionResult<TimeRecordLite> RentalAgreementsIdTimeRecordsPost([FromRoute] int id, [FromBody] TimeRecordDto item) { bool exists = _context.HetRentalAgreements.Any(a => a.RentalAgreementId == id); // not found if (!exists || item == null) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // set the time period type id int? timePeriodTypeId = StatusHelper.GetTimePeriodId(item.TimePeriod, _context); if (timePeriodTypeId == null) throw new DataException("Time Period Id cannot be null"); // get current district int? districtId = UserAccountHelper.GetUsersDistrictId(_context); // add or update time record if (item.TimeRecordId > 0) { // get record HetTimeRecord time = _context.HetTimeRecords.First(a => a.TimeRecordId == item.TimeRecordId); // not found if (time == null) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); time.ConcurrencyControlNumber = item.ConcurrencyControlNumber; time.EnteredDate = DateTime.UtcNow; time.Hours = item.Hours; time.TimePeriod = item.TimePeriod; time.TimePeriodTypeId = (int)timePeriodTypeId; time.WorkedDate = item.WorkedDate; } else // add time record { HetTimeRecord time = new HetTimeRecord { RentalAgreementId = id, EnteredDate = DateTime.UtcNow, Hours = item.Hours, TimePeriod = item.TimePeriod, TimePeriodTypeId = (int)timePeriodTypeId, WorkedDate = item.WorkedDate }; _context.HetTimeRecords.Add(time); } _context.SaveChanges(); // retrieve updated time records to return to ui return new ObjectResult(new HetsResponse(_rentalAgreementRepo.GetTimeRecords(id, districtId))); } /// <summary> /// Update or create an array of time records associated with a rental agreement /// </summary> /// <remarks>Adds Rental Agreement Time Records</remarks> /// <param name="id">id of Rental Agreement to add a time record for</param> /// <param name="items">Array of Rental Agreement Time Records</param> [HttpPost] [Route("{id}/timeRecords")] [RequiresPermission(HetPermission.Login, HetPermission.WriteAccess)] public virtual ActionResult<TimeRecordLite> RentalAgreementsIdTimeRecordsBulkPostAsync([FromRoute] int id, [FromBody] TimeRecordDto[] items) { bool exists = _context.HetRentalAgreements.Any(a => a.RentalAgreementId == id); // not found if (!exists || items == null) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // get current district int? districtId = UserAccountHelper.GetUsersDistrictId(_context); // process each time record foreach (var item in items) { // set the time period type id int? timePeriodTypeId = StatusHelper.GetTimePeriodId(item.TimePeriod, _context); if (timePeriodTypeId == null) throw new DataException("Time Period Id cannot be null"); // add or update time record if (item.TimeRecordId > 0) { // get record HetTimeRecord time = _context.HetTimeRecords.First(a => a.TimeRecordId == item.TimeRecordId); // not found if (time == null) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); time.ConcurrencyControlNumber = item.ConcurrencyControlNumber; time.EnteredDate = DateTime.UtcNow; time.Hours = item.Hours; time.TimePeriod = item.TimePeriod; time.TimePeriodTypeId = (int)timePeriodTypeId; time.WorkedDate = item.WorkedDate; } else // add time record { HetTimeRecord time = new HetTimeRecord { RentalAgreementId = id, EnteredDate = DateTime.UtcNow, Hours = item.Hours, TimePeriod = item.TimePeriod, TimePeriodTypeId = (int)timePeriodTypeId, WorkedDate = item.WorkedDate }; _context.HetTimeRecords.Add(time); } _context.SaveChanges(); } // retrieve updated time records to return to ui return new ObjectResult(new HetsResponse(_rentalAgreementRepo.GetTimeRecords(id, districtId))); } #endregion #region Rental Agreement Rate Records /// <summary> /// Get rate records associated with a rental agreement /// </summary> /// <remarks>Gets a Rental Agreements Rate Records</remarks> /// <param name="id">id of Rental Agreement to fetch Rate Records for</param> [HttpGet] [Route("{id}/rateRecords")] [RequiresPermission(HetPermission.Login)] public virtual ActionResult<List<RentalAgreementRateDto>> RentalAgreementsIdRentalAgreementRatesGet([FromRoute] int id) { bool exists = _context.HetRentalAgreements.Any(a => a.RentalAgreementId == id); // not found if (!exists) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // return rental agreement records return new ObjectResult(new HetsResponse(_rentalAgreementRepo.GetRentalRates(id))); } /// <summary> /// Add or update a rental agreement rate record /// </summary> /// <remarks>Adds Rental Agreement Rate Records</remarks> /// <param name="id">id of Rental Agreement to add a rate record for</param> /// <param name="item">Adds to Rental Agreement Rate Records</param> [HttpPost] [Route("{id}/rateRecord")] [RequiresPermission(HetPermission.Login, HetPermission.WriteAccess)] public virtual ActionResult<List<RentalAgreementRateDto>> RentalAgreementsIdRentalAgreementRatesPost([FromRoute] int id, [FromBody] RentalAgreementRateDto item) { bool exists = _context.HetRentalAgreements.Any(a => a.RentalAgreementId == id); // not found if (!exists || item == null) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // set the rate period type id int ratePeriodTypeId = StatusHelper.GetRatePeriodId(item.RatePeriod, _context) ?? throw new DataException("Rate Period Id cannot be null"); // add or update rate records if (item.RentalAgreementRateId > 0) { // get record HetRentalAgreementRate rate = _context.HetRentalAgreementRates.FirstOrDefault(a => a.RentalAgreementRateId == item.RentalAgreementRateId); // not found if (rate == null) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); rate.ConcurrencyControlNumber = item.ConcurrencyControlNumber; rate.Comment = item.Comment; rate.ComponentName = item.ComponentName; rate.Overtime = false; rate.Active = true; rate.IsIncludedInTotal = item.IsIncludedInTotal; rate.Rate = item.Rate; rate.RatePeriodTypeId = ratePeriodTypeId; rate.Set = item.Set; } else // add rate records { int agreementId = item.RentalAgreement.RentalAgreementId; HetRentalAgreementRate rate = new HetRentalAgreementRate { RentalAgreementId = agreementId, Comment = item.Comment, ComponentName = item.ComponentName, Overtime = false, Active = true, IsIncludedInTotal = item.IsIncludedInTotal, Rate = item.Rate, RatePeriodTypeId = ratePeriodTypeId, Set = item.Set }; _context.HetRentalAgreementRates.Add(rate); } _context.SaveChanges(); // retrieve updated rate records to return to ui return new ObjectResult(new HetsResponse(_rentalAgreementRepo.GetRentalRates(id))); } /// <summary> /// Update or create an array of rate records associated with a rental agreement /// </summary> /// <remarks>Adds Rental Agreement Rate Records</remarks> /// <param name="id">id of Rental Agreement to add rate records for</param> /// <param name="items">Array of Rental Agreement Rate Records</param> [HttpPost] [Route("{id}/rateRecords")] [RequiresPermission(HetPermission.Login, HetPermission.WriteAccess)] public virtual ActionResult<List<RentalAgreementRateDto>> RentalAgreementsIdRentalAgreementRatesBulkPost([FromRoute] int id, [FromBody] RentalAgreementRateDto[] items) { bool exists = _context.HetRentalAgreements.Any(a => a.RentalAgreementId == id); // not found if (!exists || items == null) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // process each rate records foreach (var item in items) { // set the rate period type id int ratePeriodTypeId = StatusHelper.GetRatePeriodId(item.RatePeriod, _context) ?? throw new DataException("Rate Period Id cannot be null"); // add or update rate records if (item.RentalAgreementRateId > 0) { // get record HetRentalAgreementRate rate = _context.HetRentalAgreementRates.FirstOrDefault(a => a.RentalAgreementRateId == item.RentalAgreementRateId); // not found if (rate == null) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); rate.ConcurrencyControlNumber = item.ConcurrencyControlNumber; rate.Comment = item.Comment; rate.ComponentName = item.ComponentName; rate.Overtime = false; rate.Active = true; rate.IsIncludedInTotal = item.IsIncludedInTotal; rate.Rate = item.Rate; rate.RatePeriodTypeId = ratePeriodTypeId; rate.Set = item.Set; } else // add rate records { int agreementId = item.RentalAgreement.RentalAgreementId; HetRentalAgreementRate rate = new HetRentalAgreementRate { RentalAgreementId = agreementId, Comment = item.Comment, ComponentName = item.ComponentName, Overtime = false, Active = true, IsIncludedInTotal = item.IsIncludedInTotal, Rate = item.Rate, RatePeriodTypeId = ratePeriodTypeId, Set = item.Set }; _context.HetRentalAgreementRates.Add(rate); } _context.SaveChanges(); } // retrieve updated rate records to return to ui return new ObjectResult(new HetsResponse(_rentalAgreementRepo.GetRentalRates(id))); } #endregion #region Rental Agreement Condition Records /// <summary> /// Get condition records associated with a rental agreement /// </summary> /// <remarks>Gets a Rental Agreement&#39;s Condition Records</remarks> /// <param name="id">id of Rental Agreement to fetch Condition Records for</param> [HttpGet] [Route("{id}/conditionRecords")] [RequiresPermission(HetPermission.Login)] public virtual ActionResult<List<RentalAgreementConditionDto>> RentalAgreementsIdRentalAgreementConditionsGet([FromRoute] int id) { bool exists = _context.HetRentalAgreements.Any(a => a.RentalAgreementId == id); // not found if (!exists) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // return rental agreement records return new ObjectResult(new HetsResponse(_rentalAgreementRepo.GetConditions(id))); } /// <summary> /// Add a rental agreement condition record /// </summary> /// <remarks>Adds Rental Agreement Condition Records</remarks> /// <param name="id">id of Rental Agreement to add a condition record for</param> /// <param name="item">Adds to Rental Agreement Condition Records</param> [HttpPost] [Route("{id}/conditionRecord")] [RequiresPermission(HetPermission.Login, HetPermission.WriteAccess)] public virtual ActionResult<List<RentalAgreementConditionDto>> RentalAgreementsIdRentalAgreementConditionsPost([FromRoute] int id, [FromBody] RentalAgreementConditionDto item) { bool exists = _context.HetRentalAgreements.Any(a => a.RentalAgreementId == id); // not found if (!exists || item == null) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // add or update condition records if (item.RentalAgreementConditionId > 0) { // get record HetRentalAgreementCondition condition = _context.HetRentalAgreementConditions .FirstOrDefault(a => a.RentalAgreementConditionId == item.RentalAgreementConditionId); // not found if (condition == null) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); condition.ConcurrencyControlNumber = item.ConcurrencyControlNumber; condition.Comment = item.Comment; condition.ConditionName = item.ConditionName; } else // add condition records { int agreementId = item.RentalAgreement.RentalAgreementId; HetRentalAgreementCondition condition = new HetRentalAgreementCondition { RentalAgreementId = agreementId, Comment = item.Comment, ConditionName = item.ConditionName }; _context.HetRentalAgreementConditions.Add(condition); } _context.SaveChanges(); // return rental agreement condition records return new ObjectResult(new HetsResponse(_rentalAgreementRepo.GetConditions(id))); } /// <summary> /// Update or create an array of condition records associated with a rental agreement /// </summary> /// <remarks>Adds Rental Agreement Condition Records</remarks> /// <param name="id">id of Rental Agreement to add condition records for</param> /// <param name="items">Array of Rental Agreement Condition Records</param> [HttpPost] [Route("{id}/conditionRecords")] [RequiresPermission(HetPermission.Login, HetPermission.WriteAccess)] public virtual ActionResult<List<RentalAgreementConditionDto>> RentalAgreementsIdRentalAgreementConditionsBulkPost([FromRoute] int id, [FromBody] RentalAgreementConditionDto[] items) { bool exists = _context.HetRentalAgreements.Any(a => a.RentalAgreementId == id); // not found if (!exists || items == null) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // process each rate records foreach (var item in items) { // add or update condition records if (item.RentalAgreementConditionId > 0) { // get record HetRentalAgreementCondition condition = _context.HetRentalAgreementConditions .FirstOrDefault(a => a.RentalAgreementConditionId == item.RentalAgreementConditionId); // not found if (condition == null) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); condition.ConcurrencyControlNumber = item.ConcurrencyControlNumber; condition.Comment = item.Comment; condition.ConditionName = item.ConditionName; } else // add condition records { int agreementId = item.RentalAgreement.RentalAgreementId; HetRentalAgreementCondition condition = new HetRentalAgreementCondition { RentalAgreementId = agreementId, Comment = item.Comment, ConditionName = item.ConditionName }; _context.HetRentalAgreementConditions.Add(condition); } _context.SaveChanges(); } // return rental agreement condition records return new ObjectResult(new HetsResponse(_rentalAgreementRepo.GetConditions(id))); } #endregion #region Blank Rental Agreement /// <summary> /// Create a new blank rental agreement (need a project id) /// </summary> [HttpPost] [Route("createBlankAgreement")] [RequiresPermission(HetPermission.Login, HetPermission.WriteAccess)] public virtual ActionResult<RentalAgreementDto> BlankRentalAgreementPost() { // get current users district int? districtId = UserAccountHelper.GetUsersDistrictId(_context); HetDistrict district = _context.HetDistricts.AsNoTracking() .FirstOrDefault(x => x.DistrictId.Equals(districtId)); if (district == null) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // get active status id int? statusId = StatusHelper.GetStatusId(HetRentalAgreement.StatusActive, "rentalAgreementStatus", _context); if (statusId == null) return new BadRequestObjectResult(new HetsResponse("HETS-23", ErrorViewModel.GetDescription("HETS-23", _configuration))); // HETS-825 - MAX number of Blank Rental Agreements and limit the functionality to ADMINS only // * Limit Blank rental agreements to a maximum of 3 List<HetRentalAgreement> agreements = _context.HetRentalAgreements.AsNoTracking() .Include(x => x.RentalAgreementStatusType) .Include(x => x.District) .Include(x => x.Project) .Include(x => x.Equipment) .Where(x => x.District.DistrictId == districtId && x.RentalRequestId == null && x.RentalRequestRotationListId == null && x.RentalAgreementStatusTypeId == statusId) .ToList(); string tempMax = _configuration.GetSection("Constants:Maximum-Blank-Agreements").Value; bool isNumeric = int.TryParse(tempMax, out int max); if (!isNumeric) max = 3; // default to 3 if (agreements.Count >= max) { return new BadRequestObjectResult(new HetsResponse("HETS-29", ErrorViewModel.GetDescription("HETS-29", _configuration))); } // set the rate period type id int? rateTypeId = StatusHelper.GetRatePeriodId(HetRatePeriodType.PeriodHourly, _context); if (rateTypeId == null) return new BadRequestObjectResult(new HetsResponse("HETS-24", ErrorViewModel.GetDescription("HETS-24", _configuration))); // create new agreement HetRentalAgreement agreement = new HetRentalAgreement { Number = RentalAgreementHelper.GetRentalAgreementNumber(district, _context), DistrictId = districtId, RentalAgreementStatusTypeId = (int)statusId, RatePeriodTypeId = (int)rateTypeId }; // add overtime rates List<HetProvincialRateType> overtime = _context.HetProvincialRateTypes.AsNoTracking() .Where(x => x.Overtime) .ToList(); // agreement overtime records (default overtime flag) foreach (HetProvincialRateType rate in overtime) { // add the rate HetRentalAgreementRate newAgreementRate = new HetRentalAgreementRate { Comment = rate.Description, ComponentName = rate.RateType, Overtime = true, Active = rate.Active, IsIncludedInTotal = rate.IsIncludedInTotal, Rate = rate.Rate }; if (agreement.HetRentalAgreementRates == null) { agreement.HetRentalAgreementRates = new List<HetRentalAgreementRate>(); } agreement.HetRentalAgreementRates.Add(newAgreementRate); } // save the changes _context.HetRentalAgreements.Add(agreement); _context.SaveChanges(); int id = agreement.RentalAgreementId; // retrieve updated rental agreement to return to ui return new ObjectResult(new HetsResponse(_rentalAgreementRepo.GetRecord(id))); } /// <summary> /// Get blank rental agreements (for the current district) /// </summary> [HttpGet] [Route("blankAgreements")] [RequiresPermission(HetPermission.Login)] public virtual ActionResult<List<RentalAgreementDto>> BlankRentalAgreementsGet() { // get the current district int? districtId = UserAccountHelper.GetUsersDistrictId(_context); // get active status id int? statusId = StatusHelper.GetStatusId(HetRentalAgreement.StatusActive, "rentalAgreementStatus", _context); if (statusId == null) return new BadRequestObjectResult(new HetsResponse("HETS-23", ErrorViewModel.GetDescription("HETS-23", _configuration))); // get all active "blank" agreements List<HetRentalAgreement> agreements = _context.HetRentalAgreements.AsNoTracking() .Include(x => x.RentalAgreementStatusType) .Include(x => x.District) .Include(x => x.Project) .Include(x => x.Equipment) .Where(x => x.District.DistrictId == districtId && x.RentalRequestId == null && x.RentalRequestRotationListId == null && x.RentalAgreementStatusTypeId == statusId) .ToList(); return new ObjectResult(new HetsResponse(_mapper.Map<List<RentalAgreementDto>>(agreements))); } /// <summary> /// Get blank rental agreements (for the current district) /// By Project Id and Equipment Id (ACTIVE AGREEMENTS ONLY) /// </summary> [HttpGet] [Route("blankAgreements/{projectId}/{equipmentId}")] [RequiresPermission(HetPermission.Login)] public virtual ActionResult<List<RentalAgreementDto>> BlankRentalAgreementLookupGet([FromRoute] int projectId, [FromRoute] int equipmentId) { // get the current district int? districtId = UserAccountHelper.GetUsersDistrictId(_context); // get agreement status int? statusId = StatusHelper.GetStatusId(HetRentalAgreement.StatusActive, "rentalAgreementStatus", _context); if (statusId == null) return new BadRequestObjectResult(new HetsResponse("HETS-23", ErrorViewModel.GetDescription("HETS-23", _configuration))); // get "blank" agreements List<HetRentalAgreement> agreements = _context.HetRentalAgreements.AsNoTracking() .Include(x => x.RentalAgreementStatusType) .Include(x => x.District) .Include(x => x.Equipment) .ThenInclude(y => y.Owner) .Include(x => x.Equipment) .ThenInclude(y => y.DistrictEquipmentType) .ThenInclude(d => d.EquipmentType) .Include(x => x.Project) .Where(x => x.District.DistrictId == districtId && x.RentalRequestId == null && x.RentalRequestRotationListId == null && x.ProjectId == projectId && x.EquipmentId == equipmentId && x.RentalAgreementStatusTypeId == statusId) .ToList(); return new ObjectResult(new HetsResponse(_mapper.Map<List<RentalAgreementDto>>(agreements))); } /// <summary> /// Delete a blank rental agreement /// </summary> /// <param name="id">id of Blank RentalAgreement to delete</param> [HttpPost] [Route("deleteBlankAgreement/{id}")] [RequiresPermission(HetPermission.Login, HetPermission.WriteAccess)] public virtual ActionResult<RentalAgreementDto> DeleteBlankRentalAgreementPost([FromRoute] int id) { // get current users district int? districtId = UserAccountHelper.GetUsersDistrictId(_context); HetDistrict district = _context.HetDistricts.AsNoTracking() .FirstOrDefault(x => x.DistrictId.Equals(districtId)); if (district == null) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); int? statusId = StatusHelper.GetStatusId(HetRentalAgreement.StatusActive, "rentalAgreementStatus", _context); if (statusId == null) return new BadRequestObjectResult(new HetsResponse("HETS-23", ErrorViewModel.GetDescription("HETS-23", _configuration))); // validate agreement id bool exists = _context.HetRentalAgreements.Any(a => a.RentalAgreementId == id); if (!exists) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // get agreement and validate HetRentalAgreement agreement = _context.HetRentalAgreements .Include(a => a.HetRentalAgreementRates) .Include(a => a.HetRentalAgreementConditions) .First(a => a.RentalAgreementId == id); if (agreement.RentalAgreementStatusTypeId != statusId) { return new BadRequestObjectResult(new HetsResponse("HETS-25", ErrorViewModel.GetDescription("HETS-25", _configuration))); } if (agreement.DistrictId != districtId) { return new BadRequestObjectResult(new HetsResponse("HETS-26", ErrorViewModel.GetDescription("HETS-26", _configuration))); } if (agreement.RentalRequestId != null) { return new BadRequestObjectResult(new HetsResponse("HETS-27", ErrorViewModel.GetDescription("HETS-27", _configuration))); } // delete rate foreach (HetRentalAgreementRate item in agreement.HetRentalAgreementRates) { _context.HetRentalAgreementRates.Remove(item); } // delete conditions foreach (HetRentalAgreementCondition item in agreement.HetRentalAgreementConditions) { _context.HetRentalAgreementConditions.Remove(item); } // delete the agreement _context.HetRentalAgreements.Remove(agreement); _context.SaveChanges(); // return rental agreement return new ObjectResult(new HetsResponse(_mapper.Map<RentalAgreementDto>(agreement))); } /// <summary> /// Clone a blank rental agreement /// </summary> /// <param name="id">id of Blank RentalAgreement to clone</param> /// <param name="agreement"></param> [HttpPost] [Route("updateCloneBlankAgreement/{id}")] [RequiresPermission(HetPermission.Login, HetPermission.WriteAccess)] public virtual ActionResult<RentalAgreementDto> CloneBlankRentalAgreementPost([FromRoute] int id, [FromBody] RentalAgreementDto agreement) { // check the ids if (id != agreement.RentalAgreementId) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // get current users district int? districtId = UserAccountHelper.GetUsersDistrictId(_context); HetDistrict district = _context.HetDistricts.AsNoTracking() .FirstOrDefault(x => x.DistrictId.Equals(districtId)); if (district == null) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // validate agreement id bool exists = _context.HetRentalAgreements.Any(a => a.RentalAgreementId == id); if (!exists) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // add overtime rates List<HetProvincialRateType> overtime = _context.HetProvincialRateTypes.AsNoTracking() .Where(x => x.Overtime) .ToList(); // get agreement and clone HetRentalAgreement oldAgreement = _context.HetRentalAgreements.AsNoTracking() .Include(a => a.HetRentalAgreementRates) .Include(a => a.HetRentalAgreementConditions) .First(a => a.RentalAgreementId == id); // create new blank agreement as a duplicate HetRentalAgreement newAgreement = new HetRentalAgreement { Number = RentalAgreementHelper.GetRentalAgreementNumber(district, _context), DistrictId = districtId, RentalAgreementStatusTypeId = oldAgreement.RentalAgreementStatusTypeId, RatePeriodTypeId = oldAgreement.RatePeriodTypeId, EstimateHours = oldAgreement.EstimateHours, EstimateStartWork = oldAgreement.EstimateStartWork, RateComment = oldAgreement.RateComment?.Trim(), EquipmentRate = oldAgreement.EquipmentRate, Note = oldAgreement.Note?.Trim(), DatedOn = oldAgreement.DatedOn, AgreementCity = oldAgreement.AgreementCity }; foreach (HetRentalAgreementCondition condition in oldAgreement.HetRentalAgreementConditions) { HetRentalAgreementCondition newCondition = new HetRentalAgreementCondition { RentalAgreementId = id, Comment = condition.Comment, ConditionName = condition.ConditionName }; newAgreement.HetRentalAgreementConditions.Add(newCondition); } if (oldAgreement.HetRentalAgreementRates != null) { foreach (HetRentalAgreementRate rate in oldAgreement.HetRentalAgreementRates) { HetRentalAgreementRate newRate = new HetRentalAgreementRate { RentalAgreementId = id, Comment = rate.Comment, Rate = rate.Rate, ComponentName = rate.ComponentName, Active = rate.Active, IsIncludedInTotal = rate.IsIncludedInTotal, Overtime = rate.Overtime }; newAgreement.HetRentalAgreementRates.Add(newRate); } } // update overtime rates (and add if they don't exist) foreach (HetProvincialRateType overtimeRate in overtime) { bool found = newAgreement.HetRentalAgreementRates.Any(x => x.ComponentName == overtimeRate.RateType); if (found) { HetRentalAgreementRate rate = newAgreement.HetRentalAgreementRates .First(x => x.ComponentName == overtimeRate.RateType); rate.Rate = overtimeRate.Rate; } else { HetRentalAgreementRate newRate = new HetRentalAgreementRate { RentalAgreementId = id, Comment = overtimeRate.Description, Rate = overtimeRate.Rate, ComponentName = overtimeRate.RateType, Active = overtimeRate.Active, IsIncludedInTotal = overtimeRate.IsIncludedInTotal, Overtime = overtimeRate.Overtime }; newAgreement.HetRentalAgreementRates.Add(newRate); } } // remove non-existent overtime rates List<string> remove = (from overtimeRate in newAgreement.HetRentalAgreementRates where overtimeRate.Overtime ?? false let found = overtime.Any(x => x.RateType == overtimeRate.ComponentName) where !found select overtimeRate.ComponentName).ToList(); if (remove.Count > 0) { foreach (string component in remove) { newAgreement.HetRentalAgreementRates.Remove( newAgreement.HetRentalAgreementRates.First(x => x.ComponentName == component)); } } // add new agreement and save changes _context.HetRentalAgreements.Add(newAgreement); _context.SaveChanges(); int newAgreementId = newAgreement.RentalAgreementId; // retrieve updated rental agreement to return to ui return new ObjectResult(new HetsResponse(_rentalAgreementRepo.GetRecord(newAgreementId))); } #endregion #region Search Rental Requests /// <summary> /// Find the latest agreement by project and equipment id /// </summary> /// <remarks>Used for the time entry page.</remarks> /// <param name="equipmentId">Equipment Id</param> /// <param name="projectId">Project Id</param> [HttpGet] [RequiresPermission(HetPermission.Login)] [Route("latest/{projectId}/{equipmentId}")] public virtual ActionResult<RentalAgreementDto> GetLatestRentalAgreement([FromRoute] int projectId, [FromRoute] int equipmentId) { // find the latest rental agreement HetRentalAgreement agreement = _context.HetRentalAgreements.AsNoTracking() .OrderByDescending(x => x.AppCreateTimestamp) .FirstOrDefault(x => x.EquipmentId == equipmentId && x.ProjectId == projectId); // if nothing exists - return an error message if (agreement == null) return new NotFoundObjectResult(new HetsResponse("HETS-35", ErrorViewModel.GetDescription("HETS-35", _configuration))); // get user's district int? districtId = UserAccountHelper.GetUsersDistrictId(_context); // get fiscal year HetDistrictStatus status = _context.HetDistrictStatuses.AsNoTracking() .First(x => x.DistrictId == districtId); int? fiscalYearStart = status.CurrentFiscalYear; if (fiscalYearStart == null) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); DateTime fiscalStart = new DateTime((int)fiscalYearStart, 4, 1); // validate that agreement is in the current fiscal year DateTime agreementDate = agreement.DatedOn ?? agreement.DbCreateTimestamp; if (agreementDate < fiscalStart) return new NotFoundObjectResult(new HetsResponse("HETS-36", ErrorViewModel.GetDescription("HETS-36", _configuration))); // return to the client return new ObjectResult(new HetsResponse(_mapper.Map<RentalAgreementDto>(agreement))); } #endregion #region Get all agreements by district for rental agreement summary filtering /// <summary> /// Get all agreements by district for rental agreement summary filtering /// </summary> [HttpGet] [Route("summaryLite")] [RequiresPermission(HetPermission.Login)] public virtual ActionResult<List<RentalAgreementSummaryLite>> RentalAgreementsGetSummaryLite() { // get user's district int? districtId = UserAccountHelper.GetUsersDistrictId(_context); IQueryable<HetRentalAgreement> agreements = _context.HetRentalAgreements.AsNoTracking() .Where(x => x.DistrictId.Equals(districtId) && !x.Number.StartsWith("BCBid")); // convert to "lite" model List<RentalAgreementSummaryLite> result = new List<RentalAgreementSummaryLite>(); foreach (HetRentalAgreement item in agreements) { result.Add(RentalAgreementHelper.ToSummaryLiteModel(item)); } // return to the client return new ObjectResult(new HetsResponse(result)); } #endregion #region AIT Report /// <summary> /// Get rental agreements for AIT Report /// </summary> /// <param name="projects">Projects (comma separated list of id numbers)</param> /// <param name="districtEquipmentTypes">District Equipment Types (comma separated list of equipment types)</param> /// <param name="equipment">Equipment (comma separated list of id numbers)</param> /// <param name="rentalAgreementNumber">Rental Agreement Number</param> /// <param name="startDate">Start date for Dated On</param> /// <param name="endDate">End date for Dated On</param> /// <returns>AIT report</returns> [HttpGet] [Route("aitReport")] [RequiresPermission(HetPermission.Login)] public virtual ActionResult<List<RentalRequestHires>> AitReportGet([FromQuery] string projects, [FromQuery] string districtEquipmentTypes, [FromQuery] string equipment, [FromQuery] string rentalAgreementNumber, [FromQuery] DateTime? startDate, [FromQuery] DateTime? endDate) { int?[] projectArray = ArrayHelper.ParseIntArray(projects); int?[] districtEquipmentTypeArray = ArrayHelper.ParseIntArray(districtEquipmentTypes); int?[] equipmentArray = ArrayHelper.ParseIntArray(equipment); IQueryable<HetRentalAgreement> agreements = _context.HetRentalAgreements.AsNoTracking() .Include(x => x.RentalAgreementStatusType) .Include(x => x.Equipment) .ThenInclude(y => y.DistrictEquipmentType) .ThenInclude(d => d.EquipmentType) .Include(x => x.Project); // limit to user's current district int? districtId = UserAccountHelper.GetUsersDistrictId(_context); agreements = agreements.Where(x => x.DistrictId == districtId); // HET-1137 do not show placeholder rental agreements created to imported from BCBid, (ones with agreement# BCBid-XX-XXXX) agreements = agreements.Where(x => !x.Number.StartsWith("BCBid")); if (!string.IsNullOrWhiteSpace(rentalAgreementNumber)) { agreements = agreements.Where(x => x.Number.ToUpper().Contains(rentalAgreementNumber.Trim().ToUpper())); } if (projectArray != null && projectArray.Length > 0) { agreements = agreements.Where(x => projectArray.Contains(x.ProjectId)); } if (districtEquipmentTypeArray != null && districtEquipmentTypeArray.Length > 0) { agreements = agreements.Where(x => districtEquipmentTypeArray.Contains(x.Equipment.DistrictEquipmentTypeId)); } if (equipmentArray != null && equipmentArray.Length > 0) { agreements = agreements.Where(x => equipmentArray.Contains(x.EquipmentId)); } if (startDate != null) { agreements = agreements.Where(x => x.DatedOn >= startDate); } if (endDate != null) { agreements = agreements.Where(x => x.DatedOn <= endDate); } var result = agreements .Select(x => AitReport.MapFromHetRentalAgreement(x)) .ToList(); return new ObjectResult(new HetsResponse(result)); } #endregion } }
/* * ****************************************************************************** * Copyright 2014-2016 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.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. * **************************************************************************** */ // This code is auto-generated, do not modify using Ds3.Models; using System; using System.Net; namespace Ds3.Calls { public class ModifyDataPolicySpectraS3Request : Ds3Request { public string DataPolicyId { get; private set; } private bool? _alwaysForcePutJobCreation; public bool? AlwaysForcePutJobCreation { get { return _alwaysForcePutJobCreation; } set { WithAlwaysForcePutJobCreation(value); } } private bool? _alwaysMinimizeSpanningAcrossMedia; public bool? AlwaysMinimizeSpanningAcrossMedia { get { return _alwaysMinimizeSpanningAcrossMedia; } set { WithAlwaysMinimizeSpanningAcrossMedia(value); } } private bool? _alwaysReplicateDeletes; public bool? AlwaysReplicateDeletes { get { return _alwaysReplicateDeletes; } set { WithAlwaysReplicateDeletes(value); } } private bool? _blobbingEnabled; public bool? BlobbingEnabled { get { return _blobbingEnabled; } set { WithBlobbingEnabled(value); } } private ChecksumType.Type? _checksumType; public ChecksumType.Type? ChecksumType { get { return _checksumType; } set { WithChecksumType(value); } } private long? _defaultBlobSize; public long? DefaultBlobSize { get { return _defaultBlobSize; } set { WithDefaultBlobSize(value); } } private Priority? _defaultGetJobPriority; public Priority? DefaultGetJobPriority { get { return _defaultGetJobPriority; } set { WithDefaultGetJobPriority(value); } } private Priority? _defaultPutJobPriority; public Priority? DefaultPutJobPriority { get { return _defaultPutJobPriority; } set { WithDefaultPutJobPriority(value); } } private Priority? _defaultVerifyJobPriority; public Priority? DefaultVerifyJobPriority { get { return _defaultVerifyJobPriority; } set { WithDefaultVerifyJobPriority(value); } } private bool? _endToEndCrcRequired; public bool? EndToEndCrcRequired { get { return _endToEndCrcRequired; } set { WithEndToEndCrcRequired(value); } } private string _name; public string Name { get { return _name; } set { WithName(value); } } private Priority? _rebuildPriority; public Priority? RebuildPriority { get { return _rebuildPriority; } set { WithRebuildPriority(value); } } private VersioningLevel? _versioning; public VersioningLevel? Versioning { get { return _versioning; } set { WithVersioning(value); } } public ModifyDataPolicySpectraS3Request WithAlwaysForcePutJobCreation(bool? alwaysForcePutJobCreation) { this._alwaysForcePutJobCreation = alwaysForcePutJobCreation; if (alwaysForcePutJobCreation != null) { this.QueryParams.Add("always_force_put_job_creation", alwaysForcePutJobCreation.ToString()); } else { this.QueryParams.Remove("always_force_put_job_creation"); } return this; } public ModifyDataPolicySpectraS3Request WithAlwaysMinimizeSpanningAcrossMedia(bool? alwaysMinimizeSpanningAcrossMedia) { this._alwaysMinimizeSpanningAcrossMedia = alwaysMinimizeSpanningAcrossMedia; if (alwaysMinimizeSpanningAcrossMedia != null) { this.QueryParams.Add("always_minimize_spanning_across_media", alwaysMinimizeSpanningAcrossMedia.ToString()); } else { this.QueryParams.Remove("always_minimize_spanning_across_media"); } return this; } public ModifyDataPolicySpectraS3Request WithAlwaysReplicateDeletes(bool? alwaysReplicateDeletes) { this._alwaysReplicateDeletes = alwaysReplicateDeletes; if (alwaysReplicateDeletes != null) { this.QueryParams.Add("always_replicate_deletes", alwaysReplicateDeletes.ToString()); } else { this.QueryParams.Remove("always_replicate_deletes"); } return this; } public ModifyDataPolicySpectraS3Request WithBlobbingEnabled(bool? blobbingEnabled) { this._blobbingEnabled = blobbingEnabled; if (blobbingEnabled != null) { this.QueryParams.Add("blobbing_enabled", blobbingEnabled.ToString()); } else { this.QueryParams.Remove("blobbing_enabled"); } return this; } public ModifyDataPolicySpectraS3Request WithChecksumType(ChecksumType.Type? checksumType) { this._checksumType = checksumType; if (checksumType != null) { this.QueryParams.Add("checksum_type", checksumType.ToString()); } else { this.QueryParams.Remove("checksum_type"); } return this; } public ModifyDataPolicySpectraS3Request WithDefaultBlobSize(long? defaultBlobSize) { this._defaultBlobSize = defaultBlobSize; if (defaultBlobSize != null) { this.QueryParams.Add("default_blob_size", defaultBlobSize.ToString()); } else { this.QueryParams.Remove("default_blob_size"); } return this; } public ModifyDataPolicySpectraS3Request WithDefaultGetJobPriority(Priority? defaultGetJobPriority) { this._defaultGetJobPriority = defaultGetJobPriority; if (defaultGetJobPriority != null) { this.QueryParams.Add("default_get_job_priority", defaultGetJobPriority.ToString()); } else { this.QueryParams.Remove("default_get_job_priority"); } return this; } public ModifyDataPolicySpectraS3Request WithDefaultPutJobPriority(Priority? defaultPutJobPriority) { this._defaultPutJobPriority = defaultPutJobPriority; if (defaultPutJobPriority != null) { this.QueryParams.Add("default_put_job_priority", defaultPutJobPriority.ToString()); } else { this.QueryParams.Remove("default_put_job_priority"); } return this; } public ModifyDataPolicySpectraS3Request WithDefaultVerifyJobPriority(Priority? defaultVerifyJobPriority) { this._defaultVerifyJobPriority = defaultVerifyJobPriority; if (defaultVerifyJobPriority != null) { this.QueryParams.Add("default_verify_job_priority", defaultVerifyJobPriority.ToString()); } else { this.QueryParams.Remove("default_verify_job_priority"); } return this; } public ModifyDataPolicySpectraS3Request WithEndToEndCrcRequired(bool? endToEndCrcRequired) { this._endToEndCrcRequired = endToEndCrcRequired; if (endToEndCrcRequired != null) { this.QueryParams.Add("end_to_end_crc_required", endToEndCrcRequired.ToString()); } else { this.QueryParams.Remove("end_to_end_crc_required"); } return this; } public ModifyDataPolicySpectraS3Request WithName(string name) { this._name = name; if (name != null) { this.QueryParams.Add("name", name); } else { this.QueryParams.Remove("name"); } return this; } public ModifyDataPolicySpectraS3Request WithRebuildPriority(Priority? rebuildPriority) { this._rebuildPriority = rebuildPriority; if (rebuildPriority != null) { this.QueryParams.Add("rebuild_priority", rebuildPriority.ToString()); } else { this.QueryParams.Remove("rebuild_priority"); } return this; } public ModifyDataPolicySpectraS3Request WithVersioning(VersioningLevel? versioning) { this._versioning = versioning; if (versioning != null) { this.QueryParams.Add("versioning", versioning.ToString()); } else { this.QueryParams.Remove("versioning"); } return this; } public ModifyDataPolicySpectraS3Request(Guid dataPolicyId) { this.DataPolicyId = dataPolicyId.ToString(); } public ModifyDataPolicySpectraS3Request(string dataPolicyId) { this.DataPolicyId = dataPolicyId; } internal override HttpVerb Verb { get { return HttpVerb.PUT; } } internal override string Path { get { return "/_rest_/data_policy/" + DataPolicyId.ToString(); } } } }
// 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 GetAndWithElementByte15() { var test = new VectorGetAndWithElement__GetAndWithElementByte15(); // 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__GetAndWithElementByte15 { private static readonly int LargestVectorSize = 16; private static readonly int ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); public bool Succeeded { get; set; } = true; public void RunBasicScenario(int imm = 15, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); Byte[] values = new Byte[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetByte(); } Vector128<Byte> value = Vector128.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], values[9], values[10], values[11], values[12], values[13], values[14], values[15]); bool succeeded = !expectedOutOfRangeException; try { Byte result = value.GetElement(imm); ValidateGetResult(result, values); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector128<Byte.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; Byte insertedValue = TestLibrary.Generator.GetByte(); try { Vector128<Byte> result2 = value.WithElement(imm, insertedValue); ValidateWithResult(result2, values, insertedValue); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector128<Byte.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunReflectionScenario(int imm = 15, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); Byte[] values = new Byte[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetByte(); } Vector128<Byte> value = Vector128.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], values[9], values[10], values[11], values[12], values[13], values[14], values[15]); bool succeeded = !expectedOutOfRangeException; try { object result = typeof(Vector128) .GetMethod(nameof(Vector128.GetElement)) .MakeGenericMethod(typeof(Byte)) .Invoke(null, new object[] { value, imm }); ValidateGetResult((Byte)(result), values); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector128<Byte.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; Byte insertedValue = TestLibrary.Generator.GetByte(); try { object result2 = typeof(Vector128) .GetMethod(nameof(Vector128.WithElement)) .MakeGenericMethod(typeof(Byte)) .Invoke(null, new object[] { value, imm, insertedValue }); ValidateWithResult((Vector128<Byte>)(result2), values, insertedValue); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector128<Byte.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunArgumentOutOfRangeScenario() { RunBasicScenario(15 - ElementCount, expectedOutOfRangeException: true); RunBasicScenario(15 + ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(15 - ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(15 + ElementCount, expectedOutOfRangeException: true); } private void ValidateGetResult(Byte result, Byte[] values, [CallerMemberName] string method = "") { if (result != values[15]) { Succeeded = false; TestLibrary.TestFramework.LogInformation($"Vector128<Byte.GetElement(15): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); } } private void ValidateWithResult(Vector128<Byte> result, Byte[] values, Byte insertedValue, [CallerMemberName] string method = "") { Byte[] resultElements = new Byte[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref resultElements[0]), result); ValidateWithResult(resultElements, values, insertedValue, method); } private void ValidateWithResult(Byte[] result, Byte[] values, Byte insertedValue, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < ElementCount; i++) { if ((i != 15) && (result[i] != values[i])) { succeeded = false; break; } } if (result[15] != insertedValue) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector128<Byte.WithElement(15): {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 (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * [email protected]. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ #if FEATURE_COM #if FEATURE_CORE_DLR using System.Linq.Expressions; #else using Microsoft.Scripting.Ast; #endif using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; namespace Microsoft.Scripting.ComInterop { internal static class TypeUtils { private const BindingFlags AnyStatic = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; internal const MethodAttributes PublicStatic = MethodAttributes.Public | MethodAttributes.Static; //CONFORMING internal static Type GetNonNullableType(Type type) { if (IsNullableType(type)) { return type.GetGenericArguments()[0]; } return type; } //CONFORMING internal static bool IsNullableType(this Type type) { return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); } //CONFORMING internal static bool AreReferenceAssignable(Type dest, Type src) { // WARNING: This actually implements "Is this identity assignable and/or reference assignable?" if (dest == src) { return true; } if (!dest.IsValueType && !src.IsValueType && AreAssignable(dest, src)) { return true; } return false; } //CONFORMING internal static bool AreAssignable(Type dest, Type src) { if (dest == src) { return true; } if (dest.IsAssignableFrom(src)) { return true; } if (dest.IsArray && src.IsArray && dest.GetArrayRank() == src.GetArrayRank() && AreReferenceAssignable(dest.GetElementType(), src.GetElementType())) { return true; } if (src.IsArray && dest.IsGenericType && (dest.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IEnumerable<>) || dest.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IList<>) || dest.GetGenericTypeDefinition() == typeof(System.Collections.Generic.ICollection<>)) && dest.GetGenericArguments()[0] == src.GetElementType()) { return true; } return false; } //CONFORMING internal static bool IsImplicitlyConvertible(Type source, Type destination) { return IsIdentityConversion(source, destination) || IsImplicitNumericConversion(source, destination) || IsImplicitReferenceConversion(source, destination) || IsImplicitBoxingConversion(source, destination); } internal static bool IsImplicitlyConvertible(Type source, Type destination, bool considerUserDefined) { return IsImplicitlyConvertible(source, destination) || (considerUserDefined && GetUserDefinedCoercionMethod(source, destination, true) != null); } //CONFORMING internal static MethodInfo GetUserDefinedCoercionMethod(Type convertFrom, Type convertToType, bool implicitOnly) { // check for implicit coercions first Type nnExprType = TypeUtils.GetNonNullableType(convertFrom); Type nnConvType = TypeUtils.GetNonNullableType(convertToType); // try exact match on types MethodInfo[] eMethods = nnExprType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); MethodInfo method = FindConversionOperator(eMethods, convertFrom, convertToType, implicitOnly); if (method != null) { return method; } MethodInfo[] cMethods = nnConvType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); method = FindConversionOperator(cMethods, convertFrom, convertToType, implicitOnly); if (method != null) { return method; } // try lifted conversion if (nnExprType != convertFrom || nnConvType != convertToType) { method = FindConversionOperator(eMethods, nnExprType, nnConvType, implicitOnly); if (method == null) { method = FindConversionOperator(cMethods, nnExprType, nnConvType, implicitOnly); } if (method != null) { return method; } } return null; } //CONFORMING internal static MethodInfo FindConversionOperator(MethodInfo[] methods, Type typeFrom, Type typeTo, bool implicitOnly) { foreach (MethodInfo mi in methods) { if (mi.Name != "op_Implicit" && (implicitOnly || mi.Name != "op_Explicit")) continue; if (mi.ReturnType != typeTo) continue; ParameterInfo[] pis = mi.GetParameters(); if (pis[0].ParameterType != typeFrom) continue; return mi; } return null; } //CONFORMING private static bool IsIdentityConversion(Type source, Type destination) { return source == destination; } //CONFORMING [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] private static bool IsImplicitNumericConversion(Type source, Type destination) { TypeCode tcSource = Type.GetTypeCode(source); TypeCode tcDest = Type.GetTypeCode(destination); switch (tcSource) { case TypeCode.SByte: switch (tcDest) { case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } return false; case TypeCode.Byte: switch (tcDest) { case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } return false; case TypeCode.Int16: switch (tcDest) { case TypeCode.Int32: case TypeCode.Int64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } return false; case TypeCode.UInt16: switch (tcDest) { case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } return false; case TypeCode.Int32: switch (tcDest) { case TypeCode.Int64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } return false; case TypeCode.UInt32: switch (tcDest) { case TypeCode.UInt32: case TypeCode.UInt64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } return false; case TypeCode.Int64: case TypeCode.UInt64: switch (tcDest) { case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } return false; case TypeCode.Char: switch (tcDest) { case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } return false; case TypeCode.Single: return (tcDest == TypeCode.Double); } return false; } //CONFORMING private static bool IsImplicitReferenceConversion(Type source, Type destination) { return AreAssignable(destination, source); } //CONFORMING private static bool IsImplicitBoxingConversion(Type source, Type destination) { if (source.IsValueType && (destination == typeof(object) || destination == typeof(System.ValueType))) return true; if (source.IsEnum && destination == typeof(System.Enum)) return true; return false; } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void CarrylessMultiplyInt6416() { var test = new PclmulqdqOpTest__CarrylessMultiplyInt6416(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Pclmulqdq.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Pclmulqdq.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Pclmulqdq.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class PclmulqdqOpTest__CarrylessMultiplyInt6416 { private struct TestStruct { public Vector128<Int64> _fld1; public Vector128<Int64> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); return testStruct; } public void RunStructFldScenario(PclmulqdqOpTest__CarrylessMultiplyInt6416 testClass) { var result = Pclmulqdq.CarrylessMultiply(_fld1, _fld2, 16); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static Int64[] _data1 = new Int64[2] {-2, -20}; private static Int64[] _data2 = new Int64[2] {25, 65535}; private static Int64[] _expectedRet = new Int64[2] {43690, 21845}; private static Vector128<Int64> _clsVar1; private static Vector128<Int64> _clsVar2; private Vector128<Int64> _fld1; private Vector128<Int64> _fld2; private SimpleBinaryOpTest__DataTable<Int64, Int64, Int64> _dataTable; static PclmulqdqOpTest__CarrylessMultiplyInt6416() { Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); } public PclmulqdqOpTest__CarrylessMultiplyInt6416() { Succeeded = true; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); _dataTable = new SimpleBinaryOpTest__DataTable<Int64, Int64, Int64>(_data1, _data2, new Int64[RetElementCount], LargestVectorSize); } public bool IsSupported => Pclmulqdq.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Pclmulqdq.CarrylessMultiply( Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr), 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Pclmulqdq.CarrylessMultiply( Pclmulqdq.LoadVector128((Int64*)(_dataTable.inArray1Ptr)), Pclmulqdq.LoadVector128((Int64*)(_dataTable.inArray2Ptr)), 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Pclmulqdq.CarrylessMultiply( Pclmulqdq.LoadAlignedVector128((Int64*)(_dataTable.inArray1Ptr)), Pclmulqdq.LoadAlignedVector128((Int64*)(_dataTable.inArray2Ptr)), 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Pclmulqdq).GetMethod(nameof(Pclmulqdq.CarrylessMultiply), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr), (byte)16 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Pclmulqdq).GetMethod(nameof(Pclmulqdq.CarrylessMultiply), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>), typeof(byte) }) .Invoke(null, new object[] { Pclmulqdq.LoadVector128((Int64*)(_dataTable.inArray1Ptr)), Pclmulqdq.LoadVector128((Int64*)(_dataTable.inArray2Ptr)), (byte)16 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Pclmulqdq).GetMethod(nameof(Pclmulqdq.CarrylessMultiply), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>), typeof(byte) }) .Invoke(null, new object[] { Pclmulqdq.LoadAlignedVector128((Int64*)(_dataTable.inArray1Ptr)), Pclmulqdq.LoadAlignedVector128((Int64*)(_dataTable.inArray2Ptr)), (byte)16 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Pclmulqdq.CarrylessMultiply( _clsVar1, _clsVar2, 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr); var result = Pclmulqdq.CarrylessMultiply(left, right, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = Pclmulqdq.LoadVector128((Int64*)(_dataTable.inArray1Ptr)); var right = Pclmulqdq.LoadVector128((Int64*)(_dataTable.inArray2Ptr)); var result = Pclmulqdq.CarrylessMultiply(left, right, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = Pclmulqdq.LoadAlignedVector128((Int64*)(_dataTable.inArray1Ptr)); var right = Pclmulqdq.LoadAlignedVector128((Int64*)(_dataTable.inArray2Ptr)); var result = Pclmulqdq.CarrylessMultiply(left, right, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new PclmulqdqOpTest__CarrylessMultiplyInt6416(); var result = Pclmulqdq.CarrylessMultiply(test._fld1, test._fld2, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Pclmulqdq.CarrylessMultiply(_fld1, _fld2, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Pclmulqdq.CarrylessMultiply(test._fld1, test._fld2, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(void* result, [CallerMemberName] string method = "") { Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(outArray, method); } private void ValidateResult(Int64[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < result.Length; i++) { if (result[i] != _expectedRet[i] ) { succeeded = false; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Pclmulqdq)}.{nameof(Pclmulqdq.CarrylessMultiply)}<Int64>(Vector128<Int64>, 16): {method} failed:"); TestLibrary.TestFramework.LogInformation($" expectedRet: ({string.Join(", ", _expectedRet)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using bv.common.Core; using bv.common.db; using bv.common.db.Core; using DevExpress.Data.Filtering; using DevExpress.Data.PivotGrid; using DevExpress.Utils; using DevExpress.XtraPivotGrid; using EIDSS; using eidss.avr.db.DBService.DataSource; using EIDSS.Enums; using eidss.model.AVR.Db; using eidss.model.Avr.Pivot; using eidss.model.Avr.View; using eidss.model.Enums; using eidss.model.Resources; using ReflectionHelper = eidss.model.Helpers.ReflectionHelper; namespace eidss.avr.db.Common { public class AvrPivotGridHelper { private const string IdColumnName = "Id"; private const string AliasColumnName = "Alias"; private const string CaptionColumnName = "Caption"; private const string OrderColumnName = "Order"; private static Dictionary<string, Type> m_FieldDataTypes; public static string GetCorrectFilter(CriteriaOperator criteria) { if (Utils.IsEmpty(criteria)) { return null; } string filter = criteria.LegacyToString(); if (!Utils.IsEmpty(filter)) { int ind = filter.IndexOf(" ?", StringComparison.InvariantCulture); while (ind >= 0) { string substrFilter = filter.Substring(0, ind); if (substrFilter.EndsWith("] =") || substrFilter.EndsWith("] <=") || substrFilter.EndsWith("] >=") || substrFilter.EndsWith("] <>") || substrFilter.EndsWith("] >") || substrFilter.EndsWith("] <")) { int bracketInd = substrFilter.LastIndexOf("[", StringComparison.InvariantCulture); if (bracketInd >= 0) { substrFilter = substrFilter.Substring(0, bracketInd) + "1 = 1"; } } if (filter.Length > ind + 2) { filter = substrFilter + filter.Substring(ind + 2); ind = filter.IndexOf(" ?", substrFilter.Length, StringComparison.InvariantCulture); } else { filter = substrFilter; ind = -1; } } } return filter; } #region Create search fields public static List<T> CreateFields<T>(DataTable data) where T : IAvrPivotGridField, new() { var list = new List<T>(); foreach (DataColumn column in data.Columns) { bool isCopy = column.ExtendedProperties.ContainsKey(QueryHelper.CopySuffix); var field = new T { Name = "field" + column.ColumnName, FieldName = column.ColumnName, Caption = column.Caption, IsHiddenFilterField = isCopy, Visible = isCopy, }; field.SearchFieldDataType = GetSearchFieldType(field.GetOriginalName()); field.UpdateImageIndex(); if (field.SearchFieldDataType == typeof (DateTime)) { field.CellFormat.FormatType = FormatType.DateTime; } field.UseNativeFormat = DefaultBoolean.False; list.Add(field); } return list; } internal static Dictionary<string, Type> GetSearchFieldDataTypes(DataTable lookupTable) { var result = new Dictionary<string, Type>(); foreach (KeyValuePair<string, SearchFieldType> pair in QueryLookupHelper.GetFieldTypes(lookupTable)) { Type value; switch (pair.Value) { case SearchFieldType.Bit: value = typeof (bool); break; case SearchFieldType.Date: value = typeof (DateTime); break; case SearchFieldType.Float: value = typeof (float); break; case SearchFieldType.ID: case SearchFieldType.Integer: value = typeof (long); break; default: value = typeof (string); break; } result.Add(pair.Key, value); result.Add(pair.Key + QueryHelper.CopySuffix, value); } return result; } internal static Type GetSearchFieldType(string fieldName) { if ((m_FieldDataTypes == null) || (!m_FieldDataTypes.ContainsKey(fieldName))) { DataTable lookupTable = QueryLookupHelper.GetQueryLookupTable(); m_FieldDataTypes = GetSearchFieldDataTypes(lookupTable); } if (!m_FieldDataTypes.ContainsKey(fieldName)) { throw new AvrException("Cannot load type for field " + fieldName); } return m_FieldDataTypes[fieldName]; } #endregion #region Load Search Fields from DB public static IEnumerable<LayoutDetailDataSet.LayoutSearchFieldRow> GetSortedLayoutSearchFieldRows (LayoutDetailDataSet.LayoutSearchFieldDataTable searchFieldDataTable) { List<LayoutDetailDataSet.LayoutSearchFieldRow> rowList = searchFieldDataTable.Rows.Cast<LayoutDetailDataSet.LayoutSearchFieldRow>().ToList(); rowList.Sort((firstRow, secondRow) => { int firstIndex = 10000 * firstRow.intPivotGridAreaType + firstRow.intFieldPivotGridAreaIndex; int secondIndex = 10000 * secondRow.intPivotGridAreaType + secondRow.intFieldPivotGridAreaIndex; return firstIndex.CompareTo(secondIndex); }); return rowList; } public static void LoadSearchFieldsVersionSixFromDB (IList<IAvrPivotGridField> avrFields, LayoutDetailDataSet.LayoutSearchFieldDataTable searchFieldDataTable, long defaultGroupIntervalId) { IEnumerable<LayoutDetailDataSet.LayoutSearchFieldRow> rowList = GetSortedLayoutSearchFieldRows(searchFieldDataTable); foreach (LayoutDetailDataSet.LayoutSearchFieldRow row in rowList) { IAvrPivotGridField field = avrFields.FirstOrDefault(f => f.GetFieldId() == row.idfLayoutSearchField); if (field != null) { field.DefaultGroupInterval = GroupIntervalHelper.GetGroupInterval(defaultGroupIntervalId); field.LoadSearchFieldFromRow(row); } } } public static void LoadExstraSearchFieldsProperties (IList<IAvrPivotGridField> avrFields, LayoutDetailDataSet.LayoutSearchFieldDataTable searchFieldDataTable) { IEnumerable<LayoutDetailDataSet.LayoutSearchFieldRow> rowList = GetSortedLayoutSearchFieldRows(searchFieldDataTable); foreach (LayoutDetailDataSet.LayoutSearchFieldRow row in rowList) { IAvrPivotGridField field = avrFields.FirstOrDefault(f => f.GetFieldId() == row.idfLayoutSearchField); if (field != null) { field.LoadSearchFieldExstraFromRow(row); field.AllPivotFields = avrFields.ToList(); PivotSummaryType summaryType = field.CustomSummaryType == CustomSummaryType.Count ? PivotSummaryType.Count : PivotSummaryType.Custom; field.SummaryType = summaryType; } } } public static void SwapOriginalAndCopiedFieldsIfReversed(IEnumerable<IAvrPivotGridField> avrFields) { Dictionary<IAvrPivotGridField, IAvrPivotGridField> fieldsAndCopies = GetFieldsAndCopiesConsideringArea(avrFields); // in case original and copied fields have been swapped in the migration process from v4 foreach (KeyValuePair<IAvrPivotGridField, IAvrPivotGridField> pair in fieldsAndCopies) { IAvrPivotGridField origin = pair.Key; IAvrPivotGridField copy = pair.Value; PivotArea newArea = origin.Area; bool newVisible = origin.Visible; int newIndex = origin.AreaIndex; bool isSwap = false; if (origin.Area == PivotArea.FilterArea) { if (copy.Area == PivotArea.FilterArea) { isSwap = (copy.AllowedAreas != (copy.AllowedAreas & PivotGridAllowedAreas.FilterArea)); newVisible = false; } else { isSwap = true; newArea = copy.Area; newVisible = copy.Visible; newIndex = copy.AreaIndex; } } IAvrPivotGridField originToProcess = isSwap ? copy : origin; IAvrPivotGridField copyToProcess = isSwap ? origin : copy; originToProcess.IsHiddenFilterField = false; originToProcess.Area = (newArea == PivotArea.FilterArea) ? PivotArea.RowArea : newArea; originToProcess.AreaIndex = newIndex; originToProcess.Visible = newVisible; copyToProcess.Visible = true; copyToProcess.IsHiddenFilterField = true; copyToProcess.GroupInterval = PivotGroupInterval.Default; } } public static Dictionary<IAvrPivotGridField, IAvrPivotGridField> GetFieldsAndCopiesConsideringArea (IEnumerable<IAvrPivotGridField> avrFields) { var fieldsAndCopies = new Dictionary<IAvrPivotGridField, IAvrPivotGridField>(); IEnumerable<IGrouping<string, IAvrPivotGridField>> grouppedField = avrFields.GroupBy(f => f.GetOriginalName()); foreach (IGrouping<string, IAvrPivotGridField> fields in grouppedField) { IAvrPivotGridField fieldCopy; fieldCopy = fields.FirstOrDefault(f => f.Area == PivotArea.FilterArea && f.AllowedAreas == (f.AllowedAreas & PivotGridAllowedAreas.FilterArea)) ?? (fields.FirstOrDefault(f => f.Area == PivotArea.FilterArea) ?? (fields.FirstOrDefault(f => !f.Visible) ?? fields.FirstOrDefault(f => f.IsHiddenFilterField))); if (fieldCopy != null) { foreach (IAvrPivotGridField field in fields) { if (field != fieldCopy) { fieldsAndCopies.Add(field, fieldCopy); } } } } return fieldsAndCopies; } #endregion #region Save Search Fields to DB public static void PrepareLayoutSearchFieldsBeforePost (IList<IAvrPivotGridField> fields, LayoutDetailDataSet.LayoutSearchFieldDataTable searchFieldTable, long idflQuery, long idflLayout) { RemoveNonExistingLayoutSearchFieldRows(fields, searchFieldTable); // just in case when no LayoutSearchFieldRow exists for some field AddMissingLayoutSearchFieldRows(fields, searchFieldTable, idflQuery, idflLayout); UpdateLayoutSearchFieldRows(fields, searchFieldTable); } private static void RemoveNonExistingLayoutSearchFieldRows (IEnumerable<IAvrPivotGridField> fields, LayoutDetailDataSet.LayoutSearchFieldDataTable searchFieldTable) { List<string> originalFieldNames = fields.Select(field => field.GetOriginalName()).ToList(); IEnumerable<LayoutDetailDataSet.LayoutSearchFieldRow> allRows = searchFieldTable.Rows.Cast<LayoutDetailDataSet.LayoutSearchFieldRow>(); List<LayoutDetailDataSet.LayoutSearchFieldRow> rowsToRemove = allRows.Where(r => !originalFieldNames.Contains(r.strSearchFieldAlias)).ToList(); foreach (LayoutDetailDataSet.LayoutSearchFieldRow row in rowsToRemove) { searchFieldTable.RemoveLayoutSearchFieldRow(row); } } private static void AddMissingLayoutSearchFieldRows (IList<IAvrPivotGridField> fields, LayoutDetailDataSet.LayoutSearchFieldDataTable searchFieldTable, long idflQuery, long idflLayout) { int length = 0; foreach (IAvrPivotGridField field in fields) { string filter = String.Format("{0}='{1}'", searchFieldTable.strSearchFieldAliasColumn.ColumnName, field.GetOriginalName()); if (searchFieldTable.Select(filter).Length == 0) { length++; } } List<long> ids = BaseDbService.NewListIntID(length); int count = 0; foreach (IAvrPivotGridField field in fields) { string filter = String.Format("{0}='{1}'", searchFieldTable.strSearchFieldAliasColumn.ColumnName, field.GetOriginalName()); if (searchFieldTable.Select(filter).Length == 0) { AddNewLayoutSearchFieldRow(searchFieldTable, idflQuery, idflLayout, field.GetOriginalName(), (long) field.CustomSummaryType, ids[count]); count++; } } } private static void UpdateLayoutSearchFieldRows (IEnumerable<IAvrPivotGridField> fields, LayoutDetailDataSet.LayoutSearchFieldDataTable searchFieldTable) { searchFieldTable.BeginLoadData(); foreach (IAvrPivotGridField field in fields) { field.SaveSearchFieldToTable(searchFieldTable); } searchFieldTable.EndLoadData(); } #endregion #region Get Search Fields by condition public static List<IAvrPivotGridField> GetFieldCollectionFromArea (IEnumerable<IAvrPivotGridField> allFields, PivotArea pivotArea) { var dataField = new SortedDictionary<int, IAvrPivotGridField>(); foreach (IAvrPivotGridField field in allFields) { if ((field.Visible) && (field.Area == pivotArea)) { dataField.Add(field.AreaIndex, field); } } var fields = new List<IAvrPivotGridField>(dataField.Values); fields.Sort((f1, f2) => f1.AreaIndex.CompareTo(f2.AreaIndex)); return fields; } public static IAvrPivotGridField GetGenderField(IEnumerable<IAvrPivotGridField> fields) { return GetCulumnField(fields, @"sflHC_PatientSex"); } public static IAvrPivotGridField GetAgeGroupField(IEnumerable<IAvrPivotGridField> fields) { return GetCulumnField(fields, @"sflHCAG_AgeGroup"); } private static IAvrPivotGridField GetCulumnField(IEnumerable<IAvrPivotGridField> fields, string fieldAlias) { IAvrPivotGridField genderField = fields.ToList().SingleOrDefault( field => field.Visible && field.Area == PivotArea.ColumnArea && field.FieldName.Contains(fieldAlias)); return genderField; } #endregion #region Process Search Field Summary public static bool TryGetDefaultSummaryTypeFor(string name, out CustomSummaryType result) { DataView searchFields = GetSearchFieldRowByName(name); if (searchFields.Count > 0) { object idAggrFunction = searchFields[0]["idfsDefaultAggregateFunction"]; if (idAggrFunction is long) { result = (CustomSummaryType) idAggrFunction; return true; } } result = CustomSummaryType.Undefined; return false; } public static Dictionary<string, CustomSummaryType> GetNameSummaryTypeDictionary (LayoutDetailDataSet.LayoutSearchFieldDataTable layoutSearchFieldTable) { var dictionary = new Dictionary<string, CustomSummaryType>(); foreach (LayoutDetailDataSet.LayoutSearchFieldRow row in layoutSearchFieldTable.Rows) { string key = AvrPivotGridFieldHelper.CreateFieldName(row.strSearchFieldAlias, row.idfLayoutSearchField); if (!dictionary.ContainsKey(key)) { CustomSummaryType value = ParseSummaryType(row.idfsAggregateFunction); dictionary.Add(key, value); } } return dictionary; } public static CustomSummaryType ParseSummaryType(long value) { IEnumerable<CustomSummaryType> allEnumValues = Enum.GetValues(typeof (CustomSummaryType)).Cast<CustomSummaryType>(); CustomSummaryType result = allEnumValues.Any(current => current == (CustomSummaryType) value) ? (CustomSummaryType) value : CustomSummaryType.Max; return result; } #endregion #region Prepare Pivot Data Source public static DataTable GetPreparedDataSource (LayoutDetailDataSet.LayoutSearchFieldDataTable layoutSearchFieldTable, long queryId, long layoutId, DataTable queryResult, bool isNewObject) { if (queryResult == null) { return null; } FillNewLayoutSearchFields(layoutSearchFieldTable, queryId, layoutId, queryResult, isNewObject); DeleteColumnsMissingInLayoutSearchFieldTable(layoutSearchFieldTable, queryResult, isNewObject); CreateCopiedColumnsAndAjustColumnNames(layoutSearchFieldTable, queryResult); queryResult.AcceptChanges(); return queryResult; } /// <summary> /// method generates LayoutSearchFieldRow for each column in the Data Source that hasn't aggregate information /// </summary> /// <param name="layoutSearchFieldTable"></param> /// <param name="queryId"></param> /// <param name="layoutId"></param> /// <param name="newDataSource"></param> /// <param name="isNewObject"></param> public static void FillNewLayoutSearchFields (LayoutDetailDataSet.LayoutSearchFieldDataTable layoutSearchFieldTable, long queryId, long layoutId, DataTable newDataSource, bool isNewObject) { List<LayoutDetailDataSet.LayoutSearchFieldRow> rows = layoutSearchFieldTable.Rows.Cast<LayoutDetailDataSet.LayoutSearchFieldRow>() .OrderBy(row => row.idfLayoutSearchField) .ToList(); // If LayoutSearchFieldTable doesn't contain row with Search Field that corresponds to one of QueryResult column, // we should create corresponding LayoutSearchField row List<long> idList = null; if (isNewObject) { idList = BaseDbService.NewListIntID(newDataSource.Columns.Count); } int count = 0; foreach (DataColumn column in newDataSource.Columns) { string columnName = column.ColumnName; // process original fields, not copied fields in filter // we think than each column has a copy if (AvrPivotGridFieldHelper.GetIsCopyForFilter(columnName)) { continue; } List<LayoutDetailDataSet.LayoutSearchFieldRow> foundRows = rows.FindAll(row => (row.strSearchFieldAlias == columnName)); if (foundRows.Count < 2) { CustomSummaryType summaryType = (foundRows.Count == 0) ? Configuration.GetDefaultSummaryTypeFor(columnName, column.DataType) : (CustomSummaryType) foundRows[0].idfsAggregateFunction; string copyColumnName = columnName + QueryHelper.CopySuffix; if (isNewObject && idList != null) { if (foundRows.Count == 0) { AddNewLayoutSearchFieldRow(layoutSearchFieldTable, queryId, layoutId, columnName, (long) summaryType, idList[count]); count++; } LayoutDetailDataSet.LayoutSearchFieldRow copyRow = AddNewLayoutSearchFieldRow(layoutSearchFieldTable, queryId, layoutId, copyColumnName, (long) summaryType, idList[count]); copyRow.blnHiddenFilterField = true; count++; } else { if (foundRows.Count == 0) { AddNewLayoutSearchFieldRow(layoutSearchFieldTable, queryId, layoutId, columnName, (long) summaryType); } LayoutDetailDataSet.LayoutSearchFieldRow copyRow = AddNewLayoutSearchFieldRow(layoutSearchFieldTable, queryId, layoutId, copyColumnName, (long) summaryType); copyRow.blnHiddenFilterField = true; } } else { // second row corresponding to the copied column, so we should change strSearchFieldAlias according to copied column name foundRows[1].strSearchFieldAlias = columnName + QueryHelper.CopySuffix; foundRows[0].blnHiddenFilterField = false; foundRows[1].blnHiddenFilterField = true; } } } /// <summary> /// If Current object is NOT new, Method deletes all columns in the Data Source that hasn't corresponding rows in /// AggregateTable /// </summary> /// <param name="layoutSearchFieldTable"> </param> /// <param name="newDataSource"> </param> /// <param name="isNewObject"> </param> private static void DeleteColumnsMissingInLayoutSearchFieldTable (LayoutDetailDataSet.LayoutSearchFieldDataTable layoutSearchFieldTable, DataTable newDataSource, bool isNewObject) { if (!isNewObject) { List<LayoutDetailDataSet.LayoutSearchFieldRow> rows = layoutSearchFieldTable.Rows.Cast<LayoutDetailDataSet.LayoutSearchFieldRow>().ToList(); List<DataColumn> dataColumns = newDataSource.Columns.Cast<DataColumn>().ToList(); foreach (DataColumn column in dataColumns) { string columnName = column.ExtendedProperties.ContainsKey(QueryHelper.CopySuffix) ? AvrPivotGridFieldHelper.GetOriginalNameFromCopyForFilterName(column.ColumnName) : column.ColumnName; LayoutDetailDataSet.LayoutSearchFieldRow foundRow = rows.Find(row => (row.strSearchFieldAlias == columnName)); if (foundRow == null) { newDataSource.Columns.Remove(column); } } } } /// <summary> /// If LayoutSearchFieldTable contains multiple rows with the same strSearchFieldAlias, method creates corresponding /// columns. /// Also /// method appends Column Name with corresponding idfLayoutSearchField for each column /// </summary> /// <param name="layoutSearchFieldTable"> </param> /// <param name="newDataSource"> </param> private static void CreateCopiedColumnsAndAjustColumnNames (LayoutDetailDataSet.LayoutSearchFieldDataTable layoutSearchFieldTable, DataTable newDataSource) { try { newDataSource.BeginInit(); newDataSource.BeginLoadData(); List<DataColumn> dataColumns = newDataSource.Columns.Cast<DataColumn>().ToList(); List<LayoutDetailDataSet.LayoutSearchFieldRow> rows = layoutSearchFieldTable.Rows.Cast<LayoutDetailDataSet.LayoutSearchFieldRow>().ToList(); foreach (DataColumn column in dataColumns) { string originalName = column.ColumnName; List<LayoutDetailDataSet.LayoutSearchFieldRow> foundRows = rows.FindAll(row => (row.strSearchFieldAlias == originalName)); int rowCounter = 0; foreach (LayoutDetailDataSet.LayoutSearchFieldRow row in foundRows) { CheckLayoutSearchFieldRowTranslations(row); if (column.ExtendedProperties.ContainsKey(QueryHelper.CopySuffix)) { row.strSearchFieldAlias = AvrPivotGridFieldHelper.GetOriginalNameFromCopyForFilterName(originalName); } string caption = row.IsstrNewFieldCaptionNull() || Utils.IsEmpty(row.strNewFieldCaption) ? row.strOriginalFieldCaption : row.strNewFieldCaption; if (rowCounter == 0) { // change name so it shall contain idfLayoutSearchField column.ColumnName = AvrPivotGridFieldHelper.CreateFieldName(row.strSearchFieldAlias, row.idfLayoutSearchField); column.Caption = caption; } else { // create copy of column with new idfLayoutSearchField // name of new column shall contain new id CreateDataSourceColumnCopy(newDataSource, column.ColumnName, row.strSearchFieldAlias, caption, row.idfLayoutSearchField); } rowCounter++; } } } finally { newDataSource.EndLoadData(); newDataSource.EndInit(); } } public static DataColumn CreateDataSourceColumnCopy (DataTable dataSource, string fullFieldName, string originalFieldName, string fieldCaption, long idfLayoutSearchField) { DataColumn sourceColumn = dataSource.Columns[fullFieldName]; DataColumn destColumn = ReflectionHelper.CreateAndCopyProperties(sourceColumn); destColumn.ColumnName = AvrPivotGridFieldHelper.CreateFieldName(originalFieldName, idfLayoutSearchField); destColumn.Caption = fieldCaption; dataSource.Columns.Add(destColumn); int destIndex = dataSource.Columns.IndexOf(destColumn); int sourceIndex = dataSource.Columns.IndexOf(sourceColumn); //var sw = new Stopwatch(); //sw.Start(); foreach (DataRow row in dataSource.Rows) { row.BeginEdit(); row[destIndex] = row[sourceIndex]; } //long msAdd = sw.ElapsedMilliseconds; return destColumn; } private static void CheckLayoutSearchFieldRowTranslations(LayoutDetailDataSet.LayoutSearchFieldRow row) { string msg = EidssMessages.Get("msgEmptyRow", "One of rows has empty translation {0}"); if (row.IsstrOriginalFieldENCaptionNull() || row.IsstrOriginalFieldCaptionNull()) { throw new AvrDbException(String.Format(msg, row.strSearchFieldAlias)); } } #endregion #region Administrative Unit & Statistic date field processing public static DataView GetStatisticDateView(IEnumerable<IAvrPivotGridField> avrFields) { DataTable dataTable = CreateListDataTable("DateFieldList"); dataTable.BeginLoadData(); foreach (IAvrPivotGridField field in avrFields) { if (field.Visible && field.Area == PivotArea.ColumnArea && field.SearchFieldDataType == typeof (DateTime)) { DataRow dr = dataTable.NewRow(); dr[IdColumnName] = AvrPivotGridFieldHelper.GetIdFromFieldName(field.FieldName); dr[AliasColumnName] = field.FieldName; dr[CaptionColumnName] = field.Caption; dataTable.Rows.Add(dr); } } dataTable.EndLoadData(); dataTable.AcceptChanges(); return new DataView(dataTable, "", string.Format("{0}, {1}", CaptionColumnName, AliasColumnName), DataViewRowState.CurrentRows); } public static DataView GetAdministrativeUnitView(long queryId, List<IAvrPivotGridField> allFields) { DataView dvMapFieldList = GetMapFiledView(queryId); DataTable dataTable = CreateListDataTable("AdmUnitList"); var colOrder = new DataColumn(OrderColumnName, typeof (int)); dataTable.Columns.Add(colOrder); dataTable.BeginLoadData(); foreach (DataRowView r in dvMapFieldList) { IEnumerable<IAvrPivotGridField> rowFields = GetFieldsInRow(allFields, Utils.Str(r["FieldAlias"])); foreach (IAvrPivotGridField field in rowFields) { DataRow dr = dataTable.NewRow(); dr[IdColumnName] = AvrPivotGridFieldHelper.GetIdFromFieldName(field.FieldName); dr[AliasColumnName] = field.FieldName; dr[CaptionColumnName] = field.Caption; dr[OrderColumnName] = r["intIncidenceDisplayOrder"]; dataTable.Rows.Add(dr); } } DataRow countryRow = dataTable.NewRow(); countryRow[IdColumnName] = -1; countryRow[AliasColumnName] = AvrPivotGridFieldHelper.VirtualCountryFieldName; countryRow[CaptionColumnName] = EidssMessages.Get("strCountry", "Country"); countryRow[OrderColumnName] = -1; dataTable.Rows.Add(countryRow); dataTable.EndLoadData(); dataTable.AcceptChanges(); return new DataView(dataTable, "", string.Format("{0}, {1}, {2}", OrderColumnName, CaptionColumnName, AliasColumnName), DataViewRowState.CurrentRows); } public static DataView GetMapFiledView(long queryId, bool isMap = false) { string key = LookupTables.QuerySearchField.ToString(); DataTable dtMapFieldList = LookupCache.Fill(LookupCache.LookupTables[key]); string field = isMap ? "intMapDisplayOrder" : "intIncidenceDisplayOrder"; string filter = String.Format("idflQuery = {0} and {1} is not null", queryId, field); string sort = String.Format("{0}, FieldCaption", field); var dvMapFieldList = new DataView(dtMapFieldList, filter, sort, DataViewRowState.CurrentRows); return dvMapFieldList; } public static DataTable CreateListDataTable(string tableName) { var dataTable = new DataTable(tableName); var colId = new DataColumn(IdColumnName, typeof (long)); dataTable.Columns.Add(colId); var colAlias = new DataColumn(AliasColumnName, typeof (string)); dataTable.Columns.Add(colAlias); var colCaption = new DataColumn(CaptionColumnName, typeof (string)); dataTable.Columns.Add(colCaption); dataTable.PrimaryKey = new[] {colAlias}; return dataTable; } public static IEnumerable<IAvrPivotGridField> GetFieldsInRow(List<IAvrPivotGridField> fields, string originalFieldName) { Utils.CheckNotNullOrEmpty(originalFieldName, "originalFieldName"); List<IAvrPivotGridField> found = fields.FindAll(field => (field.Visible) && (field.AreaIndex >= 0) && (field.Area == PivotArea.RowArea) && (field.GetOriginalName() == originalFieldName)); return found; } #endregion #region Add Search Field Row public static LayoutDetailDataSet.LayoutSearchFieldRow AddNewLayoutSearchFieldRow (LayoutDetailDataSet.LayoutSearchFieldDataTable layoutSearchFieldTable, long queryId, long layoutId, string originalFieldName, long aggregateFunctionId) { return AddNewLayoutSearchFieldRow(layoutSearchFieldTable, queryId, layoutId, originalFieldName, aggregateFunctionId, BaseDbService.NewIntID()); } public static LayoutDetailDataSet.LayoutSearchFieldRow AddNewLayoutSearchFieldRow (LayoutDetailDataSet.LayoutSearchFieldDataTable searchFieldTable, long queryId, long layoutId, string originalFieldName, long aggregateFunctionId, long idfLayoutSearchField) { LayoutDetailDataSet.LayoutSearchFieldRow newRow = searchFieldTable.NewLayoutSearchFieldRow(); newRow.idflLayout = layoutId; newRow.strSearchFieldAlias = originalFieldName; newRow.idfsAggregateFunction = aggregateFunctionId; newRow.idfLayoutSearchField = idfLayoutSearchField; newRow.SetidfsGroupDateNull(); newRow.blnShowMissedValue = false; newRow.SetdatDiapasonStartDateNull(); newRow.SetdatDiapasonEndDateNull(); //todo: [ivan] possible performance issue FillMissedReferenceAttribues(newRow, originalFieldName); newRow.SetintPrecisionNull(); newRow.intFieldColumnWidth = AvrView.DefaultFieldWidth; newRow.intFieldCollectionIndex = 0; newRow.intPivotGridAreaType = 0; newRow.intFieldPivotGridAreaIndex = 0; newRow.blnVisible = false; newRow.blnHiddenFilterField = false; newRow.intFieldColumnWidth = AvrView.DefaultFieldWidth; newRow.blnSortAcsending = true; KeyValuePair<string, string> translations = QueryProcessor.GetTranslations(queryId, originalFieldName); newRow.strOriginalFieldENCaption = translations.Key; newRow.strOriginalFieldCaption = translations.Value; searchFieldTable.AddLayoutSearchFieldRow(newRow); return newRow; } private static void FillMissedReferenceAttribues(LayoutDetailDataSet.LayoutSearchFieldRow newRow, string name) { newRow.blnAllowMissedReferenceValues = false; newRow.strLookupTable = String.Empty; newRow.strLookupAttribute = String.Empty; DataView searchFields = GetSearchFieldRowByName(name); if (searchFields.Count > 0) { DataRowView row = searchFields[0]; object flag = row["blnAllowMissedReferenceValues"]; if (flag is bool) { newRow.blnAllowMissedReferenceValues = (bool) flag; } newRow.strLookupTable = Utils.Str(row["strLookupTable"]); if (row["idfsReferenceType"] is long) { newRow.idfsReferenceType = (long) row["idfsReferenceType"]; } if (row["idfsGISReferenceType"] is long) { newRow.idfsGISReferenceType = (long) row["idfsGISReferenceType"]; } newRow.strLookupAttribute = Utils.Str(row["strLookupAttribute"]); } } private static DataView GetSearchFieldRowByName(string name) { Utils.CheckNotNullOrEmpty(name, "name"); string originalName = AvrPivotGridFieldHelper.GetOriginalNameFromCopyForFilterName(name); DataView searchFields = LookupCache.Get(LookupTables.SearchField); if (searchFields == null) { throw new AvrException("Could not load lookup SearchField. Check taht Database contains spAsSearchFieldSelectLookup"); } searchFields.RowFilter = String.Format("strSearchFieldAlias = '{0}'", originalName); return searchFields; } #endregion #region Add Missed Values public static void AddMissedValuesInRowColumnArea(AvrPivotGridData dataSource, IList<IAvrPivotGridField> avrFields) { if (dataSource == null) { return; } try { dataSource.BeginLoadData(); List<IAvrPivotGridField> baseFields = GetFieldCollectionFromArea(avrFields, PivotArea.RowArea); baseFields.AddRange(GetFieldCollectionFromArea(avrFields, PivotArea.ColumnArea)); List<IAvrPivotGridField> cortegeFields = AddRelatedFields(baseFields); var fieldsAndFieldCopy = new Dictionary<IAvrPivotGridField, List<IAvrPivotGridField>>(); foreach (IAvrPivotGridField field in cortegeFields) { IAvrPivotGridField originalField = field; List<IAvrPivotGridField> fieldCopy = avrFields.Where(f => f.GetOriginalName() == originalField.GetOriginalName() && f != originalField).ToList(); fieldsAndFieldCopy.Add(field, fieldCopy); } var cortege = new FieldValueCollection(fieldsAndFieldCopy); if (cortege.AddMissedValues) { AddMissedValuesForFields(dataSource, cortege, dataSource.Rows, 0); } } finally { dataSource.EndLoadData(); } } public static void AddMissedValuesForFields (AvrPivotGridData dataSource, FieldValueCollection fieldValuesCortege, IEnumerable<DataRow> dataRows, int fieldIndex) { if (fieldIndex < fieldValuesCortege.Count) { IAvrPivotGridField field = fieldValuesCortege[fieldIndex].Field; var valuesDictionary = new Dictionary<object, List<DataRow>>(); bool isDateTimeField = field.IsDateTimeField; foreach (DataRow row in dataRows) { object fieldValue = row[field.FieldName]; if (isDateTimeField && fieldValue is DateTime) { var currentDate = (DateTime) row[field.FieldName]; fieldValue = currentDate.TruncateToFirstDateInInterval(field.GroupInterval); } if (!valuesDictionary.ContainsKey(fieldValue)) { valuesDictionary.Add(fieldValue, new List<DataRow>()); } valuesDictionary[fieldValue].Add(row); } bool isNonCountryFieldRelated = (field.GisReferenceTypeId != (long) GisReferenceType.Country && fieldValuesCortege[fieldIndex].IsRelated); if (field.AddMissedValues || isNonCountryFieldRelated) { IEnumerable<object> missedValues; try { missedValues = isDateTimeField ? field.AddMissedDates() : field.AddMissedReferencies(fieldValuesCortege); } catch (Exception ex) { throw new AvrException(field.GetMissedValuesErrorMessage(), ex); } foreach (object missedValue in missedValues) { if (!valuesDictionary.ContainsKey(missedValue)) { valuesDictionary.Add(missedValue, new List<DataRow>()); } } } if (valuesDictionary.Count == 0) { //var childCortege = new FieldValueCollection(fieldValuesCortege, true); // var childCortege = new FieldValueCollection(fieldValuesCortege, false); for (int i = fieldIndex; i < fieldValuesCortege.Count; i++) { fieldValuesCortege[i].Value = null; } AddMissedValuesForFields(dataSource, fieldValuesCortege, new List<DataRow>(), fieldValuesCortege.Count); } foreach (KeyValuePair<object, List<DataRow>> pair in valuesDictionary) { // var childCortege = new FieldValueCollection(fieldValuesCortege, false); fieldValuesCortege[fieldIndex].Value = pair.Key; AddMissedValuesForFields(dataSource, fieldValuesCortege, pair.Value, fieldIndex + 1); } } else { DataRow row = dataSource.NewRow(); foreach (FieldValuePair pair in fieldValuesCortege) { row[pair.Field.FieldName] = pair.Value ?? DBNull.Value; if (!pair.Field.IsDateTimeField) { foreach (IAvrPivotGridField copy in pair.FieldCopy) { row[copy.FieldName] = pair.Value ?? DBNull.Value; } } } dataSource.AddRow(row); } } public static List<IAvrPivotGridField> AddRelatedFields(IEnumerable<IAvrPivotGridField> baseFields) { List<IAvrPivotGridField> allFields = baseFields.ToList(); //for fields with missing value remove all their copies without missing values var removeFields = new List<IAvrPivotGridField>(); foreach (IAvrPivotGridField field in allFields.Where(f => f.AddMissedValues && !f.IsDateTimeField)) { IAvrPivotGridField originalField = field; removeFields.AddRange( allFields.Where(f => !f.AddMissedValues && f != originalField && f.GetOriginalName() == originalField.GetOriginalName())); } foreach (IAvrPivotGridField field in removeFields) { allFields.Remove(field); } //for fields remove all their copies except first one var distinctFields = new List<IAvrPivotGridField>(); foreach (IAvrPivotGridField field in allFields) { IAvrPivotGridField originalField = field; if (originalField.IsDateTimeField || distinctFields.All(f => f.GetOriginalName() != originalField.GetOriginalName())) { distinctFields.Add(originalField); } } allFields = distinctFields; // remove all field copies that can be found in related chains removeFields = new List<IAvrPivotGridField>(); foreach (IAvrPivotGridField field in allFields) { removeFields.AddRange(field.GetRelatedFieldChain().Where(allFields.Contains)); } foreach (IAvrPivotGridField field in removeFields) { allFields.Remove(field); } var cortegeFields = new List<IAvrPivotGridField>(); foreach (IAvrPivotGridField field in allFields) { cortegeFields.AddRange(field.GetRelatedFieldChain()); cortegeFields.Add(field); } return cortegeFields; } #endregion #region Create/delete Field Copy public static T CreateFieldCopy<T> (IAvrPivotGridField sourceField, LayoutDetailDataSet layoutDataset, AvrPivotGridData pivotData, long queryId, long layoutId) where T : IAvrPivotGridField, new() { Utils.CheckNotNull(sourceField, "sourceField"); LayoutDetailDataSet.LayoutSearchFieldRow destRow = CreateLayoutSearchFieldInformationCopy(sourceField, layoutDataset, queryId, layoutId); DataColumn destColumn = CreateDataSourceColumnCopy(pivotData.RealPivotData, sourceField.FieldName, sourceField.GetOriginalName(), sourceField.Caption, destRow.idfLayoutSearchField); var copy = new T(); sourceField.CreatePivotGridFieldCopy(copy, destColumn.ColumnName); var allFields = new List<IAvrPivotGridField>(); allFields.AddRange(sourceField.AllPivotFields); allFields.Add(copy); foreach (IAvrPivotGridField field in allFields) { field.AllPivotFields.Add(copy); } return copy; } private static LayoutDetailDataSet.LayoutSearchFieldRow CreateLayoutSearchFieldInformationCopy (IAvrPivotGridField sourceField, LayoutDetailDataSet layoutDataset, long queryId, long layoutId) { LayoutDetailDataSet.LayoutSearchFieldRow sourceRow = GetLayoutSearchFieldRowByField(sourceField, layoutDataset); LayoutDetailDataSet.LayoutSearchFieldRow destRow = AddNewLayoutSearchFieldRow(layoutDataset.LayoutSearchField, queryId, layoutId, sourceRow.strSearchFieldAlias, (long) sourceField.GetDefaultSummaryType()); destRow.strNewFieldCaption = sourceRow.strNewFieldCaption; destRow.strNewFieldENCaption = sourceRow.strNewFieldENCaption; if (!sourceRow.IsidfUnitLayoutSearchFieldNull() && !sourceRow.IsstrUnitSearchFieldAliasNull()) { destRow.strUnitSearchFieldAlias = sourceRow.strUnitSearchFieldAlias; destRow.idfUnitLayoutSearchField = sourceRow.idfUnitLayoutSearchField; } if (!sourceRow.IsidfDateLayoutSearchFieldNull() && !sourceRow.IsstrDateSearchFieldAliasNull()) { destRow.strDateSearchFieldAlias = sourceRow.strDateSearchFieldAlias; destRow.idfDateLayoutSearchField = sourceRow.idfDateLayoutSearchField; } destRow.strLookupAttribute = sourceRow.strLookupAttribute; destRow.strLookupTable = sourceRow.strLookupTable; if (!sourceRow.IsidfsReferenceTypeNull()) { destRow.idfsReferenceType = sourceRow.idfsReferenceType; } if (!sourceRow.IsidfsGISReferenceTypeNull()) { destRow.idfsGISReferenceType = sourceRow.idfsGISReferenceType; } if (sourceRow.IsblnAllowMissedReferenceValuesNull()) { destRow.blnAllowMissedReferenceValues = sourceRow.blnAllowMissedReferenceValues; } return destRow; } public static LayoutDetailDataSet.LayoutSearchFieldRow GetLayoutSearchFieldRowByField (IAvrPivotGridField sourceField, LayoutDetailDataSet layoutDataset) { Utils.CheckNotNull(sourceField, "sourceField"); if (sourceField.GetFieldId() < 0) { throw new AvrException(String.Format("Field {0} doesn't has Id", sourceField.FieldName)); } LayoutDetailDataSet.LayoutSearchFieldRow sourceRow = layoutDataset.LayoutSearchField.FindByidfLayoutSearchField(sourceField.GetFieldId()); if (sourceRow == null) { throw new AvrException(String.Format("LayoutSearchField information not found for field {0} with ID {1}", sourceField.FieldName, sourceField.GetFieldId())); } return sourceRow; } public static void DeleteFieldCopy(IAvrPivotGridField sourceField, LayoutDetailDataSet layoutDataset, AvrPivotGridData pivotData) { DataColumn sourceColumn = pivotData.RealPivotData.Columns[sourceField.FieldName]; pivotData.RealPivotData.Columns.Remove(sourceColumn); // clear Unit, Denoninator, Date and other fields here string originalName = sourceField.GetOriginalName(); List<LayoutDetailDataSet.LayoutSearchFieldRow> rows = layoutDataset.LayoutSearchField.Rows.Cast<LayoutDetailDataSet.LayoutSearchFieldRow>().ToList(); List<LayoutDetailDataSet.LayoutSearchFieldRow> unitRows = rows.FindAll(uRow => (!uRow.IsstrUnitSearchFieldAliasNull() && uRow.strUnitSearchFieldAlias == originalName)); foreach (LayoutDetailDataSet.LayoutSearchFieldRow uRow in unitRows) { uRow.SetstrUnitSearchFieldAliasNull(); uRow.SetidfUnitLayoutSearchFieldNull(); } List<LayoutDetailDataSet.LayoutSearchFieldRow> dateRows = rows.FindAll(dateRow => (!dateRow.IsstrDateSearchFieldAliasNull() && dateRow.strDateSearchFieldAlias == originalName)); foreach (LayoutDetailDataSet.LayoutSearchFieldRow dateRow in dateRows) { dateRow.SetstrDateSearchFieldAliasNull(); dateRow.SetidfDateLayoutSearchFieldNull(); } // remove corresponding aggregate row LayoutDetailDataSet.LayoutSearchFieldRow row = layoutDataset.LayoutSearchField.FindByidfLayoutSearchField(sourceField.GetFieldId()); layoutDataset.LayoutSearchField.RemoveLayoutSearchFieldRow(row); //remove field in fieldlist for each field var allFields = new List<IAvrPivotGridField>(); allFields.AddRange(sourceField.AllPivotFields); foreach (IAvrPivotGridField field in allFields) { field.AllPivotFields.Remove(sourceField); } } public static bool EnableDeleteField(IAvrPivotGridField field, IEnumerable<IAvrPivotGridField> avrFields) { if (field == null) { return false; } int count = avrFields.Count(f => f.GetOriginalName() == field.GetOriginalName()); return count > 2; } #endregion } }